hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
02f49d379b3c7b6f9d35c8f19c898a0637545318
18,324
cpp
C++
src/core/main.cpp
Zeyu747823/ZeyuExperiment
a05358b15040499bd6beb2d06ad126dafa2fc64c
[ "Apache-2.0" ]
null
null
null
src/core/main.cpp
Zeyu747823/ZeyuExperiment
a05358b15040499bd6beb2d06ad126dafa2fc64c
[ "Apache-2.0" ]
null
null
null
src/core/main.cpp
Zeyu747823/ZeyuExperiment
a05358b15040499bd6beb2d06ad126dafa2fc64c
[ "Apache-2.0" ]
1
2021-04-01T02:57:50.000Z
2021-04-01T02:57:50.000Z
/* * * /file main.cpp * /author William Campbell * /version 0.1 * /date 2020-04-09 * * /copyright Copyright (c) 2020 * * * This file is an adaptation of CANopenSocket, a Linux implementation of CANopen * stack with master functionality. Project home page is * <https://github.com/CANopenNode/CANopenSocket>. CANopenSocket is based * on CANopenNode: <https://github.com/CANopenNode/CANopenNode>. * * The adaptation is specifically designed for use with the RobotCANControl design stack and * a multi limbed robot. It has been tested using a Beagle Bone black and the Fourier Intelligence X2 * exoskelton in a lab testing setting.It can be addapted for use with other CANopen enabled linux based robotic projects. * * 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. */ #include "application.h" /* Threads and thread safety variables***********************************************************/ /** * Mutex is locked, when CAN is not valid (configuration state). * May be used from other threads. RT threads may use CO->CANmodule[0]->CANnormal instead. */ pthread_mutex_t CO_CAN_VALID_mtx = PTHREAD_MUTEX_INITIALIZER; static int mainline_epoll_fd; /*!< epoll file descriptor for mainline */ static CO_time_t CO_time; /*!< Object for current time */ bool readyToStart = false; /*!< Flag used by control thread to indicate CAN stack functional */ uint32_t tmr1msPrev = 0; /*CAN msg processing thread variables*/ static int rtPriority = 90; /*!< priority of rt CANmsg thread */ static void *rt_thread(void *arg); static pthread_t rt_thread_id; static int rt_thread_epoll_fd; /*!< epoll file descriptor for rt thread */ /* Application Control loop thread */ static int rtControlPriority = 80; /*!< priority of application thread */ static void *rt_control_thread(void *arg); static pthread_t rt_control_thread_id; const float controlLoopPeriodInms = 2; /*!< Define the control loop period (in ms): the period of rt_control_thread loop. */ const float CANUpdateLoopPeriodInms = 2; /*!< Define the CAN PDO sync message period (and so PDO update rate). In ms. Less than 3 can lead to unstable communication */ CO_NMT_reset_cmd_t reset_local = CO_RESET_NOT; /** @brief Task Timer used for the Control Loop*/ struct period_info { struct timespec next_period; long period_ns; }; /** @brief Struct to hold arguments for ROS thread*/ struct ros_arg_holder { int argc; char **argv; }; /* Forward declartion of control loop thread timer functions*/ static void inc_period(struct period_info *pinfo); static void periodic_task_init(struct period_info *pinfo); static void wait_rest_of_period(struct period_info *pinfo); /* Forward declartion of CAN helper functions*/ void configureCANopen(int nodeId, int rtPriority, int CANdevice0Index, char *CANdevice); void CO_errExit(char const *msg); /*!< CAN object error code and exit program*/ void CO_error(const uint32_t info); /*!< send CANopen generic emergency message */ volatile uint32_t CO_timer1ms = 0U; /*!< Global variable increments each millisecond */ volatile sig_atomic_t CO_endProgram = 0; /*!< Signal handler: controls the end of CAN processing thread*/ volatile sig_atomic_t endProgram = 0; /*!< Signal handler: controls the end of application side (rt thread and main)*/ static void sigHandler(int sig) { endProgram = 1; } /* Privileges management */ static uid_t uid, gid; //Saved uid and gid void save_privileges() { uid = getuid(); gid = getgid(); } int drop_privileges() { if (uid == 0) { //Drop group privileges first if( setegid(1000)<0 || seteuid(1000)<0 ) { CO_errExit("Failed to drop privileges."); return -1; } } return 0; } int restore_privileges() { if( setreuid(uid, gid)<0 ) { CO_errExit("Failed to restore privileges."); return -1; } return 0; } /* --------------------- */ /******************************************************************************/ /** Mainline and threads **/ /******************************************************************************/ int main(int argc, char *argv[]) { //Drop privileges to create log save_privileges(); drop_privileges(); //Initialise console and file logging. Name file can be specified if required (see logging.h) init_logging(); restore_privileges(); //Check if running with root privilege if (getuid() != 0) { //Fallback to standard non RT thread rtPriority = -1; rtControlPriority = -1; spdlog::warn("Running without root privilege: using non-RT priority threads"); } else { spdlog::info("Running with root privilege: using RT priority threads"); } /* TODO : MOVE bellow definitionsTO SOME KIND OF CANobject, struct or the like*/ CO_NMT_reset_cmd_t reset = CO_RESET_NOT; bool_t firstRun = true; bool_t rebootEnable = false; /*!< Configurable by use case */ // TODO: DO WE EVER RESET? OR NEED TO? int nodeId = NODEID; /*!< CAN Network NODEID */ int can_dev_number = 6; char CANdeviceList[can_dev_number][10] = {"vcan0\0", "can0\0", "can1\0", "can2\0", "can3\0", "can4\0"}; /*!< linux CAN device interface for app to bind to: change to can1 for bbb, can0 for BBAI vcan0 for virtual can*/ for (int i = 1; i < argc; i++) { // skip index 0 because it gives the executable address std::string arg = argv[i]; if (arg.find("-can") != std::string::npos) { // if there is a -can argument spdlog::info("CAN argument found: {}", argv[i + 1]); strcpy(CANdeviceList[0], argv[i + 1]); // coppy the argument to the first element of CANdeviceList can_dev_number = 1; // set can_dev_number to 1 so that other devices are not checked break; } } char CANdevice[10] = ""; int CANdevice0Index; //Rotate through list of interfaces and select first one existing and up for (int i = 0; i < can_dev_number; i++) { //Check if interface exists CANdevice0Index = if_nametoindex(CANdeviceList[i]); /*map linux CAN interface to corresponding int index return zero if no interface exists.*/ if (CANdevice0Index != 0) { char operstate_filename[255], operstate_s[25]; snprintf(operstate_filename, 254, "/sys/class/net/%s/operstate", CANdeviceList[i]); //Check if it's up FILE *operstate_f = fopen(operstate_filename, "r"); if (fscanf(operstate_f, "%s", &operstate_s) > 0) { spdlog::info("{}: {}", CANdeviceList[i], operstate_s); //Check if not "down" as will be "unknown" if up if (strcmp(operstate_s, "down") != 0) { snprintf(CANdevice, 9, "%s", CANdeviceList[i]); spdlog::info("Using: {} ({})", CANdeviceList[i], CANdevice0Index); break; } else { CANdevice0Index = 0; } } else { CANdevice0Index = 0; } } else { spdlog::info("{}: -", CANdeviceList[i]); } } configureCANopen(nodeId, rtPriority, CANdevice0Index, CANdevice); struct ros_arg_holder *ros_args = (ros_arg_holder *)malloc(sizeof(*ros_args)); ros_args->argc = argc; ros_args->argv = argv; /* Set up catch of linux signals SIGINT(ctrl+c) and SIGTERM (terminate program - shell kill command) bind to sigHandler -> raise CO_endProgram flag and safely close application threads*/ if (signal(SIGINT, sigHandler) == SIG_ERR) CO_errExit("Program init - SIGINIT handler creation failed"); if (signal(SIGTERM, sigHandler) == SIG_ERR) CO_errExit("Program init - SIGTERM handler creation failed"); spdlog::info("Starting CANopen device with Node ID {}", nodeId); //Set synch signal period (in us) CO_OD_RAM.communicationCyclePeriod = CANUpdateLoopPeriodInms * 1000; while (reset != CO_RESET_APP && reset != CO_RESET_QUIT && endProgram == 0) { /* CANopen communication reset || first run of app- initialize CANopen objects *******************/ //CO_ReturnError_t err; /*mutex locking for thread safe OD access*/ pthread_mutex_lock(&CO_CAN_VALID_mtx); /* Wait rt_thread. */ if (!firstRun) { CO_LOCK_OD(); CO->CANmodule[0]->CANnormal = false; CO_UNLOCK_OD(); } CO_configure(); /* Execute optional additional application code */ app_communicationReset(argc, argv); /* initialize CANopen with CAN interface and nodeID */ if (CO_init(CANdevice0Index, nodeId, 0) != CO_ERROR_NO) { char s[120]; snprintf(s, 120, "Communication reset - CANopen initialization failed"); CO_errExit(s); } /* Configure callback functions for task control */ CO_EM_initCallback(CO->em, taskMain_cbSignal); CO_SDO_initCallback(CO->SDO[0], taskMain_cbSignal); CO_SDOclient_initCallback(CO->SDOclient, taskMain_cbSignal); /* Initialize time */ CO_time_init(&CO_time, CO->SDO[0], &OD_time.epochTimeBaseMs, &OD_time.epochTimeOffsetMs, 0x2130); /* First time only initialization */ if (firstRun) { firstRun = false; /* Configure epoll for mainline */ mainline_epoll_fd = epoll_create(4); if (mainline_epoll_fd == -1) CO_errExit("Program init - epoll_create mainline failed"); /* Init mainline */ taskMain_init(mainline_epoll_fd, &OD_performance[ODA_performance_mainCycleMaxTime]); /* Configure epoll for rt_thread */ rt_thread_epoll_fd = epoll_create(2); if (rt_thread_epoll_fd == -1) CO_errExit("Program init - epoll_create rt_thread failed"); /* Init taskRT */ CANrx_taskTmr_init(rt_thread_epoll_fd, TMR_TASK_INTERVAL_NS, &OD_performance[ODA_performance_timerCycleMaxTime]); OD_performance[ODA_performance_timerCycleTime] = TMR_TASK_INTERVAL_NS / 1000; /* informative */ /* Create rt_thread */ if (pthread_create(&rt_thread_id, NULL, rt_thread, NULL) != 0) CO_errExit("Program init - rt_thread creation failed"); /* Set priority for rt_thread */ if (rtPriority > 0) { struct sched_param param; param.sched_priority = rtPriority; if (pthread_setschedparam(rt_thread_id, SCHED_FIFO, &param) != 0) { CO_errExit("Program init - rt_thread set scheduler failed (are you root?)"); } } /* Create control_thread */ if (pthread_create(&rt_control_thread_id, NULL, rt_control_thread, ros_args) != 0) CO_errExit("Program init - rt_thread_control creation failed"); /* Set priority for control thread */ if (rtPriority > 0) { struct sched_param paramc; paramc.sched_priority = rtControlPriority; if (pthread_setschedparam(rt_control_thread_id, SCHED_FIFO, &paramc) != 0) { CO_errExit("Program init - rt_thread set scheduler failed (are you root?)"); } } //Privileges not required anymore drop_privileges(); /* start CAN */ CO_CANsetNormalMode(CO->CANmodule[0]); pthread_mutex_unlock(&CO_CAN_VALID_mtx); reset = CO_RESET_NOT; readyToStart = true; while (reset == CO_RESET_NOT && endProgram == 0) { /* loop for normal program execution main epoll reading ******************************************/ int ready; struct epoll_event ev; ready = epoll_wait(mainline_epoll_fd, &ev, 1, -1); if (ready != 1) { if (errno != EINTR) { CO_error(0x11100000L + errno); } } else if (taskMain_process(ev.data.fd, &reset, CO_timer1ms)) { uint32_t timer1msDiff; timer1msDiff = CO_timer1ms - tmr1msPrev; tmr1msPrev = CO_timer1ms; /* Execute optional additional alication code */ app_programAsync(timer1msDiff); } else { /* No file descriptor was processed. */ CO_error(0x11200000L); } reset = reset_local; } } /* program exit ***************************************************************/ //End application first endProgram = 1; if (pthread_join(rt_control_thread_id, NULL) != 0) { CO_errExit("Program end - pthread_join failed"); } usleep(500000); /*wait for last CAN commands to be processed if any */ //End CAN communication processing CO_endProgram = 1; if (pthread_join(rt_thread_id, NULL) != 0) { CO_errExit("Program end - pthread_join failed"); } /* delete objects from memory */ CANrx_taskTmr_close(); taskMain_close(); CO_delete(CANdevice0Index); spdlog::info("Canopend on {} (nodeId={}) - finished.", CANdevice, nodeId); /* Flush all buffers (and reboot) */ if (rebootEnable && reset == CO_RESET_APP) { sync(); if (reboot(LINUX_REBOOT_CMD_RESTART) != 0) { CO_errExit("Program end - reboot failed"); } } exit(EXIT_SUCCESS); } } /* Function for CAN send, receive and taskTmr ********************************/ static void *rt_thread(void *arg) { while (CO_endProgram == 0) { struct epoll_event ev; int ready = epoll_wait(rt_thread_epoll_fd, &ev, 1, -1); if (ready != 1) { if (errno != EINTR) { CO_error(0x12100000L + errno); } } else if (CANrx_taskTmr_process(ev.data.fd)) { /* code was processed in the above function. Additional code process below */ INCREMENT_1MS(CO_timer1ms); /* Monitor variables with trace objects */ CO_time_process(&CO_time); #if CO_NO_TRACE > 0 for (i = 0; i < OD_traceEnable && i < CO_NO_TRACE; i++) { CO_trace_process(CO->trace[i], *CO_time.epochTimeOffsetMs); } #endif /* Detect timer large overflow */ if (OD_performance[ODA_performance_timerCycleMaxTime] > TMR_TASK_OVERFLOW_US && rtPriority > 0 && CO->CANmodule[0]->CANnormal) { CO_errorReport(CO->em, CO_EM_ISR_TIMER_OVERFLOW, CO_EMC_SOFTWARE_INTERNAL, 0x22400000L | OD_performance[ODA_performance_timerCycleMaxTime]); } } else { /* No file descriptor was processed. */ CO_error(0x12200000L); } } return NULL; } /* Control thread function ********************************/ static void *rt_control_thread(void *arg) { struct period_info pinfo; periodic_task_init(&pinfo); app_programStart(); wait_rest_of_period(&pinfo); while (!readyToStart) { wait_rest_of_period(&pinfo); } while (endProgram == 0) { periodic_task_init(&pinfo); app_programControlLoop(); wait_rest_of_period(&pinfo); } app_programEnd(); return NULL; } /* Control thread time functions ********************************/ static void inc_period(struct period_info *pinfo) { pinfo->next_period.tv_nsec += pinfo->period_ns; while (pinfo->next_period.tv_nsec >= 1000000000) { /* timespec nsec overflow */ pinfo->next_period.tv_sec++; pinfo->next_period.tv_nsec -= 1000000000; } } static void periodic_task_init(struct period_info *pinfo) { /* for simplicity, hardcoding a 1ms period */ pinfo->period_ns = controlLoopPeriodInms * 1000000; clock_gettime(CLOCK_MONOTONIC, &(pinfo->next_period)); } static void wait_rest_of_period(struct period_info *pinfo) { inc_period(pinfo); /* for simplicity, ignoring possibilities of signal wakes */ clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &pinfo->next_period, NULL); } /* CAN messaging helper functions ********************************/ void configureCANopen(int nodeId, int rtPriority, int CANdevice0Index, char *CANdevice) { if (nodeId < 1 || nodeId > 127) { fprintf(stderr, "NODE ID outside range (%d)\n", nodeId); exit(EXIT_FAILURE); } // rt Thread priority sanity check if (rtPriority != -1 && (rtPriority < sched_get_priority_min(SCHED_FIFO) || rtPriority > sched_get_priority_max(SCHED_FIFO))) { spdlog::critical("Wrong RT priority ({})", rtPriority); exit(EXIT_FAILURE); } if (CANdevice0Index == 0) { spdlog::critical("Can't find any CAN device"); exit(EXIT_FAILURE); } /* Verify, if OD structures have proper alignment of initial values */ if (CO_OD_RAM.FirstWord != CO_OD_RAM.LastWord) { spdlog::critical("Program init - Canopend- Error in CO_OD_RAM."); exit(EXIT_FAILURE); } }; void CO_errExit(char const *msg) { spdlog::critical(msg); exit(EXIT_FAILURE); } void CO_error(const uint32_t info) { CO_errorReport(CO->em, CO_EM_GENERIC_SOFTWARE_ERROR, CO_EMC_SOFTWARE_INTERNAL, info); //fprintf(stderr, "canopend generic error: 0x%X\n", info); spdlog::error("canopend generic error: {}", info); }
42.221198
221
0.606036
[ "object" ]
02f7546e4aa884f1b5ef9df60ba24322a16323f6
12,538
cpp
C++
android/android_9/frameworks/rs/rsov/compiler/Builtin.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
android/android_9/frameworks/rs/rsov/compiler/Builtin.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
android/android_9/frameworks/rs/rsov/compiler/Builtin.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
/* * Copyright 2017, The Android Open Source Project * * 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. */ #include "Builtin.h" #include "cxxabi.h" #include "spirit.h" #include "transformer.h" #include <stdint.h> #include <map> #include <string> #include <vector> namespace android { namespace spirit { namespace { Instruction *translateClampVector(const char *name, const FunctionCallInst *call, Transformer *tr, Builder *b, Module *m) { int width = name[10] - '0'; if (width < 2 || width > 4) { return nullptr; } uint32_t extOpCode = 0; switch (name[strlen(name) - 1]) { case 'f': extOpCode = 43; break; // FClamp // TODO: Do we get _Z5clampDV_uuu at all? Does LLVM convert u into i? case 'u': extOpCode = 44; break; // UClamp case 'i': extOpCode = 45; break; // SClamp default: return nullptr; } std::vector<IdRef> minConstituents(width, call->mOperand2[1]); std::unique_ptr<Instruction> min( b->MakeCompositeConstruct(call->mResultType, minConstituents)); tr->insert(min.get()); std::vector<IdRef> maxConstituents(width, call->mOperand2[2]); std::unique_ptr<Instruction> max( b->MakeCompositeConstruct(call->mResultType, maxConstituents)); tr->insert(max.get()); std::vector<IdRef> extOpnds = {call->mOperand2[0], min.get(), max.get()}; return b->MakeExtInst(call->mResultType, m->getGLExt(), extOpCode, extOpnds); } Instruction *translateExtInst(const uint32_t extOpCode, const FunctionCallInst *call, Builder *b, Module *m) { return b->MakeExtInst(call->mResultType, m->getGLExt(), extOpCode, {call->mOperand2[0]}); } } // anonymous namespace typedef std::function<Instruction *(const char *, const FunctionCallInst *, Transformer *, Builder *, Module *)> InstTrTy; class BuiltinLookupTable { public: BuiltinLookupTable() { for (sNameCode const *p = &mFPMathFuncOpCode[0]; p->name; p++) { const char *name = p->name; const uint32_t extOpCode = p->code; addMapping(name, {"*"}, {{"float+"}}, {1, 2, 3, 4}, [extOpCode](const char *, const FunctionCallInst *call, Transformer *, Builder *b, Module *m) { return translateExtInst(extOpCode, call, b, m); }); } addMapping("abs", {"*"}, {{"int+"}, {"char+"}}, {1, 2, 3, 4}, [](const char *, const FunctionCallInst *call, Transformer *, Builder *b, Module *m) { return translateExtInst(5, call, b, m); // SAbs }); addMapping("clamp", {"*"}, {{"int+", "int", "int"}, {"float+", "float", "float"}}, {1, 2, 3, 4}, [](const char *name, const FunctionCallInst *call, Transformer *tr, Builder *b, Module *m) { return translateClampVector(name, call, tr, b, m); }); addMapping("convert", {"char+", "int+", "uchar+", "uint+"}, {{"char+"}, {"int+"}, {"uchar+"}, {"uint+"}}, {1, 2, 3, 4}, [](const char *, const FunctionCallInst *call, Transformer *, Builder *b, Module *) -> Instruction * { return b->MakeUConvert(call->mResultType, call->mOperand2[0]); }); addMapping( "convert", {"char+", "int+", "uchar+", "uint+"}, {{"float+"}}, {1, 2, 3, 4}, [](const char *, const FunctionCallInst *call, Transformer *, Builder *b, Module *) -> Instruction * { return b->MakeConvertFToU(call->mResultType, call->mOperand2[0]); }); addMapping( "convert", {"float+"}, {{"char+"}, {"int+"}, {"uchar+"}, {"uint+"}}, {1, 2, 3, 4}, [](const char *, const FunctionCallInst *call, Transformer *, Builder *b, Module *) { return b->MakeConvertUToF(call->mResultType, call->mOperand2[0]); }); addMapping("dot", {"*"}, {{"float+"}}, {1, 2, 3, 4}, [](const char *, const FunctionCallInst *call, Transformer *, Builder *b, Module *) { return b->MakeDot(call->mResultType, call->mOperand2[0], call->mOperand2[1]); }); addMapping("min", {"*"}, {{"uint+"}, {"uchar+"}}, {1, 2, 3, 4}, [](const char *, const FunctionCallInst *call, Transformer *, Builder *b, Module *m) { return translateExtInst(38, call, b, m); // UMin }); addMapping("min", {"*"}, {{"int+"}, {"char+"}}, {1, 2, 3, 4}, [](const char *, const FunctionCallInst *call, Transformer *, Builder *b, Module *m) { return translateExtInst(39, call, b, m); // SMin }); addMapping("max", {"*"}, {{"uint+"}, {"uchar+"}}, {1, 2, 3, 4}, [](const char *, const FunctionCallInst *call, Transformer *, Builder *b, Module *m) { return translateExtInst(41, call, b, m); // UMax }); addMapping("max", {"*"}, {{"int+"}, {"char+"}}, {1, 2, 3, 4}, [](const char *, const FunctionCallInst *call, Transformer *, Builder *b, Module *m) { return translateExtInst(42, call, b, m); // SMax }); addMapping("rsUnpackColor8888", {"*"}, {{"uchar+"}}, {4}, [](const char *, const FunctionCallInst *call, Transformer *, Builder *b, Module *m) { auto cast = b->MakeBitcast(m->getUnsignedIntType(32), call->mOperand2[0]); return b->MakeExtInst(call->mResultType, m->getGLExt(), 64, {cast}); // UnpackUnorm4x8 }); addMapping("rsPackColorTo8888", {"*"}, {{"float+"}}, {4}, [](const char *, const FunctionCallInst *call, Transformer *, Builder *b, Module *m) { // PackUnorm4x8 auto packed = b->MakeExtInst(call->mResultType, m->getGLExt(), 55, {call->mOperand2[0]}); return b->MakeBitcast( m->getVectorType(m->getUnsignedIntType(8), 4), packed); }); } static const BuiltinLookupTable &getInstance() { static BuiltinLookupTable table; return table; } void addMapping(const char *funcName, const std::vector<std::string> &retTypes, const std::vector<std::vector<std::string>> &argTypes, const std::vector<uint8_t> &vecWidths, InstTrTy fp) { for (auto width : vecWidths) { for (auto retType : retTypes) { std::string suffixed(funcName); if (retType != "*") { if (retType.back() == '+') { retType.pop_back(); if (width > 1) { retType.append(1, '0' + width); } } suffixed.append("_").append(retType); } for (auto argList : argTypes) { std::string args("("); bool first = true; for (auto argType : argList) { if (first) { first = false; } else { args.append(", "); } if (argType.front() == 'u') { argType.replace(0, 1, "unsigned "); } if (argType.back() == '+') { argType.pop_back(); if (width > 1) { argType.append(" vector["); argType.append(1, '0' + width); argType.append("]"); } } args.append(argType); } args.append(")"); mFuncNameMap[suffixed + args] = fp; } } } } InstTrTy lookupTranslation(const char *mangled) const { const char *demangled = __cxxabiv1::__cxa_demangle(mangled, nullptr, nullptr, nullptr); if (!demangled) { // All RS runtime/builtin functions are overloaded, therefore // name-mangled. return nullptr; } std::string strDemangled(demangled); auto it = mFuncNameMap.find(strDemangled); if (it == mFuncNameMap.end()) { return nullptr; } return it->second; } private: std::map<std::string, InstTrTy> mFuncNameMap; struct sNameCode { const char *name; uint32_t code; }; static sNameCode constexpr mFPMathFuncOpCode[] = { {"abs", 4}, {"sin", 13}, {"cos", 14}, {"tan", 15}, {"asin", 16}, {"acos", 17}, {"atan", 18}, {"sinh", 19}, {"cosh", 20}, {"tanh", 21}, {"asinh", 22}, {"acosh", 23}, {"atanh", 24}, {"atan2", 25}, {"pow", 26}, {"exp", 27}, {"log", 28}, {"exp2", 29}, {"log2", 30}, {"sqrt", 31}, {"modf", 35}, {"min", 37}, {"max", 40}, {"length", 66}, {"normalize", 69}, {nullptr, 0}, }; }; // BuiltinLookupTable BuiltinLookupTable::sNameCode constexpr BuiltinLookupTable::mFPMathFuncOpCode[]; class BuiltinTransformer : public Transformer { public: // BEGIN: cleanup unrelated to builtin functions, but necessary for LLVM-SPIRV // converter generated code. // TODO: Move these in its own pass std::vector<uint32_t> runAndSerialize(Module *module, int *error) override { module->addExtInstImport("GLSL.std.450"); return Transformer::runAndSerialize(module, error); } Instruction *transform(CapabilityInst *inst) override { // Remove capabilities Address, Linkage, and Kernel. if (inst->mOperand1 == Capability::Addresses || inst->mOperand1 == Capability::Linkage || inst->mOperand1 == Capability::Kernel) { return nullptr; } return inst; } Instruction *transform(ExtInstImportInst *inst) override { if (inst->mOperand1.compare("OpenCL.std") == 0) { return nullptr; } return inst; } Instruction *transform(InBoundsPtrAccessChainInst *inst) override { // Transform any OpInBoundsPtrAccessChain instruction to an // OpInBoundsAccessChain instruction, since the former is not allowed by // the Vulkan validation rules. auto newInst = mBuilder.MakeInBoundsAccessChain(inst->mResultType, inst->mOperand1, inst->mOperand3); newInst->setId(inst->getId()); return newInst; } Instruction *transform(SourceInst *inst) override { if (inst->mOperand1 == SourceLanguage::Unknown) { return nullptr; } return inst; } Instruction *transform(DecorateInst *inst) override { if (inst->mOperand2 == Decoration::LinkageAttributes || inst->mOperand2 == Decoration::Alignment) { return nullptr; } return inst; } // END: cleanup unrelated to builtin functions Instruction *transform(FunctionCallInst *call) { FunctionInst *func = static_cast<FunctionInst *>(call->mOperand1.mInstruction); // TODO: attach name to the instruction to avoid linear search in the debug // section, i.e., // const char *name = func->getName(); const char *name = getModule()->lookupNameByInstruction(func); if (!name) { return call; } // Maps name into a SPIR-V instruction auto fpTranslate = BuiltinLookupTable::getInstance().lookupTranslation(name); if (!fpTranslate) { return call; } Instruction *inst = fpTranslate(name, call, this, &mBuilder, getModule()); if (inst) { inst->setId(call->getId()); } return inst; } private: Builder mBuilder; }; } // namespace spirit } // namespace android namespace rs2spirv { android::spirit::Pass *CreateBuiltinPass() { return new android::spirit::BuiltinTransformer(); } } // namespace rs2spirv
33.613941
80
0.543548
[ "vector", "transform" ]
02f863514d823741191afde8da6beb9c209de54e
97,788
cc
C++
bench/convolution.cc
shi510/XNNPACK
ea2088b668b760cdc5c67df7d2854320ee34aeb8
[ "BSD-3-Clause" ]
null
null
null
bench/convolution.cc
shi510/XNNPACK
ea2088b668b760cdc5c67df7d2854320ee34aeb8
[ "BSD-3-Clause" ]
null
null
null
bench/convolution.cc
shi510/XNNPACK
ea2088b668b760cdc5c67df7d2854320ee34aeb8
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) Facebook, Inc. and its affiliates. // All rights reserved. // // Copyright 2019 Google LLC // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. #include <algorithm> #include <cfloat> #include <cmath> #include <functional> #include <limits> #include <ostream> #include <random> #include <string> #include <vector> #include <cpuinfo.h> #include <xnnpack.h> #ifdef BENCHMARK_ARM_COMPUTE_LIBRARY #include "arm_compute/core/Types.h" #include "arm_compute/runtime/Tensor.h" #include "arm_compute/runtime/CPP/CPPScheduler.h" #include "arm_compute/runtime/NEON/functions/NEDepthwiseConvolutionLayer.h" #include "arm_compute/runtime/NEON/functions/NEConvolutionLayer.h" #endif // BENCHMARK_ARM_COMPUTE_LIBRARY #include <benchmark/benchmark.h> #ifdef BENCHMARK_TENSORFLOW_LITE #include "flatbuffers/include/flatbuffers/flatbuffers.h" #include "tensorflow/lite/interpreter.h" #include "tensorflow/lite/kernels/register.h" #include "tensorflow/lite/model.h" #include "tensorflow/lite/schema/schema_generated.h" #include "tensorflow/lite/version.h" #endif // BENCHMARK_TENSORFLOW_LITE #include "bench/utils.h" void xnnpack_convolution_q8(benchmark::State& state, const char* net) { const size_t batch_size = state.range(0); const size_t input_height = state.range(1); const size_t input_width = state.range(2); const size_t kernel_height = state.range(3); const size_t kernel_width = state.range(4); const size_t padding_height = state.range(5); const size_t padding_width = state.range(6); const size_t subsampling = state.range(7); const size_t dilation = state.range(8); const size_t groups = state.range(9); const size_t group_input_channels = state.range(10); const size_t group_output_channels = state.range(11); std::random_device random_device; auto rng = std::mt19937(random_device()); auto s32rng = std::bind(std::uniform_int_distribution<int32_t>(-10000, 10000), rng); auto u8rng = std::bind(std::uniform_int_distribution<uint32_t>(0, std::numeric_limits<uint8_t>::max()), rng); const size_t output_pixel_stride = groups * group_output_channels; const size_t input_pixel_stride = groups * group_input_channels; const size_t effective_kernel_height = (kernel_height - 1) * dilation + 1; const size_t effective_kernel_width = (kernel_width - 1) * dilation + 1; const size_t padding_left = padding_width / 2; const size_t padding_top = padding_height / 2; const size_t padding_right = padding_width - padding_left; const size_t padding_bottom = padding_height - padding_top; const size_t output_height = (input_height + padding_height - effective_kernel_height) / subsampling + 1; const size_t output_width = (input_width + padding_width - effective_kernel_width) / subsampling + 1; std::vector<uint8_t> input(batch_size * input_height * input_width * input_pixel_stride); std::generate(input.begin(), input.end(), std::ref(u8rng)); std::vector<uint8_t> kernel(groups * group_output_channels * kernel_height * kernel_width * group_input_channels); std::generate(kernel.begin(), kernel.end(), std::ref(u8rng)); std::vector<int32_t> bias(groups * group_output_channels); std::generate(bias.begin(), bias.end(), std::ref(s32rng)); const size_t output_elements = batch_size * output_height * output_width * output_pixel_stride; xnn_status status = xnn_initialize(nullptr /* allocator */); if (status != xnn_status_success) { state.SkipWithError("failed to initialize XNNPACK"); return; } if (!cpuinfo_initialize()) { state.SkipWithError("cpuinfo initialization failed"); return; } const size_t num_buffers = 1 + benchmark::utils::DivideRoundUp<size_t>(benchmark::utils::GetMaxCacheSize(), sizeof(uint8_t) * kernel.size() + sizeof(int32_t) * bias.size() + sizeof(uint8_t) * output_elements); std::vector<uint8_t> output(output_elements * num_buffers); std::vector<xnn_operator_t> convolution_operators(num_buffers); for (xnn_operator_t& convolution_op : convolution_operators) { status = xnn_create_convolution2d_nhwc_q8( padding_top, padding_right, padding_bottom, padding_left, kernel_height, kernel_width, subsampling, subsampling, dilation, dilation, groups, group_input_channels, group_output_channels, input_pixel_stride, output_pixel_stride, 127, 0.5f, 127, 0.5f, kernel.data(), bias.data(), 127, 0.5f, 0, 255, 0 /* flags */, &convolution_op); if (status != xnn_status_success) { state.SkipWithError("failed to create QINT8 Convolution operator"); return; } } for (size_t i = 0; i < convolution_operators.size(); i++) { status = xnn_setup_convolution2d_nhwc_q8( convolution_operators[i], batch_size, input_height, input_width, input.data(), output.data() + i * output_elements, nullptr /* thread pool */); if (status != xnn_status_success) { state.SkipWithError("failed to setup QINT8 Convolution operator"); return; } } size_t buffer_index = 0; for (auto _ : state) { state.PauseTiming(); benchmark::utils::PrefetchToL1(input.data(), input.size() * sizeof(uint8_t)); buffer_index = (buffer_index + 1) % num_buffers; state.ResumeTiming(); status = xnn_run_operator(convolution_operators[buffer_index], nullptr /* thread pool */); if (status != xnn_status_success) { state.SkipWithError("failed to run QINT8 Convolution operator"); return; } } for (xnn_operator_t& convolution_op : convolution_operators) { status = xnn_delete_operator(convolution_op); if (status != xnn_status_success) { state.SkipWithError("failed to delete QINT8 Convolution operator"); return; } convolution_op = nullptr; } state.counters["Freq"] = benchmark::utils::GetCurrentCpuFrequency(); state.counters["OPS"] = benchmark::Counter( uint64_t(state.iterations()) * 2 * batch_size * output_height * output_width * groups * group_input_channels * group_output_channels * kernel_height * kernel_width, benchmark::Counter::kIsRate); } void xnnpack_convolution_f32(benchmark::State& state, const char* net) { const size_t batch_size = state.range(0); const size_t input_height = state.range(1); const size_t input_width = state.range(2); const size_t kernel_height = state.range(3); const size_t kernel_width = state.range(4); const size_t padding_height = state.range(5); const size_t padding_width = state.range(6); const size_t subsampling = state.range(7); const size_t dilation = state.range(8); const size_t groups = state.range(9); const size_t group_input_channels = state.range(10); const size_t group_output_channels = state.range(11); std::random_device random_device; auto rng = std::mt19937(random_device()); auto f32rng = std::bind(std::uniform_real_distribution<float>(0.0f, 1.0f), rng); const size_t output_pixel_stride = groups * group_output_channels; const size_t input_pixel_stride = groups * group_input_channels; const size_t effective_kernel_height = (kernel_height - 1) * dilation + 1; const size_t effective_kernel_width = (kernel_width - 1) * dilation + 1; const size_t padding_left = padding_width / 2; const size_t padding_top = padding_height / 2; const size_t padding_right = padding_width - padding_left; const size_t padding_bottom = padding_height - padding_top; const size_t output_height = (input_height + padding_height - effective_kernel_height) / subsampling + 1; const size_t output_width = (input_width + padding_width - effective_kernel_width) / subsampling + 1; std::vector<float> input(batch_size * input_height * input_width * input_pixel_stride + XNN_EXTRA_BYTES / sizeof(float)); std::generate(input.begin(), input.end(), std::ref(f32rng)); std::vector<float> kernel(groups * group_output_channels * kernel_height * kernel_width * group_input_channels); std::generate(kernel.begin(), kernel.end(), std::ref(f32rng)); std::vector<float> bias(groups * group_output_channels); std::generate(bias.begin(), bias.end(), std::ref(f32rng)); const size_t output_elements = batch_size * output_height * output_width * output_pixel_stride; xnn_status status = xnn_initialize(nullptr /* allocator */); if (status != xnn_status_success) { state.SkipWithError("failed to initialize XNNPACK"); return; } if (!cpuinfo_initialize()) { state.SkipWithError("cpuinfo initialization failed"); return; } const size_t num_buffers = 1 + benchmark::utils::DivideRoundUp<size_t>(benchmark::utils::GetMaxCacheSize(), sizeof(float) * (kernel.size() + bias.size() + output_elements)); std::vector<float> output(output_elements * num_buffers); std::vector<xnn_operator_t> convolution_operators(num_buffers); for (xnn_operator_t& convolution_op : convolution_operators) { status = xnn_create_convolution2d_nhwc_f32( padding_top, padding_right, padding_bottom, padding_left, kernel_height, kernel_width, subsampling, subsampling, dilation, dilation, groups, group_input_channels, group_output_channels, input_pixel_stride, output_pixel_stride, kernel.data(), bias.data(), -std::numeric_limits<float>::infinity(), +std::numeric_limits<float>::infinity(), 0 /* flags */, &convolution_op); if (status != xnn_status_success) { state.SkipWithError("failed to create FP32 Convolution operator"); return; } } for (size_t i = 0; i < convolution_operators.size(); i++) { status = xnn_setup_convolution2d_nhwc_f32( convolution_operators[i], batch_size, input_height, input_width, input.data(), output.data() + i * output_elements, nullptr /* thread pool */); if (status != xnn_status_success) { state.SkipWithError("failed to setup FP32 Convolution operator"); return; } } size_t buffer_index = 0; for (auto _ : state) { state.PauseTiming(); benchmark::utils::PrefetchToL1(input.data(), input.size() * sizeof(float)); buffer_index = (buffer_index + 1) % num_buffers; state.ResumeTiming(); status = xnn_run_operator(convolution_operators[buffer_index], nullptr /* thread pool */); if (status != xnn_status_success) { state.SkipWithError("failed to run FP32 Convolution operator"); return; } } for (xnn_operator_t& convolution_op : convolution_operators) { status = xnn_delete_operator(convolution_op); if (status != xnn_status_success) { state.SkipWithError("failed to delete FP32 Convolution operator"); return; } convolution_op = nullptr; } state.counters["Freq"] = benchmark::utils::GetCurrentCpuFrequency(); state.counters["FLOPS"] = benchmark::Counter( uint64_t(state.iterations()) * 2 * batch_size * output_height * output_width * groups * group_input_channels * group_output_channels * kernel_height * kernel_width, benchmark::Counter::kIsRate); } #ifdef BENCHMARK_TENSORFLOW_LITE void tflite_convolution_f32(benchmark::State& state, const char* net) { const size_t batch_size = state.range(0); const size_t input_height = state.range(1); const size_t input_width = state.range(2); const size_t kernel_height = state.range(3); const size_t kernel_width = state.range(4); const size_t padding_height = state.range(5); const size_t padding_width = state.range(6); const size_t subsampling = state.range(7); const size_t dilation = state.range(8); const size_t groups = state.range(9); const size_t group_input_channels = state.range(10); const size_t group_output_channels = state.range(11); bool is_depthwise = false; if (groups != 1) { if (group_input_channels == 1) { is_depthwise = true; } else { state.SkipWithError("grouped convolution is not supported"); return; } } std::random_device random_device; auto rng = std::mt19937(random_device()); auto f32rng = std::bind(std::uniform_real_distribution<float>(0.0f, 1.0f), rng); const size_t effective_kernel_height = (kernel_height - 1) * dilation + 1; const size_t effective_kernel_width = (kernel_width - 1) * dilation + 1; tflite::Padding padding = tflite::Padding_VALID; if (padding_width == (effective_kernel_width - 1) && padding_height == (effective_kernel_height - 1)) { padding = tflite::Padding_SAME; } else if (padding_width == 0 && padding_height == 0) { padding = tflite::Padding_VALID; } else { state.SkipWithError("unsupported padding"); return; } const size_t output_height = (input_height + padding_height - effective_kernel_height) / subsampling + 1; const size_t output_width = (input_width + padding_width - effective_kernel_width) / subsampling + 1; std::vector<float> kernel(groups * group_output_channels * kernel_height * kernel_width * group_input_channels); std::generate(kernel.begin(), kernel.end(), std::ref(f32rng)); std::vector<float> bias(groups * group_output_channels); std::generate(bias.begin(), bias.end(), std::ref(f32rng)); flatbuffers::FlatBufferBuilder builder; flatbuffers::Offset<tflite::OperatorCode> operator_code = CreateOperatorCode( builder, is_depthwise ? tflite::BuiltinOperator_DEPTHWISE_CONV_2D : tflite::BuiltinOperator_CONV_2D, 0); flatbuffers::Offset<tflite::Conv2DOptions> conv2d_options = CreateConv2DOptions( builder, padding, static_cast<int32_t>(subsampling), static_cast<int32_t>(subsampling), tflite::ActivationFunctionType_NONE, static_cast<int32_t>(dilation), static_cast<int32_t>(dilation)); flatbuffers::Offset<tflite::DepthwiseConv2DOptions> dwconv2d_options = CreateDepthwiseConv2DOptions( builder, padding, static_cast<int32_t>(subsampling), static_cast<int32_t>(subsampling), static_cast<int32_t>(group_output_channels), tflite::ActivationFunctionType_NONE, static_cast<int32_t>(dilation), static_cast<int32_t>(dilation)); flatbuffers::Offset<tflite::Buffer> buffers[3] = { tflite::CreateBuffer(builder, builder.CreateVector({})), tflite::CreateBuffer(builder, builder.CreateVector( reinterpret_cast<const uint8_t*>(kernel.data()), sizeof(float) * kernel.size())), tflite::CreateBuffer(builder, builder.CreateVector( reinterpret_cast<const uint8_t*>(bias.data()), sizeof(float) * bias.size())), }; const int32_t input_shape[4] = { static_cast<int32_t>(batch_size), static_cast<int32_t>(input_height), static_cast<int32_t>(input_width), static_cast<int32_t>(groups * group_input_channels) }; const int32_t output_shape[4] = { static_cast<int32_t>(batch_size), static_cast<int32_t>(output_height), static_cast<int32_t>(output_width), static_cast<int32_t>(groups * group_output_channels) }; const int32_t filter_shape[4] = { static_cast<int32_t>(group_output_channels), static_cast<int32_t>(kernel_height), static_cast<int32_t>(kernel_width), static_cast<int32_t>(groups * group_input_channels) }; const int32_t bias_shape[1] = { static_cast<int32_t>(groups * group_output_channels) }; flatbuffers::Offset<tflite::Tensor> tensors[4] = { tflite::CreateTensor(builder, builder.CreateVector<int32_t>(input_shape, 4), tflite::TensorType_FLOAT32, 0 /* buffer id */, builder.CreateString("input")), tflite::CreateTensor(builder, builder.CreateVector<int32_t>(filter_shape, 4), tflite::TensorType_FLOAT32, 1 /* buffer id */, builder.CreateString("filter")), tflite::CreateTensor(builder, builder.CreateVector<int32_t>(bias_shape, 1), tflite::TensorType_FLOAT32, 2 /* buffer id */, builder.CreateString("bias")), tflite::CreateTensor(builder, builder.CreateVector<int32_t>(output_shape, 4), tflite::TensorType_FLOAT32, 0 /* buffer id */, builder.CreateString("output")), }; const int32_t op_inputs[3] = { 0, 1, 2 }; const int32_t op_outputs[1] = { 3 }; flatbuffers::Offset<tflite::Operator> op = CreateOperator( builder, 0 /* opcode_index */, builder.CreateVector<int32_t>(op_inputs, 3), builder.CreateVector<int32_t>(op_outputs, 1), is_depthwise ? tflite::BuiltinOptions_DepthwiseConv2DOptions : tflite::BuiltinOptions_Conv2DOptions, is_depthwise ? dwconv2d_options.Union() : conv2d_options.Union(), /*custom_options */ 0, tflite::CustomOptionsFormat_FLEXBUFFERS); const int32_t graph_inputs[1] = { 0 }; const int32_t graph_outputs[1] = { 3 }; flatbuffers::Offset<tflite::SubGraph> subgraph = CreateSubGraph( builder, builder.CreateVector(tensors, 4), builder.CreateVector<int32_t>(graph_inputs, 1), builder.CreateVector<int32_t>(graph_outputs, 1), builder.CreateVector(&op, 1), builder.CreateString("Conv2D subgraph")); flatbuffers::Offset<flatbuffers::String> description = builder.CreateString("Conv2D model"); flatbuffers::Offset<tflite::Model> model_buffer = tflite::CreateModel(builder, TFLITE_SCHEMA_VERSION, builder.CreateVector(&operator_code, 1), builder.CreateVector(&subgraph, 1), description, builder.CreateVector(buffers, 3)); builder.Finish(model_buffer); const tflite::Model* model = tflite::GetModel(builder.GetBufferPointer()); tflite::ops::builtin::BuiltinOpResolver resolver; tflite::InterpreterBuilder interpreterBuilder(model, resolver); std::unique_ptr<tflite::Interpreter> interpreter; if (interpreterBuilder(&interpreter) != kTfLiteOk) { state.SkipWithError("failed to create TFLite interpreter"); return; } if (interpreter == nullptr) { state.SkipWithError("TFLite interpreter is null"); return; } interpreter->SetNumThreads(1); if (interpreter->AllocateTensors() != kTfLiteOk) { state.SkipWithError("failed to allocate tensors"); return; } std::generate( interpreter->typed_tensor<float>(0), interpreter->typed_tensor<float>(0) + batch_size * groups * group_input_channels * input_height * input_width, std::ref(f32rng)); for (auto _ : state) { state.PauseTiming(); benchmark::utils::WipeCache(); benchmark::utils::PrefetchToL1( interpreter->typed_tensor<float>(0), batch_size * groups * group_input_channels * input_height * input_width * sizeof(float)); state.ResumeTiming(); if (interpreter->Invoke() != kTfLiteOk) { state.SkipWithError("failed to invoke TFLite interpreter"); return; } } state.counters["Freq"] = benchmark::utils::GetCurrentCpuFrequency(); state.counters["FLOPS"] = benchmark::Counter( uint64_t(state.iterations()) * 2 * batch_size * output_height * output_width * groups * group_input_channels * group_output_channels * kernel_height * kernel_width, benchmark::Counter::kIsRate); interpreter.reset(); } #endif // BENCHMARK_TENSORFLOW_LITE #ifdef BENCHMARK_ARM_COMPUTE_LIBRARY static std::string compare_with_convolution_f32_reference_output( const benchmark::State& state, const float* input, size_t input_size, const float* kernel, size_t kernel_size, const float* bias, size_t bias_size, const float* output, size_t output_size) { const size_t batch_size = state.range(0); const size_t input_height = state.range(1); const size_t input_width = state.range(2); const size_t kernel_height = state.range(3); const size_t kernel_width = state.range(4); const size_t padding_height = state.range(5); const size_t padding_width = state.range(6); const size_t subsampling = state.range(7); const size_t dilation = state.range(8); const size_t groups = state.range(9); const size_t group_input_channels = state.range(10); const size_t group_output_channels = state.range(11); const size_t effective_kernel_height = (kernel_height - 1) * dilation + 1; const size_t effective_kernel_width = (kernel_width - 1) * dilation + 1; const size_t output_height = (input_height + padding_height - effective_kernel_height) / subsampling + 1; const size_t output_width = (input_width + padding_width - effective_kernel_width) / subsampling + 1; const size_t input_pixel_stride = groups * group_input_channels; const size_t padding_left = padding_width / 2; const size_t padding_top = padding_height / 2; assert(input_size == batch_size * input_height * input_width * groups * group_input_channels); assert(kernel_size == group_output_channels * kernel_height * kernel_width * groups * group_input_channels); assert(bias_size == groups * group_output_channels); assert(output_size == batch_size * output_height * output_width * groups * group_output_channels); std::vector<float> output_ref(output_size); for (size_t i = 0; i < batch_size; i++) { for (size_t oy = 0; oy < output_height; oy++) { for (size_t ox = 0; ox < output_width; ox++) { for (size_t g = 0; g < groups; g++) { for (size_t oc = 0; oc < group_output_channels; oc++) { output_ref[(((i * output_height + oy) * output_width + ox) * groups + g) * group_output_channels + oc] = bias[g * group_output_channels + oc]; } } } } } for (size_t i = 0; i < batch_size; i++) { for (size_t oy = 0; oy < output_height; oy++) { for (size_t ox = 0; ox < output_width; ox++) { for (size_t ky = 0; ky < kernel_height; ky++) { const size_t iy = oy * subsampling + ky * dilation - padding_top; if (iy < input_height) { for (size_t kx = 0; kx < kernel_width; kx++) { const size_t ix = ox * subsampling + kx * dilation - padding_left; if (ix < input_width) { for (size_t g = 0; g < groups; g++) { for (size_t oc = 0; oc < group_output_channels; oc++) { for (size_t ic = 0; ic < group_input_channels; ic++) { output_ref[(((i * output_height + oy) * output_width + ox) * groups + g) * group_output_channels + oc] += input[((i * input_height + iy) * input_width + ix) * input_pixel_stride + g * group_input_channels + ic] * kernel[(((oc * kernel_height + ky) * kernel_width + kx) * groups + g) * group_input_channels + ic]; } // group_input_channels loop } // group_output_channels loop } // groups loop } } // kernel_width loop } } // kernel_height loop } // output_width loop } // output_height loop } // batch_size loop const float relative_error_tolerance = 1e-4; for (size_t i = 0; i < batch_size; i++) { for (size_t y = 0; y < output_height; y++) { for (size_t x = 0; x < output_width; x++) { for (size_t g = 0; g < groups; g++) { for (size_t c = 0; c < group_output_channels; c++) { const size_t idx = (((i * output_height + y) * output_width + x) * groups + g) * group_output_channels + c; const float value_ref = output_ref[idx]; const float value = output[idx]; if (std::abs(value - value_ref) > std::max(std::abs(value_ref) * relative_error_tolerance, std::numeric_limits<float>::epsilon())) { std::ostringstream error_stream; error_stream << "(x, y) = (" << x << ", " << y << "), group = " << g << ", channel = " << c << ", refValue = " << value_ref << ", actualValue = " << value << ", absDiff=" << std::abs(value - value_ref); return error_stream.str(); } } } } } } return ""; } void armcl_convolution_f32(benchmark::State& state, const char* net) { const size_t batch_size = state.range(0); const size_t input_height = state.range(1); const size_t input_width = state.range(2); const size_t kernel_height = state.range(3); const size_t kernel_width = state.range(4); const size_t padding_height = state.range(5); const size_t padding_width = state.range(6); const size_t subsampling = state.range(7); const size_t dilation = state.range(8); const size_t groups = state.range(9); const size_t group_input_channels = state.range(10); const size_t group_output_channels = state.range(11); const size_t effective_kernel_height = (kernel_height - 1) * dilation + 1; const size_t effective_kernel_width = (kernel_width - 1) * dilation + 1; const size_t padding_left = padding_width / 2; const size_t padding_top = padding_height / 2; const size_t padding_right = padding_width - padding_left; const size_t padding_bottom = padding_height - padding_top; const size_t output_height = (input_height + padding_height - effective_kernel_height) / subsampling + 1; const size_t output_width = (input_width + padding_width - effective_kernel_width) / subsampling + 1; arm_compute::PadStrideInfo pad_stride_info( subsampling /* stride height */, subsampling /* stride width */, padding_left, padding_right, padding_top, padding_bottom, arm_compute::DimensionRoundingType::FLOOR); arm_compute::Size2D dilation_info(dilation, dilation); // Note: activation is disabled by default. arm_compute::ActivationLayerInfo activation_info; // Note: no batch size and reverse order of dimensions, i.e. CWHN for NHWC. arm_compute::TensorShape input_shape( /* C */ groups * group_input_channels, /* W */ input_width, /* H */ input_height, /* N */ batch_size); arm_compute::TensorInfo input_info( input_shape, 1 /* number of channels per element (!) */, arm_compute::DataType::F32); input_info.set_data_layout(arm_compute::DataLayout::NHWC); arm_compute::Tensor input_tensor; input_tensor.allocator()->init(input_info); input_tensor.allocator()->allocate(); // Note: reverse order of dimensions, i.e. for IWHO for OHWI. arm_compute::TensorShape kernel_shape( /* I */ groups * group_input_channels, /* W */ kernel_width, /* H */ kernel_height, /* O */ group_output_channels); arm_compute::TensorInfo kernel_info( kernel_shape, 1 /* number of channels per element (!) */, arm_compute::DataType::F32); kernel_info.set_data_layout(arm_compute::DataLayout::NHWC); arm_compute::Tensor kernelTensor; kernelTensor.allocator()->init(kernel_info); kernelTensor.allocator()->allocate(); arm_compute::TensorShape bias_shape(groups * group_output_channels); arm_compute::TensorInfo bias_info( bias_shape, 1 /* number of channels per element (!) */, arm_compute::DataType::F32); bias_info.set_data_layout(arm_compute::DataLayout::NHWC); arm_compute::Tensor bias_tensor; bias_tensor.allocator()->init(bias_info); bias_tensor.allocator()->allocate(); // Note: no batch size and reverse order of dimensions, i.e. CWHN for NHWC. arm_compute::TensorShape output_shape( /* C */ groups * group_output_channels, /* W */ output_width, /* H */ output_height, /* N */ batch_size); arm_compute::TensorInfo output_info( output_shape, 1 /* number of channels per element (!) */, arm_compute::DataType::F32); output_info.set_data_layout(arm_compute::DataLayout::NHWC); arm_compute::Tensor output_tensor; output_tensor.allocator()->init(output_info); output_tensor.allocator()->allocate(); std::random_device random_device; auto rng = std::mt19937(random_device()); auto f32rng = std::bind(std::uniform_real_distribution<float>(0.0f, 1.0f), rng); std::generate( reinterpret_cast<float*>(input_tensor.buffer()), reinterpret_cast<float*>(input_tensor.buffer()) + input_shape.total_size(), std::ref(f32rng)); std::generate( reinterpret_cast<float*>(kernelTensor.buffer()), reinterpret_cast<float*>(kernelTensor.buffer()) + kernel_shape.total_size(), std::ref(f32rng)); std::generate( reinterpret_cast<float*>(bias_tensor.buffer()), reinterpret_cast<float*>(bias_tensor.buffer()) + bias_shape.total_size(), std::ref(f32rng)); std::generate( reinterpret_cast<float*>(output_tensor.buffer()), reinterpret_cast<float*>(output_tensor.buffer()) + output_shape.total_size(), std::ref(f32rng)); bool is_depthwise = false; if (groups != 1) { // NEConvolutionLayer uses NEGEMMConvolutionLayer by default, which doesn't support grouped convolution. // However, depthwise convolution is supported via NEDepthwiseConvolutionLayer. if (group_input_channels == 1) { is_depthwise = true; } else { state.SkipWithError("grouped convolution is not supported"); return; } } std::shared_ptr<arm_compute::IFunction> layer; if (is_depthwise) { if (dilation != 1) { state.SkipWithError("dilated depthwise convolution is not supported"); return; } // Avoid NEDepthwiseConvolutionLayer3x3 when stride isn't 2 in order to pass the output verification. // TODO(b/130206370) This looks like a bug and needs further investigation. if (kernel_height == 3 && kernel_width == 3 && subsampling == 2) { auto* depthwise_3x3_convolution_layer = new arm_compute::NEDepthwiseConvolutionLayer3x3(); layer.reset(depthwise_3x3_convolution_layer); depthwise_3x3_convolution_layer->configure( &input_tensor, &kernelTensor, &bias_tensor, &output_tensor, pad_stride_info, group_output_channels, activation_info); if (!depthwise_3x3_convolution_layer->validate( &input_info, &kernel_info, &bias_info, &output_info, pad_stride_info, group_output_channels, activation_info)) { state.SkipWithError("validation failed"); return; } } else { auto* depthwise_convolution_layer = new arm_compute::NEDepthwiseConvolutionLayer(); layer.reset(depthwise_convolution_layer); depthwise_convolution_layer->configure( &input_tensor, &kernelTensor, &bias_tensor, &output_tensor, pad_stride_info, group_output_channels, activation_info); if (!depthwise_convolution_layer->validate( &input_info, &kernel_info, &bias_info, &output_info, pad_stride_info, group_output_channels, activation_info)) { state.SkipWithError("validation failed"); return; } } } else { auto* convolution_layer = new arm_compute::NEConvolutionLayer(); layer.reset(convolution_layer); convolution_layer->configure( &input_tensor, &kernelTensor, &bias_tensor, &output_tensor, pad_stride_info, arm_compute::WeightsInfo(), dilation_info, activation_info, true /* enable fast math */, groups); if (!convolution_layer->validate( &input_info, &kernel_info, &bias_info, &output_info, pad_stride_info, arm_compute::WeightsInfo(), dilation_info, activation_info, true /* enable fast math */, groups)) { state.SkipWithError("validation failed"); return; } } // Dry run to let ACL do one-time initializations. arm_compute::CPPScheduler::get().set_num_threads(1); layer->run(); for (auto _ : state) { state.PauseTiming(); benchmark::utils::WipeCache(); benchmark::utils::PrefetchToL1( input_tensor.buffer(), batch_size * groups * group_input_channels * input_height * input_width * sizeof(float)); state.ResumeTiming(); layer->run(); } // Validate outputs. const std::string error_string = compare_with_convolution_f32_reference_output( state, reinterpret_cast<const float*>(input_tensor.buffer()), input_shape.total_size(), reinterpret_cast<const float*>(kernelTensor.buffer()), kernel_shape.total_size(), reinterpret_cast<const float*>(bias_tensor.buffer()), bias_shape.total_size(), reinterpret_cast<const float*>(output_tensor.buffer()), output_shape.total_size()); if (!error_string.empty()) { state.SkipWithError(("validation failed: " + error_string).c_str()); return; } input_tensor.allocator()->free(); kernelTensor.allocator()->free(); bias_tensor.allocator()->free(); output_tensor.allocator()->free(); state.counters["Freq"] = benchmark::utils::GetCurrentCpuFrequency(); state.counters["FLOPS"] = benchmark::Counter( uint64_t(state.iterations()) * 2 * batch_size * output_height * output_width * groups * group_input_channels * group_output_channels * kernel_height * kernel_width, benchmark::Counter::kIsRate); } #endif // BENCHMARK_ARM_COMPUTE_LIBRARY // ShuffleNet v1 with 1 group. static void ShuffleNetV1G1(benchmark::internal::Benchmark* b) { b->ArgNames({"N", "H", "W", "KH", "KW", "PH", "PW", "S", "D", "G", "GCin", "GCout"}); /*************************** Conv 1 **************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 224, 224, 3, 3, 2, 2, 2, 1, 1, 3, 24}); /******************* Stage 2: stride-2 unit ******************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 56, 56, 1, 1, 0, 0, 1, 1, 1, 24, 36}); b->Args({1, 56, 56, 3, 3, 2, 2, 2, 1, 36, 1, 1}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 36, 120}); /******************* Stage 2: stride-1 units *****************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 144, 36}); b->Args({1, 28, 28, 3, 3, 2, 2, 2, 1, 36, 1, 1}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 36, 144}); /******************* Stage 3: stride-2 unit ******************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 144, 72}); b->Args({1, 28, 28, 3, 3, 2, 2, 2, 1, 72, 1, 1}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 72, 144}); /******************* Stage 3: stride-1 units *****************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 288, 72}); b->Args({1, 14, 14, 3, 3, 2, 2, 2, 1, 72, 1, 1}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 72, 288}); /******************* Stage 4: stride-2 unit ******************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 288, 144}); b->Args({1, 14, 14, 3, 3, 2, 2, 2, 1, 144, 1, 1}); b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 144, 288}); /******************* Stage 4: stride-1 units *****************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 576, 144}); b->Args({1, 7, 7, 3, 3, 2, 2, 2, 1, 144, 1, 1}); b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 144, 576}); } // ShuffleNet v1 with 2 groups. static void ShuffleNetV1G2(benchmark::internal::Benchmark* b) { b->ArgNames({"N", "H", "W", "KH", "KW", "PH", "PW", "S", "D", "G", "GCin", "GCout"}); /*************************** Conv 1 **************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 224, 224, 3, 3, 2, 2, 2, 1, 1, 3, 24}); /******************* Stage 2: stride-2 unit ******************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 56, 56, 1, 1, 0, 0, 1, 1, 1, 24, 50}); b->Args({1, 56, 56, 3, 3, 2, 2, 2, 1, 50, 1, 1}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 2, 25, 88}); /******************* Stage 2: stride-1 units *****************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 2, 100, 25}); b->Args({1, 28, 28, 3, 3, 2, 2, 2, 1, 50, 1, 1}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 2, 25, 100}); /******************* Stage 3: stride-2 unit ******************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 2, 100, 50}); b->Args({1, 28, 28, 3, 3, 2, 2, 2, 1, 100, 1, 1}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 2, 50, 100}); /******************* Stage 3: stride-1 units *****************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 2, 200, 50}); b->Args({1, 14, 14, 3, 3, 2, 2, 2, 1, 100, 1, 1}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 2, 50, 200}); /******************* Stage 4: stride-2 unit ******************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 2, 200, 100}); b->Args({1, 14, 14, 3, 3, 2, 2, 2, 1, 200, 1, 1}); b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 2, 100, 200}); /******************* Stage 4: stride-1 units *****************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 2, 400, 100}); b->Args({1, 7, 7, 3, 3, 2, 2, 2, 1, 200, 1, 1}); b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 2, 100, 400}); } // ShuffleNet v1 with 3 groups. static void ShuffleNetV1G3(benchmark::internal::Benchmark* b) { b->ArgNames({"N", "H", "W", "KH", "KW", "PH", "PW", "S", "D", "G", "GCin", "GCout"}); /*************************** Conv 1 **************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 224, 224, 3, 3, 2, 2, 2, 1, 1, 3, 24}); /******************* Stage 2: stride-2 unit ******************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 56, 56, 1, 1, 0, 0, 1, 1, 1, 24, 60}); b->Args({1, 56, 56, 3, 3, 2, 2, 2, 1, 60, 1, 1}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 3, 20, 72}); /******************* Stage 2: stride-1 units *****************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 3, 80, 20}); b->Args({1, 28, 28, 3, 3, 2, 2, 2, 1, 60, 1, 1}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 3, 20, 80}); /******************* Stage 3: stride-2 unit ******************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 3, 80, 40}); b->Args({1, 28, 28, 3, 3, 2, 2, 2, 1, 120, 1, 1}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 3, 40, 80}); /******************* Stage 3: stride-1 units *****************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 3, 160, 40}); b->Args({1, 14, 14, 3, 3, 2, 2, 2, 1, 120, 1, 1}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 3, 40, 160}); /******************* Stage 4: stride-2 unit ******************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 3, 160, 80}); b->Args({1, 14, 14, 3, 3, 2, 2, 2, 1, 240, 1, 1}); b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 3, 80, 160}); /******************* Stage 4: stride-1 units *****************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 3, 320, 80}); b->Args({1, 7, 7, 3, 3, 2, 2, 2, 1, 240, 1, 1}); b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 3, 80, 320}); } // ShuffleNet v1 with 4 groups. static void ShuffleNetV1G4(benchmark::internal::Benchmark* b) { b->ArgNames({"N", "H", "W", "KH", "KW", "PH", "PW", "S", "D", "G", "GCin", "GCout"}); /*************************** Conv 1 **************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 224, 224, 3, 3, 2, 2, 2, 1, 1, 3, 24}); /******************* Stage 2: stride-2 unit ******************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 56, 56, 1, 1, 0, 0, 1, 1, 1, 24, 68}); b->Args({1, 56, 56, 3, 3, 2, 2, 2, 1, 68, 1, 1}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 4, 17, 62}); /******************* Stage 2: stride-1 units *****************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 4, 68, 17}); b->Args({1, 28, 28, 3, 3, 2, 2, 2, 1, 68, 1, 1}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 4, 17, 68}); /******************* Stage 3: stride-2 unit ******************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 4, 68, 34}); b->Args({1, 28, 28, 3, 3, 2, 2, 2, 1, 136, 1, 1}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 4, 34, 68}); /******************* Stage 3: stride-1 units *****************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 4, 136, 34}); b->Args({1, 14, 14, 3, 3, 2, 2, 2, 1, 136, 1, 1}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 4, 34, 136}); /******************* Stage 4: stride-2 unit ******************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 4, 136, 68}); b->Args({1, 14, 14, 3, 3, 2, 2, 2, 1, 272, 1, 1}); b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 4, 68, 136}); /******************* Stage 4: stride-1 units *****************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 4, 272, 68}); b->Args({1, 7, 7, 3, 3, 2, 2, 2, 1, 272, 1, 1}); b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 4, 68, 272}); } // ShuffleNet v1 with 8 groups. static void ShuffleNetV1G8(benchmark::internal::Benchmark* b) { b->ArgNames({"N", "H", "W", "KH", "KW", "PH", "PW", "S", "D", "G", "GCin", "GCout"}); /*************************** Conv 1 **************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 224, 224, 3, 3, 2, 2, 2, 1, 1, 3, 24}); /******************* Stage 2: stride-2 unit ******************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 56, 56, 1, 1, 0, 0, 1, 1, 1, 24, 96}); b->Args({1, 56, 56, 3, 3, 2, 2, 2, 1, 96, 1, 1}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 8, 12, 45}); /******************* Stage 2: stride-1 units *****************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 8, 48, 12}); b->Args({1, 28, 28, 3, 3, 2, 2, 2, 1, 96, 1, 1}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 8, 12, 48}); /******************* Stage 3: stride-2 unit ******************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 8, 48, 24}); b->Args({1, 28, 28, 3, 3, 2, 2, 2, 1, 192, 1, 1}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 8, 24, 48}); /******************* Stage 3: stride-1 units *****************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 8, 96, 24}); b->Args({1, 14, 14, 3, 3, 2, 2, 2, 1, 192, 1, 1}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 8, 24, 96}); /******************* Stage 4: stride-2 unit ******************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 8, 96, 48}); b->Args({1, 14, 14, 3, 3, 2, 2, 2, 1, 384, 1, 1}); b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 8, 48, 96}); /******************* Stage 4: stride-1 units *****************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 8, 192, 48}); b->Args({1, 7, 7, 3, 3, 2, 2, 2, 1, 384, 1, 1}); b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 8, 48, 192}); } // ShuffleNet v2 (0.5X scale) static void ShuffleNetV2X05(benchmark::internal::Benchmark* b) { b->ArgNames({"N", "H", "W", "KH", "KW", "PH", "PW", "S", "D", "G", "GCin", "GCout"}); /*************************** Conv 1 **************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 224, 224, 3, 3, 2, 2, 2, 1, 1, 3, 24}); /************************** Stage 2 **************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 56, 56, 3, 3, 2, 2, 2, 1, 24, 1, 1}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 24, 24}); b->Args({1, 56, 56, 1, 1, 0, 0, 1, 1, 1, 24, 24}); b->Args({1, 28, 28, 3, 3, 2, 2, 1, 1, 24, 1, 1}); /************************** Stage 3 **************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 28, 28, 3, 3, 2, 2, 2, 1, 48, 1, 1}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 48, 48}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 48, 48}); b->Args({1, 14, 14, 3, 3, 2, 2, 1, 1, 48, 1, 1}); /************************** Stage 4 **************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 14, 14, 3, 3, 2, 2, 2, 1, 96, 1, 1}); b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 96, 96}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 96, 96}); b->Args({1, 7, 7, 3, 3, 2, 2, 1, 1, 96, 1, 1}); /*************************** Conv 5 **************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 192, 1024}); } // ShuffleNet v2 (1.0X scale) static void ShuffleNetV2X10(benchmark::internal::Benchmark* b) { b->ArgNames({"N", "H", "W", "KH", "KW", "PH", "PW", "S", "D", "G", "GCin", "GCout"}); /*************************** Conv 1 **************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 224, 224, 3, 3, 2, 2, 2, 1, 1, 3, 24}); /************************** Stage 2 **************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 56, 56, 3, 3, 2, 2, 2, 1, 24, 1, 1}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 24, 58}); b->Args({1, 56, 56, 1, 1, 0, 0, 1, 1, 1, 24, 58}); b->Args({1, 56, 56, 3, 3, 2, 2, 2, 1, 58, 1, 1}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 58, 58}); b->Args({1, 28, 28, 3, 3, 2, 2, 1, 1, 58, 1, 1}); /************************** Stage 3 **************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 28, 28, 3, 3, 2, 2, 2, 1, 116, 1, 1}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 116, 116}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 116, 116}); b->Args({1, 14, 14, 3, 3, 2, 2, 1, 1, 116, 1, 1}); /************************** Stage 4 **************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 14, 14, 3, 3, 2, 2, 2, 1, 232, 1, 1}); b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 232, 232}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 232, 232}); b->Args({1, 7, 7, 3, 3, 2, 2, 1, 1, 232, 1, 1}); /*************************** Conv 5 **************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 464, 1024}); } // ShuffleNet v2 (1.5X scale) static void ShuffleNetV2X15(benchmark::internal::Benchmark* b) { b->ArgNames({"N", "H", "W", "KH", "KW", "PH", "PW", "S", "D", "G", "GCin", "GCout"}); /*************************** Conv 1 **************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 224, 224, 3, 3, 2, 2, 2, 1, 1, 3, 24}); /************************** Stage 2 **************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 56, 56, 3, 3, 2, 2, 2, 1, 24, 1, 1}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 24, 88}); b->Args({1, 56, 56, 1, 1, 0, 0, 1, 1, 1, 24, 88}); b->Args({1, 56, 56, 3, 3, 2, 2, 2, 1, 88, 1, 1}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 88, 88}); b->Args({1, 28, 28, 3, 3, 2, 2, 1, 1, 88, 1, 1}); /************************** Stage 3 **************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 28, 28, 3, 3, 2, 2, 2, 1, 176, 1, 1}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 176, 176}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 176, 176}); b->Args({1, 14, 14, 3, 3, 2, 2, 1, 1, 176, 1, 1}); /************************** Stage 4 **************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 14, 14, 3, 3, 2, 2, 2, 1, 352, 1, 1}); b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 352, 352}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 352, 352}); b->Args({1, 7, 7, 3, 3, 2, 2, 1, 1, 352, 1, 1}); /*************************** Conv 5 **************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 704, 1024}); } // ShuffleNet v2 (2.0X scale) static void ShuffleNetV2X20(benchmark::internal::Benchmark* b) { b->ArgNames({"N", "H", "W", "KH", "KW", "PH", "PW", "S", "D", "G", "GCin", "GCout"}); /*************************** Conv 1 **************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 224, 224, 3, 3, 2, 2, 2, 1, 1, 3, 24}); /************************** Stage 2 **************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 56, 56, 3, 3, 2, 2, 2, 1, 24, 1, 1}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 24, 122}); b->Args({1, 56, 56, 1, 1, 0, 0, 1, 1, 1, 24, 122}); b->Args({1, 56, 56, 3, 3, 2, 2, 2, 1, 122, 1, 1}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 122, 122}); b->Args({1, 28, 28, 3, 3, 2, 2, 1, 1, 122, 1, 1}); /************************** Stage 3 **************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 28, 28, 3, 3, 2, 2, 2, 1, 244, 1, 1}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 244, 244}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 244, 244}); b->Args({1, 14, 14, 3, 3, 2, 2, 1, 1, 244, 1, 1}); /************************** Stage 4 **************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 14, 14, 3, 3, 2, 2, 2, 1, 488, 1, 1}); b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 488, 488}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 488, 488}); b->Args({1, 7, 7, 3, 3, 2, 2, 1, 1, 488, 1, 1}); /*************************** Conv 5 **************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 976, 2048}); } static void MobileNetV1(benchmark::internal::Benchmark* b) { b->ArgNames({"N", "H", "W", "KH", "KW", "PH", "PW", "S", "D", "G", "GCin", "GCout"}); /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 224, 224, 3, 3, 2, 2, 2, 1, 1, 3, 32}); b->Args({1, 112, 112, 3, 3, 2, 2, 1, 1, 32, 1, 1}); b->Args({1, 112, 112, 1, 1, 0, 0, 1, 1, 1, 32, 64}); b->Args({1, 112, 112, 3, 3, 2, 2, 2, 1, 64, 1, 1}); b->Args({1, 56, 56, 1, 1, 0, 0, 1, 1, 1, 64, 128}); b->Args({1, 56, 56, 3, 3, 2, 2, 1, 1, 128, 1, 1}); b->Args({1, 56, 56, 1, 1, 0, 0, 1, 1, 1, 128, 128}); b->Args({1, 56, 56, 3, 3, 2, 2, 2, 1, 128, 1, 1}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 128, 256}); b->Args({1, 28, 28, 3, 3, 2, 2, 1, 1, 256, 1, 1}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 256, 256}); b->Args({1, 28, 28, 3, 3, 2, 2, 2, 1, 256, 1, 1}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 256, 512}); b->Args({1, 14, 14, 3, 3, 2, 2, 1, 1, 512, 1, 1}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 512, 512}); b->Args({1, 14, 14, 3, 3, 2, 2, 2, 1, 512, 1, 1}); b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 512, 1024}); b->Args({1, 7, 7, 3, 3, 2, 2, 1, 1, 1024, 1, 1}); b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 1024, 1024}); } static void MobileNetV2(benchmark::internal::Benchmark* b) { b->ArgNames({"N", "H", "W", "KH", "KW", "PH", "PW", "S", "D", "G", "GCin", "GCout"}); /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 224, 224, 3, 3, 2, 2, 2, 1, 1, 3, 32}); /************************ Bottleneck 1 ***********************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 112, 112, 3, 3, 2, 2, 1, 1, 32, 1, 1}); b->Args({1, 112, 112, 1, 1, 0, 0, 1, 1, 1, 32, 16}); /************************ Bottleneck 2 ***********************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 112, 112, 1, 1, 0, 0, 1, 1, 1, 16, 96}); b->Args({1, 112, 112, 3, 3, 2, 2, 2, 1, 96, 1, 1}); b->Args({1, 56, 56, 1, 1, 0, 0, 1, 1, 1, 96, 24}); b->Args({1, 56, 56, 1, 1, 0, 0, 1, 1, 1, 24, 144}); b->Args({1, 56, 56, 3, 3, 2, 2, 1, 1, 144, 1, 1}); b->Args({1, 56, 56, 1, 1, 0, 0, 1, 1, 1, 144, 24}); /************************ Bottleneck 3 ***********************/ /* N H W KH KW PH PW S D G GCin GCout */ //b->Args({1, 56, 56, 1, 1, 0, 0, 1, 1, 1, 24, 144}); b->Args({1, 56, 56, 3, 3, 2, 2, 2, 1, 144, 1, 1}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 144, 32}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 32, 192}); b->Args({1, 28, 28, 3, 3, 2, 2, 1, 1, 192, 1, 1}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 192, 32}); //b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 32, 192}); //b->Args({1, 28, 28, 3, 3, 2, 2, 1, 1, 192, 1, 1}); //b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 192, 32}); /************************ Bottleneck 4 ***********************/ /* N H W KH KW PH PW S D G GCin GCout */ //b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 32, 192}); b->Args({1, 28, 28, 3, 3, 2, 2, 2, 1, 192, 1, 1}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 192, 64}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 64, 384}); b->Args({1, 14, 14, 3, 3, 2, 2, 1, 1, 384, 1, 1}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 384, 64}); //b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 64, 384}); //b->Args({1, 14, 14, 3, 3, 2, 2, 1, 1, 384, 1, 1}); //b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 384, 64}); //b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 64, 384}); //b->Args({1, 14, 14, 3, 3, 2, 2, 1, 1, 384, 1, 1}); //b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 384, 64}); /************************ Bottleneck 5 ***********************/ /* N H W KH KW PH PW S D G GCin GCout */ //b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 64, 384}); //b->Args({1, 14, 14, 3, 3, 2, 2, 1, 1, 384, 1, 1}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 384, 96}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 96, 576}); b->Args({1, 14, 14, 3, 3, 2, 2, 1, 1, 576, 1, 1}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 576, 96}); //b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 96, 576}); //b->Args({1, 14, 14, 3, 3, 2, 2, 1, 1, 576, 1, 1}); //b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 576, 96}); /************************ Bottleneck 6 ***********************/ /* N H W KH KW PH PW S D G GCin GCout */ //b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 96, 576}); b->Args({1, 14, 14, 3, 3, 2, 2, 2, 1, 576, 1, 1}); b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 576, 160}); b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 160, 960}); b->Args({1, 7, 7, 3, 3, 2, 2, 1, 1, 960, 1, 1}); b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 960, 160}); //b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 160, 960}); //b->Args({1, 7, 7, 3, 3, 2, 2, 1, 1, 960, 1, 1}); //b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 960, 160}); /************************ Bottleneck 7 ***********************/ /* N H W KH KW PH PW S D G GCin GCout */ //b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 160, 960}); //b->Args({1, 7, 7, 3, 3, 2, 2, 1, 1, 960, 1, 1}); b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 960, 320}); /******************** Pre-pooling Conv2D *********************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 320, 1280}); /******************** Post-pooling Conv2D ********************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1280, 1000}); } static void MobileNetV3Small(benchmark::internal::Benchmark* b) { b->ArgNames({"N", "H", "W", "KH", "KW", "PH", "PW", "S", "D", "G", "GCin", "GCout"}); /*********************** Initial Stage ***********************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 224, 224, 3, 3, 2, 2, 2, 1, 1, 3, 16}); /*********************** Bottleneck 1 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 112, 112, 3, 3, 2, 2, 2, 1, 16, 1, 1}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 16, 8}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 8, 16}); b->Args({1, 56, 56, 1, 1, 0, 0, 1, 1, 1, 16, 16}); /*********************** Bottleneck 2 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 56, 56, 1, 1, 0, 0, 1, 1, 1, 16, 72}); b->Args({1, 56, 56, 3, 3, 2, 2, 2, 1, 72, 1, 1}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 72, 24}); /*********************** Bottleneck 3 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 24, 88}); b->Args({1, 28, 28, 3, 3, 2, 2, 1, 1, 88, 1, 1}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 88, 24}); /*********************** Bottleneck 4 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 24, 96}); b->Args({1, 28, 28, 5, 5, 4, 4, 2, 1, 96, 1, 1}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 96, 24}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 24, 96}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 96, 40}); /*********************** Bottleneck 5 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 40, 240}); b->Args({1, 14, 14, 5, 5, 4, 4, 1, 1, 240, 1, 1}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 240, 64}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 64, 240}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 240, 40}); /*********************** Bottleneck 6 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ //b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 40, 240}); //b->Args({1, 14, 14, 5, 5, 4, 4, 1, 1, 240, 1, 1}); //b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 240, 64}); //b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 64, 240}); //b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 240, 40}); /*********************** Bottleneck 7 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 40, 120}); b->Args({1, 14, 14, 5, 5, 4, 4, 1, 1, 120, 1, 1}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 120, 32}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 32, 120}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 120, 48}); /*********************** Bottleneck 8 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 48, 144}); b->Args({1, 14, 14, 5, 5, 4, 4, 1, 1, 144, 1, 1}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 144, 40}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 40, 144}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 144, 48}); /*********************** Bottleneck 9 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 48, 288}); b->Args({1, 14, 14, 5, 5, 4, 4, 2, 1, 288, 1, 1}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 288, 72}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 72, 288}); b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 288, 96}); /*********************** Bottleneck 10 ***********************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 96, 576}); b->Args({1, 7, 7, 5, 5, 4, 4, 1, 1, 576, 1, 1}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 576, 144}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 144, 576}); b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 576, 96}); /*********************** Bottleneck 11 ***********************/ /* N H W KH KW PH PW S D G GCin GCout */ //b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 96, 576}); //b->Args({1, 7, 7, 5, 5, 4, 4, 1, 1, 576, 1, 1}); //b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 576, 144}); //b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 144, 576}); //b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 576, 96}); /************************ Last Stage ************************/ /* N H W KH KW PH PW S D G GCin GCout */ //b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 96, 576}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 576, 1024}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1024, 1001}); } static void MobileNetV3Large(benchmark::internal::Benchmark* b) { b->ArgNames({"N", "H", "W", "KH", "KW", "PH", "PW", "S", "D", "G", "GCin", "GCout"}); /*********************** Initial Stage ***********************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 224, 224, 3, 3, 2, 2, 2, 1, 1, 3, 16}); /*********************** Bottleneck 1 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 112, 112, 3, 3, 2, 2, 1, 1, 16, 1, 1}); b->Args({1, 112, 112, 1, 1, 0, 0, 1, 1, 1, 16, 16}); /*********************** Bottleneck 2 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 112, 112, 1, 1, 0, 0, 1, 1, 1, 16, 64}); b->Args({1, 112, 112, 3, 3, 2, 2, 2, 1, 64, 1, 1}); b->Args({1, 56, 56, 1, 1, 0, 0, 1, 1, 1, 64, 24}); /*********************** Bottleneck 3 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 56, 56, 1, 1, 0, 0, 1, 1, 1, 24, 72}); b->Args({1, 56, 56, 3, 3, 2, 2, 1, 1, 72, 1, 1}); b->Args({1, 56, 56, 1, 1, 0, 0, 1, 1, 1, 72, 24}); /*********************** Bottleneck 4 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ //b->Args({1, 56, 56, 1, 1, 0, 0, 1, 1, 1, 24, 72}); b->Args({1, 56, 56, 5, 5, 4, 4, 2, 1, 72, 1, 1}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 72, 24}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 24, 72}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 72, 40}); /*********************** Bottleneck 5 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 40, 120}); b->Args({1, 28, 28, 5, 5, 4, 4, 1, 1, 120, 1, 1}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 120, 32}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 32, 120}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 120, 40}); /*********************** Bottleneck 6 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ //b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 40, 120}); //b->Args({1, 28, 28, 5, 5, 4, 4, 1, 1, 120, 1, 1}); //b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 120, 32}); //b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 32, 120}); //b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 120, 40}); /*********************** Bottleneck 7 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 40, 240}); b->Args({1, 28, 28, 3, 3, 2, 2, 2, 1, 240, 1, 1}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 240, 80}); /*********************** Bottleneck 8 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 80, 200}); b->Args({1, 14, 14, 3, 3, 2, 2, 1, 1, 200, 1, 1}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 200, 80}); /*********************** Bottleneck 9 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 80, 184}); b->Args({1, 14, 14, 3, 3, 2, 2, 1, 1, 184, 1, 1}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 184, 80}); /********************** Bottleneck 10 ***********************/ /* N H W KH KW PH PW S D G GCin GCout */ //b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 80, 184}); //b->Args({1, 14, 14, 3, 3, 2, 2, 1, 1, 184, 1, 1}); //b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 184, 80}); /********************** Bottleneck 11 ***********************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 80, 480}); b->Args({1, 14, 14, 3, 3, 2, 2, 1, 1, 480, 1, 1}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 480, 120}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 120, 480}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 480, 112}); /********************** Bottleneck 12 ***********************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 112, 672}); b->Args({1, 14, 14, 3, 3, 2, 2, 1, 1, 672, 1, 1}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 672, 168}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 168, 672}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 672, 112}); /********************** Bottleneck 13 ***********************/ /* N H W KH KW PH PW S D G GCin GCout */ //b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 112, 672}); b->Args({1, 14, 14, 5, 5, 4, 4, 2, 1, 672, 1, 1}); b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 672, 160}); /********************** Bottleneck 14 ***********************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 160, 960}); b->Args({1, 7, 7, 5, 5, 4, 4, 1, 1, 960, 1, 1}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 960, 240}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 240, 960}); b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 960, 160}); /********************** Bottleneck 15 ***********************/ /* N H W KH KW PH PW S D G GCin GCout */ //b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 160, 960}); //b->Args({1, 7, 7, 5, 5, 4, 4, 1, 1, 960, 1, 1}); //b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 960, 240}); //b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 240, 960}); //b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 960, 160}); /************************ Last Stage ***********************/ /* N H W KH KW PH PW S D G GCin GCout */ //b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 160, 960}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 960, 1280}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1280, 1001}); } // SqueezeNet 1.0 static void SqueezeNetV10(benchmark::internal::Benchmark* b) { b->ArgNames({"N", "H", "W", "KH", "KW", "PH", "PW", "S", "D", "G", "GCin", "GCout"}); /************************** Conv 1 *************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 224, 224, 7, 7, 6, 6, 2, 1, 1, 3, 96}); /************************** Fire 2 *************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 55, 55, 1, 1, 0, 0, 1, 1, 1, 96, 16}); b->Args({1, 55, 55, 1, 1, 0, 0, 1, 1, 1, 16, 64}); b->Args({1, 55, 55, 3, 3, 2, 2, 1, 1, 1, 16, 64}); /************************** Fire 3 *************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 56, 55, 1, 1, 0, 0, 1, 1, 1, 128, 16}); //b->Args({1, 55, 55, 1, 1, 0, 0, 1, 1, 1, 16, 64}); //b->Args({1, 55, 55, 3, 3, 2, 2, 1, 1, 1, 16, 64}); /************************** Fire 4 *************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 55, 55, 1, 1, 0, 0, 1, 1, 1, 128, 32}); b->Args({1, 55, 55, 1, 1, 0, 0, 1, 1, 1, 32, 128}); b->Args({1, 55, 55, 3, 3, 2, 2, 1, 1, 1, 32, 128}); /************************** Fire 5 *************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 27, 27, 1, 1, 0, 0, 1, 1, 1, 256, 32}); b->Args({1, 27, 27, 1, 1, 0, 0, 1, 1, 1, 32, 128}); b->Args({1, 27, 27, 3, 3, 2, 2, 1, 1, 1, 32, 128}); /************************** Fire 6 *************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 27, 27, 1, 1, 0, 0, 1, 1, 1, 256, 48}); b->Args({1, 27, 27, 1, 1, 0, 0, 1, 1, 1, 48, 192}); b->Args({1, 27, 27, 3, 3, 2, 2, 1, 1, 1, 48, 192}); /************************** Fire 7 *************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 27, 27, 1, 1, 0, 0, 1, 1, 1, 384, 48}); //b->Args({1, 27, 27, 1, 1, 0, 0, 1, 1, 1, 48, 192}); //b->Args({1, 27, 27, 3, 3, 2, 2, 1, 1, 1, 48, 192}); /************************** Fire 8 *************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 27, 27, 1, 1, 0, 0, 1, 1, 1, 384, 64}); b->Args({1, 27, 27, 1, 1, 0, 0, 1, 1, 1, 64, 256}); b->Args({1, 27, 27, 3, 3, 2, 2, 1, 1, 1, 64, 256}); /************************** Fire 9 *************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 13, 13, 1, 1, 0, 0, 1, 1, 1, 512, 64}); b->Args({1, 13, 13, 1, 1, 0, 0, 1, 1, 1, 64, 256}); b->Args({1, 13, 13, 3, 3, 2, 2, 1, 1, 1, 64, 256}); /************************* Conv 10 *************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 13, 13, 1, 1, 0, 0, 1, 1, 1, 512, 1000}); } // SqueezeNet 1.1 static void SqueezeNetV11(benchmark::internal::Benchmark* b) { b->ArgNames({"N", "H", "W", "KH", "KW", "PH", "PW", "S", "D", "G", "GCin", "GCout"}); /************************** Conv 1 *************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 224, 224, 3, 3, 2, 2, 2, 1, 1, 3, 64}); /************************** Fire 2 *************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 55, 55, 1, 1, 0, 0, 1, 1, 1, 64, 16}); b->Args({1, 55, 55, 1, 1, 0, 0, 1, 1, 1, 16, 64}); b->Args({1, 55, 55, 3, 3, 2, 2, 1, 1, 1, 16, 64}); /************************** Fire 3 *************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 55, 55, 1, 1, 0, 0, 1, 1, 1, 128, 16}); //b->Args({1, 55, 55, 1, 1, 0, 0, 1, 1, 1, 16, 64}); //b->Args({1, 55, 55, 3, 3, 2, 2, 1, 1, 1, 16, 64}); /************************** Fire 4 *************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 27, 27, 1, 1, 0, 0, 1, 1, 1, 128, 32}); b->Args({1, 27, 27, 1, 1, 0, 0, 1, 1, 1, 32, 128}); b->Args({1, 27, 27, 3, 3, 2, 2, 1, 1, 1, 32, 128}); /************************** Fire 5 *************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 27, 27, 1, 1, 0, 0, 1, 1, 1, 256, 32}); //b->Args({1, 27, 27, 1, 1, 0, 0, 1, 1, 1, 32, 128}); //b->Args({1, 27, 27, 3, 3, 2, 2, 1, 1, 1, 32, 128}); /************************** Fire 6 *************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 13, 13, 1, 1, 0, 0, 1, 1, 1, 256, 48}); b->Args({1, 13, 13, 1, 1, 0, 0, 1, 1, 1, 48, 192}); b->Args({1, 13, 13, 3, 3, 2, 2, 1, 1, 1, 48, 192}); /************************** Fire 7 *************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 13, 13, 1, 1, 0, 0, 1, 1, 1, 384, 48}); //b->Args({1, 13, 13, 1, 1, 0, 0, 1, 1, 1, 48, 192}); //b->Args({1, 13, 13, 3, 3, 2, 2, 1, 1, 1, 48, 192}); /************************** Fire 8 *************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 13, 13, 1, 1, 0, 0, 1, 1, 1, 384, 64}); b->Args({1, 13, 13, 1, 1, 0, 0, 1, 1, 1, 64, 256}); b->Args({1, 13, 13, 3, 3, 2, 2, 1, 1, 1, 64, 256}); /************************** Fire 9 *************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 13, 13, 1, 1, 0, 0, 1, 1, 1, 512, 64}); //b->Args({1, 13, 13, 1, 1, 0, 0, 1, 1, 1, 64, 256}); //b->Args({1, 13, 13, 3, 3, 2, 2, 1, 1, 1, 64, 256}); /************************* Conv 10 *************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 13, 13, 1, 1, 0, 0, 1, 1, 1, 512, 1000}); } static void InceptionV3(benchmark::internal::Benchmark* b) { b->ArgNames({"N", "H", "W", "KH", "KW", "PH", "PW", "S", "D", "G", "GCin", "GCout"}); /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 299, 299, 3, 3, 0, 0, 2, 1, 1, 3, 32}); b->Args({1, 149, 149, 3, 3, 0, 0, 1, 1, 1, 32, 32}); b->Args({1, 147, 147, 3, 3, 2, 2, 1, 1, 1, 32, 64}); b->Args({1, 73, 73, 1, 1, 0, 0, 1, 1, 1, 64, 80}); b->Args({1, 73, 73, 3, 3, 0, 0, 1, 1, 1, 80, 192}); b->Args({1, 35, 35, 1, 1, 0, 0, 1, 1, 1, 192, 64}); b->Args({1, 35, 35, 1, 1, 0, 0, 1, 1, 1, 192, 48}); b->Args({1, 35, 35, 5, 5, 4, 4, 1, 1, 1, 48, 64}); b->Args({1, 35, 35, 3, 3, 2, 2, 1, 1, 1, 64, 96}); b->Args({1, 35, 35, 3, 3, 2, 2, 1, 1, 1, 96, 96}); b->Args({1, 35, 35, 1, 1, 0, 0, 1, 1, 1, 192, 32}); b->Args({1, 35, 35, 1, 1, 0, 0, 1, 1, 1, 256, 64}); b->Args({1, 35, 35, 1, 1, 0, 0, 1, 1, 1, 256, 48}); b->Args({1, 35, 35, 1, 1, 0, 0, 1, 1, 1, 288, 64}); b->Args({1, 35, 35, 1, 1, 0, 0, 1, 1, 1, 288, 48}); b->Args({1, 35, 35, 3, 3, 0, 0, 2, 1, 1, 288, 384}); b->Args({1, 35, 35, 3, 3, 0, 0, 2, 1, 1, 96, 96}); b->Args({1, 17, 17, 1, 1, 0, 0, 1, 1, 1, 768, 192}); b->Args({1, 17, 17, 1, 1, 0, 0, 1, 1, 1, 768, 128}); b->Args({1, 17, 17, 1, 7, 0, 6, 1, 1, 1, 128, 128}); b->Args({1, 17, 17, 7, 1, 6, 0, 1, 1, 1, 128, 192}); b->Args({1, 17, 17, 7, 1, 6, 0, 1, 1, 1, 128, 128}); b->Args({1, 17, 17, 1, 7, 0, 6, 1, 1, 1, 128, 192}); b->Args({1, 17, 17, 1, 1, 0, 0, 1, 1, 1, 768, 160}); b->Args({1, 17, 17, 1, 7, 0, 6, 1, 1, 1, 160, 160}); b->Args({1, 17, 17, 7, 1, 6, 0, 1, 1, 1, 160, 192}); b->Args({1, 17, 17, 7, 1, 6, 0, 1, 1, 1, 160, 160}); b->Args({1, 17, 17, 1, 7, 0, 6, 1, 1, 1, 160, 192}); b->Args({1, 17, 17, 1, 7, 0, 6, 1, 1, 1, 192, 192}); b->Args({1, 17, 17, 7, 1, 6, 0, 1, 1, 1, 192, 192}); b->Args({1, 17, 17, 3, 3, 0, 0, 2, 1, 1, 192, 320}); b->Args({1, 17, 17, 3, 3, 0, 0, 2, 1, 1, 192, 192}); b->Args({1, 8, 8, 1, 1, 0, 0, 1, 1, 1, 1280, 320}); b->Args({1, 8, 8, 1, 1, 0, 0, 1, 1, 1, 1280, 384}); b->Args({1, 8, 8, 1, 3, 0, 2, 1, 1, 1, 384, 384}); b->Args({1, 8, 8, 3, 1, 2, 0, 1, 1, 1, 384, 384}); b->Args({1, 8, 8, 1, 1, 0, 0, 1, 1, 1, 1280, 448}); b->Args({1, 8, 8, 3, 3, 2, 2, 1, 1, 1, 448, 384}); b->Args({1, 8, 8, 1, 1, 0, 0, 1, 1, 1, 1280, 192}); b->Args({1, 8, 8, 1, 1, 0, 0, 1, 1, 1, 2048, 320}); b->Args({1, 8, 8, 1, 1, 0, 0, 1, 1, 1, 2048, 384}); b->Args({1, 8, 8, 1, 1, 0, 0, 1, 1, 1, 2048, 448}); b->Args({1, 8, 8, 1, 1, 0, 0, 1, 1, 1, 2048, 192}); b->Args({1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 2048, 1001}); } static void ResNet18(benchmark::internal::Benchmark* b) { b->ArgNames({"N", "H", "W", "KH", "KW", "PH", "PW", "S", "D", "G", "GCin", "GCout"}); /************************* Conv 1 *************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 224, 224, 7, 7, 6, 6, 2, 1, 1, 3, 64}); /************************ Conv 2.X ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 56, 56, 3, 3, 2, 2, 1, 1, 1, 64, 64}); /************************ Conv 3.X ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 56, 56, 3, 3, 2, 2, 2, 1, 1, 64, 128}); b->Args({1, 28, 28, 3, 3, 2, 2, 1, 1, 1, 128, 128}); b->Args({1, 56, 56, 1, 1, 0, 0, 2, 1, 1, 64, 128}); /************************ Conv 4.X ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 28, 28, 3, 3, 2, 2, 2, 1, 1, 128, 256}); b->Args({1, 14, 14, 3, 3, 2, 2, 1, 1, 1, 256, 256}); b->Args({1, 28, 28, 1, 1, 0, 0, 2, 1, 1, 128, 256}); /************************ Conv 5.X ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 14, 14, 3, 3, 2, 2, 2, 1, 1, 256, 512}); b->Args({1, 7, 7, 3, 3, 2, 2, 1, 1, 1, 512, 512}); b->Args({1, 14, 14, 1, 1, 0, 0, 2, 1, 1, 256, 512}); } static void ResNet50(benchmark::internal::Benchmark* b) { b->ArgNames({"N", "H", "W", "KH", "KW", "PH", "PW", "S", "D", "G", "GCin", "GCout"}); /************************* Conv 1 *************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 224, 224, 7, 7, 6, 6, 2, 1, 1, 3, 64}); /************************ Conv 2.1 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 56, 56, 1, 1, 0, 0, 1, 1, 1, 64, 64}); b->Args({1, 56, 56, 3, 3, 2, 2, 1, 1, 1, 64, 64}); b->Args({1, 56, 56, 1, 1, 0, 0, 1, 1, 1, 64, 256}); //b->Args({1, 56, 56, 1, 1, 0, 0, 1, 1, 1, 64, 256}); /************************ Conv 2.X ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 56, 56, 1, 1, 0, 0, 1, 1, 1, 256, 64}); //b->Args({1, 56, 56, 3, 3, 2, 2, 1, 1, 1, 64, 64}); //b->Args({1, 56, 56, 1, 1, 0, 0, 1, 1, 1, 64, 256}); /************************ Conv 3.1 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 56, 56, 1, 1, 0, 0, 1, 1, 1, 256, 128}); b->Args({1, 56, 56, 3, 3, 2, 2, 2, 1, 1, 128, 128}); b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 128, 512}); b->Args({1, 56, 56, 1, 1, 0, 0, 2, 1, 1, 256, 512}); /************************ Conv 3.X ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 512, 128}); b->Args({1, 28, 28, 3, 3, 2, 2, 1, 1, 1, 128, 128}); //b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 128, 512}); /************************ Conv 4.1 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 512, 256}); b->Args({1, 28, 28, 3, 3, 2, 2, 2, 1, 1, 256, 256}); b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 256, 1024}); b->Args({1, 28, 28, 1, 1, 0, 0, 2, 1, 1, 512, 1024}); /************************ Conv 4.X ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 1024, 256}); b->Args({1, 14, 14, 3, 3, 2, 2, 1, 1, 1, 256, 256}); //b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 256, 1024}); /************************ Conv 5.1 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 1024, 512}); b->Args({1, 14, 14, 3, 3, 2, 2, 2, 1, 1, 512, 512}); b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 512, 2048}); b->Args({1, 14, 14, 1, 1, 0, 0, 2, 1, 1, 1024, 2048}); /************************ Conv 5.X ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 2048, 512}); b->Args({1, 7, 7, 3, 3, 2, 2, 1, 1, 1, 512, 512}); //b->Args({1, 7, 7, 1, 1, 0, 0, 1, 1, 1, 512, 2048}); } static void VGG(benchmark::internal::Benchmark* b) { b->ArgNames({"N", "H", "W", "KH", "KW", "PH", "PW", "S", "D", "G", "GCin", "GCout"}); /************************* Conv 1.1 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 224, 224, 3, 3, 2, 2, 1, 1, 1, 3, 64}); /************************* Conv 1.2 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 224, 224, 3, 3, 2, 2, 1, 1, 1, 64, 64}); /************************* Conv 2.1 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 112, 112, 3, 3, 2, 2, 1, 1, 1, 64, 128}); /************************* Conv 2.2 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 112, 112, 3, 3, 2, 2, 1, 1, 1, 128, 128}); /************************* Conv 3.1 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 56, 56, 3, 3, 2, 2, 1, 1, 1, 128, 256}); /************************* Conv 3.2 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 56, 56, 3, 3, 2, 2, 1, 1, 1, 256, 256}); /************************* Conv 3.3 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 56, 56, 1, 1, 0, 0, 1, 1, 1, 256, 256}); /************************* Conv 4.1 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 28, 28, 3, 3, 2, 2, 1, 1, 1, 256, 512}); /************************* Conv 4.2 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 28, 28, 3, 3, 2, 2, 1, 1, 1, 512, 512}); /************************* Conv 4.3 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 28, 28, 1, 1, 0, 0, 1, 1, 1, 512, 512}); /************************* Conv 5.X ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 14, 14, 3, 3, 2, 2, 1, 1, 1, 512, 512}); /************************* Conv 5.3 ************************/ /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 14, 14, 1, 1, 0, 0, 1, 1, 1, 512, 512}); } // SRCNN (9-1-5) static void SRCNN915(benchmark::internal::Benchmark* b) { b->ArgNames({"N", "H", "W", "KH", "KW", "PH", "PW", "S", "D", "G", "GCin", "GCout"}); /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 384, 384, 9, 9, 0, 0, 1, 1, 1, 1, 64}); b->Args({1, 376, 376, 1, 1, 0, 0, 1, 1, 1, 64, 32}); b->Args({1, 376, 376, 5, 5, 0, 0, 1, 1, 1, 32, 1}); } // SRCNN (9-3-5) static void SRCNN935(benchmark::internal::Benchmark* b) { b->ArgNames({"N", "H", "W", "KH", "KW", "PH", "PW", "S", "D", "G", "GCin", "GCout"}); /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 384, 384, 9, 9, 0, 0, 1, 1, 1, 1, 64}); b->Args({1, 376, 376, 3, 3, 0, 0, 1, 1, 1, 64, 32}); b->Args({1, 374, 374, 5, 5, 0, 0, 1, 1, 1, 32, 1}); } // SRCNN (9-5-5) static void SRCNN955(benchmark::internal::Benchmark* b) { b->ArgNames({"N", "H", "W", "KH", "KW", "PH", "PW", "S", "D", "G", "GCin", "GCout"}); /* N H W KH KW PH PW S D G GCin GCout */ b->Args({1, 384, 384, 9, 9, 0, 0, 1, 1, 1, 1, 64}); b->Args({1, 376, 376, 5, 5, 0, 0, 1, 1, 1, 64, 32}); b->Args({1, 372, 372, 5, 5, 0, 0, 1, 1, 1, 32, 1}); } BENCHMARK_CAPTURE(xnnpack_convolution_f32, mobilenet_v1, "MobileNet v1")->Apply(MobileNetV1)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_f32, mobilenet_v2, "MobileNet v2")->Apply(MobileNetV2)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_f32, mobilenet_v3_small, "MobileNet v3 Small")->Apply(MobileNetV3Small)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_f32, mobilenet_v3_large, "MobileNet v3 Large")->Apply(MobileNetV3Large)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_f32, shufflenet_v1_g1, "ShuffleNet v1 (1 group)")->Apply(ShuffleNetV1G1)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_f32, shufflenet_v1_g2, "ShuffleNet v1 (2 groups)")->Apply(ShuffleNetV1G2)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_f32, shufflenet_v1_g3, "ShuffleNet v1 (3 groups)")->Apply(ShuffleNetV1G3)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_f32, shufflenet_v1_g4, "ShuffleNet v1 (4 groups)")->Apply(ShuffleNetV1G4)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_f32, shufflenet_v1_g8, "ShuffleNet v1 (8 groups)")->Apply(ShuffleNetV1G8)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_f32, shufflenet_v2_x05, "ShuffleNet v2 0.5X")->Apply(ShuffleNetV2X05)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_f32, shufflenet_v2_x10, "ShuffleNet v2 1.0X")->Apply(ShuffleNetV2X10)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_f32, shufflenet_v2_x15, "ShuffleNet v2 1.5X")->Apply(ShuffleNetV2X15)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_f32, shufflenet_v2_x20, "ShuffleNet v2 2.0X")->Apply(ShuffleNetV2X20)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_f32, squeezenet_v10, "SqueezeNet 1.0")->Apply(SqueezeNetV10)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_f32, squeezenet_v11, "SqueezeNet 1.1")->Apply(SqueezeNetV11)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_f32, inception_v3, "Inception v3")->Apply(InceptionV3)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_f32, resnet18, "ResNet-18")->Apply(ResNet18)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_f32, resnet50, "ResNet-50")->Apply(ResNet50)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_f32, vgg, "VGG")->Apply(VGG)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_f32, srcnn915, "SRCNN (9-1-5)")->Apply(SRCNN915)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_f32, srcnn935, "SRCNN (9-3-5)")->Apply(SRCNN935)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_f32, srcnn955, "SRCNN (9-5-5)")->Apply(SRCNN955)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_q8, mobilenet_v1, "MobileNet v1")->Apply(MobileNetV1)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_q8, mobilenet_v2, "MobileNet v2")->Apply(MobileNetV2)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_q8, mobilenet_v3_small, "MobileNet v3 Small")->Apply(MobileNetV3Small)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_q8, mobilenet_v3_large, "MobileNet v3 Large")->Apply(MobileNetV3Large)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_q8, shufflenet_v1_g1, "ShuffleNet v1 (1 group)")->Apply(ShuffleNetV1G1)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_q8, shufflenet_v1_g2, "ShuffleNet v1 (2 groups)")->Apply(ShuffleNetV1G2)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_q8, shufflenet_v1_g3, "ShuffleNet v1 (3 groups)")->Apply(ShuffleNetV1G3)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_q8, shufflenet_v1_g4, "ShuffleNet v1 (4 groups)")->Apply(ShuffleNetV1G4)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_q8, shufflenet_v1_g8, "ShuffleNet v1 (8 groups)")->Apply(ShuffleNetV1G8)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_q8, shufflenet_v2_x05, "ShuffleNet v2 0.5X")->Apply(ShuffleNetV2X05)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_q8, shufflenet_v2_x10, "ShuffleNet v2 1.0X")->Apply(ShuffleNetV2X10)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_q8, shufflenet_v2_x15, "ShuffleNet v2 1.5X")->Apply(ShuffleNetV2X15)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_q8, shufflenet_v2_x20, "ShuffleNet v2 2.0X")->Apply(ShuffleNetV2X20)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_q8, squeezenet_v10, "SqueezeNet 1.0")->Apply(SqueezeNetV10)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_q8, squeezenet_v11, "SqueezeNet 1.1")->Apply(SqueezeNetV11)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_q8, inception_v3, "Inception v3")->Apply(InceptionV3)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_q8, resnet18, "ResNet-18")->Apply(ResNet18)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_q8, resnet50, "ResNet-50")->Apply(ResNet50)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_q8, vgg, "VGG")->Apply(VGG)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_q8, srcnn915, "SRCNN (9-1-5)")->Apply(SRCNN915)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_q8, srcnn935, "SRCNN (9-3-5)")->Apply(SRCNN935)->UseRealTime(); BENCHMARK_CAPTURE(xnnpack_convolution_q8, srcnn955, "SRCNN (9-5-5)")->Apply(SRCNN955)->UseRealTime(); #ifdef BENCHMARK_TENSORFLOW_LITE BENCHMARK_CAPTURE(tflite_convolution_f32, mobilenet_v1, "MobileNet v1")->Apply(MobileNetV1)->UseRealTime(); BENCHMARK_CAPTURE(tflite_convolution_f32, mobilenet_v2, "MobileNet v2")->Apply(MobileNetV2)->UseRealTime(); BENCHMARK_CAPTURE(tflite_convolution_f32, mobilenet_v3_small, "MobileNet v3 Small")->Apply(MobileNetV3Small)->UseRealTime(); BENCHMARK_CAPTURE(tflite_convolution_f32, mobilenet_v3_large, "MobileNet v3 Large")->Apply(MobileNetV3Large)->UseRealTime(); BENCHMARK_CAPTURE(tflite_convolution_f32, shufflenet_v1_g1, "ShuffleNet v1 (1 group)")->Apply(ShuffleNetV1G1)->UseRealTime(); BENCHMARK_CAPTURE(tflite_convolution_f32, shufflenet_v1_g2, "ShuffleNet v1 (2 groups)")->Apply(ShuffleNetV1G2)->UseRealTime(); BENCHMARK_CAPTURE(tflite_convolution_f32, shufflenet_v1_g3, "ShuffleNet v1 (3 groups)")->Apply(ShuffleNetV1G3)->UseRealTime(); BENCHMARK_CAPTURE(tflite_convolution_f32, shufflenet_v1_g4, "ShuffleNet v1 (4 groups)")->Apply(ShuffleNetV1G4)->UseRealTime(); BENCHMARK_CAPTURE(tflite_convolution_f32, shufflenet_v1_g8, "ShuffleNet v1 (8 groups)")->Apply(ShuffleNetV1G8)->UseRealTime(); BENCHMARK_CAPTURE(tflite_convolution_f32, shufflenet_v2_x05, "ShuffleNet v2 0.5X")->Apply(ShuffleNetV2X05)->UseRealTime(); BENCHMARK_CAPTURE(tflite_convolution_f32, shufflenet_v2_x10, "ShuffleNet v2 1.0X")->Apply(ShuffleNetV2X10)->UseRealTime(); BENCHMARK_CAPTURE(tflite_convolution_f32, shufflenet_v2_x15, "ShuffleNet v2 1.5X")->Apply(ShuffleNetV2X15)->UseRealTime(); BENCHMARK_CAPTURE(tflite_convolution_f32, shufflenet_v2_x20, "ShuffleNet v2 2.0X")->Apply(ShuffleNetV2X20)->UseRealTime(); BENCHMARK_CAPTURE(tflite_convolution_f32, squeezenet_v10, "SqueezeNet 1.0")->Apply(SqueezeNetV10)->UseRealTime(); BENCHMARK_CAPTURE(tflite_convolution_f32, squeezenet_v11, "SqueezeNet 1.1")->Apply(SqueezeNetV11)->UseRealTime(); BENCHMARK_CAPTURE(tflite_convolution_f32, inception_v3, "Inception v3")->Apply(InceptionV3)->UseRealTime(); BENCHMARK_CAPTURE(tflite_convolution_f32, resnet18, "ResNet-18")->Apply(ResNet18)->UseRealTime(); BENCHMARK_CAPTURE(tflite_convolution_f32, resnet50, "ResNet-50")->Apply(ResNet50)->UseRealTime(); BENCHMARK_CAPTURE(tflite_convolution_f32, vgg, "VGG")->Apply(VGG)->UseRealTime(); BENCHMARK_CAPTURE(tflite_convolution_f32, srcnn915, "SRCNN (9-1-5)")->Apply(SRCNN915)->UseRealTime(); BENCHMARK_CAPTURE(tflite_convolution_f32, srcnn935, "SRCNN (9-3-5)")->Apply(SRCNN935)->UseRealTime(); BENCHMARK_CAPTURE(tflite_convolution_f32, srcnn955, "SRCNN (9-5-5)")->Apply(SRCNN955)->UseRealTime(); #endif // BENCHMARK_TENSORFLOW_LITE #ifdef BENCHMARK_ARM_COMPUTE_LIBRARY BENCHMARK_CAPTURE(armcl_convolution_f32, mobilenet_v1, "MobileNet v1")->Apply(MobileNetV1)->UseRealTime(); BENCHMARK_CAPTURE(armcl_convolution_f32, mobilenet_v2, "MobileNet v2")->Apply(MobileNetV2)->UseRealTime(); BENCHMARK_CAPTURE(armcl_convolution_f32, shufflenet_v1_g1, "ShuffleNet v1 (1 group)")->Apply(ShuffleNetV1G1)->UseRealTime(); BENCHMARK_CAPTURE(armcl_convolution_f32, shufflenet_v1_g2, "ShuffleNet v1 (2 groups)")->Apply(ShuffleNetV1G2)->UseRealTime(); BENCHMARK_CAPTURE(armcl_convolution_f32, shufflenet_v1_g3, "ShuffleNet v1 (3 groups)")->Apply(ShuffleNetV1G3)->UseRealTime(); BENCHMARK_CAPTURE(armcl_convolution_f32, shufflenet_v1_g4, "ShuffleNet v1 (4 groups)")->Apply(ShuffleNetV1G4)->UseRealTime(); BENCHMARK_CAPTURE(armcl_convolution_f32, shufflenet_v1_g8, "ShuffleNet v1 (8 groups)")->Apply(ShuffleNetV1G8)->UseRealTime(); BENCHMARK_CAPTURE(armcl_convolution_f32, shufflenet_v2_x05, "ShuffleNet v2 0.5X")->Apply(ShuffleNetV2X05)->UseRealTime(); BENCHMARK_CAPTURE(armcl_convolution_f32, shufflenet_v2_x10, "ShuffleNet v2 1.0X")->Apply(ShuffleNetV2X10)->UseRealTime(); BENCHMARK_CAPTURE(armcl_convolution_f32, shufflenet_v2_x15, "ShuffleNet v2 1.5X")->Apply(ShuffleNetV2X15)->UseRealTime(); BENCHMARK_CAPTURE(armcl_convolution_f32, shufflenet_v2_x20, "ShuffleNet v2 2.0X")->Apply(ShuffleNetV2X20)->UseRealTime(); BENCHMARK_CAPTURE(armcl_convolution_f32, squeezenet_v10, "SqueezeNet 1.0")->Apply(SqueezeNetV10)->UseRealTime(); BENCHMARK_CAPTURE(armcl_convolution_f32, squeezenet_v11, "SqueezeNet 1.1")->Apply(SqueezeNetV11)->UseRealTime(); BENCHMARK_CAPTURE(armcl_convolution_f32, inception_v3, "Inception v3")->Apply(InceptionV3)->UseRealTime(); BENCHMARK_CAPTURE(armcl_convolution_f32, resnet18, "ResNet-18")->Apply(ResNet18)->UseRealTime(); BENCHMARK_CAPTURE(armcl_convolution_f32, resnet50, "ResNet-50")->Apply(ResNet50)->UseRealTime(); BENCHMARK_CAPTURE(armcl_convolution_f32, vgg, "VGG")->Apply(VGG)->UseRealTime(); BENCHMARK_CAPTURE(armcl_convolution_f32, srcnn915, "SRCNN (9-1-5)")->Apply(SRCNN915)->UseRealTime(); BENCHMARK_CAPTURE(armcl_convolution_f32, srcnn935, "SRCNN (9-3-5)")->Apply(SRCNN935)->UseRealTime(); BENCHMARK_CAPTURE(armcl_convolution_f32, srcnn955, "SRCNN (9-5-5)")->Apply(SRCNN955)->UseRealTime(); #endif // BENCHMARK_ARM_COMPUTE_LIBRARY #ifndef XNNPACK_BENCHMARK_NO_MAIN BENCHMARK_MAIN(); #endif
53.582466
144
0.496022
[ "vector", "model" ]
02fbb0b86115dea6df684855ec5cace091b9beab
2,067
cpp
C++
modules/io/src/serializable.cpp
cecabert/FaceKit
766a32fc7f65ae5deceeba5628c225631986c4d8
[ "Apache-2.0" ]
null
null
null
modules/io/src/serializable.cpp
cecabert/FaceKit
766a32fc7f65ae5deceeba5628c225631986c4d8
[ "Apache-2.0" ]
null
null
null
modules/io/src/serializable.cpp
cecabert/FaceKit
766a32fc7f65ae5deceeba5628c225631986c4d8
[ "Apache-2.0" ]
1
2017-11-29T12:03:08.000Z
2017-11-29T12:03:08.000Z
/** * @file serializable.cpp * @brief Interface definition for object that can be saved/loaded into file * @ingroup io * * @author Christophe Ecabert * @date 24.09.17 * Copyright © 2017 Christophe Ecabert. All rights reserved. */ #include <fstream> #include "facekit/io/serializable.hpp" #include "facekit/io/object_manager.hpp" #include "facekit/io/file_io.hpp" /** * @namespace FaceKit * @brief Development space */ namespace FaceKit { /* * @name StreamHelper * @fn static int StreamHelper(std::istream& stream, const std::string& classname) * @brief Helper method to search within a stream a given object name. * @param[in,out] stream Binary stream to search in. * @param[in] classname Object's name to search for * @retunr -1 if no object match the name, 0 otherwise. When returning 0 the stream is already at the correct position, therefore object can be loaded directly. */ int Serializable::StreamHelper(std::istream& stream, const std::string& classname) { int err = -1; if (stream.good()) { size_t id = ObjectManager::Get().GetId(classname); err = IO::ScanStream(stream, id); } return err; } /* * @name Load * @fn int Load(const std::string& filename) * @brief Load from a given \p filename * @param[in] filename Path to the model file * @return -1 if error, 0 otherwise */ int Serializable::Load(const std::string& filename) { int err = -1; std::ifstream stream(filename.c_str(), std::ios_base::binary); if (stream.is_open()) { err = this->Load(stream); } return err; } /* * @name Save * @fn int Save(const std::string& filename) const * @brief Save to a given \p filename * @param[in] filename Path to the model file * @return -1 if error, 0 otherwise */ int Serializable::Save(const std::string& filename) const { int err = -1; std::ofstream stream(filename.c_str(), std::ios_base::binary); if (stream.is_open()) { err = this->Save(stream); } return err; } } // namespace FaceKit
27.197368
77
0.656991
[ "object", "model" ]
02fdaab211d305a8b0ec943362549e62b3af3aba
9,109
cpp
C++
src/aux/aux_line_like.cpp
somerandomdev49/ldpl
c9d94b0d402bbccbcc6a3be81c7a5a0e94d10ac3
[ "Apache-2.0" ]
142
2019-01-30T08:00:04.000Z
2022-03-12T17:26:53.000Z
src/aux/aux_line_like.cpp
somerandomdev49/ldpl
c9d94b0d402bbccbcc6a3be81c7a5a0e94d10ac3
[ "Apache-2.0" ]
188
2019-03-03T06:56:29.000Z
2022-02-10T21:45:48.000Z
src/aux/aux_line_like.cpp
somerandomdev49/ldpl
c9d94b0d402bbccbcc6a3be81c7a5a0e94d10ac3
[ "Apache-2.0" ]
35
2019-02-18T00:46:06.000Z
2022-01-30T03:06:29.000Z
/* This file contains the line_like function used for pattern matching lines */ // +---------------------------------------------+ // | TODO: comment and format this file properly | // +---------------------------------------------+ // Check if the tokens of a line passed are like the ones of a model line bool line_like(string model_line, vector<string> &tokens, compiler_state &state) { // Tokenize model line vector<string> model_tokens; tokenize(model_line, model_tokens, state.where, false, ' '); // Check that tokens match between line and model line if (tokens.size() < model_tokens.size()) return false; unsigned int i = 0; unsigned int j = 0; for (; i < model_tokens.size(); ++i) { if (model_tokens[i] == "$name") // $name is a valid identifier for a variable or a sub-procedure { for (char letter : tokens[j]) if (letter == ':') return false; for (char letter : tokens[j]) if (letter == '\"') return false; for (char letter : tokens[j]) if (letter == '(') return false; for (char letter : tokens[j]) if (letter == ')') return false; if (is_number(tokens[j])) return false; if (tokens[j] == "+") return false; if (tokens[j] == "-") return false; if (tokens[j] == "*") return false; if (tokens[j] == "/") return false; } else if (model_tokens[i] == "$num-var") // $num-var is NUMBER variable { if (!is_num_var(tokens[j], state)) return false; } else if (model_tokens[i] == "$str-var") // $str-var is TEXT variable { if (!is_txt_var(tokens[j], state)) return false; } else if (model_tokens[i] == "$var") // $var is either a NUMBER variable or a TEXT variable { if (!is_scalar_variable(tokens[j], state)) return false; } else if (model_tokens[i] == "$anyVar") // $anyVar is any variable { if (!variable_exists(tokens[j], state)) return false; } else if (model_tokens[i] == "$scalar-map") { // $scalar-map is TEXT MAP, NUMBER MAP if (!is_scalar_map(tokens[j], state)) return false; } else if (model_tokens[i] == "$num-vec") // $num-vec is NUMBER vector { if (!is_num_map(tokens[j], state)) return false; } else if (model_tokens[i] == "$str-vec") // $str-vec is TEXT vector { if (!is_txt_map(tokens[j], state)) return false; } else if (model_tokens[i] == "$list") { // $list is a LIST if (variable_type(tokens[j], state).back() != 3) return false; } else if (model_tokens[i] == "$map") { // $map is a MAP if (variable_type(tokens[j], state).back() != 4) return false; } else if (model_tokens[i] == "$scalar-list") { // $scalar-list is a LIST of scalar values if (!is_scalar_list(tokens[j], state)) return false; } else if (model_tokens[i] == "$num-list") // $num-vec is NUMBER list { if (!is_num_list(tokens[j], state)) return false; } else if (model_tokens[i] == "$str-list") // $str-vec is TEXT list { if (!is_txt_list(tokens[j], state)) return false; } else if (model_tokens[i] == "$list-list") // $str-vec is a LIST of LISTs { if (!is_list_list(tokens[j], state)) return false; } else if (model_tokens[i] == "$map-list") // $str-vec is LIST of MAPs { if (!is_map_list(tokens[j], state)) return false; } else if (model_tokens[i] == "$collection") // $collection is either a MAP or a LIST { // if(!is_scalar_map(tokens[j], state) && !is_scalar_list(tokens[j], state) && (variable_type(tokens[j], state).size() < 2)) return false; if (variable_type(tokens[j], state).size() < 2) return false; } else if (model_tokens[i] == "$literal") // $literal is either a NUMBER or a TEXT { if (!is_string(tokens[j]) && !is_number(tokens[j])) return false; } else if (model_tokens[i] == "$string") // $string is a TEXT literal { if (!is_string(tokens[j])) return false; } else if (model_tokens[i] == "$number") // $number is a NUMBER literal { if (!is_number(tokens[j])) return false; } else if (model_tokens[i] == "$expression") // $expression is NUMBER, TEXT, TEXT-VAR, NUMBER-VAR { if (!is_expression(tokens[j], state)) return false; } else if (model_tokens[i] == "$str-expr") // $str-expr is either a TEXT or a TEXT variable { if (!is_txt_expr(tokens[j], state)) return false; } else if (model_tokens[i] == "$num-expr") // $num-expr is either a NUMBER or a NUMBER variable { if (!is_num_expr(tokens[j], state)) return false; } else if (model_tokens[i].find("$var-type-") == 0) // variable with a given type number { vector<unsigned int> actual_type = variable_type(tokens[j], state); string expected_type = model_tokens[i].substr(10); if (actual_type.size() != expected_type.length()) return false; for (size_t t = 0; t < actual_type.size(); ++t) { if ((int)actual_type[t] != expected_type[t] - '0') return false; } } else if (model_tokens[i] == "$natural") // $natural is an integer greater than 0 { if (!is_natural(tokens[j])) return false; } else if (model_tokens[i] == "$display") // multiple NUMBER, TEXT, TEXT-VAR, NUMBER-VAR { for (; j < tokens.size(); ++j) { if (!is_expression(tokens[j], state)) return false; } } else if (model_tokens[i] == "$subprocedure") // $subprocedure is a SUB-PROCEDURE { if (!is_subprocedure(tokens[j], state)) return false; } else if (model_tokens[i] == "$external") // $external is a C++ function defined elsewhere { return !is_subprocedure(tokens[j], state) && !is_expression(tokens[j], state); } else if (model_tokens[i] == "$label") // $label is a GOTO label { return is_label(tokens[j]); } else if (model_tokens[i] == "$math") // $math is a math expression { vector<string> maths; // further tokenize math expressions string math_token = ""; for (; j < tokens.size(); ++j) { for (unsigned int z = 0; z < tokens[j].size(); ++z) { if (tokens[j][z] == '(' || tokens[j][z] == ')') { if (!math_token.empty()) maths.push_back(math_token); math_token = tokens[j][z]; maths.push_back(math_token); math_token = ""; } else { math_token += tokens[j][z]; } } if (!math_token.empty()) maths.push_back(math_token); math_token = ""; } // replace LDPL line tokens with new math tokens tokens.erase(tokens.begin() + i, tokens.end()); tokens.insert(tokens.end(), maths.begin(), maths.end()); // validate the new tokens for (unsigned int z = i; z < tokens.size(); ++z) { if (!is_math_symbol(tokens[z]) && !is_expression(tokens[z], state)) return false; } return true; } else if (model_tokens[i] == "$condition") // $condition is a IF/WHILE condition { // Skip to the last token (THEN/DO), // the condition is validated in get_c_condition j = tokens.size() - 1; continue; } else if (model_tokens[i] == "$anything") return true; else if (model_tokens[i] != tokens[j]) return false; ++j; } if (j < tokens.size()) return false; return true; }
37.485597
150
0.466681
[ "vector", "model" ]
f301ab11be75110caa67d946aaf3c68d3993fa9a
31,079
cpp
C++
player/common/Content/StatusDisplay.cpp
Bhaskers-Blu-Org2/MixedReality-HolographicRemoting-Samples
6c27b5f963874c65e00997720f7b05df2ca9638e
[ "MIT" ]
null
null
null
player/common/Content/StatusDisplay.cpp
Bhaskers-Blu-Org2/MixedReality-HolographicRemoting-Samples
6c27b5f963874c65e00997720f7b05df2ca9638e
[ "MIT" ]
null
null
null
player/common/Content/StatusDisplay.cpp
Bhaskers-Blu-Org2/MixedReality-HolographicRemoting-Samples
6c27b5f963874c65e00997720f7b05df2ca9638e
[ "MIT" ]
1
2020-07-30T13:17:29.000Z
2020-07-30T13:17:29.000Z
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "pch.h" #include "StatusDisplay.h" #include <shaders\GeometryShader.h> #include <shaders\PixelShader.h> #include <shaders\VPRTVertexShader.h> #include <shaders\VertexShader.h> constexpr const wchar_t Font[] = L"Segoe UI"; // Font size in percent. constexpr float FontSizeLarge = 0.045f; constexpr float FontSizeMedium = 0.035f; constexpr float FontSizeSmall = 0.03f; constexpr const wchar_t FontLanguage[] = L"en-US"; constexpr const float Degree2Rad = 3.14159265359f / 180.0f; constexpr const float Meter2Inch = 39.37f; using namespace DirectX; using namespace Concurrency; using namespace winrt::Windows::Foundation::Numerics; using namespace winrt::Windows::UI::Input::Spatial; // Initializes D2D resources used for text rendering. StatusDisplay::StatusDisplay(const std::shared_ptr<DXHelper::DeviceResourcesCommon>& deviceResources) : m_deviceResources(deviceResources) { CreateDeviceDependentResources(); } // Called once per frame. Rotates the quad, and calculates and sets the model matrix // relative to the position transform indicated by hologramPositionTransform. void StatusDisplay::Update(float deltaTimeInSeconds) { UpdateConstantBuffer( deltaTimeInSeconds, m_modelConstantBufferDataImage, m_isOpaque ? m_positionContent : m_positionOffset, m_normalContent); UpdateConstantBuffer(deltaTimeInSeconds, m_modelConstantBufferDataText, m_positionContent, m_normalContent); } // Renders a frame to the screen. void StatusDisplay::Render() { // Loading is asynchronous. Resources must be created before drawing can occur. if (!m_loadingComplete) { return; } // First render all text using direct2D. { std::scoped_lock lock(m_lineMutex); if (m_lines.size() > 0 && m_lines != m_previousLines) { m_previousLines.resize(m_lines.size()); m_runtimeLines.resize(m_lines.size()); for (int i = 0; i < m_lines.size(); ++i) { if (m_lines[i] != m_previousLines[i]) { UpdateLineInternal(m_runtimeLines[i], m_lines[i]); m_previousLines[i] = m_lines[i]; } } m_deviceResources->UseD3DDeviceContext( [&](auto context) { context->ClearRenderTargetView(m_textRenderTarget.get(), DirectX::Colors::Transparent); }); m_d2dTextRenderTarget->BeginDraw(); float top = 0.0f; for (auto& line : m_runtimeLines) { if (line.alignBottom) { top = m_textTextureHeight - line.metrics.height; } m_d2dTextRenderTarget->DrawTextLayout(D2D1::Point2F(0, top), line.layout.get(), m_brushes[line.color].get()); top += line.metrics.height * line.lineHeightMultiplier; } // Ignore D2DERR_RECREATE_TARGET here. This error indicates that the device // is lost. It will be handled during the next call to Present. const HRESULT hr = m_d2dTextRenderTarget->EndDraw(); if (hr != D2DERR_RECREATE_TARGET) { winrt::check_hresult(hr); } } } // Now render the quads into 3d space if (m_imageEnabled && m_imageView || !m_lines.empty()) { m_deviceResources->UseD3DDeviceContext([&](auto context) { DXHelper::D3D11StoreAndRestoreState(context, [&]() { // Each vertex is one instance of the VertexBufferElement struct. const UINT stride = sizeof(VertexBufferElement); const UINT offset = 0; ID3D11Buffer* pBufferToSet = m_vertexBufferImage.get(); context->IASetVertexBuffers(0, 1, &pBufferToSet, &stride, &offset); context->IASetIndexBuffer(m_indexBuffer.get(), DXGI_FORMAT_R16_UINT, 0); context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); context->IASetInputLayout(m_inputLayout.get()); context->OMSetBlendState(m_textAlphaBlendState.get(), nullptr, 0xffffffff); context->OMSetDepthStencilState(m_depthStencilState.get(), 0); context->UpdateSubresource(m_modelConstantBuffer.get(), 0, nullptr, &m_modelConstantBufferDataImage, 0, 0); // Apply the model constant buffer to the vertex shader. pBufferToSet = m_modelConstantBuffer.get(); context->VSSetConstantBuffers(0, 1, &pBufferToSet); // Attach the vertex shader. context->VSSetShader(m_vertexShader.get(), nullptr, 0); // On devices that do not support the D3D11_FEATURE_D3D11_OPTIONS3:: // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature, // a pass-through geometry shader sets the render target ID. context->GSSetShader(!m_usingVprtShaders ? m_geometryShader.get() : nullptr, nullptr, 0); // Attach the pixel shader. context->PSSetShader(m_pixelShader.get(), nullptr, 0); // Draw the image. if (m_imageEnabled && m_imageView) { ID3D11ShaderResourceView* pShaderViewToSet = m_imageView.get(); context->PSSetShaderResources(0, 1, &pShaderViewToSet); ID3D11SamplerState* pSamplerToSet = m_imageSamplerState.get(); context->PSSetSamplers(0, 1, &pSamplerToSet); context->DrawIndexedInstanced( m_indexCount, // Index count per instance. 2, // Instance count. 0, // Start index location. 0, // Base vertex location. 0 // Start instance location. ); } // Draw the text. if (!m_lines.empty()) { // Set up for rendering the texture that contains the text pBufferToSet = m_vertexBufferText.get(); context->IASetVertexBuffers(0, 1, &pBufferToSet, &stride, &offset); ID3D11ShaderResourceView* pShaderViewToSet = m_textShaderResourceView.get(); context->PSSetShaderResources(0, 1, &pShaderViewToSet); ID3D11SamplerState* pSamplerToSet = m_textSamplerState.get(); context->PSSetSamplers(0, 1, &pSamplerToSet); context->UpdateSubresource(m_modelConstantBuffer.get(), 0, nullptr, &m_modelConstantBufferDataText, 0, 0); context->DrawIndexedInstanced( m_indexCount, // Index count per instance. 2, // Instance count. 0, // Start index location. 0, // Base vertex location. 0 // Start instance location. ); } }); }); } } void StatusDisplay::CreateDeviceDependentResources() { auto device = m_deviceResources->GetD3DDevice(); CD3D11_TEXTURE2D_DESC textureDesc( DXGI_FORMAT_B8G8R8A8_UNORM, m_textTextureWidth, m_textTextureHeight, 1, 1, D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET); m_textTexture = nullptr; device->CreateTexture2D(&textureDesc, nullptr, m_textTexture.put()); m_textShaderResourceView = nullptr; device->CreateShaderResourceView(m_textTexture.get(), nullptr, m_textShaderResourceView.put()); m_textRenderTarget = nullptr; device->CreateRenderTargetView(m_textTexture.get(), nullptr, m_textRenderTarget.put()); D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties( D2D1_RENDER_TARGET_TYPE_DEFAULT, D2D1::PixelFormat(DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED), 96, 96); winrt::com_ptr<IDXGISurface> dxgiSurface; m_textTexture.as(dxgiSurface); m_d2dTextRenderTarget = nullptr; winrt::check_hresult( m_deviceResources->GetD2DFactory()->CreateDxgiSurfaceRenderTarget(dxgiSurface.get(), &props, m_d2dTextRenderTarget.put())); CreateFonts(); CreateBrushes(); m_usingVprtShaders = m_deviceResources->GetDeviceSupportsVprt(); // If the optional VPRT feature is supported by the graphics device, we // can avoid using geometry shaders to set the render target array index. const auto vertexShaderData = m_usingVprtShaders ? VPRTVertexShader : VertexShader; const auto vertexShaderDataSize = m_usingVprtShaders ? sizeof(VPRTVertexShader) : sizeof(VertexShader); // create the vertex shader and input layout. task<void> createVSTask = task<void>([this, device, vertexShaderData, vertexShaderDataSize]() { winrt::check_hresult(device->CreateVertexShader(vertexShaderData, vertexShaderDataSize, nullptr, m_vertexShader.put())); static const D3D11_INPUT_ELEMENT_DESC vertexDesc[] = { {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0}, }; winrt::check_hresult( device->CreateInputLayout(vertexDesc, ARRAYSIZE(vertexDesc), vertexShaderData, vertexShaderDataSize, m_inputLayout.put())); }); // create the pixel shader and constant buffer. task<void> createPSTask([this, device]() { winrt::check_hresult(device->CreatePixelShader(PixelShader, sizeof(PixelShader), nullptr, m_pixelShader.put())); const CD3D11_BUFFER_DESC constantBufferDesc(sizeof(ModelConstantBuffer), D3D11_BIND_CONSTANT_BUFFER); winrt::check_hresult(device->CreateBuffer(&constantBufferDesc, nullptr, m_modelConstantBuffer.put())); }); task<void> createGSTask; if (!m_usingVprtShaders) { // create the geometry shader. createGSTask = task<void>([this, device]() { winrt::check_hresult(device->CreateGeometryShader(GeometryShader, sizeof(GeometryShader), nullptr, m_geometryShader.put())); }); } // Once all shaders are loaded, create the mesh. task<void> shaderTaskGroup = m_usingVprtShaders ? (createPSTask && createVSTask) : (createPSTask && createVSTask && createGSTask); task<void> createQuadTask = shaderTaskGroup.then([this, device]() { // Load mesh indices. Each trio of indices represents // a triangle to be rendered on the screen. // For example: 2,1,0 means that the vertices with indexes // 2, 1, and 0 from the vertex buffer compose the // first triangle of this mesh. // Note that the winding order is clockwise by default. static const unsigned short quadIndices[] = { 0, 2, 3, // -z 0, 1, 2, }; m_indexCount = ARRAYSIZE(quadIndices); D3D11_SUBRESOURCE_DATA indexBufferData = {0}; indexBufferData.pSysMem = quadIndices; indexBufferData.SysMemPitch = 0; indexBufferData.SysMemSlicePitch = 0; const CD3D11_BUFFER_DESC indexBufferDesc(sizeof(quadIndices), D3D11_BIND_INDEX_BUFFER); winrt::check_hresult(device->CreateBuffer(&indexBufferDesc, &indexBufferData, m_indexBuffer.put())); }); // Create image sampler state { D3D11_SAMPLER_DESC samplerDesc = {}; samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP; samplerDesc.MaxAnisotropy = 1; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = 3; samplerDesc.MipLODBias = 0.f; samplerDesc.BorderColor[0] = 0.f; samplerDesc.BorderColor[1] = 0.f; samplerDesc.BorderColor[2] = 0.f; samplerDesc.BorderColor[3] = 0.f; samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; winrt::check_hresult(device->CreateSamplerState(&samplerDesc, m_imageSamplerState.put())); } // Create text sampler state { CD3D11_SAMPLER_DESC samplerDesc(D3D11_DEFAULT); winrt::check_hresult(device->CreateSamplerState(&samplerDesc, m_textSamplerState.put())); } // Create the blend state. This sets up a blend state for pre-multiplied alpha produced by TextRenderer.cpp's Direct2D text // renderer. CD3D11_BLEND_DESC blendStateDesc(D3D11_DEFAULT); blendStateDesc.AlphaToCoverageEnable = FALSE; blendStateDesc.IndependentBlendEnable = FALSE; const D3D11_RENDER_TARGET_BLEND_DESC rtBlendDesc = { TRUE, D3D11_BLEND_SRC_ALPHA, D3D11_BLEND_INV_SRC_ALPHA, D3D11_BLEND_OP_ADD, D3D11_BLEND_INV_DEST_ALPHA, D3D11_BLEND_ONE, D3D11_BLEND_OP_ADD, D3D11_COLOR_WRITE_ENABLE_ALL, }; for (UINT i = 0; i < D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; ++i) { blendStateDesc.RenderTarget[i] = rtBlendDesc; } winrt::check_hresult(device->CreateBlendState(&blendStateDesc, m_textAlphaBlendState.put())); D3D11_DEPTH_STENCIL_DESC depthStencilDesc = {}; device->CreateDepthStencilState(&depthStencilDesc, m_depthStencilState.put()); // Once the quad is loaded, the object is ready to be rendered. auto loadCompleteCallback = createQuadTask.then([this]() { m_loadingComplete = true; }); } void StatusDisplay::ReleaseDeviceDependentResources() { m_loadingComplete = false; m_usingVprtShaders = false; m_vertexShader = nullptr; m_inputLayout = nullptr; m_pixelShader = nullptr; m_geometryShader = nullptr; m_modelConstantBuffer = nullptr; m_vertexBufferImage = nullptr; m_vertexBufferText = nullptr; m_indexBuffer = nullptr; m_imageView = nullptr; m_imageSamplerState = nullptr; m_textSamplerState = nullptr; m_textAlphaBlendState = nullptr; for (size_t i = 0; i < ARRAYSIZE(m_brushes); i++) { m_brushes[i] = nullptr; } for (size_t i = 0; i < ARRAYSIZE(m_textFormats); i++) { m_textFormats[i] = nullptr; } } void StatusDisplay::ClearLines() { std::scoped_lock lock(m_lineMutex); m_lines.resize(0); } void StatusDisplay::SetLines(winrt::array_view<Line> lines) { std::scoped_lock lock(m_lineMutex); auto numLines = lines.size(); m_lines.resize(numLines); for (uint32_t i = 0; i < numLines; i++) { assert((!lines[i].alignBottom || i == numLines - 1) && "Only the last line can use alignBottom = true"); m_lines[i] = lines[i]; } } void StatusDisplay::UpdateLineText(size_t index, std::wstring text) { std::scoped_lock lock(m_lineMutex); if (index >= m_lines.size()) { return; } m_lines[index].text = text; } size_t StatusDisplay::AddLine(const Line& line) { std::scoped_lock lock(m_lineMutex); size_t newIndex = m_lines.size(); m_lines.resize(newIndex + 1); m_lines[newIndex] = line; return newIndex; } bool StatusDisplay::HasLine(size_t index) { std::scoped_lock lock(m_lineMutex); return index < m_lines.size(); } void StatusDisplay::CreateFonts() { // DIP font size, based on the horizontal size of the virtual display. float fontSizeLargeDIP = (m_virtualDisplaySizeInchX * FontSizeLarge) * 96; float fontSizeMediumDIP = (m_virtualDisplaySizeInchX * FontSizeMedium) * 96; float fontSizeSmallDIP = (m_virtualDisplaySizeInchX * FontSizeSmall) * 96; // Create Large font m_textFormats[Large] = nullptr; winrt::check_hresult(m_deviceResources->GetDWriteFactory()->CreateTextFormat( Font, nullptr, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, fontSizeLargeDIP, FontLanguage, m_textFormats[Large].put())); winrt::check_hresult(m_textFormats[Large]->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)); winrt::check_hresult(m_textFormats[Large]->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER)); // Create large bold font m_textFormats[LargeBold] = nullptr; winrt::check_hresult(m_deviceResources->GetDWriteFactory()->CreateTextFormat( Font, nullptr, DWRITE_FONT_WEIGHT_BOLD, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, fontSizeLargeDIP, FontLanguage, m_textFormats[LargeBold].put())); winrt::check_hresult(m_textFormats[LargeBold]->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)); winrt::check_hresult(m_textFormats[LargeBold]->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER)); // Create small font m_textFormats[Small] = nullptr; winrt::check_hresult(m_deviceResources->GetDWriteFactory()->CreateTextFormat( Font, nullptr, DWRITE_FONT_WEIGHT_MEDIUM, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, fontSizeSmallDIP, FontLanguage, m_textFormats[Small].put())); winrt::check_hresult(m_textFormats[Small]->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)); winrt::check_hresult(m_textFormats[Small]->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER)); // Create medium font m_textFormats[Medium] = nullptr; winrt::check_hresult(m_deviceResources->GetDWriteFactory()->CreateTextFormat( Font, nullptr, DWRITE_FONT_WEIGHT_MEDIUM, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, fontSizeMediumDIP, FontLanguage, m_textFormats[Medium].put())); winrt::check_hresult(m_textFormats[Medium]->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)); winrt::check_hresult(m_textFormats[Medium]->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER)); static_assert(TextFormatCount == 4, "Expected 4 text formats"); } void StatusDisplay::CreateBrushes() { m_brushes[White] = nullptr; winrt::check_hresult(m_d2dTextRenderTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::FloralWhite), m_brushes[White].put())); m_brushes[Yellow] = nullptr; winrt::check_hresult(m_d2dTextRenderTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Yellow), m_brushes[Yellow].put())); m_brushes[Red] = nullptr; winrt::check_hresult(m_d2dTextRenderTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Red), m_brushes[Red].put())); } void StatusDisplay::UpdateLineInternal(RuntimeLine& runtimeLine, const Line& line) { assert(line.format >= 0 && line.format < TextFormatCount && "Line text format out of bounds"); assert(line.color >= 0 && line.color < TextColorCount && "Line text color out of bounds"); if (line.format != runtimeLine.format || line.text != runtimeLine.text) { runtimeLine.format = line.format; runtimeLine.text = line.text; const float virtualDisplayDPIx = m_textTextureWidth / m_virtualDisplaySizeInchX; const float virtualDisplayDPIy = m_textTextureHeight / m_virtualDisplaySizeInchY; const float dpiScaleX = virtualDisplayDPIx / 96.0f; const float dpiScaleY = virtualDisplayDPIy / 96.0f; runtimeLine.layout = nullptr; winrt::check_hresult(m_deviceResources->GetDWriteFactory()->CreateTextLayout( line.text.c_str(), static_cast<UINT32>(line.text.length()), m_textFormats[line.format].get(), static_cast<float>(m_textTextureWidth / dpiScaleX), // Max width of the input text. static_cast<float>(m_textTextureHeight / dpiScaleY), // Max height of the input text. runtimeLine.layout.put())); winrt::check_hresult(runtimeLine.layout->GetMetrics(&runtimeLine.metrics)); } runtimeLine.color = line.color; runtimeLine.lineHeightMultiplier = line.lineHeightMultiplier; runtimeLine.alignBottom = line.alignBottom; } void StatusDisplay::SetImage(const winrt::com_ptr<ID3D11ShaderResourceView>& imageView) { m_imageView = imageView; } // This function uses a SpatialPointerPose to position the world-locked hologram // two meters in front of the user's heading. void StatusDisplay::PositionDisplay(float deltaTimeInSeconds, const SpatialPointerPose& pointerPose, float imageOffsetX, float imageOffsetY) { if (pointerPose != nullptr) { // Get the gaze direction relative to the given coordinate system. const float3 headPosition = pointerPose.Head().Position(); const float3 headDirection = pointerPose.Head().ForwardDirection(); const float3 contentPosition = headPosition + (headDirection * m_statusDisplayDistance); const float3 headRight = normalize(cross(headDirection, float3(0, 1, 0))); const float3 headUp = normalize(cross(headRight, headDirection)); m_positionContent = lerp(m_positionContent, contentPosition, deltaTimeInSeconds * c_lerpRate); m_positionOffset = m_positionContent + (headRight * m_virtualDisplaySizeInchX * imageOffsetX) + (headUp * m_virtualDisplaySizeInchY * imageOffsetY); m_normalContent = headDirection; } } void StatusDisplay::UpdateConstantBuffer( float deltaTimeInSeconds, ModelConstantBuffer& buffer, winrt::Windows::Foundation::Numerics::float3 position, winrt::Windows::Foundation::Numerics::float3 normal) { // Create a direction normal from the hologram's position to the origin of person space. // This is the z-axis rotation. XMVECTOR facingNormal = XMVector3Normalize(-XMLoadFloat3(&normal)); // Rotate the x-axis around the y-axis. // This is a 90-degree angle from the normal, in the xz-plane. // This is the x-axis rotation. XMVECTOR xAxisRotation = XMVector3Normalize(XMVectorSet(XMVectorGetZ(facingNormal), 0.f, -XMVectorGetX(facingNormal), 0.f)); // Create a third normal to satisfy the conditions of a rotation matrix. // The cross product of the other two normals is at a 90-degree angle to // both normals. (Normalize the cross product to avoid floating-point math // errors.) // Note how the cross product will never be a zero-matrix because the two normals // are always at a 90-degree angle from one another. XMVECTOR yAxisRotation = XMVector3Normalize(XMVector3Cross(facingNormal, xAxisRotation)); // Construct the 4x4 rotation matrix. // Rotate the quad to face the user. XMMATRIX rotationMatrix = XMMATRIX(xAxisRotation, yAxisRotation, facingNormal, XMVectorSet(0.f, 0.f, 0.f, 1.f)); // Position the quad. const XMMATRIX modelTranslation = XMMatrixTranslationFromVector(XMLoadFloat3(&position)); // The view and projection matrices are provided by the system; they are associated // with holographic cameras, and updated on a per-camera basis. // Here, we provide the model transform for the sample hologram. The model transform // matrix is transposed to prepare it for the shader. XMStoreFloat4x4(&buffer.model, XMMatrixTranspose(rotationMatrix * modelTranslation)); } void StatusDisplay::UpdateTextScale( winrt::Windows::Graphics::Holographic::HolographicStereoTransform holoTransform, float screenWidth, float screenHeight, bool isLandscape, bool isOpaque) { DirectX::XMMATRIX projMat = XMLoadFloat4x4(&holoTransform.Left); DirectX::XMFLOAT4X4 proj; DirectX::XMStoreFloat4x4(&proj, projMat); // Check if the projection matrix has changed. bool projHasChanged = false; for (int x = 0; x < 4; ++x) { for (int y = 0; y < 4; ++y) { if (proj.m[x][y] != m_projection.m[x][y]) { projHasChanged = true; break; } } if (projHasChanged) { break; } } m_isOpaque = isOpaque; float quadFov = m_defaultQuadFov; float heightRatio = 1.0f; if (isLandscape) { quadFov = m_landscapeQuadFov; heightRatio = m_landscapeHeightRatio; } if (m_isOpaque) { quadFov *= 1.5f; } const float fovDiff = m_currentQuadFov - quadFov; const float fovEpsilon = 0.1f; const bool quadFovHasChanged = std::abs(fovDiff) > fovEpsilon; m_currentQuadFov = quadFov; const float heightRatioDiff = m_currentHeightRatio - heightRatio; const float heightRatioEpsilon = 0.1f; const bool quadRatioHasChanged = std::abs(heightRatioDiff) > heightRatioEpsilon; m_currentHeightRatio = heightRatio; // Only update the StatusDisplay resolution and size if something has changed. if (projHasChanged || quadFovHasChanged || quadRatioHasChanged) { // Quad extent based on FOV. const float quadExtentX = tan((m_currentQuadFov / 2.0f) * Degree2Rad) * m_statusDisplayDistance; const float quadExtentY = m_currentHeightRatio * quadExtentX; // Calculate the virtual display size in inch. m_virtualDisplaySizeInchX = (quadExtentX * 2.0f) * Meter2Inch; m_virtualDisplaySizeInchY = (quadExtentY * 2.0f) * Meter2Inch; // Pixel perfect resolution. const float resX = screenWidth * quadExtentX / m_statusDisplayDistance * proj._11; const float resY = screenHeight * quadExtentY / m_statusDisplayDistance * proj._22; // sample with double resolution for multi sampling. m_textTextureWidth = static_cast<int>(resX * 2.0f); m_textTextureHeight = static_cast<int>(resY * 2.0f); m_projection = proj; // Create the new texture. auto device = m_deviceResources->GetD3DDevice(); // Load mesh vertices. Each vertex has a position and a color. // Note that the quad size has changed from the default DirectX app // template. The quad size is based on the target FOV. const VertexBufferElement quadVerticesText[] = { {XMFLOAT3(-quadExtentX, quadExtentY, 0.f), XMFLOAT2(0.f, 0.f)}, {XMFLOAT3(quadExtentX, quadExtentY, 0.f), XMFLOAT2(1.f, 0.f)}, {XMFLOAT3(quadExtentX, -quadExtentY, 0.f), XMFLOAT2(1.f, 1.f)}, {XMFLOAT3(-quadExtentX, -quadExtentY, 0.f), XMFLOAT2(0.f, 1.f)}, }; D3D11_SUBRESOURCE_DATA vertexBufferDataText = {0}; vertexBufferDataText.pSysMem = quadVerticesText; vertexBufferDataText.SysMemPitch = 0; vertexBufferDataText.SysMemSlicePitch = 0; const CD3D11_BUFFER_DESC vertexBufferDescText(sizeof(quadVerticesText), D3D11_BIND_VERTEX_BUFFER); m_vertexBufferText = nullptr; winrt::check_hresult(device->CreateBuffer(&vertexBufferDescText, &vertexBufferDataText, m_vertexBufferText.put())); // Create image buffer // The image contains 50% of the textFOV. const float imageFOVDegree = (m_isOpaque ? 0.75f : 0.2f) * (m_currentQuadFov * 0.5f); const float imageQuadExtent = m_statusDisplayDistance / tan((90.0f - imageFOVDegree) * Degree2Rad); const VertexBufferElement quadVertices[] = { {XMFLOAT3(-imageQuadExtent, imageQuadExtent, 0.f), XMFLOAT2(0.f, 0.f)}, {XMFLOAT3(imageQuadExtent, imageQuadExtent, 0.f), XMFLOAT2(1.f, 0.f)}, {XMFLOAT3(imageQuadExtent, -imageQuadExtent, 0.f), XMFLOAT2(1.f, 1.f)}, {XMFLOAT3(-imageQuadExtent, -imageQuadExtent, 0.f), XMFLOAT2(0.f, 1.f)}, }; D3D11_SUBRESOURCE_DATA vertexBufferData = {0}; vertexBufferData.pSysMem = quadVertices; vertexBufferData.SysMemPitch = 0; vertexBufferData.SysMemSlicePitch = 0; const CD3D11_BUFFER_DESC vertexBufferDesc(sizeof(quadVertices), D3D11_BIND_VERTEX_BUFFER); m_vertexBufferImage = nullptr; winrt::check_hresult(device->CreateBuffer(&vertexBufferDesc, &vertexBufferData, m_vertexBufferImage.put())); CD3D11_TEXTURE2D_DESC textureDesc( DXGI_FORMAT_B8G8R8A8_UNORM, m_textTextureWidth, m_textTextureHeight, 1, 1, D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET); m_textTexture = nullptr; device->CreateTexture2D(&textureDesc, nullptr, m_textTexture.put()); m_textShaderResourceView = nullptr; device->CreateShaderResourceView(m_textTexture.get(), nullptr, m_textShaderResourceView.put()); m_textRenderTarget = nullptr; device->CreateRenderTargetView(m_textTexture.get(), nullptr, m_textRenderTarget.put()); const float virtualDisplayDPIx = m_textTextureWidth / m_virtualDisplaySizeInchX; const float virtualDisplayDPIy = m_textTextureHeight / m_virtualDisplaySizeInchY; D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties( D2D1_RENDER_TARGET_TYPE_DEFAULT, D2D1::PixelFormat(DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED), virtualDisplayDPIx, virtualDisplayDPIy); winrt::com_ptr<IDXGISurface> dxgiSurface; m_textTexture.as(dxgiSurface); m_d2dTextRenderTarget = nullptr; winrt::check_hresult( m_deviceResources->GetD2DFactory()->CreateDxgiSurfaceRenderTarget(dxgiSurface.get(), &props, m_d2dTextRenderTarget.put())); // Update the fonts. CreateFonts(); // Trigger full recreation in the next frame m_previousLines.clear(); m_runtimeLines.clear(); } } bool StatusDisplay::Line::operator==(const Line& line) const { return std::tie(text, format, color, lineHeightMultiplier, alignBottom) == std::tie(line.text, line.format, line.color, line.lineHeightMultiplier, line.alignBottom); } bool StatusDisplay::Line::operator!=(const Line& line) const { return !operator==(line); }
41.164238
141
0.654139
[ "mesh", "geometry", "render", "object", "model", "transform", "3d" ]
f301ae188a4675ed9ce6cdacaf0bd397fd1f52d9
7,115
cpp
C++
GLEANKernel/GLEANLib/Framework Classes/Device_base.cpp
dekieras/GLEANKernel
fac01f025b65273be96c5ea677c0ce192c570799
[ "MIT" ]
1
2018-06-22T23:01:13.000Z
2018-06-22T23:01:13.000Z
GLEANKernel/GLEANLib/Framework Classes/Device_base.cpp
dekieras/GLEANKernel
fac01f025b65273be96c5ea677c0ce192c570799
[ "MIT" ]
null
null
null
GLEANKernel/GLEANLib/Framework Classes/Device_base.cpp
dekieras/GLEANKernel
fac01f025b65273be96c5ea677c0ce192c570799
[ "MIT" ]
null
null
null
#include "Device_base.h" #include "Device_processor.h" #include "Coordinator.h" #include "Human_base.h" //#include "Human_processor.h" #include "Geometry.h" #include "Symbol_Geometry_utilities.h" #include "Output_tee_globals.h" #include "Glean_standard_symbols.h" #include <iostream> #include <cassert> #include <string> #include <sstream> using namespace std; namespace GU = Geometry_Utilities; Device_base::Device_base(const string& id, Output_tee& ot) : device_out(ot), device_name(id), device_proc_ptr(0) { // create a Device_processor and connect this device to it. // Processor() automatically adds itself to the simulation device_proc_ptr = new Device_processor(device_name + "_interface"); device_proc_ptr->connect(this); } Device_base::~Device_base() { // ~Processor automatically removes itself from the simulation delete device_proc_ptr; device_proc_ptr = 0; } /* // create a Device_processor and connect this device to it. // Device_processor() automatically adds itself to the simulation void Device_base::create_and_connect_interface(const string& interface_name) { device_proc_ptr = new Device_processor(device_proc_name); device_proc_ptr->connect(this); this->connect(device_proc_ptr); } */ void Device_base::initialize() { // make sure we are connected to the rest of the system Assert(device_proc_ptr); } // These dummy functions should be overridden to obtain more complex behavior. void Device_base::handle_Start_event() { } void Device_base::handle_Stop_event() { } void Device_base::handle_Report_event(long) { } void Device_base::handle_Delay_event(const Symbol& type, const Symbol& datum, const Symbol& object_name, const Symbol& property_name, const Symbol& property_value) { } void Device_base::handle_Keystroke_event(const Symbol& key_name) { } void Device_base::handle_Type_In_event(const Symbol& type_in_string) { } void Device_base::handle_Hold_event(const Symbol& button_name) { } void Device_base::handle_Release_event(const Symbol& button_name) { } void Device_base::handle_Click_event(const Symbol& button_name) { } void Device_base::handle_Double_Click_event(const Symbol& button_name) { } void Device_base::handle_Point_event(const Symbol& target_name) { } void Device_base::handle_Ply_event(const Symbol& cursor_name, const Symbol& target_name, GU::Point new_location, GU::Polar_vector movement_vector) { } void Device_base::handle_Vocal_event(const Symbol& vocal_input) { } void Device_base::handle_Vocal_event(const Symbol& vocal_input, long duration) { } void Device_base::handle_VisualFocusChange_event(const Symbol& object_name) { } void Device_base::handle_Eyemovement_Start_event(const Symbol& target_name, GU::Point new_location) { } void Device_base::handle_Eyemovement_End_event(const Symbol& target_name, GU::Point new_location) { } void Device_base::handle_HLGet_event(const Symbol_list_t& props, const Symbol_list_t& values, const Symbol& tag) { // default response is to simply echo the information back with a dummy name make_high_level_input_appear(Symbol("HLDummyObject"), props, values, tag); } void Device_base::handle_HLPut_event(const Symbol_list_t& props, const Symbol_list_t& values) { } /* Services for derived and related classes */ string Device_base::processor_info() const { ostringstream oss; oss << get_time() << ' ' << device_name << ':'; return oss.str(); } long Device_base::get_time() const { return Coordinator::get_instance().get_time(); } bool Device_base::get_trace() const { return device_proc_ptr->get_trace(); } void Device_base::set_trace(bool trace_) { device_proc_ptr->set_trace(trace_); } // Tell the simulated human we have a new visual object with unspecified location and size void Device_base::make_visual_object_appear(const Symbol& object_name) { device_proc_ptr->make_visual_object_appear(object_name); } // Tell the simulated human we have a new visual object with specified location and size void Device_base::make_visual_object_appear(const Symbol& object_name, Geometry_Utilities::Point location, Geometry_Utilities::Size size) { device_proc_ptr->make_visual_object_appear(object_name, location, size); } void Device_base::set_visual_object_location(const Symbol& object_name, GU::Point location) { device_proc_ptr->set_visual_object_location(object_name, location); } void Device_base::set_visual_object_size(const Symbol& object_name, GU::Size size) { device_proc_ptr->set_visual_object_size(object_name, size); } // Tell the simulated human we have a value for a property of a visual object void Device_base::set_visual_object_property(const Symbol& object_name, const Symbol& property_name, const Symbol& property_value) { Assert(object_name != Nil_c); device_proc_ptr->set_visual_object_property(object_name, property_name, property_value); } // Tell the simulated human that a visual object is gone void Device_base::make_visual_object_disappear(const Symbol& object_name) { device_proc_ptr->make_visual_object_disappear(object_name); } // Tell the simulated human that an auditory event is present void Device_base::make_auditory_event(const Symbol& message) { device_proc_ptr->make_auditory_event(message); } // A speech event with source, content (utterance), and duration void Device_base::make_auditory_speech_sound_event(const Symbol& name, const Symbol& source, const Symbol& utterance, long duration) { device_proc_ptr->make_auditory_speech_sound_event(name, source, utterance, duration); } // Tell the simulated human that a High-Level input object with properties and values should be // stored under a WM tag after a specified time delay from now void Device_base::make_high_level_input_appear(const Symbol& object_name, const Symbol_list_t& props, const Symbol_list_t& values, const Symbol& tag) { device_proc_ptr->make_high_level_input_appear(object_name, props, values, tag); } // Tell the simulated human that a High-Level input object is gone // A high-level input disappears after a specified delay void Device_base::make_high_level_input_disappear(const Symbol& object_name) { device_proc_ptr->make_high_level_input_disappear(object_name); } // send a Device_Delay_event to self void Device_base::schedule_delay_event(long delay) { device_proc_ptr->schedule_delay_event(delay); } void Device_base::schedule_delay_event(long delay, const Symbol& delay_type, const Symbol& delay_datum) { device_proc_ptr->schedule_delay_event(delay, delay_type, delay_datum); } void Device_base::schedule_delay_event(long delay, const Symbol& delay_type, const Symbol& object_name, const Symbol& property_name, const Symbol& property_value) { device_proc_ptr->schedule_delay_event(delay, delay_type, object_name, property_name, property_value); } // Tell the simulated human that a report with the specified duration must be made // this is done visually void Device_base::make_report(long time, long duration) { device_proc_ptr->make_report(time, duration); } // service for descendant classes to use to halt simulation. void Device_base::stop_simulation() { device_proc_ptr->do_stop_simulation(); }
27.471042
149
0.793535
[ "geometry", "object" ]
f30324f1be09b778119064ebb5a107de3546d0f3
9,794
cpp
C++
os/kernel/pc/sb16.cpp
rvedam/es-operating-system
32d3e4791c28a5623744800f108d029c40c745fc
[ "Apache-2.0" ]
2
2020-11-30T18:38:20.000Z
2021-06-07T07:44:03.000Z
os/kernel/pc/sb16.cpp
LambdaLord/es-operating-system
32d3e4791c28a5623744800f108d029c40c745fc
[ "Apache-2.0" ]
1
2019-01-14T03:09:45.000Z
2019-01-14T03:09:45.000Z
os/kernel/pc/sb16.cpp
LambdaLord/es-operating-system
32d3e4791c28a5623744800f108d029c40c745fc
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2008, 2009 Google Inc. * Copyright 2006, 2007 Nintendo Co., Ltd. * * 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. */ #include <errno.h> #include <stdio.h> #include <string.h> #include <es.h> #include <es/exception.h> #include <es/handle.h> #include "8237a.h" #include "core.h" #include "io.h" #include "sb16.h" u8* const SoundBlaster16::dmaBuffer8 = (u8*) 0x80021000; u8* const SoundBlaster16::dmaBuffer16 = (u8*) 0x80022000; u8 SoundBlaster16:: readData() { for (;;) { if (inpb(base + READ_STATUS) & 0x80) { return inpb(base + READ); } } } void SoundBlaster16:: writeData(u8 cmd) { for (;;) { if (!(inpb(base + WRITE_STATUS) & 0x80)) { outpb(base + WRITE, cmd); return; } } } u8 SoundBlaster16:: readMixer(u8 addr) { outpb(base + MIXER_ADDR, addr); return inpb(base + MIXER_DATA); } u8 SoundBlaster16:: writeMixer(u8 addr, u8 val) { outpb(base + MIXER_ADDR, addr); outpb(base + MIXER_DATA, val); return inpb(base + MIXER_DATA); } SoundBlaster16:: SoundBlaster16(u8 bus, Dmac* master, Dmac* slave, u16 base, u8 irq, u8 chan8, u8 chan16, u16 mpu401) : base(base), mpu401(mpu401), irq(irq), chan8(chan8), chan16(chan16), odd8(false), odd16(false), line8(0), line16(0), inputLine(this), outputLine(this) { memset(dmaBuffer8, 128, dmaBufferSize8); memset(dmaBuffer16, 0, dmaBufferSize16); // Reset DSP outpb(base + RESET, 1); esSleep(30); // wait for 3 microseconds outpb(base + RESET, 0); esSleep(1000); // wait for 100 microseconds u8 data = readData(); if (data != 0xaa) { throw SystemException<ENODEV>(); } writeData(GET_VERSION); major = readData(); minor = readData(); if (major != 4) { esReport("No SoundBlaster16 compatible sound card found. (DSP version %d.%d)\n", major, minor); throw SystemException<ENODEV>(); } // // initialize the mixer // writeMixer(MIXER_RESET, 0); writeMixer(MIXER_OUTPUT_SWITCHES, 0); writeMixer(MIXER_INPUT_SWITCHES_L, 0); writeMixer(MIXER_INPUT_SWITCHES_R, 0); writeMixer(MIXER_MASTER_L, 31 << 3); writeMixer(MIXER_MASTER_R, 31 << 3); writeMixer(MIXER_VOICE_L, 31 << 3); writeMixer(MIXER_VOICE_R, 31 << 3); writeMixer(MIXER_MIDI_L, 0); writeMixer(MIXER_MIDI_R, 0); writeMixer(MIXER_CD_L, 0); writeMixer(MIXER_CD_R, 0); writeMixer(MIXER_LINE_L, 0); writeMixer(MIXER_LINE_R, 0); writeMixer(MIXER_MIC, 0); writeMixer(MIXER_PC_SPEAKER, 0); writeMixer(MIXER_INPUT_GAIN_L, 0); writeMixer(MIXER_INPUT_GAIN_R, 0); writeMixer(MIXER_OUTPUT_GAIN_L, 0); writeMixer(MIXER_OUTPUT_GAIN_R, 0); writeMixer(MIXER_AGC, 0); writeMixer(MIXER_TREBLE_L, 8 << 4); writeMixer(MIXER_TREBLE_R, 8 << 4); writeMixer(MIXER_BASS_L, 8 << 4); writeMixer(MIXER_BASS_R, 8 << 4); // // Select DMA channels // u8 dma; dma = writeMixer(DMA_SETUP, (1u << chan8) | (1u << chan16)); chan8 = ffs(dma & 0xb) - 1; chan16 = ffs(dma & 0xe0) - 1; if (chan8 != 0xff) { dmac8 = &slave->chan[chan8 & 3]; } else { dmac8 = 0; } if (chan16 != 0xff) { dmac16 = &master->chan[chan16 & 3]; } else { dmac16 = 0; } // // Select IRQ // u8 is; switch (irq) { case 2: is = 0x01; break; case 5: is = 0x02; break; case 7: is = 0x04; break; case 10: is = 0x08; break; default: is = readMixer(INTERRUPT_SETUP); break; } is = writeMixer(INTERRUPT_SETUP, is & 0x0f) & 0x0f; switch (is) { case 0x01: irq = 2; break; case 0x02: irq = 5; break; case 0x04: irq = 7; break; case 0x08: irq = 10; break; default: throw SystemException<ENODEV>(); break; } Core::registerInterruptHandler(bus, irq, this); writeData(SPEAKER_ON); esSleep(1120000); esReport("SoundBlaster DSP version %d.%d - irq %d, chan8 %d chan16 %d\n", major, minor, irq, chan8, chan16); } SoundBlaster16:: ~SoundBlaster16() { } int SoundBlaster16:: invoke(int irq) { switch (irq) { case 0: start(&inputLine); return 0; case 1: start(&outputLine); return 0; default: break; } u8* ptr; u8 status = readMixer(INTERRUPT_STATUS); if (status & 0x01) { // 8-bit DMA ptr = dmaBuffer8; if (odd8) { ptr += dmaBufferSize8 / 2; } if (line8 == &inputLine) { int count = line8->write(ptr, dmaBufferSize8 / 2); if (count == 0) { stop(line8); } } else if (line8 == &outputLine) { int count = line8->read(ptr, dmaBufferSize8 / 2); if (count < dmaBufferSize8 / 2) { memset(ptr + count, 128, dmaBufferSize8 / 2 - count); } if (count == 0) { stop(line8); } } odd8 ^= true; inpb(base + READ_STATUS); } if (status & 0x02) { // 16-bit DMA ptr = dmaBuffer16; if (odd16) { ptr += dmaBufferSize16 / 2; } if (line16 == &inputLine) { line16->write(ptr, dmaBufferSize16 / 2); } else if (line16 == &outputLine) { int count = line16->read(ptr, dmaBufferSize16 / 2); if (count < dmaBufferSize16 / 2) { memset(ptr + count, 0, dmaBufferSize16 / 2 - count); } if (count == 0) { stop(line16); } } odd16 ^= true; inpb(base + READ_STATUS_16); } if (status & 0x04) { // MPU-401 inpb(mpu401); } return 0; } void SoundBlaster16:: start(Line* line) { u8 channels = line->getChannels(); if (channels != 1 && channels != 2) { return; } u8 cmd; u8 mode; if (line == &inputLine) { cmd = SET_INPUT_SAMPLING_RATE; mode = es::Dmac::READ | es::Dmac::AUTO_INITIALIZE; } else if (line == &outputLine) { cmd = SET_OUTPUT_SAMPLING_RATE; mode = es::Dmac::WRITE | es::Dmac::AUTO_INITIALIZE; } else { return; } u8 bits = line->getBitsPerSample(); switch (bits) { case 8: if (line8) { return; } line8 = line; dmac8->setup(dmaBuffer8, dmaBufferSize8, mode); dmac8->start(); break; case 16: if (line16) { return; } line16 = line; dmac16->setup(dmaBuffer16, dmaBufferSize16, mode); dmac16->start(); break; default: return; } writeData(cmd); u16 rate = line->getSamplingRate(); writeData((u8) (rate >> 8)); writeData((u8) rate); u16 samples; switch (bits) { case 8: if (line == &inputLine) { cmd = SET_MODE_8BIT_INPUT; } else { cmd = SET_MODE_8BIT_OUTPUT; } if (channels == 1) { mode = MODE_8BIT_MONO; } else { mode = MODE_8BIT_STEREO; } samples = dmaBufferSize8 / 2 / channels - 1; break; case 16: if (line == &inputLine) { cmd = SET_MODE_16BIT_INPUT; } else { cmd = SET_MODE_16BIT_OUTPUT; } if (channels == 1) { mode = MODE_16BIT_MONO; } else { mode = MODE_16BIT_STEREO; } samples = dmaBufferSize16 / 2 / channels - 1; break; } writeData(cmd); writeData(mode); writeData((u8) samples); writeData((u8) (samples >> 8)); } void SoundBlaster16:: stop(Line* line) { u8 bits = line->getBitsPerSample(); switch (bits) { case 8: writeData(EXIT_AUTOINIT_DMA_8BIT); writeData(PUASE_8BIT); dmac8->stop(); line8 = 0; break; case 16: writeData(EXIT_AUTOINIT_DMA_16BIT); writeData(PUASE_16BIT); dmac16->stop(); line16 = 0; break; } } Object* SoundBlaster16:: queryInterface(const char* riid) { Object* objectPtr; if (strcmp(riid, es::Callback::iid()) == 0) { objectPtr = static_cast<es::Callback*>(this); } else if (strcmp(riid, Object::iid()) == 0) { objectPtr = static_cast<es::Callback*>(this); } else { return NULL; } objectPtr->addRef(); return objectPtr; } unsigned int SoundBlaster16:: addRef() { return ref.addRef(); } unsigned int SoundBlaster16:: release() { unsigned int count = ref.release(); if (count == 0) { delete this; return 0; } return count; }
20.882729
112
0.526241
[ "object" ]
f3032db467384a936aa9afb777dd431e7b5f9238
1,829
cpp
C++
src/RESTAPI_callback.cpp
sdechi/wlan-cloud-ucentralgw
fc7933f8919d50c493d7da0c2cb7e415bce2df43
[ "BSD-3-Clause" ]
null
null
null
src/RESTAPI_callback.cpp
sdechi/wlan-cloud-ucentralgw
fc7933f8919d50c493d7da0c2cb7e415bce2df43
[ "BSD-3-Clause" ]
null
null
null
src/RESTAPI_callback.cpp
sdechi/wlan-cloud-ucentralgw
fc7933f8919d50c493d7da0c2cb7e415bce2df43
[ "BSD-3-Clause" ]
null
null
null
// // License type: BSD 3-Clause License // License copy: https://github.com/Telecominfraproject/wlan-cloud-ucentralgw/blob/master/LICENSE // // Created by Stephane Bourque on 2021-03-04. // Arilia Wireless Inc. // #include "RESTAPI_callback.h" #include "Poco/JSON/Object.h" #include "Poco/JSON/Parser.h" #include "uStorageService.h" #include "RESTAPI_protocol.h" void RESTAPI_callback::handleRequest(Poco::Net::HTTPServerRequest& Request, Poco::Net::HTTPServerResponse& Response) { if(!ContinueProcessing(Request,Response)) return; if(!ValidateAPIKey(Request, Response)) return; ParseParameters(Request); try { if(Request.getMethod()==Poco::Net::HTTPRequest::HTTP_POST) DoPost(Request, Response); return; } catch(const Poco::Exception &E) { Logger_.error(Poco::format("%s: failed with %s",std::string(__func__), E.displayText())); } BadRequest(Request, Response); } void RESTAPI_callback::DoPost(Poco::Net::HTTPServerRequest &Request, Poco::Net::HTTPServerResponse &Response) { try { Poco::JSON::Parser parser; Poco::JSON::Object::Ptr Obj = parser.parse(Request.stream()).extract<Poco::JSON::Object::Ptr>(); Poco::DynamicStruct ds = *Obj; auto Topic = GetParameter(uCentral::RESTAPI::Protocol::TOPIC,""); if(Topic=="ucentralfws") { if(ds.contains(uCentral::RESTAPI::Protocol::FIRMWARES) && ds[uCentral::RESTAPI::Protocol::FIRMWARES].isArray()) { std::cout << "Proper manifest received..." << std::endl; Logger_.information("New manifest..."); OK(Request, Response); return; } else { std::cout << __LINE__ << std::endl; Logger_.information("Bad manifest. JSON does not contain firmwares"); } } else { Logger_.information("Missing topic in callback."); } } catch (const Poco::Exception &E) { Logger_.log(E); } BadRequest(Request, Response); }
29.031746
118
0.703663
[ "object" ]
f307f9cef9f7bb3a54cd304ecd538871c9ac85f0
5,744
cpp
C++
src/tools/editor/src/scene/scene_editor_game_bridge.cpp
chidddy/halley
f828b74a6bbe7f172a7dba84e72429d3163bd61c
[ "Apache-2.0" ]
null
null
null
src/tools/editor/src/scene/scene_editor_game_bridge.cpp
chidddy/halley
f828b74a6bbe7f172a7dba84e72429d3163bd61c
[ "Apache-2.0" ]
null
null
null
src/tools/editor/src/scene/scene_editor_game_bridge.cpp
chidddy/halley
f828b74a6bbe7f172a7dba84e72429d3163bd61c
[ "Apache-2.0" ]
null
null
null
#include "scene_editor_game_bridge.h" #include "scene_editor_gizmo_collection.h" #include "halley/tools/project/project.h" #include "src/project/core_api_wrapper.h" #include "src/ui/project_window.h" using namespace Halley; SceneEditorGameBridge::SceneEditorGameBridge(const HalleyAPI& api, Resources& resources, UIFactory& factory, Project& project, ProjectWindow& projectWindow) : api(api) , resources(resources) , project(project) , projectWindow(projectWindow) , factory(factory) { gizmos = std::make_unique<SceneEditorGizmoCollection>(factory, resources); gameResources = &project.getGameResources(); project.withLoadedDLL([&] (DynamicLibrary& dll) { load(); }); } SceneEditorGameBridge::~SceneEditorGameBridge() { unload(); } bool SceneEditorGameBridge::isLoaded() const { return interfaceReady; } ISceneEditor& SceneEditorGameBridge::getInterface() const { Expects(interface); return *interface; } void SceneEditorGameBridge::update(Time t, SceneEditorInputState inputState, SceneEditorOutputState& outputState) { if (errorState) { unload(); } if (interface) { initializeInterfaceIfNeeded(); if (interfaceReady) { interface->update(t, inputState, outputState); } } } void SceneEditorGameBridge::render(RenderContext& rc) const { if (errorState) { return; } if (interface && interfaceReady) { guardedRun([&]() { interface->render(rc); }); } } void SceneEditorGameBridge::initializeInterfaceIfNeeded() { if (!interface) { project.withLoadedDLL([&] (DynamicLibrary& dll) { load(); }); } if (interface && !interfaceReady) { if (interface->isReadyToCreateWorld()) { guardedRun([&]() { interface->createWorld(factory.getColourScheme()); SceneEditorInputState inputState; SceneEditorOutputState outputState; interface->update(0, inputState, outputState); interfaceReady = true; }, true); } } } SceneEditorGizmoCollection& SceneEditorGameBridge::getGizmos() const { return *gizmos; } void SceneEditorGameBridge::changeZoom(int amount, Vector2f mousePos) { if (interfaceReady) { interface->changeZoom(amount, mousePos); } } void SceneEditorGameBridge::dragCamera(Vector2f pos) { if (interfaceReady) { interface->dragCamera(pos); } } std::shared_ptr<UIWidget> SceneEditorGameBridge::makeCustomUI() const { std::shared_ptr<UIWidget> result; if (interfaceReady) { guardedRun([&] () { result = interface->makeCustomUI(); }); } return result; } void SceneEditorGameBridge::setSelectedEntity(const UUID& uuid, EntityData& data) { if (interfaceReady) { interface->setSelectedEntity(uuid, data); } } void SceneEditorGameBridge::showEntity(const UUID& uuid) { if (interfaceReady) { interface->showEntity(uuid); } } void SceneEditorGameBridge::onEntityAdded(const UUID& uuid, const EntityData& data) { if (interfaceReady) { interface->onEntityAdded(uuid, data); } } void SceneEditorGameBridge::onEntityRemoved(const UUID& uuid) { if (interfaceReady) { interface->onEntityRemoved(uuid); } } void SceneEditorGameBridge::onEntityModified(const UUID& uuid, const EntityData& data) { if (interfaceReady) { interface->onEntityModified(uuid, data); } } void SceneEditorGameBridge::onEntityMoved(const UUID& uuid, const EntityData& data) { if (interfaceReady) { interface->onEntityMoved(uuid, data); } } ConfigNode SceneEditorGameBridge::onToolSet(SceneEditorTool tool, const String& componentName, const String& fieldName, ConfigNode options) { if (interfaceReady) { return interface->onToolSet(tool, componentName, fieldName, std::move(options)); } return options; } void SceneEditorGameBridge::onSceneLoaded(Prefab& scene) { if (interfaceReady) { interface->onSceneLoaded(scene); } } void SceneEditorGameBridge::onSceneSaved() { if (interfaceReady) { interface->onSceneSaved(); } } void SceneEditorGameBridge::setupConsoleCommands(UIDebugConsoleController& controller, ISceneEditorWindow& sceneEditor) { if (interfaceReady) { interface->setupConsoleCommands(controller, sceneEditor); } } bool SceneEditorGameBridge::saveAsset(const Path& path, gsl::span<const gsl::byte> data) { return project.writeAssetToDisk(path, data); } void SceneEditorGameBridge::addTask(std::unique_ptr<Task> task) { projectWindow.addTask(std::move(task)); } void SceneEditorGameBridge::refreshAssets() { if (interfaceReady) { interface->refreshAssets(); } } void SceneEditorGameBridge::load() { guardedRun([&]() { const auto game = project.createGameInstance(api); if (!game) { throw Exception("Unable to load scene editor", HalleyExceptions::Tools); } interface = game->createSceneEditorInterface(); interfaceReady = false; errorState = false; }); if (interface) { gameCoreAPI = std::make_unique<CoreAPIWrapper>(*api.core); gameAPI = api.clone(); gameAPI->replaceCoreAPI(gameCoreAPI.get()); SceneEditorContext context; context.resources = gameResources; context.editorResources = &resources; context.api = gameAPI.get(); context.gizmos = gizmos.get(); context.editorInterface = this; guardedRun([&]() { interface->init(context); }); if (errorState) { unload(); } else { initializeInterfaceIfNeeded(); } } } void SceneEditorGameBridge::unload() { interface.reset(); interfaceReady = false; gameAPI.reset(); gameCoreAPI.reset(); errorState = false; } void SceneEditorGameBridge::guardedRun(const std::function<void()>& f, bool allowFailure) const { try { f(); } catch (const std::exception& e) { Logger::logException(e); if (!allowFailure) { errorState = true; } } catch (...) { Logger::logError("Unknown error in SceneEditorCanvas, probably from game dll"); if (!allowFailure) { errorState = true; } } }
21.040293
156
0.729457
[ "render" ]
f30c6fbb43fc36ee3be4faa8a80184bbc4016296
16,135
cpp
C++
op3_offset_tuner_client/src/main_window.cpp
sm02/ROBOTIS-OP3-Tools
1bc52ecadded573d5990d625260e67c61f719f30
[ "Apache-2.0" ]
1
2019-11-06T14:12:40.000Z
2019-11-06T14:12:40.000Z
op3_offset_tuner_client/src/main_window.cpp
sm02/ROBOTIS-OP3-Tools
1bc52ecadded573d5990d625260e67c61f719f30
[ "Apache-2.0" ]
4
2017-12-13T06:21:23.000Z
2021-03-13T11:00:34.000Z
op3_offset_tuner_client/src/main_window.cpp
sm02/ROBOTIS-OP3-Tools
1bc52ecadded573d5990d625260e67c61f719f30
[ "Apache-2.0" ]
12
2017-09-21T13:59:21.000Z
2021-09-26T11:33:25.000Z
/******************************************************************************* * Copyright 2017 ROBOTIS CO., LTD. * * 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: Kayman Jung */ /***************************************************************************** ** Includes *****************************************************************************/ #include <QtGui> #include <QMessageBox> #include <QCheckBox> #include <iostream> #include "../include/op3_offset_tuner_client/main_window.hpp" /***************************************************************************** ** Namespaces *****************************************************************************/ namespace op3_offset_tuner_client { using namespace Qt; /***************************************************************************** ** Implementation [MainWindow] *****************************************************************************/ MainWindow::MainWindow(int argc, char** argv, QWidget *parent) : QMainWindow(parent), qnode_(argc, argv) { ui_.setupUi(this); // Calling this incidentally connects all ui's triggers to on_...() callbacks in this class. QObject::connect(ui_.actionAbout_Qt, SIGNAL(triggered(bool)), qApp, SLOT(aboutQt())); // qApp is a global variable for the application setWindowIcon(QIcon(":/images/icon.png")); ui_.tab_manager->setCurrentIndex(0); // ensure the first tab is showing - qt-designer should have this already hardwired, but often loses it (settings?). QObject::connect(&qnode_, SIGNAL(rosShutdown()), this, SLOT(close())); all_torque_on_ = false; spinBox_list_.push_back("goal"); spinBox_list_.push_back("offset"); spinBox_list_.push_back("mod"); spinBox_list_.push_back("present"); spinBox_list_.push_back("p_gain"); spinBox_list_.push_back("i_gain"); spinBox_list_.push_back("d_gain"); /**************************** ** Connect ****************************/ qRegisterMetaType<op3_offset_tuner_msgs::JointOffsetPositionData>("op3_offset_tuner_msgs::JointOffsetPositionData"); QObject::connect(&qnode_, SIGNAL(updatePresentJointOffsetData(op3_offset_tuner_msgs::JointOffsetPositionData)), this, SLOT(updateJointOffsetSpinbox(op3_offset_tuner_msgs::JointOffsetPositionData))); /********************* ** Logging **********************/ ui_.view_logging->setModel(qnode_.loggingModel()); QObject::connect(&qnode_, SIGNAL(loggingUpdated()), this, SLOT(updateLoggingView())); /**************************** ** Connect ****************************/ /********************* ** Auto Start **********************/ qnode_.init(); // make ui makeUI(); } MainWindow::~MainWindow() { } /***************************************************************************** ** Implementation [Slots] *****************************************************************************/ void MainWindow::on_save_button_clicked(bool check) { std_msgs::String msg; msg.data = "save"; qnode_.sendCommandMsg(msg); } void MainWindow::on_inipose_button_clicked(bool checck) { std_msgs::String msg; msg.data = "ini_pose"; qnode_.sendCommandMsg(msg); } void MainWindow::on_refresh_button_clicked(bool check) { qnode_.getPresentJointOffsetData(); } void MainWindow::clickedAllTorqueOnButton(QObject *button_group) { all_torque_on_ = true; QButtonGroup* torque_button_group = qobject_cast<QButtonGroup*>(button_group); if (!torque_button_group) // this is just a safety check return; QList<QAbstractButton *> torque_buttons = torque_button_group->buttons(); for (int ix = 0; ix < torque_buttons.size(); ix++) { if (torque_buttons[ix]->isChecked() == false) torque_buttons[ix]->click(); } qnode_.getPresentJointOffsetData(true); all_torque_on_ = false; } void MainWindow::clickedAllTorqueOffButton(QObject *button_group) { QButtonGroup* torque_button_group = qobject_cast<QButtonGroup*>(button_group); if (!torque_button_group) // this is just a safety check return; QList<QAbstractButton *> torque_buttons = torque_button_group->buttons(); for (int ix = 0; ix < torque_buttons.size(); ix++) { if (torque_buttons[ix]->isChecked() == true) torque_buttons[ix]->click(); } } //void MainWindow::checkbox_clicked(QString joint_name) void MainWindow::clickedTorqueCheckbox(QWidget *widget) { QCheckBox* checkBox = qobject_cast<QCheckBox*>(widget); if (!checkBox) // this is just a safety check return; std::string joint_name = checkBox->text().toStdString(); bool is_on = checkBox->isChecked(); QList<QAbstractSpinBox *> spinbox_list = joint_spinbox_map_[joint_name]; for (int ix = 0; ix < spinbox_list.size(); ix++) { spinbox_list[ix]->setEnabled(is_on); } publishTorqueMsgs(joint_name, is_on); } void MainWindow::publishTorqueMsgs(std::string &joint_name, bool torque_on) { op3_offset_tuner_msgs::JointTorqueOnOffArray torque_array_msg; op3_offset_tuner_msgs::JointTorqueOnOff torque_msg; torque_msg.joint_name = joint_name; torque_msg.torque_enable = torque_on; torque_array_msg.torque_enable_data.push_back(torque_msg); qnode_.sendTorqueEnableMsg(torque_array_msg); if (all_torque_on_ == false) qnode_.getPresentJointOffsetData(true); } void MainWindow::changedSpinBoxValue(QString q_joint_name) { if (qnode_.isRefresh() == true) return; op3_offset_tuner_msgs::JointOffsetData msg; std::string joint_name = q_joint_name.toStdString(); QList<QAbstractSpinBox *> spinbox_list = joint_spinbox_map_[joint_name]; QDoubleSpinBox *mod_spinBox; msg.joint_name = joint_name; for (int ix = 0; ix < spinbox_list.size(); ix++) { if (spinbox_list[ix]->whatsThis().toStdString() == "goal") { QDoubleSpinBox* spinBox = qobject_cast<QDoubleSpinBox*>(spinbox_list[ix]); if (!spinBox) // this is just a safety check continue; msg.goal_value = spinBox->value() * M_PI / 180.0; } else if (spinbox_list[ix]->whatsThis().toStdString() == "offset") { QDoubleSpinBox* spinBox = qobject_cast<QDoubleSpinBox*>(spinbox_list[ix]); if (!spinBox) // this is just a safety check continue; msg.offset_value = spinBox->value() * M_PI / 180.0; } else if (spinbox_list[ix]->whatsThis().toStdString() == "mod") { mod_spinBox = qobject_cast<QDoubleSpinBox*>(spinbox_list[ix]); } else if (spinbox_list[ix]->whatsThis().toStdString() == "p_gain") { QSpinBox* spinBox = qobject_cast<QSpinBox*>(spinbox_list[ix]); if (!spinBox) // this is just a safety check continue; msg.p_gain = spinBox->value(); } else if (spinbox_list[ix]->whatsThis().toStdString() == "i_gain") { QSpinBox* spinBox = qobject_cast<QSpinBox*>(spinbox_list[ix]); if (!spinBox) // this is just a safety check continue; msg.i_gain = spinBox->value(); } else if (spinbox_list[ix]->whatsThis().toStdString() == "d_gain") { QSpinBox* spinBox = qobject_cast<QSpinBox*>(spinbox_list[ix]); if (!spinBox) // this is just a safety check continue; msg.d_gain = spinBox->value(); } } if (mod_spinBox) // this is just a safety check mod_spinBox->setValue((msg.goal_value + msg.offset_value) * 180.0 / M_PI); qnode_.sendJointOffsetDataMsg(msg); } void MainWindow::updateJointOffsetSpinbox(op3_offset_tuner_msgs::JointOffsetPositionData msg) { std::string joint_name = msg.joint_name; QList<QAbstractSpinBox *> spinbox_list = joint_spinbox_map_[joint_name]; for (int ix = 0; ix < spinbox_list.size(); ix++) { if (spinbox_list[ix]->whatsThis().toStdString() == "goal") { QDoubleSpinBox* spinBox = qobject_cast<QDoubleSpinBox*>(spinbox_list[ix]); if (!spinBox) // this is just a safety check continue; spinBox->setValue(msg.goal_value * 180.0 / M_PI); } else if (spinbox_list[ix]->whatsThis().toStdString() == "offset") { QDoubleSpinBox* spinBox = qobject_cast<QDoubleSpinBox*>(spinbox_list[ix]); if (!spinBox) // this is just a safety check continue; spinBox->setValue(msg.offset_value * 180.0 / M_PI); } else if (spinbox_list[ix]->whatsThis().toStdString() == "present") { QDoubleSpinBox* spinBox = qobject_cast<QDoubleSpinBox*>(spinbox_list[ix]); if (!spinBox) // this is just a safety check continue; spinBox->setValue(msg.present_value * 180.0 / M_PI); } else if (spinbox_list[ix]->whatsThis().toStdString() == "p_gain") { QSpinBox* spinBox = qobject_cast<QSpinBox*>(spinbox_list[ix]); if (!spinBox) // this is just a safety check continue; spinBox->setValue(msg.p_gain); } else if (spinbox_list[ix]->whatsThis().toStdString() == "i_gain") { QSpinBox* spinBox = qobject_cast<QSpinBox*>(spinbox_list[ix]); if (!spinBox) // this is just a safety check continue; spinBox->setValue(msg.i_gain); } else if (spinbox_list[ix]->whatsThis().toStdString() == "d_gain") { QSpinBox* spinBox = qobject_cast<QSpinBox*>(spinbox_list[ix]); if (!spinBox) // this is just a safety check continue; spinBox->setValue(msg.d_gain); } } } /***************************************************************************** ** Implemenation [Slots][manually connected] *****************************************************************************/ /** * This function is signalled by the underlying model. When the model changes, * this will drop the cursor down to the last line in the QListview to ensure * the user can always see the latest log message. */ void MainWindow::updateLoggingView() { ui_.view_logging->scrollToBottom(); } void MainWindow::makeUI() { makeTabUI(ui_.right_arm_group, ui_.right_arm_torque, right_arm_button_group_, qnode_.right_arm_offset_group_); makeTabUI(ui_.left_arm_group, ui_.left_arm_torque, left_arm_button_group_, qnode_.left_arm_offset_group_); makeTabUI(ui_.leg_group, ui_.leg_torque, legs_button_group_, qnode_.legs_offset_group_); makeTabUI(ui_.body_group, ui_.body_torque, body_button_group_, qnode_.body_offset_group_); } void MainWindow::makeTabUI(QGroupBox *joint_widget, QGroupBox *torque_widget, QButtonGroup *button_group, std::map<int, std::string> &offset_group) { QSignalMapper *torque_checkbox_signalMapper = new QSignalMapper(this); QGridLayout *grid_layout = (QGridLayout *) joint_widget->layout(); QGridLayout *torque_layout = (QGridLayout *) torque_widget->layout(); button_group = new QButtonGroup(); button_group->setExclusive(false); int num_row = 3; int torque_checkbox_index = 0; int torque_row = 1; int torque_col = 0; for (std::map<int, std::string>::iterator map_it = offset_group.begin(); map_it != offset_group.end(); ++map_it) { QSignalMapper *spingox_signalMapper = new QSignalMapper(this); QList<QAbstractSpinBox *> spinbox_list; // spin_box int num_col = 0; int spinbox_size = 1; std::string joint_name = map_it->second; QString q_joint_name = QString::fromStdString(joint_name); // label QLabel *joint_label = new QLabel(q_joint_name); grid_layout->addWidget(joint_label, num_row, num_col++, 1, spinbox_size); // double spin box : goal, offset, mod, present for (int ix = 0; ix < 4; ix++) { QDoubleSpinBox *spin_box = new QDoubleSpinBox(); spin_box->setWhatsThis(tr(spinBox_list_[ix].c_str())); spin_box->setMinimum(-360); spin_box->setMaximum(360); spin_box->setSingleStep(0.05); switch (ix) { case 2: case 3: spin_box->setReadOnly(true); break; default: spingox_signalMapper->setMapping(spin_box, q_joint_name); QObject::connect(spin_box, SIGNAL(valueChanged(QString)), spingox_signalMapper, SLOT(map())); break; } grid_layout->addWidget(spin_box, num_row, num_col++, 1, spinbox_size); spinbox_list.append(spin_box); } // spin box : p gain, i gain, d gain for (int ix = 0; ix < 3; ix++) { QSpinBox *spin_box = new QSpinBox(); spin_box->setWhatsThis(tr(spinBox_list_[ix + 4].c_str())); spin_box->setMinimum(0); spin_box->setMaximum(16000); spin_box->setSingleStep(10); switch (ix) { case 0: spin_box->setValue(640); break; case 1: spin_box->setValue(0); break; case 2: spin_box->setValue(4000); break; default: spin_box->setReadOnly(true); break; } spingox_signalMapper->setMapping(spin_box, q_joint_name); QObject::connect(spin_box, SIGNAL(valueChanged(QString)), spingox_signalMapper, SLOT(map())); grid_layout->addWidget(spin_box, num_row, num_col++, 1, spinbox_size); spinbox_list.append(spin_box); } // spinbox joint_spinbox_map_[joint_name] = spinbox_list; QObject::connect(spingox_signalMapper, SIGNAL(mapped(QString)), this, SLOT(changedSpinBoxValue(QString))); num_row += 1; // torque checkbox torque_row = torque_checkbox_index / 6; torque_col = torque_checkbox_index % 6; QCheckBox *torque_check_box = new QCheckBox(q_joint_name); torque_check_box->setChecked(true); torque_layout->addWidget(torque_check_box, torque_row, torque_col, 1, spinbox_size); button_group->addButton(torque_check_box); torque_checkbox_signalMapper->setMapping(torque_check_box, torque_check_box); QObject::connect(torque_check_box, SIGNAL(clicked()), torque_checkbox_signalMapper, SLOT(map())); torque_checkbox_index += 1; } // all torque on QSignalMapper *torque_on_signalMapper = new QSignalMapper(this); QPushButton *torque_on_button = new QPushButton(tr("All torque ON")); torque_layout->addWidget(torque_on_button, torque_row + 1, 4, 1, 1); torque_on_signalMapper->setMapping(torque_on_button, button_group); QObject::connect(torque_on_button, SIGNAL(clicked()), torque_on_signalMapper, SLOT(map())); QObject::connect(torque_on_signalMapper, SIGNAL(mapped(QObject*)), this, SLOT(clickedAllTorqueOnButton(QObject*))); // all torque off QSignalMapper *torque_off_signalMapper = new QSignalMapper(this); QPushButton *torque_off_button = new QPushButton(tr("All torque OFF")); torque_layout->addWidget(torque_off_button, torque_row + 1, 5, 1, 1); torque_off_signalMapper->setMapping(torque_off_button, button_group); QObject::connect(torque_off_button, SIGNAL(clicked()), torque_off_signalMapper, SLOT(map())); QObject::connect(torque_off_signalMapper, SIGNAL(mapped(QObject*)), this, SLOT(clickedAllTorqueOffButton(QObject*))); QObject::connect(torque_checkbox_signalMapper, SIGNAL(mapped(QWidget*)), this, SLOT(clickedTorqueCheckbox(QWidget*))); } /***************************************************************************** ** Implementation [Menu] *****************************************************************************/ void MainWindow::on_actionAbout_triggered() { QMessageBox::about(this, tr("About ..."), tr("<h2>OP3 Offset Tuner Clinet 0.10</h2><p>Copyright ROBOTIS</p>")); } /***************************************************************************** ** Implementation [Configuration] *****************************************************************************/ void MainWindow::closeEvent(QCloseEvent *event) { QMainWindow::closeEvent(event); } } // namespace op3_offset_tuner_client
32.861507
156
0.634521
[ "model" ]
f311f90e17814a05d082a0df67108f242018bb69
9,438
cxx
C++
Accelerators/Vtkm/Core/vtkmlib/DataSetConverters.cxx
txwhhny/vtk
854d9aa87b944bc9079510515996406b98b86f7c
[ "BSD-3-Clause" ]
2
2021-07-07T22:53:19.000Z
2021-07-31T19:29:35.000Z
Accelerators/Vtkm/Core/vtkmlib/DataSetConverters.cxx
txwhhny/vtk
854d9aa87b944bc9079510515996406b98b86f7c
[ "BSD-3-Clause" ]
2
2020-11-18T16:50:34.000Z
2022-01-21T13:31:47.000Z
Accelerators/Vtkm/Core/vtkmlib/DataSetConverters.cxx
txwhhny/vtk
854d9aa87b944bc9079510515996406b98b86f7c
[ "BSD-3-Clause" ]
5
2020-10-02T10:14:35.000Z
2022-03-10T07:50:22.000Z
//============================================================================= // // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. // // Copyright 2012 Sandia Corporation. // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // //============================================================================= #include "DataSetConverters.h" #include "ArrayConverters.h" #include "CellSetConverters.h" #include "ImageDataConverter.h" #include "PolyDataConverter.h" #include "UnstructuredGridConverter.h" #include "vtkmDataArray.h" #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkCellTypes.h" #include "vtkDataObject.h" #include "vtkDataObjectTypes.h" #include "vtkDataSetAttributes.h" #include "vtkImageData.h" #include "vtkNew.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkRectilinearGrid.h" #include "vtkSmartPointer.h" #include "vtkStructuredGrid.h" #include "vtkUnstructuredGrid.h" #include <vtkm/cont/ArrayHandle.h> #include <vtkm/cont/ArrayHandleCartesianProduct.h> #include <vtkm/cont/ArrayHandleUniformPointCoordinates.h> #include <vtkm/cont/CellSetStructured.h> #include <vtkm/cont/Field.h> namespace tovtkm { namespace { template <typename T> vtkm::cont::CoordinateSystem deduce_container(vtkPoints* points) { typedef vtkm::Vec<T, 3> Vec3; vtkAOSDataArrayTemplate<T>* typedIn = vtkAOSDataArrayTemplate<T>::FastDownCast(points->GetData()); if (typedIn) { auto p = DataArrayToArrayHandle<vtkAOSDataArrayTemplate<T>, 3>::Wrap(typedIn); return vtkm::cont::CoordinateSystem("coords", p); } vtkSOADataArrayTemplate<T>* typedIn2 = vtkSOADataArrayTemplate<T>::FastDownCast(points->GetData()); if (typedIn2) { auto p = DataArrayToArrayHandle<vtkSOADataArrayTemplate<T>, 3>::Wrap(typedIn2); return vtkm::cont::CoordinateSystem("coords", p); } vtkmDataArray<T>* typedIn3 = vtkmDataArray<T>::SafeDownCast(points->GetData()); if (typedIn3) { return vtkm::cont::CoordinateSystem("coords", typedIn3->GetVtkmVariantArrayHandle()); } typedef vtkm::Vec<T, 3> Vec3; Vec3* xyz = nullptr; return vtkm::cont::make_CoordinateSystem("coords", xyz, 0); } } //------------------------------------------------------------------------------ // convert a vtkPoints array into a coordinate system vtkm::cont::CoordinateSystem Convert(vtkPoints* points) { if (points) { if (points->GetDataType() == VTK_FLOAT) { return deduce_container<vtkm::Float32>(points); } else if (points->GetDataType() == VTK_DOUBLE) { return deduce_container<vtkm::Float64>(points); } } // unsupported/null point set typedef vtkm::Vec<vtkm::Float32, 3> Vec3; Vec3* xyz = nullptr; return vtkm::cont::make_CoordinateSystem("coords", xyz, 0); } //------------------------------------------------------------------------------ // convert an structured grid type vtkm::cont::DataSet Convert(vtkStructuredGrid* input, FieldsFlag fields) { const int dimensionality = input->GetDataDimension(); int dims[3]; input->GetDimensions(dims); vtkm::cont::DataSet dataset; // first step convert the points over to an array handle vtkm::cont::CoordinateSystem coords = Convert(input->GetPoints()); dataset.AddCoordinateSystem(coords); // second step is to create structured cellset that represe if (dimensionality == 1) { vtkm::cont::CellSetStructured<1> cells; cells.SetPointDimensions(dims[0]); dataset.SetCellSet(cells); } else if (dimensionality == 2) { vtkm::cont::CellSetStructured<2> cells; cells.SetPointDimensions(vtkm::make_Vec(dims[0], dims[1])); dataset.SetCellSet(cells); } else { // going to presume 3d for everything else vtkm::cont::CellSetStructured<3> cells; cells.SetPointDimensions(vtkm::make_Vec(dims[0], dims[1], dims[2])); dataset.SetCellSet(cells); } ProcessFields(input, dataset, fields); return dataset; } //------------------------------------------------------------------------------ // determine the type and call the proper Convert routine vtkm::cont::DataSet Convert(vtkDataSet* input, FieldsFlag fields) { switch (input->GetDataObjectType()) { case VTK_UNSTRUCTURED_GRID: return Convert(vtkUnstructuredGrid::SafeDownCast(input), fields); case VTK_STRUCTURED_GRID: return Convert(vtkStructuredGrid::SafeDownCast(input), fields); case VTK_UNIFORM_GRID: case VTK_IMAGE_DATA: return Convert(vtkImageData::SafeDownCast(input), fields); case VTK_POLY_DATA: return Convert(vtkPolyData::SafeDownCast(input), fields); case VTK_UNSTRUCTURED_GRID_BASE: case VTK_RECTILINEAR_GRID: case VTK_STRUCTURED_POINTS: default: return vtkm::cont::DataSet(); } } } // namespace tovtkm namespace fromvtkm { namespace { struct ComputeExtents { template <vtkm::IdComponent Dim> void operator()(const vtkm::cont::CellSetStructured<Dim>& cs, const vtkm::Id3& structuredCoordsDims, int extent[6]) const { auto extStart = cs.GetGlobalPointIndexStart(); for (int i = 0, ii = 0; i < 3; ++i) { if (structuredCoordsDims[i] > 1) { extent[2 * i] = vtkm::VecTraits<decltype(extStart)>::GetComponent(extStart, ii++); extent[(2 * i) + 1] = extent[2 * i] + structuredCoordsDims[i] - 1; } else { extent[2 * i] = extent[(2 * i) + 1] = 0; } } } template <vtkm::IdComponent Dim> void operator()(const vtkm::cont::CellSetStructured<Dim>& cs, int extent[6]) const { auto extStart = cs.GetGlobalPointIndexStart(); auto csDim = cs.GetPointDimensions(); for (int i = 0; i < Dim; ++i) { extent[2 * i] = vtkm::VecTraits<decltype(extStart)>::GetComponent(extStart, i); extent[(2 * i) + 1] = extent[2 * i] + vtkm::VecTraits<decltype(csDim)>::GetComponent(csDim, i) - 1; } for (int i = Dim; i < 3; ++i) { extent[2 * i] = extent[(2 * i) + 1] = 0; } } }; } // anonymous namespace void PassAttributesInformation(vtkDataSetAttributes* input, vtkDataSetAttributes* output) { for (int attribType = 0; attribType < vtkDataSetAttributes::NUM_ATTRIBUTES; attribType++) { vtkDataArray* attribute = input->GetAttribute(attribType); if (attribute == nullptr) { continue; } output->SetActiveAttribute(attribute->GetName(), attribType); } } bool Convert(const vtkm::cont::DataSet& vtkmOut, vtkRectilinearGrid* output, vtkDataSet* input) { using ListCellSetStructured = vtkm::List<vtkm::cont::CellSetStructured<1>, vtkm::cont::CellSetStructured<2>, vtkm::cont::CellSetStructured<3>>; auto cellSet = vtkmOut.GetCellSet().ResetCellSetList(ListCellSetStructured{}); using coordType = vtkm::cont::ArrayHandleCartesianProduct<vtkm::cont::ArrayHandle<vtkm::FloatDefault>, vtkm::cont::ArrayHandle<vtkm::FloatDefault>, vtkm::cont::ArrayHandle<vtkm::FloatDefault>>; auto coordsArray = vtkm::cont::Cast<coordType>(vtkmOut.GetCoordinateSystem().GetData()); vtkSmartPointer<vtkDataArray> xArray = Convert(vtkm::cont::make_FieldPoint("xArray", coordsArray.GetStorage().GetFirstArray())); vtkSmartPointer<vtkDataArray> yArray = Convert(vtkm::cont::make_FieldPoint("yArray", coordsArray.GetStorage().GetSecondArray())); vtkSmartPointer<vtkDataArray> zArray = Convert(vtkm::cont::make_FieldPoint("zArray", coordsArray.GetStorage().GetThirdArray())); if (!xArray || !yArray || !zArray) { return false; } vtkm::Id3 dims( xArray->GetNumberOfValues(), yArray->GetNumberOfValues(), zArray->GetNumberOfValues()); int extents[6]; vtkm::cont::CastAndCall(cellSet, ComputeExtents{}, dims, extents); output->SetExtent(extents); output->SetXCoordinates(xArray); output->SetYCoordinates(yArray); output->SetZCoordinates(zArray); // Next we need to convert any extra fields from vtkm over to vtk if (!fromvtkm::ConvertArrays(vtkmOut, output)) { return false; } // Pass information about attributes. PassAttributesInformation(input->GetPointData(), output->GetPointData()); PassAttributesInformation(input->GetCellData(), output->GetCellData()); return true; } bool Convert(const vtkm::cont::DataSet& vtkmOut, vtkStructuredGrid* output, vtkDataSet* input) { using ListCellSetStructured = vtkm::List<vtkm::cont::CellSetStructured<1>, vtkm::cont::CellSetStructured<2>, vtkm::cont::CellSetStructured<3>>; auto cellSet = vtkmOut.GetCellSet().ResetCellSetList(ListCellSetStructured{}); int extents[6]; vtkm::cont::CastAndCall(cellSet, ComputeExtents{}, extents); vtkSmartPointer<vtkPoints> points = Convert(vtkmOut.GetCoordinateSystem()); if (!points) { return false; } output->SetExtent(extents); output->SetPoints(points); // Next we need to convert any extra fields from vtkm over to vtk if (!fromvtkm::ConvertArrays(vtkmOut, output)) { return false; } // Pass information about attributes. PassAttributesInformation(input->GetPointData(), output->GetPointData()); PassAttributesInformation(input->GetCellData(), output->GetCellData()); return true; } } // namespace fromvtkm
30.445161
100
0.677898
[ "3d" ]
f3137272b83358b23def23fa8604b905035d5dc3
2,769
hpp
C++
code/geodb/utility/movable_adapter.hpp
mbeckem/msc
93e71ba163a7ffef4eec3e83934fa793f3f50ff6
[ "MIT" ]
null
null
null
code/geodb/utility/movable_adapter.hpp
mbeckem/msc
93e71ba163a7ffef4eec3e83934fa793f3f50ff6
[ "MIT" ]
null
null
null
code/geodb/utility/movable_adapter.hpp
mbeckem/msc
93e71ba163a7ffef4eec3e83934fa793f3f50ff6
[ "MIT" ]
null
null
null
#ifndef GEODB_UTILITY_MOVABLE_ADAPTER_HPP #define GEODB_UTILITY_MOVABLE_ADAPTER_HPP #include "geodb/common.hpp" #include <tpie/memory.h> #include <type_traits> /// \file /// Wrapper class that makes non-movable objects movable. namespace geodb { template<typename T, typename Enable = void> class movable_adapter; struct in_place_t {}; /// A template class for making an arbitrary type /// move-constructible. /// This is done by wrapping non-movable objects into a unique pointer. /// If the object is already move-constructible, then we will simply /// store the object itself. /// /// The inner object can be accessed using `operator->` or `operator*`. /// /// It is an error to access the inner object after it has been moved. template<typename T, typename Enable> class movable_adapter { public: static constexpr bool wrapped = true; template<typename... Args> movable_adapter(in_place_t, Args&&... args) : m_inner(std::make_unique<T>(std::forward<Args>(args)...)) {} movable_adapter(movable_adapter&& other) noexcept = default; movable_adapter& operator=(movable_adapter&& other) = delete; T& operator*() { check(); return *m_inner; } const T& operator*() const { check(); return *m_inner; } T* operator->() { check(); return m_inner.get(); } const T* operator->() const { check(); return m_inner.get(); } private: void check() const { geodb_assert(m_inner, "instance is in moved from state"); } private: std::unique_ptr<T> m_inner; }; // Specialization for move-constructible types. template<typename T> class movable_adapter<T, std::enable_if_t<std::is_move_constructible<T>::value>> { static_assert(std::is_nothrow_move_constructible<T>::value, "The type must be noexcept-move-constructible"); public: static constexpr bool wrapped = false; template<typename... Args> movable_adapter(in_place_t, Args&&... args) : m_inner(std::forward<Args>(args)...) {} movable_adapter(T&& other) noexcept : m_inner(std::move(other)) {} movable_adapter(movable_adapter&& other) noexcept : m_inner(std::move(other.m_inner)) {} movable_adapter& operator=(movable_adapter&& other) = delete; T& operator*() { return m_inner; } const T& operator*() const { return m_inner; } T* operator->() { return std::addressof(m_inner); } const T* operator->() const { return std::addressof(m_inner); } private: T m_inner; }; /// Factory function for movable adapters. template<typename T, typename... Args> movable_adapter<T> make_movable(Args&&... args) { return movable_adapter<T>(in_place_t(), std::forward<Args>(args)...); } } // namespace geodb #endif // GEODB_UTILITY_MOVABLE_ADAPTER_HPP
28.255102
82
0.685807
[ "object" ]
f317d77686510f875e06c5c905ff0287b7957a8d
15,229
cpp
C++
KBProcessing/OntyxProcessing/exportBtrisOWLProtege/exportBTRISOwlProtege.cpp
NCIEVS/OPS-Native-Utilities
2ca0803ba1aa2ace8047673afe71d4e1f22d826d
[ "BSD-3-Clause" ]
null
null
null
KBProcessing/OntyxProcessing/exportBtrisOWLProtege/exportBTRISOwlProtege.cpp
NCIEVS/OPS-Native-Utilities
2ca0803ba1aa2ace8047673afe71d4e1f22d826d
[ "BSD-3-Clause" ]
null
null
null
KBProcessing/OntyxProcessing/exportBtrisOWLProtege/exportBTRISOwlProtege.cpp
NCIEVS/OPS-Native-Utilities
2ca0803ba1aa2ace8047673afe71d4e1f22d826d
[ "BSD-3-Clause" ]
null
null
null
#include <fstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <set> #include <algorithm> #include <ctime> #include "OntyxKb.h" #include "OntyxProperty.h" using namespace std; string getDayStamp (void); string characterEscape (const string & inString); int main (int argc, char * argv[]) { OntyxKb tdeKb, compareKb; // input/output kb clock_t tstart, tend; vector<string> commLine; for ( int i = 0; i < argc; i++) commLine.push_back(*argv++); if( commLine.size() != 2 ) { cerr << "Error: incorrect number of command line parameters." << endl << "\nUsage:\n\texportOwlProtege tde.xml" << endl << endl << "Requires ancillary header.owl, and headerCode.owl files." << endl; exit(0); } tstart = clock(); tdeKb.readOntyxXMLFile( commLine[1] ); cerr << "Read \"" << commLine[1].c_str() << "\"" << endl; cerr << "TDE file read -----------------------------------------------------------------" << endl; // KB concept iterator, used in all the processing below map<long, OntyxConcept>::iterator posCon; vector<OntyxProperty> propVecDel, propVecAdd; vector<OntyxProperty>::iterator pPropVec; multimap<long, OntyxProperty> conPropMap; multimap<long, OntyxProperty>::iterator pConProp; bool good, hasProp; string newValue; // ************* CONVERT SYNONYMS TO FULLSYNS ************* // ************* Use_Code qualifier is dismissed for( posCon = tdeKb.getFirstConceptIterator(); posCon != tdeKb.getEndConceptIterator(); ++posCon) { good = false; hasProp = false; propVecDel.clear(); propVecAdd.clear(); conPropMap = posCon->second.getProperties(); for( pConProp = conPropMap.begin(); pConProp != conPropMap.end(); ++pConProp) { if( pConProp->second.getName()== "Synonym" ) { hasProp = true; propVecDel.push_back( pConProp->second ); OntyxProperty tmpProp("FULL_SYN", pConProp->second.getValue()); if( pConProp->second.hasQualifier() ) { vector<OntyxQualifier> quals = pConProp->second.getQualifiers(); vector<OntyxQualifier>::const_iterator pQuals = quals.begin(); for( ; pQuals != quals.end(); ++pQuals ) { // dismiss Use_Code if( pQuals->getName() == "Syn_Source" || pQuals->getName() == "Syn_Source_Local_Code" || pQuals->getName() == "Syn_Term_Type" ) { OntyxQualifier qual( pQuals->getName(), pQuals->getValue() ); tmpProp.addQualifier(qual); } } } propVecAdd.push_back(tmpProp); } } if( hasProp ) { pPropVec = propVecDel.begin(); for( ; pPropVec != propVecDel.end(); ++pPropVec ) { posCon->second.deleteProperty( *pPropVec ); } pPropVec = propVecAdd.begin(); for( ; pPropVec != propVecAdd.end(); ++pPropVec ) { posCon->second.addProperty( *pPropVec ); } } // ************* END CONVERT SYNONYMS TO FULLSYNS ************* // ************* posCon ITERATION CONTINUES ******************* // ************* CONVERT LONG_DEFINITION TO DEFINITION ******** // ************* no qualifiers are dismissed good = false; hasProp = false; propVecDel.clear(); propVecAdd.clear(); for( pConProp = conPropMap.begin(); pConProp != conPropMap.end(); ++pConProp) { if( pConProp->second.getName()== "LONG_DEFINITION" ) { hasProp = true; propVecDel.push_back( pConProp->second ); OntyxProperty tmpProp("DEFINITION", pConProp->second.getValue()); if( pConProp->second.hasQualifier() ) { vector<OntyxQualifier> quals = pConProp->second.getQualifiers(); vector<OntyxQualifier>::const_iterator pQuals = quals.begin(); for( ; pQuals != quals.end(); ++pQuals ) { // no qualifiers dismissed, add all OntyxQualifier qual( pQuals->getName(), pQuals->getValue() ); tmpProp.addQualifier(qual); } } propVecAdd.push_back(tmpProp); } } if( hasProp ) { pPropVec = propVecDel.begin(); for( ; pPropVec != propVecDel.end(); ++pPropVec ) { posCon->second.deleteProperty( *pPropVec ); } pPropVec = propVecAdd.begin(); for( ; pPropVec != propVecAdd.end(); ++pPropVec ) { posCon->second.addProperty( *pPropVec ); } } // ************* END CONVERT LONG_DEFINITION TO DEFINITION **** // ************* posCon ITERATION CONTINUES ******************* // ************* PROCESS DEFINITION AND ALT_DEFINITION ******** // ************* syn_term_type is dismissed // ************* syn_source is converted to def-source good = false; hasProp = false; propVecDel.clear(); propVecAdd.clear(); newValue = ""; for( pConProp = conPropMap.begin(); pConProp != conPropMap.end(); ++pConProp) { if( pConProp->second.getName()== "DEFINITION" || pConProp->second.getName()== "ALT_DEFINITION") { if( pConProp->second.hasQualifier() ) { // don't process ncit definitions hasProp = true; propVecDel.push_back( pConProp->second ); // will need to delete the qualified value newValue = "<def-definition>" + characterEscape(pConProp->second.getValue()) + "</def-definition>"; vector<OntyxQualifier> quals = pConProp->second.getQualifiers(); vector<OntyxQualifier>::const_iterator pQuals = quals.begin(); for( ; pQuals != quals.end(); ++pQuals ) { // syn_term_type is dismissed, the rest are added if( pQuals->getName() == "Definition_Source" || pQuals->getName() == "Syn_Source" ) newValue = newValue + "<def-source>" + characterEscape(pQuals->getValue()) + "</def-source>"; else if( pQuals->getName() == "Definition_Attribution" ) newValue = newValue + "<attr>" + characterEscape(pQuals->getValue()) + "</attr>"; } OntyxProperty tmpProp( pConProp->second.getName(), newValue ); propVecAdd.push_back(tmpProp); } else if( pConProp->second.getValue().find("def-source") == string::npos) { // doesn't have microsyntax either hasProp = true; propVecDel.push_back( pConProp->second ); newValue = "<def-definition>" + characterEscape(pConProp->second.getValue()) + "</def-definition>>"; newValue = newValue + "<def-source>RED</def-source>"; OntyxProperty tmpProp( pConProp->second.getName(), newValue ); propVecAdd.push_back(tmpProp); } } } if( hasProp ) { pPropVec = propVecDel.begin(); for( ; pPropVec != propVecDel.end(); ++pPropVec ) { posCon->second.deleteProperty( *pPropVec ); } pPropVec = propVecAdd.begin(); for( ; pPropVec != propVecAdd.end(); ++pPropVec ) { posCon->second.addProperty( *pPropVec ); } } // ************* END PROCESS DEFINITION AND ALT_DEFINITION **** // ************* posCon ITERATION CONTINUES ******************* // ************* PROCESS FULL_SYN ***************************** // ************* convert or pass-thru, listing elsewhere (but can be read from code below) // ************* good = false; hasProp = false; propVecDel.clear(); propVecAdd.clear(); newValue = ""; for( pConProp = conPropMap.begin(); pConProp != conPropMap.end(); ++pConProp) { if( pConProp->second.getName()== "FULL_SYN" ) { if( pConProp->second.hasQualifier() ) { // don't process ncit-derived full_syns hasProp = true; propVecDel.push_back( pConProp->second ); // will need to delete the qualified value newValue = "<term-name>" + characterEscape(pConProp->second.getValue()) + "</term-name>"; vector<OntyxQualifier> quals = pConProp->second.getQualifiers(); vector<OntyxQualifier>::const_iterator pQuals = quals.begin(); for( ; pQuals != quals.end(); ++pQuals ) { if( pQuals->getName() == "Syn_Abbreviation" ) newValue = newValue + "<term-name>" + characterEscape(pQuals->getValue()) + "</term-name>"; else if( pQuals->getName() == "Syn_Source" || pQuals->getName() == "Definition_Source" ) newValue = newValue + "<term-source>" + characterEscape(pQuals->getValue()) + "</term-source>"; else if( pQuals->getName() == "Syn_Source_Local_Code" || pQuals->getName() == "Syn_Source_Second_ID" ) newValue = newValue + "<source-code>" + characterEscape(pQuals->getValue()) + "</source-code>"; else if( pQuals->getName() == "Syn_Term_Type" ) newValue = newValue + "<term-group>" + characterEscape(pQuals->getValue()) + "</term-group>"; else newValue = newValue + "<" + pQuals->getName() + ">" + characterEscape(pQuals->getValue()) + "</" + pQuals->getName() + ">"; } OntyxProperty tmpProp( pConProp->second.getName(), newValue ); propVecAdd.push_back(tmpProp); } else if( pConProp->second.getValue().find("term-name") == string::npos ) { // it doesn't have microsyntax either hasProp = true; propVecDel.push_back( pConProp->second ); newValue = "<term-name>" + characterEscape(pConProp->second.getValue()) + "</term-name>"; newValue = newValue + "<term-source>RED</term-source><term-group>SY</term-group>"; OntyxProperty tmpProp( pConProp->second.getName(), newValue ); propVecAdd.push_back(tmpProp); } } } if( hasProp ) { pPropVec = propVecDel.begin(); for( ; pPropVec != propVecDel.end(); ++pPropVec ) { posCon->second.deleteProperty( *pPropVec ); } pPropVec = propVecAdd.begin(); for( ; pPropVec != propVecAdd.end(); ++pPropVec ) { posCon->second.addProperty( *pPropVec ); } } // ************* END PROCESS FULL_SYN ************************* // ************* posCon ITERATION CONTINUES ******************* // ************* PROCESS Reference_Source AND Lab_Test_Status // ************* dismiss Use_Code good = false; hasProp = false; propVecDel.clear(); propVecAdd.clear(); newValue = ""; for( pConProp = conPropMap.begin(); pConProp != conPropMap.end(); ++pConProp) { if( pConProp->second.getName()== "Reference_Source" || pConProp->second.getName()== "Lab_Test_Status" ) { hasProp = true; propVecDel.push_back( pConProp->second ); // will need to delete the qualified value if( pConProp->second.getName()== "Reference_Source" ) newValue = "<rs-value>" + characterEscape(pConProp->second.getValue()) + "</rs-value>"; else newValue = "<lts-value>" + characterEscape(pConProp->second.getValue()) + "</lts-value>"; if( pConProp->second.hasQualifier() ) { vector<OntyxQualifier> quals = pConProp->second.getQualifiers(); vector<OntyxQualifier>::const_iterator pQuals = quals.begin(); for( ; pQuals != quals.end(); ++pQuals ) { if( pQuals->getName() != "Use_Code" ) newValue = newValue + "<" + pQuals->getName() + ">" + characterEscape(pQuals->getValue()) + "</" + pQuals->getName() + ">"; } } OntyxProperty tmpProp( pConProp->second.getName(), newValue ); propVecAdd.push_back(tmpProp); } } if( hasProp ) { pPropVec = propVecDel.begin(); for( ; pPropVec != propVecDel.end(); ++pPropVec ) { posCon->second.deleteProperty( *pPropVec ); } pPropVec = propVecAdd.begin(); for( ; pPropVec != propVecAdd.end(); ++pPropVec ) { posCon->second.addProperty( *pPropVec ); } } // ************* END PROCESS Reference_Source AND Lab_Test_Status // ************* posCon ITERATION CONTINUES ******************* // ************* PROCESS Contributing_Source_Local_Code // ************* convert Syn_Source to Use_Source good = false; hasProp = false; propVecDel.clear(); propVecAdd.clear(); newValue = ""; for( pConProp = conPropMap.begin(); pConProp != conPropMap.end(); ++pConProp) { if( pConProp->second.getName()== "Contributing_Source_Local_Code" ) { hasProp = true; propVecDel.push_back( pConProp->second ); // will need to delete the qualified value newValue = "<cslc-value>" + characterEscape(pConProp->second.getValue()) + "</cslc-value>"; if( pConProp->second.hasQualifier() ) { vector<OntyxQualifier> quals = pConProp->second.getQualifiers(); vector<OntyxQualifier>::const_iterator pQuals = quals.begin(); for( ; pQuals != quals.end(); ++pQuals ) { if( pQuals->getName() != "Syn_Source" ) newValue = newValue + "<Use_Source>" + characterEscape(pQuals->getValue()) + "</Use_Source>"; else newValue = newValue + "<" + pQuals->getName() + ">" + characterEscape(pQuals->getValue()) + "</" + pQuals->getName() + ">"; } } OntyxProperty tmpProp( pConProp->second.getName(), newValue ); propVecAdd.push_back(tmpProp); } } if( hasProp ) { pPropVec = propVecDel.begin(); for( ; pPropVec != propVecDel.end(); ++pPropVec ) { posCon->second.deleteProperty( *pPropVec ); } pPropVec = propVecAdd.begin(); for( ; pPropVec != propVecAdd.end(); ++pPropVec ) { posCon->second.addProperty( *pPropVec ); } } // ************* END PROCESS Contributing_Source_Local_Code } // ************* END posCon ITERATION string filename; string daystamp = getDayStamp(); // ************* WRITE BY NAME OWL FILE ************* filename = "Red-" + daystamp + ".owl"; cerr << "Writing output OWL file '" << filename << "', properties with role names are not exported." << endl; tdeKb.writeOWLFileByName (filename, "header.owl", true); // if noProps is true, properties with names derived from roles are not exported // ************* END WRITE OWL FILE ************* /* // ************* WRITE BY CODE OWL FILE ************* filename = "Thesaurus-ByCode-" + daystamp + ".owl"; cerr << "Writing output OWL file '" << filename << "', properties with role names are not exported." << endl; tdeKb.writeOWLFile (filename, "headerCode.owl", true); // if noProps is true, properties with names derived from roles are not exported // ************* END WRITE OWL FILE ************* */ tend = clock(); cerr << "Execution took " << (tend-tstart)/1000.0 << " seconds" << endl; return 0; } string getDayStamp (void) { char sumFile[10] = {0}; struct tm when; time_t now; char *p; char tempS[20] = {0}, monS[3] = {0}, dayS[3] = {0}, yearS[5] = {0}; time( &now ); when = *localtime( &now ); sprintf (yearS, "%d", when.tm_year); // years since 1900 if (strlen(yearS) > 2) { // use only last two digits of year p = &yearS[strlen(yearS)-2]; strcpy(tempS, p); strcpy(yearS, tempS); } sprintf (monS, "%d", when.tm_mon + 1); sprintf (dayS, "%d", when.tm_mday); if (strlen(monS) == 1) { // use month with two digits strcpy(tempS, "0"); strcat(tempS, monS); strcpy(monS, tempS); } if (strlen(dayS) == 1) { // use days with two digits strcpy(tempS, "0"); strcat(tempS, dayS); strcpy(dayS, tempS); } strcat(sumFile, yearS); strcat(sumFile, monS); strcat(sumFile, dayS); string stamp = sumFile; return stamp; } string characterEscape (const string & inString) { string searVec[] = { "&", "<" }; string repVec[] = { "&amp;", "&lt;" }; unsigned pos; // startPos, endPos, unsigned i; string tmpString = inString; if( tmpString.find_first_of("<&",0) != string::npos ) { for( i = 0; i < sizeof(searVec)/sizeof(string); i++ ) { pos = 0; while ( (pos = tmpString.find(searVec[i], pos)) != string::npos ) { tmpString = tmpString.replace(pos++, searVec[i].size(), repVec[i]); ++pos; } } } return tmpString; }
34.84897
130
0.608773
[ "vector" ]
f31972a63723b5223d4ed399b5946ff7f1e76ca8
1,215
hpp
C++
includes/space.hpp
xetqL/liblj
6ae643a192cd4711efb34889ff147bb17ce97a0e
[ "Unlicense" ]
null
null
null
includes/space.hpp
xetqL/liblj
6ae643a192cd4711efb34889ff147bb17ce97a0e
[ "Unlicense" ]
null
null
null
includes/space.hpp
xetqL/liblj
6ae643a192cd4711efb34889ff147bb17ce97a0e
[ "Unlicense" ]
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: space.hpp * Author: xetql * * Created on April 23, 2017, 3:53 PM */ #ifndef SPACE_HPP #define SPACE_HPP #include <memory> #include <vector> #include "atomic_cells.hpp" namespace liblj { //const double C = 0.034; const double SIG = 1e-2; const double RCUT = (2.5*SIG); class space_t { std::vector<atomic_cell_t> borders; std::vector<atomic_cell_t> cells; //also includes bordering cells public: space_t() {} void add_cell(atomic_cell_t c) { if (c.is_bordering_cell) borders.push_back(c); cells.push_back(c); } /** * Checks if a work unit interacts outside of this space * @param wu * @return */ bool is_interacting_outside(work_unit_t wu) { for (atomic_cell_t border_cell : borders) { if(border_cell.distance2(wu) < std::pow(RCUT, 2)) return true; } return false; } }; } #endif /* SPACE_HPP */
22.090909
79
0.588477
[ "vector" ]
f32172b507b1e89e3ddf28cffdca29fa89e8004b
10,640
hpp
C++
PATCH/mkldnn_patch/include/patch_mkldnn.hpp
rfsaliev/light-model-transformer
550a357db8f0c6765328cd42d312fa1be62eae91
[ "Apache-2.0" ]
67
2018-08-13T02:57:35.000Z
2021-09-20T05:47:46.000Z
PATCH/mkldnn_patch/include/patch_mkldnn.hpp
Mengjintao/light-model-transformer
9e0c7d5c3ec4042d30e6d8ee67a9c856837573c8
[ "Apache-2.0" ]
3
2018-08-14T05:54:10.000Z
2019-09-06T20:50:02.000Z
PATCH/mkldnn_patch/include/patch_mkldnn.hpp
Mengjintao/light-model-transformer
9e0c7d5c3ec4042d30e6d8ee67a9c856837573c8
[ "Apache-2.0" ]
18
2018-08-13T03:02:00.000Z
2021-12-10T01:57:28.000Z
/******************************************************************************* * Copyright 2018 Intel Corporation * * 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. *******************************************************************************/ #ifndef PATCH_MKLDNN_HPP #define PATCH_MKLDNN_HPP #ifndef DOXYGEN_SHOULD_SKIP_THIS #include <stdlib.h> #include <memory> #include <vector> #include <algorithm> #include <iterator> #include <string> #include "mkldnn.h" #include "mkldnn.hpp" #include "patch_mkldnn.h" #endif namespace mkldnn { /// Base class for all computational primitives. class patch_primitive: public primitive { public: /// A proxy to C primitive kind enum enum class kind { extract_image_patches = mkldnn_extract_image_patches, resize_bilinear = mkldnn_resize_bilinear, }; }; enum patch_query { extract_image_patches_d = mkldnn_query_extract_image_patches_d, resize_bilinear_d = mkldnn_query_resize_bilinear_d, }; /// @addtogroup cpp_api_memory Memory /// A primitive to describe data. /// /// @addtogroup cpp_api_extract_image_patches extract_image_patches /// A primitive to perform extract_image_patches. /// /// @sa @ref c_api_extract_image_patches in @ref c_api /// @{ struct extract_image_patches_forward : public patch_primitive { struct desc { mkldnn_extract_image_patches_desc_t data; desc(prop_kind aprop_kind, const memory::desc &src_desc, const memory::desc &dst_desc, const memory::dims strides, const memory::dims kernel, const memory::dims padding_l, const memory::dims padding_r, const int rate_h, const int rate_w, const padding_kind apadding_kind) { memory::validate_dims(strides); memory::validate_dims(kernel); memory::validate_dims(padding_l); memory::validate_dims(padding_r); error::wrap_c_api(mkldnn_extract_image_patches_forward_desc_init(&data, mkldnn::convert_to_c(aprop_kind), &src_desc.data, &dst_desc.data, &strides[0], &kernel[0], &padding_l[0], &padding_r[0], &rate_h, &rate_w, mkldnn::convert_to_c(apadding_kind)), "could not init a forward extract_image_patches descriptor"); } }; struct primitive_desc : public handle<mkldnn_primitive_desc_t> { primitive_desc(const desc &adesc, const engine &aengine) { mkldnn_primitive_desc_t result; error::wrap_c_api(mkldnn_primitive_desc_create( &result, &adesc.data, aengine.get(), nullptr), "could not create a forward extract_image_patches primitive descriptor"); reset(result); } memory::primitive_desc workspace_primitive_desc() const { memory::primitive_desc adesc; mkldnn_primitive_desc_t cdesc; const_mkldnn_primitive_desc_t const_cdesc = mkldnn_primitive_desc_query_pd(get(), mkldnn::convert_to_c(workspace_pd), 0); error::wrap_c_api(mkldnn_primitive_desc_clone(&cdesc, const_cdesc), "could not clone a workspace primititve descriptor"); adesc.reset(cdesc); return adesc; } memory::primitive_desc dst_primitive_desc() const { memory::primitive_desc adesc; mkldnn_primitive_desc_t cdesc; const_mkldnn_primitive_desc_t const_cdesc = mkldnn_primitive_desc_query_pd(get(), mkldnn::convert_to_c(dst_pd), 0); error::wrap_c_api(mkldnn_primitive_desc_clone(&cdesc, const_cdesc), "could not clone a dst primitive descriptor"); adesc.reset(cdesc); return adesc; } memory::primitive_desc src_primitive_desc() const { memory::primitive_desc adesc; mkldnn_primitive_desc_t cdesc; const_mkldnn_primitive_desc_t const_cdesc = mkldnn_primitive_desc_query_pd(get(), mkldnn::convert_to_c(src_pd), 0); error::wrap_c_api(mkldnn_primitive_desc_clone(&cdesc, const_cdesc), "could not clone a src primitive descriptor"); adesc.reset(cdesc); return adesc; } engine get_engine() { return engine::query(*this); } }; extract_image_patches_forward(const primitive_desc &aprimitive_desc, const primitive::at &src, const memory &dst) { mkldnn_primitive_t result; mkldnn_primitive_at_t inputs[] = { src.data }; const_mkldnn_primitive_t outputs[] = { dst.get(), nullptr }; check_num_parameters(aprimitive_desc.get(), 1, 1, "extract_image_patches forward"); error::wrap_c_api(mkldnn_primitive_create(&result, aprimitive_desc.get(), inputs, outputs), "could not create a extract_image_patches forward primitive"); reset(result); } extract_image_patches_forward(const primitive_desc &aprimitive_desc, const primitive::at &src, const memory &dst, const memory &workspace) { mkldnn_primitive_t result; mkldnn_primitive_at_t inputs[] = { src.data }; const_mkldnn_primitive_t outputs[] = { dst.get(), workspace.get() }; check_num_parameters(aprimitive_desc.get(), 1, 2, "extract_image_patches forward"); error::wrap_c_api(mkldnn_primitive_create(&result, aprimitive_desc.get(), inputs, outputs), "could not create a extract_image_patches forward primitive"); reset(result); } }; /// @} /// @addtogroup cpp_api_memory Memory /// A primitive to describe data. /// /// @addtogroup cpp_api_resize_bilinear resize_bilinear /// A primitive to perform resize_bilinear. /// /// @sa @ref c_api_resize_bilinear in @ref c_api /// @{ struct resize_bilinear_forward : public patch_primitive { struct desc { mkldnn_resize_bilinear_desc_t data; desc(prop_kind aprop_kind, const memory::desc &src_desc, const memory::desc &dst_desc, const int align_corners) { error::wrap_c_api(mkldnn_resize_bilinear_forward_desc_init(&data, mkldnn::convert_to_c(aprop_kind), &src_desc.data, &dst_desc.data, &align_corners), "could not init a forward resize_bilinear descriptor"); } }; struct primitive_desc : public handle<mkldnn_primitive_desc_t> { primitive_desc(const desc &adesc, const engine &aengine) { mkldnn_primitive_desc_t result; error::wrap_c_api(mkldnn_primitive_desc_create( &result, &adesc.data, aengine.get(), nullptr), "could not create a forward resize_bilinear primitive descriptor"); reset(result); } memory::primitive_desc workspace_primitive_desc() const { memory::primitive_desc adesc; mkldnn_primitive_desc_t cdesc; const_mkldnn_primitive_desc_t const_cdesc = mkldnn_primitive_desc_query_pd(get(), mkldnn::convert_to_c(workspace_pd), 0); error::wrap_c_api(mkldnn_primitive_desc_clone(&cdesc, const_cdesc), "could not clone a workspace primititve descriptor"); adesc.reset(cdesc); return adesc; } memory::primitive_desc dst_primitive_desc() const { memory::primitive_desc adesc; mkldnn_primitive_desc_t cdesc; const_mkldnn_primitive_desc_t const_cdesc = mkldnn_primitive_desc_query_pd(get(), mkldnn::convert_to_c(dst_pd), 0); error::wrap_c_api(mkldnn_primitive_desc_clone(&cdesc, const_cdesc), "could not clone a dst primitive descriptor"); adesc.reset(cdesc); return adesc; } memory::primitive_desc src_primitive_desc() const { memory::primitive_desc adesc; mkldnn_primitive_desc_t cdesc; const_mkldnn_primitive_desc_t const_cdesc = mkldnn_primitive_desc_query_pd(get(), mkldnn::convert_to_c(src_pd), 0); error::wrap_c_api(mkldnn_primitive_desc_clone(&cdesc, const_cdesc), "could not clone a src primitive descriptor"); adesc.reset(cdesc); return adesc; } engine get_engine() { return engine::query(*this); } }; resize_bilinear_forward(const primitive_desc &aprimitive_desc, const primitive::at &src, const memory &dst) { mkldnn_primitive_t result; mkldnn_primitive_at_t inputs[] = { src.data }; const_mkldnn_primitive_t outputs[] = { dst.get(), nullptr }; check_num_parameters(aprimitive_desc.get(), 1, 1, "resize_bilinear forward"); error::wrap_c_api(mkldnn_primitive_create(&result, aprimitive_desc.get(), inputs, outputs), "could not create a resize_bilinear forward primitive"); reset(result); } resize_bilinear_forward(const primitive_desc &aprimitive_desc, const primitive::at &src, const memory &dst, const memory &workspace) { mkldnn_primitive_t result; mkldnn_primitive_at_t inputs[] = { src.data }; const_mkldnn_primitive_t outputs[] = { dst.get(), workspace.get() }; check_num_parameters(aprimitive_desc.get(), 1, 2, "resize_bilinear forward"); error::wrap_c_api(mkldnn_primitive_create(&result, aprimitive_desc.get(), inputs, outputs), "could not create a resize_bilinear forward primitive"); reset(result); } }; /// @} /// @} C++ API } // namespace mkldnn #endif
40.150943
98
0.619737
[ "vector" ]
f32571864fc48ec5ce4db3528b75e65dc3fb7b0e
3,249
cpp
C++
codeforces/DivC/PairOfTopics/main.cpp
jeevanpuchakay/a2oj
f867e9b2ced6619be3ca6b1a1a1838107322782d
[ "MIT" ]
null
null
null
codeforces/DivC/PairOfTopics/main.cpp
jeevanpuchakay/a2oj
f867e9b2ced6619be3ca6b1a1a1838107322782d
[ "MIT" ]
null
null
null
codeforces/DivC/PairOfTopics/main.cpp
jeevanpuchakay/a2oj
f867e9b2ced6619be3ca6b1a1a1838107322782d
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long double ld; typedef long long int ll; #define endl "\n" vector<vector<ll>> adjlist; ll max(ll x, ll y) { return (x > y) ? x : y; } ll min(ll x, ll y) { return (x > y) ? y : x; } #define mod 1000000007 #define precision(precision) cout << fixed << setprecision(precision) #define printTestCaseNum(x) cout << "Case #" << x << ": " ll cases = 1, n, sum, m; ll x, y; ll countInversions(ll startPos, ll endPos, vector<ll> &interestDiff) { ll mid = startPos + (endPos - startPos) / 2, ans = 0; if ((endPos - startPos + 1) <= 1) { return 0; } else if ((endPos - startPos + 1) <= 2) { if (-interestDiff[startPos] < interestDiff[endPos]) { ans++; } if (interestDiff[startPos] > interestDiff[endPos]) { swap(interestDiff[startPos], interestDiff[endPos]); } return ans; } ans = countInversions(startPos, mid, interestDiff) + countInversions(mid + 1, endPos, interestDiff); ll start1 = startPos, start2 = mid + 1, pos; ll tempArr[endPos - startPos + 1]; while (start1 <= mid) { /* code */ // for (ll j = mid + 1; j <= endPos; j++) // { // if (-interestDiff[start1] < interestDiff[j]) // { // ans += (endPos - j + 1); // break; // } // } ll left = mid + 1, right = endPos, curr, possible = -1; while (left <= right) { curr = left + (right - left) / 2; if (-interestDiff[start1] < interestDiff[curr]) { possible = curr; right = curr - 1; } else { left = curr + 1; } } if (possible != -1) { ans += (endPos - possible + 1); } start1++; } start1 = startPos, start2 = mid + 1, pos = 0; while (start1 <= mid && start2 <= endPos) { /* code */ if (interestDiff[start1] < interestDiff[start2]) { tempArr[pos++] = interestDiff[start1++]; } else { tempArr[pos++] = interestDiff[start2++]; } } while (start1 <= mid) { tempArr[pos++] = interestDiff[start1++]; } while (start2 <= endPos) { /* code */ tempArr[pos++] = interestDiff[start2++]; } pos = 0, start1 = startPos; while (start1 <= endPos) { interestDiff[start1++] = tempArr[pos++]; } return ans; } void solveCase(ll testCaseNum) { cin >> n; vector<ll> teachersInterest(n), studentsInterest(n), interestDiff(n); for (ll i = 0; i < n; i++) cin >> teachersInterest[i]; for (ll i = 0; i < n; i++) cin >> studentsInterest[i]; ll ans = 0; for (ll i = 0; i < n; i++) { interestDiff[i] = teachersInterest[i] - studentsInterest[i]; } ans = countInversions(0, n - 1, interestDiff); cout << ans << endl; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); // cin >> cases; for (ll t = 1; t <= cases; t++) { solveCase(t); } return 0; }
25.582677
104
0.485996
[ "vector" ]
f3258a6b144eb3f113cbf115e8f856386eb51b22
8,014
cpp
C++
src/moderate.cpp
lkeegan/CTCI
1f15dabaf85aaa6d2f8bd21b5451d55173cf8ad4
[ "MIT" ]
1
2018-10-09T03:52:16.000Z
2018-10-09T03:52:16.000Z
src/moderate.cpp
lkeegan/CTCI
1f15dabaf85aaa6d2f8bd21b5451d55173cf8ad4
[ "MIT" ]
null
null
null
src/moderate.cpp
lkeegan/CTCI
1f15dabaf85aaa6d2f8bd21b5451d55173cf8ad4
[ "MIT" ]
null
null
null
#include "moderate.hpp" namespace ctci { namespace moderate { int word_frequency(const std::string& word, const std::string& book, const std::string& delims) { int count = 0; std::size_t next = -1; do { std::size_t curr = next + 1; next = book.find_first_of(delims, curr); if (book.substr(curr, next - curr) == word) { ++count; } } while (next != std::string::npos); return count; } std::unordered_map<std::string, int> word_frequency_map( const std::string& book, const std::string& delims) { std::unordered_map<std::string, int> counts; std::size_t next = -1; do { std::size_t curr = next + 1; next = book.find_first_of(delims, curr); ++counts[book.substr(curr, next - curr)]; } while (next != std::string::npos); return counts; } bool MyIntersection::intersect(const line& a, const line& b, point* intersection_point) { // want to find x such that // a_0 + a_1 x = b_0 + b_1 x double a1 = (a.end.y - a.start.y) / (a.end.x - a.start.x); double a0 = a.start.y - a1 * a.start.x; double b1 = (b.end.y - b.start.y) / (b.end.x - b.start.x); double b0 = b.start.y - b1 * b.start.x; double x = (b0 - a0) / (a1 - b1); // check that x lies between start and end x points for both lines // NB allows for case that "start.x" > "end.x" bool a_in_range = (((x >= a.start.x) && (x <= a.end.x)) || ((x >= a.end.x) && (x <= a.start.x))); bool b_in_range = (((x >= b.start.x) && (x <= b.end.x)) || ((x >= b.end.x) && (x <= b.start.x))); if (a_in_range && b_in_range) { // optionally write location to intersection_point if (intersection_point) { intersection_point->x = x; intersection_point->y = a0 + a1 * x; } return true; } return false; } unsigned int factorial_trailing_zeros(unsigned int n) { unsigned long long sig_digits = 1; unsigned int zeros = 0; for (unsigned int i = 1; i <= n; ++i) { unsigned long long old_sig_digits = sig_digits; sig_digits *= i; // if multiplying by i results in a smaller // unsigned long integer, then we have overflow if (sig_digits < old_sig_digits) { throw std::overflow_error("integer overflow in factorial_trailing_zeros"); } // remove and count trailing 0's while ((sig_digits % 10) == 0) { sig_digits /= 10; ++zeros; } } return zeros; } int smallest_difference(std::vector<int> a, const std::vector<int>& b) { // brute force: O(n_a n_b) check all pairs - requires no extra storage // this implementation: // -sort array a: O(n_a log(n_a)) // -for each value in b, find the closest not-smaller-than-it // value in a and compare resulting difference: O(n_b log(n_a)) // -overall: O((n_a + n_b) log(n_a)) // -plus O(n_a) storage for sorted copy of a int min_diff = std::numeric_limits<int>::max(); std::sort(a.begin(), a.end()); for (int b_val : b) { auto a_gtr_than_b = std::lower_bound(a.begin(), a.end(), b_val); if (a_gtr_than_b != a.end()) { min_diff = std::min(min_diff, *a_gtr_than_b - b_val); } } return min_diff; } std::string english_int(unsigned long long int number) { std::array<std::string, 20> digits{ "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; std::array<std::string, 10> tens{"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; // assuming ULL int can go up to 2^64-1 < 10^20 // can safely express any number in this range with // powers of 1000 up to 7, i.e. 10^21 == Sextillion: // https://simple.wikipedia.org/wiki/Names_for_large_numbers std::array<std::string, 8> thousand_to_nth_power{ "", " Thousand", " Million", " Billion", " Trillion", " Quadrillion", " Quintillion", " Sextillion"}; auto str_thousand_power = thousand_to_nth_power.begin(); std::string int_as_text; while (number > 0) { if (int_as_text.size() > 0) { // add space between previous part and new part int_as_text = " " + int_as_text; } // text for 3rd least significant digit (hundreds) std::string str_ls3; int ls3 = (number % 1000) / 100; int ls2 = number % 100; if (ls3 > 0) { str_ls3 = digits[ls3] + " Hundred"; if (ls2 > 0) { // if there is more to come, add a space str_ls3 += " "; } } // text for two least significant digits (0-99) if (ls2 < 20) { // 1-19 str_ls3 += digits[ls2]; } else { // 20-99 str_ls3 += tens[ls2 / 10]; if (ls2 % 10 > 0) { str_ls3 += " " + digits[ls2 % 10]; } } // add text from these 3 digits to result if (str_ls3.size() > 0) { int_as_text = str_ls3 + *str_thousand_power + int_as_text; } // remove last 3 digits from number number /= 1000; // increment 10^3 factor ++str_thousand_power; } return int_as_text; } // a - b int operations_minus(int a, int b) { if (a < b) { return -operations_minus(b, a); } int result = 0; while (a > b) { ++b; ++result; } return result; } // a * b int operations_multiply(int a, int b) { // if a, b have opposite sign, result will be negative bool result_neg = ((a < 0) != (b < 0)); // multiply abs(a) and abs(b) int result = 0; for (int i = 0; i < abs(b); ++i) { result += abs(a); } // return result with correct sign return result_neg ? -result : result; } // a / b int operations_divide(int a, int b) { // if a, b have opposite sign, result will be negative bool result_neg = ((a < 0) != (b < 0)); int result = 0; int mult = abs(b); // do abs(a) / abs(b) while (mult <= abs(a)) { ++result; mult += abs(b); } // return result with correct sign return result_neg ? -result : result; } int year_with_most_people( const std::vector<std::pair<int, int>>& birth_death_years) { // O(n) for n people constexpr int MIN_YEAR = 1900; constexpr int MAX_YEAR = 2000; constexpr int N_YEARS = MAX_YEAR - MIN_YEAR + 1; // delta[i] = n : change of n in net for year i + MIN_YEAR // e.g. a birth in year y --> +1 at year y // and a death in year z --> -1 at year z+1 std::array<int, N_YEARS + 1> delta_people{}; for (const auto& p : birth_death_years) { ++delta_people[p.first - MIN_YEAR]; // birth (at start of year) --delta_people[p.second + 1 - MIN_YEAR]; // death (at end of year) } int max_count = 0; int cur_count = 0; std::size_t max_i = 0; for (std::size_t i = 0; i < delta_people.size(); ++i) { cur_count += delta_people[i]; if (cur_count > max_count) { max_count = cur_count; max_i = i; } } return static_cast<int>(max_i + MIN_YEAR); } std::unordered_set<int> enumerate_lengths(int k, int shorter, int longer) { std::unordered_set<int> lengths; // s shorter + l longer = length // for all (s,l) such that s + l = k for (int l = 0; l <= k; ++l) { int s = k - l; int length = s * shorter + l * longer; // add to unordered_set to ignore duplicates lengths.insert(length); } return lengths; } int rand7(rand_n& rand5) { // amortised cost = (50/21) ~ 2.5x rand5() calls // stochastically have 21/25 chance of getting a rand7 // for each pair of rand5() calls int r7 = 7; while (r7 > 6) { // get flat sample in [0,25) // using 2x rand5 calls: r7 = rand5() + 5 * rand5(); // divide by 3 r7 /= 3; // {0,1,2}->0, {3,4,5}->1, ..., {18,19,20}->6, // {21,22,23}->7, {24}->8 // i.e. flat distrib in [0,7) // plus 4/25 chance of higher number, in which case // we discard it and try again } return r7; } } // namespace moderate } // namespace ctci
31.427451
80
0.578862
[ "vector" ]
f3268ac892605e084d28e9e7994bacfb7aa42f62
2,404
cpp
C++
AIProject/ArrivalBehaviour.cpp
ZetaFuntime/AI-Term-3
58cc8b00406e119f76538af5b8a59f7cdb85e22b
[ "MIT" ]
null
null
null
AIProject/ArrivalBehaviour.cpp
ZetaFuntime/AI-Term-3
58cc8b00406e119f76538af5b8a59f7cdb85e22b
[ "MIT" ]
null
null
null
AIProject/ArrivalBehaviour.cpp
ZetaFuntime/AI-Term-3
58cc8b00406e119f76538af5b8a59f7cdb85e22b
[ "MIT" ]
null
null
null
#include "ArrivalBehaviour.h" #include "GameObject.h" #include <Renderer2D.h> #include <glm\glm.hpp> #include <iostream> ArrivalBehaviour::ArrivalBehaviour() : Behaviour(), m_slowingRadius(100.f), m_targetRadius(10.f), m_forceStrength(100.f) { } ArrivalBehaviour::~ArrivalBehaviour() { } void ArrivalBehaviour::Update(GameObject *object, float deltaTime) { float lastDistanceToTarget = glm::length(m_targetPosition - m_lastPosition); float distanceToTarget = glm::length(m_targetPosition - object->GetPosition()); // Have we just entered the target radius if (m_onTargetRadiusEnter && lastDistanceToTarget > m_targetRadius && distanceToTarget <= m_targetRadius) m_onTargetRadiusEnter(); // -------------------------------------------------------------- // If the agent is outside the slowing radius, don't slow it down // -------------------------------------------------------------- float slowRatio = (distanceToTarget < m_slowingRadius) ? (distanceToTarget / (m_slowingRadius)) : 1; // -------------------------------------------------------------- // Apply a constant force to the agent which is scaled down as the // agent gets closer to the destination. // -------------------------------------------------------------- glm::vec2 currentDirToTarget = glm::normalize(m_targetPosition - object->GetPosition()) * slowRatio * m_forceStrength; object->SetVelocity(currentDirToTarget); m_lastPosition = object->GetPosition(); } void ArrivalBehaviour::Draw(GameObject *object, aie::Renderer2D *renderer) { if (IsDrawnByGameObject()) { renderer->drawBox(m_targetPosition.x, m_targetPosition.y, 10.f, 10.f); renderer->setRenderColour(1.0f, 1.0f, 1.0f, 0.1f); renderer->drawCircle(m_targetPosition.x, m_targetPosition.y, m_slowingRadius); renderer->setRenderColour(1.0f, 1.0f, 1.0f, 0.2f); renderer->drawCircle(m_targetPosition.x, m_targetPosition.y, m_targetRadius); renderer->setRenderColour(1.0f, 1.0f, 1.0f, 1.0f); } } const glm::vec2 &ArrivalBehaviour::GetTarget() { return m_targetPosition; } void ArrivalBehaviour::SetTarget(const glm::vec2 &target) { m_targetPosition = target; } float ArrivalBehaviour::GetSlowingRadius() { return m_slowingRadius; } void ArrivalBehaviour::SetSlowingRadius(float radius) { m_slowingRadius = radius; } void ArrivalBehaviour::OnTargetRadiusEnter(std::function< void() > func) { m_onTargetRadiusEnter = func; }
30.05
119
0.674709
[ "object" ]
f32bf4237a54ea0fba87c954374204045b54e7c3
2,634
cc
C++
src/Hcompute.cc
mhdeleglise/Gh
21a0b9bd53ae9de17f8b99040cac95cd6e1897e4
[ "MIT" ]
null
null
null
src/Hcompute.cc
mhdeleglise/Gh
21a0b9bd53ae9de17f8b99040cac95cd6e1897e4
[ "MIT" ]
null
null
null
src/Hcompute.cc
mhdeleglise/Gh
21a0b9bd53ae9de17f8b99040cac95cd6e1897e4
[ "MIT" ]
null
null
null
#include<gmpxx.h> #include<cmath> #include<vector> #include<unistd.h> #include"utilities.h" #include"Gfunction.h" #include"theta.h" #include<mpfr.h> #include<gmp.h> #include"Nk.h" void invli(mpfr_t res, mpfr_t x, double precision); class Hn { public: Gdelta gdelta; mpz_t n; mpfr_t n_mpfr; mpfr_t logn; mpfr_t thetak; mpfr_t logh; mpfr_t num_bn; mpfr_t den_bn; mpfr_t bn; mpfr_t invli2n; Hn(mpz_t n, long pk, long deltak); void show_Bvalue() {}; void compute_Log(); void compute_bn(); }; Hn::Hn(mpz_t nn, long pk,long m){ gdelta.init(pk,m,500,0); mpz_init(n); mpz_set(n,nn); mpfr_init_set_z(n_mpfr,n,MPFR_RNDN); mpfr_inits2(256, logn, thetak, logh, num_bn, den_bn, bn, invli2n, (mpfr_ptr) 0); mpfr_set_si(logn,0,MPFR_RNDN); mpfr_set_si(thetak,0,MPFR_RNDN); mpfr_set_si(logh,0,MPFR_RNDN); mpfr_set_si(num_bn,0,MPFR_RNDN); mpfr_set_si(den_bn,0,MPFR_RNDN); mpfr_set_si(bn,0,MPFR_RNDN); mpfr_set_si(invli2n,0,MPFR_RNDN); } void Hn::compute_Log() { theta(thetak,gdelta.pk); gdelta.compute_Glog(); mpfr_add(logh, thetak, gdelta.Glog, MPFR_RNDN); } void Hn::compute_bn() { mpfr_t invli2n,x2; mpfr_inits2(256,x2, invli2n, (mpfr_ptr) 0); mpfr_set_si(x2,0,MPFR_RNDN); invli(x2,n_mpfr,1e-12); mpfr_sqrt(invli2n,x2,MPFR_RNDN); compute_Log(); mpfr_sub(num_bn,invli2n,logh,MPFR_RNDN); mpfr_set(den_bn,n_mpfr,MPFR_RNDN); mpfr_log(logn, n_mpfr, MPFR_RNDN); mpfr_mul(den_bn, den_bn, logn, MPFR_RNDN); mpfr_root(den_bn, den_bn, 4, MPFR_RNDN); mpfr_div(bn, num_bn, den_bn, MPFR_RNDN); mpfr_printf ("%.30RZf\n", bn); } int main(int argc, char* argv[]){ mpz_t n; int Pplus, Log, Factors, Value, ShowBvalue; Pplus=Log=Factors=Value=ShowBvalue=0; int c; while((c= getopt(argc, argv, "lpfvb")) != EOF) { switch (c) { case 'p': Pplus=1; break; case 'l': Log=1; break; case 'f': Factors=1; break; case 'v': Value=1; break; case 'b': ShowBvalue=1; break; } } mpz_init(n); mpz_set_str(n, argv[optind], 10); long p=atol(argv[optind+1]); long m=atol(argv[optind+2]); Hn hn(n,p,m); mpfr_printf("hn initialise %.30RZ\n",hn.n_mpfr); // printf("n= %ld p= %ld m=%ld\n",n,p,m); //Gdelta res(p,m,maxdinit,verbose); if (Factors) { hn.gdelta.show_factors(); } if (Log) { mpfr_printf("Compute Log h(n):\n"); hn.compute_Log(); mpfr_printf("Log h(n): %.26Re\n\n",hn.logh); } if (Pplus) cout << "Pplus = " << hn.gdelta.Pplus() << endl << endl; if (Factors) { } if (ShowBvalue) { hn.compute_bn(); } return 0; }
20.578125
82
0.637054
[ "vector" ]
f32c486d4e3683dd5ec4df615d611378d9b83dcd
2,771
cpp
C++
test/test.cpp
andrewarchi/wslang
57b1313484880261c623dc5e371bbdd2b39b520f
[ "MIT" ]
null
null
null
test/test.cpp
andrewarchi/wslang
57b1313484880261c623dc5e371bbdd2b39b520f
[ "MIT" ]
null
null
null
test/test.cpp
andrewarchi/wslang
57b1313484880261c623dc5e371bbdd2b39b520f
[ "MIT" ]
1
2020-11-09T09:35:11.000Z
2020-11-09T09:35:11.000Z
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include <sstream> #include <string> #include <vector> #include <map> #include "../src/instruction.h" #include "../src/parser.h" #include "../src/vm.h" using namespace WS; std::vector<Instruction> parseProgram(const char *path) { FILE* in_file = fopen(path, "r"); Parser parser(in_file); std::vector<Instruction> instructions; Instruction instr; while (parser.next(instr)) { instructions.push_back(instr); } fclose(in_file); return instructions; } void compareProgramOutput(std::vector<Instruction> program_a, std::vector<Instruction> program_b, std::string input) { std::istringstream in(input); std::ostringstream out_a, out_b; VM(program_a, in, out_a).execute(); VM(program_b, in, out_b).execute(); REQUIRE(out_a.str() == out_b.str()); } void testProgramOutput(std::vector<Instruction> program, std::string input, std::string output) { std::istringstream in(input); std::ostringstream out; VM(program, in, out).execute(); REQUIRE(output == out.str()); } void testProgram(std::vector<Instruction> program, std::vector<integer_t> stack, std::map<integer_t, integer_t> heap) { VM vm(program); vm.execute(); REQUIRE(vm.getStack() == stack); REQUIRE(vm.getHeap() == heap); } TEST_CASE("VM executes simple stack instructions", "[vm]") { const std::vector<integer_t> stack{1, 2, 3, 4, 5}; std::istringstream in; std::ostringstream out; VM vm({ Instruction(PUSH, 1), Instruction(PUSH, 2), Instruction(PUSH, 3), DUP, Instruction(PUSH, 1), ADD, Instruction(COPY, 1), Instruction(COPY, 3), ADD }, in, out); vm.execute(); SECTION("Simple stack instructions ouput correctly") { REQUIRE(vm.getStack() == stack); } SECTION("VM::getStack returns a copy of the stack") { vm.getStack().push_back(42); REQUIRE(vm.getStack() == stack); } } TEST_CASE("Bottles instructions execute identically to parsed WS program", "[bottles]") { compareProgramOutput({ #include "../programs/bottles.instr" }, parseProgram("programs/bottles.generated.ws"), ""); } TEST_CASE("Copy and slide run as expected", "[instructions]") { testProgram({ Instruction(PUSH, 1), Instruction(PUSH, 2), Instruction(PUSH, 3), Instruction(PUSH, 4), Instruction(PUSH, 5), Instruction(PUSH, 6), Instruction(COPY, 3), // Should push 3 Instruction(SLIDE, 2) }, { 1, 2, 3, 4, 3 }, {}); } TEST_CASE("Test programs", "[programs]") { SECTION("hello-world.ws") { testProgramOutput(parseProgram("programs/hello-world.ws"), "", "Hello, World!\n"); } }
27.989899
119
0.630819
[ "vector" ]
f3314fdab9ad47cb04d6fbdc0ff091f015b2213f
23,647
cpp
C++
ECEditorModule/ECEditorWindow.cpp
mattire/naali
28c9cdc84c6a85e0151a222e55ae35c9403f0212
[ "Apache-2.0" ]
1
2018-04-02T15:38:10.000Z
2018-04-02T15:38:10.000Z
ECEditorModule/ECEditorWindow.cpp
mattire/naali
28c9cdc84c6a85e0151a222e55ae35c9403f0212
[ "Apache-2.0" ]
null
null
null
ECEditorModule/ECEditorWindow.cpp
mattire/naali
28c9cdc84c6a85e0151a222e55ae35c9403f0212
[ "Apache-2.0" ]
null
null
null
/** * For conditions of distribution and use, see copyright notice in license.txt * * @file ECEditorWindow.cpp * @brief Entity-component editor window. */ #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "ECEditorWindow.h" #include "ECEditorModule.h" #include "ECBrowser.h" #include "EntityPlacer.h" #include "ModuleManager.h" #include "SceneManager.h" #include "ComponentManager.h" #include "XMLUtilities.h" #include "SceneEvents.h" #include "EventManager.h" #include "EC_OgrePlaceable.h" #include <QUiLoader> #include <QDomDocument> #include "MemoryLeakCheck.h" using namespace RexTypes; namespace ECEditor { //! @bug code below causes a crash if user relog into the server and try to use ECEditorWindow. uint AddUniqueListItem(QListWidget* list, const QString& name) { for (int i = 0; i < list->count(); ++i) if (list->item(i)->text() == name) return i; list->addItem(name); return list->count() - 1; } uint AddTreeItem(QTreeWidget *list, const QString &type_name, const QString &name, int entity_id) { for(int i = 0; i < list->topLevelItemCount(); ++i) { QTreeWidgetItem *existing = list->topLevelItem(i); if (existing && existing->text(0) == type_name) { // We have already item for this EC. Create a dummy parent for the existing EC item and // the new one we're adding if it's not already. ///\todo Check/test if the code block below is required for real. if (existing->text(2) == "(Multiple)") { // It's already dummy parent. Add new item to its child. QTreeWidgetItem *item = new QTreeWidgetItem(existing); item->setText(0, type_name); item->setText(1, name); item->setText(2, QString::number(entity_id)); existing->addChild(item); return i; } // The existing item is not dummy parent yet, make it now. QTreeWidgetItem *dummyParent = new QTreeWidgetItem(list); dummyParent->setText(0, type_name); dummyParent->setText(1, ""); dummyParent->setText(2, "(Multiple)"); // Relocate the existing item from the top level to a child of the dummy parent. existing = list->takeTopLevelItem(i); dummyParent->addChild(existing); list->addTopLevelItem(dummyParent); // Finally, create new item for this EC. QTreeWidgetItem *item = new QTreeWidgetItem(dummyParent); item->setText(0, type_name); item->setText(1, name); item->setText(2, QString::number(entity_id)); dummyParent->addChild(item); return i; } } // No existing top level item, create one now. QTreeWidgetItem *item = new QTreeWidgetItem(list); item->setText(0, type_name); item->setText(1, name); item->setText(2, QString::number(entity_id)); list->addTopLevelItem(item); return list->topLevelItemCount() - 1; } ECEditorWindow::ECEditorWindow(Foundation::Framework* framework) : QWidget(), framework_(framework), toggle_entities_button_(0), entity_list_(0), browser_(0) { Initialize(); } ECEditorWindow::~ECEditorWindow() { } void ECEditorWindow::AddEntity(entity_id_t entity_id) { if (entity_list_) { QString entity_id_str; entity_id_str.setNum((int)entity_id); entity_list_->clearSelection(); entity_list_->setCurrentRow(AddUniqueListItem(entity_list_, entity_id_str)); } } void ECEditorWindow::RemoveEntity(entity_id_t entity_id) { if (!entity_list_) return; for(int i = 0; i < entity_list_->count(); ++i) { if (entity_list_->item(i)->text() == QString::number(entity_id)) { QListWidgetItem* item = entity_list_->takeItem(i); SAFE_DELETE(item); } } } void ECEditorWindow::ClearEntities() { if (entity_list_) entity_list_->clear(); RefreshPropertyBrowser(); } void ECEditorWindow::DeleteEntitiesFromList() { if ((entity_list_) && (entity_list_->hasFocus())) { for (int i = entity_list_->count() - 1; i >= 0; --i) { if (entity_list_->item(i)->isSelected()) { QListWidgetItem* item = entity_list_->takeItem(i); delete item; } } } } void ECEditorWindow::DeleteComponent(const QString &componentType, const QString &name) { if(componentType.isEmpty()) return; std::vector<Scene::EntityPtr> entities = GetSelectedEntities(); for(uint i = 0; i < entities.size(); i++) { Foundation::ComponentInterfacePtr component = entities[i]->GetComponent(componentType, name); if(component) { entities[i]->RemoveComponent(component, AttributeChange::Local); BoldEntityListItem(entities[i]->GetId(), false); } } } void ECEditorWindow::CreateComponent() { bool ok; QString typeName = QInputDialog::getItem(this, tr("Create Component"), tr("Component:"), GetAvailableComponents(), 0, false, &ok); if (!ok || typeName.isEmpty()) return; QString name = QInputDialog::getText(this, tr("Set component name (optional)"), tr("Name:"), QLineEdit::Normal, QString(), &ok); if (!ok) return; std::vector<Scene::EntityPtr> entities = GetSelectedEntities(); for (uint i = 0; i < entities.size(); ++i) { Foundation::ComponentInterfacePtr comp; comp = entities[i]->GetComponent(typeName, name); // Check if component has been already added to a entity. if(comp.get()) continue; // We (mis)use the GetOrCreateComponent function to avoid adding the same EC multiple times, since identifying multiple EC's of similar type // is problematic with current API if(!name.isEmpty()) comp = framework_->GetComponentManager()->CreateComponent(typeName, name); else comp = framework_->GetComponentManager()->CreateComponent(typeName); if (comp) entities[i]->AddComponent(comp, AttributeChange::Local); } } void ECEditorWindow::DeleteEntity() { Scene::ScenePtr scene = framework_->GetDefaultWorldScene(); if (!scene) return; std::vector<Scene::EntityPtr> entities = GetSelectedEntities(); for(uint i = 0; i < entities.size(); ++i) scene->RemoveEntity(entities[i]->GetId(), AttributeChange::Local); } void ECEditorWindow::CopyEntity() { //! @todo will only take a copy of first entity of the selection. //! should we support multi entity copy and paste functionality. std::vector<Scene::EntityPtr> entities = GetSelectedEntities(); QClipboard *clipboard = QApplication::clipboard(); QDomDocument temp_doc; for(uint i = 0; i < entities.size(); i++) { Scene::Entity *entity = entities[i].get(); if(entity) { QDomElement entity_elem = temp_doc.createElement("entity"); QString id_str; id_str.setNum((int)entity->GetId()); entity_elem.setAttribute("id", id_str); const Scene::Entity::ComponentVector &components = entity->GetComponentVector(); for(uint i = 0; i < components.size(); ++i) if (components[i]->IsSerializable()) components[i]->SerializeTo(temp_doc, entity_elem); temp_doc.appendChild(entity_elem); } } clipboard->setText(temp_doc.toString()); } void ECEditorWindow::PasteEntity() { // Dont allow paste operation if we are placing previosly pasted object to a scene. if(findChild<QObject*>("EntityPlacer")) return; // First we need to check if component is holding EC_OgrePlacable component to tell where entity should be located at. //! \todo local only server wont save those objects. Scene::ScenePtr scene = framework_->GetDefaultWorldScene(); assert(scene.get()); if(!scene.get()) return; QDomDocument temp_doc; QClipboard *clipboard = QApplication::clipboard(); if (temp_doc.setContent(clipboard->text())) { //Check if clipboard contain infomation about entity's id, //switch is used to find a right type of entity from the scene. QDomElement ent_elem = temp_doc.firstChildElement("entity"); if(ent_elem.isNull()) return; QString id = ent_elem.attribute("id"); Scene::EntityPtr originalEntity = scene->GetEntity(ParseString<entity_id_t>(id.toStdString())); if(!originalEntity.get()) { ECEditorModule::LogWarning("ECEditorWindow cannot create a new copy of entity, cause scene manager couldn't find entity. (id " + id.toStdString() + ")."); return; } Scene::ScenePtr scene = framework_->GetDefaultWorldScene(); Scene::EntityPtr entity = scene->CreateEntity(framework_->GetDefaultWorldScene()->GetNextFreeId()); assert(entity.get()); if(!entity.get()) return; bool hasPlaceable = false; Scene::Entity::ComponentVector components = originalEntity->GetComponentVector(); for(uint i = 0; i < components.size(); i++) { // If the entity is holding placeable component we can place it into the scene. if(components[i]->TypeName() == "EC_OgrePlaceable") { hasPlaceable = true; Foundation::ComponentInterfacePtr component = entity->GetOrCreateComponent(components[i]->TypeName(), components[i]->Name(), components[i]->GetChange()); } // Ignore all nonserializable components. if(components[i]->IsSerializable()) { Foundation::ComponentInterfacePtr component = entity->GetOrCreateComponent(components[i]->TypeName(), components[i]->Name(), components[i]->GetChange()); AttributeVector attributes = components[i]->GetAttributes(); for(uint j = 0; j < attributes.size(); j++) { AttributeInterface *attribute = component->GetAttribute(attributes[j]->GetNameString()); if(attribute) attribute->FromString(attributes[j]->ToString(), AttributeChange::Local); } component->ComponentChanged(AttributeChange::Local); } } if(hasPlaceable) { EntityPlacer *entityPlacer = new EntityPlacer(framework_, entity->GetId(), this); entityPlacer->setObjectName("EntityPlacer"); } AddEntity(entity->GetId()); scene->EmitEntityCreated(entity); } } void ECEditorWindow::HighlightEntities(Foundation::ComponentInterface *component) { std::vector<Scene::EntityPtr> entities = GetSelectedEntities(); for(uint i = 0; i < entities.size(); i++) { if(entities[i]->GetComponent(component->TypeName(), component->Name())) BoldEntityListItem(entities[i]->GetId(), true); else BoldEntityListItem(entities[i]->GetId(), false); } } void ECEditorWindow::RefreshPropertyBrowser() { PROFILE(EC_refresh_browser); if(!browser_) return; Scene::ScenePtr scene = framework_->GetDefaultWorldScene(); if (!scene) { browser_->clear(); return; } std::vector<Scene::EntityPtr> entities = GetSelectedEntities(); // If any of enities was not selected clear the browser window. if(!entities.size()) { browser_->clear(); // Unbold all list elements from the enity list. for(uint i = 0; i < entity_list_->count(); i++) BoldEntityListItem(entity_list_->item(i)->text().toInt(), false); return; } //! \todo hackish way to improve the browser performance by hiding the widget until all the changes are made //! so that unnecessary widget paints are avoided. This need be fixed in a way that browser's load is minimal. //! To ensure that the editor can handle thousands of induvicual elements in the same time. browser_->hide(); EntityIdSet noneSelectedEntities = selectedEntities_; selectedEntities_.clear(); // Check what new entities has been added and what old need to be removed from the browser. for(uint i = 0; i < entities.size(); i++) { browser_->AddNewEntity(entities[i].get()); selectedEntities_.insert(entities[i]->GetId()); noneSelectedEntities.erase(entities[i]->GetId()); } // After we have the list of entities that need to be removed we do so and after we are done, we will update browser's ui // to fit those changes that we just made. while(!noneSelectedEntities.empty()) { Scene::EntityPtr entity = scene->GetEntity(*(noneSelectedEntities.begin())); if (entity) { BoldEntityListItem(entity->GetId(), false); browser_->RemoveEntity(entity.get()); } noneSelectedEntities.erase(noneSelectedEntities.begin()); } browser_->show(); browser_->UpdateBrowser(); } void ECEditorWindow::ShowEntityContextMenu(const QPoint &pos) { assert(entity_list_); if (!entity_list_) return; QListWidgetItem *item = entity_list_->itemAt(pos); if (!item) return; QMenu *menu = new QMenu(this); menu->setAttribute(Qt::WA_DeleteOnClose); QAction *editXml = new QAction(tr("Edit XML..."), menu); QAction *deleteEntity= new QAction(tr("Delete"), menu); QAction *addComponent = new QAction(tr("Add new component..."), menu); QAction *copyEntity = new QAction(tr("Copy"), menu); QAction *pasteEntity = new QAction(tr("Paste"), menu); connect(editXml, SIGNAL(triggered()), this, SLOT(ShowXmlEditorForEntity())); connect(deleteEntity, SIGNAL(triggered()), this, SLOT(DeleteEntity())); connect(addComponent, SIGNAL(triggered()), this, SLOT(CreateComponent())); connect(copyEntity, SIGNAL(triggered()), this, SLOT(CopyEntity())); connect(pasteEntity, SIGNAL(triggered()), this, SLOT(PasteEntity())); menu->addAction(editXml); menu->addAction(deleteEntity); menu->addAction(addComponent); menu->addAction(copyEntity); menu->addAction(pasteEntity); menu->popup(entity_list_->mapToGlobal(pos)); } void ECEditorWindow::ShowXmlEditorForEntity() { std::vector<Scene::EntityPtr> entities = GetSelectedEntities(); std::vector<EntityComponentSelection> selection;// = GetSelectedComponents(); for(uint i = 0; i < entities.size(); i++) { EntityComponentSelection entityComponent; entityComponent.entity = entities[i]; entityComponent.components = entities[i]->GetComponentVector(); selection.push_back(entityComponent); } if (!selection.size()) return; QList<Scene::EntityPtr> ents; foreach(EntityComponentSelection ecs, selection) ents << ecs.entity; emit EditEntityXml(ents); } void ECEditorWindow::ShowXmlEditorForComponent(std::vector<Foundation::ComponentInterfacePtr> components) { if(!components.size()) return; QList<Foundation::ComponentPtr> comps; foreach(Foundation::ComponentInterfacePtr component, components) comps << component; emit EditComponentXml(comps); } void ECEditorWindow::ShowXmlEditorForComponent(const std::string &componentType) { if(componentType.empty()) return; std::vector<Scene::EntityPtr> entities = GetSelectedEntities(); for(uint i = 0; i < entities.size(); i++) { Foundation::ComponentInterfacePtr component = entities[i]->GetComponent(QString::fromStdString(componentType)); if(component) emit EditComponentXml(component); } } void ECEditorWindow::ToggleEntityList() { QWidget *entity_widget = findChild<QWidget*>("entity_widget"); if(entity_widget) { if (entity_widget->isVisible()) { entity_widget->hide(); resize(size().width() - entity_widget->size().width(), size().height()); if (toggle_entities_button_) toggle_entities_button_->setText(tr("Show entities")); } else { entity_widget->show(); resize(size().width() + entity_widget->sizeHint().width(), size().height()); if (toggle_entities_button_) toggle_entities_button_->setText(tr("Hide entities")); } } } void ECEditorWindow::hideEvent(QHideEvent* hide_event) { ClearEntities(); if(browser_) browser_->clear(); QWidget::hideEvent(hide_event); } void ECEditorWindow::changeEvent(QEvent *e) { if (e->type() == QEvent::LanguageChange) { QString title = QApplication::translate("ECEditor", "Entity-component Editor"); setWindowTitle(title); } else QWidget::changeEvent(e); } void ECEditorWindow::BoldEntityListItem(entity_id_t entity_id, bool bold) { QString entity_id_str; entity_id_str.setNum((int)entity_id); QList<QListWidgetItem*> items = entity_list_->findItems(QString::fromStdString(entity_id_str.toStdString()), Qt::MatchExactly); for(uint i = 0; i < items.size(); i++) { QFont font = items[i]->font(); font.setBold(bold); items[i]->setFont(font); } } void ECEditorWindow::Initialize() { QUiLoader loader; loader.setLanguageChangeEnabled(true); QFile file("./data/ui/eceditor.ui"); file.open(QFile::ReadOnly); QWidget *contents = loader.load(&file, this); if (!contents) { ECEditorModule::LogError("Could not load editor layout"); return; } file.close(); QVBoxLayout *layout = new QVBoxLayout(this); layout->addWidget(contents); layout->setContentsMargins(0,0,0,0); setLayout(layout); setWindowTitle(contents->windowTitle()); resize(contents->size()); toggle_entities_button_ = findChild<QPushButton *>("but_show_entities"); entity_list_ = findChild<QListWidget*>("list_entities"); QWidget *entity_widget = findChild<QWidget*>("entity_widget"); if(entity_widget) entity_widget->hide(); QWidget *browserWidget = findChild<QWidget*>("browser_widget"); if(browserWidget) { browser_ = new ECBrowser(framework_, browserWidget); browser_->setMinimumWidth(100); QVBoxLayout *property_layout = dynamic_cast<QVBoxLayout *>(browserWidget->layout()); if (property_layout) property_layout->addWidget(browser_); } if(browser_) { // signals from attribute browser to editor window. QObject::connect(browser_, SIGNAL(ShowXmlEditorForComponent(const std::string &)), this, SLOT(ShowXmlEditorForComponent(const std::string &))); QObject::connect(browser_, SIGNAL(CreateNewComponent()), this, SLOT(CreateComponent())); QObject::connect(browser_, SIGNAL(ComponentSelected(Foundation::ComponentInterface *)), this, SLOT(HighlightEntities(Foundation::ComponentInterface *))); } /* if (component_list_ && browser_) connect(browser_, SIGNAL(AttributesChanged()), this, SLOT(RefreshComponentXmlData())); */ if (entity_list_) { entity_list_->setSelectionMode(QAbstractItemView::ExtendedSelection); QShortcut* delete_shortcut = new QShortcut(QKeySequence(Qt::Key_Delete), entity_list_); QShortcut* copy_shortcut = new QShortcut(QKeySequence(Qt::Key_Control + Qt::Key_C), entity_list_); QShortcut* paste_shortcut = new QShortcut(QKeySequence(Qt::Key_Control + Qt::Key_V), entity_list_); connect(delete_shortcut, SIGNAL(activated()), this, SLOT(DeleteEntitiesFromList())); connect(copy_shortcut, SIGNAL(activated()), this, SLOT(CopyEntity())); connect(paste_shortcut, SIGNAL(activated()), this, SLOT(PasteEntity())); connect(entity_list_, SIGNAL(itemSelectionChanged()), this, SLOT(RefreshPropertyBrowser())); connect(entity_list_, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(ShowEntityContextMenu(const QPoint &))); } if (toggle_entities_button_) connect(toggle_entities_button_, SIGNAL(pressed()), this, SLOT(ToggleEntityList())); } QStringList ECEditorWindow::GetAvailableComponents() const { QStringList components; Foundation::ComponentManagerPtr comp_mgr = framework_->GetComponentManager(); const Foundation::ComponentManager::ComponentFactoryMap& factories = comp_mgr->GetComponentFactoryMap(); Foundation::ComponentManager::ComponentFactoryMap::const_iterator i = factories.begin(); while (i != factories.end()) { components.append(i->first); //<< i->first.c_str(); ++i; } return components; } std::vector<Scene::EntityPtr> ECEditorWindow::GetSelectedEntities() { std::vector<Scene::EntityPtr> ret; if (!entity_list_) return ret; Scene::ScenePtr scene = framework_->GetDefaultWorldScene(); if (!scene) return ret; for (uint i = 0; i < entity_list_->count(); ++i) { QListWidgetItem* item = entity_list_->item(i); if (item->isSelected()) { entity_id_t id = (entity_id_t)item->text().toInt(); Scene::EntityPtr entity = scene->GetEntity(id); if (entity) ret.push_back(entity); } } return ret; } }
38.263754
173
0.583837
[ "object", "vector" ]
f33305cc0abb71d808832589bce9a141264af3d3
5,447
cpp
C++
core/src/server/DBWrapper.cpp
AmyYH/milvus
d993bcc9894f30fd1bbf3a3b998bcaa7226260da
[ "Apache-2.0" ]
null
null
null
core/src/server/DBWrapper.cpp
AmyYH/milvus
d993bcc9894f30fd1bbf3a3b998bcaa7226260da
[ "Apache-2.0" ]
null
null
null
core/src/server/DBWrapper.cpp
AmyYH/milvus
d993bcc9894f30fd1bbf3a3b998bcaa7226260da
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2019-2020 Zilliz. All rights reserved. // // 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. #include "server/DBWrapper.h" #include <omp.h> #include <cmath> #include <string> #include <vector> #include <faiss/utils/distances.h> #include "config/ServerConfig.h" #include "db/DBFactory.h" #include "db/snapshot/OperationExecutor.h" #include "utils/CommonUtil.h" #include "utils/ConfigUtils.h" #include "utils/Log.h" #include "utils/StringHelpFunctions.h" namespace milvus { namespace server { Status DBWrapper::StartService() { Status s; // db config engine::DBOptions opt; opt.meta_.backend_uri_ = config.general.meta_uri(); std::string path = config.storage.path(); opt.meta_.path_ = path + "/db"; opt.auto_flush_interval_ = config.storage.auto_flush_interval(); opt.metric_enable_ = config.metric.enable(); opt.insert_cache_immediately_ = config.cache.cache_insert_data(); opt.insert_buffer_size_ = config.cache.insert_buffer_size(); if (not config.cluster.enable()) { opt.mode_ = engine::DBOptions::MODE::SINGLE; } else if (config.cluster.role() == ClusterRole::RO) { opt.mode_ = engine::DBOptions::MODE::CLUSTER_READONLY; } else if (config.cluster.role() == ClusterRole::RW) { opt.mode_ = engine::DBOptions::MODE::CLUSTER_WRITABLE; } else { std::cerr << "Error: cluster.role is not one of rw and ro." << std::endl; kill(0, SIGUSR1); } opt.wal_enable_ = config.wal.enable(); // disable wal for ci devtest opt.wal_enable_ = false; if (opt.wal_enable_) { int64_t wal_buffer_size = config.wal.buffer_size(); wal_buffer_size /= (1024 * 1024); opt.buffer_size_ = wal_buffer_size; opt.mxlog_path_ = config.wal.path(); } // engine config int64_t omp_thread = config.engine.omp_thread_num(); if (omp_thread > 0) { omp_set_num_threads(omp_thread); LOG_SERVER_DEBUG_ << "Specify openmp thread number: " << omp_thread; } else { int64_t sys_thread_cnt = 8; if (GetSystemAvailableThreads(sys_thread_cnt)) { omp_thread = static_cast<int32_t>(ceil(sys_thread_cnt * 0.5)); omp_set_num_threads(omp_thread); } } // init faiss global variable int64_t use_blas_threshold = config.engine.use_blas_threshold(); faiss::distance_compute_blas_threshold = use_blas_threshold; // create db root folder s = CommonUtil::CreateDirectory(opt.meta_.path_); if (!s.ok()) { std::cerr << "Error: Failed to create database primary path: " << path << ". Possible reason: db_config.primary_path is wrong in server_config.yaml or not available." << std::endl; kill(0, SIGUSR1); } try { db_ = engine::DBFactory::BuildDB(opt); db_->Start(); } catch (std::exception& ex) { std::cerr << "Error: failed to open database: " << ex.what() << ". Possible reason: out of storage, meta schema is damaged " << "or created by in-compatible Milvus version." << std::endl; kill(0, SIGUSR1); } // preload collection std::string preload_collections = config.cache.preload_collection(); s = PreloadCollections(preload_collections); if (!s.ok()) { std::cerr << "ERROR! Failed to preload collections: " << preload_collections << std::endl; std::cerr << s.ToString() << std::endl; kill(0, SIGUSR1); } return Status::OK(); } Status DBWrapper::StopService() { if (db_) { db_->Stop(); } // SS TODO /* engine::snapshot::OperationExecutor::GetInstance().Stop(); */ return Status::OK(); } Status DBWrapper::PreloadCollections(const std::string& preload_collections) { if (preload_collections.empty()) { // do nothing } else if (preload_collections == "*") { // load all collections std::vector<std::string> names; auto status = db_->ListCollections(names); if (!status.ok()) { return status; } for (auto& name : names) { std::vector<std::string> field_names; // input empty field names will load all fileds auto status = db_->LoadCollection(nullptr, name, field_names); if (!status.ok()) { return status; } } } else { std::vector<std::string> collection_names; StringHelpFunctions::SplitStringByDelimeter(preload_collections, ",", collection_names); for (auto& name : collection_names) { std::vector<std::string> field_names; // input empty field names will load all fileds auto status = db_->LoadCollection(nullptr, name, field_names); if (!status.ok()) { return status; } } } return Status::OK(); } } // namespace server } // namespace milvus
32.616766
113
0.63356
[ "vector" ]
f33fa23e1b3234175b52710f50b7fb359283f0bb
72,876
hh
C++
ai.hh
NikitaMushchak/DBSCAN
73616381c8778da8b047cab44c50d9465bcb0f0d
[ "MIT" ]
null
null
null
ai.hh
NikitaMushchak/DBSCAN
73616381c8778da8b047cab44c50d9465bcb0f0d
[ "MIT" ]
null
null
null
ai.hh
NikitaMushchak/DBSCAN
73616381c8778da8b047cab44c50d9465bcb0f0d
[ "MIT" ]
null
null
null
#if !defined(AILIBRARY_HH) #define AILIBRARY_HH /// \file ai.hh /// \author Egor Starobinskii /// \date 05 Feb 2018 /// \brief Single-header C++ Library /// \details This is a single-header C++ Library from Ailurus Studio that /// brings you extra time to admire life instead of coding the same functions /// again and again. Meets the C++11 standard. /// \see https://starobinskii.github.io/AiLibrary /// \see https://github.com/starobinskii/AiLibrary /// \see https://snapcraft.io/ailibrary /// \see https://ailurus.ru/ /// \brief If defined, funstions will be marked as inline /// \details If defined, funstions will be marked as inline. Comment the line /// if you want to omit this behavior #define INLINE inline /// \todo add #define STRINGIFY(x) #x #define TO_STRING(x) STRINGIFY(x) /// \brief If defined, functions using dirent.h will be included /// \details If defined, functions using dirent.h (POSIX) will be included. /// Uncomment the line or pass the defined value at compile time if you want /// this behavior. Windows users may need to specify the location of the header /// below // #define AI_DIRENT_SUPPORT /// \brief If defined, functions requiring UNIX shell will be included /// \details If defined, functions requiring UNIX shell will be included. /// Uncomment the line or pass the defined value at compile time if you want /// this behavior. // #define AI_SHELL_SUPPORT /// \brief If defined, declarations of not yet implemented functions will be /// accessible /// \details If defined, declarations of not yet implemented functions will be /// accessible. Uncomment the line or pass the defined value at compile time /// if you want this behavior // #define AI_FUTURE #include <array> #include <cmath> #include <chrono> #include <limits> #include <memory> #include <random> #include <string> #include <vector> #include <cstdlib> #include <iomanip> #include <fstream> #include <sstream> #include <iostream> #include <algorithm> #include <stdexcept> #include <sys/stat.h> #if defined(AI_DIRENT_SUPPORT) /// On Windows, you can use nice dirent.h implementation from Toni Ronkko /// (MIT license). Its copy is located at include/dirent. /// \see https://github.com/tronkko/dirent #include <dirent.h> // #include "include/dirent/dirent.h" #endif /// \namespace ai /// \brief Main namespace /// \details Main namespace containing all the functions of AiLibrary /// \defgroup AiNamespace AiLibrary Namespace /// \brief Main group /// \details Main group containing all the functions of AiLibrary /// \{ namespace ai{ /// \defgroup LibraryInfo Library Info /// \brief Functions providing info about the library /// \details Group of functions that provides information about this /// library /// \{ /// \fn std::string getVersion(); /// \brief Gets version of the lib /// \details This function returns version of the AiLibrary (we use SemVer) /// \return Version as a string INLINE std::string getVersion(){ return "1.2.8"; } /// \} End of LibraryInfo Group /// \defgroup StringFunctions String Functions /// \brief Functions providing additional methods to work with strings /// \details Group of functions that allows you to freely manipulate and /// analyze strings /// \{ /// \fn std::string string(const T value); /// \brief Converts input into a string /// \details This function converts your variable into std::string using /// std::ostringstream /// \param value Your variable to convert /// \return std::string copy of your input template<typename T> INLINE std::string string(const T value){ std::ostringstream stream; stream << value; return stream.str(); } /// \fn bool hasPrefix(const std::string &text, const std::string &prefix); /// \brief Checks if a string begins with a substring /// \details This function checks if a string begins with a substring /// \param text Your string to test /// \param prefix Your substring /// \return True if string begins with a substring, false otherwise INLINE bool hasPrefix(const std::string &text, const std::string &prefix){ return text.size() >= prefix.size() && 0 == text.compare(0, prefix.size(), prefix); } /// \fn bool hasSuffix(const std::string &text, const std::string &suffix); /// \brief Checks if a string ends with a substring /// \details This function checks if a string ends with a substring /// \param text Your string to test /// \param suffix Your substring /// \return True if string ends with a substring, false otherwise INLINE bool hasSuffix(const std::string &text, const std::string &suffix){ return text.size() >= suffix.size() && 0 == text.compare( text.size() - suffix.size(), suffix.size(), suffix ); } /// \fn bool contains(const std::string &text, const std::string /// &substring); /// \brief Checks if a string contains a substring /// \details This function checks if a string contains a substring /// \param text Your string to test /// \param substring Your substring /// \return True if string contains a substring, false otherwise INLINE bool contains( const std::string &text, const std::string &substring ){ return std::string::npos != text.find(substring); } /// \fn std::string replace(std::string text, const std::string &substring, /// const std::string &replacement) /// \brief Replaces all occurrences of a substring in a copy of the initial /// string with your text /// \details This function replaces all occurrences of a substring in a /// string with your text and return the result. Initial string stays the /// same /// \param text Your string to modify /// \param substring Your substring to find in the string /// \param replacement Replacement for all the substring occurrences /// \return Modified copy of the initial string INLINE std::string replace( std::string text, const std::string &substring, const std::string &replacement ){ std::size_t position = text.find(substring); std::size_t substringSize = substring.size(); std::size_t replacementSize = replacement.size(); while(std::string::npos != position){ text.replace(position, substringSize, replacement); position = text.find(substring, position + replacementSize); } return text; } /// \fn void applyReplace(std::string &text, const std::string /// &substring, const std::string &replacement) /// \brief Modifies your string by replacing all occurrences of a substring /// string with your text /// \details This function replaces all occurrences of a substring in a /// string with your text (modifies the initial string) /// \param text Your string to modify /// \param substring Your substring to find in the string /// \param replacement Replacement for all the substring occurrences INLINE void applyReplace( std::string &text, const std::string &substring, const std::string &replacement ){ std::size_t position = text.find(substring); std::size_t substringSize = substring.size(); std::size_t replacementSize = replacement.size(); while(std::string::npos != position){ text.replace(position, substringSize, replacement); position = text.find(substring, position + replacementSize); } } /// \fn bool equal(const char *charString, const std::string string1); /// \brief Checks if a char string is equal to a std::string /// \details This function compares a char string with a std::string /// \param charString Your char string to compare /// \param string1 Your std::string to compare /// \return True if strings are equal, false otherwise INLINE bool equal(const char *charString, const std::string string1){ const std::string string2(charString); return string1 == string2; } /// \todo Add description. Add tests INLINE std::string toUpperCase(std::string input){ std::transform(input.begin(), input.end(), input.begin(), ::toupper); return input; } /// \todo Add description. Add tests INLINE std::string toLowerCase(std::string input){ std::transform(input.begin(), input.end(), input.begin(), ::tolower); return input; } /// \fn std::string prependNumber(const T value, const std::size_t /// digitsBeforePoint, const char symbolToPrepend) /// \brief Convert number co counter-like string /// \details This function converts number to std::string type and /// prepends some zeros (of other given symbol) if needed /// \param value Number to style /// \param symbolsBeforePoint Minimal required number of symbols before /// point /// \param symbolToPrepend Prepending symbol, zero by default /// \return Styled string /// \todo Add tests template<typename T> INLINE std::string prependNumber( const T value, const std::size_t symbolsBeforePoint, const char symbolToPrepend = '0' ){ std::string token = ai::string(value); const int counter = symbolsBeforePoint - (ai::string((int) value)).size(); for(int i = 0; i < counter; ++i){ token = ai::string(symbolToPrepend) + token; } return token; } /// \} End of StringFunctions Group /// \defgroup DebugFunctions Debug Functions /// \brief Functions providing some help to debug programs /// \details Group of functions that can be useful if you want to debug /// your code /// \{ /// \fn std::size_t counter(std::size_t value = 0); /// \brief Returns ID starting from zero or the specified value /// \details This function returns ID (increases it at each call) starting /// from zero or the specified non-negative value /// \param value The non-negative value to which the counter should be /// reset (optional) /// \return Counter value INLINE std::size_t counter(const std::size_t value = 0){ static std::size_t count = 0; ++count; if(0 != value){ count = value; } return count; } /// \fn std::string marker(std::size_t value = 0); /// \brief Returns a string containing the word "Marker" and its ID /// \details This function returns a string containing the word "marker" /// and its ID (increases it at each call). ID specified in the same way /// as in the function counter() /// \param value The non-negative value to which the counter should be /// reset (optional) /// \return Marker string INLINE std::string marker(const std::size_t value = 0){ static std::size_t count = 0; ++count; if(0 != value){ count = value; } return "Marker #" + ai::string(count); } /// \fn void printMarker(std::size_t value = 0); /// \brief Calls marker() and prints result to stdout /// \details This function calls marker() and prints result to stdout /// \param value The non-negative value to which the counter should be /// reset (optional) INLINE void printMarker(const std::size_t value = 0){ std::cout << marker(value) << std::endl; } /// \} End of DebugFunctions Group /// \defgroup MathFunctions Math Functions /// \brief Functions providing different math methods and checks /// \details Group of functions that completes standard C++ mathematical /// methods and helps with matrices and vectors /// \{ /// \brief Mathematical constant 'e' /// \details Mathematical constant \f$e\f$ (20 decimal places) const double e = 2.71828182845904523536; /// \brief Mathematical constant 'pi' /// \details Mathematical constant \f$\pi\f$ (20 decimal places) const double pi = 3.14159265358979323846; /// \fn T sign(const T value); /// \brief Returns signum of the value /// \details This function returns signum of the number value (usign /// copysign()) /// \param value The number to which signum is applied /// \return -1 for negative values, +1 for positive, 0 for zero /// \tparam T A number type template<typename T> INLINE T sign(const T value){ if(0 == value){ return (T) 0; } return copysign(1, value); } /// \fn T min(const T a, const T b); /// \brief Returns minimum of two values /// \details This function compares two values and returns a minimum /// \param a First number /// \param b Second number /// \return Minimum of two values /// \tparam T A number type template<typename T> INLINE T min(const T a, const T b){ if(a > b){ return b; } return a; } /// \fn T max(const T a, const T b); /// \brief Returns maximum of two values /// \details This function compares two values and returns a maximum /// \param a First number /// \param b Second number /// \return Maximum of two values /// \tparam T A number type template<typename T> INLINE T max(const T a, const T b){ if(a < b){ return b; } return a; } /// \fn T min(const std::vector<T> &input); /// \brief Returns minimum of vector values /// \details This function compares vector values using min() and returns /// a minimum /// \param input Vector to search for a minimum value /// \return Minimum of vector values /// \tparam T A number type /// \todo Add tests template<typename T> INLINE T min(const std::vector<T> &input){ T minimum = input[0]; for(std::size_t i = 1; i < input.size(); ++i){ minimum = ai::min(minimum, input[i]); } return minimum; } /// \fn T max(const std::vector<T> &input); /// \brief Returns maximum of vector values /// \details This function compares vector values using max() and returns /// a maximum /// \param input Vector to search for a maximum value /// \return Maximum of vector values /// \tparam T A number type /// \todo Add tests template<typename T> INLINE T max(const std::vector<T> &input){ T maximum = input[0]; for(std::size_t i = 1; i < input.size(); ++i){ maximum = ai::max(maximum, input[i]); } return maximum; } /// \fn T min(const std::vector< std::vector<T> > &input); /// \brief Returns minimum of matrix values /// \details This function compares matrix values using min() and returns /// a minimum /// \param input Matrix to search for a minimum value /// \return Minimum of matrix values /// \tparam T A number type /// \todo Add tests template<typename T> INLINE T min(const std::vector< std::vector<T> > &input){ T minimum = input[0][0]; for(std::size_t i = 0; i < input.size(); ++i){ for(std::size_t j = 0; j < input[0].size(); ++j){ minimum = ai::min(minimum, input[i][j]); } } return minimum; } /// \fn T max(const std::vector< std::vector<T> > &input); /// \brief Returns maximum of matrix values /// \details This function compares matrix values using max() and returns /// a maximum /// \param input Matrix to search for a maximum value /// \return Maximum of matrix values /// \tparam T A number type /// \todo Add tests template<typename T> INLINE T max(const std::vector< std::vector<T> > &input){ T maximum = input[0][0]; for(std::size_t i = 0; i < input.size(); ++i){ for(std::size_t j = 0; j < input[0].size(); ++j){ maximum = ai::max(maximum, input[i][j]); } } return maximum; } /// \fn bool isSquare(const T value); /// \brief Checks if number is square /// \details This function checks if number is square /// \param value Number to test /// \return True if number is a square, false otherwise /// \tparam T A number type /// \todo Add tests template<typename T> INLINE bool isSquare(const T value){ if(0 >= value){ return false; } T root = (T) round(sqrt(value)); return value == root * root; } /// \fn bool isSquare(const std::vector< std::vector<T> > matrix); /// \brief Checks if matrix is square /// \details This function checks if matrix is square /// \param matrix Matrix to test /// \return True if matrix is square, false otherwise /// \todo Add tests template<typename T> INLINE bool isSquare(const std::vector< std::vector<T> > matrix){ return 0 < matrix.size() && matrix.size() == matrix[0].size(); } /// \fn void generateRandomVector(std::vector<T> &vector, const /// std::size_t length, const T min = std::numeric_limits<T>::min(), /// const T max = std::numeric_limits<T>::max()); /// \brief Fill vector with random values /// \details This function fills the vector of given length with random /// values using std::random_device. /// \param vector Vector to fill /// \param length Required length of the vector /// \param min Lower limit of generated values, no limitation by default /// \param max Upper limit of generated values, no limitation by default /// \todo Add tests template<typename T> INLINE void generateRandomVector( std::vector<T> &vector, const std::size_t length, const T min = std::numeric_limits<T>::min(), const T max = std::numeric_limits<T>::max() ){ std::uniform_real_distribution<T> distribution(min, max); std::random_device device; double currentTime = (double) ( std::chrono::high_resolution_clock::now() ).time_since_epoch().count(); srand(device() * currentTime); vector.resize(length); std::generate( vector.begin(), vector.end(), [&device, &distribution](){ return distribution(device); } ); } /// \fn void generateRandomMatrix(std::vector< std::vector<T> > &matrix, /// const std::size_t xSize, const std::size_t ySize, const T min = /// std::numeric_limits<T>::min(), const T max = /// std::numeric_limits<T>::max()); /// \brief Fill matrix with random values /// \details This function fills the matrix of given sizes with random /// values using std::random_device and generateRandomVector(). /// \param matrix Matrix to fill /// \param xSize Required length of the matrix /// \param ySize Required height of the matrix /// \param min Lower limit of generated values, no limitation by default /// \param max Upper limit of generated values, no limitation by default /// \todo Add tests template<typename T> INLINE void generateRandomMatrix( std::vector< std::vector<T> > &matrix, const std::size_t xSize, const std::size_t ySize, const T min = std::numeric_limits<T>::min(), const T max = std::numeric_limits<T>::max() ){ matrix.resize(xSize); for(size_t i = 0; i < xSize; ++i){ matrix[i].resize(ySize); std::vector<T> row; ai::generateRandomVector(row, ySize, min, max); matrix[i] = row; } } /// \fn void generateRandomMatrix(std::vector< std::vector<T> > &matrix, /// const std::size_t size, const T min = std::numeric_limits<T>::min(), /// const T max = std::numeric_limits<T>::max()); /// \brief Fill matrix with random values /// \details This function fills the square matrix of given sizes with /// random values using std::random_device and generateRandomVector(). /// \param matrix Matrix to fill /// \param size Required size of the square matrix /// \param min Lower limit of generated values, no limitation by default /// \param max Upper limit of generated values, no limitation by default /// \todo Add tests template<typename T> INLINE void generateRandomMatrix( std::vector< std::vector<T> > &matrix, const std::size_t size, const T min = std::numeric_limits<T>::min(), const T max = std::numeric_limits<T>::max() ){ ai::generateRandomMatrix(matrix, size, size, min, max); } /// \fn void translateMatrixIntoVector(std::vector< std::vector<T> > /// &matrix, std::vector<T> &vector); /// \brief Elongates matrix into a vector /// \details This function converts the matrix into a vector, writing each /// row one after another in a line /// \param matrix Matrix to tranform /// \param vector Vector to store the result /// \todo Add tests template<typename T> INLINE void translateMatrixIntoVector( std::vector< std::vector<T> > &matrix, std::vector<T> &vector ){ for(std::size_t i = 0; i < matrix.size(); ++i){ for(std::size_t j = 0; j < matrix[i].size(); ++j){ vector.push_back(matrix[i][j]); } } } /// \fn void translateVectorIntoSquareMatrix(std::vector<T> &vector, /// std::vector< std::vector<T> > &matrix); /// \brief Transform vector in a square matrix (if possible) /// \details This function converts the vector into a matrix, if possible. /// Otherwise, an exception will be thrown at runtime /// \param vector Vector to tranform /// \param matrix Matrix to store the result /// \exception std::runtime_error If \p matrix is not square /// \todo Add tests template<typename T> INLINE void translateVectorIntoSquareMatrix( std::vector<T> &vector, std::vector< std::vector<T> > &matrix ){ if(!isSquare(vector.size())){ throw std::runtime_error( ai::string("Exception while converting vector into the ") + ai::string("square matrix: vector size should be square") ); } std::size_t size = (std::size_t) round(sqrt(vector.size())); for(std::size_t i = 0; i < size; ++i){ std::vector<T> row; for(std::size_t j = 0; j < size; ++j){ row.push_back(vector[i * size + j]); } matrix.push_back(row); } } /// \fn void generateCirculantMatrix(std::vector< std::vector<double> > /// &matrix, std::vector<double> &source, const bool moveToTheRight = /// true); /// \brief Fill a circulant matrix with values from the input vector /// \details This function Fills the matrix by rotating the input vector /// to the left or right by one value in a row forming a circalunt /// \see https://en.wikipedia.org/wiki/Circulant_matrix /// row one after another in a line /// \param matrix Matrix to fill /// \param vector Vector storing the values /// \param moveToTheRight If true, shift the vector to the right. /// Otherwise to the left. True by default. /// \exception std::runtime_error If \p source is an empty vector /// \todo Add tests INLINE void generateCirculantMatrix( std::vector< std::vector<double> > &matrix, std::vector<double> &source, const bool moveToTheRight = true ){ if(1 > source.size()){ throw std::runtime_error( ai::string("Exception while creating a circulant: ") + ai::string("size of the source should be at least 1.") ); } std::size_t length = source.size(); std::size_t displacement = 0; matrix.clear(); matrix.resize(length); if(moveToTheRight){ for(std::size_t i = 0; i < length; ++i){ matrix[i].resize(length); std::size_t k = displacement; for(std::size_t j = 0; j < length - displacement; ++j){ matrix[i][k] = source[j]; ++k; } k = 0; for(std::size_t j = length - displacement; j < length; ++j){ matrix[i][k] = source[j]; ++k; } ++displacement; } }else{ for(std::size_t i = 0; i < length; ++i){ matrix[i].resize(length); std::size_t k = 0; for(std::size_t j = displacement; j < length; ++j){ matrix[i][k] = source[j]; ++k; } for(std::size_t j = 0; j < displacement; ++j){ matrix[i][k] = source[j]; ++k; } ++displacement; } } } /// \todo Add description. Add tests template<typename T> INLINE void multiply( const std::vector< std::vector<T> > &left, const std::vector< std::vector<T> > &right, std::vector< std::vector<T> > &result ){ if( 1 > left.size() || 1 > right.size() || left[0].size() != right.size() ){ throw std::runtime_error( "Exception while multiplying: check the sizes of the input." ); } std::size_t vLength = left.size(); std::size_t hLength = right[0].size(); std::size_t fLength = left[0].size(); result.resize(vLength); for(std::size_t i = 0; i < vLength; ++i){ result[i].resize(hLength); for(std::size_t j = 0; j < hLength; ++j){ result[i][j] = (T) 0.; } for(std::size_t k = 0; k < fLength; ++k){ for(std::size_t j = 0; j < hLength; ++j){ result[i][j] += left[i][k] * right[k][j]; } } } }; /// \todo Add description. Add tests template<typename T> INLINE void multiply( const std::vector< std::vector<T> > &left, const std::vector<T> &right, std::vector<T> &result ){ if(1 > left.size() || left[0].size() != right.size()){ throw std::runtime_error( "Exception while multiplying: check the sizes of the input." ); } std::size_t vLength = left.size(); int hLength = (int) right.size(); int j = 0; result.resize(vLength); for(int i = 0; i < vLength; ++i){ j = 0; result[i] = (T) 0.; for(; j <= hLength - 4; j += 4){ result[i] += left[i][j] * right[j] + left[i][j + 1] * right[j + 1] + left[i][j + 2] * right[j + 2] + left[i][j + 3] * right[j + 3]; } for(; j < hLength; ++j){ result[i] += left[i][j] * right[j]; } } } /// \todo Add description. Add tests template<typename T> INLINE void multiply( const std::vector<T> &left, const std::vector<T> &right, T &result ){ if(left.size() != right.size()){ throw std::runtime_error( "Exception while multiplying: check the sizes of the input." ); } int length = (int) left.size(); int i = 0; result = (T) 0.; for(; i <= length - 4; i += 4){ result += left[i] * right[i] + left[i + 1] * right[i + 1] + left[i + 2] * right[i + 2] + left[i + 3] * right[i + 3]; } for(; i < length; ++i){ result += left[i] * right[i]; } } /// \todo Add description. Add tests template<typename T> INLINE void multiplyElementWise( const std::vector< std::vector<T> > &left, const std::vector< std::vector<T> > &right, std::vector< std::vector<T> > &result ){ if( 1 > left.size() || 1 > right.size() || left.size() != right.size() || left[0].size() != right[0].size() ){ throw std::runtime_error( "Exception while multiplying: check the sizes of the input." ); } std::size_t vLength = left.size(); std::size_t hLength = left[0].size(); result.resize(vLength); for(std::size_t i = 0; i < vLength; ++i){ result[i].resize(hLength); for(std::size_t j = 0; j < hLength; ++j){ result[i][j] = left[i][j] * right[i][j]; } } } /// \todo Add description. Add tests template<typename T> INLINE void multiplyElementWise( const std::vector<T> &left, const std::vector<T> &right, std::vector<T> &result ){ if(left.size() != right.size()){ throw std::runtime_error( "Exception while multiplying: check the sizes of the input." ); } int length = (int) left.size(); result.resize(length); for(std::size_t i = 0; i < length; ++i){ result[i] = left[i] * right[i]; } } /// \todo Add description. Add tests template<typename T> INLINE void multiplyComplexElementWise( const std::vector< std::vector<T> > &left, const std::vector< std::vector<T> > &right, std::vector< std::vector<T> > &result ){ if( left.size() != right.size() || 2 != left[0].size() || 2 != right[0].size() ){ throw std::runtime_error( "Exception while multiplying: check the sizes of the input." ); } const std::size_t length = left.size(); result.resize(length); for(std::size_t i = 0; i < length; ++i){ result[i].resize(2); result[i][0] = left[i][0] * right[i][0] - left[i][1] * right[i][1]; result[i][1] = left[i][0] * right[i][1] + left[i][1] * right[i][0]; } } template<typename T> INLINE std::string complexIntoString(const std::vector<T> complexValue){ return ai::string(complexValue[0]) + ai::string(" + i") + ai::string(complexValue[1]); } /// \todo Add description. Add tests template<typename T> INLINE void conjugate(std::vector< std::vector<T> > &complexVector){ const std::size_t length = complexVector.size(); for(std::size_t i = 0; i < length; ++i){ complexVector[i][1] = -complexVector[i][1]; } } /// \todo Add description. Add tests template<typename T> INLINE void fft(std::vector< std::vector<T> > &complexVector){ const std::size_t length = complexVector.size(); if(2 > length || !(length & (length - 1)) == 0){ throw std::runtime_error( std::string("Exception while calculatingFFT: ") + std::string("vector length must be a power of two.") ); } std::size_t j = 0; std::size_t k = length; std::size_t n = 0; const double doubleTypeLength = (double) k; double thetaT = ai::pi / doubleTypeLength; double swap0 = 0.; double swap1 = 0.; double T0 = 1.; double T1 = 0.; double phiT0 = cos(thetaT); double phiT1 = -sin(thetaT); while(1 < k){ n = k; T0 = 1.; T1 = 0.; swap0 = phiT0; swap1 = phiT1; phiT0 = swap0 * swap0 - swap1 * swap1; phiT1 = 2. * swap0 * swap1; k >>= 1; for(std::size_t l = 0; l < k; ++l){ for(std::size_t i = l; i < length; i += n){ j = i + k; swap0 = complexVector[i][0] - complexVector[j][0]; swap1 = complexVector[i][1] - complexVector[j][1]; complexVector[i][0] += complexVector[j][0]; complexVector[i][1] += complexVector[j][1]; complexVector[j][0] = swap0 * T0 - swap1 * T1; complexVector[j][1] = swap0 * T1 + swap1 * T0; } swap0 = T0; T0 = swap0 * phiT0 - T1 * phiT1; T1 = swap0 * phiT1 + T1 * phiT0; } } std::size_t m = (std::size_t) log2(doubleTypeLength); for(std::size_t i = 0; i < length; ++i){ j = i; j = (((j & 0xaaaaaaaa) >> 1) | ((j & 0x55555555) << 1)); j = (((j & 0xcccccccc) >> 2) | ((j & 0x33333333) << 2)); j = (((j & 0xf0f0f0f0) >> 4) | ((j & 0x0f0f0f0f) << 4)); j = (((j & 0xff00ff00) >> 8) | ((j & 0x00ff00ff) << 8)); j = ((j >> 16) | (j << 16)) >> (32 - m); if(j > i){ swap0 = complexVector[i][0]; swap1 = complexVector[i][1]; complexVector[i][0] = complexVector[j][0]; complexVector[i][1] = complexVector[j][1]; complexVector[j][0] = swap0; complexVector[j][1] = swap1; } } } /// \todo Add description. Add tests template<typename T> INLINE void ifft(std::vector< std::vector<T> > &complexVector){ const std::size_t length = complexVector.size(); const double doubleTypeLength = (double) length; conjugate(complexVector); fft(complexVector); conjugate(complexVector); for(std::size_t i = 0; i < length; ++i){ complexVector[i][0] /= doubleTypeLength; complexVector[i][1] /= doubleTypeLength; } } /// \} End of MathFunctions Group /// \defgroup TimeFunctions Time Functions /// \brief Functions providing methods to measure time /// \details Group of functions that is in help when you need to measure /// execution time of some code section /// \{ /// \fn std::chrono::high_resolution_clock::time_point time(); /// \brief Returns current time point /// \details This function returns current time point using std::chrono /// \return std::chrono::high_resolution_clock entity /// \todo Add tests INLINE std::chrono::high_resolution_clock::time_point time(){ return std::chrono::high_resolution_clock::now(); } /// \fn double duration(const /// std::chrono::high_resolution_clock::time_point start, const /// std::chrono::high_resolution_clock::time_point finish, const /// std::string scale = std::string("ms")); /// \brief Returns the difference between two time points /// \details This function returns the difference between two time points /// in hours, minutes, seconds, milliseconds, microseconds or nanoseconds /// using std::chrono (handy to measure functions and code blocks) /// \param start Time point /// \param finish Time point /// \param scale Optional. By default function will return difference in /// milliseconds. Set \p scale to "h" for hours, "m" for minutes, "s" for /// seconds, "us" for microseconds, "ns" for nanoseconds /// \return Difference between points /// \todo Add tests INLINE double duration( const std::chrono::high_resolution_clock::time_point start, const std::chrono::high_resolution_clock::time_point finish, const std::string scale = std::string("ms") ){ if(std::string("h") == scale){ return (double) std::chrono::duration_cast <std::chrono::hours> (finish - start).count(); } if(std::string("m") == scale){ return (double) std::chrono::duration_cast <std::chrono::minutes> (finish - start).count(); } if(std::string("s") == scale){ return (double) std::chrono::duration_cast <std::chrono::seconds> (finish - start).count(); } if(std::string("us") == scale){ return (double) std::chrono::duration_cast <std::chrono::microseconds> (finish - start).count(); } if(std::string("ns") == scale){ return (double) std::chrono::duration_cast <std::chrono::nanoseconds> (finish - start).count(); } return (double) std::chrono::duration_cast <std::chrono::milliseconds> (finish - start).count(); } /// \todo Add tests. Add description INLINE double duration( const std::chrono::high_resolution_clock::time_point start, const std::string scale = std::string("ms") ){ return ai::duration(start, ai::time(), scale); } /// \todo Add tests. Add description INLINE void printDuration( const std::chrono::high_resolution_clock::time_point start, const std::chrono::high_resolution_clock::time_point finish, const std::string scale = std::string("ms"), const std::size_t count = 0 ){ std::cout << "Timer #" << counter(count) << ": " << ai::duration(start, finish, scale) << scale << std::endl; } /// \todo Add tests. Add description INLINE void printDuration( const std::chrono::high_resolution_clock::time_point start, const std::string scale = std::string("ms"), const std::size_t count = 0 ){ std::chrono::high_resolution_clock::time_point finish = ai::time(); ai::printDuration(start, finish, scale, count); } /// \todo Add description. Add tests INLINE std::string getDateAndTime( std::chrono::system_clock::time_point timePoint = std::chrono::system_clock::now() ){ std::time_t date = std::chrono::system_clock::to_time_t(timePoint); std::ostringstream stream; stream << std::put_time(std::localtime(&date), "%F %T"); return stream.str(); } /// \todo Add description. Add tests INLINE std::string getDate( std::chrono::system_clock::time_point timePoint = std::chrono::system_clock::now() ){ std::time_t date = std::chrono::system_clock::to_time_t(timePoint); std::ostringstream stream; stream << std::put_time(std::localtime(&date), "%F"); return stream.str(); } /// \todo Add description. Add tests INLINE std::string getTime( std::chrono::system_clock::time_point timePoint = std::chrono::system_clock::now() ){ std::time_t date = std::chrono::system_clock::to_time_t(timePoint); std::ostringstream stream; stream << std::put_time(std::localtime(&date), "%T"); return stream.str(); } /// \} End of TimeFunctions Group /// \defgroup ParameterFunctions Parameter Functions /// \brief Functions providing methods to parse and assign parameters /// \details Group of functions that is useful to parse parameters (e.g., /// from command line) and assign its values to your variables /// \{ /// \todo Add description. Add tests INLINE std::string parseParameter( const char *input, const std::string name ){ std::string parameter(input); if(hasPrefix(parameter, name)){ parameter = parameter.substr(name.size()); return parameter; } return NULL; } /// \todo Add description. Add tests template<typename T> INLINE void assignFromVectorByIntervalCondition( T &value, const T parameter, const std::vector< std::vector<T> > intervals ){ for(std::size_t i = 0; i < intervals.size(); ++i){ if(intervals[i][0] <= parameter && parameter <= intervals[i][1]){ value = intervals[i][2]; return; } } } /// \todo Add description. Add tests template<typename T> INLINE void assignFromVectorByIntervalCondition( T &firstValue, T &secondValue, const T parameter, const std::vector< std::vector<T> > intervals ){ for(std::size_t i = 0; i < intervals.size(); ++i){ if(intervals[i][0] <= parameter && parameter <= intervals[i][1]){ firstValue = intervals[i][1]; secondValue = intervals[i][2]; return; } } } /// \todo Add description. Add tests INLINE bool assignBooleanParameter( const char *input, const std::string name, bool &value ){ if(name == std::string(input)){ value = true; return true; } return false; } /// \todo Add description. Add tests INLINE bool assignCharParameter( const char *input, const std::string name, char &value ){ std::string parameter = std::string(input); if(ai::hasPrefix(parameter, name)){ parameter = parameter.substr(name.size()); if(std::string() != parameter){ value = (char) parameter[0]; }else{ value = ' '; } return true; } return false; } /// \todo Add description. Add tests INLINE bool assignStringParameter( const char *input, const std::string name, std::string &value ){ std::string parameter = std::string(input); if(ai::hasPrefix(parameter, name)){ value = parameter.substr(name.size()); return true; } return false; } /// \todo Add description. Add tests template<typename T> INLINE bool assignParameter( const char *input, const std::string name, T &value ){ std::string parameter = std::string(input); if(ai::hasPrefix(parameter, name)){ parameter = parameter.substr(name.size()); if(std::istringstream(parameter) >> value){ return true; } } return false; } /// \todo Add description. Add tests INLINE bool assignAbsDoubleParameter( const char *input, const std::string name, double &value ){ std::string parameter = std::string(input); if(ai::hasPrefix(parameter, name)){ parameter = parameter.substr(name.size()); value = std::abs(strtod(parameter.c_str(), nullptr)); return true; } return false; } /// \todo Add description. Add tests template<typename T> INLINE bool assignByCheckingParameter( const char *input, const std::string parameter, T &value, const T supposed ){ if(ai::equal(input, parameter)){ value = supposed; return true; } return false; } /// \} End of ParameterFunctions Group /// \defgroup InterfaceFunctions Interface Functions /// \brief Functions providing some style to your console output /// \details Group of functions that animate your console with a style-ish /// interface /// \{ /// \fn void showProgressBar(double progress, const std::size_t /// screenWidth = 80); /// \brief Prints a simple progress-bar to stdout /// \details This function prints a simple progress-bar to stdout /// \param progress Number from 0 to 1 to /// \param screenWidth Optional. The maximum length of the progress-bar in /// the symbols. Default is 80, should be at least 20 /// \exception std::runtime_error If \p screenWidth is less than 20 INLINE void showProgressBar( double progress, const int screenWidth = 80 ){ if(1 < progress){ progress = 1; } if(0.01 > progress){ progress = 0; } if(20 > screenWidth){ throw std::runtime_error( ai::string("Screen width should be at least 20 (not ") + ai::string(screenWidth) + ai::string(")") ); } const std::size_t barWidth = screenWidth - 7; int width = progress * barWidth; std::cout << std::fixed; std::cout.precision(1); std::cout.flush(); std::cout << "\r" << std::string(width, '=') << std::string(barWidth - width, '-') << " " << progress * 100. << "%"; } /// \fn void printLine(const std::string line, const std::size_t /// screenWidth = 80); /// \brief Prints a line with specified width /// \details This function prints a line with specified width. Can be /// useful to print output when progress-bar is displayed (function /// showProgressBar()). /// \param line Text to print /// \param screenWidth Optional. The maximum length of the progress-bar in /// the symbols. Default is 80, should be at least 20 /// \exception std::runtime_error If \p screenWidth is less than 20 INLINE void printLine( const std::string line, const int screenWidth = 80 ){ if(20 > screenWidth){ throw std::runtime_error( ai::string("Screen width should be at least 20 (not ") + ai::string(screenWidth) + ai::string(")") ); } std::cout << "\r" << std::setw(screenWidth) << std::left << line << std::endl; } /// \} End of InterfaceFunctions Group /// \defgroup ReadFunctions Read Functions /// \brief Functions providing the ability to read your data /// \details Group of functions that reads files and writes its content /// into your variables /// \{ /// \todo Add description. Add tests template<typename T> INLINE void parseFileInMatrix( const std::string filename, const char separator, std::vector< std::vector<T> > &matrix ){ std::ifstream input(filename); if(!input.good()){ throw std::runtime_error( ai::string("Exception while parsing the file into a matrix: ") + filename ); } std::string token; T value; for(std::string line; std::getline(input, line);){ if('#' == line[0]){ continue; } std::istringstream stream(line); std::vector<T> row; while(std::getline(stream, token, separator)){ if(std::istringstream(token) >> value){ row.push_back(value); } } matrix.push_back(row); } input.close(); } /// \todo Add description. Add tests template<typename T> INLINE void parseFileInVector( const std::string filename, const char separator, std::vector<T> &vector ){ std::ifstream input(filename); if(!input.good()){ throw std::runtime_error( ai::string("Exception while parsing the file into a vector: ") + filename ); } std::string token; T value; if('\n' == separator){ for(std::string line; std::getline(input, line);){ if('#' == line[0]){ continue; } if(std::istringstream(line) >> value){ vector.push_back(value); } } }else{ std::string line; std::getline(input, line); std::istringstream stream(line); while(std::getline(stream, token, separator)){ if(std::istringstream(token) >> value){ vector.push_back(value); } } } input.close(); } /// \todo Add description. Add tests INLINE void parseFileIntoString( const std::string filename, std::string &content ){ std::ifstream input(filename); if(!input.good()){ throw std::runtime_error( ai::string("Exception while parsing the file into a string: ") + filename ); } std::ostringstream stream; stream << input.rdbuf(); content = stream.str(); input.close(); } /// \todo Add description. Add tests template<typename T> INLINE void accumulateFileInMatrix( const std::string filename, const char separator, std::vector< std::vector<T> > &matrix ){ std::vector< std::vector<T> > matrixToAdd; ai::parseFileInMatrix(filename, separator, matrixToAdd); for(std::size_t i = 0; i < matrix.size(); ++i){ std::transform( matrix[i].begin(), matrix[i].end(), matrixToAdd[i].begin(), matrix[i].begin(), std::plus<T>() ); } } /// \todo Add description. Add tests template<typename T> INLINE void accumulateFileInVector( const std::string filename, const char separator, std::vector<T> &vector, const bool checkForNaN = false ){ std::vector<T> vectorToAdd; ai::parseFileInVector(filename, separator, vectorToAdd); std::transform( vector.begin(), vector.end(), vectorToAdd.begin(), vector.begin(), std::plus<T>() ); } /// \} End of ReadFunctions Group /// \defgroup PrintFunctions Print Functions /// \brief Functions providing the ability to print your data /// \details Group of functions that prints your data and its parameters /// for quick analysis /// \{ /// \todo Add description. Add tests template<typename T> INLINE void printMatrix( const std::vector<std::vector <T> > &matrix, const bool transpose = false, const int precision = 5 ){ if(1 > matrix.size()){ throw std::runtime_error( ai::string("Exception while printing the matrix: ") + ai::string("size should be at least 1.") ); } std::cout << std::scientific; std::cout.precision(precision); std::cout << "Matrix[" << matrix.size() << "x" << matrix[0].size() << "] = {" << std::endl; if(transpose){ for(std::size_t j = 0; j < matrix[0].size(); ++j){ const std::size_t lastIndex = matrix.size() - 1; for(std::size_t i = 0; i < lastIndex; ++i){ std::cout << matrix[i][j] << ", "; } std::cout << matrix[lastIndex][j] << std::endl; } }else{ for(std::size_t i = 0; i < matrix.size(); ++i){ const std::size_t lastIndex = matrix[i].size() - 1; for(std::size_t j = 0; j < lastIndex; ++j){ std::cout << matrix[i][j] << ", "; } std::cout << matrix[i][lastIndex] << std::endl; } } std::cout << "}[" << matrix.size() << "x" << matrix[0].size() << "]" << std::endl; } /// \todo Add description. Add tests template<typename T> INLINE void printVector( const std::vector<T> &vector, const int precision = 5 ){ if(1 > vector.size()){ throw std::runtime_error( ai::string("Exception while printing the vector: ") + ai::string("size should be at least 1.") ); } std::size_t lastIndex = vector.size() - 1; std::cout << std::scientific; std::cout.precision(precision); std::cout << "Vector[" << vector.size() << "] = {" << std::endl; for(std::size_t i = 0; i < lastIndex; ++i){ std::cout << vector[i] << ", "; } std::cout << vector[lastIndex] << std::endl; std::cout << "}[" << vector.size() << "]" << std::endl; } /// \} End of PrintFunctions Group /// \defgroup SaveFunctions Save Functions /// \brief Functions providing the ability to save your data /// \details Group of functions that will make saving data much easier /// by supporting various formats and styles /// \{ /// \todo Add description. Add tests template<typename T> INLINE void saveMatrix( const std::string filename, const std::vector<std::vector <T> > &matrix, std::string comment = std::string(), const bool transpose = false, std::string type = std::string("text"), std::string delimiter = std::string(" "), const std::size_t tokenWidth = 14 ){ std::string extension("_m.txt"); std::string prefix(""); std::string suffix(""); if(std::string("wolfram") == type){ extension = std::string("_m.wm"); prefix = std::string("{"); delimiter = std::string(", "); suffix = std::string("}"); } if(std::string("excel") == type){ extension = std::string("_m.csv"); delimiter = std::string("; "); } if(std::string("data") == type){ extension = std::string("_m.dat"); delimiter = std::string("\t"); } std::ofstream output(filename + extension); if(!output.good()){ throw std::runtime_error( ai::string("Exception while saving the matrix into the file: ") + filename ); } if(std::string() != comment){ output << comment << std::endl; } output << prefix; if(transpose){ for(std::size_t j = 0; j < matrix[0].size(); ++j){ output << prefix; const std::size_t lastIndex = matrix.size() - 1; for(std::size_t i = 0; i < lastIndex; ++i){ output << std::setw(tokenWidth) << matrix[i][j] << delimiter; } output << std::setw(tokenWidth) << matrix[lastIndex][j] << suffix << std::endl; } }else{ for(std::size_t i = 0; i < matrix.size(); ++i){ output << prefix; const std::size_t lastIndex = matrix[i].size() - 1; for(std::size_t j = 0; j < lastIndex; ++j){ output << std::setw(tokenWidth) << matrix[i][j] << delimiter; } output << std::setw(tokenWidth) << matrix[i][lastIndex] << suffix << std::endl; } } output << suffix; output.close(); } /// \todo Add description. Add tests template<typename T> INLINE void saveVector( const std::string filename, const std::vector<T> &vector, std::string comment = std::string(), std::string type = std::string("text"), std::string delimiter = std::string("\n") ){ std::string extension("_v.txt"); std::string prefix(""); std::string suffix(""); if(std::string("wolfram") == type){ extension = std::string("_v.wm"); prefix = std::string("{"); delimiter = std::string(", "); suffix = std::string("}"); } if(std::string("excel") == type){ extension = std::string("_v.csv"); delimiter = std::string("; "); } if(std::string("data") == type){ extension = std::string("_v.dat"); delimiter = std::string("\t"); } std::ofstream output(filename + extension); if(!output.good()){ throw std::runtime_error( ai::string("Exception while saving the vector into the file: ") + filename ); } if(std::string() != comment){ output << comment << std::endl; } output << prefix; const std::size_t lastIndex = vector.size() - 1; for(std::size_t i = 0; i < lastIndex; ++i){ output << vector[i] << delimiter; } output << vector[lastIndex] << suffix; output.close(); } /// \todo Add description. Add tests template<typename T> INLINE void saveLine( const std::string filename, const std::string line, std::string comment = std::string() ){ std::ofstream output(filename + "_l.txt"); if(!output.good()){ throw std::runtime_error( ai::string("Exception while saving the line into the file: ") + filename ); } if(std::string() != comment){ output << comment << "\n"; } output << line << std::endl; output.close(); } /// \todo Add description. Add tests INLINE void saveLog( const std::string filename, std::string log, const bool timestamp = false, const std::string stampSeparator = std::string(" ") ){ std::ofstream output(filename, std::ios_base::app); if(!output.good()){ throw std::runtime_error( ai::string("Exception while saving log into the file: ") + filename ); } if(timestamp){ output << ai::getDateAndTime() << stampSeparator; } output << log << std::endl; output.close(); } /// \todo Add description. Add tests INLINE void saveLog( const std::string filename, std::vector<std::string> &logs, const bool timestamp = false, const std::string stampSeparator = std::string(" ") ){ std::ofstream output(filename, std::ios_base::app); if(!output.good()){ throw std::runtime_error( ai::string("Exception while saving log into the file: ") + filename ); } std::string prefix(""); if(timestamp){ prefix = ai::getDateAndTime() + stampSeparator; } for(std::size_t i = 0; i < logs.size(); ++i){ output << prefix << logs[i] << std::endl; } output.close(); } /// \todo Add description. Add tests template<typename T> INLINE bool loadA3R( const std::string filename, std::vector< std::vector<T> > &positions, double &radius ){ std::ifstream input(filename, std::ios::binary | std::ios::in); if(!input.good()){ throw std::runtime_error( ai::string("Exception while reading positions from the file: ") + filename ); } char numberOfParticlesValue[4]; char startByte[4]; char radiusValue[8]; char value[4]; input.seekg(4); input.read(numberOfParticlesValue, 4); input.read(startByte, 4); input.seekg(24); input.read(radiusValue, 8); input.seekg(reinterpret_cast<int&>(startByte)); radius = reinterpret_cast<double&>(radiusValue); std::size_t numberOfParticles = (std::size_t) reinterpret_cast<int&>( numberOfParticlesValue ); positions.resize(numberOfParticles); for(std::size_t i = 0; i < numberOfParticles; ++i){ positions[i].resize(3); for(std::size_t j = 0; j < 3; ++j){ input.read(value, 4); positions[i][j] = (T) reinterpret_cast<float&>(value); } std::cout << std::endl; } input.close(); return true; } /// \todo Add description. Add tests template<typename T> INLINE bool saveA3R( const std::string filename, const std::vector< std::vector<T> > &positions, const double radius = 1 ){ std::ofstream output( filename + std::string(".a3r"), std::ios::binary | std::ios::out ); if(!output.good()){ throw std::runtime_error( ai::string("Exception while saving positions into the file: ") + filename ); } const std::size_t numberOfParticles = positions.size(); const int integerNumberOfParticles = (int) numberOfParticles; const int startByte = 36; const int futureValue = 0; const int intSize = 4; const int floatSize = 4; const int doubleSize = 8; output.write("a3r\0", 4); output.write((char*) &integerNumberOfParticles, intSize); output.write((char*) &startByte, intSize); output.write("AiLib 1.1.0\0", 12); output.write((char*) &radius, doubleSize); output.write((char*) &futureValue, intSize); if(2 == positions[0].size()){ for(std::size_t i = 0; i < numberOfParticles; ++i){ float x = (float) positions[i][0]; float y = (float) positions[i][1]; float z = 0.; output.write((char*) &x, floatSize); output.write((char*) &y, floatSize); output.write((char*) &z, floatSize); } }else{ if(3 == positions[0].size()){ for(std::size_t i = 0; i < numberOfParticles; ++i){ float x = (float) positions[i][0]; float y = (float) positions[i][1]; float z = (float) positions[i][2]; output.write((char*) &x, floatSize); output.write((char*) &y, floatSize); output.write((char*) &z, floatSize); } }else{ return false; } } output.close(); return true; } /// \see https://en.wikipedia.org/wiki/XYZ_file_format /// \todo Add description. Add tests template<typename T> INLINE void loadXYZ( const std::string filename, std::vector< std::vector<T> > &matrix ){ std::ifstream input(filename); if(!input.good()){ throw std::runtime_error( ai::string("Exception while reading positions from the file: ") + filename ); } std::size_t counter = 0; std::string token; T value; for(std::string line; std::getline(input, line);){ ++counter; if(3 > counter){ continue; } std::istringstream stream(line); std::vector<T> row; std::size_t subCounter = 0; while(std::getline(stream, token, ' ')){ ++subCounter; if(2 > subCounter){ continue; } if(std::istringstream(token) >> value){ row.push_back(value); } } matrix.push_back(row); } input.close(); } /// \todo Add description. Add tests template<typename T> INLINE void saveXYZ( const std::string filename, const std::vector< std::vector<T> > &matrix, const std::vector<T> &tones, std::string elementName = "C" ){ std::ofstream output(filename + std::string(".xyz")); if(!output.good()){ throw std::runtime_error( ai::string("Exception while saving positions into the file: ") + filename ); } const std::size_t numberOfParticles = matrix.size(); bool withColors = (tones.size() == numberOfParticles); output << numberOfParticles << std::endl << std::endl; for(std::size_t i = 0; i < numberOfParticles; ++i){ output << elementName; for(std::size_t j = 0; j < matrix[i].size(); ++j){ output << " " << matrix[i][j]; } if(withColors){ double color = 1. - 2. * tones[i]; if(1. < color){ color = 1.; }else{ if(0. > color){ color = 0.; } } output << " " << color; color = 1. - std::abs(2. * tones[i] - 1.); if(1. < color){ color = 1.; }else{ if(0. > color){ color = 0.; } } output << " " << color; color = 2. * tones[i] - 1.; if(1. < color){ color = 1.; }else{ if(0. > color){ color = 0.; } } output << " " << color; } output << std::endl; } output.close(); } /// \todo Add description. Add tests template<typename T> INLINE void saveXYZ( const std::string filename, const std::vector< std::vector<T> > &matrix, std::string elementName = "C" ){ saveXYZ(filename, matrix, std::vector<T>(), elementName); } /// \} End of SaveFunctions Group /// \defgroup FileFunctions File Functions /// \brief Functions providing the ability to check files and folders /// \details Group of functions that checks and analyzes folders and files /// \{ /// \fn bool folderExists(const std::string name); /// \brief Checks if folder exists /// \details This function checks if the given directory actually /// exists /// \param name Path to the folder /// \return True if folder exists, false otherwise /// \todo Add tests INLINE bool folderExists(const std::string name){ struct stat buffer; return 0 == stat(name.c_str(), &buffer); } /// \todo Add description. Add tests INLINE std::size_t countLinesInFile( const std::string filename, const std::string token = std::string() ){ std::ifstream input(filename); if(!input.good()){ throw std::runtime_error( ai::string("Exception while counting lines in the file: ") + filename ); } std::size_t count = 0; if(std::string() == token){ for(std::string line; getline(input, line);){ ++count; } }else{ for(std::string line; getline(input, line);){ if(std::string::npos != line.find(token)){ ++count; } } } input.close(); return count; } #if defined(AI_DIRENT_SUPPORT) /// \todo Add description. Add tests INLINE std::vector<std::string> listFilesWithExtension( std::string path, const std::string extension, const std::string prefix = std::string(), const bool addPathToFileNames = false ){ DIR *dir; struct dirent *ent; dir = opendir(path.c_str()); std::vector<std::string> files; if(NULL != dir){ while(NULL != (ent = readdir (dir))){ if( DT_REG == ent->d_type && hasSuffix(ent->d_name, extension) ){ files.push_back(prefix + ent->d_name); } } closedir(dir); } if(addPathToFileNames){ path += std::string("/"); for(std::size_t i = 0; i < files.size(); ++i){ files[i] = path + files[i]; } } return files; } #endif /// \} End of FileFunctions Group /// \defgroup ShellFunctions Shell Functions /// \brief Functions providing shell support /// \details Group of functions that will help you to interact with /// shell and other programs /// \{ /// \todo Add description. Add tests INLINE void setLocale(const std::string locale){ if(std::string("en") == ai::toLowerCase(locale)){ std::locale::global(std::locale("en_US.utf8")); }else{ std::locale::global( std::locale( ai::toLowerCase(locale) + ai::string("_") + ai::toUpperCase(locale) + ai::string(".utf8") ) ); } } #if defined(AI_SHELL_SUPPORT) /// \todo Add description. Add tests INLINE std::string execute( const std::string command ){ const std::size_t bufferSize = 128; std::array<char, bufferSize> buffer; std::string result; std::shared_ptr<FILE> pipe(popen(command.c_str(), "r"), pclose); if(!pipe){ throw std::runtime_error( ai::string("Exception while executing the command: ") + command ); } while(!feof(pipe.get())){ if(nullptr != fgets(buffer.data(), bufferSize, pipe.get())){ result += buffer.data(); } } return result; } #endif /// \} End of Shell Functions Group } /// \} End of Main Group #if defined(AI_FUTURE) /// Functions to be added in future releases namespace ai{ /// Still looking for a good cross-platform solution for C++11 INLINE bool createFolder(const std::string name); } #endif #endif
32.075704
80
0.522449
[ "vector", "transform" ]
f340eecf9dd3772cc3c8cbf8b3f8fc3efedf2702
574
cpp
C++
math/matrix.cpp
fiore57/competitive-cpp
b42d29ad01dcf56ba31e397e5d6436b4a3dd9067
[ "WTFPL" ]
1
2020-09-06T12:55:57.000Z
2020-09-06T12:55:57.000Z
math/matrix.cpp
fiore57/competitive-cpp
b42d29ad01dcf56ba31e397e5d6436b4a3dd9067
[ "WTFPL" ]
2
2020-09-06T12:50:48.000Z
2020-09-08T05:38:56.000Z
math/matrix.cpp
fiore57/competitive-cpp
b42d29ad01dcf56ba31e397e5d6436b4a3dd9067
[ "WTFPL" ]
1
2020-09-06T12:36:59.000Z
2020-09-06T12:36:59.000Z
using Vector = vll; using Matrix = vvll; // A * B Matrix matMul(const Matrix &A, const Matrix &B, const int Mod) { Matrix C(A.size(), Vector(B.front().size())); rep(i, A.size()) rep(k, B.size()) rep(j, B.front().size()) C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % Mod; return C; } // A^n Matrix matPow(Matrix A, ll n, const int Mod) { Matrix B(A.size(), Vector(A.size())); rep(i, A.size()) B[i][i] = 1; while (n > 0) { if (n & 1) B = matMul(B, A, Mod); A = matMul(A, A, Mod); n >>= 1; } return B; }
24.956522
72
0.479094
[ "vector" ]
f34495ad4d8dad2042de282325be26f985e2bc1d
21,653
cpp
C++
Blik2D/addon/openalpr-2.3.0_for_blik/src/openalpr/textdetection/characteranalysis.cpp
BonexGu/Blik2D
8e0592787e5c8e8a28682d0e1826b8223eae5983
[ "MIT" ]
13
2017-02-22T02:20:06.000Z
2018-06-06T04:18:03.000Z
Blik2D/addon/openalpr-2.3.0_for_blik/src/openalpr/textdetection/characteranalysis.cpp
BonexGu/Blik2D
8e0592787e5c8e8a28682d0e1826b8223eae5983
[ "MIT" ]
null
null
null
Blik2D/addon/openalpr-2.3.0_for_blik/src/openalpr/textdetection/characteranalysis.cpp
BonexGu/Blik2D
8e0592787e5c8e8a28682d0e1826b8223eae5983
[ "MIT" ]
null
null
null
/* * Copyright (c) 2015 OpenALPR Technology, Inc. * Open source Automated License Plate Recognition [http://www.openalpr.com] * * This file is part of OpenALPR. * * OpenALPR is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License * version 3 as published by the Free Software Foundation * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include BLIK_OPENCV_V_opencv2__imgproc__imgproc_hpp //original-code:<opencv2/imgproc/imgproc.hpp> #include "characteranalysis.h" #include "linefinder.h" using namespace cv; using namespace std; namespace alpr { bool sort_text_line(TextLine i, TextLine j) { return (i.topLine.p1.y < j.topLine.p1.y); } CharacterAnalysis::CharacterAnalysis(PipelineData* pipeline_data) { this->pipeline_data = pipeline_data; this->config = pipeline_data->config; if (this->config->debugCharAnalysis) cout << "Starting CharacterAnalysis identification" << endl; this->analyze(); } CharacterAnalysis::~CharacterAnalysis() { } void CharacterAnalysis::analyze() { timespec startTime; getTimeMonotonic(&startTime); if (config->always_invert) bitwise_not(pipeline_data->crop_gray, pipeline_data->crop_gray); pipeline_data->clearThresholds(); pipeline_data->thresholds = produceThresholds(pipeline_data->crop_gray, config); timespec contoursStartTime; getTimeMonotonic(&contoursStartTime); pipeline_data->textLines.clear(); for (unsigned int i = 0; i < pipeline_data->thresholds.size(); i++) { TextContours tc(pipeline_data->thresholds[i]); allTextContours.push_back(tc); } if (config->debugTiming) { timespec contoursEndTime; getTimeMonotonic(&contoursEndTime); cout << " -- Character Analysis Find Contours Time: " << diffclock(contoursStartTime, contoursEndTime) << "ms." << endl; } //Mat img_equalized = equalizeBrightness(img_gray); timespec filterStartTime; getTimeMonotonic(&filterStartTime); for (unsigned int i = 0; i < pipeline_data->thresholds.size(); i++) { this->filter(pipeline_data->thresholds[i], allTextContours[i]); if (config->debugCharAnalysis) cout << "Threshold " << i << " had " << allTextContours[i].getGoodIndicesCount() << " good indices." << endl; } if (config->debugTiming) { timespec filterEndTime; getTimeMonotonic(&filterEndTime); cout << " -- Character Analysis Filter Time: " << diffclock(filterStartTime, filterEndTime) << "ms." << endl; } PlateMask plateMask(pipeline_data); plateMask.findOuterBoxMask(allTextContours); pipeline_data->hasPlateBorder = plateMask.hasPlateMask; pipeline_data->plateBorderMask = plateMask.getMask(); if (plateMask.hasPlateMask) { // Filter out bad contours now that we have an outer box mask... for (unsigned int i = 0; i < pipeline_data->thresholds.size(); i++) { filterByOuterMask(allTextContours[i]); } } int bestFitScore = -1; int bestFitIndex = -1; for (unsigned int i = 0; i < pipeline_data->thresholds.size(); i++) { int segmentCount = allTextContours[i].getGoodIndicesCount(); if (segmentCount > bestFitScore) { bestFitScore = segmentCount; bestFitIndex = i; bestThreshold = pipeline_data->thresholds[i]; bestContours = allTextContours[i]; } } if (this->config->debugCharAnalysis) cout << "Best fit score: " << bestFitScore << " Index: " << bestFitIndex << endl; if (bestFitScore <= 1) { pipeline_data->disqualified = true; pipeline_data->disqualify_reason = "Low best fit score in characteranalysis"; return; } //getColorMask(img, allContours, allHierarchy, charSegments); if (this->config->debugCharAnalysis) { Mat img_contours = bestContours.drawDebugImage(bestThreshold); displayImage(config, "Matching Contours", img_contours); } if (config->auto_invert) pipeline_data->plate_inverted = isPlateInverted(); else pipeline_data->plate_inverted = config->always_invert; if (config->debugGeneral) cout << "Plate inverted: " << pipeline_data->plate_inverted << endl; // Invert multiline plates and redo the thresholds before finding the second line if (config->multiline && config->auto_invert && pipeline_data->plate_inverted) { bitwise_not(pipeline_data->crop_gray, pipeline_data->crop_gray); pipeline_data->thresholds = produceThresholds(pipeline_data->crop_gray, pipeline_data->config); } LineFinder lf(pipeline_data); vector<vector<Point> > linePolygons = lf.findLines(pipeline_data->crop_gray, bestContours); vector<TextLine> tempTextLines; for (unsigned int i = 0; i < linePolygons.size(); i++) { vector<Point> linePolygon = linePolygons[i]; LineSegment topLine = LineSegment(linePolygon[0].x, linePolygon[0].y, linePolygon[1].x, linePolygon[1].y); LineSegment bottomLine = LineSegment(linePolygon[3].x, linePolygon[3].y, linePolygon[2].x, linePolygon[2].y); vector<Point> textArea = getCharArea(topLine, bottomLine); TextLine textLine(textArea, linePolygon, pipeline_data->crop_gray.size()); tempTextLines.push_back(textLine); } filterBetweenLines(bestThreshold, bestContours, tempTextLines); // Sort the lines from top to bottom. std::sort(tempTextLines.begin(), tempTextLines.end(), sort_text_line); // Now that we've filtered a few more contours, re-do the text area. for (unsigned int i = 0; i < tempTextLines.size(); i++) { vector<Point> updatedTextArea = getCharArea(tempTextLines[i].topLine, tempTextLines[i].bottomLine); vector<Point> linePolygon = tempTextLines[i].linePolygon; if (updatedTextArea.size() > 0 && linePolygon.size() > 0) { pipeline_data->textLines.push_back(TextLine(updatedTextArea, linePolygon, pipeline_data->crop_gray.size())); } } if (pipeline_data->textLines.size() > 0) { int confidenceDrainers = 0; int charSegmentCount = this->bestContours.getGoodIndicesCount(); if (charSegmentCount == 1) confidenceDrainers += 91; else if (charSegmentCount < 5) confidenceDrainers += (5 - charSegmentCount) * 10; // Use the angle for the first line -- assume they'll always be parallel for multi-line plates int absangle = abs(pipeline_data->textLines[0].topLine.angle); if (absangle > config->maxPlateAngleDegrees) confidenceDrainers += 91; else if (absangle > 1) confidenceDrainers += absangle ; // If a multiline plate has only one line, disqualify if (pipeline_data->isMultiline && pipeline_data->textLines.size() < 2) { if (config->debugCharAnalysis) std::cout << "Did not detect multiple lines on multi-line plate" << std::endl; confidenceDrainers += 95; } if (confidenceDrainers >= 90) { pipeline_data->disqualified = true; pipeline_data->disqualify_reason = "Low confidence in characteranalysis"; } else { float confidence = 100 - confidenceDrainers; pipeline_data->confidence_weights.setScore("CHARACTER_ANALYSIS_SCORE", confidence, 1.0); } } else { pipeline_data->disqualified = true; pipeline_data->disqualify_reason = "No text lines found in characteranalysis"; } if (config->debugTiming) { timespec endTime; getTimeMonotonic(&endTime); cout << "Character Analysis Time: " << diffclock(startTime, endTime) << "ms." << endl; } // Draw debug dashboard if (this->pipeline_data->config->debugCharAnalysis && pipeline_data->textLines.size() > 0) { vector<Mat> tempDash; for (unsigned int z = 0; z < pipeline_data->thresholds.size(); z++) { Mat tmp(pipeline_data->thresholds[z].size(), pipeline_data->thresholds[z].type()); pipeline_data->thresholds[z].copyTo(tmp); cvtColor(tmp, tmp, CV_GRAY2BGR); tempDash.push_back(tmp); } Mat bestVal(this->bestThreshold.size(), this->bestThreshold.type()); this->bestThreshold.copyTo(bestVal); cvtColor(bestVal, bestVal, CV_GRAY2BGR); for (unsigned int z = 0; z < this->bestContours.size(); z++) { Scalar dcolor(255,0,0); if (this->bestContours.goodIndices[z]) dcolor = Scalar(0,255,0); drawContours(bestVal, this->bestContours.contours, z, dcolor, 1); } tempDash.push_back(bestVal); displayImage(config, "Character Region Step 1 Thresholds", drawImageDashboard(tempDash, bestVal.type(), 3)); } } Mat CharacterAnalysis::getCharacterMask() { Mat charMask = Mat::zeros(bestThreshold.size(), CV_8U); for (unsigned int i = 0; i < bestContours.size(); i++) { if (bestContours.goodIndices[i] == false) continue; drawContours(charMask, bestContours.contours, i, // draw this contour cv::Scalar(255,255,255), // in CV_FILLED, 8, bestContours.hierarchy, 1 ); } return charMask; } void CharacterAnalysis::filter(Mat img, TextContours& textContours) { int STARTING_MIN_HEIGHT = round (((float) img.rows) * config->charAnalysisMinPercent); int STARTING_MAX_HEIGHT = round (((float) img.rows) * (config->charAnalysisMinPercent + config->charAnalysisHeightRange)); int HEIGHT_STEP = round (((float) img.rows) * config->charAnalysisHeightStepSize); int NUM_STEPS = config->charAnalysisNumSteps; int bestFitScore = -1; vector<bool> bestIndices; for (int i = 0; i < NUM_STEPS; i++) { //vector<bool> goodIndices(contours.size()); for (unsigned int z = 0; z < textContours.size(); z++) textContours.goodIndices[z] = true; this->filterByBoxSize(textContours, STARTING_MIN_HEIGHT + (i * HEIGHT_STEP), STARTING_MAX_HEIGHT + (i * HEIGHT_STEP)); int goodIndices = textContours.getGoodIndicesCount(); if ( goodIndices == 0 || goodIndices <= bestFitScore) // Don't bother doing more filtering if we already lost... continue; this->filterContourHoles(textContours); goodIndices = textContours.getGoodIndicesCount(); if ( goodIndices == 0 || goodIndices <= bestFitScore) // Don't bother doing more filtering if we already lost... continue; int segmentCount = textContours.getGoodIndicesCount(); if (segmentCount > bestFitScore) { bestFitScore = segmentCount; bestIndices = textContours.getIndicesCopy(); } } textContours.setIndices(bestIndices); } // Goes through the contours for the plate and picks out possible char segments based on min/max height void CharacterAnalysis::filterByBoxSize(TextContours& textContours, int minHeightPx, int maxHeightPx) { // For multiline plates, we want to target the biggest line for character analysis, since it should be easier to spot. float larger_char_height_mm = 0; float larger_char_width_mm = 0; for (unsigned int i = 0; i < config->charHeightMM.size(); i++) { if (config->charHeightMM[i] > larger_char_height_mm) { larger_char_height_mm = config->charHeightMM[i]; larger_char_width_mm = config->charWidthMM[i]; } } float idealAspect=larger_char_width_mm / larger_char_height_mm; float aspecttolerance=0.25; for (unsigned int i = 0; i < textContours.size(); i++) { if (textContours.goodIndices[i] == false) continue; textContours.goodIndices[i] = false; // Set it to not included unless it proves valid //Create bounding rect of object Rect mr= boundingRect(textContours.contours[i]); float minWidth = mr.height * 0.2; //Crop image //cout << "Height: " << minHeightPx << " - " << mr.height << " - " << maxHeightPx << " ////// Width: " << mr.width << " - " << minWidth << endl; if(mr.height >= minHeightPx && mr.height <= maxHeightPx && mr.width > minWidth) { float charAspect= (float)mr.width/(float)mr.height; //cout << " -- stage 2 aspect: " << abs(charAspect) << " - " << aspecttolerance << endl; if (abs(charAspect - idealAspect) < aspecttolerance) textContours.goodIndices[i] = true; } } } void CharacterAnalysis::filterContourHoles(TextContours& textContours) { for (unsigned int i = 0; i < textContours.size(); i++) { if (textContours.goodIndices[i] == false) continue; textContours.goodIndices[i] = false; // Set it to not included unless it proves valid int parentIndex = textContours.hierarchy[i][3]; if (parentIndex >= 0 && textContours.goodIndices[parentIndex]) { // this contour is a child of an already identified contour. REMOVE it if (this->config->debugCharAnalysis) { cout << "filterContourHoles: contour index: " << i << endl; } } else { textContours.goodIndices[i] = true; } } } // Goes through the contours for the plate and picks out possible char segments based on min/max height // returns a vector of indices corresponding to valid contours void CharacterAnalysis::filterByParentContour( TextContours& textContours) { vector<int> parentIDs; vector<int> votes; for (unsigned int i = 0; i < textContours.size(); i++) { if (textContours.goodIndices[i] == false) continue; textContours.goodIndices[i] = false; // Set it to not included unless it proves int voteIndex = -1; int parentID = textContours.hierarchy[i][3]; // check if parentID is already in the lsit for (unsigned int j = 0; j < parentIDs.size(); j++) { if (parentIDs[j] == parentID) { voteIndex = j; break; } } if (voteIndex == -1) { parentIDs.push_back(parentID); votes.push_back(1); } else { votes[voteIndex] = votes[voteIndex] + 1; } } // Tally up the votes, pick the winner int totalVotes = 0; int winningParentId = 0; int highestVotes = 0; for (unsigned int i = 0; i < parentIDs.size(); i++) { if (votes[i] > highestVotes) { winningParentId = parentIDs[i]; highestVotes = votes[i]; } totalVotes += votes[i]; } // Now filter out all the contours with a different parent ID (assuming the totalVotes > 2) for (unsigned int i = 0; i < textContours.size(); i++) { if (textContours.goodIndices[i] == false) continue; if (totalVotes <= 2) { textContours.goodIndices[i] = true; } else if (textContours.hierarchy[i][3] == winningParentId) { textContours.goodIndices[i] = true; } } } void CharacterAnalysis::filterBetweenLines(Mat img, TextContours& textContours, vector<TextLine> textLines ) { static float MIN_AREA_PERCENT_WITHIN_LINES = 0.88; static float MAX_DISTANCE_PERCENT_FROM_LINES = 0.15; if (textLines.size() == 0) return; vector<Point> validPoints; // Create a white mask for the area inside the polygon Mat outerMask = Mat::zeros(img.size(), CV_8U); for (unsigned int i = 0; i < textLines.size(); i++) fillConvexPoly(outerMask, textLines[i].linePolygon.data(), textLines[i].linePolygon.size(), Scalar(255,255,255)); // For each contour, determine if enough of it is between the lines to qualify for (unsigned int i = 0; i < textContours.size(); i++) { if (textContours.goodIndices[i] == false) continue; float percentInsideMask = getContourAreaPercentInsideMask(outerMask, textContours.contours, textContours.hierarchy, (int) i); if (percentInsideMask < MIN_AREA_PERCENT_WITHIN_LINES) { // Not enough area is inside the lines. if (config->debugCharAnalysis) cout << "Rejecting due to insufficient area" << endl; textContours.goodIndices[i] = false; continue; } // now check to make sure that the top and bottom of the contour are near enough to the lines // First get the high and low point for the contour // Remember that origin is top-left, so the top Y values are actually closer to 0. Rect brect = boundingRect(textContours.contours[i]); int xmiddle = brect.x + (brect.width / 2); Point topMiddle = Point(xmiddle, brect.y); Point botMiddle = Point(xmiddle, brect.y+brect.height); // Get the absolute distance from the top and bottom lines for (unsigned int i = 0; i < textLines.size(); i++) { Point closestTopPoint = textLines[i].topLine.closestPointOnSegmentTo(topMiddle); Point closestBottomPoint = textLines[i].bottomLine.closestPointOnSegmentTo(botMiddle); float absTopDistance = distanceBetweenPoints(closestTopPoint, topMiddle); float absBottomDistance = distanceBetweenPoints(closestBottomPoint, botMiddle); float maxDistance = textLines[i].lineHeight * MAX_DISTANCE_PERCENT_FROM_LINES; if (absTopDistance < maxDistance && absBottomDistance < maxDistance) { // It's ok, leave it as-is. } else { textContours.goodIndices[i] = false; if (config->debugCharAnalysis) cout << "Rejecting due to top/bottom points that are out of range" << endl; } } } } void CharacterAnalysis::filterByOuterMask(TextContours& textContours) { float MINIMUM_PERCENT_LEFT_AFTER_MASK = 0.1; float MINIMUM_PERCENT_OF_CHARS_INSIDE_PLATE_MASK = 0.6; if (this->pipeline_data->hasPlateBorder == false) return; cv::Mat plateMask = pipeline_data->plateBorderMask; Mat tempMaskedContour = Mat::zeros(plateMask.size(), CV_8U); Mat tempFullContour = Mat::zeros(plateMask.size(), CV_8U); int charsInsideMask = 0; int totalChars = 0; vector<bool> originalindices; for (unsigned int i = 0; i < textContours.size(); i++) originalindices.push_back(textContours.goodIndices[i]); for (unsigned int i=0; i < textContours.size(); i++) { if (textContours.goodIndices[i] == false) continue; totalChars++; tempFullContour = Mat::zeros(plateMask.size(), CV_8U); drawContours(tempFullContour, textContours.contours, i, Scalar(255,255,255), CV_FILLED, 8, textContours.hierarchy); bitwise_and(tempFullContour, plateMask, tempMaskedContour); textContours.goodIndices[i] = false; float beforeMaskWhiteness = mean(tempFullContour)[0]; float afterMaskWhiteness = mean(tempMaskedContour)[0]; if (afterMaskWhiteness / beforeMaskWhiteness > MINIMUM_PERCENT_LEFT_AFTER_MASK) { charsInsideMask++; textContours.goodIndices[i] = true; } } if (totalChars == 0) { textContours.goodIndices = originalindices; return; } // Check to make sure that this is a valid box. If the box is too small (e.g., 1 char is inside, and 3 are outside) // then don't use this to filter. float percentCharsInsideMask = ((float) charsInsideMask) / ((float) totalChars); if (percentCharsInsideMask < MINIMUM_PERCENT_OF_CHARS_INSIDE_PLATE_MASK) { textContours.goodIndices = originalindices; return; } } bool CharacterAnalysis::isPlateInverted() { Mat charMask = getCharacterMask(); Scalar meanVal = mean(bestThreshold, charMask)[0]; if (this->config->debugCharAnalysis) cout << "CharacterAnalysis, plate inverted: MEAN: " << meanVal << " : " << bestThreshold.type() << endl; if (meanVal[0] < 100) // Half would be 122.5. Give it a little extra oomf before saying it needs inversion. Most states aren't inverted. return true; return false; } vector<Point> CharacterAnalysis::getCharArea(LineSegment topLine, LineSegment bottomLine) { const int MAX = 100000; const int MIN= -1; int leftX = MAX; int rightX = MIN; for (unsigned int i = 0; i < bestContours.size(); i++) { if (bestContours.goodIndices[i] == false) continue; for (unsigned int z = 0; z < bestContours.contours[i].size(); z++) { if (bestContours.contours[i][z].x < leftX) leftX = bestContours.contours[i][z].x; if (bestContours.contours[i][z].x > rightX) rightX = bestContours.contours[i][z].x; } } vector<Point> charArea; if (leftX != MAX && rightX != MIN) { Point tl(leftX, topLine.getPointAt(leftX)); Point tr(rightX, topLine.getPointAt(rightX)); Point br(rightX, bottomLine.getPointAt(rightX)); Point bl(leftX, bottomLine.getPointAt(leftX)); charArea.push_back(tl); charArea.push_back(tr); charArea.push_back(br); charArea.push_back(bl); } return charArea; } }
31.702782
150
0.647254
[ "object", "vector" ]
f3462af7a12aaf61e2c82b2d4946285780f482b4
2,957
cpp
C++
test/regex.cpp
ioperations/patterns
01e66f044652f582650b5e27849d9e18fe46f5dc
[ "BSL-1.0" ]
null
null
null
test/regex.cpp
ioperations/patterns
01e66f044652f582650b5e27849d9e18fe46f5dc
[ "BSL-1.0" ]
null
null
null
test/regex.cpp
ioperations/patterns
01e66f044652f582650b5e27849d9e18fe46f5dc
[ "BSL-1.0" ]
null
null
null
// MPark.Patterns // // Copyright Michael Park, 2017 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.md or copy at // http://boost.org/LICENSE_1_0.txt) #include <gtest/gtest.h> #include <mpark/patterns.hpp> #include <regex> #include <sstream> #include <string> #include <string_view> #include <tuple> #include <utility> #include <vector> struct Token { enum Kind { ID, NUM, OP, WS }; Token(Kind kind_, std::string lexeme_) : kind(kind_), lexeme(std::move(lexeme_)) {} Kind kind; std::string lexeme; }; bool operator==(const Token &lhs, const Token &rhs) { return std::tie(lhs.kind, lhs.lexeme) == std::tie(rhs.kind, rhs.lexeme); } bool operator!=(const Token &lhs, const Token &rhs) { return !(lhs == rhs); } TEST(Regex, String) { auto lex = [](std::string_view sv) { using namespace mpark::patterns; return match(sv)( pattern(arg(re.match(R"~([_a-zA-Z]\w*)~"))) = [](auto lexeme) { return Token(Token::ID, std::string(lexeme)); }, pattern(arg(re.match(R"~(-?\d+)~"))) = [](auto lexeme) { return Token(Token::NUM, std::string(lexeme)); }, pattern(arg(re.match(R"~([*|/|+|-])~"))) = [](auto lexeme) { return Token(Token::OP, std::string(lexeme)); }); }; EXPECT_EQ(lex("foobar"), Token(Token::ID, "foobar")); EXPECT_EQ(lex("x"), Token(Token::ID, "x")); EXPECT_EQ(lex("x0"), Token(Token::ID, "x0")); EXPECT_EQ(lex("42"), Token(Token::NUM, "42")); EXPECT_EQ(lex("101"), Token(Token::NUM, "101")); EXPECT_EQ(lex("-202"), Token(Token::NUM, "-202")); EXPECT_EQ(lex("*"), Token(Token::OP, "*")); EXPECT_EQ(lex("/"), Token(Token::OP, "/")); EXPECT_EQ(lex("+"), Token(Token::OP, "+")); EXPECT_EQ(lex("-"), Token(Token::OP, "-")); } TEST(Regex, Stream) { std::regex id(R"~([_a-zA-Z]\w*)~"); std::regex num(R"~(-?\d+)~"); std::regex op(R"~([*|/|+|-])~"); std::istringstream strm("foo + -42 - x * 101 / bar"); std::vector<Token> expected = { {Token::ID, "foo"}, {Token::OP, "+"}, {Token::NUM, "-42"}, {Token::OP, "-"}, {Token::ID, "x"}, {Token::OP, "*"}, {Token::NUM, "101"}, {Token::OP, "/"}, {Token::ID, "bar"}}; std::vector<Token> actual; for (std::string token; strm >> token;) { using namespace mpark::patterns; actual.push_back(match(token)( pattern(arg(re.match(id))) = [](const auto &lexeme) { return Token(Token::ID, lexeme); }, pattern(arg(re.match(num))) = [](const auto &lexeme) { return Token(Token::NUM, lexeme); }, pattern(arg(re.match(op))) = [](const auto &lexeme) { return Token(Token::OP, lexeme); })); } EXPECT_EQ(expected, actual); }
31.457447
78
0.528238
[ "vector" ]
f34a855355277d903d852fe332b5f6f08696403c
5,513
hpp
C++
include/lbann/execution_algorithms/kfac/kfac_block_bn.hpp
aj-prime/lbann
a4cf81386b3f43586057b5312192e180b1259add
[ "Apache-2.0" ]
null
null
null
include/lbann/execution_algorithms/kfac/kfac_block_bn.hpp
aj-prime/lbann
a4cf81386b3f43586057b5312192e180b1259add
[ "Apache-2.0" ]
null
null
null
include/lbann/execution_algorithms/kfac/kfac_block_bn.hpp
aj-prime/lbann
a4cf81386b3f43586057b5312192e180b1259add
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2014-2019, Lawrence Livermore National Security, LLC. // Produced at the Lawrence Livermore National Laboratory. // Written by the LBANN Research Team (B. Van Essen, et al.) listed in // the CONTRIBUTORS file. <lbann-dev@llnl.gov> // // LLNL-CODE-697807. // All rights reserved. // // This file is part of LBANN: Livermore Big Artificial Neural Network // Toolkit. For details, see http://software.llnl.gov/LBANN or // https://github.com/LLNL/LBANN. // // Licensed under the Apache License, Version 2.0 (the "Licensee"); 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. //////////////////////////////////////////////////////////////////////////////// #ifndef LBANN_EXECUTION_ALGORITHMS_KFAC_KFAC_BLOCK_BN_HPP_INCLUDED #define LBANN_EXECUTION_ALGORITHMS_KFAC_KFAC_BLOCK_BN_HPP_INCLUDED #include "lbann/execution_algorithms/kfac/kfac_block.hpp" #include "lbann/layers/learning/fully_connected.hpp" #include "lbann/layers/learning/convolution.hpp" namespace lbann { namespace kfac_bn_util { /** @brief The memory copy part of compute_bn_factor. Combined with * GEMM. **/ template <El::Device Device> void compute_bn_factor_data2col( const El::Matrix<DataType, Device>& activations, const El::Matrix<DataType, Device>& errors, const El::Matrix<DataType, Device>& scales, const El::Matrix<DataType, Device>& biases, El::Matrix<DataType, Device>& cols, size_t batch_size, size_t num_channels, size_t spatial_prod, const El::SyncInfo<Device>& sync_info); } // namespace kfac_bn_util /** A BN building block for K-FAC. */ template <El::Device Device> class kfac_block_bn: public kfac_block<Device> { public: /** Constructor. */ kfac_block_bn(Layer* layer, kfac::ExecutionContext* context, size_t layer_id, size_t inverse_proc_rank) : kfac_block<Device>(layer, context, layer_id, inverse_proc_rank) { const auto parent = layer->get_parent_layers()[0]; const bool is_after_fc = (dynamic_cast<const fully_connected_layer<DataType, data_layout::DATA_PARALLEL, Device>*>(parent) != nullptr); m_is_after_conv = (dynamic_cast<const convolution_layer<DataType, data_layout::DATA_PARALLEL, Device>*>(parent) != nullptr); if(!is_after_fc && !m_is_after_conv) { std::stringstream err; err << "The K-FAC only supports batch-normalization layers after " << "fully-connected layers or convolutional layers." << " layer: " << layer->get_name() << " parent type: " << parent->get_type(); LBANN_ERROR(err.str()); } if(is_after_fc) { const auto& dtl_parent = dynamic_cast<const data_type_layer<DataType>&>(*parent); const El::AbstractMatrix<DataType>& local_activations = dtl_parent.get_local_activations(); m_num_channels = local_activations.Height(); m_spatial_prod = 1; } else { const auto input_dims = layer->get_input_dims(); m_num_channels = input_dims[0]; m_spatial_prod = 1; // std::accumulate might overflow for large 3D layers for(auto i = input_dims.begin()+1; i != input_dims.end(); i++) m_spatial_prod *= *i; } } kfac_block_bn(const kfac_block_bn&) = default; kfac_block_bn& operator=(const kfac_block_bn&) = default; void compute_local_kronecker_factors( lbann_comm* comm, bool print_matrix, bool print_matrix_summary) override; const std::vector<El::AbstractMatrix<DataType>*> get_local_kronecker_buffers() override { std::vector<El::AbstractMatrix<DataType>*> ret = {&m_fisher_buf}; return ret; } void update_kronecker_average( lbann_comm* comm, DataType kronecker_decay, bool print_matrix, bool print_matrix_summary) override; void update_kronecker_inverse( lbann_comm* comm, bool use_pi, DataType damping_act, DataType damping_err, DataType learning_rate_factor, bool print_matrix, bool print_matrix_summary, bool print_time) override; const std::vector<El::AbstractMatrix<DataType>*> get_preconditioned_grad_buffers() override; std::vector<std::tuple<std::string, size_t, size_t>> get_internal_matrix_info() const override; std::string get_info() const override { std::ostringstream oss; oss << kfac_block<Device>::get_info() << ", is_after_conv=" << m_is_after_conv; return oss.str(); } private: /** @brief Information to perform its computation. **/ bool m_is_after_conv; size_t m_num_channels, m_spatial_prod; /** @brief Lower triangle buffers of the Fisher block. */ El::Matrix<DataType, Device> m_fisher_buf; /** @brief Exponential moving average of the Fisher matrix. */ El::Matrix<DataType, Device> m_fisher_average; /** @brief Inverse of the average Fisher matrix. */ El::Matrix<DataType, Device> m_fisher_inverse; }; } // namespace lbann #endif // LBANN_EXECUTION_ALGORITHMS_KFAC_KFAC_BLOCK_BN_HPP_INCLUDED
34.030864
97
0.686015
[ "vector", "3d" ]
f351369380024d95b764108cf638d3b59ae6ce2b
24,482
cpp
C++
src/mame/video/lockon.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/mame/video/lockon.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/mame/video/lockon.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:Philip Bennett /*************************************************************************** Lock-On video hardware ***************************************************************************/ #include "emu.h" #include "includes/lockon.h" #include "cpu/nec/nec.h" #include "video/resnet.h" #define CURSOR_XPOS 168 #define CURSOR_YPOS 239 #define FRAMEBUFFER_MAX_X 431 #define FRAMEBUFFER_MAX_Y (uint32_t)((FRAMEBUFFER_CLOCK / (FRAMEBUFFER_MAX_X-1)).dvalue() / (PIXEL_CLOCK/(HTOTAL*VTOTAL)).dvalue()) /************************************* * * HD46505S-2 CRT Controller * *************************************/ uint16_t lockon_state::lockon_crtc_r() { return 0xffff; } void lockon_state::lockon_crtc_w(offs_t offset, uint16_t data) { #if 0 data &= 0xff; if (offset == 0) { switch (data) { case 0x00: osd_printf_debug("Horizontal Total "); break; case 0x01: osd_printf_debug("Horizontal displayed "); break; case 0x02: osd_printf_debug("Horizontal sync position "); break; case 0x03: osd_printf_debug("Horizontal sync width "); break; case 0x04: osd_printf_debug("Vertical total "); break; case 0x05: osd_printf_debug("Vertical total adjust "); break; case 0x06: osd_printf_debug("Vertical displayed "); break; case 0x07: osd_printf_debug("Vertical sync position "); break; case 0x08: osd_printf_debug("Interlace mode "); break; case 0x09: osd_printf_debug("Max. scan line address "); break; case 0x0a: osd_printf_debug("Cursror start "); break; case 0x0b: osd_printf_debug("Cursor end "); break; case 0x0c: osd_printf_debug("Start address (h) "); break; case 0x0d: osd_printf_debug("Start address (l) "); break; case 0x0e: osd_printf_debug("Cursor (h) "); break; case 0x0f: osd_printf_debug("Cursor (l) "); break; case 0x10: osd_printf_debug("Light pen (h)) "); break; case 0x11: osd_printf_debug("Light pen (l) "); break; } } else if (offset == 1) { osd_printf_debug("0x%.2x, (%d)\n",data, data); } #endif } TIMER_CALLBACK_MEMBER(lockon_state::cursor_callback) { if (m_main_inten) m_maincpu->set_input_line_and_vector(0, HOLD_LINE, 0xff); // V30 m_cursor_timer->adjust(m_screen->time_until_pos(CURSOR_YPOS, CURSOR_XPOS)); } /************************************* * * Palette decoding * *************************************/ static const res_net_info lockon_net_info = { RES_NET_VCC_5V | RES_NET_VBIAS_5V | RES_NET_VIN_TTL_OUT, { {RES_NET_AMP_NONE, 560, 0, 5, {4700, 2200, 1000, 470, 220}}, {RES_NET_AMP_NONE, 560, 0, 5, {4700, 2200, 1000, 470, 220}}, {RES_NET_AMP_NONE, 560, 0, 5, {4700, 2200, 1000, 470, 220}} } }; static const res_net_info lockon_pd_net_info = { RES_NET_VCC_5V | RES_NET_VBIAS_5V | RES_NET_VIN_TTL_OUT, { {RES_NET_AMP_NONE, 560, 580, 5, {4700, 2200, 1000, 470, 220}}, {RES_NET_AMP_NONE, 560, 580, 5, {4700, 2200, 1000, 470, 220}}, {RES_NET_AMP_NONE, 560, 580, 5, {4700, 2200, 1000, 470, 220}} } }; void lockon_state::lockon_palette(palette_device &palette) const { uint8_t const *const color_prom = memregion("proms")->base(); for (int i = 0; i < 1024; ++i) { uint8_t r, g, b; uint8_t const p1 = color_prom[i]; uint8_t const p2 = color_prom[i + 0x400]; if (p2 & 0x80) { r = compute_res_net((p2 >> 2) & 0x1f, 0, lockon_net_info); g = compute_res_net(((p1 >> 5) & 0x7) | (p2 & 3) << 3, 1, lockon_net_info); b = compute_res_net((p1 & 0x1f), 2, lockon_net_info); } else { r = compute_res_net((p2 >> 2) & 0x1f, 0, lockon_pd_net_info); g = compute_res_net(((p1 >> 5) & 0x7) | (p2 & 3) << 3, 1, lockon_pd_net_info); b = compute_res_net((p1 & 0x1f), 2, lockon_pd_net_info); } palette.set_pen_color(i, rgb_t(r, g, b)); } } /************************************* * * Character tilemap handling * *************************************/ void lockon_state::lockon_char_w(offs_t offset, uint16_t data) { m_char_ram[offset] = data; m_tilemap->mark_tile_dirty(offset); } TILE_GET_INFO_MEMBER(lockon_state::get_lockon_tile_info) { uint32_t tileno = m_char_ram[tile_index] & 0x03ff; uint32_t col = (m_char_ram[tile_index] >> 10) & 0x3f; col = (col & 0x1f) + (col & 0x20 ? 64 : 0); tileinfo.set(0, tileno, col, 0); } /******************************************************************************************* Scene tilemap hardware *******************************************************************************************/ void lockon_state::lockon_scene_h_scr_w(uint16_t data) { m_scroll_h = data & 0x1ff; } void lockon_state::lockon_scene_v_scr_w(uint16_t data) { m_scroll_v = data & 0x81ff; } void lockon_state::scene_draw( ) { /* 3bpp characters */ const uint8_t *const gfx1 = memregion("gfx2")->base(); const uint8_t *const gfx2 = gfx1 + 0x10000; const uint8_t *const gfx3 = gfx1 + 0x20000; const uint8_t *const clut = gfx1 + 0x30000; for (uint32_t y = 0; y < FRAMEBUFFER_MAX_Y; ++y) { uint32_t d0 = 0, d1 = 0, d2 = 0; uint32_t colour = 0; uint32_t y_offs; uint32_t x_offs; uint32_t y_gran; uint32_t ram_mask = 0x7ff; y_offs = (y + m_scroll_v) & 0x1ff; /* Clamp - stops tilemap wrapping when screen is rotated */ if (BIT(m_scroll_v, 15) && y_offs & 0x100) ram_mask = 0x7; x_offs = (m_scroll_h - 8) & 0x1ff; y_gran = y_offs & 7; if (x_offs & 7) { uint32_t tileidx; uint16_t addr = ((y_offs & ~7) << 3) + ((x_offs >> 3) & 0x3f); uint16_t ram_val = m_scene_ram[addr & ram_mask]; colour = (clut[ram_val & 0x7fff] & 0x3f) << 3; tileidx = ((ram_val & 0x0fff) << 3) + y_gran; d0 = *(gfx1 + tileidx); d1 = *(gfx2 + tileidx); d2 = *(gfx3 + tileidx); } uint16_t *bmpaddr = &m_back_buffer->pix(y); for (uint32_t x = 0; x < FRAMEBUFFER_MAX_X; ++x) { uint32_t x_gran = (x_offs & 7) ^ 7; uint32_t col; if (!(x_offs & 7)) { uint32_t tileidx; uint16_t addr = ((y_offs & ~7) << 3) + ((x_offs >> 3) & 0x3f); uint16_t ram_val = m_scene_ram[addr & ram_mask]; colour = (clut[ram_val & 0x7fff] & 0x3f) << 3; tileidx = ((ram_val & 0x0fff) << 3) + y_gran; d0 = *(gfx1 + tileidx); d1 = *(gfx2 + tileidx); d2 = *(gfx3 + tileidx); } col = colour | (((d2 >> x_gran) & 1) << 2) | (((d1 >> x_gran) & 1) << 1) | ( (d0 >> x_gran) & 1); *bmpaddr++ = 0xa00 + col; x_offs = (x_offs + 1) & 0x1ff; } } } /******************************************************************************************* Ground Hardware Each framebuffer line corresponds to a three word entry in ground RAM, starting from offset 3: FEDCBA9876543210 0 |.............xxx| Tile line (A0-A2 GFX ROMs) |...........xx...| Tile index (A6-A5 GFX ROMs) |........xxx.....| ROM lut address (A6-A4) |.xxxxxxx........| ROM lut address (A13-A7) |x...............| /Line enable 1 |........xxxxxxxx| TZ2213 value |xxxxxxxx........| X offset 2 |........xxxxxxxx| TZ2213 DX |.......x........| Carry |x...............| End of list marker An 8-bit ground control register controls the following: 76543210 |......xx| LUT ROM A15-A14 |....xx..| LUT ROM select |..xx....| CLUT ROM A13-A12 |.x......| GFX ROM A15, CLUT ROM A14 |x.......| GFX ROM bank select (always 0 - only 1 bank is present) *******************************************************************************************/ void lockon_state::lockon_ground_ctrl_w(uint16_t data) { m_ground_ctrl = data & 0xff; } TIMER_CALLBACK_MEMBER(lockon_state::bufend_callback) { m_ground->set_input_line_and_vector(0, HOLD_LINE, 0xff); // V30 m_object->set_input_line(NEC_INPUT_LINE_POLL, ASSERT_LINE); } /* Get data for a each 8x8x3 ground tile */ #define GET_GROUND_DATA() \ { \ uint32_t gfx_a4_3 = (ls163 & 0xc) << 1; \ uint32_t lut_addr = lut_address + ((ls163 >> 4) & 0xf); \ uint32_t gfx_a14_7 = lut_rom[lut_addr] << 7; \ clut_addr = (lut_rom[lut_addr] << 4) | clut_a14_12 | clut_a4_3 | (ls163 & 0xc) >> 2; \ gfx_addr = gfx_a15 | gfx_a14_7 | gfx_a6_5 | gfx_a4_3 | gfx_a2_0; \ pal = (clut_rom[clut_addr] << 3); \ rom_data1 = gfx_rom[gfx_addr]; \ rom_data2 = gfx_rom[gfx_addr + 0x10000]; \ rom_data3 = gfx_rom[gfx_addr + 0x20000]; \ } void lockon_state::ground_draw( ) { /* ROM pointers */ const uint8_t *const gfx_rom = memregion("gfx4")->base(); const uint8_t *const lut_rom = gfx_rom + 0x30000 + ((m_ground_ctrl >> 2) & 0x3 ? 0x10000 : 0); const uint8_t *const clut_rom = gfx_rom + 0x50000; uint32_t lut_a15_14 = (m_ground_ctrl & 0x3) << 14; uint32_t clut_a14_12 = (m_ground_ctrl & 0x70) << 8; uint32_t gfx_a15 = (m_ground_ctrl & 0x40) << 9; uint32_t offs = 3; uint32_t y; /* TODO: Clean up and emulate CS of GFX ROMs? */ for (y = 0; y < FRAMEBUFFER_MAX_Y; ++y) { uint16_t *bmpaddr = &m_back_buffer->pix(y); uint8_t ls163; uint32_t clut_addr; uint32_t gfx_addr; uint8_t rom_data1 = 0; uint8_t rom_data2 = 0; uint8_t rom_data3 = 0; uint32_t pal = 0; uint32_t x; /* Draw this line? */ if (!(m_ground_ram[offs] & 0x8000)) { uint32_t gfx_a2_0 = m_ground_ram[offs] & 0x0007; uint32_t gfx_a6_5 = (m_ground_ram[offs] & 0x0018) << 2; uint32_t clut_a4_3 = (m_ground_ram[offs] & 0x0018) >> 1; uint8_t tz2213_x = m_ground_ram[offs + 1] & 0xff; uint8_t tz2213_dx = m_ground_ram[offs + 2] & 0xff; uint32_t lut_address = lut_a15_14 + ((m_ground_ram[offs] & 0x7fe0) >> 1); uint32_t cy = m_ground_ram[offs + 2] & 0x0100; uint32_t color; uint32_t gpbal2_0_prev; ls163 = m_ground_ram[offs + 1] >> 8; gpbal2_0_prev = ((ls163 & 3) << 1) | BIT(tz2213_x, 7); if (gpbal2_0_prev) GET_GROUND_DATA(); for (x = 0; x < FRAMEBUFFER_MAX_X; x++) { uint32_t tz2213_cy; uint32_t gpbal2_0 = ((ls163 & 3) << 1) | BIT(tz2213_x, 7); /* Stepped into a new tile? */ if (gpbal2_0 < gpbal2_0_prev) GET_GROUND_DATA(); gpbal2_0_prev = gpbal2_0; color = pal; color += (rom_data1 >> gpbal2_0) & 0x1; color += ((rom_data2 >> gpbal2_0) & 0x1) << 1; color += ((rom_data3 >> gpbal2_0) & 0x1) << 2; *bmpaddr++ = 0x800 + color; /* Update the counters */ tz2213_cy = (uint8_t)tz2213_dx > (uint8_t)~(tz2213_x); tz2213_x = (tz2213_x + tz2213_dx); /* Carry? */ if (tz2213_cy || cy) ++ls163; } } offs += 3; /* End of list marker */ if (m_ground_ram[offs + 2] & 0x8000) { m_bufend_timer->adjust(attotime::from_hz(FRAMEBUFFER_CLOCK) * (FRAMEBUFFER_MAX_X * y)); } } } /******************************************************************************************* Object hardware Customs (4 each, 1 per bitplane) TZA118 - Scaling TZ4203 - Objects with integrated line buffer. FEDCBA9876543210 0 |......xxxxxxxxxx| Y position |....xx..........| Object Y size |..xx............| Object X size |.x..............| Y flip |x...............| X flip 1 |........xxxxxxxx| X/Y scale |.xxxxxxx........| Colour |x...............| End of list marker 2 |xxxxxxxxxxxxxxxx| Chunk ROM address 3 |.....xxxxxxxxxxx| X position *******************************************************************************************/ /* There's logic to prevent shadow pixels from being drawn against the scene tilemap, so that shadows don't appear against the sky. */ #define DRAW_OBJ_PIXEL(COLOR) \ do { \ if (px < FRAMEBUFFER_MAX_X) \ if (COLOR != 0xf) \ { \ uint8_t clr = m_obj_pal_ram[(pal << 4) + COLOR]; \ uint16_t *pix = (line + px); \ if (!(clr == 0xff && ((*pix & 0xe00) == 0xa00))) \ *pix = 0x400 + clr; \ } \ px = (px + 1) & 0x7ff; \ } while(0) void lockon_state::objects_draw( ) { const uint8_t *const romlut = memregion("user1")->base(); const uint16_t *const chklut = (uint16_t*)memregion("user2")->base(); const uint8_t *const gfxrom = memregion("gfx5")->base(); const uint8_t *const sproms = memregion("proms")->base() + 0x800; for (uint32_t offs = 0; offs < m_object_ram.bytes(); offs += 4) { /* Retrieve the object attributes */ uint32_t ypos = m_object_ram[offs] & 0x03ff; uint32_t xpos = m_object_ram[offs + 3] & 0x07ff; uint32_t ysize = (m_object_ram[offs] >> 10) & 0x3; uint32_t xsize = (m_object_ram[offs] >> 12) & 0x3; uint32_t yflip = BIT(m_object_ram[offs], 14); uint32_t xflip = BIT(m_object_ram[offs], 15); uint32_t scale = m_object_ram[offs + 1] & 0xff; uint32_t pal = (m_object_ram[offs + 1] >> 8) & 0x7f; uint32_t opsta = m_object_ram[offs + 2]; if (m_iden) { m_obj_pal_ram[(pal << 4) + m_obj_pal_addr] = m_obj_pal_latch; break; } /* How many lines will this sprite occupy? The PAL @ IC154 knows... */ uint32_t lines = scale >> (3 - ysize); uint32_t opsta15_8 = opsta & 0xff00; /* Account for line buffering */ ypos -=1; for (uint32_t y = 0; y < FRAMEBUFFER_MAX_Y; y++) { uint32_t cy = (y + ypos) & 0x3ff; uint32_t optab; uint32_t lutaddr; uint32_t tile; uint8_t cnt; uint32_t yidx; uint16_t *line = &m_back_buffer->pix(y); uint32_t px = xpos; /* Outside the limits? */ if (cy & 0x300) continue; if ((cy & 0xff) >= lines) break; lutaddr = (scale & 0x80 ? 0x8000 : 0) | ((scale & 0x7f) << 8) | (cy & 0xff); optab = romlut[lutaddr] & 0x7f; if (yflip) optab ^= 7; yidx = (optab & 7); /* Now calculate the lower 7-bits of the LUT ROM address. PAL @ IC157 does this */ cnt = (optab >> 3) * (1 << xsize); if (xflip) cnt ^= 7 >> (3 - xsize); if (yflip) cnt ^= (0xf >> (3 - ysize)) * (1 << xsize); cnt = (cnt + (opsta & 0xff)); /* Draw! */ for (tile = 0; tile < (1 << xsize); ++tile) { uint16_t sc; uint16_t scl; uint32_t x; uint32_t tileaddr; uint16_t td0, td1, td2, td3; uint32_t j; uint32_t bank; scl = scale & 0x7f; tileaddr = (chklut[opsta15_8 + cnt] & 0x7fff); bank = ((tileaddr >> 12) & 3) * 0x40000; tileaddr = bank + ((tileaddr & ~0xf000) << 3); if (xflip) --cnt; else ++cnt; /* Draw two 8x8 tiles */ for (j = 0; j < 2; ++j) { /* Get tile data */ uint32_t tileadd = tileaddr + (0x20000 * (j ^ xflip)); /* Retrieve scale values from PROMs */ sc = sproms[(scl << 4) + (tile * 2) + j]; /* Data from ROMs is inverted */ td3 = gfxrom[tileadd + yidx] ^ 0xff; td2 = gfxrom[tileadd + 0x8000 + yidx] ^ 0xff; td1 = gfxrom[tileadd + 0x10000 + yidx] ^ 0xff; td0 = gfxrom[tileadd + 0x18000 + yidx] ^ 0xff; if (scale & 0x80) { for (x = 0; x < 8; ++x) { uint8_t col; uint8_t pix = x; if (!xflip) pix ^= 0x7; col = BIT(td0, pix) | (BIT(td1, pix) << 1) | (BIT(td2, pix) << 2) | (BIT(td3, pix) << 3); DRAW_OBJ_PIXEL(col); if (BIT(sc, x)) DRAW_OBJ_PIXEL(col); } } else { for (x = 0; x < 8; ++x) { uint8_t col; uint8_t pix = x; if (BIT(sc, x)) { if (!xflip) pix ^= 0x7; col = BIT(td0, pix) | (BIT(td1, pix) << 1) | (BIT(td2, pix) << 2) | (BIT(td3, pix) << 3); DRAW_OBJ_PIXEL(col); } } } } } } /* Check for the end of list marker */ if (m_object_ram[offs + 1] & 0x8000) return; } } /* The mechanism used by the object CPU to update the object ASICs palette RAM */ void lockon_state::lockon_tza112_w(offs_t offset, uint16_t data) { if (m_iden) { m_obj_pal_latch = data & 0xff; m_obj_pal_addr = offset & 0xf; objects_draw(); } } uint16_t lockon_state::lockon_obj_4000_r() { m_object->set_input_line(NEC_INPUT_LINE_POLL, CLEAR_LINE); return 0xffff; } void lockon_state::lockon_obj_4000_w(uint16_t data) { m_iden = data & 1; } /******************************************************************************************* Frame buffer rotation hardware FEDCBA9876543210 0 |........xxxxxxxx| X start address |.......x........| Direction 1 |........xxxxxxxx| TZ2213 IC65 value |.......x........| TZ2213 IC65 /enable 2 |........xxxxxxxx| TZ2213 IC65 delta 3 |........xxxxxxxx| TZ2213 IC106 delta |.......x........| TZ2213 IC106 enable 4 |.......xxxxxxxxx| Y start address 5 |........xxxxxxxx| TZ2213 IC66 value 6 |........xxxxxxxx| TZ2213 IC66 delta |.......x........| TZ2213 IC65 /enable 7 |........xxxxxxxx| TZ2213 IC107 delta |.......x........| TZ2213 /enable |......x.........| Direction *******************************************************************************************/ void lockon_state::lockon_fb_clut_w(offs_t offset, uint16_t data) { rgb_t color; color = m_palette->pen_color(0x300 + (data & 0xff)); m_palette->set_pen_color(0x400 + offset, color); } /* Rotation control register */ void lockon_state::lockon_rotate_w(offs_t offset, uint16_t data) { switch (offset & 7) { case 0: m_xsal = data & 0x1ff; break; case 1: m_x0ll = data & 0xff; break; case 2: m_dx0ll = data & 0x1ff; break; case 3: m_dxll = data & 0x1ff; break; case 4: m_ysal = data & 0x1ff; break; case 5: m_y0ll = data & 0xff; break; case 6: m_dy0ll = data & 0x1ff; break; case 7: m_dyll = data & 0x3ff; break; } } #define INCREMENT(ACC, CNT) \ do { \ carry = (uint8_t)d##ACC > (uint8_t)~ACC; \ ACC += d##ACC; \ if (carry) ++CNT; \ } while(0) #define DECREMENT(ACC, CNT) \ do { \ carry = (uint8_t)d##ACC > (uint8_t)ACC; \ ACC -= d##ACC; \ if (carry) --CNT; \ } while(0) void lockon_state::rotate_draw( bitmap_ind16 &bitmap, const rectangle &cliprect ) { /* Counters */ uint32_t cxy = m_xsal & 0xff; uint32_t cyy = m_ysal & 0x1ff; /* Accumulator values and deltas */ uint8_t axy = m_x0ll & 0xff; uint8_t daxy = m_dx0ll & 0xff; uint8_t ayy = m_y0ll & 0xff; uint8_t dayy = m_dy0ll & 0xff; uint8_t dayx = m_dyll & 0xff; uint8_t daxx = m_dxll & 0xff; uint32_t xy_up = BIT(m_xsal, 8); uint32_t yx_up = BIT(m_dyll, 9); uint32_t axx_en = !BIT(m_dxll, 8); uint32_t ayx_en = !BIT(m_dyll, 8); uint32_t axy_en = !BIT(m_dx0ll, 8); uint32_t ayy_en = !BIT(m_dy0ll, 8); for (uint32_t y = 0; y <= cliprect.max_y; ++y) { uint32_t carry; uint16_t *dst = &bitmap.pix(y); uint32_t cx = cxy; uint32_t cy = cyy; uint8_t axx = axy; uint8_t ayx = ayy; for (uint32_t x = 0; x <= cliprect.max_x; ++x) { cx &= 0x1ff; cy &= 0x1ff; *dst++ = m_front_buffer->pix(cy, cx); if (axx_en) INCREMENT(axx, cx); else ++cx; if (ayx_en) { if (yx_up) INCREMENT(ayx, cy); else DECREMENT(ayx, cy); } else { if (yx_up) ++cy; else --cy; } } if (axy_en) { if (xy_up) INCREMENT(axy, cxy); else DECREMENT(axy, cxy); } else { if (xy_up) ++cxy; else --cxy; } if (ayy_en) INCREMENT(ayy, cyy); else ++cyy; cxy &= 0xff; cyy &= 0x1ff; } } /******************************************************************************************* HUD Drawing Hardware A sprite layer that uses 8x8x1bpp tiles to form bigger sprites 0 |.......xxxxxxxxx| Y Position |xxxxxxx.........| Code 1 |.......xxxxxxxxx| X Position |....xxx.........| Colour |.xxx............| Sprite width (0=8, 1=16, 2=24, 3=32 pixels, etc.) |x...............| End of list marker *******************************************************************************************/ void lockon_state::hud_draw( bitmap_ind16 &bitmap, const rectangle &cliprect ) { uint8_t const *const tile_rom = memregion("gfx3")->base(); for (uint32_t offs = 0x0; offs <= m_hud_ram.bytes(); offs += 2) { uint32_t y_pos; uint32_t x_pos; uint32_t y_size; uint32_t x_size; uint32_t layout; uint16_t colour; uint32_t code; uint32_t rom_a12_7; /* End of sprite list marker */ if (m_hud_ram[offs + 1] & 0x8000) break; y_pos = m_hud_ram[offs] & 0x1ff; x_pos = m_hud_ram[offs + 1] & 0x1ff; x_size = (m_hud_ram[offs + 1] >> 12) & 7; code = (m_hud_ram[offs] >> 9) & 0x7f; colour = 0x200 + ((m_hud_ram[offs + 1] >> 9) & 7); layout = (code >> 5) & 3; rom_a12_7 = (code & 0xfe) << 6; /* Account for line buffering */ y_pos -= 1; if (layout == 3) y_size = 32; else if (layout == 2) y_size = 16; else y_size = 8; for (uint32_t y = cliprect.min_y; y <= cliprect.max_y; ++y) { uint32_t xt; uint32_t cy; cy = y_pos + y; if (cy < 0x200) continue; if ((cy & 0xff) == y_size) break; for (xt = 0; xt <= x_size; ++xt) { uint32_t rom_a6_3; uint32_t px; uint8_t gfx_strip; if (layout == 3) rom_a6_3 = (BIT(cy, 4) << 3) | (BIT(cy, 3) << 2) | (BIT(xt, 1) << 1) | BIT(xt, 0); else if (layout == 2) rom_a6_3 = ((BIT(code, 0) << 3) | (BIT(xt, 1) << 2) | (BIT(cy, 3) << 1) | (BIT(xt, 0))); else rom_a6_3 = (BIT(code, 0) << 3) | (xt & 7); rom_a6_3 <<= 3; /* Get tile data */ gfx_strip = tile_rom[rom_a12_7 | rom_a6_3 | (cy & 7)]; if (gfx_strip == 0) continue; /* Draw */ for (px = 0; px < 8; ++px) { uint32_t x = x_pos + (xt << 3) + px; if (x <= cliprect.max_x) { uint16_t *const dst = &bitmap.pix(y, x); if (BIT(gfx_strip, px ^ 7) && *dst > 255) *dst = colour; } } } } } } /************************************* * * Driver video handlers * *************************************/ void lockon_state::video_start() { m_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(*this, FUNC(lockon_state::get_lockon_tile_info)), TILEMAP_SCAN_ROWS, 8, 8, 64, 32); m_tilemap->set_transparent_pen(0); /* Allocate the two frame buffers for rotation */ m_back_buffer = std::make_unique<bitmap_ind16>(512, 512); m_front_buffer = std::make_unique<bitmap_ind16>(512, 512); /* 2kB of object ASIC palette RAM */ m_obj_pal_ram = std::make_unique<uint8_t[]>(2048); /* Timer for ground display list callback */ m_bufend_timer = machine().scheduler().timer_alloc(timer_expired_delegate(FUNC(lockon_state::bufend_callback),this)); /* Timer for the CRTC cursor pulse */ m_cursor_timer = machine().scheduler().timer_alloc(timer_expired_delegate(FUNC(lockon_state::cursor_callback),this)); m_cursor_timer->adjust(m_screen->time_until_pos(CURSOR_YPOS, CURSOR_XPOS)); save_item(NAME(*m_back_buffer)); save_item(NAME(*m_front_buffer)); save_pointer(NAME(m_obj_pal_ram), 2048); } uint32_t lockon_state::screen_update_lockon(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect) { /* If screen output is disabled, fill with black */ if (!BIT(m_ctrl_reg, 7)) { bitmap.fill(m_palette->black_pen(), cliprect); return 0; } /* Scan out the frame buffer in rotated order */ rotate_draw(bitmap, cliprect); /* Draw the character tilemap */ m_tilemap->draw(screen, bitmap, cliprect, 0, 0); /* Draw the HUD */ hud_draw(bitmap, cliprect); return 0; } WRITE_LINE_MEMBER(lockon_state::screen_vblank_lockon) { // on falling edge if (!state) { /* Swap the frame buffers */ m_front_buffer.swap(m_back_buffer); /* Draw the frame buffer layers */ scene_draw(); ground_draw(); objects_draw(); } }
26.553145
164
0.541336
[ "object" ]
f3532bf62b2cb5c4352725050ee3c588d6900e03
4,945
cpp
C++
aws-cpp-sdk-alexaforbusiness/source/model/Profile.cpp
woohoou/aws-sdk-cpp
a42835a8aad2eac1e334d899a3fbfedcaa341d51
[ "Apache-2.0" ]
1
2020-07-16T19:03:13.000Z
2020-07-16T19:03:13.000Z
aws-cpp-sdk-alexaforbusiness/source/model/Profile.cpp
woohoou/aws-sdk-cpp
a42835a8aad2eac1e334d899a3fbfedcaa341d51
[ "Apache-2.0" ]
18
2018-05-15T16:41:07.000Z
2018-05-21T00:46:30.000Z
aws-cpp-sdk-alexaforbusiness/source/model/Profile.cpp
woohoou/aws-sdk-cpp
a42835a8aad2eac1e334d899a3fbfedcaa341d51
[ "Apache-2.0" ]
1
2019-10-31T11:19:50.000Z
2019-10-31T11:19:50.000Z
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #include <aws/alexaforbusiness/model/Profile.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace AlexaForBusiness { namespace Model { Profile::Profile() : m_profileArnHasBeenSet(false), m_profileNameHasBeenSet(false), m_addressHasBeenSet(false), m_timezoneHasBeenSet(false), m_distanceUnit(DistanceUnit::NOT_SET), m_distanceUnitHasBeenSet(false), m_temperatureUnit(TemperatureUnit::NOT_SET), m_temperatureUnitHasBeenSet(false), m_wakeWord(WakeWord::NOT_SET), m_wakeWordHasBeenSet(false), m_setupModeDisabled(false), m_setupModeDisabledHasBeenSet(false), m_maxVolumeLimit(0), m_maxVolumeLimitHasBeenSet(false), m_pSTNEnabled(false), m_pSTNEnabledHasBeenSet(false) { } Profile::Profile(const JsonValue& jsonValue) : m_profileArnHasBeenSet(false), m_profileNameHasBeenSet(false), m_addressHasBeenSet(false), m_timezoneHasBeenSet(false), m_distanceUnit(DistanceUnit::NOT_SET), m_distanceUnitHasBeenSet(false), m_temperatureUnit(TemperatureUnit::NOT_SET), m_temperatureUnitHasBeenSet(false), m_wakeWord(WakeWord::NOT_SET), m_wakeWordHasBeenSet(false), m_setupModeDisabled(false), m_setupModeDisabledHasBeenSet(false), m_maxVolumeLimit(0), m_maxVolumeLimitHasBeenSet(false), m_pSTNEnabled(false), m_pSTNEnabledHasBeenSet(false) { *this = jsonValue; } Profile& Profile::operator =(const JsonValue& jsonValue) { if(jsonValue.ValueExists("ProfileArn")) { m_profileArn = jsonValue.GetString("ProfileArn"); m_profileArnHasBeenSet = true; } if(jsonValue.ValueExists("ProfileName")) { m_profileName = jsonValue.GetString("ProfileName"); m_profileNameHasBeenSet = true; } if(jsonValue.ValueExists("Address")) { m_address = jsonValue.GetString("Address"); m_addressHasBeenSet = true; } if(jsonValue.ValueExists("Timezone")) { m_timezone = jsonValue.GetString("Timezone"); m_timezoneHasBeenSet = true; } if(jsonValue.ValueExists("DistanceUnit")) { m_distanceUnit = DistanceUnitMapper::GetDistanceUnitForName(jsonValue.GetString("DistanceUnit")); m_distanceUnitHasBeenSet = true; } if(jsonValue.ValueExists("TemperatureUnit")) { m_temperatureUnit = TemperatureUnitMapper::GetTemperatureUnitForName(jsonValue.GetString("TemperatureUnit")); m_temperatureUnitHasBeenSet = true; } if(jsonValue.ValueExists("WakeWord")) { m_wakeWord = WakeWordMapper::GetWakeWordForName(jsonValue.GetString("WakeWord")); m_wakeWordHasBeenSet = true; } if(jsonValue.ValueExists("SetupModeDisabled")) { m_setupModeDisabled = jsonValue.GetBool("SetupModeDisabled"); m_setupModeDisabledHasBeenSet = true; } if(jsonValue.ValueExists("MaxVolumeLimit")) { m_maxVolumeLimit = jsonValue.GetInteger("MaxVolumeLimit"); m_maxVolumeLimitHasBeenSet = true; } if(jsonValue.ValueExists("PSTNEnabled")) { m_pSTNEnabled = jsonValue.GetBool("PSTNEnabled"); m_pSTNEnabledHasBeenSet = true; } return *this; } JsonValue Profile::Jsonize() const { JsonValue payload; if(m_profileArnHasBeenSet) { payload.WithString("ProfileArn", m_profileArn); } if(m_profileNameHasBeenSet) { payload.WithString("ProfileName", m_profileName); } if(m_addressHasBeenSet) { payload.WithString("Address", m_address); } if(m_timezoneHasBeenSet) { payload.WithString("Timezone", m_timezone); } if(m_distanceUnitHasBeenSet) { payload.WithString("DistanceUnit", DistanceUnitMapper::GetNameForDistanceUnit(m_distanceUnit)); } if(m_temperatureUnitHasBeenSet) { payload.WithString("TemperatureUnit", TemperatureUnitMapper::GetNameForTemperatureUnit(m_temperatureUnit)); } if(m_wakeWordHasBeenSet) { payload.WithString("WakeWord", WakeWordMapper::GetNameForWakeWord(m_wakeWord)); } if(m_setupModeDisabledHasBeenSet) { payload.WithBool("SetupModeDisabled", m_setupModeDisabled); } if(m_maxVolumeLimitHasBeenSet) { payload.WithInteger("MaxVolumeLimit", m_maxVolumeLimit); } if(m_pSTNEnabledHasBeenSet) { payload.WithBool("PSTNEnabled", m_pSTNEnabled); } return payload; } } // namespace Model } // namespace AlexaForBusiness } // namespace Aws
23.107477
113
0.73913
[ "model" ]
f35676fd7399a0973b50e1f79c17a091389fa34d
29,034
cxx
C++
ds/ds/src/common/atq/hashtab.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
ds/ds/src/common/atq/hashtab.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
ds/ds/src/common/atq/hashtab.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1995-1996 Microsoft Corporation Module Name : hashtab.cxx Abstract: Implements the member functions for Hash table Author: Murali R. Krishnan ( MuraliK ) 02-Oct-1996 Environment: Win32 - User Mode Project: Internet Server DLL Functions Exported: Revision History: --*/ /************************************************************ * Include Headers ************************************************************/ # if !defined(dllexp) # define dllexp __declspec( dllexport) # endif # include "isatq.hxx" # include "hashtab.hxx" # include "dbgutil.h" /*++ Organization of Hash Table The hash table consists of a set of hash buckets controlled by the number of buckets specified during creation. Each bucket consists of a set of bucket chunks. Each bucket owns a separate critical section to protect the entries in the bucket itself. Each bucket chunk consists of an array of MAX_ELEMENTS_PER_BUCKET HashTableBucketElement Entries (HTBE_ENTRY). Each HTBE_ENTRY maintains a hash value and pointer to the Hash Element. --*/ /************************************************************ * HASH_TABLE_BUCKET ************************************************************/ struct HTBE_ENTRY { DWORD m_hashValue; HT_ELEMENT * m_phte; inline BOOL IsMatch( DWORD hashValue, LPCSTR pszKey, DWORD cchKey) const { return ((hashValue == m_hashValue) && (NULL != m_phte) && m_phte->IsMatch( pszKey, cchKey) ); } inline BOOL IsMatch( IN HT_ELEMENT * phte) const { return ( phte == m_phte); } inline BOOL IsEmpty( VOID) const { return ( NULL == m_phte); } VOID Print( VOID) const { m_phte->Print(); } }; typedef HTBE_ENTRY * PHTBE_ENTRY; // // Chunk size should be carefully (empirically) chosen. // Small Chunk size => large number of chunks // Large Chunk size => high cost of search on failures. // For now we choose the chunk size to be 20 entries. # define MAX_ELEMENTS_PER_BUCKET ( 20 ) struct HTB_ELEMENT { HTBE_ENTRY m_rgElements[MAX_ELEMENTS_PER_BUCKET]; DWORD m_nElements; LIST_ENTRY m_ListEntry; HTB_ELEMENT(VOID) : m_nElements ( 0) { InitializeListHead( &m_ListEntry); ZeroMemory( m_rgElements, sizeof( m_rgElements)); } ~HTB_ELEMENT(VOID) { Cleanup(); } VOID Cleanup( VOID); inline HT_ELEMENT * Lookup( IN DWORD hashValue, IN LPCSTR pszKey, DWORD cchKey); inline BOOL Insert( IN DWORD hashVal, IN HT_ELEMENT * phte); inline BOOL Delete( IN HT_ELEMENT * phte); VOID Print( IN DWORD level) const; HTBE_ENTRY * FirstElement(VOID) { return ( m_rgElements); } HTBE_ENTRY * LastElement(VOID) { return ( m_rgElements + MAX_ELEMENTS_PER_BUCKET); } VOID NextElement( HTBE_ENTRY * & phtbe) { phtbe++; } VOID IncrementElements(VOID) { m_nElements++; } VOID DecrementElements(VOID) { m_nElements--; } DWORD NumElements( VOID) const { return ( m_nElements); } BOOL IsSpaceAvailable(VOID) const { return ( NumElements() < MAX_ELEMENTS_PER_BUCKET); } DWORD FindNextElement( IN OUT LPDWORD pdwPos, OUT HT_ELEMENT ** pphte); }; typedef HTB_ELEMENT * PHTB_ELEMENT; class HASH_TABLE_BUCKET { public: HASH_TABLE_BUCKET(VOID); ~HASH_TABLE_BUCKET( VOID); HT_ELEMENT * Lookup( IN DWORD hashValue, IN LPCSTR pszKey, DWORD cchKey); BOOL Insert( IN DWORD hashVal, IN HT_ELEMENT * phte, IN BOOL fCheckForDuplicate); BOOL Delete( IN HT_ELEMENT * phte); VOID Print( IN DWORD level); DWORD NumEntries( VOID); DWORD InitializeIterator( IN HT_ITERATOR * phti); DWORD FindNextElement( IN HT_ITERATOR * phti, OUT HT_ELEMENT ** pphte); DWORD CloseIterator( IN HT_ITERATOR * phti); private: CRITICAL_SECTION m_csLock; LIST_ENTRY m_lHead; DWORD m_nEntries; HTB_ELEMENT m_htbeFirst; // the first bucket chunk VOID Lock(VOID) { EnterCriticalSection( &m_csLock); } VOID Unlock( VOID) { LeaveCriticalSection( &m_csLock); } }; /************************************************************ * Member Functions of HTB_ELEMENT ************************************************************/ VOID HTB_ELEMENT::Cleanup( VOID) { if ( m_nElements > 0) { PHTBE_ENTRY phtbeEntry; // free up all the entries in this bucket. for (phtbeEntry = FirstElement(); phtbeEntry < (LastElement()); NextElement( phtbeEntry)) { if ( !phtbeEntry->IsEmpty() ) { // release the object now. DecrementElements(); // Assert that ref == 1 DerefAndKillElement( phtbeEntry->m_phte); phtbeEntry->m_phte = NULL; phtbeEntry->m_hashValue = 0; } } // for } DBG_ASSERT( 0 == m_nElements); return; } // HTB_ELEMENT::Cleanup() inline HT_ELEMENT * HTB_ELEMENT::Lookup( IN DWORD hashValue, IN LPCSTR pszKey, DWORD cchKey) { HT_ELEMENT * phte = NULL; if ( m_nElements > 0) { PHTBE_ENTRY phtbeEntry; // find the entry by scanning all entries in this bucket chunk // if found, increment ref count and return a pointer to the object for (phtbeEntry = FirstElement(); phtbeEntry < (LastElement()); NextElement( phtbeEntry)) { // // If the hash values match and the strings match up, return // the corresponding hash table entry object // if ( phtbeEntry->IsMatch( hashValue, pszKey, cchKey)) { // we found the entry. return it. phte = phtbeEntry->m_phte; DBG_REQUIRE( phte->Reference() > 0); break; } } // for } return ( phte); } // HTB_ELEMENT::Lookup() inline BOOL HTB_ELEMENT::Insert( IN DWORD hashVal, IN HT_ELEMENT * phte ) { if ( m_nElements < MAX_ELEMENTS_PER_BUCKET) { // there is some empty space. // Find one such a slot and add this new entry PHTBE_ENTRY phtbeEntry; for (phtbeEntry = FirstElement(); phtbeEntry < LastElement(); NextElement( phtbeEntry)) { if ( phtbeEntry->IsEmpty() ) { DBG_ASSERT( NULL != phte); // Assume that the object phte already has non-zero ref count // we found a free entry. insert the new element here. phtbeEntry->m_hashValue = hashVal; phtbeEntry->m_phte = phte; IncrementElements(); return ( TRUE); } } // for // we should not come here. If we do then there is trouble :( DBG_ASSERT( FALSE); } SetLastError( ERROR_INSUFFICIENT_BUFFER); return ( FALSE); } // HTB_ELEMENT::Insert() DWORD HTB_ELEMENT::FindNextElement( IN OUT LPDWORD pdwPos, OUT HT_ELEMENT ** pphte) { DWORD dwErr = ERROR_NO_MORE_ITEMS; DBG_ASSERT( NULL != pdwPos ); DBG_ASSERT( NULL != pphte ); // Find the first valid element to return back. // // Given that deletion might happen any time, we cannot rely on the // comparison *pdwPos < m_nElements // // Do scans with *pdwPos < MAX_ELEMENTS_PER_BUCKET // if ( *pdwPos < MAX_ELEMENTS_PER_BUCKET ) { PHTBE_ENTRY phtbeEntry; // find the entry by scanning all entries in this bucket chunk // if found, increment ref count and return a pointer to the object for (phtbeEntry = m_rgElements + *pdwPos; phtbeEntry < (LastElement()); NextElement( phtbeEntry)) { if ( phtbeEntry->m_phte != NULL ) { // // Store the element pointer and the offset // and return after referencing the element // *pphte = phtbeEntry->m_phte; (*pphte)->Reference(); *pdwPos = ( 1 + (DWORD)(phtbeEntry - FirstElement())); dwErr = NO_ERROR; break; } } // for } return ( dwErr); } // HTB_ELEMENT::FindNextElement() inline BOOL HTB_ELEMENT::Delete( IN HT_ELEMENT * phte) { DBG_ASSERT( NULL != phte); if ( m_nElements > 0) { PHTBE_ENTRY phtbeEntry; // find the entry by scanning all entries in this bucket chunk // if found, increment ref count and return a pointer to the object for (phtbeEntry = FirstElement(); phtbeEntry < (LastElement()); NextElement( phtbeEntry)) { // // If the hash values match and the strings match up, // decrement ref count and kill the element. // if ( phtbeEntry->IsMatch( phte)) { // We found the entry. Remove it from the table phtbeEntry->m_phte = NULL; DecrementElements(); DerefAndKillElement( phte); return ( TRUE); } } // for } return ( FALSE); } // HTB_ELEMENT::Delete() VOID HTB_ELEMENT::Print(IN DWORD level) const { const HTBE_ENTRY * phtbeEntry; CHAR rgchBuffer[MAX_ELEMENTS_PER_BUCKET * 22 + 200]; DWORD cch; DWORD i; cch = wsprintf( rgchBuffer, "HTB_ELEMENT(%p) # Elements %4d; " "Flink: %p Blink: %p\n" , this, m_nElements, m_ListEntry.Flink, m_ListEntry.Blink); if ( level > 0) { // NYI: I need to walk down the entire array. // Not just the first few entries for( i = 0; i < m_nElements; i++) { phtbeEntry = &m_rgElements[i]; cch += wsprintf( rgchBuffer + cch, " %08x %p", phtbeEntry->m_hashValue, phtbeEntry->m_phte ); if ( i % 4 == 0) { rgchBuffer[cch++] = '\n'; rgchBuffer[cch] = '\0'; } } // for } DBGDUMP(( DBG_CONTEXT, rgchBuffer)); return; } // HTB_ELEMENT::Print() /************************************************************ * Member Functions of HASH_TABLE_BUCKET ************************************************************/ HASH_TABLE_BUCKET::HASH_TABLE_BUCKET(VOID) : m_nEntries ( 0), m_htbeFirst() { InitializeListHead( &m_lHead); InitializeCriticalSection( & m_csLock); SET_CRITICAL_SECTION_SPIN_COUNT( &m_csLock, IIS_DEFAULT_CS_SPIN_COUNT); } // HASH_TABLE_BUCKET::HASH_TABLE_BUCKET() HASH_TABLE_BUCKET::~HASH_TABLE_BUCKET( VOID) { PLIST_ENTRY pl; PHTB_ELEMENT phtbe; // Free up the elements in the list Lock(); while ( !IsListEmpty( &m_lHead)) { pl = RemoveHeadList( &m_lHead); phtbe = CONTAINING_RECORD( pl, HTB_ELEMENT, m_ListEntry); delete phtbe; } // while m_htbeFirst.Cleanup(); Unlock(); DeleteCriticalSection( &m_csLock); } // HASH_TABLE_BUCKET::~HASH_TABLE_BUCKET() HT_ELEMENT * HASH_TABLE_BUCKET::Lookup( IN DWORD hashValue, IN LPCSTR pszKey, DWORD cchKey) { HT_ELEMENT * phte; Lock(); // 1. search in the first bucket phte = m_htbeFirst.Lookup( hashValue, pszKey, cchKey); if ( NULL == phte ) { // 2. search in the auxiliary buckets PLIST_ENTRY pl; for ( pl = m_lHead.Flink; (phte == NULL) && (pl != &m_lHead); pl = pl->Flink) { HTB_ELEMENT * phtbe = CONTAINING_RECORD( pl, HTB_ELEMENT, m_ListEntry); phte = phtbe->Lookup( hashValue, pszKey, cchKey); } // for } Unlock(); return (phte); } // HASH_TABLE_BUCKET::Lookup() BOOL HASH_TABLE_BUCKET::Insert( IN DWORD hashValue, IN HT_ELEMENT * phte, IN BOOL fCheckForDuplicate) { BOOL fReturn = FALSE; if ( fCheckForDuplicate) { Lock(); // do a lookup and find out if this data exists. HT_ELEMENT * phteLookedup = Lookup( hashValue, phte->QueryKey(), phte->QueryKeyLen() ); if ( NULL != phteLookedup) { // the element is already present - return failure DerefAndKillElement( phteLookedup); } Unlock(); if ( NULL != phteLookedup) { SetLastError( ERROR_DUP_NAME); return ( FALSE); } } Lock(); // 1. try inserting in the first bucket chunk, if possible if ( m_htbeFirst.IsSpaceAvailable()) { fReturn = m_htbeFirst.Insert( hashValue, phte); } else { // 2. Find the first chunk that has space and insert it there. PLIST_ENTRY pl; HTB_ELEMENT * phtbe; for ( pl = m_lHead.Flink; (pl != &m_lHead); pl = pl->Flink) { phtbe = CONTAINING_RECORD( pl, HTB_ELEMENT, m_ListEntry); if ( phtbe->IsSpaceAvailable()) { fReturn = phtbe->Insert( hashValue, phte); break; } } // for if ( !fReturn ) { // // We ran out of space. // Allocate a new bucket and insert the new element. // phtbe = new HTB_ELEMENT(); if ( NULL != phtbe) { // add the bucket to the list of buckets and // then add the element to the bucket InsertTailList( &m_lHead, &phtbe->m_ListEntry); fReturn = phtbe->Insert(hashValue, phte); } else { IF_DEBUG( ERROR) { DBGPRINTF(( DBG_CONTEXT, " HTB(%08x)::Insert: Unable to add a chunk\n", this)); } SetLastError( ERROR_NOT_ENOUGH_MEMORY); } } } Unlock(); return ( fReturn); } // HASH_TABLE_BUCKET::Insert() BOOL HASH_TABLE_BUCKET::Delete( IN HT_ELEMENT * phte) { BOOL fReturn = FALSE; // We do not know which bucket this element belongs to. // So we should try all chunks to delete this element. Lock(); // 1. try deleting the element from first bucket chunk, if possible fReturn = m_htbeFirst.Delete( phte); if (!fReturn) { // it was not on the first bucket chunk. // 2. Find the first chunk that might contain this element // and delete it. PLIST_ENTRY pl; for ( pl = m_lHead.Flink; !fReturn && (pl != &m_lHead); pl = pl->Flink) { HTB_ELEMENT * phtbe = CONTAINING_RECORD( pl, HTB_ELEMENT, m_ListEntry); fReturn = phtbe->Delete( phte); } // for // the element should have been in the hash table, // otherwise the app is calling with wrong entry DBG_ASSERT( fReturn); } Unlock(); return ( fReturn); } // HASH_TABLE_BUCKET::Delete() DWORD HASH_TABLE_BUCKET::NumEntries( VOID) { DWORD nEntries; Lock(); nEntries = m_htbeFirst.NumElements(); PLIST_ENTRY pl; for ( pl = m_lHead.Flink; (pl != &m_lHead); pl = pl->Flink) { HTB_ELEMENT * phtbe = CONTAINING_RECORD( pl, HTB_ELEMENT, m_ListEntry); nEntries += phtbe->NumElements(); } // for Unlock(); return (nEntries); } // HASH_TABLE_BUCKET::NumEntries() DWORD HASH_TABLE_BUCKET::InitializeIterator( IN HT_ITERATOR * phti) { DWORD dwErr = ERROR_NO_MORE_ITEMS; // // find the first chunk that has a valid element. // if we find one, leave the lock on for subsequent accesses. // CloseIterator will shut down the lock // If we do not find one, we should unlock and return // phti->nChunkId = NULL; phti->nPos = 0; Lock(); if ( m_htbeFirst.NumElements() > 0) { phti->nChunkId = (DWORD_PTR) &m_htbeFirst; dwErr = NO_ERROR; } else { // find the first chunk that has an element PLIST_ENTRY pl; for ( pl = m_lHead.Flink; (pl != &m_lHead); pl = pl->Flink) { HTB_ELEMENT * phtbe = CONTAINING_RECORD( pl, HTB_ELEMENT, m_ListEntry); if ( phtbe->NumElements() > 0) { phti->nChunkId = (DWORD_PTR) phtbe; dwErr = NO_ERROR; break; } } // for } // if we did not find any elements, then unlock and return // Otherwise leave the unlocking to the CloseIterator() if ( dwErr == ERROR_NO_MORE_ITEMS) { // get out of this bucket completely. Unlock(); } return ( dwErr); } // HASH_TABLE_BUCKET::InitializeIterator() DWORD HASH_TABLE_BUCKET::FindNextElement( IN HT_ITERATOR * phti, OUT HT_ELEMENT ** pphte) { // this function should be called only when the bucket is locked. DWORD dwErr; HTB_ELEMENT * phtbe = (HTB_ELEMENT * )phti->nChunkId; // // phti contains the <chunk, pos> from which we should start scan for // next element. // DBG_ASSERT( NULL != phtbe); dwErr = phtbe->FindNextElement( &phti->nPos, pphte); if ( ERROR_NO_MORE_ITEMS == dwErr ) { // scan the rest of the chunks for next element PLIST_ENTRY pl = ((phtbe == &m_htbeFirst) ? m_lHead.Flink : phtbe->m_ListEntry.Flink); for ( ; (pl != &m_lHead); pl = pl->Flink) { phtbe = CONTAINING_RECORD( pl, HTB_ELEMENT, m_ListEntry); if ( phtbe->NumElements() > 0) { phti->nPos = 0; dwErr = phtbe->FindNextElement( &phti->nPos, pphte); DBG_ASSERT( NO_ERROR == dwErr); phti->nChunkId = (DWORD_PTR) phtbe; break; } } // for } if ( dwErr == ERROR_NO_MORE_ITEMS) { phti->nChunkId = (DWORD ) NULL; } return ( dwErr); } // HASH_TABLE_BUCKET::FindNextElement() DWORD HASH_TABLE_BUCKET::CloseIterator( IN HT_ITERATOR * phti) { // just unlock the current bucket. Unlock(); return ( NO_ERROR); } // HASH_TABLE_BUCKET::CloseIterator() VOID HASH_TABLE_BUCKET::Print( IN DWORD level) { Lock(); DBGPRINTF(( DBG_CONTEXT, "\n\nHASH_TABLE_BUCKET (%08x): Head.Flink=%08x; Head.Blink=%08x\n" " Bucket Chunk # 0:\n" , this, m_lHead.Flink, m_lHead.Blink )); m_htbeFirst.Print( level); if ( level > 0) { PLIST_ENTRY pl; DWORD i; for ( pl = m_lHead.Flink, i = 1; (pl != &m_lHead); pl = pl->Flink, i++) { HTB_ELEMENT * phtbe = CONTAINING_RECORD( pl, HTB_ELEMENT, m_ListEntry); DBGPRINTF(( DBG_CONTEXT, "\n Bucket Chunk # %d\n", i)); phtbe->Print( level); } // for } Unlock(); return; } // HASH_TABLE_BUCKET::Print() /************************************************************ * Member Functions of HASH_TABLE ************************************************************/ HASH_TABLE::HASH_TABLE( IN DWORD nBuckets, IN LPCSTR pszIdentifier, IN DWORD dwHashTableFlags ) : m_nBuckets ( nBuckets), m_dwFlags ( dwHashTableFlags), m_nEntries ( 0), m_nLookups ( 0), m_nHits ( 0), m_nInserts ( 0), m_nFlushes ( 0) { if ( NULL != pszIdentifier) { lstrcpynA( m_rgchId, pszIdentifier, sizeof( m_rgchId)); } m_prgBuckets = new HASH_TABLE_BUCKET[nBuckets]; } // HASH_TABLE::HASH_TABLE() DWORD HASH_TABLE::CalculateHash( IN LPCSTR pszKey, DWORD cchKey) const { DWORD hash = 0; DBG_ASSERT( pszKey != NULL ); if ( cchKey > 8) { // // hash the last 8 characters // pszKey = (pszKey + cchKey - 8); } while ( *pszKey != '\0') { // // This is an extremely slimey way of getting upper case. // Kids, don't try this at home // -johnson // DWORD ch = ((*pszKey++) & ~0x20); // NYI: this is a totally pipe-line unfriendly code. Improve this. hash <<= 2; hash ^= ch; hash += ch; } // while // // Multiply by length (to introduce some randomness. Murali said so. // return( hash * cchKey); } // CalculateHash() VOID HASH_TABLE::Cleanup(VOID) { if ( NULL != m_prgBuckets ) { delete [] m_prgBuckets; m_prgBuckets = NULL; } } // HASH_TABLE::Cleanup() # define INCREMENT_LOOKUPS() \ { InterlockedIncrement( (LPLONG ) &m_nLookups); } # define INCREMENT_HITS( phte) \ if ( NULL != phte) { InterlockedIncrement( (LPLONG ) &m_nHits); } # define INCREMENT_INSERTS() \ { InterlockedIncrement( (LPLONG ) &m_nInserts); } # define INCREMENT_FLUSHES() \ { InterlockedIncrement( (LPLONG ) &m_nFlushes); } # define INCREMENT_ENTRIES( fRet) \ if ( fRet) { InterlockedIncrement( (LPLONG ) &m_nEntries); } # define DECREMENT_ENTRIES( fRet) \ if ( fRet) { InterlockedDecrement( (LPLONG ) &m_nEntries); } HT_ELEMENT * HASH_TABLE::Lookup( IN LPCSTR pszKey, DWORD cchKey) { // 1. Calculate the hash value for pszKey // 2. Find the bucket for the hash value // 3. Search for given item in the bucket // 4. return the result, after updating statistics DWORD hashVal = CalculateHash( pszKey, cchKey); HT_ELEMENT * phte; INCREMENT_LOOKUPS(); DBG_ASSERT( NULL != m_prgBuckets); phte = m_prgBuckets[hashVal % m_nBuckets].Lookup( hashVal, pszKey, cchKey); INCREMENT_HITS( phte); return ( phte); } // HASH_TABLE::Lookup() BOOL HASH_TABLE::Insert( HT_ELEMENT * phte, IN BOOL fCheckBeforeInsert) { // 1. Calculate the hash value for key of the HT_ELEMENT object // 2. Find the bucket for the hash value // 3. Check if this item is not already present and insert // it into the hash table. // (the check can be bypassed if fCheck is set to FALSE) // 4. return the result, after updating statistics DWORD hashVal = CalculateHash( phte->QueryKey()); BOOL fRet; INCREMENT_INSERTS(); DBG_ASSERT( NULL != m_prgBuckets); fRet = m_prgBuckets[hashVal % m_nBuckets].Insert( hashVal, phte, fCheckBeforeInsert); IF_DEBUG( ERROR) { if ( !fRet) { DBGPRINTF(( DBG_CONTEXT, " Unable to insert %08x into bucket %d." " Bucket has %d elements. Error = %d\n", phte, hashVal % m_nBuckets, m_prgBuckets[hashVal % m_nBuckets].NumEntries(), GetLastError() )); } } INCREMENT_ENTRIES( fRet); return ( fRet); } // HASH_TABLE::Insert() BOOL HASH_TABLE::Delete( HT_ELEMENT * phte) { BOOL fRet; DWORD hashVal = CalculateHash( phte->QueryKey(), phte->QueryKeyLen()); DBG_ASSERT( NULL != m_prgBuckets); fRet = m_prgBuckets[hashVal % m_nBuckets].Delete( phte); DECREMENT_ENTRIES( fRet); return ( fRet); } // HASH_TABLE::Delete() VOID HASH_TABLE::Print( IN DWORD level) { DWORD i; DBGPRINTF(( DBG_CONTEXT, "HASH_TABLE(%08x) " "%s: nBuckets = %d; dwFlags = %d;" " nEntries = %d; nLookups = %d; nHits = %d;" " nInserts = %d; nFlushes = %d;" " m_prgBuckets = %d\n", this, m_rgchId, m_nBuckets, m_dwFlags, m_nEntries, m_nLookups, m_nHits, m_nInserts, m_nFlushes, m_prgBuckets)); if ( level == 0 ) { CHAR rgchBuff[2000]; DWORD cch; cch = wsprintfA( rgchBuff, "\tBucket NumEntries\n"); DBG_ASSERT( NULL != m_prgBuckets); for (i = 0; i < m_nBuckets; i++) { cch += wsprintf( rgchBuff + cch, "\t[%4d] %4d,\n", i, m_prgBuckets[i].NumEntries()); } // for DBGDUMP(( DBG_CONTEXT, rgchBuff)); } else { DBG_ASSERT( NULL != m_prgBuckets); for (i = 0; i < m_nBuckets; i++) { m_prgBuckets[i].Print( level); } // for } return; } // HASH_TABLE::Print() DWORD HASH_TABLE::InitializeIterator( IN HT_ITERATOR * phti) { DWORD dwErr = ERROR_NO_MORE_ITEMS; DBG_ASSERT( IsValid()); DBG_ASSERT( NULL != phti); // initialize the iterator phti->nBucketNumber = INFINITE; phti->nChunkId = NULL; phti->nPos = 0; if ( m_nEntries > 0) { // set the iterator to point to the first bucket with some elements. for ( DWORD i = 0; (i < m_nBuckets); i++) { dwErr = m_prgBuckets[i].InitializeIterator( phti); if ( dwErr == NO_ERROR) { phti->nBucketNumber = i; break; } } } return ( dwErr); } // HASH_TABLE::InitializeIterator() DWORD HASH_TABLE::FindNextElement( IN HT_ITERATOR * phti, OUT HT_ELEMENT ** pphte) { DWORD dwErr = ERROR_NO_MORE_ITEMS; DBG_ASSERT( IsValid()); DBG_ASSERT( NULL != phti); DBG_ASSERT( NULL != pphte); if ( INFINITE != phti->nBucketNumber) { // iterator has some valid state use it. DBG_ASSERT( phti->nBucketNumber < m_nBuckets); dwErr = m_prgBuckets[ phti->nBucketNumber].FindNextElement( phti, pphte); if ( ERROR_NO_MORE_ITEMS == dwErr) { DBG_REQUIRE( m_prgBuckets[ phti->nBucketNumber]. CloseIterator( phti) == NO_ERROR ); // hunt for the next bucket with an element. for ( DWORD i = (phti->nBucketNumber + 1); (i < m_nBuckets); i++) { dwErr = m_prgBuckets[i].InitializeIterator( phti); if ( dwErr == NO_ERROR) { phti->nBucketNumber = i; dwErr = m_prgBuckets[ i].FindNextElement( phti, pphte); DBG_ASSERT( dwErr == NO_ERROR); break; } } // for if ( ERROR_NO_MORE_ITEMS == dwErr) { // reset the bucket number phti->nBucketNumber = INFINITE; } } } return ( dwErr); } // HASH_TABLE::FindNextElement() DWORD HASH_TABLE::CloseIterator( IN HT_ITERATOR * phti) { DBG_ASSERT( IsValid()); DBG_ASSERT( NULL != phti); if ( INFINITE != phti->nBucketNumber) { DBG_ASSERT( phti->nBucketNumber < m_nBuckets); DBG_REQUIRE( m_prgBuckets[ phti->nBucketNumber]. CloseIterator( phti) == NO_ERROR ); phti->nBucketNumber = INFINITE; } return ( NO_ERROR); } // HASH_TABLE::CloseIterator() /************************ End of File ***********************/
26.710212
83
0.5145
[ "object" ]
f357fc8fb08c01f91bd577a8aa037e6f843d9952
2,406
cpp
C++
Algorithm/Project3.cpp
SamuelWongSN/UTA-Projects
dba16be8d9c1dbbe8d418e7880db264445a8b5eb
[ "MIT" ]
null
null
null
Algorithm/Project3.cpp
SamuelWongSN/UTA-Projects
dba16be8d9c1dbbe8d418e7880db264445a8b5eb
[ "MIT" ]
null
null
null
Algorithm/Project3.cpp
SamuelWongSN/UTA-Projects
dba16be8d9c1dbbe8d418e7880db264445a8b5eb
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <stack> using namespace std; int timestamp = 0; typedef struct Node { int color; int pai; int starttime; int finishtime; }; //存储每个节点所需信息 struct Node list[12]; vector<int> Topo_list; void DFS_Visit(int u, vector<vector<int>> array) { cout << u << " "; list[u].color = 1; timestamp++; list[u].starttime = timestamp; for (int v = 0; v < array[u].size(); v++) { int tempv = array[u][v]; if (list[tempv].color == 0) { list[tempv].pai = u; DFS_Visit(tempv, array); } } list[u].color = 2; Topo_list.push_back(u); timestamp++; list[u].finishtime = timestamp; } void DFS(vector<vector<int>> array) { for (int i = 1; i < 12; i++) { list[i].color = 0; list[i].pai = -1; } //从点7开始 /* cout << "Root of tree : " << 7 << endl; cout << "Tree :"; DFS_Visit(7, array); */ //从点11开始 /* cout << "Root of tree : " << 11 << endl; cout << "Tree :"; DFS_Visit(11, array); */ for (int i = 1; i < 12; i++) { if (list[i].color == 0) { cout << "Root of tree : " << i << endl; cout << "Tree :"; DFS_Visit(i, array); cout << endl; } } } int main() { //初始化为12 * 12大小的数组用于存储 //array[m][n] = 1,意味着有从m指向n的线 vector<vector<int>> array; for (int i = 0; i < 12; i++) { vector<int> path; array.push_back(path); } //初始化二维数组 array[1].push_back(2); array[2].push_back(3); array[3].push_back(6); array[4].push_back(1), array[4].push_back(5); array[5].push_back(1); array[6].push_back(8), array[6].push_back(9); array[7].push_back(4), array[7].push_back(10); array[8].push_back(5), array[8].push_back(9); array[10].push_back(8), array[10].push_back(11); array[11].push_back(9); //邻接矩阵 cout << "邻接链表:" << endl; for (int i = 1; i < 12; i++) { cout << i; for (int j = 0; j < array[i].size(); j++) { cout << "->" << array[i][j]; } cout << endl; } cout << endl; cout << "start from Node 1:"<<endl; DFS(array); cout << endl << "Topo_list:" << endl; for (int i = Topo_list.size()-1; i >= 0; i--) { cout << Topo_list[i] << " "; Topo_list.pop_back(); } cout << endl << endl; for (int i = 1; i < 12; i++) { cout << "Node " << i << " starttime = " << list[i].starttime << ", finishtime = " << list[i].finishtime << endl; } cout << endl; return 0; }
19.095238
115
0.530756
[ "vector" ]
f35a751173b05639334f3d5ac87707a589a51d39
43,536
cc
C++
chrome/browser/ui/webui/print_preview/print_preview_ui.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/browser/ui/webui/print_preview/print_preview_ui.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
chrome/browser/ui/webui/print_preview/print_preview_ui.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/print_preview/print_preview_ui.h" #include <string> #include <utility> #include <vector> #include "ash/constants/ash_features.h" #include "base/bind.h" #include "base/containers/flat_map.h" #include "base/containers/id_map.h" #include "base/files/file_path.h" #include "base/lazy_instance.h" #include "base/memory/ref_counted_memory.h" #include "base/metrics/histogram_functions.h" #include "base/numerics/safe_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/synchronization/lock.h" #include "base/values.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/pdf/pdf_extension_util.h" #include "chrome/browser/printing/background_printing_manager.h" #include "chrome/browser/printing/pdf_nup_converter_client.h" #include "chrome/browser/printing/print_job_manager.h" #include "chrome/browser/printing/print_preview_data_service.h" #include "chrome/browser/printing/print_preview_dialog_controller.h" #include "chrome/browser/printing/print_view_manager.h" #include "chrome/browser/printing/printer_query.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/ui_features.h" #include "chrome/browser/ui/webui/metrics_handler.h" #include "chrome/browser/ui/webui/plural_string_handler.h" #include "chrome/browser/ui/webui/print_preview/data_request_filter.h" #include "chrome/browser/ui/webui/print_preview/print_preview_handler.h" #include "chrome/browser/ui/webui/theme_source.h" #include "chrome/browser/ui/webui/webui_util.h" #include "chrome/common/buildflags.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "chrome/grit/browser_resources.h" #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" #include "chrome/grit/print_preview_resources.h" #include "chrome/grit/print_preview_resources_map.h" #include "components/prefs/pref_service.h" #include "components/printing/browser/print_composite_client.h" #include "components/printing/browser/print_manager_utils.h" #include "components/strings/grit/components_strings.h" #include "components/user_manager/user_manager.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/url_data_source.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui_data_source.h" #include "content/public/common/url_constants.h" #include "extensions/common/constants.h" #include "mojo/public/cpp/bindings/callback_helpers.h" #include "printing/buildflags/buildflags.h" #include "printing/mojom/print.mojom.h" #include "printing/nup_parameters.h" #include "printing/print_job_constants.h" #include "services/network/public/mojom/content_security_policy.mojom.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/webui/web_ui_util.h" #include "ui/gfx/geometry/rect.h" #include "ui/web_dialogs/web_dialog_delegate.h" #include "ui/web_dialogs/web_dialog_ui.h" #if defined(OS_CHROMEOS) #include "chrome/browser/ui/webui/print_preview/print_preview_handler_chromeos.h" #endif #if !BUILDFLAG(OPTIMIZE_WEBUI) #include "chrome/browser/ui/webui/managed_ui_handler.h" #endif #if BUILDFLAG(ENABLE_OOP_PRINTING) #include "chrome/browser/printing/print_backend_service_manager.h" #include "printing/printing_features.h" #endif using content::WebContents; namespace printing { namespace { #if defined(OS_MAC) const char16_t kBasicPrintShortcut[] = u"\u0028\u21e7\u2318\u0050\u0029"; #elif !defined(OS_CHROMEOS) const char16_t kBasicPrintShortcut[] = u"(Ctrl+Shift+P)"; #endif constexpr char kInvalidArgsForDidStartPreview[] = "Invalid arguments for DidStartPreview"; constexpr char kInvalidPageNumberForDidPreviewPage[] = "Invalid page number for DidPreviewPage"; constexpr char kInvalidPageCountForMetafileReadyForPrinting[] = "Invalid page count for MetafileReadyForPrinting"; PrintPreviewUI::TestDelegate* g_test_delegate = nullptr; void StopWorker(int document_cookie) { if (document_cookie <= 0) return; scoped_refptr<PrintQueriesQueue> queue = g_browser_process->print_job_manager()->queue(); std::unique_ptr<PrinterQuery> printer_query = queue->PopPrinterQuery(document_cookie); if (printer_query) { content::GetIOThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&PrinterQuery::StopWorker, std::move(printer_query))); } } bool IsValidPageNumber(uint32_t page_number, uint32_t page_count) { return page_number < page_count; } bool ShouldUseCompositor(PrintPreviewUI* print_preview_ui) { return IsOopifEnabled() && print_preview_ui->source_is_modifiable(); } WebContents* GetInitiator(content::WebUI* web_ui) { PrintPreviewDialogController* dialog_controller = PrintPreviewDialogController::GetInstance(); if (!dialog_controller) return nullptr; return dialog_controller->GetInitiator(web_ui->GetWebContents()); } // Thread-safe wrapper around a base::flat_map to keep track of mappings from // PrintPreviewUI IDs to most recent print preview request IDs. class PrintPreviewRequestIdMapWithLock { public: PrintPreviewRequestIdMapWithLock() {} PrintPreviewRequestIdMapWithLock(const PrintPreviewRequestIdMapWithLock&) = delete; PrintPreviewRequestIdMapWithLock& operator=( const PrintPreviewRequestIdMapWithLock&) = delete; ~PrintPreviewRequestIdMapWithLock() {} // Gets the value for |preview_id|. // Returns true and sets |out_value| on success. bool Get(int32_t preview_id, int* out_value) { base::AutoLock lock(lock_); PrintPreviewRequestIdMap::const_iterator it = map_.find(preview_id); if (it == map_.end()) return false; *out_value = it->second; return true; } // Sets the |value| for |preview_id|. void Set(int32_t preview_id, int value) { base::AutoLock lock(lock_); map_[preview_id] = value; } // Erases the entry for |preview_id|. void Erase(int32_t preview_id) { base::AutoLock lock(lock_); map_.erase(preview_id); } private: // Mapping from PrintPreviewUI ID to print preview request ID. using PrintPreviewRequestIdMap = base::flat_map<int, int>; PrintPreviewRequestIdMap map_; base::Lock lock_; }; // Written to on the UI thread, read from any thread. base::LazyInstance<PrintPreviewRequestIdMapWithLock>::DestructorAtExit g_print_preview_request_id_map = LAZY_INSTANCE_INITIALIZER; // PrintPreviewUI IDMap used to avoid exposing raw pointer addresses to WebUI. // Only accessed on the UI thread. base::LazyInstance<base::IDMap<PrintPreviewUI*>>::DestructorAtExit g_print_preview_ui_id_map = LAZY_INSTANCE_INITIALIZER; void AddPrintPreviewStrings(content::WebUIDataSource* source) { static constexpr webui::LocalizedString kLocalizedStrings[] = { {"accountSelectTitle", IDS_PRINT_PREVIEW_ACCOUNT_SELECT_TITLE}, {"addAccountTitle", IDS_PRINT_PREVIEW_ADD_ACCOUNT_TITLE}, {"advancedSettingsDialogConfirm", IDS_PRINT_PREVIEW_ADVANCED_SETTINGS_DIALOG_CONFIRM}, {"advancedSettingsDialogTitle", IDS_PRINT_PREVIEW_ADVANCED_SETTINGS_DIALOG_TITLE}, {"advancedSettingsSearchBoxPlaceholder", IDS_PRINT_PREVIEW_ADVANCED_SETTINGS_SEARCH_BOX_PLACEHOLDER}, {"bottom", IDS_PRINT_PREVIEW_BOTTOM_MARGIN_LABEL}, {"cancel", IDS_CANCEL}, {"clearSearch", IDS_CLEAR_SEARCH}, {"copiesInstruction", IDS_PRINT_PREVIEW_COPIES_INSTRUCTION}, {"copiesLabel", IDS_PRINT_PREVIEW_COPIES_LABEL}, {"couldNotPrint", IDS_PRINT_PREVIEW_COULD_NOT_PRINT}, {"customMargins", IDS_PRINT_PREVIEW_CUSTOM_MARGINS}, {"defaultMargins", IDS_PRINT_PREVIEW_DEFAULT_MARGINS}, {"destinationLabel", IDS_PRINT_PREVIEW_DESTINATION_LABEL}, {"destinationSearchTitle", IDS_PRINT_PREVIEW_DESTINATION_SEARCH_TITLE}, {"dpiItemLabel", IDS_PRINT_PREVIEW_DPI_ITEM_LABEL}, {"dpiLabel", IDS_PRINT_PREVIEW_DPI_LABEL}, {"examplePageRangeText", IDS_PRINT_PREVIEW_EXAMPLE_PAGE_RANGE_TEXT}, {"extensionDestinationIconTooltip", IDS_PRINT_PREVIEW_EXTENSION_DESTINATION_ICON_TOOLTIP}, {"goBackButton", IDS_PRINT_PREVIEW_BUTTON_GO_BACK}, {"invalidPrinterSettings", IDS_PRINT_PREVIEW_INVALID_PRINTER_SETTINGS}, {"layoutLabel", IDS_PRINT_PREVIEW_LAYOUT_LABEL}, {"learnMore", IDS_LEARN_MORE}, {"left", IDS_PRINT_PREVIEW_LEFT_MARGIN_LABEL}, {"loading", IDS_PRINT_PREVIEW_LOADING}, {"manage", IDS_PRINT_PREVIEW_MANAGE}, {"managedSettings", IDS_PRINT_PREVIEW_MANAGED_SETTINGS_TEXT}, {"marginsLabel", IDS_PRINT_PREVIEW_MARGINS_LABEL}, {"mediaSizeLabel", IDS_PRINT_PREVIEW_MEDIA_SIZE_LABEL}, {"minimumMargins", IDS_PRINT_PREVIEW_MINIMUM_MARGINS}, {"moreOptionsLabel", IDS_MORE_OPTIONS_LABEL}, {"newShowAdvancedOptions", IDS_PRINT_PREVIEW_NEW_SHOW_ADVANCED_OPTIONS}, {"noAdvancedSettingsMatchSearchHint", IDS_PRINT_PREVIEW_NO_ADVANCED_SETTINGS_MATCH_SEARCH_HINT}, {"noDestinationsMessage", IDS_PRINT_PREVIEW_NO_DESTINATIONS_MESSAGE}, {"noLongerSupported", IDS_PRINT_PREVIEW_NO_LONGER_SUPPORTED}, {"noLongerSupportedFragment", IDS_PRINT_PREVIEW_NO_LONGER_SUPPORTED_FRAGMENT}, {"noMargins", IDS_PRINT_PREVIEW_NO_MARGINS}, {"nonIsotropicDpiItemLabel", IDS_PRINT_PREVIEW_NON_ISOTROPIC_DPI_ITEM_LABEL}, {"offline", IDS_PRINT_PREVIEW_OFFLINE}, {"offlineForMonth", IDS_PRINT_PREVIEW_OFFLINE_FOR_MONTH}, {"offlineForWeek", IDS_PRINT_PREVIEW_OFFLINE_FOR_WEEK}, {"offlineForYear", IDS_PRINT_PREVIEW_OFFLINE_FOR_YEAR}, {"optionAllPages", IDS_PRINT_PREVIEW_OPTION_ALL_PAGES}, {"optionBackgroundColorsAndImages", IDS_PRINT_PREVIEW_OPTION_BACKGROUND_COLORS_AND_IMAGES}, {"optionBw", IDS_PRINT_PREVIEW_OPTION_BW}, {"optionCollate", IDS_PRINT_PREVIEW_OPTION_COLLATE}, {"optionColor", IDS_PRINT_PREVIEW_OPTION_COLOR}, {"optionCustomPages", IDS_PRINT_PREVIEW_OPTION_CUSTOM_PAGES}, {"optionCustomScaling", IDS_PRINT_PREVIEW_OPTION_CUSTOM_SCALING}, {"optionDefaultScaling", IDS_PRINT_PREVIEW_OPTION_DEFAULT_SCALING}, {"optionEvenPages", IDS_PRINT_PREVIEW_OPTION_EVEN_PAGES}, {"optionFitToPage", IDS_PRINT_PREVIEW_OPTION_FIT_TO_PAGE}, {"optionFitToPaper", IDS_PRINT_PREVIEW_OPTION_FIT_TO_PAPER}, {"optionHeaderFooter", IDS_PRINT_PREVIEW_OPTION_HEADER_FOOTER}, {"optionLandscape", IDS_PRINT_PREVIEW_OPTION_LANDSCAPE}, {"optionLongEdge", IDS_PRINT_PREVIEW_OPTION_LONG_EDGE}, {"optionOddPages", IDS_PRINT_PREVIEW_OPTION_ODD_PAGES}, {"optionPortrait", IDS_PRINT_PREVIEW_OPTION_PORTRAIT}, {"optionRasterize", IDS_PRINT_PREVIEW_OPTION_RASTERIZE}, {"optionSelectionOnly", IDS_PRINT_PREVIEW_OPTION_SELECTION_ONLY}, {"optionShortEdge", IDS_PRINT_PREVIEW_OPTION_SHORT_EDGE}, {"optionTwoSided", IDS_PRINT_PREVIEW_OPTION_TWO_SIDED}, {"optionsLabel", IDS_PRINT_PREVIEW_OPTIONS_LABEL}, {"pageDescription", IDS_PRINT_PREVIEW_DESCRIPTION}, {"pageRangeLimitInstructionWithValue", IDS_PRINT_PREVIEW_PAGE_RANGE_LIMIT_INSTRUCTION_WITH_VALUE}, {"pageRangeSyntaxInstruction", IDS_PRINT_PREVIEW_PAGE_RANGE_SYNTAX_INSTRUCTION}, {"pagesLabel", IDS_PRINT_PREVIEW_PAGES_LABEL}, {"pagesPerSheetLabel", IDS_PRINT_PREVIEW_PAGES_PER_SHEET_LABEL}, {"previewFailed", IDS_PRINT_PREVIEW_FAILED}, {"printOnBothSidesLabel", IDS_PRINT_PREVIEW_PRINT_ON_BOTH_SIDES_LABEL}, {"printButton", IDS_PRINT_PREVIEW_PRINT_BUTTON}, {"printDestinationsTitle", IDS_PRINT_PREVIEW_PRINT_DESTINATIONS_TITLE}, {"printPagesLabel", IDS_PRINT_PREVIEW_PRINT_PAGES_LABEL}, #if defined(OS_CHROMEOS) {"printToGoogleDrive", IDS_PRINT_PREVIEW_PRINT_TO_GOOGLE_DRIVE}, #endif {"printToPDF", IDS_PRINT_PREVIEW_PRINT_TO_PDF}, {"printing", IDS_PRINT_PREVIEW_PRINTING}, {"recentDestinationsTitle", IDS_PRINT_PREVIEW_RECENT_DESTINATIONS_TITLE}, {"registerPrinterInformationMessage", IDS_CLOUD_PRINT_REGISTER_PRINTER_INFORMATION}, {"resolveExtensionUSBDialogTitle", IDS_PRINT_PREVIEW_RESOLVE_EXTENSION_USB_DIALOG_TITLE}, {"resolveExtensionUSBErrorMessage", IDS_PRINT_PREVIEW_RESOLVE_EXTENSION_USB_ERROR_MESSAGE}, {"resolveExtensionUSBPermissionMessage", IDS_PRINT_PREVIEW_RESOLVE_EXTENSION_USB_PERMISSION_MESSAGE}, {"right", IDS_PRINT_PREVIEW_RIGHT_MARGIN_LABEL}, {"saveButton", IDS_PRINT_PREVIEW_SAVE_BUTTON}, {"saving", IDS_PRINT_PREVIEW_SAVING}, {"scalingInstruction", IDS_PRINT_PREVIEW_SCALING_INSTRUCTION}, {"scalingLabel", IDS_PRINT_PREVIEW_SCALING_LABEL}, {"searchBoxPlaceholder", IDS_PRINT_PREVIEW_SEARCH_BOX_PLACEHOLDER}, {"searchResultBubbleText", IDS_SEARCH_RESULT_BUBBLE_TEXT}, {"searchResultsBubbleText", IDS_SEARCH_RESULTS_BUBBLE_TEXT}, {"selectButton", IDS_PRINT_PREVIEW_BUTTON_SELECT}, {"seeMore", IDS_PRINT_PREVIEW_SEE_MORE}, {"seeMoreDestinationsLabel", IDS_PRINT_PREVIEW_SEE_MORE_DESTINATIONS_LABEL}, #if defined(OS_CHROMEOS) {"serverSearchBoxPlaceholder", IDS_PRINT_PREVIEW_SERVER_SEARCH_BOX_PLACEHOLDER}, #endif {"title", IDS_PRINT_PREVIEW_TITLE}, {"top", IDS_PRINT_PREVIEW_TOP_MARGIN_LABEL}, {"unsupportedCloudPrinter", IDS_PRINT_PREVIEW_UNSUPPORTED_CLOUD_PRINTER}, #if defined(OS_CHROMEOS) {"configuringFailedText", IDS_PRINT_CONFIGURING_FAILED_TEXT}, {"configuringInProgressText", IDS_PRINT_CONFIGURING_IN_PROGRESS_TEXT}, {"optionPin", IDS_PRINT_PREVIEW_OPTION_PIN}, {"pinErrorMessage", IDS_PRINT_PREVIEW_PIN_ERROR_MESSAGE}, {"pinPlaceholder", IDS_PRINT_PREVIEW_PIN_PLACEHOLDER}, {"printerEulaURL", IDS_PRINT_PREVIEW_EULA_URL}, {"printerStatusDeviceError", IDS_PRINT_PREVIEW_PRINTER_STATUS_DEVICE_ERROR}, {"printerStatusDoorOpen", IDS_PRINT_PREVIEW_PRINTER_STATUS_DOOR_OPEN}, {"printerStatusLowOnInk", IDS_PRINT_PREVIEW_PRINTER_STATUS_LOW_ON_INK}, {"printerStatusLowOnPaper", IDS_PRINT_PREVIEW_PRINTER_STATUS_LOW_ON_PAPER}, {"printerStatusOutOfInk", IDS_PRINT_PREVIEW_PRINTER_STATUS_OUT_OF_INK}, {"printerStatusOutOfPaper", IDS_PRINT_PREVIEW_PRINTER_STATUS_OUT_OF_PAPER}, {"printerStatusOutputAlmostFull", IDS_PRINT_PREVIEW_PRINTER_STATUS_OUPUT_ALMOST_FULL}, {"printerStatusOutputFull", IDS_PRINT_PREVIEW_PRINTER_STATUS_OUPUT_FULL}, {"printerStatusPaperJam", IDS_PRINT_PREVIEW_PRINTER_STATUS_PAPER_JAM}, {"printerStatusPaused", IDS_PRINT_PREVIEW_PRINTER_STATUS_PAUSED}, {"printerStatusPrinterQueueFull", IDS_PRINT_PREVIEW_PRINTER_STATUS_PRINTER_QUEUE_FULL}, {"printerStatusPrinterUnreachable", IDS_PRINT_PREVIEW_PRINTER_STATUS_PRINTER_UNREACHABLE}, {"printerStatusStopped", IDS_PRINT_PREVIEW_PRINTER_STATUS_STOPPED}, {"printerStatusTrayMissing", IDS_PRINT_PREVIEW_PRINTER_STATUS_TRAY_MISSING}, #endif #if defined(OS_MAC) {"openPdfInPreviewOption", IDS_PRINT_PREVIEW_OPEN_PDF_IN_PREVIEW_APP}, {"openingPDFInPreview", IDS_PRINT_PREVIEW_OPENING_PDF_IN_PREVIEW_APP}, #endif }; source->AddLocalizedStrings(kLocalizedStrings); source->AddString("gcpCertificateErrorLearnMoreURL", chrome::kCloudPrintCertificateErrorLearnMoreURL); #if !defined(OS_CHROMEOS) const std::u16string shortcut_text(kBasicPrintShortcut); source->AddString("systemDialogOption", l10n_util::GetStringFUTF16( IDS_PRINT_PREVIEW_SYSTEM_DIALOG_OPTION, shortcut_text)); #endif // Register strings for the PDF viewer, so that $i18n{} replacements work. base::Value pdf_strings(base::Value::Type::DICTIONARY); pdf_extension_util::AddStrings( pdf_extension_util::PdfViewerContext::kPrintPreview, &pdf_strings); pdf_extension_util::AddAdditionalData(/*enable_annotations=*/false, &pdf_strings); source->AddLocalizedStrings(base::Value::AsDictionaryValue(pdf_strings)); } void AddPrintPreviewFlags(content::WebUIDataSource* source, Profile* profile) { #if defined(OS_CHROMEOS) source->AddBoolean("useSystemDefaultPrinter", false); #else bool system_default_printer = profile->GetPrefs()->GetBoolean( prefs::kPrintPreviewUseSystemDefaultPrinter); source->AddBoolean("useSystemDefaultPrinter", system_default_printer); #endif source->AddBoolean("isEnterpriseManaged", webui::IsEnterpriseManaged()); } void SetupPrintPreviewPlugin(content::WebUIDataSource* source) { // TODO(crbug.com/1238829): Only serve PDF from chrome-untrusted://print. The // legacy Pepper-based PDF plugin still requires this. AddDataRequestFilter(*source); source->OverrideContentSecurityPolicy( network::mojom::CSPDirectiveName::ChildSrc, "child-src 'self' chrome-untrusted://print;"); source->DisableDenyXFrameOptions(); source->OverrideContentSecurityPolicy( network::mojom::CSPDirectiveName::ObjectSrc, "object-src chrome-untrusted://print;"); } content::WebUIDataSource* CreatePrintPreviewUISource(Profile* profile) { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIPrintHost); webui::SetupWebUIDataSource( source, base::make_span(kPrintPreviewResources, kPrintPreviewResourcesSize), IDR_PRINT_PREVIEW_PRINT_PREVIEW_HTML); AddPrintPreviewStrings(source); SetupPrintPreviewPlugin(source); AddPrintPreviewFlags(source, profile); return source; } PrintPreviewHandler* CreatePrintPreviewHandlers(content::WebUI* web_ui) { auto handler = std::make_unique<PrintPreviewHandler>(); PrintPreviewHandler* handler_ptr = handler.get(); #if defined(OS_CHROMEOS) web_ui->AddMessageHandler(std::make_unique<PrintPreviewHandlerChromeOS>()); #endif web_ui->AddMessageHandler(std::move(handler)); web_ui->AddMessageHandler(std::make_unique<MetricsHandler>()); // Add a handler to provide pluralized strings. auto plural_string_handler = std::make_unique<PluralStringHandler>(); plural_string_handler->AddLocalizedString( "printPreviewPageSummaryLabel", IDS_PRINT_PREVIEW_PAGE_SUMMARY_LABEL); plural_string_handler->AddLocalizedString( "printPreviewSheetSummaryLabel", IDS_PRINT_PREVIEW_SHEET_SUMMARY_LABEL); #if defined(OS_CHROMEOS) plural_string_handler->AddLocalizedString( "sheetsLimitErrorMessage", IDS_PRINT_PREVIEW_SHEETS_LIMIT_ERROR_MESSAGE); #endif web_ui->AddMessageHandler(std::move(plural_string_handler)); return handler_ptr; } } // namespace PrintPreviewUI::PrintPreviewUI(content::WebUI* web_ui, std::unique_ptr<PrintPreviewHandler> handler) : ConstrainedWebDialogUI(web_ui), initial_preview_start_time_(base::TimeTicks::Now()), handler_(handler.get()) { web_ui->AddMessageHandler(std::move(handler)); #if BUILDFLAG(ENABLE_OOP_PRINTING) // Register with print backend service manager; it is beneficial to have a // the print backend service be present and ready for at least as long as // this UI is around. if (base::FeatureList::IsEnabled(features::kEnableOopPrintDrivers)) { service_manager_client_id_ = PrintBackendServiceManager::GetInstance().RegisterClient(); } #endif } PrintPreviewUI::PrintPreviewUI(content::WebUI* web_ui) : ConstrainedWebDialogUI(web_ui), initial_preview_start_time_(base::TimeTicks::Now()), handler_(CreatePrintPreviewHandlers(web_ui)) { // Allow requests to URLs like chrome-untrusted://print/. web_ui->AddRequestableScheme(content::kChromeUIUntrustedScheme); // Set up the chrome://print/ data source. Profile* profile = Profile::FromWebUI(web_ui); content::WebUIDataSource* source = CreatePrintPreviewUISource(profile); #if !BUILDFLAG(OPTIMIZE_WEBUI) // For the Polymer 3 demo page. ManagedUIHandler::Initialize(web_ui, source); #endif content::WebUIDataSource::Add(profile, source); // Set up the chrome://theme/ source. content::URLDataSource::Add(profile, std::make_unique<ThemeSource>(profile)); #if BUILDFLAG(ENABLE_OOP_PRINTING) // Register with print backend service manager; it is beneficial to have a // the print backend service be present and ready for at least as long as // this UI is around. if (base::FeatureList::IsEnabled(features::kEnableOopPrintDrivers)) { service_manager_client_id_ = PrintBackendServiceManager::GetInstance().RegisterClient(); } #endif } PrintPreviewUI::~PrintPreviewUI() { #if BUILDFLAG(ENABLE_OOP_PRINTING) if (base::FeatureList::IsEnabled(features::kEnableOopPrintDrivers)) { PrintBackendServiceManager::GetInstance().UnregisterClient( service_manager_client_id_); } #endif ClearPreviewUIId(); } mojo::PendingAssociatedRemote<mojom::PrintPreviewUI> PrintPreviewUI::BindPrintPreviewUI() { return receiver_.BindNewEndpointAndPassRemote(); } bool PrintPreviewUI::IsBound() const { return receiver_.is_bound(); } void PrintPreviewUI::ClearPreviewUIId() { if (!id_) return; receiver_.reset(); PrintPreviewDataService::GetInstance()->RemoveEntry(*id_); g_print_preview_request_id_map.Get().Erase(*id_); g_print_preview_ui_id_map.Get().Remove(*id_); id_.reset(); } void PrintPreviewUI::GetPrintPreviewDataForIndex( int index, scoped_refptr<base::RefCountedMemory>* data) const { PrintPreviewDataService::GetInstance()->GetDataEntry(*id_, index, data); } void PrintPreviewUI::SetPrintPreviewDataForIndex( int index, scoped_refptr<base::RefCountedMemory> data) { PrintPreviewDataService::GetInstance()->SetDataEntry(*id_, index, std::move(data)); } void PrintPreviewUI::ClearAllPreviewData() { PrintPreviewDataService::GetInstance()->RemoveEntry(*id_); } void PrintPreviewUI::NotifyUIPreviewPageReady( uint32_t page_number, int request_id, scoped_refptr<base::RefCountedMemory> data_bytes) { if (!data_bytes || !data_bytes->size()) return; // Don't bother notifying the UI if this request has been cancelled already. if (ShouldCancelRequest(id_, request_id)) return; DCHECK_NE(page_number, kInvalidPageIndex); SetPrintPreviewDataForIndex(base::checked_cast<int>(page_number), std::move(data_bytes)); if (g_test_delegate) g_test_delegate->DidRenderPreviewPage(web_ui()->GetWebContents()); handler_->SendPagePreviewReady(base::checked_cast<int>(page_number), *id_, request_id); } void PrintPreviewUI::NotifyUIPreviewDocumentReady( int request_id, scoped_refptr<base::RefCountedMemory> data_bytes) { if (!data_bytes || !data_bytes->size()) return; // Don't bother notifying the UI if this request has been cancelled already. if (ShouldCancelRequest(id_, request_id)) return; if (!initial_preview_start_time_.is_null()) { base::UmaHistogramTimes( "PrintPreview.InitialDisplayTime", base::TimeTicks::Now() - initial_preview_start_time_); initial_preview_start_time_ = base::TimeTicks(); } SetPrintPreviewDataForIndex(COMPLETE_PREVIEW_DOCUMENT_INDEX, std::move(data_bytes)); handler_->OnPrintPreviewReady(*id_, request_id); } void PrintPreviewUI::OnCompositePdfPageDone( uint32_t page_number, int document_cookie, int32_t request_id, mojom::PrintCompositor::Status status, base::ReadOnlySharedMemoryRegion region) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (ShouldCancelRequest(id_, request_id)) return; if (status != mojom::PrintCompositor::Status::kSuccess) { DLOG(ERROR) << "Compositing pdf failed with error " << status; OnPrintPreviewFailed(request_id); return; } if (pages_per_sheet_ == 1) { NotifyUIPreviewPageReady( page_number, request_id, base::RefCountedSharedMemoryMapping::CreateFromWholeRegion(region)); } else { AddPdfPageForNupConversion(std::move(region)); uint32_t current_page_index = GetPageToNupConvertIndex(page_number); if (current_page_index == kInvalidPageIndex) return; if (((current_page_index + 1) % pages_per_sheet_) == 0 || LastPageComposited(page_number)) { uint32_t new_page_number = base::checked_cast<uint32_t>(current_page_index / pages_per_sheet_); DCHECK_NE(new_page_number, kInvalidPageIndex); std::vector<base::ReadOnlySharedMemoryRegion> pdf_page_regions = TakePagesForNupConvert(); gfx::Rect printable_rect = PageSetup::GetSymmetricalPrintableArea(page_size(), printable_area()); if (printable_rect.IsEmpty()) return; WebContents* web_contents = GetInitiator(web_ui()); if (!web_contents) return; auto* client = PdfNupConverterClient::FromWebContents(web_contents); DCHECK(client); client->DoNupPdfConvert( document_cookie, pages_per_sheet_, page_size(), printable_rect, std::move(pdf_page_regions), mojo::WrapCallbackWithDefaultInvokeIfNotRun( base::BindOnce(&PrintPreviewUI::OnNupPdfConvertDone, weak_ptr_factory_.GetWeakPtr(), new_page_number, request_id), mojom::PdfNupConverter::Status::CONVERSION_FAILURE, base::ReadOnlySharedMemoryRegion())); } } } void PrintPreviewUI::OnNupPdfConvertDone( uint32_t page_number, int32_t request_id, mojom::PdfNupConverter::Status status, base::ReadOnlySharedMemoryRegion region) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (status != mojom::PdfNupConverter::Status::SUCCESS) { DLOG(ERROR) << "Nup pdf page conversion failed with error " << status; OnPrintPreviewFailed(request_id); return; } NotifyUIPreviewPageReady( page_number, request_id, base::RefCountedSharedMemoryMapping::CreateFromWholeRegion(region)); } void PrintPreviewUI::OnCompositeToPdfDone( int document_cookie, int32_t request_id, mojom::PrintCompositor::Status status, base::ReadOnlySharedMemoryRegion region) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (ShouldCancelRequest(id_, request_id)) return; if (status != mojom::PrintCompositor::Status::kSuccess) { DLOG(ERROR) << "Completion of document to pdf failed with error " << status; OnPrintPreviewFailed(request_id); return; } if (pages_per_sheet_ == 1) { NotifyUIPreviewDocumentReady( request_id, base::RefCountedSharedMemoryMapping::CreateFromWholeRegion(region)); } else { WebContents* web_contents = GetInitiator(web_ui()); if (!web_contents) return; auto* client = PdfNupConverterClient::FromWebContents(web_contents); DCHECK(client); gfx::Rect printable_rect = PageSetup::GetSymmetricalPrintableArea(page_size_, printable_area_); if (printable_rect.IsEmpty()) return; client->DoNupPdfDocumentConvert( document_cookie, pages_per_sheet_, page_size_, printable_rect, std::move(region), mojo::WrapCallbackWithDefaultInvokeIfNotRun( base::BindOnce(&PrintPreviewUI::OnNupPdfDocumentConvertDone, weak_ptr_factory_.GetWeakPtr(), request_id), mojom::PdfNupConverter::Status::CONVERSION_FAILURE, base::ReadOnlySharedMemoryRegion())); } } void PrintPreviewUI::OnPrepareForDocumentToPdfDone( int32_t request_id, mojom::PrintCompositor::Status status) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (ShouldCancelRequest(id_, request_id)) return; if (status != mojom::PrintCompositor::Status::kSuccess) OnPrintPreviewFailed(request_id); } void PrintPreviewUI::OnNupPdfDocumentConvertDone( int32_t request_id, mojom::PdfNupConverter::Status status, base::ReadOnlySharedMemoryRegion region) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (status != mojom::PdfNupConverter::Status::SUCCESS) { DLOG(ERROR) << "Nup pdf document convert failed with error " << status; OnPrintPreviewFailed(request_id); return; } NotifyUIPreviewDocumentReady( request_id, base::RefCountedSharedMemoryMapping::CreateFromWholeRegion(region)); } void PrintPreviewUI::SetInitiatorTitle(const std::u16string& job_title) { initiator_title_ = job_title; } bool PrintPreviewUI::LastPageComposited(uint32_t page_number) const { if (pages_to_render_.empty()) return false; return page_number == pages_to_render_.back(); } uint32_t PrintPreviewUI::GetPageToNupConvertIndex(uint32_t page_number) const { for (size_t index = 0; index < pages_to_render_.size(); ++index) { if (page_number == pages_to_render_[index]) return index; } return kInvalidPageIndex; } std::vector<base::ReadOnlySharedMemoryRegion> PrintPreviewUI::TakePagesForNupConvert() { return std::move(pages_for_nup_convert_); } void PrintPreviewUI::AddPdfPageForNupConversion( base::ReadOnlySharedMemoryRegion pdf_page) { pages_for_nup_convert_.push_back(std::move(pdf_page)); } // static void PrintPreviewUI::SetInitialParams( content::WebContents* print_preview_dialog, const mojom::RequestPrintPreviewParams& params) { if (!print_preview_dialog || !print_preview_dialog->GetWebUI()) return; PrintPreviewUI* print_preview_ui = static_cast<PrintPreviewUI*>( print_preview_dialog->GetWebUI()->GetController()); print_preview_ui->source_is_arc_ = params.is_from_arc; print_preview_ui->source_is_modifiable_ = params.is_modifiable; print_preview_ui->source_has_selection_ = params.has_selection; print_preview_ui->print_selection_only_ = params.selection_only; } // static bool PrintPreviewUI::ShouldCancelRequest( const absl::optional<int32_t>& preview_ui_id, int request_id) { if (!preview_ui_id) return true; int current_id = -1; if (!g_print_preview_request_id_map.Get().Get(*preview_ui_id, &current_id)) return true; return request_id != current_id; } absl::optional<int32_t> PrintPreviewUI::GetIDForPrintPreviewUI() const { return id_; } void PrintPreviewUI::OnPrintPreviewDialogClosed() { WebContents* preview_dialog = web_ui()->GetWebContents(); BackgroundPrintingManager* background_printing_manager = g_browser_process->background_printing_manager(); if (background_printing_manager->HasPrintPreviewDialog(preview_dialog)) return; OnClosePrintPreviewDialog(); } void PrintPreviewUI::OnInitiatorClosed() { // Should only get here if the initiator was still tracked by the Print // Preview Dialog Controller, so the print job has not yet been sent. WebContents* preview_dialog = web_ui()->GetWebContents(); BackgroundPrintingManager* background_printing_manager = g_browser_process->background_printing_manager(); if (background_printing_manager->HasPrintPreviewDialog(preview_dialog)) { // Dialog is hidden but is still generating the preview. Cancel the print // request as it can't be completed. background_printing_manager->OnPrintRequestCancelled(preview_dialog); handler_->OnPrintRequestCancelled(); } else { // Initiator was closed while print preview dialog was still open. OnClosePrintPreviewDialog(); } } void PrintPreviewUI::OnPrintPreviewRequest(int request_id) { if (!initial_preview_start_time_.is_null()) { base::UmaHistogramTimes( "PrintPreview.InitializationTime", base::TimeTicks::Now() - initial_preview_start_time_); } g_print_preview_request_id_map.Get().Set(*id_, request_id); } void PrintPreviewUI::DidStartPreview(mojom::DidStartPreviewParamsPtr params, int32_t request_id) { if (params->page_count == 0 || params->page_count > kMaxPageCount || params->pages_to_render.empty()) { receiver_.ReportBadMessage(kInvalidArgsForDidStartPreview); return; } for (uint32_t page_number : params->pages_to_render) { if (!IsValidPageNumber(page_number, params->page_count)) { receiver_.ReportBadMessage(kInvalidArgsForDidStartPreview); return; } } if (!printing::NupParameters::IsSupported(params->pages_per_sheet)) { receiver_.ReportBadMessage(kInvalidArgsForDidStartPreview); return; } if (params->page_size.IsEmpty()) { receiver_.ReportBadMessage(kInvalidArgsForDidStartPreview); return; } pages_to_render_ = params->pages_to_render; pages_to_render_index_ = 0; pages_per_sheet_ = params->pages_per_sheet; page_size_ = params->page_size; ClearAllPreviewData(); if (g_test_delegate) g_test_delegate->DidGetPreviewPageCount(params->page_count); handler_->SendPageCountReady(base::checked_cast<int>(params->page_count), params->fit_to_page_scaling, request_id); } void PrintPreviewUI::DidGetDefaultPageLayout( mojom::PageSizeMarginsPtr page_layout_in_points, const gfx::Rect& printable_area_in_points, bool has_custom_page_size_style, int32_t request_id) { if (printable_area_in_points.width() <= 0 || printable_area_in_points.height() <= 0) { NOTREACHED(); return; } // Save printable_area_in_points information for N-up conversion. printable_area_ = printable_area_in_points; if (page_layout_in_points->margin_top < 0 || page_layout_in_points->margin_left < 0 || page_layout_in_points->margin_bottom < 0 || page_layout_in_points->margin_right < 0 || page_layout_in_points->content_width < 0 || page_layout_in_points->content_height < 0) { // Even though it early returns here, it doesn't block printing the page. return; } base::DictionaryValue layout; layout.SetDoubleKey(kSettingMarginTop, page_layout_in_points->margin_top); layout.SetDoubleKey(kSettingMarginLeft, page_layout_in_points->margin_left); layout.SetDoubleKey(kSettingMarginBottom, page_layout_in_points->margin_bottom); layout.SetDoubleKey(kSettingMarginRight, page_layout_in_points->margin_right); layout.SetDoubleKey(kSettingContentWidth, page_layout_in_points->content_width); layout.SetDoubleKey(kSettingContentHeight, page_layout_in_points->content_height); layout.SetInteger(kSettingPrintableAreaX, printable_area_in_points.x()); layout.SetInteger(kSettingPrintableAreaY, printable_area_in_points.y()); layout.SetInteger(kSettingPrintableAreaWidth, printable_area_in_points.width()); layout.SetInteger(kSettingPrintableAreaHeight, printable_area_in_points.height()); handler_->SendPageLayoutReady(layout, has_custom_page_size_style, request_id); } bool PrintPreviewUI::OnPendingPreviewPage(uint32_t page_number) { if (pages_to_render_index_ >= pages_to_render_.size()) return false; bool matched = page_number == pages_to_render_[pages_to_render_index_]; ++pages_to_render_index_; return matched; } void PrintPreviewUI::OnCancelPendingPreviewRequest() { if (id_) g_print_preview_request_id_map.Get().Set(*id_, -1); } void PrintPreviewUI::OnPrintPreviewFailed(int request_id) { OnCancelPendingPreviewRequest(); handler_->OnPrintPreviewFailed(request_id); } void PrintPreviewUI::OnHidePreviewDialog() { WebContents* preview_dialog = web_ui()->GetWebContents(); BackgroundPrintingManager* background_printing_manager = g_browser_process->background_printing_manager(); if (background_printing_manager->HasPrintPreviewDialog(preview_dialog)) return; ConstrainedWebDialogDelegate* delegate = GetConstrainedDelegate(); if (!delegate) return; std::unique_ptr<content::WebContents> preview_contents = delegate->ReleaseWebContents(); DCHECK_EQ(preview_dialog, preview_contents.get()); background_printing_manager->OwnPrintPreviewDialog( std::move(preview_contents)); OnClosePrintPreviewDialog(); } void PrintPreviewUI::OnClosePrintPreviewDialog() { if (dialog_closed_) return; dialog_closed_ = true; ConstrainedWebDialogDelegate* delegate = GetConstrainedDelegate(); if (!delegate) return; delegate->GetWebDialogDelegate()->OnDialogClosed(std::string()); delegate->OnDialogCloseFromWebUI(); } void PrintPreviewUI::SetOptionsFromDocument( const mojom::OptionsFromDocumentParamsPtr params, int32_t request_id) { if (ShouldCancelRequest(id_, request_id)) return; handler_->SendPrintPresetOptions(params->is_scaling_disabled, params->copies, params->duplex, request_id); } void PrintPreviewUI::DidPrepareDocumentForPreview(int32_t document_cookie, int32_t request_id) { // Determine if document composition from individual pages with the print // compositor is the desired configuration. Issue a preparation call to the // PrintCompositeClient if that hasn't been done yet. Otherwise, return early. if (!ShouldUseCompositor(this)) return; WebContents* web_contents = GetInitiator(web_ui()); if (!web_contents) return; // For case of print preview, page metafile is used to composite into // the document PDF at same time. Need to indicate that this scenario // is at play for the compositor. auto* client = PrintCompositeClient::FromWebContents(web_contents); DCHECK(client); if (client->GetIsDocumentConcurrentlyComposited(document_cookie)) return; content::RenderFrameHost* render_frame_host = PrintViewManager::FromWebContents(web_contents)->print_preview_rfh(); // |render_frame_host| could be null when the print preview dialog is closed. if (!render_frame_host) return; client->DoPrepareForDocumentToPdf( document_cookie, render_frame_host, mojo::WrapCallbackWithDefaultInvokeIfNotRun( base::BindOnce(&PrintPreviewUI::OnPrepareForDocumentToPdfDone, weak_ptr_factory_.GetWeakPtr(), request_id), mojom::PrintCompositor::Status::kCompositingFailure)); } void PrintPreviewUI::DidPreviewPage(mojom::DidPreviewPageParamsPtr params, int32_t request_id) { uint32_t page_number = params->page_number; const mojom::DidPrintContentParams& content = *params->content; if (page_number == kInvalidPageIndex || !content.metafile_data_region.IsValid()) { return; } if (!OnPendingPreviewPage(page_number)) { receiver_.ReportBadMessage(kInvalidPageNumberForDidPreviewPage); return; } if (ShouldUseCompositor(this)) { // Don't bother compositing if this request has been cancelled already. if (ShouldCancelRequest(id_, request_id)) return; WebContents* web_contents = GetInitiator(web_ui()); if (!web_contents) return; auto* client = PrintCompositeClient::FromWebContents(web_contents); DCHECK(client); content::RenderFrameHost* render_frame_host = PrintViewManager::FromWebContents(web_contents)->print_preview_rfh(); // |render_frame_host| could be null when the print preview dialog is // closed. if (!render_frame_host) return; // Use utility process to convert skia metafile to pdf. client->DoCompositePageToPdf( params->document_cookie, render_frame_host, content, mojo::WrapCallbackWithDefaultInvokeIfNotRun( base::BindOnce(&PrintPreviewUI::OnCompositePdfPageDone, weak_ptr_factory_.GetWeakPtr(), page_number, params->document_cookie, request_id), mojom::PrintCompositor::Status::kCompositingFailure, base::ReadOnlySharedMemoryRegion())); } else { NotifyUIPreviewPageReady( page_number, request_id, base::RefCountedSharedMemoryMapping::CreateFromWholeRegion( content.metafile_data_region)); } } void PrintPreviewUI::MetafileReadyForPrinting( mojom::DidPreviewDocumentParamsPtr params, int32_t request_id) { // Always try to stop the worker. StopWorker(params->document_cookie); const bool composite_document_using_individual_pages = ShouldUseCompositor(this); const base::ReadOnlySharedMemoryRegion& metafile = params->content->metafile_data_region; // When the Print Compositor is active, the print document is composed from // the individual pages, so |metafile| should be invalid. // When it is inactive, the print document is composed from |metafile|. // So if this comparison succeeds, that means the renderer sent bad data. if (composite_document_using_individual_pages == metafile.IsValid()) return; if (params->expected_pages_count == 0) { receiver_.ReportBadMessage(kInvalidPageCountForMetafileReadyForPrinting); return; } if (composite_document_using_individual_pages) { // Don't bother compositing if this request has been cancelled already. if (ShouldCancelRequest(id_, request_id)) return; auto callback = base::BindOnce(&PrintPreviewUI::OnCompositeToPdfDone, weak_ptr_factory_.GetWeakPtr(), params->document_cookie, request_id); WebContents* web_contents = GetInitiator(web_ui()); if (!web_contents) return; // Page metafile is used to composite into the document at same time. // Need to provide particulars of how many pages are required before // document will be completed. auto* client = PrintCompositeClient::FromWebContents(web_contents); client->DoCompleteDocumentToPdf( params->document_cookie, params->expected_pages_count, mojo::WrapCallbackWithDefaultInvokeIfNotRun( std::move(callback), mojom::PrintCompositor::Status::kCompositingFailure, base::ReadOnlySharedMemoryRegion())); } else { NotifyUIPreviewDocumentReady( request_id, base::RefCountedSharedMemoryMapping::CreateFromWholeRegion(metafile)); } } void PrintPreviewUI::PrintPreviewFailed(int32_t document_cookie, int32_t request_id) { StopWorker(document_cookie); if (ShouldCancelRequest(id_, request_id)) return; OnPrintPreviewFailed(request_id); } void PrintPreviewUI::PrintPreviewCancelled(int32_t document_cookie, int32_t request_id) { // Always need to stop the worker. StopWorker(document_cookie); if (ShouldCancelRequest(id_, request_id)) return; handler_->OnPrintPreviewCancelled(request_id); } void PrintPreviewUI::PrinterSettingsInvalid(int32_t document_cookie, int32_t request_id) { StopWorker(document_cookie); if (ShouldCancelRequest(id_, request_id)) return; handler_->OnInvalidPrinterSettings(request_id); } // static void PrintPreviewUI::SetDelegateForTesting(TestDelegate* delegate) { g_test_delegate = delegate; } void PrintPreviewUI::SetSelectedFileForTesting(const base::FilePath& path) { handler_->FileSelectedForTesting(path, 0, nullptr); } void PrintPreviewUI::SetPdfSavedClosureForTesting(base::OnceClosure closure) { handler_->SetPdfSavedClosureForTesting(std::move(closure)); } void PrintPreviewUI::SetPrintPreviewDataForIndexForTest( int index, scoped_refptr<base::RefCountedMemory> data) { SetPrintPreviewDataForIndex(index, data); } void PrintPreviewUI::ClearAllPreviewDataForTest() { ClearAllPreviewData(); } void PrintPreviewUI::SetPreviewUIId() { DCHECK(!id_); id_ = g_print_preview_ui_id_map.Get().Add(this); g_print_preview_request_id_map.Get().Set(*id_, -1); } } // namespace printing
38.493369
81
0.75503
[ "geometry", "object", "vector" ]
f35bb2c96c30949ea2efb6ebe59a64a467355d89
3,897
cpp
C++
94_connect_same_level_nodes.cpp
swapmali/Must-Do-Coding-Questions-For-Companies-GFG
b68340c150f572c0fad7311af87f79b684060fb9
[ "MIT" ]
1
2021-02-07T19:50:36.000Z
2021-02-07T19:50:36.000Z
94_connect_same_level_nodes.cpp
swapmali/Must-Do-Coding-Questions-For-Companies-GFG
b68340c150f572c0fad7311af87f79b684060fb9
[ "MIT" ]
null
null
null
94_connect_same_level_nodes.cpp
swapmali/Must-Do-Coding-Questions-For-Companies-GFG
b68340c150f572c0fad7311af87f79b684060fb9
[ "MIT" ]
1
2021-05-06T15:30:47.000Z
2021-05-06T15:30:47.000Z
// https://practice.geeksforgeeks.org/problems/connect-nodes-at-same-level/1 #include <bits/stdc++.h> using namespace std; // Tree Node struct Node { int data; Node* left; Node* right; Node* nextRight; }; // Utility function to create a new Tree Node Node* newNode(int val) { Node* temp = new Node; temp->data = val; temp->left = NULL; temp->right = NULL; temp->nextRight = NULL; return temp; } // Function to Build Tree Node* buildTree(string str) { // Corner Case if (str.length() == 0 || str[0] == 'N') return NULL; // Creating vector of strings from input // string after spliting by space vector<string> ip; istringstream iss(str); for (string str; iss >> str; ) ip.push_back(str); // Create the root of the tree Node* root = newNode(stoi(ip[0])); // Push the root to the queue queue<Node*> queue; queue.push(root); // Starting from the second element int i = 1; while (!queue.empty() && i < ip.size()) { // Get and remove the front of the queue Node* currNode = queue.front(); queue.pop(); // Get the current node's value from the string string currVal = ip[i]; // If the left child is not null if (currVal != "N") { // Create the left child for the current node currNode->left = newNode(stoi(currVal)); // Push it to the queue queue.push(currNode->left); } // For the right child i++; if (i >= ip.size()) break; currVal = ip[i]; // If the right child is not null if (currVal != "N") { // Create the right child for the current node currNode->right = newNode(stoi(currVal)); // Push it to the queue queue.push(currNode->right); } i++; } return root; } void connect(struct Node *p); /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ void printSpecial(Node *root) { if (root == NULL) return; Node* next_root = NULL; while (root != NULL) { cout << root->data << " "; if ( root->left && (!next_root) ) next_root = root->left; else if ( root->right && (!next_root) ) next_root = root->right; root = root->nextRight; } printSpecial(next_root); } void inorder(Node *root) { if (root == NULL) return; inorder(root->left); cout << root->data << " "; inorder(root->right); } /* Driver program to test size function*/ int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int t; scanf("%d\n", &t); while (t--) { string s; getline(cin, s); Node* root = buildTree(s); connect(root); printSpecial(root); cout << endl; inorder(root); cout << endl; } return 0; } /* struct Node { int data; Node *left, *right; Node *nextRight; // This has garbage value in input trees }; */ // Should set the nextRight for all nodes void connect(Node *root) { queue <Node*> q1, q2; q1.push(root); Node *cur_node, *next_node, *node; while (!q1.empty()) { while (!q1.empty()) { cur_node = q1.front(); q1.pop(); if (!q1.empty()) next_node = q1.front(); else next_node = NULL; q2.push(cur_node -> left); q2.push(cur_node -> right); cur_node -> nextRight = next_node; } while (!q2.empty()) { node = q2.front(); q2.pop(); if (node != NULL) q1.push(node); } } }
20.087629
76
0.52117
[ "vector" ]
f3613283479c364bcde51c2bdfb96b3677a3bf7a
7,295
hpp
C++
src/rdb_protocol/func.hpp
NicoHood/rethinkdb
8d7e97b7838b844902d222e7c9790fadbaf70441
[ "Apache-2.0" ]
null
null
null
src/rdb_protocol/func.hpp
NicoHood/rethinkdb
8d7e97b7838b844902d222e7c9790fadbaf70441
[ "Apache-2.0" ]
null
null
null
src/rdb_protocol/func.hpp
NicoHood/rethinkdb
8d7e97b7838b844902d222e7c9790fadbaf70441
[ "Apache-2.0" ]
null
null
null
// Copyright 2010-2015 RethinkDB, all rights reserved. #ifndef RDB_PROTOCOL_FUNC_HPP_ #define RDB_PROTOCOL_FUNC_HPP_ #include <map> #include <string> #include <utility> #include <vector> #include "errors.hpp" #include <boost/variant/static_visitor.hpp> #include "containers/counted.hpp" #include "containers/uuid.hpp" #include "rdb_protocol/datum.hpp" #include "rdb_protocol/env.hpp" #include "rdb_protocol/op.hpp" #include "rdb_protocol/sym.hpp" #include "rdb_protocol/term.hpp" #include "rdb_protocol/term_storage.hpp" #include "rpc/serialize_macros.hpp" class js_runner_t; namespace ql { class func_visitor_t; class func_t : public slow_atomic_countable_t<func_t>, public bt_rcheckable_t { public: virtual ~func_t(); virtual scoped_ptr_t<val_t> call( env_t *env, const std::vector<datum_t> &args, eval_flags_t eval_flags = NO_FLAGS) const = 0; virtual optional<size_t> arity() const = 0; virtual deterministic_t is_deterministic() const = 0; // Used by info_term_t. virtual std::string print_source() const = 0; // Similar to `print_source()`, but prints a JS expression of the form // `function(arg1, arg2, ...) { return body; }`. Fails if the func_t has a non-empty // captured scope. virtual std::string print_js_function() const = 0; virtual void visit(func_visitor_t *visitor) const = 0; void assert_deterministic(const char *extra_msg) const; bool filter_call(env_t *env, datum_t arg, counted_t<const func_t> default_filter_val) const; // These are simple, they call the vector version of call. scoped_ptr_t<val_t> call(env_t *env, eval_flags_t eval_flags = NO_FLAGS) const; scoped_ptr_t<val_t> call(env_t *env, datum_t arg, eval_flags_t eval_flags = NO_FLAGS) const; scoped_ptr_t<val_t> call(env_t *env, datum_t arg1, datum_t arg2, eval_flags_t eval_flags = NO_FLAGS) const; virtual bool is_simple_selector() const { return false; } protected: explicit func_t(backtrace_id_t bt); private: virtual bool filter_helper(env_t *env, datum_t arg) const = 0; DISABLE_COPYING(func_t); }; class reql_func_t : public func_t { public: // Used when constructing in an existing environment - reusing another term storage reql_func_t(const var_scope_t &captured_scope, std::vector<sym_t> arg_names, counted_t<const term_t> body); // Used when constructing from a function read off the wire reql_func_t(scoped_ptr_t<term_storage_t> &&_storage, const var_scope_t &captured_scope, std::vector<sym_t> arg_names, counted_t<const term_t> body); ~reql_func_t(); scoped_ptr_t<val_t> call( env_t *env, const std::vector<datum_t> &args, eval_flags_t eval_flags) const; optional<size_t> arity() const; deterministic_t is_deterministic() const; std::string print_source() const; std::string print_js_function() const; void visit(func_visitor_t *visitor) const; bool is_simple_selector() const final; private: template <cluster_version_t> friend class wire_func_serialization_visitor_t; bool filter_helper(env_t *env, datum_t arg) const; // Only contains the parts of the scope that `body` uses. var_scope_t captured_scope; // The argument names, for the corresponding positional argument number. std::vector<sym_t> arg_names; // Term storage if this was deserialized off the wire to ensure the lifetime of // the raw term tree. scoped_ptr_t<term_storage_t> term_storage; // The body of the function, which gets ->eval(...) called when call(...) is called. counted_t<const term_t> body; DISABLE_COPYING(reql_func_t); }; class js_func_t : public func_t { public: js_func_t(const std::string &_js_source, uint64_t timeout_ms, backtrace_id_t backtrace); ~js_func_t(); // Some queries, like filter, can take a shortcut object instead of a // function as their argument. scoped_ptr_t<val_t> call(env_t *env, const std::vector<datum_t> &args, eval_flags_t eval_flags) const; optional<size_t> arity() const; deterministic_t is_deterministic() const; std::string print_source() const; std::string print_js_function() const; void visit(func_visitor_t *visitor) const; private: template <cluster_version_t> friend class wire_func_serialization_visitor_t; bool filter_helper(env_t *env, datum_t arg) const; std::string js_source; uint64_t js_timeout_ms; DISABLE_COPYING(js_func_t); }; class func_visitor_t { public: virtual void on_reql_func(const reql_func_t *reql_func) = 0; virtual void on_js_func(const js_func_t *js_func) = 0; protected: func_visitor_t() { } virtual ~func_visitor_t() { } DISABLE_COPYING(func_visitor_t); }; // Some queries, like filter, can take a shortcut object instead of a // function as their argument. counted_t<const func_t> new_constant_func(datum_t obj, backtrace_id_t bt); counted_t<const func_t> new_pluck_func(datum_t obj, backtrace_id_t bt); counted_t<const func_t> new_get_field_func(datum_t obj, backtrace_id_t bt); counted_t<const func_t> new_eq_comparison_func(datum_t obj, backtrace_id_t bt); counted_t<const func_t> new_page_func(datum_t method, backtrace_id_t bt); class js_result_visitor_t : public boost::static_visitor<val_t *> { public: js_result_visitor_t(const std::string &_code, uint64_t _timeout_ms, const bt_rcheckable_t *_parent) : code(_code), timeout_ms(_timeout_ms), parent(_parent) { } // The caller needs to take ownership of the return value. Boost static_visitor // can't handle movable types. // This JS evaluation resulted in an error val_t *operator()(const std::string &err_val) const; // This JS call resulted in a JSON value val_t *operator()(const datum_t &json_val) const; // This JS evaluation resulted in an id for a js function val_t *operator()(const js_id_t id_val) const; private: std::string code; uint64_t timeout_ms; const bt_rcheckable_t *parent; }; // Evaluating this returns a `func_t` wrapped in a `val_t`. class func_term_t : public term_t { public: func_term_t(compile_env_t *env, const raw_term_t &term); // eval(scoped_env_t *env) is a dumb wrapper for this. Evaluates the func_t without // going by way of val_t, and without requiring a full-blown env. counted_t<const func_t> eval_to_func(const var_scope_t &env_scope) const; private: virtual void accumulate_captures(var_captures_t *captures) const; virtual deterministic_t is_deterministic() const; virtual scoped_ptr_t<val_t> term_eval(scope_env_t *env, eval_flags_t flags) const; virtual const char *name() const { return "func"; } std::vector<sym_t> arg_names; counted_t<const term_t> body; var_captures_t external_captures; }; } // namespace ql #endif // RDB_PROTOCOL_FUNC_HPP_
31.580087
88
0.690747
[ "object", "vector" ]
f3657b3648c92d43d8f981823a8f0c2f0f91a38a
1,532
cpp
C++
src/game/shared/econ/econ_game_account_server.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/game/shared/econ/econ_game_account_server.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/game/shared/econ/econ_game_account_server.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: Code for the CEconGameAccount object // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "econ_game_account_server.h" using namespace GCSDK; #ifdef GC_DLL //--------------------------------------------------------------------------------- // Purpose: //--------------------------------------------------------------------------------- IMPLEMENT_CLASS_MEMPOOL( CEconGameServerAccount, 100, UTLMEMORYPOOL_GROW_SLOW ); void GameServerAccount_GenerateIdentityToken( char* pIdentityToken, uint32 unMaxChars ) { static const char s_ValidChars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890./+!$%^-_+?<>()&~:"; const int nLastValidIndex = ARRAYSIZE(s_ValidChars) - 2; // last = size - 1, minus another one for null terminator // create a randomized token for ( uint32 i = 0; i < unMaxChars - 1; ++i ) { pIdentityToken[i] = s_ValidChars[ RandomInt( 0, nLastValidIndex ) ]; } pIdentityToken[unMaxChars - 1] = 0; } //--------------------------------------------------------------------------------- // Purpose: Selective account-level data for game servers //--------------------------------------------------------------------------------- IMPLEMENT_CLASS_MEMPOOL( CEconGameAccountForGameServers, 10 * 1000, UTLMEMORYPOOL_GROW_SLOW ); #endif // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h"
37.365854
119
0.53329
[ "object" ]
f3662e2cfe44d640d4d39a022b021d6fcb3d9620
12,305
cpp
C++
RayEngine/Source/OpenGL/GLPipelineState.cpp
Mumsfilibaba/RayEngine
68496966c1d7b91bc8fbdd305226ece9b9f596b2
[ "Apache-2.0" ]
null
null
null
RayEngine/Source/OpenGL/GLPipelineState.cpp
Mumsfilibaba/RayEngine
68496966c1d7b91bc8fbdd305226ece9b9f596b2
[ "Apache-2.0" ]
null
null
null
RayEngine/Source/OpenGL/GLPipelineState.cpp
Mumsfilibaba/RayEngine
68496966c1d7b91bc8fbdd305226ece9b9f596b2
[ "Apache-2.0" ]
null
null
null
/*//////////////////////////////////////////////////////////// Copyright 2018 Alexander Dahlin 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 THIS SOFTWARE IS PROVIDED "AS IS". MEANING NO WARRANTY OR SUPPORT IS PROVIDED OF ANY KIND. In event of any damages, direct or indirect that can be traced back to the use of this software, shall no contributor be held liable. This includes computer failure and or malfunction of any kind. ////////////////////////////////////////////////////////////*/ #include <RayEngine.h> #include <OpenGL/GLDevice.h> #include <OpenGL/GLShader.h> #include <OpenGL/GLPipelineState.h> namespace RayEngine { namespace Graphics { ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// GLPipelineState::GLPipelineState(IDevice* pDevice, const PipelineStateDesc* pDesc) : m_Device(nullptr), m_InputLayout(), m_DepthState(), m_RasterizerState(), m_BlendState(), m_Desc(), m_Program(0), m_References(0) { AddRef(); m_Device = reinterpret_cast<GLDevice*>(pDevice); Create(pDesc); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// GLPipelineState::~GLPipelineState() { if (glIsProgram(m_Program)) { glDeleteProgram(m_Program); } delete[] m_InputLayout.pElements; m_InputLayout.pElements = nullptr; if (m_Desc.Type == PIPELINE_TYPE_GRAPHICS) { if (m_Desc.Graphics.InputLayout.pElements != nullptr) { delete[] m_Desc.Graphics.InputLayout.pElements; m_Desc.Graphics.InputLayout.pElements = nullptr; m_Desc.Graphics.InputLayout.ElementCount = 0; } } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void GLPipelineState::GetDesc(PipelineStateDesc* pDesc) const { *pDesc = m_Desc; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CounterType GLPipelineState::Release() { CounterType refs = --m_References; if (refs < 1) delete this; return refs; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CounterType GLPipelineState::AddRef() { return ++m_References; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void GLPipelineState::Create(const PipelineStateDesc* pDesc) { if (pDesc->Type == PIPELINE_TYPE_GRAPHICS) CreateGraphicsPipeline(pDesc); else if (pDesc->Type == PIPELINE_TYPE_COMPUTE) CreateComputePipeline(pDesc); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void GLPipelineState::CreateGraphicsPipeline(const PipelineStateDesc* pDesc) { m_Program = glCreateProgram(); GLShader* pShader = nullptr; if (pDesc->Graphics.pVertexShader != nullptr) { pShader = reinterpret_cast<GLShader*>(pDesc->Graphics.pVertexShader); glAttachShader(m_Program, pShader->GetGLShaderID()); } if (pDesc->Graphics.pHullShader != nullptr) { pShader = reinterpret_cast<GLShader*>(pDesc->Graphics.pHullShader); glAttachShader(m_Program, pShader->GetGLShaderID()); } if (pDesc->Graphics.pDomainShader != nullptr) { pShader = reinterpret_cast<GLShader*>(pDesc->Graphics.pDomainShader); glAttachShader(m_Program, pShader->GetGLShaderID()); } if (pDesc->Graphics.pGeometryShader != nullptr) { pShader = reinterpret_cast<GLShader*>(pDesc->Graphics.pGeometryShader); glAttachShader(m_Program, pShader->GetGLShaderID()); } if (pDesc->Graphics.pPixelShader != nullptr) { pShader = reinterpret_cast<GLShader*>(pDesc->Graphics.pPixelShader); glAttachShader(m_Program, pShader->GetGLShaderID()); } LinkShaders(); CreateInputLayout(pDesc); CreateDepthState(pDesc); CreateRasterizerState(pDesc); CreateBlendState(pDesc); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void GLPipelineState::CreateComputePipeline(const PipelineStateDesc* pDesc) { m_Program = glCreateProgram(); if (pDesc->Graphics.pGeometryShader != nullptr) { GLShader* pShader = reinterpret_cast<GLShader*>(pDesc->Graphics.pGeometryShader); glAttachShader(m_Program, pShader->GetGLShaderID()); } LinkShaders(); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void GLPipelineState::LinkShaders() { glLinkProgram(m_Program); int32 result = GL_TRUE; glGetProgramiv(m_Program, GL_LINK_STATUS, &result); if (result != GL_TRUE) { int32 len = 0; glGetProgramiv(m_Program, GL_INFO_LOG_LENGTH, &len); std::string message = "OpenGL: Could not link program.\n"; if (len > 0) { std::vector<char> log; log.resize(len); glGetProgramInfoLog(m_Program, len, &len, log.data()); message += log.data(); } LOG_ERROR(message); } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void GLPipelineState::CreateInputLayout(const PipelineStateDesc* pDesc) { m_InputLayout.ElementCount = pDesc->Graphics.InputLayout.ElementCount; m_InputLayout.pElements = new GLInputLayoutElement[m_InputLayout.ElementCount]; InputElementDesc* pElements = pDesc->Graphics.InputLayout.pElements; for (uint32 i = 0; i < m_InputLayout.ElementCount; i++) { m_InputLayout.pElements[i].Stride = pElements[i].StrideBytes; m_InputLayout.pElements[i].Offset = pElements[i].ElementOffset; m_InputLayout.pElements[i].Type = GetVertexFormat(pElements[i].Format); m_InputLayout.pElements[i].Size = GetVertexComponents(pElements[i].Format); m_InputLayout.pElements[i].Normalized = NormalizedVertexFormat(pElements[i].Format); m_InputLayout.pElements[i].Divisor = pElements[i].DataStepRate; } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void GLPipelineState::CreateDepthState(const PipelineStateDesc* pDesc) { m_DepthState.DepthEnable = pDesc->Graphics.DepthStencilState.DepthEnable; m_DepthState.DepthFunc = ComparisonFuncToGL(pDesc->Graphics.DepthStencilState.DepthFunc); if (pDesc->Graphics.DepthStencilState.DepthWriteMask == DEPTH_WRITE_MASK_ALL) m_DepthState.DepthMask = GL_TRUE; else if (pDesc->Graphics.DepthStencilState.DepthWriteMask == DEPTH_WRITE_MASK_ZERO) m_DepthState.DepthMask = GL_FALSE; else m_DepthState.DepthMask = 0; m_DepthState.StencilEnable = pDesc->Graphics.DepthStencilState.StencilEnable; m_DepthState.WriteMask = pDesc->Graphics.DepthStencilState.StencilWriteMask; m_DepthState.FrontFace.StencilFunc = ComparisonFuncToGL(pDesc->Graphics.DepthStencilState.FrontFace.StencilFunc); m_DepthState.FrontFace.ReadMask = pDesc->Graphics.DepthStencilState.StencilReadMask; m_DepthState.FrontFace.StencilFailOp = StencilOpToGL(pDesc->Graphics.DepthStencilState.FrontFace.StencilFailOperation); m_DepthState.FrontFace.DepthFailOp = StencilOpToGL(pDesc->Graphics.DepthStencilState.FrontFace.StencilDepthFailOperation); m_DepthState.FrontFace.PassOp = StencilOpToGL(pDesc->Graphics.DepthStencilState.FrontFace.StencilPassOperation); m_DepthState.BackFace.StencilFunc = ComparisonFuncToGL(pDesc->Graphics.DepthStencilState.BackFace.StencilFunc); m_DepthState.BackFace.ReadMask = pDesc->Graphics.DepthStencilState.StencilReadMask; m_DepthState.BackFace.StencilFailOp = StencilOpToGL(pDesc->Graphics.DepthStencilState.BackFace.StencilFailOperation); m_DepthState.BackFace.DepthFailOp = StencilOpToGL(pDesc->Graphics.DepthStencilState.BackFace.StencilDepthFailOperation); m_DepthState.BackFace.PassOp = StencilOpToGL(pDesc->Graphics.DepthStencilState.BackFace.StencilPassOperation); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void GLPipelineState::CreateRasterizerState(const PipelineStateDesc* pDesc) { m_RasterizerState.ConservativeRasterizerEnable = pDesc->Graphics.RasterizerState.ConservativeRasterizerEnable; if (pDesc->Graphics.RasterizerState.FillMode == FILL_MODE_SOLID) m_RasterizerState.PolygonMode = GL_FILL; else if (pDesc->Graphics.RasterizerState.FillMode == FILL_MODE_WIREFRAME) m_RasterizerState.PolygonMode = GL_LINE; if (pDesc->Graphics.RasterizerState.CullMode == CULL_MODE_BACK) m_RasterizerState.CullMode = GL_BACK; else if (pDesc->Graphics.RasterizerState.CullMode == CULL_MODE_FRONT) m_RasterizerState.CullMode = GL_FRONT; if (pDesc->Graphics.RasterizerState.FrontCounterClockwise) m_RasterizerState.FrontFace = GL_CCW; else m_RasterizerState.FrontFace = GL_CW; m_RasterizerState.DepthClipEnable = pDesc->Graphics.RasterizerState.DepthClipEnable; m_RasterizerState.DepthBias = (float)pDesc->Graphics.RasterizerState.DepthBias; m_RasterizerState.DepthBiasClamp = pDesc->Graphics.RasterizerState.DepthBiasClamp; m_RasterizerState.SlopeScaleDepthBias = pDesc->Graphics.RasterizerState.SlopeScaleDepthBias; m_RasterizerState.AntialiasedLineEnable = pDesc->Graphics.RasterizerState.AntialiasedLineEnable; m_RasterizerState.MultisampleEnable = pDesc->Graphics.RasterizerState.MultisampleEnable; m_RasterizerState.ScissorEnable = pDesc->Graphics.RasterizerState.ScissorEnable; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void GLPipelineState::CreateBlendState(const PipelineStateDesc* pDesc) { m_BlendState.AlphaToCoverageEnable = pDesc->Graphics.BlendState.AlphaToCoverageEnable; m_BlendState.IndependentBlendEnable = pDesc->Graphics.BlendState.IndependentBlendEnable; m_BlendState.LogicOpEnable = pDesc->Graphics.BlendState.LogicOpEnable; for (uint32 i = 0; i < 4; i++) m_BlendState.BlendFactor[i] = pDesc->Graphics.BlendState.BlendFactor[i]; for (uint32 i = 0; i < RE_MAX_RENDERTARGETS; i++) { m_BlendState.RenderTargets[i].blendEnable = pDesc->Graphics.BlendState.RenderTargets[i].BlendEnable; m_BlendState.RenderTargets[i].SrcBlend = BlendTypeToGL(pDesc->Graphics.BlendState.RenderTargets[i].SrcBlend); m_BlendState.RenderTargets[i].DstBlend = BlendTypeToGL(pDesc->Graphics.BlendState.RenderTargets[i].DstBlend); m_BlendState.RenderTargets[i].SrcAlphaBlend = BlendTypeToGL(pDesc->Graphics.BlendState.RenderTargets[i].SrcAlphaBlend); m_BlendState.RenderTargets[i].DstAlphaBlend = BlendTypeToGL(pDesc->Graphics.BlendState.RenderTargets[i].DstAlphaBlend); m_BlendState.RenderTargets[i].BlendOperation = BlendOperationToGL(pDesc->Graphics.BlendState.RenderTargets[i].BlendOperation); m_BlendState.RenderTargets[i].AlphaBlendOperation = BlendOperationToGL(pDesc->Graphics.BlendState.RenderTargets[i].AlphaBlendOperation); if (pDesc->Graphics.BlendState.RenderTargets[i].WriteMask & COLOR_WRITE_ENABLE_RED) m_BlendState.RenderTargets[i].WriteMask[0] = GL_TRUE; else m_BlendState.RenderTargets[i].WriteMask[0] = GL_FALSE; if (pDesc->Graphics.BlendState.RenderTargets[i].WriteMask & COLOR_WRITE_ENABLE_GREEN) m_BlendState.RenderTargets[i].WriteMask[1] = GL_TRUE; else m_BlendState.RenderTargets[i].WriteMask[1] = GL_FALSE; if (pDesc->Graphics.BlendState.RenderTargets[i].WriteMask & COLOR_WRITE_ENABLE_BLUE) m_BlendState.RenderTargets[i].WriteMask[2] = GL_TRUE; else m_BlendState.RenderTargets[i].WriteMask[2] = GL_FALSE; if (pDesc->Graphics.BlendState.RenderTargets[i].WriteMask & COLOR_WRITE_ENABLE_ALPHA) m_BlendState.RenderTargets[i].WriteMask[3] = GL_TRUE; else m_BlendState.RenderTargets[i].WriteMask[3] = GL_FALSE; } } } }
39.187898
140
0.651443
[ "vector" ]
f36ee20a2dbfad354dcbedf95555f722ee74155d
830
cpp
C++
LeetCode-Challenges/2020/4. April/27_maximal_square.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
LeetCode-Challenges/2020/4. April/27_maximal_square.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
LeetCode-Challenges/2020/4. April/27_maximal_square.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
class Solution { public: int maximalSquare(vector<vector<char>> &matrix) { int nr = matrix.size(); if (nr == 0) { return 0; } int nc = matrix[0].size(); vector<vector<int>> dp(nr + 1, vector<int>(nc + 1)); int ans = 0; for (int r = 1; r < nr + 1; r++) { int i = r - 1; for (int c = 1; c < nc + 1; c++) { int j = c - 1; if (matrix[i][j] == '1') { int x = min({dp[r - 1][c], dp[r][c - 1], dp[r - 1][c - 1]}) + 1; dp[r][c] = x; if (x > ans) { ans = x; } } } } return ans * ans; } };
23.055556
84
0.287952
[ "vector" ]
f36fc605481c858f445494198fc3e06785cde124
18,283
cpp
C++
multimedia/dshow/filters/image/dither/dither.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
multimedia/dshow/filters/image/dither/dither.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
multimedia/dshow/filters/image/dither/dither.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// Copyright (c) Microsoft Corporation 1994-1996. All Rights Reserved // This implements VGA colour dithering, April 1996, Anthony Phillips #include <streams.h> #include <initguid.h> #include <dither.h> #include <limits.h> // This is a VGA colour dithering filter. When ActiveMovie is installed it // may be done on a system set with a 16 colour display mode. Without this // we would not be able to show any video as none of the AVI/MPEG decoders // can dither to 16 colours. As a quick hack we dither to 16 colours but // we only use the black, white and grey thereby doing a halftoned dither // This filter does not have a worker thread so it executes the colour space // conversion on the calling thread. It is meant to be as lightweight as is // possible so we do very little type checking on connection over and above // ensuring we understand the types involved. The assumption is that when the // type eventually gets through to an end point (probably the video renderer // supplied) it will do a thorough type checking and reject bad streams. // List of CLSIDs and creator functions for class factory #ifdef FILTER_DLL CFactoryTemplate g_Templates[1] = { { L"" , &CLSID_Dither , CDither::CreateInstance , NULL , &sudDitherFilter } }; int g_cTemplates = sizeof(g_Templates) / sizeof(g_Templates[0]); #endif // This goes in the factory template table to create new instances CUnknown *CDither::CreateInstance(LPUNKNOWN pUnk,HRESULT *phr) { return new CDither(NAME("VGA Ditherer"),pUnk); } // Setup data const AMOVIESETUP_MEDIATYPE sudDitherInputPinTypes = { &MEDIATYPE_Video, // Major &MEDIASUBTYPE_RGB8 // Subtype }; const AMOVIESETUP_MEDIATYPE sudDitherOutpinPinTypes = { &MEDIATYPE_Video, // Major &MEDIASUBTYPE_RGB4 // Subtype }; const AMOVIESETUP_PIN sudDitherPin[] = { { L"Input", // Name of the pin FALSE, // Is pin rendered FALSE, // Is an Output pin FALSE, // Ok for no pins FALSE, // Can we have many &CLSID_NULL, // Connects to filter NULL, // Name of pin connect 1, // Number of pin types &sudDitherInputPinTypes}, // Details for pins { L"Output", // Name of the pin FALSE, // Is pin rendered TRUE, // Is an Output pin FALSE, // Ok for no pins FALSE, // Can we have many &CLSID_NULL, // Connects to filter NULL, // Name of pin connect 1, // Number of pin types &sudDitherOutpinPinTypes} // Details for pins }; const AMOVIESETUP_FILTER sudDitherFilter = { &CLSID_Dither, // CLSID of filter L"VGA 16 Color Ditherer", // Filter name MERIT_UNLIKELY, // Filter merit 2, // Number of pins sudDitherPin // Pin information }; #pragma warning(disable:4355) // Constructor initialises base transform class CDither::CDither(TCHAR *pName,LPUNKNOWN pUnk) : CTransformFilter(pName,pUnk,CLSID_Dither), m_fInit(FALSE) { } // Do the actual transform into the VGA colours HRESULT CDither::Transform(IMediaSample *pIn,IMediaSample *pOut) { NOTE("Entering Transform"); BYTE *pInput = NULL; BYTE *pOutput = NULL; HRESULT hr = NOERROR; AM_MEDIA_TYPE *pmt; if (!m_fInit) { return E_FAIL; } // Retrieve the output image pointer hr = pOut->GetPointer(&pOutput); if (FAILED(hr)) { NOTE("No output"); return hr; } // And the input image buffer as well hr = pIn->GetPointer(&pInput); if (FAILED(hr)) { NOTE("No input"); return hr; } // // If the media type has changed then pmt is NOT NULL // pOut->GetMediaType(&pmt); if (pmt != NULL) { CMediaType cmt(*pmt); DeleteMediaType(pmt); SetOutputPinMediaType(&cmt); } pIn->GetMediaType(&pmt); if (pmt != NULL) { CMediaType cmt(*pmt); DeleteMediaType(pmt); hr = SetInputPinMediaType(&cmt); if (FAILED(hr)) { return hr; } } Dither8(pOutput, pInput); return NOERROR; } // This function is handed a media type object and it looks after making sure // that it is superficially correct. This doesn't amount to a whole lot more // than making sure the type is right and that the media format block exists // So we delegate type checking to the downstream filter that really draws it HRESULT CDither::CheckVideoType(const CMediaType *pmt) { NOTE("Entering CheckVideoType"); // Check the major type is digital video if (pmt->majortype != MEDIATYPE_Video) { NOTE("Major type not MEDIATYPE_Video"); return VFW_E_TYPE_NOT_ACCEPTED; } // Check this is a VIDEOINFO type if (pmt->formattype != FORMAT_VideoInfo) { NOTE("Format not a VIDEOINFO"); return VFW_E_TYPE_NOT_ACCEPTED; } // Quick sanity check on the input format if (pmt->cbFormat < SIZE_VIDEOHEADER) { NOTE("Format too small for a VIDEOINFO"); return VFW_E_TYPE_NOT_ACCEPTED; } return NOERROR; } // Check we like the look of this input format HRESULT CDither::CheckInputType(const CMediaType *pmtIn) { NOTE("Entering CheckInputType"); // Is the input type MEDIASUBTYPE_RGB8 if (pmtIn->subtype != MEDIASUBTYPE_RGB8) { NOTE("Subtype not MEDIASUBTYPE_RGB8"); return VFW_E_TYPE_NOT_ACCEPTED; } return CheckVideoType(pmtIn); } // Can we do this input to output transform. We will only be called here if // the input pin is connected. We cannot stretch nor compress the image and // the only allowed output format is MEDIASUBTYPE_RGB4. There is no point us // doing pass through like the colour space convertor because DirectDraw is // not available in any VGA display modes - it works with a minimum of 8bpp HRESULT CDither::CheckTransform(const CMediaType *pmtIn,const CMediaType *pmtOut) { VIDEOINFO *pTrgInfo = (VIDEOINFO *) pmtOut->Format(); VIDEOINFO *pSrcInfo = (VIDEOINFO *) pmtIn->Format(); NOTE("Entering CheckTransform"); // Quick sanity check on the output format HRESULT hr = CheckVideoType(pmtOut); if (FAILED(hr)) { return hr; } // Check the output format is VGA colours if (*pmtOut->Subtype() != MEDIASUBTYPE_RGB4) { NOTE("Output not VGA"); return E_INVALIDARG; } // See if we can use direct draw if (IsRectEmpty(&pTrgInfo->rcSource) == TRUE) { ASSERT(IsRectEmpty(&pTrgInfo->rcTarget) == TRUE); if (pSrcInfo->bmiHeader.biWidth == pTrgInfo->bmiHeader.biWidth) { if (pSrcInfo->bmiHeader.biHeight == pTrgInfo->bmiHeader.biHeight) { return S_OK; } } return VFW_E_TYPE_NOT_ACCEPTED; } // Create a source rectangle if it's empty RECT Source = pTrgInfo->rcSource; if (IsRectEmpty(&Source) == TRUE) { NOTE("Source rectangle filled in"); Source.left = Source.top = 0; Source.right = pSrcInfo->bmiHeader.biWidth; Source.bottom = ABSOL(pSrcInfo->bmiHeader.biHeight); } // Create a destination rectangle if it's empty RECT Target = pTrgInfo->rcTarget; if (IsRectEmpty(&Target) == TRUE) { NOTE("Target rectangle filled in"); Target.left = Target.top = 0; Target.right = pSrcInfo->bmiHeader.biWidth; Target.bottom = ABSOL(pSrcInfo->bmiHeader.biHeight); } // Check we are not stretching nor compressing the image if (WIDTH(&Source) == WIDTH(&Target)) { if (HEIGHT(&Source) == HEIGHT(&Target)) { NOTE("No stretch"); return NOERROR; } } return VFW_E_TYPE_NOT_ACCEPTED; } // We offer only one output format which is MEDIASUBTYPE_RGB4. The VGA colours // are fixed in time and space forever so we just copy the 16 colours onto the // end of the output VIDEOINFO we construct. We set the image size field to be // the actual image size rather than the default zero so that when we come to // deciding and allocating buffering we can use this to specify the image size HRESULT CDither::GetMediaType(int iPosition,CMediaType *pmtOut) { NOTE("Entering GetMediaType"); CMediaType InputType; ASSERT(pmtOut); // We only offer one format if (iPosition) { NOTE("Exceeds types supplied"); return VFW_S_NO_MORE_ITEMS; } // Allocate and zero fill the output format pmtOut->ReallocFormatBuffer(sizeof(VIDEOINFO)); VIDEOINFO *pVideoInfo = (VIDEOINFO *) pmtOut->Format(); if (pVideoInfo == NULL) { NOTE("No type memory"); return E_OUTOFMEMORY; } // Reset the output format and install the palette ZeroMemory((PVOID) pVideoInfo,sizeof(VIDEOINFO)); m_pInput->ConnectionMediaType(&InputType); VIDEOINFO *pInput = (VIDEOINFO *) InputType.Format(); BITMAPINFOHEADER *pHeader = HEADER(pVideoInfo); // Copy the system colours from the VGA palette for (LONG Index = 0;Index < 16;Index++) { pVideoInfo->bmiColors[Index].rgbRed = VGAColours[Index].rgbRed; pVideoInfo->bmiColors[Index].rgbGreen = VGAColours[Index].rgbGreen; pVideoInfo->bmiColors[Index].rgbBlue = VGAColours[Index].rgbBlue; pVideoInfo->bmiColors[Index].rgbReserved = 0; } // Copy these fields from the source format pVideoInfo->rcSource = pInput->rcSource; pVideoInfo->rcTarget = pInput->rcTarget; pVideoInfo->dwBitRate = pInput->dwBitRate; pVideoInfo->dwBitErrorRate = pInput->dwBitErrorRate; pVideoInfo->AvgTimePerFrame = pInput->AvgTimePerFrame; pHeader->biSize = sizeof(BITMAPINFOHEADER); pHeader->biWidth = pInput->bmiHeader.biWidth; pHeader->biHeight = pInput->bmiHeader.biHeight; pHeader->biPlanes = pInput->bmiHeader.biPlanes; pHeader->biBitCount = 4; pHeader->biCompression = BI_RGB; pHeader->biXPelsPerMeter = 0; pHeader->biYPelsPerMeter = 0; pHeader->biClrUsed = 16; pHeader->biClrImportant = 16; pHeader->biSizeImage = GetBitmapSize(pHeader); pmtOut->SetType(&MEDIATYPE_Video); pmtOut->SetSubtype(&MEDIASUBTYPE_RGB4); pmtOut->SetFormatType(&FORMAT_VideoInfo); pmtOut->SetSampleSize(pHeader->biSizeImage); pmtOut->SetTemporalCompression(FALSE); return NOERROR; } // Called to prepare the allocator's count of buffers and sizes, we don't care // who provides the allocator so long as it will give us a media sample. The // output format we produce is not temporally compressed so in principle we // could use any number of output buffers but it doesn't appear to gain much // performance and does add to the overall memory footprint of the system HRESULT CDither::DecideBufferSize(IMemAllocator *pAllocator, ALLOCATOR_PROPERTIES *pProperties) { NOTE("Entering DecideBufferSize"); CMediaType OutputType; ASSERT(pAllocator); ASSERT(pProperties); HRESULT hr = NOERROR; m_pOutput->ConnectionMediaType(&OutputType); pProperties->cBuffers = 1; pProperties->cbBuffer = OutputType.GetSampleSize(); ASSERT(pProperties->cbBuffer); // Ask the allocator to reserve us some sample memory, NOTE the function // can succeed (that is return NOERROR) but still not have allocated the // memory that we requested, so we must check we got whatever we wanted ALLOCATOR_PROPERTIES Actual; hr = pAllocator->SetProperties(pProperties,&Actual); if (FAILED(hr)) { NOTE("Properties failed"); return hr; } // Did we get the buffering requirements if (Actual.cbBuffer >= (LONG) OutputType.GetSampleSize()) { if (Actual.cBuffers >= 1) { NOTE("Request ok"); return NOERROR; } } return VFW_E_SIZENOTSET; } // Called when the media type is set for one of our pins HRESULT CDither::SetMediaType(PIN_DIRECTION direction,const CMediaType *pmt) { HRESULT hr = S_OK; if (direction == PINDIR_INPUT) { ASSERT(*pmt->Subtype() == MEDIASUBTYPE_RGB8); hr = SetInputPinMediaType(pmt); } else { ASSERT(*pmt->Subtype() == MEDIASUBTYPE_RGB4); SetOutputPinMediaType(pmt); } return hr; } HRESULT CDither::SetInputPinMediaType(const CMediaType *pmt) { VIDEOINFO *pInput = (VIDEOINFO *)pmt->pbFormat; BITMAPINFOHEADER *pbiSrc = HEADER(pInput); m_fInit = DitherDeviceInit(pbiSrc); if (!m_fInit) { return E_OUTOFMEMORY; } ASSERT(pbiSrc->biBitCount == 8); m_wWidthSrc = (pbiSrc->biWidth + 3) & ~3; return S_OK; } void CDither::SetOutputPinMediaType(const CMediaType *pmt) { VIDEOINFO *pOutput = (VIDEOINFO *)pmt->pbFormat; BITMAPINFOHEADER *pbiDst = HEADER(pOutput); ASSERT(pbiDst->biBitCount == 4); m_wWidthDst = ((pbiDst->biWidth * 4) + 7) / 8; m_wWidthDst = (m_wWidthDst + 3) & ~3; m_DstXE = pbiDst->biWidth; m_DstYE = pbiDst->biHeight; } // Dither to the colors of the display driver BOOL CDither::DitherDeviceInit(LPBITMAPINFOHEADER lpbi) { HBRUSH hbr = (HBRUSH) NULL; HDC hdcMem = (HDC) NULL; HDC hdc = (HDC) NULL; HBITMAP hbm = (HBITMAP) NULL; HBITMAP hbmT = (HBITMAP) NULL; int i; int nColors; LPBYTE lpDitherTable; LPRGBQUAD prgb; BYTE biSave[sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD)]; LPBITMAPINFOHEADER lpbiOut = (LPBITMAPINFOHEADER)&biSave; NOTE("DitherDeviceInit called"); // // we dont need to re-init the dither table, unless it is not ours then // we should free it. // lpDitherTable = (LPBYTE)GlobalAllocPtr(GHND, 256*8*4); if (lpDitherTable == NULL) { return FALSE; } hdc = GetDC(NULL); if ( ! hdc ) goto ErrorExit; hdcMem = CreateCompatibleDC(hdc); if ( ! hdcMem ) goto ErrorExit; hbm = CreateCompatibleBitmap(hdc, 256*8, 8); if ( ! hbm ) goto ErrorExit; hbmT = (HBITMAP)SelectObject(hdcMem, (HBITMAP)hbm); if ((nColors = (int)lpbi->biClrUsed) == 0) nColors = 1 << (int)lpbi->biBitCount; prgb = (LPRGBQUAD)(lpbi+1); for (i=0; i<nColors; i++) { hbr = CreateSolidBrush(RGB(prgb[i].rgbRed, prgb[i].rgbGreen, prgb[i].rgbBlue)); if ( hbr ) { hbr = (HBRUSH)SelectObject(hdcMem, hbr); PatBlt(hdcMem, i*8, 0, 8, 8, PATCOPY); hbr = (HBRUSH)SelectObject(hdcMem, hbr); DeleteObject(hbr); } } SelectObject(hdcMem, hbmT); DeleteDC(hdcMem); lpbiOut->biSize = sizeof(BITMAPINFOHEADER); lpbiOut->biPlanes = 1; lpbiOut->biBitCount = 4; lpbiOut->biWidth = 256*8; lpbiOut->biHeight = 8; lpbiOut->biCompression = BI_RGB; lpbiOut->biSizeImage = 256*8*4; lpbiOut->biXPelsPerMeter = 0; lpbiOut->biYPelsPerMeter = 0; lpbiOut->biClrUsed = 0; lpbiOut->biClrImportant = 0; GetDIBits(hdc, hbm, 0, 8, lpDitherTable, (LPBITMAPINFO)lpbiOut, DIB_RGB_COLORS); DeleteObject(hbm); ReleaseDC(NULL, hdc); for (i = 0; i < 256*8*4; i++) { BYTE twoPels = lpDitherTable[i]; m_DitherTable[(i * 2) + 0] = (BYTE)((twoPels & 0xF0) >> 4); m_DitherTable[(i * 2) + 1] = (BYTE)(twoPels & 0x0F); } GlobalFreePtr(lpDitherTable); return TRUE; ErrorExit: if ( NULL != hdcMem && NULL != hbmT ) SelectObject(hdcMem, hbmT); if ( NULL != hdcMem ) DeleteDC(hdcMem); if ( hbm ) DeleteObject(hbm); if ( hdc ) ReleaseDC(NULL, hdc); if ( lpDitherTable ) GlobalFreePtr(lpDitherTable); return FALSE; } #define DODITH8(px, _x_) (m_DitherTable)[yDith + (px) * 8 + (_x_)] // Call this to actually do the dither. void CDither::Dither8(LPBYTE lpDst,LPBYTE lpSrc) { int x,y; BYTE *pbS; BYTE *pbD; DWORD dw; NOTE("Dither8"); for (y=0; y < m_DstYE; y++) { int yDith = (y & 7) * 256 * 8; pbD = lpDst; pbS = lpSrc; // write one DWORD (one dither cell horizontally) at once for (x=0; x + 8 <= m_DstXE; x += 8) { dw = DODITH8(*(pbS + 6), 6); dw <<= 4; dw |= DODITH8(*(pbS + 7), 7); dw <<= 4; dw |= DODITH8(*(pbS + 4), 4); dw <<= 4; dw |= DODITH8(*(pbS + 5), 5); dw <<= 4; dw |= DODITH8(*(pbS + 2), 2); dw <<= 4; dw |= DODITH8(*(pbS + 3), 3); dw <<= 4; dw |= DODITH8(*(pbS + 0), 0); dw <<= 4; dw |= DODITH8(*(pbS + 1), 1); *((DWORD UNALIGNED *) pbD) = dw; pbS += 8; pbD += 4; } // clean up remainder (less than 8 bytes per row) int EvenPelsLeft = ((m_DstXE - x) & ~1); int OddPelLeft = ((m_DstXE - x) & 1); for (x = 0; x < EvenPelsLeft; x += 2) { *pbD++ = (DODITH8(*pbS++, x ) << 4) | DODITH8(*pbS++, x+1); } if (OddPelLeft) { *pbD++ = (DODITH8(*pbS++, x) << 4); } lpSrc += m_wWidthSrc; lpDst += m_wWidthDst; } }
29.346709
82
0.590877
[ "object", "transform" ]
f377d90b128e43ee8d4ea419d0e4c64bf80223b4
4,305
cpp
C++
lib/Instrumentation/Callbacks.cpp
clagah/mull
9b5a7824b4f3ecdeff64e3b77ee63db2b40b3f99
[ "Apache-2.0" ]
null
null
null
lib/Instrumentation/Callbacks.cpp
clagah/mull
9b5a7824b4f3ecdeff64e3b77ee63db2b40b3f99
[ "Apache-2.0" ]
null
null
null
lib/Instrumentation/Callbacks.cpp
clagah/mull
9b5a7824b4f3ecdeff64e3b77ee63db2b40b3f99
[ "Apache-2.0" ]
1
2019-06-10T02:43:04.000Z
2019-06-10T02:43:04.000Z
#include "mull/Instrumentation/Callbacks.h" #include "mull/Driver.h" #include "mull/Instrumentation/DynamicCallTree.h" #include "mull/Instrumentation/Instrumentation.h" #include "mull/MullModule.h" #include <llvm/IR/Constants.h> #include <llvm/IR/GlobalVariable.h> #include <llvm/IR/Instructions.h> #include <llvm/IR/Module.h> using namespace mull; using namespace llvm; namespace mull { extern "C" void mull_enterFunction(void **trampoline, uint32_t functionIndex) { InstrumentationInfo *info = (InstrumentationInfo *)*trampoline; assert(info); assert(info->callTreeMapping); DynamicCallTree::enterFunction(functionIndex, info->callTreeMapping, info->callstack); } extern "C" void mull_leaveFunction(void **trampoline, uint32_t functionIndex) { InstrumentationInfo *info = (InstrumentationInfo *)*trampoline; assert(info); assert(info->callTreeMapping); DynamicCallTree::leaveFunction(functionIndex, info->callTreeMapping, info->callstack); } } // namespace mull Value *Callbacks::injectInstrumentationInfoPointer(Module *module, const char *variableName) { auto &context = module->getContext(); auto trampolineType = Type::getInt8Ty(context)->getPointerTo(); return module->getOrInsertGlobal(variableName, trampolineType); } Value * Callbacks::injectFunctionIndexOffset(Module *module, const char *functionIndexOffsetPrefix) { auto &context = module->getContext(); auto functionIndexOffsetType = Type::getInt32Ty(context); std::string functionIndexOffset(functionIndexOffsetPrefix); functionIndexOffset += module->getModuleIdentifier(); return module->getOrInsertGlobal(functionIndexOffset, functionIndexOffsetType); } void Callbacks::injectCallbacks(llvm::Function *function, uint32_t index, Value *infoPointer, Value *offset) { auto &context = function->getParent()->getContext(); auto intType = Type::getInt32Ty(context); auto trampolineType = Type::getInt8Ty(context)->getPointerTo()->getPointerTo(); auto voidType = Type::getVoidTy(context); std::vector<Type *> parameterTypes({trampolineType, intType}); FunctionType *callbackType = FunctionType::get(voidType, parameterTypes, false); Function *enterFunction = function->getParent()->getFunction("mull_enterFunction"); Function *leaveFunction = function->getParent()->getFunction("mull_leaveFunction"); if (enterFunction == nullptr && leaveFunction == nullptr) { enterFunction = Function::Create(callbackType, Function::ExternalLinkage, "mull_enterFunction", function->getParent()); leaveFunction = Function::Create(callbackType, Function::ExternalLinkage, "mull_leaveFunction", function->getParent()); } assert(enterFunction); assert(leaveFunction); Value *functionIndex = ConstantInt::get(intType, index); auto &entryBlock = *function->getBasicBlockList().begin(); auto firstInstruction = &*entryBlock.getInstList().begin(); Value *offsetValue = new LoadInst(offset, "offset", firstInstruction); Value *indexAndOffset = BinaryOperator::Create(Instruction::Add, functionIndex, offsetValue, "functionIndex", firstInstruction); std::vector<Value *> enterParameters({infoPointer, indexAndOffset}); CallInst *enterFunctionCall = CallInst::Create(enterFunction, enterParameters); enterFunctionCall->insertBefore(firstInstruction); for (auto &block : function->getBasicBlockList()) { ReturnInst *returnStatement = nullptr; if (!(returnStatement = dyn_cast<ReturnInst>(block.getTerminator()))) { continue; } Value *offsetValue = new LoadInst(offset, "offset", returnStatement); Value *indexAndOffset = BinaryOperator::Create(Instruction::Add, functionIndex, offsetValue, "functionIndex", returnStatement); std::vector<Value *> leaveParameters({infoPointer, indexAndOffset}); CallInst *leaveFunctionCall = CallInst::Create(leaveFunction, leaveParameters); leaveFunctionCall->insertBefore(returnStatement); } }
36.794872
79
0.695703
[ "vector" ]
f37aa186115aff679b97800b260d8bc8fdae5cce
1,150
hpp
C++
Questless/Questless/src/ui/inventory_widget.hpp
jonathansharman/questless
bb9ffb2d21cbfde2a71edfecfcbf466479bbbe7d
[ "MIT" ]
2
2020-07-14T12:50:06.000Z
2020-11-04T02:25:09.000Z
Questless/Questless/src/ui/inventory_widget.hpp
jonathansharman/questless
bb9ffb2d21cbfde2a71edfecfcbf466479bbbe7d
[ "MIT" ]
null
null
null
Questless/Questless/src/ui/inventory_widget.hpp
jonathansharman/questless
bb9ffb2d21cbfde2a71edfecfcbf466479bbbe7d
[ "MIT" ]
null
null
null
//! @file //! @copyright See <a href="LICENSE.txt">LICENSE.txt</a>. #pragma once #include "widget.hpp" #include "items/inventory.hpp" namespace ql { struct hotbar; //! Interfaces with an inventory. struct inventory_widget : widget { inventory_widget(inventory& inventory, hotbar& hotbar); auto get_size() const -> view::vector final; auto update(sec elapsed_time) -> void final; auto set_position(view::point position) -> void final; auto get_position() const -> view::point final; auto on_parent_resize(view::vector parent_size) -> void final; auto on_key_press(sf::Event::KeyEvent const&) -> event_handled final; auto on_mouse_move(view::point mouse_position) -> void final; private: gsl::not_null<inventory*> _inv; gsl::not_null<hotbar*> _hotbar; view::point _position; view::vector _size; int _inv_page = 0; //! @todo Replace with filters and a scrollable view. int _row_count; int _col_count; std::vector<id> _displayed_items; view::point _mouse_position; auto draw(sf::RenderTarget& target, sf::RenderStates states) const -> void final; auto assign_idx(size_t hotbar_idx) -> void; }; }
24.468085
83
0.716522
[ "vector" ]
3ce244a4f6fb645a97f632b996a73caaa5bbcf1e
14,477
cpp
C++
core/common/chandir.cpp
plonk/peercast-0.1218
30fc2401dc798336429a979fe7aaca8883e63ed9
[ "PSF-2.0", "Apache-2.0", "OpenSSL", "MIT" ]
null
null
null
core/common/chandir.cpp
plonk/peercast-0.1218
30fc2401dc798336429a979fe7aaca8883e63ed9
[ "PSF-2.0", "Apache-2.0", "OpenSSL", "MIT" ]
null
null
null
core/common/chandir.cpp
plonk/peercast-0.1218
30fc2401dc798336429a979fe7aaca8883e63ed9
[ "PSF-2.0", "Apache-2.0", "OpenSSL", "MIT" ]
null
null
null
#include <algorithm> #include <sstream> #include <memory> // unique_ptr #include <stdexcept> // runtime_error #include "http.h" #include "version2.h" #include "socket.h" #include "chandir.h" #include "uri.h" #include "servmgr.h" using namespace std; std::vector<ChannelEntry> ChannelEntry::textToChannelEntries(const std::string& text, const std::string& aFeedUrl, std::vector<std::string>& errors) { istringstream in(text); string line; vector<ChannelEntry> res; int lineno = 0; while (getline(in, line)) { lineno++; vector<string> fields = str::split(line, "<>"); if (fields.size() != 19) { errors.push_back(str::format("Parse error at line %d.", lineno)); } else { res.push_back(ChannelEntry(fields, aFeedUrl)); } } return res; } std::string ChannelEntry::chatUrl() { if (encodedName.empty()) return ""; auto index = feedUrl.rfind('/'); if (index == std::string::npos) return ""; else return feedUrl.substr(0, index) + "/chat.php?cn=" + encodedName; } std::string ChannelEntry::statsUrl() { if (encodedName.empty()) return ""; auto index = feedUrl.rfind('/'); if (index == std::string::npos) return ""; else return feedUrl.substr(0, index) + "/getgmt.php?cn=" + encodedName; } ChannelDirectory::ChannelDirectory() : m_lastUpdate(0) { } int ChannelDirectory::numChannels() const { std::lock_guard<std::recursive_mutex> cs(m_lock); return m_channels.size(); } int ChannelDirectory::numFeeds() const { std::lock_guard<std::recursive_mutex> cs(m_lock); return m_feeds.size(); } #include "sslclientsocket.h" // index.txt を指す URL である url からチャンネルリストを読み込み、out // に格納する。成功した場合は true が返る。エラーが発生した場合は // false が返る。false を返した場合でも out に読み込めたチャンネル情報 // が入っている場合がある。 static bool getFeed(std::string url, std::vector<ChannelEntry>& out) { out.clear(); URI feed(url); if (!feed.isValid()) { LOG_ERROR("invalid URL (%s)", url.c_str()); return false; } if (feed.scheme() != "http" && feed.scheme() != "https") { LOG_ERROR("unsupported protocol (%s)", url.c_str()); return false; } Host host; host.fromStrName(feed.host().c_str(), feed.port()); if (!host.ip) { LOG_ERROR("Could not resolve %s", feed.host().c_str()); return false; } std::shared_ptr<ClientSocket> rsock; if (feed.scheme() == "https") { rsock = std::make_shared<SslClientSocket>(); } else { rsock = sys->createSocket(); } try { LOG_TRACE("Connecting to %s (%s) port %d ...", feed.host().c_str(), host.ip.str().c_str(), feed.port()); rsock->open(host); rsock->connect(); LOG_TRACE("Connected to %s", host.str().c_str()); HTTP rhttp(*rsock); HTTPRequest req("GET", feed.path() + "?host=" + cgi::escape(servMgr->serverHost), "HTTP/1.1", { { "Host", feed.host() }, { "Connection", "close" }, { "User-Agent", PCX_AGENT } }); HTTPResponse res = rhttp.send(req); if (res.statusCode != 200) { LOG_ERROR("%s: status code %d", feed.host().c_str(), res.statusCode); return false; } std::vector<std::string> errors; out = ChannelEntry::textToChannelEntries(res.body, url, errors); for (auto& message : errors) { LOG_ERROR("%s", message.c_str()); } return errors.empty(); } catch (StreamException& e) { LOG_ERROR("%s", e.msg); return false; } } #include "sstream.h" #include "defer.h" #include "logbuf.h" static std::string runProcess(std::function<void(Stream&)> action) { StringStream ss; try { assert(AUX_LOG_FUNC_VECTOR != nullptr); AUX_LOG_FUNC_VECTOR->push_back([&](LogBuffer::TYPE type, const char* msg) -> void { if (type == LogBuffer::T_ERROR) ss.writeString("Error: "); else if (type == LogBuffer::T_WARN) ss.writeString("Warning: "); ss.writeLine(msg); }); Defer defer([]() { AUX_LOG_FUNC_VECTOR->pop_back(); }); action(ss); } catch(GeneralException& e) { ss.writeLineF("Error: %s\n", e.what()); } return ss.str(); } bool ChannelDirectory::update(UpdateMode mode) { std::lock_guard<std::recursive_mutex> cs(m_lock); const unsigned int coolDownTime = (mode==kUpdateManual) ? 30 : 5 * 60; if (sys->getTime() - m_lastUpdate < coolDownTime) return false; double t0 = sys->getDTime(); std::vector<std::thread> workers; std::mutex mutex; // m_channels を保護するミューテックス。 m_channels.clear(); for (auto& feed : m_feeds) { std::function<void(void)> getChannels = [&feed, &mutex, this] { assert(AUX_LOG_FUNC_VECTOR == nullptr); AUX_LOG_FUNC_VECTOR = new std::vector<std::function<void(LogBuffer::TYPE type, const char*)>>(); assert(AUX_LOG_FUNC_VECTOR != nullptr); Defer defer([]() { assert(AUX_LOG_FUNC_VECTOR != nullptr); delete AUX_LOG_FUNC_VECTOR; }); feed.log = runProcess([&feed, &mutex, this](Stream& s) { // print start time String time; time.setFromTime(sys->getTime()); s.writeStringF("Start time: %s\n", time.c_str()); // two newlines at the end std::vector<ChannelEntry> channels; bool success; double t1 = sys->getDTime(); success = getFeed(feed.url, channels); double t2 = sys->getDTime(); LOG_TRACE("Got %zu channels from %s (%.6f seconds)", channels.size(), feed.url.c_str(), t2 - t1); if (success) { feed.status = ChannelFeed::Status::kOk; } else { feed.status = ChannelFeed::Status::kError; } { std::lock_guard<std::mutex> lock(mutex); for (auto& c : channels) m_channels.push_back(c); } }); }; workers.push_back(std::thread(getChannels)); } for (auto& t : workers) t.join(); sort(m_channels.begin(), m_channels.end(), [](ChannelEntry& a, ChannelEntry& b) { return a.numDirects > b.numDirects; }); m_lastUpdate = sys->getTime(); LOG_INFO("Channel feed update: total of %zu channels in %f sec", m_channels.size(), sys->getDTime() - t0); return true; } // index番目のチャンネル詳細のフィールドを出力する。成功したら true を返す。 bool ChannelDirectory::writeChannelVariable(Stream& out, const String& varName, int index) { using namespace std; std::lock_guard<std::recursive_mutex> cs(m_lock); if (!(index >= 0 && (size_t)index < m_channels.size())) return false; string buf; ChannelEntry& ch = m_channels[index]; if (varName == "name") { buf = ch.name; } else if (varName == "id") { buf = ch.id.str(); } else if (varName == "bitrate") { buf = to_string(ch.bitrate); } else if (varName == "contentTypeStr") { buf = ch.contentTypeStr; } else if (varName == "desc") { buf = ch.desc; } else if (varName == "genre") { buf = ch.genre; } else if (varName == "url") { buf = ch.url; } else if (varName == "tip") { buf = ch.tip; } else if (varName == "encodedName") { buf = ch.encodedName; } else if (varName == "uptime") { buf = ch.uptime; } else if (varName == "numDirects") { buf = to_string(ch.numDirects); } else if (varName == "numRelays") { buf = to_string(ch.numRelays); } else if (varName == "chatUrl") { buf = ch.chatUrl(); } else if (varName == "statsUrl") { buf = ch.statsUrl(); } else if (varName == "isPlayable") { buf = to_string(ch.id.isSet()); } else { return false; } out.writeString(buf); return true; } bool ChannelDirectory::writeFeedVariable(Stream& out, const String& varName, int index) { std::lock_guard<std::recursive_mutex> cs(m_lock); if (!(index >= 0 && (size_t)index < m_feeds.size())) { // empty string return true; } string value; if (varName == "url") { value = m_feeds[index].url; } else if (varName == "directoryUrl") { value = str::replace_suffix(m_feeds[index].url, "index.txt", ""); } else if (varName == "status") { value = ChannelFeed::statusToString(m_feeds[index].status); } else { return false; } out.writeString(value.c_str()); return true; } static std::string formatTime(unsigned int diff) { auto min = diff / 60; auto sec = diff % 60; if (min == 0) { return str::format("%ds", sec); } else { return str::format("%dm %ds", min, sec); } } amf0::Value ChannelDirectory::getState() { std::vector<amf0::Value> channels; for (auto& c : this->channels()) { channels.push_back(amf0::Value::object( { { "name", c.name }, { "id", c.id.str() }, { "tip", c.tip }, { "url", c.url }, { "genre", c.genre }, { "desc", c.desc }, { "numDirects", c.numDirects }, { "numRelays", c.numRelays }, { "bitrate", c.bitrate }, { "contentTypeStr", c.contentTypeStr }, { "trackArtist", c.trackArtist }, { "trackAlbum", c.trackAlbum }, { "trackName", c.trackName }, { "trackContact", c.trackContact }, { "encodedName", c.encodedName }, { "uptime", c.uptime }, { "status", c.status }, { "comment", c.comment }, { "direct", c.direct }, { "feedUrl", c.feedUrl }, { "chatUrl", c.chatUrl() }, { "statsUrl", c.statsUrl() }, })); } std::vector<amf0::Value> feeds; for (auto& f : this->feeds()) { feeds.push_back(amf0::Value::object( { {"url", f.url}, {"directoryUrl", str::replace_suffix(f.url, "index.txt", "")}, {"status", ChannelFeed::statusToString(f.status) } })); } return amf0::Value::object( { {"totalListeners", totalListeners()}, {"totalRelays", totalRelays()}, {"lastUpdate", formatTime(sys->getTime() - m_lastUpdate)}, {"channels", amf0::Value::strictArray(channels) }, {"feeds", amf0::Value::strictArray(feeds) }, }); } int ChannelDirectory::totalListeners() const { std::lock_guard<std::recursive_mutex> cs(m_lock); int res = 0; for (const ChannelEntry& e : m_channels) { res += std::max(0, e.numDirects); } return res; } int ChannelDirectory::totalRelays() const { std::lock_guard<std::recursive_mutex> cs(m_lock); int res = 0; for (const ChannelEntry& e : m_channels) { res += std::max(0, e.numRelays); } return res; } std::vector<ChannelFeed> ChannelDirectory::feeds() const { std::lock_guard<std::recursive_mutex> cs(m_lock); return m_feeds; } bool ChannelDirectory::addFeed(const std::string& url) { std::lock_guard<std::recursive_mutex> cs(m_lock); auto iter = find_if(m_feeds.begin(), m_feeds.end(), [&](ChannelFeed& f) { return f.url == url;}); if (iter != m_feeds.end()) { LOG_ERROR("Already have feed %s", url.c_str()); return false; } URI u(url); if (!u.isValid() || (u.scheme() != "http" && u.scheme() != "https")) { LOG_ERROR("Invalid feed URL %s", url.c_str()); return false; } m_feeds.push_back(ChannelFeed(url)); return true; } void ChannelDirectory::clearFeeds() { std::lock_guard<std::recursive_mutex> cs(m_lock); m_feeds.clear(); m_channels.clear(); m_lastUpdate = 0; } std::string ChannelDirectory::findTracker(const GnuID& id) const { for (const ChannelEntry& entry : m_channels) { if (entry.id.isSame(id)) return entry.tip; } return ""; } std::string ChannelFeed::statusToString(ChannelFeed::Status s) { switch (s) { case Status::kUnknown: return "UNKNOWN"; case Status::kOk: return "OK"; case Status::kError: return "ERROR"; } throw std::logic_error("should be unreachable"); } std::vector<ChannelEntry> ChannelDirectory::channels() const { std::lock_guard<std::recursive_mutex> cs(m_lock); return m_channels; }
30.802128
139
0.490157
[ "object", "vector" ]
3ce2964f719e650ac641ce48e519ef97f9e867ed
2,061
cpp
C++
ncnn/ncnn_mnist_classify/ncnn_mnist_classify.cpp
zczjx/es_ai_inference
dce23f9f7a5cde3c3e051fe75b929bf16b9c7df7
[ "MIT" ]
null
null
null
ncnn/ncnn_mnist_classify/ncnn_mnist_classify.cpp
zczjx/es_ai_inference
dce23f9f7a5cde3c3e051fe75b929bf16b9c7df7
[ "MIT" ]
null
null
null
ncnn/ncnn_mnist_classify/ncnn_mnist_classify.cpp
zczjx/es_ai_inference
dce23f9f7a5cde3c3e051fe75b929bf16b9c7df7
[ "MIT" ]
null
null
null
#include <time.h> #include <pthread.h> #include <unistd.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #include <vector> #include <deque> #include <list> #include <iostream> #include <algorithm> #include <cstdio> #include "platform.h" #include "net.h" #include "es_ncnn_common.hpp" using namespace std; using namespace es_ncnn; int main(int argc, char** argv) { list< pair<ncnn:: Mat, uint8_t> > test_dat; int err_cnt, total_cnt; float acc_rate = 0.0; ncnn::Net demo_net; time_t start_time, end_time; double infer_sec = 0.0; if(argc < 5) { cout << "exam: ./ncnn_mnist_classify test_datset test_labels ncnn.bin ncnn.param " << endl; return -1; } test_dat = load_mnist_fmt_data(argv[1], argv[2]); demo_net.load_param(argv[4]); demo_net.load_model(argv[3]); err_cnt = 0; total_cnt = 0; start_time = time(NULL); for(pair<ncnn:: Mat, uint8_t> pair_item : test_dat) { ncnn:: Mat ncnn_in = pair_item.first; int label = pair_item.second; ncnn:: Mat ncnn_out; int out_val; ncnn::Extractor ex = demo_net.create_extractor(); ex.input("demo_in_data", ncnn_in); ex.extract("demo_out_data", ncnn_out); vector<float> out_vec(ncnn_out.w); for (int j = 0; j < ncnn_out.w; j++) { out_vec[j] = ncnn_out[j]; } vector<float>:: iterator max_iter = max_element(out_vec.begin(), out_vec.end()); out_val = distance(out_vec.begin(), max_iter); total_cnt++; if(out_val != label) err_cnt++; } end_time = time(NULL); infer_sec = difftime(end_time, start_time); printf("total_cnt: %d, err_cnt: %d, inference time %f sec\n", total_cnt, err_cnt, infer_sec); acc_rate = ((float) (total_cnt - err_cnt)) / (float) (total_cnt); printf("test acc_rate: %f\n", acc_rate); cout << "finish cnn test......" << endl; return 0; }
25.444444
99
0.594857
[ "vector" ]
3ce795822ca18de8309887be32ed9e49a9f30d60
2,400
cxx
C++
src/Cxx/Visualization/ScaleGlyphs.cxx
cvandijck/VTKExamples
b6bb89414522afc1467be8a1f0089a37d0c16883
[ "Apache-2.0" ]
309
2017-05-21T09:07:19.000Z
2022-03-15T09:18:55.000Z
src/Cxx/Visualization/ScaleGlyphs.cxx
yijianmingliu/VTKExamples
dc8aac47c4384f9a2de9facbdd1ab3249f62ec99
[ "Apache-2.0" ]
379
2017-05-21T09:06:43.000Z
2021-03-29T20:30:50.000Z
src/Cxx/Visualization/ScaleGlyphs.cxx
yijianmingliu/VTKExamples
dc8aac47c4384f9a2de9facbdd1ab3249f62ec99
[ "Apache-2.0" ]
170
2017-05-17T14:47:41.000Z
2022-03-31T13:16:26.000Z
#include <vtkSmartPointer.h> #include <vtkPointData.h> #include <vtkCubeSource.h> #include <vtkPolyData.h> #include <vtkPoints.h> #include <vtkGlyph3D.h> #include <vtkCellArray.h> #include <vtkPolyDataMapper.h> #include <vtkActor.h> #include <vtkRenderWindow.h> #include <vtkRenderer.h> #include <vtkRenderWindowInteractor.h> #include <vtkFloatArray.h> int main(int, char *[]) { // Create points vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); points->InsertNextPoint(0,0,0); points->InsertNextPoint(5,0,0); points->InsertNextPoint(10,0,0); // Setup scales vtkSmartPointer<vtkFloatArray> scales = vtkSmartPointer<vtkFloatArray>::New(); scales->SetName("scales"); scales->InsertNextValue(1.0); scales->InsertNextValue(2.0); scales->InsertNextValue(3.0); // Combine into a polydata vtkSmartPointer<vtkPolyData> polydata = vtkSmartPointer<vtkPolyData>::New(); polydata->SetPoints(points); polydata->GetPointData()->SetScalars(scales); // Create anything you want here, we will use a cube for the demo. vtkSmartPointer<vtkCubeSource> cubeSource = vtkSmartPointer<vtkCubeSource>::New(); vtkSmartPointer<vtkGlyph3D> glyph3D = vtkSmartPointer<vtkGlyph3D>::New(); glyph3D->SetScaleModeToScaleByScalar(); glyph3D->SetSourceConnection(cubeSource->GetOutputPort()); glyph3D->SetInputData(polydata); glyph3D->Update(); // Create a mapper and actor vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); mapper->SetInputConnection(glyph3D->GetOutputPort()); vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New(); actor->SetMapper(mapper); // Create a renderer, render window, and interactor vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New(); vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<vtkRenderWindow>::New(); renderWindow->AddRenderer(renderer); vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New(); renderWindowInteractor->SetRenderWindow(renderWindow); // Add the actor to the scene renderer->AddActor(actor); renderer->SetBackground(1,1,1); // Background color white // Render and interact renderWindow->Render(); renderWindowInteractor->Start(); return EXIT_SUCCESS; }
30.769231
70
0.74125
[ "render" ]
3ce86df20fd6740c921dc70f61482c3440bdc251
10,069
cpp
C++
libcxx/test/libcxx/iterators/iterator.requirements/iterator.assoc.types/iterator.traits/legacy_iterator.compile.pass.cpp
lxbndr/llvm-project
2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34
[ "Apache-2.0" ]
null
null
null
libcxx/test/libcxx/iterators/iterator.requirements/iterator.assoc.types/iterator.traits/legacy_iterator.compile.pass.cpp
lxbndr/llvm-project
2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34
[ "Apache-2.0" ]
null
null
null
libcxx/test/libcxx/iterators/iterator.requirements/iterator.assoc.types/iterator.traits/legacy_iterator.compile.pass.cpp
lxbndr/llvm-project
2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34
[ "Apache-2.0" ]
null
null
null
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++03, c++11, c++14, c++17 // This test uses iterator types from std::filesystem, which were introduced in macOS 10.15. // XFAIL: use_system_cxx_lib && target={{.+}}-apple-macosx10.{{9|10|11|12|13|14}} // template<class I> // concept __iterator_traits_detail::__cpp17_iterator; #include <iterator> #include <array> #include <deque> #ifndef _LIBCPP_HAS_NO_FILESYSTEM_LIBRARY #include <filesystem> #endif #include <forward_list> #include <list> #include <map> #include <set> #include <string> #include <string_view> #include <unordered_map> #include <unordered_set> #include <vector> #include "iterator_traits_cpp17_iterators.h" static_assert(std::__iterator_traits_detail::__cpp17_iterator<iterator_traits_cpp17_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<iterator_traits_cpp17_proxy_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<iterator_traits_cpp17_input_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<iterator_traits_cpp17_proxy_input_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<iterator_traits_cpp17_forward_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<iterator_traits_cpp17_bidirectional_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<iterator_traits_cpp17_random_access_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<int*>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<int const*>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<int volatile*>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<int const volatile*>); // <array> static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::array<int, 10>::iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::array<int, 10>::const_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::array<int, 10>::reverse_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::array<int, 10>::const_reverse_iterator>); // <deque> static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::deque<int>::iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::deque<int>::const_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::deque<int>::reverse_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::deque<int>::const_reverse_iterator>); // <filesystem> #ifndef _LIBCPP_HAS_NO_FILESYSTEM_LIBRARY static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::filesystem::directory_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::filesystem::recursive_directory_iterator>); #endif // <forward_list> static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::forward_list<int>::iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::forward_list<int>::const_iterator>); // <iterator> static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::back_insert_iterator<std::vector<int>>>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::front_insert_iterator<std::vector<int>>>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::insert_iterator<std::vector<int>>>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::move_iterator<int*>>); // <list> static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::list<int>::iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::list<int>::const_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::list<int>::reverse_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::list<int>::const_reverse_iterator>); // <map> static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::map<int, int>::iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::map<int, int>::const_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::map<int, int>::reverse_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::map<int, int>::const_reverse_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::multimap<int, int>::iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::multimap<int, int>::const_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::multimap<int, int>::reverse_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::multimap<int, int>::const_reverse_iterator>); // <set> static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::set<int>::iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::set<int>::const_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::set<int>::reverse_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::set<int>::const_reverse_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::multiset<int>::iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::multiset<int>::const_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::multiset<int>::reverse_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::multiset<int>::const_reverse_iterator>); // <string> static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::string::iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::string::const_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::string::reverse_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::string::const_reverse_iterator>); // <string_view> static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::string_view::iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::string_view::const_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::string_view::reverse_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::string_view::const_reverse_iterator>); // <unordered_map> static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::unordered_map<int, int>::iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::unordered_map<int, int>::const_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::unordered_map<int, int>::local_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::unordered_map<int, int>::const_local_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::unordered_multimap<int, int>::iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::unordered_multimap<int, int>::const_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::unordered_multimap<int, int>::local_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::unordered_multimap<int, int>::const_local_iterator>); // <unordered_set> static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::unordered_set<int>::iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::unordered_set<int>::const_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::unordered_set<int>::local_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::unordered_set<int>::const_local_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::unordered_multiset<int>::iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::unordered_multiset<int>::const_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::unordered_multiset<int>::local_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::unordered_multiset<int>::const_local_iterator>); // <vector> static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::vector<int>::iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::vector<int>::const_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::vector<int>::reverse_iterator>); static_assert(std::__iterator_traits_detail::__cpp17_iterator<std::vector<int>::const_reverse_iterator>); // Not iterators static_assert(!std::__iterator_traits_detail::__cpp17_iterator<void>); static_assert(!std::__iterator_traits_detail::__cpp17_iterator<void*>); static_assert(!std::__iterator_traits_detail::__cpp17_iterator<int* const>); static_assert(!std::__iterator_traits_detail::__cpp17_iterator<std::vector<int>::iterator volatile>); static_assert(!std::__iterator_traits_detail::__cpp17_iterator<std::vector<int>::iterator&>); static_assert(!std::__iterator_traits_detail::__cpp17_iterator<std::vector<int>::iterator&&>); static_assert(!std::__iterator_traits_detail::__cpp17_iterator<int>); static_assert(!std::__iterator_traits_detail::__cpp17_iterator<int[]>); static_assert(!std::__iterator_traits_detail::__cpp17_iterator<int[10]>); static_assert(!std::__iterator_traits_detail::__cpp17_iterator<int()>); static_assert(!std::__iterator_traits_detail::__cpp17_iterator<int (*)()>); static_assert(!std::__iterator_traits_detail::__cpp17_iterator<int (&)()>); struct S {}; static_assert(!std::__iterator_traits_detail::__cpp17_iterator<S>); static_assert(!std::__iterator_traits_detail::__cpp17_iterator<int S::*>); static_assert(!std::__iterator_traits_detail::__cpp17_iterator<int (S::*)()>);
61.773006
120
0.812891
[ "vector" ]
3ce9681d61a403f9610c09575378d4c40eda99ff
17,966
cpp
C++
schwarzwald/test/TestTiler.cpp
igd-geo/schwarzwald
e3e041f87c93985394444ee056ce8ba7ae62194b
[ "Apache-2.0" ]
10
2021-01-06T14:16:31.000Z
2022-02-13T00:15:17.000Z
schwarzwald/test/TestTiler.cpp
igd-geo/schwarzwald
e3e041f87c93985394444ee056ce8ba7ae62194b
[ "Apache-2.0" ]
1
2022-03-25T08:37:30.000Z
2022-03-30T06:28:06.000Z
schwarzwald/test/TestTiler.cpp
igd-geo/schwarzwald
e3e041f87c93985394444ee056ce8ba7ae62194b
[ "Apache-2.0" ]
3
2020-12-03T13:50:42.000Z
2022-02-08T11:45:45.000Z
// TODO Rewrite these tests once the 'MultiReaderPointSource' can work with // in-memory files // #include "catch.hpp" // #include "datastructures/SparseGrid.h" // #include "io/BinaryPersistence.h" // #include "io/MemoryPersistence.h" // #include "process/Tiler.h" // #include "tiling/OctreeAlgorithms.h" // #include <debug/ProgressReporter.h> // #include <boost/algorithm/string/predicate.hpp> // #include <boost/format.hpp> // #include <boost/functional/hash.hpp> // #include <boost/scope_exit.hpp> // #include <random> // #include <unordered_set> // namespace std { // template<> // struct hash<Vector3<double>> // { // typedef Vector3<double> argument_type; // typedef std::size_t result_type; // result_type operator()(Vector3<double> const& s) const noexcept // { // size_t seed = std::hash<double>{}(s.x); // boost::hash_combine(seed, std::hash<double>{}(s.y)); // boost::hash_combine(seed, std::hash<double>{}(s.z)); // return seed; // } // }; // } // namespace std // static PointBuffer // create_random_dataset(size_t num_points) // { // std::default_random_engine rnd{ static_cast<uint32_t>(time(nullptr)) }; // std::uniform_real_distribution<float> dist; // // Create num_points random points in [0;1]³ // std::vector<Vector3<double>> positions; // positions.reserve(num_points); // std::generate_n(std::back_inserter(positions), num_points, [&]() -> // Vector3<double> { // return { dist(rnd), dist(rnd), dist(rnd) }; // }); // PointBuffer point_buffer{ num_points, std::move(positions) }; // return point_buffer; // } // // static bool // // points_obey_minimum_distance(const PointBuffer& points, const AABB& // bounds, // // float min_distance) // // { // // SparseGrid grid{ bounds, min_distance }; // // for (auto& pos : points.positions()) { // // if (!grid.add(pos)) // // return false; // // } // // return true; // // } // static bool // points_are_contained_in_bounds(const PointBuffer& points, // const AABB& bounds, // Vector3<double>* fail_point = nullptr) // { // for (auto& pos : points.positions()) { // if (!bounds.isInside(pos)) { // if (fail_point) { // *fail_point = pos; // } // return false; // } // } // return true; // } // TEST_CASE("Tiler works", "[Tiler]") // { // constexpr size_t NumPoints = 1'000'000; // constexpr size_t MaxPointsPerNode = 20'000; // const auto dataset = create_random_dataset(NumPoints); // AABB bounds{ { 0, 0, 0 }, { 1, 1, 1 } }; // auto spacing_at_root = 0.1f; // const auto sampling_strategy = // make_sampling_strategy<RandomSortedGridSampling>(MaxPointsPerNode); // PointsPersistence persistence{ MemoryPersistence{} }; // TilerMetaParameters tiler_meta_parameters; // tiler_meta_parameters.spacing_at_root = spacing_at_root; // tiler_meta_parameters.max_depth = 40; // tiler_meta_parameters.max_points_per_node = MaxPointsPerNode; // tiler_meta_parameters.internal_cache_size = 100'000; // Use small internal // cache size to guarantee // // out-of-core // processing // Tiler writer{ bounds, tiler_meta_parameters, sampling_strategy, nullptr, // persistence, "." }; // writer.cache(dataset); // writer.index(); // writer.close(); // // Two properties have to hold: // // 1) The converter processes and stores ALL points (except when the tree // is // // too shallow due to max_depth) 2) All points of each node must be // contained // // within the bounds of their respective node // // There is also the spacing property (min distance), however this depends // on // // the sampling strategy used. The naive version of my algorithm uses the // // 'random sorted grid' approach, which can result in arbitrarily close // // points. Once other sampling strategies are implemented, there will be // tests // // for their correctness! // // For fast matching of processed points with existing points we use // // unordered_set // std::unordered_set<Vector3<double>> expected_points; // expected_points.reserve(NumPoints); // for (auto& pos : dataset.positions()) { // expected_points.insert(pos); // } // const auto processed_points = // persistence.get<MemoryPersistence>().get_points(); for (auto& kv : // processed_points) { // const auto& node_name = kv.first; // const auto& points = kv.second; // const auto node_key = from_string<21>(node_name); // const auto node_level = node_name.size() - 1; // Node level, root = -1 // const auto node_bounds = get_bounds_from_morton_index(node_key, bounds, // node_level); // // const auto min_distance_at_node = spacing_at_root / std::pow(2, // // node_level + 1); REQUIRE(points_obey_minimum_distance(points, // // node_bounds, min_distance_at_node)); // REQUIRE(points_are_contained_in_bounds(points, node_bounds)); // for (auto& pos : points.positions()) { // const auto point_iter = expected_points.find(pos); // const auto point_exists_in_dataset = (expected_points.find(pos) != // expected_points.end()); REQUIRE(point_exists_in_dataset); // expected_points.erase(point_iter); // Make sure we don't allow // duplicate points! // } // } // const auto num_processed_points = (dataset.count() - // expected_points.size()); REQUIRE(num_processed_points == NumPoints); // } // TEST_CASE("Tiler with deep tree works", "[Tiler]") // { // constexpr size_t NumPoints = 1'000'000; // constexpr size_t MaxPointsPerNode = 20'000; // const auto dataset = create_random_dataset(NumPoints); // // Very large bounds will force the octree to become deeper than the 21 // levels // // that MortonIndex64 can support. This should trigger the re-indexing // // mechanism, which is what we want to test with this test case! What we // don't // // want is dropped points, everything should still be indexed correctly! // AABB bounds{ { 0, 0, 0 }, { 1 << 20, 1 << 20, 1 << 20 } }; // auto spacing_at_root = (1 << 20) / 10.f; // const auto sampling_strategy = // make_sampling_strategy<RandomSortedGridSampling>(MaxPointsPerNode); // PointsPersistence persistence{ MemoryPersistence{} }; // TilerMetaParameters tiler_meta_parameters; // tiler_meta_parameters.spacing_at_root = spacing_at_root; // tiler_meta_parameters.max_depth = 40; // tiler_meta_parameters.max_points_per_node = MaxPointsPerNode; // tiler_meta_parameters.internal_cache_size = 100'000; // Use small internal // cache size to guarantee // // out-of-core // processing // Tiler writer{ bounds, tiler_meta_parameters, sampling_strategy, nullptr, // persistence, "." }; // writer.cache(dataset); // writer.index(); // writer.close(); // // Two properties have to hold: // // 1) The converter processes and stores ALL points (except when the tree // is // // too shallow due to max_depth) 2) All points of each node must be // contained // // within the bounds of their respective node // // There is also the spacing property (min distance), however this depends // on // // the sampling strategy used. The naive version of my algorithm uses the // // 'random sorted grid' approach, which can result in arbitrarily close // // points. Once other sampling strategies are implemented, there will be // tests // // for their correctness! // // For fast matching of processed points with existing points we use // // unordered_set // std::unordered_set<Vector3<double>> expected_points; // expected_points.reserve(NumPoints); // for (auto& pos : dataset.positions()) { // expected_points.insert(pos); // } // const auto processed_points = // persistence.get<MemoryPersistence>().get_points(); for (auto& kv : // processed_points) { // const auto& node_name = kv.first; // const auto& points = kv.second; // const auto node_key = from_string<21>(node_name); // const auto node_level = node_name.size() - 1; // Node level, root = -1 // const auto node_bounds = get_bounds_from_morton_index(node_key, bounds, // node_level); // // const auto min_distance_at_node = spacing_at_root / std::pow(2, // // node_level + 1); REQUIRE(points_obey_minimum_distance(points, // // node_bounds, min_distance_at_node)); // REQUIRE(points_are_contained_in_bounds(points, node_bounds)); // for (auto& pos : points.positions()) { // const auto point_iter = expected_points.find(pos); // const auto point_exists_in_dataset = (expected_points.find(pos) != // expected_points.end()); REQUIRE(point_exists_in_dataset); // expected_points.erase(point_iter); // Make sure we don't allow // duplicate points! // } // } // const auto num_processed_points = (dataset.count() - // expected_points.size()); REQUIRE(num_processed_points == NumPoints); // } // TEST_CASE("Tiler with GridCenter sampling", "[Tiler]") // { // constexpr size_t NumPoints = 1'000'000; // constexpr size_t MaxPointsPerNode = 20'000; // const auto dataset = create_random_dataset(NumPoints); // AABB bounds{ { 0, 0, 0 }, { 1, 1, 1 } }; // auto spacing_at_root = 0.1f; // const auto sampling_strategy = // make_sampling_strategy<GridCenterSampling>(MaxPointsPerNode); // PointsPersistence persistence{ MemoryPersistence{} }; // TilerMetaParameters tiler_meta_parameters; // tiler_meta_parameters.spacing_at_root = spacing_at_root; // tiler_meta_parameters.max_depth = 40; // tiler_meta_parameters.max_points_per_node = MaxPointsPerNode; // tiler_meta_parameters.internal_cache_size = 100'000; // Use small internal // cache size to guarantee // // out-of-core // processing // Tiler writer{ bounds, tiler_meta_parameters, sampling_strategy, nullptr, // persistence, "." }; // writer.cache(dataset); // writer.index(); // writer.close(); // // Two properties have to hold: // // 1) The converter processes and stores ALL points (except when the tree // is // // too shallow due to max_depth) 2) All points of each node must be // contained // // within the bounds of their respective node // // For fast matching of processed points with existing points we use // // unordered_set // std::unordered_set<Vector3<double>> expected_points; // expected_points.reserve(NumPoints); // for (auto& pos : dataset.positions()) { // expected_points.insert(pos); // } // const auto processed_points = // persistence.get<MemoryPersistence>().get_points(); for (auto& kv : // processed_points) { // const auto& node_name = kv.first; // const auto& points = kv.second; // const auto node_key = from_string<21>(node_name); // const auto node_level = node_name.size() - 1; // Node level, root = -1 // const auto node_bounds = get_bounds_from_morton_index(node_key, bounds, // node_level); // // const auto min_distance_at_node = spacing_at_root / std::pow(2, // // node_level + 1); REQUIRE(points_obey_minimum_distance(points, // // node_bounds, min_distance_at_node)); // REQUIRE(points_are_contained_in_bounds(points, node_bounds)); // for (auto& pos : points.positions()) { // const auto point_iter = expected_points.find(pos); // const auto point_exists_in_dataset = (expected_points.find(pos) != // expected_points.end()); REQUIRE(point_exists_in_dataset); // expected_points.erase(point_iter); // Make sure we don't allow // duplicate points! // } // } // const auto num_processed_points = (dataset.count() - // expected_points.size()); REQUIRE(num_processed_points == NumPoints); // } // TEST_CASE("Tiler with PossionDisk sampling", "[Tiler]") // { // constexpr size_t NumPoints = 1'000'000; // constexpr size_t MaxPointsPerNode = 20'000; // const auto dataset = create_random_dataset(NumPoints); // AABB bounds{ { 0, 0, 0 }, { 1, 1, 1 } }; // auto spacing_at_root = 0.05f; // const auto sampling_strategy = // make_sampling_strategy<PoissonDiskSampling>(MaxPointsPerNode); // PointsPersistence persistence{ MemoryPersistence{} }; // TilerMetaParameters tiler_meta_parameters; // tiler_meta_parameters.spacing_at_root = spacing_at_root; // tiler_meta_parameters.max_depth = 40; // tiler_meta_parameters.max_points_per_node = MaxPointsPerNode; // tiler_meta_parameters.internal_cache_size = 100'000; // Use small internal // cache size to guarantee // // out-of-core // processing // Tiler writer{ bounds, tiler_meta_parameters, sampling_strategy, nullptr, // persistence, "." }; // writer.cache(dataset); // writer.index(); // writer.close(); // // Two properties have to hold: // // 1) The converter processes and stores ALL points (except when the tree // is // // too shallow due to max_depth) 2) All points of each node must be // contained // // within the bounds of their respective node // // For fast matching of processed points with existing points we use // // unordered_set // std::unordered_set<Vector3<double>> expected_points; // expected_points.reserve(NumPoints); // for (auto& pos : dataset.positions()) { // expected_points.insert(pos); // } // const auto points_obey_minimum_distance = // [](const auto& points, const auto& bounds, double min_distance) -> bool { // SparseGrid grid{ bounds, static_cast<float>(min_distance) }; // for (auto& point : points) { // if (!grid.add(point)) // return false; // } // return true; // }; // const auto is_leaf_node = [](const std::string& node_name, const auto& // all_nodes) { // for (auto& kv : all_nodes) { // const auto& other_node_name = kv.first; // if (other_node_name.size() != (node_name.size() + 1)) // continue; // if (boost::starts_with(other_node_name, node_name)) // return false; // } // return true; // }; // const auto processed_points = // persistence.get<MemoryPersistence>().get_points(); for (auto& kv : // processed_points) { // const auto& node_name = kv.first; // const auto& points = kv.second; // const auto node_key = from_string<21>(node_name); // const auto node_level = static_cast<int32_t>(node_name.size()) - 2; // // Node level, root = -1 const auto node_bounds = // get_bounds_from_morton_index(node_key, bounds, node_level + 1); const // auto min_distance_at_node = spacing_at_root / std::pow(2, node_level + // 1); // const auto is_leaf = is_leaf_node(node_name, processed_points); // if (!is_leaf) { // REQUIRE(points_obey_minimum_distance(points.positions(), node_bounds, // min_distance_at_node)); // } // Vector3<double> fail_point; // const auto points_all_contained = // points_are_contained_in_bounds(points, node_bounds, &fail_point); // if (!points_all_contained) { // UNSCOPED_INFO("Position " << fail_point.x << " " << fail_point.y << " " // << fail_point.z // << " not contained in bounds!"); // } // REQUIRE(points_all_contained); // for (auto& pos : points.positions()) { // const auto point_iter = expected_points.find(pos); // const auto point_exists_in_dataset = (expected_points.find(pos) != // expected_points.end()); REQUIRE(point_exists_in_dataset); // expected_points.erase(point_iter); // Make sure we don't allow // duplicate points! // } // } // const auto num_processed_points = (dataset.count() - // expected_points.size()); REQUIRE(num_processed_points == NumPoints); // } // TEST_CASE("Tiler with BinaryPersistence writer", "[Tiler]") // { // constexpr size_t NumPoints = 1'000'000; // constexpr size_t MaxPointsPerNode = 20'000; // const auto dataset = create_random_dataset(NumPoints); // AABB bounds{ { 0, 0, 0 }, { 1, 1, 1 } }; // auto spacing_at_root = 0.1f; // const auto sampling_strategy = // make_sampling_strategy<RandomSortedGridSampling>(MaxPointsPerNode); // // MemoryPersistence persistence; // PointAttributes attributes; // attributes.insert(PointAttribute::Position); // const auto tmp_directory = // (boost::format("./tmp_%1%") % // (std::chrono::high_resolution_clock::now().time_since_epoch().count())) // .str(); // if (!fs::exists(tmp_directory)) { // if (!fs::create_directories(tmp_directory)) { // FAIL("Could not create temporary output directory"); // } // } // BOOST_SCOPE_EXIT(&tmp_directory) // { // std::error_code ec; // fs::remove_all(tmp_directory, ec); // if (ec) { // UNSCOPED_INFO("Could not remove temporary output directory"); // } // } // BOOST_SCOPE_EXIT_END // PointsPersistence persistence{ BinaryPersistence{ tmp_directory, attributes // } }; // TilerMetaParameters tiler_meta_parameters; // tiler_meta_parameters.spacing_at_root = spacing_at_root; // tiler_meta_parameters.max_depth = 40; // tiler_meta_parameters.max_points_per_node = MaxPointsPerNode; // tiler_meta_parameters.internal_cache_size = 100'000; // Use small internal // cache size to guarantee // // out-of-core // processing // Tiler writer{ bounds, tiler_meta_parameters, sampling_strategy, nullptr, // persistence, "." }; // writer.cache(dataset); // writer.index(); // writer.close(); // }
37.66457
80
0.647223
[ "vector" ]
3cef6b51252e7debf7241899485b912d2b47973a
38,295
inl
C++
OgreMain/include/Math/Array/NEON/Single/OgreArrayMatrixAf4x3.inl
Stazer/ogre-next
4d3aa2aedf4575ac8a9e32a4e2af859562752d51
[ "MIT" ]
11
2017-01-17T15:02:25.000Z
2020-11-27T16:54:42.000Z
OgreMain/include/Math/Array/NEON/Single/OgreArrayMatrixAf4x3.inl
Stazer/ogre-next
4d3aa2aedf4575ac8a9e32a4e2af859562752d51
[ "MIT" ]
9
2016-10-23T20:15:38.000Z
2018-02-06T11:23:17.000Z
OgreMain/include/Math/Array/NEON/Single/OgreArrayMatrixAf4x3.inl
Stazer/ogre-next
4d3aa2aedf4575ac8a9e32a4e2af859562752d51
[ "MIT" ]
11
2021-09-08T17:28:54.000Z
2022-03-02T04:18:18.000Z
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd 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. ----------------------------------------------------------------------------- */ namespace Ogre { /// Concatenates two 4x3 array matrices. /// @remarks /// 99.99% of the cases the matrix isn't concatenated with itself, therefore it's /// safe to assume &lhs != &rhs. RESTRICT_ALIAS modifier is used (a non-standard /// C++ extension) is used when available to dramatically improve performance, /// particularly of the update operations ( a *= b ) /// This function will assert if OGRE_RESTRICT_ALIASING is enabled and any of the /// given pointers point to the same location FORCEINLINE void concatArrayMatAf4x3( ArrayReal * RESTRICT_ALIAS outChunkBase, const ArrayReal * RESTRICT_ALIAS lhsChunkBase, const ArrayReal * RESTRICT_ALIAS rhsChunkBase ) { #if OGRE_RESTRICT_ALIASING != 0 assert( outChunkBase != lhsChunkBase && outChunkBase != rhsChunkBase && lhsChunkBase != rhsChunkBase && "Re-strict aliasing rule broken. Compile without OGRE_RESTRICT_ALIASING" ); #endif outChunkBase[0] = _mm_madd_ps( lhsChunkBase[0], rhsChunkBase[0], _mm_madd_ps( lhsChunkBase[1], rhsChunkBase[4], vmulq_f32( lhsChunkBase[2], rhsChunkBase[8] ) ) ); outChunkBase[1] = _mm_madd_ps( lhsChunkBase[0], rhsChunkBase[1], _mm_madd_ps( lhsChunkBase[1], rhsChunkBase[5], vmulq_f32( lhsChunkBase[2], rhsChunkBase[9] ) ) ); outChunkBase[2] = _mm_madd_ps( lhsChunkBase[0], rhsChunkBase[2], _mm_madd_ps( lhsChunkBase[1], rhsChunkBase[6], vmulq_f32( lhsChunkBase[2], rhsChunkBase[10] ) ) ); outChunkBase[3] = _mm_madd_ps( lhsChunkBase[0], rhsChunkBase[3], _mm_madd_ps( lhsChunkBase[1], rhsChunkBase[7], _mm_madd_ps( lhsChunkBase[2], rhsChunkBase[11], lhsChunkBase[3] ) ) ); /* Next row (1) */ outChunkBase[4] = _mm_madd_ps( lhsChunkBase[4], rhsChunkBase[0], _mm_madd_ps( lhsChunkBase[5], rhsChunkBase[4], vmulq_f32( lhsChunkBase[6], rhsChunkBase[8] ) ) ); outChunkBase[5] = _mm_madd_ps( lhsChunkBase[4], rhsChunkBase[1], _mm_madd_ps( lhsChunkBase[5], rhsChunkBase[5], vmulq_f32( lhsChunkBase[6], rhsChunkBase[9] ) ) ); outChunkBase[6] = _mm_madd_ps( lhsChunkBase[4], rhsChunkBase[2], _mm_madd_ps( lhsChunkBase[5], rhsChunkBase[6], vmulq_f32( lhsChunkBase[6], rhsChunkBase[10] ) ) ); outChunkBase[7] = _mm_madd_ps( lhsChunkBase[4], rhsChunkBase[3], _mm_madd_ps( lhsChunkBase[5], rhsChunkBase[7], _mm_madd_ps( lhsChunkBase[6], rhsChunkBase[11], lhsChunkBase[7] ) ) ); /* Next row (2) */ outChunkBase[8] = _mm_madd_ps( lhsChunkBase[8], rhsChunkBase[0], _mm_madd_ps( lhsChunkBase[9], rhsChunkBase[4], vmulq_f32( lhsChunkBase[10],rhsChunkBase[8] ) ) ); outChunkBase[9] = _mm_madd_ps( lhsChunkBase[8], rhsChunkBase[1], _mm_madd_ps( lhsChunkBase[9], rhsChunkBase[5], vmulq_f32( lhsChunkBase[10],rhsChunkBase[9] ) ) ); outChunkBase[10] = _mm_madd_ps( lhsChunkBase[8], rhsChunkBase[2], _mm_madd_ps( lhsChunkBase[9], rhsChunkBase[6], vmulq_f32( lhsChunkBase[10],rhsChunkBase[10] ) ) ); outChunkBase[11] = _mm_madd_ps( lhsChunkBase[8], rhsChunkBase[3], _mm_madd_ps( lhsChunkBase[9], rhsChunkBase[7], _mm_madd_ps( lhsChunkBase[10],rhsChunkBase[11], lhsChunkBase[11] ) ) ); } /// Update version FORCEINLINE void concatArrayMatAf4x3( ArrayReal * RESTRICT_ALIAS lhsChunkBase, const ArrayReal * RESTRICT_ALIAS rhsChunkBase ) { #if OGRE_RESTRICT_ALIASING != 0 assert( lhsChunkBase != rhsChunkBase && "Re-strict aliasing rule broken. Compile without OGRE_RESTRICT_ALIASING" ); #endif ArrayReal lhs0 = lhsChunkBase[0]; lhsChunkBase[0] = _mm_madd_ps( lhsChunkBase[0], rhsChunkBase[0], _mm_madd_ps( lhsChunkBase[1], rhsChunkBase[4], vmulq_f32( lhsChunkBase[2], rhsChunkBase[8] ) ) ); ArrayReal lhs1 = lhsChunkBase[1]; lhsChunkBase[1] = _mm_madd_ps( lhs0, rhsChunkBase[1], _mm_madd_ps( lhsChunkBase[1], rhsChunkBase[5], vmulq_f32( lhsChunkBase[2], rhsChunkBase[9] ) ) ); ArrayReal lhs2 = lhsChunkBase[2]; lhsChunkBase[2] = _mm_madd_ps( lhs0, rhsChunkBase[2], _mm_madd_ps( lhs1, rhsChunkBase[6], vmulq_f32( lhsChunkBase[2], rhsChunkBase[10] ) ) ); lhsChunkBase[3] = _mm_madd_ps( lhs0, rhsChunkBase[3], _mm_madd_ps( lhs1, rhsChunkBase[7], _mm_madd_ps( lhs2, rhsChunkBase[11], lhsChunkBase[3] ) ) ); /* Next row (1) */ lhs0 = lhsChunkBase[4]; lhsChunkBase[4] = _mm_madd_ps( lhsChunkBase[4], rhsChunkBase[0], _mm_madd_ps( lhsChunkBase[5], rhsChunkBase[4], vmulq_f32( lhsChunkBase[6], rhsChunkBase[8] ) ) ); lhs1 = lhsChunkBase[5]; lhsChunkBase[5] = _mm_madd_ps( lhs0, rhsChunkBase[1], _mm_madd_ps( lhsChunkBase[5], rhsChunkBase[5], vmulq_f32( lhsChunkBase[6], rhsChunkBase[9] ) ) ); lhs2 = lhsChunkBase[6]; lhsChunkBase[6] = _mm_madd_ps( lhs0, rhsChunkBase[2], _mm_madd_ps( lhs1, rhsChunkBase[6], vmulq_f32( lhsChunkBase[6], rhsChunkBase[10] ) ) ); lhsChunkBase[7] = _mm_madd_ps( lhs0, rhsChunkBase[3], _mm_madd_ps( lhs1, rhsChunkBase[7], _mm_madd_ps( lhs2, rhsChunkBase[11], lhsChunkBase[7] ) ) ); /* Next row (2) */ lhs0 = lhsChunkBase[8]; lhsChunkBase[8] = _mm_madd_ps( lhsChunkBase[8], rhsChunkBase[0], _mm_madd_ps( lhsChunkBase[9], rhsChunkBase[4], vmulq_f32( lhsChunkBase[10],rhsChunkBase[8] ) ) ); lhs1 = lhsChunkBase[9]; lhsChunkBase[9] = _mm_madd_ps( lhs0, rhsChunkBase[1], _mm_madd_ps( lhsChunkBase[9], rhsChunkBase[5], vmulq_f32( lhsChunkBase[10],rhsChunkBase[9] ) ) ); lhs2 = lhsChunkBase[10]; lhsChunkBase[10] = _mm_madd_ps( lhs0, rhsChunkBase[2], _mm_madd_ps( lhs1, rhsChunkBase[6], vmulq_f32( lhsChunkBase[10],rhsChunkBase[10] ) ) ); lhsChunkBase[11] = _mm_madd_ps( lhs0, rhsChunkBase[3], _mm_madd_ps( lhs1, rhsChunkBase[7], _mm_madd_ps( lhs2,rhsChunkBase[11], lhsChunkBase[11] ) ) ); } FORCEINLINE ArrayMatrixAf4x3 operator * ( const ArrayMatrixAf4x3 &lhs, const ArrayMatrixAf4x3 &rhs ) { ArrayMatrixAf4x3 retVal; concatArrayMatAf4x3( retVal.mChunkBase, lhs.mChunkBase, rhs.mChunkBase ); return retVal; } //----------------------------------------------------------------------------------- inline ArrayVector3 ArrayMatrixAf4x3::operator * ( const ArrayVector3 &rhs ) const { return ArrayVector3( //X // (m00 * v.x + m01 * v.y) + (m02 * v.z + m03) vaddq_f32( _mm_madd_ps( mChunkBase[0], rhs.mChunkBase[0], vmulq_f32( mChunkBase[1], rhs.mChunkBase[1] ) ), _mm_madd_ps( mChunkBase[2], rhs.mChunkBase[2], mChunkBase[3] ) ), //Y // (m10 * v.x + m11 * v.y) + (m12 * v.z + m13) vaddq_f32( _mm_madd_ps( mChunkBase[4], rhs.mChunkBase[0], vmulq_f32( mChunkBase[5], rhs.mChunkBase[1] ) ), _mm_madd_ps( mChunkBase[6], rhs.mChunkBase[2], mChunkBase[7] ) ), //Z // (m20 * v.x + m21 * v.y) + (m22 * v.z + m23) vaddq_f32( _mm_madd_ps( mChunkBase[8], rhs.mChunkBase[0], vmulq_f32( mChunkBase[9], rhs.mChunkBase[1] ) ), _mm_madd_ps( mChunkBase[10], rhs.mChunkBase[2], mChunkBase[11] ) ) ); } //----------------------------------------------------------------------------------- FORCEINLINE void ArrayMatrixAf4x3::operator *= ( const ArrayMatrixAf4x3 &rhs ) { concatArrayMatAf4x3( mChunkBase, rhs.mChunkBase ); } //----------------------------------------------------------------------------------- inline void ArrayMatrixAf4x3::fromQuaternion( const ArrayQuaternion &q ) { ArrayReal * RESTRICT_ALIAS chunkBase = mChunkBase; const ArrayReal * RESTRICT_ALIAS qChunkBase = q.mChunkBase; ArrayReal fTx = vaddq_f32( qChunkBase[1], qChunkBase[1] ); // 2 * x ArrayReal fTy = vaddq_f32( qChunkBase[2], qChunkBase[2] ); // 2 * y ArrayReal fTz = vaddq_f32( qChunkBase[3], qChunkBase[3] ); // 2 * z ArrayReal fTwx = vmulq_f32( fTx, qChunkBase[0] ); // fTx*w; ArrayReal fTwy = vmulq_f32( fTy, qChunkBase[0] ); // fTy*w; ArrayReal fTwz = vmulq_f32( fTz, qChunkBase[0] ); // fTz*w; ArrayReal fTxx = vmulq_f32( fTx, qChunkBase[1] ); // fTx*x; ArrayReal fTxy = vmulq_f32( fTy, qChunkBase[1] ); // fTy*x; ArrayReal fTxz = vmulq_f32( fTz, qChunkBase[1] ); // fTz*x; ArrayReal fTyy = vmulq_f32( fTy, qChunkBase[2] ); // fTy*y; ArrayReal fTyz = vmulq_f32( fTz, qChunkBase[2] ); // fTz*y; ArrayReal fTzz = vmulq_f32( fTz, qChunkBase[3] ); // fTz*z; chunkBase[0] = vsubq_f32( MathlibNEON::ONE, vaddq_f32( fTyy, fTzz ) ); chunkBase[1] = vsubq_f32( fTxy, fTwz ); chunkBase[2] = vaddq_f32( fTxz, fTwy ); chunkBase[4] = vaddq_f32( fTxy, fTwz ); chunkBase[5] = vsubq_f32( MathlibNEON::ONE, vaddq_f32( fTxx, fTzz ) ); chunkBase[6] = vsubq_f32( fTyz, fTwx ); chunkBase[8] = vsubq_f32( fTxz, fTwy ); chunkBase[9] = vaddq_f32( fTyz, fTwx ); chunkBase[10]= vsubq_f32( MathlibNEON::ONE, vaddq_f32( fTxx, fTyy ) ); } //----------------------------------------------------------------------------------- inline void ArrayMatrixAf4x3::makeTransform( const ArrayVector3 &position, const ArrayVector3 &scale, const ArrayQuaternion &orientation ) { ArrayReal * RESTRICT_ALIAS chunkBase = mChunkBase; const ArrayReal * RESTRICT_ALIAS posChunkBase = position.mChunkBase; const ArrayReal * RESTRICT_ALIAS scaleChunkBase = scale.mChunkBase; this->fromQuaternion( orientation ); chunkBase[0] = vmulq_f32( chunkBase[0], scaleChunkBase[0] ); //m00 * scale.x chunkBase[1] = vmulq_f32( chunkBase[1], scaleChunkBase[1] ); //m01 * scale.y chunkBase[2] = vmulq_f32( chunkBase[2], scaleChunkBase[2] ); //m02 * scale.z chunkBase[3] = posChunkBase[0]; //m03 * pos.x chunkBase[4] = vmulq_f32( chunkBase[4], scaleChunkBase[0] ); //m10 * scale.x chunkBase[5] = vmulq_f32( chunkBase[5], scaleChunkBase[1] ); //m11 * scale.y chunkBase[6] = vmulq_f32( chunkBase[6], scaleChunkBase[2] ); //m12 * scale.z chunkBase[7] = posChunkBase[1]; //m13 * pos.y chunkBase[8] = vmulq_f32( chunkBase[8], scaleChunkBase[0] ); //m20 * scale.x chunkBase[9] = vmulq_f32( chunkBase[9], scaleChunkBase[1] ); //m21 * scale.y chunkBase[10]= vmulq_f32( chunkBase[10],scaleChunkBase[2] ); //m22 * scale.z chunkBase[11]= posChunkBase[2]; //m23 * pos.z } //----------------------------------------------------------------------------------- inline void ArrayMatrixAf4x3::decomposition( ArrayVector3 &position, ArrayVector3 &scale, ArrayQuaternion &orientation ) const { const ArrayReal * RESTRICT_ALIAS chunkBase = mChunkBase; // build orthogonal matrix Q ArrayReal m00 = mChunkBase[0], m01 = mChunkBase[1], m02 = mChunkBase[2]; ArrayReal m10 = mChunkBase[4], m11 = mChunkBase[5], m12 = mChunkBase[6]; ArrayReal m20 = mChunkBase[8], m21 = mChunkBase[9], m22 = mChunkBase[10]; //fInvLength = 1.0f / sqrt( m00 * m00 + m10 * m10 + m20 * m20 ); ArrayReal fInvLength = MathlibNEON::InvSqrt4( _mm_madd_ps( m00, m00, _mm_madd_ps( m10, m10, vmulq_f32( m20, m20 ) ) ) ); ArrayReal q00, q01, q02, q10, q11, q12, q20, q21, q22; //3x3 matrix q00 = vmulq_f32( m00, fInvLength ); //q00 = m00 * fInvLength q10 = vmulq_f32( m10, fInvLength ); //q10 = m10 * fInvLength q20 = vmulq_f32( m20, fInvLength ); //q20 = m20 * fInvLength //fDot = q00*m01 + q10*m11 + q20*m21 ArrayReal fDot = _mm_madd_ps( q00, m01, _mm_madd_ps( q10, m11, vmulq_f32( q20, m21 ) ) ); q01 = vsubq_f32( m01, vmulq_f32( fDot, q00 ) ); //q01 = m01 - fDot * q00; q11 = vsubq_f32( m11, vmulq_f32( fDot, q10 ) ); //q11 = m11 - fDot * q10; q21 = vsubq_f32( m21, vmulq_f32( fDot, q20 ) ); //q21 = m21 - fDot * q20; //fInvLength = 1.0f / sqrt( q01 * q01 + q11 * q11 + q21 * q21 ); fInvLength = MathlibNEON::InvSqrt4( _mm_madd_ps( q01, q01, _mm_madd_ps( q11, q11, vmulq_f32( q21, q21 ) ) ) ); q01 = vmulq_f32( q01, fInvLength ); //q01 *= fInvLength; q11 = vmulq_f32( q11, fInvLength ); //q11 *= fInvLength; q21 = vmulq_f32( q21, fInvLength ); //q21 *= fInvLength; //fDot = q00 * m02 + q10 * m12 + q20 * m22; fDot = _mm_madd_ps( q00, m02, _mm_madd_ps( q10, m12, vmulq_f32( q20, m22 ) ) ); q02 = vsubq_f32( m02, vmulq_f32( fDot, q00 ) ); //q02 = m02 - fDot * q00; q12 = vsubq_f32( m12, vmulq_f32( fDot, q10 ) ); //q12 = m12 - fDot * q10; q22 = vsubq_f32( m22, vmulq_f32( fDot, q20 ) ); //q22 = m22 - fDot * q20; //fDot = q01 * m02 + q11 * m12 + q21 * m22; fDot = _mm_madd_ps( q01, m02, _mm_madd_ps( q11, m12, vmulq_f32( q21, m22 ) ) ); q02 = vsubq_f32( q02, vmulq_f32( fDot, q01 ) ); //q02 = q02 - fDot * q01; q12 = vsubq_f32( q12, vmulq_f32( fDot, q11 ) ); //q12 = q12 - fDot * q11; q22 = vsubq_f32( q22, vmulq_f32( fDot, q21 ) ); //q22 = q22 - fDot * q21; //fInvLength = 1.0f / sqrt( q02 * q02 + q12 * q12 + q22 * q22 ); fInvLength = MathlibNEON::InvSqrt4( _mm_madd_ps( q02, q02, _mm_madd_ps( q12, q12, vmulq_f32( q22, q22 ) ) ) ); q02 = vmulq_f32( q02, fInvLength ); //q02 *= fInvLength; q12 = vmulq_f32( q12, fInvLength ); //q12 *= fInvLength; q22 = vmulq_f32( q22, fInvLength ); //q22 *= fInvLength; // guarantee that orthogonal matrix has determinant 1 (no reflections) //fDet = q00*q11*q22 + q01*q12*q20 + // q02*q10*q21 - q02*q11*q20 - // q01*q10*q22 - q00*q12*q21; //fDet = (q00*q11*q22 + q01*q12*q20 + q02*q10*q21) - // (q02*q11*q20 + q01*q10*q22 + q00*q12*q21); ArrayReal fDet = vaddq_f32( vaddq_f32( vmulq_f32( vmulq_f32( q00, q11 ), q22 ), vmulq_f32( vmulq_f32( q01, q12 ), q20 ) ), vmulq_f32( vmulq_f32( q02, q10 ), q21 ) ); ArrayReal fTmp = vaddq_f32( vaddq_f32( vmulq_f32( vmulq_f32( q02, q11 ), q20 ), vmulq_f32( vmulq_f32( q01, q10 ), q22 ) ), vmulq_f32( vmulq_f32( q00, q12 ), q21 ) ); fDet = vsubq_f32( fDet, fTmp ); //if ( fDet < 0.0 ) //{ // for (size_t iRow = 0; iRow < 3; iRow++) // for (size_t iCol = 0; iCol < 3; iCol++) // kQ[iRow][iCol] = -kQ[iRow][iCol]; //} fDet = vandq_f32( fDet, MathlibNEON::SIGN_MASK ); q00 = veorq_f32( q00, fDet ); q01 = veorq_f32( q01, fDet ); q02 = veorq_f32( q02, fDet ); q10 = veorq_f32( q10, fDet ); q11 = veorq_f32( q11, fDet ); q12 = veorq_f32( q12, fDet ); q20 = veorq_f32( q20, fDet ); q21 = veorq_f32( q21, fDet ); q22 = veorq_f32( q22, fDet ); const ArrayReal matrix[9] = { q00, q01, q02, q10, q11, q12, q20, q21, q22 }; orientation.FromOrthoDet1RotationMatrix( matrix ); //scale.x = q00 * m00 + q10 * m10 + q20 * m20; //scale.y = q01 * m01 + q11 * m11 + q21 * m21; //scale.z = q02 * m02 + q12 * m12 + q22 * m22; ArrayReal * RESTRICT_ALIAS scaleChunkBase = scale.mChunkBase; scaleChunkBase[0] = _mm_madd_ps( q00, m00, _mm_madd_ps( q10, m10, vmulq_f32( q20, m20 ) ) ); scaleChunkBase[1] = _mm_madd_ps( q01, m01, _mm_madd_ps( q11, m11, vmulq_f32( q21, m21 ) ) ); scaleChunkBase[2] = _mm_madd_ps( q02, m02, _mm_madd_ps( q12, m12, vmulq_f32( q22, m22 ) ) ); ArrayReal * RESTRICT_ALIAS posChunkBase = position.mChunkBase; posChunkBase[0] = chunkBase[3]; posChunkBase[1] = chunkBase[7]; posChunkBase[2] = chunkBase[11]; } //----------------------------------------------------------------------------------- inline void ArrayMatrixAf4x3::setToInverse(void) { ArrayReal m10 = mChunkBase[4], m11 = mChunkBase[5], m12 = mChunkBase[6]; ArrayReal m20 = mChunkBase[8], m21 = mChunkBase[9], m22 = mChunkBase[10]; ArrayReal t00 = _mm_nmsub_ps( m21, m12, vmulq_f32( m22, m11 ) ); //m22 * m11 - m21 * m12; ArrayReal t10 = _mm_nmsub_ps( m22, m10, vmulq_f32( m20, m12 ) ); //m20 * m12 - m22 * m10; ArrayReal t20 = _mm_nmsub_ps( m20, m11, vmulq_f32( m21, m10 ) ); //m21 * m10 - m20 * m11; ArrayReal m00 = mChunkBase[0], m01 = mChunkBase[1], m02 = mChunkBase[2]; //det = m00 * t00 + m01 * t10 + m02 * t20 ArrayReal det = _mm_madd_ps( m00, t00, _mm_madd_ps( m01, t10, vmulq_f32( m02, t20 ) ) ); ArrayReal invDet= vdivq_f32( MathlibNEON::ONE, det ); //High precision division t00 = vmulq_f32( t00, invDet ); t10 = vmulq_f32( t10, invDet ); t20 = vmulq_f32( t20, invDet ); m00 = vmulq_f32( m00, invDet ); m01 = vmulq_f32( m01, invDet ); m02 = vmulq_f32( m02, invDet ); ArrayReal r00 = t00; ArrayReal r01 = _mm_nmsub_ps( m01, m22, vmulq_f32( m02, m21 ) ); //m02 * m21 - m01 * m22; ArrayReal r02 = _mm_nmsub_ps( m02, m11, vmulq_f32( m01, m12 ) ); //m01 * m12 - m02 * m11; ArrayReal r10 = t10; ArrayReal r11 = _mm_nmsub_ps( m02, m20, vmulq_f32( m00, m22 ) ); //m00 * m22 - m02 * m20; ArrayReal r12 = _mm_nmsub_ps( m00, m12, vmulq_f32( m02, m10 ) ); //m02 * m10 - m00 * m12; ArrayReal r20 = t20; ArrayReal r21 = _mm_nmsub_ps( m00, m21, vmulq_f32( m01, m20 ) ); //m01 * m20 - m00 * m21; ArrayReal r22 = _mm_nmsub_ps( m01, m10, vmulq_f32( m00, m11 ) ); //m00 * m11 - m01 * m10; ArrayReal m03 = mChunkBase[3], m13 = mChunkBase[7], m23 = mChunkBase[11]; //r03 = (r00 * m03 + r01 * m13 + r02 * m23) //r13 = (r10 * m03 + r11 * m13 + r12 * m23) //r23 = (r20 * m03 + r21 * m13 + r22 * m23) ArrayReal r03 = _mm_madd_ps( r00, m03, _mm_madd_ps( r01, m13, vmulq_f32( r02, m23 ) ) ); ArrayReal r13 = _mm_madd_ps( r10, m03, _mm_madd_ps( r11, m13, vmulq_f32( r12, m23 ) ) ); ArrayReal r23 = _mm_madd_ps( r20, m03, _mm_madd_ps( r21, m13, vmulq_f32( r22, m23 ) ) ); r03 = vmulq_f32( r03, MathlibNEON::NEG_ONE ); //r03 = -r03 r13 = vmulq_f32( r13, MathlibNEON::NEG_ONE ); //r13 = -r13 r23 = vmulq_f32( r23, MathlibNEON::NEG_ONE ); //r23 = -r23 mChunkBase[0] = r00; mChunkBase[1] = r01; mChunkBase[2] = r02; mChunkBase[3] = r03; mChunkBase[4] = r10; mChunkBase[5] = r11; mChunkBase[6] = r12; mChunkBase[7] = r13; mChunkBase[8] = r20; mChunkBase[9] = r21; mChunkBase[10]= r22; mChunkBase[11]= r23; } //----------------------------------------------------------------------------------- inline void ArrayMatrixAf4x3::setToInverseDegeneratesAsIdentity(void) { ArrayReal m10 = mChunkBase[4], m11 = mChunkBase[5], m12 = mChunkBase[6]; ArrayReal m20 = mChunkBase[8], m21 = mChunkBase[9], m22 = mChunkBase[10]; ArrayReal t00 = _mm_nmsub_ps( m21, m12, vmulq_f32( m22, m11 ) ); //m22 * m11 - m21 * m12; ArrayReal t10 = _mm_nmsub_ps( m22, m10, vmulq_f32( m20, m12 ) ); //m20 * m12 - m22 * m10; ArrayReal t20 = _mm_nmsub_ps( m20, m11, vmulq_f32( m21, m10 ) ); //m21 * m10 - m20 * m11; ArrayReal m00 = mChunkBase[0], m01 = mChunkBase[1], m02 = mChunkBase[2]; //det = m00 * t00 + m01 * t10 + m02 * t20 ArrayReal det = _mm_madd_ps( m00, t00, _mm_madd_ps( m01, t10, vmulq_f32( m02, t20 ) ) ); ArrayReal invDet= vdivq_f32( MathlibNEON::ONE, det ); //High precision division //degenerateMask = Abs( det ) < fEpsilon; ArrayMaskR degenerateMask = vcltq_f32( MathlibNEON::Abs4( det ), MathlibNEON::fEpsilon ); t00 = vmulq_f32( t00, invDet ); t10 = vmulq_f32( t10, invDet ); t20 = vmulq_f32( t20, invDet ); m00 = vmulq_f32( m00, invDet ); m01 = vmulq_f32( m01, invDet ); m02 = vmulq_f32( m02, invDet ); ArrayReal r00 = t00; ArrayReal r01 = _mm_nmsub_ps( m01, m22, vmulq_f32( m02, m21 ) ); //m02 * m21 - m01 * m22; ArrayReal r02 = _mm_nmsub_ps( m02, m11, vmulq_f32( m01, m12 ) ); //m01 * m12 - m02 * m11; ArrayReal r10 = t10; ArrayReal r11 = _mm_nmsub_ps( m02, m20, vmulq_f32( m00, m22 ) ); //m00 * m22 - m02 * m20; ArrayReal r12 = _mm_nmsub_ps( m00, m12, vmulq_f32( m02, m10 ) ); //m02 * m10 - m00 * m12; ArrayReal r20 = t20; ArrayReal r21 = _mm_nmsub_ps( m00, m21, vmulq_f32( m01, m20 ) ); //m01 * m20 - m00 * m21; ArrayReal r22 = _mm_nmsub_ps( m01, m10, vmulq_f32( m00, m11 ) ); //m00 * m11 - m01 * m10; ArrayReal m03 = mChunkBase[3], m13 = mChunkBase[7], m23 = mChunkBase[11]; //r03 = (r00 * m03 + r01 * m13 + r02 * m23) //r13 = (r10 * m03 + r11 * m13 + r12 * m23) //r13 = (r20 * m03 + r21 * m13 + r22 * m23) ArrayReal r03 = _mm_madd_ps( r00, m03, _mm_madd_ps( r01, m13, vmulq_f32( r02, m23 ) ) ); ArrayReal r13 = _mm_madd_ps( r10, m03, _mm_madd_ps( r11, m13, vmulq_f32( r12, m23 ) ) ); ArrayReal r23 = _mm_madd_ps( r20, m03, _mm_madd_ps( r21, m13, vmulq_f32( r22, m23 ) ) ); r03 = vmulq_f32( r03, MathlibNEON::NEG_ONE ); //r03 = -r03 r13 = vmulq_f32( r13, MathlibNEON::NEG_ONE ); //r13 = -r13 r23 = vmulq_f32( r23, MathlibNEON::NEG_ONE ); //r23 = -r23 mChunkBase[0] = MathlibNEON::CmovRobust( MathlibNEON::ONE, r00, degenerateMask ); mChunkBase[1] = MathlibNEON::CmovRobust( vdupq_n_f32( 0.0f ), r01, degenerateMask ); mChunkBase[2] = MathlibNEON::CmovRobust( vdupq_n_f32( 0.0f ), r02, degenerateMask ); mChunkBase[3] = MathlibNEON::CmovRobust( vdupq_n_f32( 0.0f ), r03, degenerateMask ); mChunkBase[4] = MathlibNEON::CmovRobust( vdupq_n_f32( 0.0f ), r10, degenerateMask ); mChunkBase[5] = MathlibNEON::CmovRobust( MathlibNEON::ONE, r11, degenerateMask ); mChunkBase[6] = MathlibNEON::CmovRobust( vdupq_n_f32( 0.0f ), r12, degenerateMask ); mChunkBase[7] = MathlibNEON::CmovRobust( vdupq_n_f32( 0.0f ), r13, degenerateMask ); mChunkBase[8] = MathlibNEON::CmovRobust( vdupq_n_f32( 0.0f ), r20, degenerateMask ); mChunkBase[9] = MathlibNEON::CmovRobust( vdupq_n_f32( 0.0f ), r21, degenerateMask ); mChunkBase[10]= MathlibNEON::CmovRobust( MathlibNEON::ONE, r22, degenerateMask ); mChunkBase[11]= MathlibNEON::CmovRobust( vdupq_n_f32( 0.0f ), r23, degenerateMask ); } //----------------------------------------------------------------------------------- inline void ArrayMatrixAf4x3::retain( ArrayMaskR orientation, ArrayMaskR scale ) { ArrayVector3 row0( mChunkBase[0], mChunkBase[1], mChunkBase[2] ); ArrayVector3 row1( mChunkBase[4], mChunkBase[5], mChunkBase[6] ); ArrayVector3 row2( mChunkBase[8], mChunkBase[9], mChunkBase[10] ); ArrayVector3 vScale( row0.length(), row1.length(), row2.length() ); ArrayVector3 vInvScale( vScale ); vInvScale.inverseLeaveZeroes(); row0 *= vInvScale.mChunkBase[0]; row1 *= vInvScale.mChunkBase[1]; row2 *= vInvScale.mChunkBase[2]; vScale.Cmov4( scale, ArrayVector3::UNIT_SCALE ); row0.Cmov4( orientation, ArrayVector3::UNIT_X ); row1.Cmov4( orientation, ArrayVector3::UNIT_Y ); row2.Cmov4( orientation, ArrayVector3::UNIT_Z ); row0 *= vScale.mChunkBase[0]; row1 *= vScale.mChunkBase[1]; row2 *= vScale.mChunkBase[2]; mChunkBase[0] = row0.mChunkBase[0]; mChunkBase[1] = row0.mChunkBase[1]; mChunkBase[2] = row0.mChunkBase[2]; mChunkBase[4] = row1.mChunkBase[0]; mChunkBase[5] = row1.mChunkBase[1]; mChunkBase[6] = row1.mChunkBase[2]; mChunkBase[8] = row2.mChunkBase[0]; mChunkBase[9] = row2.mChunkBase[1]; mChunkBase[10]= row2.mChunkBase[2]; } //----------------------------------------------------------------------------------- inline void ArrayMatrixAf4x3::streamToAoS( Matrix4 * RESTRICT_ALIAS dst ) const { //Do not use the unpack version, use the shuffle. Shuffle is faster in k10 processors //("The conceptual shuffle" http://developer.amd.com/community/blog/the-conceptual-shuffle/) //and the unpack version uses 64-bit moves, which can cause store forwarding issues when //then loading them with 128-bit movaps #define _MM_TRANSPOSE4_SRC_DST_PS(row0, row1, row2, row3, dst0, dst1, dst2, dst3) { \ float32x4x4_t tmp0, tmp1; \ tmp0.val[0] = row0; \ tmp0.val[1] = row1; \ tmp0.val[2] = row2; \ tmp0.val[3] = row3; \ vst4q_f32((float32_t*)&tmp1, tmp0); \ dst0 = tmp1.val[0]; \ dst1 = tmp1.val[1]; \ dst2 = tmp1.val[2]; \ dst3 = tmp1.val[3]; \ } register ArrayReal m0, m1, m2, m3; _MM_TRANSPOSE4_SRC_DST_PS( this->mChunkBase[0], this->mChunkBase[1], this->mChunkBase[2], this->mChunkBase[3], m0, m1, m2, m3 ); vst1q_f32( dst[0]._m, m0 ); vst1q_f32( dst[1]._m, m1 ); vst1q_f32( dst[2]._m, m2 ); vst1q_f32( dst[3]._m, m3 ); _MM_TRANSPOSE4_SRC_DST_PS( this->mChunkBase[4], this->mChunkBase[5], this->mChunkBase[6], this->mChunkBase[7], m0, m1, m2, m3 ); vst1q_f32( dst[0]._m+4, m0 ); vst1q_f32( dst[1]._m+4, m1 ); vst1q_f32( dst[2]._m+4, m2 ); vst1q_f32( dst[3]._m+4, m3 ); _MM_TRANSPOSE4_SRC_DST_PS( this->mChunkBase[8], this->mChunkBase[9], this->mChunkBase[10], this->mChunkBase[11], m0, m1, m2, m3 ); vst1q_f32( dst[0]._m+8, m0 ); vst1q_f32( dst[1]._m+8, m1 ); vst1q_f32( dst[2]._m+8, m2 ); vst1q_f32( dst[3]._m+8, m3 ); vst1q_f32( dst[0]._m+12, MathlibNEON::LAST_AFFINE_COLUMN ); vst1q_f32( dst[1]._m+12, MathlibNEON::LAST_AFFINE_COLUMN ); vst1q_f32( dst[2]._m+12, MathlibNEON::LAST_AFFINE_COLUMN ); vst1q_f32( dst[3]._m+12, MathlibNEON::LAST_AFFINE_COLUMN ); } //----------------------------------------------------------------------------------- inline void ArrayMatrixAf4x3::storeToAoS( SimpleMatrixAf4x3 * RESTRICT_ALIAS dst ) const { _MM_TRANSPOSE4_SRC_DST_PS( this->mChunkBase[0], this->mChunkBase[1], this->mChunkBase[2], this->mChunkBase[3], dst[0].mChunkBase[0], dst[1].mChunkBase[0], dst[2].mChunkBase[0], dst[3].mChunkBase[0] ); _MM_TRANSPOSE4_SRC_DST_PS( this->mChunkBase[4], this->mChunkBase[5], this->mChunkBase[6], this->mChunkBase[7], dst[0].mChunkBase[1], dst[1].mChunkBase[1], dst[2].mChunkBase[1], dst[3].mChunkBase[1] ); _MM_TRANSPOSE4_SRC_DST_PS( this->mChunkBase[8], this->mChunkBase[9], this->mChunkBase[10], this->mChunkBase[11], dst[0].mChunkBase[2], dst[1].mChunkBase[2], dst[2].mChunkBase[2], dst[3].mChunkBase[2] ); } //----------------------------------------------------------------------------------- inline void ArrayMatrixAf4x3::streamToAoS( SimpleMatrixAf4x3 * RESTRICT_ALIAS _dst ) const { register ArrayReal dst0, dst1, dst2, dst3; Real *dst = reinterpret_cast<Real*>( _dst ); _MM_TRANSPOSE4_SRC_DST_PS( this->mChunkBase[0], this->mChunkBase[1], this->mChunkBase[2], this->mChunkBase[3], dst0, dst1, dst2, dst3 ); vst1q_f32( &dst[0], dst0 ); vst1q_f32( &dst[12], dst1 ); vst1q_f32( &dst[24], dst2 ); vst1q_f32( &dst[36], dst3 ); _MM_TRANSPOSE4_SRC_DST_PS( this->mChunkBase[4], this->mChunkBase[5], this->mChunkBase[6], this->mChunkBase[7], dst0, dst1, dst2, dst3 ); vst1q_f32( &dst[4], dst0 ); vst1q_f32( &dst[16], dst1 ); vst1q_f32( &dst[28], dst2 ); vst1q_f32( &dst[40], dst3 ); _MM_TRANSPOSE4_SRC_DST_PS( this->mChunkBase[8], this->mChunkBase[9], this->mChunkBase[10], this->mChunkBase[11], dst0, dst1, dst2, dst3 ); vst1q_f32( &dst[8], dst0 ); vst1q_f32( &dst[20], dst1 ); vst1q_f32( &dst[32], dst2 ); vst1q_f32( &dst[44], dst3 ); } //----------------------------------------------------------------------------------- inline void ArrayMatrixAf4x3::loadFromAoS( const Matrix4 * RESTRICT_ALIAS src ) { _MM_TRANSPOSE4_SRC_DST_PS( vld1q_f32( src[0]._m ), vld1q_f32( src[1]._m ), vld1q_f32( src[2]._m ), vld1q_f32( src[3]._m ), this->mChunkBase[0], this->mChunkBase[1], this->mChunkBase[2], this->mChunkBase[3] ); _MM_TRANSPOSE4_SRC_DST_PS( vld1q_f32( src[0]._m+4 ), vld1q_f32( src[1]._m+4 ), vld1q_f32( src[2]._m+4 ), vld1q_f32( src[3]._m+4 ), this->mChunkBase[4], this->mChunkBase[5], this->mChunkBase[6], this->mChunkBase[7] ); _MM_TRANSPOSE4_SRC_DST_PS( vld1q_f32( src[0]._m+8 ), vld1q_f32( src[1]._m+8 ), vld1q_f32( src[2]._m+8 ), vld1q_f32( src[3]._m+8 ), this->mChunkBase[8], this->mChunkBase[9], this->mChunkBase[10], this->mChunkBase[11] ); } //----------------------------------------------------------------------------------- inline void ArrayMatrixAf4x3::loadFromAoS( const Matrix4 * RESTRICT_ALIAS * src ) { _MM_TRANSPOSE4_SRC_DST_PS( vld1q_f32( src[0]->_m ), vld1q_f32( src[1]->_m ), vld1q_f32( src[2]->_m ), vld1q_f32( src[3]->_m ), this->mChunkBase[0], this->mChunkBase[1], this->mChunkBase[2], this->mChunkBase[3] ); _MM_TRANSPOSE4_SRC_DST_PS( vld1q_f32( src[0]->_m+4 ), vld1q_f32( src[1]->_m+4 ), vld1q_f32( src[2]->_m+4 ), vld1q_f32( src[3]->_m+4 ), this->mChunkBase[4], this->mChunkBase[5], this->mChunkBase[6], this->mChunkBase[7] ); _MM_TRANSPOSE4_SRC_DST_PS( vld1q_f32( src[0]->_m+8 ), vld1q_f32( src[1]->_m+8 ), vld1q_f32( src[2]->_m+8 ), vld1q_f32( src[3]->_m+8 ), this->mChunkBase[8], this->mChunkBase[9], this->mChunkBase[10], this->mChunkBase[11] ); } //----------------------------------------------------------------------------------- inline void ArrayMatrixAf4x3::loadFromAoS( const SimpleMatrixAf4x3 * RESTRICT_ALIAS src ) { _MM_TRANSPOSE4_SRC_DST_PS( src[0].mChunkBase[0], src[1].mChunkBase[0], src[2].mChunkBase[0], src[3].mChunkBase[0], this->mChunkBase[0], this->mChunkBase[1], this->mChunkBase[2], this->mChunkBase[3] ); _MM_TRANSPOSE4_SRC_DST_PS( src[0].mChunkBase[1], src[1].mChunkBase[1], src[2].mChunkBase[1], src[3].mChunkBase[1], this->mChunkBase[4], this->mChunkBase[5], this->mChunkBase[6], this->mChunkBase[7] ); _MM_TRANSPOSE4_SRC_DST_PS( src[0].mChunkBase[2], src[1].mChunkBase[2], src[2].mChunkBase[2], src[3].mChunkBase[2], this->mChunkBase[8], this->mChunkBase[9], this->mChunkBase[10], this->mChunkBase[11] ); } //----------------------------------------------------------------------------------- inline void ArrayMatrixAf4x3::loadFromAoS( const SimpleMatrixAf4x3 * RESTRICT_ALIAS * src ) { _MM_TRANSPOSE4_SRC_DST_PS( src[0]->mChunkBase[0], src[1]->mChunkBase[0], src[2]->mChunkBase[0], src[3]->mChunkBase[0], this->mChunkBase[0], this->mChunkBase[1], this->mChunkBase[2], this->mChunkBase[3] ); _MM_TRANSPOSE4_SRC_DST_PS( src[0]->mChunkBase[1], src[1]->mChunkBase[1], src[2]->mChunkBase[1], src[3]->mChunkBase[1], this->mChunkBase[4], this->mChunkBase[5], this->mChunkBase[6], this->mChunkBase[7] ); _MM_TRANSPOSE4_SRC_DST_PS( src[0]->mChunkBase[2], src[1]->mChunkBase[2], src[2]->mChunkBase[2], src[3]->mChunkBase[2], this->mChunkBase[8], this->mChunkBase[9], this->mChunkBase[10], this->mChunkBase[11] ); } //----------------------------------------------------------------------------------- #undef _MM_TRANSPOSE4_SRC_DST_PS }
53.785112
105
0.516725
[ "object" ]
3cf410eebfe8e42829267fb6dcf92c85510fc9cb
1,050
cpp
C++
source/Camera/Basic/CaptureHDR/CaptureHDR.cpp
ZachZheng0316/Cpp_Sample_For_Zivid_Camera
f448e5a206bc755813727b319eae43dfe1504e6d
[ "BSD-3-Clause" ]
null
null
null
source/Camera/Basic/CaptureHDR/CaptureHDR.cpp
ZachZheng0316/Cpp_Sample_For_Zivid_Camera
f448e5a206bc755813727b319eae43dfe1504e6d
[ "BSD-3-Clause" ]
null
null
null
source/Camera/Basic/CaptureHDR/CaptureHDR.cpp
ZachZheng0316/Cpp_Sample_For_Zivid_Camera
f448e5a206bc755813727b319eae43dfe1504e6d
[ "BSD-3-Clause" ]
null
null
null
#include <Zivid/Zivid.h> #include <iostream> int main() { try { Zivid::Application zivid; std::cout << "Connecting to camera" << std::endl; auto camera = zivid.connectCamera(); std::cout << "Recording HDR source images" << std::endl; std::vector<Zivid::Frame> frames; for(const size_t iris : { 20U, 25U, 30U }) { std::cout << "Capture frame with iris = " << iris << std::endl; camera << Zivid::Settings::Iris{ iris }; frames.emplace_back(camera.capture()); } std::cout << "Creating HDR frame" << std::endl; auto hdrFrame = Zivid::HDR::combineFrames(begin(frames), end(frames)); std::cout << "Saving the frames" << std::endl; frames[0].save("20.zdf"); frames[1].save("25.zdf"); frames[2].save("30.zdf"); hdrFrame.save("HDR.zdf"); } catch(const std::exception &e) { std::cerr << "Error: " << Zivid::toString(e) << std::endl; return EXIT_FAILURE; } }
27.631579
78
0.535238
[ "vector" ]
3cf418e2ec41f857b5972c4b2acc4db7dfe5dbaa
2,982
cpp
C++
lonestar/experimental/ordered/avi/libElm/libElement/test/testP13DElementBoundaryTraces.cpp
rohankadekodi/compilers_project
2f9455a5d0c516b9f1766afd1cdac1b86c930ec0
[ "BSD-3-Clause" ]
null
null
null
lonestar/experimental/ordered/avi/libElm/libElement/test/testP13DElementBoundaryTraces.cpp
rohankadekodi/compilers_project
2f9455a5d0c516b9f1766afd1cdac1b86c930ec0
[ "BSD-3-Clause" ]
7
2020-02-27T19:24:51.000Z
2020-04-10T21:04:28.000Z
lonestar/experimental/ordered/avi/libElm/libElement/test/testP13DElementBoundaryTraces.cpp
rohankadekodi/compilers_project
2f9455a5d0c516b9f1766afd1cdac1b86c930ec0
[ "BSD-3-Clause" ]
2
2020-02-17T22:00:40.000Z
2020-03-24T10:18:02.000Z
/* * This file belongs to the Galois project, a C++ library for exploiting parallelism. * The code is being released under the terms of the 3-Clause BSD License (a * copy is located in LICENSE.txt at the top-level directory). * * Copyright (C) 2018, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. */ /* Sriramajayam */ // testP13DElementBoundaryTraces.cpp. #include "P13DElement.h" #include <iostream> int main() { double V0[] = {1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1}; VecDouble Vertices(V0, V0 + 12); Tetrahedron::SetGlobalCoordinatesArray(Vertices); Triangle<3>::SetGlobalCoordinatesArray(Vertices); Segment<3>::SetGlobalCoordinatesArray(Vertices); P13DElement<2> Elm(1, 2, 3, 4); P13DElementBoundaryTraces<2> EBT(Elm, true, false, true, true, P13DTrace<2>::ThreeDofs); std::cout << "\n Number of Traces: " << EBT.getNumTraceFaces() << " should be 3. \n"; for (unsigned int a = 0; a < 3; a++) // Change to test different/all traces. { int facenumber = EBT.getTraceFaceIds()[a]; std::cout << " \n FaceNumber :" << facenumber << "\n"; std::cout << "\n Normal to face: "; for (unsigned int q = 0; q < EBT.getNormal(a).size(); q++) std::cout << EBT.getNormal(a)[q] << ", "; std::cout << "\n"; } for (unsigned int a = 0; a < 1; a++) { int facenumber = EBT.getTraceFaceIds()[a]; std::cout << "\nFace Number :" << facenumber << "\n"; const Element& face = EBT[a]; // Integration weights: std::cout << "\n Integration weights: \n"; for (unsigned int q = 0; q < face.getIntegrationWeights(0).size(); q++) std::cout << face.getIntegrationWeights(0)[q] << ", "; // Integration points: std::cout << "\n Integration point coordinates: \n"; for (unsigned int q = 0; q < face.getIntegrationPtCoords(0).size(); q++) std::cout << face.getIntegrationPtCoords(0)[q] << ", "; // Shape functions: std::cout << "\n Shape Functions at quadrature points: \n"; for (unsigned int q = 0; q < face.getShapes(0).size(); q++) std::cout << face.getShapes(0)[q] << ", "; std::cout << "\n"; } }
37.746835
85
0.655936
[ "shape" ]
3cf4abea483a93e51977715f23777475aa7064d7
1,145
cpp
C++
iOS/G3MiOSSDK/Commons/JSON/JSONBaseObject.cpp
restjohn/g3m
608657fd6f0e2898bd963d15136ff085b499e97e
[ "BSD-2-Clause" ]
1
2016-08-23T10:29:44.000Z
2016-08-23T10:29:44.000Z
iOS/G3MiOSSDK/Commons/JSON/JSONBaseObject.cpp
restjohn/g3m
608657fd6f0e2898bd963d15136ff085b499e97e
[ "BSD-2-Clause" ]
null
null
null
iOS/G3MiOSSDK/Commons/JSON/JSONBaseObject.cpp
restjohn/g3m
608657fd6f0e2898bd963d15136ff085b499e97e
[ "BSD-2-Clause" ]
null
null
null
// // JSONBaseObject.cpp // G3MiOSSDK // // Created by Oliver Koehler on 02/10/12. // Copyright (c) 2012 __MyCompanyName__. All rights reserved. // //#include "ILogger.hpp" #include "JSONBaseObject.hpp" const JSONObject* JSONBaseObject::asObject() const { //ILogger::instance()->logError("The requested Object is not of type JSONObject!"); return NULL; } const JSONArray* JSONBaseObject::asArray() const { //ILogger::instance()->logError("The requested Object is not of type JSONArray!"); return NULL; } const JSONNumber* JSONBaseObject::asNumber() const { //ILogger::instance()->logError("The requested Object is not of type JSONNumber!"); return NULL; } const JSONString* JSONBaseObject::asString() const { //ILogger::instance()->logError("The requested Object is not of type JSONString!"); return NULL; } const JSONBoolean* JSONBaseObject::asBoolean() const { //ILogger::instance()->logError("The requested Object is not of type JSONBoolean!"); return NULL; } const JSONNull* JSONBaseObject::asNull() const { //ILogger::instance()->logError("The requested Object is not of type JSONNull!"); return NULL; }
27.926829
86
0.718777
[ "object" ]
3cf4d305b3162664ac8a6382363f9df0b40ff839
7,892
cpp
C++
assemblyShellExtension/assemblyShelllPropertyPage.cpp
casaletto/alby.assemblyShellExtension
e051f9179aae4ece950cd09c590b60f11cc9e844
[ "MIT" ]
null
null
null
assemblyShellExtension/assemblyShelllPropertyPage.cpp
casaletto/alby.assemblyShellExtension
e051f9179aae4ece950cd09c590b60f11cc9e844
[ "MIT" ]
null
null
null
assemblyShellExtension/assemblyShelllPropertyPage.cpp
casaletto/alby.assemblyShellExtension
e051f9179aae4ece950cd09c590b60f11cc9e844
[ "MIT" ]
1
2020-10-02T01:33:45.000Z
2020-10-02T01:33:45.000Z
#include "stdafx.h" #include "..\libAssemblyAttributes\stringHelper.h" #include "..\libAssemblyAttributes\exception.h" #include "..\libAssemblyAttributes\sprintf.h" #include "..\libAssemblyAttributes\process.h" #include "..\libAssemblyAttributes\comEnvironment.h" #include "..\libAssemblyAttributes\globalAlloc.h" #include "..\libAssemblyAttributes\globalLock.h" #include "..\libAssemblyAttributes\stgMedium.h" #include "..\libAssemblyAttributes\helper.h" #include "dllmain.h" #include "assemblyShelllPropertyPage.h" using namespace ATL ; namespace lib = alby::assemblyAttributes::lib; assemblyShelllPropertyPage::assemblyShelllPropertyPage() { //auto msg = lib::sprintf(L"assemblyShelllPropertyPage [constructor]"); //msg.debug(); } HRESULT assemblyShelllPropertyPage::FinalConstruct() { auto msg = lib::sprintf( L"assemblyShelllPropertyPage [final constructor]" ) ; msg.debug() ; msg = lib::sprintf( L"assemblyShelllPropertyPage _WIN32_WINNT=0x", std::setw(4), std::setfill( (WCHAR) '0' ), std::hex, _WIN32_WINNT ) ; msg.debug() ; msg = lib::sprintf( L"assemblyShelllPropertyPage WINVER=0x", std::setw(4), std::setfill( (WCHAR) '0' ), std::hex, WINVER ) ; msg.debug() ; return S_OK ; } void assemblyShelllPropertyPage::FinalRelease() { auto msg = lib::sprintf( L"assemblyShelllPropertyPage [final release]" ) ; msg.debug() ; } STDMETHODIMP assemblyShelllPropertyPage::HelloWorld( BSTR aString, BSTR* returnedBStr) { auto msg = lib::sprintf( L"assemblyShelllPropertyPage [HelloWorld]" ) ; msg.debug() ; lib::sprintf str( aString, L" ", lib::helper::getDateTime() ) ; str.debug() ; ::_bstr_t result( str.ws().c_str() ) ; *returnedBStr = result.Detach() ; return S_OK; } STDMETHODIMP assemblyShelllPropertyPage::Initialize ( PCIDLIST_ABSOLUTE pidlFolder, IDataObject *pDataObject, HKEY hkeyProgID ) { this->_dic.clear() ; const HRESULT HR_ABORT = E_INVALIDARG ; FORMATETC formatetc = { CF_HDROP, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL } ; std::wstring filename ; auto msg = lib::sprintf( L"assemblyShelllPropertyPage [Initialize]" ) ; msg.debug() ; try { lib::stgMedium stgMedium( pDataObject, formatetc ) ; lib::globalLock hdrop( stgMedium.getStgMedium().hGlobal ) ; auto fileCount = ::DragQueryFileW( hdrop.getPointer<HDROP>() , 0xFFFFFFFF, NULL, 0 ) ; if ( fileCount == 0 ) throw lib::exception( L"DragQueryFileW(): no files.", __FILE__, __LINE__ ) ; auto firstFile = lib::globalAlloc( (lib::helper::EXTENTED_MAX_PATH + 2) * sizeof(WCHAR) ) ; auto sz = firstFile.getPointer<LPWSTR>(); // get file name from shell ::DragQueryFileW( hdrop.getPointer<HDROP>(), 0, sz, lib::helper::EXTENTED_MAX_PATH ) ; filename = sz ; //ALBY auto directory = lib::helper::getDirectoryFromPath( filename ) ; // file name suffix must in [ .dll .exe ] auto ok = lib::stringHelper::endsWith( filename, L".dll", false ) || lib::stringHelper::endsWith( filename, L".exe", false ) ; if ( ! ok ) return HR_ABORT ; // get current folder to find exe path auto folder = lib::helper::getCurrentModuleDirectory() ; auto exe64 = lib::sprintf( folder, L"\\", lib::helper::CSHARP_ASSEMBLY_ATTRIBUTES_EXE_64 ) ; auto exe32 = lib::sprintf( folder, L"\\", lib::helper::CSHARP_ASSEMBLY_ATTRIBUTES_EXE_32 ) ; // call the child .net process, 64 bit version lib::process pr64 ; auto rc = pr64.exec( exe64.ws(), L"", filename ) ; auto theStdout = lib::stringHelper::trim( pr64.getStdout() ) ; auto theStderr = lib::stringHelper::trim( pr64.getStderr() ) ; msg = lib::sprintf( L"rc 64 [", rc, L"]" ) ; msg.debug(); // may have failed due to bad bitness auto badImageException = ( rc != 0 ) && lib::stringHelper::contains( theStderr, L"System.BadImageFormatException" ) ; // call the child .net process, 32 bit version if ( badImageException ) { lib::process pr32 ; rc = pr32.exec( exe32.ws(), L"", filename ) ; theStdout = lib::stringHelper::trim( pr32.getStdout() ) ; theStderr = lib::stringHelper::trim( pr32.getStderr() ) ; msg = lib::sprintf( L"rc 32 [", rc, L"]" ) ; msg.debug() ; } if ( ! theStderr.empty() ) throw lib::exception( theStderr, __FILE__, __LINE__); if ( rc != 0 ) return HR_ABORT ; // transform the flat string to a dictionary this->_dic = lib::helper::toMap( theStdout, L'\n', L'|' ) ; // dump it for ( auto k : this->_dic ) lib::sprintf( L"#", k.first, L"# = [", k.second, L"]" ).debug() ; // transform the dic to a formatted string for ui display this->_uiString = lib::helper::mapToString( this->_dic ) ; } catch ( const lib::exception& ex ) { auto err = lib::sprintf( L"EXCEPTION\n", ex.what() ) ; err.debug() ; return HR_ABORT ; } catch( const std::exception& ex ) { auto err = lib::sprintf( L"EXCEPTION\n", ex.what() ) ; err.debug() ; return HR_ABORT ; } catch( ... ) { auto err = lib::sprintf( L"EXCEPTION\n..." ) ; err.debug() ; return HR_ABORT ; } return S_OK ; } STDMETHODIMP assemblyShelllPropertyPage::AddPages ( LPFNSVADDPROPSHEETPAGE pfnAddPage, LPARAM lParam ) { const HRESULT HR_ABORT = E_NOTIMPL ; auto msg = lib::sprintf(L"assemblyShelllPropertyPage [AddPages]"); msg.debug(); try { auto mystr = new std::wstring( this->_uiString ) ; // freed by the receiver, the dlg proc PROPSHEETPAGEW psp ; ::ZeroMemory( &psp, sizeof(psp) ) ; psp.dwSize = sizeof( PROPSHEETPAGEW ) ; psp.dwFlags = PSP_USEREFPARENT | PSP_USETITLE | PSP_USEICONID ; psp.hInstance = _AtlBaseModule.m_hInst ; psp.pszTemplate = MAKEINTRESOURCEW( IDD_PROPPAGE_LARGE ) ; psp.pszIcon = MAKEINTRESOURCEW( IDI_ICON1 ) ; psp.pszTitle = L"alby.NET" ; psp.pfnDlgProc = (DLGPROC) MyDlgProc ; psp.lParam = (LPARAM) mystr ; //psp.pfnCallback = PropPageCallbackProc; psp.pcRefParent = (UINT*) &_AtlModule.m_nLockCnt ; auto hPage = ::CreatePropertySheetPageW( &psp ) ; if ( hPage != NULL ) if ( ! pfnAddPage( hPage, lParam ) ) { ::DestroyPropertySheetPage( hPage ) ; return HR_ABORT ; } return S_OK ; } catch ( const lib::exception& ex ) { auto err = lib::sprintf( L"EXCEPTION\n", ex.what() ) ; err.debug() ; return HR_ABORT ; } catch ( const std::exception& ex ) { auto err = lib::sprintf( L"EXCEPTION\n", ex.what() ) ; err.debug(); return HR_ABORT ; } catch (...) { auto err = lib::sprintf( L"EXCEPTION\n..." ) ; err.debug() ; return HR_ABORT ; } return HR_ABORT ; } BOOL CALLBACK assemblyShelllPropertyPage::MyDlgProc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam ) { BOOL rc = FALSE ; switch( msg ) { case WM_INITDIALOG: { auto p = (PROPSHEETPAGEW*) lParam ; ::SetWindowLong( hwnd, GWLP_USERDATA, (LONG) p->lParam ) ; auto pstr = (std::wstring*) p->lParam ; std::wstring str( *pstr ) ; delete pstr ; ::SetDlgItemTextW( hwnd, IDC_EDIT1, str.c_str() ) ; return TRUE ; } case WM_NOTIFY: { /* auto phdr = (NMHDR*) lParam ; switch( phdr->code ) { default: break ; } */ break ; } case WM_COMMAND: { switch( LOWORD(wParam) ) { case IDC_EDIT1: ::SendDlgItemMessage( hwnd, IDC_EDIT1, EM_SETSEL, -1, -1 ) ; return 0 ; break ; } break; } default: break ; } return rc ; } STDMETHODIMP assemblyShelllPropertyPage::ReplacePage ( EXPPS uPageID, LPFNSVADDPROPSHEETPAGE pfnReplaceWith, LPARAM lParam ) { auto msg = lib::sprintf(L"assemblyShelllPropertyPage [ReplacePage]"); msg.debug(); return E_NOTIMPL; }
25.540453
120
0.633933
[ "transform" ]
3cf6ce039b62958795ca8602a9fd1c03df29e340
3,170
cpp
C++
Utilities/Poco/XML/src/DOMWriter.cpp
nocnokneo/MITK
2902dcaed2ebf83b08c29d73608e8c70ead9e602
[ "BSD-3-Clause" ]
null
null
null
Utilities/Poco/XML/src/DOMWriter.cpp
nocnokneo/MITK
2902dcaed2ebf83b08c29d73608e8c70ead9e602
[ "BSD-3-Clause" ]
null
null
null
Utilities/Poco/XML/src/DOMWriter.cpp
nocnokneo/MITK
2902dcaed2ebf83b08c29d73608e8c70ead9e602
[ "BSD-3-Clause" ]
null
null
null
// // DOMWriter.cpp // // $Id$ // // Library: XML // Package: DOM // Module: DOMWriter // // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/DOM/DOMWriter.h" #include "Poco/XML/XMLWriter.h" #include "Poco/DOM/Document.h" #include "Poco/DOM/DocumentFragment.h" #include "Poco/DOM/DocumentType.h" #include "Poco/DOM/DOMException.h" #include "Poco/DOM/DOMSerializer.h" #include "Poco/SAX/LexicalHandler.h" #include "Poco/XML/XMLException.h" #include "Poco/Path.h" #include "Poco/FileStream.h" namespace Poco { namespace XML { DOMWriter::DOMWriter(): _pTextEncoding(0), _options(0) { } DOMWriter::~DOMWriter() { } void DOMWriter::setEncoding(const std::string& encodingName, Poco::TextEncoding& textEncoding) { _encodingName = encodingName; _pTextEncoding = &textEncoding; } void DOMWriter::setOptions(int options) { _options = options; } void DOMWriter::setNewLine(const std::string& newLine) { _newLine = newLine; } void DOMWriter::writeNode(XMLByteOutputStream& ostr, const Node* pNode) { poco_check_ptr (pNode); bool isFragment = pNode->nodeType() != Node::DOCUMENT_NODE; XMLWriter writer(ostr, _options, _encodingName, _pTextEncoding); writer.setNewLine(_newLine); DOMSerializer serializer; serializer.setContentHandler(&writer); serializer.setDTDHandler(&writer); serializer.setProperty(XMLReader::PROPERTY_LEXICAL_HANDLER, static_cast<LexicalHandler*>(&writer)); if (isFragment) writer.startFragment(); serializer.serialize(pNode); if (isFragment) writer.endFragment(); } void DOMWriter::writeNode(const std::string& systemId, const Node* pNode) { Poco::FileOutputStream ostr(systemId); if (ostr.good()) writeNode(ostr, pNode); else throw Poco::CreateFileException(systemId); } } } // namespace Poco::XML
27.094017
100
0.753312
[ "object" ]
3cf9a6abaef37da60587a44c351a05b3a3eac671
36,060
cpp
C++
frmts/netcdf/netcdfsg.cpp
sharkAndshark/gdal
0cf797ecaa5d1d3312f3a9f51a266cd3f9d02fb5
[ "Apache-2.0" ]
42
2021-03-26T17:34:52.000Z
2022-03-18T14:15:31.000Z
frmts/netcdf/netcdfsg.cpp
sharkAndshark/gdal
0cf797ecaa5d1d3312f3a9f51a266cd3f9d02fb5
[ "Apache-2.0" ]
29
2017-03-17T23:55:49.000Z
2018-03-13T09:27:01.000Z
frmts/netcdf/netcdfsg.cpp
sharkAndshark/gdal
0cf797ecaa5d1d3312f3a9f51a266cd3f9d02fb5
[ "Apache-2.0" ]
8
2021-05-14T19:26:37.000Z
2022-03-21T13:44:42.000Z
/****************************************************************************** * * Project: netCDF read/write Driver * Purpose: GDAL bindings over netCDF library. * Author: Winor Chen <wchen329 at wisc.edu> * ****************************************************************************** * Copyright (c) 2019, Winor Chen <wchen329 at wisc.edu> * * 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. ****************************************************************************/ #include <cstdio> #include <cstring> #include <set> #include <vector> #include "netcdf.h" #include "netcdfdataset.h" #include "netcdfsg.h" namespace nccfdriver { /* Attribute Fetch * - * A function which makes it a bit easier to fetch single text attribute values * ncid: as used in netcdf.h * varID: variable id in which to look for the attribute * attrName: name of attribute to fine * alloc: a reference to a string that will be filled with the attribute (i.e. truncated and filled with the return value) * Returns: a reference to the string to fill (a.k.a. string pointed to by alloc reference) */ std::string& attrf(int ncid, int varId, const char * attrName, std::string& alloc) { size_t len = 0; nc_inq_attlen(ncid, varId, attrName, &len); if(len < 1) { alloc.clear(); return alloc; } alloc.resize(len); memset(&alloc[0], 0, len); // Now look through this variable for the attribute nc_get_att_text(ncid, varId, attrName, &alloc[0]); return alloc; } /* SGeometry_Reader * (implementations) * */ SGeometry_Reader::SGeometry_Reader(int ncId, int geoVarId) : gc_varId(geoVarId), touple_order(0) { char container_name[NC_MAX_NAME + 1]; memset(container_name, 0, NC_MAX_NAME + 1); // Get geometry container name if(nc_inq_varname(ncId, geoVarId, container_name) != NC_NOERR) { throw SG_Exception_Existential("new geometry container", "the variable of the given ID"); } // Establish string version of container_name container_name_s = std::string(container_name); // Find geometry type this->type = nccfdriver::getGeometryType(ncId, geoVarId); if(this->type == NONE) { throw SG_Exception_Existential(static_cast<const char*>(container_name), CF_SG_GEOMETRY_TYPE); } // Get grid mapping variable, if it exists this->gm_varId = INVALID_VAR_ID; if(attrf(ncId, geoVarId, CF_GRD_MAPPING, gm_name_s) != "") { const char * gm_name = gm_name_s.c_str(); int gmVID; if(nc_inq_varid(ncId, gm_name, &gmVID) == NC_NOERR) { this->gm_varId = gmVID; } } // Find a list of node counts and part node count std::string nc_name_s; std::string pnc_name_s; std::string ir_name_s; int pnc_vid = INVALID_VAR_ID; int nc_vid = INVALID_VAR_ID; int ir_vid = INVALID_VAR_ID; int buf; size_t bound = 0; size_t total_node_count = 0; // used in error checks later size_t total_part_node_count = 0; if(attrf(ncId, geoVarId, CF_SG_NODE_COUNT, nc_name_s) != "") { const char * nc_name = nc_name_s.c_str(); nc_inq_varid(ncId, nc_name, &nc_vid); while(nc_get_var1_int(ncId, nc_vid, &bound, &buf) == NC_NOERR) { if(buf < 0) { throw SG_Exception_Value_Violation(static_cast<const char*>(container_name), CF_SG_NODE_COUNT, "negative"); } this->node_counts.push_back(buf); total_node_count += buf; bound++; } } if(attrf(ncId, geoVarId, CF_SG_PART_NODE_COUNT, pnc_name_s) != "") { const char * pnc_name = pnc_name_s.c_str(); bound = 0; nc_inq_varid(ncId, pnc_name, &pnc_vid); while(nc_get_var1_int(ncId, pnc_vid, &bound, &buf) == NC_NOERR) { if(buf < 0) { throw SG_Exception_Value_Violation(static_cast<const char*>(container_name), CF_SG_PART_NODE_COUNT, "negative"); } this->pnode_counts.push_back(buf); total_part_node_count += buf; bound++; } } if(attrf(ncId, geoVarId, CF_SG_INTERIOR_RING, ir_name_s) != "") { const char * ir_name = ir_name_s.c_str(); bound = 0; nc_inq_varid(ncId, ir_name, &ir_vid); while(nc_get_var1_int(ncId, ir_vid, &bound, &buf) == NC_NOERR) { bool store = buf == 0 ? false : true; if(buf != 0 && buf != 1) { throw SG_Exception_Value_Required(static_cast<const char*>(container_name), CF_SG_INTERIOR_RING, "0 or 1"); } this->int_rings.push_back(store); bound++; } } /* Enforcement of well formed CF files * If these are not met then the dataset is malformed and will halt further processing of * simple geometries. */ // part node count exists only when node count exists if(pnode_counts.size() > 0 && node_counts.size() == 0) { throw SG_Exception_Dep(static_cast<const char *>(container_name), CF_SG_PART_NODE_COUNT, CF_SG_NODE_COUNT); } // part node counts and node counts don't match up in count if(pnc_vid != INVALID_VAR_ID && total_node_count != total_part_node_count) { throw SG_Exception_BadSum(static_cast<const char*>(container_name), CF_SG_PART_NODE_COUNT, CF_SG_PART_NODE_COUNT); } // interior rings only exist when part node counts exist if(int_rings.size() > 0 && pnode_counts.size() == 0) { throw SG_Exception_Dep(static_cast<const char *>(container_name), CF_SG_INTERIOR_RING, CF_SG_PART_NODE_COUNT); } // cardinality of part_node_counts == cardinality of interior_ring (if interior ring > 0) if(int_rings.size() > 0) { if(int_rings.size() != pnode_counts.size()) { throw SG_Exception_Dim_MM(static_cast<const char *>(container_name), CF_SG_INTERIOR_RING, CF_SG_PART_NODE_COUNT); } } // lines and polygons require node_counts, multipolygons are checked with part_node_count if(this->type == POLYGON || this->type == LINE) { if(node_counts.size() < 1) { throw SG_Exception_Existential(static_cast<const char*>(container_name), CF_SG_NODE_COUNT); } } /* Basic Safety checks End */ // Create bound list size_t rc = 0; bound_list.push_back(0);// start with 0 if(node_counts.size() > 0) { for(size_t i = 0; i < node_counts.size() - 1; i++) { rc = rc + node_counts[i]; bound_list.push_back(rc); } } std::string cart_s; // Node Coordinates if(attrf(ncId, geoVarId, CF_SG_NODE_COORDINATES, cart_s) == "") { throw SG_Exception_Existential(container_name, CF_SG_NODE_COORDINATES); } // Create parts count list and an offset list for parts indexing if(this->node_counts.size() > 0) { int ind = 0; int parts = 0; int prog = 0; int c = 0; for(size_t pcnt = 0; pcnt < pnode_counts.size() ; pcnt++) { if(prog == 0) pnc_bl.push_back(pcnt); if(int_rings.size() > 0 && !int_rings[pcnt]) c++; prog = prog + pnode_counts[pcnt]; parts++; if(prog == node_counts[ind]) { ind++; this->parts_count.push_back(parts); if(int_rings.size() > 0) this->poly_count.push_back(c); c = 0; prog = 0; parts = 0; } else if(prog > node_counts[ind]) { throw SG_Exception_BadSum(container_name, CF_SG_PART_NODE_COUNT, CF_SG_NODE_COUNT); } } } // (1) the tuple order for a single point // (2) the variable ids with the relevant coordinate values int X = INVALID_VAR_ID; int Y = INVALID_VAR_ID; int Z = INVALID_VAR_ID; char cart[NC_MAX_NAME + 1]; memset(cart, 0, NC_MAX_NAME + 1); strncpy(cart, cart_s.c_str(), NC_MAX_NAME); char * dim = strtok(cart, " "); int axis_id = 0; while(dim != nullptr) { if(nc_inq_varid(ncId, dim, &axis_id) == NC_NOERR) { // Check axis signature std::string a_sig; attrf(ncId, axis_id, CF_AXIS, a_sig); // If valid signify axis correctly if(a_sig == "X") { X = axis_id; } else if(a_sig == "Y") { Y = axis_id; } else if(a_sig == "Z") { Z = axis_id; } else { throw SG_Exception_Dep(container_name, "A node_coordinates variable", CF_AXIS); } this->touple_order++; } else { throw SG_Exception_Existential(container_name, dim); } dim = strtok(nullptr, " "); } // Write axis in X, Y, Z order if(X != INVALID_VAR_ID) this->nodec_varIds.push_back(X); else { throw SG_Exception_Existential(container_name, "node_coordinates: X-axis"); } if(Y != INVALID_VAR_ID) this->nodec_varIds.push_back(Y); else { throw SG_Exception_Existential(container_name, "node_coordinates: Y-axis"); } if(Z != INVALID_VAR_ID) this->nodec_varIds.push_back(Z); /* Final Checks for node coordinates * (1) Each axis has one and only one dimension, dim length of each node coordinates are all equal * (2) total node count == dim length of each node coordinates (if node_counts not empty) * (3) there are at least two node coordinate variable ids */ int all_dim = INVALID_VAR_ID; bool dim_set = false; //(1) one dimension check, each node_coordinates have same dimension for(size_t nvitr = 0; nvitr < nodec_varIds.size(); nvitr++) { int dimC = 0; nc_inq_varndims(ncId, nodec_varIds[nvitr], &dimC); if(dimC != 1) { throw SG_Exception_Not1D(); } // check that all have same dimension int inter_dim[1]; if(nc_inq_vardimid(ncId, nodec_varIds[nvitr], inter_dim) != NC_NOERR) { throw SG_Exception_Existential(container_name, "one or more node_coordinate dimensions"); } if(!dim_set) { all_dim = inter_dim[0]; dim_set = true; } else { if (inter_dim[0] != all_dim) throw SG_Exception_Dim_MM(container_name, "X, Y", "in general all node coordinate axes"); } } // (2) check equality one if(node_counts.size() > 0) { size_t diml = 0; nc_inq_dimlen(ncId, all_dim, &diml); if(diml != total_node_count) throw SG_Exception_BadSum(container_name, "node_count", "node coordinate dimension length"); } // (3) check tuple order if(this->touple_order < 2) { throw SG_Exception_Existential(container_name, "insufficient node coordinates must have at least two axis"); } /* Investigate for instance dimension * The procedure is as follows * * (1) if there's node_count, use the dimension used to index node count * (2) otherwise it's point (singleton) data, in this case use the node coordinate dimension */ size_t instance_dim_len = 0; if(node_counts.size() >= 1) { int nc_dims = 0; nc_inq_varndims(ncId, nc_vid, &nc_dims); if(nc_dims != 1) throw SG_Exception_Not1D(); int nc_dim_id[1]; if(nc_inq_vardimid(ncId, nc_vid, nc_dim_id) != NC_NOERR) { throw SG_Exception_Existential(container_name, "node_count dimension"); } this->inst_dimId = nc_dim_id[0]; } else { this->inst_dimId = all_dim; } nc_inq_dimlen(ncId, this->inst_dimId, &instance_dim_len); if(instance_dim_len == 0) throw SG_Exception_EmptyDim(); // Set values accordingly this->inst_dimLen = instance_dim_len; this->pt_buffer = cpl::make_unique<Point>(this->touple_order); this->gc_varId = geoVarId; this->ncid = ncId; } Point& SGeometry_Reader::operator[](size_t index) { for(int order = 0; order < touple_order; order++) { Point& pt = *(this->pt_buffer); double data; size_t real_ind = index; // Read a single coord int err = nc_get_var1_double(ncid, nodec_varIds[order], &real_ind, &data); if(err != NC_NOERR) { throw SG_Exception_BadPoint(); } pt[order] = data; } return *(this->pt_buffer); } size_t SGeometry_Reader::get_geometry_count() { if(type == POINT) { if(this->nodec_varIds.size() < 1) return 0; // If more than one dim, then error. Otherwise inquire its length and return that int dims; if(nc_inq_varndims(this->ncid, nodec_varIds[0], &dims) != NC_NOERR) return 0; if(dims != 1) return 0; // Find which dimension is used for x int index; if(nc_inq_vardimid(this->ncid, nodec_varIds[0], &index) != NC_NOERR) { return 0; } // Finally find the length size_t len; if(nc_inq_dimlen(this->ncid, index, &len) != NC_NOERR) { return 0; } return len; } else return this->node_counts.size(); } static void add_to_buffer(std::vector<unsigned char>& buffer, uint8_t v) { buffer.push_back(v); } static void add_to_buffer(std::vector<unsigned char>& buffer, uint32_t v) { const size_t old_size = buffer.size(); buffer.resize(old_size + sizeof(v)); memcpy(&buffer[old_size], &v, sizeof(v)); } static void add_to_buffer(std::vector<unsigned char>&, int) = delete; static void add_to_buffer(std::vector<unsigned char>& buffer, double v) { const size_t old_size = buffer.size(); buffer.resize(old_size + sizeof(v)); memcpy(&buffer[old_size], &v, sizeof(v)); } /* serializeToWKB * Takes the geometry in SGeometry at a given index and converts it into WKB format. * Converting SGeometry into WKB automatically allocates the required buffer space * and returns a buffer that MUST be free'd */ std::vector<unsigned char> SGeometry_Reader::serializeToWKB(size_t featureInd) { std::vector<unsigned char> ret; int nc = 0; size_t sb = 0; // Points don't have node_count entry... only inspect and set node_counts if not a point if(this->getGeometryType() != POINT) { nc = node_counts[featureInd]; sb = bound_list[featureInd]; } // Serialization occurs differently depending on geometry // The memory requirements also differ between geometries switch(this->getGeometryType()) { case POINT: inPlaceSerialize_Point(this, featureInd, ret); break; case LINE: inPlaceSerialize_LineString(this, nc, sb, ret); break; case POLYGON: // A polygon has: // 1 byte header // 4 byte Type // 4 byte ring count (1 (exterior)) [assume only exterior rings, otherwise multipolygon] // For each ring: // 4 byte point count, 8 byte double x point count x # dimension // (This is equivalent to requesting enough for all points and a point count header for each point) // (Or 8 byte double x node count x # dimension + 4 byte point count x part_count) // if interior ring, then assume that it will be a multipolygon (maybe future work?) inPlaceSerialize_PolygonExtOnly(this, nc, sb, ret); break; case MULTIPOINT: { uint8_t header = PLATFORM_HEADER; uint32_t t = this->touple_order == 2 ? wkbMultiPoint : this->touple_order == 3 ? wkbMultiPoint25D : wkbNone; if(t == wkbNone) throw SG_Exception_BadFeature(); // Add metadata add_to_buffer(ret, header); add_to_buffer(ret, t); add_to_buffer(ret, static_cast<uint32_t>(nc)); // Add points for(int pts = 0; pts < nc; pts++) { inPlaceSerialize_Point(this, static_cast<size_t>(sb + pts), ret); } } break; case MULTILINE: { uint8_t header = PLATFORM_HEADER; uint32_t t = this->touple_order == 2 ? wkbMultiLineString : this->touple_order == 3 ? wkbMultiLineString25D : wkbNone; if(t == wkbNone) throw SG_Exception_BadFeature(); int32_t lc = parts_count[featureInd]; size_t seek_begin = sb; size_t pc_begin = pnc_bl[featureInd]; // initialize with first part count, list of part counts is contiguous std::vector<int> pnc; // Build sub vector for part_node_counts // + Calculate wkbSize for(int itr = 0; itr < lc; itr++) { pnc.push_back(pnode_counts[pc_begin + itr]); } size_t cur_point = seek_begin; size_t pcount = pnc.size(); // Begin Writing add_to_buffer(ret, header); add_to_buffer(ret, t); add_to_buffer(ret, static_cast<uint32_t>(pcount)); for(size_t itr = 0; itr < pcount; itr++) { inPlaceSerialize_LineString(this, pnc[itr], cur_point, ret); cur_point = pnc[itr] + cur_point; } } break; case MULTIPOLYGON: { uint8_t header = PLATFORM_HEADER; uint32_t t = this->touple_order == 2 ? wkbMultiPolygon: this->touple_order == 3 ? wkbMultiPolygon25D: wkbNone; if(t == wkbNone) throw SG_Exception_BadFeature(); bool noInteriors = this->int_rings.size() == 0 ? true : false; int32_t rc = parts_count[featureInd]; size_t seek_begin = sb; size_t pc_begin = pnc_bl[featureInd]; // initialize with first part count, list of part counts is contiguous std::vector<int> pnc; // Build sub vector for part_node_counts for(int itr = 0; itr < rc; itr++) { pnc.push_back(pnode_counts[pc_begin + itr]); } // Create Multipolygon headers add_to_buffer(ret, header); add_to_buffer(ret, t); if(noInteriors) { size_t cur_point = seek_begin; size_t pcount = pnc.size(); add_to_buffer(ret, static_cast<uint32_t>(pcount)); for(size_t itr = 0; itr < pcount; itr++) { inPlaceSerialize_PolygonExtOnly(this, pnc[itr], cur_point, ret); cur_point = pnc[itr] + cur_point; } } else { int32_t polys = poly_count[featureInd]; add_to_buffer(ret, static_cast<uint32_t>(polys)); size_t base = pnc_bl[featureInd]; // beginning of parts_count for this multigeometry size_t seek = seek_begin; // beginning of node range for this multigeometry size_t ir_base = base + 1; // has interior rings, for(int32_t itr = 0; itr < polys; itr++) { int rc_m = 1; // count how many parts belong to each Polygon while(ir_base < int_rings.size() && int_rings[ir_base]) { rc_m++; ir_base++; } if(rc_m == 1) ir_base++; // single ring case std::vector<int> poly_parts; // Make part node count sub vector for(int itr_2 = 0; itr_2 < rc_m; itr_2++) { poly_parts.push_back(pnode_counts[base + itr_2]); } inPlaceSerialize_Polygon(this, poly_parts, rc_m, seek, ret); // Update seek position for(size_t itr_3 = 0; itr_3 < poly_parts.size(); itr_3++) { seek += poly_parts[itr_3]; } base += poly_parts.size(); // cppcheck-suppress redundantAssignment ir_base = base + 1; } } } break; default: throw SG_Exception_BadFeature(); break; } return ret; } void SGeometry_PropertyScanner::open(int container_id) { // First check for container_id, if variable doesn't exist error out if(nc_inq_var(this->nc, container_id, nullptr, nullptr, nullptr, nullptr, nullptr) != NC_NOERR) { return; // change to exception } // Now exists, see what variables refer to this one // First get name of this container char contname[NC_MAX_NAME + 1]; memset(contname, 0, NC_MAX_NAME + 1); if(nc_inq_varname(this->nc, container_id, contname) != NC_NOERR) { return; } // Then scan throughout the netcdfDataset if those variables geometry_container // attribute matches the container int varCount = 0; if(nc_inq_nvars(this->nc, &varCount) != NC_NOERR) { return; } for(int curr = 0; curr < varCount; curr++) { size_t contname2_len = 0; // First find container length, and make buf that size in chars if(nc_inq_attlen(this->nc, curr, CF_SG_GEOMETRY, &contname2_len) != NC_NOERR) { // not a geometry variable, continue continue; } // Also if present but empty, go on if(contname2_len == 0) continue; // Otherwise, geometry: see what container it has char buf[NC_MAX_CHAR + 1]; memset(buf, 0, NC_MAX_CHAR + 1); if(nc_get_att_text(this->nc, curr, CF_SG_GEOMETRY, buf)!= NC_NOERR) { continue; } // If matches, then establish a reference by placing this variable's data in both vectors if(!strcmp(contname, buf)) { char property_name[NC_MAX_NAME + 1] = {0}; // look for special OGR original name field if(nc_get_att_text(this->nc, curr, OGR_SG_ORIGINAL_LAYERNAME, property_name) != NC_NOERR) { // if doesn't exist, then just use the variable name if(nc_inq_varname(this->nc, curr, property_name) != NC_NOERR) { throw SG_Exception_General_Malformed(contname); } } std::string n(property_name); v_ids.push_back(curr); v_headers.push_back(n); } } } // Exception Class Implementations SG_Exception_Dim_MM::SG_Exception_Dim_MM(const char* container_name, const char* field_1, const char* field_2) { std::string cn_s(container_name); std::string field1_s(field_1); std::string field2_s(field_2); this -> err_msg = "[" + cn_s + "] One or more dimensions of " + field1_s + " and " + field2_s + " do not match but must match."; } SG_Exception_Existential::SG_Exception_Existential(const char* container_name, const char* missing_name) { std::string cn_s(container_name); std::string mn_s(missing_name); this -> err_msg = "[" + cn_s + "] The property or the variable associated with " + mn_s + " is missing."; } SG_Exception_Dep::SG_Exception_Dep(const char* container_name, const char* arg1, const char* arg2) { std::string cn_s(container_name); std::string arg1_s(arg1); std::string arg2_s(arg2); this -> err_msg = "[" + cn_s + "] The attribute " + arg1_s + " may not exist without the attribute " + arg2_s + " existing."; } SG_Exception_BadSum::SG_Exception_BadSum(const char* container_name, const char* arg1, const char* arg2) { std::string cn_s(container_name); std::string arg1_s(arg1); std::string arg2_s(arg2); this -> err_msg = "[" + cn_s + "]" + " The sum of all values in " + arg1_s + " and " + arg2_s + " do not match."; } SG_Exception_General_Malformed ::SG_Exception_General_Malformed(const char * arg) { std::string arg1_s(arg); this -> err_msg = "Corruption or malformed formatting has been detected in: " + arg1_s; } // to get past linker SG_Exception::~SG_Exception() {} // Helpers // following is a short hand for a clean up and exit, since goto isn't allowed double getCFVersion(int ncid) { double ver = -1.0; std::string attrVal; // Fetch the CF attribute if(attrf(ncid, NC_GLOBAL, NCDF_CONVENTIONS, attrVal) == "") { return ver; } if(sscanf(attrVal.c_str(), "CF-%lf", &ver) != 1) { return -1.0; } return ver; } geom_t getGeometryType(int ncid, int varid) { geom_t ret = UNSUPPORTED; std::string gt_name_s; const char * gt_name= attrf(ncid, varid, CF_SG_GEOMETRY_TYPE, gt_name_s).c_str(); if(gt_name == nullptr) { return NONE; } // Points if(!strcmp(gt_name, CF_SG_TYPE_POINT)) { // Node Count not present? Assume that it is a multipoint. if(nc_inq_att(ncid, varid, CF_SG_NODE_COUNT, nullptr, nullptr) == NC_ENOTATT) { ret = POINT; } else ret = MULTIPOINT; } // Lines else if(!strcmp(gt_name, CF_SG_TYPE_LINE)) { // Part Node Count present? Assume multiline if(nc_inq_att(ncid, varid, CF_SG_PART_NODE_COUNT, nullptr, nullptr) == NC_ENOTATT) { ret = LINE; } else ret = MULTILINE; } // Polygons else if(!strcmp(gt_name, CF_SG_TYPE_POLY)) { /* Polygons versus MultiPolygons, slightly ambiguous * Part Node Count & no Interior Ring - MultiPolygon * no Part Node Count & no Interior Ring - Polygon * Part Node Count & Interior Ring - assume that it is a MultiPolygon */ int pnc_present = nc_inq_att(ncid, varid, CF_SG_PART_NODE_COUNT, nullptr, nullptr); int ir_present = nc_inq_att(ncid, varid, CF_SG_INTERIOR_RING, nullptr, nullptr); if(pnc_present == NC_ENOTATT && ir_present == NC_ENOTATT) { ret = POLYGON; } else ret = MULTIPOLYGON; } return ret; } void inPlaceSerialize_Point(SGeometry_Reader * ge, size_t seek_pos, std::vector<unsigned char>& buffer) { uint8_t order = PLATFORM_HEADER; uint32_t t = ge->get_axisCount() == 2 ? wkbPoint: ge->get_axisCount() == 3 ? wkbPoint25D: wkbNone; if(t == wkbNone) throw SG_Exception_BadFeature(); add_to_buffer(buffer, order); add_to_buffer(buffer, t); // Now get point data; Point & p = (*ge)[seek_pos]; add_to_buffer(buffer, p[0]); add_to_buffer(buffer, p[1]); if(ge->get_axisCount() >= 3) { add_to_buffer(buffer, p[2]); } } void inPlaceSerialize_LineString(SGeometry_Reader * ge, int node_count, size_t seek_begin, std::vector<unsigned char>& buffer) { uint8_t order = PLATFORM_HEADER; uint32_t t = ge->get_axisCount() == 2 ? wkbLineString: ge->get_axisCount() == 3 ? wkbLineString25D: wkbNone; if(t == wkbNone) throw SG_Exception_BadFeature(); uint32_t nc = (uint32_t) node_count; add_to_buffer(buffer, order); add_to_buffer(buffer, t); add_to_buffer(buffer, nc); // Now serialize points for(int ind = 0; ind < node_count; ind++) { Point & p = (*ge)[seek_begin + ind]; add_to_buffer(buffer, p[0]); add_to_buffer(buffer, p[1]); if(ge->get_axisCount() >= 3) { add_to_buffer(buffer, p[2]); } } } void inPlaceSerialize_PolygonExtOnly(SGeometry_Reader * ge, int node_count, size_t seek_begin, std::vector<unsigned char>& buffer) { uint8_t order = PLATFORM_HEADER; uint32_t t = ge->get_axisCount() == 2 ? wkbPolygon: ge->get_axisCount() == 3 ? wkbPolygon25D: wkbNone; if(t == wkbNone) throw SG_Exception_BadFeature(); uint32_t rc = 1; add_to_buffer(buffer, order); add_to_buffer(buffer, t); add_to_buffer(buffer, rc); add_to_buffer(buffer, static_cast<uint32_t>(node_count)); for(int pind = 0; pind < node_count; pind++) { Point & pt= (*ge)[seek_begin + pind]; add_to_buffer(buffer, pt[0]); add_to_buffer(buffer, pt[1]); if(ge->get_axisCount() >= 3) { add_to_buffer(buffer, pt[2]); } } } void inPlaceSerialize_Polygon(SGeometry_Reader * ge, std::vector<int>& pnc, int ring_count, size_t seek_begin, std::vector<unsigned char>& buffer) { uint8_t order = PLATFORM_HEADER; uint32_t t = ge->get_axisCount() == 2 ? wkbPolygon: ge->get_axisCount() == 3 ? wkbPolygon25D: wkbNone; if(t == wkbNone) throw SG_Exception_BadFeature(); uint32_t rc = static_cast<uint32_t>(ring_count); add_to_buffer(buffer, order); add_to_buffer(buffer, t); add_to_buffer(buffer, rc); int cmoffset = 0; for(int ring_c = 0; ring_c < ring_count; ring_c++) { uint32_t node_count = pnc[ring_c]; add_to_buffer(buffer, node_count); int pind = 0; for(pind = 0; pind < pnc[ring_c]; pind++) { Point & pt= (*ge)[seek_begin + cmoffset + pind]; add_to_buffer(buffer, pt[0]); add_to_buffer(buffer, pt[1]); if(ge->get_axisCount() >= 3) { add_to_buffer(buffer, pt[2]); } } cmoffset += pind; } } int scanForGeometryContainers(int ncid, std::set<int> & r_ids) { int nvars; if(nc_inq_nvars(ncid, &nvars) != NC_NOERR) { return -1; } r_ids.clear(); // For each variable check for geometry attribute // If has geometry attribute, then check the associated variable ID for(int itr = 0; itr < nvars; itr++) { char c[NC_MAX_CHAR]; memset(c, 0, NC_MAX_CHAR); if(nc_get_att_text(ncid, itr, CF_SG_GEOMETRY, c) != NC_NOERR) { continue; } int varID; if(nc_inq_varid(ncid, c, &varID) != NC_NOERR) { continue; } // Now have variable ID. See if vector contains it, and if not // insert r_ids.insert(varID); // It's a set. No big deal sets don't allow duplicates anyways } return 0 ; } }
33.954802
150
0.516999
[ "geometry", "vector" ]
a701c425d9be9724feae86c563f53cd9cad95bef
21,312
cpp
C++
src/asiAlgo/blends/asiAlgo_SuppressBlendChain.cpp
sasobadovinac/AnalysisSitus
304d39c64258d4fcca888eb8e68144eca50e785a
[ "BSD-3-Clause" ]
null
null
null
src/asiAlgo/blends/asiAlgo_SuppressBlendChain.cpp
sasobadovinac/AnalysisSitus
304d39c64258d4fcca888eb8e68144eca50e785a
[ "BSD-3-Clause" ]
null
null
null
src/asiAlgo/blends/asiAlgo_SuppressBlendChain.cpp
sasobadovinac/AnalysisSitus
304d39c64258d4fcca888eb8e68144eca50e785a
[ "BSD-3-Clause" ]
null
null
null
//----------------------------------------------------------------------------- // Created on: 17 October 2018 //----------------------------------------------------------------------------- // Copyright (c) 2018-present, Sergey Slyadnev // 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 the copyright holder(s) nor the // names of all 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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- // Own include #include <asiAlgo_SuppressBlendChain.h> // asiAlgo includes #include <asiAlgo_AAGIterator.h> #include <asiAlgo_AttrBlendCandidate.h> #include <asiAlgo_BlendTopoConditionFFIsolated.h> #include <asiAlgo_BlendTopoConditionFFOrdinaryEBF.h> #include <asiAlgo_BlendTopoConditionFFOrdinaryVBF.h> #include <asiAlgo_CheckValidity.h> #include <asiAlgo_RebuildEdge.h> #include <asiAlgo_Timer.h> #undef COUT_DEBUG #if defined COUT_DEBUG #pragma message("===== warning: COUT_DEBUG is enabled") #endif //----------------------------------------------------------------------------- namespace asiAlgo_AAGIterationRule { //! This rule prevents further iteration starting from faces which are //! not recognized as blend candidate faces. class AllowBlendCandidates : public Standard_Transient { public: // OCCT RTTI DEFINE_STANDARD_RTTI_INLINE(AllowBlendCandidates, Standard_Transient) public: //! Ctor. //! \param[in] aag attributed adjacency graph keeping information on the //! recognized properties of the model. //! \param[in] conditions collection of topological condition. This collection //! can be null at initialization stage. Alternatively, //! you may pass an existing collection here, so the //! rule will not allocate a new one but will add new //! data to the passed one. //! \param[in] progress progress notifier. //! \param[in] plottter imperative plotter. AllowBlendCandidates(const Handle(asiAlgo_AAG)& aag, const Handle(asiAlgo_HBlendTopoConditionMap)& conditions, ActAPI_ProgressEntry progress, ActAPI_PlotterEntry plotter) // : m_aag (aag), m_faceInfo (conditions), m_bAllInitialized (true), m_progress (progress), m_plotter (plotter) { if ( m_faceInfo.IsNull() ) m_faceInfo = new asiAlgo_HBlendTopoConditionMap; } public: //! For the given face ID, this method decides whether to check its //! neighbors or stop. //! \param[in] fid 1-based ID of the face in question. //! \return true if the face in question is a gatekeeper for further iteration. bool IsBlocking(const int fid) { // If there are some nodal attributes for this face, we check whether // it has already been recognized as a blend candidate. if ( m_aag->HasNodeAttributes(fid) ) { // Skip already visited nodes. if ( m_faceInfo->IsBound(fid) ) return false; // Check blend candidates. Handle(asiAlgo_FeatureAttr) attr = m_aag->GetNodeAttribute( fid, asiAlgo_AttrBlendCandidate::GUID() ); // if ( !attr.IsNull() ) { Handle(asiAlgo_AttrBlendCandidate) bcAttr = Handle(asiAlgo_AttrBlendCandidate)::DownCast(attr); // if ( bcAttr->Kind == BlendType_Uncertain ) { m_problematicFaces.Add(fid); m_bAllInitialized = false; return true; // Block further iterations. } // Prepare topological conditions. Handle(asiAlgo_BlendTopoConditionFFIsolated) cond1 = new asiAlgo_BlendTopoConditionFFIsolated(m_aag, m_progress, m_plotter); // Handle(asiAlgo_BlendTopoConditionFFOrdinaryEBF) cond2 = new asiAlgo_BlendTopoConditionFFOrdinaryEBF(m_aag, m_progress, m_plotter); // Handle(asiAlgo_BlendTopoConditionFFOrdinaryVBF) cond3 = new asiAlgo_BlendTopoConditionFFOrdinaryVBF(m_aag, m_progress, m_plotter); // Attempt to identify a topological condition. if ( cond1->Initialize(bcAttr) ) { m_progress.SendLogMessage( LogNotice(Normal) << "Confirmed condition: %1." << cond1->DynamicType()->Name() ); cond1->Dump(m_plotter); // m_faceInfo->Bind(fid, cond1); return false; // Allow further iteration. } else if ( cond2->Initialize(bcAttr) ) { m_progress.SendLogMessage( LogNotice(Normal) << "Confirmed condition: %1." << cond2->DynamicType()->Name() ); cond2->Dump(m_plotter); // m_faceInfo->Bind(fid, cond2); return false; // Allow further iteration. } else if ( cond3->Initialize(bcAttr) ) { m_progress.SendLogMessage( LogNotice(Normal) << "Confirmed condition: %1." << cond3->DynamicType()->Name() ); cond3->Dump(m_plotter); // m_faceInfo->Bind(fid, cond3); return false; // Allow further iteration. } // else if ( m_bAllInitialized ) { m_problematicFaces.Add(fid); m_bAllInitialized = false; } } } return true; // Prohibit further iteration. } //! \return recognized topological conditions. const Handle(asiAlgo_HBlendTopoConditionMap)& GetConditions() const { return m_faceInfo; } //! \return true if all topological conditions were initialized //! successfully, false -- otherwise. bool AreAllInitialized() const { return m_bAllInitialized; } //! \return IDs of the problematic faces. const TColStd_PackedMapOfInteger& GetProblematicFaces() const { return m_problematicFaces; } protected: //! AAG instance. Handle(asiAlgo_AAG) m_aag; //! This map stores for each face its topological condition. Handle(asiAlgo_HBlendTopoConditionMap) m_faceInfo; //! Indicates whether all topological conditions were identified or not. bool m_bAllInitialized; //! IDs of the faces whose topological conditions are not initialized. TColStd_PackedMapOfInteger m_problematicFaces; protected: ActAPI_ProgressEntry m_progress; //!< Progress notifier. ActAPI_PlotterEntry m_plotter; //!< Imperative plotter. }; }; //----------------------------------------------------------------------------- asiAlgo_SuppressBlendChain::asiAlgo_SuppressBlendChain(const Handle(asiAlgo_AAG)& aag, const Handle(asiAlgo_History)& history, ActAPI_ProgressEntry progress, ActAPI_PlotterEntry plotter) // : ActAPI_IAlgorithm (progress, plotter), m_aag (aag), m_history (history), m_iSuppressedChains (0) {} //----------------------------------------------------------------------------- asiAlgo_SuppressBlendChain::asiAlgo_SuppressBlendChain(const Handle(asiAlgo_AAG)& aag, ActAPI_ProgressEntry progress, ActAPI_PlotterEntry plotter) // : ActAPI_IAlgorithm (progress, plotter), m_aag (aag), m_iSuppressedChains (0) { m_history = new asiAlgo_History; } //----------------------------------------------------------------------------- bool asiAlgo_SuppressBlendChain::Perform(const int faceId) { m_iSuppressedChains = 0; /* =================================== * Initialize topological conditions * =================================== */ TIMER_NEW TIMER_GO // Identify all topological conditions. if ( !this->initTopoConditions(faceId) ) return false; TIMER_FINISH TIMER_COUT_RESULT_NOTIFIER(m_progress, "Initialize topo conditions") /* ======================================================= * Check if the chain in question is suppressible or not * ======================================================= */ TIMER_RESET TIMER_GO if ( !this->checkChainSuppressible() ) return false; TIMER_FINISH TIMER_COUT_RESULT_NOTIFIER(m_progress, "Check if chain is suppressible") /* ================================ * Perform topological operations * ================================ */ TIMER_RESET TIMER_GO TopoDS_Shape targetShape; if ( !this->performTopoOperations(targetShape) ) return false; TIMER_FINISH TIMER_COUT_RESULT_NOTIFIER(m_progress, "Topological reduction") /* ============================== * Perform geometric operations * ============================== */ TIMER_RESET TIMER_GO if ( !this->performGeomOperations(targetShape) ) return false; TIMER_FINISH TIMER_COUT_RESULT_NOTIFIER(m_progress, "Rebuild edges") /* ========================================================= * Check if the affected faces are valid after suppression * ========================================================= */ TIMER_RESET TIMER_GO std::vector<asiAlgo_History::t_item*> leafItems; m_history->GetLeafs(leafItems, TopAbs_FACE); // Check faces. for ( size_t k = 0; k < leafItems.size(); ++k ) { // Skip deleted blends. if ( leafItems[k]->IsDeleted ) continue; // Check alive faces. const TopoDS_Face& affectedFace = TopoDS::Face(leafItems[k]->TransientPtr); // if ( !this->isValidFace(affectedFace) ) { m_plotter.REDRAW_SHAPE("affectedFace_INVALID", affectedFace, Color_Red); m_progress.SendLogMessage(LogWarn(Normal) << "One of the affected faces becomes invalid " "after processing. Abort is required."); return false; } } TIMER_FINISH TIMER_COUT_RESULT_NOTIFIER(m_progress, "Check validity of faces") /* ========== * Finalize * ========== */ // Set output. m_result = targetShape; m_iSuppressedChains = 1; // Set history. m_history->AddModified(m_aag->GetMasterCAD(), m_result); return true; } //----------------------------------------------------------------------------- TColStd_PackedMapOfInteger asiAlgo_SuppressBlendChain::GetChainIds() const { if ( m_workflow.topoCondition.IsNull() ) return TColStd_PackedMapOfInteger(); TColStd_PackedMapOfInteger result; // for ( asiAlgo_HBlendTopoConditionMap::Iterator it(*m_workflow.topoCondition); it.More(); it.Next() ) { const int fid = it.Key(); result.Add(fid); } return result; } //----------------------------------------------------------------------------- TopTools_IndexedMapOfShape asiAlgo_SuppressBlendChain::GetChainFaces() const { TColStd_PackedMapOfInteger faceIds = this->GetChainIds(); TopTools_IndexedMapOfShape result; // for ( TColStd_MapIteratorOfPackedMapOfInteger fit(faceIds); fit.More(); fit.Next() ) { const int fid = fit.Key(); result.Add( m_aag->GetFace(fid) ); } return result; } //----------------------------------------------------------------------------- bool asiAlgo_SuppressBlendChain::initTopoConditions(const int faceId) { // Propagation rule. Handle(asiAlgo_AAGIterationRule::AllowBlendCandidates) itRule = new asiAlgo_AAGIterationRule::AllowBlendCandidates(m_aag, m_workflow.topoCondition, m_progress, m_plotter); // Prepare neighborhood iterator with customized propagation rule. The idea // of the following loop is to initialize all topological conditions before // suppression. int numIteratedFaces = 0; // asiAlgo_AAGNeighborsIterator<asiAlgo_AAGIterationRule::AllowBlendCandidates> nit(m_aag, faceId, itRule); // while ( nit.More() ) { nit.Next(); ++numIteratedFaces; } // Check if suppression is possible. if ( !itRule->AreAllInitialized() ) { int kk = 1; TCollection_AsciiString problemFacesStr; const TColStd_PackedMapOfInteger& problemFaces = itRule->GetProblematicFaces(); // for ( TColStd_MapIteratorOfPackedMapOfInteger fit(problemFaces); fit.More(); fit.Next(), ++kk ) { problemFacesStr += fit.Key(); if ( kk < problemFaces.Extent() ) problemFacesStr += " "; } m_progress.SendLogMessage(LogWarn(Normal) << "Some non-identified topological conditions " "remain for faces with the following IDs: %1." << problemFacesStr); return false; } // Get identified conditions. m_workflow.topoCondition = itRule->GetConditions(); return true; } //----------------------------------------------------------------------------- void asiAlgo_SuppressBlendChain::updateTopoConditions(const int toSkip, const Handle(asiAlgo_History)& history) const { for ( asiAlgo_HBlendTopoConditionMap::Iterator cit(*m_workflow.topoCondition); cit.More(); cit.Next() ) { const int fid = cit.Key(); // if ( fid == toSkip ) continue; // Actualize condition. const Handle(asiAlgo_BlendTopoCondition)& cond = cit.Value(); // cond->Actualize(history); } } //----------------------------------------------------------------------------- bool asiAlgo_SuppressBlendChain::performTopoOperations(TopoDS_Shape& resultShape) { // Input shape. resultShape = m_aag->GetMasterCAD(); // Process the initialized topological conditions. for ( asiAlgo_HBlendTopoConditionMap::Iterator cit(*m_workflow.topoCondition); cit.More(); cit.Next() ) { const int blendFaceId = cit.Key(); const Handle(asiAlgo_BlendTopoCondition)& cond = cit.Value(); if ( !cond->Suppress(resultShape, resultShape, m_history) ) { m_progress.SendLogMessage(LogErr(Normal) << "Cannot suppress topological condition for blend face %1." << blendFaceId); return false; // No sense to go further if we already fail here. } // Update all topological conditions. this->updateTopoConditions(blendFaceId, m_history); // Add edges to rebuild. cond->GatherAffectedEdges(m_workflow.edges2Rebuild); // Update all edges to rebuild. this->updateEdges2Rebuild(m_history); } return true; } //----------------------------------------------------------------------------- bool asiAlgo_SuppressBlendChain::performGeomOperations(TopoDS_Shape& targetShape) { const int numEdges = m_workflow.edges2Rebuild.edges.Extent(); m_progress.SendLogMessage(LogInfo(Normal) << "There are %1 edges to rebuild" << numEdges); // Normalize geometry. for ( int k = 1; k <= m_workflow.edges2Rebuild.edges.Extent(); ++k ) { // Update from history as the edge could have been modified by rebuilder // on previous iterations. if ( k > 1 ) this->updateEdges2Rebuild(m_history); const TopoDS_Edge& edge2Rebuild = m_workflow.edges2Rebuild.edges(k).edge; // if ( edge2Rebuild.IsNull() ) continue; // Null image of the next edge to rebuild. // m_plotter.DRAW_SHAPE(edge2Rebuild, Color_Magenta, 1.0, true, "edge2Rebuild"); // Prepare algorithm. asiAlgo_RebuildEdge rebuildEdge(targetShape, m_progress, m_plotter); // rebuildEdge.SetHistory(m_history); rebuildEdge.SetFrozenVertices(m_workflow.edges2Rebuild.edges(k).frozenVertices); // Apply geometric operator. if ( !rebuildEdge.Perform(edge2Rebuild) ) { m_plotter.DRAW_SHAPE(edge2Rebuild, Color_Red, 1.0, true, "edge2Rebuild_failed"); m_progress.SendLogMessage(LogWarn(Normal) << "Cannot rebuild edge."); return false; } // Update working part. targetShape = rebuildEdge.GetResult(); } return true; } //----------------------------------------------------------------------------- void asiAlgo_SuppressBlendChain::updateEdges2Rebuild(const Handle(asiAlgo_History)& history) { asiAlgo_Edges2Rebuild updated; for ( int k = 1; k <= m_workflow.edges2Rebuild.edges.Extent(); ++k ) { asiAlgo_Edge2Rebuild edgeInfo = m_workflow.edges2Rebuild.edges(k); // Update from history. edgeInfo.Actualize(history); // updated.Add(edgeInfo); } // Set the result. m_workflow.edges2Rebuild = updated; } //----------------------------------------------------------------------------- bool asiAlgo_SuppressBlendChain::checkChainSuppressible() const { /* Check if all cross-edges are referenced twice by the blend faces in a chain. */ // Gather all cross edges of a chain into a single collection. TColStd_PackedMapOfInteger allCrossEdgeIndices; TColStd_PackedMapOfInteger allBlendFaceIndices; // for ( asiAlgo_HBlendTopoConditionMap::Iterator cit(*m_workflow.topoCondition); cit.More(); cit.Next() ) { const int fid = cit.Key(); // Get attribute. Handle(asiAlgo_FeatureAttr) attr = m_aag->GetNodeAttribute( fid, asiAlgo_AttrBlendCandidate::GUID() ); // if ( !attr.IsNull() ) { Handle(asiAlgo_AttrBlendCandidate) bcAttr = Handle(asiAlgo_AttrBlendCandidate)::DownCast(attr); // Collect indices of cross edges allCrossEdgeIndices.Unite(bcAttr->CrossEdgeIndices); allBlendFaceIndices.Add(fid); } } // Check every cross-edge. for ( TColStd_MapIteratorOfPackedMapOfInteger eit(allCrossEdgeIndices); eit.More(); eit.Next() ) { const int eid = eit.Key(); const TopoDS_Edge& E = TopoDS::Edge( m_aag->RequestMapOfEdges()(eid) ); int numOccurrences = 0; const TopTools_ListOfShape& E_faces = m_aag->RequestMapOfEdgesFaces().FindFromKey(E); // for ( TopTools_ListIteratorOfListOfShape fit(E_faces); fit.More(); fit.Next() ) { const TopoDS_Face& F = TopoDS::Face( fit.Value() ); const int fid = m_aag->GetFaceId(F); if ( allBlendFaceIndices.Contains(fid) ) ++numOccurrences; } if ( numOccurrences != 2 ) { m_progress.SendLogMessage(LogWarn(Normal) << "Cross-edge %1 has %2 occurrence(s) while 2 is expected." << eid << numOccurrences); return false; } } m_progress.SendLogMessage(LogInfo(Normal) << "Blend chain seems to be suppressible."); return true; } //----------------------------------------------------------------------------- bool asiAlgo_SuppressBlendChain::isValidFace(const TopoDS_Face& face) const { asiAlgo_CheckValidity checker; // This calibrated value is used to compensate weird tolerances which // happen to be insufficient to cover tiny contour gaps. const double tol = checker.MaxTolerance(face)*5.0; // Perform basic check. bool ok = checker.HasAllClosedWires(face, tol) && !checker.HasEdgesWithoutVertices(face); // if ( !ok ) return false; // Check for self-intersections in the domain of the face. if ( checker.HasDomainSelfIntersections(face, true) ) // Stop at first intersection found. return false; return true; }
32.990712
108
0.589105
[ "geometry", "shape", "vector", "model" ]
a70298039ad84f00016f835456f493c1329601bf
10,336
cpp
C++
tiger_ci/erkale/mathf.cpp
EACcodes/TigerCI
ac1311ea5e2b829b5507171afdbdd6c64e12e6fd
[ "BSD-3-Clause" ]
3
2016-12-08T13:57:10.000Z
2019-01-17T17:05:46.000Z
tiger_ci/erkale/mathf.cpp
EACcodes/TigerCI
ac1311ea5e2b829b5507171afdbdd6c64e12e6fd
[ "BSD-3-Clause" ]
null
null
null
tiger_ci/erkale/mathf.cpp
EACcodes/TigerCI
ac1311ea5e2b829b5507171afdbdd6c64e12e6fd
[ "BSD-3-Clause" ]
2
2019-02-20T06:03:24.000Z
2020-06-09T09:00:49.000Z
/* * This source code is part of * * E R K A L E * - * DFT from Hel * * Written by Susi Lehtola, 2010-2011 * Copyright (c) 2010-2011, Susi Lehtola * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. */ #include "mathf.h" #include <cmath> #include <cfloat> // For exceptions #include <sstream> #include <stdexcept> extern "C" { // For factorials and so on #include <gsl/gsl_sf_gamma.h> // For spline interpolation #include <gsl/gsl_spline.h> // For Bessel functions #include <gsl/gsl_sf_bessel.h> // For hypergeometric functions #include <gsl/gsl_sf_hyperg.h> // For trigonometric functions #include <gsl/gsl_sf_trig.h> // Random number generation #include <gsl/gsl_rng.h> // Random number distributions #include <gsl/gsl_randist.h> } double doublefact(int n) { if(n<-1) { ERROR_INFO(); std::ostringstream oss; oss << "Trying to compute double factorial for n="<<n<<"!"; throw std::runtime_error(oss.str()); } if(n>=-1 && n<=1) return 1.0; else return gsl_sf_doublefact(n); } double fact(int n) { if(n<0) { ERROR_INFO(); std::ostringstream oss; oss << "Trying to compute factorial for n="<<n<<"\ !"; throw std::runtime_error(oss.str()); } return gsl_sf_fact(n); } double fact_ratio(int i, int r) { return gsl_sf_fact(i)/(gsl_sf_fact(r)*gsl_sf_fact(i-2*r)); } double fgamma(double x) { return gsl_sf_gamma(x); } double sinc(double x) { return gsl_sf_sinc(x/M_PI); } double bessel_jl(int l, double x) { // Small x: use series expansion double series=pow(x,l)/doublefact(2*l+1); if(fabs(series)<sqrt(DBL_EPSILON)) return series; // Large x: truncate due to incorrect GSL asymptotics // (GSL bug https://savannah.gnu.org/bugs/index.php?36152) if(x>1.0/DBL_EPSILON) return 0.0; // Default case: use GSL return gsl_sf_bessel_jl(l,x); } double boysF(int m, double x) { // Compute Boys' function // Check whether we are operating in the range where the Taylor series is OK if( x<=1.0 ) { // Taylor series uses -x x=-x; // (-x)^k double xk=1.0; // k! double kf=1.0; // Value of Boys' function double fm=0.0; // index k int k=0; while(k<=15) { // \f$ F_m(x) = \sum_{k=0}^\infty \frac {(-x)^k} { k! (2m+2k+1)} \f$ fm+=xk/(kf*(2*(m+k)+1)); k++; xk*=x; kf*=k; } return fm; } else if(x>=38.0) { // Use asymptotic expansion, which is precise to <1e-16 for F_n(x), n = 0 .. 60 return doublefact(2*m-1)/pow(2,m+1)*sqrt(M_PI/pow(x,2*m+1)); } else // Need to use the exact formula return 0.5*gsl_sf_gamma(m+0.5)*pow(x,-m-0.5)*gsl_sf_gamma_inc_P(m+0.5,x); } void boysF_arr(int mmax, double x, arma::vec & F) { // Resize array F.zeros(mmax+1); // Exp(-x) for recursion double emx=exp(-x); if(x<mmax) { // Fill in highest value F[mmax]=boysF(mmax,x); // and fill in the rest with downward recursion for(int m=mmax-1;m>=0;m--) F[m]=(2*x*F[m+1]+emx)/(2*m+1); } else { // Fill in lowest value F[0]=boysF(0,x); // and fill in the rest with upward recursion for(int m=1;m<=mmax;m++) F[m]=((2*m-1)*F[m-1]-emx)/(2.0*x); } } double hyperg_1F1(double a, double b, double x) { // Handle possible underflows with a Kummer transformation if(x>=-500.0) { return gsl_sf_hyperg_1F1(a,b,x); } else { return exp(x)*gsl_sf_hyperg_1F1(b-a,b,-x); } } double choose(int m, int n) { if(m<0 || n<0) { ERROR_INFO(); throw std::domain_error("Choose called with a negative argument!\n"); } return gsl_sf_choose(m,n); } int getind(int l, int m, int n) { // Silence compiler warning (void) l; // In the loop the indices will be int ii=m+n; int jj=n; // so the corresponding index is return ii*(ii+1)/2 + jj; } double max_abs(const arma::mat & R) { // Find maximum absolute value of matrix double m=0; double tmp; for(size_t i=0;i<R.n_rows;i++) for(size_t j=0;j<R.n_cols;j++) { tmp=fabs(R(i,j)); if(tmp>m) m=tmp; } return m; } double max_cabs(const arma::cx_mat & R) { // Find maximum absolute value of matrix double m=0; double tmp; for(size_t i=0;i<R.n_rows;i++) for(size_t j=0;j<R.n_cols;j++) { tmp=std::abs(R(i,j)); if(tmp>m) m=tmp; } return m; } double rms_norm(const arma::mat & R) { // Calculate \sum_ij R_ij^2 double rms=arma::trace(arma::trans(R)*R); // and convert to rms rms=sqrt(rms/(R.n_rows*R.n_cols)); return rms; } double rms_cnorm(const arma::cx_mat & R) { // Calculate \sum_ij R_ij^2 double rms=std::abs(arma::trace(arma::trans(R)*R)); // and convert to rms rms=sqrt(rms/(R.n_rows*R.n_cols)); return rms; } std::vector<double> spline_interpolation(const std::vector<double> & xt, const std::vector<double> & yt, const std::vector<double> & x) { if(xt.size()!=yt.size()) { ERROR_INFO(); std::ostringstream oss; oss << "xt and yt are of different lengths - " << xt.size() << " vs " << yt.size() << "!\n"; throw std::runtime_error(oss.str()); } // Returned data std::vector<double> y(x.size()); // Index accelerator gsl_interp_accel *acc=gsl_interp_accel_alloc(); // Interpolant gsl_interp *interp=gsl_interp_alloc(gsl_interp_cspline,xt.size()); // Initialize interpolant gsl_interp_init(interp,&(xt[0]),&(yt[0]),xt.size()); // Perform interpolation. for(size_t i=0;i<x.size();i++) { y[i]=gsl_interp_eval(interp,&(xt[0]),&(yt[0]),x[i],acc); } // Free memory gsl_interp_accel_free(acc); gsl_interp_free(interp); return y; } arma::vec spline_interpolation(const arma::vec & xtv, const arma::vec & ytv, const arma::vec & xv) { return arma::conv_to<arma::colvec>::from(spline_interpolation(arma::conv_to< std::vector<double> >::from(xtv), arma::conv_to< std::vector<double> >::from(ytv), arma::conv_to< std::vector<double> >::from(xv))); } double spline_interpolation(const std::vector<double> & xt, const std::vector<double> & yt, double x) { if(xt.size()!=yt.size()) { ERROR_INFO(); std::ostringstream oss; oss << "xt and yt are of different lengths - " << xt.size() << " vs " << yt.size() << "!\n"; throw std::runtime_error(oss.str()); } // Index accelerator gsl_interp_accel *acc=gsl_interp_accel_alloc(); // Interpolant gsl_interp *interp=gsl_interp_alloc(gsl_interp_cspline,xt.size()); // Initialize interpolant gsl_interp_init(interp,&(xt[0]),&(yt[0]),xt.size()); // Perform interpolation. double y=gsl_interp_eval(interp,&(xt[0]),&(yt[0]),x,acc); // Free memory gsl_interp_accel_free(acc); gsl_interp_free(interp); return y; } arma::mat randu_mat(size_t M, size_t N, unsigned long int seed) { // Use Mersenne Twister algorithm gsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937); // Set seed gsl_rng_set(r,seed); // Matrix arma::mat mat(M,N); // Fill it for(size_t i=0;i<M;i++) for(size_t j=0;j<N;j++) mat(i,j)=gsl_rng_uniform(r); // Free rng gsl_rng_free(r); return mat; } arma::mat randn_mat(size_t M, size_t N, unsigned long int seed) { // Use Mersenne Twister algorithm gsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937); // Set seed gsl_rng_set(r,seed); // Matrix arma::mat mat(M,N); // Fill it for(size_t i=0;i<M;i++) for(size_t j=0;j<N;j++) mat(i,j)=gsl_ran_gaussian(r,1.0); // Free rng gsl_rng_free(r); return mat; } arma::mat real_orthogonal(size_t N, unsigned long int seed) { arma::mat U(N,N); U.zeros(); // Generate totally random matrix arma::mat A=randn_mat(N,N,seed); // Perform QR decomposition on matrix arma::mat Q, R; bool ok=arma::qr(Q,R,A); if(!ok) { ERROR_INFO(); throw std::runtime_error("QR decomposition failure in complex_unitary.\n"); } // Check that Q is orthogonal arma::mat test=Q*arma::trans(Q); for(size_t i=0;i<test.n_cols;i++) test(i,i)-=1.0; double n=rms_norm(test); if(n>10*DBL_EPSILON) { ERROR_INFO(); throw std::runtime_error("Generated matrix is not unitary!\n"); } return Q; } arma::cx_mat complex_unitary(size_t N, unsigned long int seed) { arma::cx_mat U(N,N); U.zeros(); // Generate totally random matrix arma::cx_mat A=std::complex<double>(1.0,0.0)*randn_mat(N,N,seed) + std::complex<double>(0.0,1.0)*randn_mat(N,N,seed+1); // Perform QR decomposition on matrix arma::cx_mat Q, R; bool ok=arma::qr(Q,R,A); if(!ok) { ERROR_INFO(); throw std::runtime_error("QR decomposition failure in complex_unitary.\n"); } // Check that Q is unitary arma::cx_mat test=Q*arma::trans(Q); for(size_t i=0;i<test.n_cols;i++) test(i,i)-=1.0; double n=rms_cnorm(test); if(n>10*DBL_EPSILON) { ERROR_INFO(); throw std::runtime_error("Generated matrix is not unitary!\n"); } return Q; } double round(double x, unsigned n) { double fac=pow(10.0,n); return round(fac*x)/fac; } arma::vec find_minima(const arma::vec & x, const arma::vec & y, size_t runave, double thr) { if(x.n_elem != y.n_elem) { ERROR_INFO(); throw std::runtime_error("Input vectors are of inconsistent size!\n"); } // Create averaged vectors arma::vec xave(x.n_elem-2*runave); arma::vec yave(y.n_elem-2*runave); if(runave==0) { xave=x; yave=y; } else { for(arma::uword i=runave;i<x.n_elem-runave;i++) { xave(i-runave)=arma::mean(x.subvec(i-runave,i+runave)); yave(i-runave)=arma::mean(y.subvec(i-runave,i+runave)); } } // Find minima std::vector<size_t> minloc; if(yave(0)<yave(1)) minloc.push_back(0); for(arma::uword i=1;i<yave.n_elem-1;i++) if(yave(i)<yave(i-1) && yave(i)<yave(i+1)) minloc.push_back(i); if(yave(yave.n_elem-1)<yave(yave.n_elem-2)) minloc.push_back(yave.n_elem-1); // Check the minimum values for(size_t i=minloc.size()-1;i<minloc.size();i--) if(yave(minloc[i]) >= thr) minloc.erase(minloc.begin()+i); // Returned minima arma::vec ret(minloc.size()); for(size_t i=0;i<minloc.size();i++) ret(i)=xave(minloc[i]); return ret; }
24.09324
211
0.625774
[ "vector" ]
a706eec303f86667aaf535e0536c47b78274d1b8
839
cpp
C++
examples/track_shared/example.cpp
zsombi/sywu
e7a83d0b6e1da5aa66b68ad1f9c42fb2d6ab9b17
[ "MIT" ]
null
null
null
examples/track_shared/example.cpp
zsombi/sywu
e7a83d0b6e1da5aa66b68ad1f9c42fb2d6ab9b17
[ "MIT" ]
3
2020-12-14T09:23:56.000Z
2021-01-09T10:29:22.000Z
examples/track_shared/example.cpp
zsombi/sywu
e7a83d0b6e1da5aa66b68ad1f9c42fb2d6ab9b17
[ "MIT" ]
1
2020-12-10T13:50:42.000Z
2020-12-10T13:50:42.000Z
#include <comp/signal.hpp> #include <iostream> class Object : public comp::enable_shared_from_this<Object> { public: explicit Object() = default; }; int main() { comp::Signal<void()> signal; auto object = comp::make_shared<Object>(); // Note: capture shared objects as weak pointer! auto slot = [weakObject = comp::weak_ptr<Object>(object)]() { auto locked = weakObject.lock(); if (!locked) { return; } // Use the locked object. }; // Connect slot and bind tracker. auto connection = signal.connect(slot).bind(object); // Emit the signal. signal(); // Reset the object, then see the connection disconnected. object.reset(); if (!connection) { std::puts("The connection is disconnected."); } return 0; }
19.97619
63
0.595948
[ "object" ]
a708b1e8b1ca65a29116823b508c2a5a2b7370e8
2,405
cpp
C++
LeetCode/ThousandOne/0715-range_module.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
LeetCode/ThousandOne/0715-range_module.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
LeetCode/ThousandOne/0715-range_module.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
#include "leetcode.hpp" /* 715. Range 模块 Range 模块是跟踪数字范围的模块。你的任务是以一种有效的方式设计和实现以下接口。 addRange(int left, int right) 添加半开区间 [left, right),跟踪该区间中的每个实数。添加与当前跟踪的数字部分重叠的区间时,应当添加在区间 [left, right) 中尚未跟踪的任何数字到该区间中。 queryRange(int left, int right) 只有在当前正在跟踪区间 [left, right) 中的每一个实数时,才返回 true。 removeRange(int left, int right) 停止跟踪区间 [left, right) 中当前正在跟踪的每个实数。 示例: addRange(10, 20): null removeRange(14, 16): null queryRange(10, 14): true (区间 [10, 14) 中的每个数都正在被跟踪) queryRange(13, 15): false (未跟踪区间 [13, 15) 中像 14, 14.03, 14.17 这样的数字) queryRange(16, 17): true (尽管执行了删除操作,区间 [16, 17) 中的数字 16 仍然会被跟踪) 提示: 半开区间 [left, right) 表示所有满足 left <= x < right 的实数。 对 addRange, queryRange, removeRange 的所有调用中 0 < left < right < 10^9。 在单个测试用例中,对 addRange 的调用总数不超过 1000 次。 在单个测试用例中,对 queryRange 的调用总数不超过 5000 次。 在单个测试用例中,对 removeRange 的调用总数不超过 1000 次。 */ // https://leetcode.com/problems/range-module/discuss/108912/C%2B%2B-vector-O(n)-and-map-O(logn)-compare-two-solutions // 抄的 class RangeModule { vector<pair<int, int>> cur, tmp; public: RangeModule() {} void addRange(int left, int right) { size_t n = cur.size(); tmp.clear(); tmp.reserve(n); for (size_t i = 0; i <= n; ++i) { if (i == n || cur[i].first > right) { tmp.emplace_back(left, right); for (; i < n; ++i) tmp.push_back(cur[i]); } else if (cur[i].second < left) tmp.push_back(cur[i]); else { left = std::min(left, cur[i].first); right = std::max(right, cur[i].second); } } cur.swap(tmp); } bool queryRange(int left, int right) { size_t L = 0, R = cur.size(); while (L < R) { size_t M = (L + R) / 2; if (cur[M].first >= right) R = M; else if (cur[M].second <= left) L = M + 1; else return (cur[M].first <= left && right <= cur[M].second); } return false; } void removeRange(int left, int right) { size_t n = cur.size(); tmp.clear(); tmp.reserve(n); for (size_t i = 0; i < n; ++i) { if (cur[i].second <= left || cur[i].first >= right) tmp.push_back(cur[i]); else { if (cur[i].first < left) tmp.emplace_back(cur[i].first, left); if (cur[i].second > right) tmp.emplace_back(right, cur[i].second); } } cur.swap(tmp); } }; int main() { RangeModule rm; rm.addRange(10, 20); rm.removeRange(14, 16); OutBool(rm.queryRange(10, 14)); OutBool(rm.queryRange(12, 15)); OutBool(rm.queryRange(16, 17)); }
22.688679
121
0.624532
[ "vector" ]
a709c529be178dcfa7ff3990ac89f1b67c474e97
5,396
cpp
C++
GPUFilterRGBToYUVTestApp/widget.cpp
douzhongqiang/GPUFilterEngine
8b4a8595440331a0a2ace6cd91db24785a7a8350
[ "MIT" ]
4
2021-05-03T15:32:28.000Z
2021-08-31T11:45:40.000Z
GPUFilterRGBToYUVTestApp/widget.cpp
douzhongqiang/GPUFilterEngine
8b4a8595440331a0a2ace6cd91db24785a7a8350
[ "MIT" ]
1
2021-06-29T13:22:27.000Z
2021-06-29T13:22:27.000Z
GPUFilterRGBToYUVTestApp/widget.cpp
douzhongqiang/GPUFilterEngine
8b4a8595440331a0a2ace6cd91db24785a7a8350
[ "MIT" ]
3
2021-06-28T08:08:04.000Z
2021-08-31T11:45:46.000Z
#include "widget.h" #include <QVBoxLayout> #include <QFileDialog> #include "GPUFilterVideoDecodec.h" #include "YUVToRGBProcesser.h" #include "RGBToYUVProcesser.h" Widget::Widget(QWidget *parent) : QWidget(parent) { init(); // Create Video Decodec m_pVideoDecodec = new GPUFilterVideoDecodec(this); QObject::connect(m_pVideoDecodec, &GPUFilterVideoDecodec::updateDisplay, this, &Widget::onUpdateDisplay); m_pYUVToRGBProcesser = new YUVToRGBProcesser(this); m_pRGBToYUVProcesser = new RGBToYUVProcesser(this); } Widget::~Widget() { } void Widget::init(void) { QVBoxLayout* mainLayout = new QVBoxLayout(this); // Top Widget QWidget* pTopWidget = new QWidget; mainLayout->addWidget(pTopWidget); QHBoxLayout* pTopLayout = new QHBoxLayout(pTopWidget); pTopLayout->setMargin(0); // Tag Label QLabel* pTopLable = new QLabel(tr("YUVToRGB:")); pTopLayout->addWidget(pTopLable); // File Path m_pVideoFilePathLineEdit = new QLineEdit; pTopLayout->addWidget(m_pVideoFilePathLineEdit); // Browse QPushButton* pBroseButton = new QPushButton(tr("Brose")); pTopLayout->addWidget(pBroseButton); QObject::connect(pBroseButton, &QPushButton::clicked, this, &Widget::onClickedBroseVideoButton); // Begin Conver Button QPushButton* pBeginConvertButton = new QPushButton(tr("Begin Conver")); m_YUVToRGBButton = pBeginConvertButton; m_YUVToRGBButton->setEnabled(false); pTopLayout->addWidget(pBeginConvertButton); QObject::connect(pBeginConvertButton, &QPushButton::clicked, this, &Widget::onClickedConverYUVToRGBButton); // Bottom Widget QWidget* pBottomWidget = new QWidget; mainLayout->addWidget(pBottomWidget); // Bottom Tag QHBoxLayout* pBottomLaout = new QHBoxLayout(pBottomWidget); pBottomLaout->setMargin(0); QLabel* pBottomTag = new QLabel(tr("RGBToYUV:")); pBottomLaout->addWidget(pBottomTag); // File Path m_pImagePathLineEdit = new QLineEdit; pBottomLaout->addWidget(m_pImagePathLineEdit); // Image Button QPushButton* pImageButton = new QPushButton(tr("Brose")); pBottomLaout->addWidget(pImageButton); QObject::connect(pImageButton, &QPushButton::clicked, this, &Widget::onClickedBroseImageButton); // Begin Button QPushButton* pBeginButton = new QPushButton(tr("ConverToYUVImage")); pBottomLaout->addWidget(pBeginButton); m_RGBToYUVButton = pBeginButton; m_RGBToYUVButton->setEnabled(false); QObject::connect(pBeginButton, &QPushButton::clicked, this, &Widget::onClickedConverRGBToYUVButton); } void Widget::onClickedBroseVideoButton(void) { QString fileName = QFileDialog::getOpenFileName(this, "Open Video", "./"); if (fileName.isEmpty()) return; m_pVideoFilePathLineEdit->setText(fileName); m_YUVToRGBButton->setEnabled(true); } void Widget::onClickedConverYUVToRGBButton(void) { m_isRunningConver = !m_isRunningConver; if (m_isRunningConver) m_YUVToRGBButton->setText(tr("End Conver")); else m_YUVToRGBButton->setText(tr("Begin Conver")); if (m_isYUVToRGBInited) return; if (m_pVideoDecodec->openVideoFile(m_pVideoFilePathLineEdit->text())) m_pVideoDecodec->start(); } void Widget::onClickedBroseImageButton(void) { QString fileName = QFileDialog::getOpenFileName(this, "Open Video", "./"); if (fileName.isEmpty()) return; m_pImagePathLineEdit->setText(fileName); m_RGBToYUVButton->setEnabled(true); } void Widget::onClickedConverRGBToYUVButton(void) { // Init if (!m_isRGBToYUVInited) { m_pRGBToYUVProcesser->init(); m_isRGBToYUVInited = true; } // Resize QImage image(m_pImagePathLineEdit->text()); int nWidth = image.width() / 4; int nHeight = image.height() + image.height() / 2; m_pRGBToYUVProcesser->resize(nWidth, nHeight); // Set Image image = image.mirrored(); m_pRGBToYUVProcesser->setImage(image); // Render m_pRGBToYUVProcesser->render(); // Pack Image m_pRGBToYUVProcesser->packImage(); QImage tempImage = m_pRGBToYUVProcesser->packImage(); QString imageName = "%1/%2.bmp"; imageName = imageName.arg(qApp->applicationDirPath() + "/ConverImage/").arg("TestYUV"); tempImage.save(imageName); } void Widget::onUpdateDisplay(void) { if (m_pVideoDecodec == nullptr || !m_isRunningConver) return; QVector<QByteArray> yuvDatas; int type = 0; m_pVideoDecodec->getYUVData(yuvDatas, type); int nWidth, nHeight; m_pVideoDecodec->getVideoSize(nWidth, nHeight); if (!m_isYUVToRGBInited) { m_pYUVToRGBProcesser->init(); m_isYUVToRGBInited = true; } m_pYUVToRGBProcesser->resize(nWidth, nHeight); // Set YUV Data m_pYUVToRGBProcesser->setYData(yuvDatas[0], nWidth, nHeight); m_pYUVToRGBProcesser->setUData(yuvDatas[1], nWidth, nHeight); m_pYUVToRGBProcesser->setVData(yuvDatas[2], nWidth, nHeight); // Render m_pYUVToRGBProcesser->render(); // Save Image QImage image = m_pYUVToRGBProcesser->packImage(); static int number = 0; QString imageName = "%1/%2.bmp"; imageName = imageName.arg(qApp->applicationDirPath() + "/ConverImage/").arg(number++); qDebug() << imageName; image.save(imageName); //m_pRenderWidget->setYUVData(type, yuvDatas, nWidth, nHeight); }
30.314607
111
0.70404
[ "render" ]
a70ec8ea3caf8c0c72dd6bb76f6aa96bf0c5e82e
1,453
cpp
C++
src/tests/test_propertydouble.cpp
JoshuaSBrown/QC_Tools
35b23b483e1534a1a883f2480973ed54d371eaa4
[ "MIT" ]
28
2017-02-23T22:56:18.000Z
2021-12-11T01:56:12.000Z
src/tests/test_propertydouble.cpp
JoshuaSBrown/QC_Tools
35b23b483e1534a1a883f2480973ed54d371eaa4
[ "MIT" ]
32
2018-03-06T01:19:49.000Z
2021-03-06T06:25:54.000Z
src/tests/test_propertydouble.cpp
JoshuaSBrown/QC_Tools
35b23b483e1534a1a883f2480973ed54d371eaa4
[ "MIT" ]
14
2018-06-25T17:19:51.000Z
2022-02-21T06:52:10.000Z
#include "../libcatnip/io/arguments/properties/propertydouble.hpp" #include <cassert> #include <exception> #include <iostream> #include <string> #include <vector> using namespace catnip; using namespace std; int main(void) { cerr << "Testing: PropertyDouble" << endl; cerr << "Testing: constructor" << endl; { PropertyDouble propDouble; } cerr << "Testing: getPropertyName" << endl; { PropertyDouble propDouble; string name = propDouble.getPropertyName(); assert(name.compare("PROPERTY_DOUBLE") == 0); } cerr << "Testing: getPropertyOptions" << endl; { PropertyDouble propDouble; auto options = propDouble.getPropertyOptions(); string opt = options.at(0); assert(opt.compare("MIN") == 0); opt = options.at(1); assert(opt.compare("MAX") == 0); } cerr << "Testing: propValid" << endl; { PropertyDouble propDouble; bool valid = propDouble.propValid(0.0); assert(valid); } cerr << "Testing: setPropOption" << endl; { PropertyDouble propDouble; double val = -1.2; propDouble.setPropOption("MIN", val); propDouble.propValid(0.0); bool excep = false; try { val = -2.3; propDouble.propValid(val); } catch (...) { excep = true; } assert(excep); excep = false; try { val = 3.5; propDouble.setPropOption("MAXimum", val); } catch (...) { excep = true; } assert(excep); } return 0; }
21.057971
66
0.616655
[ "vector" ]
a714b7d6fad06067b64627cf3f20d680512d4f9a
1,723
cpp
C++
cpp/p62.cpp
voltrevo/project-euler
0db5451f72b1353b295e56f928c968801e054444
[ "MIT" ]
null
null
null
cpp/p62.cpp
voltrevo/project-euler
0db5451f72b1353b295e56f928c968801e054444
[ "MIT" ]
null
null
null
cpp/p62.cpp
voltrevo/project-euler
0db5451f72b1353b295e56f928c968801e054444
[ "MIT" ]
null
null
null
#include <algorithm> #include <deque> #include <iostream> #include <vector> #include "boost/cstdint.hpp" int main() { std::deque<std::pair<std::vector<int>, int> > cubes; for (boost::uint64_t i = 0; i != 300000; ++i) { cubes.push_back(std::pair<std::vector<int>, int>()); cubes.back().second = i; boost::uint64_t digits = i * i * i; while (digits > 0) { cubes.back().first.push_back(digits % 10); digits /= 10; } std::sort(cubes.back().first.begin(), cubes.back().first.end()); } std::sort(cubes.begin(), cubes.end()); int repeats = 0; std::pair<std::vector<int>, int> firstOfRun; std::deque<std::pair<int, int> > results; for (auto it = cubes.begin(); it != cubes.end(); ++it) { if (it->first == firstOfRun.first) { ++repeats; } else { if (repeats > 1) results.push_back(std::make_pair(repeats, firstOfRun.second)); repeats = 0; firstOfRun = *it; } } if (repeats > 1) results.push_back(std::make_pair(repeats, firstOfRun.second)); std::sort(results.begin(), results.end()); for ( std::deque<std::pair<int, int> >::reverse_iterator rit = results.rbegin(); rit != results.rend(); ++rit) { std::cout << rit->second << ", repeats: " << rit->first << std::endl; } for (auto it = cubes.begin(); it != cubes.end(); ++it) { for (int x : it->first) std::cout << x << ' '; std::cout << ", " << it->second << std::endl; } return 0; }
25.338235
82
0.487522
[ "vector" ]
a719af8c70000bc6c262b109507d783307fafa89
4,072
cpp
C++
third/qcustomplotdemo/frmexample/frmsincscatter.cpp
alexwang815/QWidgetDemo
293a8d9c40d686397829c5d415fc531b6956883e
[ "MulanPSL-1.0" ]
36
2020-04-27T06:56:30.000Z
2022-03-16T02:05:38.000Z
third/qcustomplotdemo/frmexample/frmsincscatter.cpp
alexwang815/QWidgetDemo
293a8d9c40d686397829c5d415fc531b6956883e
[ "MulanPSL-1.0" ]
null
null
null
third/qcustomplotdemo/frmexample/frmsincscatter.cpp
alexwang815/QWidgetDemo
293a8d9c40d686397829c5d415fc531b6956883e
[ "MulanPSL-1.0" ]
15
2021-11-01T14:42:53.000Z
2022-03-23T07:27:00.000Z
#include "frmsincscatter.h" #include "ui_frmsincscatter.h" #include "qdebug.h" frmSincScatter::frmSincScatter(QWidget *parent) : QWidget(parent), ui(new Ui::frmSincScatter) { ui->setupUi(this); this->initForm(); } frmSincScatter::~frmSincScatter() { delete ui; } void frmSincScatter::initForm() { ui->customPlot->legend->setVisible(true); ui->customPlot->legend->setFont(QFont("Helvetica", 9)); // set locale to english, so we get english decimal separator: ui->customPlot->setLocale(QLocale(QLocale::English, QLocale::UnitedKingdom)); // add confidence band graphs: ui->customPlot->addGraph(); QPen pen; pen.setStyle(Qt::DotLine); pen.setWidth(1); pen.setColor(QColor(180, 180, 180)); ui->customPlot->graph(0)->setName("Confidence Band 68%"); ui->customPlot->graph(0)->setPen(pen); ui->customPlot->graph(0)->setBrush(QBrush(QColor(255, 50, 30, 20))); ui->customPlot->addGraph(); ui->customPlot->legend->removeItem(ui->customPlot->legend->itemCount() - 1); // don't show two confidence band graphs in legend ui->customPlot->graph(1)->setPen(pen); ui->customPlot->graph(0)->setChannelFillGraph(ui->customPlot->graph(1)); // add theory curve graph: ui->customPlot->addGraph(); pen.setStyle(Qt::DashLine); pen.setWidth(2); pen.setColor(Qt::red); ui->customPlot->graph(2)->setPen(pen); ui->customPlot->graph(2)->setName("Theory Curve"); // add data point graph: ui->customPlot->addGraph(); ui->customPlot->graph(3)->setPen(QPen(Qt::blue)); ui->customPlot->graph(3)->setName("Measurement"); ui->customPlot->graph(3)->setLineStyle(QCPGraph::lsNone); ui->customPlot->graph(3)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCross, 4)); // add error bars: QCPErrorBars *errorBars = new QCPErrorBars(ui->customPlot->xAxis, ui->customPlot->yAxis); errorBars->removeFromLegend(); errorBars->setAntialiased(false); errorBars->setDataPlottable(ui->customPlot->graph(3)); errorBars->setPen(QPen(QColor(180, 180, 180))); // generate ideal sinc curve data and some randomly perturbed data for scatter plot: QVector<double> x0(250), y0(250); QVector<double> yConfUpper(250), yConfLower(250); for (int i = 0; i < 250; ++i) { x0[i] = (i / 249.0 - 0.5) * 30 + 0.01; // by adding a small offset we make sure not do divide by zero in next code line y0[i] = qSin(x0[i]) / x0[i]; // sinc function yConfUpper[i] = y0[i] + 0.15; yConfLower[i] = y0[i] - 0.15; x0[i] *= 1000; } QVector<double> x1(50), y1(50), y1err(50); for (int i = 0; i < 50; ++i) { // generate a gaussian distributed random number: double tmp1 = rand() / (double)RAND_MAX; double tmp2 = rand() / (double)RAND_MAX; double r = qSqrt(-2 * qLn(tmp1)) * qCos(2 * M_PI * tmp2); // box-muller transform for gaussian distribution // set y1 to value of y0 plus a random gaussian pertubation: x1[i] = (i / 50.0 - 0.5) * 30 + 0.25; y1[i] = qSin(x1[i]) / x1[i] + r * 0.15; x1[i] *= 1000; y1err[i] = 0.15; } // pass data to graphs and let Qui->customPlot determine the axes ranges so the whole thing is visible: ui->customPlot->graph(0)->setData(x0, yConfUpper); ui->customPlot->graph(1)->setData(x0, yConfLower); ui->customPlot->graph(2)->setData(x0, y0); ui->customPlot->graph(3)->setData(x1, y1); errorBars->setData(y1err); ui->customPlot->graph(2)->rescaleAxes(); ui->customPlot->graph(3)->rescaleAxes(true); // setup look of bottom tick labels: ui->customPlot->xAxis->setTickLabelRotation(30); ui->customPlot->xAxis->ticker()->setTickCount(9); ui->customPlot->xAxis->setNumberFormat("ebc"); ui->customPlot->xAxis->setNumberPrecision(1); ui->customPlot->xAxis->moveRange(-10); // make top right axes clones of bottom left axes. Looks prettier: ui->customPlot->axisRect()->setupFullAxesBox(); ui->customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom); }
42.863158
131
0.647102
[ "transform" ]
a71a3ad60a7f8327b4a60fc13f363aa8a49bdeca
6,632
cpp
C++
Atcoder/practice/f_encloseAll.cpp
Shahraaz/CP_P_S5
b068ad02d34338337e549d92a14e3b3d9e8df712
[ "MIT" ]
null
null
null
Atcoder/practice/f_encloseAll.cpp
Shahraaz/CP_P_S5
b068ad02d34338337e549d92a14e3b3d9e8df712
[ "MIT" ]
null
null
null
Atcoder/practice/f_encloseAll.cpp
Shahraaz/CP_P_S5
b068ad02d34338337e549d92a14e3b3d9e8df712
[ "MIT" ]
null
null
null
// Optimise #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; // #define MULTI_TEST #ifdef LOCAL #include "/home/shahraaz/bin/debug.h" #else #define db(...) #define pc(...) #endif #define f first #define s second #define pb push_back #define all(v) v.begin(), v.end() auto TimeStart = chrono::steady_clock::now(); auto seed = TimeStart.time_since_epoch().count(); std::mt19937 rng(seed); using ll = long long; template <typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <typename T> using Random = std::uniform_int_distribution<T>; const int NAX = 2e5 + 5, MOD = 1000000007; using point = complex<double>; const double EPS = 1e-8; class Solution { private: const double pi = acos(-1); double correct(double ang) { while (ang >= pi) ang -= pi; while (ang < 0) ang += pi; return ang; } public: Solution() {} ~Solution() {} void solveCase() { int n; vector<point> points; cin >> n; for (size_t i = 0; i < n; i++) { int x, y; cin >> x >> y; points.pb(point(x, y)); } double l = 0, r = 4000, ans = r; auto intersect = [&](pair<double, double> C1, double R1, pair<double, double> C2, double R2) { vector<pair<double, double>> res; auto x1 = C1.first; auto y1 = C1.second; auto x2 = C2.first; auto y2 = C2.second; double a = 2 * (x1 - x2); double b = 2 * (y1 - y2); double c = R2 * R2 - R1 * R1 - (x2 * x2 - x1 * x1) - (y2 * y2 - y1 * y1); if (abs(b) < EPS) { double x = c / a; double d = R1 * R1 - (x - x1) * (x - x1); if (d + EPS >= 0) { if (d < EPS) { d = 0; } d = sqrt(d); res.emplace_back(x, y1 + d); res.emplace_back(x, y1 - d); } } else { double aa = a / b; double bb = y1 - c / b; double A = 1 + aa * aa; double B = 2 * (aa * bb - x1); double C = -(R1 * R1 - x1 * x1 - bb * bb); double d = B * B - 4 * A * C; if (d + EPS >= 0) { if (d < 0) { d = 0; } d = sqrt(d); for (int i = -1; i < 2; i += 2) { double x = (-B + d * i) / (2 * A); double y = (c - a * x) / b; res.emplace_back(x, y); } } } return res; }; auto getIntersection = [&](int idx1, int idx2, double rad) -> pair<point, point> { auto ret = intersect({points[idx1].real(), points[idx1].imag()}, rad, {points[idx2].real(), points[idx2].imag()}, rad); if (ret.size() == 0) return {point(-1), point(-1)}; return {point(ret.front().f, ret.front().s), point(ret.back().f, ret.back().s)}; }; auto check = [&](double rad) -> bool { for (size_t i = 0; i < n; i++) { bool ok = true; for (size_t k = 0; k < n; k++) ok = ok && (rad >= (abs(points[k] - points[i])) - EPS); if (ok) return true; for (size_t j = i + 1; j < n; j++) { auto centres = getIntersection(i, j, rad); // db(centres, rad); if (centres.f.real() < 0) continue; // if (fabs(abs(centres.f - points[i])) > EPS || fabs(abs(centres.f - points[j])) > EPS) // { // db(points[i], points[j], centres, rad); // db(i, j, abs(centres.f - points[i]), abs(centres.f - points[j])); // // getIntersection(i, j, rad, true); // assert(false); // } // if (fabs(abs(centres.s - points[i])) > EPS || fabs(abs(centres.s - points[j])) > EPS) // { // db(points[i], points[j], centres, rad); // // db(i, j, abs(centres.f - points[i]), abs(centres.s - points[j])); // // getIntersection(i, j, rad, true); // assert(false); // } bool ok = true; for (size_t k = 0; k < n; k++) if (k == i || j == i) ; else ok = ok && (rad >= (abs(points[k] - centres.f)) - EPS); if (ok) return true; ok = true; for (size_t k = 0; k < n; k++) if (k == i || j == i) ; else ok = ok && (rad >= (abs(points[k] - centres.s) - EPS)); if (ok) return true; } } return false; }; int cnt = 200; while (cnt--) { auto findMin = [](double x, double y) { if (x < 1 || y < 1) return (x + y) / 2; return sqrt(x * y); }; auto mid = findMin(l, r); auto res = check(mid); db(l, r, mid, res); if (res) r = mid, ans = min(ans, mid); else l = mid; } cout << fixed << setprecision(10) << ans << '\n'; } }; int32_t main() { #ifndef LOCAL ios_base::sync_with_stdio(0); cin.tie(0); #endif int t = 1; #ifdef MULTI_TEST cin >> t; #endif Solution mySolver; for (int i = 1; i <= t; ++i) { mySolver.solveCase(); #ifdef TIME cerr << "Case #" << i << ": Time " << chrono::duration<double>(chrono::steady_clock::now() - TimeStart).count() << " s.\n"; TimeStart = chrono::steady_clock::now(); #endif } return 0; }
31.43128
131
0.382841
[ "vector" ]
a71a8dcd06beb3b464aa77d8b5eb24160ae47b83
3,777
hpp
C++
src/ngraph/shape_util.hpp
magrawal128/ngraph
ca911487d1eadfe6ec66dbe3da6f05cee3645b24
[ "Apache-2.0" ]
1
2021-10-04T21:55:19.000Z
2021-10-04T21:55:19.000Z
src/ngraph/shape_util.hpp
biswajitcsecu/ngraph
d6bff37d7968922ef81f3bed63379e849fcf3b45
[ "Apache-2.0" ]
1
2019-02-20T20:56:47.000Z
2019-02-22T20:10:28.000Z
src/ngraph/shape_util.hpp
biswajitcsecu/ngraph
d6bff37d7968922ef81f3bed63379e849fcf3b45
[ "Apache-2.0" ]
null
null
null
//***************************************************************************** // Copyright 2017-2019 Intel Corporation // // 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 "ngraph/partial_shape.hpp" namespace ngraph { template <typename AXIS_VALUES> AXIS_VALUES project(const AXIS_VALUES& axis_values, const AxisSet& axes) { AXIS_VALUES result; for (size_t i = 0; i < axis_values.size(); i++) { if (axes.find(i) != axes.end()) { result.push_back(axis_values[i]); } } return result; } template <> PartialShape project(const PartialShape& shape, const AxisSet& axes); // Removes some values from a vector of axis values template <typename AXIS_VALUES> AXIS_VALUES reduce(const AXIS_VALUES& axis_values, const AxisSet& deleted_axes) { AxisSet axes; for (size_t i = 0; i < axis_values.size(); i++) { if (deleted_axes.find(i) == deleted_axes.end()) { axes.insert(i); } } return project(axis_values, axes); } template <> PartialShape reduce(const PartialShape& shape, const AxisSet& deleted_axes); // TODO: check validity, i.e. that the new axis indices are all less than // axis_values.size()+num_new_axes. // Add new values at particular axis positions template <typename AXIS_VALUES, typename AXIS_VALUE> AXIS_VALUES inject_pairs(const AXIS_VALUES& axis_values, std::vector<std::pair<size_t, AXIS_VALUE>> new_axis_pos_value_pairs) { AXIS_VALUES result; size_t original_pos = 0; for (size_t result_pos = 0; result_pos < axis_values.size() + new_axis_pos_value_pairs.size(); result_pos++) { // Would be nice to use std::find_if here but would rather not #include <algorithm> in // this header auto search_it = new_axis_pos_value_pairs.begin(); while (search_it != new_axis_pos_value_pairs.end()) { if (search_it->first == result_pos) { break; } ++search_it; } if (search_it == new_axis_pos_value_pairs.end()) { result.push_back(axis_values[original_pos++]); } else { result.push_back(search_it->second); } } return result; } template <> PartialShape inject_pairs(const PartialShape& shape, std::vector<std::pair<size_t, Dimension>> new_axis_pos_value_pairs); // Add a new value at a particular axis position template <typename AXIS_VALUES, typename AXIS_VALUE> AXIS_VALUES inject(const AXIS_VALUES& axis_values, size_t new_axis_pos, AXIS_VALUE new_axis_val) { return inject_pairs(axis_values, std::vector<std::pair<size_t, AXIS_VALUE>>{ std::pair<size_t, AXIS_VALUE>(new_axis_pos, new_axis_val)}); } }
32.560345
100
0.574001
[ "shape", "vector" ]
a7206baeb34c815e1730384e51eccd52fa7323d0
11,377
cc
C++
arcane/ceapart/src/arcane/mathlink/mathlink.cc
JeromeDuboisPro/framework
d88925495e3787fdaf640c29728dcac385160188
[ "Apache-2.0" ]
null
null
null
arcane/ceapart/src/arcane/mathlink/mathlink.cc
JeromeDuboisPro/framework
d88925495e3787fdaf640c29728dcac385160188
[ "Apache-2.0" ]
null
null
null
arcane/ceapart/src/arcane/mathlink/mathlink.cc
JeromeDuboisPro/framework
d88925495e3787fdaf640c29728dcac385160188
[ "Apache-2.0" ]
null
null
null
// -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*- //----------------------------------------------------------------------------- // Copyright 2000-2021 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com) // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: Apache-2.0 //----------------------------------------------------------------------------- /*---------------------------------------------------------------------------*/ /* mathlink.cc (C) 2013 */ /* */ /*---------------------------------------------------------------------------*/ #include "arcane/IApplication.h" #include "arcane/IParallelMng.h" #include "arcane/AbstractService.h" #include "arcane/FactoryService.h" #include "arcane/IVariableMng.h" #include "arcane/SharedVariable.h" #include "arcane/CommonVariables.h" #include "arcane/IMesh.h" #include "arcane/IItemFamily.h" #include <arcane/MathUtils.h> #include <arcane/Timer.h> #include <arcane/IParallelMng.h> #include <arcane/ITimeLoopMng.h> #include <mathlink.h> #include <arcane/mathlink/mathlink.h> /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ ARCANE_BEGIN_NAMESPACE // **************************************************************************** // * mathlink // **************************************************************************** mathlink::mathlink(const ServiceBuildInfo & sbi): AbstractService(sbi), m_sub_domain(sbi.subDomain()), mathenv(NULL), mathlnk(NULL), mathtmr(new Timer(m_sub_domain,"mathlink",Timer::TimerReal)){} // **************************************************************************** // * ~mathlink // **************************************************************************** mathlink::~mathlink(){} // **************************************************************************** // * link // **************************************************************************** void mathlink::link(){ int error; // Il n'y a que le master en 0 qui se link à Mathematica if (m_sub_domain->parallelMng()->commRank()!=0) return; debug()<<"[mathlink::link]"<<" linking?" <<" (commSize=" << m_sub_domain->parallelMng()->commSize() <<", commRank=" << m_sub_domain->parallelMng()->commRank()<<")"; { // Initializes the MathLink environment object and passes parameters in p mathenv = MLInitialize((char *)NULL); if(mathenv == (MLENV)NULL) throw Arcane::FatalErrorException(A_FUNCINFO, "Unable to initialize the MathLink environment"); debug()<<"[mathlink::link] initialized!"; } { // Opens a MathLink connection taking parameters from a character string // -linkhost localhost /cea/produits1/mathematica-8.0.0/Executables/math // pkill -9 MathKernel // SharedMemory char master_string[]="-linkname /cea/produits1/mathematica-8.0.0/Executables/math -mathlink -linkmode launch -linkprotocol SharedMemory"; char slave_string[] ="-linkname /cea/produits1/mathematica-8.0.0/Executables/math -mathlink -linkmode connect -linkprotocol tcpip"; if (m_sub_domain->parallelMng()->commRank()==0){ mathlnk = MLOpenString(mathenv, master_string, &error); }else{ mathlnk = MLOpenString(mathenv, slave_string, &error); } if ((mathlnk==(MLINK)NULL)||(error!=MLEOK)) throw Arcane::FatalErrorException(A_FUNCINFO, "Unable to create the link"); } { // Activates a MathLink connection, waiting for the program at the other end to respond. if (!MLActivate(mathlnk)) throw Arcane::FatalErrorException(A_FUNCINFO, "Unable to establish communication"); info()<<"Mathematica launched on rank #"<<m_sub_domain->parallelMng()->commRank(); } } // **************************************************************************** // * unlink // **************************************************************************** void mathlink::unlink(){ info()<<__FUNCTION__<<" MLClose"; if (!mathlnk) return; MLPutFunction(mathlnk, "Exit", 0); // Closes a MathLink connection MLClose(mathlnk); info()<<__FUNCTION__<<" MLDeinitialize"; if (!mathenv) return; // Destructs the MathLink environment object MLDeinitialize(mathenv); } // **************************************************************************** // * statics to read outputs // **************************************************************************** static int read_and_print_expression( MLINK lp); static int read_and_print_atom( MLINK lp, int tag){ const char *s; if( tag == MLTKSTR) putchar( '"'); if( MLGetString( lp, &s)){ printf( "%s", s); //MLDisownString( lp, s); ARCANE_FATAL("MLDisownString is unknown"); } if( tag == MLTKSTR) putchar( '"'); putchar( ' '); return MLError( lp) == MLEOK; } static int read_and_print_function( MLINK lp){ int len, i; static int indent; if( ! MLGetArgCount( lp, &len)) return 0; indent += 3; printf( "\n%*.*s", indent, indent, ""); if( read_and_print_expression( lp) == 0) return 0; printf( "["); for( i = 1; i <= len; ++i) { if( read_and_print_expression( lp) == 0) return 0; if( i < len) printf( ", "); } printf( "]"); indent -= 3; return 1; } static int read_and_print_expression( MLINK lp){ int tag; switch (tag = MLGetNext( lp)) { case MLTKSYM: case MLTKSTR: case MLTKINT: case MLTKREAL: return read_and_print_atom(lp, tag); case MLTKFUNC: return read_and_print_function(lp); case MLTKERROR:{ printf("MLTKERROR!\n"); break; } default: printf("\nread_and_print_expression default!"); } return 0; } // **************************************************************************** // * skip any packets before the first ReturnPacket // **************************************************************************** void mathlink::skipAnyPacketsBeforeTheFirstReturnPacket(){ int pkt; while( (pkt = MLNextPacket(mathlnk), pkt) && pkt != RETURNPKT) { MLNewPacket(mathlnk); if (MLError(mathlnk)) mathlink::error(); } } // **************************************************************************** // * Prime // * gives the nth prime number // **************************************************************************** Integer mathlink::Prime(Integer n){ mlint64 prime; if (n==0) return 1; debug()<<"[mathlink::Prime] n=" << n; MLPutFunction(mathlnk, "EvaluatePacket", 1L); MLPutFunction(mathlnk, "Prime", 1L); MLPutInteger64(mathlnk, n); MLEndPacket(mathlnk); skipAnyPacketsBeforeTheFirstReturnPacket(); if (MLGetNext(mathlnk)!=MLTKINT) mathlink::error(); MLGetInteger64(mathlnk, &prime); debug()<<"[mathlink::Prime] returning " << prime; return prime; } // **************************************************************************** // * tests // **************************************************************************** void mathlink::tests(){ testFactorInteger(7420738134810L); UniqueArray<Integer> coefs; coefs.add(3); coefs.add(4); coefs.add(7); testLinearProgramming(coefs.view()); } // **************************************************************************** // * testFactorInteger // **************************************************************************** void mathlink::testFactorInteger(Int64 n){ info()<<__FUNCTION__<<" is now factoring "<<n; { int pkt, expt; mlint64 prime; long len, lenp, k; Timer::Sentry ts(mathtmr); MLPutFunction(mathlnk, "EvaluatePacket", 1L); MLPutFunction(mathlnk, "FactorInteger", 1L); MLPutInteger64(mathlnk, n); MLEndPacket(mathlnk); while( (pkt = MLNextPacket(mathlnk), pkt) && pkt != RETURNPKT) { MLNewPacket(mathlnk); if (MLError(mathlnk)) mathlink::error(); } if (!MLCheckFunction(mathlnk, "List", &len)) mathlink::error(); for (k = 1; k <= len; k++) { if (MLCheckFunction(mathlnk, "List", &lenp) && lenp == 2 && MLGetInteger64(mathlnk, &prime) && MLGetInteger(mathlnk, &expt) ){ info()<<prime<<"^"<< expt; }else mathlink::error(); } } info()<<__FUNCTION__<<" "<<mathtmr->lastActivationTime()<<"s"; } // **************************************************************************** // * testLinearProgramming // **************************************************************************** void mathlink::testLinearProgramming(ArrayView<Integer> coefs){ { int pkt,sol; long len,k; Timer::Sentry ts(mathtmr); MLPutFunction(mathlnk, "EvaluatePacket", 1); MLPutFunction(mathlnk, "LinearProgramming", 5); int c[]={1,1,1,1,1,1}; int m[5][6]={{7, 4, 3, 0, 0, 0}, {0, 0, 0, 7, 4, 3}, {1, 0, 0, 1, 0, 0}, {0, 1, 0, 0, 1, 0}, {0, 0, 1, 0, 0, 1}}; int b[5][2]={{9, -1}, {9, -1}, {1, 0}, {1, 0}, {1, 0}}; int l[6][2]={{0, 1}, {0, 1}, {0, 1}, {0, 1}, {0, 1}, {0, 1}}; MLPutIntegerList(mathlnk, c, 6); MLPutFunction(mathlnk, "List", 5); MLPutIntegerList(mathlnk, m[0], 6); MLPutIntegerList(mathlnk, m[1], 6); MLPutIntegerList(mathlnk, m[2], 6); MLPutIntegerList(mathlnk, m[3], 6); MLPutIntegerList(mathlnk, m[4], 6); MLPutFunction(mathlnk, "List", 5); MLPutIntegerList(mathlnk, b[0], 2); MLPutIntegerList(mathlnk, b[1], 2); MLPutIntegerList(mathlnk, b[2], 2); MLPutIntegerList(mathlnk, b[3], 2); MLPutIntegerList(mathlnk, b[4], 2); MLPutFunction(mathlnk, "List", 6); MLPutIntegerList(mathlnk, l[0], 2); MLPutIntegerList(mathlnk, l[1], 2); MLPutIntegerList(mathlnk, l[2], 2); MLPutIntegerList(mathlnk, l[3], 2); MLPutIntegerList(mathlnk, l[4], 2); MLPutIntegerList(mathlnk, l[5], 2); MLPutFunction(mathlnk, "List", 6); MLPutSymbol(mathlnk, "Integers"); MLPutSymbol(mathlnk, "Integers"); MLPutSymbol(mathlnk, "Integers"); MLPutSymbol(mathlnk, "Integers"); MLPutSymbol(mathlnk, "Integers"); MLPutSymbol(mathlnk, "Integers"); MLEndPacket(mathlnk); while( (pkt = MLNextPacket(mathlnk), pkt) && pkt != RETURNPKT) { MLNewPacket(mathlnk); if (MLError(mathlnk)) mathlink::error(); } if (!MLCheckFunction(mathlnk, "List", &len)) mathlink::error(); for (k = 1; k <= len; k++) { if (MLGetInteger(mathlnk, &sol)){ info()<<sol; }else mathlink::error(); } } info()<<__FUNCTION__<<" "<<mathtmr->lastActivationTime()<<"s"; } // **************************************************************************** // * error // **************************************************************************** void mathlink::error(){ if (MLError(mathlnk)) throw Arcane::FatalErrorException(A_FUNCINFO, MLErrorMessage(mathlnk)); else throw Arcane::FatalErrorException(A_FUNCINFO,"Error detected by mathlink.\n"); } ARCANE_REGISTER_SUB_DOMAIN_FACTORY(mathlink, mathlink, mathlink); /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ ARCANE_END_NAMESPACE /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/
34.898773
141
0.497319
[ "object" ]
a72071fc7cc38223aa76b9d4f6582f2061b25fcc
30,072
cc
C++
tests/module_tests/checkpoint_test.cc
hisundar/ep-engine
7f7cb5b4a5528c17ae10d2d5bb644885d1cd0837
[ "Apache-2.0" ]
null
null
null
tests/module_tests/checkpoint_test.cc
hisundar/ep-engine
7f7cb5b4a5528c17ae10d2d5bb644885d1cd0837
[ "Apache-2.0" ]
null
null
null
tests/module_tests/checkpoint_test.cc
hisundar/ep-engine
7f7cb5b4a5528c17ae10d2d5bb644885d1cd0837
[ "Apache-2.0" ]
null
null
null
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2011 Couchbase, Inc * * 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. */ #include "config.h" #include <signal.h> #include <algorithm> #include <set> #include <vector> #include "checkpoint.h" #include "stats.h" #include "vbucket.h" #include <gtest/gtest.h> #ifdef _MSC_VER #define alarm(a) #endif #define NUM_TAP_THREADS 3 #define NUM_SET_THREADS 4 #define NUM_ITEMS 10000 #define DCP_CURSOR_PREFIX "dcp-client-" #define TAP_CURSOR_PREFIX "tap-client-" struct thread_args { SyncObject *mutex; SyncObject *gate; RCPtr<VBucket> vbucket; CheckpointManager *checkpoint_manager; int *counter; std::string name; }; extern "C" { static rel_time_t basic_current_time(void) { return 0; } rel_time_t (*ep_current_time)() = basic_current_time; time_t ep_real_time() { return time(NULL); } /** * Dummy callback to replace the flusher callback. */ class DummyCB: public Callback<uint16_t> { public: DummyCB() {} void callback(uint16_t &dummy) { (void) dummy; } }; // Test fixture for Checkpoint tests. Once constructed provides a checkpoint // manager and single vBucket (VBID 0). class CheckpointTest : public ::testing::Test { protected: CheckpointTest() : callback(new DummyCB()), vbucket(new VBucket(0, vbucket_state_active, global_stats, checkpoint_config, /*kvshard*/NULL, /*lastSeqno*/1000, /*lastSnapStart*/0, /*lastSnapEnd*/0, /*table*/NULL, callback)) { createManager(); } void createManager() { manager.reset(new CheckpointManager(global_stats, vbucket->getId(), checkpoint_config, /*lastSeqno*/1000, /*lastSnapStart*/0,/*lastSnapEnd*/0, callback)); } EPStats global_stats; CheckpointConfig checkpoint_config; std::shared_ptr<Callback<uint16_t> > callback; RCPtr<VBucket> vbucket; std::unique_ptr<CheckpointManager> manager; }; static void launch_persistence_thread(void *arg) { struct thread_args *args = static_cast<struct thread_args *>(arg); std::unique_lock<std::mutex> lh(*(args->mutex)); std::unique_lock<std::mutex> lhg(*(args->gate)); ++(*(args->counter)); lhg.unlock(); args->gate->notify_all(); args->mutex->wait(lh); lh.unlock(); bool flush = false; while(true) { size_t itemPos; std::vector<queued_item> items; const std::string cursor(CheckpointManager::pCursorName); args->checkpoint_manager->getAllItemsForCursor(cursor, items); for(itemPos = 0; itemPos < items.size(); ++itemPos) { queued_item qi = items.at(itemPos); if (qi->getOperation() == queue_op_flush) { flush = true; break; } } if (flush) { // Checkpoint start and end operations may have been introduced in // the items queue after the "flush" operation was added. Ignore // these. Anything else will be considered an error. for(size_t i = itemPos + 1; i < items.size(); ++i) { queued_item qi = items.at(i); EXPECT_TRUE(queue_op_checkpoint_start == qi->getOperation() || queue_op_checkpoint_end == qi->getOperation()) << "Unexpected operation:" << qi->getOperation(); } break; } } EXPECT_TRUE(flush); } static void launch_tap_client_thread(void *arg) { struct thread_args *args = static_cast<struct thread_args *>(arg); std::unique_lock<std::mutex> lh(*(args->mutex)); std::unique_lock<std::mutex> lhg(*(args->gate)); ++(*(args->counter)); lhg.unlock(); args->gate->notify_all(); args->mutex->wait(lh); lh.unlock(); bool flush = false; bool isLastItem = false; while(true) { queued_item qi = args->checkpoint_manager->nextItem(args->name, isLastItem); if (qi->getOperation() == queue_op_flush) { flush = true; break; } } EXPECT_TRUE(flush); } static void launch_checkpoint_cleanup_thread(void *arg) { struct thread_args *args = static_cast<struct thread_args *>(arg); std::unique_lock<std::mutex> lh(*(args->mutex)); std::unique_lock<std::mutex> lhg(*(args->gate)); ++(*(args->counter)); lhg.unlock(); args->gate->notify_all(); args->mutex->wait(lh); lh.unlock(); while (args->checkpoint_manager->getNumOfCursors() > 1) { bool newCheckpointCreated; args->checkpoint_manager->removeClosedUnrefCheckpoints(args->vbucket, newCheckpointCreated); } } static void launch_set_thread(void *arg) { struct thread_args *args = static_cast<struct thread_args *>(arg); std::unique_lock<std::mutex> lh(*(args->mutex)); std::unique_lock<std::mutex> lhg(*(args->gate)); ++(*(args->counter)); lhg.unlock(); args->gate->notify_all(); args->mutex->wait(lh); lh.unlock(); int i(0); for (i = 0; i < NUM_ITEMS; ++i) { std::stringstream key; key << "key-" << i; queued_item qi(new Item(key.str(), args->vbucket->getId(), queue_op_set, 0, 0)); args->checkpoint_manager->queueDirty(args->vbucket, qi, true); } } } TEST_F(CheckpointTest, basic_chk_test) { std::shared_ptr<Callback<uint16_t> > cb(new DummyCB()); RCPtr<VBucket> vbucket(new VBucket(0, vbucket_state_active, global_stats, checkpoint_config, NULL, 0, 0, 0, NULL, cb)); CheckpointManager *checkpoint_manager = new CheckpointManager(global_stats, 0, checkpoint_config, 1, 0, 0, cb); SyncObject *mutex = new SyncObject(); SyncObject *gate = new SyncObject(); int *counter = new int; *counter = 0; cb_thread_t tap_threads[NUM_TAP_THREADS]; cb_thread_t set_threads[NUM_SET_THREADS]; cb_thread_t persistence_thread; cb_thread_t checkpoint_cleanup_thread; int i(0), rc(0); struct thread_args t_args; t_args.checkpoint_manager = checkpoint_manager; t_args.vbucket = vbucket; t_args.mutex = mutex; t_args.gate = gate; t_args.counter = counter; struct thread_args tap_t_args[NUM_TAP_THREADS]; for (i = 0; i < NUM_TAP_THREADS; ++i) { std::string name(TAP_CURSOR_PREFIX + std::to_string(i)); tap_t_args[i].checkpoint_manager = checkpoint_manager; tap_t_args[i].vbucket = vbucket; tap_t_args[i].mutex = mutex; tap_t_args[i].gate = gate; tap_t_args[i].counter = counter; tap_t_args[i].name = name; checkpoint_manager->registerCursor(name, 1, false, MustSendCheckpointEnd::YES); } // Start a timer so that the test can be killed if it doesn't finish in a // reasonable amount of time alarm(60); rc = cb_create_thread(&persistence_thread, launch_persistence_thread, &t_args, 0); EXPECT_EQ(0, rc); rc = cb_create_thread(&checkpoint_cleanup_thread, launch_checkpoint_cleanup_thread, &t_args, 0); EXPECT_EQ(0, rc); for (i = 0; i < NUM_TAP_THREADS; ++i) { rc = cb_create_thread(&tap_threads[i], launch_tap_client_thread, &tap_t_args[i], 0); EXPECT_EQ(0, rc); } for (i = 0; i < NUM_SET_THREADS; ++i) { rc = cb_create_thread(&set_threads[i], launch_set_thread, &t_args, 0); EXPECT_EQ(0, rc); } // Wait for all threads to reach the starting gate while (true) { std::unique_lock<std::mutex> lh(*gate); if (*counter == (NUM_TAP_THREADS + NUM_SET_THREADS + 2)) { break; } gate->wait(lh); } sleep(1); mutex->notify_all(); for (i = 0; i < NUM_SET_THREADS; ++i) { rc = cb_join_thread(set_threads[i]); EXPECT_EQ(0, rc); } // Push the flush command into the queue so that all other threads can be terminated. std::string key("flush"); queued_item qi(new Item(key, vbucket->getId(), queue_op_flush, 0xffff, 0)); checkpoint_manager->queueDirty(vbucket, qi, true); rc = cb_join_thread(persistence_thread); EXPECT_EQ(0, rc); for (i = 0; i < NUM_TAP_THREADS; ++i) { rc = cb_join_thread(tap_threads[i]); EXPECT_EQ(0, rc); std::stringstream name; name << "tap-client-" << i; checkpoint_manager->removeCursor(name.str()); } rc = cb_join_thread(checkpoint_cleanup_thread); EXPECT_EQ(0, rc); delete checkpoint_manager; delete gate; delete mutex; delete counter; } TEST_F(CheckpointTest, reset_checkpoint_id) { std::shared_ptr<Callback<uint16_t> > cb(new DummyCB()); RCPtr<VBucket> vbucket(new VBucket(0, vbucket_state_active, global_stats, checkpoint_config, NULL, 0, 0, 0, NULL, cb)); CheckpointManager *manager = new CheckpointManager(global_stats, 0, checkpoint_config, 1, 0, 0, cb); int i; for (i = 0; i < 10; ++i) { std::stringstream key; key << "key-" << i; queued_item qi(new Item(key.str(), vbucket->getId(), queue_op_set, 0, 0)); manager->queueDirty(vbucket, qi, true); } manager->createNewCheckpoint(); size_t itemPos; uint64_t chk = 1; size_t lastMutationId = 0; std::vector<queued_item> items; const std::string cursor(CheckpointManager::pCursorName); manager->getAllItemsForCursor(cursor, items); for(itemPos = 0; itemPos < items.size(); ++itemPos) { queued_item qi = items.at(itemPos); if (qi->getOperation() != queue_op_checkpoint_start && qi->getOperation() != queue_op_checkpoint_end) { size_t mid = qi->getBySeqno(); EXPECT_GT(mid, lastMutationId); lastMutationId = qi->getBySeqno(); } if (itemPos == 0 || itemPos == (items.size() - 1)) { EXPECT_EQ(queue_op_checkpoint_start, qi->getOperation()) << "For itemPos:" << itemPos; } else if (itemPos == (items.size() - 2)) { EXPECT_EQ(queue_op_checkpoint_end, qi->getOperation()) << "For itemPos:" << itemPos; chk++; } else { EXPECT_EQ(queue_op_set, qi->getOperation()) << "For itemPos:" << itemPos; } } EXPECT_EQ(13, items.size()); items.clear(); manager->checkAndAddNewCheckpoint(1, vbucket); manager->getAllItemsForCursor(cursor, items); EXPECT_EQ(0, items.size()); delete manager; } // Sanity check test fixture TEST_F(CheckpointTest, CheckFixture) { // Should intially have a single cursor (persistence). EXPECT_EQ(1, manager->getNumOfCursors()); EXPECT_EQ(1, manager->getNumOpenChkItems()); for (auto& cursor : manager->getAllCursors()) { EXPECT_EQ(CheckpointManager::pCursorName, cursor.first); } // Should initially be zero items to persist. EXPECT_EQ(0, manager->getNumItemsForCursor(CheckpointManager::pCursorName)); } // Basic test of a single, open checkpoint. TEST_F(CheckpointTest, OneOpenCkpt) { // Queue a set operation. queued_item qi(new Item("key1", vbucket->getId(), queue_op_set, /*revSeq*/20, /*bySeq*/0)); // No set_ops in queue, expect queueDirty to return true (increase // persistence queue size). EXPECT_TRUE(manager->queueDirty(vbucket, qi, true)); EXPECT_EQ(1, manager->getNumCheckpoints()); // Single open checkpoint. EXPECT_EQ(2, manager->getNumOpenChkItems()); // 1x op_checkpoint_start, 1x op_set EXPECT_EQ(1001, qi->getBySeqno()); EXPECT_EQ(20, qi->getRevSeqno()); EXPECT_EQ(1, manager->getNumItemsForCursor(CheckpointManager::pCursorName)); // Adding the same key again shouldn't increase the size. queued_item qi2(new Item("key1", vbucket->getId(), queue_op_set, /*revSeq*/21, /*bySeq*/0)); EXPECT_FALSE(manager->queueDirty(vbucket, qi2, true)); EXPECT_EQ(1, manager->getNumCheckpoints()); EXPECT_EQ(2, manager->getNumOpenChkItems()); EXPECT_EQ(1002, qi2->getBySeqno()); EXPECT_EQ(21, qi2->getRevSeqno()); EXPECT_EQ(1, manager->getNumItemsForCursor(CheckpointManager::pCursorName)); // Adding a different key should increase size. queued_item qi3(new Item("key2", vbucket->getId(), queue_op_set, /*revSeq*/0, /*bySeq*/0)); EXPECT_TRUE(manager->queueDirty(vbucket, qi3, true)); EXPECT_EQ(1, manager->getNumCheckpoints()); EXPECT_EQ(3, manager->getNumOpenChkItems()); EXPECT_EQ(1003, qi3->getBySeqno()); EXPECT_EQ(0, qi3->getRevSeqno()); EXPECT_EQ(2, manager->getNumItemsForCursor(CheckpointManager::pCursorName)); } // Test with one open and one closed checkpoint. TEST_F(CheckpointTest, OneOpenOneClosed) { // Add some items to the initial (open) checkpoint. for (auto i : {1,2}) { queued_item qi(new Item("key" + std::to_string(i), vbucket->getId(), queue_op_set, /*revSeq*/0, /*bySeq*/0)); EXPECT_TRUE(manager->queueDirty(vbucket, qi, true)); } EXPECT_EQ(1, manager->getNumCheckpoints()); EXPECT_EQ(3, manager->getNumOpenChkItems()); // 1x op_checkpoint_start, 2x op_set EXPECT_EQ(3, manager->getNumItems()); const uint64_t ckpt_id1 = manager->getOpenCheckpointId(); // Create a new checkpoint (closing the current open one). const uint64_t ckpt_id2 = manager->createNewCheckpoint(); EXPECT_NE(ckpt_id1, ckpt_id2) << "New checkpoint ID should differ from old"; EXPECT_EQ(ckpt_id1, manager->getLastClosedCheckpointId()); EXPECT_EQ(1, manager->getNumOpenChkItems()); // 1x op_checkpoint_start // Add some items to the newly-opened checkpoint (note same keys as 1st // ckpt). for (auto ii : {1,2}) { queued_item qi(new Item("key" + std::to_string(ii), vbucket->getId(), queue_op_set, /*revSeq*/1, /*bySeq*/0)); EXPECT_TRUE(manager->queueDirty(vbucket, qi, true)); } EXPECT_EQ(2, manager->getNumCheckpoints()); EXPECT_EQ(3, manager->getNumOpenChkItems()); // 1x op_checkpoint_start, 2x op_set EXPECT_EQ(3 + 4, manager->getNumItems()); // open items + 1x op_ckpt_start, 2x op_set, 1x op_ckpt_end // Examine the items - should be 2 lots of two keys. EXPECT_EQ(4, manager->getNumItemsForCursor(CheckpointManager::pCursorName)); } // Test the automatic creation of checkpoints based on the number of items. TEST_F(CheckpointTest, ItemBasedCheckpointCreation) { // Size down the default number of items to create a new checkpoint and // recreate the manager checkpoint_config = CheckpointConfig(DEFAULT_CHECKPOINT_PERIOD, MIN_CHECKPOINT_ITEMS, /*numCheckpoints*/2, /*itemBased*/true, /*keepClosed*/false, /*enableMerge*/false); createManager(); // Sanity check initial state. EXPECT_EQ(1, manager->getNumOfCursors()); EXPECT_EQ(1, manager->getNumOpenChkItems()); EXPECT_EQ(1, manager->getNumCheckpoints()); // Create one less than the number required to create a new checkpoint. queued_item qi; for (unsigned int ii = 0; ii < MIN_CHECKPOINT_ITEMS; ii++) { EXPECT_EQ(ii + 1, manager->getNumOpenChkItems()); /* +1 for op_ckpt_start */ qi.reset(new Item("key" + std::to_string(ii), vbucket->getId(), queue_op_set, /*revSeq*/0, /*bySeq*/0)); EXPECT_TRUE(manager->queueDirty(vbucket, qi, true)); EXPECT_EQ(1, manager->getNumCheckpoints()); } // Add one more - should create a new checkpoint. qi.reset(new Item("key_epoch", vbucket->getId(), queue_op_set, /*revSeq*/0, /*bySeq*/0)); EXPECT_TRUE(manager->queueDirty(vbucket, qi, true)); EXPECT_EQ(2, manager->getNumCheckpoints()); EXPECT_EQ(2, manager->getNumOpenChkItems()); // 1x op_ckpt_start, 1x op_set // Fill up this checkpoint also - note loop for MIN_CHECKPOINT_ITEMS - 1 for (unsigned int ii = 0; ii < MIN_CHECKPOINT_ITEMS - 1; ii++) { EXPECT_EQ(ii + 2, manager->getNumOpenChkItems()); /* +2 op_ckpt_start, key_epoch */ qi.reset(new Item("key" + std::to_string(ii), vbucket->getId(), queue_op_set, /*revSeq*/1, /*bySeq*/0)); EXPECT_TRUE(manager->queueDirty(vbucket, qi, true)); EXPECT_EQ(2, manager->getNumCheckpoints()); } // Add one more - as we have hit maximum checkpoints should *not* create a // new one. qi.reset(new Item("key_epoch2", vbucket->getId(), queue_op_set, /*revSeq*/1, /*bySeq*/0)); EXPECT_TRUE(manager->queueDirty(vbucket, qi, true)); EXPECT_EQ(2, manager->getNumCheckpoints()); EXPECT_EQ(12, // 1x op_ckpt_start, 1x key_epoch, 9x key_X, 1x key_epoch2 manager->getNumOpenChkItems()); // Fetch the items associated with the persistence cursor. This // moves the single cursor registered outside of the initial checkpoint, // allowing a new open checkpoint to be created. EXPECT_EQ(1, manager->getNumOfCursors()); snapshot_range_t range; std::vector<queued_item> items; range = manager->getAllItemsForCursor(CheckpointManager::pCursorName, items); // Should still have the same number of checkpoints and open items. EXPECT_EQ(2, manager->getNumCheckpoints()); EXPECT_EQ(12, manager->getNumOpenChkItems()); // But adding a new item will create a new one. qi.reset(new Item("key_epoch3", vbucket->getId(), queue_op_set, /*revSeq*/1, /*bySeq*/0)); EXPECT_TRUE(manager->queueDirty(vbucket, qi, true)); EXPECT_EQ(3, manager->getNumCheckpoints()); EXPECT_EQ(2, manager->getNumOpenChkItems()); // 1x op_ckpt_start, 1x op_set } // Test checkpoint and cursor accounting - when checkpoints are closed the // offset of cursors is updated as appropriate. TEST_F(CheckpointTest, CursorOffsetOnCheckpointClose) { // Add two items to the initial (open) checkpoint. for (auto i : {1,2}) { queued_item qi(new Item("key" + std::to_string(i), vbucket->getId(), queue_op_set, /*revSeq*/0, /*bySeq*/0)); EXPECT_TRUE(manager->queueDirty(vbucket, qi, true)); } EXPECT_EQ(1, manager->getNumCheckpoints()); EXPECT_EQ(3, manager->getNumOpenChkItems()); // 1x op_checkpoint_start, 2x op_set EXPECT_EQ(3, manager->getNumItems()); // Use the existing persistence cursor for this test: EXPECT_EQ(2, manager->getNumItemsForCursor(CheckpointManager::pCursorName)) << "Cursor should initially have two items pending"; // Check de-dupe counting - after adding another item with the same key, // should still see two items. queued_item qi(new Item("key1", vbucket->getId(), queue_op_set, /*revSeq*/0, /*bySeq*/0)); EXPECT_FALSE(manager->queueDirty(vbucket, qi, true)) << "Adding a duplicate key to open checkpoint should not increase queue size"; EXPECT_EQ(2, manager->getNumItemsForCursor(CheckpointManager::pCursorName)) << "Expected 2 items for cursor (2x op_set) after adding a duplicate."; // Create a new checkpoint (closing the current open one). manager->createNewCheckpoint(); EXPECT_EQ(1, manager->getNumOpenChkItems()) << "Expected 1 item (1x op_checkpoint_start)"; EXPECT_EQ(2, manager->getNumCheckpoints()); // Advance cursor - first to get the 'checkpoint_start' meta item, // and a second time to get the a 'proper' mutation. bool isLastMutationItem; auto item = manager->nextItem(CheckpointManager::pCursorName, isLastMutationItem); EXPECT_TRUE(item->isCheckPointMetaItem()); EXPECT_FALSE(isLastMutationItem); item = manager->nextItem(CheckpointManager::pCursorName, isLastMutationItem); EXPECT_FALSE(item->isCheckPointMetaItem()); EXPECT_FALSE(isLastMutationItem); EXPECT_EQ(1, manager->getNumItemsForCursor(CheckpointManager::pCursorName)) << "Expected 1 item for cursor after advancing by 1"; // Add two items to the newly-opened checkpoint. Same keys as 1st ckpt, // but cannot de-dupe across checkpoints. for (auto ii : {1,2}) { queued_item qi(new Item("key" + std::to_string(ii), vbucket->getId(), queue_op_set, /*revSeq*/1, /*bySeq*/0)); EXPECT_TRUE(manager->queueDirty(vbucket, qi, true)); } EXPECT_EQ(3, manager->getNumItemsForCursor(CheckpointManager::pCursorName)) << "Expected 3 items for cursor after adding 2 more to new checkpoint"; // Advance the cursor 'out' of the first checkpoint. item = manager->nextItem(CheckpointManager::pCursorName, isLastMutationItem); EXPECT_FALSE(item->isCheckPointMetaItem()); EXPECT_TRUE(isLastMutationItem); // Now at the end of the first checkpoint, move into the next checkpoint. item = manager->nextItem(CheckpointManager::pCursorName, isLastMutationItem); EXPECT_TRUE(item->isCheckPointMetaItem()); EXPECT_TRUE(isLastMutationItem); item = manager->nextItem(CheckpointManager::pCursorName, isLastMutationItem); EXPECT_TRUE(item->isCheckPointMetaItem()); EXPECT_FALSE(isLastMutationItem); // Tell Checkpoint manager the items have been persisted, so it advances // pCursorPreCheckpointId, which will allow us to remove the closed // unreferenced checkpoints. manager->itemsPersisted(); // Both previous checkpoints are unreferenced. Close them. This will // cause the offset of this cursor to be recalculated. bool new_open_ckpt_created; EXPECT_EQ(2, manager->removeClosedUnrefCheckpoints(vbucket, new_open_ckpt_created)); EXPECT_EQ(1, manager->getNumCheckpoints()); EXPECT_EQ(2, manager->getNumItemsForCursor(CheckpointManager::pCursorName)); // Drain the remaining items. item = manager->nextItem(CheckpointManager::pCursorName, isLastMutationItem); EXPECT_FALSE(item->isCheckPointMetaItem()); EXPECT_FALSE(isLastMutationItem); item = manager->nextItem(CheckpointManager::pCursorName, isLastMutationItem); EXPECT_FALSE(item->isCheckPointMetaItem()); EXPECT_TRUE(isLastMutationItem); EXPECT_EQ(0, manager->getNumItemsForCursor(CheckpointManager::pCursorName)); } // Test the getAllItemsForCursor() TEST_F(CheckpointTest, ItemsForCheckpointCursor) { /* We want to have items across 2 checkpoints. Size down the default number of items to create a new checkpoint and recreate the manager */ checkpoint_config = CheckpointConfig(DEFAULT_CHECKPOINT_PERIOD, MIN_CHECKPOINT_ITEMS, /*numCheckpoints*/2, /*itemBased*/true, /*keepClosed*/false, /*enableMerge*/false); createManager(); /* Sanity check initial state */ EXPECT_EQ(1, manager->getNumOfCursors()); EXPECT_EQ(1, manager->getNumOpenChkItems()); EXPECT_EQ(1, manager->getNumCheckpoints()); /* Add items such that we have 2 checkpoints */ queued_item qi; for (unsigned int ii = 0; ii < 2 * MIN_CHECKPOINT_ITEMS; ii++) { qi.reset(new Item("key" + std::to_string(ii), vbucket->getId(), queue_op_set, /*revSeq*/0, /*bySeq*/0)); EXPECT_TRUE(manager->queueDirty(vbucket, qi, true)); } /* Check if we have desired number of checkpoints and desired number of items */ EXPECT_EQ(2, manager->getNumCheckpoints()); EXPECT_EQ(MIN_CHECKPOINT_ITEMS + 1, manager->getNumOpenChkItems()); /* MIN_CHECKPOINT_ITEMS items + op_ckpt_start */ /* Register DCP replication cursor */ std::string dcp_cursor(DCP_CURSOR_PREFIX + std::to_string(1)); manager->registerCursorBySeqno(dcp_cursor.c_str(), 0, MustSendCheckpointEnd::NO); /* Get items for persistence*/ std::vector<queued_item> items; manager->getAllItemsForCursor(CheckpointManager::pCursorName, items); /* We should have got (2 * MIN_CHECKPOINT_ITEMS + 3) items. 3 additional are op_ckpt_start, op_ckpt_end and op_ckpt_start */ EXPECT_EQ(2 * MIN_CHECKPOINT_ITEMS + 3, items.size()); /* Get items for DCP replication cursor */ items.clear(); manager->getAllItemsForCursor(dcp_cursor.c_str(), items); EXPECT_EQ(2 * MIN_CHECKPOINT_ITEMS + 3, items.size()); } // Test the checkpoint cursor movement TEST_F(CheckpointTest, CursorMovement) { /* We want to have items across 2 checkpoints. Size down the default number of items to create a new checkpoint and recreate the manager */ checkpoint_config = CheckpointConfig(DEFAULT_CHECKPOINT_PERIOD, MIN_CHECKPOINT_ITEMS, /*numCheckpoints*/2, /*itemBased*/true, /*keepClosed*/false, /*enableMerge*/false); createManager(); /* Sanity check initial state */ EXPECT_EQ(1, manager->getNumOfCursors()); EXPECT_EQ(1, manager->getNumOpenChkItems()); EXPECT_EQ(1, manager->getNumCheckpoints()); /* Add items such that we have 1 full (max items as per config) checkpoint. Adding another would open new checkpoint */ queued_item qi; for (unsigned int ii = 0; ii < MIN_CHECKPOINT_ITEMS; ii++) { qi.reset(new Item("key" + std::to_string(ii), vbucket->getId(), queue_op_set, /*revSeq*/0, /*bySeq*/0)); EXPECT_TRUE(manager->queueDirty(vbucket, qi, true)); } /* Check if we have desired number of checkpoints and desired number of items */ EXPECT_EQ(1, manager->getNumCheckpoints()); EXPECT_EQ(MIN_CHECKPOINT_ITEMS + 1, manager->getNumOpenChkItems()); /* MIN_CHECKPOINT_ITEMS items + op_ckpt_start */ /* Register DCP replication cursor */ std::string dcp_cursor(DCP_CURSOR_PREFIX + std::to_string(1)); manager->registerCursorBySeqno(dcp_cursor.c_str(), 0, MustSendCheckpointEnd::NO); /* Registor TAP cursor */ std::string tap_cursor(TAP_CURSOR_PREFIX + std::to_string(1)); manager->registerCursor(tap_cursor, 1, false, MustSendCheckpointEnd::YES); /* Get items for persistence cursor */ std::vector<queued_item> items; manager->getAllItemsForCursor(CheckpointManager::pCursorName, items); /* We should have got (MIN_CHECKPOINT_ITEMS + op_ckpt_start) items. */ EXPECT_EQ(MIN_CHECKPOINT_ITEMS + 1, items.size()); /* Get items for DCP replication cursor */ items.clear(); manager->getAllItemsForCursor(dcp_cursor.c_str(), items); EXPECT_EQ(MIN_CHECKPOINT_ITEMS + 1, items.size()); /* Get items for TAP cursor */ int num_items = 0; while(true) { bool isLastItem = false; qi = manager->nextItem(tap_cursor, isLastItem); num_items++; if (isLastItem) { break; } } EXPECT_EQ(MIN_CHECKPOINT_ITEMS + 1, num_items); uint64_t curr_open_chkpt_id = manager->getOpenCheckpointId_UNLOCKED(); /* Run the checkpoint remover so that new open checkpoint is created */ bool newCheckpointCreated; manager->removeClosedUnrefCheckpoints(vbucket, newCheckpointCreated); EXPECT_EQ(curr_open_chkpt_id + 1, manager->getOpenCheckpointId_UNLOCKED()); /* Get items for persistence cursor */ items.clear(); manager->getAllItemsForCursor(CheckpointManager::pCursorName, items); /* We should have got op_ckpt_start item */ EXPECT_EQ(1, items.size()); /* Get items for DCP replication cursor */ items.clear(); manager->getAllItemsForCursor(dcp_cursor.c_str(), items); /* Expecting only 1 op_ckpt_start item */ EXPECT_EQ(1, items.size()); /* Get item for TAP cursor. We expect TAP to send op_ckpt_end of last checkpoint. TAP unlike DCP cannot skip the op_ckpt_end message */ bool isLastItem = false; qi = manager->nextItem(tap_cursor, isLastItem); EXPECT_EQ(queue_op_checkpoint_end, qi->getOperation()); EXPECT_EQ(true, isLastItem); } /* static storage for environment variable set by putenv(). */ static char allow_no_stats_env[] = "ALLOW_NO_STATS_UPDATE=yeah"; int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); putenv(allow_no_stats_env); HashTable::setDefaultNumBuckets(5); HashTable::setDefaultNumLocks(1); return RUN_ALL_TESTS(); }
38.852713
98
0.631385
[ "vector" ]
a720acd65eb312c101f3acce88a32ed3e1e52d1f
1,660
cpp
C++
ospray/embree-v2.7.1/common/sys/regression.cpp
mathstuf/ospray
5c34884317b5bb84346e4e1e2e2bf8c7f50d307c
[ "Apache-2.0" ]
1
2016-05-24T19:27:01.000Z
2016-05-24T19:27:01.000Z
ospray/embree-v2.7.1/common/sys/regression.cpp
mathstuf/ospray
5c34884317b5bb84346e4e1e2e2bf8c7f50d307c
[ "Apache-2.0" ]
null
null
null
ospray/embree-v2.7.1/common/sys/regression.cpp
mathstuf/ospray
5c34884317b5bb84346e4e1e2e2bf8c7f50d307c
[ "Apache-2.0" ]
null
null
null
// ======================================================================== // // Copyright 2009-2016 Intel Corporation // // // // 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. // // ======================================================================== // #include "regression.h" namespace embree { static std::vector<RegressionTest*>* regression_tests; void registerRegressionTest(RegressionTest* test) { if (regression_tests == nullptr) regression_tests = new std::vector<RegressionTest*>; regression_tests->push_back(test); } void runRegressionTests() { if (regression_tests == nullptr) return; for (size_t i=0; i<regression_tests->size(); i++) (*(*regression_tests)[i])(); } }
43.684211
89
0.463855
[ "vector" ]
a7239ba98ff6c3ee3d17e583fa845ec784f91742
108,508
cpp
C++
NPB-FF/BT/bt.cpp
GMAP/NPB-CPP
2f77a1bce83c4efda56c4bafb555bcf9abe85dd2
[ "MIT" ]
11
2020-12-16T22:44:08.000Z
2022-03-30T00:52:58.000Z
NPB-FF/BT/bt.cpp
GMAP/NPB-CPP
2f77a1bce83c4efda56c4bafb555bcf9abe85dd2
[ "MIT" ]
1
2021-04-01T09:07:52.000Z
2021-07-21T22:10:07.000Z
NPB-FF/BT/bt.cpp
GMAP/NPB-CPP
2f77a1bce83c4efda56c4bafb555bcf9abe85dd2
[ "MIT" ]
3
2020-12-21T18:47:43.000Z
2021-11-20T19:48:45.000Z
/* MIT License Copyright (c) 2021 Parallel Applications Modelling Group - GMAP GMAP website: https://gmap.pucrs.br Pontifical Catholic University of Rio Grande do Sul (PUCRS) Av. Ipiranga, 6681, Porto Alegre - Brazil, 90619-900 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. ------------------------------------------------------------------------------ The original NPB 3.4.1 version was written in Fortran and belongs to: http://www.nas.nasa.gov/Software/NPB/ Authors of the Fortran code: R. Van der Wijngaart T. Harris M. Yarrow H. Jin ------------------------------------------------------------------------------ The serial C++ version is a translation of the original NPB 3.4.1 Serial C++ version: https://github.com/GMAP/NPB-CPP/tree/master/NPB-SER Authors of the C++ code: Dalvan Griebler <dalvangriebler@gmail.com> Gabriell Araujo <hexenoften@gmail.com> Júnior Löff <loffjh@gmail.com> ------------------------------------------------------------------------------ The FastFlow version is a parallel implementation of the serial C++ version FastFlow version: https://github.com/GMAP/NPB-CPP/tree/master/NPB-FF Authors of the FastFlow code: Júnior Löff <loffjh@gmail.com> */ #include "ff/ff.hpp" #include "ff/parallel_for.hpp" #include "../common/npb-CPP.hpp" #include "npbparams.hpp" #define IMAX PROBLEM_SIZE #define JMAX PROBLEM_SIZE #define KMAX PROBLEM_SIZE #define IMAXP (IMAX/2*2) #define JMAXP (JMAX/2*2) #define AA 0 #define BB 1 #define CC 2 #define BLOCK_SIZE 5 #define T_TOTAL 1 #define T_RHSX 2 #define T_RHSY 3 #define T_RHSZ 4 #define T_RHS 5 #define T_XSOLVE 6 #define T_YSOLVE 7 #define T_ZSOLVE 8 #define T_RDIS1 9 #define T_RDIS2 10 #define T_ADD 11 #define T_LAST 11 /* global variables */ #if defined(DO_NOT_ALLOCATE_ARRAYS_WITH_DYNAMIC_MEMORY_AND_AS_SINGLE_DIMENSION) static double us[KMAX][JMAXP+1][IMAXP+1]; static double vs[KMAX][JMAXP+1][IMAXP+1]; static double ws[KMAX][JMAXP+1][IMAXP+1]; static double qs[KMAX][JMAXP+1][IMAXP+1]; static double rho_i[KMAX][JMAXP+1][IMAXP+1]; static double square[KMAX][JMAXP+1][IMAXP+1]; static double forcing[KMAX][JMAXP+1][IMAXP+1][5]; static double u[KMAX][JMAXP+1][IMAXP+1][5]; static double rhs[KMAX][JMAXP+1][IMAXP+1][5]; static double cuf[PROBLEM_SIZE+1]; static double q[PROBLEM_SIZE+1]; static double ue[5][PROBLEM_SIZE+1]; static double buf[5][PROBLEM_SIZE+1]; static double fjac[PROBLEM_SIZE+1][5][5]; static double njac[PROBLEM_SIZE+1][5][5]; static double lhs[PROBLEM_SIZE+1][3][5][5]; static double ce[13][5]; #else static double (*us)[JMAXP+1][IMAXP+1]=(double(*)[JMAXP+1][IMAXP+1])malloc(sizeof(double)*((KMAX)*(JMAXP+1)*(IMAXP+1))); static double (*vs)[JMAXP+1][IMAXP+1]=(double(*)[JMAXP+1][IMAXP+1])malloc(sizeof(double)*((KMAX)*(JMAXP+1)*(IMAXP+1))); static double (*ws)[JMAXP+1][IMAXP+1]=(double(*)[JMAXP+1][IMAXP+1])malloc(sizeof(double)*((KMAX)*(JMAXP+1)*(IMAXP+1))); static double (*qs)[JMAXP+1][IMAXP+1]=(double(*)[JMAXP+1][IMAXP+1])malloc(sizeof(double)*((KMAX)*(JMAXP+1)*(IMAXP+1))); static double (*rho_i)[JMAXP+1][IMAXP+1]=(double(*)[JMAXP+1][IMAXP+1])malloc(sizeof(double)*((KMAX)*(JMAXP+1)*(IMAXP+1))); static double (*square)[JMAXP+1][IMAXP+1]=(double(*)[JMAXP+1][IMAXP+1])malloc(sizeof(double)*((KMAX)*(JMAXP+1)*(IMAXP+1))); static double (*forcing)[JMAXP+1][IMAXP+1][5]=(double(*)[JMAXP+1][IMAXP+1][5])malloc(sizeof(double)*((KMAX)*(JMAXP+1)*(IMAXP+1)*(5))); static double (*u)[JMAXP+1][IMAXP+1][5]=(double(*)[JMAXP+1][IMAXP+1][5])malloc(sizeof(double)*((KMAX)*(JMAXP+1)*(IMAXP+1)*(5))); static double (*rhs)[JMAXP+1][IMAXP+1][5]=(double(*)[JMAXP+1][IMAXP+1][5])malloc(sizeof(double)*((KMAX)*(JMAXP+1)*(IMAXP+1)*(5))); static double (*cuf)=(double*)malloc(sizeof(double)*(PROBLEM_SIZE+1)); static double (*q)=(double*)malloc(sizeof(double)*(PROBLEM_SIZE+1)); static double (*ue)[PROBLEM_SIZE+1]=(double(*)[PROBLEM_SIZE+1])malloc(sizeof(double)*((PROBLEM_SIZE+1)*(5))); static double (*buf)[PROBLEM_SIZE+1]=(double(*)[PROBLEM_SIZE+1])malloc(sizeof(double)*((PROBLEM_SIZE+1)*(5))); static double (*fjac)[5][5]=(double(*)[5][5])malloc(sizeof(double)*((PROBLEM_SIZE+1)*(5)*(5))); static double (*njac)[5][5]=(double(*)[5][5])malloc(sizeof(double)*((PROBLEM_SIZE+1)*(5)*(5))); double (*lhs)[3][5][5]=(double(*)[3][5][5])malloc(sizeof(double)*((PROBLEM_SIZE+1)*(3)*(5)*(5))); static double (*ce)[5]=(double(*)[5])malloc(sizeof(double)*((13)*(5))); #endif static double tx1, tx2, tx3, ty1, ty2, ty3, tz1, tz2, tz3, dx1, dx2, dx3, dx4, dx5, dy1, dy2, dy3, dy4, dy5, dz1, dz2, dz3, dz4, dz5, dssp, dt, dxmax, dymax, dzmax, xxcon1, xxcon2, xxcon3, xxcon4, xxcon5, dx1tx1, dx2tx1, dx3tx1, dx4tx1, dx5tx1, yycon1, yycon2, yycon3, yycon4, yycon5, dy1ty1, dy2ty1, dy3ty1, dy4ty1, dy5ty1, zzcon1, zzcon2, zzcon3, zzcon4, zzcon5, dz1tz1, dz2tz1, dz3tz1, dz4tz1, dz5tz1, dnxm1, dnym1, dnzm1, c1c2, c1c5, c3c4, c1345, conz1, c1, c2, c3, c4, c5, c4dssp, c5dssp, dtdssp, dttx1, dttx2, dtty1, dtty2, dttz1, dttz2, c2dttx1, c2dtty1, c2dttz1, comz1, comz4, comz5, comz6, c3c4tx3, c3c4ty3, c3c4tz3, c2iv, con43, con16, elapsed_time, tmp1, tmp2, tmp3; static int grid_points[3]; static boolean timeron; /* function prototypes */ static void add(); static void adi(); static void binvcrhs(double lhs[5][5], double c[5][5], double r[5]); static void binvrhs(double lhs[5][5], double r[5]); static void compute_rhs(); static void error_norm(double rms[5]); static void exact_rhs(); static void exact_solution(double xi, double eta, double zeta, double dtemp[5]); static void initialize(); static void lhsinit(double lhs[][3][5][5], int size); static void matmul_sub(double ablock[5][5], double bblock[5][5], double cblock[5][5]); static void matvec_sub(double ablock[5][5], double avec[5], double bvec[5]); static void rhs_norm(double rms[5]); static void set_constants(); static void verify(int no_time_steps, char* class_npb, boolean* verified); static void x_solve(); static void y_solve(); static void z_solve(); int num_workers; ff::ParallelFor * pf; /* bt */ int main(int argc, char* argv[]){ #if defined(DO_NOT_ALLOCATE_ARRAYS_WITH_DYNAMIC_MEMORY_AND_AS_SINGLE_DIMENSION) printf(" DO_NOT_ALLOCATE_ARRAYS_WITH_DYNAMIC_MEMORY_AND_AS_SINGLE_DIMENSION mode on\n"); #endif int i, niter, step; double navg, mflops, n3; double tmax, t, trecs[T_LAST+1]; boolean verified; char class_npb; char* t_names[T_LAST+1]; if(const char * nw = std::getenv("FF_NUM_THREADS")){ num_workers = atoi(nw); }else{ num_workers = 1; } pf = new ff::ParallelFor(num_workers, true); /* * --------------------------------------------------------------------- * root node reads input file (if it exists) else takes * defaults from parameters * --------------------------------------------------------------------- */ FILE* fp; if((fp=fopen("inputbt.data","r"))!=NULL){ int avoid_warning; printf(" Reading from input file inputbt.data\n"); avoid_warning=fscanf(fp,"%d",&niter); while(fgetc(fp)!='\n'); avoid_warning=fscanf(fp,"%lf",&dt); while(fgetc(fp)!='\n'); avoid_warning=fscanf(fp,"%d%d%d\n",&grid_points[0],&grid_points[1],&grid_points[2]); fclose(fp); }else{ printf(" No input file inputbt.data. Using compiled defaults\n"); niter=NITER_DEFAULT; dt=DT_DEFAULT; grid_points[0]=PROBLEM_SIZE; grid_points[1]=PROBLEM_SIZE; grid_points[2]=PROBLEM_SIZE; } if((fp=fopen("timer.flag","r"))!= NULL){ timeron=TRUE; t_names[T_TOTAL]=(char*)"total"; t_names[T_RHSX]=(char*)"rhsx"; t_names[T_RHSY]=(char*)"rhsy"; t_names[T_RHSZ]=(char*)"rhsz"; t_names[T_RHS]=(char*)"rhs"; t_names[T_XSOLVE]=(char*)"xsolve"; t_names[T_YSOLVE]=(char*)"ysolve"; t_names[T_ZSOLVE]=(char*)"zsolve"; t_names[T_RDIS1]=(char*)"redist1"; t_names[T_RDIS2]=(char*)"redist2"; t_names[T_ADD]=(char*)"add"; fclose(fp); }else{ timeron=FALSE; } printf("\n\n NAS Parallel Benchmarks 4.1 Parallel C++ version with FastFlow - BT Benchmark\n\n"); printf(" Size: %4dx%4dx%4d\n",grid_points[0],grid_points[1],grid_points[2]); printf(" Iterations: %4d dt: %10.6f\n",niter,dt); printf("\n"); if((grid_points[0]>IMAX)||(grid_points[1]>JMAX)||(grid_points[2]>KMAX)){ printf(" %d, %d, %d\n",grid_points[0],grid_points[1],grid_points[2]); printf(" Problem size too big for compiled array sizes\n"); return 0; } set_constants(); for(i=1;i<=T_LAST;i++){timer_clear(i);} initialize(); exact_rhs(); /* * --------------------------------------------------------------------- * do one time step to touch all code, and reinitialize * --------------------------------------------------------------------- */ adi(); initialize(); for(i=1;i<=T_LAST;i++){timer_clear(i);} timer_start(1); for(step=1; step<=niter; step++){ if((step%20)==0||step==1){ printf(" Time step %4d\n",step); } adi(); } timer_stop(1); tmax=timer_read(1); verify(niter, &class_npb, &verified); n3=1.0*grid_points[0]*grid_points[1]*grid_points[2]; navg=(grid_points[0]+grid_points[1]+grid_points[2])/3.0; if(tmax!=0.0){ mflops=1.0e-6*(double)niter* (3478.8*n3-17655.7*(navg*navg)+28023.7*navg) /tmax; }else{ mflops=0.0; } setenv("FF_NUM_THREADS","1",0); c_print_results((char*)"BT", class_npb, grid_points[0], grid_points[1], grid_points[2], niter, tmax, mflops, (char*)" floating point", verified, (char*)NPBVERSION, (char*)COMPILETIME, (char*)COMPILERVERSION, (char*)LIBVERSION, std::getenv("FF_NUM_THREADS"), (char*)CS1, (char*)CS2, (char*)CS3, (char*)CS4, (char*)CS5, (char*)CS6, (char*)"(none)"); /* * --------------------------------------------------------------------- * more timers * --------------------------------------------------------------------- */ if(timeron){ for(i=1; i<=T_LAST; i++){ trecs[i]=timer_read(i); } if(tmax==0.0){tmax=1.0;} printf(" SECTION Time (secs)\n"); for(i=1; i<=T_LAST; i++){ printf(" %-8s:%9.3f (%6.2f%%)\n", t_names[i], trecs[i], trecs[i]*100./tmax); if(i==T_RHS){ t=trecs[T_RHSX]+trecs[T_RHSY]+trecs[T_RHSZ]; printf(" --> %8s:%9.3f (%6.2f%%)\n","sub-rhs",t,t*100./tmax); t=trecs[T_RHS]-t; printf(" --> %8s:%9.3f (%6.2f%%)\n", "rest-rhs",t,t*100./tmax); }else if(i==T_ZSOLVE){ t=trecs[T_ZSOLVE]-trecs[T_RDIS1]-trecs[T_RDIS2]; printf(" --> %8s:%9.3f (%6.2f%%)\n", "sub-zsol",t,t*100./tmax); }else if(i==T_RDIS2){ t=trecs[T_RDIS1]+trecs[T_RDIS2]; printf(" --> %8s:%9.3f (%6.2f%%)\n","redist",t,t*100./tmax); } } } return 0; } /* * --------------------------------------------------------------------- * addition of update to the vector u * --------------------------------------------------------------------- */ void add(){ if(timeron){timer_start(T_ADD);} pf->parallel_for(1, grid_points[2]-1, 1, [&](int k){ int i, j, m; for(j=1; j<=grid_points[1]-2; j++){ for(i=1; i<=grid_points[0]-2; i++){ for(m=0; m<5; m++){ u[k][j][i][m]=u[k][j][i][m]+rhs[k][j][i][m]; } } } }); if(timeron){timer_stop(T_ADD);} } void adi(){ compute_rhs(); x_solve(); y_solve(); z_solve(); add(); } void binvcrhs(double lhs[5][5], double c[5][5], double r[5]){ double pivot, coeff; pivot=1.00/lhs[0][0]; lhs[1][0]=lhs[1][0]*pivot; lhs[2][0]=lhs[2][0]*pivot; lhs[3][0]=lhs[3][0]*pivot; lhs[4][0]=lhs[4][0]*pivot; c[0][0]=c[0][0]*pivot; c[1][0]=c[1][0]*pivot; c[2][0]=c[2][0]*pivot; c[3][0]=c[3][0]*pivot; c[4][0]=c[4][0]*pivot; r[0]=r[0]*pivot; /* */ coeff=lhs[0][1]; lhs[1][1]=lhs[1][1]-coeff*lhs[1][0]; lhs[2][1]=lhs[2][1]-coeff*lhs[2][0]; lhs[3][1]=lhs[3][1]-coeff*lhs[3][0]; lhs[4][1]=lhs[4][1]-coeff*lhs[4][0]; c[0][1]=c[0][1]-coeff*c[0][0]; c[1][1]=c[1][1]-coeff*c[1][0]; c[2][1]=c[2][1]-coeff*c[2][0]; c[3][1]=c[3][1]-coeff*c[3][0]; c[4][1]=c[4][1]-coeff*c[4][0]; r[1]=r[1]-coeff*r[0]; /* */ coeff=lhs[0][2]; lhs[1][2]=lhs[1][2]-coeff*lhs[1][0]; lhs[2][2]=lhs[2][2]-coeff*lhs[2][0]; lhs[3][2]=lhs[3][2]-coeff*lhs[3][0]; lhs[4][2]=lhs[4][2]-coeff*lhs[4][0]; c[0][2]=c[0][2]-coeff*c[0][0]; c[1][2]=c[1][2]-coeff*c[1][0]; c[2][2]=c[2][2]-coeff*c[2][0]; c[3][2]=c[3][2]-coeff*c[3][0]; c[4][2]=c[4][2]-coeff*c[4][0]; r[2]=r[2]-coeff*r[0]; /* */ coeff=lhs[0][3]; lhs[1][3]=lhs[1][3]-coeff*lhs[1][0]; lhs[2][3]=lhs[2][3]-coeff*lhs[2][0]; lhs[3][3]=lhs[3][3]-coeff*lhs[3][0]; lhs[4][3]=lhs[4][3]-coeff*lhs[4][0]; c[0][3]=c[0][3]-coeff*c[0][0]; c[1][3]=c[1][3]-coeff*c[1][0]; c[2][3]=c[2][3]-coeff*c[2][0]; c[3][3]=c[3][3]-coeff*c[3][0]; c[4][3]=c[4][3]-coeff*c[4][0]; r[3]=r[3]-coeff*r[0]; /* */ coeff=lhs[0][4]; lhs[1][4]=lhs[1][4]-coeff*lhs[1][0]; lhs[2][4]=lhs[2][4]-coeff*lhs[2][0]; lhs[3][4]=lhs[3][4]-coeff*lhs[3][0]; lhs[4][4]=lhs[4][4]-coeff*lhs[4][0]; c[0][4]=c[0][4]-coeff*c[0][0]; c[1][4]=c[1][4]-coeff*c[1][0]; c[2][4]=c[2][4]-coeff*c[2][0]; c[3][4]=c[3][4]-coeff*c[3][0]; c[4][4]=c[4][4]-coeff*c[4][0]; r[4]=r[4]-coeff*r[0]; /* */ pivot=1.00/lhs[1][1]; lhs[2][1]=lhs[2][1]*pivot; lhs[3][1]=lhs[3][1]*pivot; lhs[4][1]=lhs[4][1]*pivot; c[0][1]=c[0][1]*pivot; c[1][1]=c[1][1]*pivot; c[2][1]=c[2][1]*pivot; c[3][1]=c[3][1]*pivot; c[4][1]=c[4][1]*pivot; r[1]=r[1]*pivot; /* */ coeff=lhs[1][0]; lhs[2][0]=lhs[2][0]-coeff*lhs[2][1]; lhs[3][0]=lhs[3][0]-coeff*lhs[3][1]; lhs[4][0]=lhs[4][0]-coeff*lhs[4][1]; c[0][0]=c[0][0]-coeff*c[0][1]; c[1][0]=c[1][0]-coeff*c[1][1]; c[2][0]=c[2][0]-coeff*c[2][1]; c[3][0]=c[3][0]-coeff*c[3][1]; c[4][0]=c[4][0]-coeff*c[4][1]; r[0]=r[0]-coeff*r[1]; /* */ coeff = lhs[1][2]; lhs[2][2]=lhs[2][2]-coeff*lhs[2][1]; lhs[3][2]=lhs[3][2]-coeff*lhs[3][1]; lhs[4][2]=lhs[4][2]-coeff*lhs[4][1]; c[0][2]=c[0][2]-coeff*c[0][1]; c[1][2]=c[1][2]-coeff*c[1][1]; c[2][2]=c[2][2]-coeff*c[2][1]; c[3][2]=c[3][2]-coeff*c[3][1]; c[4][2]=c[4][2]-coeff*c[4][1]; r[2]=r[2]-coeff*r[1]; /* */ coeff=lhs[1][3]; lhs[2][3]=lhs[2][3]-coeff*lhs[2][1]; lhs[3][3]=lhs[3][3]-coeff*lhs[3][1]; lhs[4][3]=lhs[4][3]-coeff*lhs[4][1]; c[0][3]=c[0][3]-coeff*c[0][1]; c[1][3]=c[1][3]-coeff*c[1][1]; c[2][3]=c[2][3]-coeff*c[2][1]; c[3][3]=c[3][3]-coeff*c[3][1]; c[4][3]=c[4][3]-coeff*c[4][1]; r[3]=r[3]-coeff*r[1]; /* */ coeff=lhs[1][4]; lhs[2][4]=lhs[2][4]-coeff*lhs[2][1]; lhs[3][4]=lhs[3][4]-coeff*lhs[3][1]; lhs[4][4]=lhs[4][4]-coeff*lhs[4][1]; c[0][4]=c[0][4]-coeff*c[0][1]; c[1][4]=c[1][4]-coeff*c[1][1]; c[2][4]=c[2][4]-coeff*c[2][1]; c[3][4]=c[3][4]-coeff*c[3][1]; c[4][4]=c[4][4]-coeff*c[4][1]; r[4]=r[4]-coeff*r[1]; /* */ pivot = 1.00/lhs[2][2]; lhs[3][2]=lhs[3][2]*pivot; lhs[4][2]=lhs[4][2]*pivot; c[0][2]=c[0][2]*pivot; c[1][2]=c[1][2]*pivot; c[2][2]=c[2][2]*pivot; c[3][2]=c[3][2]*pivot; c[4][2]=c[4][2]*pivot; r[2]=r[2]*pivot; /* */ coeff=lhs[2][0]; lhs[3][0]=lhs[3][0]-coeff*lhs[3][2]; lhs[4][0]=lhs[4][0]-coeff*lhs[4][2]; c[0][0]=c[0][0]-coeff*c[0][2]; c[1][0]=c[1][0]-coeff*c[1][2]; c[2][0]=c[2][0]-coeff*c[2][2]; c[3][0]=c[3][0]-coeff*c[3][2]; c[4][0]=c[4][0]-coeff*c[4][2]; r[0]=r[0]-coeff*r[2]; /* */ coeff=lhs[2][1]; lhs[3][1]=lhs[3][1]-coeff*lhs[3][2]; lhs[4][1]=lhs[4][1]-coeff*lhs[4][2]; c[0][1]=c[0][1]-coeff*c[0][2]; c[1][1]=c[1][1]-coeff*c[1][2]; c[2][1]=c[2][1]-coeff*c[2][2]; c[3][1]=c[3][1]-coeff*c[3][2]; c[4][1]=c[4][1]-coeff*c[4][2]; r[1]=r[1]-coeff*r[2]; /* */ coeff=lhs[2][3]; lhs[3][3]=lhs[3][3]-coeff*lhs[3][2]; lhs[4][3]=lhs[4][3]-coeff*lhs[4][2]; c[0][3]=c[0][3]-coeff*c[0][2]; c[1][3]=c[1][3]-coeff*c[1][2]; c[2][3]=c[2][3]-coeff*c[2][2]; c[3][3]=c[3][3]-coeff*c[3][2]; c[4][3]=c[4][3]-coeff*c[4][2]; r[3]=r[3]-coeff*r[2]; /* */ coeff=lhs[2][4]; lhs[3][4]=lhs[3][4]-coeff*lhs[3][2]; lhs[4][4]=lhs[4][4]-coeff*lhs[4][2]; c[0][4]=c[0][4]-coeff*c[0][2]; c[1][4]=c[1][4]-coeff*c[1][2]; c[2][4]=c[2][4]-coeff*c[2][2]; c[3][4]=c[3][4]-coeff*c[3][2]; c[4][4]=c[4][4]-coeff*c[4][2]; r[4]=r[4]-coeff*r[2]; /* */ pivot=1.00/lhs[3][3]; lhs[4][3]=lhs[4][3]*pivot; c[0][3]=c[0][3]*pivot; c[1][3]=c[1][3]*pivot; c[2][3]=c[2][3]*pivot; c[3][3]=c[3][3]*pivot; c[4][3]=c[4][3]*pivot; r[3]=r[3] *pivot; /* */ coeff=lhs[3][0]; lhs[4][0]=lhs[4][0]-coeff*lhs[4][3]; c[0][0]=c[0][0]-coeff*c[0][3]; c[1][0]=c[1][0]-coeff*c[1][3]; c[2][0]=c[2][0]-coeff*c[2][3]; c[3][0]=c[3][0]-coeff*c[3][3]; c[4][0]=c[4][0]-coeff*c[4][3]; r[0]=r[0]-coeff*r[3]; /* */ coeff=lhs[3][1]; lhs[4][1]=lhs[4][1]-coeff*lhs[4][3]; c[0][1]=c[0][1]-coeff*c[0][3]; c[1][1]=c[1][1]-coeff*c[1][3]; c[2][1]=c[2][1]-coeff*c[2][3]; c[3][1]=c[3][1]-coeff*c[3][3]; c[4][1]=c[4][1]-coeff*c[4][3]; r[1]=r[1]-coeff*r[3]; /* */ coeff=lhs[3][2]; lhs[4][2]=lhs[4][2]-coeff*lhs[4][3]; c[0][2]=c[0][2]-coeff*c[0][3]; c[1][2]=c[1][2]-coeff*c[1][3]; c[2][2]=c[2][2]-coeff*c[2][3]; c[3][2]=c[3][2]-coeff*c[3][3]; c[4][2]=c[4][2]-coeff*c[4][3]; r[2]=r[2]-coeff*r[3]; /* */ coeff=lhs[3][4]; lhs[4][4]=lhs[4][4]-coeff*lhs[4][3]; c[0][4]=c[0][4]-coeff*c[0][3]; c[1][4]=c[1][4]-coeff*c[1][3]; c[2][4]=c[2][4]-coeff*c[2][3]; c[3][4]=c[3][4]-coeff*c[3][3]; c[4][4]=c[4][4]-coeff*c[4][3]; r[4]=r[4]-coeff*r[3]; /* */ pivot=1.00/lhs[4][4]; c[0][4]=c[0][4]*pivot; c[1][4]=c[1][4]*pivot; c[2][4]=c[2][4]*pivot; c[3][4]=c[3][4]*pivot; c[4][4]=c[4][4]*pivot; r[4]=r[4]*pivot; /* */ coeff=lhs[4][0]; c[0][0]=c[0][0]-coeff*c[0][4]; c[1][0]=c[1][0]-coeff*c[1][4]; c[2][0]=c[2][0]-coeff*c[2][4]; c[3][0]=c[3][0]-coeff*c[3][4]; c[4][0]=c[4][0]-coeff*c[4][4]; r[0]=r[0]-coeff*r[4]; /* */ coeff=lhs[4][1]; c[0][1]=c[0][1]-coeff*c[0][4]; c[1][1]=c[1][1]-coeff*c[1][4]; c[2][1]=c[2][1]-coeff*c[2][4]; c[3][1]=c[3][1]-coeff*c[3][4]; c[4][1]=c[4][1]-coeff*c[4][4]; r[1]=r[1]-coeff*r[4]; /* */ coeff=lhs[4][2]; c[0][2]=c[0][2]-coeff*c[0][4]; c[1][2]=c[1][2]-coeff*c[1][4]; c[2][2]=c[2][2]-coeff*c[2][4]; c[3][2]=c[3][2]-coeff*c[3][4]; c[4][2]=c[4][2]-coeff*c[4][4]; r[2]=r[2]-coeff*r[4]; /* */ coeff=lhs[4][3]; c[0][3]=c[0][3]-coeff*c[0][4]; c[1][3]=c[1][3]-coeff*c[1][4]; c[2][3]=c[2][3]-coeff*c[2][4]; c[3][3]=c[3][3]-coeff*c[3][4]; c[4][3]=c[4][3]-coeff*c[4][4]; r[3]=r[3]-coeff*r[4]; } void binvrhs(double lhs[5][5], double r[5]){ double pivot, coeff; pivot=1.00/lhs[0][0]; lhs[1][0]=lhs[1][0]*pivot; lhs[2][0]=lhs[2][0]*pivot; lhs[3][0]=lhs[3][0]*pivot; lhs[4][0]=lhs[4][0]*pivot; r[0]=r[0]*pivot; /* */ coeff=lhs[0][1]; lhs[1][1]=lhs[1][1]-coeff*lhs[1][0]; lhs[2][1]=lhs[2][1]-coeff*lhs[2][0]; lhs[3][1]=lhs[3][1]-coeff*lhs[3][0]; lhs[4][1]=lhs[4][1]-coeff*lhs[4][0]; r[1]=r[1]-coeff*r[0]; /* */ coeff=lhs[0][2]; lhs[1][2]=lhs[1][2]-coeff*lhs[1][0]; lhs[2][2]=lhs[2][2]-coeff*lhs[2][0]; lhs[3][2]=lhs[3][2]-coeff*lhs[3][0]; lhs[4][2]=lhs[4][2]-coeff*lhs[4][0]; r[2]=r[2]-coeff*r[0]; /* */ coeff=lhs[0][3]; lhs[1][3]=lhs[1][3]-coeff*lhs[1][0]; lhs[2][3]=lhs[2][3]-coeff*lhs[2][0]; lhs[3][3]=lhs[3][3]-coeff*lhs[3][0]; lhs[4][3]=lhs[4][3]-coeff*lhs[4][0]; r[3]=r[3]-coeff*r[0]; /* */ coeff=lhs[0][4]; lhs[1][4]=lhs[1][4]-coeff*lhs[1][0]; lhs[2][4]=lhs[2][4]-coeff*lhs[2][0]; lhs[3][4]=lhs[3][4]-coeff*lhs[3][0]; lhs[4][4]=lhs[4][4]-coeff*lhs[4][0]; r[4]=r[4]-coeff*r[0]; /* */ pivot=1.00/lhs[1][1]; lhs[2][1]=lhs[2][1]*pivot; lhs[3][1]=lhs[3][1]*pivot; lhs[4][1]=lhs[4][1]*pivot; r[1]=r[1]*pivot; /* */ coeff=lhs[1][0]; lhs[2][0]=lhs[2][0]-coeff*lhs[2][1]; lhs[3][0]=lhs[3][0]-coeff*lhs[3][1]; lhs[4][0]=lhs[4][0]-coeff*lhs[4][1]; r[0]=r[0]-coeff*r[1]; /* */ coeff=lhs[1][2]; lhs[2][2]=lhs[2][2]-coeff*lhs[2][1]; lhs[3][2]=lhs[3][2]-coeff*lhs[3][1]; lhs[4][2]=lhs[4][2]-coeff*lhs[4][1]; r[2]=r[2]-coeff*r[1]; /* */ coeff=lhs[1][3]; lhs[2][3]=lhs[2][3]-coeff*lhs[2][1]; lhs[3][3]=lhs[3][3]-coeff*lhs[3][1]; lhs[4][3]=lhs[4][3]-coeff*lhs[4][1]; r[3]=r[3]-coeff*r[1]; /* */ coeff=lhs[1][4]; lhs[2][4]=lhs[2][4]-coeff*lhs[2][1]; lhs[3][4]=lhs[3][4]-coeff*lhs[3][1]; lhs[4][4]=lhs[4][4]-coeff*lhs[4][1]; r[4]=r[4]-coeff*r[1]; /* */ pivot=1.00/lhs[2][2]; lhs[3][2]=lhs[3][2]*pivot; lhs[4][2]=lhs[4][2]*pivot; r[2]=r[2]*pivot; /* */ coeff=lhs[2][0]; lhs[3][0]=lhs[3][0]-coeff*lhs[3][2]; lhs[4][0]=lhs[4][0]-coeff*lhs[4][2]; r[0]=r[0]-coeff*r[2]; /* */ coeff=lhs[2][1]; lhs[3][1]=lhs[3][1]-coeff*lhs[3][2]; lhs[4][1]=lhs[4][1]-coeff*lhs[4][2]; r[1]=r[1]-coeff*r[2]; /* */ coeff=lhs[2][3]; lhs[3][3]=lhs[3][3]-coeff*lhs[3][2]; lhs[4][3]=lhs[4][3]-coeff*lhs[4][2]; r[3]=r[3]-coeff*r[2]; /* */ coeff=lhs[2][4]; lhs[3][4]=lhs[3][4]-coeff*lhs[3][2]; lhs[4][4]=lhs[4][4]-coeff*lhs[4][2]; r[4]=r[4]-coeff*r[2]; /* */ pivot=1.00/lhs[3][3]; lhs[4][3]=lhs[4][3]*pivot; r[3]=r[3]*pivot; /* */ coeff=lhs[3][0]; lhs[4][0]=lhs[4][0]-coeff*lhs[4][3]; r[0]=r[0]-coeff*r[3]; /* */ coeff=lhs[3][1]; lhs[4][1]=lhs[4][1]-coeff*lhs[4][3]; r[1]=r[1]-coeff*r[3]; /* */ coeff=lhs[3][2]; lhs[4][2]=lhs[4][2]-coeff*lhs[4][3]; r[2]=r[2]-coeff*r[3]; /* */ coeff=lhs[3][4]; lhs[4][4]=lhs[4][4]-coeff*lhs[4][3]; r[4]=r[4]-coeff*r[3]; /* */ pivot=1.00/lhs[4][4]; r[4]=r[4]*pivot; /* */ coeff=lhs[4][0]; r[0]=r[0]-coeff*r[4]; /* */ coeff=lhs[4][1]; r[1]=r[1]-coeff*r[4]; /* */ coeff=lhs[4][2]; r[2]=r[2]-coeff*r[4]; /* */ coeff=lhs[4][3]; r[3]=r[3]-coeff*r[4]; } void compute_rhs(){ int i, j, k, m; double rho_inv, uijk, up1, um1, vijk, vp1, vm1, wijk, wp1, wm1; if(timeron){timer_start(T_RHS);} /* * --------------------------------------------------------------------- * compute the reciprocal of density, and the kinetic energy, * and the speed of sound. * --------------------------------------------------------------------- */ pf->parallel_for(0, grid_points[2], 1, [&](int k){ int j, i; double rho_inv; for(j=0; j<=grid_points[1]-1; j++){ for(i=0; i<=grid_points[0]-1; i++){ rho_inv=1.0/u[k][j][i][0]; rho_i[k][j][i]=rho_inv; us[k][j][i]=u[k][j][i][1]*rho_inv; vs[k][j][i]=u[k][j][i][2]*rho_inv; ws[k][j][i]=u[k][j][i][3]*rho_inv; square[k][j][i]=0.5*( u[k][j][i][1]*u[k][j][i][1]+ u[k][j][i][2]*u[k][j][i][2]+ u[k][j][i][3]*u[k][j][i][3])*rho_inv; qs[k][j][i]=square[k][j][i]*rho_inv; } } }); /* * --------------------------------------------------------------------- * copy the exact forcing term to the right hand side; because * this forcing term is known, we can store it on the whole grid * including the boundary * --------------------------------------------------------------------- */ pf->parallel_for(0, grid_points[2]-1+1, 1, [&](int k){ int j, i, m; for(j=0; j<=grid_points[1]-1; j++){ for(i=0; i<=grid_points[0]-1; i++){ for(m=0; m<5; m++){ rhs[k][j][i][m]=forcing[k][j][i][m]; } } } }); if(timeron){timer_start(T_RHSX);} /* * --------------------------------------------------------------------- * compute xi-direction fluxes * --------------------------------------------------------------------- */ pf->parallel_for(1, grid_points[2]-1, 1, [&](int k){ double uijk, up1, um1; int j, i, m; for(j=1; j<=grid_points[1]-2; j++){ for(i=1; i<=grid_points[0]-2; i++){ uijk=us[k][j][i]; up1=us[k][j][i+1]; um1=us[k][j][i-1]; rhs[k][j][i][0]=rhs[k][j][i][0]+dx1tx1* (u[k][j][i+1][0]-2.0*u[k][j][i][0]+ u[k][j][i-1][0])- tx2*(u[k][j][i+1][1]-u[k][j][i-1][1]); rhs[k][j][i][1]=rhs[k][j][i][1]+dx2tx1* (u[k][j][i+1][1]-2.0*u[k][j][i][1]+ u[k][j][i-1][1])+ xxcon2*con43*(up1-2.0*uijk+um1)- tx2*(u[k][j][i+1][1]*up1- u[k][j][i-1][1]*um1+ (u[k][j][i+1][4]- square[k][j][i+1]- u[k][j][i-1][4]+ square[k][j][i-1])* c2); rhs[k][j][i][2]=rhs[k][j][i][2]+dx3tx1* (u[k][j][i+1][2]-2.0*u[k][j][i][2]+ u[k][j][i-1][2])+ xxcon2*(vs[k][j][i+1]-2.0*vs[k][j][i]+ vs[k][j][i-1])- tx2*(u[k][j][i+1][2]*up1- u[k][j][i-1][2]*um1); rhs[k][j][i][3]=rhs[k][j][i][3]+dx4tx1* (u[k][j][i+1][3]-2.0*u[k][j][i][3]+ u[k][j][i-1][3])+ xxcon2*(ws[k][j][i+1]-2.0*ws[k][j][i]+ ws[k][j][i-1])- tx2*(u[k][j][i+1][3]*up1- u[k][j][i-1][3]*um1); rhs[k][j][i][4]=rhs[k][j][i][4]+dx5tx1* (u[k][j][i+1][4]-2.0*u[k][j][i][4]+ u[k][j][i-1][4])+ xxcon3*(qs[k][j][i+1]-2.0*qs[k][j][i]+ qs[k][j][i-1])+ xxcon4*(up1*up1-2.0*uijk*uijk+ um1*um1)+ xxcon5*(u[k][j][i+1][4]*rho_i[k][j][i+1]- 2.0*u[k][j][i][4]*rho_i[k][j][i]+ u[k][j][i-1][4]*rho_i[k][j][i-1])- tx2*((c1*u[k][j][i+1][4]- c2*square[k][j][i+1])*up1- (c1*u[k][j][i-1][4]- c2*square[k][j][i-1])*um1); } } /* * --------------------------------------------------------------------- * add fourth order xi-direction dissipation * --------------------------------------------------------------------- */ for(j=1; j<=grid_points[1]-2; j++){ i=1; for(m=0; m<5; m++){ rhs[k][j][i][m]=rhs[k][j][i][m]-dssp* (5.0*u[k][j][i][m]-4.0*u[k][j][i+1][m]+ u[k][j][i+2][m]); } i=2; for(m=0; m<5; m++){ rhs[k][j][i][m]=rhs[k][j][i][m]-dssp* (-4.0*u[k][j][i-1][m]+6.0*u[k][j][i][m]- 4.0*u[k][j][i+1][m]+u[k][j][i+2][m]); } } for(j=1; j<=grid_points[1]-2; j++){ for(i=3; i<=grid_points[0]-4; i++){ for(m=0; m<5; m++){ rhs[k][j][i][m]=rhs[k][j][i][m]-dssp * (u[k][j][i-2][m]-4.0*u[k][j][i-1][m]+ 6.0*u[k][j][i][m]-4.0*u[k][j][i+1][m]+ u[k][j][i+2][m]); } } } for(j=1; j<=grid_points[1]-2; j++){ i=grid_points[0]-3; for(m=0; m<5; m++){ rhs[k][j][i][m]=rhs[k][j][i][m]-dssp* (u[k][j][i-2][m]-4.0*u[k][j][i-1][m]+ 6.0*u[k][j][i][m]-4.0*u[k][j][i+1][m]); } i=grid_points[0]-2; for(m=0; m<5; m++){ rhs[k][j][i][m]=rhs[k][j][i][m]-dssp* (u[k][j][i-2][m]-4.*u[k][j][i-1][m]+ 5.*u[k][j][i][m]); } } }); if(timeron){timer_stop(T_RHSX);} if(timeron){timer_start(T_RHSY);} /* * --------------------------------------------------------------------- * compute eta-direction fluxes * --------------------------------------------------------------------- */ pf->parallel_for(1, grid_points[2]-1, 1, [&](int k){ double vijk, vp1, vm1; int j, i, m; for(j=1; j<=grid_points[1]-2; j++){ for(i=1; i<=grid_points[0]-2; i++){ vijk=vs[k][j][i]; vp1=vs[k][j+1][i]; vm1=vs[k][j-1][i]; rhs[k][j][i][0]=rhs[k][j][i][0]+dy1ty1* (u[k][j+1][i][0]-2.0*u[k][j][i][0]+ u[k][j-1][i][0])- ty2*(u[k][j+1][i][2]-u[k][j-1][i][2]); rhs[k][j][i][1]=rhs[k][j][i][1]+dy2ty1* (u[k][j+1][i][1]-2.0*u[k][j][i][1]+ u[k][j-1][i][1])+ yycon2*(us[k][j+1][i]-2.0*us[k][j][i]+ us[k][j-1][i])- ty2*(u[k][j+1][i][1]*vp1- u[k][j-1][i][1]*vm1); rhs[k][j][i][2]=rhs[k][j][i][2]+dy3ty1* (u[k][j+1][i][2]-2.0*u[k][j][i][2]+ u[k][j-1][i][2])+ yycon2*con43*(vp1-2.0*vijk+vm1)- ty2*(u[k][j+1][i][2]*vp1- u[k][j-1][i][2]*vm1+ (u[k][j+1][i][4]-square[k][j+1][i]- u[k][j-1][i][4]+square[k][j-1][i]) *c2); rhs[k][j][i][3]=rhs[k][j][i][3]+dy4ty1* (u[k][j+1][i][3]-2.0*u[k][j][i][3]+ u[k][j-1][i][3])+ yycon2*(ws[k][j+1][i]-2.0*ws[k][j][i]+ ws[k][j-1][i])- ty2*(u[k][j+1][i][3]*vp1- u[k][j-1][i][3]*vm1); rhs[k][j][i][4]=rhs[k][j][i][4]+dy5ty1* (u[k][j+1][i][4]-2.0*u[k][j][i][4]+ u[k][j-1][i][4])+ yycon3*(qs[k][j+1][i]-2.0*qs[k][j][i]+ qs[k][j-1][i])+ yycon4*(vp1*vp1-2.0*vijk*vijk+ vm1*vm1)+ yycon5*(u[k][j+1][i][4]*rho_i[k][j+1][i]- 2.0*u[k][j][i][4]*rho_i[k][j][i]+ u[k][j-1][i][4]*rho_i[k][j-1][i])- ty2*((c1*u[k][j+1][i][4]- c2*square[k][j+1][i])*vp1- (c1*u[k][j-1][i][4]- c2*square[k][j-1][i])*vm1); } } /* * --------------------------------------------------------------------- * add fourth order eta-direction dissipation * --------------------------------------------------------------------- */ j=1; for(i=1; i<=grid_points[0]-2; i++){ for(m=0; m<5; m++){ rhs[k][j][i][m]=rhs[k][j][i][m]-dssp* (5.0*u[k][j][i][m]-4.0*u[k][j+1][i][m]+ u[k][j+2][i][m]); } } j=2; for(i=1; i<=grid_points[0]-2; i++){ for(m=0; m<5; m++){ rhs[k][j][i][m]=rhs[k][j][i][m]-dssp* (-4.0*u[k][j-1][i][m]+6.0*u[k][j][i][m]- 4.0*u[k][j+1][i][m]+u[k][j+2][i][m]); } } for(j=3; j<=grid_points[1]-4; j++){ for(i=1; i<=grid_points[0]-2; i++){ for(m=0; m<5; m++){ rhs[k][j][i][m]=rhs[k][j][i][m]-dssp* (u[k][j-2][i][m]-4.0*u[k][j-1][i][m]+ 6.0*u[k][j][i][m]-4.0*u[k][j+1][i][m]+ u[k][j+2][i][m]); } } } j=grid_points[1]-3; for(i=1; i<=grid_points[0]-2; i++){ for(m=0; m<5; m++){ rhs[k][j][i][m]=rhs[k][j][i][m]-dssp* (u[k][j-2][i][m]-4.0*u[k][j-1][i][m]+ 6.0*u[k][j][i][m]-4.0*u[k][j+1][i][m]); } } j=grid_points[1]-2; for(i=1; i<=grid_points[0]-2; i++){ for(m=0; m<5; m++){ rhs[k][j][i][m]=rhs[k][j][i][m]-dssp* (u[k][j-2][i][m]-4.*u[k][j-1][i][m]+ 5.*u[k][j][i][m]); } } }); if(timeron){timer_stop(T_RHSY);} if(timeron){timer_start(T_RHSZ);} /* * --------------------------------------------------------------------- * compute zeta-direction fluxes * --------------------------------------------------------------------- */ pf->parallel_for(1, grid_points[2]-1, 1, [&](int k){ double wijk, wp1, wm1; int j, i, m; for(j=1; j<=grid_points[1]-2; j++){ for(i=1; i<=grid_points[0]-2; i++){ wijk=ws[k][j][i]; wp1=ws[k+1][j][i]; wm1=ws[k-1][j][i]; rhs[k][j][i][0]=rhs[k][j][i][0]+dz1tz1* (u[k+1][j][i][0]-2.0*u[k][j][i][0]+ u[k-1][j][i][0])- tz2*(u[k+1][j][i][3]-u[k-1][j][i][3]); rhs[k][j][i][1]=rhs[k][j][i][1]+dz2tz1* (u[k+1][j][i][1]-2.0*u[k][j][i][1]+ u[k-1][j][i][1])+ zzcon2*(us[k+1][j][i]-2.0*us[k][j][i]+ us[k-1][j][i])- tz2*(u[k+1][j][i][1]*wp1- u[k-1][j][i][1]*wm1); rhs[k][j][i][2]=rhs[k][j][i][2]+dz3tz1* (u[k+1][j][i][2]-2.0*u[k][j][i][2]+ u[k-1][j][i][2])+ zzcon2*(vs[k+1][j][i]-2.0*vs[k][j][i]+ vs[k-1][j][i])- tz2*(u[k+1][j][i][2]*wp1- u[k-1][j][i][2]*wm1); rhs[k][j][i][3]=rhs[k][j][i][3]+dz4tz1* (u[k+1][j][i][3]-2.0*u[k][j][i][3]+ u[k-1][j][i][3])+ zzcon2*con43*(wp1-2.0*wijk+wm1)- tz2*(u[k+1][j][i][3]*wp1- u[k-1][j][i][3]*wm1+ (u[k+1][j][i][4]-square[k+1][j][i]- u[k-1][j][i][4]+square[k-1][j][i]) *c2); rhs[k][j][i][4]=rhs[k][j][i][4]+dz5tz1* (u[k+1][j][i][4]-2.0*u[k][j][i][4]+ u[k-1][j][i][4])+ zzcon3*(qs[k+1][j][i]-2.0*qs[k][j][i]+ qs[k-1][j][i])+ zzcon4*(wp1*wp1-2.0*wijk*wijk+ wm1*wm1)+ zzcon5*(u[k+1][j][i][4]*rho_i[k+1][j][i]- 2.0*u[k][j][i][4]*rho_i[k][j][i]+ u[k-1][j][i][4]*rho_i[k-1][j][i])- tz2*((c1*u[k+1][j][i][4]- c2*square[k+1][j][i])*wp1- (c1*u[k-1][j][i][4]- c2*square[k-1][j][i])*wm1); } } }); /* * --------------------------------------------------------------------- * add fourth order zeta-direction dissipation * --------------------------------------------------------------------- */ k=1; pf->parallel_for(1, grid_points[1]-1, 1, [&](int j){ int i, m; for(i=1; i<=grid_points[0]-2; i++){ for(m=0; m<5; m++){ rhs[k][j][i][m]=rhs[k][j][i][m]-dssp* (5.0*u[k][j][i][m]-4.0*u[k+1][j][i][m]+ u[k+2][j][i][m]); } } }); k=2; pf->parallel_for(1, grid_points[1]-1, 1, [&](int j){ int i, m; for(i=1; i<=grid_points[0]-2; i++){ for(m=0; m<5; m++){ rhs[k][j][i][m]=rhs[k][j][i][m]-dssp* (-4.0*u[k-1][j][i][m]+6.0*u[k][j][i][m]- 4.0*u[k+1][j][i][m]+u[k+2][j][i][m]); } } }); pf->parallel_for(3, grid_points[2]-3, 1, [&](int k){ int j, i, m; for(j=1; j<=grid_points[1]-2; j++){ for(i=1; i<=grid_points[0]-2; i++){ for(m=0; m<5; m++){ rhs[k][j][i][m]=rhs[k][j][i][m]-dssp* (u[k-2][j][i][m]-4.0*u[k-1][j][i][m]+ 6.0*u[k][j][i][m]-4.0*u[k+1][j][i][m]+ u[k+2][j][i][m]); } } } }); k=grid_points[2]-3; pf->parallel_for(1, grid_points[1]-1, 1, [&](int j){ int i, m; for(i=1; i<=grid_points[0]-2; i++){ for(m=0; m<5; m++){ rhs[k][j][i][m]=rhs[k][j][i][m]-dssp* (u[k-2][j][i][m]-4.0*u[k-1][j][i][m]+ 6.0*u[k][j][i][m]-4.0*u[k+1][j][i][m]); } } }); k=grid_points[2]-2; pf->parallel_for(1, grid_points[1]-1, 1, [&](int j){ int i, m; for(i=1; i<=grid_points[0]-2; i++){ for(m=0; m<5; m++){ rhs[k][j][i][m]=rhs[k][j][i][m]-dssp* (u[k-2][j][i][m]-4.*u[k-1][j][i][m]+ 5.*u[k][j][i][m]); } } }); if(timeron){timer_stop(T_RHSZ);} pf->parallel_for(1, grid_points[2]-1, 1, [&](int k){ int j, i, m; for(j=1; j<=grid_points[1]-2; j++){ for(i=1; i<=grid_points[0]-2; i++){ for(m=0; m<5; m++){ rhs[k][j][i][m]=rhs[k][j][i][m]*dt; } } } }); if(timeron){timer_stop(T_RHS);} } /* * --------------------------------------------------------------------- * this function computes the norm of the difference between the * computed solution and the exact solution * --------------------------------------------------------------------- */ void error_norm(double rms[5]){ int i, j, k, m, d; double xi, eta, zeta, u_exact[5], add; for(m=0;m<5;m++){rms[m]=0.0;} for(k=0; k<=grid_points[2]-1; k++){ zeta=(double)(k)*dnzm1; for(j=0; j<=grid_points[1]-1; j++){ eta=(double)(j)*dnym1; for(i=0; i<=grid_points[0]-1; i++){ xi=(double)(i)*dnxm1; exact_solution(xi, eta, zeta, u_exact); for(m=0; m<5; m++){ add=u[k][j][i][m]-u_exact[m]; rms[m]=rms[m]+add*add; } } } } for(m=0; m<5; m++){ for(d=0; d<3; d++){ rms[m]=rms[m]/(double)(grid_points[d]-2); } rms[m]=sqrt(rms[m]); } } /* * --------------------------------------------------------------------- * compute the right hand side based on exact solution * --------------------------------------------------------------------- */ void exact_rhs(){ double dtemp[5], xi, eta, zeta, dtpp; int m, i, j, k, ip1, im1, jp1, jm1, km1, kp1; /* * --------------------------------------------------------------------- * initialize * --------------------------------------------------------------------- */ for(k=0; k<=grid_points[2]-1; k++){ for(j=0; j<=grid_points[1]-1; j++){ for(i=0; i<=grid_points[0]-1; i++){ for(m=0; m<5; m++){ forcing[k][j][i][m]=0.0; } } } } /* * --------------------------------------------------------------------- * xi-direction flux differences * --------------------------------------------------------------------- */ for(k=1; k<=grid_points[2]-2; k++){ zeta=(double)(k)*dnzm1; for(j=1; j<=grid_points[1]-2; j++){ eta=(double)(j)*dnym1; for(i=0; i<=grid_points[0]-1; i++){ xi=(double)(i)*dnxm1; exact_solution(xi, eta, zeta, dtemp); for(m=0; m<5; m++){ ue[m][i]=dtemp[m]; } dtpp=1.0/dtemp[0]; for(m=1; m<5; m++){ buf[m][i]=dtpp*dtemp[m]; } cuf[i]=buf[1][i]*buf[1][i]; buf[0][i]=cuf[i]+buf[2][i]*buf[2][i]+buf[3][i]*buf[3][i]; q[i]=0.5*(buf[1][i]*ue[1][i]+buf[2][i]*ue[2][i]+ buf[3][i]*ue[3][i]); } for(i=1; i<=grid_points[0]-2; i++){ im1=i-1; ip1=i+1; forcing[k][j][i][0]=forcing[k][j][i][0]- tx2*(ue[1][ip1]-ue[1][im1])+ dx1tx1*(ue[0][ip1]-2.0*ue[0][i]+ue[0][im1]); forcing[k][j][i][1]=forcing[k][j][i][1]-tx2*( (ue[1][ip1]*buf[1][ip1]+c2*(ue[4][ip1]-q[ip1]))- (ue[1][im1]*buf[1][im1]+c2*(ue[4][im1]-q[im1])))+ xxcon1*(buf[1][ip1]-2.0*buf[1][i]+buf[1][im1])+ dx2tx1*(ue[1][ip1]-2.0*ue[1][i]+ue[1][im1]); forcing[k][j][i][2]=forcing[k][j][i][2]-tx2*( ue[2][ip1]*buf[1][ip1]-ue[2][im1]*buf[1][im1])+ xxcon2*(buf[2][ip1]-2.0*buf[2][i]+buf[2][im1])+ dx3tx1*(ue[2][ip1]-2.0*ue[2][i] +ue[2][im1]); forcing[k][j][i][3]=forcing[k][j][i][3]-tx2*( ue[3][ip1]*buf[1][ip1]-ue[3][im1]*buf[1][im1])+ xxcon2*(buf[3][ip1]-2.0*buf[3][i]+buf[3][im1])+ dx4tx1*(ue[3][ip1]-2.0*ue[3][i]+ue[3][im1]); forcing[k][j][i][4]=forcing[k][j][i][4]-tx2*( buf[1][ip1]*(c1*ue[4][ip1]-c2*q[ip1])- buf[1][im1]*(c1*ue[4][im1]-c2*q[im1]))+ 0.5*xxcon3*(buf[0][ip1]-2.0*buf[0][i]+ buf[0][im1])+ xxcon4*(cuf[ip1]-2.0*cuf[i]+cuf[im1])+ xxcon5*(buf[4][ip1]-2.0*buf[4][i]+buf[4][im1])+ dx5tx1*(ue[4][ip1]-2.0*ue[4][i]+ue[4][im1]); } /* * --------------------------------------------------------------------- * fourth-order dissipation * --------------------------------------------------------------------- */ for(m=0; m<5; m++){ i=1; forcing[k][j][i][m]=forcing[k][j][i][m]-dssp* (5.0*ue[m][i]-4.0*ue[m][i+1]+ue[m][i+2]); i=2; forcing[k][j][i][m]=forcing[k][j][i][m]-dssp* (-4.0*ue[m][i-1]+6.0*ue[m][i]- 4.0*ue[m][i+1]+ue[m][i+2]); } for(i=3; i<=grid_points[0]-4; i++){ for(m=0; m<5; m++){ forcing[k][j][i][m]=forcing[k][j][i][m]-dssp* (ue[m][i-2]-4.0*ue[m][i-1]+ 6.0*ue[m][i]-4.0*ue[m][i+1]+ue[m][i+2]); } } for(m=0; m<5; m++){ i=grid_points[0]-3; forcing[k][j][i][m]=forcing[k][j][i][m]-dssp* (ue[m][i-2]-4.0*ue[m][i-1]+ 6.0*ue[m][i]-4.0*ue[m][i+1]); i=grid_points[0]-2; forcing[k][j][i][m]=forcing[k][j][i][m]-dssp* (ue[m][i-2]-4.0*ue[m][i-1]+5.0*ue[m][i]); } } } /* * --------------------------------------------------------------------- * eta-direction flux differences * --------------------------------------------------------------------- */ for(k=1; k<=grid_points[2]-2; k++){ zeta=(double)(k)*dnzm1; for(i=1; i<=grid_points[0]-2; i++){ xi=(double)(i)*dnxm1; for(j=0; j<=grid_points[1]-1; j++){ eta=(double)(j)*dnym1; exact_solution(xi, eta, zeta, dtemp); for(m=0; m<5; m++){ ue[m][j]=dtemp[m]; } dtpp=1.0/dtemp[0]; for(m=1; m<5; m++){ buf[m][j]=dtpp*dtemp[m]; } cuf[j]=buf[2][j]*buf[2][j]; buf[0][j]=cuf[j]+buf[1][j]*buf[1][j]+buf[3][j]*buf[3][j]; q[j]=0.5*(buf[1][j]*ue[1][j]+buf[2][j]*ue[2][j]+ buf[3][j]*ue[3][j]); } for(j=1; j<=grid_points[1]-2; j++){ jm1=j-1; jp1=j+1; forcing[k][j][i][0]=forcing[k][j][i][0]- ty2*(ue[2][jp1]-ue[2][jm1])+ dy1ty1*(ue[0][jp1]-2.0*ue[0][j]+ue[0][jm1]); forcing[k][j][i][1]=forcing[k][j][i][1]-ty2*( ue[1][jp1]*buf[2][jp1]-ue[1][jm1]*buf[2][jm1])+ yycon2*(buf[1][jp1]-2.0*buf[1][j]+buf[1][jm1])+ dy2ty1*(ue[1][jp1]-2.0*ue[1][j]+ue[1][jm1]); forcing[k][j][i][2]=forcing[k][j][i][2]-ty2*( (ue[2][jp1]*buf[2][jp1]+c2*(ue[4][jp1]-q[jp1]))- (ue[2][jm1]*buf[2][jm1]+c2*(ue[4][jm1]-q[jm1])))+ yycon1*(buf[2][jp1]-2.0*buf[2][j]+buf[2][jm1])+ dy3ty1*(ue[2][jp1]-2.0*ue[2][j]+ue[2][jm1]); forcing[k][j][i][3]=forcing[k][j][i][3]-ty2*( ue[3][jp1]*buf[2][jp1]-ue[3][jm1]*buf[2][jm1])+ yycon2*(buf[3][jp1]-2.0*buf[3][j]+buf[3][jm1])+ dy4ty1*(ue[3][jp1]-2.0*ue[3][j]+ue[3][jm1]); forcing[k][j][i][4]=forcing[k][j][i][4]-ty2*( buf[2][jp1]*(c1*ue[4][jp1]-c2*q[jp1])- buf[2][jm1]*(c1*ue[4][jm1]-c2*q[jm1]))+ 0.5*yycon3*(buf[0][jp1]-2.0*buf[0][j]+ buf[0][jm1])+ yycon4*(cuf[jp1]-2.0*cuf[j]+cuf[jm1])+ yycon5*(buf[4][jp1]-2.0*buf[4][j]+buf[4][jm1])+ dy5ty1*(ue[4][jp1]-2.0*ue[4][j]+ue[4][jm1]); } /* * --------------------------------------------------------------------- * fourth-order dissipation * --------------------------------------------------------------------- */ for(m=0; m<5; m++){ j=1; forcing[k][j][i][m]=forcing[k][j][i][m]-dssp* (5.0*ue[m][j]-4.0*ue[m][j+1] +ue[m][j+2]); j=2; forcing[k][j][i][m]=forcing[k][j][i][m]-dssp* (-4.0*ue[m][j-1]+6.0*ue[m][j]- 4.0*ue[m][j+1]+ue[m][j+2]); } for(j=3; j<=grid_points[1]-4; j++){ for(m=0; m<5; m++){ forcing[k][j][i][m]=forcing[k][j][i][m]-dssp* (ue[m][j-2]-4.0*ue[m][j-1]+ 6.0*ue[m][j]-4.0*ue[m][j+1]+ue[m][j+2]); } } for(m=0; m<5; m++){ j=grid_points[1]-3; forcing[k][j][i][m]=forcing[k][j][i][m]-dssp* (ue[m][j-2]-4.0*ue[m][j-1]+ 6.0*ue[m][j]-4.0*ue[m][j+1]); j=grid_points[1]-2; forcing[k][j][i][m]=forcing[k][j][i][m]-dssp* (ue[m][j-2]-4.0*ue[m][j-1]+5.0*ue[m][j]); } } } /* * --------------------------------------------------------------------- * zeta-direction flux differences * --------------------------------------------------------------------- */ for(j=1; j<=grid_points[1]-2; j++){ eta=(double)(j)*dnym1; for(i=1; i<=grid_points[0]-2; i++){ xi=(double)(i)*dnxm1; for(k=0; k<=grid_points[2]-1; k++){ zeta=(double)(k)*dnzm1; exact_solution(xi, eta, zeta, dtemp); for(m=0; m<5; m++){ ue[m][k]=dtemp[m]; } dtpp=1.0/dtemp[0]; for(m=1; m<5; m++){ buf[m][k]=dtpp*dtemp[m]; } cuf[k]=buf[3][k]*buf[3][k]; buf[0][k]=cuf[k]+buf[1][k]*buf[1][k]+buf[2][k]*buf[2][k]; q[k]=0.5*(buf[1][k]*ue[1][k]+buf[2][k]*ue[2][k]+ buf[3][k]*ue[3][k]); } for(k=1; k<=grid_points[2]-2; k++){ km1=k-1; kp1=k+1; forcing[k][j][i][0]=forcing[k][j][i][0]- tz2*(ue[3][kp1]-ue[3][km1])+ dz1tz1*(ue[0][kp1]-2.0*ue[0][k]+ue[0][km1]); forcing[k][j][i][1]=forcing[k][j][i][1]-tz2*( ue[1][kp1]*buf[3][kp1]-ue[1][km1]*buf[3][km1])+ zzcon2*(buf[1][kp1]-2.0*buf[1][k]+buf[1][km1])+ dz2tz1*(ue[1][kp1]-2.0*ue[1][k]+ue[1][km1]); forcing[k][j][i][2]=forcing[k][j][i][2]-tz2*( ue[2][kp1]*buf[3][kp1]-ue[2][km1]*buf[3][km1])+ zzcon2*(buf[2][kp1]-2.0*buf[2][k]+buf[2][km1])+ dz3tz1*(ue[2][kp1]-2.0*ue[2][k]+ue[2][km1]); forcing[k][j][i][3]=forcing[k][j][i][3]-tz2*( (ue[3][kp1]*buf[3][kp1]+c2*(ue[4][kp1]-q[kp1]))- (ue[3][km1]*buf[3][km1]+c2*(ue[4][km1]-q[km1])))+ zzcon1*(buf[3][kp1]-2.0*buf[3][k]+buf[3][km1])+ dz4tz1*(ue[3][kp1]-2.0*ue[3][k]+ue[3][km1]); forcing[k][j][i][4]=forcing[k][j][i][4]-tz2*( buf[3][kp1]*(c1*ue[4][kp1]-c2*q[kp1])- buf[3][km1]*(c1*ue[4][km1]-c2*q[km1]))+ 0.5*zzcon3*(buf[0][kp1]-2.0*buf[0][k] +buf[0][km1])+ zzcon4*(cuf[kp1]-2.0*cuf[k]+cuf[km1])+ zzcon5*(buf[4][kp1]-2.0*buf[4][k]+buf[4][km1])+ dz5tz1*(ue[4][kp1]-2.0*ue[4][k]+ue[4][km1]); } /* * --------------------------------------------------------------------- * fourth-order dissipation * --------------------------------------------------------------------- */ for(m=0; m<5; m++){ k=1; forcing[k][j][i][m]=forcing[k][j][i][m]-dssp* (5.0*ue[m][k]-4.0*ue[m][k+1]+ue[m][k+2]); k=2; forcing[k][j][i][m]=forcing[k][j][i][m]-dssp* (-4.0*ue[m][k-1]+6.0*ue[m][k]- 4.0*ue[m][k+1]+ue[m][k+2]); } for(k=3; k<=grid_points[2]-4; k++){ for(m=0; m<5; m++){ forcing[k][j][i][m]=forcing[k][j][i][m]-dssp* (ue[m][k-2]-4.0*ue[m][k-1]+ 6.0*ue[m][k]-4.0*ue[m][k+1]+ue[m][k+2]); } } for(m=0; m<5; m++){ k=grid_points[2]-3; forcing[k][j][i][m]=forcing[k][j][i][m]-dssp* (ue[m][k-2]-4.0*ue[m][k-1]+ 6.0*ue[m][k]-4.0*ue[m][k+1]); k=grid_points[2]-2; forcing[k][j][i][m]=forcing[k][j][i][m]-dssp* (ue[m][k-2]-4.0*ue[m][k-1]+5.0*ue[m][k]); } } } /* * --------------------------------------------------------------------- * now change the sign of the forcing function * --------------------------------------------------------------------- */ for(k=1; k<=grid_points[2]-2; k++){ for(j=1; j<=grid_points[1]-2; j++){ for(i=1; i<=grid_points[0]-2; i++){ for(m=0; m<5; m++){ forcing[k][j][i][m]=-1.0*forcing[k][j][i][m]; } } } } } /* * --------------------------------------------------------------------- * this function returns the exact solution at point xi, eta, zeta * --------------------------------------------------------------------- */ void exact_solution(double xi, double eta, double zeta, double dtemp[5]){ int m; for(m=0; m<5; m++){ dtemp[m]=ce[0][m]+ xi*(ce[1][m]+ xi*(ce[4][m]+ xi*(ce[7][m]+ xi*ce[10][m])))+ eta*(ce[2][m]+ eta*(ce[5][m]+ eta*(ce[8][m]+ eta*ce[11][m])))+ zeta*(ce[3][m]+ zeta*(ce[6][m]+ zeta*(ce[9][m]+ zeta*ce[12][m]))); } } /* * --------------------------------------------------------------------- * this subroutine initializes the field variable u using * tri-linear transfinite interpolation of the boundary values * --------------------------------------------------------------------- */ void initialize(){ int i, j, k, m, ix, iy, iz; double xi, eta, zeta, Pface[2][3][5], Pxi, Peta, Pzeta, temp[5]; /* * --------------------------------------------------------------------- * later (in compute_rhs) we compute 1/u for every element. a few of * the corner elements are not used, but it convenient (and faster) * to compute the whole thing with a simple loop. make sure those * values are nonzero by initializing the whole thing here. * --------------------------------------------------------------------- */ pf->parallel_for(0, grid_points[2]-1+1, 1, [&](int k){ int j, i, m; for(j=0; j<=grid_points[1]-1; j++){ for(i=0; i<=grid_points[0]-1; i++){ for(m=0; m<5; m++){ u[k][j][i][m]=1.0; } } } }); /* * --------------------------------------------------------------------- * first store the "interpolated" values everywhere on the grid * --------------------------------------------------------------------- */ pf->parallel_for(0, grid_points[2], 1, [&](int k){ double xi, eta, zeta; double Pxi, Peta, Pzeta; int i, j, ix, iy, iz, m; double Pface[2][3][5]; zeta=(double)(k)* dnzm1; for(j=0; j<=grid_points[1]-1; j++){ eta=(double)(j)*dnym1; for(i=0; i<=grid_points[0]-1; i++){ xi=(double)(i)*dnxm1; for(ix=0; ix<2; ix++){ exact_solution((double)ix, eta, zeta, &Pface[ix][0][0]); } for(iy=0; iy<2; iy++){ exact_solution(xi, (double)iy , zeta, &Pface[iy][1][0]); } for(iz=0; iz<2; iz++){ exact_solution(xi, eta, (double)iz, &Pface[iz][2][0]); } for(m=0; m<5; m++){ Pxi=xi*Pface[1][0][m]+(1.0-xi)*Pface[0][0][m]; Peta=eta*Pface[1][1][m]+(1.0-eta)*Pface[0][1][m]; Pzeta=zeta*Pface[1][2][m]+(1.0-zeta)*Pface[0][2][m]; u[k][j][i][m]=Pxi+Peta+Pzeta- Pxi*Peta-Pxi*Pzeta-Peta*Pzeta+ Pxi*Peta*Pzeta; } } } }); /* * --------------------------------------------------------------------- * now store the exact values on the boundaries * --------------------------------------------------------------------- * west face * --------------------------------------------------------------------- */ i=0; xi=0.0; pf->parallel_for(0, grid_points[2]-1+1, 1, [&](int k){ int j, m; double zeta, eta, temp[5]; zeta=(double)(k)*dnzm1; for(j=0; j<=grid_points[1]-1; j++){ eta=(double)(j)*dnym1; exact_solution(xi, eta, zeta, temp); for(m=0; m<5; m++){ u[k][j][i][m]=temp[m]; } } }); /* * --------------------------------------------------------------------- * east face * --------------------------------------------------------------------- */ i=grid_points[0]-1; xi=1.0; pf->parallel_for(0, grid_points[2]-1+1, 1, [&](int k){ int j, m; double zeta, eta, temp[5]; zeta=(double)(k)*dnzm1; for(j=0; j<=grid_points[1]-1; j++){ eta=(double)(j)*dnym1; exact_solution(xi, eta, zeta, temp); for(m=0; m<5; m++){ u[k][j][i][m]=temp[m]; } } }); /* * --------------------------------------------------------------------- * south face * --------------------------------------------------------------------- */ j=0; eta=0.0; pf->parallel_for(0, grid_points[2]-1+1, 1, [&](int k){ int i, m; double zeta, temp[5], xi; zeta=(double)(k)*dnzm1; for(i=0; i<=grid_points[0]-1; i++){ xi=(double)(i)*dnxm1; exact_solution(xi, eta, zeta, temp); for(m=0; m<5; m++){ u[k][j][i][m]=temp[m]; } } }); /* * --------------------------------------------------------------------- * north face * --------------------------------------------------------------------- */ j=grid_points[1]-1; eta=1.0; pf->parallel_for(0, grid_points[2]-1+1, 1, [&](int k){ int i, m; double zeta, temp[5], xi; zeta=(double)(k)*dnzm1; for(i=0; i<=grid_points[0]-1; i++){ xi=(double)(i)*dnxm1; exact_solution(xi, eta, zeta, temp); for(m=0; m<5; m++){ u[k][j][i][m]=temp[m]; } } }); /* * --------------------------------------------------------------------- * bottom face * --------------------------------------------------------------------- */ k=0; zeta=0.0; pf->parallel_for(0, grid_points[1]-1+1, 1, [&](int j){ int i, m; double eta, temp[5], xi; eta=(double)(j)*dnym1; for(i=0; i<=grid_points[0]-1; i++){ xi=(double)(i)*dnxm1; exact_solution(xi, eta, zeta, temp); for(m=0; m<5; m++){ u[k][j][i][m]=temp[m]; } } }); /* * --------------------------------------------------------------------- * top face * --------------------------------------------------------------------- */ k=grid_points[2]-1; zeta=1.0; pf->parallel_for(0, grid_points[1]-1+1, 1, [&](int j){ int i, m; double eta, temp[5], xi; eta=(double)(j)*dnym1; for(i=0; i<=grid_points[0]-1; i++){ xi=(double)(i)*dnxm1; exact_solution(xi, eta, zeta, temp); for(m=0; m<5; m++){ u[k][j][i][m]=temp[m]; } } }); } void lhsinit(double lhs[][3][5][5], int size){ int i, m, n; i=size; /* * --------------------------------------------------------------------- * zero the whole left hand side for starters * --------------------------------------------------------------------- */ for(m=0; m<5; m++){ for(n=0; n<5; n++){ lhs[0][0][n][m]=0.0; lhs[0][1][n][m]=0.0; lhs[0][2][n][m]=0.0; lhs[i][0][n][m]=0.0; lhs[i][1][n][m]=0.0; lhs[i][2][n][m]=0.0; } } /* * --------------------------------------------------------------------- * next, set all diagonal values to 1. This is overkill, but convenient * --------------------------------------------------------------------- */ for(m=0; m<5; m++){ lhs[0][1][m][m]=1.0; lhs[i][1][m][m]=1.0; } } /* * --------------------------------------------------------------------- * subtracts a(i,j,k) X b(i,j,k) from c(i,j,k) * --------------------------------------------------------------------- */ void matmul_sub(double ablock[5][5], double bblock[5][5], double cblock[5][5]){ cblock[0][0]=cblock[0][0]-ablock[0][0]*bblock[0][0] -ablock[1][0]*bblock[0][1] -ablock[2][0]*bblock[0][2] -ablock[3][0]*bblock[0][3] -ablock[4][0]*bblock[0][4]; cblock[0][1]=cblock[0][1]-ablock[0][1]*bblock[0][0] -ablock[1][1]*bblock[0][1] -ablock[2][1]*bblock[0][2] -ablock[3][1]*bblock[0][3] -ablock[4][1]*bblock[0][4]; cblock[0][2]=cblock[0][2]-ablock[0][2]*bblock[0][0] -ablock[1][2]*bblock[0][1] -ablock[2][2]*bblock[0][2] -ablock[3][2]*bblock[0][3] -ablock[4][2]*bblock[0][4]; cblock[0][3]=cblock[0][3]-ablock[0][3]*bblock[0][0] -ablock[1][3]*bblock[0][1] -ablock[2][3]*bblock[0][2] -ablock[3][3]*bblock[0][3] -ablock[4][3]*bblock[0][4]; cblock[0][4]=cblock[0][4]-ablock[0][4]*bblock[0][0] -ablock[1][4]*bblock[0][1] -ablock[2][4]*bblock[0][2] -ablock[3][4]*bblock[0][3] -ablock[4][4]*bblock[0][4]; cblock[1][0]=cblock[1][0]-ablock[0][0]*bblock[1][0] -ablock[1][0]*bblock[1][1] -ablock[2][0]*bblock[1][2] -ablock[3][0]*bblock[1][3] -ablock[4][0]*bblock[1][4]; cblock[1][1]=cblock[1][1]-ablock[0][1]*bblock[1][0] -ablock[1][1]*bblock[1][1] -ablock[2][1]*bblock[1][2] -ablock[3][1]*bblock[1][3] -ablock[4][1]*bblock[1][4]; cblock[1][2]=cblock[1][2]-ablock[0][2]*bblock[1][0] -ablock[1][2]*bblock[1][1] -ablock[2][2]*bblock[1][2] -ablock[3][2]*bblock[1][3] -ablock[4][2]*bblock[1][4]; cblock[1][3]=cblock[1][3]-ablock[0][3]*bblock[1][0] -ablock[1][3]*bblock[1][1] -ablock[2][3]*bblock[1][2] -ablock[3][3]*bblock[1][3] -ablock[4][3]*bblock[1][4]; cblock[1][4]=cblock[1][4]-ablock[0][4]*bblock[1][0] -ablock[1][4]*bblock[1][1] -ablock[2][4]*bblock[1][2] -ablock[3][4]*bblock[1][3] -ablock[4][4]*bblock[1][4]; cblock[2][0]=cblock[2][0]-ablock[0][0]*bblock[2][0] -ablock[1][0]*bblock[2][1] -ablock[2][0]*bblock[2][2] -ablock[3][0]*bblock[2][3] -ablock[4][0]*bblock[2][4]; cblock[2][1]=cblock[2][1]-ablock[0][1]*bblock[2][0] -ablock[1][1]*bblock[2][1] -ablock[2][1]*bblock[2][2] -ablock[3][1]*bblock[2][3] -ablock[4][1]*bblock[2][4]; cblock[2][2]=cblock[2][2]-ablock[0][2]*bblock[2][0] -ablock[1][2]*bblock[2][1] -ablock[2][2]*bblock[2][2] -ablock[3][2]*bblock[2][3] -ablock[4][2]*bblock[2][4]; cblock[2][3]=cblock[2][3]-ablock[0][3]*bblock[2][0] -ablock[1][3]*bblock[2][1] -ablock[2][3]*bblock[2][2] -ablock[3][3]*bblock[2][3] -ablock[4][3]*bblock[2][4]; cblock[2][4]=cblock[2][4]-ablock[0][4]*bblock[2][0] -ablock[1][4]*bblock[2][1] -ablock[2][4]*bblock[2][2] -ablock[3][4]*bblock[2][3] -ablock[4][4]*bblock[2][4]; cblock[3][0]=cblock[3][0]-ablock[0][0]*bblock[3][0] -ablock[1][0]*bblock[3][1] -ablock[2][0]*bblock[3][2] -ablock[3][0]*bblock[3][3] -ablock[4][0]*bblock[3][4]; cblock[3][1]=cblock[3][1]-ablock[0][1]*bblock[3][0] -ablock[1][1]*bblock[3][1] -ablock[2][1]*bblock[3][2] -ablock[3][1]*bblock[3][3] -ablock[4][1]*bblock[3][4]; cblock[3][2]=cblock[3][2]-ablock[0][2]*bblock[3][0] -ablock[1][2]*bblock[3][1] -ablock[2][2]*bblock[3][2] -ablock[3][2]*bblock[3][3] -ablock[4][2]*bblock[3][4]; cblock[3][3]=cblock[3][3]-ablock[0][3]*bblock[3][0] -ablock[1][3]*bblock[3][1] -ablock[2][3]*bblock[3][2] -ablock[3][3]*bblock[3][3] -ablock[4][3]*bblock[3][4]; cblock[3][4]=cblock[3][4]-ablock[0][4]*bblock[3][0] -ablock[1][4]*bblock[3][1] -ablock[2][4]*bblock[3][2] -ablock[3][4]*bblock[3][3] -ablock[4][4]*bblock[3][4]; cblock[4][0]=cblock[4][0]-ablock[0][0]*bblock[4][0] -ablock[1][0]*bblock[4][1] -ablock[2][0]*bblock[4][2] -ablock[3][0]*bblock[4][3] -ablock[4][0]*bblock[4][4]; cblock[4][1]=cblock[4][1]-ablock[0][1]*bblock[4][0] -ablock[1][1]*bblock[4][1] -ablock[2][1]*bblock[4][2] -ablock[3][1]*bblock[4][3] -ablock[4][1]*bblock[4][4]; cblock[4][2]=cblock[4][2]-ablock[0][2]*bblock[4][0] -ablock[1][2]*bblock[4][1] -ablock[2][2]*bblock[4][2] -ablock[3][2]*bblock[4][3] -ablock[4][2]*bblock[4][4]; cblock[4][3]=cblock[4][3]-ablock[0][3]*bblock[4][0] -ablock[1][3]*bblock[4][1] -ablock[2][3]*bblock[4][2] -ablock[3][3]*bblock[4][3] -ablock[4][3]*bblock[4][4]; cblock[4][4]=cblock[4][4]-ablock[0][4]*bblock[4][0] -ablock[1][4]*bblock[4][1] -ablock[2][4]*bblock[4][2] -ablock[3][4]*bblock[4][3] -ablock[4][4]*bblock[4][4]; } /* * --------------------------------------------------------------------- * subtracts bvec=bvec - ablock*avec * --------------------------------------------------------------------- */ void matvec_sub(double ablock[5][5], double avec[5], double bvec[5]){ /* * --------------------------------------------------------------------- * rhs[kc][jc][ic][i] = rhs[kc][jc][ic][i] - lhs[ia][ablock][0][i]* * --------------------------------------------------------------------- */ bvec[0]=bvec[0]-ablock[0][0]*avec[0] -ablock[1][0]*avec[1] -ablock[2][0]*avec[2] -ablock[3][0]*avec[3] -ablock[4][0]*avec[4]; bvec[1]=bvec[1]-ablock[0][1]*avec[0] -ablock[1][1]*avec[1] -ablock[2][1]*avec[2] -ablock[3][1]*avec[3] -ablock[4][1]*avec[4]; bvec[2]=bvec[2]-ablock[0][2]*avec[0] -ablock[1][2]*avec[1] -ablock[2][2]*avec[2] -ablock[3][2]*avec[3] -ablock[4][2]*avec[4]; bvec[3]=bvec[3]-ablock[0][3]*avec[0] -ablock[1][3]*avec[1] -ablock[2][3]*avec[2] -ablock[3][3]*avec[3] -ablock[4][3]*avec[4]; bvec[4]=bvec[4]-ablock[0][4]*avec[0] -ablock[1][4]*avec[1] -ablock[2][4]*avec[2] -ablock[3][4]*avec[3] -ablock[4][4]*avec[4]; } void rhs_norm(double rms[5]){ int i, j, k, d, m; double add; for(m=0; m<5; m++){ rms[m]=0.0; } for(k=1; k<=grid_points[2]-2; k++){ for(j=1; j<=grid_points[1]-2; j++){ for(i=1; i<=grid_points[0]-2; i++){ for(m=0; m<5; m++) { add=rhs[k][j][i][m]; rms[m]=rms[m]+add*add; } } } } for(m=0; m<5; m++){ for(d=0; d<3; d++){ rms[m]=rms[m]/(double)(grid_points[d]-2); } rms[m]=sqrt(rms[m]); } } void set_constants(){ ce[0][0]=2.0; ce[1][0]=0.0; ce[2][0]=0.0; ce[3][0]=4.0; ce[4][0]=5.0; ce[5][0]=3.0; ce[6][0]=0.5; ce[7][0]=0.02; ce[8][0]=0.01; ce[9][0]=0.03; ce[10][0]=0.5; ce[11][0]=0.4; ce[12][0]=0.3; /* */ ce[0][1]=1.0; ce[1][1]=0.0; ce[2][1]=0.0; ce[3][1]=0.0; ce[4][1]=1.0; ce[5][1]=2.0; ce[6][1]=3.0; ce[7][1]=0.01; ce[8][1]=0.03; ce[9][1]=0.02; ce[10][1]=0.4; ce[11][1]=0.3; ce[12][1]=0.5; /* */ ce[0][2]=2.0; ce[1][2]=2.0; ce[2][2]=0.0; ce[3][2]=0.0; ce[4][2]=0.0; ce[5][2]=2.0; ce[6][2]=3.0; ce[7][2]=0.04; ce[8][2]=0.03; ce[9][2]=0.05; ce[10][2]=0.3; ce[11][2]=0.5; ce[12][2]=0.4; /* */ ce[0][3]=2.0; ce[1][3]=2.0; ce[2][3]=0.0; ce[3][3]=0.0; ce[4][3]=0.0; ce[5][3]=2.0; ce[6][3]=3.0; ce[7][3]=0.03; ce[8][3]=0.05; ce[9][3]=0.04; ce[10][3]=0.2; ce[11][3]=0.1; ce[12][3]=0.3; /* */ ce[0][4]=5.0; ce[1][4]=4.0; ce[2][4]=3.0; ce[3][4]=2.0; ce[4][4]=0.1; ce[5][4]=0.4; ce[6][4]=0.3; ce[7][4]=0.05; ce[8][4]=0.04; ce[9][4]=0.03; ce[10][4]=0.1; ce[11][4]=0.3; ce[12][4]=0.2; /* */ c1=1.4; c2=0.4; c3=0.1; c4=1.0; c5=1.4; dnxm1=1.0/(double)(grid_points[0]-1); dnym1=1.0/(double)(grid_points[1]-1); dnzm1=1.0/(double)(grid_points[2]-1); c1c2=c1*c2; c1c5=c1*c5; c3c4=c3*c4; c1345=c1c5*c3c4; conz1=(1.0-c1c5); tx1=1.0/(dnxm1*dnxm1); tx2=1.0/(2.0*dnxm1); tx3=1.0/dnxm1; ty1=1.0/(dnym1*dnym1); ty2=1.0/(2.0*dnym1); ty3=1.0/dnym1; tz1=1.0/(dnzm1*dnzm1); tz2=1.0/(2.0*dnzm1); tz3=1.0/dnzm1; dx1=0.75; dx2=0.75; dx3=0.75; dx4=0.75; dx5=0.75; dy1=0.75; dy2=0.75; dy3=0.75; dy4=0.75; dy5=0.75; dz1=1.0; dz2=1.0; dz3=1.0; dz4=1.0; dz5=1.0; dxmax=max(dx3, dx4); dymax=max(dy2, dy4); dzmax=max(dz2, dz3); dssp=0.25*max(dx1, max(dy1, dz1)); c4dssp=4.0*dssp; c5dssp=5.0*dssp; dttx1=dt*tx1; dttx2=dt*tx2; dtty1=dt*ty1; dtty2=dt*ty2; dttz1=dt*tz1; dttz2=dt*tz2; c2dttx1=2.0*dttx1; c2dtty1=2.0*dtty1; c2dttz1=2.0*dttz1; dtdssp=dt*dssp; comz1=dtdssp; comz4=4.0*dtdssp; comz5=5.0*dtdssp; comz6=6.0*dtdssp; c3c4tx3=c3c4*tx3; c3c4ty3=c3c4*ty3; c3c4tz3=c3c4*tz3; dx1tx1=dx1*tx1; dx2tx1=dx2*tx1; dx3tx1=dx3*tx1; dx4tx1=dx4*tx1; dx5tx1=dx5*tx1; dy1ty1=dy1*ty1; dy2ty1=dy2*ty1; dy3ty1=dy3*ty1; dy4ty1=dy4*ty1; dy5ty1=dy5*ty1; dz1tz1=dz1*tz1; dz2tz1=dz2*tz1; dz3tz1=dz3*tz1; dz4tz1=dz4*tz1; dz5tz1=dz5*tz1; c2iv=2.5; con43=4.0/3.0; con16=1.0/6.0; xxcon1=c3c4tx3*con43*tx3; xxcon2=c3c4tx3*tx3; xxcon3=c3c4tx3*conz1*tx3; xxcon4=c3c4tx3*con16*tx3; xxcon5=c3c4tx3*c1c5*tx3; yycon1=c3c4ty3*con43*ty3; yycon2=c3c4ty3*ty3; yycon3=c3c4ty3*conz1*ty3; yycon4=c3c4ty3*con16*ty3; yycon5=c3c4ty3*c1c5*ty3; zzcon1=c3c4tz3*con43*tz3; zzcon2=c3c4tz3*tz3; zzcon3=c3c4tz3*conz1*tz3; zzcon4=c3c4tz3*con16*tz3; zzcon5=c3c4tz3*c1c5*tz3; } /* * --------------------------------------------------------------------- * verification routine * --------------------------------------------------------------------- */ void verify(int no_time_steps, char* class_npb, boolean* verified){ double xcrref[5], xceref[5], xcrdif[5], xcedif[5]; double epsilon, xce[5], xcr[5], dtref=0.0; int m; /* * --------------------------------------------------------------------- * tolerance level * --------------------------------------------------------------------- */ epsilon=1.0e-08; /* * --------------------------------------------------------------------- * compute the error norm and the residual norm, and exit if not printing * --------------------------------------------------------------------- */ error_norm(xce); compute_rhs(); rhs_norm(xcr); for(m=0; m<5; m++){ xcr[m]=xcr[m]/dt; } *class_npb='U'; *verified=TRUE; for(m=0; m<5; m++){ xcrref[m]=1.0; xceref[m]=1.0; } /* * --------------------------------------------------------------------- * reference data for 12X12X12 grids after 60 time steps, with DT = 1.0e-02 * --------------------------------------------------------------------- */ if((grid_points[0]==12)&& (grid_points[1]==12)&& (grid_points[2]==12)&& (no_time_steps==60)){ *class_npb='S'; dtref=1.0e-2; /* * --------------------------------------------------------------------- * reference values of RMS-norms of residual. * --------------------------------------------------------------------- */ xcrref[0]=1.7034283709541311e-01; xcrref[1]=1.2975252070034097e-02; xcrref[2]=3.2527926989486055e-02; xcrref[3]=2.6436421275166801e-02; xcrref[4]=1.9211784131744430e-01; /* * --------------------------------------------------------------------- * reference values of RMS-norms of solution error. * --------------------------------------------------------------------- */ xceref[0]=4.9976913345811579e-04; xceref[1]=4.5195666782961927e-05; xceref[2]=7.3973765172921357e-05; xceref[3]=7.3821238632439731e-05; xceref[4]=8.9269630987491446e-04; /* * --------------------------------------------------------------------- * reference data for 24X24X24 grids after 200 time steps, with DT = 0.8d-3 * --------------------------------------------------------------------- */ }else if((grid_points[0]==24)&& (grid_points[1]==24)&& (grid_points[2]==24)&& (no_time_steps==200)){ *class_npb='W'; dtref = 0.8e-3; /* * --------------------------------------------------------------------- * reference values of RMS-norms of residual. * --------------------------------------------------------------------- */ xcrref[0]=0.1125590409344e+03; xcrref[1]=0.1180007595731e+02; xcrref[2]=0.2710329767846e+02; xcrref[3]=0.2469174937669e+02; xcrref[4]=0.2638427874317e+03; /* * --------------------------------------------------------------------- * reference values of RMS-norms of solution error. * --------------------------------------------------------------------- */ xceref[0]=0.4419655736008e+01; xceref[1]=0.4638531260002e+00; xceref[2]=0.1011551749967e+01; xceref[3]=0.9235878729944e+00; xceref[4]=0.1018045837718e+02; /* * --------------------------------------------------------------------- * reference data for 64X64X64 grids after 200 time steps, with DT = 0.8d-3 * --------------------------------------------------------------------- */ }else if((grid_points[0]==64)&& (grid_points[1]==64)&& (grid_points[2]==64)&& (no_time_steps==200)){ *class_npb='A'; dtref=0.8e-3; /* * --------------------------------------------------------------------- * reference values of RMS-norms of residual. * --------------------------------------------------------------------- */ xcrref[0]=1.0806346714637264e+02; xcrref[1]=1.1319730901220813e+01; xcrref[2]=2.5974354511582465e+01; xcrref[3]=2.3665622544678910e+01; xcrref[4]=2.5278963211748344e+02; /* * --------------------------------------------------------------------- * reference values of RMS-norms of solution error. * --------------------------------------------------------------------- */ xceref[0]=4.2348416040525025e+00; xceref[1]=4.4390282496995698e-01; xceref[2]=9.6692480136345650e-01; xceref[3]=8.8302063039765474e-01; xceref[4]=9.7379901770829278e+00; /* * --------------------------------------------------------------------- * reference data for 102X102X102 grids after 200 time steps, * with DT = 3.0e-04 * --------------------------------------------------------------------- */ }else if((grid_points[0]==102)&& (grid_points[1]==102)&& (grid_points[2]==102)&& (no_time_steps==200)){ *class_npb='B'; dtref=3.0e-4; /* * --------------------------------------------------------------------- * reference values of RMS-norms of residual. * --------------------------------------------------------------------- */ xcrref[0]=1.4233597229287254e+03; xcrref[1]=9.9330522590150238e+01; xcrref[2]=3.5646025644535285e+02; xcrref[3]=3.2485447959084092e+02; xcrref[4]=3.2707541254659363e+03; /* * --------------------------------------------------------------------- * reference values of RMS-norms of solution error. * --------------------------------------------------------------------- */ xceref[0]=5.2969847140936856e+01; xceref[1]=4.4632896115670668e+00; xceref[2]=1.3122573342210174e+01; xceref[3]=1.2006925323559144e+01; xceref[4]=1.2459576151035986e+02; /* * --------------------------------------------------------------------- * reference data for 162X162X162 grids after 200 time steps, * with DT = 1.0e-04 * --------------------------------------------------------------------- */ }else if((grid_points[0]==162)&& (grid_points[1]==162)&& (grid_points[2]==162)&& (no_time_steps==200)){ *class_npb='C'; dtref=1.0e-4; /* * --------------------------------------------------------------------- * reference values of RMS-norms of residual. * --------------------------------------------------------------------- */ xcrref[0]=0.62398116551764615e+04; xcrref[1]=0.50793239190423964e+03; xcrref[2]=0.15423530093013596e+04; xcrref[3]=0.13302387929291190e+04; xcrref[4]=0.11604087428436455e+05; /* * --------------------------------------------------------------------- * reference values of RMS-norms of solution error. * --------------------------------------------------------------------- */ xceref[0]=0.16462008369091265e+03; xceref[1]=0.11497107903824313e+02; xceref[2]=0.41207446207461508e+02; xceref[3]=0.37087651059694167e+02; xceref[4]=0.36211053051841265e+03; /* * --------------------------------------------------------------------- * reference data for 408x408x408 grids after 250 time steps, * with DT = 0.2e-04 * --------------------------------------------------------------------- */ }else if((grid_points[0]==408)&& (grid_points[1]==408)&& (grid_points[2]==408)&& (no_time_steps==250)){ *class_npb='D'; dtref=0.2e-4; /* * --------------------------------------------------------------------- * reference values of RMS-norms of residual. * --------------------------------------------------------------------- */ xcrref[0]=0.2533188551738e+05; xcrref[1]=0.2346393716980e+04; xcrref[2]=0.6294554366904e+04; xcrref[3]=0.5352565376030e+04; xcrref[4]=0.3905864038618e+05; /* * --------------------------------------------------------------------- * reference values of RMS-norms of solution error. * --------------------------------------------------------------------- */ xceref[0]=0.3100009377557e+03; xceref[1]=0.2424086324913e+02; xceref[2]=0.7782212022645e+02; xceref[3]=0.6835623860116e+02; xceref[4]=0.6065737200368e+03; /* * --------------------------------------------------------------------- * reference data for 1020x1020x1020 grids after 250 time steps, * with DT = 0.4e-05 * --------------------------------------------------------------------- */ }else if((grid_points[0]==1020)&& (grid_points[1]==1020)&& (grid_points[2]==1020)&& (no_time_steps==250)){ *class_npb='E'; dtref=0.4e-5; /* * --------------------------------------------------------------------- * reference values of RMS-norms of residual. * --------------------------------------------------------------------- */ xcrref[0]=0.9795372484517e+05; xcrref[1]=0.9739814511521e+04; xcrref[2]=0.2467606342965e+05; xcrref[3]=0.2092419572860e+05; xcrref[4]=0.1392138856939e+06; /* * --------------------------------------------------------------------- * reference values of RMS-norms of solution error. * --------------------------------------------------------------------- */ xceref[0]=0.4327562208414e+03; xceref[1]=0.3699051964887e+02; xceref[2]=0.1089845040954e+03; xceref[3]=0.9462517622043e+02; xceref[4]=0.7765512765309e+03; }else{ *verified=FALSE; } /* * --------------------------------------------------------------------- * verification test for residuals if gridsize is one of * the defined grid sizes above (*class_npb != 'U') * --------------------------------------------------------------------- * compute the difference of solution values and the known reference values. * --------------------------------------------------------------------- */ for(m=0; m<5; m++){ xcrdif[m]=fabs((xcr[m]-xcrref[m])/xcrref[m]); xcedif[m]=fabs((xce[m]-xceref[m])/xceref[m]); } /* * --------------------------------------------------------------------- * output the comparison of computed results to known cases. * --------------------------------------------------------------------- */ if(*class_npb!='U'){ printf(" Verification being performed for class_npb %c\n",*class_npb); printf(" accuracy setting for epsilon = %20.13E\n",epsilon); *verified=(fabs(dt-dtref)<=epsilon); if(!(*verified)){ *class_npb='U'; printf(" DT does not match the reference value of %15.8E\n",dtref); } }else{ printf(" Unknown class_npb\n"); } if(*class_npb!='U'){ printf(" Comparison of RMS-norms of residual\n"); }else{ printf(" RMS-norms of residual\n"); } for(m=0; m<5; m++){ if(*class_npb=='U'){ printf(" %2d%20.13E\n",m+1,xcr[m]); }else if(xcrdif[m]<=epsilon){ printf(" %2d%20.13E%20.13E%20.13E\n",m+1,xcr[m],xcrref[m],xcrdif[m]); }else{ *verified=FALSE; printf(" FAILURE: %2d%20.13E%20.13E%20.13E\n",m+1,xcr[m],xcrref[m],xcrdif[m]); } } if(*class_npb!='U'){ printf(" Comparison of RMS-norms of solution error\n"); }else{ printf(" RMS-norms of solution error\n"); } for(m=0; m<5; m++){ if(*class_npb=='U'){ printf(" %2d%20.13E\n",m+1,xce[m]); }else if(xcedif[m]<=epsilon){ printf(" %2d%20.13E%20.13E%20.13E\n",m+1,xce[m],xceref[m],xcedif[m]); }else{ *verified=FALSE; printf(" FAILURE: %2d%20.13E%20.13E%20.13E\n",m+1,xce[m],xceref[m],xcedif[m]); } } if(*class_npb=='U'){ printf(" No reference values provided\n"); printf(" No verification performed\n"); }else if(*verified){ printf(" Verification Successful\n"); }else{ printf(" Verification failed\n"); } } /* * --------------------------------------------------------------------- * performs line solves in X direction by first factoring * the block-tridiagonal matrix into an upper triangular matrix, * and then performing back substitution to solve for the unknow * vectors of each line. * * make sure we treat elements zero to cell_size in the direction * of the sweep. * --------------------------------------------------------------------- */ void x_solve(){ int i, j, k, m, n, isize; if(timeron){timer_start(T_XSOLVE);} /* * --------------------------------------------------------------------- * this function computes the left hand side in the xi-direction * --------------------------------------------------------------------- */ isize=grid_points[0]-1; /* * --------------------------------------------------------------------- * determine a (labeled f) and n jacobians * --------------------------------------------------------------------- */ pf->parallel_for(1, grid_points[2]-1, 1, [&](int k){ double fjac[PROBLEM_SIZE+1][5][5]; double njac[PROBLEM_SIZE+1][5][5]; double lhs[PROBLEM_SIZE+1][3][5][5]; double tmp1, tmp2, tmp3; int i, j, m, n; for(j=1; j<=grid_points[1]-2; j++){ for(i=0; i<=isize; i++){ tmp1=rho_i[k][j][i]; tmp2=tmp1*tmp1; tmp3=tmp1*tmp2; fjac[i][0][0]=0.0; fjac[i][1][0]=1.0; fjac[i][2][0]=0.0; fjac[i][3][0]=0.0; fjac[i][4][0]=0.0; fjac[i][0][1]=-(u[k][j][i][1]*tmp2*u[k][j][i][1])+c2*qs[k][j][i]; fjac[i][1][1]=(2.0-c2)*(u[k][j][i][1]/u[k][j][i][0]); fjac[i][2][1]=-c2*(u[k][j][i][2]*tmp1); fjac[i][3][1]=-c2*(u[k][j][i][3]*tmp1); fjac[i][4][1]=c2; fjac[i][0][2]=-(u[k][j][i][1]*u[k][j][i][2])*tmp2; fjac[i][1][2]=u[k][j][i][2]*tmp1; fjac[i][2][2]=u[k][j][i][1]*tmp1; fjac[i][3][2]=0.0; fjac[i][4][2]=0.0; fjac[i][0][3]=-(u[k][j][i][1]*u[k][j][i][3])*tmp2; fjac[i][1][3]=u[k][j][i][3]*tmp1; fjac[i][2][3]=0.0; fjac[i][3][3]=u[k][j][i][1]*tmp1; fjac[i][4][3]=0.0; fjac[i][0][4]=(c2*2.0*square[k][j][i]-c1*u[k][j][i][4])*(u[k][j][i][1]*tmp2); fjac[i][1][4]=c1*u[k][j][i][4]*tmp1-c2*(u[k][j][i][1]*u[k][j][i][1]*tmp2+qs[k][j][i]); fjac[i][2][4]=-c2*(u[k][j][i][2]*u[k][j][i][1])*tmp2; fjac[i][3][4]=-c2*(u[k][j][i][3]*u[k][j][i][1])*tmp2; fjac[i][4][4]=c1*(u[k][j][i][1]*tmp1); njac[i][0][0]=0.0; njac[i][1][0]=0.0; njac[i][2][0]=0.0; njac[i][3][0]=0.0; njac[i][4][0]=0.0; njac[i][0][1]=-con43*c3c4*tmp2*u[k][j][i][1]; njac[i][1][1]=con43*c3c4*tmp1; njac[i][2][1]=0.0; njac[i][3][1]=0.0; njac[i][4][1]=0.0; njac[i][0][2]=-c3c4*tmp2*u[k][j][i][2]; njac[i][1][2]=0.0; njac[i][2][2]=c3c4*tmp1; njac[i][3][2]=0.0; njac[i][4][2]=0.0; njac[i][0][3]=-c3c4*tmp2*u[k][j][i][3]; njac[i][1][3]=0.0; njac[i][2][3]=0.0; njac[i][3][3]=c3c4*tmp1; njac[i][4][3]=0.0; njac[i][0][4]=-(con43*c3c4-c1345)*tmp3*(u[k][j][i][1]*u[k][j][i][1]) -(c3c4-c1345)*tmp3*(u[k][j][i][2]*u[k][j][i][2]) -(c3c4-c1345)*tmp3*(u[k][j][i][3]*u[k][j][i][3]) -c1345*tmp2*u[k][j][i][4]; njac[i][1][4]=(con43*c3c4-c1345)*tmp2*u[k][j][i][1]; njac[i][2][4]=(c3c4-c1345)*tmp2*u[k][j][i][2]; njac[i][3][4]=(c3c4-c1345)*tmp2*u[k][j][i][3]; njac[i][4][4]=(c1345)*tmp1; } /* * --------------------------------------------------------------------- * now jacobians set, so form left hand side in x direction * --------------------------------------------------------------------- */ lhsinit(lhs, isize); for(i=1; i<=isize-1; i++){ tmp1=dt*tx1; tmp2=dt*tx2; lhs[i][AA][0][0]=-tmp2*fjac[i-1][0][0] -tmp1*njac[i-1][0][0] -tmp1*dx1; lhs[i][AA][1][0]=-tmp2*fjac[i-1][1][0] -tmp1*njac[i-1][1][0]; lhs[i][AA][2][0]=-tmp2*fjac[i-1][2][0] -tmp1*njac[i-1][2][0]; lhs[i][AA][3][0]=-tmp2*fjac[i-1][3][0] -tmp1*njac[i-1][3][0]; lhs[i][AA][4][0]=-tmp2*fjac[i-1][4][0] -tmp1*njac[i-1][4][0]; lhs[i][AA][0][1]=-tmp2*fjac[i-1][0][1] -tmp1*njac[i-1][0][1]; lhs[i][AA][1][1]=-tmp2*fjac[i-1][1][1] -tmp1*njac[i-1][1][1] -tmp1*dx2; lhs[i][AA][2][1]=-tmp2*fjac[i-1][2][1] -tmp1*njac[i-1][2][1]; lhs[i][AA][3][1]=-tmp2*fjac[i-1][3][1] -tmp1*njac[i-1][3][1]; lhs[i][AA][4][1]=-tmp2*fjac[i-1][4][1] -tmp1*njac[i-1][4][1]; lhs[i][AA][0][2]=-tmp2*fjac[i-1][0][2] -tmp1*njac[i-1][0][2]; lhs[i][AA][1][2]=-tmp2*fjac[i-1][1][2] -tmp1*njac[i-1][1][2]; lhs[i][AA][2][2]=-tmp2*fjac[i-1][2][2] -tmp1*njac[i-1][2][2] -tmp1*dx3; lhs[i][AA][3][2]=-tmp2*fjac[i-1][3][2] -tmp1*njac[i-1][3][2]; lhs[i][AA][4][2]=-tmp2*fjac[i-1][4][2] -tmp1*njac[i-1][4][2]; lhs[i][AA][0][3]=-tmp2*fjac[i-1][0][3] -tmp1*njac[i-1][0][3]; lhs[i][AA][1][3]=-tmp2*fjac[i-1][1][3] -tmp1*njac[i-1][1][3]; lhs[i][AA][2][3]=-tmp2*fjac[i-1][2][3] -tmp1*njac[i-1][2][3]; lhs[i][AA][3][3]=-tmp2*fjac[i-1][3][3] -tmp1*njac[i-1][3][3] -tmp1*dx4; lhs[i][AA][4][3]=-tmp2*fjac[i-1][4][3] -tmp1*njac[i-1][4][3]; lhs[i][AA][0][4]=-tmp2*fjac[i-1][0][4] -tmp1*njac[i-1][0][4]; lhs[i][AA][1][4]=-tmp2*fjac[i-1][1][4] -tmp1*njac[i-1][1][4]; lhs[i][AA][2][4]=-tmp2*fjac[i-1][2][4] -tmp1*njac[i-1][2][4]; lhs[i][AA][3][4]=-tmp2*fjac[i-1][3][4] -tmp1*njac[i-1][3][4]; lhs[i][AA][4][4]=-tmp2*fjac[i-1][4][4] -tmp1*njac[i-1][4][4] -tmp1*dx5; lhs[i][BB][0][0]=1.0 +tmp1*2.0*njac[i][0][0] +tmp1*2.0*dx1; lhs[i][BB][1][0]=tmp1*2.0*njac[i][1][0]; lhs[i][BB][2][0]=tmp1*2.0*njac[i][2][0]; lhs[i][BB][3][0]=tmp1*2.0*njac[i][3][0]; lhs[i][BB][4][0]=tmp1*2.0*njac[i][4][0]; lhs[i][BB][0][1]=tmp1*2.0*njac[i][0][1]; lhs[i][BB][1][1]=1.0 +tmp1*2.0*njac[i][1][1] +tmp1*2.0*dx2; lhs[i][BB][2][1]=tmp1*2.0*njac[i][2][1]; lhs[i][BB][3][1]=tmp1*2.0*njac[i][3][1]; lhs[i][BB][4][1]=tmp1*2.0*njac[i][4][1]; lhs[i][BB][0][2]=tmp1*2.0*njac[i][0][2]; lhs[i][BB][1][2]=tmp1*2.0*njac[i][1][2]; lhs[i][BB][2][2]=1.0 +tmp1*2.0*njac[i][2][2] +tmp1*2.0*dx3; lhs[i][BB][3][2]=tmp1*2.0*njac[i][3][2]; lhs[i][BB][4][2]=tmp1*2.0*njac[i][4][2]; lhs[i][BB][0][3]=tmp1*2.0*njac[i][0][3]; lhs[i][BB][1][3]=tmp1*2.0*njac[i][1][3]; lhs[i][BB][2][3]=tmp1*2.0*njac[i][2][3]; lhs[i][BB][3][3]=1.0 +tmp1*2.0*njac[i][3][3] +tmp1*2.0*dx4; lhs[i][BB][4][3]=tmp1*2.0*njac[i][4][3]; lhs[i][BB][0][4]=tmp1*2.0*njac[i][0][4]; lhs[i][BB][1][4]=tmp1*2.0*njac[i][1][4]; lhs[i][BB][2][4]=tmp1*2.0*njac[i][2][4]; lhs[i][BB][3][4]=tmp1*2.0*njac[i][3][4]; lhs[i][BB][4][4]=1.0 +tmp1*2.0*njac[i][4][4] +tmp1*2.0*dx5; lhs[i][CC][0][0]=tmp2*fjac[i+1][0][0] -tmp1*njac[i+1][0][0] -tmp1*dx1; lhs[i][CC][1][0]=tmp2*fjac[i+1][1][0] -tmp1*njac[i+1][1][0]; lhs[i][CC][2][0]=tmp2*fjac[i+1][2][0] -tmp1*njac[i+1][2][0]; lhs[i][CC][3][0]=tmp2*fjac[i+1][3][0] -tmp1*njac[i+1][3][0]; lhs[i][CC][4][0]=tmp2*fjac[i+1][4][0] -tmp1*njac[i+1][4][0]; lhs[i][CC][0][1]=tmp2*fjac[i+1][0][1] -tmp1*njac[i+1][0][1]; lhs[i][CC][1][1]=tmp2*fjac[i+1][1][1] -tmp1*njac[i+1][1][1] -tmp1*dx2; lhs[i][CC][2][1]=tmp2*fjac[i+1][2][1] -tmp1*njac[i+1][2][1]; lhs[i][CC][3][1]=tmp2*fjac[i+1][3][1] -tmp1*njac[i+1][3][1]; lhs[i][CC][4][1]=tmp2*fjac[i+1][4][1] -tmp1*njac[i+1][4][1]; lhs[i][CC][0][2]=tmp2*fjac[i+1][0][2] -tmp1*njac[i+1][0][2]; lhs[i][CC][1][2]=tmp2*fjac[i+1][1][2] -tmp1*njac[i+1][1][2]; lhs[i][CC][2][2]=tmp2*fjac[i+1][2][2] -tmp1*njac[i+1][2][2] -tmp1*dx3; lhs[i][CC][3][2]=tmp2*fjac[i+1][3][2] -tmp1*njac[i+1][3][2]; lhs[i][CC][4][2]=tmp2*fjac[i+1][4][2] -tmp1*njac[i+1][4][2]; lhs[i][CC][0][3]=tmp2*fjac[i+1][0][3] -tmp1*njac[i+1][0][3]; lhs[i][CC][1][3]=tmp2*fjac[i+1][1][3] -tmp1*njac[i+1][1][3]; lhs[i][CC][2][3]=tmp2*fjac[i+1][2][3] -tmp1*njac[i+1][2][3]; lhs[i][CC][3][3]=tmp2*fjac[i+1][3][3] -tmp1*njac[i+1][3][3] -tmp1*dx4; lhs[i][CC][4][3]=tmp2*fjac[i+1][4][3] -tmp1*njac[i+1][4][3]; lhs[i][CC][0][4]=tmp2*fjac[i+1][0][4] -tmp1*njac[i+1][0][4]; lhs[i][CC][1][4]=tmp2*fjac[i+1][1][4] -tmp1*njac[i+1][1][4]; lhs[i][CC][2][4]=tmp2*fjac[i+1][2][4] -tmp1*njac[i+1][2][4]; lhs[i][CC][3][4]=tmp2 * fjac[i+1][3][4] -tmp1*njac[i+1][3][4]; lhs[i][CC][4][4]=tmp2*fjac[i+1][4][4] -tmp1*njac[i+1][4][4] -tmp1*dx5; } /* * --------------------------------------------------------------------- * performs guaussian elimination on this cell. * * assumes that unpacking routines for non-first cells * preload C' and rhs' from previous cell. * * assumed send happens outside this routine, but that * c'(IMAX) and rhs'(IMAX) will be sent to next cell * --------------------------------------------------------------------- * outer most do loops - sweeping in i direction * --------------------------------------------------------------------- * multiply c(0,j,k) by b_inverse and copy back to c * multiply rhs(0) by b_inverse(0) and copy to rhs * --------------------------------------------------------------------- */ binvcrhs(lhs[0][BB], lhs[0][CC], rhs[k][j][0]); /* * --------------------------------------------------------------------- * begin inner most do loop * do all the elements of the cell unless last * --------------------------------------------------------------------- */ for(i=1; i<=isize-1; i++){ /* * ------------------------------------------------------------------- * rhs(i) = rhs(i) - A*rhs(i-1) * ------------------------------------------------------------------- */ matvec_sub(lhs[i][AA], rhs[k][j][i-1], rhs[k][j][i]); /* * ------------------------------------------------------------------- * B(i) = B(i) - C(i-1)*A(i) * ------------------------------------------------------------------- */ matmul_sub(lhs[i][AA], lhs[i-1][CC], lhs[i][BB]); /* * ------------------------------------------------------------------- * multiply c(i,j,k) by b_inverse and copy back to c * multiply rhs(1,j,k) by b_inverse(1,j,k) and copy to rhs * ------------------------------------------------------------------- */ binvcrhs(lhs[i][BB], lhs[i][CC], rhs[k][j][i]); } /* * --------------------------------------------------------------------- * rhs(isize) = rhs(isize) - A*rhs(isize-1) * --------------------------------------------------------------------- */ matvec_sub(lhs[isize][AA], rhs[k][j][isize-1], rhs[k][j][isize]); /* * --------------------------------------------------------------------- * B(isize) = B(isize) - C(isize-1)*A(isize) * --------------------------------------------------------------------- */ matmul_sub(lhs[isize][AA], lhs[isize-1][CC], lhs[isize][BB]); /* * --------------------------------------------------------------------- * multiply rhs() by b_inverse() and copy to rhs * --------------------------------------------------------------------- */ binvrhs(lhs[isize][BB], rhs[k][j][isize]); /* * --------------------------------------------------------------------- * back solve: if last cell, then generate U(isize)=rhs(isize) * else assume U(isize) is loaded in un pack backsub_info * so just use it * after u(istart) will be sent to next cell * --------------------------------------------------------------------- */ for(i=isize-1; i>=0; i--){ for(m=0; m<BLOCK_SIZE; m++){ for(n=0; n<BLOCK_SIZE; n++){ rhs[k][j][i][m]=rhs[k][j][i][m]-lhs[i][CC][n][m]*rhs[k][j][i+1][n]; } } } } }); if(timeron){timer_stop(T_XSOLVE);} } /* * --------------------------------------------------------------------- * performs line solves in y direction by first factoring * the block-tridiagonal matrix into an upper triangular matrix, * and then performing back substitution to solve for the unknow * vectors of each line. * * make sure we treat elements zero to cell_size in the direction * of the sweep. * --------------------------------------------------------------------- */ void y_solve(){ int i, j, k, m, n, jsize; if(timeron){timer_start(T_YSOLVE);} /* * --------------------------------------------------------------------- * this function computes the left hand side for the three y-factors * --------------------------------------------------------------------- */ jsize=grid_points[1]-1; /* * --------------------------------------------------------------------- * compute the indices for storing the tri-diagonal matrix; * determine a (labeled f) and n jacobians for cell c * --------------------------------------------------------------------- */ pf->parallel_for(1, grid_points[2]-1, 1, [&](int k){ double fjac[PROBLEM_SIZE+1][5][5]; double njac[PROBLEM_SIZE+1][5][5]; double lhs[PROBLEM_SIZE+1][3][5][5]; double tmp1, tmp2, tmp3; int i, j, m, n; for(i=1; i<=grid_points[0]-2; i++){ for(j=0; j<=jsize; j++){ tmp1=rho_i[k][j][i]; tmp2=tmp1*tmp1; tmp3=tmp1*tmp2; fjac[j][0][0]=0.0; fjac[j][1][0]=0.0; fjac[j][2][0]=1.0; fjac[j][3][0]=0.0; fjac[j][4][0]=0.0; fjac[j][0][1]=-(u[k][j][i][1]*u[k][j][i][2])*tmp2; fjac[j][1][1]=u[k][j][i][2]*tmp1; fjac[j][2][1]=u[k][j][i][1]*tmp1; fjac[j][3][1]=0.0; fjac[j][4][1]=0.0; fjac[j][0][2]=-(u[k][j][i][2]*u[k][j][i][2]*tmp2)+c2*qs[k][j][i]; fjac[j][1][2]=-c2*u[k][j][i][1]*tmp1; fjac[j][2][2]=(2.0-c2)*u[k][j][i][2]*tmp1; fjac[j][3][2]=-c2*u[k][j][i][3]*tmp1; fjac[j][4][2]=c2; fjac[j][0][3]=-(u[k][j][i][2]*u[k][j][i][3])*tmp2; fjac[j][1][3]=0.0; fjac[j][2][3]=u[k][j][i][3]*tmp1; fjac[j][3][3]=u[k][j][i][2]*tmp1; fjac[j][4][3]=0.0; fjac[j][0][4]=(c2*2.0*square[k][j][i]-c1*u[k][j][i][4])*u[k][j][i][2]*tmp2; fjac[j][1][4]=-c2*u[k][j][i][1]*u[k][j][i][2]*tmp2; fjac[j][2][4]=c1*u[k][j][i][4]*tmp1-c2*(qs[k][j][i]+u[k][j][i][2]*u[k][j][i][2]*tmp2); fjac[j][3][4]=-c2*(u[k][j][i][2]*u[k][j][i][3])*tmp2; fjac[j][4][4]=c1*u[k][j][i][2]*tmp1; njac[j][0][0]=0.0; njac[j][1][0]=0.0; njac[j][2][0]=0.0; njac[j][3][0]=0.0; njac[j][4][0]=0.0; njac[j][0][1]=-c3c4*tmp2*u[k][j][i][1]; njac[j][1][1]=c3c4*tmp1; njac[j][2][1]=0.0; njac[j][3][1]=0.0; njac[j][4][1]=0.0; njac[j][0][2]=-con43*c3c4*tmp2*u[k][j][i][2]; njac[j][1][2]=0.0; njac[j][2][2]=con43*c3c4*tmp1; njac[j][3][2]=0.0; njac[j][4][2]=0.0; njac[j][0][3]=-c3c4*tmp2*u[k][j][i][3]; njac[j][1][3]=0.0; njac[j][2][3]=0.0; njac[j][3][3]=c3c4*tmp1; njac[j][4][3]=0.0; njac[j][0][4]=-(c3c4-c1345)*tmp3*(u[k][j][i][1]*u[k][j][i][1]) -(con43*c3c4-c1345)*tmp3*(u[k][j][i][2]*u[k][j][i][2]) -(c3c4-c1345)*tmp3*(u[k][j][i][3]*u[k][j][i][3]) -c1345*tmp2*u[k][j][i][4]; njac[j][1][4]=(c3c4-c1345)*tmp2*u[k][j][i][1]; njac[j][2][4]=(con43*c3c4-c1345)*tmp2*u[k][j][i][2]; njac[j][3][4]=(c3c4-c1345)*tmp2*u[k][j][i][3]; njac[j][4][4]=(c1345)*tmp1; } /* * --------------------------------------------------------------------- * now joacobians set, so form left hand side in y direction * --------------------------------------------------------------------- */ lhsinit(lhs, jsize); for(j=1; j<=jsize-1; j++){ tmp1=dt*ty1; tmp2=dt*ty2; lhs[j][AA][0][0]=-tmp2*fjac[j-1][0][0] -tmp1*njac[j-1][0][0] -tmp1*dy1; lhs[j][AA][1][0]=-tmp2*fjac[j-1][1][0] -tmp1*njac[j-1][1][0]; lhs[j][AA][2][0]=-tmp2*fjac[j-1][2][0] -tmp1*njac[j-1][2][0]; lhs[j][AA][3][0]=-tmp2*fjac[j-1][3][0] -tmp1*njac[j-1][3][0]; lhs[j][AA][4][0]=-tmp2*fjac[j-1][4][0] -tmp1*njac[j-1][4][0]; lhs[j][AA][0][1]=-tmp2*fjac[j-1][0][1] -tmp1*njac[j-1][0][1]; lhs[j][AA][1][1]=-tmp2*fjac[j-1][1][1] -tmp1*njac[j-1][1][1] -tmp1*dy2; lhs[j][AA][2][1]=-tmp2*fjac[j-1][2][1] -tmp1*njac[j-1][2][1]; lhs[j][AA][3][1]=-tmp2*fjac[j-1][3][1] -tmp1*njac[j-1][3][1]; lhs[j][AA][4][1]=-tmp2*fjac[j-1][4][1] -tmp1*njac[j-1][4][1]; lhs[j][AA][0][2]=-tmp2*fjac[j-1][0][2] -tmp1*njac[j-1][0][2]; lhs[j][AA][1][2]=-tmp2*fjac[j-1][1][2] -tmp1*njac[j-1][1][2]; lhs[j][AA][2][2]=-tmp2*fjac[j-1][2][2] -tmp1*njac[j-1][2][2] -tmp1*dy3; lhs[j][AA][3][2]=-tmp2*fjac[j-1][3][2] -tmp1*njac[j-1][3][2]; lhs[j][AA][4][2]=-tmp2*fjac[j-1][4][2] -tmp1*njac[j-1][4][2]; lhs[j][AA][0][3]=-tmp2*fjac[j-1][0][3] -tmp1*njac[j-1][0][3]; lhs[j][AA][1][3]=-tmp2*fjac[j-1][1][3] -tmp1*njac[j-1][1][3]; lhs[j][AA][2][3]=-tmp2*fjac[j-1][2][3] -tmp1*njac[j-1][2][3]; lhs[j][AA][3][3]=-tmp2*fjac[j-1][3][3] -tmp1*njac[j-1][3][3] -tmp1*dy4; lhs[j][AA][4][3]=-tmp2*fjac[j-1][4][3] -tmp1*njac[j-1][4][3]; lhs[j][AA][0][4]=-tmp2*fjac[j-1][0][4] -tmp1*njac[j-1][0][4]; lhs[j][AA][1][4]=-tmp2*fjac[j-1][1][4] -tmp1*njac[j-1][1][4]; lhs[j][AA][2][4]=-tmp2*fjac[j-1][2][4] -tmp1*njac[j-1][2][4]; lhs[j][AA][3][4]=-tmp2*fjac[j-1][3][4] -tmp1*njac[j-1][3][4]; lhs[j][AA][4][4]=-tmp2*fjac[j-1][4][4] -tmp1*njac[j-1][4][4] -tmp1*dy5; lhs[j][BB][0][0]=1.0 +tmp1*2.0*njac[j][0][0] +tmp1*2.0*dy1; lhs[j][BB][1][0]=tmp1*2.0*njac[j][1][0]; lhs[j][BB][2][0]=tmp1*2.0*njac[j][2][0]; lhs[j][BB][3][0]=tmp1*2.0*njac[j][3][0]; lhs[j][BB][4][0]=tmp1*2.0*njac[j][4][0]; lhs[j][BB][0][1]=tmp1*2.0*njac[j][0][1]; lhs[j][BB][1][1]=1.0 +tmp1*2.0*njac[j][1][1] +tmp1*2.0*dy2; lhs[j][BB][2][1]=tmp1*2.0*njac[j][2][1]; lhs[j][BB][3][1]=tmp1*2.0*njac[j][3][1]; lhs[j][BB][4][1]=tmp1*2.0*njac[j][4][1]; lhs[j][BB][0][2]=tmp1*2.0*njac[j][0][2]; lhs[j][BB][1][2]=tmp1*2.0*njac[j][1][2]; lhs[j][BB][2][2]=1.0 +tmp1*2.0*njac[j][2][2] +tmp1*2.0*dy3; lhs[j][BB][3][2]=tmp1*2.0*njac[j][3][2]; lhs[j][BB][4][2]=tmp1*2.0*njac[j][4][2]; lhs[j][BB][0][3]=tmp1*2.0*njac[j][0][3]; lhs[j][BB][1][3]=tmp1*2.0*njac[j][1][3]; lhs[j][BB][2][3]=tmp1*2.0*njac[j][2][3]; lhs[j][BB][3][3]=1.0 +tmp1*2.0*njac[j][3][3] +tmp1*2.0*dy4; lhs[j][BB][4][3]=tmp1*2.0*njac[j][4][3]; lhs[j][BB][0][4]=tmp1*2.0*njac[j][0][4]; lhs[j][BB][1][4]=tmp1*2.0*njac[j][1][4]; lhs[j][BB][2][4]=tmp1*2.0*njac[j][2][4]; lhs[j][BB][3][4]=tmp1*2.0*njac[j][3][4]; lhs[j][BB][4][4]=1.0 +tmp1*2.0*njac[j][4][4] +tmp1*2.0*dy5; lhs[j][CC][0][0]=tmp2*fjac[j+1][0][0] -tmp1*njac[j+1][0][0] -tmp1*dy1; lhs[j][CC][1][0]=tmp2*fjac[j+1][1][0] -tmp1*njac[j+1][1][0]; lhs[j][CC][2][0]=tmp2*fjac[j+1][2][0] -tmp1*njac[j+1][2][0]; lhs[j][CC][3][0]=tmp2*fjac[j+1][3][0] -tmp1*njac[j+1][3][0]; lhs[j][CC][4][0]=tmp2*fjac[j+1][4][0] -tmp1*njac[j+1][4][0]; lhs[j][CC][0][1]=tmp2*fjac[j+1][0][1] -tmp1*njac[j+1][0][1]; lhs[j][CC][1][1]=tmp2*fjac[j+1][1][1] -tmp1*njac[j+1][1][1] -tmp1*dy2; lhs[j][CC][2][1]=tmp2*fjac[j+1][2][1] -tmp1*njac[j+1][2][1]; lhs[j][CC][3][1]=tmp2*fjac[j+1][3][1] -tmp1*njac[j+1][3][1]; lhs[j][CC][4][1]=tmp2*fjac[j+1][4][1] -tmp1*njac[j+1][4][1]; lhs[j][CC][0][2]=tmp2*fjac[j+1][0][2] -tmp1*njac[j+1][0][2]; lhs[j][CC][1][2]=tmp2*fjac[j+1][1][2] -tmp1*njac[j+1][1][2]; lhs[j][CC][2][2]=tmp2*fjac[j+1][2][2] -tmp1*njac[j+1][2][2] -tmp1*dy3; lhs[j][CC][3][2]=tmp2*fjac[j+1][3][2] -tmp1*njac[j+1][3][2]; lhs[j][CC][4][2]=tmp2*fjac[j+1][4][2] -tmp1*njac[j+1][4][2]; lhs[j][CC][0][3]=tmp2*fjac[j+1][0][3] -tmp1*njac[j+1][0][3]; lhs[j][CC][1][3]=tmp2*fjac[j+1][1][3] -tmp1*njac[j+1][1][3]; lhs[j][CC][2][3]=tmp2*fjac[j+1][2][3] -tmp1*njac[j+1][2][3]; lhs[j][CC][3][3]=tmp2*fjac[j+1][3][3] -tmp1*njac[j+1][3][3] -tmp1*dy4; lhs[j][CC][4][3]=tmp2*fjac[j+1][4][3] -tmp1*njac[j+1][4][3]; lhs[j][CC][0][4]=tmp2*fjac[j+1][0][4] -tmp1*njac[j+1][0][4]; lhs[j][CC][1][4]=tmp2*fjac[j+1][1][4] -tmp1*njac[j+1][1][4]; lhs[j][CC][2][4]=tmp2*fjac[j+1][2][4] -tmp1*njac[j+1][2][4]; lhs[j][CC][3][4]=tmp2*fjac[j+1][3][4] -tmp1*njac[j+1][3][4]; lhs[j][CC][4][4]=tmp2*fjac[j+1][4][4] -tmp1*njac[j+1][4][4] -tmp1*dy5; } /* * --------------------------------------------------------------------- * performs guaussian elimination on this cell. * * assumes that unpacking routines for non-first cells * preload c' and rhs' from previous cell. * * assumed send happens outside this routine, but that * c'(JMAX) and rhs'(JMAX) will be sent to next cell * --------------------------------------------------------------------- * multiply c(i,0,k) by b_inverse and copy back to c * multiply rhs(0) by b_inverse(0) and copy to rhs * --------------------------------------------------------------------- */ binvcrhs(lhs[0][BB], lhs[0][CC], rhs[k][0][i]); /* * --------------------------------------------------------------------- * begin inner most do loop * do all the elements of the cell unless last * --------------------------------------------------------------------- */ for(j=1; j<=jsize-1; j++){ /* * ------------------------------------------------------------------- * subtract A*lhs_vector(j-1) from lhs_vector(j) * * rhs(j) = rhs(j) - A*rhs(j-1) * ------------------------------------------------------------------- */ matvec_sub(lhs[j][AA], rhs[k][j-1][i], rhs[k][j][i]); /* * ------------------------------------------------------------------- * B(j) = B(j) - C(j-1)*A(j) * ------------------------------------------------------------------- */ matmul_sub(lhs[j][AA], lhs[j-1][CC], lhs[j][BB]); /* * ------------------------------------------------------------------- * multiply c(i,j,k) by b_inverse and copy back to c * multiply rhs(i,1,k) by b_inverse(i,1,k) and copy to rhs * ------------------------------------------------------------------- */ binvcrhs(lhs[j][BB], lhs[j][CC], rhs[k][j][i]); } /* * --------------------------------------------------------------------- * rhs(jsize) = rhs(jsize) - A*rhs(jsize-1) * --------------------------------------------------------------------- */ matvec_sub(lhs[jsize][AA], rhs[k][jsize-1][i], rhs[k][jsize][i]); /* * --------------------------------------------------------------------- * B(jsize) = B(jsize) - C(jsize-1)*A(jsize) * matmul_sub(aa,i,jsize,k,c, * $ cc,i,jsize-1,k,c,bb,i,jsize,k) * --------------------------------------------------------------------- */ matmul_sub(lhs[jsize][AA], lhs[jsize-1][CC], lhs[jsize][BB]); /* * --------------------------------------------------------------------- * multiply rhs(jsize) by b_inverse(jsize) and copy to rhs * --------------------------------------------------------------------- */ binvrhs(lhs[jsize][BB], rhs[k][jsize][i]); /* * --------------------------------------------------------------------- * back solve: if last cell, then generate U(jsize)=rhs(jsize) * else assume U(jsize) is loaded in un pack backsub_info * so just use it * after u(jstart) will be sent to next cell * --------------------------------------------------------------------- */ for(j=jsize-1; j>=0; j--){ for(m=0; m<BLOCK_SIZE; m++){ for(n=0; n<BLOCK_SIZE; n++){ rhs[k][j][i][m]=rhs[k][j][i][m]-lhs[j][CC][n][m]*rhs[k][j+1][i][n]; } } } } }); if(timeron){timer_stop(T_YSOLVE);} } /* * --------------------------------------------------------------------- * performs line solves in Z direction by first factoring * the block-tridiagonal matrix into an upper triangular matrix, * and then performing back substitution to solve for the unknow * vectors of each line. * * make sure we treat elements zero to cell_size in the direction * of the sweep. * --------------------------------------------------------------------- */ void z_solve(){ int i, j, k, m, n, ksize; if(timeron){timer_start(T_ZSOLVE);} /* * --------------------------------------------------------------------- * this function computes the left hand side for the three z-factors * --------------------------------------------------------------------- */ ksize = grid_points[2]-1; /* * --------------------------------------------------------------------- * compute the indices for storing the block-diagonal matrix; * determine c (labeled f) and s jacobians * --------------------------------------------------------------------- */ pf->parallel_for(1, grid_points[1]-1, 1, [&](int j){ double fjac[PROBLEM_SIZE+1][5][5]; double njac[PROBLEM_SIZE+1][5][5]; double lhs[PROBLEM_SIZE+1][3][5][5]; double tmp1, tmp2, tmp3; int i, k, m, n; for(i=1; i<=grid_points[0]-2; i++){ for(k=0; k<=ksize; k++){ tmp1=1.0/u[k][j][i][0]; tmp2=tmp1*tmp1; tmp3=tmp1*tmp2; fjac[k][0][0]=0.0; fjac[k][1][0]=0.0; fjac[k][2][0]=0.0; fjac[k][3][0]=1.0; fjac[k][4][0]=0.0; fjac[k][0][1]=-(u[k][j][i][1]*u[k][j][i][3])*tmp2; fjac[k][1][1]=u[k][j][i][3]*tmp1; fjac[k][2][1]=0.0; fjac[k][3][1]=u[k][j][i][1]*tmp1; fjac[k][4][1]=0.0; fjac[k][0][2]=-(u[k][j][i][2]*u[k][j][i][3])*tmp2; fjac[k][1][2]=0.0; fjac[k][2][2]=u[k][j][i][3]*tmp1; fjac[k][3][2]=u[k][j][i][2]*tmp1; fjac[k][4][2]=0.0; fjac[k][0][3]=-(u[k][j][i][3]*u[k][j][i][3]*tmp2)+c2*qs[k][j][i]; fjac[k][1][3]=-c2*u[k][j][i][1]*tmp1; fjac[k][2][3]=-c2*u[k][j][i][2]*tmp1; fjac[k][3][3]=(2.0-c2)*u[k][j][i][3]*tmp1; fjac[k][4][3]=c2; fjac[k][0][4]=(c2*2.0*square[k][j][i]-c1*u[k][j][i][4])*u[k][j][i][3]*tmp2; fjac[k][1][4]=-c2*(u[k][j][i][1]*u[k][j][i][3])*tmp2; fjac[k][2][4]=-c2*(u[k][j][i][2]*u[k][j][i][3])*tmp2; fjac[k][3][4]=c1*(u[k][j][i][4]*tmp1)-c2*(qs[k][j][i]+u[k][j][i][3]*u[k][j][i][3]*tmp2); fjac[k][4][4]=c1*u[k][j][i][3]*tmp1; njac[k][0][0]=0.0; njac[k][1][0]=0.0; njac[k][2][0]=0.0; njac[k][3][0]=0.0; njac[k][4][0]=0.0; njac[k][0][1]=-c3c4*tmp2*u[k][j][i][1]; njac[k][1][1]=c3c4*tmp1; njac[k][2][1]=0.0; njac[k][3][1]=0.0; njac[k][4][1]=0.0; njac[k][0][2]=-c3c4*tmp2*u[k][j][i][2]; njac[k][1][2]=0.0; njac[k][2][2]=c3c4*tmp1; njac[k][3][2]=0.0; njac[k][4][2]=0.0; njac[k][0][3]=-con43*c3c4*tmp2*u[k][j][i][3]; njac[k][1][3]=0.0; njac[k][2][3]=0.0; njac[k][3][3]=con43*c3*c4*tmp1; njac[k][4][3]=0.0; njac[k][0][4]=-(c3c4-c1345)*tmp3*(u[k][j][i][1]*u[k][j][i][1]) -(c3c4-c1345)*tmp3*(u[k][j][i][2]*u[k][j][i][2]) -(con43*c3c4-c1345)*tmp3*(u[k][j][i][3]*u[k][j][i][3]) -c1345*tmp2*u[k][j][i][4]; njac[k][1][4]=(c3c4-c1345)*tmp2*u[k][j][i][1]; njac[k][2][4]=(c3c4-c1345)*tmp2*u[k][j][i][2]; njac[k][3][4]=(con43*c3c4-c1345)*tmp2*u[k][j][i][3]; njac[k][4][4]=(c1345)*tmp1; } /* * --------------------------------------------------------------------- * now jacobians set, so form left hand side in z direction * --------------------------------------------------------------------- */ lhsinit(lhs, ksize); for(k=1; k<=ksize-1; k++){ tmp1=dt*tz1; tmp2=dt*tz2; lhs[k][AA][0][0]=-tmp2*fjac[k-1][0][0] -tmp1*njac[k-1][0][0] -tmp1*dz1; lhs[k][AA][1][0]=-tmp2*fjac[k-1][1][0] -tmp1*njac[k-1][1][0]; lhs[k][AA][2][0]=-tmp2*fjac[k-1][2][0] -tmp1*njac[k-1][2][0]; lhs[k][AA][3][0]=-tmp2*fjac[k-1][3][0] -tmp1*njac[k-1][3][0]; lhs[k][AA][4][0]=-tmp2*fjac[k-1][4][0] -tmp1*njac[k-1][4][0]; lhs[k][AA][0][1]=-tmp2*fjac[k-1][0][1] -tmp1*njac[k-1][0][1]; lhs[k][AA][1][1]=-tmp2*fjac[k-1][1][1] -tmp1*njac[k-1][1][1] -tmp1*dz2; lhs[k][AA][2][1]=-tmp2*fjac[k-1][2][1] -tmp1*njac[k-1][2][1]; lhs[k][AA][3][1]=-tmp2*fjac[k-1][3][1] -tmp1*njac[k-1][3][1]; lhs[k][AA][4][1]=-tmp2*fjac[k-1][4][1] -tmp1*njac[k-1][4][1]; lhs[k][AA][0][2]=-tmp2*fjac[k-1][0][2] -tmp1*njac[k-1][0][2]; lhs[k][AA][1][2]=-tmp2*fjac[k-1][1][2] -tmp1*njac[k-1][1][2]; lhs[k][AA][2][2]=-tmp2*fjac[k-1][2][2] -tmp1*njac[k-1][2][2] -tmp1*dz3; lhs[k][AA][3][2]=-tmp2*fjac[k-1][3][2] -tmp1*njac[k-1][3][2]; lhs[k][AA][4][2]=-tmp2*fjac[k-1][4][2] -tmp1*njac[k-1][4][2]; lhs[k][AA][0][3]=-tmp2*fjac[k-1][0][3] -tmp1*njac[k-1][0][3]; lhs[k][AA][1][3]=-tmp2*fjac[k-1][1][3] -tmp1*njac[k-1][1][3]; lhs[k][AA][2][3]=-tmp2*fjac[k-1][2][3] -tmp1*njac[k-1][2][3]; lhs[k][AA][3][3]=-tmp2*fjac[k-1][3][3] -tmp1*njac[k-1][3][3] -tmp1*dz4; lhs[k][AA][4][3]=-tmp2*fjac[k-1][4][3] -tmp1*njac[k-1][4][3]; lhs[k][AA][0][4]=-tmp2*fjac[k-1][0][4] -tmp1*njac[k-1][0][4]; lhs[k][AA][1][4]=-tmp2*fjac[k-1][1][4] -tmp1*njac[k-1][1][4]; lhs[k][AA][2][4]=-tmp2*fjac[k-1][2][4] -tmp1*njac[k-1][2][4]; lhs[k][AA][3][4]=-tmp2*fjac[k-1][3][4] -tmp1*njac[k-1][3][4]; lhs[k][AA][4][4]=-tmp2*fjac[k-1][4][4] -tmp1*njac[k-1][4][4] -tmp1*dz5; lhs[k][BB][0][0]=1.0 +tmp1*2.0*njac[k][0][0] +tmp1*2.0*dz1; lhs[k][BB][1][0]=tmp1*2.0*njac[k][1][0]; lhs[k][BB][2][0]=tmp1*2.0*njac[k][2][0]; lhs[k][BB][3][0]=tmp1*2.0*njac[k][3][0]; lhs[k][BB][4][0]=tmp1*2.0*njac[k][4][0]; lhs[k][BB][0][1]=tmp1*2.0*njac[k][0][1]; lhs[k][BB][1][1]=1.0 +tmp1*2.0*njac[k][1][1] +tmp1*2.0*dz2; lhs[k][BB][2][1]=tmp1*2.0*njac[k][2][1]; lhs[k][BB][3][1]=tmp1*2.0*njac[k][3][1]; lhs[k][BB][4][1]=tmp1*2.0*njac[k][4][1]; lhs[k][BB][0][2]=tmp1*2.0*njac[k][0][2]; lhs[k][BB][1][2]=tmp1*2.0*njac[k][1][2]; lhs[k][BB][2][2]=1.0 +tmp1*2.0*njac[k][2][2] +tmp1*2.0*dz3; lhs[k][BB][3][2]=tmp1*2.0*njac[k][3][2]; lhs[k][BB][4][2]=tmp1*2.0*njac[k][4][2]; lhs[k][BB][0][3]=tmp1*2.0*njac[k][0][3]; lhs[k][BB][1][3]=tmp1*2.0*njac[k][1][3]; lhs[k][BB][2][3]=tmp1*2.0*njac[k][2][3]; lhs[k][BB][3][3]=1.0 +tmp1*2.0*njac[k][3][3] +tmp1*2.0*dz4; lhs[k][BB][4][3]=tmp1*2.0*njac[k][4][3]; lhs[k][BB][0][4]=tmp1*2.0*njac[k][0][4]; lhs[k][BB][1][4]=tmp1*2.0*njac[k][1][4]; lhs[k][BB][2][4]=tmp1*2.0*njac[k][2][4]; lhs[k][BB][3][4]=tmp1*2.0*njac[k][3][4]; lhs[k][BB][4][4]=1.0 +tmp1*2.0*njac[k][4][4] +tmp1*2.0*dz5; lhs[k][CC][0][0]=tmp2*fjac[k+1][0][0] -tmp1*njac[k+1][0][0] -tmp1*dz1; lhs[k][CC][1][0]=tmp2*fjac[k+1][1][0] -tmp1*njac[k+1][1][0]; lhs[k][CC][2][0]=tmp2*fjac[k+1][2][0] -tmp1*njac[k+1][2][0]; lhs[k][CC][3][0]=tmp2*fjac[k+1][3][0] -tmp1*njac[k+1][3][0]; lhs[k][CC][4][0]=tmp2*fjac[k+1][4][0] -tmp1*njac[k+1][4][0]; lhs[k][CC][0][1]=tmp2*fjac[k+1][0][1] -tmp1*njac[k+1][0][1]; lhs[k][CC][1][1]=tmp2*fjac[k+1][1][1] -tmp1*njac[k+1][1][1] -tmp1*dz2; lhs[k][CC][2][1]=tmp2*fjac[k+1][2][1] -tmp1*njac[k+1][2][1]; lhs[k][CC][3][1]=tmp2*fjac[k+1][3][1] -tmp1*njac[k+1][3][1]; lhs[k][CC][4][1]=tmp2*fjac[k+1][4][1] -tmp1*njac[k+1][4][1]; lhs[k][CC][0][2]=tmp2*fjac[k+1][0][2] -tmp1*njac[k+1][0][2]; lhs[k][CC][1][2]= tmp2*fjac[k+1][1][2] -tmp1*njac[k+1][1][2]; lhs[k][CC][2][2]=tmp2*fjac[k+1][2][2] -tmp1*njac[k+1][2][2] -tmp1*dz3; lhs[k][CC][3][2]=tmp2*fjac[k+1][3][2] -tmp1*njac[k+1][3][2]; lhs[k][CC][4][2]=tmp2*fjac[k+1][4][2] -tmp1*njac[k+1][4][2]; lhs[k][CC][0][3]=tmp2*fjac[k+1][0][3] -tmp1*njac[k+1][0][3]; lhs[k][CC][1][3]=tmp2*fjac[k+1][1][3] -tmp1*njac[k+1][1][3]; lhs[k][CC][2][3]=tmp2*fjac[k+1][2][3] -tmp1*njac[k+1][2][3]; lhs[k][CC][3][3]=tmp2*fjac[k+1][3][3] -tmp1*njac[k+1][3][3] -tmp1*dz4; lhs[k][CC][4][3]=tmp2*fjac[k+1][4][3] -tmp1*njac[k+1][4][3]; lhs[k][CC][0][4]=tmp2*fjac[k+1][0][4] -tmp1*njac[k+1][0][4]; lhs[k][CC][1][4]=tmp2*fjac[k+1][1][4] -tmp1*njac[k+1][1][4]; lhs[k][CC][2][4]=tmp2*fjac[k+1][2][4] -tmp1*njac[k+1][2][4]; lhs[k][CC][3][4]=tmp2*fjac[k+1][3][4] -tmp1*njac[k+1][3][4]; lhs[k][CC][4][4]=tmp2*fjac[k+1][4][4] -tmp1*njac[k+1][4][4] -tmp1*dz5; } /* * --------------------------------------------------------------------- * performs guaussian elimination on this cell. * * assumes that unpacking routines for non-first cells * preload c' and rhs' from previous cell. * * assumed send happens outside this routine, but that * c'(KMAX) and rhs'(KMAX) will be sent to next cell. * --------------------------------------------------------------------- * outer most do loops - sweeping in i direction * --------------------------------------------------------------------- * multiply c(i,j,0) by b_inverse and copy back to c * multiply rhs(0) by b_inverse(0) and copy to rhs * --------------------------------------------------------------------- */ binvcrhs(lhs[0][BB], lhs[0][CC], rhs[0][j][i]); /* * --------------------------------------------------------------------- * begin inner most do loop * do all the elements of the cell unless last * --------------------------------------------------------------------- */ for(k=1; k<=ksize-1; k++){ /* * ------------------------------------------------------------------- * subtract A*lhs_vector(k-1) from lhs_vector(k) * * rhs(k) = rhs(k) - A*rhs(k-1) * ------------------------------------------------------------------- */ matvec_sub(lhs[k][AA], rhs[k-1][j][i], rhs[k][j][i]); /* * ------------------------------------------------------------------- * B(k) = B(k) - C(k-1)*A(k) * matmul_sub(aa,i,j,k,c,cc,i,j,k-1,c,bb,i,j,k) * -------------------------------------------------------------------- */ matmul_sub(lhs[k][AA], lhs[k-1][CC], lhs[k][BB]); /* * ------------------------------------------------------------------- * multiply c(i,j,k) by b_inverse and copy back to c * multiply rhs(i,j,1) by b_inverse(i,j,1) and copy to rhs * ------------------------------------------------------------------- */ binvcrhs(lhs[k][BB], lhs[k][CC], rhs[k][j][i]); } /* * --------------------------------------------------------------------- * now finish up special cases for last cell * --------------------------------------------------------------------- * rhs(ksize) = rhs(ksize) - A*rhs(ksize-1) * --------------------------------------------------------------------- */ matvec_sub(lhs[ksize][AA], rhs[ksize-1][j][i], rhs[ksize][j][i]); /* * --------------------------------------------------------------------- * B(ksize) = B(ksize) - C(ksize-1)*A(ksize) * matmul_sub(aa,i,j,ksize,c, * $ cc,i,j,ksize-1,c,bb,i,j,ksize) * --------------------------------------------------------------------- */ matmul_sub(lhs[ksize][AA], lhs[ksize-1][CC], lhs[ksize][BB]); /* * --------------------------------------------------------------------- * multiply rhs(ksize) by b_inverse(ksize) and copy to rhs * --------------------------------------------------------------------- */ binvrhs(lhs[ksize][BB], rhs[ksize][j][i]); /* * --------------------------------------------------------------------- * back solve: if last cell, then generate U(ksize)=rhs(ksize) * else assume U(ksize) is loaded in un pack backsub_info * so just use it * after u(kstart) will be sent to next cell * --------------------------------------------------------------------- */ for(k=ksize-1; k>=0; k--){ for(m=0; m<BLOCK_SIZE; m++){ for(n=0; n<BLOCK_SIZE; n++){ rhs[k][j][i][m]=rhs[k][j][i][m]-lhs[k][CC][n][m]*rhs[k+1][j][i][n]; } } } } }); if(timeron){timer_stop(T_ZSOLVE);} }
32.19822
134
0.441507
[ "vector" ]
a72932c0193808436554f3e287ba29a55f084c1b
36,301
cpp
C++
virtual_scan/src/vscan_server.cpp
LXYYY/CoScan
abd87b9e004cdf683b458d76cb93e62485aeba3c
[ "MIT" ]
15
2020-03-31T01:54:43.000Z
2022-03-31T16:27:29.000Z
virtual_scan/src/vscan_server.cpp
LXYYY/CoScan
abd87b9e004cdf683b458d76cb93e62485aeba3c
[ "MIT" ]
1
2022-03-18T10:27:55.000Z
2022-03-31T16:18:47.000Z
virtual_scan/src/vscan_server.cpp
LXYYY/CoScan
abd87b9e004cdf683b458d76cb93e62485aeba3c
[ "MIT" ]
7
2020-04-01T13:05:28.000Z
2021-03-08T04:58:01.000Z
// ros msgs && opencv #include "ros/ros.h" #include "geometry_msgs/Twist.h" #include "gazebo_msgs/SetModelState.h" #include "gazebo_msgs/GetModelState.h" #include "sensor_msgs/CameraInfo.h" #include <image_transport/image_transport.h> #include "std_msgs/String.h" #include <sensor_msgs/Image.h> #include <sensor_msgs/image_encodings.h> #include <cv_bridge/cv_bridge.h> #include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <stdio.h> #include <stdlib.h> #include <fstream> #include <sstream> #include <sys/types.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/wait.h> #include <pthread.h> #include <netinet/tcp.h> using namespace std; #define PI 3.1415926 #define SERVPORT 3333 int sockfd,client_fd,sin_size; struct sockaddr_in my_addr; struct sockaddr_in remote_addr; const int MAXRECV = 10240; #define BACKLOG 10 int rbtnum = 3; float camera_height = 1.1; cv::Mat rgbImg; cv::Mat shortImg(480, 640, CV_16UC1); bool rgb_ready = false; bool depth_ready = false; // image transport image_transport::ImageTransport* it; // rgbd data from topics vector<cv::Mat> crt_rgb_images(rbtnum); vector<cv::Mat> crt_depth_images(rbtnum); // subscribers vector<image_transport::Subscriber> subsColor(rbtnum); vector<image_transport::Subscriber> subsDepth(rbtnum); ros::ServiceClient gclient; ros::ServiceClient sclient; float pose[7]; bool pose_ready = false; const float camera_factor = 1000; const float camera_cx = 320.500000; const float camera_cy = 240.500000; const float camera_fx = 554.382713; const float camera_fy = 554.382713; const int times = 1.0; float rbt_v = 1.0/times - 0.01; //const double move_distance_rate = 1; // data offline rcv writer ofstream ofs_off; string int2str(int n) { stringstream ss; string s; ss<<n; ss>>s; return s; } int str2int(string s) { stringstream ss(s); int number; ss>>number; return number; } // color frame callback. 2018-09-10. no mem leak. 2018-09-19. void rgbImageCallback(const sensor_msgs::ImageConstPtr& msg, const std::string &rbtID) { printf("rgb callback, robot index: %s\n", rbtID.c_str()); int rbtIndex = str2int(rbtID); cv_bridge::CvImagePtr cvImgPtr; cv::Mat rgbPass; try { cvImgPtr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8); rgbPass = cvImgPtr->image; } catch(cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); } crt_rgb_images[rbtIndex] = rgbPass; } // depth frame callback. 2018-09-10. no mem leak. 2018-09-19. void depthImageCallback(const sensor_msgs::ImageConstPtr& msg, const std::string &rbtID) { printf("depth callback, robot index: %s\n", rbtID.c_str()); int rbtIndex = str2int(rbtID); cv_bridge::CvImagePtr cvImgPtr; cv::Mat depthImg; try { cvImgPtr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::TYPE_32FC1); depthImg = cvImgPtr->image; } catch(cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); } cv::Mat shortPass(480, 640, CV_16UC1); for (int i = 0; i < 480; ++i) { for (int j = 0; j < 640; ++j) { shortPass.ptr<short>(i)[j] = (short)(depthImg.ptr<float>(i)[j] * 1000); } } crt_depth_images[rbtIndex] = shortPass; } // pose void callForPose(int id){ gazebo_msgs::GetModelState getmodelstate; char s[10]; sprintf(s, "robot_%d", id); getmodelstate.request.model_name = (std::string) s; //ROS_INFO("call server to get pose"); if (gclient.call(getmodelstate)) { //ROS_INFO("success"); } else { ROS_ERROR("Failed to call service"); } pose[0] = getmodelstate.response.pose.position.x; pose[1] = getmodelstate.response.pose.position.y; pose[2] = getmodelstate.response.pose.position.z; pose[3] = getmodelstate.response.pose.orientation.x; pose[4] = getmodelstate.response.pose.orientation.y; pose[5] = getmodelstate.response.pose.orientation.z; pose[6] = getmodelstate.response.pose.orientation.w; pose_ready = true; } void setForPose(int id, float x, float y, float z, float qx, float qy, float qz, float qw){ printf("set pose for robot %d...", id); gazebo_msgs::SetModelState setmodelstate; char s[10]; sprintf(s, "robot_%d", id); geometry_msgs::Pose posemsg; posemsg.position.x = x; posemsg.position.y = y; posemsg.position.z = z; posemsg.orientation.x = qx; posemsg.orientation.y = qy; posemsg.orientation.z = qz; posemsg.orientation.w = qw; gazebo_msgs::ModelState modelstate; modelstate.pose = posemsg; modelstate.model_name = (std::string) s; setmodelstate.request.model_state = modelstate; if (sclient.call(setmodelstate)){} else ROS_ERROR("Failed to call service"); printf(" succeed.\n"); } void infoCallback(const sensor_msgs::CameraInfoConstPtr &msg){ //printf("cx: %lf, cy: %lf, fx: %lf, fy: %lf\n", msg->K[2], msg->K[5], msg->K[0], msg->K[4]); //printf("fx: %lf\n", msg->K[0]); } // recv int recvData(const int client_fd, char buf[], int len) { memset (buf, 0, len); int i=0; while(i<len){ char buf_tem[MAXRECV]; memset (buf_tem, 0, MAXRECV); int status = recv(client_fd, buf_tem, MAXRECV, 0); memcpy(buf+i, buf_tem, status); i = i+status; //printf("i:%d\n", i); //printf("len:%d\n", len); //printf("status:%d\n", status); if ( status == -1 ) { printf("status == -1 errno == %s in Socket::recv\n",errno); return 0; } else if( status == 0 ) { //stop(client_fd); //return 0; break; } else if(len<=MAXRECV+1) { break; } /*else { return status; }*/ } } // send bool sendData(const int client_fd, const char *ch, const int len) { int status = send(client_fd, ch, len, 0); if ( status == -1 ) { return false; } else { return true; } } // send data. 2018-09-17 int sendTotalData(const int client_fd, const char *buf, const int len){ int total = 0; // how many bytes we've sent int bytesleft = len; // how many we have left to send int n; while(total < len) { n = send(client_fd, buf+total, bytesleft, 0); if (n == -1) { break; } total += n; bytesleft -= n; } return n==-1 ? 0:1; // return -1 onm failure, 0 on success } // socket get rgbd bool getRGBD(int client_fd){ ros::spinOnce(); ros::Rate rate(1); // 1hz rate.sleep(); // rgb { int data_len = 480 * 640 * 3 * sizeof(uchar) * rbtnum; char* rgbData = (char *)malloc(data_len); //if(rgbData == NULL) printf("malloc failed\n"); while(!rgbData) { usleep(100000); rgbData = (char *)malloc(data_len); } // for multi robot int ind = 0; for (int rid = 0; rid < rbtnum; ++rid) { for (int i = 0; i < 480; ++i) { for (int j = 0; j < 640; ++j) { memcpy(&rgbData[ind], &crt_rgb_images[rid].ptr<cv::Vec3b>(i)[j][0], sizeof(uchar)); ind+=sizeof(uchar); memcpy(&rgbData[ind], &crt_rgb_images[rid].ptr<cv::Vec3b>(i)[j][1], sizeof(uchar)); ind+=sizeof(uchar); memcpy(&rgbData[ind], &crt_rgb_images[rid].ptr<cv::Vec3b>(i)[j][2], sizeof(uchar)); ind+=sizeof(uchar); } } } int rtnCode = sendTotalData(client_fd, rgbData, data_len); printf("rgb data %d byte send back done. rtnCode = %d\n", data_len, rtnCode); free(rgbData); } // depth { int data_len = 480 * 640 * sizeof(short) * rbtnum; char* depthData = (char *)malloc(data_len); while(!depthData) { usleep(100000); depthData = (char *)malloc(data_len); } // for multi robot int ind = 0; for (int rid = 0; rid < rbtnum; ++rid) { for (int i = 0; i < 480; ++i) { for (int j = 0; j < 640; ++j) { memcpy(&depthData[ind], &crt_depth_images[rid].ptr<short>(i)[j], sizeof(short)); ind+=sizeof(short); } } } //int rtnCode = sendData(client_fd, depthData, data_len); int rtnCode = sendTotalData(client_fd, depthData, data_len); printf("depth data %d byte send back done. rtnCode = %d\n", data_len, rtnCode); free(depthData); } return true; } // socket get depth bool getDepth(int client_fd){ printf("this method is abandoned"); getchar(); return true; } // socket get pose bool getPose(int client_fd) { printf("\ngetPose: ...\n"); int data_len = 7 * sizeof(float) * rbtnum; char* poseData = (char *)malloc(data_len); while(!poseData) { usleep(100000); poseData = (char *)malloc(data_len); } // for multi robot int ind = 0; for (int rid = 0; rid < rbtnum; ++rid) { callForPose(rid); for (int i = 0; i < 7; ++i) { memcpy(&poseData[ind], &pose[i], sizeof(float)); ind+=sizeof(float); } } //int rtnCode = sendData(client_fd, poseData, data_len); int rtnCode = sendTotalData(client_fd, poseData, data_len); //printf("pose data %d byte send back done. rtnCode = %d\n", data_len, rtnCode); ind = 0; for (int rid = 0; rid < rbtnum; ++rid) { for (int i = 0; i < 7; ++i) { float temp; memcpy(&temp, &poseData[ind], sizeof(float)); ind+=sizeof(float); printf("%f ", temp); } printf("\n"); } free(poseData); printf("getPose: done.\n"); return true; } void goToPose(float x0 , float y0, float qx0, float qy0, float qz0, float qw0, float x1 , float y1, float qx1, float qy1, float qz1, float qw1, float x2 , float y2, float qx2, float qy2, float qz2, float qw2){ printf("\ngoToPose\n"); //printf("set to x0=%f y0=%f x1=%f y1=%f x2=%f y2=%f\n", x0, y0, x1, y1, x2, y2); // rotation try // pose0 callForPose(0); float originTheta0 = acos(pose[6])*2; if(pose[5]<0) originTheta0 = -originTheta0; float objectTheta0 = acos(qw0)*2; if(qz0<0) objectTheta0 = -objectTheta0; float dTheta0 = objectTheta0 - originTheta0; float dx0 = rbt_v * (x0 - pose[0]); float dy0 = rbt_v * (y0 - pose[1]); // pose1 callForPose(1); float originTheta1 = acos(pose[6])*2; if(pose[5]<0) originTheta1 = -originTheta1; float objectTheta1 = acos(qw1)*2; if(qz1<0) objectTheta1 = -objectTheta1; float dTheta1 = objectTheta1 - originTheta1; float dx1 = rbt_v * (x1 - pose[0]); float dy1 = rbt_v * (y1 - pose[1]); // pose2 callForPose(2); float originTheta2 = acos(pose[6])*2; if(pose[5]<0) originTheta2 = -originTheta2; float objectTheta2 = acos(qw2)*2; if(qz2<0) objectTheta2 = -objectTheta2; float dTheta2 = objectTheta2 - originTheta2; float dx2 = rbt_v * (x2 - pose[0]); float dy2 = rbt_v * (y2 - pose[1]); for (int i = 0; i < times; ++i) { float ox = 0.0, oy = 0.0, oz = 1.0; // pose 0 callForPose(0); float crtTheta0 = acos(pose[6])*2; if(pose[5]<0) crtTheta0 = -crtTheta0; float temp_theta0 = crtTheta0 + dTheta0/times; setForPose(0, pose[0], pose[1], camera_height, ox*sin(temp_theta0/2), oy*sin(temp_theta0/2), oz*sin(temp_theta0/2), cos(temp_theta0/2)); // pose 1 callForPose(1); float crtTheta1 = acos(pose[6])*2; if(pose[5]<0) crtTheta1 = -crtTheta1; float temp_theta1 = crtTheta1 + dTheta1/times; setForPose(1, pose[0], pose[1], camera_height, ox*sin(temp_theta1/2), oy*sin(temp_theta1/2), oz*sin(temp_theta1/2), cos(temp_theta1/2)); // pose 2 callForPose(2); float crtTheta2 = acos(pose[6])*2; if(pose[5]<0) crtTheta2 = -crtTheta2; float temp_theta2 = crtTheta2 + dTheta2/times; setForPose(2, pose[0], pose[1], camera_height, ox*sin(temp_theta2/2), oy*sin(temp_theta2/2), oz*sin(temp_theta2/2), cos(temp_theta2/2)); // send to socket ros::spinOnce(); ros::Rate rate(1); //ros::Rate rate(10); // 01-09. rate.sleep(); //getDepth(client_fd); getPose(client_fd); getRGBD(client_fd); } // move for (int i = 0; i < times; ++i){ //0 callForPose(0); float tx0 = pose[0] + dx0; float ty0 = pose[1] + dy0; //1 callForPose(1); float tx1 = pose[0] + dx1; float ty1 = pose[1] + dy1; //2 callForPose(2); float tx2 = pose[0] + dx2; float ty2 = pose[1] + dy2; setForPose(0, tx0, ty0, camera_height, qx0, qy0, qz0, qw0); setForPose(1, tx1, ty1, camera_height, qx1, qy1, qz1, qw1); setForPose(2, tx2, ty2, camera_height, qx2, qy2, qz2, qw2); // send to socket ros::spinOnce(); ros::Rate rate(1); //ros::Rate rate(10); // 01-09. rate.sleep(); //getDepth(client_fd); getPose(client_fd); getRGBD(client_fd); } printf("goToPose: done.\n"); } // socket move to views bool move_to_views(int client_fd){ printf("\nfunc move_to_views begin\n"); // receive data int data_len = rbtnum * 7 * sizeof(float); char* poseData = (char *)malloc(data_len); while(!poseData) { usleep(100000); poseData = (char *)malloc(data_len); } //printf("before recv\n"); int rcv_len = recvData(client_fd, poseData, data_len); // recv //printf("after recv\n"); float pass_pose[rbtnum][7]; int ind = 0; // move: set poses to views for (int id = 0; id < rbtnum; ++id) { float set_pose[7]; for (int i = 0; i < 7; ++i) { memcpy(&set_pose[i], &poseData[ind], sizeof(float)); memcpy(&pass_pose[id][i], &poseData[ind], sizeof(float)); ind+=sizeof(float); } setForPose(id, set_pose[0], set_pose[1], set_pose[2], set_pose[3], set_pose[4], set_pose[5], set_pose[6]); //printf("pose for robot%d: %f, %f, %f, %f, %f, %f, %f\n", id, // set_pose[0], set_pose[1], set_pose[2], // set_pose[3], set_pose[4], set_pose[5], set_pose[6]); } // free free(poseData); printf("func move_to_views end\n\n"); // update rgbd and pose topic ros::spinOnce(); ros::Rate rate(1); rate.sleep(); return true; } // socket set pose bool setPose(int client_fd){ printf("\nsetPose\n"); int data_len = rbtnum * 7 * sizeof(float); char* poseData = (char *)malloc(data_len); while(!poseData) { usleep(100000); poseData = (char *)malloc(data_len); } int rcv_len = recvData(client_fd, poseData, data_len); float pass_pose[rbtnum][7]; int ind = 0; for (int id = 0; id < rbtnum; ++id) { float set_pose[7]; for (int i = 0; i < 7; ++i) { memcpy(&set_pose[i], &poseData[ind], sizeof(float)); memcpy(&pass_pose[id][i], &poseData[ind], sizeof(float)); ind+=sizeof(float); } } goToPose( pass_pose[0][0], pass_pose[0][1], pass_pose[0][3], pass_pose[0][4], pass_pose[0][5], pass_pose[0][6], pass_pose[1][0], pass_pose[1][1], pass_pose[1][3], pass_pose[1][4], pass_pose[1][5], pass_pose[1][6], pass_pose[2][0], pass_pose[2][1], pass_pose[2][3], pass_pose[2][4], pass_pose[2][5], pass_pose[2][6]); free(poseData); printf("\nsetPose: done.\n"); return true; } //vector< vector< vector<float> > > send_poses; struct PositionInGazebo{ float x; float y; float z; PositionInGazebo(float ix, float iy, float iz){ x = ix; y = iy; z = iz; } }; vector< vector< PositionInGazebo > > path_poses; vector< PositionInGazebo > task_poses; // set path bool setPath(int client_fd){ /* /// clear and resize path_poses path_poses.clear(); path_poses.resize(rbtnum); // recv path data for (int rid = 0; rid < rbtnum; ++rid) { char len_data[sizeof(int)]; recvData(client_fd, len_data, sizeof(int));//recv data lenth int data_len = 0; memcpy(&data_len, &len_data, sizeof(int)); char path_data[MAXRECV]; recvData(client_fd, path_data, data_len);// recv path data // memcpy to path_poses int path_size = ceil(data_len/3/sizeof(float)); int ind = 0; for (int pid = 0; pid < path_size; ++pid) { float x, y, z; memcpy(&x, &path_data[ind], sizeof(float)); ind+=sizeof(float); memcpy(&y, &path_data[ind], sizeof(float)); ind+=sizeof(float); memcpy(&z, &path_data[ind], sizeof(float)); ind+=sizeof(float); PositionInGazebo crt_p = PositionInGazebo(x, y, z); path_poses[rid].push_back(crt_p); } } // compute path distance for each robot vector<float> path_dises; double min_dis = DBL_MAX; int min_rid = -1; for (int rid = 0; rid < rbtnum; ++rid) { if(path_poses[rid].size() == 1){ // if dont have move path path_dises.push_back(0); continue; } float path_dis = 0; for (int pid = 0; pid < path_poses[rid].size()-1; ++pid) { path_dis+= sqrt( (path_poses[rid][pid].x-path_poses[rid][pid+1].x)*(path_poses[rid][pid].x-path_poses[rid][pid+1].x) + (path_poses[rid][pid].y-path_poses[rid][pid+1].y)*(path_poses[rid][pid].y-path_poses[rid][pid+1].y)); } path_dises.push_back(path_dis); } // compute min distance path for (int rid = 0; rid < path_dises.size(); ++rid) { printf("rbt%d path distance = %f\n", rid, path_dises[rid]); if(min_dis>path_dises[rid]){ min_dis = path_dises[rid]; min_rid = rid; } } printf("min_dis = %f\n", min_dis); {//move_distance_rate min_rid = -1; min_dis *= move_distance_rate; } // move robots for (int rid = 0; rid < rbtnum; ++rid) { // move for no path robot if(path_poses[rid].size() == 1){ callForPose(rid); float obj_x=.1, obj_y=.1, crt_x = .1, crt_y = .1; obj_x = task_poses[rid].x; obj_y = task_poses[rid].y; crt_x = pose[0]; crt_y = pose[1]; float dir_theta; printf("fabs(obj_x - crt_x)=%f fabs(obj_y - crt_y)=%f\n", fabs(obj_x - crt_x), fabs(obj_y - crt_y)); if(fabs(obj_x - crt_x) < 0.2 && fabs(obj_y - crt_y) < 0.2){ // task_pose == rbt pose float originTheta = acos(pose[6])*2; if(pose[5]<0) originTheta = -originTheta; dir_theta = originTheta+PI/3; if(dir_theta>PI) dir_theta = -PI + dir_theta - PI; printf("turn PI/3\n"); }else{// task_pose != rbt pose // compute direction float dx = obj_x - crt_x; float dy = obj_y - crt_y; // compute rotation if (dx > 0){ if(dy == 0){ dir_theta = 0; } else{ dir_theta = atan(dy / dx); } } else if (dx == 0){ if(dy > 0){ dir_theta = PI/2; } else if (dy == 0){ dir_theta = 0; // need to modify to origin direction } else{// dy < 0 dir_theta = -PI/2; } } else{ // dx < 0 if(dy>0){ dir_theta = PI - fabs(atan(dy / dx)); } else if(dy == 0){ dir_theta = PI; } else{// dy < 0 dir_theta = -(PI - fabs(atan(dy / dx))); } } } setForPose(rid, crt_x, crt_y, camera_height, 0.0*sin(dir_theta/2), 0.0*sin(dir_theta/2), 1.0*sin(dir_theta/2), cos(dir_theta/2)); printf("rbt%d dont move\n", rid); printf("rbt%d set to (%f, %f)\n", rid, crt_x, crt_y); continue; } // move for min robot if(rid == min_rid){ int node_num = path_poses[rid].size(); // compute direction float dx = task_poses[rid].x - path_poses[rid][node_num-1].x; float dy = task_poses[rid].y - path_poses[rid][node_num-1].y; // float dx = path_poses[rid][node_num-1].x - path_poses[rid][node_num-2].x; // float dy = path_poses[rid][node_num-1].y - path_poses[rid][node_num-2].y; float dir_theta; // compute rotation if (dx > 0){ if(dy == 0){ dir_theta = 0; } else{ dir_theta = atan(dy / dx); } } else if (dx == 0){ if(dy > 0){ dir_theta = PI/2; } else if (dy == 0){ dir_theta = 0; // need to modify to origin direction } else{// dy < 0 dir_theta = -PI/2; } } else{ // dx < 0 if(dy>0){ dir_theta = PI - fabs(atan(dy / dx)); } else if(dy == 0){ dir_theta = PI; } else{// dy < 0 dir_theta = -(PI - fabs(atan(dy / dx))); } } // set pose setForPose(rid, path_poses[rid][node_num-1].x, path_poses[rid][node_num-1].y, camera_height, 0.0*sin(dir_theta/2), 0.0*sin(dir_theta/2), 1.0*sin(dir_theta/2), cos(dir_theta/2)); printf("rbt%d min\n", rid); printf("rbt%d set to (%f, %f)\n", rid, path_poses[rid][node_num-1].x, path_poses[rid][node_num-1].y); } // move for not min robot else{ float obj_x=.1, obj_y=.1, crt_x = .1, crt_y = .1, lst_x=.1, lst_y=.1; float crt_dis = 0; for (int pid = 0; pid < path_poses[rid].size()-1; ++pid) // find obj position and lst position { float tmp_dis = sqrt( (path_poses[rid][pid].x-path_poses[rid][pid+1].x)*(path_poses[rid][pid].x-path_poses[rid][pid+1].x) + (path_poses[rid][pid].y-path_poses[rid][pid+1].y)*(path_poses[rid][pid].y-path_poses[rid][pid+1].y)); crt_dis += tmp_dis; //printf(" rbt%d crt_dis = %f\n", rid, crt_dis); if(crt_dis == min_dis){ //printf(" rbt%d crt_dis == min_dis\n", rid); obj_x = task_poses[rid].x; obj_y = task_poses[rid].y; crt_x = path_poses[rid][pid+1].x; crt_y = path_poses[rid][pid+1].y; // obj_x = path_poses[rid][pid+1].x; // obj_y = path_poses[rid][pid+1].y; // lst_x = path_poses[rid][pid].x; // lst_y = path_poses[rid][pid].y; break; } if(crt_dis > min_dis){ //printf(" rbt%d crt_dis > min_dis\n", rid); crt_dis -= tmp_dis; float res_dis = min_dis - crt_dis; {// temp use this obj_x = task_poses[rid].x; obj_y = task_poses[rid].y; crt_x = path_poses[rid][pid+1].x; crt_y = path_poses[rid][pid+1].y; // obj_x = path_poses[rid][pid+1].x; // obj_y = path_poses[rid][pid+1].y; // lst_x = path_poses[rid][pid].x; // lst_y = path_poses[rid][pid].y; } { // to do? } break; } } // compute direction float dx = obj_x - crt_x; float dy = obj_y - crt_y; float dir_theta; // compute rotation if (dx > 0){ if(dy == 0){ dir_theta = 0; } else{ dir_theta = atan(dy / dx); } } else if (dx == 0){ if(dy > 0){ dir_theta = PI/2; } else if (dy == 0){ dir_theta = 0; // need to modify to origin direction } else{// dy < 0 dir_theta = -PI/2; } } else{ // dx < 0 if(dy>0){ dir_theta = PI - fabs(atan(dy / dx)); } else if(dy == 0){ dir_theta = PI; } else{// dy < 0 dir_theta = -(PI - fabs(atan(dy / dx))); } } // set pose setForPose(rid, crt_x, crt_y, camera_height, 0.0*sin(dir_theta/2), 0.0*sin(dir_theta/2), 1.0*sin(dir_theta/2), cos(dir_theta/2)); printf("rbt%d not min\n", rid); printf("rbt%d set to (%f, %f)\n", rid, crt_x, crt_y); } } // get scans // send to socket ros::spinOnce(); ros::Rate rate(1); //ros::Rate rate(10); // 01-09. rate.sleep(); getPose(client_fd); getRGBD(client_fd); //getchar(); printf("move correctly\n"); //*/ return true; } // set up bool scanSurroundings(int client_fd){ printf("scanning surroundings...\n"); //float cover_angle = PI/3; for (int i = 0; i < 6; ++i) { for (int rid = 0; rid < rbtnum; ++rid) { callForPose(rid); float originTheta = acos(pose[6])*2; if(pose[5]<0) originTheta = -originTheta; float dir_theta = originTheta+PI/3; if(dir_theta>PI) dir_theta = -PI + dir_theta - PI; setForPose(rid, pose[0], pose[1], camera_height, 0.0*sin(dir_theta/2), 0.0*sin(dir_theta/2), 1.0*sin(dir_theta/2), cos(dir_theta/2)); printf("robot_%d turned 60 degree.\n", rid); } // get scans // send to socket printf("ros sleep and spin once to get pose and rgbd...\n"); ros::spinOnce(); ros::Rate rate(1); //ros::Rate rate(10); // 01-09. rate.sleep(); //printf("ros getting pose...\n"); getPose(client_fd); //printf("ros getting rgbd...\n"); getRGBD(client_fd); } return true; } // set task positions bool setTaskPositions(int client_fd){ task_poses.clear(); // recv data int data_len = rbtnum*2*sizeof(float); char otp_data[MAXRECV]; recvData(client_fd, otp_data, data_len);// recv otp data // memcpy to task_poses int ind = 0; for (int rid = 0; rid < rbtnum; ++rid) { float x, y; memcpy(&x, &otp_data[ind], sizeof(float)); ind+=sizeof(float); memcpy(&y, &otp_data[ind], sizeof(float)); ind+=sizeof(float); PositionInGazebo crt_p = PositionInGazebo(x, y, camera_height); task_poses.push_back(crt_p); } return true; } // change robot number void change_robot_number_local(int number) { // change robot number rbtnum = number; // re initialization { // frame data. crt_rgb_images.clear(); crt_rgb_images.resize(rbtnum); crt_depth_images.clear(); crt_depth_images.resize(rbtnum); for (int rid = 0; rid < rbtnum; ++rid) { crt_rgb_images[rid] = cv::Mat(480, 640, CV_8UC3); crt_depth_images[rid] = cv::Mat(480, 640, CV_16UC1); } // ros topics. RGBD. subsColor.clear(); subsColor.resize(rbtnum); subsDepth.clear(); subsDepth.resize(rbtnum); for (int rid = 0; rid < rbtnum; ++rid) { { // color char topicName[100]; sprintf(topicName, "camera%d/rgb/image_raw", rid); //subsColor[rid] = it.subscribe(topicName, 1, boost::bind(rgbImageCallback, _1, int2str(rid))); subsColor[rid] = it->subscribe(topicName, 1, boost::bind(rgbImageCallback, _1, int2str(rid))); } {// depth char topicName[100]; sprintf(topicName, "camera%d/depth/image_raw", rid); //subsDepth[rid] = it.subscribe(topicName, 1, boost::bind(depthImageCallback, _1, int2str(rid))); subsDepth[rid] = it->subscribe(topicName, 1, boost::bind(depthImageCallback, _1, int2str(rid))); } } } // end. return; } // change robot number bool change_robot_number(int client_fd) { // recv robot number int data_len = sizeof(int); char recv_data[MAXRECV]; recvData(client_fd, recv_data, data_len); int number = rbtnum; memcpy(&number, &recv_data[0], sizeof(int)); // change number change_robot_number_local(number); printf("changed robot number: %d\n", rbtnum); return true; } // thread void *thread(void *ptr) { int client = *(int *)ptr; bool stopped=false; while(!stopped) { char message [MAXRECV+1]; printf("wait for a command...\n"); if(recvData(client_fd, message, MAXRECV+1)) { printf("message: %s\n", message); if(message!=NULL&&strlen(message)!=0) { printf("command message: %c\n", message[0]); switch(message[0]) { case '0': { printf("ask for depth\n"); getDepth(client_fd); break; } case '1': { printf("ask for pose\n"); getPose(client_fd); break; } case '2': { printf("ask to set pose\n"); setPose(client_fd); break; } case '3': { printf("ask for rgbd\n"); getRGBD(client_fd); break; } case '4': { printf("ask to set path\n"); setPath(client_fd); break; } case '5': { printf("set up surroundings\n"); scanSurroundings(client_fd); break; } case '6': { printf("ask to set task positions\n"); setTaskPositions(client_fd); break; } case 'm': { printf("move_to_views\n"); move_to_views(client_fd); break; } case 'e': { printf("command: stop the socket thread\n"); stopped = true; break; } case 'n': { printf("check robot number\n"); change_robot_number(client_fd); break; } default: { printf("invalid command\n"); break; } } } } usleep(100000); // 100 ms } printf("thread stop done.\n"); return 0; } // enter point int main(int argc, char **argv){ printf("this new workspace\n"); //getchar(); // set up ros env ros::init(argc, argv, "octo_navi"); ros::NodeHandle n; it = new image_transport::ImageTransport(n); // need release manually. // // write // ofs_off.open("/home/dsy/catkin_ws/src/virtual_scan/data/offline/pose_history.txt"); // //ofs_off.close(); // input robot number { ifstream ifs("/home/bamboo/catkin_ws/src/virtual_scan/config_nrbt.txt"); ifs>>rbtnum; ifs.close(); printf("robot number = %d\n", rbtnum); } // initialization { // frame data. crt_rgb_images.clear(); crt_rgb_images.resize(rbtnum); crt_depth_images.clear(); crt_depth_images.resize(rbtnum); for (int rid = 0; rid < rbtnum; ++rid) { crt_rgb_images[rid] = cv::Mat(480, 640, CV_8UC3); crt_depth_images[rid] = cv::Mat(480, 640, CV_16UC1); } // ros topics. RGBD. subsColor.clear(); subsColor.resize(rbtnum); subsDepth.clear(); subsDepth.resize(rbtnum); for (int rid = 0; rid < rbtnum; ++rid) { { // color char topicName[100]; sprintf(topicName, "camera%d/rgb/image_raw", rid); //subsColor[rid] = it.subscribe(topicName, 1, boost::bind(rgbImageCallback, _1, int2str(rid))); subsColor[rid] = it->subscribe(topicName, 1, boost::bind(rgbImageCallback, _1, int2str(rid))); } {// depth char topicName[100]; sprintf(topicName, "camera%d/depth/image_raw", rid); //subsDepth[rid] = it.subscribe(topicName, 1, boost::bind(depthImageCallback, _1, int2str(rid))); subsDepth[rid] = it->subscribe(topicName, 1, boost::bind(depthImageCallback, _1, int2str(rid))); } } } // kinect calibration //ros::Subscriber calib_sub = n.subscribe("camera/depth/camera_info", 1, infoCallback); // services: pose gclient = n.serviceClient<gazebo_msgs::GetModelState>("/gazebo/get_model_state"); sclient = n.serviceClient<gazebo_msgs::SetModelState>("/gazebo/set_model_state"); // // test callback func // ros::spin(); // return 0; // socket if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } my_addr.sin_family=AF_INET; my_addr.sin_port=htons(SERVPORT); my_addr.sin_addr.s_addr = INADDR_ANY; bzero(&(my_addr.sin_zero),8); if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) { perror("bind"); exit(1); } if (listen(sockfd, BACKLOG) == -1) { perror("listen"); exit(1); } // set keepalive { int keepAlive = 1; // enable keepalive int keepIdle = 60; // 60 second int keepInterval = 5; // 5 second int keepCount = 3; setsockopt(client_fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepAlive, sizeof(keepAlive)); setsockopt(client_fd, SOL_TCP, TCP_KEEPIDLE, (void*)&keepIdle, sizeof(keepIdle)); setsockopt(client_fd, SOL_TCP, TCP_KEEPINTVL, (void *)&keepInterval, sizeof(keepInterval)); setsockopt(client_fd, SOL_TCP, TCP_KEEPCNT, (void *)&keepCount, sizeof(keepCount)); } // disable nagle { int flag = 1; if(setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, (char*)&flag, sizeof(int))<0){ printf("disable nagle failed\n"); } } while (1) { sin_size = sizeof(my_addr); printf("%s\n", "waiting for a connection"); client_fd = accept(sockfd, (struct sockaddr*)&remote_addr, (socklen_t *) &sin_size); if (client_fd == -1) { perror("failed"); continue; } printf("%s\n", "received a connection"); // set keepalive { int keepAlive = 1; int keepIdle = 60; int keepInterval = 5; int keepCount = 3; setsockopt(client_fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepAlive, sizeof(keepAlive)); setsockopt(client_fd, SOL_TCP, TCP_KEEPIDLE, (void*)&keepIdle, sizeof(keepIdle)); setsockopt(client_fd, SOL_TCP, TCP_KEEPINTVL, (void *)&keepInterval, sizeof(keepInterval)); setsockopt(client_fd, SOL_TCP, TCP_KEEPCNT, (void *)&keepCount, sizeof(keepCount)); } // disable nagle { int flag = 1; if(setsockopt(client_fd, IPPROTO_TCP, TCP_NODELAY, (char*)&flag, sizeof(int))<0){ printf("disable nagle failed\n"); } } pthread_t id; int ret = pthread_create(&id, NULL, thread, &client_fd); if(ret!=0) { printf("Create pthread error: %s\n", strerror(ret)); continue; } printf("succeed connected.\n"); usleep(100000); } return 0; }
28.948166
186
0.53544
[ "vector" ]
a729c96cd60a6b4b1e0ce79f3b366e70e0e6ea39
20,110
hpp
C++
src/third_party/catch/include/helpers.hpp
eldruin/mongo-cxx-driver
22d6f93c7187f56e9049f10223cf2bbe07a1f472
[ "Apache-2.0" ]
1
2021-09-02T06:34:29.000Z
2021-09-02T06:34:29.000Z
src/third_party/catch/include/helpers.hpp
eldruin/mongo-cxx-driver
22d6f93c7187f56e9049f10223cf2bbe07a1f472
[ "Apache-2.0" ]
1
2021-06-28T14:22:32.000Z
2021-06-28T14:22:32.000Z
src/third_party/catch/include/helpers.hpp
PiratesOnlineClassic/mongo-cxx-driver
8371f2ea47b24fe1eebd89131d35b1f42e50777d
[ "Apache-2.0" ]
1
2019-08-14T09:31:02.000Z
2019-08-14T09:31:02.000Z
// Copyright 2014 MongoDB Inc. // // 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 <bsoncxx/test_util/catch.hh> #include <mongocxx/exception/exception.hpp> #include <mongocxx/private/libmongoc.hh> #include <mongocxx/config/private/prelude.hh> namespace mongocxx { MONGOCXX_INLINE_NAMESPACE_BEGIN namespace test_util { // Check that an error message includes a substring, case-insensitively. Use like: // REQUIRE_THROWS_MATCHES(function(), mongocxx::exception, mongocxx_exception_matcher("substring") class mongocxx_exception_matcher : public Catch::MatcherBase<mongocxx::exception> { std::string expected_msg; public: mongocxx_exception_matcher(std::string msg) : expected_msg(msg) {} bool match(const mongocxx::exception& exc) const override { return Catch::Contains(expected_msg, Catch::CaseSensitive::No).match(exc.what()); } std::string describe() const override { return std::string("mongocxx::exception contains message: \"") + expected_msg + "\""; } }; } // namespace test_util MONGOCXX_INLINE_NAMESPACE_END } // namespace mongocxx #define CHECK_OPTIONAL_ARGUMENT(OBJECT, NAME, VALUE) \ SECTION("has NAME disengaged") { \ REQUIRE(!OBJECT.NAME()); \ } \ \ SECTION("has a method to set the NAME") { \ OBJECT.NAME(VALUE); \ REQUIRE(OBJECT.NAME().value() == VALUE); \ } #define MOCK_POOL_NOSSL \ auto client_pool_new = libmongoc::client_pool_new.create_instance(); \ client_pool_new->interpose([](const mongoc_uri_t*) { return nullptr; }).forever(); \ auto client_pool_destroy = libmongoc::client_pool_destroy.create_instance(); \ client_pool_destroy->interpose([&](::mongoc_client_pool_t*) {}).forever(); \ auto client_pool_pop = libmongoc::client_pool_pop.create_instance(); \ client_pool_pop->interpose([](::mongoc_client_pool_t*) { return nullptr; }).forever(); \ auto client_pool_push = libmongoc::client_pool_push.create_instance(); \ client_pool_push->interpose([](::mongoc_client_pool_t*, ::mongoc_client_t*) {}).forever(); \ auto client_pool_try_pop = libmongoc::client_pool_try_pop.create_instance(); \ client_pool_try_pop->interpose([](::mongoc_client_pool_t*) { return nullptr; }).forever(); #if defined(MONGOCXX_ENABLE_SSL) && defined(MONGOC_ENABLE_SSL) #define MOCK_POOL \ MOCK_POOL_NOSSL \ auto client_pool_set_ssl_opts = libmongoc::client_pool_set_ssl_opts.create_instance(); \ client_pool_set_ssl_opts->interpose([](::mongoc_client_pool_t*, const ::mongoc_ssl_opt_t*) {}); #else #define MOCK_POOL MOCK_POOL_NOSSL #endif #define MOCK_CLIENT_NOSSL \ auto client_new = libmongoc::client_new_from_uri.create_instance(); \ auto client_destroy = libmongoc::client_destroy.create_instance(); \ auto client_set_read_concern = libmongoc::client_set_read_concern.create_instance(); \ auto client_set_preference = libmongoc::client_set_read_prefs.create_instance(); \ client_set_preference->interpose([](mongoc_client_t*, const mongoc_read_prefs_t*) {}) \ .forever(); \ auto client_get_preference = libmongoc::client_get_read_prefs.create_instance(); \ client_get_preference->interpose([](const mongoc_client_t*) { return nullptr; }).forever(); \ auto client_set_concern = libmongoc::client_set_write_concern.create_instance(); \ client_set_concern->interpose([](mongoc_client_t*, const mongoc_write_concern_t*) {}) \ .forever(); \ auto client_get_concern = libmongoc::client_get_write_concern.create_instance(); \ client_get_concern->interpose([](const mongoc_client_t*) { return nullptr; }).forever(); \ auto client_start_session = libmongoc::client_start_session.create_instance(); #if defined(MONGOCXX_ENABLE_SSL) && defined(MONGOC_ENABLE_SSL) #define MOCK_CLIENT \ MOCK_CLIENT_NOSSL \ auto client_set_ssl_opts = libmongoc::client_set_ssl_opts.create_instance(); \ client_set_ssl_opts->interpose([](::mongoc_client_t*, const ::mongoc_ssl_opt_t*) {}); #else #define MOCK_CLIENT MOCK_CLIENT_NOSSL #endif #define MOCK_DATABASE \ auto get_database = libmongoc::client_get_database.create_instance(); \ get_database->interpose([&](mongoc_client_t*, const char*) { return nullptr; }); \ auto database_set_read_concern = libmongoc::database_set_read_concern.create_instance(); \ auto database_set_preference = libmongoc::database_set_read_prefs.create_instance(); \ database_set_preference->interpose([](mongoc_database_t*, const mongoc_read_prefs_t*) {}) \ .forever(); \ auto database_get_preference = libmongoc::database_get_read_prefs.create_instance(); \ database_get_preference->interpose([](const mongoc_database_t*) { return nullptr; }) \ .forever(); \ auto database_set_concern = libmongoc::database_set_write_concern.create_instance(); \ database_set_concern->interpose([](mongoc_database_t*, const mongoc_write_concern_t*) {}) \ .forever(); \ auto database_get_concern = libmongoc::database_get_write_concern.create_instance(); \ database_get_concern->interpose([](const mongoc_database_t*) { return nullptr; }).forever(); \ auto database_destroy = libmongoc::database_destroy.create_instance(); \ database_destroy->interpose([](mongoc_database_t*) {}).forever(); \ auto database_drop = libmongoc::database_drop.create_instance(); \ database_drop->interpose([](mongoc_database_t*, bson_error_t*) { return true; }).forever(); \ auto database_get_collection = libmongoc::database_get_collection.create_instance(); \ database_get_collection->interpose([](mongoc_database_t*, const char*) { return nullptr; }) \ .forever(); \ auto database_has_collection = libmongoc::database_has_collection.create_instance(); \ auto database_command_with_opts = libmongoc::database_command_with_opts.create_instance(); \ database_command_with_opts \ ->interpose([](mongoc_database_t*, \ const bson_t*, \ const mongoc_read_prefs_t*, \ const bson_t*, \ bson_t*, \ bson_error_t*) { return true; }) \ .forever(); #define MOCK_COLLECTION \ auto collection_set_preference = libmongoc::collection_set_read_prefs.create_instance(); \ collection_set_preference->interpose([](mongoc_collection_t*, const mongoc_read_prefs_t*) {}) \ .forever(); \ auto collection_get_preference = libmongoc::collection_get_read_prefs.create_instance(); \ collection_get_preference->interpose([](const mongoc_collection_t*) { return nullptr; }) \ .forever(); \ auto collection_set_read_concern = libmongoc::collection_set_read_concern.create_instance(); \ auto collection_set_concern = libmongoc::collection_set_write_concern.create_instance(); \ collection_set_concern->interpose([](mongoc_collection_t*, const mongoc_write_concern_t*) {}) \ .forever(); \ auto collection_destroy = libmongoc::collection_destroy.create_instance(); \ collection_destroy->interpose([](mongoc_collection_t*) {}); \ auto collection_drop = libmongoc::collection_drop.create_instance(); \ auto collection_count_documents = libmongoc::collection_count_documents.create_instance(); \ auto collection_estimated_document_count = \ libmongoc::collection_estimated_document_count.create_instance(); \ auto collection_count_with_opts = libmongoc::collection_count_with_opts.create_instance(); \ auto collection_find_with_opts = libmongoc::collection_find_with_opts.create_instance(); \ auto collection_aggregate = libmongoc::collection_aggregate.create_instance(); \ auto collection_get_name = libmongoc::collection_get_name.create_instance(); \ collection_get_name->interpose([](mongoc_collection_t*) { return "dummy_collection"; }); \ auto collection_rename = libmongoc::collection_rename.create_instance(); \ auto collection_find_and_modify_with_opts = \ libmongoc::collection_find_and_modify_with_opts.create_instance(); #define MOCK_CHANGE_STREAM \ auto collection_watch = libmongoc::collection_watch.create_instance(); \ auto database_watch = libmongoc::database_watch.create_instance(); \ auto client_watch = libmongoc::client_watch.create_instance(); \ auto change_stream_destroy = libmongoc::change_stream_destroy.create_instance(); \ auto change_stream_next = libmongoc::change_stream_next.create_instance(); \ auto change_stream_error_document = libmongoc::change_stream_error_document.create_instance(); #define MOCK_FAM \ auto find_and_modify_opts_destroy = libmongoc::find_and_modify_opts_destroy.create_instance(); \ find_and_modify_opts_destroy->interpose([](mongoc_find_and_modify_opts_t*) {}).forever(); \ auto find_and_modify_opts_new = libmongoc::find_and_modify_opts_new.create_instance(); \ find_and_modify_opts_new->interpose([]() { return nullptr; }).forever(); \ bool expected_find_and_modify_opts_bypass_document_validation; \ auto find_and_modify_opts_set_bypass_document_validation = \ libmongoc::find_and_modify_opts_set_bypass_document_validation.create_instance(); \ find_and_modify_opts_set_bypass_document_validation->interpose( \ [&expected_find_and_modify_opts_bypass_document_validation]( \ mongoc_find_and_modify_opts_t*, bool bypass_document_validation) { \ REQUIRE(bypass_document_validation == \ expected_find_and_modify_opts_bypass_document_validation); \ return true; \ }); \ bsoncxx::document::view expected_find_and_modify_opts_fields; \ auto find_and_modify_opts_set_fields = \ libmongoc::find_and_modify_opts_set_fields.create_instance(); \ find_and_modify_opts_set_fields->interpose([&expected_find_and_modify_opts_fields]( \ mongoc_find_and_modify_opts_t*, const ::bson_t* fields) { \ auto fields_view = bsoncxx::helpers::view_from_bson_t(fields); \ REQUIRE(fields_view == expected_find_and_modify_opts_fields); \ return true; \ }); \ ::mongoc_find_and_modify_flags_t expected_find_and_modify_opts_flags; \ auto find_and_modify_opts_set_flags = \ libmongoc::find_and_modify_opts_set_flags.create_instance(); \ find_and_modify_opts_set_flags->interpose([&expected_find_and_modify_opts_flags]( \ mongoc_find_and_modify_opts_t*, const ::mongoc_find_and_modify_flags_t flags) { \ REQUIRE(flags == expected_find_and_modify_opts_flags); \ return true; \ }); \ bsoncxx::document::view expected_find_and_modify_opts_sort; \ auto find_and_modify_opts_set_sort = \ libmongoc::find_and_modify_opts_set_sort.create_instance(); \ find_and_modify_opts_set_sort->interpose([&expected_find_and_modify_opts_sort]( \ mongoc_find_and_modify_opts_t*, const ::bson_t* sort) { \ auto sort_view = bsoncxx::helpers::view_from_bson_t(sort); \ REQUIRE(sort_view == expected_find_and_modify_opts_sort); \ return true; \ }); \ bsoncxx::document::view expected_find_and_modify_opts_update; \ auto find_and_modify_opts_set_update = \ libmongoc::find_and_modify_opts_set_update.create_instance(); \ find_and_modify_opts_set_update->interpose([&expected_find_and_modify_opts_update]( \ mongoc_find_and_modify_opts_t*, const ::bson_t* update) { \ auto update_view = bsoncxx::helpers::view_from_bson_t(update); \ REQUIRE(update_view == expected_find_and_modify_opts_update); \ return true; \ }); #define MOCK_CURSOR \ auto cursor_destroy = libmongoc::cursor_destroy.create_instance(); \ cursor_destroy->interpose([&](mongoc_cursor_t*) {}); #define MOCK_BULK \ auto bulk_operation_insert_with_opts = \ libmongoc::bulk_operation_insert_with_opts.create_instance(); \ auto bulk_operation_remove_one_with_opts = \ libmongoc::bulk_operation_remove_one_with_opts.create_instance(); \ auto bulk_operation_update_one_with_opts = \ libmongoc::bulk_operation_update_one_with_opts.create_instance(); \ auto bulk_operation_replace_one_with_opts = \ libmongoc::bulk_operation_replace_one_with_opts.create_instance(); \ auto bulk_operation_update_many_with_opts = \ libmongoc::bulk_operation_update_many_with_opts.create_instance(); \ auto bulk_operation_remove_many_with_opts = \ libmongoc::bulk_operation_remove_many_with_opts.create_instance(); \ auto bulk_operation_set_bypass_document_validation = \ libmongoc::bulk_operation_set_bypass_document_validation.create_instance(); \ auto bulk_operation_execute = libmongoc::bulk_operation_execute.create_instance(); \ auto bulk_operation_destroy = libmongoc::bulk_operation_destroy.create_instance(); \ auto collection_create_bulk_operation_with_opts = \ libmongoc::collection_create_bulk_operation_with_opts.create_instance(); \ bool bulk_operation_op_called = false; \ bool bulk_operation_set_bypass_document_validation_called = false; \ bool bulk_operation_execute_called = false; \ bool bulk_operation_destroy_called = false; \ bool collection_create_bulk_operation_called = false; #define MOCK_CONCERN \ auto concern_copy = libmongoc::write_concern_copy.create_instance(); \ concern_copy->interpose([](const mongoc_write_concern_t*) { return nullptr; }).forever(); #define MOCK_READ_PREFERENCE \ auto read_prefs_get_max_staleness_seconds = \ libmongoc::read_prefs_get_max_staleness_seconds.create_instance(); \ auto read_prefs_get_mode = libmongoc::read_prefs_get_mode.create_instance(); \ auto read_prefs_get_tags = libmongoc::read_prefs_get_tags.create_instance(); \ auto read_prefs_set_max_staleness_seconds = \ libmongoc::read_prefs_set_max_staleness_seconds.create_instance(); \ auto read_prefs_set_mode = libmongoc::read_prefs_set_mode.create_instance(); \ auto read_prefs_set_tags = libmongoc::read_prefs_set_tags.create_instance(); #include <mongocxx/config/private/postlude.hh>
75.601504
101
0.544704
[ "object" ]
a730e56c3fb75e0a1b7f15a3283969a96e8b0e54
12,417
cc
C++
tests/third_party/poppler/poppler/Hints.cc
albertobarri/idk
a250884f79e2a484251fc750bb915ecbc962be58
[ "MIT" ]
9,724
2015-01-01T02:06:30.000Z
2019-01-17T15:13:51.000Z
tests/third_party/poppler/poppler/Hints.cc
albertobarri/idk
a250884f79e2a484251fc750bb915ecbc962be58
[ "MIT" ]
7,584
2019-01-17T22:58:27.000Z
2022-03-31T23:10:22.000Z
tests/third_party/poppler/poppler/Hints.cc
albertobarri/idk
a250884f79e2a484251fc750bb915ecbc962be58
[ "MIT" ]
1,519
2015-01-01T18:11:12.000Z
2019-01-17T14:16:02.000Z
//======================================================================== // // Hints.cc // // This file is licensed under the GPLv2 or later // // Copyright 2010 Hib Eris <hib@hiberis.nl> // Copyright 2010 Albert Astals Cid <aacid@kde.org> // Copyright 2010 Pino Toscano <pino@kde.org> // //======================================================================== #include <config.h> #include "Hints.h" #include "Linearization.h" #include "Object.h" #include "Stream.h" #include "XRef.h" #include "Parser.h" #include "Lexer.h" #include "SecurityHandler.h" #include <limits.h> //------------------------------------------------------------------------ // Hints //------------------------------------------------------------------------ Hints::Hints(BaseStream *str, Linearization *linearization, XRef *xref, SecurityHandler *secHdlr) { mainXRefEntriesOffset = linearization->getMainXRefEntriesOffset(); nPages = linearization->getNumPages(); pageFirst = linearization->getPageFirst(); pageEndFirst = linearization->getEndFirst(); pageObjectFirst = linearization->getObjectNumberFirst(); if (pageObjectFirst < 0 || pageObjectFirst >= xref->getNumObjects()) { error(-1, "Invalid reference for first page object (%d) in linearization table ", pageObjectFirst); pageObjectFirst = 0; } pageOffsetFirst = xref->getEntry(pageObjectFirst)->offset; if (nPages >= INT_MAX / (int)sizeof(Guint)) { error(-1, "Invalid number of pages (%d) for hints table", nPages); nPages = 0; } nObjects = (Guint *) gmallocn_checkoverflow(nPages, sizeof(Guint)); pageObjectNum = (int *) gmallocn_checkoverflow(nPages, sizeof(int)); xRefOffset = (Guint *) gmallocn_checkoverflow(nPages, sizeof(Guint)); pageLength = (Guint *) gmallocn_checkoverflow(nPages, sizeof(Guint)); pageOffset = (Guint *) gmallocn_checkoverflow(nPages, sizeof(Guint)); numSharedObject = (Guint *) gmallocn_checkoverflow(nPages, sizeof(Guint)); sharedObjectId = (Guint **) gmallocn_checkoverflow(nPages, sizeof(Guint*)); if (!nObjects || !pageObjectNum || !xRefOffset || !pageLength || !pageOffset || !numSharedObject || !sharedObjectId) { error(-1, "Failed to allocate memory for hints tabel"); nPages = 0; } memset(numSharedObject, 0, nPages * sizeof(Guint)); nSharedGroups = 0; groupLength = NULL; groupOffset = NULL; groupHasSignature = NULL; groupNumObjects = NULL; groupXRefOffset = NULL; readTables(str, linearization, xref, secHdlr); } Hints::~Hints() { gfree(nObjects); gfree(pageObjectNum); gfree(xRefOffset); gfree(pageLength); gfree(pageOffset); for (int i=0; i< nPages; i++) { if (numSharedObject[i]) { gfree(sharedObjectId[i]); } } gfree(sharedObjectId); gfree(numSharedObject); gfree(groupLength); gfree(groupOffset); gfree(groupHasSignature); gfree(groupNumObjects); gfree(groupXRefOffset); } void Hints::readTables(BaseStream *str, Linearization *linearization, XRef *xref, SecurityHandler *secHdlr) { hintsOffset = linearization->getHintsOffset(); hintsLength = linearization->getHintsLength(); hintsOffset2 = linearization->getHintsOffset2(); hintsLength2 = linearization->getHintsLength2(); Parser *parser; Object obj; int bufLength = hintsLength + hintsLength2; std::vector<char> buf(bufLength); char *p = &buf[0]; obj.initNull(); Stream *s = str->makeSubStream(hintsOffset, gFalse, hintsLength, &obj); s->reset(); for (Guint i=0; i < hintsLength; i++) { *p++ = s->getChar(); } delete s; if (hintsOffset2 && hintsLength2) { obj.initNull(); s = str->makeSubStream(hintsOffset2, gFalse, hintsLength2, &obj); s->reset(); for (Guint i=0; i < hintsLength2; i++) { *p++ = s->getChar(); } delete s; } obj.initNull(); MemStream *memStream = new MemStream (&buf[0], 0, bufLength, &obj); obj.initNull(); parser = new Parser(xref, new Lexer(xref, memStream), gTrue); int num, gen; if (parser->getObj(&obj)->isInt() && (num = obj.getInt(), obj.free(), parser->getObj(&obj)->isInt()) && (gen = obj.getInt(), obj.free(), parser->getObj(&obj)->isCmd("obj")) && (obj.free(), parser->getObj(&obj, secHdlr ? secHdlr->getFileKey() : (Guchar *)NULL, secHdlr ? secHdlr->getEncAlgorithm() : cryptRC4, secHdlr ? secHdlr->getFileKeyLength() : 0, num, gen)->isStream())) { Stream *hintsStream = obj.getStream(); Dict *hintsDict = obj.streamGetDict(); int sharedStreamOffset = 0; if (hintsDict->lookupInt("S", NULL, &sharedStreamOffset) && sharedStreamOffset > 0) { hintsStream->reset(); readPageOffsetTable(hintsStream); hintsStream->reset(); for (int i=0; i<sharedStreamOffset; i++) hintsStream->getChar(); readSharedObjectsTable(hintsStream); } else { error(-1, "Invalid shared object hint table offset"); } } else { error(-1, "Failed parsing hints table object"); } obj.free(); delete parser; } void Hints::readPageOffsetTable(Stream *str) { if (nPages < 1) { error(-1, "Invalid number of pages reading page offset hints table"); return; } inputBits = 0; // reset on byte boundary. nObjectLeast = readBits(32, str); objectOffsetFirst = readBits(32, str); if (objectOffsetFirst >= hintsOffset) objectOffsetFirst += hintsLength; nBitsDiffObjects = readBits(16, str); pageLengthLeast = readBits(32, str); nBitsDiffPageLength = readBits(16, str); OffsetStreamLeast = readBits(32, str); nBitsOffsetStream = readBits(16, str); lengthStreamLeast = readBits(32, str); nBitsLengthStream = readBits(16, str); nBitsNumShared = readBits(16, str); nBitsShared = readBits(16, str); nBitsNumerator = readBits(16, str); denominator = readBits(16, str); for (int i=0; i<nPages; i++) { nObjects[i] = nObjectLeast + readBits(nBitsDiffObjects, str); } nObjects[0] = 0; xRefOffset[0] = mainXRefEntriesOffset + 20; for (int i=1; i<nPages; i++) { xRefOffset[i] = xRefOffset[i-1] + 20*nObjects[i-1]; } pageObjectNum[0] = 1; for (int i=1; i<nPages; i++) { pageObjectNum[i] = pageObjectNum[i-1] + nObjects[i-1]; } pageObjectNum[0] = pageObjectFirst; inputBits = 0; // reset on byte boundary. Not in specs! for (int i=0; i<nPages; i++) { pageLength[i] = pageLengthLeast + readBits(nBitsDiffPageLength, str); } inputBits = 0; // reset on byte boundary. Not in specs! numSharedObject[0] = readBits(nBitsNumShared, str); numSharedObject[0] = 0; // Do not trust the read value to be 0. sharedObjectId[0] = NULL; for (int i=1; i<nPages; i++) { numSharedObject[i] = readBits(nBitsNumShared, str); if (numSharedObject[i] >= INT_MAX / (int)sizeof(Guint)) { error(-1, "Invalid number of shared objects"); numSharedObject[i] = 0; return; } sharedObjectId[i] = (Guint *) gmallocn_checkoverflow(numSharedObject[i], sizeof(Guint)); if (numSharedObject[i] && !sharedObjectId[i]) { error(-1, "Failed to allocate memory for shared object IDs"); numSharedObject[i] = 0; return; } } inputBits = 0; // reset on byte boundary. Not in specs! for (int i=1; i<nPages; i++) { for (Guint j=0; j < numSharedObject[i]; j++) { sharedObjectId[i][j] = readBits(nBitsShared, str); } } pageOffset[0] = pageOffsetFirst; // find pageOffsets. for (int i=1; i<nPages; i++) { pageOffset[i] = pageOffset[i-1] + pageLength[i-1]; } } void Hints::readSharedObjectsTable(Stream *str) { inputBits = 0; // reset on byte boundary. Guint firstSharedObjectNumber = readBits(32, str); Guint firstSharedObjectOffset = readBits(32, str); firstSharedObjectOffset += hintsLength; Guint nSharedGroupsFirst = readBits(32, str); Guint nSharedGroups = readBits(32, str); Guint nBitsNumObjects = readBits(16, str); Guint groupLengthLeast = readBits(32, str); Guint nBitsDiffGroupLength = readBits(16, str); if ((!nSharedGroups) || (nSharedGroups >= INT_MAX / (int)sizeof(Guint))) { error(-1, "Invalid number of shared object groups"); nSharedGroups = 0; return; } if ((!nSharedGroupsFirst) || (nSharedGroupsFirst > nSharedGroups)) { error(-1, "Invalid number of first page shared object groups"); nSharedGroupsFirst = nSharedGroups; } groupLength = (Guint *) gmallocn_checkoverflow(nSharedGroups, sizeof(Guint)); groupOffset = (Guint *) gmallocn_checkoverflow(nSharedGroups, sizeof(Guint)); groupHasSignature = (Guint *) gmallocn_checkoverflow(nSharedGroups, sizeof(Guint)); groupNumObjects = (Guint *) gmallocn_checkoverflow(nSharedGroups, sizeof(Guint)); groupXRefOffset = (Guint *) gmallocn_checkoverflow(nSharedGroups, sizeof(Guint)); if (!groupLength || !groupOffset || !groupHasSignature || !groupNumObjects || !groupXRefOffset) { error(-1, "Failed to allocate memory for shared object groups"); nSharedGroups = 0; return; } inputBits = 0; // reset on byte boundary. Not in specs! for (Guint i=0; i<nSharedGroups; i++) { groupLength[i] = groupLengthLeast + readBits(nBitsDiffGroupLength, str); } groupOffset[0] = objectOffsetFirst; for (Guint i=1; i<nSharedGroupsFirst; i++) { groupOffset[i] = groupOffset[i-1] + groupLength[i-1]; } if (nSharedGroups > nSharedGroupsFirst ) { groupOffset[nSharedGroupsFirst] = firstSharedObjectOffset; for (Guint i=nSharedGroupsFirst+1; i<nSharedGroups; i++) { groupOffset[i] = groupOffset[i-1] + groupLength[i-1]; } } inputBits = 0; // reset on byte boundary. Not in specs! for (Guint i=0; i<nSharedGroups; i++) { groupHasSignature[i] = readBits(1, str); } inputBits = 0; // reset on byte boundary. Not in specs! for (Guint i=0; i<nSharedGroups; i++) { if (groupHasSignature[i]) { readBits(128, str); } } inputBits = 0; // reset on byte boundary. Not in specs! for (Guint i=0; i<nSharedGroups; i++) { groupNumObjects[i] = nBitsNumObjects ? 1 + readBits(nBitsNumObjects, str) : 1; } for (Guint i=0; i<nSharedGroupsFirst; i++) { groupNumObjects[i] = 0; groupXRefOffset[i] = 0; } if (nSharedGroups > nSharedGroupsFirst ) { groupXRefOffset[nSharedGroupsFirst] = mainXRefEntriesOffset + 20*firstSharedObjectNumber; for (Guint i=nSharedGroupsFirst+1; i<nSharedGroups; i++) { groupXRefOffset[i] = groupXRefOffset[i-1] + 20*groupNumObjects[i-1]; } } } Guint Hints::getPageOffset(int page) { if ((page < 1) || (page > nPages)) return 0; if (page-1 > pageFirst) return pageOffset[page-1]; else if (page-1 < pageFirst) return pageOffset[page]; else return pageOffset[0]; } std::vector<ByteRange>* Hints::getPageRanges(int page) { if ((page < 1) || (page > nPages)) return NULL; int idx; if (page-1 > pageFirst) idx = page-1; else if (page-1 < pageFirst) idx = page; else idx = 0; ByteRange pageRange; std::vector<ByteRange> *v = new std::vector<ByteRange>; pageRange.offset = pageOffset[idx]; pageRange.length = pageLength[idx]; v->push_back(pageRange); pageRange.offset = xRefOffset[idx]; pageRange.length = 20*nObjects[idx]; v->push_back(pageRange); for (Guint j=0; j<numSharedObject[idx]; j++) { Guint k = sharedObjectId[idx][j]; pageRange.offset = groupOffset[k]; pageRange.length = groupLength[k]; v->push_back(pageRange); pageRange.offset = groupXRefOffset[k]; pageRange.length = 20*groupNumObjects[k]; v->push_back(pageRange); } return v; } Guint Hints::readBit(Stream *str) { Guint bit; int c; if (inputBits == 0) { if ((c = str->getChar()) == EOF) { return (Guint) -1; } bitsBuffer = c; inputBits = 8; } bit = (bitsBuffer >> (inputBits - 1)) & 1; --inputBits; return bit; } Guint Hints::readBits(int n, Stream *str) { Guint bit, bits; if (n < 0) return -1; if (n == 0) return 0; if (n == 1) return readBit(str); bit = (readBit(str) << (n-1)); if (bit == (Guint) -1) return -1; bits = readBits(n-1, str); if (bits == (Guint) -1) return -1; return bit | bits; } int Hints::getPageObjectNum(int page) { if ((page < 1) || (page > nPages)) return 0; if (page-1 > pageFirst) return pageObjectNum[page-1]; else if (page-1 < pageFirst) return pageObjectNum[page]; else return pageObjectNum[0]; }
28.09276
107
0.642345
[ "object", "vector" ]
a73579707f3fcc636d1a46029d5c15821b75c240
299
cpp
C++
Source/Engine/Graphics/Drawing/Scene.cpp
MintaiDS/White
4776792d45042adbe3dbc647a4d71c80ee3b9387
[ "MIT" ]
null
null
null
Source/Engine/Graphics/Drawing/Scene.cpp
MintaiDS/White
4776792d45042adbe3dbc647a4d71c80ee3b9387
[ "MIT" ]
null
null
null
Source/Engine/Graphics/Drawing/Scene.cpp
MintaiDS/White
4776792d45042adbe3dbc647a4d71c80ee3b9387
[ "MIT" ]
null
null
null
#include "Scene.h" namespace White { namespace Engine { Scene::Scene() {} void Scene::AddObject(unsigned object) { ip.Add(object, objects.size()); objects.push_back(object); } void Scene::RemoveObject(unsigned object) { unsigned index = ip.Get(object); ip.Remove(object); } } }
14.95
43
0.672241
[ "object" ]
a738c58675da29ffda5be5a6d8215dcf643c89f7
3,455
cpp
C++
SDL_DirectX_Setup/Camera.cpp
josephwhittington/ImGui_Dx11_SDL_Setup
74bfbff2ca911f994bb24ea33698482548fa6669
[ "MIT" ]
null
null
null
SDL_DirectX_Setup/Camera.cpp
josephwhittington/ImGui_Dx11_SDL_Setup
74bfbff2ca911f994bb24ea33698482548fa6669
[ "MIT" ]
null
null
null
SDL_DirectX_Setup/Camera.cpp
josephwhittington/ImGui_Dx11_SDL_Setup
74bfbff2ca911f994bb24ea33698482548fa6669
[ "MIT" ]
1
2020-05-12T05:32:52.000Z
2020-05-12T05:32:52.000Z
#include "Camera.h" void Camera::GetViewMatrix(XMMATRIX& viewMatrix) { XMVECTOR position, targetPosition, up; position = XMLoadFloat3(&m_position); targetPosition = XMLoadFloat3(&m_targetPosition); up = XMLoadFloat3(&m_up); viewMatrix = XMMatrixLookAtLH(position, targetPosition, up); } DirectX::XMFLOAT3& Camera::GetRight() { return m_right; } DirectX::XMFLOAT3& Camera::GetLook() { return m_look; } DirectX::XMFLOAT3& Camera::GetUp() { return m_up; } DirectX::XMFLOAT3& Camera::GetPosition() { return m_position; } float Camera::GetFOV() { return m_fov; } float Camera::GetFOVDegrees() { return XMConvertToDegrees(m_fov); } float Camera::GetNear() { return m_near; } float Camera::GetFar() { return m_far; } //************************************ // Method: SetFOV // FullName: Camera::SetFOV // Access: public // Returns: void // Qualifier: // Parameter: float fov - in degrees (function converts to radians) //************************************ void Camera::SetFOV(float fov) { m_fov = XMConvertToRadians(fov); } void Camera::SetClippingPlanes(float _near, float _far) { m_near = _near; m_far = _far; } Camera::Camera() { m_position = XMFLOAT3(0, 0, 0); m_targetPosition = XMFLOAT3(0, 0, 0); m_up = XMFLOAT3(0, 1, 0); m_right = XMFLOAT3(0, 0, 0); m_worldUp = XMFLOAT3(0, 1, 0); m_yaw = WMATH_PI; m_fov = WMATH_PI / 4; // default fov m_near = .01; m_far = 1000; } //************************************ // FPS CAMERA //************************************ FPSCamera::FPSCamera(XMFLOAT3 position /*= XMFLOAT3(0, 0, 0)*/, float yaw /*= PI*/, float pitch /*= 0*/) { m_position = position; m_yaw = yaw; m_pitch = pitch; } void FPSCamera::SetPosition(XMFLOAT3 position) { m_position = position; UpdateCameraVectors(); } void FPSCamera::Rotate(float yaw, float pitch) { // Convert the yaw and pitch to radians m_yaw += XMConvertToRadians(yaw); m_pitch += XMConvertToRadians(pitch); // Clamp the pitch between -180 and 180 exclusive if (m_pitch < (-WMATH_PI / 2) + .1) m_pitch = (-WMATH_PI / 2) + .1; else if (m_pitch > (WMATH_PI / 2) - .1) m_pitch = (WMATH_PI / 2) - .1; // Update the other shit UpdateCameraVectors(); } void FPSCamera::Move(XMFLOAT3 position) { XMVECTOR posOld, posNew, result; posOld = XMLoadFloat3(&m_position); posNew = XMLoadFloat3(&position); result = XMVectorAdd(posNew, posOld); XMStoreFloat3(&m_position, result); // Update the other shit UpdateCameraVectors(); } void FPSCamera::UpdateCameraVectors() { XMFLOAT3 look; look.x = cosf(m_pitch) * sinf(m_yaw); look.y = sinf(m_pitch); look.z = -(cosf(m_pitch) * cosf(m_yaw)); XMVECTOR lookvector, worldupvector, rightvector, positionvector, upvector, targetpositionvector; lookvector = XMLoadFloat3(&look); worldupvector = XMLoadFloat3(&m_worldUp); rightvector = XMLoadFloat3(&m_right); positionvector = XMLoadFloat3(&m_position); // Normalize the look vector & store it XMVector3Normalize(lookvector); XMStoreFloat3(&m_look, lookvector); // Recompute the right and up vectors rightvector = XMVector3Normalize(XMVector3Cross(lookvector, worldupvector)); upvector = XMVector3Normalize(XMVector3Cross(rightvector, lookvector)); // Store right & up vector XMStoreFloat3(&m_right, rightvector); XMStoreFloat3(&m_up, upvector); targetpositionvector = positionvector + lookvector; // Store the new target position XMStoreFloat3(&m_targetPosition, targetpositionvector); }
21.459627
104
0.68191
[ "vector" ]
a742df393e35bad3a80707304c2717682144aad2
4,539
hpp
C++
include/LuminoEngine/Base/Task.hpp
infinnie/Lumino
921caabdbcb91528a2aac290e31d650628bc3bed
[ "MIT" ]
null
null
null
include/LuminoEngine/Base/Task.hpp
infinnie/Lumino
921caabdbcb91528a2aac290e31d650628bc3bed
[ "MIT" ]
null
null
null
include/LuminoEngine/Base/Task.hpp
infinnie/Lumino
921caabdbcb91528a2aac290e31d650628bc3bed
[ "MIT" ]
null
null
null
 #pragma once #include <functional> namespace ln { class TaskScheduler; class Dispatcher; enum class TaskStatus { Created, /**< Task オブジェクトは生成されているが、スケジューラに追加されていない。*/ Waiting, /**< スケジューラに追加され、実行されるのを待機中。*/ Running, /**< 実行中。*/ Completed, /**< 処理は正常に完了した。*/ Faulted, /**< 実行中にハンドルされない例外が発生して終了した。*/ }; // TODO: deprecated class Task : public RefObject { public: //static Promise invoke(const std::function<void()>& action); //// ↓以下、いろいろあるけど UI では↑をメインに使う。 static Ref<Task> create(const std::function<void()>& action); static Ref<Task> run(const std::function<void()>& action); void start(); void wait(); // 正常終了した場合の後続の処理を追加する。 // Task* then(const std::function<void()>& action, Dispatcher* dispatcher = nullptr); //Task* rejected(const std::function<void()>& action, Dispatcher* dispatcher = nullptr); //Task* awaitThen(const std::function<void()>& action, Dispatcher* dispatcher = nullptr); /** この Task の現在の状態を取得します。*/ TaskStatus status() const; /** この Task が正常に完了したかどうかを確認します。*/ bool isCompleted() const; /** 実行中にハンドルされない例外が発生したことが原因で Task が終了したかを確認します。*/ bool isFaulted() const; /** 実行中に発生しハンドルされなかった例外を返します。例外が発生していなければ nullptr です。*/ Exception* exception() const; void then(const std::function<void()>& action) { if (LN_REQUIRE(!this->m_prevTask)) return; auto continuationsTask = Task::create(action); continuationsTask->m_prevTask = this; continuationsTask->start(); } protected: Task(const std::function<void()>& action); ~Task(); void execute(); //struct NextTask //{ // Ref<Task> task; // TaskScheduler* scheduler; // Dispatcher* dispatcher; //}; std::function<void()> m_action; std::atomic<TaskStatus> m_status; //std::vector<NextTask> m_nextTasks; Exception* m_exception; ConditionEvent m_waiting; Ref<Task> m_prevTask = nullptr; friend class TaskScheduler; friend class Dispatcher; }; template<class TResult> class GenericTask : public Task { public: static Ref<GenericTask<TResult>> create(const std::function<TResult()>& action); TResult result() { wait(); return m_result; } private: GenericTask(const std::function<TResult()>& action); //std::function<TResult()> m_action; TResult m_result; }; template<class TResult> Ref<GenericTask<TResult>> GenericTask<TResult>::create(const std::function<TResult()>& action) { return Ref<GenericTask<TResult>>(LN_NEW GenericTask<TResult>(action), false); } template<class TResult> GenericTask<TResult>::GenericTask(const std::function<TResult()>& action) : Task([this, action]() { m_result = action(); }), m_result{} { } namespace detail { class semaphore { private: std::mutex mutex_; std::condition_variable condition_; unsigned long count_ = 0; // Initialized as locked. public: void notify() { std::lock_guard<decltype(mutex_)> lock(mutex_); ++count_; condition_.notify_one(); } void wait() { std::unique_lock<decltype(mutex_)> lock(mutex_); while (!count_) // Handle spurious wake-ups. condition_.wait(lock); --count_; } bool try_wait() { std::lock_guard<decltype(mutex_)> lock(mutex_); if (count_) { --count_; return true; } return false; } }; } // namespace detail class Dispatcher : public RefObject { public: //static Dispatcher* mainThread(); void post(Task* task); void post(const std::function<void()>& action); // これを、Task を実行したいスレッドで呼び出す。 void executeTasks(uint32_t maxCount = UINT32_MAX); void dispose(); private: std::deque<Ref<Task>> m_taskQueue; std::mutex m_taskQueueMutex; }; class TaskScheduler : public RefObject { public: static void init(); static void finalizeInternal(); static TaskScheduler* get(); // この TaskScheduler が同時に並列実行できる Task の数を取得します。 int maxConcurrencyLevel() const; private: TaskScheduler(int threadCount); ~TaskScheduler(); void dispose(); void queueTask(Task* task); void executeThread(); List<std::shared_ptr<std::thread>> m_threadList; List<Ref<Task>> m_taskQueue; //std::deque<Ref<Task>> m_taskQueue; detail::semaphore m_semaphore; std::mutex m_taskQueueMutex; std::atomic<bool> m_endRequested; static TaskScheduler* s_instance; friend class Task; }; } // namespace ln
20.821101
94
0.649042
[ "vector" ]
a7438548558f10f95fceb4f54b1bb543a71e794b
160,997
cpp
C++
Source/SGame/iTween/iTween.cpp
ZDron3/SimpleGame-Match-
427040e3dce0e76c710e0baab021f9a9ae2a8530
[ "MIT" ]
null
null
null
Source/SGame/iTween/iTween.cpp
ZDron3/SimpleGame-Match-
427040e3dce0e76c710e0baab021f9a9ae2a8530
[ "MIT" ]
null
null
null
Source/SGame/iTween/iTween.cpp
ZDron3/SimpleGame-Match-
427040e3dce0e76c710e0baab021f9a9ae2a8530
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "SGame.h" #include "iTweenPCH.h" #include "iTweenEvent.h" #include "iTween.h" UWorld* UiTween::GetWorldLocal() { for (TObjectIterator<UGameViewportClient> Itr; Itr; ++Itr) { return Itr->GetWorld(); } return nullptr; } AiTweenEvent* UiTween::SpawnEvent(AiTAux* aux) { UWorld* world = GetWorldLocal(); if (world) { if (aux) { FActorSpawnParameters params; params.Owner = aux; AiTweenEvent* ie = nullptr; params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn; ie = world->SpawnActor<AiTweenEvent>(AiTweenEvent::StaticClass(), FTransform::Identity, params); return ie; } else { if (GEngine) { GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, "No iTAux defined"); } return nullptr; } } else { if (aux) { Print("No world defined", "error"); } else { if (GEngine) { GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, "No iTAux defined"); } } return nullptr; } } AiTAux* UiTween::GetAux() { AiTAux* aux = nullptr; for (TObjectIterator<AiTAux> Itr; Itr; ++Itr) { if (Itr->IsA(AiTAux::StaticClass())) { return *Itr; } } FActorSpawnParameters params; params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn; aux = (AiTAux*)(GetWorldLocal()->SpawnActor<AiTAux>(AiTAux::StaticClass(), params)); return aux; } UObject* UiTween::FindObjectByName(FString s) { FName n = FName(*s); for (TObjectIterator<UObject> Itr; Itr; ++Itr) { FName f = Itr->GetFName(); if (f == n) { Print("UObject found!"); return *Itr; } else { continue; } } Print("No UObject with the specified name was found.", "error"); return nullptr; } void UiTween::Print(FString message, FString type, float time, bool printToLog) { AiTAux* aux = GetAux(); if (aux && aux->printDebugMessages && type == "debug") { if (GEngine) { GEngine->AddOnScreenDebugMessage(-1, time, FColor::Cyan, message); } if (printToLog) { UE_LOG(LogTemp, All, TEXT("%s"), *message); } } if (aux && aux->printErrorMessages && type == "error") { if (GEngine) { GEngine->AddOnScreenDebugMessage(-1, time, FColor::Red, message); } if (printToLog) { UE_LOG(LogTemp, All, TEXT("%s"), *message); } } } //Constraints FVector UiTween::ConstrainVector(FVector inputVector, FVector currentVector, EVectorConstraints::VectorConstraints vectorConstraints) { switch (vectorConstraints) { case EVectorConstraints::VectorConstraints::none: return inputVector; case EVectorConstraints::VectorConstraints::xOnly: return FVector(inputVector.X, currentVector.Y, currentVector.Z); case EVectorConstraints::VectorConstraints::yOnly: return FVector(currentVector.X, inputVector.Y, currentVector.Z); case EVectorConstraints::VectorConstraints::zOnly: return FVector(currentVector.X, currentVector.Y, inputVector.Z); case EVectorConstraints::VectorConstraints::xyOnly: return FVector(inputVector.X, inputVector.Y, currentVector.Z); case EVectorConstraints::VectorConstraints::yzOnly: return FVector(currentVector.X, inputVector.Y, inputVector.Z); case EVectorConstraints::VectorConstraints::xzOnly: return FVector(inputVector.X, currentVector.Y, inputVector.Z); default: return inputVector; } } FVector2D UiTween::ConstrainVector2D(FVector2D inputVector2D, FVector2D currentVector2D, EVector2DConstraints::Vector2DConstraints vector2DConstraints) { switch (vector2DConstraints) { case EVector2DConstraints::Vector2DConstraints::none: return inputVector2D; case EVector2DConstraints::Vector2DConstraints::xOnly: return FVector2D(inputVector2D.X, currentVector2D.Y); case EVector2DConstraints::Vector2DConstraints::yOnly: return FVector2D(currentVector2D.X, inputVector2D.Y); default: return inputVector2D; } } FRotator UiTween::ConstrainRotator(FRotator inputRotator, FRotator currentRotator, ERotatorConstraints::RotatorConstraints rotatorConstraints) { switch (rotatorConstraints) { case ERotatorConstraints::RotatorConstraints::none: return inputRotator; case ERotatorConstraints::RotatorConstraints::pitchOnly: return FRotator(inputRotator.Pitch, currentRotator.Yaw, currentRotator.Roll); case ERotatorConstraints::RotatorConstraints::yawOnly: return FRotator(currentRotator.Pitch, inputRotator.Yaw, currentRotator.Roll); case ERotatorConstraints::RotatorConstraints::rollOnly: return FRotator(currentRotator.Pitch, currentRotator.Yaw, inputRotator.Roll); case ERotatorConstraints::RotatorConstraints::pitchYawOnly: return FRotator(inputRotator.Pitch, inputRotator.Yaw, currentRotator.Roll); case ERotatorConstraints::RotatorConstraints::yawRollOnly: return FRotator(currentRotator.Pitch, inputRotator.Yaw, inputRotator.Roll); case ERotatorConstraints::RotatorConstraints::pitchRollOnly: return FRotator(inputRotator.Pitch, currentRotator.Yaw, inputRotator.Roll); default: return inputRotator; } } //General Use void UiTween::GenerateSplineFromVectorArray(AiTSpline* &owningActor, USplineComponent* &splineComponent, FVector referenceVector, FRotator referenceRotator, TArray<FVector> vectorArray, bool localToReference, bool closeSpline) { UWorld* world = GetWorldLocal(); AiTSpline* a = nullptr; FActorSpawnParameters params; params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn; a = world->SpawnActor<AiTSpline>(AiTSpline::StaticClass(), params); a->SetActorLocation(referenceVector); owningActor = a; splineComponent = a->spline; splineComponent->ClearSplinePoints(); for (int i = 0; i < vectorArray.Num(); i++) { if (localToReference) { splineComponent->AddSplineWorldPoint(referenceRotator.RotateVector(vectorArray[i]) + referenceVector); } else { splineComponent->AddSplineWorldPoint(vectorArray[i]); } } splineComponent->SetClosedLoop(closeSpline); } void UiTween::GenerateSplineFromRotatorArray(AiTSpline* &owningActor, USplineComponent* &splineComponent, FVector referenceVector, FRotator referenceRotator, TArray<FRotator> rotatorArray, float generatedPointDistance, bool localToReference, bool closeSpline) { UWorld* world = GetWorldLocal(); AiTSpline* a = nullptr; FActorSpawnParameters params; params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn; a = world->SpawnActor<AiTSpline>(AiTSpline::StaticClass(), params); a->SetActorLocation(referenceVector); owningActor = a; splineComponent = a->spline; splineComponent->ClearSplinePoints(); for (int i = 0; i < rotatorArray.Num(); i++) { if (localToReference) { splineComponent->AddSplineWorldPoint(FRotator(FQuat(referenceRotator) * FQuat(rotatorArray[i])).RotateVector(FVector::ForwardVector) * generatedPointDistance + referenceVector); } else { splineComponent->AddSplineWorldPoint(rotatorArray[i].RotateVector(FVector::ForwardVector) * generatedPointDistance + referenceVector); } } splineComponent->SetClosedLoop(closeSpline); } float UiTween::GetDistanceBetweenTwoVectors(FVector sourceVector, FVector destination) { return FMath::Sqrt(FMath::Pow((destination.X - sourceVector.X), 2) + FMath::Pow((destination.Y - sourceVector.Y), 2) + FMath::Pow((destination.Z - sourceVector.Z), 2)); } //Stopping, Pausing and Resuming Tweens void UiTween::StopTweeningByIndex(int32 index) { GetAux()->currentTweens[index]->EndPhase(); } void UiTween::StopTweeningByTweeningObjectName(FName objectName) { for (AiTweenEvent* e : GetAux()->currentTweens) { if (e->actorTweening != nullptr) { if (e->actorTweening->GetFName() == objectName) { e->EndPhase(); } } else if (e->componentTweening != nullptr) { if (e->componentTweening->GetFName() == objectName) { e->EndPhase(); } } else if (e->widgetTweening != nullptr) { if (e->widgetTweening->GetFName() == objectName) { e->EndPhase(); } } } } void UiTween::StopTweeningByTweenName(FName tweenName) { TArray<FName> arr; for (AiTweenEvent* e : GetAux()->currentTweens) { arr.Add(e->tweenName); } while (arr.Contains(tweenName)) { for (AiTweenEvent* e : GetAux()->currentTweens) { if (e->tweenName == tweenName) { e->EndPhase(); break; } } arr.Empty(); for (AiTweenEvent* e : GetAux()->currentTweens) { arr.Add(e->tweenName); } } } void UiTween::StopTweeningByTweeningObjectReference(UObject* object) { TArray<UObject*> arr; for (AiTweenEvent* e : GetAux()->currentTweens) { if (e->actorTweening != nullptr) { arr.Add(e->actorTweening); } else if (e->componentTweening != nullptr) { arr.Add(e->componentTweening); } else if (e->widgetTweening != nullptr) { arr.Add(e->widgetTweening); } } while (arr.Contains(object)) { for (AiTweenEvent* e : GetAux()->currentTweens) { if (e->actorTweening != nullptr) { if (e->actorTweening == object) { e->EndPhase(); } } else if (e->componentTweening != nullptr) { if (e->componentTweening == object) { e->EndPhase(); } } else if (e->widgetTweening != nullptr) { if (e->widgetTweening == object) { e->EndPhase(); } } break; } arr.Empty(); for (AiTweenEvent* e : GetAux()->currentTweens) { if (e->actorTweening != nullptr) { arr.Add(e->actorTweening); } else if (e->componentTweening != nullptr) { arr.Add(e->componentTweening); } else if (e->widgetTweening != nullptr) { arr.Add(e->widgetTweening); } } } } void UiTween::StopTweeningByEventReference(AiTweenEvent* object) { for (AiTweenEvent* e : GetAux()->currentTweens) { if (e == object) { e->EndPhase(); } } } void UiTween::StopAllTweens() { for (AiTweenEvent* e : GetAux()->currentTweens) { e->EndPhase(); } } void UiTween::PauseTweeningByIndex(int32 index) { AiTweenEvent* e = GetAux()->currentTweens[index]; e->isTweenPaused = true; e->shouldTick = false; } void UiTween::PauseTweeningByTweeningObjectName(FName objectName) { for (AiTweenEvent* e : GetAux()->currentTweens) { if (e->actorTweening != nullptr) { if (e->actorTweening->GetFName() == objectName) { e->isTweenPaused = true; e->shouldTick = false; } } else if (e->componentTweening != nullptr) { if (e->componentTweening->GetFName() == objectName) { e->isTweenPaused = true; e->shouldTick = false; } } else if (e->widgetTweening != nullptr) { if (e->widgetTweening->GetFName() == objectName) { e->isTweenPaused = true; e->shouldTick = false; } } } } void UiTween::PauseTweeningByTweenName(FName tweenName) { for (AiTweenEvent* e : GetAux()->currentTweens) { if (e->tweenName == tweenName) { e->isTweenPaused = true; e->shouldTick = false; } } } void UiTween::PauseTweeningByTweeningObjectReference(UObject* object) { for (AiTweenEvent* e : GetAux()->currentTweens) { if (e->actorTweening != nullptr) { if (e->actorTweening == object) { e->isTweenPaused = true; e->shouldTick = false; } } else if (e->componentTweening != nullptr) { if (e->componentTweening == object) { e->isTweenPaused = true; e->shouldTick = false; } } else if (e->widgetTweening != nullptr) { if (e->widgetTweening == object) { e->isTweenPaused = true; e->shouldTick = false; } } } } void UiTween::PauseTweeningByEventReference(AiTweenEvent* object) { for (AiTweenEvent* e : GetAux()->currentTweens) { if (e == object) { e->isTweenPaused = true; e->shouldTick = false; } } } void UiTween::PauseAllTweens() { for (AiTweenEvent* e : GetAux()->currentTweens) { e->isTweenPaused = true; e->shouldTick = false; } } void UiTween::ResumeTweeningByIndex(int32 index) { AiTweenEvent* e = GetAux()->currentTweens[index]; e->isTweenPaused = false; e->shouldTick = true; } void UiTween::ResumeTweeningByTweeningObjectName(FName objectName) { for (AiTweenEvent* e : GetAux()->currentTweens) { if (e->actorTweening != nullptr) { if (e->actorTweening->GetFName() == objectName) { e->isTweenPaused = false; e->shouldTick = true; } } else if (e->componentTweening != nullptr) { if (e->componentTweening->GetFName() == objectName) { e->isTweenPaused = false; e->shouldTick = true; } } else if (e->widgetTweening != nullptr) { if (e->widgetTweening->GetFName() == objectName) { e->isTweenPaused = false; e->shouldTick = true; } } } } void UiTween::ResumeTweeningByTweenName(FName tweenName) { for (AiTweenEvent* e : GetAux()->currentTweens) { if (e->tweenName == tweenName) { e->isTweenPaused = false; e->shouldTick = true; } } } void UiTween::ResumeTweeningByTweeningObjectReference(UObject* object) { for (AiTweenEvent* e : GetAux()->currentTweens) { if (e->actorTweening != nullptr) { if (e->actorTweening == object) { e->isTweenPaused = false; e->shouldTick = true; } } else if (e->componentTweening != nullptr) { if (e->componentTweening == object) { e->isTweenPaused = false; e->shouldTick = true; } } else if (e->widgetTweening != nullptr) { if (e->widgetTweening == object) { e->isTweenPaused = false; e->shouldTick = true; } } } } void UiTween::ResumeTweeningByEventReference(AiTweenEvent* object) { for (AiTweenEvent* e : GetAux()->currentTweens) { if (e == object) { e->isTweenPaused = false; e->shouldTick = true; } } } void UiTween::ResumeAllTweens() { for (AiTweenEvent* e : GetAux()->currentTweens) { e->isTweenPaused = false; e->shouldTick = true; } } //Get iTweenEvents AiTweenEvent* UiTween::GetEventByIndex(int32 index) { return GetAux()->currentTweens[index]; } TArray<AiTweenEvent*> UiTween::GetEventsByTweeningObjectName(FName objectName) { TArray<AiTweenEvent*> arr; for (AiTweenEvent* e : GetAux()->currentTweens) { if (e->actorTweening != nullptr) { if (e->actorTweening->GetFName() == objectName) { arr.Add(e); } } else if (e->componentTweening != nullptr) { if (e->componentTweening->GetFName() == objectName) { arr.Add(e); } } else if (e->widgetTweening != nullptr) { if (e->widgetTweening->GetFName() == objectName) { arr.Add(e); } } } return arr; } TArray<AiTweenEvent*> UiTween::GetEventsByTweenName(FName tweenName) { TArray<AiTweenEvent*> arr; for (AiTweenEvent* e : GetAux()->currentTweens) { if (e->tweenName == tweenName) { arr.Add(e); } } return arr; } TArray<AiTweenEvent*> UiTween::GetEventsByTweeningObjectReference(UObject* object) { TArray<AiTweenEvent*> arr; for (AiTweenEvent* e : GetAux()->currentTweens) { if (e->actorTweening != nullptr) { if (e->actorTweening == object) { arr.Add(e); } } else if (e->componentTweening != nullptr) { if (e->componentTweening == object) { arr.Add(e); } } else if (e->widgetTweening != nullptr) { if (e->widgetTweening == object) { arr.Add(e); } } } return arr; } //FRotator UiTween::GetActorRotationByParent(AActor* actor) //{ // return FRotator::ZeroRotator; //} //Actor //Actor Move From/To AiTweenEvent* UiTween::ActorMoveFromToFull(float timerInterval /*= 0.f*/, FName tweenName /*= "No Name"*/, AActor* actorToMove /*= nullptr*/, FVector locationFrom /*= FVector::ZeroVector*/, FVector locationTo /*= FVector::ZeroVector*/, bool enforceValueTo /*= true*/, EVectorConstraints::VectorConstraints vectorConstraints /*= VectorConstraints::none*/, ECoordinateSpace::CoordinateSpace coordinateSpace /*= CoordinateSpace::world*/, bool sweep /*= false*/, float delay /*= 0.0f*/, EDelayType::DelayType delayType /*= first*/, ETickType::TickType tickType /*= seconds*/, float tickTypeValue /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, UCurveFloat* customEaseTypeCurve /*= nullptr*/, float punchAmplitude /*= 1.0f*/, ELoopType::LoopType loopType /*= once*/, int32 maximumLoopSections /*= 0*/, ELookType::LookType orientation /*= noOrientationChange*/, UObject* orientationTarget /*= nullptr*/, float orientationSpeed /*= 5.0f*/, ERotatorConstraints::RotatorConstraints rotatorConstraints /*= RotatorConstraints::none*/, UObject* onTweenStartTarget /*= nullptr*/, FString OnTweenStartFunctionName /*= ""*/, UObject* onTweenUpdateTarget /*= nullptr*/, FString OnTweenUpdateFunctionName /*= ""*/, UObject* onTweenLoopTarget /*= nullptr*/, FString OnTweenLoopFunctionName /*= ""*/, UObject* onTweenCompleteTarget /*= nullptr*/, FString OnTweenCompleteFunctionName /*= ""*/, bool tickWhenPaused /*= false*/, bool ignoreTimeDilation /*= false*/, bool tieToObjectValidity /*= true*/, bool cullNonRenderedTweens /*= false*/, float secondsToWaitBeforeCull /*= 3.f*/) { //Make sure we have a valid object to tween before proceeding if (actorToMove) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::actorMoveFromTo; ie->timerInterval = timerInterval; ie->tweenName = tweenName; ie->actorTweening = actorToMove; ie->vectorFrom = locationFrom; ie->vectorTo = locationTo; ie->enforceValueTo = enforceValueTo; ie->vectorConstraints = vectorConstraints; ie->coordinateSpace = coordinateSpace; ie->sweep = sweep; ie->delay = delay; ie->delayType = delayType; ie->tickType = tickType; ie->tickTypeValue = tickTypeValue; ie->easeType = easeType; ie->customEaseTypeCurve = customEaseTypeCurve; ie->punchAmplitude = punchAmplitude; ie->loopType = loopType; ie->maximumLoopSections = maximumLoopSections; ie->orientation = orientation; ie->orientationTarget = orientationTarget; ie->orientationSpeed = orientationSpeed; ie->rotatorConstraints = rotatorConstraints; ie->onTweenStartTarget = onTweenStartTarget; ie->OnTweenStartFunctionName = OnTweenStartFunctionName; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->OnTweenUpdateFunctionName = OnTweenUpdateFunctionName; ie->onTweenLoopTarget = onTweenLoopTarget; ie->OnTweenLoopFunctionName = OnTweenLoopFunctionName; ie->onTweenCompleteTarget = onTweenCompleteTarget; ie->OnTweenCompleteFunctionName = OnTweenCompleteFunctionName; ie->tickWhenPaused = tickWhenPaused; ie->ignoreTimeDilation = ignoreTimeDilation; ie->tieToObjectValidity = tieToObjectValidity; ie->cullNonRenderedTweens = cullNonRenderedTweens; ie->secondsToWaitBeforeCull = secondsToWaitBeforeCull; //Initialize Event ie->InitEvent(); return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::ActorMoveFromToSimple(FName tweenName /*= "No Name"*/, AActor* actorToMove /*= nullptr*/, FVector locationFrom /*= FVector::ZeroVector*/, FVector locationTo /*= FVector::ZeroVector*/, ECoordinateSpace::CoordinateSpace coordinateSpace, bool sweep, float timeInSeconds /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, FString parameters, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget /*= nullptr*/) { //Make sure we have a valid object to tween before proceeding if (actorToMove) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::actorMoveFromTo; ie->tweenName = tweenName; ie->actorTweening = actorToMove; ie->vectorFrom = locationFrom; ie->vectorTo = locationTo; ie->coordinateSpace = coordinateSpace; ie->sweep = sweep; ie->tickTypeValue = timeInSeconds; ie->easeType = easeType; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event ie->InitEvent(); return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::ActorMoveFromToExpert(AActor* actorToMove, FString parameters, bool initializeOnSpawn, UCurveFloat* customEaseTypeCurve, UObject* orientationTarget, UObject* onTweenStartTarget, UObject* onTweenUpdateTarget, UObject* onTweenLoopTarget, UObject* onTweenCompleteTarget) { //Make sure we have a valid object to tween before proceeding if (actorToMove) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::actorMoveFromTo; ie->actorTweening = actorToMove; ie->customEaseTypeCurve = customEaseTypeCurve; ie->orientationTarget = orientationTarget; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::ActorMoveFromToMin(AActor* actorToMove, FString parameters, bool initializeOnSpawn) { //Make sure we have a valid object to tween before proceeding if (actorToMove) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::actorMoveFromTo; ie->actorTweening = actorToMove; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } //Actor Move To Spline Point AiTweenEvent* UiTween::ActorMoveToSplinePointFull(float timerInterval, FName tweenName /*= "No Name"*/, AActor* actorToMove /*= nullptr*/, USplineComponent* splineComponent /*= nullptr*/, bool moveToPath /*= false*/, bool enforceValueTo, EVectorConstraints::VectorConstraints vectorConstraints /*= VectorConstraints::none*/, bool sweep /*= false*/, float delay /*= 0.0f*/, EDelayType::DelayType delayType /*= first*/, ETickType::TickType tickType /*= seconds*/, float tickTypeValue /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, UCurveFloat* customEaseTypeCurve /*= nullptr*/, float punchAmplitude /*= 1.0f*/, ELoopType::LoopType loopType /*= once*/, int32 maximumLoopSections, bool switchPathOrientationDirection, ELookType::LookType orientation /*= noOrientationChange*/, UObject* orientationTarget /*= nullptr*/, float orientationSpeed /*= 5.0f*/, ERotatorConstraints::RotatorConstraints rotatorConstraints /*= RotatorConstraints::none*/, UObject* onTweenStartTarget /*= nullptr*/, FString OnTweenStartFunctionName /*= ""*/, UObject* onTweenUpdateTarget /*= nullptr*/, FString OnTweenUpdateFunctionName /*= ""*/, UObject* onTweenLoopTarget /*= nullptr*/, FString OnTweenLoopFunctionName /*= ""*/, UObject* onTweenCompleteTarget /*= nullptr*/, FString OnTweenCompleteFunctionName /*= ""*/, bool tickWhenPaused /*= false*/, bool ignoreTimeDilation /*) = false*/, bool destroySplineComponent, bool tieToObjectValidity, bool cullNonRenderedTweens, float secondsToWaitBeforeCull) { //Make sure we have a valid object to tween and a valid spline before proceeding if (actorToMove && splineComponent) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::actorMoveToSplinePoint; ie->timerInterval = timerInterval; ie->tweenName = tweenName; ie->actorTweening = actorToMove; ie->splineComponent = splineComponent; ie->interpolateToSpline = moveToPath; ie->enforceValueTo = enforceValueTo; ie->vectorConstraints = vectorConstraints; ie->sweep = sweep; ie->delay = delay; ie->delayType = delayType; ie->tickType = tickType; ie->tickTypeValue = tickTypeValue; ie->easeType = easeType; ie->customEaseTypeCurve = customEaseTypeCurve; ie->punchAmplitude = punchAmplitude; ie->loopType = loopType; ie->maximumLoopSections = maximumLoopSections; ie->switchPathOrientationDirection = switchPathOrientationDirection; ie->orientation = orientation; ie->orientationTarget = orientationTarget; ie->orientationSpeed = orientationSpeed; ie->rotatorConstraints = rotatorConstraints; ie->onTweenStartTarget = onTweenStartTarget; ie->OnTweenStartFunctionName = OnTweenStartFunctionName; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->OnTweenUpdateFunctionName = OnTweenUpdateFunctionName; ie->onTweenLoopTarget = onTweenLoopTarget; ie->OnTweenLoopFunctionName = OnTweenLoopFunctionName; ie->onTweenCompleteTarget = onTweenCompleteTarget; ie->OnTweenCompleteFunctionName = OnTweenCompleteFunctionName; ie->tickWhenPaused = tickWhenPaused; ie->ignoreTimeDilation = ignoreTimeDilation; ie->destroySplineObject = destroySplineComponent; ie->tieToObjectValidity = tieToObjectValidity; ie->cullNonRenderedTweens = cullNonRenderedTweens; ie->secondsToWaitBeforeCull = secondsToWaitBeforeCull; //Initialize Event ie->InitEvent(); return ie; } else { if (!actorToMove) { Print("No tweenable object defined. No tweening operation will occur.", "error"); } else if (!splineComponent) { Print("No spline defined. No tweening operation will occur.", "error"); } return nullptr; } } AiTweenEvent* UiTween::ActorMoveToSplinePointSimple(FName tweenName /*= "No Name"*/, AActor* actorToMove /*= nullptr*/, USplineComponent* splineComponent /*= nullptr*/, bool moveToPath /*= false*/, bool sweep /*= false*/, float timeInSeconds /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, FString parameters, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget /*= nullptr*/, bool destroySplineComponent) { //Make sure we have a valid object to tween and a valid spline before proceeding if (actorToMove && splineComponent) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::actorMoveToSplinePoint; ie->tweenName = tweenName; ie->actorTweening = actorToMove; ie->splineComponent = splineComponent; ie->interpolateToSpline = moveToPath; ie->sweep = sweep; ie->tickTypeValue = timeInSeconds; ie->easeType = easeType; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; ie->destroySplineObject = destroySplineComponent; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event ie->InitEvent(); return ie; } else { if (!actorToMove) { Print("No tweenable object defined. No tweening operation will occur.", "error"); } else if (!splineComponent) { Print("No spline defined. No tweening operation will occur.", "error"); } return nullptr; } } AiTweenEvent* UiTween::ActorMoveToSplinePointExpert(AActor* actorToMove /*= nullptr*/, USplineComponent* splineComponent /*= nullptr*/, FString parameters, bool initializeOnSpawn, UCurveFloat* customEaseTypeCurve /*= nullptr*/, UObject* orientationTarget /*= nullptr*/, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget) { //Make sure we have a valid object to tween and a valid spline before proceeding if (actorToMove && splineComponent) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::actorMoveToSplinePoint; ie->actorTweening = actorToMove; ie->splineComponent = splineComponent; ie->customEaseTypeCurve = customEaseTypeCurve; ie->orientationTarget = orientationTarget; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { if (!actorToMove) { Print("No tweenable object defined. No tweening operation will occur.", "error"); } else if (!splineComponent) { Print("No spline defined. No tweening operation will occur.", "error"); } return nullptr; } } AiTweenEvent* UiTween::ActorMoveToSplinePointMin(AActor* actorToMove /*= nullptr*/, USplineComponent* splineComponent /*= nullptr*/, FString parameters, bool initializeOnSpawn) { //Make sure we have a valid object to tween and a valid spline before proceeding if (actorToMove && splineComponent) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::actorMoveToSplinePoint; ie->actorTweening = actorToMove; ie->splineComponent = splineComponent; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { if (!actorToMove) { Print("No tweenable object defined. No tweening operation will occur.", "error"); } else if (!splineComponent) { Print("No spline defined. No tweening operation will occur.", "error"); } return nullptr; } } //Actor Move Update void UiTween::ActorMoveUpdate(AActor* actorToMove, FVector locationTo, float delta, float speed, bool isLocal, bool sweep, EVectorConstraints::VectorConstraints vectorConstraints, ELookType::LookType orientation, UObject* orientationTarget, float orientationSpeed, ERotatorConstraints::RotatorConstraints rotatorConstraints) { //Make sure we have a valid object to tween before proceeding if (actorToMove) { if (isLocal && actorToMove->GetRootComponent()->GetAttachParent()) { locationTo = (actorToMove->GetRootComponent()->GetAttachParent()->GetOwner()->GetActorRotation().RotateVector(locationTo) + actorToMove->GetRootComponent()->GetAttachParent()->GetOwner()->GetActorLocation()); } actorToMove->SetActorLocation(ConstrainVector(FMath::VInterpTo(actorToMove->GetActorLocation(), locationTo, delta, speed), actorToMove->GetActorLocation(), vectorConstraints), sweep); if (orientation == orientToTarget) { if (orientationTarget->IsA(AActor::StaticClass())) { ActorRotateUpdate(actorToMove, FRotationMatrix::MakeFromX(((AActor*)orientationTarget)->GetActorLocation() - actorToMove->GetActorLocation()).Rotator(), delta, orientationSpeed, /*false, */false, rotatorConstraints); } else if (orientationTarget->IsA(USceneComponent::StaticClass())) { ActorRotateUpdate(actorToMove, FRotationMatrix::MakeFromX(((USceneComponent*)orientationTarget)->GetComponentLocation() - actorToMove->GetActorLocation()).Rotator(), delta, orientationSpeed, /*false, */false, rotatorConstraints); } else if (orientationTarget->IsA(UWidget::StaticClass())) { //Feature is still to come. Waiting on getting the ability to read widget position in screen space } } else if (orientation == orientToPath) { actorToMove->SetActorRotation(ConstrainRotator(FMath::RInterpTo(actorToMove->GetActorRotation(), FRotationMatrix::MakeFromX((ConstrainVector(locationTo, actorToMove->GetActorLocation(), vectorConstraints)) - actorToMove->GetActorLocation()).Rotator(), delta, orientationSpeed), actorToMove->GetActorRotation(), rotatorConstraints)); } } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); } } //Actor Rotate From/To AiTweenEvent* UiTween::ActorRotateFromToFull(float timerInterval, FName tweenName /*= "No Name"*/, AActor* actorToRotate /*= nullptr*/, FRotator rotationFrom /*= FRotator::ZeroRotator*/, FRotator rotationTo /*= FRotator::ZeroRotator*/, bool enforceValueTo, ERotatorConstraints::RotatorConstraints rotatorConstraints /*= VectorConstraints::none*/, ECoordinateSpace::CoordinateSpace coordinateSpace, bool shortestPath /*= false*/, float delay /*= 0.0f*/, EDelayType::DelayType delayType /*= first*/, ETickType::TickType tickType /*= seconds*/, float tickTypeValue /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, UCurveFloat* customEaseTypeCurve /*= nullptr*/, float punchAmplitude /*= 1.0f*/, ELoopType::LoopType loopType /*= once*/, int32 maximumLoopSections, UObject* onTweenStartTarget /*= nullptr*/, FString OnTweenStartFunctionName /*= ""*/, UObject* onTweenUpdateTarget /*= nullptr*/, FString OnTweenUpdateFunctionName /*= ""*/, UObject* onTweenLoopTarget /*= nullptr*/, FString OnTweenLoopFunctionName /*= ""*/, UObject* onTweenCompleteTarget /*= nullptr*/, FString OnTweenCompleteFunctionName /*= ""*/, bool tickWhenPaused /*= false*/, bool ignoreTimeDilation /*= false*/, bool tieToObjectValidity, bool cullNonRenderedTweens, float secondsToWaitBeforeCull) { //Make sure we have a valid object to tween before proceeding if (actorToRotate) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::actorRotateFromTo; ie->timerInterval = timerInterval; ie->tweenName = tweenName; ie->actorTweening = actorToRotate; ie->rotatorFrom = rotationFrom; ie->rotatorTo = rotationTo; ie->enforceValueTo = enforceValueTo; ie->rotatorConstraints = rotatorConstraints; ie->coordinateSpace = coordinateSpace; ie->shortestPath = shortestPath; ie->delay = delay; ie->delayType = delayType; ie->tickType = tickType; ie->tickTypeValue = tickTypeValue; ie->easeType = easeType; ie->customEaseTypeCurve = customEaseTypeCurve; ie->punchAmplitude = punchAmplitude; ie->loopType = loopType; ie->maximumLoopSections = maximumLoopSections; ie->onTweenStartTarget = onTweenStartTarget; ie->OnTweenStartFunctionName = OnTweenStartFunctionName; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->OnTweenUpdateFunctionName = OnTweenUpdateFunctionName; ie->onTweenLoopTarget = onTweenLoopTarget; ie->OnTweenLoopFunctionName = OnTweenLoopFunctionName; ie->onTweenCompleteTarget = onTweenCompleteTarget; ie->OnTweenCompleteFunctionName = OnTweenCompleteFunctionName; ie->tickWhenPaused = tickWhenPaused; ie->ignoreTimeDilation = ignoreTimeDilation; ie->tieToObjectValidity = tieToObjectValidity; ie->cullNonRenderedTweens = cullNonRenderedTweens; ie->secondsToWaitBeforeCull = secondsToWaitBeforeCull; //Initialize Event ie->InitEvent(); return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::ActorRotateFromToSimple(FName tweenName /*= "No Name"*/, AActor* actorToRotate /*= nullptr*/, FRotator rotationFrom /*= FRotator::ZeroRotator*/, FRotator rotationTo /*= FRotator::ZeroRotator*/, ECoordinateSpace::CoordinateSpace coordinateSpace, bool shortestPath /*= false*/, float timeInSeconds /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, FString parameters, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget /*= nullptr*/) { //Make sure we have a valid object to tween before proceeding if (actorToRotate) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::actorRotateFromTo; ie->tweenName = tweenName; ie->actorTweening = actorToRotate; ie->rotatorFrom = rotationFrom; ie->rotatorTo = rotationTo; ie->coordinateSpace = coordinateSpace; ie->shortestPath = shortestPath; ie->tickTypeValue = timeInSeconds; ie->easeType = easeType; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event ie->InitEvent(); return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::ActorRotateFromToExpert(AActor* actorToRotate /*= nullptr*/, FString parameters, bool initializeOnSpawn, UCurveFloat* customEaseTypeCurve /*= nullptr*/, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget) { //Make sure we have a valid object to tween before proceeding if (actorToRotate) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::actorRotateFromTo; ie->actorTweening = actorToRotate; ie->customEaseTypeCurve = customEaseTypeCurve; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::ActorRotateFromToMin(AActor* actorToRotate /*= nullptr*/, FString parameters, bool initializeOnSpawn) { //Make sure we have a valid object to tween before proceeding if (actorToRotate) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::actorRotateFromTo; ie->actorTweening = actorToRotate; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } //Actor Rotate To Spline Point AiTweenEvent* UiTween::ActorRotateToSplinePointFull(float timerInterval, FName tweenName /*= "No Name"*/, AActor* actorToRotate /*= nullptr*/, USplineComponent* splineComponent /*= nullptr*/, bool rotateToPath /*= false*/, bool enforceValueTo, float generatedPointDistance, ERotatorConstraints::RotatorConstraints rotatorConstraints /*= RotatorConstraints::none*/, float delay /*= 0.0f*/, EDelayType::DelayType delayType /*= first*/, ETickType::TickType tickType /*= seconds*/, float tickTypeValue /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, UCurveFloat* customEaseTypeCurve /*= nullptr*/, float punchAmplitude /*= 1.0f*/, ELoopType::LoopType loopType /*= once*/, int32 maximumLoopSections, UObject* onTweenStartTarget /*= nullptr*/, FString OnTweenStartFunctionName /*= ""*/, UObject* onTweenUpdateTarget /*= nullptr*/, FString OnTweenUpdateFunctionName /*= ""*/, UObject* onTweenLoopTarget /*= nullptr*/, FString OnTweenLoopFunctionName /*= ""*/, UObject* onTweenCompleteTarget /*= nullptr*/, FString OnTweenCompleteFunctionName /*= ""*/, bool tickWhenPaused /*= false*/, bool ignoreTimeDilation /*= false*/, bool destroySplineComponent, bool tieToObjectValidity, bool cullNonRenderedTweens, float secondsToWaitBeforeCull) { //Make sure we have a valid object to tween and a valid spline before proceeding if (actorToRotate && splineComponent) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::actorRotateToSplinePoint; ie->timerInterval = timerInterval; ie->tweenName = tweenName; ie->actorTweening = actorToRotate; ie->splineComponent = splineComponent; ie->interpolateToSpline = rotateToPath; ie->enforceValueTo = enforceValueTo; ie->generatedPointDistance = generatedPointDistance; ie->rotatorConstraints = rotatorConstraints; ie->delay = delay; ie->delayType = delayType; ie->tickType = tickType; ie->tickTypeValue = tickTypeValue; ie->easeType = easeType; ie->customEaseTypeCurve = customEaseTypeCurve; ie->punchAmplitude = punchAmplitude; ie->loopType = loopType; ie->maximumLoopSections = maximumLoopSections; ie->onTweenStartTarget = onTweenStartTarget; ie->OnTweenStartFunctionName = OnTweenStartFunctionName; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->OnTweenUpdateFunctionName = OnTweenUpdateFunctionName; ie->onTweenLoopTarget = onTweenLoopTarget; ie->OnTweenLoopFunctionName = OnTweenLoopFunctionName; ie->onTweenCompleteTarget = onTweenCompleteTarget; ie->OnTweenCompleteFunctionName = OnTweenCompleteFunctionName; ie->tickWhenPaused = tickWhenPaused; ie->ignoreTimeDilation = ignoreTimeDilation; ie->destroySplineObject = destroySplineComponent; ie->tieToObjectValidity = tieToObjectValidity; ie->cullNonRenderedTweens = cullNonRenderedTweens; ie->secondsToWaitBeforeCull = secondsToWaitBeforeCull; //Initialize Event ie->InitEvent(); return ie; } else { if (!actorToRotate) { Print("No tweenable object defined. No tweening operation will occur.", "error"); } else if (!splineComponent) { Print("No spline defined. No tweening operation will occur.", "error"); } return nullptr; } } AiTweenEvent* UiTween::ActorRotateToSplinePointSimple(FName tweenName /*= "No Name"*/, AActor* actorToRotate /*= nullptr*/, USplineComponent* splineComponent /*= nullptr*/, bool rotateToPath /*= false*/, float generatedPointDistance, float timeInSeconds /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, FString parameters, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget /*= nullptr*/, bool destroySplineComponent) { //Make sure we have a valid object to tween and a valid spline before proceeding if (actorToRotate && splineComponent) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::actorRotateToSplinePoint; ie->tweenName = tweenName; ie->actorTweening = actorToRotate; ie->splineComponent = splineComponent; ie->interpolateToSpline = rotateToPath; ie->generatedPointDistance = generatedPointDistance; ie->tickTypeValue = timeInSeconds; ie->easeType = easeType; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; ie->destroySplineObject = destroySplineComponent; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event ie->InitEvent(); return ie; } else { if (!actorToRotate) { Print("No tweenable object defined. No tweening operation will occur.", "error"); } else if (!splineComponent) { Print("No spline defined. No tweening operation will occur.", "error"); } return nullptr; } } AiTweenEvent* UiTween::ActorRotateToSplinePointExpert(AActor* actorToRotate /*= nullptr*/, USplineComponent* splineComponent /*= nullptr*/, FString parameters, bool initializeOnSpawn, UCurveFloat* customEaseTypeCurve /*= nullptr*/, UObject* orientationTarget /*= nullptr*/, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget) { //Make sure we have a valid object to tween and a valid spline before proceeding if (actorToRotate && splineComponent) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::actorRotateToSplinePoint; ie->actorTweening = actorToRotate; ie->splineComponent = splineComponent; ie->customEaseTypeCurve = customEaseTypeCurve; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { if (!actorToRotate) { Print("No tweenable object defined. No tweening operation will occur.", "error"); } else if (!splineComponent) { Print("No spline defined. No tweening operation will occur.", "error"); } return nullptr; } } AiTweenEvent* UiTween::ActorRotateToSplinePointMin(AActor* actorToRotate /*= nullptr*/, USplineComponent* splineComponent /*= nullptr*/, FString parameters, bool initializeOnSpawn) { //Make sure we have a valid object to tween and a valid spline before proceeding if (actorToRotate && splineComponent) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::actorRotateToSplinePoint; ie->actorTweening = actorToRotate; ie->splineComponent = splineComponent; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { if (!actorToRotate) { Print("No tweenable object defined. No tweening operation will occur.", "error"); } else if (!splineComponent) { Print("No spline defined. No tweening operation will occur.", "error"); } return nullptr; } } //Actor Rotate Update void UiTween::ActorRotateUpdate(AActor* actorToRotate, FRotator rotationTo, float delta, float speed, bool isLocal, ERotatorConstraints::RotatorConstraints rotatorConstraints) { //Make sure we have a valid object to tween before proceeding if (actorToRotate) { if (isLocal && actorToRotate->GetRootComponent()->GetAttachParent()) { rotationTo = FRotator(FQuat(actorToRotate->GetRootComponent()->GetAttachParent()->GetComponentRotation()) * FQuat(rotationTo)); } actorToRotate->SetActorRotation(ConstrainRotator(FMath::RInterpTo(actorToRotate->GetActorRotation(), rotationTo, delta, speed), actorToRotate->GetActorRotation(), rotatorConstraints)); } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); } } //Actor Scale From/To AiTweenEvent* UiTween::ActorScaleFromToFull(float timerInterval, FName tweenName /*= "No Name"*/, AActor* actorToScale /*= nullptr*/, FVector scaleFrom /*= FVector::ZeroVector*/, FVector scaleTo /*= FVector(1,1,1)*/, bool enforceValueTo, EVectorConstraints::VectorConstraints vectorConstraints /*= VectorConstraints::none*/, bool isLocal, float delay /*= 0.0f*/, EDelayType::DelayType delayType /*= first*/, ETickType::TickType tickType /*= seconds*/, float tickTypeValue /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, UCurveFloat* customEaseTypeCurve /*= nullptr*/, float punchAmplitude /*= 1.0f*/, ELoopType::LoopType loopType /*= once*/, int32 maximumLoopSections, UObject* onTweenStartTarget /*= nullptr*/, FString OnTweenStartFunctionName /*= ""*/, UObject* onTweenUpdateTarget /*= nullptr*/, FString OnTweenUpdateFunctionName /*= ""*/, UObject* onTweenLoopTarget /*= nullptr*/, FString OnTweenLoopFunctionName /*= ""*/, UObject* onTweenCompleteTarget /*= nullptr*/, FString OnTweenCompleteFunctionName /*= ""*/, bool tickWhenPaused /*= false*/, bool ignoreTimeDilation /*= false*/, bool tieToObjectValidity, bool cullNonRenderedTweens, float secondsToWaitBeforeCull) { //Make sure we have a valid object to tween before proceeding if (actorToScale) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::actorScaleFromTo; ie->timerInterval = timerInterval; ie->tweenName = tweenName; ie->actorTweening = actorToScale; ie->vectorFrom = scaleFrom; ie->vectorTo = scaleTo; ie->enforceValueTo = enforceValueTo; ie->vectorConstraints = vectorConstraints; if (isLocal) { ie->coordinateSpace = CoordinateSpace::parent; } ie->delay = delay; ie->delayType = delayType; ie->tickType = tickType; ie->tickTypeValue = tickTypeValue; ie->easeType = easeType; ie->customEaseTypeCurve = customEaseTypeCurve; ie->punchAmplitude = punchAmplitude; ie->loopType = loopType; ie->maximumLoopSections = maximumLoopSections; ie->onTweenStartTarget = onTweenStartTarget; ie->OnTweenStartFunctionName = OnTweenStartFunctionName; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->OnTweenUpdateFunctionName = OnTweenUpdateFunctionName; ie->onTweenLoopTarget = onTweenLoopTarget; ie->OnTweenLoopFunctionName = OnTweenLoopFunctionName; ie->onTweenCompleteTarget = onTweenCompleteTarget; ie->OnTweenCompleteFunctionName = OnTweenCompleteFunctionName; ie->tickWhenPaused = tickWhenPaused; ie->ignoreTimeDilation = ignoreTimeDilation; ie->tieToObjectValidity = tieToObjectValidity; ie->cullNonRenderedTweens = cullNonRenderedTweens; ie->secondsToWaitBeforeCull = secondsToWaitBeforeCull; //Initialize Event ie->InitEvent(); return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::ActorScaleFromToSimple(FName tweenName /*= "No Name"*/, AActor* actorToScale /*= nullptr*/, FVector scaleFrom /*= FVector::ZeroVector*/, FVector scaleTo /*= FVector(1,1,1)*/, bool isLocal, float timeInSeconds /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, FString parameters, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget /*= nullptr*/) { //Make sure we have a valid object to tween before proceeding if (actorToScale) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::actorScaleFromTo; ie->tweenName = tweenName; ie->actorTweening = actorToScale; ie->vectorFrom = scaleFrom; ie->vectorTo = scaleTo; if (isLocal) { ie->coordinateSpace = CoordinateSpace::parent; } ie->tickTypeValue = timeInSeconds; ie->easeType = easeType; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event ie->InitEvent(); return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::ActorScaleFromToExpert(AActor* actorToScale /*= nullptr*/, FString parameters, bool initializeOnSpawn, UCurveFloat* customEaseTypeCurve /*= nullptr*/, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget) { //Make sure we have a valid object to tween before proceeding if (actorToScale) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::actorScaleFromTo; ie->actorTweening = actorToScale; ie->customEaseTypeCurve = customEaseTypeCurve; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::ActorScaleFromToMin(AActor* actorToScale /*= nullptr*/, FString parameters, bool initializeOnSpawn) { //Make sure we have a valid object to tween before proceeding if (actorToScale) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::actorScaleFromTo; ie->actorTweening = actorToScale; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } //Actor Scale Update void UiTween::ActorScaleUpdate(AActor* actorToScale, FVector scaleTo, float delta, float speed, bool isLocal, EVectorConstraints::VectorConstraints vectorConstraints) { //Make sure we have a valid object to tween before proceeding if (actorToScale) { if (isLocal && actorToScale->GetRootComponent()->GetAttachParent()) { scaleTo = actorToScale->GetRootComponent()->GetAttachParent()->GetComponentScale() * scaleTo; } actorToScale->SetActorScale3D(ConstrainVector(FMath::VInterpTo(actorToScale->GetActorScale3D(), scaleTo, delta, speed), actorToScale->GetActorScale3D(), vectorConstraints)); } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); } } //Component //Component Move From/To AiTweenEvent* UiTween::ComponentMoveFromToFull(float timerInterval, FName tweenName /*= "No Name"*/, USceneComponent* componentToMove /*= nullptr*/, FVector locationFrom /*= FVector::ZeroVector*/, FVector locationTo /*= FVector::ZeroVector*/, bool enforceValueTo, EVectorConstraints::VectorConstraints vectorConstraints /*= VectorConstraints::none*/, ECoordinateSpace::CoordinateSpace coordinateSpace /*= CoordinateSpace::world*/, bool sweep /*= false*/, float delay /*= 0.0f*/, EDelayType::DelayType delayType /*= first*/, ETickType::TickType tickType /*= seconds*/, float tickTypeValue /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, UCurveFloat* customEaseTypeCurve /*= nullptr*/, float punchAmplitude /*= 1.0f*/, ELoopType::LoopType loopType /*= once*/, int32 maximumLoopSections, ELookType::LookType orientation /*= noOrientationChange*/, UObject* orientationTarget /*= nullptr*/, float orientationSpeed /*= 5.0f*/, ERotatorConstraints::RotatorConstraints rotatorConstraints /*= RotatorConstraints::none*/, UObject* onTweenStartTarget /*= nullptr*/, FString OnTweenStartFunctionName /*= ""*/, UObject* onTweenUpdateTarget /*= nullptr*/, FString OnTweenUpdateFunctionName /*= ""*/, UObject* onTweenLoopTarget /*= nullptr*/, FString OnTweenLoopFunctionName /*= ""*/, UObject* onTweenCompleteTarget /*= nullptr*/, FString OnTweenCompleteFunctionName /*= ""*/, bool tickWhenPaused /*= false*/, bool ignoreTimeDilation /*= false*/, bool tieToObjectValidity, bool cullNonRenderedTweens, float secondsToWaitBeforeCull) { //Make sure we have a valid object to tween before proceeding if (componentToMove) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::compMoveFromTo; ie->timerInterval = timerInterval; ie->tweenName = tweenName; ie->componentTweening = componentToMove; ie->vectorFrom = locationFrom; ie->vectorTo = locationTo; ie->enforceValueTo = enforceValueTo; ie->vectorConstraints = vectorConstraints; ie->coordinateSpace = coordinateSpace; ie->sweep = sweep; ie->delay = delay; ie->delayType = delayType; ie->tickType = tickType; ie->tickTypeValue = tickTypeValue; ie->easeType = easeType; ie->customEaseTypeCurve = customEaseTypeCurve; ie->punchAmplitude = punchAmplitude; ie->loopType = loopType; ie->maximumLoopSections = maximumLoopSections; ie->orientation = orientation; ie->orientationTarget = orientationTarget; ie->orientationSpeed = orientationSpeed; ie->rotatorConstraints = rotatorConstraints; ie->onTweenStartTarget = onTweenStartTarget; ie->OnTweenStartFunctionName = OnTweenStartFunctionName; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->OnTweenUpdateFunctionName = OnTweenUpdateFunctionName; ie->onTweenLoopTarget = onTweenLoopTarget; ie->OnTweenLoopFunctionName = OnTweenLoopFunctionName; ie->onTweenCompleteTarget = onTweenCompleteTarget; ie->OnTweenCompleteFunctionName = OnTweenCompleteFunctionName; ie->tickWhenPaused = tickWhenPaused; ie->ignoreTimeDilation = ignoreTimeDilation; ie->tieToObjectValidity = tieToObjectValidity; ie->cullNonRenderedTweens = cullNonRenderedTweens; ie->secondsToWaitBeforeCull = secondsToWaitBeforeCull; //Initialize Event ie->InitEvent(); return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::ComponentMoveFromToSimple(FName tweenName /*= "No Name"*/, USceneComponent* componentToMove /*= nullptr*/, FVector locationFrom /*= FVector::ZeroVector*/, FVector locationTo /*= FVector::ZeroVector*/, ECoordinateSpace::CoordinateSpace coordinateSpace /*= CoordinateSpace::world*/, bool sweep /*= false*/, float timeInSeconds /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, FString parameters, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget /*= nullptr*/) { //Make sure we have a valid object to tween before proceeding if (componentToMove) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::compMoveFromTo; ie->tweenName = tweenName; ie->componentTweening = componentToMove; ie->vectorFrom = locationFrom; ie->vectorTo = locationTo; ie->coordinateSpace = coordinateSpace; ie->sweep = sweep; ie->tickTypeValue = timeInSeconds; ie->easeType = easeType; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event ie->InitEvent(); return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::ComponentMoveFromToExpert(USceneComponent* componentToMove /*= nullptr*/, FString parameters, bool initializeOnSpawn, UCurveFloat* customEaseTypeCurve /*= nullptr*/, UObject* orientationTarget /*= nullptr*/, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget) { //Make sure we have a valid object to tween before proceeding if (componentToMove) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::compMoveFromTo; ie->componentTweening = componentToMove; ie->customEaseTypeCurve = customEaseTypeCurve; ie->orientationTarget = orientationTarget; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::ComponentMoveFromToMin(USceneComponent* componentToMove /*= nullptr*/, FString parameters, bool initializeOnSpawn) { //Make sure we have a valid object to tween before proceeding if (componentToMove) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::compMoveFromTo; ie->componentTweening = componentToMove; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } //Component Move To Spline Point AiTweenEvent* UiTween::ComponentMoveToSplinePointFull(float timerInterval, FName tweenName /*= "No Name"*/, USceneComponent* componentToMove /*= nullptr*/, USplineComponent* splineComponent /*= nullptr*/, bool moveToPath /*= false*/, bool enforceValueTo, EVectorConstraints::VectorConstraints vectorConstraints /*= VectorConstraints::none*/, bool sweep /*= false*/, float delay /*= 0.0f*/, EDelayType::DelayType delayType /*= first*/, ETickType::TickType tickType /*= seconds*/, float tickTypeValue /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, UCurveFloat* customEaseTypeCurve /*= nullptr*/, float punchAmplitude /*= 1.0f*/, ELoopType::LoopType loopType /*= once*/, int32 maximumLoopSections, bool switchPathOrientationDirection /*= true*/, ELookType::LookType orientation /*= noOrientationChange*/, UObject* orientationTarget /*= nullptr*/, float orientationSpeed /*= 5.0f*/, ERotatorConstraints::RotatorConstraints rotatorConstraints /*= RotatorConstraints::none*/, UObject* onTweenStartTarget /*= nullptr*/, FString OnTweenStartFunctionName /*= ""*/, UObject* onTweenUpdateTarget /*= nullptr*/, FString OnTweenUpdateFunctionName /*= ""*/, UObject* onTweenLoopTarget /*= nullptr*/, FString OnTweenLoopFunctionName /*= ""*/, UObject* onTweenCompleteTarget /*= nullptr*/, FString OnTweenCompleteFunctionName /*= ""*/, bool tickWhenPaused, bool ignoreTimeDilation, bool destroySplineComponent, bool tieToObjectValidity, bool cullNonRenderedTweens, float secondsToWaitBeforeCull) { //Make sure we have a valid object to tween and a valid spline before proceeding if (componentToMove && splineComponent) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::compMoveToSplinePoint; ie->timerInterval = timerInterval; ie->tweenName = tweenName; ie->componentTweening = componentToMove; ie->splineComponent = splineComponent; ie->interpolateToSpline = moveToPath; ie->enforceValueTo = enforceValueTo; ie->vectorConstraints = vectorConstraints; ie->sweep = sweep; ie->delay = delay; ie->delayType = delayType; ie->tickType = tickType; ie->tickTypeValue = tickTypeValue; ie->easeType = easeType; ie->customEaseTypeCurve = customEaseTypeCurve; ie->punchAmplitude = punchAmplitude; ie->loopType = loopType; ie->maximumLoopSections = maximumLoopSections; ie->switchPathOrientationDirection = switchPathOrientationDirection; ie->orientation = orientation; ie->orientationTarget = orientationTarget; ie->orientationSpeed = orientationSpeed; ie->rotatorConstraints = rotatorConstraints; ie->onTweenStartTarget = onTweenStartTarget; ie->OnTweenStartFunctionName = OnTweenStartFunctionName; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->OnTweenUpdateFunctionName = OnTweenUpdateFunctionName; ie->onTweenLoopTarget = onTweenLoopTarget; ie->OnTweenLoopFunctionName = OnTweenLoopFunctionName; ie->onTweenCompleteTarget = onTweenCompleteTarget; ie->OnTweenCompleteFunctionName = OnTweenCompleteFunctionName; ie->tickWhenPaused = tickWhenPaused; ie->ignoreTimeDilation = ignoreTimeDilation; ie->destroySplineObject = destroySplineComponent; ie->tieToObjectValidity = tieToObjectValidity; ie->cullNonRenderedTweens = cullNonRenderedTweens; ie->secondsToWaitBeforeCull = secondsToWaitBeforeCull; //Initialize Event ie->InitEvent(); return ie; } else { if (!componentToMove) { Print("No tweenable object defined. No tweening operation will occur.", "error"); } else if (!splineComponent) { Print("No spline defined. No tweening operation will occur.", "error"); } return nullptr; } } AiTweenEvent* UiTween::ComponentMoveToSplinePointSimple(FName tweenName /*= "No Name"*/, USceneComponent* componentToMove /*= nullptr*/, USplineComponent* splineComponent /*= nullptr*/, bool moveToPath /*= false*/, bool sweep /*= false*/, float timeInSeconds /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, FString parameters, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget /*= nullptr*/, bool destroySplineComponent) { //Make sure we have a valid object to tween and a valid spline before proceeding if (componentToMove && splineComponent) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::compMoveToSplinePoint; ie->tweenName = tweenName; ie->componentTweening = componentToMove; ie->splineComponent = splineComponent; ie->interpolateToSpline = moveToPath; ie->sweep = sweep; ie->tickTypeValue = timeInSeconds; ie->easeType = easeType; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; ie->destroySplineObject = destroySplineComponent; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event ie->InitEvent(); return ie; } else { if (!componentToMove) { Print("No tweenable object defined. No tweening operation will occur.", "error"); } else if (!splineComponent) { Print("No spline defined. No tweening operation will occur.", "error"); } return nullptr; } } AiTweenEvent* UiTween::ComponentMoveToSplinePointExpert(USceneComponent* componentToMove /*= nullptr*/, USplineComponent* splineComponent /*= nullptr*/, FString parameters, bool initializeOnSpawn, UCurveFloat* customEaseTypeCurve /*= nullptr*/, UObject* orientationTarget /*= nullptr*/, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget) { //Make sure we have a valid object to tween and a valid spline before proceeding if (componentToMove && splineComponent) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::compMoveToSplinePoint; ie->componentTweening = componentToMove; ie->splineComponent = splineComponent; ie->customEaseTypeCurve = customEaseTypeCurve; ie->orientationTarget = orientationTarget; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { if (!componentToMove) { Print("No tweenable object defined. No tweening operation will occur.", "error"); } else if (!splineComponent) { Print("No spline defined. No tweening operation will occur.", "error"); } return nullptr; } } AiTweenEvent* UiTween::ComponentMoveToSplinePointMin(USceneComponent* componentToMove /*= nullptr*/, USplineComponent* splineComponent /*= nullptr*/, FString parameters, bool initializeOnSpawn) { //Make sure we have a valid object to tween and a valid spline before proceeding if (componentToMove && splineComponent) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::compMoveToSplinePoint; ie->componentTweening = componentToMove; ie->splineComponent = splineComponent; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { if (!componentToMove) { Print("No tweenable object defined. No tweening operation will occur.", "error"); } else if (!splineComponent) { Print("No spline defined. No tweening operation will occur.", "error"); } return nullptr; } } //Component Move Update void UiTween::ComponentMoveUpdate(USceneComponent* componentToMove, FVector locationTo, float delta, float speed, bool isLocal, bool sweep, EVectorConstraints::VectorConstraints vectorConstraints, ELookType::LookType orientation, UObject* orientationTarget, float orientationSpeed, ERotatorConstraints::RotatorConstraints rotatorConstraints) { //Make sure we have a valid object to tween before proceeding if (componentToMove) { if (isLocal && componentToMove->GetOwner()) { locationTo = (componentToMove->GetOwner()->GetActorRotation().RotateVector(locationTo) + componentToMove->GetOwner()->GetActorLocation()); } componentToMove->SetWorldLocation(ConstrainVector(FMath::VInterpTo(componentToMove->GetComponentLocation(), locationTo, delta, speed), componentToMove->GetComponentLocation(), vectorConstraints), sweep); if (orientation == orientToTarget) { if (orientationTarget->IsA(AActor::StaticClass())) { ComponentRotateUpdate(componentToMove, FRotationMatrix::MakeFromX(((AActor*)orientationTarget)->GetActorLocation() - componentToMove->GetComponentLocation()).Rotator(), delta, orientationSpeed, /*false, */false, rotatorConstraints); } else if (orientationTarget->IsA(USceneComponent::StaticClass())) { ComponentRotateUpdate(componentToMove, FRotationMatrix::MakeFromX(((USceneComponent*)orientationTarget)->GetComponentLocation() - componentToMove->GetComponentLocation()).Rotator(), delta, orientationSpeed, /*false, */false, rotatorConstraints); } else if (orientationTarget->IsA(UWidget::StaticClass())) { //Feature is still to come. Waiting on getting the ability to read widget position in screen space } } else if (orientation == orientToPath) { componentToMove->SetWorldRotation(ConstrainRotator(FMath::RInterpTo(componentToMove->GetComponentRotation(), FRotationMatrix::MakeFromX((ConstrainVector(locationTo, componentToMove->GetComponentLocation(), vectorConstraints)) - componentToMove->GetComponentLocation()).Rotator(), delta, orientationSpeed), componentToMove->GetComponentRotation(), rotatorConstraints)); } } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); } } //Component Rotate From/To AiTweenEvent* UiTween::ComponentRotateFromToFull(float timerInterval, FName tweenName /*= "No Name"*/, USceneComponent* componentToRotate /*= nullptr*/, FRotator rotationFrom /*= FRotator::ZeroRotator*/, FRotator rotationTo /*= FRotator::ZeroRotator*/, bool enforceValueTo, ERotatorConstraints::RotatorConstraints rotatorConstraints /*= RotatorConstraints::none*/, ECoordinateSpace::CoordinateSpace coordinateSpace /*= CoordinateSpace::world*/, bool shortestPath /*= false*/, float delay /*= 0.0f*/, EDelayType::DelayType delayType /*= first*/, ETickType::TickType tickType /*= seconds*/, float tickTypeValue /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, UCurveFloat* customEaseTypeCurve /*= nullptr*/, float punchAmplitude /*= 1.0f*/, ELoopType::LoopType loopType /*= once*/, int32 maximumLoopSections, UObject* onTweenStartTarget /*= nullptr*/, FString OnTweenStartFunctionName /*= ""*/, UObject* onTweenUpdateTarget /*= nullptr*/, FString OnTweenUpdateFunctionName /*= ""*/, UObject* onTweenLoopTarget /*= nullptr*/, FString OnTweenLoopFunctionName /*= ""*/, UObject* onTweenCompleteTarget /*= nullptr*/, FString OnTweenCompleteFunctionName /*= ""*/, bool tickWhenPaused /*= false*/, bool ignoreTimeDilation /*= false*/, bool tieToObjectValidity, bool cullNonRenderedTweens, float secondsToWaitBeforeCull) { //Make sure we have a valid object to tween before proceeding if (componentToRotate) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::compRotateFromTo; ie->timerInterval = timerInterval; ie->tweenName = tweenName; ie->componentTweening = componentToRotate; ie->rotatorFrom = rotationFrom; ie->rotatorTo = rotationTo; ie->enforceValueTo = enforceValueTo; ie->rotatorConstraints = rotatorConstraints; ie->coordinateSpace = coordinateSpace; ie->shortestPath = shortestPath; ie->delay = delay; ie->delayType = delayType; ie->tickType = tickType; ie->tickTypeValue = tickTypeValue; ie->easeType = easeType; ie->customEaseTypeCurve = customEaseTypeCurve; ie->punchAmplitude = punchAmplitude; ie->loopType = loopType; ie->maximumLoopSections = maximumLoopSections; ie->onTweenStartTarget = onTweenStartTarget; ie->OnTweenStartFunctionName = OnTweenStartFunctionName; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->OnTweenUpdateFunctionName = OnTweenUpdateFunctionName; ie->onTweenLoopTarget = onTweenLoopTarget; ie->OnTweenLoopFunctionName = OnTweenLoopFunctionName; ie->onTweenCompleteTarget = onTweenCompleteTarget; ie->OnTweenCompleteFunctionName = OnTweenCompleteFunctionName; ie->tickWhenPaused = tickWhenPaused; ie->ignoreTimeDilation = ignoreTimeDilation; ie->tieToObjectValidity = tieToObjectValidity; ie->cullNonRenderedTweens = cullNonRenderedTweens; ie->secondsToWaitBeforeCull = secondsToWaitBeforeCull; //Initialize Event ie->InitEvent(); return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::ComponentRotateFromToSimple(FName tweenName /*= "No Name"*/, USceneComponent* componentToRotate /*= nullptr*/, FRotator rotationFrom /*= FRotator::ZeroRotator*/, FRotator rotationTo /*= FRotator::ZeroRotator*/, ECoordinateSpace::CoordinateSpace coordinateSpace /*= CoordinateSpace::world*/, bool shortestPath /*= false*/, float timeInSeconds /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, FString parameters, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget /*= nullptr*/) { //Make sure we have a valid object to tween before proceeding if (componentToRotate) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::compRotateFromTo; ie->tweenName = tweenName; ie->componentTweening = componentToRotate; ie->rotatorFrom = rotationFrom; ie->rotatorTo = rotationTo; ie->coordinateSpace = coordinateSpace; ie->shortestPath = shortestPath; ie->tickTypeValue = timeInSeconds; ie->easeType = easeType; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event ie->InitEvent(); return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::ComponentRotateFromToExpert(USceneComponent* componentToRotate /*= nullptr*/, FString parameters, bool initializeOnSpawn, UCurveFloat* customEaseTypeCurve /*= nullptr*/, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget) { //Make sure we have a valid object to tween before proceeding if (componentToRotate) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::compRotateFromTo; ie->componentTweening = componentToRotate; ie->customEaseTypeCurve = customEaseTypeCurve; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::ComponentRotateFromToMin(USceneComponent* componentToRotate /*= nullptr*/, FString parameters, bool initializeOnSpawn) { //Make sure we have a valid object to tween before proceeding if (componentToRotate) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::compRotateFromTo; ie->componentTweening = componentToRotate; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } //Component Rotate To Spline Point AiTweenEvent* UiTween::ComponentRotateToSplinePointFull(float timerInterval, FName tweenName /*= "No Name"*/, USceneComponent* componentToRotate /*= nullptr*/, USplineComponent* splineComponent /*= nullptr*/, bool rotateToPath /*= false*/, bool enforceValueTo, float generatedPointDistance /*= 100.f*/, ERotatorConstraints::RotatorConstraints rotatorConstraints /*= RotatorConstraints::none*/, float delay /*= 0.0f*/, EDelayType::DelayType delayType /*= first*/, ETickType::TickType tickType /*= seconds*/, float tickTypeValue /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, UCurveFloat* customEaseTypeCurve /*= nullptr*/, float punchAmplitude /*= 1.0f*/, ELoopType::LoopType loopType /*= once*/, int32 maximumLoopSections, UObject* onTweenStartTarget /*= nullptr*/, FString OnTweenStartFunctionName /*= ""*/, UObject* onTweenUpdateTarget /*= nullptr*/, FString OnTweenUpdateFunctionName /*= ""*/, UObject* onTweenLoopTarget /*= nullptr*/, FString OnTweenLoopFunctionName /*= ""*/, UObject* onTweenCompleteTarget /*= nullptr*/, FString OnTweenCompleteFunctionName /*= ""*/, bool tickWhenPaused /*= false*/, bool ignoreTimeDilation /*= false*/, bool destroySplineComponent, bool tieToObjectValidity, bool cullNonRenderedTweens, float secondsToWaitBeforeCull) { //Make sure we have a valid object to tween and a valid spline before proceeding if (componentToRotate && splineComponent) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::compRotateToSplinePoint; ie->timerInterval = timerInterval; ie->tweenName = tweenName; ie->componentTweening = componentToRotate; ie->splineComponent = splineComponent; ie->interpolateToSpline = rotateToPath; ie->enforceValueTo = enforceValueTo; ie->generatedPointDistance = generatedPointDistance; ie->rotatorConstraints = rotatorConstraints; ie->delay = delay; ie->delayType = delayType; ie->tickType = tickType; ie->tickTypeValue = tickTypeValue; ie->easeType = easeType; ie->customEaseTypeCurve = customEaseTypeCurve; ie->punchAmplitude = punchAmplitude; ie->loopType = loopType; ie->maximumLoopSections = maximumLoopSections; ie->onTweenStartTarget = onTweenStartTarget; ie->OnTweenStartFunctionName = OnTweenStartFunctionName; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->OnTweenUpdateFunctionName = OnTweenUpdateFunctionName; ie->onTweenLoopTarget = onTweenLoopTarget; ie->OnTweenLoopFunctionName = OnTweenLoopFunctionName; ie->onTweenCompleteTarget = onTweenCompleteTarget; ie->OnTweenCompleteFunctionName = OnTweenCompleteFunctionName; ie->tickWhenPaused = tickWhenPaused; ie->ignoreTimeDilation = ignoreTimeDilation; ie->destroySplineObject = destroySplineComponent; ie->tieToObjectValidity = tieToObjectValidity; ie->cullNonRenderedTweens = cullNonRenderedTweens; ie->secondsToWaitBeforeCull = secondsToWaitBeforeCull; //Initialize Event ie->InitEvent(); return ie; } else { if (!componentToRotate) { Print("No tweenable object defined. No tweening operation will occur.", "error"); } else if (!splineComponent) { Print("No spline defined. No tweening operation will occur.", "error"); } return nullptr; } } AiTweenEvent* UiTween::ComponentRotateToSplinePointSimple(FName tweenName /*= "No Name"*/, USceneComponent* componentToRotate /*= nullptr*/, USplineComponent* splineComponent /*= nullptr*/, bool rotateToPath /*= false*/, float generatedPointDistance /*= 100.f*/, float timeInSeconds /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, FString parameters, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget /*= nullptr*/, bool destroySplineComponent) { //Make sure we have a valid object to tween and a valid spline before proceeding if (componentToRotate && splineComponent) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::compRotateToSplinePoint; ie->tweenName = tweenName; ie->componentTweening = componentToRotate; ie->splineComponent = splineComponent; ie->interpolateToSpline = rotateToPath; ie->generatedPointDistance = generatedPointDistance; ie->tickTypeValue = timeInSeconds; ie->easeType = easeType; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; ie->destroySplineObject = destroySplineComponent; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event ie->InitEvent(); return ie; } else { if (!componentToRotate) { Print("No tweenable object defined. No tweening operation will occur.", "error"); } else if (!splineComponent) { Print("No spline defined. No tweening operation will occur.", "error"); } return nullptr; } } AiTweenEvent* UiTween::ComponentRotateToSplinePointExpert(USceneComponent* componentToRotate /*= nullptr*/, USplineComponent* splineComponent /*= nullptr*/, FString parameters, bool initializeOnSpawn, UCurveFloat* customEaseTypeCurve /*= nullptr*/, UObject* orientationTarget /*= nullptr*/, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget) { //Make sure we have a valid object to tween and a valid spline before proceeding if (componentToRotate && splineComponent) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::compRotateToSplinePoint; ie->componentTweening = componentToRotate; ie->splineComponent = splineComponent; ie->customEaseTypeCurve = customEaseTypeCurve; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { if (!componentToRotate) { Print("No tweenable object defined. No tweening operation will occur.", "error"); } else if (!splineComponent) { Print("No spline defined. No tweening operation will occur.", "error"); } return nullptr; } } AiTweenEvent* UiTween::ComponentRotateToSplinePointMin(USceneComponent* componentToRotate /*= nullptr*/, USplineComponent* splineComponent /*= nullptr*/, FString parameters, bool initializeOnSpawn) { //Make sure we have a valid object to tween and a valid spline before proceeding if (componentToRotate && splineComponent) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::compRotateToSplinePoint; ie->componentTweening = componentToRotate; ie->splineComponent = splineComponent; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { if (!componentToRotate) { Print("No tweenable object defined. No tweening operation will occur.", "error"); } else if (!splineComponent) { Print("No spline defined. No tweening operation will occur.", "error"); } return nullptr; } } //Component Rotate Update void UiTween::ComponentRotateUpdate(USceneComponent* componentToRotate, FRotator rotationTo, float delta, float speed, bool isLocal, ERotatorConstraints::RotatorConstraints rotatorConstraints) { //Make sure we have a valid object to tween before proceeding if (componentToRotate) { if (isLocal && componentToRotate->GetOwner()) { rotationTo = FRotator(FQuat(componentToRotate->GetOwner()->GetActorRotation()) * FQuat(rotationTo)); } componentToRotate->SetWorldRotation(ConstrainRotator(FMath::RInterpTo(componentToRotate->GetComponentRotation(), rotationTo, delta, speed), componentToRotate->GetComponentRotation(), rotatorConstraints)); } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); } } //Component Scale From/To AiTweenEvent* UiTween::ComponentScaleFromToFull(float timerInterval, FName tweenName /*= "No Name"*/, USceneComponent* componentToScale /*= nullptr*/, FVector scaleFrom /*= FVector::ZeroVector*/, FVector scaleTo /*= FVector(1, 1, 1)*/, bool enforceValueTo, EVectorConstraints::VectorConstraints vectorConstraints /*= VectorConstraints::none*/, bool isLocal, float delay /*= 0.0f*/, EDelayType::DelayType delayType /*= first*/, ETickType::TickType tickType /*= seconds*/, float tickTypeValue /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, UCurveFloat* customEaseTypeCurve /*= nullptr*/, float punchAmplitude /*= 1.0f*/, ELoopType::LoopType loopType /*= once*/, int32 maximumLoopSections, UObject* onTweenStartTarget /*= nullptr*/, FString OnTweenStartFunctionName /*= ""*/, UObject* onTweenUpdateTarget /*= nullptr*/, FString OnTweenUpdateFunctionName /*= ""*/, UObject* onTweenLoopTarget /*= nullptr*/, FString OnTweenLoopFunctionName /*= ""*/, UObject* onTweenCompleteTarget /*= nullptr*/, FString OnTweenCompleteFunctionName /*= ""*/, bool tickWhenPaused /*= false*/, bool ignoreTimeDilation /*= false*/, bool tieToObjectValidity, bool cullNonRenderedTweens, float secondsToWaitBeforeCull) { //Make sure we have a valid object to tween before proceeding if (componentToScale) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::compScaleFromTo; ie->timerInterval = timerInterval; ie->tweenName = tweenName; ie->componentTweening = componentToScale; ie->vectorFrom = scaleFrom; ie->vectorTo = scaleTo; ie->enforceValueTo = enforceValueTo; ie->vectorConstraints = vectorConstraints; if (isLocal) { ie->coordinateSpace = CoordinateSpace::parent; } ie->delay = delay; ie->delayType = delayType; ie->tickType = tickType; ie->tickTypeValue = tickTypeValue; ie->easeType = easeType; ie->customEaseTypeCurve = customEaseTypeCurve; ie->punchAmplitude = punchAmplitude; ie->loopType = loopType; ie->maximumLoopSections = maximumLoopSections; ie->onTweenStartTarget = onTweenStartTarget; ie->OnTweenStartFunctionName = OnTweenStartFunctionName; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->OnTweenUpdateFunctionName = OnTweenUpdateFunctionName; ie->onTweenLoopTarget = onTweenLoopTarget; ie->OnTweenLoopFunctionName = OnTweenLoopFunctionName; ie->onTweenCompleteTarget = onTweenCompleteTarget; ie->OnTweenCompleteFunctionName = OnTweenCompleteFunctionName; ie->tickWhenPaused = tickWhenPaused; ie->ignoreTimeDilation = ignoreTimeDilation; ie->tieToObjectValidity = tieToObjectValidity; ie->cullNonRenderedTweens = cullNonRenderedTweens; ie->secondsToWaitBeforeCull = secondsToWaitBeforeCull; //Initialize Event ie->InitEvent(); return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::ComponentScaleFromToSimple(FName tweenName /*= "No Name"*/, USceneComponent* componentToScale /*= nullptr*/, FVector scaleFrom /*= FVector::ZeroVector*/, FVector scaleTo /*= FVector(1, 1, 1)*/, bool isLocal, float timeInSeconds /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, FString parameters, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget /*= nullptr*/) { //Make sure we have a valid object to tween before proceeding if (componentToScale) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::compScaleFromTo; ie->tweenName = tweenName; ie->componentTweening = componentToScale; ie->vectorFrom = scaleFrom; ie->vectorTo = scaleTo; if (isLocal) { ie->coordinateSpace = CoordinateSpace::parent; } ie->tickTypeValue = timeInSeconds; ie->easeType = easeType; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event ie->InitEvent(); return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::ComponentScaleFromToExpert(USceneComponent* componentToScale /*= nullptr*/, FString parameters, bool initializeOnSpawn, UCurveFloat* customEaseTypeCurve /*= nullptr*/, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget) { //Make sure we have a valid object to tween before proceeding if (componentToScale) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::compScaleFromTo; ie->componentTweening = componentToScale; ie->customEaseTypeCurve = customEaseTypeCurve; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::ComponentScaleFromToMin(USceneComponent* componentToScale /*= nullptr*/, FString parameters, bool initializeOnSpawn) { //Make sure we have a valid object to tween before proceeding if (componentToScale) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::compScaleFromTo; ie->componentTweening = componentToScale; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } //Component Scale Update void UiTween::ComponentScaleUpdate(USceneComponent* componentToScale, FVector scaleTo, float delta, float speed, bool isLocal, EVectorConstraints::VectorConstraints vectorConstraints) { //Make sure we have a valid object to tween before proceeding if (componentToScale) { if (isLocal && componentToScale->GetOwner()) { scaleTo = componentToScale->GetOwner()->GetActorScale3D() * scaleTo; } componentToScale->SetWorldScale3D(ConstrainVector(FMath::VInterpTo(componentToScale->GetComponentScale(), scaleTo, delta, speed), componentToScale->GetComponentScale(), vectorConstraints)); } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); } } //UMG RT //UMG RT Move From/To AiTweenEvent* UiTween::UMGRTMoveFromToFull(float timerInterval, FName tweenName /*= "No Name"*/, UWidget* widgetToMove /*= nullptr*/, FVector2D locationFrom /*= FVector2D::ZeroVector*/, FVector2D locationTo /*= FVector2D::ZeroVector*/, bool enforceValueTo, EVector2DConstraints::Vector2DConstraints vector2DConstraints /*= Vector2DConstraints::none*/, float delay /*= 0.0f*/, EDelayType::DelayType delayType /*= first*/, ETickType::TickType tickType /*= seconds*/, float tickTypeValue /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, UCurveFloat* customEaseTypeCurve /*= nullptr*/, float punchAmplitude /*= 1.0f*/, ELoopType::LoopType loopType /*= once*/, int32 maximumLoopSections, /*ELookType::LookType orientation, UObject* orientationTarget, float orientationSpeed, */UObject* onTweenStartTarget /*= nullptr*/, FString OnTweenStartFunctionName /*= ""*/, UObject* onTweenUpdateTarget /*= nullptr*/, FString OnTweenUpdateFunctionName /*= ""*/, UObject* onTweenLoopTarget /*= nullptr*/, FString OnTweenLoopFunctionName /*= ""*/, UObject* onTweenCompleteTarget /*= nullptr*/, FString OnTweenCompleteFunctionName /*= ""*/, bool tickWhenPaused /*= false*/, bool ignoreTimeDilation /*= false*/, bool tieToObjectValidity) { //Make sure we have a valid object to tween before proceeding if (widgetToMove) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::umgRTMoveFromTo; ie->timerInterval = timerInterval; ie->tweenName = tweenName; ie->widgetTweening = widgetToMove; ie->vector2DFrom = locationFrom; ie->vector2DTo = locationTo; ie->enforceValueTo = enforceValueTo; ie->vector2DConstraints = vector2DConstraints; ie->delay = delay; ie->delayType = delayType; ie->tickType = tickType; ie->tickTypeValue = tickTypeValue; ie->easeType = easeType; ie->customEaseTypeCurve = customEaseTypeCurve; ie->punchAmplitude = punchAmplitude; ie->loopType = loopType; ie->maximumLoopSections = maximumLoopSections; //ie->orientation = orientation; //ie->orientationTarget = orientationTarget; //ie->orientationSpeed = orientationSpeed; ie->onTweenStartTarget = onTweenStartTarget; ie->OnTweenStartFunctionName = OnTweenStartFunctionName; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->OnTweenUpdateFunctionName = OnTweenUpdateFunctionName; ie->onTweenLoopTarget = onTweenLoopTarget; ie->OnTweenLoopFunctionName = OnTweenLoopFunctionName; ie->onTweenCompleteTarget = onTweenCompleteTarget; ie->OnTweenCompleteFunctionName = OnTweenCompleteFunctionName; ie->tickWhenPaused = tickWhenPaused; ie->ignoreTimeDilation = ignoreTimeDilation; ie->tieToObjectValidity = tieToObjectValidity; //Initialize Event ie->InitEvent(); return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::UMGRTMoveFromToSimple(FName tweenName /*= "No Name"*/, UWidget* widgetToMove /*= nullptr*/, FVector2D locationFrom /*= FVector2D::ZeroVector*/, FVector2D locationTo /*= FVector2D::ZeroVector*/, float timeInSeconds /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, FString parameters, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget /*= nullptr*/) { //Make sure we have a valid object to tween before proceeding if (widgetToMove) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::umgRTMoveFromTo; ie->tweenName = tweenName; ie->widgetTweening = widgetToMove; ie->vector2DFrom = locationFrom; ie->vector2DTo = locationTo; ie->tickTypeValue = timeInSeconds; ie->easeType = easeType; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event ie->InitEvent(); return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::UMGRTMoveFromToExpert(UWidget* widgetToMove /*= nullptr*/, FString parameters, bool initializeOnSpawn, UCurveFloat* customEaseTypeCurve /*= nullptr*/, /*UObject* orientationTarget = nullptr, */UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget) { //Make sure we have a valid object to tween before proceeding if (widgetToMove) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::umgRTMoveFromTo; ie->widgetTweening = widgetToMove; ie->customEaseTypeCurve = customEaseTypeCurve; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::UMGRTMoveFromToMin(UWidget* widgetToMove /*= nullptr*/, FString parameters, bool initializeOnSpawn) { //Make sure we have a valid object to tween before proceeding if (widgetToMove) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::umgRTMoveFromTo; ie->widgetTweening = widgetToMove; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } //UMG RT Move Update void UiTween::UMGRTMoveUpdate(UWidget* widgetToMove, FVector2D locationTo, float delta, float speed, EVector2DConstraints::Vector2DConstraints vector2DConstraints) { //Make sure we have a valid object to tween before proceeding if (widgetToMove) { FVector v = FMath::VInterpTo(FVector(widgetToMove->RenderTransform.Translation.X, widgetToMove->RenderTransform.Translation.Y, 0), FVector(locationTo.X, locationTo.Y, 0), delta, speed); widgetToMove->SetRenderTranslation(ConstrainVector2D(FVector2D(v.X, v.Y), widgetToMove->RenderTransform.Translation, vector2DConstraints)); //DevNote: Orientation logic when the time comes } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); } } //UMG RT Rotate From/To AiTweenEvent* UiTween::UMGRTRotateFromToFull(float timerInterval, FName tweenName /*= "No Name"*/, UWidget* widgetToRotate /*= nullptr*/, float angleFrom /*= 0*/, float angleTo /*= 90*/, bool enforceValueTo, float delay /*= 0.0f*/, EDelayType::DelayType delayType /*= first*/, ETickType::TickType tickType /*= seconds*/, float tickTypeValue /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, UCurveFloat* customEaseTypeCurve /*= nullptr*/, float punchAmplitude /*= 1.0f*/, ELoopType::LoopType loopType /*= once*/, int32 maximumLoopSections, UObject* onTweenStartTarget /*= nullptr*/, FString OnTweenStartFunctionName /*= ""*/, UObject* onTweenUpdateTarget /*= nullptr*/, FString OnTweenUpdateFunctionName /*= ""*/, UObject* onTweenLoopTarget /*= nullptr*/, FString OnTweenLoopFunctionName /*= ""*/, UObject* onTweenCompleteTarget /*= nullptr*/, FString OnTweenCompleteFunctionName /*= ""*/, bool tickWhenPaused /*= false*/, bool ignoreTimeDilation /*= false*/, bool tieToObjectValidity) { //Make sure we have a valid object to tween before proceeding if (widgetToRotate) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::umgRTRotateFromTo; ie->timerInterval = timerInterval; ie->tweenName = tweenName; ie->widgetTweening = widgetToRotate; ie->floatFrom = angleFrom; ie->floatTo = angleTo; ie->enforceValueTo = enforceValueTo; ie->delay = delay; ie->delayType = delayType; ie->tickType = tickType; ie->tickTypeValue = tickTypeValue; ie->easeType = easeType; ie->customEaseTypeCurve = customEaseTypeCurve; ie->punchAmplitude = punchAmplitude; ie->loopType = loopType; ie->maximumLoopSections = maximumLoopSections; ie->onTweenStartTarget = onTweenStartTarget; ie->OnTweenStartFunctionName = OnTweenStartFunctionName; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->OnTweenUpdateFunctionName = OnTweenUpdateFunctionName; ie->onTweenLoopTarget = onTweenLoopTarget; ie->OnTweenLoopFunctionName = OnTweenLoopFunctionName; ie->onTweenCompleteTarget = onTweenCompleteTarget; ie->OnTweenCompleteFunctionName = OnTweenCompleteFunctionName; ie->tickWhenPaused = tickWhenPaused; ie->ignoreTimeDilation = ignoreTimeDilation; ie->tieToObjectValidity = tieToObjectValidity; //Initialize Event ie->InitEvent(); return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::UMGRTRotateFromToSimple(FName tweenName /*= "No Name"*/, UWidget* widgetToRotate /*= nullptr*/, float angleFrom /*= 0*/, float angleTo /*= 90*/, float timeInSeconds /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, FString parameters, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget /*= nullptr*/) { //Make sure we have a valid object to tween before proceeding if (widgetToRotate) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::umgRTRotateFromTo; ie->tweenName = tweenName; ie->widgetTweening = widgetToRotate; ie->floatFrom = angleFrom; ie->floatTo = angleTo; ie->tickTypeValue = timeInSeconds; ie->easeType = easeType; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event ie->InitEvent(); return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::UMGRTRotateFromToExpert(UWidget* widgetToRotate /*= nullptr*/, FString parameters, bool initializeOnSpawn, UCurveFloat* customEaseTypeCurve /*= nullptr*/, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget) { //Make sure we have a valid object to tween before proceeding if (widgetToRotate) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::umgRTRotateFromTo; ie->widgetTweening = widgetToRotate; ie->customEaseTypeCurve = customEaseTypeCurve; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::UMGRTRotateFromToMin(UWidget* widgetToRotate /*= nullptr*/, FString parameters, bool initializeOnSpawn) { //Make sure we have a valid object to tween before proceeding if (widgetToRotate) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::umgRTRotateFromTo; ie->widgetTweening = widgetToRotate; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } //UMG RT Rotate Update void UiTween::UMGRTRotateUpdate(UWidget* widgetToRotate, float angleTo, float delta, float speed) { //Make sure we have a valid object to tween before proceeding if (widgetToRotate) { widgetToRotate->SetRenderTransformAngle(FMath::FInterpTo(widgetToRotate->RenderTransform.Angle, angleTo, delta, speed)); } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); } } //UMG RT Scale From/To AiTweenEvent* UiTween::UMGRTScaleFromToFull(float timerInterval, FName tweenName /*= "No Name"*/, UWidget* widgetToScale /*= nullptr*/, FVector2D scaleFrom /*= FVector2D(1,1)*/, FVector2D scaleTo /*= FVector2D(2,2)*/, bool enforceValueTo, EVector2DConstraints::Vector2DConstraints vector2DConstraints /*= Vector2DConstraints::none*/, float delay /*= 0.0f*/, EDelayType::DelayType delayType /*= first*/, ETickType::TickType tickType /*= seconds*/, float tickTypeValue /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, UCurveFloat* customEaseTypeCurve /*= nullptr*/, float punchAmplitude /*= 1.0f*/, ELoopType::LoopType loopType /*= once*/, int32 maximumLoopSections, UObject* onTweenStartTarget /*= nullptr*/, FString OnTweenStartFunctionName /*= ""*/, UObject* onTweenUpdateTarget /*= nullptr*/, FString OnTweenUpdateFunctionName /*= ""*/, UObject* onTweenLoopTarget /*= nullptr*/, FString OnTweenLoopFunctionName /*= ""*/, UObject* onTweenCompleteTarget /*= nullptr*/, FString OnTweenCompleteFunctionName /*= ""*/, bool tickWhenPaused /*= false*/, bool ignoreTimeDilation /*= false*/, bool tieToObjectValidity) { //Make sure we have a valid object to tween before proceeding if (widgetToScale) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::umgRTScaleFromTo; ie->timerInterval = timerInterval; ie->tweenName = tweenName; ie->widgetTweening = widgetToScale; ie->vector2DFrom = scaleFrom; ie->vector2DTo = scaleTo; ie->enforceValueTo = enforceValueTo; ie->vector2DConstraints = vector2DConstraints; ie->delay = delay; ie->delayType = delayType; ie->tickType = tickType; ie->tickTypeValue = tickTypeValue; ie->easeType = easeType; ie->customEaseTypeCurve = customEaseTypeCurve; ie->punchAmplitude = punchAmplitude; ie->loopType = loopType; ie->maximumLoopSections = maximumLoopSections; ie->onTweenStartTarget = onTweenStartTarget; ie->OnTweenStartFunctionName = OnTweenStartFunctionName; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->OnTweenUpdateFunctionName = OnTweenUpdateFunctionName; ie->onTweenLoopTarget = onTweenLoopTarget; ie->OnTweenLoopFunctionName = OnTweenLoopFunctionName; ie->onTweenCompleteTarget = onTweenCompleteTarget; ie->OnTweenCompleteFunctionName = OnTweenCompleteFunctionName; ie->tickWhenPaused = tickWhenPaused; ie->ignoreTimeDilation = ignoreTimeDilation; ie->tieToObjectValidity = tieToObjectValidity; //Initialize Event ie->InitEvent(); return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::UMGRTScaleFromToSimple(FName tweenName /*= "No Name"*/, UWidget* widgetToScale /*= nullptr*/, FVector2D scaleFrom /*= FVector2D(1, 1)*/, FVector2D scaleTo /*= FVector2D(2, 2)*/, float timeInSeconds /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, FString parameters, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget /*= nullptr*/) { //Make sure we have a valid object to tween before proceeding if (widgetToScale) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::umgRTScaleFromTo; ie->tweenName = tweenName; ie->widgetTweening = widgetToScale; ie->vector2DFrom = scaleFrom; ie->vector2DTo = scaleTo; ie->tickTypeValue = timeInSeconds; ie->easeType = easeType; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event ie->InitEvent(); return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::UMGRTScaleFromToExpert(UWidget* widgetToScale /*= nullptr*/, FString parameters, bool initializeOnSpawn, UCurveFloat* customEaseTypeCurve /*= nullptr*/, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget) { //Make sure we have a valid object to tween before proceeding if (widgetToScale) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::umgRTScaleFromTo; ie->widgetTweening = widgetToScale; ie->customEaseTypeCurve = customEaseTypeCurve; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::UMGRTScaleFromToMin(UWidget* widgetToScale /*= nullptr*/, FString parameters, bool initializeOnSpawn) { //Make sure we have a valid object to tween before proceeding if (widgetToScale) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::umgRTScaleFromTo; ie->widgetTweening = widgetToScale; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } //UMG RT Scale Update void UiTween::UMGRTScaleUpdate(UWidget* widgetToScale, FVector2D scaleTo, float delta, float speed, EVector2DConstraints::Vector2DConstraints vector2DConstraints) { //Make sure we have a valid object to tween before proceeding if (widgetToScale) { FVector v = FMath::VInterpTo(FVector(widgetToScale->RenderTransform.Scale.X, widgetToScale->RenderTransform.Scale.Y, 0), FVector(scaleTo.X, scaleTo.Y, 0), delta, speed); widgetToScale->SetRenderScale(ConstrainVector2D(FVector2D(v.X, v.Y), widgetToScale->RenderTransform.Scale, vector2DConstraints)); } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); } } //UMG RT Shear From/To AiTweenEvent* UiTween::UMGRTShearFromToFull(float timerInterval, FName tweenName /*= "No Name"*/, UWidget* widgetToShear /*= nullptr*/, FVector2D shearFrom /*= FVector2D(1, 1)*/, FVector2D shearTo /*= FVector2D(2, 2)*/, bool enforceValueTo, EVector2DConstraints::Vector2DConstraints vector2DConstraints /*= Vector2DConstraints::none*/, float delay /*= 0.0f*/, EDelayType::DelayType delayType /*= first*/, ETickType::TickType tickType /*= seconds*/, float tickTypeValue /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, UCurveFloat* customEaseTypeCurve /*= nullptr*/, float punchAmplitude /*= 1.0f*/, ELoopType::LoopType loopType /*= once*/, int32 maximumLoopSections, UObject* onTweenStartTarget /*= nullptr*/, FString OnTweenStartFunctionName /*= ""*/, UObject* onTweenUpdateTarget /*= nullptr*/, FString OnTweenUpdateFunctionName /*= ""*/, UObject* onTweenLoopTarget /*= nullptr*/, FString OnTweenLoopFunctionName /*= ""*/, UObject* onTweenCompleteTarget /*= nullptr*/, FString OnTweenCompleteFunctionName /*= ""*/, bool tickWhenPaused /*= false*/, bool ignoreTimeDilation /*= false*/, bool tieToObjectValidity) { //Make sure we have a valid object to tween before proceeding if (widgetToShear) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::umgRTShearFromTo; ie->timerInterval = timerInterval; ie->tweenName = tweenName; ie->widgetTweening = widgetToShear; ie->vector2DFrom = shearFrom; ie->vector2DTo = shearTo; ie->enforceValueTo = enforceValueTo; ie->vector2DConstraints = vector2DConstraints; ie->delay = delay; ie->delayType = delayType; ie->tickType = tickType; ie->tickTypeValue = tickTypeValue; ie->easeType = easeType; ie->customEaseTypeCurve = customEaseTypeCurve; ie->punchAmplitude = punchAmplitude; ie->loopType = loopType; ie->maximumLoopSections = maximumLoopSections; ie->onTweenStartTarget = onTweenStartTarget; ie->OnTweenStartFunctionName = OnTweenStartFunctionName; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->OnTweenUpdateFunctionName = OnTweenUpdateFunctionName; ie->onTweenLoopTarget = onTweenLoopTarget; ie->OnTweenLoopFunctionName = OnTweenLoopFunctionName; ie->onTweenCompleteTarget = onTweenCompleteTarget; ie->OnTweenCompleteFunctionName = OnTweenCompleteFunctionName; ie->tickWhenPaused = tickWhenPaused; ie->ignoreTimeDilation = ignoreTimeDilation; ie->tieToObjectValidity = tieToObjectValidity; //Initialize Event ie->InitEvent(); return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::UMGRTShearFromToSimple(FName tweenName /*= "No Name"*/, UWidget* widgetToShear /*= nullptr*/, FVector2D shearFrom /*= FVector2D(1, 1)*/, FVector2D shearTo /*= FVector2D(2, 2)*/, float timeInSeconds /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, FString parameters, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget /*= nullptr*/) { //Make sure we have a valid object to tween before proceeding if (widgetToShear) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::umgRTShearFromTo; ie->tweenName = tweenName; ie->widgetTweening = widgetToShear; ie->vector2DFrom = shearFrom; ie->vector2DTo = shearTo; ie->tickTypeValue = timeInSeconds; ie->easeType = easeType; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event ie->InitEvent(); return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::UMGRTShearFromToExpert(UWidget* widgetToShear /*= nullptr*/, FString parameters, bool initializeOnSpawn, UCurveFloat* customEaseTypeCurve /*= nullptr*/, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget) { //Make sure we have a valid object to tween before proceeding if (widgetToShear) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::umgRTShearFromTo; ie->widgetTweening = widgetToShear; ie->customEaseTypeCurve = customEaseTypeCurve; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::UMGRTShearFromToMin(UWidget* widgetToShear /*= nullptr*/, FString parameters, bool initializeOnSpawn) { //Make sure we have a valid object to tween before proceeding if (widgetToShear) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::umgRTShearFromTo; ie->widgetTweening = widgetToShear; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } //UMG RT Shear Update void UiTween::UMGRTShearUpdate(UWidget* widgetToShear, FVector2D shearTo, float delta, float speed, EVector2DConstraints::Vector2DConstraints vector2DConstraints) { //Make sure we have a valid object to tween before proceeding if (widgetToShear) { FVector v = FMath::VInterpTo(FVector(widgetToShear->RenderTransform.Shear.X, widgetToShear->RenderTransform.Shear.Y, 0), FVector(shearTo.X, shearTo.Y, 0), delta, speed); widgetToShear->SetRenderShear(ConstrainVector2D(FVector2D(v.X, v.Y), widgetToShear->RenderTransform.Shear, vector2DConstraints)); } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); } } //Data Type //Float From/To AiTweenEvent* UiTween::FloatFromToFull(float timerInterval, FName tweenName /*= "No Name"*/, float startValue /*= 0.f*/, float endValue /*= 1.f*/, bool enforceValueTo, float delay /*= 0.0f*/, EDelayType::DelayType delayType /*= first*/, ETickType::TickType tickType /*= seconds*/, float tickTypeValue /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, UCurveFloat* customEaseTypeCurve /*= nullptr*/, float punchAmplitude /*= 1.0f*/, ELoopType::LoopType loopType /*= once*/, int32 maximumLoopSections, UObject* onTweenStartTarget /*= nullptr*/, FString OnTweenStartFunctionName /*= ""*/, UObject* onTweenUpdateTarget /*= nullptr*/, FString OnTweenUpdateFunctionName /*= ""*/, UObject* onTweenLoopTarget /*= nullptr*/, FString OnTweenLoopFunctionName /*= ""*/, UObject* onTweenCompleteTarget /*= nullptr*/, FString OnTweenCompleteFunctionName /*= ""*/, bool tickWhenPaused /*= false*/, bool ignoreTimeDilation /*= false*/) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::floatFromTo; ie->timerInterval = timerInterval; ie->tweenName = tweenName; ie->floatFrom = startValue; ie->floatTo = endValue; ie->enforceValueTo = enforceValueTo; ie->delay = delay; ie->delayType = delayType; ie->tickType = tickType; ie->tickTypeValue = tickTypeValue; ie->easeType = easeType; ie->customEaseTypeCurve = customEaseTypeCurve; ie->punchAmplitude = punchAmplitude; ie->loopType = loopType; ie->maximumLoopSections = maximumLoopSections; ie->onTweenStartTarget = onTweenStartTarget; ie->OnTweenStartFunctionName = OnTweenStartFunctionName; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->OnTweenUpdateFunctionName = OnTweenUpdateFunctionName; ie->onTweenLoopTarget = onTweenLoopTarget; ie->OnTweenLoopFunctionName = OnTweenLoopFunctionName; ie->onTweenCompleteTarget = onTweenCompleteTarget; ie->OnTweenCompleteFunctionName = OnTweenCompleteFunctionName; ie->tickWhenPaused = tickWhenPaused; ie->ignoreTimeDilation = ignoreTimeDilation; //Initialize Event ie->InitEvent(); return ie; } AiTweenEvent* UiTween::FloatFromToSimple(FName tweenName /*= "No Name"*/, float startValue /*= 0.f*/, float endValue /*= 1.f*/, float timeInSeconds /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, FString parameters, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget /*= nullptr*/) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::floatFromTo; ie->tweenName = tweenName; ie->floatFrom = startValue; ie->floatTo = endValue; ie->tickTypeValue = timeInSeconds; ie->easeType = easeType; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event ie->InitEvent(); return ie; } AiTweenEvent* UiTween::FloatFromToExpert(FString parameters, bool initializeOnSpawn, UCurveFloat* customEaseTypeCurve /*= nullptr*/, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::floatFromTo; ie->customEaseTypeCurve = customEaseTypeCurve; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } AiTweenEvent* UiTween::FloatFromToMin(FString parameters, bool initializeOnSpawn) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::floatFromTo; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } //Vector From/To AiTweenEvent* UiTween::VectorFromToFull(float timerInterval, FName tweenName /*= "No Name"*/, FVector startValue /*= FVector::ZeroVector*/, FVector endValue /*= FVector::ZeroVector*/, bool enforceValueTo, EVectorConstraints::VectorConstraints vectorConstraints/*= VectorConstraints::none*/, float delay /*= 0.0f*/, EDelayType::DelayType delayType /*= first*/, ETickType::TickType tickType /*= seconds*/, float tickTypeValue /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, UCurveFloat* customEaseTypeCurve /*= nullptr*/, float punchAmplitude /*= 1.0f*/, ELoopType::LoopType loopType /*= once*/, int32 maximumLoopSections, UObject* onTweenStartTarget /*= nullptr*/, FString OnTweenStartFunctionName /*= ""*/, UObject* onTweenUpdateTarget /*= nullptr*/, FString OnTweenUpdateFunctionName /*= ""*/, UObject* onTweenLoopTarget /*= nullptr*/, FString OnTweenLoopFunctionName /*= ""*/, UObject* onTweenCompleteTarget /*= nullptr*/, FString OnTweenCompleteFunctionName /*= ""*/, bool tickWhenPaused /*= false*/, bool ignoreTimeDilation /*= false*/) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::vectorFromTo; ie->timerInterval = timerInterval; ie->tweenName = tweenName; ie->vectorFrom = startValue; ie->vectorTo = endValue; ie->enforceValueTo = enforceValueTo; ie->vectorConstraints = vectorConstraints; ie->delay = delay; ie->delayType = delayType; ie->tickType = tickType; ie->tickTypeValue = tickTypeValue; ie->easeType = easeType; ie->customEaseTypeCurve = customEaseTypeCurve; ie->punchAmplitude = punchAmplitude; ie->loopType = loopType; ie->maximumLoopSections = maximumLoopSections; ie->onTweenStartTarget = onTweenStartTarget; ie->OnTweenStartFunctionName = OnTweenStartFunctionName; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->OnTweenUpdateFunctionName = OnTweenUpdateFunctionName; ie->onTweenLoopTarget = onTweenLoopTarget; ie->OnTweenLoopFunctionName = OnTweenLoopFunctionName; ie->onTweenCompleteTarget = onTweenCompleteTarget; ie->OnTweenCompleteFunctionName = OnTweenCompleteFunctionName; ie->tickWhenPaused = tickWhenPaused; ie->ignoreTimeDilation = ignoreTimeDilation; //Initialize Event ie->InitEvent(); return ie; } AiTweenEvent* UiTween::VectorFromToSimple(FName tweenName /*= "No Name"*/, FVector startValue /*= FVector::ZeroVector*/, FVector endValue /*= FVector::ZeroVector*/, float timeInSeconds /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, FString parameters, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget /*= nullptr*/) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::vectorFromTo; ie->tweenName = tweenName; ie->vectorFrom = startValue; ie->vectorTo = endValue; ie->tickTypeValue = timeInSeconds; ie->easeType = easeType; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event ie->InitEvent(); return ie; } AiTweenEvent* UiTween::VectorFromToExpert(FString parameters, bool initializeOnSpawn, UCurveFloat* customEaseTypeCurve /*= nullptr*/, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::vectorFromTo; ie->customEaseTypeCurve = customEaseTypeCurve; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } AiTweenEvent* UiTween::VectorFromToMin(FString parameters, bool initializeOnSpawn) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::vectorFromTo; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } //Vector2D From/To AiTweenEvent* UiTween::Vector2DFromToFull(float timerInterval, FName tweenName /*= "No Name"*/, FVector2D startValue /*= FVector2D::ZeroVector*/, FVector2D endValue /*= FVector2D::ZeroVector*/, bool enforceValueTo, EVector2DConstraints::Vector2DConstraints vector2DConstraints /*= Vector2DConstraints::none*/, float delay /*= 0.0f*/, EDelayType::DelayType delayType /*= first*/, ETickType::TickType tickType /*= seconds*/, float tickTypeValue /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, UCurveFloat* customEaseTypeCurve /*= nullptr*/, float punchAmplitude /*= 1.0f*/, ELoopType::LoopType loopType /*= once*/, int32 maximumLoopSections, UObject* onTweenStartTarget /*= nullptr*/, FString OnTweenStartFunctionName /*= ""*/, UObject* onTweenUpdateTarget /*= nullptr*/, FString OnTweenUpdateFunctionName /*= ""*/, UObject* onTweenLoopTarget /*= nullptr*/, FString OnTweenLoopFunctionName /*= ""*/, UObject* onTweenCompleteTarget /*= nullptr*/, FString OnTweenCompleteFunctionName /*= ""*/, bool tickWhenPaused /*= false*/, bool ignoreTimeDilation /*= false*/) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::vector2DFromTo; ie->timerInterval = timerInterval; ie->tweenName = tweenName; ie->vector2DFrom = startValue; ie->vector2DTo = endValue; ie->enforceValueTo = enforceValueTo; ie->vector2DConstraints = vector2DConstraints; ie->delay = delay; ie->delayType = delayType; ie->tickType = tickType; ie->tickTypeValue = tickTypeValue; ie->easeType = easeType; ie->customEaseTypeCurve = customEaseTypeCurve; ie->punchAmplitude = punchAmplitude; ie->loopType = loopType; ie->maximumLoopSections = maximumLoopSections; ie->onTweenStartTarget = onTweenStartTarget; ie->OnTweenStartFunctionName = OnTweenStartFunctionName; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->OnTweenUpdateFunctionName = OnTweenUpdateFunctionName; ie->onTweenLoopTarget = onTweenLoopTarget; ie->OnTweenLoopFunctionName = OnTweenLoopFunctionName; ie->onTweenCompleteTarget = onTweenCompleteTarget; ie->OnTweenCompleteFunctionName = OnTweenCompleteFunctionName; ie->tickWhenPaused = tickWhenPaused; ie->ignoreTimeDilation = ignoreTimeDilation; //Initialize Event ie->InitEvent(); return ie; } AiTweenEvent* UiTween::Vector2DFromToSimple(FName tweenName /*= "No Name"*/, FVector2D startValue /*= FVector2D::ZeroVector*/, FVector2D endValue /*= FVector2D::ZeroVector*/, float timeInSeconds /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, FString parameters, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget /*= nullptr*/) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::vector2DFromTo; ie->tweenName = tweenName; ie->vector2DFrom = startValue; ie->vector2DTo = endValue; ie->tickTypeValue = timeInSeconds; ie->easeType = easeType; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event ie->InitEvent(); return ie; } AiTweenEvent* UiTween::Vector2DFromToExpert(FString parameters, bool initializeOnSpawn, UCurveFloat* customEaseTypeCurve /*= nullptr*/, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::vector2DFromTo; ie->customEaseTypeCurve = customEaseTypeCurve; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } AiTweenEvent* UiTween::Vector2DFromToMin(FString parameters, bool initializeOnSpawn) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::vector2DFromTo; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } //Rotator From/To AiTweenEvent* UiTween::RotatorFromToFull(float timerInterval, FName tweenName /*= "No Name"*/, FRotator startValue /*= FRotator::ZeroRotator*/, FRotator endValue /*= FRotator::ZeroRotator*/, bool enforceValueTo, ERotatorConstraints::RotatorConstraints rotatorConstraints /*= RotatorConstraints::none*/, bool shortestPath, float delay /*= 0.0f*/, EDelayType::DelayType delayType /*= first*/, ETickType::TickType tickType /*= seconds*/, float tickTypeValue /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, UCurveFloat* customEaseTypeCurve /*= nullptr*/, float punchAmplitude /*= 1.0f*/, ELoopType::LoopType loopType /*= once*/, int32 maximumLoopSections, UObject* onTweenStartTarget /*= nullptr*/, FString OnTweenStartFunctionName /*= ""*/, UObject* onTweenUpdateTarget /*= nullptr*/, FString OnTweenUpdateFunctionName /*= ""*/, UObject* onTweenLoopTarget /*= nullptr*/, FString OnTweenLoopFunctionName /*= ""*/, UObject* onTweenCompleteTarget /*= nullptr*/, FString OnTweenCompleteFunctionName /*= ""*/, bool tickWhenPaused /*= false*/, bool ignoreTimeDilation /*= false*/) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::rotatorFromTo; ie->timerInterval = timerInterval; ie->tweenName = tweenName; ie->rotatorFrom = startValue; ie->rotatorTo = endValue; ie->enforceValueTo = enforceValueTo; ie->rotatorConstraints = rotatorConstraints; ie->shortestPath = shortestPath; ie->delay = delay; ie->delayType = delayType; ie->tickType = tickType; ie->tickTypeValue = tickTypeValue; ie->easeType = easeType; ie->customEaseTypeCurve = customEaseTypeCurve; ie->punchAmplitude = punchAmplitude; ie->loopType = loopType; ie->maximumLoopSections = maximumLoopSections; ie->onTweenStartTarget = onTweenStartTarget; ie->OnTweenStartFunctionName = OnTweenStartFunctionName; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->OnTweenUpdateFunctionName = OnTweenUpdateFunctionName; ie->onTweenLoopTarget = onTweenLoopTarget; ie->OnTweenLoopFunctionName = OnTweenLoopFunctionName; ie->onTweenCompleteTarget = onTweenCompleteTarget; ie->OnTweenCompleteFunctionName = OnTweenCompleteFunctionName; ie->tickWhenPaused = tickWhenPaused; ie->ignoreTimeDilation = ignoreTimeDilation; //Initialize Event ie->InitEvent(); return ie; } AiTweenEvent* UiTween::RotatorFromToSimple(FName tweenName /*= "No Name"*/, FRotator startValue /*= FRotator::ZeroRotator*/, FRotator endValue /*= FRotator::ZeroRotator*/, bool shortestPath, float timeInSeconds /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, FString parameters, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget /*= nullptr*/) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::rotatorFromTo; ie->tweenName = tweenName; ie->rotatorFrom = startValue; ie->rotatorTo = endValue; ie->shortestPath = shortestPath; ie->tickTypeValue = timeInSeconds; ie->easeType = easeType; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event ie->InitEvent(); return ie; } AiTweenEvent* UiTween::RotatorFromToExpert(FString parameters, bool initializeOnSpawn, UCurveFloat* customEaseTypeCurve /*= nullptr*/, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::rotatorFromTo; ie->customEaseTypeCurve = customEaseTypeCurve; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } AiTweenEvent* UiTween::RotatorFromToMin(FString parameters, bool initializeOnSpawn) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::rotatorFromTo; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } //Linear Color From/To AiTweenEvent* UiTween::LinearColorFromToFull(float timerInterval, FName tweenName /*= "No Name"*/, FLinearColor startValue /*= FLinearColor::White*/, FLinearColor endValue /*= FLinearColor::Black*/, bool enforceValueTo, float delay /*= 0.0f*/, EDelayType::DelayType delayType /*= first*/, ETickType::TickType tickType /*= seconds*/, float tickTypeValue /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, UCurveFloat* customEaseTypeCurve /*= nullptr*/, float punchAmplitude /*= 1.0f*/, ELoopType::LoopType loopType /*= once*/, int32 maximumLoopSections, UObject* onTweenStartTarget /*= nullptr*/, FString OnTweenStartFunctionName /*= ""*/, UObject* onTweenUpdateTarget /*= nullptr*/, FString OnTweenUpdateFunctionName /*= ""*/, UObject* onTweenLoopTarget /*= nullptr*/, FString OnTweenLoopFunctionName /*= ""*/, UObject* onTweenCompleteTarget /*= nullptr*/, FString OnTweenCompleteFunctionName /*= ""*/, bool tickWhenPaused /*= false*/, bool ignoreTimeDilation /*= false*/) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::linearColorFromTo; ie->timerInterval = timerInterval; ie->tweenName = tweenName; ie->linearColorFrom = startValue; ie->linearColorTo = endValue; ie->enforceValueTo = enforceValueTo; ie->delay = delay; ie->delayType = delayType; ie->tickType = tickType; ie->tickTypeValue = tickTypeValue; ie->easeType = easeType; ie->customEaseTypeCurve = customEaseTypeCurve; ie->punchAmplitude = punchAmplitude; ie->loopType = loopType; ie->maximumLoopSections = maximumLoopSections; ie->onTweenStartTarget = onTweenStartTarget; ie->OnTweenStartFunctionName = OnTweenStartFunctionName; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->OnTweenUpdateFunctionName = OnTweenUpdateFunctionName; ie->onTweenLoopTarget = onTweenLoopTarget; ie->OnTweenLoopFunctionName = OnTweenLoopFunctionName; ie->onTweenCompleteTarget = onTweenCompleteTarget; ie->OnTweenCompleteFunctionName = OnTweenCompleteFunctionName; ie->tickWhenPaused = tickWhenPaused; ie->ignoreTimeDilation = ignoreTimeDilation; //Initialize Event ie->InitEvent(); return ie; } AiTweenEvent* UiTween::LinearColorFromToSimple(FName tweenName /*= "No Name"*/, FLinearColor startValue /*= FLinearColor::White*/, FLinearColor endValue /*= FLinearColor::Black*/, float timeInSeconds /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, FString parameters, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget /*= nullptr*/) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::linearColorFromTo; ie->tweenName = tweenName; ie->linearColorFrom = startValue; ie->linearColorTo = endValue; ie->tickTypeValue = timeInSeconds; ie->easeType = easeType; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event ie->InitEvent(); return ie; } AiTweenEvent* UiTween::LinearColorFromToExpert(FString parameters, bool initializeOnSpawn, UCurveFloat* customEaseTypeCurve /*= nullptr*/, UObject* onTweenStartTarget /*= nullptr*/, UObject* onTweenUpdateTarget /*= nullptr*/, UObject* onTweenLoopTarget /*= nullptr*/, UObject* onTweenCompleteTarget) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::linearColorFromTo; ie->customEaseTypeCurve = customEaseTypeCurve; ie->onTweenStartTarget = onTweenStartTarget; ie->onTweenUpdateTarget = onTweenUpdateTarget; ie->onTweenLoopTarget = onTweenLoopTarget; ie->onTweenCompleteTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } AiTweenEvent* UiTween::LinearColorFromToMin(FString parameters /*= ""*/, bool initializeOnSpawn /*= true*/) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::linearColorFromTo; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } //Data Type //Float From/To AiTweenEvent* UiTween::SlateFloatFromToFull(float timerInterval, FName tweenName /*= "No Name"*/, float startValue /*= 0.f*/, float endValue /*= 1.f*/, float delay /*= 0.0f*/, EDelayType::DelayType delayType /*= first*/, ETickType::TickType tickType /*= seconds*/, float tickTypeValue /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, UCurveFloat* customEaseTypeCurve /*= nullptr*/, float punchAmplitude /*= 1.0f*/, ELoopType::LoopType loopType /*= once*/, STweenableWidget* onTweenStartTarget /*= nullptr*/, STweenableWidget* onTweenTickTarget /*= nullptr*/, STweenableWidget* onTweenLoopTarget /*= nullptr*/, STweenableWidget* onTweenCompleteTarget /*= nullptr*/, bool tickWhenPaused /*= false*/, bool ignoreTimeDilation /*= false*/) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::floatFromTo; ie->tweenName = tweenName; ie->floatFrom = startValue; ie->floatTo = endValue; ie->delay = delay; ie->delayType = delayType; ie->tickType = tickType; ie->tickTypeValue = tickTypeValue; ie->easeType = easeType; ie->customEaseTypeCurve = customEaseTypeCurve; ie->punchAmplitude = punchAmplitude; ie->loopType = loopType; ie->onTweenStartSlateTarget = onTweenStartTarget; ie->onTweenTickSlateTarget = onTweenTickTarget; ie->onTweenLoopSlateTarget = onTweenLoopTarget; ie->onTweenCompleteSlateTarget = onTweenCompleteTarget; ie->tickWhenPaused = tickWhenPaused; ie->ignoreTimeDilation = ignoreTimeDilation; //Initialize Event ie->InitEvent(); return ie; } AiTweenEvent* UiTween::SlateFloatFromToSimple(FName tweenName /*= "No Name"*/, float startValue /*= 0.f*/, float endValue /*= 1.f*/, float timeInSeconds /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, FString parameters, STweenableWidget* onTweenStartTarget /*= nullptr*/, STweenableWidget* onTweenTickTarget /*= nullptr*/, STweenableWidget* onTweenCompleteTarget /*= nullptr*/) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::floatFromTo; ie->tweenName = tweenName; ie->floatFrom = startValue; ie->floatTo = endValue; ie->tickTypeValue = timeInSeconds; ie->easeType = easeType; ie->onTweenStartSlateTarget = onTweenStartTarget; ie->onTweenTickSlateTarget = onTweenTickTarget; ie->onTweenCompleteSlateTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event ie->InitEvent(); return ie; } AiTweenEvent* UiTween::SlateFloatFromToExpert(FString parameters, bool initializeOnSpawn, UCurveFloat* customEaseTypeCurve /*= nullptr*/, STweenableWidget* onTweenStartTarget /*= nullptr*/, STweenableWidget* onTweenTickTarget /*= nullptr*/, STweenableWidget* onTweenLoopTarget /*= nullptr*/, STweenableWidget* onTweenCompleteTarget) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::floatFromTo; ie->customEaseTypeCurve = customEaseTypeCurve; ie->onTweenStartSlateTarget = onTweenStartTarget; ie->onTweenTickSlateTarget = onTweenTickTarget; ie->onTweenLoopSlateTarget = onTweenLoopTarget; ie->onTweenCompleteSlateTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } //UMG RT //UMG RT Move From/To AiTweenEvent* UiTween::SlateMoveFromToFull(float timerInterval, FName tweenName /*= "No Name"*/, STweenableWidget* widgetToMove /*= nullptr*/, FVector2D locationFrom /*= FVector2D::ZeroVector*/, FVector2D locationTo /*= FVector2D::ZeroVector*/, EVector2DConstraints::Vector2DConstraints vector2DConstraints /*= Vector2DConstraints::none*/, float delay /*= 0.0f*/, EDelayType::DelayType delayType /*= first*/, ETickType::TickType tickType /*= seconds*/, float tickTypeValue /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, UCurveFloat* customEaseTypeCurve /*= nullptr*/, float punchAmplitude /*= 1.0f*/, ELoopType::LoopType loopType /*= once*/, /*ELookType::LookType orientation, STweenableWidget* orientationTarget, float orientationSpeed, */STweenableWidget* onTweenStartTarget /*= nullptr*/, STweenableWidget* onTweenTickTarget /*= nullptr*/, STweenableWidget* onTweenLoopTarget /*= nullptr*/, STweenableWidget* onTweenCompleteTarget /*= nullptr*/, bool tickWhenPaused /*= false*/, bool ignoreTimeDilation /*= false*/) { //Make sure we have a valid object to tween before proceeding if (widgetToMove) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::slateMoveFromTo; ie->tweenName = tweenName; ie->slateTweening = widgetToMove; ie->vector2DFrom = locationFrom; ie->vector2DTo = locationTo; ie->vector2DConstraints = vector2DConstraints; ie->delay = delay; ie->delayType = delayType; ie->tickType = tickType; ie->tickTypeValue = tickTypeValue; ie->easeType = easeType; ie->customEaseTypeCurve = customEaseTypeCurve; ie->punchAmplitude = punchAmplitude; ie->loopType = loopType; //ie->orientation = orientation; //ie->orientationTarget = orientationTarget; //ie->orientationSpeed = orientationSpeed; ie->onTweenStartSlateTarget = onTweenStartTarget; ie->onTweenTickSlateTarget = onTweenTickTarget; ie->onTweenLoopSlateTarget = onTweenLoopTarget; ie->onTweenCompleteSlateTarget = onTweenCompleteTarget; ie->tickWhenPaused = tickWhenPaused; ie->ignoreTimeDilation = ignoreTimeDilation; //Initialize Event ie->InitEvent(); return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::SlateMoveFromToSimple(FName tweenName /*= "No Name"*/, STweenableWidget* widgetToMove /*= nullptr*/, FVector2D locationFrom /*= FVector2D::ZeroVector*/, FVector2D locationTo /*= FVector2D::ZeroVector*/, float timeInSeconds /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, FString parameters, STweenableWidget* onTweenStartTarget /*= nullptr*/, STweenableWidget* onTweenTickTarget /*= nullptr*/, STweenableWidget* onTweenCompleteTarget /*= nullptr*/) { //Make sure we have a valid object to tween before proceeding if (widgetToMove) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::slateMoveFromTo; ie->tweenName = tweenName; ie->slateTweening = widgetToMove; ie->vector2DFrom = locationFrom; ie->vector2DTo = locationTo; ie->tickTypeValue = timeInSeconds; ie->easeType = easeType; ie->onTweenStartSlateTarget = onTweenStartTarget; ie->onTweenTickSlateTarget = onTweenTickTarget; ie->onTweenCompleteSlateTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event ie->InitEvent(); return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::SlateMoveFromToExpert(STweenableWidget* widgetToMove /*= nullptr*/, FString parameters, bool initializeOnSpawn, UCurveFloat* customEaseTypeCurve /*= nullptr*/, /*STweenableWidget* orientationTarget = nullptr, */STweenableWidget* onTweenStartTarget /*= nullptr*/, STweenableWidget* onTweenTickTarget /*= nullptr*/, STweenableWidget* onTweenLoopTarget /*= nullptr*/, STweenableWidget* onTweenCompleteTarget) { //Make sure we have a valid object to tween before proceeding if (widgetToMove) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::slateMoveFromTo; ie->slateTweening = widgetToMove; ie->customEaseTypeCurve = customEaseTypeCurve; ie->onTweenStartSlateTarget = onTweenStartTarget; ie->onTweenTickSlateTarget = onTweenTickTarget; ie->onTweenLoopSlateTarget = onTweenLoopTarget; ie->onTweenCompleteSlateTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } //UMG RT Scale From/To AiTweenEvent* UiTween::SlateScaleFromToFull(float timerInterval, FName tweenName /*= "No Name"*/, STweenableWidget* widgetToScale /*= nullptr*/, FVector2D scaleFrom /*= FVector2D(1,1)*/, FVector2D scaleTo /*= FVector2D(2,2)*/, EVector2DConstraints::Vector2DConstraints vector2DConstraints /*= Vector2DConstraints::none*/, float delay /*= 0.0f*/, EDelayType::DelayType delayType /*= first*/, ETickType::TickType tickType /*= seconds*/, float tickTypeValue /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, UCurveFloat* customEaseTypeCurve /*= nullptr*/, float punchAmplitude /*= 1.0f*/, ELoopType::LoopType loopType /*= once*/, STweenableWidget* onTweenStartTarget /*= nullptr*/, STweenableWidget* onTweenTickTarget /*= nullptr*/, STweenableWidget* onTweenLoopTarget /*= nullptr*/, STweenableWidget* onTweenCompleteTarget /*= nullptr*/, bool tickWhenPaused /*= false*/, bool ignoreTimeDilation /*= false*/) { //Make sure we have a valid object to tween before proceeding if (widgetToScale) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::slateScaleFromTo; ie->tweenName = tweenName; ie->slateTweening = widgetToScale; ie->vector2DFrom = scaleFrom; ie->vector2DTo = scaleTo; ie->vector2DConstraints = vector2DConstraints; ie->delay = delay; ie->delayType = delayType; ie->tickType = tickType; ie->tickTypeValue = tickTypeValue; ie->easeType = easeType; ie->customEaseTypeCurve = customEaseTypeCurve; ie->punchAmplitude = punchAmplitude; ie->loopType = loopType; ie->onTweenStartSlateTarget = onTweenStartTarget; ie->onTweenTickSlateTarget = onTweenTickTarget; ie->onTweenLoopSlateTarget = onTweenLoopTarget; ie->onTweenCompleteSlateTarget = onTweenCompleteTarget; ie->tickWhenPaused = tickWhenPaused; ie->ignoreTimeDilation = ignoreTimeDilation; //Initialize Event ie->InitEvent(); return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::SlateScaleFromToSimple(FName tweenName /*= "No Name"*/, STweenableWidget* widgetToScale /*= nullptr*/, FVector2D scaleFrom /*= FVector2D(1, 1)*/, FVector2D scaleTo /*= FVector2D(2, 2)*/, float timeInSeconds /*= 5.0f*/, EEaseType::EaseType easeType /*= linear*/, FString parameters, STweenableWidget* onTweenStartTarget /*= nullptr*/, STweenableWidget* onTweenTickTarget /*= nullptr*/, STweenableWidget* onTweenCompleteTarget /*= nullptr*/) { //Make sure we have a valid object to tween before proceeding if (widgetToScale) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::slateScaleFromTo; ie->tweenName = tweenName; ie->slateTweening = widgetToScale; ie->vector2DFrom = scaleFrom; ie->vector2DTo = scaleTo; ie->tickTypeValue = timeInSeconds; ie->easeType = easeType; ie->onTweenStartSlateTarget = onTweenStartTarget; ie->onTweenTickSlateTarget = onTweenTickTarget; ie->onTweenCompleteSlateTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event ie->InitEvent(); return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } } AiTweenEvent* UiTween::SlateScaleFromToExpert(STweenableWidget* widgetToScale /*= nullptr*/, FString parameters, bool initializeOnSpawn, UCurveFloat* customEaseTypeCurve /*= nullptr*/, STweenableWidget* onTweenStartTarget /*= nullptr*/, STweenableWidget* onTweenTickTarget /*= nullptr*/, STweenableWidget* onTweenLoopTarget /*= nullptr*/, STweenableWidget* onTweenCompleteTarget) { //Make sure we have a valid object to tween before proceeding if (widgetToScale) { //Create Actor Instance AiTweenEvent* ie = (AiTweenEvent*)SpawnEvent(GetAux()); //Set Event Type ie->eventType = EEventType::EventType::slateScaleFromTo; ie->slateTweening = widgetToScale; ie->customEaseTypeCurve = customEaseTypeCurve; ie->onTweenStartSlateTarget = onTweenStartTarget; ie->onTweenTickSlateTarget = onTweenTickTarget; ie->onTweenLoopSlateTarget = onTweenLoopTarget; ie->onTweenCompleteSlateTarget = onTweenCompleteTarget; //Set tweening variables based on string parameters ie->ParseParameters(parameters); //Initialize Event if initializeOnSpawn is true, otherwise user must manually initialize by calling InitEvent() on //AiTweenEvent AActor* if (initializeOnSpawn) { ie->InitEvent(); } return ie; } else { Print("No tweenable object defined. No tweening operation will occur.", "error"); return nullptr; } }
39.334718
1,568
0.749306
[ "object", "vector" ]
a74537089149014344f9cbbeb8adf8240bfa0d79
7,841
cpp
C++
AllJoyn/Samples/BACnetAdapter/AdapterLib/BACnetAdapterIoRequest.cpp
halitcan/samples
995f850e0ed6c1cd2bc87c8af39b7a4cf41fe425
[ "MIT" ]
1,433
2015-04-30T09:26:53.000Z
2022-03-26T12:44:12.000Z
AllJoyn/Samples/BACnetAdapter/AdapterLib/BACnetAdapterIoRequest.cpp
LeCampusAzure/ms-iot-samples
c0da021a312a631c8a26771a0d203e0de80fc597
[ "MIT" ]
530
2015-05-02T09:12:48.000Z
2018-01-03T17:52:01.000Z
AllJoyn/Samples/BACnetAdapter/AdapterLib/BACnetAdapterIoRequest.cpp
LeCampusAzure/ms-iot-samples
c0da021a312a631c8a26771a0d203e0de80fc597
[ "MIT" ]
1,878
2015-04-30T04:18:57.000Z
2022-03-15T16:51:17.000Z
// Copyright (c) 2015, Microsoft Corporation // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR // IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // #include "pch.h" #include "AdapterUtils.h" #include "BACnetAdapterIoRequest.h" using namespace Platform; using namespace BridgeRT; // // IO request. // Description: // IO request information. // BACnetAdapterIoRequest::BACnetAdapterIoRequest(BACnetAdapterIoRequestPool* PoolPtr, Object^ Parent) : parent(Parent) , refCount(1) , reqStatus(ERROR_SUCCESS) , reqActualBytes(0) , state(StateFree) , allocatorPtr(PoolPtr) , cancelRoutinePtr(nullptr) { this->completionEvent = ::CreateEventEx(nullptr, nullptr, CREATE_EVENT_MANUAL_RESET, EVENT_MODIFY_STATE | SYNCHRONIZE); DSB_ASSERT(this->completionEvent != NULL); this->reInitialize(Parent); } BACnetAdapterIoRequest::~BACnetAdapterIoRequest() { if (this->completionEvent != NULL) { CloseHandle(this->completionEvent); } } void BACnetAdapterIoRequest::reInitialize(Platform::Object^ Parent) { this->parent = Parent; this->refCount = 1; this->reqStatus = ERROR_SUCCESS; this->reqActualBytes = 0; this->bytesReturnedPtr = nullptr; this->state = StateFree; this->cancelRoutinePtr = nullptr; this->completionRoutinePtr = nullptr; this->completionRoutineContextPtr = nullptr; ::ResetEvent(this->completionEvent); this->parameters.Type = ULONG(-1); this->parameters.InputBufferPtr = nullptr; this->parameters.InputBufferSize = 0; this->parameters.OutputBufferPtr = nullptr; this->parameters.OutputBufferSize = 0; } void BACnetAdapterIoRequest::setState(BACnetAdapterIoRequest::STATE NewState) { AutoLock sync(this->lock); if (NewState == StatePending) { this->reqStatus = ERROR_IO_PENDING; } this->state = NewState; } BACnetAdapterIoRequest::STATE BACnetAdapterIoRequest::getState() { AutoLock sync(this->lock); return this->state; } void BACnetAdapterIoRequest::Reference() { ::InterlockedIncrement(&this->refCount); } bool BACnetAdapterIoRequest::Dereference() { DSB_ASSERT(this->refCount > 0); bool isToBeFree = ::InterlockedDecrement(&this->refCount) == 0; if (isToBeFree) { this->allocatorPtr->Free(this); } return isToBeFree; } _Use_decl_annotations_ void BACnetAdapterIoRequest::Initialialize( const BACnetAdapterIoRequest::IO_PARAMETERS* RequestPrametersPtr, PDWORD BytesReturnedPtr ) { this->bytesReturnedPtr = BytesReturnedPtr; this->parameters = *RequestPrametersPtr; this->setState(StateActive); } _Use_decl_annotations_ void BACnetAdapterIoRequest::GetIoParameters(BACnetAdapterIoRequest::IO_PARAMETERS* RequestParamatersPtr) { AutoLock sync(this->lock); *RequestParamatersPtr = this->parameters; } ULONG BACnetAdapterIoRequest::GetType() { AutoLock sync(this->lock); return this->parameters.Type; } void BACnetAdapterIoRequest::SetCancelRoutine(CANCEL_REQUEST_HANDLER CancelRoutinePtr) { AutoLock sync(this->lock); this->cancelRoutinePtr = CancelRoutinePtr; } void BACnetAdapterIoRequest::SetCompletionRoutine(COMPLETE_REQUEST_HANDLER CompletionRoutinePtr, PVOID ContextPtr) { AutoLock sync(this->lock); this->completionRoutinePtr = CompletionRoutinePtr; this->completionRoutineContextPtr = ContextPtr; } void BACnetAdapterIoRequest::Complete(DWORD Status, DWORD ActualBytes) { AutoLock sync(this->lock); this->SetCancelRoutine(nullptr); this->reqStatus = Status; this->reqActualBytes = ActualBytes; if (this->bytesReturnedPtr != nullptr) { *this->bytesReturnedPtr = ActualBytes; } this->setState(StateCompleted); if (this->completionRoutinePtr != nullptr) { this->completionRoutinePtr( this, this->completionRoutineContextPtr, this->reqStatus ); this->completionRoutinePtr = nullptr; } if (this->completionEvent != NULL) { ::SetEvent(this->completionEvent); } this->Dereference(); } void BACnetAdapterIoRequest::MarkPending() { this->setState(StatePending); } _Use_decl_annotations_ uint32 BACnetAdapterIoRequest::Wait(DWORD TimeoutMsec, HANDLE AbortEvent) { { AutoLock sync(this->lock); if (this->getState() != StatePending) { return this->reqStatus; } } if (this->completionEvent == NULL) { DSB_ASSERT(FALSE); return ERROR_INVALID_HANDLE; } HANDLE events[2] = { this->completionEvent, AbortEvent }; DWORD eventCount = AbortEvent == NULL ? 1 : 2; DWORD waitRes = ::WaitForMultipleObjectsEx(eventCount, events, FALSE, TimeoutMsec, FALSE); // Translate to ERROR_xxx status codes DWORD status = ERROR_SUCCESS; switch (waitRes) { case WAIT_OBJECT_0: status = ERROR_SUCCESS; break; case WAIT_OBJECT_0 + 1: status = ERROR_REQUEST_ABORTED; break; case WAIT_TIMEOUT: status = ERROR_TIMEOUT; case WAIT_FAILED: default: status = ERROR_GEN_FAILURE; break; } return status; } uint32 BACnetAdapterIoRequest::Cancel() { AutoLock sync(this->lock); if ((this->state != StatePending) && (this->state != StateActive)) { DSB_ASSERT(FALSE); return ERROR_SUCCESS; } this->setState(StateCancelled); bool isCanceled = false; if (this->cancelRoutinePtr != nullptr) { isCanceled = this->cancelRoutinePtr(this); } return isCanceled ? ERROR_SUCCESS : ERROR_NOT_CAPABLE; } _Use_decl_annotations_ DWORD BACnetAdapterIoRequest::GetStatus(PDWORD ActualBytesPtr) { AutoLock sync(this->lock); if (ActualBytesPtr != nullptr) { *ActualBytesPtr = this->reqActualBytes; } return this->reqStatus; } HANDLE BACnetAdapterIoRequest::GetCompletionEvent() { AutoLock sync(this->lock); return this->completionEvent; } // // BACnetAdapterIoRequestPool class // Description: // DSB request pool. // BACnetAdapterIoRequestPool::BACnetAdapterIoRequestPool() { } BACnetAdapterIoRequestPool::~BACnetAdapterIoRequestPool() { } void BACnetAdapterIoRequestPool::Free(BACnetAdapterIoRequest^ IoRequest) { AutoLock sync(this->lock); if (IoRequest != nullptr) { IoRequest->setState(BACnetAdapterIoRequest::StateFree); this->push(IoRequest); } else { DSB_ASSERT(FALSE); } } BACnetAdapterIoRequest^ BACnetAdapterIoRequestPool::pop() { AutoLock sync(this->lock); if (this->freeRequestList.size() == 0) { return nullptr; } BACnetAdapterIoRequest^ request = this->freeRequestList.front(); this->freeRequestList.erase(this->freeRequestList.begin()); return request; } void BACnetAdapterIoRequestPool::push(BACnetAdapterIoRequest^ IoRequest) { AutoLock sync(this->lock); if (IoRequest != nullptr) { this->freeRequestList.push_back(std::move(IoRequest)); } else { DSB_ASSERT(FALSE); } }
20.366234
123
0.685754
[ "object" ]
a74ce8d60ebbb0c115c1d9e778d24aae21cba5b0
2,227
cc
C++
Solutions/binary-tree-inorder-traversal/solution1.cc
NobodyXu/leetcode
1f4f4e013c786164c0bdaf8fb792f49ae2ff297c
[ "MIT" ]
null
null
null
Solutions/binary-tree-inorder-traversal/solution1.cc
NobodyXu/leetcode
1f4f4e013c786164c0bdaf8fb792f49ae2ff297c
[ "MIT" ]
null
null
null
Solutions/binary-tree-inorder-traversal/solution1.cc
NobodyXu/leetcode
1f4f4e013c786164c0bdaf8fb792f49ae2ff297c
[ "MIT" ]
null
null
null
#include <stack> template <class T, class Container> auto pop(std::stack<T, Container> &s) { auto ret = s.top(); s.pop(); return ret; } /** * Precondition: root != nullptr and the tree is BST */ auto BST_to_array(TreeNode *root) -> vector<int> { vector<int> ret; std::stack<TreeNode*> stack; auto node = root; // Inorder traversal do { do { stack.push(node); node = node->left; } while (node != nullptr); // Now stack.top() contains the left-most node. do { if (stack.size() == 0) return ret; node = pop(stack); // process the element ret.push_back(node->val); // Explore right-node node = node->right; } while (node == nullptr); } while (true); } /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> inorderTraversal(TreeNode* root) { if (root != nullptr) return BST_to_array(root); else return vector<int>(); } };
36.508197
119
0.290076
[ "vector" ]
a74f4bdc7687796b5424f010340114c54cc13193
13,357
hpp
C++
contrib/native/client/src/include/drill/drillClient.hpp
vkorukanti/drill
87b62003bc5742e63ca31ce2ac1845cd95039321
[ "Apache-2.0" ]
3
2019-02-13T03:12:45.000Z
2020-05-04T10:49:54.000Z
contrib/native/client/src/include/drill/drillClient.hpp
vkorukanti/drill
87b62003bc5742e63ca31ce2ac1845cd95039321
[ "Apache-2.0" ]
4
2020-06-30T21:24:55.000Z
2022-01-27T16:17:29.000Z
contrib/native/client/src/include/drill/drillClient.hpp
akkapur/druid-connector
5398891a076c7b777dca2ca4ace66cbde6d73978
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ #ifndef DRILL_CLIENT_H #define DRILL_CLIENT_H #include <vector> #include <boost/thread.hpp> #include "drill/common.hpp" #include "drill/protobuf/Types.pb.h" #if defined _WIN32 || defined __CYGWIN__ #ifdef DRILL_CLIENT_EXPORTS #define DECLSPEC_DRILL_CLIENT __declspec(dllexport) #else #ifdef USE_STATIC_LIBDRILL #define DECLSPEC_DRILL_CLIENT #else #define DECLSPEC_DRILL_CLIENT __declspec(dllimport) #endif #endif #else #if __GNUC__ >= 4 #define DECLSPEC_DRILL_CLIENT __attribute__ ((visibility ("default"))) #else #define DECLSPEC_DRILL_CLIENT #endif #endif namespace exec{ namespace shared{ class DrillPBError; }; }; namespace Drill{ //struct UserServerEndPoint; class DrillClientImplBase; class DrillClientImpl; class DrillClientQueryResult; class FieldMetadata; class RecordBatch; class SchemaDef; enum QueryType{ SQL = 1, LOGICAL = 2, PHYSICAL = 3 }; class DECLSPEC_DRILL_CLIENT DrillClientError{ public: static const uint32_t CONN_ERROR_START = 100; static const uint32_t QRY_ERROR_START = 200; DrillClientError(uint32_t s, uint32_t e, char* m){status=s; errnum=e; msg=m;}; DrillClientError(uint32_t s, uint32_t e, std::string m){status=s; errnum=e; msg=m;}; static DrillClientError* getErrorObject(const exec::shared::DrillPBError& e); // To get the error number we add a error range start number to // the status code returned (either status_t or connectionStatus_t) uint32_t status; // could be either status_t or connectionStatus_t uint32_t errnum; std::string msg; }; // Only one instance of this class exists. A static member of DrillClientImpl; class DECLSPEC_DRILL_CLIENT DrillClientInitializer{ public: DrillClientInitializer(); ~DrillClientInitializer(); }; // Only one instance of this class exists. A static member of DrillClientImpl; class DECLSPEC_DRILL_CLIENT DrillClientConfig{ public: DrillClientConfig(); ~DrillClientConfig(); static void initLogging(const char* path); static void setLogLevel(logLevel_t l); static void setBufferLimit(uint64_t l); static uint64_t getBufferLimit(); static void setSocketTimeout(int32_t l); static void setHandshakeTimeout(int32_t l); static void setQueryTimeout(int32_t l); static void setHeartbeatFrequency(int32_t l); static int32_t getSocketTimeout(); static int32_t getHandshakeTimeout(); static int32_t getQueryTimeout(); static int32_t getHeartbeatFrequency(); static logLevel_t getLogLevel(); private: // The logging level static logLevel_t s_logLevel; // The total amount of memory to be allocated by an instance of DrillClient. // For future use. Currently, not enforced. static uint64_t s_bufferLimit; /** * DrillClient configures timeout (in seconds) in a fine granularity. * Disabled by setting the value to zero. * * s_socketTimout: (default 0) * set SO_RCVTIMEO and SO_SNDTIMEO socket options and place a * timeout on socket receives and sends. It is disabled by default. * * s_handshakeTimeout: (default 5) * place a timeout on validating handshake. When an endpoint (host:port) * is reachable but drillbit hangs or running another service. It will * avoid the client hanging. * * s_queryTimeout: (default 180) * place a timeout on waiting result of querying. * * s_heartbeatFrequency: (default 30) * Seconds of idle activity after which a heartbeat is sent to the drillbit */ static int32_t s_socketTimeout; static int32_t s_handshakeTimeout; static int32_t s_queryTimeout; static int32_t s_heartbeatFrequency; static boost::mutex s_mutex; }; class DECLSPEC_DRILL_CLIENT DrillUserProperties{ public: static const std::map<std::string, uint32_t> USER_PROPERTIES; DrillUserProperties(){}; void setProperty( const std::string& propName, const std::string& propValue){ std::pair< std::string, std::string> in = make_pair(propName, propValue); m_properties.push_back(in); } size_t size() const { return m_properties.size(); } const std::string& keyAt(size_t i) const { return m_properties.at(i).first; } const std::string& valueAt(size_t i) const { return m_properties.at(i).second; } bool validate(std::string& err); private: std::vector< std::pair< std::string, std::string> > m_properties; }; /* * Handle to the Query submitted for execution. * */ typedef void* QueryHandle_t; /* * Query Results listener callback. This function is called for every record batch after it has * been received and decoded. The listener function should return a status. * If the listener returns failure, the query will be canceled. * The listener is also called one last time when the query is completed or gets an error. In that * case the RecordBatch Parameter is NULL. The DrillClientError parameter is NULL is there was no * error oterwise it will have a valid DrillClientError object. * DrillClientQueryResult will hold a listener & listener contxt for the call back function */ typedef status_t (*pfnQueryResultsListener)(QueryHandle_t ctx, RecordBatch* b, DrillClientError* err); /* * The schema change listener callback. This function is called if the record batch detects a * change in the schema. The client application can call getColDefs in the RecordIterator or * get the field information from the RecordBatch itself and handle the change appropriately. */ typedef status_t (*pfnSchemaListener)(void* ctx, FieldDefPtr f, DrillClientError* err); /* * A Record Iterator instance is returned by the SubmitQuery class. Calls block until some data * is available, or until all data has been returned. */ class DECLSPEC_DRILL_CLIENT RecordIterator{ friend class DrillClient; public: ~RecordIterator(); /* * Returns a vector of column(i.e. field) definitions. The returned reference is guaranteed to be valid till the * end of the query or until a schema change event is received. If a schema change event is received by the * application, the application should discard the reference it currently holds and call this function again. */ FieldDefPtr getColDefs(); /* Move the current pointer to the next record. */ status_t next(); /* Gets the ith column in the current record. */ status_t getCol(size_t i, void** b, size_t* sz); /* true if ith column in the current record is NULL */ bool isNull(size_t i); /* Cancels the query. */ status_t cancel(); /* Returns true is the schem has changed from the previous record. Returns false for the first record. */ bool hasSchemaChanged(); void registerSchemaChangeListener(pfnSchemaListener l); bool hasError(); /* * Returns the last error message */ const std::string& getError(); private: RecordIterator(DrillClientQueryResult* pResult){ this->m_currentRecord=-1; this->m_pCurrentRecordBatch=NULL; this->m_pQueryResult=pResult; //m_pColDefs=NULL; } DrillClientQueryResult* m_pQueryResult; size_t m_currentRecord; RecordBatch* m_pCurrentRecordBatch; boost::mutex m_recordBatchMutex; FieldDefPtr m_pColDefs; // Copy of the latest column defs made from the // first record batch with this definition }; class DECLSPEC_DRILL_CLIENT DrillClient{ public: /* * Get the application context from query handle */ static void* getApplicationContext(QueryHandle_t handle); /* * Get the query status from query handle */ static status_t getQueryStatus(QueryHandle_t handle); DrillClient(); ~DrillClient(); // change the logging level static void initLogging(const char* path, logLevel_t l); /** * Connect the client to a Drillbit using connection string and default schema. * * @param[in] connectStr: connection string * @param[in] defaultSchema: default schema (set to NULL and ignore it * if not specified) * @return connection status */ DEPRECATED connectionStatus_t connect(const char* connectStr, const char* defaultSchema=NULL); /* * Connect the client to a Drillbit using connection string and a set of user properties. * The connection string format can be found in comments of * [DRILL-780](https://issues.apache.org/jira/browse/DRILL-780) * * To connect via zookeeper, use the format: * "zk=zk1:port[,zk2:p2,...][/<path_to_drill_root>/<cluster_id>]". * * e.g. * ``` * zk=localhost:2181 * zk=localhost:2181/drill/drillbits1 * zk=localhost:2181,zk2:2181/drill/drillbits1 * ``` * * To connect directly to a drillbit, use the format "local=host:port". * * e.g. * ``` * local=127.0.0.1:31010 * ``` * * User properties is a set of name value pairs. The following properties are recognized: * schema * userName * password * useSSL [true|false] * pemLocation * pemFile * (see drill/common.hpp for friendly defines and the latest list of supported proeprties) * * @param[in] connectStr: connection string * @param[in] properties * if not specified) * @return connection status */ connectionStatus_t connect(const char* connectStr, DrillUserProperties* properties); /* test whether the client is active */ bool isActive(); /* close the connection. cancel any pending requests. */ void close() ; /* * Submit a query asynchronously and wait for results to be returned through a callback. A query context handle is passed * back. The listener callback will return the handle in the ctx parameter. */ status_t submitQuery(Drill::QueryType t, const std::string& plan, pfnQueryResultsListener listener, void* listenerCtx, QueryHandle_t* qHandle); /* * Submit a query asynchronously and wait for results to be returned through an iterator that returns * results synchronously. The client app needs to call delete on the iterator when done. */ RecordIterator* submitQuery(Drill::QueryType t, const std::string& plan, DrillClientError* err); /* * The client application should call this function to wait for results if it has registered a * listener. */ void waitForResults(); /* * Returns the last error message */ std::string& getError(); /* * Returns the error message associated with the query handle */ const std::string& getError(QueryHandle_t handle); /* * Applications using the async query submit method can register a listener for schema changes * */ void registerSchemaChangeListener(QueryHandle_t* handle, pfnSchemaListener l); /* * Applications using the async query submit method should call freeQueryResources to free up resources * once the query is no longer being processed. */ void freeQueryResources(QueryHandle_t* handle); /* * Applications using the sync query submit method should call freeQueryIterator to free up resources * once the RecordIterator is no longer being processed. */ void freeQueryIterator(RecordIterator** pIter){ delete *pIter; *pIter=NULL;}; /* * Applications using the async query submit method should call freeRecordBatch to free up resources * once the RecordBatch is processed and no longer needed. */ void freeRecordBatch(RecordBatch* pRecordBatch); private: static DrillClientInitializer s_init; static DrillClientConfig s_config; DrillClientImplBase * m_pImpl; }; } // namespace Drill #endif
34.874674
151
0.667365
[ "object", "vector" ]
a753c538f98182f783dfbab6083ec1467bba3cf9
1,567
cpp
C++
test/integration/demo/inventory/character_sheet_imgui.cpp
Laguna1989/JamTemplateCpp
66f6e547b3702d106d26c29f9eb0e7d052bcbdb5
[ "CC0-1.0" ]
6
2021-09-05T08:31:36.000Z
2021-12-09T21:14:37.000Z
test/integration/demo/inventory/character_sheet_imgui.cpp
Laguna1989/JamTemplateCpp
66f6e547b3702d106d26c29f9eb0e7d052bcbdb5
[ "CC0-1.0" ]
30
2021-05-19T15:33:03.000Z
2022-03-30T19:26:37.000Z
test/integration/demo/inventory/character_sheet_imgui.cpp
Laguna1989/JamTemplateCpp
66f6e547b3702d106d26c29f9eb0e7d052bcbdb5
[ "CC0-1.0" ]
3
2021-05-23T16:06:01.000Z
2021-10-01T01:17:08.000Z
#include "character_sheet_imgui.hpp" #include "game_interface.hpp" #include "imgui.h" CharacterSheetImgui::CharacterSheetImgui(std::weak_ptr<ItemRepository> repo) : m_repository { repo } { } void CharacterSheetImgui::doUpdate(float const) { if (getGame()->input().keyboard()->justPressed(jt::KeyCode::C)) { m_drawCharacterSheet = !m_drawCharacterSheet; } } void CharacterSheetImgui::doDraw() const { if (!m_drawCharacterSheet) { return; } ImGui::SetNextWindowPos(ImVec2 { 0, 0 }); ImGui::SetNextWindowSize(ImVec2 { 400, 600 }); ImGui::Begin("PlayerCharacter", &m_drawCharacterSheet); int totalarmor = 0; int totalResistanceElectric = 0; int totalResistanceFire = 0; auto itemRepository = m_repository.lock(); for (auto const& itemRef : m_equippedItems) { auto const armor_optional = itemRepository->getItemReferenceFromString(itemRef)->armor; if (!armor_optional.has_value()) { continue; } auto const armor = armor_optional.value(); totalarmor += armor.armor; totalResistanceFire += armor.resistanceFire; totalResistanceElectric += armor.resistanceElectric; } ImGui::Text("TotalArmor: %s", std::to_string(totalarmor).c_str()); ImGui::Text("Fire: %s", std::to_string(totalResistanceFire).c_str()); ImGui::Text("Electric: %s", std::to_string(totalResistanceElectric).c_str()); ImGui::End(); } void CharacterSheetImgui::setEquippedItems(std::vector<std::string> const& items) { m_equippedItems = items; }
31.34
95
0.68411
[ "vector" ]
a7551b38480353aed934b706d486da2586d76d25
2,387
hpp
C++
external_libs/link/include/ableton/link/MeasurementEndpointV4.hpp
llloret/sp_link
b87ee622517fc68845b8f1d19c735c0e3bd05176
[ "MIT" ]
null
null
null
external_libs/link/include/ableton/link/MeasurementEndpointV4.hpp
llloret/sp_link
b87ee622517fc68845b8f1d19c735c0e3bd05176
[ "MIT" ]
null
null
null
external_libs/link/include/ableton/link/MeasurementEndpointV4.hpp
llloret/sp_link
b87ee622517fc68845b8f1d19c735c0e3bd05176
[ "MIT" ]
1
2021-02-22T11:37:41.000Z
2021-02-22T11:37:41.000Z
/* Copyright 2016, Ableton AG, Berlin. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * If you would like to incorporate Link into a proprietary software application, * please contact <link-devs@ableton.com>. */ #pragma once #include <ableton/discovery/NetworkByteStreamSerializable.hpp> #include <ableton/platforms/asio/AsioWrapper.hpp> namespace ableton { namespace link { struct MeasurementEndpointV4 { static const std::int32_t key = 'mep4'; static_assert(key == 0x6d657034, "Unexpected byte order"); // Model the NetworkByteStreamSerializable concept friend std::uint32_t sizeInByteStream(const MeasurementEndpointV4 mep) { return discovery::sizeInByteStream( static_cast<std::uint32_t>(mep.ep.address().to_v4().to_ulong())) + discovery::sizeInByteStream(mep.ep.port()); } template <typename It> friend It toNetworkByteStream(const MeasurementEndpointV4 mep, It out) { return discovery::toNetworkByteStream(mep.ep.port(), discovery::toNetworkByteStream( static_cast<std::uint32_t>(mep.ep.address().to_v4().to_ulong()), std::move(out))); } template <typename It> static std::pair<MeasurementEndpointV4, It> fromNetworkByteStream(It begin, It end) { using namespace std; auto addrRes = discovery::Deserialize<std::uint32_t>::fromNetworkByteStream(std::move(begin), end); auto portRes = discovery::Deserialize<std::uint16_t>::fromNetworkByteStream( std::move(addrRes.second), end); return make_pair(MeasurementEndpointV4{{asio::ip::address_v4{std::move(addrRes.first)}, std::move(portRes.first)}}, std::move(portRes.second)); } asio::ip::udp::endpoint ep; }; } // namespace link } // namespace ableton
34.594203
91
0.718056
[ "model" ]
a75728b1a641c77b5764fea12d0bbc67d688de4e
2,256
cpp
C++
c/expressgames/monkeyrooms.cpp
vadim-cherepanov/arduino
fc919c279eebc43f7bd53d97fe1e3c501f489f19
[ "MIT" ]
null
null
null
c/expressgames/monkeyrooms.cpp
vadim-cherepanov/arduino
fc919c279eebc43f7bd53d97fe1e3c501f489f19
[ "MIT" ]
null
null
null
c/expressgames/monkeyrooms.cpp
vadim-cherepanov/arduino
fc919c279eebc43f7bd53d97fe1e3c501f489f19
[ "MIT" ]
null
null
null
#include "monkeyrooms.h" #include <Adafruit_CircuitPlayground.h> static auto &Express = CircuitPlayground; static const unsigned long stateMask = 0x55555ul; static const unsigned long colors[4] { 0x000000ul, 0x101010ul, 0x000010ul, 0x001000ul }; static const unsigned long colorCursor = 0x400000ul; static const int stepsOptimal[6] {0, 0, 8, 4, 3, 2}; void MonkeyRooms::Reset() { _states = stateMask; _steps = 0; _cursor = 9; } unsigned long TransformStates(unsigned long states) { states &= ~states >> 1; return stateMask & ((states << 2) | (states >> 2) | ((states >> 18) & 1) | ((states & 1) << 18)); } bool MonkeyRooms::Move() { bool stateChanged = false; if (_buttonLeft.Clicked()) { if (--_cursor < 0) _cursor = 9; stateChanged = true; } if (_buttonRight.Clicked()) { unsigned long bit = 2 << (_cursor << 1); if (_states & bit) { _states &= ~bit; } else { _states |= bit; int marked = 0; for (unsigned long i = 0, b = 2; i < 10; ++i, b <<= 2) if (_states & b) ++marked; if (!TransformStates(_states) || marked == _parameter) Transform(); } stateChanged = true; } return stateChanged; } void MonkeyRooms::Draw() const { for (int i = 0; i < 10; ++i) { unsigned long color = colors[(_states >> (i << 1)) & 3]; if (i == _cursor) color |= colorCursor; Express.setPixelColor(i, color); } } void MonkeyRooms::Transform() { _states = TransformStates(_states); ++_steps; if (!_states) Win(); } void MonkeyRooms::Win() { vector<unsigned long> states; if (_steps == stepsOptimal[_parameter]) { unsigned long state = 0; for (int i = 0; i < 7 || !state; ++i) { state += random(1, 3); states.push_back(1 + state % 3); } } states.push_back(1); for (int i = 0; i < 10 * states.size(); ++i) { _states &= ~(3 << (_cursor << 1)); _states |= states[i / 10] << (_cursor << 1); if (--_cursor < 0) _cursor = 9; Draw(); delay(25); } while (_cursor) { --_cursor; Draw(); delay(25); } Reset(); Draw(); }
27.180723
101
0.540337
[ "vector", "transform" ]
a7580a98b4a81e511312d46a7a875aa4f22c42ee
12,426
cpp
C++
Final/Dataset/B2016_Z5_Z2/student6419.cpp
Team-PyRated/PyRated
1df171c8a5a98977b7a96ee298a288314d1b1b96
[ "MIT" ]
null
null
null
Final/Dataset/B2016_Z5_Z2/student6419.cpp
Team-PyRated/PyRated
1df171c8a5a98977b7a96ee298a288314d1b1b96
[ "MIT" ]
null
null
null
Final/Dataset/B2016_Z5_Z2/student6419.cpp
Team-PyRated/PyRated
1df171c8a5a98977b7a96ee298a288314d1b1b96
[ "MIT" ]
null
null
null
/B16/17 (Zadaća 5, Zadatak 2) //Autotestovi by Eldar Kurtic (mail: ekurtic3@etf.unsa.ba) //Za autotestove se obracati *iskljucivo* osobi koja ih pise #include <iostream> #include <string> #include <stdexcept> #include <vector> #include <map> #include <utility> #include <memory> struct Korisnik { std::string ime, prezime, adresa, telefon; }; class Knjiga { std::string Naslov, ImePisca, Zanr; int GodinaIzdavanja; Korisnik *zaduzenje; public: Knjiga(std::string Naslov, std::string ImePisca, std::string Zanr, int GodinaIzdavanja): zaduzenje(nullptr) { Knjiga::Naslov=Naslov; Knjiga::ImePisca=ImePisca; Knjiga::Zanr=Zanr; Knjiga::GodinaIzdavanja=GodinaIzdavanja; } std::string DajNaslov() const { return Naslov; } std::string DajAutora() const { return ImePisca; } std::string DajZanr() const { return Zanr; } int DajGodinuIzdavanja() const { return GodinaIzdavanja; } Korisnik *DajKodKogaJe() const { return zaduzenje; } void ZaduziKnjigu(Korisnik &korisnik) { zaduzenje=&korisnik; } void RazduziKnjigu() { zaduzenje=nullptr; } bool DaLiJeZaduzena()const{ if(zaduzenje==nullptr) return false; return true; } }; class Biblioteka { std::map<int, std::shared_ptr<Korisnik>> MapaKorisnika; std::map<int, std::shared_ptr<Knjiga>> MapaKnjiga; public: Biblioteka()=default; Biblioteka(const Biblioteka &b); Biblioteka(Biblioteka &&b); Biblioteka &operator=(const Biblioteka &b); Biblioteka &operator=(Biblioteka &&b); void RegistrirajNovogKorisnika(int clanskibroj, std::string ime, std::string prezime, std::string adresa, std::string telefon); void RegistrirajNovuKnjigu(int brojknjige, std::string Naslov, std::string ImePisca, std::string Zanr, int GodinaIzdavanja); Korisnik &NadjiKorisnika(int clanskibroj); Knjiga &NadjiKnjigu(int brojknjige); void IzlistajKorisnike()const; void IzlistajKnjige()const; void ZaduziKnjigu(int brojknjige, int clanskibroj); void RazduziKnjigu(int brojknjige); void PrikaziZaduzenja(int clanskibroj); }; Biblioteka::Biblioteka(const Biblioteka &b) { for(auto it(b.MapaKorisnika.begin()); it!=b.MapaKorisnika.end(); it++) { MapaKorisnika.insert(std::make_pair(it->first, it->second)); } for(auto it(b.MapaKnjiga.begin()); it!=b.MapaKnjiga.end(); it++) { MapaKnjiga.insert(std::make_pair(it->first, it->second)); } } Biblioteka::Biblioteka(Biblioteka &&b) { // ili sa : vidjet cemo MapaKnjiga=b.MapaKnjiga, MapaKorisnika=b.MapaKorisnika; b.MapaKnjiga.clear(); b.MapaKorisnika.clear(); } Biblioteka &Biblioteka::operator =(const Biblioteka &b) { MapaKorisnika.clear(); MapaKnjiga.clear(); for(auto it(b.MapaKorisnika.begin()); it!=b.MapaKorisnika.end(); it++) { MapaKorisnika.insert(std::make_pair(it->first, it->second)); } for(auto it(b.MapaKnjiga.begin()); it!=b.MapaKnjiga.end(); it++) { MapaKnjiga.insert(std::make_pair(it->first, it->second)); } return *this; } Biblioteka &Biblioteka::operator =(Biblioteka &&b) { std::swap(MapaKnjiga, b.MapaKnjiga); std::swap(MapaKorisnika, b.MapaKorisnika); return *this; } void Biblioteka::RegistrirajNovogKorisnika(int clanskibroj, std::string ime, std::string prezime, std::string adresa, std::string telefon) { auto it(MapaKorisnika.find(clanskibroj)); if(it==MapaKorisnika.end()) { auto novi(std::make_shared<Korisnik>()); novi->ime=ime; novi->prezime=prezime; novi->adresa=adresa; novi->telefon=telefon; MapaKorisnika.insert(std::make_pair(clanskibroj, novi)); } else throw std::logic_error("Korisnik vec postoji"); } void Biblioteka::RegistrirajNovuKnjigu(int brojknjige, std::string Naslov, std::string ImePisca, std::string Zanr, int GodinaIzdavanja) { auto it(MapaKnjiga.find(brojknjige)); if(it==MapaKnjiga.end()) { std::shared_ptr<Knjiga>nova=std::make_shared<Knjiga>(Naslov, ImePisca, Zanr, GodinaIzdavanja); MapaKnjiga.insert(std::make_pair(brojknjige, nova)); } else throw std::logic_error("Knjiga vec postoji"); } Korisnik &Biblioteka::NadjiKorisnika(int clanskibroj) { auto it(MapaKorisnika.find(clanskibroj)); if(it==MapaKorisnika.end()) throw std::logic_error("Korisnik nije nadjen"); return *(MapaKorisnika[clanskibroj]); } Knjiga &Biblioteka::NadjiKnjigu(int brojknjige) { auto it(MapaKnjiga.find(brojknjige)); if(it==MapaKnjiga.end()) throw std::logic_error("Knjiga nije nadjena"); return *(MapaKnjiga[brojknjige]); } void Biblioteka::IzlistajKorisnike() const { for(auto it(MapaKorisnika.begin()); it!=MapaKorisnika.end(); it++) { std::cout << "Clanski broj: " << it->first << std::endl; std::cout << "Ime i prezime: " << it->second->ime << " " << it->second->prezime << std::endl; std::cout << "Adresa: " << it->second->adresa << std::endl; std::cout << "Broj telefona: " << it->second->telefon << std::endl << std::endl; } } void Biblioteka::IzlistajKnjige() const { int broj(0); for(auto it(MapaKnjiga.begin()); it!=MapaKnjiga.end(); it++) { std::cout << "Evidencijski broj: " << it->first << std::endl; std::cout << "Naslov: " << it->second->DajNaslov() << std::endl; std::cout << "Pisac: " << it->second->DajAutora() << std::endl; std::cout << "Zanr: " << it->second->DajZanr() << std::endl; std::cout << "Godina izdavanja: " << it->second->DajGodinuIzdavanja() << std::endl; if(it->second->DaLiJeZaduzena()) { std::cout << "Zaduzena kod korisnika: " << it->second->DajKodKogaJe()->ime << " " << it->second->DajKodKogaJe()->prezime << std::endl << std::endl; broj=1; } if(broj==0) std::cout << std::endl; } } void Biblioteka::ZaduziKnjigu(int brojknjige, int clanskibroj) { auto it(MapaKnjiga.find(brojknjige)); if(it==MapaKnjiga.end()) throw std::logic_error("Knjiga nije nadjena"); auto at(MapaKorisnika.find(clanskibroj)); if(at==MapaKorisnika.end()) throw std::logic_error("Korisnik nije nadjen"); if(it->second->DaLiJeZaduzena()==true) throw std::logic_error("Knjiga vec zaduzena"); it->second->ZaduziKnjigu(*MapaKorisnika[clanskibroj]); } void Biblioteka::RazduziKnjigu(int brojknjige) { auto it(MapaKnjiga.find(brojknjige)); if(it==MapaKnjiga.end()) throw std::logic_error("Knjiga nije nadjena"); if(it->second->DaLiJeZaduzena()==false) throw std::logic_error("Knjiga nije zaduzena"); it->second->RazduziKnjigu(); } void Biblioteka::PrikaziZaduzenja(int clanskibroj) { auto it(MapaKorisnika.find(clanskibroj)); if(it==MapaKorisnika.end()) throw std::domain_error("Korisnik nije nadjen"); std::vector<Knjiga> knjige; std::vector<int> brojknjiga; Korisnik duzbenik=NadjiKorisnika(clanskibroj); for(auto at(MapaKnjiga.begin()); at!=MapaKnjiga.end(); at++) { if(duzbenik.ime==at->second->DajKodKogaJe()->ime && duzbenik.prezime==at->second->DajKodKogaJe()->prezime && duzbenik.adresa==at->second->DajKodKogaJe()->adresa && duzbenik.telefon==at->second->DajKodKogaJe()->telefon) { knjige.push_back(*(at->second)); brojknjiga.push_back(at->first); } } if(knjige.size()==0) std::cout << "Nema zaduzenja za tog korisnika" << std::endl; else { for(int i(0); i<knjige.size(); i++) { std::cout << "Evidencijski broj: " << brojknjiga[i] << std::endl; std::cout << "Naslov: " << knjige[i].DajNaslov() << std::endl; std::cout << "Pisac: " << knjige[i].DajAutora() << std::endl; std::cout << "Zanr: " << knjige[i].DajZanr() << std::endl; std::cout << "Godina izdavanja: " << knjige[i].DajGodinuIzdavanja() << std::endl << std::endl; } } } int main (){ Biblioteka bajbuk; for(;;) { std::cout << "Odaberite opciju: " << std::endl; std::cout << " 1 - Registriraj novog korisnika" << std::endl << " 2 - Registriraj novu knjigu" << std::endl << " 0 - Kraj registracija" << std::endl; int opcija; std::cin >> opcija; if(!std::cin && opcija!=1 && opcija!=2 && opcija!=0) std::cout << "Ponovo pokreni program! Pazi sta unosis"; if(opcija==1) { std::cout << "Unesite podatke za korisnika: " << std::endl; std::string ime, prezime, adresa, telefon; int clanskibroj; std::cout << "Unesite clanski broj: "; std::cin >> clanskibroj; std::cin.ignore(100000, '\n'); std::cout << "Unesite ime: "; std::getline(std::cin, ime); std::cout << "Unesite prezime: "; std::getline(std::cin, prezime); std::cout << "Unesite adresu: "; std::getline(std::cin, adresa); std::cout << "Unesite broj telefona: "; std::getline(std::cin, telefon); bajbuk.RegistrirajNovogKorisnika(clanskibroj, ime, prezime, adresa, telefon); } if(opcija==2) { std::cout << "Unesite podatke za knjigu: " << std::endl; int brojknjige, GodinaIzdavanja; std::string Naslov, ImePisca, Zanr; std::cin.ignore(10000, '\n'); std::cout << "Unesite broj knjige: "; std::cin.ignore(10000, '\n'); std::cin >> brojknjige; std::cout << "Unesite naslov: "; std::getline(std::cin, Naslov); std::cout << "Unesite autora: "; std::getline(std::cin, ImePisca); std::cout << "Unesite zanr: "; std::getline(std::cin, Zanr); std::cout << "Unesite godinu izdavanja: "; std::cin >> GodinaIzdavanja; bajbuk.RegistrirajNovuKnjigu(brojknjige, Naslov, ImePisca, Zanr, GodinaIzdavanja); } if(opcija==0) break; } for(;;) { int opcija; std::cout << "Unesite opciju: " << std::endl; std::cout << " 1 - Nadji korisnika" << std::endl << " 2 - Nadji knjigu" << std::endl << " 3 - Izlistaj korisnike" << std::endl << " 4 - Izlistaj knjige" << std::endl << " 5 - Zaduzi knjigu" << std::endl << " 6 - Razduzi knjigu" << std::endl << " 7 - Prikazi zaduzenja" << std::endl << " 0 - kraj" << std::endl; std::cin >> opcija; if(!std::cin && opcija!=1 && opcija!=2 && opcija!=3 && opcija!=4 && opcija!=5 && opcija!=6 && opcija!=7 && opcija!=0) std::cout << "Ponovo!" << std::endl; if(opcija==1) { int clanskibroj; std::cout << "Unesite clanski broj: "; std::cin >> clanskibroj; auto Korisnik=bajbuk.NadjiKorisnika(clanskibroj); std::cout << "Korisnik: " << Korisnik.ime << " " << Korisnik.prezime << " " << Korisnik.adresa << " " << Korisnik.telefon << std::endl; } if(opcija==2) { int brojknjige; std::cout << "Unesite broj knjige: "; std::cin >> brojknjige; auto Knjiga=bajbuk.NadjiKnjigu(brojknjige); std::cout << "Knjiga: " << Knjiga.DajNaslov() << " " << Knjiga.DajAutora() << " " << Knjiga.DajZanr() << " " << Knjiga.DajGodinuIzdavanja() << std::endl; } if(opcija==3) bajbuk.IzlistajKorisnike(); if(opcija==4) bajbuk.IzlistajKnjige(); if(opcija==5) { std::cout << "Unesite broj knjige i clanski broj korisnika: "; int brojknjige, clanskibroj; std::cin >> brojknjige >> clanskibroj; bajbuk.ZaduziKnjigu(brojknjige, clanskibroj); } if(opcija==6) { std::cout << "Unesite broj knjige: "; int brojknjige; std::cin >> brojknjige; bajbuk.RazduziKnjigu(brojknjige); } if(opcija==7) { std::cout << "Unesite clanski broj korisnika: "; int clanskibroj; std::cin >> clanskibroj; bajbuk.PrikaziZaduzenja(clanskibroj); } if(opcija==0) return 0; } return 0; }
47.976834
229
0.589892
[ "vector" ]
a75a28b8ac589150d9e9630eee80d8a2007615a2
2,358
cpp
C++
REDSI_1160929_1161573/boost_1_67_0/libs/geometry/index/example/benchmark2.cpp
Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo
eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8
[ "MIT" ]
85
2015-02-08T20:36:17.000Z
2021-11-14T20:38:31.000Z
libs/boost/libs/geometry/index/example/benchmark2.cpp
flingone/frameworks_base_cmds_remoted
4509d9f0468137ed7fd8d100179160d167e7d943
[ "Apache-2.0" ]
9
2015-01-28T16:33:19.000Z
2020-04-12T23:03:28.000Z
libs/boost/libs/geometry/index/example/benchmark2.cpp
flingone/frameworks_base_cmds_remoted
4509d9f0468137ed7fd8d100179160d167e7d943
[ "Apache-2.0" ]
27
2015-01-28T16:33:30.000Z
2021-08-12T05:04:39.000Z
// Boost.Geometry Index // Compare performance with std::set using 1-dimensional object // (i.e. angle, or number line coordiante) // Copyright (c) 2011-2013 Adam Wulkiewicz, Lodz, Poland. // Use, modification and distribution is subject to 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) #include <iostream> #include <boost/geometry.hpp> #include <boost/geometry/index/rtree.hpp> #include <boost/chrono.hpp> #include <boost/foreach.hpp> #include <boost/random.hpp> #include <set> int main() { namespace bg = boost::geometry; namespace bgi = bg::index; typedef boost::chrono::thread_clock clock_t; typedef boost::chrono::duration<float> dur_t; size_t values_count = 1001; size_t count_start = 10; size_t count_stop = 1000; size_t count_step = 10; size_t insrem_count = 3000000; typedef bg::model::point<float, 1, bg::cs::cartesian> P; //typedef bgi::rtree<P, bgi::linear<8, 3> > RT; typedef bgi::rtree<P, bgi::quadratic<8, 3> > RT; //typedef bgi::rtree<P, bgi::rstar<8, 3> > RT; RT t; std::set<float> s; size_t val_i = 0; for ( size_t curr_count = count_start ; curr_count < count_stop ; curr_count += count_step ) { // inserting test { for (; val_i < curr_count ; ++val_i ) { float v = val_i / 100.0f; P p(v); t.insert(p); s.insert(v); } float v = (val_i+1) / 100.0f; P test_p(v); std::cout << t.size() << ' '; clock_t::time_point start = clock_t::now(); for (size_t i = 0 ; i < insrem_count ; ++i ) { t.insert(test_p); t.remove(test_p); } dur_t time = clock_t::now() - start; std::cout << time.count() << ' '; start = clock_t::now(); for (size_t i = 0 ; i < insrem_count ; ++i ) { s.insert(v); s.erase(v); } time = clock_t::now() - start; std::cout << time.count() << ' '; } std::cout << '\n'; } return 0; }
27.103448
97
0.515691
[ "geometry", "object", "model" ]
a75a4597f8458d055e151251d8bfff8aed596113
12,994
hpp
C++
dev/so_5/disp/adv_thread_pool/h/pub.hpp
eao197/so-5-5
fa0c31c84d2637dce04e13a155040150d505fbbd
[ "BSL-1.0" ]
76
2016-03-25T15:22:03.000Z
2022-02-03T15:11:43.000Z
dev/so_5/disp/adv_thread_pool/h/pub.hpp
eao197/so-5-5
fa0c31c84d2637dce04e13a155040150d505fbbd
[ "BSL-1.0" ]
19
2017-03-09T19:21:53.000Z
2021-02-24T13:02:18.000Z
dev/so_5/disp/adv_thread_pool/h/pub.hpp
eao197/so-5-5
fa0c31c84d2637dce04e13a155040150d505fbbd
[ "BSL-1.0" ]
21
2016-09-23T10:01:09.000Z
2020-08-31T12:01:10.000Z
/* * SObjectizer-5 */ /*! * \since * v.5.4.0 * * \file * \brief Public interface of advanced thread pool dispatcher. */ #pragma once #include <so_5/h/declspec.hpp> #include <so_5/rt/h/disp_binder.hpp> #include <so_5/disp/mpmc_queue_traits/h/pub.hpp> #include <so_5/disp/reuse/h/work_thread_activity_tracking.hpp> #include <utility> namespace so_5 { namespace disp { namespace adv_thread_pool { /*! * \brief Alias for namespace with traits of event queue. * * \since * v.5.5.11 */ namespace queue_traits = so_5::disp::mpmc_queue_traits; // // disp_params_t // /*! * \brief Parameters for %adv_thread_pool dispatcher. * * \since * v.5.5.11 */ class disp_params_t : public so_5::disp::reuse::work_thread_activity_tracking_flag_mixin_t< disp_params_t > { using activity_tracking_mixin_t = so_5::disp::reuse:: work_thread_activity_tracking_flag_mixin_t< disp_params_t >; public : //! Default constructor. disp_params_t() {} //! Copy constructor. disp_params_t( const disp_params_t & o ) : activity_tracking_mixin_t( o ) , m_thread_count{ o.m_thread_count } , m_queue_params{ o.m_queue_params } {} //! Move constructor. disp_params_t( disp_params_t && o ) : activity_tracking_mixin_t( std::move(o) ) , m_thread_count{ std::move(o.m_thread_count) } , m_queue_params{ std::move(o.m_queue_params) } {} friend inline void swap( disp_params_t & a, disp_params_t & b ) { swap( static_cast< activity_tracking_mixin_t & >(a), static_cast< activity_tracking_mixin_t & >(b) ); std::swap( a.m_thread_count, b.m_thread_count ); swap( a.m_queue_params, b.m_queue_params ); } //! Copy operator. disp_params_t & operator=( const disp_params_t & o ) { disp_params_t tmp{ o }; swap( *this, tmp ); return *this; } //! Move operator. disp_params_t & operator=( disp_params_t && o ) { disp_params_t tmp{ std::move(o) }; swap( *this, tmp ); return *this; } //! Setter for thread count. disp_params_t & thread_count( std::size_t count ) { m_thread_count = count; return *this; } //! Getter for thread count. std::size_t thread_count() const { return m_thread_count; } //! Setter for queue parameters. disp_params_t & set_queue_params( queue_traits::queue_params_t p ) { m_queue_params = std::move(p); return *this; } //! Tuner for queue parameters. /*! * Accepts lambda-function or functional object which tunes * queue parameters. \code using namespace so_5::disp::thread_pool; create_private_disp( env, "workers_disp", disp_params_t{} .thread_count( 10 ) .tune_queue_params( []( queue_traits::queue_params_t & p ) { p.lock_factory( queue_traits::simple_lock_factory() ); } ) ); \endcode */ template< typename L > disp_params_t & tune_queue_params( L tunner ) { tunner( m_queue_params ); return *this; } //! Getter for queue parameters. const queue_traits::queue_params_t & queue_params() const { return m_queue_params; } private : //! Count of working threads. /*! * Value 0 means that actual thread will be detected automatically. */ std::size_t m_thread_count = { 0 }; //! Queue parameters. queue_traits::queue_params_t m_queue_params; }; // // fifo_t // /*! * \brief Type of FIFO mechanism for agent's demands. * * \since * v.5.4.0 */ enum class fifo_t { //! A FIFO for demands for all agents from the same cooperation. /*! * It means that agents from the same cooperation for which this * FIFO mechanism is used will be worked on the same thread. */ cooperation, //! A FIFO for demands only for one agent. /*! * It means that FIFO is only supported for the concrete agent. * If several agents from a cooperation have this FIFO type they * will process demands independently and on different threads. */ individual }; // // bind_params_t // /*! * \brief Parameters for binding agents to %adv_thread_pool dispatcher. * * \since * v.5.5.11 */ class bind_params_t { public : //! Set FIFO type. bind_params_t & fifo( fifo_t v ) { m_fifo = v; return *this; } //! Get FIFO type. fifo_t query_fifo() const { return m_fifo; } private : //! FIFO type. fifo_t m_fifo = { fifo_t::cooperation }; }; // // params_t // /*! * \brief Alias for bind_params. * * \since * v.5.4.0 * * \deprecated Since v.5.5.11 bind_params_t must be used instead. */ using params_t = bind_params_t; // // default_thread_pool_size // /*! * \brief A helper function for detecting default thread count for * thread pool. * * \since * v.5.4.0 */ inline std::size_t default_thread_pool_size() { auto c = std::thread::hardware_concurrency(); if( !c ) c = 2; return c; } // // private_dispatcher_t // /*! * \brief An interface for %adv_thread_pool private dispatcher. * * \since * v.5.5.4 */ class SO_5_TYPE private_dispatcher_t : public so_5::atomic_refcounted_t { public : virtual ~private_dispatcher_t() SO_5_NOEXCEPT = default; //! Create a binder for that private dispatcher. virtual disp_binder_unique_ptr_t binder( //! Binding parameters for the agent. const bind_params_t & params ) = 0; //! Create a binder for that private dispatcher. /*! * This method allows parameters tuning via lambda-function * or other functional objects. */ template< typename Setter > inline disp_binder_unique_ptr_t binder( //! Function for the parameters tuning. Setter params_setter ) { bind_params_t p; params_setter( p ); return this->binder( p ); } }; /*! * \brief A handle for the %adv_thread_pool private dispatcher. * * \since * v.5.5.4 */ using private_dispatcher_handle_t = so_5::intrusive_ptr_t< private_dispatcher_t >; // // create_disp // /*! * \brief Create %adv_thread_pool dispatcher instance to be used as * named dispatcher. * * \since * v.5.5.11 * * \par Usage sample \code so_5::launch( []( so_5::environment_t & env ) {...}, []( so_5::environment_params_t & env_params ) { using namespace so_5::disp::adv_thread_pool; env_params.add_named_dispatcher( create_disp( disp_params_t{} .thread_count( 16 ) .tune_queue_params( queue_traits::queue_params_t & params ) { params.lock_factory( queue_traits::simple_lock_factory() ); } ) ); } ); \endcode */ SO_5_FUNC dispatcher_unique_ptr_t create_disp( //! Parameters for the dispatcher. disp_params_t params ); // // create_disp // /*! * \brief Create thread pool dispatcher. * * \since * v.5.4.0 */ inline dispatcher_unique_ptr_t create_disp( //! Count of working threads. std::size_t thread_count ) { return create_disp( disp_params_t{}.thread_count( thread_count ) ); } // // create_disp // /*! * \brief Create thread pool dispatcher. * * Size of pool is detected automatically. * * \since * v.5.4.0 */ inline dispatcher_unique_ptr_t create_disp() { return create_disp( default_thread_pool_size() ); } // // create_private_disp // /*! * \brief Create a private %adv_thread_pool dispatcher. * * \since * v.5.5.11 * * \par Usage sample \code using namespace so_5::disp::adv_thread_pool; auto private_disp = create_private_disp( env, disp_params_t{} .thread_count( 16 ) .tune_queue_params( []( queue_traits::queue_params_t & params ) { params.lock_factory( queue_traits::simple_lock_factory() ); } ), "db_workers_pool" ); auto coop = env.create_coop( so_5::autoname, // The main dispatcher for that coop will be // private thread_pool dispatcher. private_disp->binder( bind_params_t{} ) ); \endcode */ SO_5_FUNC private_dispatcher_handle_t create_private_disp( //! SObjectizer Environment to work in. environment_t & env, //! Parameters for the dispatcher. disp_params_t disp_params, //! Value for creating names of data sources for //! run-time monitoring. const std::string & data_sources_name_base ); // // create_private_disp // /*! * \since * v.5.5.15.1 * * \brief Create a private %adv_thread_pool dispatcher. * * \par Usage sample \code using namespace so_5::disp::adv_thread_pool; auto private_disp = create_private_disp( env, "db_workers_pool", disp_params_t{} .thread_count( 16 ) .tune_queue_params( []( queue_traits::queue_params_t & params ) { params.lock_factory( queue_traits::simple_lock_factory() ); } ) ); auto coop = env.create_coop( so_5::autoname, // The main dispatcher for that coop will be // private thread_pool dispatcher. private_disp->binder( bind_params_t{} ) ); \endcode * * This function is added to fix order of parameters and make it similar * to create_private_disp from other dispatchers. */ inline private_dispatcher_handle_t create_private_disp( //! SObjectizer Environment to work in. environment_t & env, //! Value for creating names of data sources for //! run-time monitoring. const std::string & data_sources_name_base, //! Parameters for the dispatcher. disp_params_t disp_params ) { return create_private_disp( env, std::move(disp_params), data_sources_name_base ); } // // create_private_disp // /*! * \brief Create a private %adv_thread_pool dispatcher. * * \since * v.5.5.4 * * \par Usage sample \code auto private_disp = so_5::disp::adv_thread_pool::create_private_disp( env, 16, "req_processors" ); auto coop = env.create_coop( so_5::autoname, // The main dispatcher for that coop will be // private adv_thread_pool dispatcher. private_disp->binder( so_5::disp::adv_thread_pool::bind_params_t{} ) ); \endcode */ inline private_dispatcher_handle_t create_private_disp( //! SObjectizer Environment to work in. environment_t & env, //! Count of working threads. std::size_t thread_count, //! Value for creating names of data sources for //! run-time monitoring. const std::string & data_sources_name_base ) { return create_private_disp( env, disp_params_t{}.thread_count( thread_count ), data_sources_name_base ); } /*! * \brief Create a private %adv_thread_pool dispatcher. * * \since * v.5.5.4 * * \par Usage sample \code auto private_disp = so_5::disp::adv_thread_pool::create_private_disp( env, 16 ); auto coop = env.create_coop( so_5::autoname, // The main dispatcher for that coop will be // private adv_thread_pool dispatcher. private_disp->binder( so_5::disp::adv_thread_pool::bind_params_t{} ) ); \endcode */ inline private_dispatcher_handle_t create_private_disp( //! SObjectizer Environment to work in. environment_t & env, //! Count of working threads. std::size_t thread_count ) { return create_private_disp( env, thread_count, std::string() ); } // // create_private_disp // /*! * \brief Create a private %adv_thread_pool dispatcher with the default * count of working threads. * * \since * v.5.5.4 * * \par Usage sample \code auto private_disp = so_5::disp::adv_thread_pool::create_private_disp( env ); auto coop = env.create_coop( so_5::autoname, // The main dispatcher for that coop will be // private adv_thread_pool dispatcher. private_disp->binder( so_5::disp::adv_thread_pool::bind_params_t{} ) ); \endcode */ inline private_dispatcher_handle_t create_private_disp( //! SObjectizer Environment to work in. environment_t & env ) { return create_private_disp( env, default_thread_pool_size(), std::string() ); } // // create_disp_binder // /*! * \brief Create dispatcher binder for thread pool dispatcher. * * \since * v.5.4.0 */ SO_5_FUNC disp_binder_unique_ptr_t create_disp_binder( //! Name of the dispatcher. std::string disp_name, //! Parameters for binding. const bind_params_t & params ); /*! * \brief Create dispatcher binder for thread pool dispatcher. * * \since * v.5.4.0 * * Usage example: \code create_disp_binder( "tpool", []( so_5::disp::adv_thread_pool::bind_params_t & p ) { p.fifo( so_5::disp::thread_pool::fifo_t::individual ); } ); \endcode */ template< typename Setter > inline disp_binder_unique_ptr_t create_disp_binder( //! Name of the dispatcher. std::string disp_name, //! Function for setting the binding's params. Setter params_setter ) { bind_params_t params; params_setter( params ); return create_disp_binder( std::move(disp_name), params ); } } /* namespace adv_thread_pool */ } /* namespace disp */ } /* namespace so_5 */
22.061121
89
0.659612
[ "object" ]
a75fdd3dc45a72beedd3e2335268c8cbac44a7eb
32,280
cc
C++
components/service/ucloud/ocr/src/OcrClient.cc
wanguojian/AliOS-Things
47fce29d4dd39d124f0bfead27998ad7beea8441
[ "Apache-2.0" ]
1
2021-04-09T03:18:41.000Z
2021-04-09T03:18:41.000Z
components/service/ucloud/ocr/src/OcrClient.cc
wanguojian/AliOS-Things
47fce29d4dd39d124f0bfead27998ad7beea8441
[ "Apache-2.0" ]
null
null
null
components/service/ucloud/ocr/src/OcrClient.cc
wanguojian/AliOS-Things
47fce29d4dd39d124f0bfead27998ad7beea8441
[ "Apache-2.0" ]
1
2021-06-20T06:43:12.000Z
2021-06-20T06:43:12.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * 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. */ #include <alibabacloud/ocr/OcrClient.h> #include <alibabacloud/core/SimpleCredentialsProvider.h> using namespace AlibabaCloud; using namespace AlibabaCloud::Location; using namespace AlibabaCloud::Ocr; using namespace AlibabaCloud::Ocr::Model; namespace { const std::string SERVICE_NAME = "ocr"; } OcrClient::OcrClient(const Credentials &credentials, const ClientConfiguration &configuration) : RpcServiceClient(SERVICE_NAME, std::make_shared<SimpleCredentialsProvider>(credentials), configuration) { auto locationClient = std::make_shared<LocationClient>(credentials, configuration); endpointProvider_ = std::make_shared<EndpointProvider>(locationClient, configuration.regionId(), SERVICE_NAME, "ocr"); } OcrClient::OcrClient(const std::shared_ptr<CredentialsProvider>& credentialsProvider, const ClientConfiguration & configuration) : RpcServiceClient(SERVICE_NAME, credentialsProvider, configuration) { auto locationClient = std::make_shared<LocationClient>(credentialsProvider, configuration); endpointProvider_ = std::make_shared<EndpointProvider>(locationClient, configuration.regionId(), SERVICE_NAME, "ocr"); } OcrClient::OcrClient(const std::string & accessKeyId, const std::string & accessKeySecret, const ClientConfiguration & configuration) : RpcServiceClient(SERVICE_NAME, std::make_shared<SimpleCredentialsProvider>(accessKeyId, accessKeySecret), configuration) { auto locationClient = std::make_shared<LocationClient>(accessKeyId, accessKeySecret, configuration); endpointProvider_ = std::make_shared<EndpointProvider>(locationClient, configuration.regionId(), SERVICE_NAME, "ocr"); } OcrClient::~OcrClient() {} OcrClient::DetectCardScreenshotOutcome OcrClient::detectCardScreenshot(const DetectCardScreenshotRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DetectCardScreenshotOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DetectCardScreenshotOutcome(DetectCardScreenshotResult(outcome.result())); else return DetectCardScreenshotOutcome(outcome.error()); } void OcrClient::detectCardScreenshotAsync(const DetectCardScreenshotRequest& request, const DetectCardScreenshotAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, detectCardScreenshot(request), context); }; asyncExecute(new Runnable(fn)); } OcrClient::DetectCardScreenshotOutcomeCallable OcrClient::detectCardScreenshotCallable(const DetectCardScreenshotRequest &request) const { auto task = std::make_shared<std::packaged_task<DetectCardScreenshotOutcome()>>( [this, request]() { return this->detectCardScreenshot(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } OcrClient::GetAsyncJobResultOutcome OcrClient::getAsyncJobResult(const GetAsyncJobResultRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return GetAsyncJobResultOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return GetAsyncJobResultOutcome(GetAsyncJobResultResult(outcome.result())); else return GetAsyncJobResultOutcome(outcome.error()); } void OcrClient::getAsyncJobResultAsync(const GetAsyncJobResultRequest& request, const GetAsyncJobResultAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, getAsyncJobResult(request), context); }; asyncExecute(new Runnable(fn)); } OcrClient::GetAsyncJobResultOutcomeCallable OcrClient::getAsyncJobResultCallable(const GetAsyncJobResultRequest &request) const { auto task = std::make_shared<std::packaged_task<GetAsyncJobResultOutcome()>>( [this, request]() { return this->getAsyncJobResult(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } OcrClient::RecognizeAccountPageOutcome OcrClient::recognizeAccountPage(const RecognizeAccountPageRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return RecognizeAccountPageOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return RecognizeAccountPageOutcome(RecognizeAccountPageResult(outcome.result())); else return RecognizeAccountPageOutcome(outcome.error()); } void OcrClient::recognizeAccountPageAsync(const RecognizeAccountPageRequest& request, const RecognizeAccountPageAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, recognizeAccountPage(request), context); }; asyncExecute(new Runnable(fn)); } OcrClient::RecognizeAccountPageOutcomeCallable OcrClient::recognizeAccountPageCallable(const RecognizeAccountPageRequest &request) const { auto task = std::make_shared<std::packaged_task<RecognizeAccountPageOutcome()>>( [this, request]() { return this->recognizeAccountPage(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } OcrClient::RecognizeBankCardOutcome OcrClient::recognizeBankCard(const RecognizeBankCardRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return RecognizeBankCardOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return RecognizeBankCardOutcome(RecognizeBankCardResult(outcome.result())); else return RecognizeBankCardOutcome(outcome.error()); } void OcrClient::recognizeBankCardAsync(const RecognizeBankCardRequest& request, const RecognizeBankCardAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, recognizeBankCard(request), context); }; asyncExecute(new Runnable(fn)); } OcrClient::RecognizeBankCardOutcomeCallable OcrClient::recognizeBankCardCallable(const RecognizeBankCardRequest &request) const { auto task = std::make_shared<std::packaged_task<RecognizeBankCardOutcome()>>( [this, request]() { return this->recognizeBankCard(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } OcrClient::RecognizeBusinessCardOutcome OcrClient::recognizeBusinessCard(const RecognizeBusinessCardRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return RecognizeBusinessCardOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return RecognizeBusinessCardOutcome(RecognizeBusinessCardResult(outcome.result())); else return RecognizeBusinessCardOutcome(outcome.error()); } void OcrClient::recognizeBusinessCardAsync(const RecognizeBusinessCardRequest& request, const RecognizeBusinessCardAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, recognizeBusinessCard(request), context); }; asyncExecute(new Runnable(fn)); } OcrClient::RecognizeBusinessCardOutcomeCallable OcrClient::recognizeBusinessCardCallable(const RecognizeBusinessCardRequest &request) const { auto task = std::make_shared<std::packaged_task<RecognizeBusinessCardOutcome()>>( [this, request]() { return this->recognizeBusinessCard(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } OcrClient::RecognizeBusinessLicenseOutcome OcrClient::recognizeBusinessLicense(const RecognizeBusinessLicenseRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return RecognizeBusinessLicenseOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return RecognizeBusinessLicenseOutcome(RecognizeBusinessLicenseResult(outcome.result())); else return RecognizeBusinessLicenseOutcome(outcome.error()); } void OcrClient::recognizeBusinessLicenseAsync(const RecognizeBusinessLicenseRequest& request, const RecognizeBusinessLicenseAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, recognizeBusinessLicense(request), context); }; asyncExecute(new Runnable(fn)); } OcrClient::RecognizeBusinessLicenseOutcomeCallable OcrClient::recognizeBusinessLicenseCallable(const RecognizeBusinessLicenseRequest &request) const { auto task = std::make_shared<std::packaged_task<RecognizeBusinessLicenseOutcome()>>( [this, request]() { return this->recognizeBusinessLicense(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } OcrClient::RecognizeCharacterOutcome OcrClient::recognizeCharacter(const RecognizeCharacterRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return RecognizeCharacterOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return RecognizeCharacterOutcome(RecognizeCharacterResult(outcome.result())); else return RecognizeCharacterOutcome(outcome.error()); } void OcrClient::recognizeCharacterAsync(const RecognizeCharacterRequest& request, const RecognizeCharacterAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, recognizeCharacter(request), context); }; asyncExecute(new Runnable(fn)); } OcrClient::RecognizeCharacterOutcomeCallable OcrClient::recognizeCharacterCallable(const RecognizeCharacterRequest &request) const { auto task = std::make_shared<std::packaged_task<RecognizeCharacterOutcome()>>( [this, request]() { return this->recognizeCharacter(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } OcrClient::RecognizeChinapassportOutcome OcrClient::recognizeChinapassport(const RecognizeChinapassportRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return RecognizeChinapassportOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return RecognizeChinapassportOutcome(RecognizeChinapassportResult(outcome.result())); else return RecognizeChinapassportOutcome(outcome.error()); } void OcrClient::recognizeChinapassportAsync(const RecognizeChinapassportRequest& request, const RecognizeChinapassportAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, recognizeChinapassport(request), context); }; asyncExecute(new Runnable(fn)); } OcrClient::RecognizeChinapassportOutcomeCallable OcrClient::recognizeChinapassportCallable(const RecognizeChinapassportRequest &request) const { auto task = std::make_shared<std::packaged_task<RecognizeChinapassportOutcome()>>( [this, request]() { return this->recognizeChinapassport(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } OcrClient::RecognizeDriverLicenseOutcome OcrClient::recognizeDriverLicense(const RecognizeDriverLicenseRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return RecognizeDriverLicenseOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return RecognizeDriverLicenseOutcome(RecognizeDriverLicenseResult(outcome.result())); else return RecognizeDriverLicenseOutcome(outcome.error()); } void OcrClient::recognizeDriverLicenseAsync(const RecognizeDriverLicenseRequest& request, const RecognizeDriverLicenseAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, recognizeDriverLicense(request), context); }; asyncExecute(new Runnable(fn)); } OcrClient::RecognizeDriverLicenseOutcomeCallable OcrClient::recognizeDriverLicenseCallable(const RecognizeDriverLicenseRequest &request) const { auto task = std::make_shared<std::packaged_task<RecognizeDriverLicenseOutcome()>>( [this, request]() { return this->recognizeDriverLicense(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } OcrClient::RecognizeDrivingLicenseOutcome OcrClient::recognizeDrivingLicense(const RecognizeDrivingLicenseRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return RecognizeDrivingLicenseOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return RecognizeDrivingLicenseOutcome(RecognizeDrivingLicenseResult(outcome.result())); else return RecognizeDrivingLicenseOutcome(outcome.error()); } void OcrClient::recognizeDrivingLicenseAsync(const RecognizeDrivingLicenseRequest& request, const RecognizeDrivingLicenseAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, recognizeDrivingLicense(request), context); }; asyncExecute(new Runnable(fn)); } OcrClient::RecognizeDrivingLicenseOutcomeCallable OcrClient::recognizeDrivingLicenseCallable(const RecognizeDrivingLicenseRequest &request) const { auto task = std::make_shared<std::packaged_task<RecognizeDrivingLicenseOutcome()>>( [this, request]() { return this->recognizeDrivingLicense(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } OcrClient::RecognizeIdentityCardOutcome OcrClient::recognizeIdentityCard(const RecognizeIdentityCardRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return RecognizeIdentityCardOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return RecognizeIdentityCardOutcome(RecognizeIdentityCardResult(outcome.result())); else return RecognizeIdentityCardOutcome(outcome.error()); } void OcrClient::recognizeIdentityCardAsync(const RecognizeIdentityCardRequest& request, const RecognizeIdentityCardAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, recognizeIdentityCard(request), context); }; asyncExecute(new Runnable(fn)); } OcrClient::RecognizeIdentityCardOutcomeCallable OcrClient::recognizeIdentityCardCallable(const RecognizeIdentityCardRequest &request) const { auto task = std::make_shared<std::packaged_task<RecognizeIdentityCardOutcome()>>( [this, request]() { return this->recognizeIdentityCard(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } OcrClient::RecognizeLicensePlateOutcome OcrClient::recognizeLicensePlate(const RecognizeLicensePlateRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return RecognizeLicensePlateOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return RecognizeLicensePlateOutcome(RecognizeLicensePlateResult(outcome.result())); else return RecognizeLicensePlateOutcome(outcome.error()); } void OcrClient::recognizeLicensePlateAsync(const RecognizeLicensePlateRequest& request, const RecognizeLicensePlateAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, recognizeLicensePlate(request), context); }; asyncExecute(new Runnable(fn)); } OcrClient::RecognizeLicensePlateOutcomeCallable OcrClient::recognizeLicensePlateCallable(const RecognizeLicensePlateRequest &request) const { auto task = std::make_shared<std::packaged_task<RecognizeLicensePlateOutcome()>>( [this, request]() { return this->recognizeLicensePlate(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } OcrClient::RecognizePassportMRZOutcome OcrClient::recognizePassportMRZ(const RecognizePassportMRZRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return RecognizePassportMRZOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return RecognizePassportMRZOutcome(RecognizePassportMRZResult(outcome.result())); else return RecognizePassportMRZOutcome(outcome.error()); } void OcrClient::recognizePassportMRZAsync(const RecognizePassportMRZRequest& request, const RecognizePassportMRZAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, recognizePassportMRZ(request), context); }; asyncExecute(new Runnable(fn)); } OcrClient::RecognizePassportMRZOutcomeCallable OcrClient::recognizePassportMRZCallable(const RecognizePassportMRZRequest &request) const { auto task = std::make_shared<std::packaged_task<RecognizePassportMRZOutcome()>>( [this, request]() { return this->recognizePassportMRZ(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } OcrClient::RecognizePoiNameOutcome OcrClient::recognizePoiName(const RecognizePoiNameRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return RecognizePoiNameOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return RecognizePoiNameOutcome(RecognizePoiNameResult(outcome.result())); else return RecognizePoiNameOutcome(outcome.error()); } void OcrClient::recognizePoiNameAsync(const RecognizePoiNameRequest& request, const RecognizePoiNameAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, recognizePoiName(request), context); }; asyncExecute(new Runnable(fn)); } OcrClient::RecognizePoiNameOutcomeCallable OcrClient::recognizePoiNameCallable(const RecognizePoiNameRequest &request) const { auto task = std::make_shared<std::packaged_task<RecognizePoiNameOutcome()>>( [this, request]() { return this->recognizePoiName(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } OcrClient::RecognizeQrCodeOutcome OcrClient::recognizeQrCode(const RecognizeQrCodeRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return RecognizeQrCodeOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return RecognizeQrCodeOutcome(RecognizeQrCodeResult(outcome.result())); else return RecognizeQrCodeOutcome(outcome.error()); } void OcrClient::recognizeQrCodeAsync(const RecognizeQrCodeRequest& request, const RecognizeQrCodeAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, recognizeQrCode(request), context); }; asyncExecute(new Runnable(fn)); } OcrClient::RecognizeQrCodeOutcomeCallable OcrClient::recognizeQrCodeCallable(const RecognizeQrCodeRequest &request) const { auto task = std::make_shared<std::packaged_task<RecognizeQrCodeOutcome()>>( [this, request]() { return this->recognizeQrCode(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } OcrClient::RecognizeStampOutcome OcrClient::recognizeStamp(const RecognizeStampRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return RecognizeStampOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return RecognizeStampOutcome(RecognizeStampResult(outcome.result())); else return RecognizeStampOutcome(outcome.error()); } void OcrClient::recognizeStampAsync(const RecognizeStampRequest& request, const RecognizeStampAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, recognizeStamp(request), context); }; asyncExecute(new Runnable(fn)); } OcrClient::RecognizeStampOutcomeCallable OcrClient::recognizeStampCallable(const RecognizeStampRequest &request) const { auto task = std::make_shared<std::packaged_task<RecognizeStampOutcome()>>( [this, request]() { return this->recognizeStamp(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } OcrClient::RecognizeTableOutcome OcrClient::recognizeTable(const RecognizeTableRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return RecognizeTableOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return RecognizeTableOutcome(RecognizeTableResult(outcome.result())); else return RecognizeTableOutcome(outcome.error()); } void OcrClient::recognizeTableAsync(const RecognizeTableRequest& request, const RecognizeTableAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, recognizeTable(request), context); }; asyncExecute(new Runnable(fn)); } OcrClient::RecognizeTableOutcomeCallable OcrClient::recognizeTableCallable(const RecognizeTableRequest &request) const { auto task = std::make_shared<std::packaged_task<RecognizeTableOutcome()>>( [this, request]() { return this->recognizeTable(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } OcrClient::RecognizeTakeoutOrderOutcome OcrClient::recognizeTakeoutOrder(const RecognizeTakeoutOrderRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return RecognizeTakeoutOrderOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return RecognizeTakeoutOrderOutcome(RecognizeTakeoutOrderResult(outcome.result())); else return RecognizeTakeoutOrderOutcome(outcome.error()); } void OcrClient::recognizeTakeoutOrderAsync(const RecognizeTakeoutOrderRequest& request, const RecognizeTakeoutOrderAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, recognizeTakeoutOrder(request), context); }; asyncExecute(new Runnable(fn)); } OcrClient::RecognizeTakeoutOrderOutcomeCallable OcrClient::recognizeTakeoutOrderCallable(const RecognizeTakeoutOrderRequest &request) const { auto task = std::make_shared<std::packaged_task<RecognizeTakeoutOrderOutcome()>>( [this, request]() { return this->recognizeTakeoutOrder(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } OcrClient::RecognizeTaxiInvoiceOutcome OcrClient::recognizeTaxiInvoice(const RecognizeTaxiInvoiceRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return RecognizeTaxiInvoiceOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return RecognizeTaxiInvoiceOutcome(RecognizeTaxiInvoiceResult(outcome.result())); else return RecognizeTaxiInvoiceOutcome(outcome.error()); } void OcrClient::recognizeTaxiInvoiceAsync(const RecognizeTaxiInvoiceRequest& request, const RecognizeTaxiInvoiceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, recognizeTaxiInvoice(request), context); }; asyncExecute(new Runnable(fn)); } OcrClient::RecognizeTaxiInvoiceOutcomeCallable OcrClient::recognizeTaxiInvoiceCallable(const RecognizeTaxiInvoiceRequest &request) const { auto task = std::make_shared<std::packaged_task<RecognizeTaxiInvoiceOutcome()>>( [this, request]() { return this->recognizeTaxiInvoice(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } OcrClient::RecognizeTrainTicketOutcome OcrClient::recognizeTrainTicket(const RecognizeTrainTicketRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return RecognizeTrainTicketOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return RecognizeTrainTicketOutcome(RecognizeTrainTicketResult(outcome.result())); else return RecognizeTrainTicketOutcome(outcome.error()); } void OcrClient::recognizeTrainTicketAsync(const RecognizeTrainTicketRequest& request, const RecognizeTrainTicketAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, recognizeTrainTicket(request), context); }; asyncExecute(new Runnable(fn)); } OcrClient::RecognizeTrainTicketOutcomeCallable OcrClient::recognizeTrainTicketCallable(const RecognizeTrainTicketRequest &request) const { auto task = std::make_shared<std::packaged_task<RecognizeTrainTicketOutcome()>>( [this, request]() { return this->recognizeTrainTicket(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } OcrClient::RecognizeVATInvoiceOutcome OcrClient::recognizeVATInvoice(const RecognizeVATInvoiceRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return RecognizeVATInvoiceOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return RecognizeVATInvoiceOutcome(RecognizeVATInvoiceResult(outcome.result())); else return RecognizeVATInvoiceOutcome(outcome.error()); } void OcrClient::recognizeVATInvoiceAsync(const RecognizeVATInvoiceRequest& request, const RecognizeVATInvoiceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, recognizeVATInvoice(request), context); }; asyncExecute(new Runnable(fn)); } OcrClient::RecognizeVATInvoiceOutcomeCallable OcrClient::recognizeVATInvoiceCallable(const RecognizeVATInvoiceRequest &request) const { auto task = std::make_shared<std::packaged_task<RecognizeVATInvoiceOutcome()>>( [this, request]() { return this->recognizeVATInvoice(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } OcrClient::RecognizeVINCodeOutcome OcrClient::recognizeVINCode(const RecognizeVINCodeRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return RecognizeVINCodeOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return RecognizeVINCodeOutcome(RecognizeVINCodeResult(outcome.result())); else return RecognizeVINCodeOutcome(outcome.error()); } void OcrClient::recognizeVINCodeAsync(const RecognizeVINCodeRequest& request, const RecognizeVINCodeAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, recognizeVINCode(request), context); }; asyncExecute(new Runnable(fn)); } OcrClient::RecognizeVINCodeOutcomeCallable OcrClient::recognizeVINCodeCallable(const RecognizeVINCodeRequest &request) const { auto task = std::make_shared<std::packaged_task<RecognizeVINCodeOutcome()>>( [this, request]() { return this->recognizeVINCode(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } OcrClient::RecognizeVerificationcodeOutcome OcrClient::recognizeVerificationcode(const RecognizeVerificationcodeRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return RecognizeVerificationcodeOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return RecognizeVerificationcodeOutcome(RecognizeVerificationcodeResult(outcome.result())); else return RecognizeVerificationcodeOutcome(outcome.error()); } void OcrClient::recognizeVerificationcodeAsync(const RecognizeVerificationcodeRequest& request, const RecognizeVerificationcodeAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, recognizeVerificationcode(request), context); }; asyncExecute(new Runnable(fn)); } OcrClient::RecognizeVerificationcodeOutcomeCallable OcrClient::recognizeVerificationcodeCallable(const RecognizeVerificationcodeRequest &request) const { auto task = std::make_shared<std::packaged_task<RecognizeVerificationcodeOutcome()>>( [this, request]() { return this->recognizeVerificationcode(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } OcrClient::TrimDocumentOutcome OcrClient::trimDocument(const TrimDocumentRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return TrimDocumentOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return TrimDocumentOutcome(TrimDocumentResult(outcome.result())); else return TrimDocumentOutcome(outcome.error()); } void OcrClient::trimDocumentAsync(const TrimDocumentRequest& request, const TrimDocumentAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, trimDocument(request), context); }; asyncExecute(new Runnable(fn)); } OcrClient::TrimDocumentOutcomeCallable OcrClient::trimDocumentCallable(const TrimDocumentRequest &request) const { auto task = std::make_shared<std::packaged_task<TrimDocumentOutcome()>>( [this, request]() { return this->trimDocument(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); }
35.163399
213
0.784789
[ "model" ]
a761298a403284ef7d258fd815ce357a8585766b
8,325
cpp
C++
CloudTcpForwarderAgent/tcp_client.cpp
ahmed-eg/Cloud-port-forward
fb92021d47daaab90bcaf73ed63ebf7acf227f09
[ "Unlicense" ]
null
null
null
CloudTcpForwarderAgent/tcp_client.cpp
ahmed-eg/Cloud-port-forward
fb92021d47daaab90bcaf73ed63ebf7acf227f09
[ "Unlicense" ]
null
null
null
CloudTcpForwarderAgent/tcp_client.cpp
ahmed-eg/Cloud-port-forward
fb92021d47daaab90bcaf73ed63ebf7acf227f09
[ "Unlicense" ]
null
null
null
/** ------------------------------------------------------- File name: tcp_client.cpp Purpose: connect to destination device and forword the responce to the server via tcp_client_agent.cpp Version: 1.0 11/23/2017 Auther: Ahmed Elaraby ---------------------------------------------------------*/ #include "stdafx.h" #define _WINSOCK_DEPRECATED_NO_WARNINGS #include "tcp_client.h" #include <stdlib.h> #include <cstring> #include <stdlib.h> #include <cstdio> #include <stdint.h> #pragma comment(lib, "Ws2_32.lib") //#define request "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: keep-alive\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36\r\nUpgrade-Insecure-Requests: 1\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\nDNT: 1\r\nAccept-Encoding: gzip, deflate, br\r\nAccept-Language: en-US,en;q=0.9,ar;q=0.8\r\nAlexaToolbar-ALX_NS_PH: AlexaToolbar/alx-4.0.1\r\n\r\n" tcp_client::tcp_client(char * _ip_address, uint16_t _port, int _respond_socket) { recthread_started = 0; port = _port; ip_address = _ip_address; respond_socket = _respond_socket; lock(); is_closed = 0; *clients_connected++; tcp_init(); } void error(const char *msg) { //perror(msg); debug1(msg); //exit(0); } void send_agent(sPacket * _packet, int _socket) { if (_packet == nullptr) { debug2("send_agent: (Client) _packet is null\n"); return; } is_sending.lock(); static char arr[BUFFER_SIZE]; int n = 0; arr[0] = PACKET_HEADER; arr[1] = _packet->packet_index; arr[2] = _packet->data_length; arr[3] = (char)_packet->status; memcpy(&arr[4], &_packet->data[0], _packet->data_length); n= write(_socket, &arr[0], (_packet->data_length + 4), 0); add_sent(n); if (n < (_packet->data_length + 4)) debug2("sent only %d/%d\n", n, (_packet->data_length + 4)); //else debug2("s[%d] ", n); is_sending.unlock(); } void send_close_command(unsigned char _client_index, int _socket) { //----------- when close connection, send close command sPacket * packet = new sPacket; packet->data_length = 0; packet->status = ePacket_Status::csFinshedSuccess; packet->packet_index = _client_index; packet->packet_socket = 0; send_agent(packet, _socket); debug2("send close connection command %d\n", _client_index); delete packet; } //sPacket * parse_packet(char * data, int len) { // // if (data[0] == PACKET_HEADER) { // sPacket * p = new sPacket; // p->packet_index = (unsigned char)data[1]; // p->data_length = (unsigned char)data[2]; // p->status = (ePacket_Status)data[3]; // memcpy(p->data, &data[4], len - 4); // return p; // } // else { // debug("xxxxxxxxxxxxxxxxx"); // return nullptr; // } // //} ///================================================= /// read from client endpoint and send for server ///================================================= DWORD WINAPI recthread(__in LPVOID lpParameter) { //sPacket * packet; int n; tcp_client * current = (tcp_client*)lpParameter; char buffer[BUFFER_SIZE]; if (current->recthread_started)return 0; current->recthread_started = 1; int rec_n = 0; while (!current->get_is_closed()) { n = read(current->sockfd, &buffer[4], PACKET_DATA_SIZE, 0); // check if no if (n <= 0) //SOCKET_ERROR) { current->set_is_closed(1); // marke the socket as closed so it will terminate the client object break; } else { is_sending.lock(); buffer[0] = PACKET_HEADER; buffer[1] = current->client_index; buffer[2] = (unsigned char)n; buffer[3] = (char)ePacket_Status::csNew; //memcpy(&arr[4], &_packet->data[0], _packet->data_length); rec_n = write(current->respond_socket, &buffer[0], (n + 4), 0); add_rec(rec_n); if (rec_n < (n + 4)) debug2("sent only %d/%d\n", rec_n, (n + 4)); //else debug2("s[%d] ", n); is_sending.unlock(); /*packet = new sPacket; packet->data_length = (char)n; packet->status = ePacket_Status::csNew; packet->packet_index = client_index; packet->packet_socket = 0; memcpy(&packet->data[0], &buffer[0], n); send_agent(packet);*/ //write(respond_socket, &buffer[0], n, 0); //buffer[n] = 0; //debug(&buffer[0]); debug3("------ client rec length %d - %d\n", n, rec_n); //delete packet; } //} } current->set_is_closed(1); send_close_command(current->client_index,current->respond_socket); //current->unlock(); debug2("colsed (recthread) %d\n", current->client_index); //CloseHandle(recthandle0); return 0; } void tcp_client::tcp_init(void) { struct sockaddr_in serv_addr; struct hostent *server; ///////////////////////////////////////////////////// /// Error handler ///////////////////////////////////////////////////// WORD wVersionRequested; WSADATA wsaData; int err; /* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */ wVersionRequested = MAKEWORD(2, 2); err = WSAStartup(wVersionRequested, &wsaData); if (err != 0) { /* Tell the user that we could not find a usable */ /* Winsock DLL. */ debug("WSAStartup failed with error: %d\n", err); return ; } ///////////////////////////////////////////////////// //portno = atoi(argv[2]); sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) error("ERROR opening socket\n"); server = gethostbyname(ip_address); if (server == NULL) { //fprintf(stderr, "ERROR, no such host\n"); return; } //bzero((char *)&serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; //bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); memcpy((char *)&serv_addr.sin_addr.s_addr, (char *)server->h_addr, server->h_length); serv_addr.sin_port = htons(port); if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) error("ERROR connecting\n"); //printf("Please enter the message: "); //bzero(buffer, 256); //fgets(buffer, 255, stdin); //n = write(sockfd, request, strlen(request), 0); //if (n < 0) // error("ERROR writing to socket"); //bzero(buffer, 256); //DWORD WINAPI recthread(__in LPVOID lpParameter) // recthandle0 = CreateThread(0, 0, recthread, this, 0, &recthreadid0); //return 0; } void tcp_client::tcp_write_packet(sPacket * p) { if (p == nullptr) { debug2("tcp_write_packet: p is null"); return; } if (p->status == ePacket_Status::csNew) { client_index = p->packet_index; is_sending.lock(); int n0 = write(sockfd, p->data, p->data_length, 0); is_sending.unlock(); add_rec(n0); if (n0 < 0) { is_closed = 1; //send_close_command(); unlock(); debug2("ERROR writing to socket (client tcp_write_packet) %d\n", n0); } else //debug("sent %d\n", _len); { //_req[_len] = 0; //debug(_req); debug3("--------- client sent %d\n", n0); } } else if (p->status == ePacket_Status::csFinshedSuccess) { shutdown(sockfd,0); closesocket(sockfd); is_closed = 1; } else { debug3("packet status is incorrect\n"); } } void tcp_client::tcp_write(char * _req, int _len) { //write(sockfd, request, strlen(request), 0); //return; is_sending.lock(); int n0 = write(sockfd, _req, _len, 0); is_sending.unlock(); add_rec(n0); if (n0 < 0) { is_closed = 1; //send_close_command(); unlock(); debug2("ERROR writing to socket (client tcp_write) %d\n", n0); } else //debug("sent %d\n", _len); { //_req[_len] = 0; //debug(_req); debug3("--------- client sent %d\n", _len); } } char tcp_client::get_is_closed() { //if (this < (void*)0xffff) { return 1; } if (!this) { return 1; } //if (&is_closed == nullptr) { return 1; } //char _busy; //access_lock.lock(); return is_closed; //access_lock.unlock(); //return _busy; } void tcp_client::set_is_closed(char _value) { //if (this < (void*)0xffff) { return; } if (!this) { return ; } //if (&is_closed == nullptr) return; //access_lock.lock(); is_closed = _value; //access_lock.unlock(); } tcp_client::~tcp_client() { //if (this < (void*)0xffff) { return ;} *clients_connected--; if (!this ) { return ; } debug2("Dispose client class\n"); //send_close_command(); if (&recthandle0 != nullptr) { TerminateThread(recthandle0, 0); // Dangerous source of errors! CloseHandle(recthandle0); } //closesocket(sockfd); if (&sockfd != nullptr) { shutdown(sockfd, 0); } }
27.117264
489
0.626186
[ "object" ]
a77a9ea85168a86cfa75d0e6b37e219f6c33f6f6
5,327
cpp
C++
src/programs/libpfasst_swe_sphere/chooks.cpp
raaphy/sweet
69fcf1920becd4fd762ded2f726614aae00b3f69
[ "MIT" ]
6
2017-11-20T08:12:46.000Z
2021-03-11T15:32:36.000Z
src/programs/libpfasst_swe_sphere/chooks.cpp
raaphy/sweet
69fcf1920becd4fd762ded2f726614aae00b3f69
[ "MIT" ]
4
2018-02-02T21:46:33.000Z
2022-01-11T11:10:27.000Z
src/programs/libpfasst_swe_sphere/chooks.cpp
raaphy/sweet
69fcf1920becd4fd762ded2f726614aae00b3f69
[ "MIT" ]
12
2016-03-01T18:33:34.000Z
2022-02-08T22:20:31.000Z
#include "SphereDataVars.hpp" #include "SphereDataCtx.hpp" #include "ceval.hpp" extern "C" { void cecho_error(SphereData_Spectral* sd, int step) { // not implemented } void cecho_residual(SphereDataCtx *i_ctx, double i_norm, int i_current_proc, int i_current_step, int i_current_iter, int i_nnodes, int i_niters) { // get the residual vector std::vector<std::vector<double> >& residuals = i_ctx->get_residuals(); // save the residual residuals[i_current_proc].push_back(i_norm); } void cecho_output_invariants( SphereDataCtx *i_ctx, SphereDataVars *i_Y, int i_current_proc, int i_current_step, int i_current_iter, int i_nnodes, int i_niters ) { const SphereData_Spectral& phi_Y = i_Y->get_phi(); const SphereData_Spectral& vort_Y = i_Y->get_vort(); const SphereData_Spectral& div_Y = i_Y->get_div(); // get the current space-time level const int level = i_Y->get_level(); // get the simulation variables SimulationVariables* simVars = i_ctx->get_simulation_variables(); // get the SphereDiagnostics object from context SphereHelpers_Diagnostics* sphereDiagnostics = i_ctx->get_sphere_diagnostics(); // get the SphereOperators object from context SphereOperators_SphereData* sphereOperators = i_ctx->get_sphere_operators(level); // compute the invariants sphereDiagnostics->update_phi_vrt_div_2_mass_energy_enstrophy( *sphereOperators, phi_Y, vort_Y, div_Y, *simVars ); std::cout << std::setprecision(20) << "mass = " << simVars->diag.total_mass << " energy = " << simVars->diag.total_energy << " potential_enstrophy = " << simVars->diag.total_potential_enstrophy << std::endl; // save the invariants for plotting at the end i_ctx->save_physical_invariants(i_current_step); } void cecho_output_jump( SphereDataCtx *i_ctx, SphereDataVars *i_Y, int i_current_proc, int i_current_step, int i_current_iter, int i_nnodes, int i_niters ) { const SphereData_Spectral& phi_Y = i_Y->get_phi(); const SphereData_Spectral& vort_Y = i_Y->get_vort(); const SphereData_Spectral& div_Y = i_Y->get_div(); // write the data to file std::string filename = "prog_jump_phi_current_proc_"+std::to_string(i_current_proc) +"_current_step_"+std::to_string(i_current_step) +"_current_iter_"+std::to_string(i_current_iter) +"_nnodes_" +std::to_string(i_nnodes) +"_niters_" +std::to_string(i_niters); write_file(*i_ctx, phi_Y, filename.c_str()); filename = "prog_jump_vort_current_proc_"+std::to_string(i_current_proc) +"_current_step_"+std::to_string(i_current_step) +"_current_iter_"+std::to_string(i_current_iter) +"_nnodes_" +std::to_string(i_nnodes) +"_niters_" +std::to_string(i_niters); write_file(*i_ctx, vort_Y, filename.c_str()); filename = "prog_jump_div_current_proc_"+std::to_string(i_current_proc) +"_current_step_"+std::to_string(i_current_step) +"_current_iter_"+std::to_string(i_current_iter) +"_nnodes_" +std::to_string(i_nnodes) +"_niters_" +std::to_string(i_niters); write_file(*i_ctx, div_Y, filename.c_str()); } void cecho_output_solution( SphereDataCtx *i_ctx, SphereDataVars *i_Y, int i_current_proc, int i_current_step, int i_current_iter, int i_nnodes, int i_niters ) { const SphereData_Spectral& phi_Y = i_Y->get_phi(); const SphereData_Spectral& vort_Y = i_Y->get_vort(); const SphereData_Spectral& div_Y = i_Y->get_div(); // write the data to file std::string filename = "prog_phi_current_proc_"+std::to_string(i_current_proc) +"_current_step_"+std::to_string(i_current_step) +"_current_iter_"+std::to_string(i_current_iter) +"_nnodes_" +std::to_string(i_nnodes) +"_niters_" +std::to_string(i_niters); write_file(*i_ctx, phi_Y, filename.c_str()); filename = "prog_vort_current_proc_"+std::to_string(i_current_proc) +"_current_step_"+std::to_string(i_current_step) +"_current_iter_"+std::to_string(i_current_iter) +"_nnodes_" +std::to_string(i_nnodes) +"_niters_" +std::to_string(i_niters); write_file(*i_ctx, vort_Y, filename.c_str()); filename = "prog_div_current_proc_"+std::to_string(i_current_proc) +"_current_step_"+std::to_string(i_current_step) +"_current_iter_"+std::to_string(i_current_iter) +"_nnodes_" +std::to_string(i_nnodes) +"_niters_" +std::to_string(i_niters); write_file(*i_ctx, div_Y, filename.c_str()); } }
34.816993
89
0.607096
[ "object", "vector" ]
a77bf4a830a17f91b4b83e78915d8364b4c2cd5b
8,372
cpp
C++
programs/pyeos/interface/wasm_.cpp
learnforpractice/pyeos
4f04eb982c86c1fdb413084af77c713a6fda3070
[ "MIT" ]
144
2017-10-18T16:38:51.000Z
2022-01-09T12:43:57.000Z
programs/pyeos/interface/wasm_.cpp
openchatproject/safeos
2c8dbf57d186696ef6cfcbb671da9705b8f3d9f7
[ "MIT" ]
60
2017-10-11T13:07:43.000Z
2019-03-26T04:33:27.000Z
programs/pyeos/interface/wasm_.cpp
learnforpractice/pyeos
4f04eb982c86c1fdb413084af77c713a6fda3070
[ "MIT" ]
38
2017-12-05T01:13:56.000Z
2022-01-07T07:06:53.000Z
#include <algorithm> #include <eosio/chain/apply_context.hpp> #include <eosio/chain/controller.hpp> #include <eosio/chain/wasm_interface.hpp> #include <eosio/chain/micropython_interface.hpp> //#include <eosio/chain/webassembly/wavm.hpp> #include <eosio/chain/webassembly/binaryen.hpp> #include <eosio/chain/webassembly/runtime_interface.hpp> #include <eosio/chain/wasm_eosio_injection.hpp> #include <eosio/chain/generated_transaction_object.hpp> #include <eosio/chain/account_object.hpp> #include <eosio/chain/types.hpp> #include <eosio/chain_plugin/chain_plugin.hpp> #include <appbase/application.hpp> #include "IR/Module.h" #include "Runtime/Intrinsics.h" #include "Platform/Platform.h" #include "WAST/WAST.h" #include "IR/Validate.h" #include <fc/io/json.hpp> #include <fc/crypto/xxhash.h> //mpeoslib.cpp extern "C" void eosio_assert(int condition, const char* str); using namespace fc; using namespace eosio::chain::webassembly; using namespace IR; using namespace Runtime; namespace eosio { namespace chain { char code_buffer[128*1024]; class vm_wasm { //wasm_interface::vm_type vm public: vm_wasm() { runtime_wavm = std::make_unique<webassembly::wavm::wavm_runtime>(); runtime_binaryen = std::make_unique<webassembly::binaryen::binaryen_runtime>(); } static vm_wasm& get() { static vm_wasm* instance = 0; if (!instance) { instance = new vm_wasm(); } return *instance; } std::vector<uint8_t> parse_initial_memory(const Module& module) { std::vector<uint8_t> mem_image; for(const DataSegment& data_segment : module.dataSegments) { FC_ASSERT(data_segment.baseOffset.type == InitializerExpression::Type::i32_const); FC_ASSERT(module.memories.defs.size()); const U32 base_offset = data_segment.baseOffset.i32; const Uptr memory_size = (module.memories.defs[0].type.size.min << IR::numBytesPerPageLog2); if(base_offset >= memory_size || base_offset + data_segment.data.size() > memory_size) FC_THROW_EXCEPTION(wasm_execution_error, "WASM data segment outside of valid memory range"); if(base_offset + data_segment.data.size() > mem_image.size()) mem_image.resize(base_offset + data_segment.data.size(), 0x00); memcpy(mem_image.data() + base_offset, data_segment.data.data(), data_segment.data.size()); } return mem_image; } std::shared_ptr<wasm_instantiated_module_interface>& get_module(const digest_type& code_id, const string& code, wasm_interface::vm_type type = wasm_interface::vm_type::binaryen, bool cache=true ) { auto it = instantiation_cache.find(code_id); if(!cache || it == instantiation_cache.end() ) { IR::Module module; try { Serialization::MemoryInputStream stream((const U8*)code.c_str(), code.length()); WASM::serialize(stream, module); } catch(Serialization::FatalSerializationException& e) { EOS_ASSERT(false, wasm_serialization_error, e.message.c_str()); } wasm_injections::wasm_binary_injection injector(module); injector.inject(); std::vector<U8> bytes; try { Serialization::ArrayOutputStream outstream; WASM::serialize(outstream, module); bytes = outstream.getBytes(); } catch(Serialization::FatalSerializationException& e) { EOS_ASSERT(false, wasm_serialization_error, e.message.c_str()); } if (type == wasm_interface::vm_type::binaryen) { it = instantiation_cache.emplace(code_id, runtime_binaryen->instantiate_module((const char*)bytes.data(), bytes.size(), parse_initial_memory(module))).first; } else { it = instantiation_cache.emplace(code_id, runtime_wavm->instantiate_module((const char*)bytes.data(), bytes.size(), parse_initial_memory(module))).first; } } return it->second; } std::unique_ptr<webassembly::wavm::wavm_runtime> runtime_wavm; std::unique_ptr<wasm_runtime_interface> runtime_binaryen; map<digest_type, std::shared_ptr<wasm_instantiated_module_interface>> instantiation_cache; }; int wasm_test___(string& code, string& func, string& contract, string& action, string& args, map<string, string>& permissions, bool sign, bool rawargs) { wlog("+++++++++++++++++wasm_test_:${n}", ("n", contract)); try { // ilog("Converting argument to binary..."); auto ro_api = app().get_plugin<chain_plugin>().get_read_only_api(); auto rw_api = app().get_plugin<chain_plugin>().get_read_write_api(); eosio::chain_apis::read_only::abi_json_to_bin_params params; if (!rawargs) { params = {contract, action, fc::json::from_string(args)}; } else { std::vector<char> v(args.begin(), args.end()); params = {contract, action, fc::variant(v)}; } vector<chain::permission_level> accountPermissions; for (auto it = permissions.begin(); it != permissions.end(); it++) { accountPermissions.push_back(chain::permission_level{name(it->first), name(it->second)}); } vector<chain::action> actions; if (action.size() == 0) {//evm string _args; if (args[0] == '0' && args[1] == 'x') { _args = string(args.begin()+2, args.end()); } else { _args = args; } bytes v; v.resize(0); v.resize(_args.size()/2); fc::from_hex(_args, v.data(), v.size()); actions.emplace_back(accountPermissions, contract, action, v); } else { auto result = ro_api.abi_json_to_bin(params); actions.emplace_back(accountPermissions, contract, action, result.binargs); } #if 0 vector<uint64_t> _args; signed_transaction trx; trx.actions = std::forward<decltype(actions)>(actions); packed_transaction packed_trx(trx); transaction_metadata mtrx( packed_trx, fc::sha256(), fc::time_point::now()); chain_controller& mutable_controller = appbase::app().get_plugin<chain_plugin>().chain(); apply_context ctx(mutable_controller, mutable_controller.get_mutable_database(), actions[0], mtrx); auto code_id = fc::sha256::hash(code.c_str(), (uint32_t)code.length()); vm_wasm::get().get_module(code_id, code)->call(func, _args, ctx); #endif } catch (...) { return 0; } return 1; } int wasm_test_(string& code, string& func, vector<uint64_t>& args, uint64_t _account, uint64_t _action, vector<char>& data) { #if 0 vector<chain::permission_level> accountPermissions; accountPermissions.push_back(chain::permission_level{_account, name("active")}); action act; act.account = _account; act.name = _action; act.authorization = accountPermissions; act.data = data; signed_transaction trx; packed_transaction packed_trx(trx); transaction_metadata mtrx( packed_trx, fc::sha256(), fc::time_point::now()); chain_controller& mutable_controller = appbase::app().get_plugin<chain_plugin>().chain(); apply_context ctx(mutable_controller, mutable_controller.get_mutable_database(), act, mtrx); auto code_id = fc::sha256::hash(code.c_str(), (uint32_t)code.length()); vm_wasm::get().get_module(code_id, code)->call(func, args, ctx); #endif return 1; } uint64_t wasm_call2_(uint64_t account, string& file_name, string& func, vector<uint64_t>& args, vector<char>& result) { // chain_controller& mutable_controller = appbase::app().get_plugin<chain_plugin>().chain(); wlog("${n1}, ${n2}, ${n3}", ("n1", account)("n2", file_name)("n3", func)); apply_context& ctx = apply_context::ctx(); //FIXME key conflict uint64_t id = XXH64(file_name.c_str(), file_name.length(), 0); int itr = ctx.db_find_i64(account, account, account, id); if (itr < 0) { return -1; } int code_size = ctx.db_get_i64(itr, code_buffer, sizeof(code_buffer)); if (code_size <= 0) { return -1; } eosio_assert( code_buffer[0] == 3, "wrong code type"); string code(code_buffer+1, (code_size-1)); auto code_id = fc::sha256::hash(code.c_str(), (uint32_t)code.length()); uint64_t ret = vm_wasm::get().get_module(code_id, code)->call(func, args, ctx); wlog("call return ${n1}", ("n1", ret)); return ret; } }}
36.881057
200
0.667702
[ "vector" ]
a780f07e8c5e02ade68cb2e969ccf20b5a9fd819
966
cpp
C++
lintcode/minimumsizesubarraysum.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
1
2016-01-20T08:26:34.000Z
2016-01-20T08:26:34.000Z
lintcode/minimumsizesubarraysum.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
1
2015-10-21T05:38:17.000Z
2015-11-02T07:42:55.000Z
lintcode/minimumsizesubarraysum.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
null
null
null
class Solution { public: /** * @param nums: a vector of integers * @param s: an integer * @return: an integer representing the minimum size of subarray */ int minimumSize(vector<int> &nums, int s) { // write your code here int start=0; int end=0; int minlen=INT_MAX; int sum=0; while(end<nums.size()){ sum+=nums[end]; if(sum>=s){ // try to move start forward while(start<nums.size() && sum>=s){ sum-=nums[start]; start++; } //start-1 to end is just fit int len=end-(start-1)+1; if(minlen>len){ minlen=len; } } end++; } if(minlen==INT_MAX){ return -1; } return minlen; } };
24.15
68
0.39648
[ "vector" ]
a7846da8c191ac96e9ad7fb5b3184518e32120b2
2,775
cc
C++
paddle/fluid/train/test_train_recognize_digits.cc
ysh329/Paddle
50ad9046c9a440564d104eaa354eb9df83a35678
[ "Apache-2.0" ]
1
2019-09-05T07:32:44.000Z
2019-09-05T07:32:44.000Z
paddle/fluid/train/test_train_recognize_digits.cc
ysh329/Paddle
50ad9046c9a440564d104eaa354eb9df83a35678
[ "Apache-2.0" ]
1
2019-05-26T14:23:24.000Z
2019-05-26T14:23:51.000Z
paddle/fluid/train/test_train_recognize_digits.cc
ysh329/Paddle
50ad9046c9a440564d104eaa354eb9df83a35678
[ "Apache-2.0" ]
1
2019-11-27T11:58:44.000Z
2019-11-27T11:58:44.000Z
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. 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. */ #include <time.h> #include <fstream> #include "gflags/gflags.h" #include "gtest/gtest.h" #include "paddle/fluid/framework/executor.h" #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/framework/program_desc.h" #include "paddle/fluid/framework/tensor_util.h" #include "paddle/fluid/inference/io.h" #include "paddle/fluid/platform/device_context.h" #include "paddle/fluid/platform/init.h" #include "paddle/fluid/platform/place.h" DEFINE_string(dirname, "", "Directory of the train model."); namespace paddle { void Train() { CHECK(!FLAGS_dirname.empty()); framework::InitDevices(false); const auto cpu_place = platform::CPUPlace(); framework::Executor executor(cpu_place); framework::Scope scope; auto train_program = inference::Load( &executor, &scope, FLAGS_dirname + "__model_combined__.main_program", FLAGS_dirname + "__params_combined__"); std::string loss_name = ""; for (auto op_desc : train_program->Block(0).AllOps()) { if (op_desc->Type() == "mean") { loss_name = op_desc->Output("Out")[0]; break; } } PADDLE_ENFORCE_NE(loss_name, "", "loss not found"); // prepare data auto x_var = scope.Var("img"); auto x_tensor = x_var->GetMutable<framework::LoDTensor>(); x_tensor->Resize({64, 1, 28, 28}); auto x_data = x_tensor->mutable_data<float>(cpu_place); for (int i = 0; i < 64 * 28 * 28; ++i) { x_data[i] = 1.0; } auto y_var = scope.Var("label"); auto y_tensor = y_var->GetMutable<framework::LoDTensor>(); y_tensor->Resize({64, 1}); auto y_data = y_tensor->mutable_data<int64_t>(cpu_place); for (int i = 0; i < 64 * 1; ++i) { y_data[i] = static_cast<int64_t>(1); } auto loss_var = scope.Var(loss_name); float first_loss = 0.0; float last_loss = 0.0; for (int i = 0; i < 100; ++i) { executor.Run(*train_program, &scope, 0, false, true); if (i == 0) { first_loss = loss_var->Get<framework::LoDTensor>().data<float>()[0]; } else if (i == 99) { last_loss = loss_var->Get<framework::LoDTensor>().data<float>()[0]; } } EXPECT_LT(last_loss, first_loss); } TEST(train, recognize_digits) { Train(); } } // namespace paddle
30.833333
75
0.68973
[ "model" ]
a78c6ac1d8c17d5c51959e79321b09283153f985
2,588
cpp
C++
Libs/Widgets/Plugins/ctkCollapsibleGroupBoxPlugin.cpp
lassoan/CTK
ba271a053217d26e90dee35837cd3979c3bb5b8b
[ "Apache-2.0" ]
1
2018-11-15T17:02:06.000Z
2018-11-15T17:02:06.000Z
Libs/Widgets/Plugins/ctkCollapsibleGroupBoxPlugin.cpp
SlicerRt/CTK
4ff3dff4b9560b0dd78512ca7fc47999b0a8fca1
[ "Apache-2.0" ]
null
null
null
Libs/Widgets/Plugins/ctkCollapsibleGroupBoxPlugin.cpp
SlicerRt/CTK
4ff3dff4b9560b0dd78512ca7fc47999b0a8fca1
[ "Apache-2.0" ]
null
null
null
/*========================================================================= Library: CTK Copyright (c) Kitware Inc. 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.txt 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. =========================================================================*/ // Qt includes #include <QDebug> // CTK includes #include "ctkCollapsibleGroupBoxPlugin.h" #include "ctkCollapsibleGroupBox.h" // -------------------------------------------------------------------------- ctkCollapsibleGroupBoxPlugin::ctkCollapsibleGroupBoxPlugin(QObject *_parent) : QObject(_parent) { } // -------------------------------------------------------------------------- QWidget *ctkCollapsibleGroupBoxPlugin::createWidget(QWidget *_parent) { ctkCollapsibleGroupBox* _widget = new ctkCollapsibleGroupBox(_parent); return _widget; } // -------------------------------------------------------------------------- QString ctkCollapsibleGroupBoxPlugin::domXml() const { return "<widget class=\"ctkCollapsibleGroupBox\" \ name=\"CollapsibleGroupBox\">\n" " <property name=\"geometry\">\n" " <rect>\n" " <x>0</x>\n" " <y>0</y>\n" " <width>300</width>\n" " <height>100</height>\n" " </rect>\n" " </property>\n" " <property name=\"title\">" " <string>GroupBox</string>" " </property>" "</widget>\n"; } // -------------------------------------------------------------------------- QIcon ctkCollapsibleGroupBoxPlugin::icon() const { return QIcon(":/Icons/groupboxcollapsible.png"); } // -------------------------------------------------------------------------- QString ctkCollapsibleGroupBoxPlugin::includeFile() const { return "ctkCollapsibleGroupBox.h"; } // -------------------------------------------------------------------------- bool ctkCollapsibleGroupBoxPlugin::isContainer() const { return true; } // -------------------------------------------------------------------------- QString ctkCollapsibleGroupBoxPlugin::name() const { return "ctkCollapsibleGroupBox"; }
31.560976
95
0.501159
[ "geometry" ]
a78f6697f8f55405b88493f35223ffff79fd56b1
20,053
cpp
C++
examples/pxScene2d/external/WinSparkle/3rdparty/wxWidgets/samples/event/event.cpp
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
471
2019-06-26T09:59:09.000Z
2022-03-30T04:59:42.000Z
examples/pxScene2d/external/WinSparkle/3rdparty/wxWidgets/samples/event/event.cpp
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
1,432
2017-06-21T04:08:48.000Z
2020-08-25T16:21:15.000Z
examples/pxScene2d/external/WinSparkle/3rdparty/wxWidgets/samples/event/event.cpp
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
317
2017-06-20T19:57:17.000Z
2020-09-16T10:28:30.000Z
///////////////////////////////////////////////////////////////////////////// // Name: event.cpp // Purpose: wxWidgets sample demonstrating different event usage // Author: Vadim Zeitlin // Modified by: // Created: 31.01.01 // Copyright: (c) 2001-2009 Vadim Zeitlin // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif // for all others, include the necessary headers (this file is usually all you // need because it includes almost all "standard" wxWidgets headers) #ifndef WX_PRECOMP #include "wx/wx.h" #endif #ifndef wxHAS_IMAGES_IN_RESOURCES #include "../sample.xpm" #endif #include <wx/statline.h> #include <wx/log.h> // ---------------------------------------------------------------------------- // event constants // ---------------------------------------------------------------------------- // define a custom event type (we don't need a separate declaration here but // usually you would use a matching wxDECLARE_EVENT in a header) wxDEFINE_EVENT(wxEVT_MY_CUSTOM_COMMAND, wxCommandEvent); // it may also be convenient to define an event table macro for this event type #define EVT_MY_CUSTOM_COMMAND(id, fn) \ DECLARE_EVENT_TABLE_ENTRY( \ wxEVT_MY_CUSTOM_COMMAND, id, wxID_ANY, \ wxCommandEventHandler(fn), \ (wxObject *) NULL \ ), // ---------------------------------------------------------------------------- // private classes // ---------------------------------------------------------------------------- // Define a new application type, each program should derive a class from wxApp class MyApp : public wxApp { public: // override base class virtuals // ---------------------------- // this one is called on application startup and is a good place for the app // initialization (doing it here and not in the ctor allows to have an error // return: if OnInit() returns false, the application terminates) virtual bool OnInit(); // these are regular event handlers used to highlight the events handling // order void OnClickDynamicHandlerApp(wxCommandEvent& event); void OnClickStaticHandlerApp(wxCommandEvent& event); // we override wxConsoleApp::FilterEvent used to highlight the events // handling order virtual int FilterEvent(wxEvent& event); private: wxDECLARE_EVENT_TABLE(); }; // Define a custom button used to highlight the events handling order class MyEvtTestButton : public wxButton { public: static long BUTTON_ID; MyEvtTestButton(wxWindow *parent, const wxString& label) : wxButton(parent, BUTTON_ID, label) { // Add a dynamic handler for this button event to button itself Connect(wxEVT_BUTTON, wxCommandEventHandler(MyEvtTestButton::OnClickDynamicHandler)); } private: void OnClickDynamicHandler(wxCommandEvent& event) { wxLogMessage("Step 3 in \"How Events are Processed\":\n" "Button::ownDynamicHandler"); event.Skip(); } void OnClickStaticHandler(wxCommandEvent& event) { wxLogMessage("Step 4 in \"How Events are Processed\":\n" "Button::ownStaticHandler"); event.Skip(); } wxDECLARE_EVENT_TABLE(); }; long MyEvtTestButton::BUTTON_ID = wxNewId(); // Define a new frame type: this is going to be our main frame class MyFrame : public wxFrame { public: // ctor(s) MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size); virtual ~MyFrame(); void OnQuit(wxCommandEvent& event); void OnAbout(wxCommandEvent& event); #ifdef wxHAS_EVENT_BIND void OnBind(wxCommandEvent& event); #endif // wxHAS_EVENT_BIND void OnConnect(wxCommandEvent& event); void OnDynamic(wxCommandEvent& event); void OnPushEventHandler(wxCommandEvent& event); void OnPopEventHandler(wxCommandEvent& event); void OnTest(wxCommandEvent& event); void OnFireCustom(wxCommandEvent& event); void OnProcessCustom(wxCommandEvent& event); void OnUpdateUIPop(wxUpdateUIEvent& event); // regular event handlers used to highlight the events handling order void OnClickDynamicHandlerFrame(wxCommandEvent& event); void OnClickDynamicHandlerButton(wxCommandEvent& event); void OnClickStaticHandlerFrame(wxCommandEvent& event); private: // symbolic names for the status bar fields enum { Status_Main = 0, Status_Dynamic, Status_Push }; void UpdateDynamicStatus(bool on) { #if wxUSE_STATUSBAR if ( on ) { SetStatusText("You can now use \"Dynamic\" item in the menu"); SetStatusText("Dynamic: on", Status_Dynamic); } else { SetStatusText("You can no more use \"Dynamic\" item in the menu"); SetStatusText("Dynamic: off", Status_Dynamic); } #endif // wxUSE_STATUSBAR } // number of pushed event handlers unsigned m_nPush; // the button to whose event we connect dynamically wxButton *m_btnDynamic; // the button used to highlight the event handlers execution order MyEvtTestButton *m_testBtn; // any class wishing to process wxWidgets events must use this macro wxDECLARE_EVENT_TABLE(); }; // Define a custom event handler class MyEvtHandler : public wxEvtHandler { public: MyEvtHandler(size_t level) { m_level = level; } void OnTest(wxCommandEvent& event) { wxLogMessage(wxT("This is the pushed test event handler #%u"), m_level); // if we don't skip the event, the other event handlers won't get it: // try commenting out this line and see what changes event.Skip(); } private: unsigned m_level; wxDECLARE_EVENT_TABLE(); }; // ---------------------------------------------------------------------------- // constants // ---------------------------------------------------------------------------- // IDs for the controls and the menu commands enum { // menu items Event_Quit = 1, Event_About, Event_Bind, Event_Connect, Event_Dynamic, Event_Push, Event_Pop, Event_Custom, Event_Test }; // ---------------------------------------------------------------------------- // event tables and other macros for wxWidgets // ---------------------------------------------------------------------------- // The event tables connect the wxWidgets events with the functions (event // handlers) which process them. wxBEGIN_EVENT_TABLE(MyApp, wxApp) // Add a static handler for button Click event in the app EVT_BUTTON(MyEvtTestButton::BUTTON_ID, MyApp::OnClickStaticHandlerApp) wxEND_EVENT_TABLE() wxBEGIN_EVENT_TABLE(MyEvtTestButton, wxButton) // Add a static handler to this button itself for its own event EVT_BUTTON(BUTTON_ID, MyEvtTestButton::OnClickStaticHandler) wxEND_EVENT_TABLE() // This can be also done at run-time, but for the // simple menu events like this the static method is much simpler. wxBEGIN_EVENT_TABLE(MyFrame, wxFrame) EVT_MENU(Event_Quit, MyFrame::OnQuit) EVT_MENU(Event_About, MyFrame::OnAbout) #ifdef wxHAS_EVENT_BIND EVT_MENU(Event_Bind, MyFrame::OnBind) #endif // wxHAS_EVENT_BIND EVT_MENU(Event_Connect, MyFrame::OnConnect) EVT_MENU(Event_Custom, MyFrame::OnFireCustom) EVT_MENU(Event_Test, MyFrame::OnTest) EVT_MENU(Event_Push, MyFrame::OnPushEventHandler) EVT_MENU(Event_Pop, MyFrame::OnPopEventHandler) EVT_UPDATE_UI(Event_Pop, MyFrame::OnUpdateUIPop) EVT_MY_CUSTOM_COMMAND(wxID_ANY, MyFrame::OnProcessCustom) // the line below would also work if OnProcessCustom() were defined as // taking a wxEvent (as required by EVT_CUSTOM) and not wxCommandEvent //EVT_CUSTOM(wxEVT_MY_CUSTOM_COMMAND, wxID_ANY, MyFrame::OnProcessCustom) // Add a static handler in the parent frame for button event EVT_BUTTON(MyEvtTestButton::BUTTON_ID, MyFrame::OnClickStaticHandlerFrame) wxEND_EVENT_TABLE() wxBEGIN_EVENT_TABLE(MyEvtHandler, wxEvtHandler) EVT_MENU(Event_Test, MyEvtHandler::OnTest) wxEND_EVENT_TABLE() // Create a new application object: this macro will allow wxWidgets to create // the application object during program execution (it's better than using a // static object for many reasons) and also declares the accessor function // wxGetApp() which will return the reference of the right type (i.e. MyApp and // not wxApp) IMPLEMENT_APP(MyApp) // ============================================================================ // implementation // ============================================================================ // ---------------------------------------------------------------------------- // the application class // ---------------------------------------------------------------------------- // 'Main program' equivalent: the program execution "starts" here bool MyApp::OnInit() { if ( !wxApp::OnInit() ) return false; // create the main application window MyFrame *frame = new MyFrame(wxT("Event wxWidgets Sample"), wxPoint(50, 50), wxSize(600, 340)); // and show it (the frames, unlike simple controls, are not shown when // created initially) frame->Show(true); // Add a dynamic handler at the application level for the test button Connect(MyEvtTestButton::BUTTON_ID, wxEVT_BUTTON, wxCommandEventHandler(MyApp::OnClickDynamicHandlerApp)); // success: wxApp::OnRun() will be called which will enter the main message // loop and the application will run. If we returned false here, the // application would exit immediately. return true; } // This is always the first to handle an event ! int MyApp::FilterEvent(wxEvent& event) { if ( event.GetEventType() == wxEVT_BUTTON && event.GetId() == MyEvtTestButton::BUTTON_ID ) { wxLogMessage("Step 0 in \"How Events are Processed\":\n" "App::FilterEvent"); } return wxApp::FilterEvent(event); } void MyApp::OnClickDynamicHandlerApp(wxCommandEvent& event) { wxLogMessage("Step 7, 3 in \"How Events are Processed\":\n" "App::DynamicHandler_InAppTable"); event.Skip(); } void MyApp::OnClickStaticHandlerApp(wxCommandEvent& event) { wxLogMessage("Step 7, 4 in \"How Events are Processed\":\n" "App::StaticHandler_InAppTable"); wxLogMessage("Button click processed, there should be no more messages " "about handling events from the button.\n\n" "The log below shows the order in which the handlers " "were executed."); wxLog::FlushActive(); event.Skip(); } // ---------------------------------------------------------------------------- // main frame // ---------------------------------------------------------------------------- // frame constructor MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size) : wxFrame(NULL, wxID_ANY, title, pos, size) { SetIcon(wxICON(sample)); // init members m_nPush = 0; m_btnDynamic = NULL; // create a menu bar wxMenu *menuFile = new wxMenu; menuFile->Append(Event_About, wxT("&About\tCtrl-A"), wxT("Show about dialog")); menuFile->AppendSeparator(); menuFile->Append(Event_Quit, wxT("E&xit\tAlt-X"), wxT("Quit this program")); wxMenu *menuEvent = new wxMenu; #ifdef wxHAS_EVENT_BIND menuEvent->AppendCheckItem(Event_Bind, "&Bind\tCtrl-B", "Bind or unbind a dynamic event handler"); #endif // wxHAS_EVENT_BIND menuEvent->AppendCheckItem(Event_Connect, wxT("&Connect\tCtrl-C"), wxT("Connect or disconnect the dynamic event handler")); menuEvent->Append(Event_Dynamic, wxT("&Dynamic event\tCtrl-D"), wxT("Dynamic event sample - only works after Connect")); menuEvent->AppendSeparator(); menuEvent->Append(Event_Push, wxT("&Push event handler\tCtrl-P"), wxT("Push event handler for test event")); menuEvent->Append(Event_Pop, wxT("P&op event handler\tCtrl-O"), wxT("Pop event handler for test event")); menuEvent->Append(Event_Test, wxT("Test event\tCtrl-T"), wxT("Test event processed by pushed event handler")); menuEvent->AppendSeparator(); menuEvent->Append(Event_Custom, wxT("Fire c&ustom event\tCtrl-U"), wxT("Generate a custom event")); // now append the freshly created menu to the menu bar... wxMenuBar *menuBar = new wxMenuBar(); menuBar->Append(menuFile, wxT("&File")); menuBar->Append(menuEvent, wxT("&Event")); // ... and attach this menu bar to the frame SetMenuBar(menuBar); #if wxUSE_STATUSBAR CreateStatusBar(3); SetStatusText(wxT("Welcome to wxWidgets event sample")); SetStatusText(wxT("Dynamic: off"), Status_Dynamic); SetStatusText(wxT("Push count: 0"), Status_Push); #endif // wxUSE_STATUSBAR wxPanel * const panel = new wxPanel(this); wxSizer * const mainSizer = new wxBoxSizer(wxVERTICAL); wxSizer * const sizer = new wxBoxSizer(wxHORIZONTAL); const wxSizerFlags centreY(wxSizerFlags().Centre().Border()); sizer->Add(new wxStaticText(panel, wxID_ANY, "This button will only work if its handler is dynamically connected"), centreY); m_btnDynamic = new wxButton(panel, Event_Dynamic, "&Dynamic button"); sizer->Add(m_btnDynamic, centreY); mainSizer->Add(sizer, 1, wxEXPAND); mainSizer->Add(new wxStaticLine(panel), 0, wxEXPAND); mainSizer->Add(new wxStaticLine(panel), 0, wxEXPAND); m_testBtn = new MyEvtTestButton(panel, "Test Event Handlers Execution Order"); // After being created, an instance of MyEvtTestButton already has its own // event handlers (see class definition); // Add a dynamic handler for this button event in the parent frame Connect(m_testBtn->GetId(), wxEVT_BUTTON, wxCommandEventHandler(MyFrame::OnClickDynamicHandlerFrame)); // Bind a method of this frame (notice "this" argument!) to the button // itself m_testBtn->Connect(wxEVT_BUTTON, wxCommandEventHandler(MyFrame::OnClickDynamicHandlerButton), NULL, this); mainSizer->Add(m_testBtn); panel->SetSizer(mainSizer); } MyFrame::~MyFrame() { // we must pop any remaining event handlers to avoid memory leaks and // crashes! while ( m_nPush-- != 0 ) { PopEventHandler(true /* delete handler */); } } // ---------------------------------------------------------------------------- // standard event handlers // ---------------------------------------------------------------------------- void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event)) { // true is to force the frame to close Close(true); } void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event)) { wxMessageBox("Event sample shows different ways of using events\n" "(c) 2001-2009 Vadim Zeitlin", "About wxWidgets Event Sample", wxOK | wxICON_INFORMATION, this); } void MyFrame::OnClickStaticHandlerFrame(wxCommandEvent& event) { wxLogMessage("Step 6, 4 in \"How Events are Processed\":\n" "parentWin::StaticHandler_InFrameTable"); event.Skip(); } // ---------------------------------------------------------------------------- // dynamic event handling stuff // ---------------------------------------------------------------------------- void MyFrame::OnClickDynamicHandlerFrame(wxCommandEvent& event) { wxLogMessage("Step 6, 3 in \"How Events are Processed\":\n" "parentWin::DynamicHandler_InFrameTable"); event.Skip(); } void MyFrame::OnClickDynamicHandlerButton(wxCommandEvent& event) { wxLogMessage("Step 3 in \"How Events are Processed\":\n" "parentWin::DynamicHandler_InButtonTable"); event.Skip(); } void MyFrame::OnDynamic(wxCommandEvent& event) { wxString origin; if ( event.GetEventObject() == this ) origin = "menu item"; else if ( event.GetEventObject() == m_btnDynamic ) origin = "button"; else origin = "unknown event source"; wxMessageBox ( "This message box is shown from the dynamically connected " "event handler in response to event generated by " + origin, "wxWidgets Event Sample", wxOK | wxICON_INFORMATION, this ); } #ifdef wxHAS_EVENT_BIND void MyFrame::OnBind(wxCommandEvent& event) { if ( event.IsChecked() ) { // as we bind directly to the button, there is no need to use an id // here: the button will only ever get its own events m_btnDynamic->Bind(wxEVT_BUTTON, &MyFrame::OnDynamic, this); // but we do need the id for the menu command as the frame gets all of // them Bind(wxEVT_MENU, &MyFrame::OnDynamic, this, Event_Dynamic); } else // disconnect { m_btnDynamic->Unbind(wxEVT_BUTTON, &MyFrame::OnDynamic, this); Unbind(wxEVT_MENU, &MyFrame::OnDynamic, this, Event_Dynamic); } UpdateDynamicStatus(event.IsChecked()); } #endif // wxHAS_EVENT_BIND void MyFrame::OnConnect(wxCommandEvent& event) { if ( event.IsChecked() ) { m_btnDynamic->Connect(wxID_ANY, wxEVT_BUTTON, wxCommandEventHandler(MyFrame::OnDynamic), NULL, this); Connect(Event_Dynamic, wxEVT_MENU, wxCommandEventHandler(MyFrame::OnDynamic)); } else // disconnect { m_btnDynamic->Disconnect(wxID_ANY, wxEVT_BUTTON, wxCommandEventHandler(MyFrame::OnDynamic), NULL, this); Disconnect(Event_Dynamic, wxEVT_MENU, wxCommandEventHandler(MyFrame::OnDynamic)); } UpdateDynamicStatus(event.IsChecked()); } // ---------------------------------------------------------------------------- // push/pop event handlers support // ---------------------------------------------------------------------------- void MyFrame::OnPushEventHandler(wxCommandEvent& WXUNUSED(event)) { PushEventHandler(new MyEvtHandler(++m_nPush)); #if wxUSE_STATUSBAR SetStatusText(wxString::Format(wxT("Push count: %u"), m_nPush), Status_Push); #endif // wxUSE_STATUSBAR } void MyFrame::OnPopEventHandler(wxCommandEvent& WXUNUSED(event)) { wxCHECK_RET( m_nPush, wxT("this command should be disabled!") ); PopEventHandler(true /* delete handler */); m_nPush--; #if wxUSE_STATUSBAR SetStatusText(wxString::Format(wxT("Push count: %u"), m_nPush), Status_Push); #endif // wxUSE_STATUSBAR } void MyFrame::OnTest(wxCommandEvent& WXUNUSED(event)) { wxLogMessage(wxT("This is the test event handler in the main frame")); } void MyFrame::OnUpdateUIPop(wxUpdateUIEvent& event) { event.Enable( m_nPush > 0 ); } // ---------------------------------------------------------------------------- // custom event methods // ---------------------------------------------------------------------------- void MyFrame::OnFireCustom(wxCommandEvent& WXUNUSED(event)) { wxCommandEvent eventCustom(wxEVT_MY_CUSTOM_COMMAND); wxPostEvent(this, eventCustom); } void MyFrame::OnProcessCustom(wxCommandEvent& WXUNUSED(event)) { wxLogMessage(wxT("Got a custom event!")); }
32.553571
83
0.599412
[ "object" ]
0427e2ea0ed911aa0ab2f4028781f00be7beeb21
31,626
cc
C++
chrome/browser/ui/app_list/arc/arc_app_icon.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
chrome/browser/ui/app_list/arc/arc_app_icon.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/browser/ui/app_list/arc/arc_app_icon.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/app_list/arc/arc_app_icon.h" #include <algorithm> #include <map> #include <memory> #include <utility> #include <vector> #include "base/bind.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/lazy_instance.h" #include "base/macros.h" #include "base/metrics/histogram_functions.h" #include "base/no_destructor.h" #include "base/task/post_task.h" #include "base/task/thread_pool.h" #include "chrome/browser/image_decoder/image_decoder.h" #include "chrome/browser/ui/app_list/arc/arc_app_icon_descriptor.h" #include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h" #include "chrome/browser/ui/app_list/arc/arc_app_utils.h" #include "chrome/browser/ui/ash/launcher/arc_app_shelf_id.h" #include "chrome/grit/component_extension_resources.h" #include "content/public/browser/browser_thread.h" #include "extensions/grit/extensions_browser_resources.h" #include "services/data_decoder/public/cpp/data_decoder.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/image/image_skia_operations.h" #include "ui/gfx/image/image_skia_source.h" namespace { bool disable_safe_decoding_for_testing = false; data_decoder::DataDecoder& GetDataDecoder() { static base::NoDestructor<data_decoder::DataDecoder> data_decoder; return *data_decoder; } } // namespace //////////////////////////////////////////////////////////////////////////////// // ArcAppIcon::ReadResult ArcAppIcon::ReadResult::ReadResult(bool error, bool request_to_install, ui::ScaleFactor scale_factor, bool resize_allowed, std::vector<std::string> unsafe_icon_data) : error(error), request_to_install(request_to_install), scale_factor(scale_factor), resize_allowed(resize_allowed), unsafe_icon_data(std::move(unsafe_icon_data)) {} ArcAppIcon::ReadResult::~ReadResult() = default; //////////////////////////////////////////////////////////////////////////////// // ArcAppIcon::Source // Initializes the ImageSkia with placeholder bitmaps, decoded from // compiled-into-the-binary resources such as IDR_APP_DEFAULT_ICON, and // schedules the asynchronous loading of the app's actual bitmaps. class ArcAppIcon::Source : public gfx::ImageSkiaSource { public: Source(const base::WeakPtr<ArcAppIcon>& host, int resource_size_in_dip); ~Source() override; private: // gfx::ImageSkiaSource overrides: gfx::ImageSkiaRep GetImageForScale(float scale) override; // Used to load images asynchronously. NULLed out when the ArcAppIcon is // destroyed. base::WeakPtr<ArcAppIcon> host_; const int resource_size_in_dip_; // A map from a pair of a resource ID and size in DIP to an image. This // is a cache to avoid resizing IDR icons in GetImageForScale every time. static base::LazyInstance<std::map<std::pair<int, int>, gfx::ImageSkia>>:: DestructorAtExit default_icons_cache_; DISALLOW_COPY_AND_ASSIGN(Source); }; base::LazyInstance<std::map<std::pair<int, int>, gfx::ImageSkia>>:: DestructorAtExit ArcAppIcon::Source::default_icons_cache_ = LAZY_INSTANCE_INITIALIZER; ArcAppIcon::Source::Source(const base::WeakPtr<ArcAppIcon>& host, int resource_size_in_dip) : host_(host), resource_size_in_dip_(resource_size_in_dip) { } ArcAppIcon::Source::~Source() { } gfx::ImageSkiaRep ArcAppIcon::Source::GetImageForScale(float scale) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); // Host loads icon asynchronously, so use default icon so far. int resource_id; if (host_ && host_->app_id() == arc::kPlayStoreAppId) { // Don't request icon from Android side. Use overloaded Chrome icon for Play // Store that is adapted according Chrome style. const int resource_size_in_px = static_cast<int>(resource_size_in_dip_ * scale + 0.5); resource_id = resource_size_in_px <= 32 ? IDR_ARC_SUPPORT_ICON_32 : IDR_ARC_SUPPORT_ICON_192; } else { if (host_) host_->LoadForScaleFactor(ui::GetSupportedScaleFactor(scale)); resource_id = IDR_APP_DEFAULT_ICON; } // Check |default_icons_cache_| and returns the existing one if possible. const auto key = std::make_pair(resource_id, resource_size_in_dip_); const auto it = default_icons_cache_.Get().find(key); if (it != default_icons_cache_.Get().end()) return it->second.GetRepresentation(scale); const gfx::ImageSkia* default_image = ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(resource_id); CHECK(default_image); gfx::ImageSkia resized_image = gfx::ImageSkiaOperations::CreateResizedImage( *default_image, skia::ImageOperations::RESIZE_BEST, gfx::Size(resource_size_in_dip_, resource_size_in_dip_)); // Add the resized image to the cache to avoid executing the expensive resize // operation many times. Caching the result is safe because unlike ARC icons // that can be updated dynamically, IDR icons are static. default_icons_cache_.Get().insert(std::make_pair(key, resized_image)); return resized_image.GetRepresentation(scale); } class ArcAppIcon::DecodeRequest : public ImageDecoder::ImageRequest { public: DecodeRequest( ArcAppIcon& host, const ArcAppIconDescriptor& descriptor, bool resize_allowed, bool retain_padding, gfx::ImageSkia& image_skia, std::map<ui::ScaleFactor, base::Time>& incomplete_scale_factors); ~DecodeRequest() override; // ImageDecoder::ImageRequest void OnImageDecoded(const SkBitmap& bitmap) override; void OnDecodeImageFailed() override; private: ArcAppIcon& host_; const ArcAppIconDescriptor descriptor_; const bool resize_allowed_; const bool retain_padding_; gfx::ImageSkia& image_skia_; std::map<ui::ScaleFactor, base::Time>& incomplete_scale_factors_; DISALLOW_COPY_AND_ASSIGN(DecodeRequest); }; //////////////////////////////////////////////////////////////////////////////// // ArcAppIcon::DecodeRequest ArcAppIcon::DecodeRequest::DecodeRequest( ArcAppIcon& host, const ArcAppIconDescriptor& descriptor, bool resize_allowed, bool retain_padding, gfx::ImageSkia& image_skia, std::map<ui::ScaleFactor, base::Time>& incomplete_scale_factors) : ImageRequest(&GetDataDecoder()), host_(host), descriptor_(descriptor), resize_allowed_(resize_allowed), retain_padding_(retain_padding), image_skia_(image_skia), incomplete_scale_factors_(incomplete_scale_factors) {} ArcAppIcon::DecodeRequest::~DecodeRequest() { ImageDecoder::Cancel(this); } void ArcAppIcon::DecodeRequest::OnImageDecoded(const SkBitmap& bitmap) { DCHECK(!bitmap.isNull() && !bitmap.empty()); const int expected_dim = descriptor_.GetSizeInPixels(); // If retain_padding is true, that means the foreground or the // background image has paddings which should be chopped by AppService, so the // raw image is forwarded without resize. if (!retain_padding_ && (bitmap.width() != expected_dim || bitmap.height() != expected_dim)) { if (!resize_allowed_) { VLOG(2) << "Decoded ARC icon has unexpected dimension " << bitmap.width() << "x" << bitmap.height() << ". Expected " << expected_dim << "."; host_.MaybeRequestIcon(descriptor_.scale_factor); } else { host_.UpdateImageSkia(descriptor_.scale_factor, skia::ImageOperations::Resize( bitmap, skia::ImageOperations::RESIZE_BEST, expected_dim, expected_dim), image_skia_, incomplete_scale_factors_); } } else { host_.UpdateImageSkia(descriptor_.scale_factor, bitmap, image_skia_, incomplete_scale_factors_); } host_.DiscardDecodeRequest(this, true /* bool is_decode_success */); } void ArcAppIcon::DecodeRequest::OnDecodeImageFailed() { VLOG(2) << "Failed to decode ARC icon."; host_.MaybeRequestIcon(descriptor_.scale_factor); host_.DiscardDecodeRequest(this, false /* bool is_decode_success*/); } //////////////////////////////////////////////////////////////////////////////// // ArcAppIcon // static void ArcAppIcon::DisableSafeDecodingForTesting() { disable_safe_decoding_for_testing = true; } // static bool ArcAppIcon::IsSafeDecodingDisabledForTesting() { return disable_safe_decoding_for_testing; } ArcAppIcon::ArcAppIcon(content::BrowserContext* context, const std::string& app_id, int resource_size_in_dip, Observer* observer, IconType icon_type) : context_(context), app_id_(app_id), mapped_app_id_(arc::GetAppFromAppOrGroupId(context, app_id)), resource_size_in_dip_(resource_size_in_dip), observer_(observer), icon_type_(icon_type) { CHECK(observer_); gfx::Size resource_size(resource_size_in_dip, resource_size_in_dip); const std::vector<ui::ScaleFactor>& scale_factors = ui::GetSupportedScaleFactors(); switch (icon_type) { case IconType::kAdaptive: foreground_image_skia_ = gfx::ImageSkia( std::make_unique<Source>(weak_ptr_factory_.GetWeakPtr(), resource_size_in_dip), resource_size); // ArcAppIcon::Source::GetImageForScale calls host_->LoadForScaleFactor to // read both the foreground and background files, so the // |background_image_skia_| doesn't need to set the host to call // LoadForScaleFactor again. Otherwise, it might duplicate the opened // files number, and cause the system crash, background_image_skia_ = gfx::ImageSkia( std::make_unique<Source>(nullptr, resource_size_in_dip), resource_size); for (const auto& scale_factor : scale_factors) { foreground_incomplete_scale_factors_.insert( {scale_factor, base::Time::Now()}); background_incomplete_scale_factors_.insert( {scale_factor, base::Time::Now()}); is_adaptive_icons_.insert({scale_factor, true}); } // Deliberately fall through to IconType::kUncompressed to update // |image_skia_| and |incomplete_scale_factors_|. FALLTHROUGH; case IconType::kUncompressed: image_skia_ = gfx::ImageSkia( std::make_unique<Source>(weak_ptr_factory_.GetWeakPtr(), resource_size_in_dip), resource_size); // Deliberately fall through to IconType::kCompressed to update // |incomplete_scale_factors_|. FALLTHROUGH; case IconType::kCompressed: for (const auto& scale_factor : scale_factors) { incomplete_scale_factors_.insert({scale_factor, base::Time::Now()}); if (icon_type != IconType::kAdaptive) is_adaptive_icons_.insert({scale_factor, false}); } break; } } ArcAppIcon::~ArcAppIcon() = default; void ArcAppIcon::LoadSupportedScaleFactors() { switch (icon_type_) { case IconType::kCompressed: for (auto scale_factor : incomplete_scale_factors_) LoadForScaleFactor(scale_factor.first); break; case IconType::kAdaptive: for (auto scale_factor : foreground_incomplete_scale_factors_) { foreground_image_skia_.GetRepresentation( ui::GetScaleForScaleFactor(scale_factor.first)); } for (auto scale_factor : background_incomplete_scale_factors_) { background_image_skia_.GetRepresentation( ui::GetScaleForScaleFactor(scale_factor.first)); } // Deliberately fall through to IconType::kCompressed to update // |image_skia_|. FALLTHROUGH; case IconType::kUncompressed: // Calling GetRepresentation indirectly calls LoadForScaleFactor but also // first initializes image_skia_ with the placeholder icons (e.g. // IDR_APP_DEFAULT_ICON), via ArcAppIcon::Source::GetImageForScale. for (auto scale_factor : incomplete_scale_factors_) { image_skia_.GetRepresentation( ui::GetScaleForScaleFactor(scale_factor.first)); } break; } } bool ArcAppIcon::EverySupportedScaleFactorIsLoaded() { switch (icon_type_) { case IconType::kUncompressed: // Deliberately fall through to IconType::kCompressed to check // |incomplete_scale_factors_|. FALLTHROUGH; case IconType::kCompressed: return incomplete_scale_factors_.empty(); case IconType::kAdaptive: { // Check whether there is non-adaptive icon for any scale. bool is_adaptive_icon = true; for (const auto& it : is_adaptive_icons_) { if (!it.second) { is_adaptive_icon = false; break; } } // All scales have adaptive icon. if (is_adaptive_icon) { return foreground_incomplete_scale_factors_.empty() && background_incomplete_scale_factors_.empty(); } // Some scales have non-adaptive icons. Copy the decode image // representation from |foreground_image_skia_| to |image_skia_|. for (auto it = is_adaptive_icons_.begin(); it != is_adaptive_icons_.end(); it++) { if (it->second && !base::Contains(foreground_incomplete_scale_factors_, it->first)) { it->second = false; float scale = ui::GetScaleForScaleFactor(it->first); image_skia_.RemoveRepresentation(scale); image_skia_.AddRepresentation( foreground_image_skia_.GetRepresentation(scale)); image_skia_.RemoveUnsupportedRepresentationsForScale(scale); incomplete_scale_factors_.erase(it->first); } } return incomplete_scale_factors_.empty(); } } } void ArcAppIcon::LoadForScaleFactor(ui::ScaleFactor scale_factor) { // We provide Play Store icon from Chrome resources and it is not expected // that we have external load request. DCHECK_NE(app_id(), arc::kPlayStoreAppId); ArcAppListPrefs* const prefs = ArcAppListPrefs::Get(context_); DCHECK(prefs); const ArcAppIconDescriptor descriptor(resource_size_in_dip_, scale_factor); std::vector<base::FilePath> paths; std::vector<base::FilePath> default_app_paths; switch (icon_type_) { case IconType::kAdaptive: { base::FilePath foreground_path = prefs->GetForegroundIconPath(mapped_app_id_, descriptor); base::FilePath background_path = prefs->GetBackgroundIconPath(mapped_app_id_, descriptor); if (foreground_path.empty() || background_path.empty()) return; paths.emplace_back(foreground_path); paths.emplace_back(background_path); default_app_paths.emplace_back( prefs->MaybeGetForegroundIconPathForDefaultApp(mapped_app_id_, descriptor)); default_app_paths.emplace_back( prefs->MaybeGetBackgroundIconPathForDefaultApp(mapped_app_id_, descriptor)); // Deliberately fall through to IconType::kCompressed to add |path| to // |paths|. For the migration scenario, when the foreground icon file // doesn't exist, load the original icon file to resolve the icon lag // issue. FALLTHROUGH; } case IconType::kUncompressed: { // Deliberately fall through to IconType::kCompressed to add |path| to // |paths|. FALLTHROUGH; } case IconType::kCompressed: { base::FilePath path = prefs->GetIconPath(mapped_app_id_, descriptor); if (path.empty()) return; paths.emplace_back(path); default_app_paths.emplace_back( prefs->MaybeGetIconPathForDefaultApp(mapped_app_id_, descriptor)); break; } } base::ThreadPool::PostTaskAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::BindOnce(&ArcAppIcon::ReadOnBackgroundThread, icon_type_, scale_factor, paths, default_app_paths), base::BindOnce(&ArcAppIcon::OnIconRead, weak_ptr_factory_.GetWeakPtr())); } void ArcAppIcon::MaybeRequestIcon(ui::ScaleFactor scale_factor) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); ArcAppListPrefs* prefs = ArcAppListPrefs::Get(context_); DCHECK(prefs); // ArcAppListPrefs notifies the ArcAppIconLoader (which is an // ArcAppListPrefs::Observer) when the icon is updated, and // ArcAppIconLoader::OnAppIconUpdated calls ArcAppIcon::LoadForScaleFactor on // the corresponding ArcAppIcon. prefs->MaybeRequestIcon( mapped_app_id_, ArcAppIconDescriptor(resource_size_in_dip_, scale_factor)); } // static std::unique_ptr<ArcAppIcon::ReadResult> ArcAppIcon::ReadOnBackgroundThread( ArcAppIcon::IconType icon_type, ui::ScaleFactor scale_factor, const std::vector<base::FilePath>& paths, const std::vector<base::FilePath>& default_app_paths) { DCHECK(!paths.empty()); switch (icon_type) { case IconType::kUncompressed: // Deliberately fall through to IconType::kCompressed. FALLTHROUGH; case IconType::kCompressed: DCHECK_EQ(1u, paths.size()); return ArcAppIcon::ReadSingleIconFile(scale_factor, paths[0], default_app_paths[0]); case IconType::kAdaptive: return ArcAppIcon::ReadAdaptiveIconFiles(scale_factor, paths, default_app_paths); } } // static std::unique_ptr<ArcAppIcon::ReadResult> ArcAppIcon::ReadSingleIconFile( ui::ScaleFactor scale_factor, const base::FilePath& path, const base::FilePath& default_app_path) { DCHECK(!path.empty()); base::FilePath path_to_read; // Allow resizing only for default app icons. bool resize_allowed; if (base::PathExists(path)) { path_to_read = path; resize_allowed = false; } else { if (default_app_path.empty() || !base::PathExists(default_app_path)) { return std::make_unique<ArcAppIcon::ReadResult>( false /* error */, true /* request_to_install */, scale_factor, false /* resize_allowed */, std::vector<std::string>() /* unsafe_icon_data */); } path_to_read = default_app_path; resize_allowed = true; } bool request_to_install = path_to_read != path; return ArcAppIcon::ReadFile(request_to_install, scale_factor, resize_allowed, path_to_read); } // static std::unique_ptr<ArcAppIcon::ReadResult> ArcAppIcon::ReadAdaptiveIconFiles( ui::ScaleFactor scale_factor, const std::vector<base::FilePath>& paths, const std::vector<base::FilePath>& default_app_paths) { DCHECK_EQ(3u, paths.size()); const base::FilePath& foreground_path = paths[0]; const base::FilePath& background_path = paths[1]; if (!base::PathExists(foreground_path)) { // For the migration scenario, when the foreground icon file doesn't // exist, load the original icon file to resolve the icon lag issue. if (!paths[2].empty() && base::PathExists(paths[2])) { return ArcAppIcon::ReadFile(true /* request_to_install */, scale_factor, false /* resize_allowed */, paths[2]); } // Check and read the default app icon path for the default app if the files // exist. return ReadDefaultAppAdaptiveIconFiles(scale_factor, default_app_paths); } if (!base::PathExists(background_path)) { // For non-adaptive icon, there could be a |foreground_icon_path| file // only without a |background_icon_path| file. base::UmaHistogramBoolean("Arc.AdaptiveIconLoad.FromArcAppIcon", false); return ArcAppIcon::ReadFile(false /* request_to_install */, scale_factor, false /* resize_allowed */, foreground_path); } base::UmaHistogramBoolean("Arc.AdaptiveIconLoad.FromArcAppIcon", true); return ArcAppIcon::ReadFiles(false /* request_to_install */, scale_factor, false /* resize_allowed */, foreground_path, background_path); } // static std::unique_ptr<ArcAppIcon::ReadResult> ArcAppIcon::ReadDefaultAppAdaptiveIconFiles( ui::ScaleFactor scale_factor, const std::vector<base::FilePath>& default_app_paths) { // Check the default app icon path, and read the icon files for the default // app if the files exist. DCHECK_EQ(3u, default_app_paths.size()); const base::FilePath& default_app_foreground_path = default_app_paths[0]; const base::FilePath& default_app_background_path = default_app_paths[1]; if (default_app_foreground_path.empty() || !base::PathExists(default_app_foreground_path)) { // For the migration scenario, when the foreground icon file doesn't // exist, load the original icon file to resolve the icon lag issue for // the default app. if (default_app_paths.size() == 3u && !default_app_paths[2].empty() && base::PathExists(default_app_paths[2])) { return ArcAppIcon::ReadFile(true /* request_to_install */, scale_factor, true /* resize_allowed */, default_app_paths[2]); } return std::make_unique<ArcAppIcon::ReadResult>( false /* error */, true /* request_to_install */, scale_factor, false /* resize_allowed */, std::vector<std::string>() /* unsafe_icon_data */); } if (default_app_background_path.empty() || !base::PathExists(default_app_background_path)) { // For non-adaptive icon, there could be a |default_app_foreground_path| // file only without a |default_app_background_path| file. base::UmaHistogramBoolean("Arc.AdaptiveIconLoad.FromArcDefaultAppIcon", false); return ArcAppIcon::ReadFile(true /* request_to_install */, scale_factor, true /* resize_allowed */, default_app_foreground_path); } base::UmaHistogramBoolean("Arc.AdaptiveIconLoad.FromArcDefaultAppIcon", true); return ArcAppIcon::ReadFiles( true /* request_to_install */, scale_factor, true /* resize_allowed */, default_app_foreground_path, default_app_background_path); } // static std::unique_ptr<ArcAppIcon::ReadResult> ArcAppIcon::ReadFile( bool request_to_install, ui::ScaleFactor scale_factor, bool resize_allowed, const base::FilePath& path) { // Read the file from disk. Sometimes, the file could be deleted, e.g. when // running unit tests, so check whether the file exists again. std::string unsafe_icon_data; if (path.empty() || !base::PathExists(path) || !base::ReadFileToString(path, &unsafe_icon_data) || unsafe_icon_data.empty()) { VLOG(2) << "Failed to read an ARC icon from file " << path.MaybeAsASCII(); // If |unsafe_icon_data| is empty typically means we have a file corruption // on cached icon file. Send request to re install the icon. request_to_install |= unsafe_icon_data.empty(); return std::make_unique<ArcAppIcon::ReadResult>( true /* error */, request_to_install, scale_factor, false /* resize_allowed */, std::vector<std::string>() /* unsafe_icon_data */); } return std::make_unique<ArcAppIcon::ReadResult>( false /* error */, request_to_install, scale_factor, resize_allowed, std::vector<std::string>{std::move(unsafe_icon_data)}); } // static std::unique_ptr<ArcAppIcon::ReadResult> ArcAppIcon::ReadFiles( bool request_to_install, ui::ScaleFactor scale_factor, bool resize_allowed, const base::FilePath& foreground_path, const base::FilePath& background_path) { // Read the file from disk. Sometimes, the file could be deleted, e.g. when // running unit tests, so check whether the file exists again. std::string unsafe_foreground_icon_data; std::string unsafe_background_icon_data; if (foreground_path.empty() || !base::PathExists(foreground_path) || !base::ReadFileToString(foreground_path, &unsafe_foreground_icon_data) || unsafe_foreground_icon_data.empty()) { VLOG(2) << "Failed to read an ARC icon from file " << foreground_path.MaybeAsASCII(); // If |unsafe_icon_data| is empty typically means we have a file corruption // on cached icon file. Send request to re install the icon. request_to_install |= unsafe_foreground_icon_data.empty(); return std::make_unique<ArcAppIcon::ReadResult>( true /* error */, true /* request_to_install */, scale_factor, false /* resize_allowed */, std::vector<std::string>() /* unsafe_icon_data */); } if (background_path.empty() || !base::PathExists(background_path) || !base::ReadFileToString(background_path, &unsafe_background_icon_data) || unsafe_background_icon_data.empty()) { VLOG(2) << "Failed to read an ARC icon from file " << background_path.MaybeAsASCII(); // If |unsafe_icon_data| is empty typically means we have a file corruption // on cached icon file. Send request to re install the icon. request_to_install |= unsafe_background_icon_data.empty(); return std::make_unique<ArcAppIcon::ReadResult>( true /* error */, true /* request_to_install */, scale_factor, false /* resize_allowed */, std::vector<std::string>() /* unsafe_icon_data */); } return std::make_unique<ArcAppIcon::ReadResult>( false /* error */, request_to_install, scale_factor, resize_allowed, std::vector<std::string>{std::move(unsafe_foreground_icon_data), std::move(unsafe_background_icon_data)}); } void ArcAppIcon::OnIconRead( std::unique_ptr<ArcAppIcon::ReadResult> read_result) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (read_result->request_to_install) MaybeRequestIcon(read_result->scale_factor); if (read_result->unsafe_icon_data.empty()) { observer_->OnIconFailed(this); return; } switch (icon_type_) { case IconType::kUncompressed: { DCHECK_EQ(1u, read_result->unsafe_icon_data.size()); DecodeImage(read_result->unsafe_icon_data[0], ArcAppIconDescriptor(resource_size_in_dip_, read_result->scale_factor), read_result->resize_allowed, false /* retain_padding */, image_skia_, incomplete_scale_factors_); return; } case IconType::kCompressed: { DCHECK_EQ(1u, read_result->unsafe_icon_data.size()); UpdateCompressed(read_result->scale_factor, std::move(read_result->unsafe_icon_data[0])); return; } case IconType::kAdaptive: { // For non-adaptive icons, |foreground_icon_path| is used to save the icon // without |background_icon_path|, so |unsafe_icon_data| could have one // element for |foreground_icon_path| only. if (read_result->unsafe_icon_data.size() == 1) { is_adaptive_icons_[read_result->scale_factor] = false; DecodeImage(read_result->unsafe_icon_data[0], ArcAppIconDescriptor(resource_size_in_dip_, read_result->scale_factor), read_result->resize_allowed, false /* retain_padding */, image_skia_, incomplete_scale_factors_); return; } DCHECK_EQ(2u, read_result->unsafe_icon_data.size()); DecodeImage(read_result->unsafe_icon_data[0], ArcAppIconDescriptor(resource_size_in_dip_, read_result->scale_factor), read_result->resize_allowed, true /* retain_padding */, foreground_image_skia_, foreground_incomplete_scale_factors_); DecodeImage(read_result->unsafe_icon_data[1], ArcAppIconDescriptor(resource_size_in_dip_, read_result->scale_factor), read_result->resize_allowed, true /* retain_padding */, background_image_skia_, background_incomplete_scale_factors_); return; } } } void ArcAppIcon::DecodeImage( const std::string& unsafe_icon_data, const ArcAppIconDescriptor& descriptor, bool resize_allowed, bool retain_padding, gfx::ImageSkia& image_skia, std::map<ui::ScaleFactor, base::Time>& incomplete_scale_factors) { decode_requests_.emplace_back(std::make_unique<DecodeRequest>( *this, descriptor, resize_allowed, retain_padding, image_skia, incomplete_scale_factors)); if (disable_safe_decoding_for_testing) { SkBitmap bitmap; if (!unsafe_icon_data.empty() && gfx::PNGCodec::Decode( reinterpret_cast<const unsigned char*>(&unsafe_icon_data.front()), unsafe_icon_data.length(), &bitmap)) { decode_requests_.back()->OnImageDecoded(bitmap); } else { decode_requests_.back()->OnDecodeImageFailed(); } } else { ImageDecoder::Start(decode_requests_.back().get(), unsafe_icon_data); } } void ArcAppIcon::UpdateImageSkia( ui::ScaleFactor scale_factor, const SkBitmap& bitmap, gfx::ImageSkia& image_skia, std::map<ui::ScaleFactor, base::Time>& incomplete_scale_factors) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); gfx::ImageSkiaRep image_rep(bitmap, ui::GetScaleForScaleFactor(scale_factor)); DCHECK(ui::IsSupportedScale(image_rep.scale())); image_skia.RemoveRepresentation(image_rep.scale()); image_skia.AddRepresentation(image_rep); image_skia.RemoveUnsupportedRepresentationsForScale(image_rep.scale()); // TODO(crbug.com/1083331): Track the adaptive icon load time in a separate // UMA. if (icon_loaded_count_++ < 5) { base::UmaHistogramTimes( "Arc.IconLoadFromFileTime.uncompressedFirst5", base::Time::Now() - incomplete_scale_factors[scale_factor]); } else { base::UmaHistogramTimes( "Arc.IconLoadFromFileTime.uncompressedOthers", base::Time::Now() - incomplete_scale_factors[scale_factor]); } incomplete_scale_factors.erase(scale_factor); observer_->OnIconUpdated(this); } void ArcAppIcon::UpdateCompressed(ui::ScaleFactor scale_factor, std::string data) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); compressed_images_[scale_factor] = std::move(data); if (icon_loaded_count_++ < 5) { base::UmaHistogramTimes( "Arc.IconLoadFromFileTime.compressedFirst5", base::Time::Now() - incomplete_scale_factors_[scale_factor]); } else { base::UmaHistogramTimes( "Arc.IconLoadFromFileTime.compressedOthers", base::Time::Now() - incomplete_scale_factors_[scale_factor]); } incomplete_scale_factors_.erase(scale_factor); observer_->OnIconUpdated(this); } void ArcAppIcon::DiscardDecodeRequest(DecodeRequest* request, bool is_decode_success) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); auto it = std::find_if(decode_requests_.begin(), decode_requests_.end(), [request](const std::unique_ptr<DecodeRequest>& ptr) { return ptr.get() == request; }); DCHECK(it != decode_requests_.end()); decode_requests_.erase(it); if (!is_decode_success) observer_->OnIconFailed(this); }
39.731156
80
0.678429
[ "geometry", "vector" ]
0429bcf72823fd1f02757e5230f2780d66fda2cc
5,909
cpp
C++
src/LuminoEngine/src/Mesh/GMesh.cpp
infinnie/Lumino
921caabdbcb91528a2aac290e31d650628bc3bed
[ "MIT" ]
null
null
null
src/LuminoEngine/src/Mesh/GMesh.cpp
infinnie/Lumino
921caabdbcb91528a2aac290e31d650628bc3bed
[ "MIT" ]
null
null
null
src/LuminoEngine/src/Mesh/GMesh.cpp
infinnie/Lumino
921caabdbcb91528a2aac290e31d650628bc3bed
[ "MIT" ]
null
null
null
 #include "Internal.hpp" #include <LuminoEngine/Mesh/MeshPrimitive.hpp> #include "../Engine/LinearAllocator.hpp" #include "../Graphics/GraphicsManager.hpp" #include "MeshManager.hpp" #include "GMesh.hpp" namespace ln { namespace detail { //============================================================================== // GMesh GMesh::GMesh(MeshManager* manager) : m_linearAllocator(makeRef<LinearAllocator>(manager->graphicsManager()->linearAllocatorPageManager())) { } void GMesh::setVertexCount(int count) { m_vertices.resize(count); for (int i = 0; i < count; i++) { m_vertices[i] = newData<GVertex>(); } } void GMesh::reserveFaceCount(int count) { m_faces.reserve(count); } GEdge* GMesh::makeEdge(GVertex* v1, GVertex* v2) { GEdge* edge = newData<GEdge>(); m_edges.push_back(edge); edge->v1 = v1; edge->v2 = v2; v1->linkEdges.push_back(edge); v2->linkEdges.push_back(edge); return edge; } GLoop* GMesh::makeLoop(GEdge* parentEdge, GVertex* from, GVertex* next) { if (LN_REQUIRE(parentEdge)) return nullptr; // 検証。from と next は edge の一部であること。 if ((parentEdge->v1 == from || parentEdge->v2 == from) && (parentEdge->v1 == next || parentEdge->v2 == next)) { } else { LN_REQUIRE(0); return nullptr; } GLoop* loop = newData<GLoop>(); m_loops.push_back(loop); loop->edge = parentEdge; loop->vertex = from; parentEdge->linkLoops.push_back(loop); return loop; } GFace* GMesh::makeFace(const int* indices, int count) { if (LN_REQUIRE(indices)) return nullptr; if (LN_REQUIRE(count >= 3)) return nullptr; GFace* face = newData<GFace>(); m_faces.push_back(face); GLoop* prevLoop = nullptr; for (int i = 0; i < count; i++) { // 始点と終点を選択 GVertex* fromVertex = vertex(indices[i]); GVertex* nextVertex = (i == count - 1) ? vertex(indices[0]) : vertex(indices[i + 1]); // 始点と終点を結ぶ Edge を探す。なければ作る GEdge* edge = findEdge(fromVertex, nextVertex); if (!edge) edge = makeEdge(fromVertex, nextVertex); GLoop* loop = makeLoop(edge, fromVertex, nextVertex); loop->face = face; loop->prevLoop = prevLoop; if (prevLoop) { prevLoop->nextLoop = loop; } if (!face->startLoop) { face->startLoop = loop; } //edge->addLinkFace(face); prevLoop = loop; } prevLoop->nextLoop = face->startLoop; face->startLoop->prevLoop = prevLoop; return face; } GEdge* GMesh::findEdge(GVertex* v1, GVertex* v2) const { // v1 を参照している Edge のいずれかに v2 があるかを見る for (GEdge* edge : v1->linkEdges) { if (edge->v1 == v2 || edge->v2 == v2) { return edge; } } return nullptr; } //GVertex* GMesh::newVertex() // //GFace* GMesh::newFace() //{ // //} //============================================================================== // GMeshOperations static Vector3 triangleNormal(const Vector3& p0, const Vector3& p1, const Vector3& p2) { Vector3 v10 = p1 - p0; Vector3 v20 = p2 - p0; Vector3 nor = Vector3::cross(v20, v10); return Vector3::normalize(nor); } void GMeshOperations::calculateNormals(GMesh* mesh, float smoothRadius) { if (LN_REQUIRE(mesh)) return; smoothRadius /= 2; float smoothThr = (-1.0 * (smoothRadius / Math::PIDiv2)) + 1.0f; // 0 .. 180 -> 1.0 .. -1.0 // 各面の法線を求める for (GFace* face : mesh->m_faces) { Vector3 normal; face->foreachTriangleFans([&](GLoop* l1, GLoop* l2, GLoop* l3) { normal += triangleNormal( l1->vertex->position, l2->vertex->position, l3->vertex->position); }); normal = Vector3::safeNormalize(normal, Vector3::UnitY); face->normal = normal; } //// 各辺の法線を求める (隣接面の平均) //for (auto& edge : m_edges) //{ // auto& faces = edge->getLinkFaces(); // Vector3 normal; // for (auto& face : faces) // { // normal += face->getNormal(); // } // normal = Vector3::safeNormalize(normal / (float)faces.getCount(), Vector3::UnitY); // edge->setNormal(normal); //} // ループの法線を求める (必要に応じてスムージング) //for (GEdge* edge : mesh->m_edges) //{ //} for (GLoop* loop : mesh->m_loops) { if (smoothRadius == 0.0f) { loop->normal = loop->face->normal; } //else //{ // Vector3 normal; // int smoothNormalCount = 0; // SrEdge* edges[] = { loop->prevLoop->edge, loop->edge }; // for (int i = 0; i < 2; i++) // { // float d = Vector3::dot(edges[i]->getNormal(), face->getNormal()); // if (d >= smoothThr) // { // normal += edges[i]->getNormal(); // smoothNormalCount++; // } // } // if (smoothNormalCount > 0) // { // loop->normal = Vector3::safeNormalize(normal / (float)smoothNormalCount, Vector3::UnitY); // } // else // { // loop->normal = loop->face->normal; // } //} } } Ref<MeshResource> GMeshOperations::generateMeshResource(GMesh* mesh) { auto meshResource = makeObject<MeshResource>(); meshResource->resizeVertexBuffer(mesh->m_loops.size()); // TODO: 仮 meshResource->resizeIndexBuffer(6); int iVertex = 0; int iIndex = 0; int triangleCount = 0; for (GFace* face : mesh->m_faces) { // vertex buffer face->foreachLoops([&](GLoop* loop, int i) { meshResource->setVertex(iVertex, Vertex( loop->vertex->position, loop->normal, loop->uv, loop->color)); iVertex++; }); // index buffer (fan) int firstVertex = 0; // TODO: 仮 int iLoop = 0; face->foreachTriangleFans([&](GLoop* l1, GLoop* l2, GLoop* l3) { meshResource->setIndex(iIndex + 0, firstVertex); meshResource->setIndex(iIndex + 1, firstVertex + iLoop + 1); meshResource->setIndex(iIndex + 2, firstVertex + iLoop + 2); iIndex += 3; iLoop++; }); triangleCount += iLoop; } // TODO: meshResource->resizeSections(1); meshResource->setSection(0, 0, triangleCount, 0); return meshResource; } } // namespace detail } // namespace ln
22.903101
105
0.597732
[ "mesh" ]
043d8cfe4ca35618743607b359ff49d8d7601357
3,626
hpp
C++
src/mongo/util/net/ssl/context_schannel.hpp
danx0r/mongo
70d4944c235bcdf7fbbc63971099563d2af72956
[ "Apache-2.0" ]
72
2020-06-12T06:33:41.000Z
2021-03-22T03:15:56.000Z
src/mongo/util/net/ssl/context_schannel.hpp
danx0r/mongo
70d4944c235bcdf7fbbc63971099563d2af72956
[ "Apache-2.0" ]
9
2020-07-02T09:36:49.000Z
2021-03-25T23:54:00.000Z
src/mongo/util/net/ssl/context_schannel.hpp
danx0r/mongo
70d4944c235bcdf7fbbc63971099563d2af72956
[ "Apache-2.0" ]
14
2020-06-12T03:08:03.000Z
2021-02-03T11:43:09.000Z
/** * Copyright (C) 2018 MongoDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects * for all of the code used other than as permitted herein. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you do not * wish to do so, delete this exception statement from your version. If you * delete this exception statement from all source files in the program, * then also delete it in the license file. */ #pragma once #include "asio/detail/config.hpp" #include "asio/buffer.hpp" #include "asio/io_context.hpp" #include "mongo/util/net/ssl/context_base.hpp" #include <string> #include "asio/detail/push_options.hpp" namespace asio { namespace ssl { class context : public context_base, private noncopyable { public: /// The native handle type of the SSL context. typedef SCHANNEL_CRED* native_handle_type; /// Constructor. ASIO_DECL explicit context(method m); #if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) /// Move-construct a context from another. /** * This constructor moves an SSL context from one object to another. * * @param other The other context object from which the move will occur. * * @note Following the move, the following operations only are valid for the * moved-from object: * @li Destruction. * @li As a target for move-assignment. */ ASIO_DECL context(context&& other); /// Move-assign a context from another. /** * This assignment operator moves an SSL context from one object to another. * * @param other The other context object from which the move will occur. * * @note Following the move, the following operations only are valid for the * moved-from object: * @li Destruction. * @li As a target for move-assignment. */ ASIO_DECL context& operator=(context&& other); #endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) /// Destructor. ASIO_DECL ~context(); /// Get the underlying implementation in the native type. /** * This function may be used to obtain the underlying implementation of the * context. This is intended to allow access to context functionality that is * not otherwise provided. */ ASIO_DECL native_handle_type native_handle(); private: SCHANNEL_CRED _cred; // The underlying native implementation. native_handle_type handle_; }; #include "asio/detail/pop_options.hpp" #if defined(ASIO_HEADER_ONLY) #include "mongo/util/net/ssl/impl/context_schannel.ipp" #endif // defined(ASIO_HEADER_ONLY) } // namespace ssl } // namespace asio
34.533333
80
0.725869
[ "object" ]
043e4f8cde32bd932aa9d3af85e7119fbf8a62c6
388
cpp
C++
Introduction/Arrays Introduction.cpp
AbdallahHemdan/Cpp-Solutions
eb22719c31b70b6d6ee4aba8313e009297df0da9
[ "MIT" ]
8
2020-05-24T20:18:01.000Z
2022-03-10T21:21:17.000Z
Introduction/Arrays Introduction.cpp
AbdallahHemdan/Cpp-Solutions
eb22719c31b70b6d6ee4aba8313e009297df0da9
[ "MIT" ]
null
null
null
Introduction/Arrays Introduction.cpp
AbdallahHemdan/Cpp-Solutions
eb22719c31b70b6d6ee4aba8313e009297df0da9
[ "MIT" ]
4
2020-05-08T06:42:27.000Z
2021-01-04T09:18:11.000Z
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int n ; cin >> n ; int arr[n] ; for (int i=0 ; i<n ; i++) cin >>arr[i] ; for (int i=0 ; i<n/2 ; i++) { swap(arr[i],arr[n-i-1]) ; } for (int i=0 ; i<n ;i++) cout << arr[i] << " " ; return 0; }
17.636364
32
0.458763
[ "vector" ]
043fcc849dc36477e073313f56aa3cb79d4e40ca
9,405
cpp
C++
tests/hardware/test_at25.cpp
brandonbraun653/FlashMemoryDev
850628e8a825c0e8dfcb4b0d0892d3bdce4e58be
[ "MIT" ]
null
null
null
tests/hardware/test_at25.cpp
brandonbraun653/FlashMemoryDev
850628e8a825c0e8dfcb4b0d0892d3bdce4e58be
[ "MIT" ]
null
null
null
tests/hardware/test_at25.cpp
brandonbraun653/FlashMemoryDev
850628e8a825c0e8dfcb4b0d0892d3bdce4e58be
[ "MIT" ]
null
null
null
/******************************************************************************** * File Name: * test_lfs_integration.cpp * * Description: * HIL integration testing with Little FS. This requires several pieces of * hardware: * 1. Development board that exposes an SPI port. * 2. A flash driver of some kind * 3. NOR flash memory chip with an SPI interface. * * 2020 | Brandon Braun | brandonbraun653@gmail.com *******************************************************************************/ /* STL Includes */ #include <array> #include <cstring> #include <memory> /* Boost Includes */ #include <boost/circular_buffer.hpp> /* Chimera Includes */ #include <Chimera/common> #include <Chimera/gpio> #include <Chimera/serial> #include <Chimera/spi> #include <Chimera/thread> /* Aurora Includes */ #include <Aurora/memory> /* Little FS Includes */ #include "lfs.h" /* Memory Driver Includes */ #include <Adesto/at25/at25_driver.hpp> /* Test Framework Includes */ #include <CppUTest/CommandLineTestRunner.h> /* Test Driver Includes */ #include <tests/common/test_common_resources.hpp> /*------------------------------------------------------------------------------- Constants -------------------------------------------------------------------------------*/ static constexpr Chimera::SPI::Channel spiChannel = Chimera::SPI::Channel::SPI1; static constexpr Chimera::Serial::Channel serialChannel = Chimera::Serial::Channel::SERIAL1; /*------------------------------------------------------------------------------- Forward Declarations -------------------------------------------------------------------------------*/ static void test_thread( void *arg ); static void initializeSPI(); static void initializeSerial(); /*------------------------------------------------------------------------------- Public Data -------------------------------------------------------------------------------*/ std::shared_ptr<Adesto::AT25::Driver> DeviceDriver; /*------------------------------------------------------------------------------- Static Data -------------------------------------------------------------------------------*/ /*------------------------------------------------- Serial Driver Configuration -------------------------------------------------*/ // Length of the hardware buffer for transceiving a Serial message static constexpr size_t HWBufferSize = 128; // Length of the user buffer for queueing multiple messages static constexpr size_t CircularBufferSize = 2 * HWBufferSize; // Serial Transmit Buffers static std::array<uint8_t, HWBufferSize> sTXHWBuffer; static boost::circular_buffer<uint8_t> sTXCircularBuffer( CircularBufferSize ); // Serial Recieve Buffers static std::array<uint8_t, HWBufferSize> sRXHWBuffer; static boost::circular_buffer<uint8_t> sRXCircularBuffer( CircularBufferSize ); /*------------------------------------------------------------------------------- Public Functions -------------------------------------------------------------------------------*/ /** * Entry point to the tests. Initializes hardware, starts the test. * Will never exit. * * @return int */ int main() { using namespace Chimera::Threading; ChimeraInit(); Thread testing; testing.initialize( test_thread, nullptr, Priority::LEVEL_3, STACK_KILOBYTES( 10 ), "test" ); testing.start(); startScheduler(); return 0; } /*------------------------------------------------------------------------------- Static Functions -------------------------------------------------------------------------------*/ static void initializeSPI() { /*------------------------------------------------- Initialize the SPI driver -------------------------------------------------*/ Chimera::SPI::DriverConfig cfg; cfg.clear(); cfg.validity = true; cfg.HWInit.bitOrder = Chimera::SPI::BitOrder::MSB_FIRST; cfg.HWInit.clockFreq = 8000000; cfg.HWInit.clockMode = Chimera::SPI::ClockMode::MODE0; cfg.HWInit.dataSize = Chimera::SPI::DataSize::SZ_8BIT; cfg.HWInit.hwChannel = spiChannel; cfg.HWInit.txfrMode = Chimera::SPI::TransferMode::INTERRUPT; cfg.HWInit.controlMode = Chimera::SPI::ControlMode::MASTER; cfg.HWInit.csMode = Chimera::SPI::CSMode::MANUAL; cfg.HWInit.validity = true; // Chip Select cfg.externalCS = false; cfg.CSInit.alternate = Chimera::GPIO::Alternate::NONE; cfg.CSInit.drive = Chimera::GPIO::Drive::OUTPUT_PUSH_PULL; cfg.CSInit.pin = 15; cfg.CSInit.port = Chimera::GPIO::Port::PORTC; cfg.CSInit.pull = Chimera::GPIO::Pull::PULL_UP; cfg.CSInit.state = Chimera::GPIO::State::HIGH; cfg.CSInit.threaded = false; cfg.CSInit.validity = true; // SCK cfg.SCKInit.alternate = Chimera::GPIO::Alternate::SPI1_SCK; cfg.SCKInit.drive = Chimera::GPIO::Drive::ALTERNATE_PUSH_PULL; cfg.SCKInit.pin = 5; cfg.SCKInit.port = Chimera::GPIO::Port::PORTA; cfg.SCKInit.threaded = false; cfg.SCKInit.validity = true; // MISO cfg.MISOInit.alternate = Chimera::GPIO::Alternate::SPI1_MISO; cfg.MISOInit.drive = Chimera::GPIO::Drive::ALTERNATE_PUSH_PULL; cfg.MISOInit.pin = 6; cfg.MISOInit.port = Chimera::GPIO::Port::PORTA; cfg.MISOInit.threaded = false; cfg.MISOInit.validity = true; // MOSI cfg.MOSIInit.alternate = Chimera::GPIO::Alternate::SPI1_MOSI; cfg.MOSIInit.drive = Chimera::GPIO::Drive::ALTERNATE_PUSH_PULL; cfg.MOSIInit.pin = 7; cfg.MOSIInit.port = Chimera::GPIO::Port::PORTA; cfg.MOSIInit.threaded = false; cfg.MOSIInit.validity = true; auto spi = Chimera::SPI::getDriver( spiChannel ); spi->init( cfg ); } static void initializeSerial() { using namespace Chimera::Serial; using namespace Chimera::Hardware; /*------------------------------------------------ Configuration info for the serial object ------------------------------------------------*/ IOPins pins; pins.tx.alternate = Chimera::GPIO::Alternate::USART1_TX; pins.tx.drive = Chimera::GPIO::Drive::ALTERNATE_PUSH_PULL; pins.tx.pin = 9; pins.tx.port = Chimera::GPIO::Port::PORTA; pins.tx.pull = Chimera::GPIO::Pull::NO_PULL; pins.tx.threaded = true; pins.tx.validity = true; pins.rx.alternate = Chimera::GPIO::Alternate::USART1_RX; pins.rx.drive = Chimera::GPIO::Drive::ALTERNATE_PUSH_PULL; pins.rx.pin = 10; pins.rx.port = Chimera::GPIO::Port::PORTA; pins.rx.pull = Chimera::GPIO::Pull::NO_PULL; pins.rx.threaded = true; pins.rx.validity = true; Config cfg; cfg.baud = 115200; cfg.flow = FlowControl::FCTRL_NONE; cfg.parity = Parity::PAR_NONE; cfg.stopBits = StopBits::SBITS_ONE; cfg.width = CharWid::CW_8BIT; /*------------------------------------------------ Create the serial object and initialize it ------------------------------------------------*/ auto result = Chimera::Status::OK; auto Serial = Chimera::Serial::getDriver( serialChannel ); if ( !Serial ) { Chimera::insert_debug_breakpoint(); } result |= Serial->assignHW( serialChannel, pins ); result |= Serial->configure( cfg ); result |= Serial->enableBuffering( SubPeripheral::TX, &sTXCircularBuffer, sTXHWBuffer.data(), sTXHWBuffer.size() ); result |= Serial->enableBuffering( SubPeripheral::RX, &sRXCircularBuffer, sRXHWBuffer.data(), sRXHWBuffer.size() ); result |= Serial->begin( PeripheralMode::INTERRUPT, PeripheralMode::INTERRUPT ); } /** * Primary thread for intializing test resources and then executing tests. * Will never exit. * * @param[in] arg Unused * @return void */ static void test_thread( void *arg ) { using namespace Adesto::Testing; /*------------------------------------------------- Configure the output style: - Colorized - Verbose -------------------------------------------------*/ const char *av_override[] = { "-c", "-v" }; /*------------------------------------------------- Initialize HW Resources -------------------------------------------------*/ initializeSPI(); initializeSerial(); /*------------------------------------------------- Allocate the device drivers -------------------------------------------------*/ auto serial = Chimera::Serial::getDriver( serialChannel ); DeviceDriver = std::make_shared<Adesto::AT25::Driver>(); DeviceDriver->configure( spiChannel ); assignDUT( DeviceDriver ); assignSPIChannelConfig( spiChannel ); assignSerialChannelConfig( serialChannel ); /*------------------------------------------------- Run the tests then break -------------------------------------------------*/ snprintf(printBuffer.data(), printBuffer.size(), "Starting Adesto AT25 driver tests. This may take a few minutes.\n" ); serial->lock(); serial->write( printBuffer.data(), strlen( printBuffer.data() ) ); serial->await( Chimera::Event::TRIGGER_WRITE_COMPLETE, Chimera::Threading::TIMEOUT_BLOCK ); serial->unlock(); int rcode = CommandLineTestRunner::RunAllTests( 2, av_override ); snprintf(printBuffer.data(), printBuffer.size(), "Test exit with code: %d\n", rcode ); serial->lock(); serial->write( printBuffer.data(), strlen( printBuffer.data() ) ); serial->await( Chimera::Event::TRIGGER_WRITE_COMPLETE, Chimera::Threading::TIMEOUT_BLOCK ); serial->unlock(); while ( 1 ) { Chimera::insert_debug_breakpoint(); } }
34.2
121
0.554067
[ "object" ]
0441ef9c47433cfd26d4b3a3712de1cb27517ab6
11,400
cc
C++
chrome/browser/metrics/usage_scenario/tab_usage_scenario_tracker.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
chrome/browser/metrics/usage_scenario/tab_usage_scenario_tracker.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/browser/metrics/usage_scenario/tab_usage_scenario_tracker.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/metrics/usage_scenario/tab_usage_scenario_tracker.h" #include "base/containers/contains.h" #include "chrome/browser/metrics/usage_scenario/usage_scenario_data_store.h" #include "components/ukm/content/source_url_recorder.h" #include "content/public/browser/visibility.h" #include "content/public/browser/web_contents.h" #include "services/metrics/public/cpp/ukm_source_id.h" #include "ui/display/screen.h" #include "url/origin.h" namespace metrics { namespace { std::pair<ukm::SourceId, url::Origin> GetNavigationInfoForContents( content::WebContents* contents) { auto* main_frame = contents->GetMainFrame(); if (!main_frame || main_frame->GetLastCommittedURL().is_empty()) return std::make_pair(ukm::kInvalidSourceId, url::Origin()); return std::make_pair(ukm::GetSourceIdForWebContentsDocument(contents), main_frame->GetLastCommittedOrigin()); } } // namespace TabUsageScenarioTracker::TabUsageScenarioTracker( UsageScenarioDataStoreImpl* usage_scenario_data_store) : usage_scenario_data_store_(usage_scenario_data_store) { // TODO(crbug.com/1153193): Owners of this class have to set the initial // state. Constructing the object like this starts off the state as empty. If // tabs/windows already exist when this object is created they need to be // added using the normal functions after creation. auto* screen = display::Screen::GetScreen(); // Make sure that this doesn't get created before setting up the global Screen // instance. DCHECK(screen); screen->AddObserver(this); } TabUsageScenarioTracker::~TabUsageScenarioTracker() { auto* screen = display::Screen::GetScreen(); // Make sure that this doesn't get destroyed after destroying the global // screen instance. DCHECK(screen); screen->RemoveObserver(this); } void TabUsageScenarioTracker::OnTabAdded(content::WebContents* web_contents) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); usage_scenario_data_store_->OnTabAdded(); // Tab is added already visible. It will not get a separate visibility update // so we handle the visibility here. if (web_contents->GetVisibility() == content::Visibility::VISIBLE) { DCHECK(!base::Contains(visible_tabs_, web_contents)); usage_scenario_data_store_->OnWindowVisible(); InsertContentsInMapOfVisibleTabs(web_contents); } } void TabUsageScenarioTracker::OnTabRemoved(content::WebContents* web_contents) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); OnWebContentsRemoved(web_contents); usage_scenario_data_store_->OnTabClosed(); } void TabUsageScenarioTracker::OnTabReplaced( content::WebContents* old_contents, content::WebContents* new_contents) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); OnWebContentsRemoved(old_contents); DCHECK(!base::Contains(visible_tabs_, old_contents)); DCHECK(!base::Contains(contents_playing_video_, old_contents)); DCHECK_NE(content_with_media_playing_fullscreen_, old_contents); // Start tracking |new_contents| if needed. if (new_contents->GetVisibility() == content::Visibility::VISIBLE) OnTabVisibilityChanged(new_contents); if (new_contents->IsCurrentlyAudible()) usage_scenario_data_store_->OnAudioStarts(); } void TabUsageScenarioTracker::OnTabVisibilityChanged( content::WebContents* web_contents) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); auto iter = visible_tabs_.find(web_contents); // The first content::Visibility::VISIBLE notification is always sent, even // if the tab starts in the visible state. if (iter == visible_tabs_.end() && web_contents->GetVisibility() == content::Visibility::VISIBLE) { usage_scenario_data_store_->OnWindowVisible(); // If this tab is playing video then record that it became visible. if (base::Contains(contents_playing_video_, web_contents)) { usage_scenario_data_store_->OnVideoStartsInVisibleTab(); } InsertContentsInMapOfVisibleTabs(web_contents); } else if (iter != visible_tabs_.end() && web_contents->GetVisibility() != content::Visibility::VISIBLE) { // The tab was previously visible and it's now hidden or occluded. OnTabBecameHidden(&iter); } } void TabUsageScenarioTracker::OnTabInteraction( content::WebContents* web_contents) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); usage_scenario_data_store_->OnUserInteraction(); } void TabUsageScenarioTracker::OnTabIsAudibleChanged( content::WebContents* web_contents) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (web_contents->IsCurrentlyAudible()) { usage_scenario_data_store_->OnAudioStarts(); } else { usage_scenario_data_store_->OnAudioStops(); } } void TabUsageScenarioTracker::OnMediaEffectivelyFullscreenChanged( content::WebContents* web_contents, bool is_fullscreen) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); auto* screen = display::Screen::GetScreen(); DCHECK(screen); if (screen->GetNumDisplays() == 1) { if (is_fullscreen) { DCHECK(!content_with_media_playing_fullscreen_); content_with_media_playing_fullscreen_ = web_contents; usage_scenario_data_store_->OnFullScreenVideoStartsOnSingleMonitor(); } else { OnContentStoppedPlayingMediaFullScreen(); } } } void TabUsageScenarioTracker::OnMainFrameNavigationCommitted( content::WebContents* web_contents) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); usage_scenario_data_store_->OnTopLevelNavigation(); if (web_contents->GetVisibility() == content::Visibility::VISIBLE) { auto iter = visible_tabs_.find(web_contents); DCHECK(iter != visible_tabs_.end()); // If there's already an entry with a valid SourceID for this in // |visible_tabs_| then it means that there's been a main frame navigation // for a visible tab. Records that the SourceID previously associated with // this tab isn't visible anymore. if (iter->second.first != ukm::kInvalidSourceId) { usage_scenario_data_store_->OnUkmSourceBecameHidden(iter->second.first, iter->second.second); } iter->second = GetNavigationInfoForContents(web_contents); if (iter->second.first != ukm::kInvalidSourceId) { usage_scenario_data_store_->OnUkmSourceBecameVisible(iter->second.first, iter->second.second); } } } void TabUsageScenarioTracker::OnVideoStartedPlaying( content::WebContents* web_contents) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!base::Contains(contents_playing_video_, web_contents)); contents_playing_video_.insert(web_contents); if (base::Contains(visible_tabs_, web_contents)) usage_scenario_data_store_->OnVideoStartsInVisibleTab(); } void TabUsageScenarioTracker::OnVideoStoppedPlaying( content::WebContents* web_contents) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(base::Contains(contents_playing_video_, web_contents)); contents_playing_video_.erase(web_contents); if (base::Contains(visible_tabs_, web_contents)) usage_scenario_data_store_->OnVideoStopsInVisibleTab(); } void TabUsageScenarioTracker::OnDisplayAdded(const display::Display& unused) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); auto* screen = display::Screen::GetScreen(); if (screen->GetNumDisplays() == 1) { if (content_with_media_playing_fullscreen_ != nullptr) { DCHECK(usage_scenario_data_store_ ->is_playing_full_screen_video_single_monitor_since() .is_null()); usage_scenario_data_store_->OnFullScreenVideoStartsOnSingleMonitor(); } return; } // Stop the fullscreen video on single monitor event if there's more than one // screen. if (!usage_scenario_data_store_ ->is_playing_full_screen_video_single_monitor_since() .is_null()) { usage_scenario_data_store_->OnFullScreenVideoEndsOnSingleMonitor(); } } void TabUsageScenarioTracker::OnDisplayRemoved(const display::Display& unused) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); auto* screen = display::Screen::GetScreen(); DCHECK(screen); // Update the data store if there's only one display now running media // fullscreen. if (screen->GetNumDisplays() == 1 && content_with_media_playing_fullscreen_ != nullptr) { DCHECK(usage_scenario_data_store_ ->is_playing_full_screen_video_single_monitor_since() .is_null()); usage_scenario_data_store_->OnFullScreenVideoStartsOnSingleMonitor(); } } void TabUsageScenarioTracker::OnContentStoppedPlayingMediaFullScreen() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); usage_scenario_data_store_->OnFullScreenVideoEndsOnSingleMonitor(); content_with_media_playing_fullscreen_ = nullptr; } void TabUsageScenarioTracker::OnTabBecameHidden( VisibleTabsMap::iterator* visible_tab_iter) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // If this tab is playing video then record that it became non visible. if (base::Contains(contents_playing_video_, (*visible_tab_iter)->first)) { usage_scenario_data_store_->OnVideoStopsInVisibleTab(); } // |OnMediaEffectivelyFullscreenChanged| doesn't get called if a tab playing // media fullscreen gets closed. if ((*visible_tab_iter)->first == content_with_media_playing_fullscreen_) OnContentStoppedPlayingMediaFullScreen(); // Record that the ukm::SourceID associated with this tab isn't visible // anymore if necessary. if ((*visible_tab_iter)->second.first != ukm::kInvalidSourceId) { usage_scenario_data_store_->OnUkmSourceBecameHidden( (*visible_tab_iter)->second.first, (*visible_tab_iter)->second.second); } visible_tabs_.erase(*visible_tab_iter); usage_scenario_data_store_->OnWindowHidden(); } void TabUsageScenarioTracker::OnWebContentsRemoved( content::WebContents* web_contents) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); auto iter = visible_tabs_.find(web_contents); DCHECK_EQ(iter != visible_tabs_.end(), web_contents->GetVisibility() == content::Visibility::VISIBLE); auto video_iter = contents_playing_video_.find(web_contents); // If |web_contents| is tracked in the list of visible WebContents then a // synthetic visibility change event should be emitted. if (iter != visible_tabs_.end()) { OnTabBecameHidden(&iter); } if (video_iter != contents_playing_video_.end()) { contents_playing_video_.erase(video_iter); } if (web_contents->IsCurrentlyAudible()) usage_scenario_data_store_->OnAudioStops(); } void TabUsageScenarioTracker::InsertContentsInMapOfVisibleTabs( content::WebContents* web_contents) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!base::Contains(visible_tabs_, web_contents)); auto iter = visible_tabs_.emplace(web_contents, GetNavigationInfoForContents(web_contents)); if (iter.first->second.first != ukm::kInvalidSourceId) { usage_scenario_data_store_->OnUkmSourceBecameVisible( iter.first->second.first, iter.first->second.second); } } } // namespace metrics
39.446367
80
0.755526
[ "object" ]
04459118ba8e9c8bee72cff1a86566e9076a80e5
22,452
cc
C++
otherlibs/libcvd/cvd_src/Linux/dvbuffer3_dc1394v2.cc
amitsingh19975/mrpt
451480f9815cc029ae427ed8067732606bcfbb43
[ "BSD-3-Clause" ]
9
2017-11-19T16:18:09.000Z
2020-07-16T02:13:43.000Z
otherlibs/libcvd/cvd_src/Linux/dvbuffer3_dc1394v2.cc
amitsingh19975/mrpt
451480f9815cc029ae427ed8067732606bcfbb43
[ "BSD-3-Clause" ]
null
null
null
otherlibs/libcvd/cvd_src/Linux/dvbuffer3_dc1394v2.cc
amitsingh19975/mrpt
451480f9815cc029ae427ed8067732606bcfbb43
[ "BSD-3-Clause" ]
4
2018-06-08T07:55:51.000Z
2022-02-22T08:56:28.000Z
// -*- c++ -*- #include <cvd/Linux/dvbuffer3.h> #include <cvd/byte.h> #include <cvd/timer.h> #include <dc1394/dc1394.h> #ifndef __APPLE__ #include <libraw1394/raw1394.h> #endif #include <vector> #include <algorithm> #include <iostream> #include <iomanip> #include <vector> #include <string> using namespace CVD; using namespace std; using namespace DV3; using CVD::Exceptions::DVBuffer3::All; namespace CVD { namespace DV3 { class VPrint_ { public: VPrint_(bool _p) :p(_p) {} template<class C> VPrint_& operator<<(const C& c) { if(p) cerr << c; return *this; } bool p; }; class VPrint: public VPrint_ { public: VPrint(bool _b) :VPrint_(_b){} template<class C> VPrint_& operator<<(const C& c) { if(p) cerr << "RawDVBuffer3: " << c; return *this; } }; string coding(dc1394color_coding_t ii) { int i = (int)ii; static vector<string> c; if(c.empty()) { c.push_back("MONO8"); c.push_back("YUV411"); c.push_back("YUV422"); c.push_back("YUV444"); c.push_back("RGB8"); c.push_back("MONO16"); c.push_back("RGB16"); c.push_back("MONO16S"); c.push_back("RGB16S"); c.push_back("RAW8"); c.push_back("RAW16"); } i-=352; if(i < 0 || i >= (int)c.size()) return "error"; else return c[i]; } string filter(dc1394color_filter_t f) { switch(f) { case DC1394_COLOR_FILTER_RGGB: return "RGGB"; case DC1394_COLOR_FILTER_BGGR: return "BGGR"; case DC1394_COLOR_FILTER_GRBG: return "GRBG"; case DC1394_COLOR_FILTER_GBRG: return "GBRG"; } return "error"; } static DV3ColourFilter DV3_from_DC_ColourFilter(dc1394color_filter_t f, uint32_t /*vendor*/, uint32_t /*model*/, uint64_t guid) { // some cameras report incorrect bayer patterns if (guid==0x814436200006075ULL) { return GBRG; } return static_cast<DV3ColourFilter>(f - DC1394_COLOR_FILTER_MIN); } struct LibDCParams { dc1394_t *pDC1394; dc1394camera_t *pCamera; LibDCParams() { pDC1394 = NULL; pCamera = NULL; } }; struct DV3Frame : public VideoFrame<byte> { DV3Frame(dc1394video_frame_t *pDC1394Frame) : VideoFrame<byte>(const_cast<const cvd_timer & >(timer).conv_ntime(pDC1394Frame->timestamp / 1000000.0), pDC1394Frame->image, ImageRef(pDC1394Frame->size[0], pDC1394Frame->size[1])) { mpDC1394Frame = pDC1394Frame; } protected: dc1394video_frame_t *mpDC1394Frame; friend class RawDVBuffer3; }; static dc1394color_coding_t DC_from_DV3_ColourSpace(DV3ColourSpace s, uint32_t /*vendor*/, uint32_t /*model*/, uint64_t guid) { // some cameras report their raw bayer mode as being mono and do not // have a mono mode at all... if (guid==0x814436200006075ULL) { //vendor==0x81443 model==0x0 ? switch(s) { case MONO8: return DC1394_COLOR_CODING_RAW8; case MONO16: return DC1394_COLOR_CODING_RAW16; case RAW8: return DC1394_COLOR_CODING_MONO8; case RAW16: return DC1394_COLOR_CODING_MONO16; default: break; } } switch(s) { case MONO8: return DC1394_COLOR_CODING_MONO8; case MONO16: return DC1394_COLOR_CODING_MONO16; case MONO16S:return DC1394_COLOR_CODING_MONO16S; case RGB8: return DC1394_COLOR_CODING_RGB8; case RGB16: return DC1394_COLOR_CODING_RGB16; case RGB16S: return DC1394_COLOR_CODING_RGB16S; case YUV411: return DC1394_COLOR_CODING_YUV411; case YUV422: return DC1394_COLOR_CODING_YUV422; case YUV444: return DC1394_COLOR_CODING_YUV444; case RAW8: return DC1394_COLOR_CODING_RAW8; case RAW16: return DC1394_COLOR_CODING_RAW16; } throw(All("DC_from_DV3: Invalid colourspace")); } static dc1394feature_t DC_from_DV3_Feature(DV3Feature f) { switch(f) { case BRIGHTNESS: return DC1394_FEATURE_BRIGHTNESS; case EXPOSURE : return DC1394_FEATURE_EXPOSURE; case SHARPNESS: return DC1394_FEATURE_SHARPNESS; case WHITE_BALANCE: return DC1394_FEATURE_WHITE_BALANCE; case HUE: return DC1394_FEATURE_HUE; case SATURATION: return DC1394_FEATURE_SATURATION; case GAMMA: return DC1394_FEATURE_GAMMA; case SHUTTER: return DC1394_FEATURE_SHUTTER; case GAIN: return DC1394_FEATURE_GAIN; case IRIS: return DC1394_FEATURE_IRIS; case FOCUS: return DC1394_FEATURE_FOCUS; case ZOOM: return DC1394_FEATURE_ZOOM; case PAN: return DC1394_FEATURE_PAN; case TILT: return DC1394_FEATURE_TILT; case FRAME_RATE: return DC1394_FEATURE_FRAME_RATE; } throw(All("DC_from_DV3: Invalid feature")); } RawDVBuffer3::RawDVBuffer3(DV3ColourSpace colourspace, int nCamNumber, uint64_t cam_guid, int cam_unit, bool verbose, bool bus_reset, ImageRef irSize, float fFrameRate, ImageRef irOffset, int format7_mode) { VPrint log(verbose); mpLDCP = new LibDCParams; // Create a libDC1394 context. mpLDCP->pDC1394 = dc1394_new(); // A variable to record error values.. dc1394error_t error; // Enumerate the cameras connected to the system. dc1394camera_list_t *pCameraList = NULL; error = dc1394_camera_enumerate(mpLDCP->pDC1394, &pCameraList); if(error) throw(All("Camera enumerate")); log << "Requesting: \n"; log << " colourspace: " << colourspace << "\n"; log << " camera number: " << nCamNumber << "\n"; log << " camera guid: " << cam_guid << "\n"; log << " camera unit: " << cam_unit << "\n"; log << " size: " << irSize << "\n"; log << " framerate: " << fFrameRate << "\n"; log << " offset: " << irOffset << "\n"; log << " format7 mode: " << format7_mode << "\n"; if(pCameraList->num == 0) { dc1394_camera_free_list(pCameraList); throw(All("No cameras found.")); } else { log << "List of cameras:\n"; for(unsigned int i=0; i < pCameraList->num; i++) { log << " Camera: " << i << ": unit=" << pCameraList->ids[i].unit << " guid=" << hex << pCameraList->ids[i].guid << dec << "\n"; if(nCamNumber == -1 && cam_guid == pCameraList->ids[i].guid) { if(cam_unit == -1 || cam_unit == pCameraList->ids[i].unit) nCamNumber = i; } } } if(nCamNumber + 1 > (int)pCameraList->num) { dc1394_camera_free_list(pCameraList); throw(All("Selected camera out of range")); } // Allocate a camera struct... mpLDCP->pCamera = dc1394_camera_new(mpLDCP->pDC1394, pCameraList->ids[nCamNumber].guid); dc1394_camera_free_list(pCameraList); if(!mpLDCP->pCamera) throw(All("Failed on dc1394_camera_new")); if (bus_reset) { dc1394switch_t is_iso_on; if (dc1394_video_get_transmission(mpLDCP->pCamera, &is_iso_on)!=DC1394_SUCCESS) is_iso_on = DC1394_OFF; if (is_iso_on==DC1394_ON) { dc1394_video_set_transmission(mpLDCP->pCamera, DC1394_OFF); } } log << "Selected camera: " << hex << mpLDCP->pCamera->vendor_id << ":" << mpLDCP->pCamera->model_id << "(guid: " << mpLDCP->pCamera->guid << dec << ")\n"; // What mode to use? dc1394color_coding_t nTargetColourCoding = DC_from_DV3_ColourSpace(colourspace, mpLDCP->pCamera->vendor_id, mpLDCP->pCamera->model_id, mpLDCP->pCamera->guid); dc1394_camera_reset(mpLDCP->pCamera); log << "Target colour coding: " << nTargetColourCoding << " (" << coding(nTargetColourCoding) << ")\n"; bool foundAStandardMode = false; dc1394video_mode_t nMode; mColourfilter = UNDEFINED; if(irOffset.x == -1 && format7_mode == -1){ try { // First, get a list of the modes which the camera supports. dc1394video_modes_t modes; error = dc1394_video_get_supported_modes(mpLDCP->pCamera, &modes); if(error) throw(All("Could not get modelist")); // Second: Build up a list of the modes which are the right colour-space std::vector<dc1394video_mode_t> vModes; for(unsigned int i = 0; i < modes.num; i++) { dc1394video_mode_t nMode = modes.modes[i]; // ignore format 7 for now if(nMode >= DC1394_VIDEO_MODE_FORMAT7_0) continue; dc1394color_coding_t nColourCoding; error=dc1394_get_color_coding_from_video_mode(mpLDCP->pCamera,nMode,&nColourCoding); if(error) throw(All("Error in get_color_coding_from_video_mode")); if(nColourCoding == nTargetColourCoding) vModes.push_back(nMode); } if(vModes.size() == 0) throw(-1); // Third: Select mode according to size bool bModeFound = false; dc1394video_mode_t nMode; if(irSize.x != -1) // Has the user specified a target size? Choose mode according to that.. for(size_t i = 0; i<vModes.size(); i++){ uint32_t x,y; dc1394_get_image_size_from_video_mode(mpLDCP->pCamera, vModes[i], &x, &y); if(x == (uint32_t) irSize.x && y == (uint32_t) irSize.y) { bModeFound = true; nMode = vModes[i]; break; } } else // If the user didn't specify a target size, choose the one with the { // highest resolution. sort(vModes.begin(), vModes.end()); bModeFound = true; nMode = vModes.back(); } if(!bModeFound) throw(-1); // Store the size of the selected mode.. uint32_t x,y; dc1394_get_image_size_from_video_mode(mpLDCP->pCamera, nMode, &x, &y); mirSize.x = x; mirSize.y = y; mirOffset = irOffset; // Got mode, now decide on frame-rate. Similar thing: first get list, then choose from list. dc1394framerates_t framerates; dc1394framerate_t nChosenFramerate = DC1394_FRAMERATE_MIN; mdFramerate = -1.0; error = dc1394_video_get_supported_framerates(mpLDCP->pCamera,nMode,&framerates); if(error) throw(All("Could not query supported framerates")); if(fFrameRate > 0) // User wants a specific frame-rate? { for(unsigned int i=0; i<framerates.num; i++){ float f_rate; dc1394_framerate_as_float(framerates.framerates[i],&f_rate); if(f_rate == fFrameRate){ nChosenFramerate = framerates.framerates[i]; mdFramerate = f_rate; break; } } } else { // Just pick the highest frame-rate the camera can do. for(unsigned int i=0; i<framerates.num; i++){ float f_rate; dc1394_framerate_as_float(framerates.framerates[i],&f_rate); if(f_rate > mdFramerate) { nChosenFramerate = framerates.framerates[i]; mdFramerate = f_rate; } } } if(mdFramerate == -1.0) throw(-1); // Selected mode and frame-rate; Now tell the camera to use these. // At the moment, hard-code the channel to speed 400. This is maybe something to fix in future? error = dc1394_video_set_iso_speed(mpLDCP->pCamera, DC1394_ISO_SPEED_400); if(error) throw(All("Could not set ISO speed.")); error = dc1394_video_set_iso_channel(mpLDCP->pCamera, nCamNumber); if(error) throw(All("Could not set ISO channel.")); error = dc1394_video_set_mode(mpLDCP->pCamera, nMode); if(error) throw(All("Could not set video mode")); error = dc1394_video_set_framerate(mpLDCP->pCamera, nChosenFramerate); if(error) throw(All("Could not set frame-rate")); // no need to check Format 7 modes foundAStandardMode = true; } catch(int e){ //cout << "DCBuffer is checking format 7 modes as well" << endl; foundAStandardMode = false; } } if(!foundAStandardMode){ log << "Failed to find a standard mode. Using FORMAT_7\n"; dc1394format7modeset_t modeset; error = dc1394_format7_get_modeset(mpLDCP->pCamera, &modeset); if(error) throw(All("Could not get Format 7 modes.")); int index = 0; if(irOffset.x == -1) mirOffset = ImageRef(0,0); else mirOffset = irOffset; for(; index < DC1394_VIDEO_MODE_FORMAT7_NUM ; ++index){ const dc1394format7mode_t & mode = modeset.mode[index]; log << " FORMAT_7 mode index " << index << "\n"; log << " present: " << mode.present << "\n"; if(!mode.present) continue; log << " size: " << mode.size_x << "x" << mode.size_y << "\n"; log << " max size: " << mode.max_size_x << "x" << mode.max_size_y << "\n"; log << " position?: " << mode.pos_x << "x" << mode.pos_y << "\n"; log << " unit size: " << mode.unit_size_x << "x" << mode.unit_size_y << "\n"; log << " unit pos: " << mode.unit_pos_x << "x" << mode.unit_pos_y << "\n"; log << " color codings: " << mode.color_codings.num << "\n"; for(unsigned int i=0; i < mode.color_codings.num && i < DC1394_COLOR_CODING_NUM; i++) log << " color: " << mode.color_codings.codings[i] << "(" << coding(mode.color_codings.codings[i]) << ")\n"; log << " color: " << mode.color_coding << "(" << coding(mode.color_coding) << ")\n"; log << " pixnum: " << mode.pixnum << "\n"; log << " packet size: " << mode.packet_size << "\n"; log << " unit pkt size: " << mode.unit_packet_size << "\n"; log << " max pkt size: " << mode.max_packet_size << "\n"; log << " total bytes: " << mode.total_bytes << "\n"; log << " color filter: " << mode.color_filter << "(" << filter(mode.color_filter) << ")\n"; if(format7_mode != -1 && format7_mode != index) continue; // does the mode exist ? // does it support the colour format we need ? unsigned int i; for(i = 0; i < mode.color_codings.num && i < DC1394_COLOR_CODING_NUM ; ++i) { if(mode.color_codings.codings[i] == nTargetColourCoding) break; } if(i == mode.color_codings.num) { log << " No matching mode\n"; continue; } if(irSize.x != -1){ // can it support the size ? if((irSize.x + mirOffset.x) > (int)mode.max_size_x || (irSize.y + mirOffset.y) > (int)mode.max_size_y || irSize.x % mode.unit_size_x != 0 || irSize.y % mode.unit_size_y != 0) { log << " Cannot support size/offset combination\n"; continue; } } else { irSize.x = mode.max_size_x; irSize.y = mode.max_size_y; } // found one break; } if(index == DC1394_VIDEO_MODE_FORMAT7_NUM) throw(All("Could not find any usable format!")); const dc1394format7mode_t & mode = modeset.mode[index]; nMode = static_cast<dc1394video_mode_t>( DC1394_VIDEO_MODE_FORMAT7_0 + index); // At the moment, hard-code the channel to speed 400. This is maybe something to fix in future? error = dc1394_video_set_iso_speed(mpLDCP->pCamera, DC1394_ISO_SPEED_400); if(error) throw(All("Could not set ISO speed.")); error = dc1394_video_set_iso_channel(mpLDCP->pCamera, nCamNumber); if(error) throw(All("Could not set ISO channel.")); error = dc1394_video_set_mode(mpLDCP->pCamera, nMode); if(error) throw(All("Could not set video mode.")); // frame rate calculations int num_packets = (int)(8000.0/fFrameRate + 0.5); log << "Number of packets: " << num_packets << "\n"; int packet_size = (irSize.x * irSize.y * 8 + num_packets * 8 - 1 ) / (num_packets * 8); mdFramerate = fFrameRate; // offset calculations if(irOffset.x == -1){ mirOffset.x = (mode.max_size_x - irSize.x) / 2; mirOffset.y = (mode.max_size_y - irSize.y) / 2; } else { mirOffset = irOffset; } mirSize = irSize; log << "Requesting:\n"; log << " packet size: " << packet_size << "\n"; log << " left: " << mirOffset.x << "\n"; log << " right: " << mirOffset.y << "\n"; log << " width: " << mirSize.x << "\n"; log << " height: " << mirSize.y << "\n"; error = dc1394_format7_set_roi( mpLDCP->pCamera, nMode, nTargetColourCoding, packet_size, mirOffset.x, // left mirOffset.y, // top mirSize.x, // width mirSize.y); // height uint32_t pkt_size, offx, offy, posx, posy; error = dc1394_format7_get_roi( mpLDCP->pCamera, nMode, &nTargetColourCoding, &pkt_size, &offx, // left &offy, // top &posx, // width &posy); // height log << "Got:\n"; log << " packet size: " << pkt_size << "\n"; log << " left: " << offx << "\n"; log << " right: " << offy << "\n"; log << " width: " << posx << "\n"; log << " height: " << posy << "\n"; log << error << "\n"; dc1394color_filter_t filterType; error = dc1394_format7_get_color_filter(mpLDCP->pCamera, nMode, &filterType); mColourfilter = DV3_from_DC_ColourFilter(filterType, mpLDCP->pCamera->vendor_id, mpLDCP->pCamera->model_id, mpLDCP->pCamera->guid); } // Hack Alert: If someone requested raw bayer output but we have not // yet determined the bayer filter type, then try harder to find it. // This happens, if a default mode announced as MONO8 is actually a // raw bayer mode instead, which is a common quirk for many cameras. // We will try to query the format 7 bayer patterns, which will // probably be the same as for all other modes... if ((mColourfilter == UNDEFINED) && ((colourspace == RAW8)||(colourspace == RAW16))) { dc1394format7modeset_t modeset; error = dc1394_format7_get_modeset(mpLDCP->pCamera, &modeset); if(error) throw(All("Could not get Format 7 modes.")); for(int index = 0; index < DC1394_VIDEO_MODE_FORMAT7_NUM ; ++index){ dc1394color_filter_t filterType; dc1394video_mode_t nMode2 = static_cast<dc1394video_mode_t>( DC1394_VIDEO_MODE_FORMAT7_0 + index); error = dc1394_format7_get_color_filter(mpLDCP->pCamera, nMode2, &filterType); if (error) continue; mColourfilter = DV3_from_DC_ColourFilter(filterType, mpLDCP->pCamera->vendor_id, mpLDCP->pCamera->model_id, mpLDCP->pCamera->guid); if (mColourfilter != UNDEFINED) break; } } // Hack Alert: The code below sets the iso channel without this // having been properly allocated! Likewise we never allocate // bandwidth. Both of these could be allocated if the following // two lines were erased, and the `0' parameter to // dc1394_capture_setup were changed to // DC1394_CAPTURE_FLAGS_DEFAULT; but this causes problems when // the program crashes, as the resources are not deallocated // properly. // This hack emulates what dvbuffer.cc does using libdc1394v1. // Hack to disable resource allocation -- see above // error = dc1394_capture_setup(mpLDCP->pCamera, 4, DC1394_CAPTURE_FLAGS_DEFAULT); error = dc1394_capture_setup(mpLDCP->pCamera, 4, 0); if(error) throw(All("Could not setup capture.")); error = dc1394_video_set_transmission(mpLDCP->pCamera, DC1394_ON); if(error) throw(All("Could not start ISO transmission.")); } RawDVBuffer3::~RawDVBuffer3() { if(mpLDCP->pCamera) { dc1394_video_set_transmission(mpLDCP->pCamera, DC1394_OFF); dc1394_capture_stop(mpLDCP->pCamera); dc1394_camera_set_power(mpLDCP->pCamera, DC1394_OFF); dc1394_camera_free(mpLDCP->pCamera); } if(mpLDCP->pDC1394) dc1394_free(mpLDCP->pDC1394); delete mpLDCP; } #ifndef __APPLE__ void RawDVBuffer3::stopAllTransmissions(void) { raw1394handle_t rawhandle = raw1394_new_handle(); int numPorts = raw1394_get_port_info(rawhandle, NULL,0); for (int i=0; i<numPorts; i++) { raw1394handle_t port = raw1394_new_handle_on_port(i); if (port==NULL) continue; raw1394_iso_stop(port); raw1394_iso_shutdown(port); raw1394_reset_bus(port); raw1394_destroy_handle(port); } raw1394_destroy_handle(rawhandle); } #endif //__APPLE__ bool RawDVBuffer3::frame_pending() { return true; } VideoFrame<byte>* RawDVBuffer3::get_frame() { dc1394error_t error; dc1394video_frame_t *pDC1394Frame; error = dc1394_capture_dequeue(mpLDCP->pCamera, DC1394_CAPTURE_POLICY_WAIT, &pDC1394Frame); if(error) throw(All("Failed on deque")); DV3::DV3Frame *pDV3Frame = new DV3::DV3Frame(pDC1394Frame); return pDV3Frame; } void RawDVBuffer3::put_frame(VideoFrame<byte> *pVidFrame) { dc1394error_t error; DV3::DV3Frame *pDV3Frame = dynamic_cast<DV3::DV3Frame*>(pVidFrame); if(!pVidFrame) throw(All("put_frame got passed an alien frame")); error = dc1394_capture_enqueue(mpLDCP->pCamera, pDV3Frame->mpDC1394Frame); if(error != DC1394_SUCCESS) { //FIXME we really need to clean up exceptions here! throw(All("failed to reenqueue frame")); } delete pDV3Frame; } unsigned int RawDVBuffer3::get_feature_value(DV3Feature nFeature) { if(!mpLDCP || !mpLDCP->pCamera) return 0; dc1394error_t error; unsigned int nValue = 0; error = dc1394_feature_get_value(mpLDCP->pCamera, DC_from_DV3_Feature(nFeature), &nValue); if(error) return 0; else return nValue; } void RawDVBuffer3::set_feature_value(DV3Feature nFeature, unsigned int nValue) { if(!mpLDCP || !mpLDCP->pCamera) return; dc1394_feature_set_value(mpLDCP->pCamera, DC_from_DV3_Feature(nFeature), nValue); } std::pair<unsigned int,unsigned int> RawDVBuffer3::get_feature_min_max(DV3Feature nFeature) { std::pair<unsigned int, unsigned int> res; res.first = res.second = 0; if(!mpLDCP || !mpLDCP->pCamera) return res; dc1394error_t error; unsigned int nMin; unsigned int nMax; error = dc1394_feature_get_boundaries(mpLDCP->pCamera, DC_from_DV3_Feature(nFeature), &nMin, &nMax); if(error) return res; res.first = nMin; res.second = nMax; return res; } void RawDVBuffer3::auto_on_off(DV3Feature nFeature, bool bValue) { if(!mpLDCP || !mpLDCP->pCamera) return; dc1394_feature_set_mode(mpLDCP->pCamera, DC_from_DV3_Feature(nFeature), bValue? DC1394_FEATURE_MODE_AUTO : DC1394_FEATURE_MODE_MANUAL); } void RawDVBuffer3::power_on_off(DV3Feature nFeature, bool bValue) { if(!mpLDCP || !mpLDCP->pCamera) return; dc1394_feature_set_power(mpLDCP->pCamera, DC_from_DV3_Feature(nFeature), bValue? DC1394_ON : DC1394_OFF); } } }
33.163959
178
0.637983
[ "vector", "model" ]
04469e87b4ea3f23d09d22852bd7b152370904d4
31,843
cpp
C++
stockfishservice/src/main/cpp/endgame.cpp
chess24com/StockfishServiceTest
0551c66885301cec812738795f105497ba9a3ad0
[ "MIT" ]
8
2018-01-13T00:24:56.000Z
2020-05-31T14:59:46.000Z
stockfishservice/src/main/cpp/endgame.cpp
chess24com/StockfishServiceTest
0551c66885301cec812738795f105497ba9a3ad0
[ "MIT" ]
6
2018-10-07T22:27:18.000Z
2019-11-23T08:11:12.000Z
stockfishservice/src/main/cpp/endgame.cpp
chess24com/StockfishServiceTest
0551c66885301cec812738795f105497ba9a3ad0
[ "MIT" ]
10
2018-04-12T08:39:16.000Z
2020-10-07T14:54:01.000Z
/* Stockfish, a UCI chess playing engine derived from Glaurung 2.1 Copyright (C) 2004-2008 Tord Romstad (Glaurung author) Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, Tord Romstad Stockfish is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Stockfish is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <cassert> #include "bitboard.h" #include "endgame.h" #include "movegen.h" using std::string; namespace { // Table used to drive the king towards the edge of the board // in KX vs K and KQ vs KR endgames. const int PushToEdges[SQUARE_NB] = { 100, 90, 80, 70, 70, 80, 90, 100, 90, 70, 60, 50, 50, 60, 70, 90, 80, 60, 40, 30, 30, 40, 60, 80, 70, 50, 30, 20, 20, 30, 50, 70, 70, 50, 30, 20, 20, 30, 50, 70, 80, 60, 40, 30, 30, 40, 60, 80, 90, 70, 60, 50, 50, 60, 70, 90, 100, 90, 80, 70, 70, 80, 90, 100 }; // Table used to drive the king towards a corner square of the // right color in KBN vs K endgames. const int PushToCorners[SQUARE_NB] = { 200, 190, 180, 170, 160, 150, 140, 130, 190, 180, 170, 160, 150, 140, 130, 140, 180, 170, 155, 140, 140, 125, 140, 150, 170, 160, 140, 120, 110, 140, 150, 160, 160, 150, 140, 110, 120, 140, 160, 170, 150, 140, 125, 140, 140, 155, 170, 180, 140, 130, 140, 150, 160, 170, 180, 190, 130, 140, 150, 160, 170, 180, 190, 200 }; // Tables used to drive a piece towards or away from another piece const int PushClose[8] = { 0, 0, 100, 80, 60, 40, 20, 10 }; const int PushAway [8] = { 0, 5, 20, 40, 60, 80, 90, 100 }; // Pawn Rank based scaling factors used in KRPPKRP endgame const int KRPPKRPScaleFactors[RANK_NB] = { 0, 9, 10, 14, 21, 44, 0, 0 }; #ifndef NDEBUG bool verify_material(const Position& pos, Color c, Value npm, int pawnsCnt) { return pos.non_pawn_material(c) == npm && pos.count<PAWN>(c) == pawnsCnt; } #endif // Map the square as if strongSide is white and strongSide's only pawn // is on the left half of the board. Square normalize(const Position& pos, Color strongSide, Square sq) { assert(pos.count<PAWN>(strongSide) == 1); if (file_of(pos.square<PAWN>(strongSide)) >= FILE_E) sq = Square(sq ^ 7); // Mirror SQ_H1 -> SQ_A1 if (strongSide == BLACK) sq = ~sq; return sq; } // Get the material key of Position out of the given endgame key code // like "KBPKN". The trick here is to first forge an ad-hoc FEN string // and then let a Position object do the work for us. Key key(const string& code, Color c) { assert(code.length() > 0 && code.length() < 8); assert(code[0] == 'K'); string sides[] = { code.substr(code.find('K', 1)), // Weak code.substr(0, code.find('K', 1)) }; // Strong std::transform(sides[c].begin(), sides[c].end(), sides[c].begin(), tolower); string fen = sides[0] + char(8 - sides[0].length() + '0') + "/8/8/8/8/8/8/" + sides[1] + char(8 - sides[1].length() + '0') + " w - - 0 10"; StateInfo st; return Position().set(fen, false, &st, nullptr).material_key(); } } // namespace /// Endgames members definitions Endgames::Endgames() { add<KPK>("KPK"); add<KNNK>("KNNK"); add<KBNK>("KBNK"); add<KRKP>("KRKP"); add<KRKB>("KRKB"); add<KRKN>("KRKN"); add<KQKP>("KQKP"); add<KQKR>("KQKR"); add<KNPK>("KNPK"); add<KNPKB>("KNPKB"); add<KRPKR>("KRPKR"); add<KRPKB>("KRPKB"); add<KBPKB>("KBPKB"); add<KBPKN>("KBPKN"); add<KBPPKB>("KBPPKB"); add<KRPPKRP>("KRPPKRP"); } template<EndgameType E, typename T> void Endgames::add(const string& code) { map<T>()[key(code, WHITE)] = std::unique_ptr<EndgameBase<T>>(new Endgame<E>(WHITE)); map<T>()[key(code, BLACK)] = std::unique_ptr<EndgameBase<T>>(new Endgame<E>(BLACK)); } /// Mate with KX vs K. This function is used to evaluate positions with /// king and plenty of material vs a lone king. It simply gives the /// attacking side a bonus for driving the defending king towards the edge /// of the board, and for keeping the distance between the two kings small. template<> Value Endgame<KXK>::operator()(const Position& pos) const { assert(verify_material(pos, weakSide, VALUE_ZERO, 0)); assert(!pos.checkers()); // Eval is never called when in check // Stalemate detection with lone king if (pos.side_to_move() == weakSide && !MoveList<LEGAL>(pos).size()) return VALUE_DRAW; Square winnerKSq = pos.square<KING>(strongSide); Square loserKSq = pos.square<KING>(weakSide); Value result = pos.non_pawn_material(strongSide) + pos.count<PAWN>(strongSide) * PawnValueEg + PushToEdges[loserKSq] + PushClose[distance(winnerKSq, loserKSq)]; if ( pos.count<QUEEN>(strongSide) || pos.count<ROOK>(strongSide) ||(pos.count<BISHOP>(strongSide) && pos.count<KNIGHT>(strongSide)) ||(pos.count<BISHOP>(strongSide) > 1 && opposite_colors(pos.squares<BISHOP>(strongSide)[0], pos.squares<BISHOP>(strongSide)[1]))) result = std::min(result + VALUE_KNOWN_WIN, VALUE_MATE_IN_MAX_PLY - 1); return strongSide == pos.side_to_move() ? result : -result; } /// Mate with KBN vs K. This is similar to KX vs K, but we have to drive the /// defending king towards a corner square of the right color. template<> Value Endgame<KBNK>::operator()(const Position& pos) const { assert(verify_material(pos, strongSide, KnightValueMg + BishopValueMg, 0)); assert(verify_material(pos, weakSide, VALUE_ZERO, 0)); Square winnerKSq = pos.square<KING>(strongSide); Square loserKSq = pos.square<KING>(weakSide); Square bishopSq = pos.square<BISHOP>(strongSide); // kbnk_mate_table() tries to drive toward corners A1 or H8. If we have a // bishop that cannot reach the above squares, we flip the kings in order // to drive the enemy toward corners A8 or H1. if (opposite_colors(bishopSq, SQ_A1)) { winnerKSq = ~winnerKSq; loserKSq = ~loserKSq; } Value result = VALUE_KNOWN_WIN + PushClose[distance(winnerKSq, loserKSq)] + PushToCorners[loserKSq]; return strongSide == pos.side_to_move() ? result : -result; } /// KP vs K. This endgame is evaluated with the help of a bitbase. template<> Value Endgame<KPK>::operator()(const Position& pos) const { assert(verify_material(pos, strongSide, VALUE_ZERO, 1)); assert(verify_material(pos, weakSide, VALUE_ZERO, 0)); // Assume strongSide is white and the pawn is on files A-D Square wksq = normalize(pos, strongSide, pos.square<KING>(strongSide)); Square bksq = normalize(pos, strongSide, pos.square<KING>(weakSide)); Square psq = normalize(pos, strongSide, pos.square<PAWN>(strongSide)); Color us = strongSide == pos.side_to_move() ? WHITE : BLACK; if (!Bitbases::probe(wksq, psq, bksq, us)) return VALUE_DRAW; Value result = VALUE_KNOWN_WIN + PawnValueEg + Value(rank_of(psq)); return strongSide == pos.side_to_move() ? result : -result; } /// KR vs KP. This is a somewhat tricky endgame to evaluate precisely without /// a bitbase. The function below returns drawish scores when the pawn is /// far advanced with support of the king, while the attacking king is far /// away. template<> Value Endgame<KRKP>::operator()(const Position& pos) const { assert(verify_material(pos, strongSide, RookValueMg, 0)); assert(verify_material(pos, weakSide, VALUE_ZERO, 1)); Square wksq = relative_square(strongSide, pos.square<KING>(strongSide)); Square bksq = relative_square(strongSide, pos.square<KING>(weakSide)); Square rsq = relative_square(strongSide, pos.square<ROOK>(strongSide)); Square psq = relative_square(strongSide, pos.square<PAWN>(weakSide)); Square queeningSq = make_square(file_of(psq), RANK_1); Value result; // If the stronger side's king is in front of the pawn, it's a win if (wksq < psq && file_of(wksq) == file_of(psq)) result = RookValueEg - distance(wksq, psq); // If the weaker side's king is too far from the pawn and the rook, // it's a win. else if ( distance(bksq, psq) >= 3 + (pos.side_to_move() == weakSide) && distance(bksq, rsq) >= 3) result = RookValueEg - distance(wksq, psq); // If the pawn is far advanced and supported by the defending king, // the position is drawish else if ( rank_of(bksq) <= RANK_3 && distance(bksq, psq) == 1 && rank_of(wksq) >= RANK_4 && distance(wksq, psq) > 2 + (pos.side_to_move() == strongSide)) result = Value(80) - 8 * distance(wksq, psq); else result = Value(200) - 8 * ( distance(wksq, psq + DELTA_S) - distance(bksq, psq + DELTA_S) - distance(psq, queeningSq)); return strongSide == pos.side_to_move() ? result : -result; } /// KR vs KB. This is very simple, and always returns drawish scores. The /// score is slightly bigger when the defending king is close to the edge. template<> Value Endgame<KRKB>::operator()(const Position& pos) const { assert(verify_material(pos, strongSide, RookValueMg, 0)); assert(verify_material(pos, weakSide, BishopValueMg, 0)); Value result = Value(PushToEdges[pos.square<KING>(weakSide)]); return strongSide == pos.side_to_move() ? result : -result; } /// KR vs KN. The attacking side has slightly better winning chances than /// in KR vs KB, particularly if the king and the knight are far apart. template<> Value Endgame<KRKN>::operator()(const Position& pos) const { assert(verify_material(pos, strongSide, RookValueMg, 0)); assert(verify_material(pos, weakSide, KnightValueMg, 0)); Square bksq = pos.square<KING>(weakSide); Square bnsq = pos.square<KNIGHT>(weakSide); Value result = Value(PushToEdges[bksq] + PushAway[distance(bksq, bnsq)]); return strongSide == pos.side_to_move() ? result : -result; } /// KQ vs KP. In general, this is a win for the stronger side, but there are a /// few important exceptions. A pawn on 7th rank and on the A,C,F or H files /// with a king positioned next to it can be a draw, so in that case, we only /// use the distance between the kings. template<> Value Endgame<KQKP>::operator()(const Position& pos) const { assert(verify_material(pos, strongSide, QueenValueMg, 0)); assert(verify_material(pos, weakSide, VALUE_ZERO, 1)); Square winnerKSq = pos.square<KING>(strongSide); Square loserKSq = pos.square<KING>(weakSide); Square pawnSq = pos.square<PAWN>(weakSide); Value result = Value(PushClose[distance(winnerKSq, loserKSq)]); if ( relative_rank(weakSide, pawnSq) != RANK_7 || distance(loserKSq, pawnSq) != 1 || !((FileABB | FileCBB | FileFBB | FileHBB) & pawnSq)) result += QueenValueEg - PawnValueEg; return strongSide == pos.side_to_move() ? result : -result; } /// KQ vs KR. This is almost identical to KX vs K: We give the attacking /// king a bonus for having the kings close together, and for forcing the /// defending king towards the edge. If we also take care to avoid null move for /// the defending side in the search, this is usually sufficient to win KQ vs KR. template<> Value Endgame<KQKR>::operator()(const Position& pos) const { assert(verify_material(pos, strongSide, QueenValueMg, 0)); assert(verify_material(pos, weakSide, RookValueMg, 0)); Square winnerKSq = pos.square<KING>(strongSide); Square loserKSq = pos.square<KING>(weakSide); Value result = QueenValueEg - RookValueEg + PushToEdges[loserKSq] + PushClose[distance(winnerKSq, loserKSq)]; return strongSide == pos.side_to_move() ? result : -result; } /// Some cases of trivial draws template<> Value Endgame<KNNK>::operator()(const Position&) const { return VALUE_DRAW; } /// KB and one or more pawns vs K. It checks for draws with rook pawns and /// a bishop of the wrong color. If such a draw is detected, SCALE_FACTOR_DRAW /// is returned. If not, the return value is SCALE_FACTOR_NONE, i.e. no scaling /// will be used. template<> ScaleFactor Endgame<KBPsK>::operator()(const Position& pos) const { assert(pos.non_pawn_material(strongSide) == BishopValueMg); assert(pos.count<PAWN>(strongSide) >= 1); // No assertions about the material of weakSide, because we want draws to // be detected even when the weaker side has some pawns. Bitboard pawns = pos.pieces(strongSide, PAWN); File pawnsFile = file_of(lsb(pawns)); // All pawns are on a single rook file? if ( (pawnsFile == FILE_A || pawnsFile == FILE_H) && !(pawns & ~file_bb(pawnsFile))) { Square bishopSq = pos.square<BISHOP>(strongSide); Square queeningSq = relative_square(strongSide, make_square(pawnsFile, RANK_8)); Square kingSq = pos.square<KING>(weakSide); if ( opposite_colors(queeningSq, bishopSq) && distance(queeningSq, kingSq) <= 1) return SCALE_FACTOR_DRAW; } // If all the pawns are on the same B or G file, then it's potentially a draw if ( (pawnsFile == FILE_B || pawnsFile == FILE_G) && !(pos.pieces(PAWN) & ~file_bb(pawnsFile)) && pos.non_pawn_material(weakSide) == 0 && pos.count<PAWN>(weakSide) >= 1) { // Get weakSide pawn that is closest to the home rank Square weakPawnSq = backmost_sq(weakSide, pos.pieces(weakSide, PAWN)); Square strongKingSq = pos.square<KING>(strongSide); Square weakKingSq = pos.square<KING>(weakSide); Square bishopSq = pos.square<BISHOP>(strongSide); // There's potential for a draw if our pawn is blocked on the 7th rank, // the bishop cannot attack it or they only have one pawn left if ( relative_rank(strongSide, weakPawnSq) == RANK_7 && (pos.pieces(strongSide, PAWN) & (weakPawnSq + pawn_push(weakSide))) && (opposite_colors(bishopSq, weakPawnSq) || pos.count<PAWN>(strongSide) == 1)) { int strongKingDist = distance(weakPawnSq, strongKingSq); int weakKingDist = distance(weakPawnSq, weakKingSq); // It's a draw if the weak king is on its back two ranks, within 2 // squares of the blocking pawn and the strong king is not // closer. (I think this rule only fails in practically // unreachable positions such as 5k1K/6p1/6P1/8/8/3B4/8/8 w // and positions where qsearch will immediately correct the // problem such as 8/4k1p1/6P1/1K6/3B4/8/8/8 w) if ( relative_rank(strongSide, weakKingSq) >= RANK_7 && weakKingDist <= 2 && weakKingDist <= strongKingDist) return SCALE_FACTOR_DRAW; } } return SCALE_FACTOR_NONE; } /// KQ vs KR and one or more pawns. It tests for fortress draws with a rook on /// the third rank defended by a pawn. template<> ScaleFactor Endgame<KQKRPs>::operator()(const Position& pos) const { assert(verify_material(pos, strongSide, QueenValueMg, 0)); assert(pos.count<ROOK>(weakSide) == 1); assert(pos.count<PAWN>(weakSide) >= 1); Square kingSq = pos.square<KING>(weakSide); Square rsq = pos.square<ROOK>(weakSide); if ( relative_rank(weakSide, kingSq) <= RANK_2 && relative_rank(weakSide, pos.square<KING>(strongSide)) >= RANK_4 && relative_rank(weakSide, rsq) == RANK_3 && ( pos.pieces(weakSide, PAWN) & pos.attacks_from<KING>(kingSq) & pos.attacks_from<PAWN>(rsq, strongSide))) return SCALE_FACTOR_DRAW; return SCALE_FACTOR_NONE; } /// KRP vs KR. This function knows a handful of the most important classes of /// drawn positions, but is far from perfect. It would probably be a good idea /// to add more knowledge in the future. /// /// It would also be nice to rewrite the actual code for this function, /// which is mostly copied from Glaurung 1.x, and isn't very pretty. template<> ScaleFactor Endgame<KRPKR>::operator()(const Position& pos) const { assert(verify_material(pos, strongSide, RookValueMg, 1)); assert(verify_material(pos, weakSide, RookValueMg, 0)); // Assume strongSide is white and the pawn is on files A-D Square wksq = normalize(pos, strongSide, pos.square<KING>(strongSide)); Square bksq = normalize(pos, strongSide, pos.square<KING>(weakSide)); Square wrsq = normalize(pos, strongSide, pos.square<ROOK>(strongSide)); Square wpsq = normalize(pos, strongSide, pos.square<PAWN>(strongSide)); Square brsq = normalize(pos, strongSide, pos.square<ROOK>(weakSide)); File f = file_of(wpsq); Rank r = rank_of(wpsq); Square queeningSq = make_square(f, RANK_8); int tempo = (pos.side_to_move() == strongSide); // If the pawn is not too far advanced and the defending king defends the // queening square, use the third-rank defence. if ( r <= RANK_5 && distance(bksq, queeningSq) <= 1 && wksq <= SQ_H5 && (rank_of(brsq) == RANK_6 || (r <= RANK_3 && rank_of(wrsq) != RANK_6))) return SCALE_FACTOR_DRAW; // The defending side saves a draw by checking from behind in case the pawn // has advanced to the 6th rank with the king behind. if ( r == RANK_6 && distance(bksq, queeningSq) <= 1 && rank_of(wksq) + tempo <= RANK_6 && (rank_of(brsq) == RANK_1 || (!tempo && distance<File>(brsq, wpsq) >= 3))) return SCALE_FACTOR_DRAW; if ( r >= RANK_6 && bksq == queeningSq && rank_of(brsq) == RANK_1 && (!tempo || distance(wksq, wpsq) >= 2)) return SCALE_FACTOR_DRAW; // White pawn on a7 and rook on a8 is a draw if black's king is on g7 or h7 // and the black rook is behind the pawn. if ( wpsq == SQ_A7 && wrsq == SQ_A8 && (bksq == SQ_H7 || bksq == SQ_G7) && file_of(brsq) == FILE_A && (rank_of(brsq) <= RANK_3 || file_of(wksq) >= FILE_D || rank_of(wksq) <= RANK_5)) return SCALE_FACTOR_DRAW; // If the defending king blocks the pawn and the attacking king is too far // away, it's a draw. if ( r <= RANK_5 && bksq == wpsq + DELTA_N && distance(wksq, wpsq) - tempo >= 2 && distance(wksq, brsq) - tempo >= 2) return SCALE_FACTOR_DRAW; // Pawn on the 7th rank supported by the rook from behind usually wins if the // attacking king is closer to the queening square than the defending king, // and the defending king cannot gain tempi by threatening the attacking rook. if ( r == RANK_7 && f != FILE_A && file_of(wrsq) == f && wrsq != queeningSq && (distance(wksq, queeningSq) < distance(bksq, queeningSq) - 2 + tempo) && (distance(wksq, queeningSq) < distance(bksq, wrsq) + tempo)) return ScaleFactor(SCALE_FACTOR_MAX - 2 * distance(wksq, queeningSq)); // Similar to the above, but with the pawn further back if ( f != FILE_A && file_of(wrsq) == f && wrsq < wpsq && (distance(wksq, queeningSq) < distance(bksq, queeningSq) - 2 + tempo) && (distance(wksq, wpsq + DELTA_N) < distance(bksq, wpsq + DELTA_N) - 2 + tempo) && ( distance(bksq, wrsq) + tempo >= 3 || ( distance(wksq, queeningSq) < distance(bksq, wrsq) + tempo && (distance(wksq, wpsq + DELTA_N) < distance(bksq, wrsq) + tempo)))) return ScaleFactor( SCALE_FACTOR_MAX - 8 * distance(wpsq, queeningSq) - 2 * distance(wksq, queeningSq)); // If the pawn is not far advanced and the defending king is somewhere in // the pawn's path, it's probably a draw. if (r <= RANK_4 && bksq > wpsq) { if (file_of(bksq) == file_of(wpsq)) return ScaleFactor(10); if ( distance<File>(bksq, wpsq) == 1 && distance(wksq, bksq) > 2) return ScaleFactor(24 - 2 * distance(wksq, bksq)); } return SCALE_FACTOR_NONE; } template<> ScaleFactor Endgame<KRPKB>::operator()(const Position& pos) const { assert(verify_material(pos, strongSide, RookValueMg, 1)); assert(verify_material(pos, weakSide, BishopValueMg, 0)); // Test for a rook pawn if (pos.pieces(PAWN) & (FileABB | FileHBB)) { Square ksq = pos.square<KING>(weakSide); Square bsq = pos.square<BISHOP>(weakSide); Square psq = pos.square<PAWN>(strongSide); Rank rk = relative_rank(strongSide, psq); Square push = pawn_push(strongSide); // If the pawn is on the 5th rank and the pawn (currently) is on // the same color square as the bishop then there is a chance of // a fortress. Depending on the king position give a moderate // reduction or a stronger one if the defending king is near the // corner but not trapped there. if (rk == RANK_5 && !opposite_colors(bsq, psq)) { int d = distance(psq + 3 * push, ksq); if (d <= 2 && !(d == 0 && ksq == pos.square<KING>(strongSide) + 2 * push)) return ScaleFactor(24); else return ScaleFactor(48); } // When the pawn has moved to the 6th rank we can be fairly sure // it's drawn if the bishop attacks the square in front of the // pawn from a reasonable distance and the defending king is near // the corner if ( rk == RANK_6 && distance(psq + 2 * push, ksq) <= 1 && (PseudoAttacks[BISHOP][bsq] & (psq + push)) && distance<File>(bsq, psq) >= 2) return ScaleFactor(8); } return SCALE_FACTOR_NONE; } /// KRPP vs KRP. There is just a single rule: if the stronger side has no passed /// pawns and the defending king is actively placed, the position is drawish. template<> ScaleFactor Endgame<KRPPKRP>::operator()(const Position& pos) const { assert(verify_material(pos, strongSide, RookValueMg, 2)); assert(verify_material(pos, weakSide, RookValueMg, 1)); Square wpsq1 = pos.squares<PAWN>(strongSide)[0]; Square wpsq2 = pos.squares<PAWN>(strongSide)[1]; Square bksq = pos.square<KING>(weakSide); // Does the stronger side have a passed pawn? if (pos.pawn_passed(strongSide, wpsq1) || pos.pawn_passed(strongSide, wpsq2)) return SCALE_FACTOR_NONE; Rank r = std::max(relative_rank(strongSide, wpsq1), relative_rank(strongSide, wpsq2)); if ( distance<File>(bksq, wpsq1) <= 1 && distance<File>(bksq, wpsq2) <= 1 && relative_rank(strongSide, bksq) > r) { assert(r > RANK_1 && r < RANK_7); return ScaleFactor(KRPPKRPScaleFactors[r]); } return SCALE_FACTOR_NONE; } /// K and two or more pawns vs K. There is just a single rule here: If all pawns /// are on the same rook file and are blocked by the defending king, it's a draw. template<> ScaleFactor Endgame<KPsK>::operator()(const Position& pos) const { assert(pos.non_pawn_material(strongSide) == VALUE_ZERO); assert(pos.count<PAWN>(strongSide) >= 2); assert(verify_material(pos, weakSide, VALUE_ZERO, 0)); Square ksq = pos.square<KING>(weakSide); Bitboard pawns = pos.pieces(strongSide, PAWN); // If all pawns are ahead of the king, on a single rook file and // the king is within one file of the pawns, it's a draw. if ( !(pawns & ~in_front_bb(weakSide, rank_of(ksq))) && !((pawns & ~FileABB) && (pawns & ~FileHBB)) && distance<File>(ksq, lsb(pawns)) <= 1) return SCALE_FACTOR_DRAW; return SCALE_FACTOR_NONE; } /// KBP vs KB. There are two rules: if the defending king is somewhere along the /// path of the pawn, and the square of the king is not of the same color as the /// stronger side's bishop, it's a draw. If the two bishops have opposite color, /// it's almost always a draw. template<> ScaleFactor Endgame<KBPKB>::operator()(const Position& pos) const { assert(verify_material(pos, strongSide, BishopValueMg, 1)); assert(verify_material(pos, weakSide, BishopValueMg, 0)); Square pawnSq = pos.square<PAWN>(strongSide); Square strongBishopSq = pos.square<BISHOP>(strongSide); Square weakBishopSq = pos.square<BISHOP>(weakSide); Square weakKingSq = pos.square<KING>(weakSide); // Case 1: Defending king blocks the pawn, and cannot be driven away if ( file_of(weakKingSq) == file_of(pawnSq) && relative_rank(strongSide, pawnSq) < relative_rank(strongSide, weakKingSq) && ( opposite_colors(weakKingSq, strongBishopSq) || relative_rank(strongSide, weakKingSq) <= RANK_6)) return SCALE_FACTOR_DRAW; // Case 2: Opposite colored bishops if (opposite_colors(strongBishopSq, weakBishopSq)) { // We assume that the position is drawn in the following three situations: // // a. The pawn is on rank 5 or further back. // b. The defending king is somewhere in the pawn's path. // c. The defending bishop attacks some square along the pawn's path, // and is at least three squares away from the pawn. // // These rules are probably not perfect, but in practice they work // reasonably well. if (relative_rank(strongSide, pawnSq) <= RANK_5) return SCALE_FACTOR_DRAW; else { Bitboard path = forward_bb(strongSide, pawnSq); if (path & pos.pieces(weakSide, KING)) return SCALE_FACTOR_DRAW; if ( (pos.attacks_from<BISHOP>(weakBishopSq) & path) && distance(weakBishopSq, pawnSq) >= 3) return SCALE_FACTOR_DRAW; } } return SCALE_FACTOR_NONE; } /// KBPP vs KB. It detects a few basic draws with opposite-colored bishops template<> ScaleFactor Endgame<KBPPKB>::operator()(const Position& pos) const { assert(verify_material(pos, strongSide, BishopValueMg, 2)); assert(verify_material(pos, weakSide, BishopValueMg, 0)); Square wbsq = pos.square<BISHOP>(strongSide); Square bbsq = pos.square<BISHOP>(weakSide); if (!opposite_colors(wbsq, bbsq)) return SCALE_FACTOR_NONE; Square ksq = pos.square<KING>(weakSide); Square psq1 = pos.squares<PAWN>(strongSide)[0]; Square psq2 = pos.squares<PAWN>(strongSide)[1]; Rank r1 = rank_of(psq1); Rank r2 = rank_of(psq2); Square blockSq1, blockSq2; if (relative_rank(strongSide, psq1) > relative_rank(strongSide, psq2)) { blockSq1 = psq1 + pawn_push(strongSide); blockSq2 = make_square(file_of(psq2), rank_of(psq1)); } else { blockSq1 = psq2 + pawn_push(strongSide); blockSq2 = make_square(file_of(psq1), rank_of(psq2)); } switch (distance<File>(psq1, psq2)) { case 0: // Both pawns are on the same file. It's an easy draw if the defender firmly // controls some square in the frontmost pawn's path. if ( file_of(ksq) == file_of(blockSq1) && relative_rank(strongSide, ksq) >= relative_rank(strongSide, blockSq1) && opposite_colors(ksq, wbsq)) return SCALE_FACTOR_DRAW; else return SCALE_FACTOR_NONE; case 1: // Pawns on adjacent files. It's a draw if the defender firmly controls the // square in front of the frontmost pawn's path, and the square diagonally // behind this square on the file of the other pawn. if ( ksq == blockSq1 && opposite_colors(ksq, wbsq) && ( bbsq == blockSq2 || (pos.attacks_from<BISHOP>(blockSq2) & pos.pieces(weakSide, BISHOP)) || distance(r1, r2) >= 2)) return SCALE_FACTOR_DRAW; else if ( ksq == blockSq2 && opposite_colors(ksq, wbsq) && ( bbsq == blockSq1 || (pos.attacks_from<BISHOP>(blockSq1) & pos.pieces(weakSide, BISHOP)))) return SCALE_FACTOR_DRAW; else return SCALE_FACTOR_NONE; default: // The pawns are not on the same file or adjacent files. No scaling. return SCALE_FACTOR_NONE; } } /// KBP vs KN. There is a single rule: If the defending king is somewhere along /// the path of the pawn, and the square of the king is not of the same color as /// the stronger side's bishop, it's a draw. template<> ScaleFactor Endgame<KBPKN>::operator()(const Position& pos) const { assert(verify_material(pos, strongSide, BishopValueMg, 1)); assert(verify_material(pos, weakSide, KnightValueMg, 0)); Square pawnSq = pos.square<PAWN>(strongSide); Square strongBishopSq = pos.square<BISHOP>(strongSide); Square weakKingSq = pos.square<KING>(weakSide); if ( file_of(weakKingSq) == file_of(pawnSq) && relative_rank(strongSide, pawnSq) < relative_rank(strongSide, weakKingSq) && ( opposite_colors(weakKingSq, strongBishopSq) || relative_rank(strongSide, weakKingSq) <= RANK_6)) return SCALE_FACTOR_DRAW; return SCALE_FACTOR_NONE; } /// KNP vs K. There is a single rule: if the pawn is a rook pawn on the 7th rank /// and the defending king prevents the pawn from advancing, the position is drawn. template<> ScaleFactor Endgame<KNPK>::operator()(const Position& pos) const { assert(verify_material(pos, strongSide, KnightValueMg, 1)); assert(verify_material(pos, weakSide, VALUE_ZERO, 0)); // Assume strongSide is white and the pawn is on files A-D Square pawnSq = normalize(pos, strongSide, pos.square<PAWN>(strongSide)); Square weakKingSq = normalize(pos, strongSide, pos.square<KING>(weakSide)); if (pawnSq == SQ_A7 && distance(SQ_A8, weakKingSq) <= 1) return SCALE_FACTOR_DRAW; return SCALE_FACTOR_NONE; } /// KNP vs KB. If knight can block bishop from taking pawn, it's a win. /// Otherwise the position is drawn. template<> ScaleFactor Endgame<KNPKB>::operator()(const Position& pos) const { Square pawnSq = pos.square<PAWN>(strongSide); Square bishopSq = pos.square<BISHOP>(weakSide); Square weakKingSq = pos.square<KING>(weakSide); // King needs to get close to promoting pawn to prevent knight from blocking. // Rules for this are very tricky, so just approximate. if (forward_bb(strongSide, pawnSq) & pos.attacks_from<BISHOP>(bishopSq)) return ScaleFactor(distance(weakKingSq, pawnSq)); return SCALE_FACTOR_NONE; } /// KP vs KP. This is done by removing the weakest side's pawn and probing the /// KP vs K bitbase: If the weakest side has a draw without the pawn, it probably /// has at least a draw with the pawn as well. The exception is when the stronger /// side's pawn is far advanced and not on a rook file; in this case it is often /// possible to win (e.g. 8/4k3/3p4/3P4/6K1/8/8/8 w - - 0 1). template<> ScaleFactor Endgame<KPKP>::operator()(const Position& pos) const { assert(verify_material(pos, strongSide, VALUE_ZERO, 1)); assert(verify_material(pos, weakSide, VALUE_ZERO, 1)); // Assume strongSide is white and the pawn is on files A-D Square wksq = normalize(pos, strongSide, pos.square<KING>(strongSide)); Square bksq = normalize(pos, strongSide, pos.square<KING>(weakSide)); Square psq = normalize(pos, strongSide, pos.square<PAWN>(strongSide)); Color us = strongSide == pos.side_to_move() ? WHITE : BLACK; // If the pawn has advanced to the fifth rank or further, and is not a // rook pawn, it's too dangerous to assume that it's at least a draw. if (rank_of(psq) >= RANK_5 && file_of(psq) != FILE_A) return SCALE_FACTOR_NONE; // Probe the KPK bitbase with the weakest side's pawn removed. If it's a draw, // it's probably at least a draw even with the pawn. return Bitbases::probe(wksq, psq, bksq, us) ? SCALE_FACTOR_NONE : SCALE_FACTOR_DRAW; }
37.63948
99
0.663568
[ "object", "transform" ]
044721f1036d27a03c1e972c87a57f05ede64e4c
3,250
cpp
C++
unittests/SyntaxParser/SyntaxParserTests.cpp
juvenal/swift
d4f54b1e9af68b0ae747fd5d4d7a5fc4434185a0
[ "Apache-2.0" ]
1
2021-11-08T09:46:05.000Z
2021-11-08T09:46:05.000Z
unittests/SyntaxParser/SyntaxParserTests.cpp
juvenal/swift
d4f54b1e9af68b0ae747fd5d4d7a5fc4434185a0
[ "Apache-2.0" ]
null
null
null
unittests/SyntaxParser/SyntaxParserTests.cpp
juvenal/swift
d4f54b1e9af68b0ae747fd5d4d7a5fc4434185a0
[ "Apache-2.0" ]
null
null
null
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift-c/SyntaxParser/SwiftSyntaxParser.h" #include "swift/Basic/LLVM.h" #include "llvm/ADT/StringRef.h" #include <vector> #include "gtest/gtest.h" using namespace swift; static swiftparse_client_node_t parse(StringRef source, swiftparse_node_handler_t node_handler, swiftparse_node_lookup_t node_lookup) { swiftparse_parser_t parser = swiftparse_parser_create(); swiftparse_parser_set_node_handler(parser, node_handler); swiftparse_parser_set_node_lookup(parser, node_lookup); swiftparse_client_node_t top = swiftparse_parse_string(parser, source.data(), source.size()); swiftparse_parser_dispose(parser); return top; } TEST(SwiftSyntaxParserTests, IncrementalParsing) { StringRef source1 = "func t1() { }\n" "func t2() { }\n"; StringRef source2 = "func t1renamed() { }\n" "func t2() { }\n"; // FIXME: Use the syntax kind directly instead of the serialization number. swiftparse_syntax_kind_t codeBlockItemList = 163; swiftparse_syntax_kind_t codeBlockItem = 92; // Assign id numbers to codeBlockItem nodes and collect the ids that are // listed as members of a codeBlockItemList node into a vector. // When we reparse, check that we got the parser to resuse the node id from // the previous parse. __block std::vector<int> nodeids; __block int idcounter = 0; size_t t2Offset = StringRef(source1).find("\nfunc t2"); __block int t2NodeId = 0; __block size_t t2NodeLength = 0; swiftparse_node_handler_t nodeHandler = ^swiftparse_client_node_t(const swiftparse_syntax_node_t *raw_node) { if (raw_node->kind == codeBlockItem) { int nodeid = ++idcounter; if (raw_node->range.offset == t2Offset) { t2NodeId = nodeid; t2NodeLength = raw_node->range.length; } return (void*)(intptr_t)nodeid; } if (raw_node->kind == codeBlockItemList) { for (unsigned i = 0, e = raw_node->layout_data.nodes_count; i != e; ++i) { nodeids.push_back((int)(intptr_t)raw_node->layout_data.nodes[i]); } } return nullptr; }; parse(source1, nodeHandler, nullptr); EXPECT_EQ(t2NodeId, 2); ASSERT_NE(t2NodeLength, size_t(0)); EXPECT_EQ(nodeids, (std::vector<int>{1, 2})); nodeids.clear(); idcounter = 1000; t2Offset = StringRef(source2).find("\nfunc t2"); swiftparse_node_lookup_t nodeLookup = ^swiftparse_lookup_result_t(size_t offset, swiftparse_syntax_kind_t kind) { if (offset == t2Offset && kind == codeBlockItem) { return { t2NodeLength, (void*)(intptr_t)t2NodeId }; } else { return {0, nullptr}; } }; parse(source2, nodeHandler, nodeLookup); EXPECT_EQ(nodeids, (std::vector<int>{1001, 2})); }
35.326087
95
0.666154
[ "vector" ]