text
stringlengths
5
1.04M
#pragma once /* ========================================================================= Copyright (c) 2015-2017, COE of Peking University, Shaoqiang Tang. ----------------- cuarma - COE of Peking University, Shaoqiang Tang. ----------------- Author Email yangxianpku@pku.edu.cn Code Repo https://github.com/yangxianpku/cuarma License: MIT (X11) License ============================================================================= */ /** @file cuarma/blas/host_based/common.hpp * @encoding:UTF-8 文档编码 @brief Common routines for single-threaded execution on CPU */ #include "cuarma/traits/handle.hpp" namespace cuarma { namespace blas { namespace host_based { namespace detail { template<typename ResultT, typename VectorT> ResultT * extract_raw_pointer(VectorT & vec) { return reinterpret_cast<ResultT *>(cuarma::traits::ram_handle(vec).get()); } template<typename ResultT, typename VectorT> ResultT const * extract_raw_pointer(VectorT const & vec) { return reinterpret_cast<ResultT const *>(cuarma::traits::ram_handle(vec).get()); } /** @brief Helper class for accessing a strided subvector of a larger vector. */ template<typename NumericT> class vector_array_wrapper { public: typedef NumericT value_type; vector_array_wrapper(value_type * A, arma_size_t start, arma_size_t inc) : A_(A), start_(start), inc_(inc) {} value_type & operator()(arma_size_t i) { return A_[i * inc_ + start_]; } private: value_type * A_; arma_size_t start_; arma_size_t inc_; }; /** @brief Helper array for accessing a strided submatrix embedded in a larger matrix. */ template<typename NumericT, typename LayoutT, bool is_transposed> class matrix_array_wrapper { public: typedef NumericT value_type; matrix_array_wrapper(value_type * A, arma_size_t start1, arma_size_t start2, arma_size_t inc1, arma_size_t inc2, arma_size_t internal_size1, arma_size_t internal_size2) : A_(A), start1_(start1), start2_(start2), inc1_(inc1), inc2_(inc2), internal_size1_(internal_size1), internal_size2_(internal_size2) {} value_type & operator()(arma_size_t i, arma_size_t j) { return A_[LayoutT::mem_index(i * inc1_ + start1_, j * inc2_ + start2_, internal_size1_, internal_size2_)]; } // convenience overloads to address signed index types for OpenMP: value_type & operator()(arma_size_t i, long j) { return operator()(i, static_cast<arma_size_t>(j)); } value_type & operator()(long i, arma_size_t j) { return operator()(static_cast<arma_size_t>(i), j); } value_type & operator()(long i, long j) { return operator()(static_cast<arma_size_t>(i), static_cast<arma_size_t>(j)); } private: value_type * A_; arma_size_t start1_, start2_; arma_size_t inc1_, inc2_; arma_size_t internal_size1_, internal_size2_; }; /** \cond */ template<typename NumericT, typename LayoutT> class matrix_array_wrapper<NumericT, LayoutT, true> { public: typedef NumericT value_type; matrix_array_wrapper(value_type * A, arma_size_t start1, arma_size_t start2, arma_size_t inc1, arma_size_t inc2, arma_size_t internal_size1, arma_size_t internal_size2) : A_(A), start1_(start1), start2_(start2), inc1_(inc1), inc2_(inc2), internal_size1_(internal_size1), internal_size2_(internal_size2) {} value_type & operator()(arma_size_t i, arma_size_t j) { //swapping row and column indices here return A_[LayoutT::mem_index(j * inc1_ + start1_, i * inc2_ + start2_, internal_size1_, internal_size2_)]; } // convenience overloads to address signed index types for OpenMP: value_type & operator()(arma_size_t i, long j) { return operator()(i, static_cast<arma_size_t>(j)); } value_type & operator()(long i, arma_size_t j) { return operator()(static_cast<arma_size_t>(i), j); } value_type & operator()(long i, long j) { return operator()(static_cast<arma_size_t>(i), static_cast<arma_size_t>(j)); } private: value_type * A_; arma_size_t start1_, start2_; arma_size_t inc1_, inc2_; arma_size_t internal_size1_, internal_size2_; }; /** \endcond */ } //namespace detail } //namespace host_based } //namespace blas } //namespace cuarma
// Copyright 2014 Stellar Development Foundation and contributors. Licensed // under the Apache License, Version 2.0. See the COPYING file at the root // of this distribution or at http://www.apache.org/licenses/LICENSE-2.0 #include "util/asio.h" #include "crypto/Hex.h" #include "herder/LedgerCloseData.h" #include "ledger/LedgerManager.h" #include "ledger/LedgerState.h" #include "ledger/LedgerStateHeader.h" #include "lib/catch.hpp" #include "main/Application.h" #include "test/TestUtils.h" #include "test/test.h" #include "transactions/TransactionUtils.h" #include "util/Logging.h" #include "util/Timer.h" #include "xdrpp/marshal.h" #include "main/Config.h" using namespace stellar; using namespace std; typedef std::unique_ptr<Application> appPtr; TEST_CASE("genesisledger", "[ledger]") { VirtualClock clock{}; auto cfg = getTestConfig(0); cfg.USE_CONFIG_FOR_GENESIS = false; auto app = Application::create<ApplicationImpl>(clock, cfg); app->start(); auto const& lcl = app->getLedgerManager().getLastClosedLedgerHeader(); auto const& header = lcl.header; REQUIRE(header.ledgerVersion == 0); REQUIRE(header.previousLedgerHash == Hash{}); REQUIRE(header.scpValue.txSetHash == Hash{}); REQUIRE(header.scpValue.closeTime == 0); REQUIRE(header.scpValue.upgrades.size() == 0); REQUIRE(header.txSetResultHash == Hash{}); REQUIRE(binToHex(header.bucketListHash) == "4e6a8404d33b17eee7031af0b3606b6af8e36fe5a3bff59e4e5e420bd0ad3bf4"); REQUIRE(header.ledgerSeq == 1); REQUIRE(header.totalCoins == 1000000000000000000); REQUIRE(header.feePool == 0); REQUIRE(header.inflationSeq == 0); REQUIRE(header.idPool == 0); REQUIRE(header.baseFee == 1); /* ONFO */ REQUIRE(header.baseReserve == 100000000); REQUIRE(header.maxTxSetSize == 100); REQUIRE(header.skipList.size() == 4); REQUIRE(header.skipList[0] == Hash{}); REQUIRE(header.skipList[1] == Hash{}); REQUIRE(header.skipList[2] == Hash{}); REQUIRE(header.skipList[3] == Hash{}); REQUIRE(binToHex(lcl.hash) == "caf73c70dde8134f792535756cc3212f65007883e8959adf92e48062f401e543"); } TEST_CASE("ledgerheader", "[ledger]") { Config cfg(getTestConfig(0, Config::TESTDB_ON_DISK_SQLITE)); Hash saved; { VirtualClock clock; Application::pointer app = Application::create(clock, cfg); app->start(); auto const& lcl = app->getLedgerManager().getLastClosedLedgerHeader(); auto const& lastHash = lcl.hash; TxSetFramePtr txSet = make_shared<TxSetFrame>(lastHash); // close this ledger StellarValue sv(txSet->getContentsHash(), 1, emptyUpgradeSteps, 0); LedgerCloseData ledgerData(lcl.header.ledgerSeq + 1, txSet, sv); app->getLedgerManager().closeLedger(ledgerData); saved = app->getLedgerManager().getLastClosedLedgerHeader().hash; } SECTION("load existing ledger") { Config cfg2(cfg); cfg2.FORCE_SCP = false; VirtualClock clock2; Application::pointer app2 = Application::create(clock2, cfg2, false); app2->start(); REQUIRE(saved == app2->getLedgerManager().getLastClosedLedgerHeader().hash); } } TEST_CASE("base reserve", "[ledger]") { Config const& cfg = getTestConfig(); VirtualClock clock; auto app = createTestApplication(clock, cfg); app->start(); auto const& lcl = app->getLedgerManager().getLastClosedLedgerHeader(); REQUIRE(lcl.header.baseReserve == 100000000); const uint32 n = 20000; int64 expectedReserve = 2000200000000ll; for_versions_to(8, *app, [&]() { LedgerState ls(app->getLedgerStateRoot()); REQUIRE(getMinBalance(ls.loadHeader(), n) < expectedReserve); }); for_versions_from(9, *app, [&]() { LedgerState ls(app->getLedgerStateRoot()); REQUIRE(getMinBalance(ls.loadHeader(), n) == expectedReserve); }); }
// 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. // Date: Thu Jul 30 17:44:54 CST 2015 #include <unistd.h> // getpagesize #include <sys/types.h> #include <sys/resource.h> // getrusage #include <dirent.h> // dirent #include <iomanip> // setw #if defined(__APPLE__) #include <libproc.h> #include <sys/resource.h> #else #endif #include "butil/time.h" #include "butil/memory/singleton_on_pthread_once.h" #include "butil/scoped_lock.h" #include "butil/files/scoped_file.h" #include "butil/files/dir_reader_posix.h" #include "butil/file_util.h" #include "butil/process_util.h" // ReadCommandLine #include "butil/popen.h" // read_command_output #include "bvar/passive_status.h" namespace bvar { template <class T, class M> M get_member_type(M T::*); #define BVAR_MEMBER_TYPE(member) BAIDU_TYPEOF(bvar::get_member_type(member)) int do_link_default_variables = 0; const int64_t CACHED_INTERVAL_US = 100000L; // 100ms // ====================================== struct ProcStat { int pid; //std::string comm; char state; int ppid; int pgrp; int session; int tty_nr; int tpgid; unsigned flags; unsigned long minflt; unsigned long cminflt; unsigned long majflt; unsigned long cmajflt; unsigned long utime; unsigned long stime; unsigned long cutime; unsigned long cstime; long priority; long nice; long num_threads; }; static bool read_proc_status(ProcStat &stat) { stat = ProcStat(); errno = 0; #if defined(OS_LINUX) // Read status from /proc/self/stat. Information from `man proc' is out of date, // see http://man7.org/linux/man-pages/man5/proc.5.html butil::ScopedFILE fp("/proc/self/stat", "r"); if (NULL == fp) { PLOG_ONCE(WARNING) << "Fail to open /proc/self/stat"; return false; } if (fscanf(fp, "%d %*s %c " "%d %d %d %d %d " "%u %lu %lu %lu " "%lu %lu %lu %lu %lu " "%ld %ld %ld", &stat.pid, &stat.state, &stat.ppid, &stat.pgrp, &stat.session, &stat.tty_nr, &stat.tpgid, &stat.flags, &stat.minflt, &stat.cminflt, &stat.majflt, &stat.cmajflt, &stat.utime, &stat.stime, &stat.cutime, &stat.cstime, &stat.priority, &stat.nice, &stat.num_threads) != 19) { PLOG(WARNING) << "Fail to fscanf"; return false; } return true; #elif defined(OS_MACOSX) // TODO(zhujiashun): get remaining state in MacOS. memset(&stat, 0, sizeof(stat)); static pid_t pid = getpid(); std::ostringstream oss; char cmdbuf[128]; snprintf(cmdbuf, sizeof(cmdbuf), "ps -p %ld -o pid,ppid,pgid,sess" ",tpgid,flags,pri,nice | tail -n1", (long)pid); if (butil::read_command_output(oss, cmdbuf) != 0) { LOG(ERROR) << "Fail to read stat"; return -1; } const std::string& result = oss.str(); if (sscanf(result.c_str(), "%d %d %d %d" "%d %x %ld %ld", &stat.pid, &stat.ppid, &stat.pgrp, &stat.session, &stat.tpgid, &stat.flags, &stat.priority, &stat.nice) != 8) { PLOG(WARNING) << "Fail to sscanf"; return false; } return true; #else return false; #endif } // Reduce pressures to functions to get system metrics. template <typename T> class CachedReader { public: CachedReader() : _mtime_us(0) { CHECK_EQ(0, pthread_mutex_init(&_mutex, NULL)); } ~CachedReader() { pthread_mutex_destroy(&_mutex); } // NOTE: may return a volatile value that may be overwritten at any time. // This is acceptable right now. Both 32-bit and 64-bit numbers are atomic // to fetch in 64-bit machines(most of baidu machines) and the code inside // this .cpp utilizing this class generally return a struct with 32-bit // and 64-bit numbers. template <typename ReadFn> static const T& get_value(const ReadFn& fn) { CachedReader* p = butil::get_leaky_singleton<CachedReader>(); const int64_t now = butil::gettimeofday_us(); if (now > p->_mtime_us + CACHED_INTERVAL_US) { pthread_mutex_lock(&p->_mutex); if (now > p->_mtime_us + CACHED_INTERVAL_US) { p->_mtime_us = now; pthread_mutex_unlock(&p->_mutex); // don't run fn inside lock otherwise a slow fn may // block all concurrent bvar dumppers. (e.g. /vars) T result; if (fn(&result)) { pthread_mutex_lock(&p->_mutex); p->_cached = result; } else { pthread_mutex_lock(&p->_mutex); } } pthread_mutex_unlock(&p->_mutex); } return p->_cached; } private: int64_t _mtime_us; pthread_mutex_t _mutex; T _cached; }; class ProcStatReader { public: bool operator()(ProcStat* stat) const { return read_proc_status(*stat); } template <typename T, size_t offset> static T get_field(void*) { return *(T*)((char*)&CachedReader<ProcStat>::get_value( ProcStatReader()) + offset); } }; #define BVAR_DEFINE_PROC_STAT_FIELD(field) \ PassiveStatus<BVAR_MEMBER_TYPE(&ProcStat::field)> g_##field( \ ProcStatReader::get_field<BVAR_MEMBER_TYPE(&ProcStat::field), \ offsetof(ProcStat, field)>, NULL); #define BVAR_DEFINE_PROC_STAT_FIELD2(field, name) \ PassiveStatus<BVAR_MEMBER_TYPE(&ProcStat::field)> g_##field( \ name, \ ProcStatReader::get_field<BVAR_MEMBER_TYPE(&ProcStat::field), \ offsetof(ProcStat, field)>, NULL); // ================================================== struct ProcMemory { long size; // total program size long resident; // resident set size long share; // shared pages long trs; // text (code) long lrs; // library long drs; // data/stack long dt; // dirty pages }; static bool read_proc_memory(ProcMemory &m) { m = ProcMemory(); errno = 0; #if defined(OS_LINUX) butil::ScopedFILE fp("/proc/self/statm", "r"); if (NULL == fp) { PLOG_ONCE(WARNING) << "Fail to open /proc/self/statm"; return false; } if (fscanf(fp, "%ld %ld %ld %ld %ld %ld %ld", &m.size, &m.resident, &m.share, &m.trs, &m.lrs, &m.drs, &m.dt) != 7) { PLOG(WARNING) << "Fail to fscanf /proc/self/statm"; return false; } return true; #elif defined(OS_MACOSX) // TODO(zhujiashun): get remaining memory info in MacOS. memset(&m, 0, sizeof(m)); static pid_t pid = getpid(); static int64_t pagesize = getpagesize(); std::ostringstream oss; char cmdbuf[128]; snprintf(cmdbuf, sizeof(cmdbuf), "ps -p %ld -o rss=,vsz=", (long)pid); if (butil::read_command_output(oss, cmdbuf) != 0) { LOG(ERROR) << "Fail to read memory state"; return -1; } const std::string& result = oss.str(); if (sscanf(result.c_str(), "%ld %ld", &m.resident, &m.size) != 2) { PLOG(WARNING) << "Fail to sscanf"; return false; } // resident and size in Kbytes m.resident = m.resident * 1024 / pagesize; m.size = m.size * 1024 / pagesize; return true; #else return false; #endif } class ProcMemoryReader { public: bool operator()(ProcMemory* stat) const { return read_proc_memory(*stat); }; template <typename T, size_t offset> static T get_field(void*) { static int64_t pagesize = getpagesize(); return *(T*)((char*)&CachedReader<ProcMemory>::get_value( ProcMemoryReader()) + offset) * pagesize; } }; #define BVAR_DEFINE_PROC_MEMORY_FIELD(field, name) \ PassiveStatus<BVAR_MEMBER_TYPE(&ProcMemory::field)> g_##field( \ name, \ ProcMemoryReader::get_field<BVAR_MEMBER_TYPE(&ProcMemory::field), \ offsetof(ProcMemory, field)>, NULL); // ================================================== struct LoadAverage { double loadavg_1m; double loadavg_5m; double loadavg_15m; }; static bool read_load_average(LoadAverage &m) { #if defined(OS_LINUX) butil::ScopedFILE fp("/proc/loadavg", "r"); if (NULL == fp) { PLOG_ONCE(WARNING) << "Fail to open /proc/loadavg"; return false; } m = LoadAverage(); errno = 0; if (fscanf(fp, "%lf %lf %lf", &m.loadavg_1m, &m.loadavg_5m, &m.loadavg_15m) != 3) { PLOG(WARNING) << "Fail to fscanf"; return false; } return true; #elif defined(OS_MACOSX) std::ostringstream oss; if (butil::read_command_output(oss, "sysctl -n vm.loadavg") != 0) { LOG(ERROR) << "Fail to read loadavg"; return -1; } const std::string& result = oss.str(); if (sscanf(result.c_str(), "{ %lf %lf %lf }", &m.loadavg_1m, &m.loadavg_5m, &m.loadavg_15m) != 3) { PLOG(WARNING) << "Fail to sscanf"; return false; } return true; #else return false; #endif } class LoadAverageReader { public: bool operator()(LoadAverage* stat) const { return read_load_average(*stat); }; template <typename T, size_t offset> static T get_field(void*) { return *(T*)((char*)&CachedReader<LoadAverage>::get_value( LoadAverageReader()) + offset); } }; #define BVAR_DEFINE_LOAD_AVERAGE_FIELD(field, name) \ PassiveStatus<BVAR_MEMBER_TYPE(&LoadAverage::field)> g_##field( \ name, \ LoadAverageReader::get_field<BVAR_MEMBER_TYPE(&LoadAverage::field), \ offsetof(LoadAverage, field)>, NULL); // ================================================== static int get_fd_count(int limit) { #if defined(OS_LINUX) butil::DirReaderPosix dr("/proc/self/fd"); int count = 0; if (!dr.IsValid()) { PLOG(WARNING) << "Fail to open /proc/self/fd"; return -1; } // Have to limit the scaning which consumes a lot of CPU when #fd // are huge (100k+) for (; dr.Next() && count <= limit + 3; ++count) {} return count - 3 /* skipped ., .. and the fd in dr*/; #elif defined(OS_MACOSX) // TODO(zhujiashun): following code will cause core dump with some // probability under mac when program exits. Fix it. /* static pid_t pid = getpid(); std::ostringstream oss; char cmdbuf[128]; snprintf(cmdbuf, sizeof(cmdbuf), "lsof -p %ld | grep -v \"txt\" | wc -l", (long)pid); if (butil::read_command_output(oss, cmdbuf) != 0) { LOG(ERROR) << "Fail to read open files"; return -1; } const std::string& result = oss.str(); int count = 0; if (sscanf(result.c_str(), "%d", &count) != 1) { PLOG(WARNING) << "Fail to sscanf"; return -1; } // skipped . and first column line count = count - 2; return std::min(count, limit); */ return 0; #else return 0; #endif } extern PassiveStatus<int> g_fd_num; const int MAX_FD_SCAN_COUNT = 10003; static butil::static_atomic<bool> s_ever_reached_fd_scan_limit = BUTIL_STATIC_ATOMIC_INIT(false); class FdReader { public: bool operator()(int* stat) const { if (s_ever_reached_fd_scan_limit.load(butil::memory_order_relaxed)) { // Never update the count again. return false; } const int count = get_fd_count(MAX_FD_SCAN_COUNT); if (count < 0) { return false; } if (count == MAX_FD_SCAN_COUNT - 2 && s_ever_reached_fd_scan_limit.exchange( true, butil::memory_order_relaxed) == false) { // Rename the bvar to notify user. g_fd_num.hide(); g_fd_num.expose("process_fd_num_too_many"); } *stat = count; return true; } }; static int print_fd_count(void*) { return CachedReader<int>::get_value(FdReader()); } // ================================================== struct ProcIO { // number of bytes the process read, using any read-like system call (from // files, pipes, tty...). size_t rchar; // number of bytes the process wrote using any write-like system call. size_t wchar; // number of read-like system call invocations that the process performed. size_t syscr; // number of write-like system call invocations that the process performed. size_t syscw; // number of bytes the process directly read from disk. size_t read_bytes; // number of bytes the process originally dirtied in the page-cache // (assuming they will go to disk later). size_t write_bytes; // number of bytes the process "un-dirtied" - e.g. using an "ftruncate" // call that truncated pages from the page-cache. size_t cancelled_write_bytes; }; static bool read_proc_io(ProcIO* s) { #if defined(OS_LINUX) butil::ScopedFILE fp("/proc/self/io", "r"); if (NULL == fp) { PLOG_ONCE(WARNING) << "Fail to open /proc/self/io"; return false; } errno = 0; if (fscanf(fp, "%*s %lu %*s %lu %*s %lu %*s %lu %*s %lu %*s %lu %*s %lu", &s->rchar, &s->wchar, &s->syscr, &s->syscw, &s->read_bytes, &s->write_bytes, &s->cancelled_write_bytes) != 7) { PLOG(WARNING) << "Fail to fscanf"; return false; } return true; #elif defined(OS_MACOSX) // TODO(zhujiashun): get rchar, wchar, syscr, syscw, cancelled_write_bytes // in MacOS. memset(s, 0, sizeof(ProcIO)); static pid_t pid = getpid(); rusage_info_current rusage; if (proc_pid_rusage(pid, RUSAGE_INFO_CURRENT, (void**)&rusage) != 0) { PLOG(WARNING) << "Fail to proc_pid_rusage"; return false; } s->read_bytes = rusage.ri_diskio_bytesread; s->write_bytes = rusage.ri_diskio_byteswritten; return true; #else return false; #endif } class ProcIOReader { public: bool operator()(ProcIO* stat) const { return read_proc_io(stat); } template <typename T, size_t offset> static T get_field(void*) { return *(T*)((char*)&CachedReader<ProcIO>::get_value( ProcIOReader()) + offset); } }; #define BVAR_DEFINE_PROC_IO_FIELD(field) \ PassiveStatus<BVAR_MEMBER_TYPE(&ProcIO::field)> g_##field( \ ProcIOReader::get_field<BVAR_MEMBER_TYPE(&ProcIO::field), \ offsetof(ProcIO, field)>, NULL); // ================================================== // Refs: // https://www.kernel.org/doc/Documentation/ABI/testing/procfs-diskstats // https://www.kernel.org/doc/Documentation/iostats.txt // // The /proc/diskstats file displays the I/O statistics of block devices. // Each line contains the following 14 fields: struct DiskStat { long long major_number; long long minor_mumber; char device_name[64]; // The total number of reads completed successfully. long long reads_completed; // wMB/s wKB/s // Reads and writes which are adjacent to each other may be merged for // efficiency. Thus two 4K reads may become one 8K read before it is // ultimately handed to the disk, and so it will be counted (and queued) // as only one I/O. This field lets you know how often this was done. long long reads_merged; // rrqm/s // The total number of sectors read successfully. long long sectors_read; // rsec/s // The total number of milliseconds spent by all reads (as // measured from __make_request() to end_that_request_last()). long long time_spent_reading_ms; // The total number of writes completed successfully. long long writes_completed; // rKB/s rMB/s // See description of reads_merged long long writes_merged; // wrqm/s // The total number of sectors written successfully. long long sectors_written; // wsec/s // The total number of milliseconds spent by all writes (as // measured from __make_request() to end_that_request_last()). long long time_spent_writing_ms; // The only field that should go to zero. Incremented as requests are // given to appropriate struct request_queue and decremented as they finish. long long io_in_progress; // This field increases so long as `io_in_progress' is nonzero. long long time_spent_io_ms; // This field is incremented at each I/O start, I/O completion, I/O // merge, or read of these stats by the number of I/Os in progress // `io_in_progress' times the number of milliseconds spent doing // I/O since the last update of this field. This can provide an easy // measure of both I/O completion time and the backlog that may be // accumulating. long long weighted_time_spent_io_ms; }; static bool read_disk_stat(DiskStat* s) { #if defined(OS_LINUX) butil::ScopedFILE fp("/proc/diskstats", "r"); if (NULL == fp) { PLOG_ONCE(WARNING) << "Fail to open /proc/diskstats"; return false; } errno = 0; if (fscanf(fp, "%lld %lld %s %lld %lld %lld %lld %lld %lld %lld " "%lld %lld %lld %lld", &s->major_number, &s->minor_mumber, s->device_name, &s->reads_completed, &s->reads_merged, &s->sectors_read, &s->time_spent_reading_ms, &s->writes_completed, &s->writes_merged, &s->sectors_written, &s->time_spent_writing_ms, &s->io_in_progress, &s->time_spent_io_ms, &s->weighted_time_spent_io_ms) != 14) { PLOG(WARNING) << "Fail to fscanf"; return false; } return true; #elif defined(OS_MACOSX) // TODO(zhujiashun) return false; #else return false; #endif } class DiskStatReader { public: bool operator()(DiskStat* stat) const { return read_disk_stat(stat); } template <typename T, size_t offset> static T get_field(void*) { return *(T*)((char*)&CachedReader<DiskStat>::get_value( DiskStatReader()) + offset); } }; #define BVAR_DEFINE_DISK_STAT_FIELD(field) \ PassiveStatus<BVAR_MEMBER_TYPE(&DiskStat::field)> g_##field( \ DiskStatReader::get_field<BVAR_MEMBER_TYPE(&DiskStat::field), \ offsetof(DiskStat, field)>, NULL); // ===================================== struct ReadSelfCmdline { std::string content; ReadSelfCmdline() { char buf[1024]; const ssize_t nr = butil::ReadCommandLine(buf, sizeof(buf), true); content.append(buf, nr); } }; static void get_cmdline(std::ostream& os, void*) { os << butil::get_leaky_singleton<ReadSelfCmdline>()->content; } struct ReadVersion { std::string content; ReadVersion() { std::ostringstream oss; if (butil::read_command_output(oss, "uname -ap") != 0) { LOG(ERROR) << "Fail to read kernel version"; return; } content.append(oss.str()); } }; static void get_kernel_version(std::ostream& os, void*) { os << butil::get_leaky_singleton<ReadVersion>()->content; } // ====================================== static int64_t g_starting_time = butil::gettimeofday_us(); static timeval get_uptime(void*) { int64_t uptime_us = butil::gettimeofday_us() - g_starting_time; timeval tm; tm.tv_sec = uptime_us / 1000000L; tm.tv_usec = uptime_us - tm.tv_sec * 1000000L; return tm; } // ====================================== class RUsageReader { public: bool operator()(rusage* stat) const { const int rc = getrusage(RUSAGE_SELF, stat); if (rc < 0) { PLOG(WARNING) << "Fail to getrusage"; return false; } return true; } template <typename T, size_t offset> static T get_field(void*) { return *(T*)((char*)&CachedReader<rusage>::get_value( RUsageReader()) + offset); } }; #define BVAR_DEFINE_RUSAGE_FIELD(field) \ PassiveStatus<BVAR_MEMBER_TYPE(&rusage::field)> g_##field( \ RUsageReader::get_field<BVAR_MEMBER_TYPE(&rusage::field), \ offsetof(rusage, field)>, NULL); \ #define BVAR_DEFINE_RUSAGE_FIELD2(field, name) \ PassiveStatus<BVAR_MEMBER_TYPE(&rusage::field)> g_##field( \ name, \ RUsageReader::get_field<BVAR_MEMBER_TYPE(&rusage::field), \ offsetof(rusage, field)>, NULL); \ // ====================================== BVAR_DEFINE_PROC_STAT_FIELD2(pid, "pid"); BVAR_DEFINE_PROC_STAT_FIELD2(ppid, "ppid"); BVAR_DEFINE_PROC_STAT_FIELD2(pgrp, "pgrp"); static void get_username(std::ostream& os, void*) { char buf[32]; if (getlogin_r(buf, sizeof(buf)) == 0) { buf[sizeof(buf)-1] = '\0'; os << buf; } else { os << "unknown (" << berror() << ')' ; } } PassiveStatus<std::string> g_username( "process_username", get_username, NULL); BVAR_DEFINE_PROC_STAT_FIELD(minflt); PerSecond<PassiveStatus<unsigned long> > g_minflt_second( "process_faults_minor_second", &g_minflt); BVAR_DEFINE_PROC_STAT_FIELD2(majflt, "process_faults_major"); BVAR_DEFINE_PROC_STAT_FIELD2(priority, "process_priority"); BVAR_DEFINE_PROC_STAT_FIELD2(nice, "process_nice"); BVAR_DEFINE_PROC_STAT_FIELD2(num_threads, "process_thread_count"); PassiveStatus<int> g_fd_num("process_fd_count", print_fd_count, NULL); BVAR_DEFINE_PROC_MEMORY_FIELD(size, "process_memory_virtual"); BVAR_DEFINE_PROC_MEMORY_FIELD(resident, "process_memory_resident"); BVAR_DEFINE_PROC_MEMORY_FIELD(share, "process_memory_shared"); BVAR_DEFINE_PROC_MEMORY_FIELD(trs, "process_memory_text"); BVAR_DEFINE_PROC_MEMORY_FIELD(drs, "process_memory_data_and_stack"); BVAR_DEFINE_LOAD_AVERAGE_FIELD(loadavg_1m, "system_loadavg_1m"); BVAR_DEFINE_LOAD_AVERAGE_FIELD(loadavg_5m, "system_loadavg_5m"); BVAR_DEFINE_LOAD_AVERAGE_FIELD(loadavg_15m, "system_loadavg_15m"); BVAR_DEFINE_PROC_IO_FIELD(rchar); BVAR_DEFINE_PROC_IO_FIELD(wchar); PerSecond<PassiveStatus<size_t> > g_io_read_second( "process_io_read_bytes_second", &g_rchar); PerSecond<PassiveStatus<size_t> > g_io_write_second( "process_io_write_bytes_second", &g_wchar); BVAR_DEFINE_PROC_IO_FIELD(syscr); BVAR_DEFINE_PROC_IO_FIELD(syscw); PerSecond<PassiveStatus<size_t> > g_io_num_reads_second( "process_io_read_second", &g_syscr); PerSecond<PassiveStatus<size_t> > g_io_num_writes_second( "process_io_write_second", &g_syscw); BVAR_DEFINE_PROC_IO_FIELD(read_bytes); BVAR_DEFINE_PROC_IO_FIELD(write_bytes); PerSecond<PassiveStatus<size_t> > g_disk_read_second( "process_disk_read_bytes_second", &g_read_bytes); PerSecond<PassiveStatus<size_t> > g_disk_write_second( "process_disk_write_bytes_second", &g_write_bytes); BVAR_DEFINE_RUSAGE_FIELD(ru_utime); BVAR_DEFINE_RUSAGE_FIELD(ru_stime); PassiveStatus<timeval> g_uptime("process_uptime", get_uptime, NULL); static int get_core_num(void*) { return sysconf(_SC_NPROCESSORS_ONLN); } PassiveStatus<int> g_core_num("system_core_count", get_core_num, NULL); struct TimePercent { int64_t time_us; int64_t real_time_us; void operator-=(const TimePercent& rhs) { time_us -= rhs.time_us; real_time_us -= rhs.real_time_us; } void operator+=(const TimePercent& rhs) { time_us += rhs.time_us; real_time_us += rhs.real_time_us; } }; inline std::ostream& operator<<(std::ostream& os, const TimePercent& tp) { if (tp.real_time_us <= 0) { return os << "0"; } else { return os << std::fixed << std::setprecision(3) << (double)tp.time_us / tp.real_time_us; } } static TimePercent get_cputime_percent(void*) { TimePercent tp = { butil::timeval_to_microseconds(g_ru_stime.get_value()) + butil::timeval_to_microseconds(g_ru_utime.get_value()), butil::timeval_to_microseconds(g_uptime.get_value()) }; return tp; } PassiveStatus<TimePercent> g_cputime_percent(get_cputime_percent, NULL); Window<PassiveStatus<TimePercent>, SERIES_IN_SECOND> g_cputime_percent_second( "process_cpu_usage", &g_cputime_percent, FLAGS_bvar_dump_interval); static TimePercent get_stime_percent(void*) { TimePercent tp = { butil::timeval_to_microseconds(g_ru_stime.get_value()), butil::timeval_to_microseconds(g_uptime.get_value()) }; return tp; } PassiveStatus<TimePercent> g_stime_percent(get_stime_percent, NULL); Window<PassiveStatus<TimePercent>, SERIES_IN_SECOND> g_stime_percent_second( "process_cpu_usage_system", &g_stime_percent, FLAGS_bvar_dump_interval); static TimePercent get_utime_percent(void*) { TimePercent tp = { butil::timeval_to_microseconds(g_ru_utime.get_value()), butil::timeval_to_microseconds(g_uptime.get_value()) }; return tp; } PassiveStatus<TimePercent> g_utime_percent(get_utime_percent, NULL); Window<PassiveStatus<TimePercent>, SERIES_IN_SECOND> g_utime_percent_second( "process_cpu_usage_user", &g_utime_percent, FLAGS_bvar_dump_interval); // According to http://man7.org/linux/man-pages/man2/getrusage.2.html // Unsupported fields in linux: // ru_ixrss // ru_idrss // ru_isrss // ru_nswap // ru_nsignals BVAR_DEFINE_RUSAGE_FIELD(ru_inblock); BVAR_DEFINE_RUSAGE_FIELD(ru_oublock); BVAR_DEFINE_RUSAGE_FIELD(ru_nvcsw); BVAR_DEFINE_RUSAGE_FIELD(ru_nivcsw); PerSecond<PassiveStatus<long> > g_ru_inblock_second( "process_inblocks_second", &g_ru_inblock); PerSecond<PassiveStatus<long> > g_ru_oublock_second( "process_outblocks_second", &g_ru_oublock); PerSecond<PassiveStatus<long> > cs_vol_second( "process_context_switches_voluntary_second", &g_ru_nvcsw); PerSecond<PassiveStatus<long> > cs_invol_second( "process_context_switches_involuntary_second", &g_ru_nivcsw); PassiveStatus<std::string> g_cmdline("process_cmdline", get_cmdline, NULL); PassiveStatus<std::string> g_kernel_version( "kernel_version", get_kernel_version, NULL); static std::string* s_gcc_version = NULL; pthread_once_t g_gen_gcc_version_once = PTHREAD_ONCE_INIT; void gen_gcc_version() { #if defined(__GNUC__) const int gcc_major = __GNUC__; #else const int gcc_major = -1; #endif #if defined(__GNUC_MINOR__) const int gcc_minor = __GNUC_MINOR__; #else const int gcc_minor = -1; #endif #if defined(__GNUC_PATCHLEVEL__) const int gcc_patchlevel = __GNUC_PATCHLEVEL__; #else const int gcc_patchlevel = -1; #endif s_gcc_version = new std::string; if (gcc_major == -1) { *s_gcc_version = "unknown"; return; } std::ostringstream oss; oss << gcc_major; if (gcc_minor == -1) { return; } oss << '.' << gcc_minor; if (gcc_patchlevel == -1) { return; } oss << '.' << gcc_patchlevel; *s_gcc_version = oss.str(); } void get_gcc_version(std::ostream& os, void*) { pthread_once(&g_gen_gcc_version_once, gen_gcc_version); os << *s_gcc_version; } // ============================================= PassiveStatus<std::string> g_gcc_version("gcc_version", get_gcc_version, NULL); void get_work_dir(std::ostream& os, void*) { butil::FilePath path; const bool rc = butil::GetCurrentDirectory(&path); LOG_IF(WARNING, !rc) << "Fail to GetCurrentDirectory"; os << path.value(); } PassiveStatus<std::string> g_work_dir("process_work_dir", get_work_dir, NULL); #undef BVAR_MEMBER_TYPE #undef BVAR_DEFINE_PROC_STAT_FIELD #undef BVAR_DEFINE_PROC_STAT_FIELD2 #undef BVAR_DEFINE_PROC_MEMORY_FIELD #undef BVAR_DEFINE_RUSAGE_FIELD #undef BVAR_DEFINE_RUSAGE_FIELD2 } // namespace bvar // In the same scope where timeval is defined. Required by clang. inline std::ostream& operator<<(std::ostream& os, const timeval& tm) { return os << tm.tv_sec << '.' << std::setw(6) << std::setfill('0') << tm.tv_usec; }
#include <ctime> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iomanip> #include <sstream> #include <iostream> #include <algorithm> #include <string> #include <vector> #include <queue> #include <list> #include <map> using namespace std; #define OUTPUT_DEBUG1(TARGET0) \ cerr << #TARGET0 << " == " << TARGET0 << endl; #define OUTPUT_DEBUG2(TARGET0, TARGET1) \ cerr << #TARGET0 << " == " << TARGET0 << "," << #TARGET1 << " == " << TARGET1 << endl; #define OUTPUT_DEBUG3(TARGET0, TARGET1, TARGET2) \ cerr << #TARGET0 << " == " << TARGET0 << "," << #TARGET1 << " == " << TARGET1 << "," << #TARGET2 << " == " << TARGET2 << endl; int n, m; int xybob[210], xydog[210]; inline int i2x(int i) { return i << 1; } inline int i2y(int i) { return (i << 1) + 1; } inline double dist(int x0, int y0, int x1, int y1) { return sqrt(double(x0 - x1) * double(x0 - x1) + double(y0 - y1) * double(y0 - y1)); } bool validChoice[110][110]; int match[2][110]; bool visited[110]; bool hungary(int curA) { for (int j = 0; j < m; ++j) { if (!validChoice[curA][j] || visited[j]) continue; visited[j] = true; if (match[1][j] == -1 || hungary(match[1][j])) { match[0][curA] = j; match[1][j] = curA; return true; } } return false; } int main() { ios::sync_with_stdio(false); memset(validChoice, 0, sizeof(validChoice)); cin >> n >> m; for (int i = 0; i < n; ++i) cin >> xybob[i2x(i)] >> xybob[i2y(i)]; for (int j = 0; j < m; ++j) { cin >> xydog[i2x(j)] >> xydog[i2y(j)]; for (int i = 1; i < n; ++i) { double distbob = dist(xybob[i2x(i)], xybob[i2y(i)], xybob[i2x(i - 1)], xybob[i2y(i - 1)]); double distdog = dist(xybob[i2x(i)], xybob[i2y(i)], xydog[i2x(j)], xydog[i2y(j)]) + dist(xydog[i2x(j)], xydog[i2y(j)], xybob[i2x(i - 1)], xybob[i2y(i - 1)]); if (distdog <= distbob * 2.0 + 1e-9) validChoice[i][j] = true; } } memset(match, -1, sizeof(match)); int ansn = 0; for (int i = 1; i < n; ++i) { if (match[0][i] == -1) { memset(visited, 0, sizeof(visited)); ansn += hungary(i) ? 1 : 0; } } cout << ansn + n << endl; for (int i = 0; i < n; ++i) { if (match[0][i] != -1) cout << xydog[i2x(match[0][i])] << ' ' << xydog[i2y(match[0][i])] << ' '; cout << xybob[i2x(i)] << ' ' << xybob[i2y(i)] << (i == n - 1 ? '\n' : ' '); } return 0; }
// 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 "ash/public/cpp/tab_cluster/correlation_clusterer.h" #include <map> #include <set> #include "ash/public/cpp/tab_cluster/undirected_graph.h" #include "base/logging.h" #include "base/rand_util.h" #include "base/strings/strcat.h" #include "base/strings/string_number_conversions.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace ash { namespace { // Number of times we run the clustering algorithm on the given graph. // This is an arbitrary number and might be subjected to further tuning. constexpr int kNumIterations = 10; // Converts current clustering into vector of vectors format. std::vector<std::vector<int>> OutputClusters( const std::vector<int>& clustering) { std::map<int, std::vector<int>> clusters; for (size_t i = 0; i < clustering.size(); ++i) { clusters[clustering[i]].push_back(i); } std::vector<std::vector<int>> output; for (auto& key_value : clusters) { auto& cluster = key_value.second; output.push_back(std::move(cluster)); } return output; } } // namespace // A helper class that keeps track of the sum of edge weights, accounting // for missing edges, for best move computations. class EdgeSum { public: EdgeSum() = default; EdgeSum(const EdgeSum&) = delete; EdgeSum& operator=(const EdgeSum&) = delete; ~EdgeSum() = default; // The edge weight `w` should have the edge weight offset subtracted before // calling this function. void Add(double w) { weight_ += w; } // Should be called at most once, after all edges have been Add()ed. void RemoveDoubleCounting() { weight_ /= 2.0; } // Retrieve the total weight of all edges seen, correcting for the implicit // negative weight of resolution multiplied by the product of the weights of // the two nodes incident to each edge. double NetWeight( double sum_prod_node_weights, const CorrelationClusterer::CorrelationClustererConfig& config) const { return weight_ - config.resolution * sum_prod_node_weights; } private: double weight_ = 0.0; }; CorrelationClusterer::CorrelationClusterer() = default; CorrelationClusterer::~CorrelationClusterer() = default; std::vector<std::vector<int>> CorrelationClusterer::Cluster( const UndirectedGraph& undirected_graph) { Reset(); graph_ = undirected_graph; num_nodes_ = graph_.NumNodes(); // Create all-singletons initial clusters std::vector<std::vector<int>> clusters; for (int i = 0; i < num_nodes_; ++i) { clusters.push_back({i}); } // Initialize to all-singletons clustering. clustering_.reserve(num_nodes_); for (int i = 0; i < num_nodes_; ++i) { int cluster = NewClusterId(); clustering_.push_back(cluster); cluster_sizes_[cluster] = 1; cluster_weights_[cluster] = graph_.NodeWeight(i); } // Modularity objective. config_.resolution = 1.0 / graph_.total_node_weight(); RefineClusters(&clusters); return clusters; } void CorrelationClusterer::RefineClusters( std::vector<std::vector<int>>* clusters_ptr) { std::string error; SetClustering(*clusters_ptr, &error); if (!error.empty()) { LOG(ERROR) << "Failed to set clustering " << error; return; } double objective = 0; auto try_moves = [&](std::vector<std::set<int>>* clusters_to_try) { base::RandomShuffle(clusters_to_try->begin(), clusters_to_try->end()); for (const auto& cluster : *clusters_to_try) { std::pair<absl::optional<int>, double> best_move = BestMove(cluster); if (best_move.second > 0) { absl::optional<int> new_cluster = best_move.first; MoveNodesToCluster(cluster, new_cluster); objective += best_move.second; } } }; for (int iter = 0; iter < kNumIterations; ++iter) { // Use current clusters as move sets, which means we'll consider // merging clusters. std::map<int, std::set<int>> node_cluster_map; for (int i = 0; i < num_nodes_; ++i) { node_cluster_map[ClusterForNode(i)].insert(i); } std::vector<std::set<int>> temp_clusters; for (auto& key_value : node_cluster_map) { auto& cluster = key_value.second; temp_clusters.push_back(std::move(cluster)); } try_moves(&temp_clusters); } *clusters_ptr = OutputClusters(clustering_); } bool CorrelationClusterer::SetClustering( const std::vector<std::vector<int>>& clusters, std::string* error) { std::vector<bool> seen_nodes(num_nodes_); for (const auto& cluster : clusters) { int id = NewClusterId(); for (const auto node : cluster) { if (node >= num_nodes_ || node < 0) { *error = base::StrCat({"Node id ", base::NumberToString(node), " in initial clusters not in expected range [0, ", base::NumberToString(num_nodes_), ")"}); return false; } if (seen_nodes[node]) { *error = base::StrCat({"Node id ", base::NumberToString(node), " appears in initial clusters more than once."}); return false; } seen_nodes[node] = true; MoveNodeToCluster(node, id); } } for (int node = 0; node < num_nodes_; ++node) { if (!seen_nodes[node]) { *error = base::StrCat({"Node id ", base::NumberToString(node), " does not appear in initial clusters."}); return false; } } return true; } void CorrelationClusterer::MoveNodeToCluster(const int node, const int new_cluster) { const int old_cluster = clustering_[node]; const double weight = graph_.NodeWeight(node); cluster_sizes_[old_cluster] -= 1; cluster_weights_[old_cluster] -= weight; if (cluster_sizes_[old_cluster] == 0) { DCHECK_EQ(static_cast<int>(cluster_sizes_.erase(old_cluster)), 1); DCHECK_EQ(static_cast<int>(cluster_weights_.erase(old_cluster)), 1); } clustering_[node] = new_cluster; cluster_sizes_[new_cluster] += 1; cluster_weights_[new_cluster] += weight; } // Null optional means make a new cluster. void CorrelationClusterer::MoveNodesToCluster(const std::set<int>& nodes, absl::optional<int> new_cluster) { int actual_new_cluster = new_cluster ? *new_cluster : NewClusterId(); for (const auto& node : nodes) { MoveNodeToCluster(node, actual_new_cluster); } } std::pair<absl::optional<int>, double> CorrelationClusterer::BestMove( const std::set<int>& moving_nodes) { // Weight of nodes in each cluster that are moving. std::map<int, double> cluster_moving_weights; // Class 2 edges where the endpoints are currently in different clusters. EdgeSum class_2_currently_separate; // Class 1 edges where the endpoints are currently in the same cluster. EdgeSum class_1_currently_together; // Class 1 edges, grouped by the cluster that the non-moving node is in. std::map<int, EdgeSum> class_1_together_after; double moving_nodes_weight = 0; for (const auto& node : moving_nodes) { const int node_cluster = clustering_[node]; cluster_moving_weights[node_cluster] += graph_.NodeWeight(node); moving_nodes_weight += graph_.NodeWeight(node); for (const auto& edge : graph_.Neighbors(node)) { const auto neighbor = edge.first; const auto weight = edge.second; const int neighbor_cluster = clustering_[neighbor]; if (moving_nodes.find(neighbor) != moving_nodes.end()) { // Class 2 edge. if (node_cluster != neighbor_cluster) { class_2_currently_separate.Add(weight); } } else { // Class 1 edge. if (node_cluster == neighbor_cluster) { class_1_currently_together.Add(weight); } class_1_together_after[neighbor_cluster].Add(weight); } } } class_2_currently_separate.RemoveDoubleCounting(); // Now cluster_moving_weights is correct and class_2_currently_separate, // class_1_currently_together, and class_1_by_cluster are ready to call // NetWeight(). return BestMoveFromStats(moving_nodes_weight, cluster_moving_weights, class_2_currently_separate, class_1_currently_together, class_1_together_after); } std::pair<absl::optional<int>, double> CorrelationClusterer::BestMoveFromStats( double moving_nodes_weight, std::map<int, double>& cluster_moving_weights, const EdgeSum& class_2_currently_separate, const EdgeSum& class_1_currently_together, const std::map<int, EdgeSum>& class_1_together_after) { double change_in_objective = 0.0; auto half_square = [](double x) { return x * x / 2.0; }; double max_edges = half_square(moving_nodes_weight); for (const auto& cluster_moving_weight : cluster_moving_weights) { max_edges -= half_square(cluster_moving_weight.second); } change_in_objective += class_2_currently_separate.NetWeight(max_edges, config_); max_edges = 0; for (const auto& cluster_moving_weights : cluster_moving_weights) { max_edges += moving_nodes_weight * (GetClusterWeight(cluster_moving_weights.first) - cluster_moving_weights.second); } change_in_objective -= class_1_currently_together.NetWeight(max_edges, config_); std::pair<absl::optional<int>, double> best_move; best_move.first = absl::nullopt; best_move.second = change_in_objective; for (const auto& cluster_data : class_1_together_after) { int cluster = cluster_data.first; const EdgeSum& data = cluster_data.second; max_edges = moving_nodes_weight * (GetClusterWeight(cluster) - cluster_moving_weights[cluster]); // Change in objective if we move the moving nodes to cluster i. double overall_change_in_objective = change_in_objective + data.NetWeight(max_edges, config_); if (overall_change_in_objective > best_move.second || (overall_change_in_objective == best_move.second && cluster < best_move.first)) { best_move.first = cluster; best_move.second = overall_change_in_objective; } } return best_move; } int CorrelationClusterer::NewClusterId() { return next_cluster_id_++; } int CorrelationClusterer::ClusterForNode(int node) const { return clustering_[node]; } double CorrelationClusterer::GetClusterWeight(int cluster_id) const { return cluster_weights_.at(cluster_id); } void CorrelationClusterer::Reset() { clustering_.clear(); cluster_sizes_.clear(); cluster_weights_.clear(); next_cluster_id_ = 0; } } // namespace ash
#include "StringOperations.h" #include "cute.h" #include "pssst.h" #include <sstream> #include <string> using namespace Pssst; struct Word:strong<std::string,Word>, Out<Word>, Add<Word>, Order<Word>{ }; Word operator"" _w(char const * const s, size_t l){ return Word{std::string{s,l}}; } Word operator"" _w(char c){ return Word{std::string{c}}; } void thisIsAStringOperationsTest() { Word const w { "hello" }; std::ostringstream out{}; out << w; ASSERT_EQUAL("hello",out.str()); } void testStringWrapperCompare(){ Word h{"Hello"}; Word w{"World"}; ASSERT_LESS(h,w); } void testStringAdditionWorks(){ Word w{}; w += "Hello"_w; w += ' '_w; w += "World!"_w; ASSERT_EQUAL("Hello World!"_w, w); } cute::suite make_suite_StringOperations() { cute::suite s { }; s.push_back(CUTE(thisIsAStringOperationsTest)); s.push_back(CUTE(testStringWrapperCompare)); s.push_back(CUTE(testStringAdditionWorks)); return s; }
// // Created by FLXR on 7/15/2018. // #include <xe/common.hpp> #include <xe/utils/sleep.hpp> #ifdef XE_PLATFORM_WINDOWS #include "window/platform/win32/win32window.hpp" typedef xe::internal::PlatformWindowWin32 PlatformWindowType; #endif #include "platformwindow.hpp" namespace xe::internal { PlatformWindow *PlatformWindow::create(VideoMode mode, const string &title, uint style) { return new PlatformWindowType(mode, title, style); } bool PlatformWindow::popEvent(Event &event, bool block) { if (events.empty()) { processEvents(); if (block) { while (events.empty()) { sleep(10); processEvents(); } } } if (!events.empty()) { event = events.front(); events.pop(); return true; } return false; } void PlatformWindow::pushEvent(const Event &event) { events.push(event); } }
// // Module to produce the calorimeter clusters from proto-clusters. See MakeCaloProtocluster for the proto-cluster formation. // // The strategy is to attach the split-off to the main cluster first, take the closest cluster if the split-off time is compatible // with several clusters. Then associate energetic clusters between them, including the reattached split-off of each cluster in the // comparison. // // Note: the cluster center-of-gravity is calculated in the calorimeter section front face frame // // Original author: B. Echenard #include "art/Framework/Core/EDProducer.h" #include "art/Framework/Principal/Event.h" #include "art/Framework/Core/ModuleMacros.h" #include "art_root_io/TFileDirectory.h" #include "art_root_io/TFileService.h" #include "cetlib_except/exception.h" #include "CalorimeterGeom/inc/Calorimeter.hh" #include "CaloCluster/inc/ClusterAssociator.hh" #include "CaloCluster/inc/ClusterMoments.hh" #include "GeometryService/inc/GeomHandle.hh" #include "RecoDataProducts/inc/CaloCrystalHitCollection.hh" #include "RecoDataProducts/inc/CaloClusterCollection.hh" #include "RecoDataProducts/inc/CaloProtoClusterCollection.hh" #include "TH1D.h" #include <iostream> #include <string> #include <list> #include <vector> #include <memory> #include <tuple> #include <array> namespace mu2e { class CaloClusterFromProtoCluster : public art::EDProducer { public: explicit CaloClusterFromProtoCluster(fhicl::ParameterSet const& pset) : art::EDProducer{pset}, caloClusterModuleLabel_(pset.get<std::string>("caloClusterModuleLabel")), mainTag_{caloClusterModuleLabel_, pset.get<std::string>("mainClusterCollName")}, splitTag_{caloClusterModuleLabel_, pset.get<std::string>("splitClusterCollName")}, mainToken_{consumes<CaloProtoClusterCollection>(mainTag_)}, splitToken_{consumes<CaloProtoClusterCollection>(splitTag_)}, deltaTime_(pset.get<double>("deltaTime")), maxDistSplit_(pset.get<double>("maxDistSplit")), maxDistMain_(pset.get<double>("maxDistMain")), cogTypeName_(pset.get<std::string>("cogTypeName")), cogType_(ClusterMoments::Linear), strategy_(pset.get<int>("strategy",0)), diagLevel_(pset.get<int>("diagLevel",0)), messageCategory_("CLUSTER") { produces<CaloClusterCollection>(); } void beginJob() override; void produce(art::Event& e) override; private: std::string const caloClusterModuleLabel_; art::InputTag const mainTag_; art::InputTag const splitTag_; art::ProductToken<CaloProtoClusterCollection> const mainToken_; art::ProductToken<CaloProtoClusterCollection> const splitToken_; double const deltaTime_; double const maxDistSplit_; double const maxDistMain_; std::string const cogTypeName_; ClusterMoments::cogtype cogType_; int const strategy_; int const diagLevel_; std::string const messageCategory_; void makeCaloClusters(CaloClusterCollection& caloClusters, const CaloProtoClusterCollection& caloClustersMain, const CaloProtoClusterCollection& caloClustersSplit); std::array<double,3> calcEnergyLayer(const Calorimeter& cal, const std::vector<art::Ptr<CaloCrystalHit>>& caloCrystalHitsPtrVector); std::array<double,4> clusterTimeEnergy(const std::vector<art::Ptr<CaloCrystalHit>>& hits); }; void CaloClusterFromProtoCluster::beginJob() { if (cogTypeName_.compare("Linear")) cogType_ = ClusterMoments::Linear; if (cogTypeName_.compare("Logarithm")) cogType_ = ClusterMoments::Logarithm; } void CaloClusterFromProtoCluster::produce(art::Event& event) { // Check that calorimeter geometry description exists art::ServiceHandle<GeometryService> geom; if( !(geom->hasElement<Calorimeter>()) ) return; auto const& caloClustersMain = *event.getValidHandle(mainToken_); auto const& caloClustersSplit = *event.getValidHandle(splitToken_); //Create a new CaloCluster collection and fill it auto caloClusters = std::make_unique<CaloClusterCollection>(); makeCaloClusters(*caloClusters, caloClustersMain, caloClustersSplit); event.put(std::move(caloClusters)); } void CaloClusterFromProtoCluster::makeCaloClusters(CaloClusterCollection& caloClusters, const CaloProtoClusterCollection& caloClustersMain, const CaloProtoClusterCollection& caloClustersSplit) { const Calorimeter& cal = *(GeomHandle<Calorimeter>()); ClusterAssociator associator(cal); associator.associateSplitOff(caloClustersMain, caloClustersSplit, deltaTime_,maxDistSplit_); //-- First, associate split-off to main cluster into intermediate buffer CaloProtoClusterCollection caloProtoClustersTemp; for (unsigned int imain(0); imain<caloClustersMain.size(); ++imain) { bool isSplit(false); std::vector<art::Ptr<CaloCrystalHit>> caloCrystalHitsPtrVector = caloClustersMain.at(imain).caloCrystalHitsPtrVector(); //search split-offs and add their hits into the main cluster for (unsigned int isplit=0;isplit<caloClustersSplit.size();++isplit) { if (associator.associatedSplitId(isplit) != imain) continue; isSplit = true; caloCrystalHitsPtrVector.insert(caloCrystalHitsPtrVector.end(), caloClustersSplit.at(isplit).caloCrystalHitsPtrVector().begin(), caloClustersSplit.at(isplit).caloCrystalHitsPtrVector().end()); if (diagLevel_ > 1) std::cout<<"Associated main cluster "<<imain <<" with split cluster "<<isplit<<std::endl; } auto timeEnergy = clusterTimeEnergy(caloCrystalHitsPtrVector); caloProtoClustersTemp.emplace_back(CaloProtoCluster(timeEnergy[0],timeEnergy[1],timeEnergy[2],timeEnergy[3],caloCrystalHitsPtrVector,isSplit)); } // combine main clusters together (split-off included in main clusters at this point) associator.associateMain(caloProtoClustersTemp, deltaTime_, maxDistMain_, strategy_); //finally, form final clusters std::vector<int> flagProto(caloClustersMain.size(),0); for (unsigned int iproto=0;iproto<caloProtoClustersTemp.size();++iproto) { if (flagProto[iproto]) continue; auto caloCrystalHitsPtrVector = caloProtoClustersTemp.at(iproto).caloCrystalHitsPtrVector(); bool isSplit = caloProtoClustersTemp.at(iproto).isSplit(); const auto& seed = **caloCrystalHitsPtrVector.begin(); int diskId = cal.crystal(seed.id()).diskId(); for (int iassoc : associator.associatedMainId(iproto)) { flagProto[iassoc] = 1; isSplit = true; caloCrystalHitsPtrVector.insert(caloCrystalHitsPtrVector.end(), caloProtoClustersTemp.at(iassoc).caloCrystalHitsPtrVector().begin(), caloProtoClustersTemp.at(iassoc).caloCrystalHitsPtrVector().end()); if (diagLevel_ > 1) std::cout<<"Associated to main cluster id="<<iproto<<" main split="<<iassoc<<std::endl; } //sort the crystal by energy std::sort(caloCrystalHitsPtrVector.begin(),caloCrystalHitsPtrVector.end(), [](const art::Ptr<CaloCrystalHit>& lhs,const art::Ptr<CaloCrystalHit>& rhs) {return lhs->energyDep() > rhs->energyDep();} ); auto timeEnergy = clusterTimeEnergy(caloCrystalHitsPtrVector); CaloCluster caloCluster(diskId,timeEnergy[0],timeEnergy[1],timeEnergy[2],timeEnergy[3],caloCrystalHitsPtrVector,caloCrystalHitsPtrVector.size(),isSplit); //calculate a lot of fancy useful things auto EnerLayer = calcEnergyLayer(cal,caloCrystalHitsPtrVector); ClusterMoments cogCalculator(cal,caloCluster,diskId); cogCalculator.calculate(cogType_); caloCluster.cog3Vector(cogCalculator.cog()); caloCluster.secondMoment(cogCalculator.secondMoment()); caloCluster.angle(cogCalculator.angle()); caloCluster.energyRing(EnerLayer[0],EnerLayer[1],EnerLayer[2]); caloClusters.push_back(caloCluster); if (diagLevel_ > 2) { std::cout<<"Making a new cluster with id= "; for (auto il = caloCrystalHitsPtrVector.begin(); il !=caloCrystalHitsPtrVector.end(); ++il) std::cout<<(*il)->id()<<" "; std::cout<<std::endl; } } //finally, sort clusters by energy std::sort(caloClusters.begin(),caloClusters.end(),[](CaloCluster& lhs, CaloCluster& rhs) {return lhs.energyDep() > rhs.energyDep();} ); } //---------------------------------------------------------------------------------------------------- std::array<double,3> CaloClusterFromProtoCluster::calcEnergyLayer(const Calorimeter& cal, const std::vector<art::Ptr<CaloCrystalHit>>& caloCrystalHitsPtrVector) { int seedId = caloCrystalHitsPtrVector[0]->id(); double seedEnergy = caloCrystalHitsPtrVector[0]->energyDep(); auto const neighborsId = cal.crystal(seedId).neighbors(); auto const nneighborsId = cal.crystal(seedId).nextNeighbors(); double e1(seedEnergy),e9(seedEnergy),e25(seedEnergy); for (const auto& il : caloCrystalHitsPtrVector) { int crid = il->id(); for (const auto& it : neighborsId) if (it==crid) {e9 += il->energyDep(); e25 += il->energyDep(); break;} for (const auto& it : nneighborsId) if (it==crid) {e25 += il->energyDep(); break;} } return std::array<double,3> {e1,e9,e25}; } //---------------------------------------------------------------------------------------------------- std::array<double,4> CaloClusterFromProtoCluster::clusterTimeEnergy(const std::vector<art::Ptr<CaloCrystalHit>>& hits) { double totalEnergy(0),totalEnergyErr(0); for (auto hit : hits) { totalEnergy += hit->energyDep(); totalEnergyErr += hit->energyDepErr()*hit->energyDepErr(); } totalEnergyErr = sqrt(totalEnergyErr); const auto& seed = *hits.begin(); double time = seed->time(); double timeErr = seed->timeErr(); return std::array<double,4>{time,timeErr,totalEnergy,totalEnergyErr}; } } DEFINE_ART_MODULE(mu2e::CaloClusterFromProtoCluster); /* To calculate clsuter time with weighted mean for (auto hit : hits) { double weight = 1.0/hit->timeErr()/hit->timeErr(); timeW += weight*hit->time(); timeWtot += weight; } double time = timeW/timeWtot; double timeErr = 1.0/sqrt(timeWtot); */
#include <utils/ColorRgb.h> #include <utils/ColorRgbw.h> void Rgb_to_Rgbw(ColorRgb input, ColorRgbw * output, std::string _whiteAlgorithm) { if (_whiteAlgorithm == "subtract_minimum") { output->white = std::min(input.red, input.green); output->white = std::min(output->white, input.blue); output->red = input.red - output->white; output->green = input.green - output->white; output->blue = input.blue - output->white; } else if (_whiteAlgorithm == "sub_min_warm_adjust") { } else if ( (_whiteAlgorithm == "") || (_whiteAlgorithm == "white_off") ) { output->red = input.red; output->green = input.green; output->blue = input.blue; output->white = 0; } else { std::cout << "ERROR: unknown whiteAlgorithm " << _whiteAlgorithm << std::endl; } }
// Copyright (c) 2011-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <QApplication> #include "guiutil.h" #include "bitcoinaddressvalidator.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "util.h" #include "init.h" #include <QDateTime> #include <QDoubleValidator> #include <QFont> #include <QLineEdit> #if QT_VERSION >= 0x050000 #include <QUrlQuery> #else #include <QUrl> #endif #include <QTextDocument> // for Qt::mightBeRichText #include <QAbstractItemView> #include <QClipboard> #include <QFileDialog> #include <QDesktopServices> #include <QThread> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #ifdef WIN32 #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include "shlwapi.h" #include "shlobj.h" #include "shellapi.h" #endif namespace GUIUtil { QString dateTimeStr(const QDateTime &date) { return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm"); } QString dateTimeStr(qint64 nTime) { return dateTimeStr(QDateTime::fromTime_t((qint32)nTime)); } QFont bitcoinAddressFont() { QFont font("Monospace"); font.setStyleHint(QFont::TypeWriter); return font; } void setupAddressWidget(QLineEdit *widget, QWidget *parent) { widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength); widget->setValidator(new BitcoinAddressValidator(parent)); widget->setFont(bitcoinAddressFont()); } void setupAmountWidget(QLineEdit *widget, QWidget *parent) { QDoubleValidator *amountValidator = new QDoubleValidator(parent); amountValidator->setDecimals(8); amountValidator->setBottom(0.0); widget->setValidator(amountValidator); widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter); } bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out) { // return if URI is not valid or is no bitcoin URI if(!uri.isValid() || uri.scheme() != QString("spec")) return false; SendCoinsRecipient rv; rv.address = uri.path(); rv.amount = 0; #if QT_VERSION < 0x050000 QList<QPair<QString, QString> > items = uri.queryItems(); #else QUrlQuery uriQuery(uri); QList<QPair<QString, QString> > items = uriQuery.queryItems(); #endif for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++) { bool fShouldReturnFalse = false; if (i->first.startsWith("req-")) { i->first.remove(0, 4); fShouldReturnFalse = true; } if (i->first == "label") { rv.label = i->second; fShouldReturnFalse = false; } else if (i->first == "amount") { if(!i->second.isEmpty()) { if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount)) { return false; } } fShouldReturnFalse = false; } if (fShouldReturnFalse) return false; } if(out) { *out = rv; } return true; } bool parseBitcoinURI(QString uri, SendCoinsRecipient *out) { // Convert bitcoin:// to bitcoin: // // Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host, // which will lower-case it (and thus invalidate the address). if(uri.startsWith("spec://")) { uri.replace(0, 11, "spec:"); } QUrl uriInstance(uri); return parseBitcoinURI(uriInstance, out); } QString HtmlEscape(const QString& str, bool fMultiLine) { #if QT_VERSION < 0x050000 QString escaped = Qt::escape(str); #else QString escaped = str.toHtmlEscaped(); #endif if(fMultiLine) { escaped = escaped.replace("\n", "<br>\n"); } return escaped; } QString HtmlEscape(const std::string& str, bool fMultiLine) { return HtmlEscape(QString::fromStdString(str), fMultiLine); } void copyEntryData(QAbstractItemView *view, int column, int role) { if(!view || !view->selectionModel()) return; QModelIndexList selection = view->selectionModel()->selectedRows(column); if(!selection.isEmpty()) { // Copy first item (global clipboard) QApplication::clipboard()->setText(selection.at(0).data(role).toString(), QClipboard::Clipboard); // Copy first item (global mouse selection for e.g. X11 - NOP on Windows) QApplication::clipboard()->setText(selection.at(0).data(role).toString(), QClipboard::Selection); } } void setClipboard(const QString& str) { QApplication::clipboard()->setText(str, QClipboard::Clipboard); QApplication::clipboard()->setText(str, QClipboard::Selection); } QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut) { QString selectedFilter; QString myDir; if(dir.isEmpty()) // Default to user documents location { #if QT_VERSION < 0x050000 myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); #else myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); #endif } else { myDir = dir; } QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter); /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */ QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]"); QString selectedSuffix; if(filter_re.exactMatch(selectedFilter)) { selectedSuffix = filter_re.cap(1); } /* Add suffix if needed */ QFileInfo info(result); if(!result.isEmpty()) { if(info.suffix().isEmpty() && !selectedSuffix.isEmpty()) { /* No suffix specified, add selected suffix */ if(!result.endsWith(".")) result.append("."); result.append(selectedSuffix); } } /* Return selected suffix if asked to */ if(selectedSuffixOut) { *selectedSuffixOut = selectedSuffix; } return result; } Qt::ConnectionType blockingGUIThreadConnection() { if(QThread::currentThread() != qApp->thread()) { return Qt::BlockingQueuedConnection; } else { return Qt::DirectConnection; } } bool checkPoint(const QPoint &p, const QWidget *w) { QWidget *atW = QApplication::widgetAt(w->mapToGlobal(p)); if (!atW) return false; return atW->topLevelWidget() == w; } bool isObscured(QWidget *w) { return !(checkPoint(QPoint(0, 0), w) && checkPoint(QPoint(w->width() - 1, 0), w) && checkPoint(QPoint(0, w->height() - 1), w) && checkPoint(QPoint(w->width() - 1, w->height() - 1), w) && checkPoint(QPoint(w->width() / 2, w->height() / 2), w)); } void openDebugLogfile() { boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; /* Open debug.log with the associated application */ if (boost::filesystem::exists(pathDebug)) QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string()))); } ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) : QObject(parent), size_threshold(size_threshold) { } bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt) { if(evt->type() == QEvent::ToolTipChange) { QWidget *widget = static_cast<QWidget*>(obj); QString tooltip = widget->toolTip(); if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt") && !Qt::mightBeRichText(tooltip)) { // Envelop with <qt></qt> to make sure Qt detects this as rich text // Escape the current message as HTML and replace \n by <br> tooltip = "<qt>" + HtmlEscape(tooltip, true) + "</qt>"; widget->setToolTip(tooltip); return true; } } return QObject::eventFilter(obj, evt); } #ifdef WIN32 boost::filesystem::path static StartupShortcutPath() { return GetSpecialFolderPath(CSIDL_STARTUP) / "SPEC.lnk"; } bool GetStartOnSystemStartup() { // check for Bitcoin.lnk return boost::filesystem::exists(StartupShortcutPath()); } bool SetStartOnSystemStartup(bool fAutoStart) { // If the shortcut exists already, remove it for updating boost::filesystem::remove(StartupShortcutPath()); if (fAutoStart) { CoInitialize(NULL); // Get a pointer to the IShellLink interface. IShellLink* psl = NULL; HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, reinterpret_cast<void**>(&psl)); if (SUCCEEDED(hres)) { // Get the current executable path TCHAR pszExePath[MAX_PATH]; GetModuleFileName(NULL, pszExePath, sizeof(pszExePath)); TCHAR pszArgs[5] = TEXT("-min"); // Set the path to the shortcut target psl->SetPath(pszExePath); PathRemoveFileSpec(pszExePath); psl->SetWorkingDirectory(pszExePath); psl->SetShowCmd(SW_SHOWMINNOACTIVE); psl->SetArguments(pszArgs); // Query IShellLink for the IPersistFile interface for // saving the shortcut in persistent storage. IPersistFile* ppf = NULL; hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf)); if (SUCCEEDED(hres)) { WCHAR pwsz[MAX_PATH]; // Ensure that the string is ANSI. MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH); // Save the link by calling IPersistFile::Save. hres = ppf->Save(pwsz, TRUE); ppf->Release(); psl->Release(); CoUninitialize(); return true; } psl->Release(); } CoUninitialize(); return false; } return true; } #elif defined(LINUX) // Follow the Desktop Application Autostart Spec: // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html boost::filesystem::path static GetAutostartDir() { namespace fs = boost::filesystem; char* pszConfigHome = getenv("XDG_CONFIG_HOME"); if (pszConfigHome) return fs::path(pszConfigHome) / "autostart"; char* pszHome = getenv("HOME"); if (pszHome) return fs::path(pszHome) / ".config" / "autostart"; return fs::path(); } boost::filesystem::path static GetAutostartFilePath() { return GetAutostartDir() / "spec.desktop"; } bool GetStartOnSystemStartup() { boost::filesystem::ifstream optionFile(GetAutostartFilePath()); if (!optionFile.good()) return false; // Scan through file for "Hidden=true": std::string line; while (!optionFile.eof()) { getline(optionFile, line); if (line.find("Hidden") != std::string::npos && line.find("true") != std::string::npos) return false; } optionFile.close(); return true; } bool SetStartOnSystemStartup(bool fAutoStart) { if (!fAutoStart) boost::filesystem::remove(GetAutostartFilePath()); else { char pszExePath[MAX_PATH+1]; memset(pszExePath, 0, sizeof(pszExePath)); if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1) return false; boost::filesystem::create_directories(GetAutostartDir()); boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc); if (!optionFile.good()) return false; // Write a bitcoin.desktop file to the autostart directory: optionFile << "[Desktop Entry]\n"; optionFile << "Type=Application\n"; optionFile << "Name=SPEC\n"; optionFile << "Exec=" << pszExePath << " -min\n"; optionFile << "Terminal=false\n"; optionFile << "Hidden=false\n"; optionFile.close(); } return true; } #elif defined(Q_OS_MAC) // based on: https://github.com/Mozketo/LaunchAtLoginController/blob/master/LaunchAtLoginController.m #include <CoreFoundation/CoreFoundation.h> #include <CoreServices/CoreServices.h> LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl); LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl) { // loop through the list of startup items and try to find the bitcoin app CFArrayRef listSnapshot = LSSharedFileListCopySnapshot(list, NULL); for(int i = 0; i < CFArrayGetCount(listSnapshot); i++) { LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(listSnapshot, i); UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes; CFURLRef currentItemURL = NULL; LSSharedFileListItemResolve(item, resolutionFlags, &currentItemURL, NULL); if(currentItemURL && CFEqual(currentItemURL, findUrl)) { // found CFRelease(currentItemURL); return item; } if(currentItemURL) { CFRelease(currentItemURL); } } return NULL; } bool GetStartOnSystemStartup() { CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle()); LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL); LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl); return !!foundItem; // return boolified object } bool SetStartOnSystemStartup(bool fAutoStart) { CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle()); LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL); LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl); if(fAutoStart && !foundItem) { // add bitcoin app to startup item list LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, NULL, NULL, bitcoinAppUrl, NULL, NULL); } else if(!fAutoStart && foundItem) { // remove item LSSharedFileListItemRemove(loginItems, foundItem); } return true; } #else bool GetStartOnSystemStartup() { return false; } bool SetStartOnSystemStartup(bool fAutoStart) { return false; } #endif HelpMessageBox::HelpMessageBox(QWidget *parent) : QMessageBox(parent) { header = tr("SPEC-Qt") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion()) + "\n\n" + tr("Usage:") + "\n" + " spec-qt [" + tr("command-line options") + "] " + "\n"; coreOptions = QString::fromStdString(HelpMessage()); uiOptions = tr("UI options") + ":\n" + " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" + " -min " + tr("Start minimized") + "\n" + " -splash " + tr("Show splash screen on startup (default: 1)") + "\n"; setWindowTitle(tr("SPEC-Qt")); setTextFormat(Qt::PlainText); // setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider. setText(header + QString(QChar(0x2003)).repeated(50)); setDetailedText(coreOptions + "\n" + uiOptions); } void HelpMessageBox::printToConsole() { // On other operating systems, the expected action is to print the message to the console. QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions; fprintf(stdout, "%s", strUsage.toStdString().c_str()); } void HelpMessageBox::showOrPrint() { #if defined(WIN32) // On Windows, show a message box, as there is no stderr/stdout in windowed applications exec(); #else // On other operating systems, print help text to console printToConsole(); #endif } } // namespace GUIUtil
/* Starstructor, the Starbound Toolset Copyright (C) 2013-2014 Chris Stamford Licensed under terms of The MIT License (MIT) Source file contributers: Chris Stamford contact: cstamford@gmail.com */ #include "utility/stlogger.hpp" #include <QTextStream> #include <QTime> #include <QDebug> #include <QDir> using lockGuard = std::lock_guard<std::recursive_mutex>; namespace Starstructor { namespace Utility { Logger::Logger(const QString& path) : m_failed(false), m_logFile(path) { // Get the directory from the full path const QDir dir(QFileInfo(m_logFile).dir()); if (!dir.exists()) dir.mkpath("."); if (!m_logFile.open(QIODevice::WriteOnly | QIODevice::Text)) { m_failed = true; #ifdef ST_USE_CONSOLE qDebug() << "Failed to open log file at " + path; #endif return; } m_stream.setDevice(&m_logFile); writeLine("Opened log file at " + path); } Logger::~Logger() { if (m_failed) return; writeLine("Closed log file at " + m_logFile.fileName()); m_logFile.close(); } Logger& Logger::operator<<(const char* input) { lockGuard lock(m_writeMutex); if (!m_failed) { m_stream << input; m_stream.flush(); } #ifdef ST_USE_CONSOLE qDebug() << input; #endif return *this; } Logger& Logger::operator<<(const std::string& input) { lockGuard lock(m_writeMutex); if (!m_failed) { m_stream << input.c_str(); m_stream.flush(); } #ifdef ST_USE_CONSOLE qDebug() << input.c_str(); #endif return *this; } Logger& Logger::operator<<(const QString& input) { lockGuard lock(m_writeMutex); if (!m_failed) { m_stream << input; m_stream.flush(); } #ifdef ST_USE_CONSOLE qDebug() << input; #endif return *this; } Logger& Logger::operator<<(const QVariant& input) { lockGuard lock(m_writeMutex); if (!m_failed) { m_stream << input.toString(); m_stream.flush(); } #ifdef ST_USE_CONSOLE qDebug() << input; #endif return *this; } Logger& Logger::operator<<(const Exception& input) { lockGuard lock(m_writeMutex); if (!m_failed) { m_stream << input.what(); m_stream.flush(); } #ifdef ST_USE_CONSOLE qDebug() << input.what(); #endif return *this; } Logger& Logger::operator<<(const std::exception& input) { lockGuard lock(m_writeMutex); if (!m_failed) { m_stream << input.what(); m_stream.flush(); } #ifdef ST_USE_CONSOLE qDebug() << input.what(); #endif return *this; } Logger& Logger::operator<<(const QTextStreamFunction& input) { lockGuard lock(m_writeMutex); if (!m_failed) { m_stream << input; m_stream.flush(); } return *this; } void Logger::write(const char* input) { lockGuard lock(m_writeMutex); const QString formattedInput(getTime() + input); *this << formattedInput; } void Logger::write(const std::string& input) { lockGuard lock(m_writeMutex); const QString formattedInput(getTime() + input.c_str()); *this << formattedInput; } void Logger::write(const QString& input) { lockGuard lock(m_writeMutex); const QString formattedInput(getTime() + input); *this << formattedInput; } void Logger::write(const QVariant& input) { lockGuard lock(m_writeMutex); const QString formattedInput(getTime() + input.toString()); *this << formattedInput; } void Logger::write(const Exception& input) { lockGuard lock(m_writeMutex); const QString formattedInput(getTime() + input.what()); *this << formattedInput; } void Logger::write(const std::exception& input) { lockGuard lock(m_writeMutex); const QString formattedInput(getTime() + input.what()); *this << formattedInput; } void Logger::writeLine(const char* input) { lockGuard lock(m_writeMutex); write(input); *this << endl; } void Logger::writeLine(const std::string& input) { lockGuard lock(m_writeMutex); write(input); *this << endl; } void Logger::writeLine(const QString& input) { lockGuard lock(m_writeMutex); write(input); *this << endl; } void Logger::writeLine(const QVariant& input) { lockGuard lock(m_writeMutex); write(input); *this << endl; } void Logger::writeLine(const Exception& input) { lockGuard lock(m_writeMutex); write(input); *this << endl; } void Logger::writeLine(const std::exception& input) { lockGuard lock(m_writeMutex); write(input); *this << endl; } bool Logger::fail() const { return m_failed; } QString Logger::getTime() { const QString format = "HH:mm:ss zzz"; return "[" + QTime::currentTime().toString(format) + "] "; } } }
#include "contact_info.h" #include "primitive_container.h" #include "ray_axis_aligned_box_intersection.h" #include "nui_node.h" namespace cgv { namespace nui { void contact_info::contact::update_orientation(const quat& q) { if (container && primitive_index != -1) { if (container->rotatable()) container->set_orientation(primitive_index, q); } else if (node->rotatable()) node->set_rotation(q); } void contact_info::contact::update_position(const vec3& r) { if (container && primitive_index != -1) { if (container->translatable()) container->set_position(primitive_index, r); } else if (node->translatable()) node->set_translation(r); } bool contact_info::contact::check_box_update(const box3& old_box, const box3& new_box) const { nui_node* N = 0; if (container && primitive_index != -1) { if (container->check_box_update(old_box, new_box)) N = node; } else { nui_node* P = get_parent(); if (P && P->check_box_update(old_box, new_box)) N = P; } bool result = N != 0; while (N) { N->set_box_outofdate(); N = &(*(N->get_parent()->cast<nui_node>())); } return result; } bool contact_info::contact::approachable() const { if (container && primitive_index != -1) return container->approachable(); return node->approachable(); } bool contact_info::contact::translatable() const { if (container && primitive_index != -1) return container->translatable(); return node->translatable(); } bool contact_info::contact::rotatable() const { if (container && primitive_index != -1) return container->rotatable(); return node->rotatable(); } contact_info::box3 contact_info::contact::get_oriented_bounding_box() const { if (container && primitive_index != -1) return container->get_oriented_bounding_box(primitive_index); box3 B = node->compute_bounding_box(); switch (node->get_scaling_mode()) { case SM_UNIFORM: B.scale(node->get_scale()[0]); break; case SM_NON_UNIFORM : B.ref_min_pnt() *= node->get_scale(); B.ref_max_pnt() *= node->get_scale(); break; } B.translate(node->get_translation()); return B; } contact_info::vec3 contact_info::contact::get_position() const { if (container && primitive_index != -1) return container->get_position(primitive_index); return node->get_translation(); } contact_info::quat contact_info::contact::get_orientation() const { if (container && primitive_index != -1) return container->get_orientation(primitive_index); return node->get_rotation(); } contact_info::box3 contact_info::contact::get_bounding_box() const { if (container && primitive_index != -1) return container->get_bounding_box(primitive_index); return node->compute_and_transform_bounding_box(); } nui_node* contact_info::contact::get_parent() const { if (container && primitive_index != -1) return node; return &(*(node->get_parent()->cast<nui_node>())); } bool contact_info::consider_closest_contact(const contact& C) { if (contacts.empty()) contacts.push_back(C); else if (contacts.front().distance <= C.distance) return false; contacts.front() = C; return true; } /* contact_info::contact& C = contacts.front(); C.distance = distance; C.position = p; C.normal = n; C.texcoord = tc; C.primitive_index = i; C.container = _container; C.node = (_container && _node == 0) ? _container->get_parent() : _node; return true; } */ void compute_closest_box_point(contact_info::contact& C, const contact_info::vec3& pos, const contact_info::vec3& center, const contact_info::vec3& extent, const contact_info::quat* orientation_ptr) { bool result = false; contact_info::vec3 h = 0.5f * extent; contact_info::vec3& p = C.position; p = pos-center; if (orientation_ptr) orientation_ptr->inverse_rotate(p); bool inside[3]; float closest[3]; float distances[3]; int inside_count = 0; for (int j = 0; j < 3; ++j) { closest[j] = p[j] < 0.0f ? -1.0f : 1.0f; distances[j] = fabs(p[j] - closest[j] * h[j]); inside[j] = (p[j] >= -h[j]) && (p[j] <= h[j]); if (inside[j]) ++inside_count; } contact_info::vec3& n = C.normal; n.zeros(); if (inside_count == 3) { int j_min = distances[1] < distances[0] ? 1 : 0; if (distances[2] < distances[j_min]) j_min = 2; C.distance = distances[j_min]; n[j_min] = closest[j_min]; p[j_min] = closest[j_min] * h[j_min]; } else { float sqr_dist = 0; for (int j = 0; j < 3; ++j) { if (!inside[j]) { sqr_dist += distances[j] * distances[j]; n[j] = closest[j]; p[j] = closest[j] * h[j]; } } C.distance = sqrt(sqr_dist); n.normalize(); } contact_info::vec3& tc = C.texcoord; tc = (p + h) / extent; if (orientation_ptr) { orientation_ptr->rotate(p); orientation_ptr->rotate(n); } p += center; } int compute_box_intersection( const contact_info::vec3& box_center, const contact_info::vec3& box_extent, const contact_info::vec3& ray_start, const contact_info::vec3& ray_direction, contact_info::contact& C, contact_info::contact* C2_ptr) { float t_result; contact_info::vec3 p_result, n_result; contact_info::box3 B(-0.5f * box_extent, 0.5f * box_extent); if (!ray_axis_aligned_box_intersection(ray_start - box_center, ray_direction, B, t_result, p_result, n_result, 0.000001f)) return 0; C.distance = t_result; C.position = p_result + box_center; C.normal = n_result; C.texcoord = (p_result + 0.5f * box_extent) / box_extent; return 1; } int compute_box_intersection( const contact_info::vec3& box_center, const contact_info::vec3& box_extent, const contact_info::quat& box_rotation, const contact_info::vec3& ray_start, const contact_info::vec3& ray_direction, contact_info::contact& C, contact_info::contact* C2_ptr) { contact_info::vec3 ro = ray_start - box_center; box_rotation.inverse_rotate(ro); ro += box_center; contact_info::vec3 rd = ray_direction; box_rotation.inverse_rotate(rd); int cnt = compute_box_intersection(box_center, box_extent, ro, rd, C, C2_ptr); // transform result back if (cnt > 0) { C.position = box_rotation.get_rotated(C.position - box_center) + box_center; box_rotation.rotate(C.normal); } if (cnt > 1) { C2_ptr->position = box_rotation.get_rotated(C2_ptr->position - box_center) + box_center; box_rotation.rotate(C2_ptr->normal); } return cnt; } } }
#include <iostream> #include <type_traits> #include <vector> #include <cassert> #include <numeric> #include <agency/execution/executor/experimental/unrolling_executor.hpp> #include <agency/execution/executor/executor_traits.hpp> int main() { using namespace agency; static const size_t unroll_factor = 10; using executor_type = experimental::unrolling_executor<unroll_factor>; static_assert(is_bulk_synchronous_executor<executor_type>::value, "unrolling_executor should be a bulk synchronous executor"); static_assert(is_bulk_executor<executor_type>::value, "unrolling_executor should be a bulk executor"); static_assert(detail::is_detected_exact<sequenced_execution_tag, executor_execution_category_t, executor_type>::value, "unrolling_executor should have sequenced_execution_tag execution_category"); static_assert(detail::is_detected_exact<size_t, executor_shape_t, executor_type>::value, "unrolling_executor should have size_t shape_type"); static_assert(detail::is_detected_exact<size_t, executor_index_t, executor_type>::value, "unrolling_executor should have size_t index_type"); static_assert(detail::is_detected_exact<std::future<int>, executor_future_t, executor_type, int>::value, "unrolling_executor should have std::future furture"); static_assert(executor_execution_depth<executor_type>::value == 1, "unrolling_executor should have execution_depth == 1"); executor_type exec; std::vector<size_t> shapes = {0, 1, 3, unroll_factor - 1, unroll_factor, unroll_factor + 1, 2 * unroll_factor - 1, 2 * unroll_factor, 100 * unroll_factor, 10000}; for(auto shape : shapes) { auto result = exec.bulk_sync_execute( [](size_t idx, std::vector<int>& results, std::vector<int>& shared_arg) { results[idx] = idx + shared_arg[idx]; }, shape, [=]{ return std::vector<int>(shape); }, // results [=]{ return std::vector<int>(shape, 13); } // shared_arg ); std::vector<int> reference(shape); std::iota(reference.begin(), reference.end(), 13); assert(reference == result); } std::cout << "OK" << std::endl; return 0; }
///////////////////////////////////////////// // Spectral processing examples // // (c) V Lazzarini, 2005 // // see License.txt for copyright information ////////////////////////////////////////////// #include <stdio.h> #include "spec.h" #include "fourier.h" /** pv main program \b usage: pv infile outfile dur(s) \n \n infile: input filename \n outfile: output filename \n \n \n all files are supposed to be mono \n some examples can be found in the audio directory */ ; int main(int argc, char **argv){ SNDFILE *fin, *fout; SF_INFO input_info; float *win, *in, *out, *spec; int outsize, specsize, fftsize=1024,hopsize=256; int dataratio=fftsize/hopsize; int frames, extraframes; int read=0, written = 0, i,j, dur; float *buff,sr; if(argc < 3) { printf("%s: unsufficient number of" " arguments(got %d, needed 2)", argv[0], argc-1); usage(); exit(-1); } if(!(fin = sf_open(argv[1], SFM_READ, &input_info))){ printf("could not open %s \n", argv[1]); exit(-1); } sr = input_info.samplerate; dur = input_info.frames; buff = new float[100]; win = new float[fftsize]; in = new float[dur]; /* number of full dataframes */ frames = ((dur*dataratio)/fftsize); /* extra frames [not completely filled] */ extraframes = 1 + (frames*fftsize - dur*dataratio)/fftsize; /* size of spectral data */ specsize = (frames + extraframes)*fftsize; spec = new float[specsize]; outsize = specsize/dataratio; out = new float[outsize]; if(!(fout = sf_open(argv[2], SFM_WRITE, &input_info))){ printf("could not open %s %s\n", argv[2]); exit(-1); } for(i=0; i< fftsize; i++) win[i] = 0.5f - (float)(0.5*cos(i*twopi/fftsize)); for(j=0; j < dur; j+=read){ read = sf_read_float(fin, buff, 100); for(i=0; i < read; i++) in[i+j] = buff[i]; } outsize = pva(in, win, spec, dur, fftsize, hopsize,sr); dur = pvs(spec, win, out, outsize, fftsize, hopsize,sr); for(j=0; j < dur;j+=written){ for(i=0; i < 100 && j < dur; i++){ if(i+j < dur) buff[i] = out[i+j]; else buff[i] = 0.f; } written = sf_write_float(fout, buff, i); } delete[] out; delete[] in; delete[] win; delete[] buff; delete[] spec; sf_close(fout); sf_close(fin); return 0; } void usage(){ puts("\n\n usage: pv input output \n"); }
#include "menu.hpp" #include "../gfx.hpp" #include "../sfx.hpp" #include "../reader.hpp" #include "../text.hpp" #include <cmath> #include <cctype> #include <algorithm> #include "../common.hpp" void Menu::onKeys(SDL_keysym* begin, SDL_keysym* end, bool contains) { for (; begin != end; ++begin) { bool isTab = begin->sym == SDLK_TAB; if ((begin->unicode >= 32 && begin->unicode < 128) || isTab) { Uint32 time = SDL_GetTicks(); if (!isTab && time - searchTime > 1500) searchPrefix.clear(); while (true) { bool wasEmpty = searchPrefix.empty(); auto newPrefix = searchPrefix; if (!isTab) newPrefix += char(begin->unicode); searchTime = time; bool found = false; int skip = isTab ? 1 : 0; for (std::size_t offs = skip; offs < items.size(); ++offs) { int i = (selection_ + offs) % (int)items.size(); auto const& menuString = items[i].string; if (items[i].visible && menuString.size() >= newPrefix.size()) { bool result; if (contains) { result = std::search(menuString.begin(), menuString.end(), newPrefix.begin(), newPrefix.end(), [](char a, char b) { return std::toupper((unsigned char)a) == std::toupper((unsigned char)b); }) != menuString.end(); } else { result = std::equal(newPrefix.begin(), newPrefix.end(), menuString.begin(), [](char a, char b) { return std::toupper((unsigned char)a) == std::toupper((unsigned char)b); }); } if (result) { found = true; moveTo(i); break; } } } if (found) { searchPrefix = newPrefix; break; } searchPrefix.clear(); if (wasEmpty) break; } } } } void Menu::draw(Common& common, bool disabled, int x, bool showDisabledSelection) { int itemsLeft = height; int curY = y; if (x < 0) x = this->x; for(int c = itemFromVisibleIndex(topItem); itemsLeft > 0 && c < (int)items.size(); ++c) { MenuItem& item = items[c]; if(!item.visible) continue; --itemsLeft; bool selected = (c == selection_) && (!disabled || showDisabledSelection); item.draw(common, x, curY, selected, disabled, centered, valueOffsetX); drawItemOverlay(common, item, x, curY, selected, disabled); curY += itemHeight; } if(visibleItemCount > height) { int menuHeight = height * itemHeight + 1; common.font.drawChar(gfx.screenBmp, 22, x - 6, y + 2, 0); common.font.drawChar(gfx.screenBmp, 22, x - 7, y + 1, 50); common.font.drawChar(gfx.screenBmp, 23, x - 6, y + menuHeight - 7, 0); common.font.drawChar(gfx.screenBmp, 23, x - 7, y + menuHeight - 8, 50); int scrollBarHeight = menuHeight - 17; int scrollTabHeight = int(height*scrollBarHeight / visibleItemCount); scrollTabHeight = std::min(scrollTabHeight, scrollBarHeight); scrollTabHeight = std::max(scrollTabHeight, 0); int scrollTabY = y + int(topItem * scrollBarHeight / visibleItemCount); fillRect(gfx.screenBmp, x - 7, scrollTabY + 9, 7, scrollTabHeight, 0); fillRect(gfx.screenBmp, x - 8, scrollTabY + 8, 7, scrollTabHeight, 7); } } void Menu::moveToId(int id) { moveTo(indexFromId(id)); } void Menu::moveTo(int newSelection) { newSelection = std::max(newSelection, 0); newSelection = std::min(newSelection, (int)items.size()-1); selection_ = firstVisibleFrom(newSelection); ensureInView(selection_); } void Menu::moveToFirstVisible() { moveTo(firstVisibleFrom(0)); } bool Menu::isInView(int item) { int visibleIndex = visibleItemIndex(item); return visibleIndex >= topItem && visibleIndex < bottomItem; } bool Menu::itemPosition(MenuItem& item, int& x, int& y) { int index = int(&item - &items[0]); if(!isInView(index)) return false; int visIdx = visibleItemIndex(index); x = this->x; y = this->y + (visIdx - topItem) * itemHeight; return true; } void Menu::ensureInView(int item) { if(item < 0 || item >= (int)items.size() || !items[item].visible) return; // Can't show items outside the menu or invisible items int visibleIndex = visibleItemIndex(item); if(visibleIndex < topItem) setTop(visibleIndex); else if(visibleIndex >= bottomItem) setBottom(visibleIndex + 1); } int Menu::firstVisibleFrom(int item) { for(std::size_t i = item; i < items.size(); ++i) { if(items[i].visible && items[i].selectable) { return (int)i; } } return (int)items.size(); } int Menu::lastVisibleFrom(int item) { for(std::size_t i = item; i-- > 0;) { if(items[i].visible && items[i].selectable) { return (int)i + 1; } } return 0; } int Menu::visibleItemIndex(int item) { int idx = 0; for(int i = 0; i < (int)items.size(); ++i) { if(!items[i].visible) continue; if(i >= item) break; ++idx; } return idx; } int Menu::itemFromVisibleIndex(int idx) { for(int i = 0; i < (int)items.size(); ++i) { if(!items[i].visible) continue; if(idx == 0) return i; --idx; } return (int)items.size(); } void Menu::setBottom(int newBottomVisIdx) { setTop(newBottomVisIdx - height); } void Menu::setTop(int newTopVisIdx) { newTopVisIdx = std::min(newTopVisIdx, visibleItemCount - height); newTopVisIdx = std::max(newTopVisIdx, 0); topItem = newTopVisIdx; bottomItem = std::min(topItem + height, visibleItemCount); } void Menu::setVisibility(int id, bool state) { int item = indexFromId(id); if (item < 0) { sassert(false); return; } if(items[item].visible && !state) --visibleItemCount; else if(!items[item].visible && state) ++visibleItemCount; int realTopItem = itemFromVisibleIndex(topItem); items[item].visible = state; #if 0 // We can't do this at every change, because it can unselect items that are hidden and then shown again if(!items[selection()].visible) movement(1); #endif setTop(visibleItemIndex(realTopItem)); ensureInView(selection()); } void Menu::scroll(int dir) { setTop(topItem + dir); } void Menu::movementPage(int direction) { int sel = visibleItemIndex(selection_); int offset = direction * (height/2); sel += offset; setTop(topItem + offset); sel = std::max(sel, 0); sel = std::min(sel, visibleItemCount-1); moveTo(itemFromVisibleIndex(sel)); } void Menu::movement(int direction) { if(direction < 0) { for(int i = selection_ - 1; i >= 0; --i) { if(items[i].visible && items[i].selectable) { moveTo(i); return; } } for(int i = (int)items.size() - 1; i > selection_; --i) { if(items[i].visible && items[i].selectable) { moveTo(i); return; } } } else if(direction > 0) { for(int i = selection_ + 1; i < (int)items.size(); ++i) { if(items[i].visible && items[i].selectable) { moveTo(i); return; } } for(int i = 0; i < selection_; ++i) { if(items[i].visible && items[i].selectable) { moveTo(i); return; } } } } void Menu::readItems(ReaderFile& f, int length, int count, bool colorPrefix, PalIdx color, PalIdx disColour) { char temp[256]; for(int i = 0; i < count; ++i) { f.get(reinterpret_cast<uint8_t*>(temp), length); int offset = 1; int length = static_cast<unsigned char>(temp[0]); if(colorPrefix) { color = disColour = temp[2]; length -= 2; offset += 2; } addItem(MenuItem(color, disColour, std::string(&temp[offset], length))); } setTop(0); } void Menu::readItem(ReaderFile& f, int offset, PalIdx color, PalIdx disColour) { addItem(MenuItem(color, disColour, readPascalStringAt(f, offset))); } int Menu::addItem(MenuItem item) { int idx = (int)items.size(); items.push_back(item); if(item.visible) ++visibleItemCount; return idx; } void Menu::clear() { items.clear(); visibleItemCount = 0; setTop(0); } int Menu::addItem(MenuItem item, int pos) { int idx = (int)items.size(); items.insert(items.begin() + pos, item); if(item.visible) ++visibleItemCount; return idx; }
#include <networkit/io/BinaryEdgeListPartitionWriter.hpp> #include <fstream> NetworKit::BinaryEdgeListPartitionWriter::BinaryEdgeListPartitionWriter(NetworKit::node firstNode, uint8_t width) : firstNode(firstNode), width(width) { if (width != 4 && width != 8) { throw std::runtime_error("Width must be 4 or 8"); } } void NetworKit::BinaryEdgeListPartitionWriter::write( NetworKit::Partition &zeta, const std::string &path ) const { auto write_little_endian = [](std::ofstream &os, index x, uint8_t width) { for (uint8_t w = 0; w < width; ++w) { os.put(uint8_t(x)); x >>= 8; } }; if (width == 4 && zeta.upperBound() > std::numeric_limits<uint32_t>::max()) { throw std::runtime_error("Error, the upper bound of the given partition cannot be represented by an unsigned int of width 4. Please use a width of 8."); } std::ofstream os(path, std::ios::trunc | std::ios::binary); os.exceptions(std::ofstream::badbit | std::ofstream::failbit); zeta.forEntries([&](NetworKit::index u, NetworKit::index p) { write_little_endian(os, u + firstNode, width); write_little_endian(os, p, width); }); }
#include "External.h" #include "Library.h" static void Init_Descriptor_Heaps(GRAPHICS_CONTEXT &gfx); void Init_Graphics_Context(HWND window, GRAPHICS_CONTEXT &gfx) { IDXGIFactory4 *factory; #ifdef _DEBUG VHR(CreateDXGIFactory2(DXGI_CREATE_FACTORY_DEBUG, IID_PPV_ARGS(&factory))); #else VHR(CreateDXGIFactory2(0, IID_PPV_ARGS(&factory))); #endif #ifdef _DEBUG { ID3D12Debug *dbg; D3D12GetDebugInterface(IID_PPV_ARGS(&dbg)); if (dbg) { dbg->EnableDebugLayer(); ID3D12Debug1 *dbg1; dbg->QueryInterface(IID_PPV_ARGS(&dbg1)); if (dbg1) { dbg1->SetEnableGPUBasedValidation(TRUE); } SAFE_RELEASE(dbg); SAFE_RELEASE(dbg1); } } #endif if (FAILED(D3D12CreateDevice(nullptr, D3D_FEATURE_LEVEL_11_1, IID_PPV_ARGS(&gfx.device)))) { MessageBox(window, "This application requires Windows 10 1709 (RS3) or newer.", "D3D12CreateDevice failed", MB_OK | MB_ICONERROR); return; } D3D12_COMMAND_QUEUE_DESC cmdqueue_desc = {}; cmdqueue_desc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; cmdqueue_desc.Priority = D3D12_COMMAND_QUEUE_PRIORITY_NORMAL; cmdqueue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; VHR(gfx.device->CreateCommandQueue(&cmdqueue_desc, IID_PPV_ARGS(&gfx.cmdqueue))); DXGI_SWAP_CHAIN_DESC swapchain_desc = {}; swapchain_desc.BufferCount = 4; swapchain_desc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swapchain_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapchain_desc.OutputWindow = window; swapchain_desc.SampleDesc.Count = 1; swapchain_desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; swapchain_desc.Windowed = TRUE; IDXGISwapChain *temp_swapchain; VHR(factory->CreateSwapChain(gfx.cmdqueue, &swapchain_desc, &temp_swapchain)); VHR(temp_swapchain->QueryInterface(IID_PPV_ARGS(&gfx.swapchain))); SAFE_RELEASE(temp_swapchain); SAFE_RELEASE(factory); RECT rect; GetClientRect(window, &rect); gfx.resolution[0] = (u32)rect.right; gfx.resolution[1] = (u32)rect.bottom; for (u32 i = 0; i < 2; ++i) { VHR(gfx.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&gfx.cmdalloc[i]))); } gfx.descriptor_size = gfx.device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); gfx.descriptor_size_rtv = gfx.device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); Init_Descriptor_Heaps(gfx); // swap buffer render targets { D3D12_CPU_DESCRIPTOR_HANDLE handle; Allocate_Descriptors(gfx, D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 4, handle); for (u32 i = 0; i < 4; ++i) { VHR(gfx.swapchain->GetBuffer(i, IID_PPV_ARGS(&gfx.swapbuffers[i]))); gfx.device->CreateRenderTargetView(gfx.swapbuffers[i], nullptr, handle); handle.ptr += gfx.descriptor_size_rtv; } } // depth-stencil target { auto image_desc = CD3DX12_RESOURCE_DESC::Tex2D(DXGI_FORMAT_D32_FLOAT, gfx.resolution[0], gfx.resolution[1], 1, 1); image_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE; VHR(gfx.device->CreateCommittedResource(&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT), D3D12_HEAP_FLAG_NONE, &image_desc, D3D12_RESOURCE_STATE_DEPTH_WRITE, &CD3DX12_CLEAR_VALUE(DXGI_FORMAT_D32_FLOAT, 1.0f, 0), IID_PPV_ARGS(&gfx.ds_buffer))); D3D12_CPU_DESCRIPTOR_HANDLE handle; Allocate_Descriptors(gfx, D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, handle); D3D12_DEPTH_STENCIL_VIEW_DESC view_desc = {}; view_desc.Format = DXGI_FORMAT_D32_FLOAT; view_desc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; view_desc.Flags = D3D12_DSV_FLAG_NONE; gfx.device->CreateDepthStencilView(gfx.ds_buffer, &view_desc, handle); } VHR(gfx.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, gfx.cmdalloc[0], nullptr, IID_PPV_ARGS(&gfx.cmdlist))); gfx.cmdlist->Close(); VHR(gfx.device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&gfx.frame_fence))); gfx.frame_fence_event = CreateEventEx(nullptr, nullptr, 0, EVENT_ALL_ACCESS); } void Shutdown_Graphics_Context(GRAPHICS_CONTEXT &gfx) { // @Incomplete: Release all resources. SAFE_RELEASE(gfx.cmdlist); SAFE_RELEASE(gfx.cmdalloc[0]); SAFE_RELEASE(gfx.cmdalloc[1]); SAFE_RELEASE(gfx.rt_heap.heap); SAFE_RELEASE(gfx.ds_heap.heap); for (u32 i = 0; i < 4; ++i) { SAFE_RELEASE(gfx.swapbuffers[i]); } CloseHandle(gfx.frame_fence_event); SAFE_RELEASE(gfx.frame_fence); SAFE_RELEASE(gfx.swapchain); SAFE_RELEASE(gfx.cmdqueue); SAFE_RELEASE(gfx.device); } void Present_Frame(GRAPHICS_CONTEXT &gfx, u32 swap_interval) { gfx.swapchain->Present(swap_interval, 0); gfx.cmdqueue->Signal(gfx.frame_fence, ++gfx.frame_count); const u64 gpu_frame_count = gfx.frame_fence->GetCompletedValue(); if ((gfx.frame_count - gpu_frame_count) >= 2) { gfx.frame_fence->SetEventOnCompletion(gpu_frame_count + 1, gfx.frame_fence_event); WaitForSingleObject(gfx.frame_fence_event, INFINITE); } gfx.frame_index = !gfx.frame_index; gfx.back_buffer_index = gfx.swapchain->GetCurrentBackBufferIndex(); gfx.gpu_descriptor_heaps[gfx.frame_index].size = 0; } void Wait_For_GPU(GRAPHICS_CONTEXT &gfx) { gfx.cmdqueue->Signal(gfx.frame_fence, ++gfx.frame_count); gfx.frame_fence->SetEventOnCompletion(gfx.frame_count, gfx.frame_fence_event); WaitForSingleObject(gfx.frame_fence_event, INFINITE); } DESCRIPTOR_HEAP & Get_Descriptor_Heap(GRAPHICS_CONTEXT &gfx, D3D12_DESCRIPTOR_HEAP_TYPE type, D3D12_DESCRIPTOR_HEAP_FLAGS flags, u32 &descriptor_size) { if (type == D3D12_DESCRIPTOR_HEAP_TYPE_RTV) { descriptor_size = gfx.descriptor_size_rtv; return gfx.rt_heap; } else if (type == D3D12_DESCRIPTOR_HEAP_TYPE_DSV) { descriptor_size = gfx.descriptor_size_rtv; return gfx.ds_heap; } else if (type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { descriptor_size = gfx.descriptor_size; if (flags == D3D12_DESCRIPTOR_HEAP_FLAG_NONE) { return gfx.cpu_descriptor_heap; } else if (flags == D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) { return gfx.gpu_descriptor_heaps[gfx.frame_index]; } } assert(0); descriptor_size = 0; return gfx.cpu_descriptor_heap; } static void Init_Descriptor_Heaps(GRAPHICS_CONTEXT &gfx) { // render target descriptor heap (RTV) { gfx.rt_heap.capacity = 16; D3D12_DESCRIPTOR_HEAP_DESC heap_desc = {}; heap_desc.NumDescriptors = gfx.rt_heap.capacity; heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; heap_desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; VHR(gfx.device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&gfx.rt_heap.heap))); gfx.rt_heap.cpu_start = gfx.rt_heap.heap->GetCPUDescriptorHandleForHeapStart(); } // depth-stencil descriptor heap (DSV) { gfx.ds_heap.capacity = 8; D3D12_DESCRIPTOR_HEAP_DESC heap_desc = {}; heap_desc.NumDescriptors = gfx.ds_heap.capacity; heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV; heap_desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; VHR(gfx.device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&gfx.ds_heap.heap))); gfx.ds_heap.cpu_start = gfx.ds_heap.heap->GetCPUDescriptorHandleForHeapStart(); } // non-shader visible descriptor heap (CBV, SRV, UAV) { gfx.cpu_descriptor_heap.capacity = 10000; D3D12_DESCRIPTOR_HEAP_DESC heap_desc = {}; heap_desc.NumDescriptors = gfx.cpu_descriptor_heap.capacity; heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; heap_desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; VHR(gfx.device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&gfx.cpu_descriptor_heap.heap))); gfx.cpu_descriptor_heap.cpu_start = gfx.cpu_descriptor_heap.heap->GetCPUDescriptorHandleForHeapStart(); } // shader visible descriptor heaps (CBV, SRV, UAV) { for (u32 i = 0; i < 2; ++i) { gfx.gpu_descriptor_heaps[i].capacity = 10000; D3D12_DESCRIPTOR_HEAP_DESC heap_desc = {}; heap_desc.NumDescriptors = gfx.gpu_descriptor_heaps[i].capacity; heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; heap_desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; VHR(gfx.device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&gfx.gpu_descriptor_heaps[i].heap))); gfx.gpu_descriptor_heaps[i].cpu_start = gfx.gpu_descriptor_heaps[i].heap->GetCPUDescriptorHandleForHeapStart(); gfx.gpu_descriptor_heaps[i].gpu_start = gfx.gpu_descriptor_heaps[i].heap->GetGPUDescriptorHandleForHeapStart(); } } } void Load_File(const char *filename, u32 &size, u8 *&data) { FILE *file = fopen(filename, "rb"); assert(file); fseek(file, 0, SEEK_END); long ret_size = ftell(file); if (ret_size == -1) { assert(0); return; } size = (u32)ret_size; data = (u8 *)Mem_Alloc(size); fseek(file, 0, SEEK_SET); fread(data, 1, size, file); fclose(file); } void Update_Frame_Stats(HWND window, const char *name, f64 &time, f32 &delta_time) { static f64 previous_time = -1.0; static f64 header_refresh_time = 0.0; static u32 frame_count = 0; if (previous_time < 0.0) { previous_time = Get_Time(); header_refresh_time = previous_time; } time = Get_Time(); delta_time = (f32)(time - previous_time); previous_time = time; if ((time - header_refresh_time) >= 1.0) { const f64 fps = frame_count / (time - header_refresh_time); const f64 ms = (1.0 / fps) * 1000.0; char header[256]; snprintf(header, sizeof(header), "[%.1f fps %.3f ms] %s", fps, ms, name); SetWindowText(window, header); header_refresh_time = time; frame_count = 0; } frame_count++; } f64 Get_Time() { static LARGE_INTEGER start_counter; static LARGE_INTEGER frequency; if (start_counter.QuadPart == 0) { QueryPerformanceFrequency(&frequency); QueryPerformanceCounter(&start_counter); } LARGE_INTEGER counter; QueryPerformanceCounter(&counter); return (counter.QuadPart - start_counter.QuadPart) / (f64)frequency.QuadPart; } static LRESULT CALLBACK Process_Window_Message(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { switch (message) { case WM_DESTROY: PostQuitMessage(0); return 0; case WM_KEYDOWN: if (wparam == VK_ESCAPE) { PostQuitMessage(0); return 0; } break; } return DefWindowProc(window, message, wparam, lparam); } HWND Create_Window(const char *name, u32 width, u32 height) { WNDCLASS winclass = {}; winclass.lpfnWndProc = Process_Window_Message; winclass.hInstance = GetModuleHandle(nullptr); winclass.hCursor = LoadCursor(nullptr, IDC_ARROW); winclass.lpszClassName = name; if (!RegisterClass(&winclass)) { assert(0); } RECT rect = { 0, 0, (LONG)width, (LONG)height }; if (!AdjustWindowRect(&rect, WS_OVERLAPPED | WS_SYSMENU | WS_CAPTION | WS_MINIMIZEBOX, 0)) { assert(0); } HWND window = CreateWindowEx(0, name, name, WS_OVERLAPPED | WS_SYSMENU | WS_CAPTION | WS_MINIMIZEBOX | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, rect.right - rect.left, rect.bottom - rect.top, nullptr, nullptr, nullptr, 0); assert(window); return window; } void * Mem_Alloc(usize size) { assert(size > 0); void *mem = HeapAlloc(GetProcessHeap(), 0, size); if (!mem) { OutputDebugString("Failed to allocate memory!"); assert(0); exit(1); } return mem; } void * Mem_Realloc(void *addr, usize size) { assert(size > 0); if (addr == NULL) { return Mem_Alloc(size); } else { void *mem = HeapReAlloc(GetProcessHeap(), 0, addr, size); if (!mem) { OutputDebugString("Failed to reallocate memory!"); assert(0); exit(1); } return mem; } } void Mem_Free(void *addr) { assert(addr); if (!HeapFree(GetProcessHeap(), 0, addr)) { OutputDebugString("Failed to free memory!"); assert(0); exit(1); } }
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html #include "test_precomp.hpp" namespace opencv_test { namespace { #ifdef HAVE_PNG TEST(Imgcodecs_Png, write_big) { const string root = cvtest::TS::ptr()->get_data_path(); const string filename = root + "readwrite/read.png"; const string dst_file = cv::tempfile(".png"); Mat img; ASSERT_NO_THROW(img = imread(filename)); ASSERT_FALSE(img.empty()); EXPECT_EQ(13043, img.cols); EXPECT_EQ(13917, img.rows); ASSERT_NO_THROW(imwrite(dst_file, img)); EXPECT_EQ(0, remove(dst_file.c_str())); } TEST(Imgcodecs_Png, encode) { vector<uchar> buff; Mat img_gt = Mat::zeros(1000, 1000, CV_8U); vector<int> param; param.push_back(IMWRITE_PNG_COMPRESSION); param.push_back(3); //default(3) 0-9. EXPECT_NO_THROW(imencode(".png", img_gt, buff, param)); Mat img; EXPECT_NO_THROW(img = imdecode(buff, IMREAD_ANYDEPTH)); // hang EXPECT_FALSE(img.empty()); EXPECT_PRED_FORMAT2(cvtest::MatComparator(0, 0), img, img_gt); } TEST(Imgcodecs_Png, regression_ImreadVSCvtColor) { const string root = cvtest::TS::ptr()->get_data_path(); const string imgName = root + "../cv/shared/lena.png"; Mat original_image = imread(imgName); Mat gray_by_codec = imread(imgName, IMREAD_GRAYSCALE); Mat gray_by_cvt; cvtColor(original_image, gray_by_cvt, COLOR_BGR2GRAY); Mat diff; absdiff(gray_by_codec, gray_by_cvt, diff); EXPECT_LT(cvtest::mean(diff)[0], 1.); EXPECT_PRED_FORMAT2(cvtest::MatComparator(10, 0), gray_by_codec, gray_by_cvt); } // Test OpenCV issue 3075 is solved TEST(Imgcodecs_Png, read_color_palette_with_alpha) { const string root = cvtest::TS::ptr()->get_data_path(); Mat img; // First Test : Read PNG with alpha, imread flag -1 img = imread(root + "readwrite/color_palette_alpha.png", IMREAD_UNCHANGED); ASSERT_FALSE(img.empty()); ASSERT_TRUE(img.channels() == 4); // pixel is red in BGRA EXPECT_EQ(img.at<Vec4b>(0, 0), Vec4b(0, 0, 255, 255)); EXPECT_EQ(img.at<Vec4b>(0, 1), Vec4b(0, 0, 255, 255)); // Second Test : Read PNG without alpha, imread flag -1 img = imread(root + "readwrite/color_palette_no_alpha.png", IMREAD_UNCHANGED); ASSERT_FALSE(img.empty()); ASSERT_TRUE(img.channels() == 3); // pixel is red in BGR EXPECT_EQ(img.at<Vec3b>(0, 0), Vec3b(0, 0, 255)); EXPECT_EQ(img.at<Vec3b>(0, 1), Vec3b(0, 0, 255)); // Third Test : Read PNG with alpha, imread flag 1 img = imread(root + "readwrite/color_palette_alpha.png", IMREAD_COLOR); ASSERT_FALSE(img.empty()); ASSERT_TRUE(img.channels() == 3); // pixel is red in BGR EXPECT_EQ(img.at<Vec3b>(0, 0), Vec3b(0, 0, 255)); EXPECT_EQ(img.at<Vec3b>(0, 1), Vec3b(0, 0, 255)); // Fourth Test : Read PNG without alpha, imread flag 1 img = imread(root + "readwrite/color_palette_no_alpha.png", IMREAD_COLOR); ASSERT_FALSE(img.empty()); ASSERT_TRUE(img.channels() == 3); // pixel is red in BGR EXPECT_EQ(img.at<Vec3b>(0, 0), Vec3b(0, 0, 255)); EXPECT_EQ(img.at<Vec3b>(0, 1), Vec3b(0, 0, 255)); } /** * Test for check whether reading exif orientation tag was processed successfully or not * The test info is the set of 8 images named testExifRotate_{1 to 8}.png * The test image is the square 10x10 points divided by four sub-squares: * (R corresponds to Red, G to Green, B to Blue, W to white) * --------- --------- * | R | G | | G | R | * |-------| - (tag 1) |-------| - (tag 2) * | B | W | | W | B | * --------- --------- * * --------- --------- * | W | B | | B | W | * |-------| - (tag 3) |-------| - (tag 4) * | G | R | | R | G | * --------- --------- * * --------- --------- * | R | B | | G | W | * |-------| - (tag 5) |-------| - (tag 6) * | G | W | | R | B | * --------- --------- * * --------- --------- * | W | G | | B | R | * |-------| - (tag 7) |-------| - (tag 8) * | B | R | | W | G | * --------- --------- * * * Every image contains exif field with orientation tag (0x112) * After reading each image and applying the orientation tag, * the resulting image should be: * --------- * | R | G | * |-------| * | B | W | * --------- * */ typedef testing::TestWithParam<string> Imgcodecs_PNG_Exif; // Solution to issue 16579: PNG read doesn't support Exif orientation data #ifdef OPENCV_IMGCODECS_PNG_WITH_EXIF TEST_P(Imgcodecs_PNG_Exif, exif_orientation) #else TEST_P(Imgcodecs_PNG_Exif, DISABLED_exif_orientation) #endif { const string root = cvtest::TS::ptr()->get_data_path(); const string filename = root + GetParam(); const int colorThresholdHigh = 250; const int colorThresholdLow = 5; Mat m_img = imread(filename); ASSERT_FALSE(m_img.empty()); Vec3b vec; //Checking the first quadrant (with supposed red) vec = m_img.at<Vec3b>(2, 2); //some point inside the square EXPECT_LE(vec.val[0], colorThresholdLow); EXPECT_LE(vec.val[1], colorThresholdLow); EXPECT_GE(vec.val[2], colorThresholdHigh); //Checking the second quadrant (with supposed green) vec = m_img.at<Vec3b>(2, 7); //some point inside the square EXPECT_LE(vec.val[0], colorThresholdLow); EXPECT_GE(vec.val[1], colorThresholdHigh); EXPECT_LE(vec.val[2], colorThresholdLow); //Checking the third quadrant (with supposed blue) vec = m_img.at<Vec3b>(7, 2); //some point inside the square EXPECT_GE(vec.val[0], colorThresholdHigh); EXPECT_LE(vec.val[1], colorThresholdLow); EXPECT_LE(vec.val[2], colorThresholdLow); } const string exif_files[] = { "readwrite/testExifOrientation_1.png", "readwrite/testExifOrientation_2.png", "readwrite/testExifOrientation_3.png", "readwrite/testExifOrientation_4.png", "readwrite/testExifOrientation_5.png", "readwrite/testExifOrientation_6.png", "readwrite/testExifOrientation_7.png", "readwrite/testExifOrientation_8.png" }; INSTANTIATE_TEST_CASE_P(ExifFiles, Imgcodecs_PNG_Exif, testing::ValuesIn(exif_files)); #endif // HAVE_PNG }} // namespace
/* AUTHOR: julianferres */ #include <bits/stdc++.h> using namespace std; // neal Debugger template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; } template<typename T_container, typename T = typename enable_if<!is_same<T_container, string>::value, typename T_container::value_type>::type> ostream& operator<<(ostream &os, const T_container &v) { os << '{'; string sep; for (const T &x : v) os << sep << x, sep = ", "; return os << '}'; } void dbg_out() { cerr << endl; } template<typename Head, typename... Tail> void dbg_out(Head H, Tail... T) { cerr << ' ' << H; dbg_out(T...); } #ifdef LOCAL #define dbg(...) cerr << "(" << #__VA_ARGS__ << "):", dbg_out(__VA_ARGS__) #else #define dbg(...) #endif typedef long long ll; typedef vector<ll> vi; typedef pair<ll,ll> ii; typedef vector<ii> vii; typedef vector<bool> vb; #define FIN ios::sync_with_stdio(0);cin.tie(0);cout.tie(0) #define forr(i, a, b) for(int i = (a); i < (int) (b); i++) #define forn(i, n) forr(i, 0, n) #define DBG(x) cerr << #x << " = " << (x) << endl #define RAYA cerr << "===============================" << endl #define pb push_back #define mp make_pair #define all(c) (c).begin(),(c).end() #define esta(x,c) ((c).find(x) != (c).end()) const int INF = 1e9+15; // const ll INF = 2e18; const int MOD = 1e9+7; // 998244353 const int MAXN = 2e5+5; int main(){ FIN; return 0; }
// //Copyright (C) 2002-2005 3Dlabs Inc. Ltd. //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 3Dlabs Inc. Ltd. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS //"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT //LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS //FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE //COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, //BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; //LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER //CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT //LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN //ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE //POSSIBILITY OF SUCH DAMAGE. // #include "../osinclude.h" #define STRICT #define VC_EXTRALEAN 1 #include <windows.h> #include <cassert> #include <process.h> #include <psapi.h> #include <cstdio> #include <cstdint> // // This file contains the Window-OS-specific functions // #if !(defined(_WIN32) || defined(_WIN64)) #error Trying to build a windows specific file in a non windows build. #endif namespace glslang { inline OS_TLSIndex ToGenericTLSIndex (DWORD handle) { return (OS_TLSIndex)((uintptr_t)handle + 1); } inline DWORD ToNativeTLSIndex (OS_TLSIndex nIndex) { return (DWORD)((uintptr_t)nIndex - 1); } // // Thread Local Storage Operations // OS_TLSIndex OS_AllocTLSIndex() { DWORD dwIndex = TlsAlloc(); if (dwIndex == TLS_OUT_OF_INDEXES) { assert(0 && "OS_AllocTLSIndex(): Unable to allocate Thread Local Storage"); return OS_INVALID_TLS_INDEX; } return ToGenericTLSIndex(dwIndex); } bool OS_SetTLSValue(OS_TLSIndex nIndex, void *lpvValue) { if (nIndex == OS_INVALID_TLS_INDEX) { assert(0 && "OS_SetTLSValue(): Invalid TLS Index"); return false; } if (TlsSetValue(ToNativeTLSIndex(nIndex), lpvValue)) return true; else return false; } void* OS_GetTLSValue(OS_TLSIndex nIndex) { assert(nIndex != OS_INVALID_TLS_INDEX); return TlsGetValue(ToNativeTLSIndex(nIndex)); } bool OS_FreeTLSIndex(OS_TLSIndex nIndex) { if (nIndex == OS_INVALID_TLS_INDEX) { assert(0 && "OS_SetTLSValue(): Invalid TLS Index"); return false; } if (TlsFree(ToNativeTLSIndex(nIndex))) return true; else return false; } HANDLE GlobalLock; void InitGlobalLock() { GlobalLock = CreateMutex(0, false, 0); } void GetGlobalLock() { WaitForSingleObject(GlobalLock, INFINITE); } void ReleaseGlobalLock() { ReleaseMutex(GlobalLock); } unsigned int __stdcall EnterGenericThread (void* entry) { return ((TThreadEntrypoint)entry)(0); } void* OS_CreateThread(TThreadEntrypoint entry) { return (void*)_beginthreadex(0, 0, EnterGenericThread, (void*)entry, 0, 0); } void OS_WaitForAllThreads(void* threads, int numThreads) { WaitForMultipleObjects(numThreads, (HANDLE*)threads, true, INFINITE); } void OS_Sleep(int milliseconds) { Sleep(milliseconds); } //#define DUMP_COUNTERS void OS_DumpMemoryCounters() { #ifdef DUMP_COUNTERS PROCESS_MEMORY_COUNTERS counters; GetProcessMemoryInfo(GetCurrentProcess(), &counters, sizeof(counters)); printf("Working set size: %d\n", counters.WorkingSetSize); #else printf("Recompile with DUMP_COUNTERS defined to see counters.\n"); #endif } } // namespace glslang
// // Created by lalo on 15-04-18. // #include "Shader.h" static void checkShaderError(GLuint shader, GLuint flag, bool isProgram, const std::string &errorMessage); static std::string loadShader(const std::string &fileName); static GLuint createShader(const std::string &text, GLenum shaderType); Shader::Shader(const std::string &fileName) { this->program = glCreateProgram(); this->shaders[0] = createShader(loadShader(fileName + ".vs.glsl"), GL_VERTEX_SHADER); this->shaders[1] = createShader(loadShader(fileName + ".fs.glsl"), GL_FRAGMENT_SHADER); for (unsigned int i = 0; i < NUM_SHADERS; i++) { glAttachShader(this->program, this->shaders[i]); } glBindAttribLocation(this->program, 0, "position"); glBindAttribLocation(this->program, 1, "texCoord"); glBindAttribLocation(this->program, 2, "normal"); glLinkProgram(this->program); checkShaderError(this->program, GL_LINK_STATUS, true, "Error: Program linking failed: "); glValidateProgram(this->program); checkShaderError(this->program, GL_VALIDATE_STATUS, true, "Error: Program is invalid: "); this->uniforms[TRANSFORM_U] = glGetUniformLocation(this->program, "transform"); } Shader::~Shader() { for (unsigned int i = 0; i < NUM_SHADERS; i++) { glDetachShader(this->program, this->shaders[i]); glDeleteShader(this->shaders[i]); } glDeleteProgram(this->program); } void Shader::bind() { glUseProgram(this->program); } void Shader::update(const Transform &transform, const Camera &camera) { glm::mat4 model = camera.getViewProjection() * transform.getModel(); glUniformMatrix4fv(this->uniforms[TRANSFORM_U], 1, GL_FALSE, &model[0][0]); } static GLuint createShader(const std::string &text, GLenum shaderType) { GLuint shader = glCreateShader(shaderType); if(shader == 0) { std::cerr << "Error: Shader creation failed!" << std::endl; } const GLchar *shaderSourceStrings[1]; GLint shaderSourceStringLength[1]; shaderSourceStrings[0] = text.c_str(); shaderSourceStringLength[0] = text.length(); glShaderSource(shader, 1, shaderSourceStrings, shaderSourceStringLength); glCompileShader(shader); checkShaderError(shader, GL_COMPILE_STATUS, false, "Error: Shader compilation failed: "); return shader; } static std::string loadShader(const std::string &fileName) { std::ifstream file; file.open((fileName).c_str()); std::string output; std::string line; if (file.is_open()) { while (file.good()) { getline(file, line); output.append(line + "\n"); } } else { std::cerr << "Unable to load shader: " << fileName << std::endl; } return output; } static void checkShaderError(GLuint shader, GLuint flag, bool isProgram, const std::string &errorMessage) { GLint success = 0; GLchar error[1024] = {0}; if (isProgram) { glGetProgramiv(shader, flag, &success); } else { glGetShaderiv(shader, flag, &success); } if (success == GL_FALSE) { if (isProgram) { glGetProgramInfoLog(shader, sizeof(error), NULL, error); } else { glGetShaderInfoLog(shader, sizeof(error), NULL, error); } std::cerr << errorMessage << ": '" << error << "'" << std::endl; } }
// Copyright (c) 2020 INRA Distributed under the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef ORG_VLEPROJECT_IRRITATOR_2020 #define ORG_VLEPROJECT_IRRITATOR_2020 #include <algorithm> #include <limits> #ifdef __has_include #if __has_include(<numbers>) #include <numbers> #define irt_have_numbers 1 #else #define irt_have_numbers 0 #endif #endif #include <string_view> #include <type_traits> #include <cmath> #include <cstdint> #include <cstring> /***************************************************************************** * * Helper macros * ****************************************************************************/ #ifndef irt_assert #include <cassert> #define irt_assert(_expr) assert(_expr) #endif namespace irt { static inline bool is_fatal_breakpoint = true; } #ifndef NDEBUG #if (defined(__i386__) || defined(__x86_64__)) && defined(__GNUC__) && \ __GNUC__ >= 2 #define irt_breakpoint() \ do { \ if (::irt::is_fatal_breakpoint) \ __asm__ __volatile__("int $03"); \ } while (0) #elif (defined(_MSC_VER) || defined(__DMC__)) && defined(_M_IX86) #define irt_breakpoint() \ do { \ if (::irt::is_fatal_breakpoint) \ __asm int 3h \ } while (0) #elif defined(_MSC_VER) #define irt_breakpoint() \ do { \ if (::irt::is_fatal_breakpoint) \ __debugbreak(); \ } while (0) #elif defined(__alpha__) && !defined(__osf__) && defined(__GNUC__) && \ __GNUC__ >= 2 #define irt_breakpoint() \ do { \ if (::irt::is_fatal_breakpoint) \ __asm__ __volatile__("bpt"); \ } while (0) #elif defined(__APPLE__) #define irt_breakpoint() \ do { \ if (::irt::is_fatal_breakpoint) \ __builtin_trap(); \ } while (0) #else /* !__i386__ && !__alpha__ */ #define irt_breakpoint() \ do { \ if (::irt::is_fatal_breakpoint) \ raise(SIGTRAP); \ } while (0) #endif /* __i386__ */ #else #define irt_breakpoint() \ do { \ } while (0) #endif #define irt_bad_return(status__) \ do { \ irt_breakpoint(); \ return status__; \ } while (0) #define irt_return_if_bad(expr__) \ do { \ auto status__ = (expr__); \ if (status__ != status::success) { \ irt_breakpoint(); \ return status__; \ } \ } while (0) #define irt_return_if_fail(expr__, status__) \ do { \ if (!(expr__)) { \ irt_breakpoint(); \ return status__; \ } \ } while (0) #if defined(__GNUC__) #define irt_unreachable() __builtin_unreachable(); #elif defined(_MSC_VER) #define irt_unreachable() __assume(0) #else #define irt_unreachable() #endif namespace irt { using i8 = int8_t; using i16 = int16_t; using i32 = int32_t; using i64 = int64_t; using u8 = uint8_t; using u16 = uint16_t; using u32 = uint32_t; using u64 = uint64_t; using sz = size_t; inline u16 make_halfword(u8 a, u8 b) noexcept { return static_cast<u16>((a << 8) | b); } inline void unpack_halfword(u16 halfword, u8* a, u8* b) noexcept { *a = static_cast<u8>((halfword >> 8) & 0xff); *b = static_cast<u8>(halfword & 0xff); } inline u32 make_word(u16 a, u16 b) noexcept { return (static_cast<u32>(a) << 16) | static_cast<u32>(b); } inline void unpack_word(u32 word, u16* a, u16* b) noexcept { *a = static_cast<u16>((word >> 16) & 0xffff); *b = static_cast<u16>(word & 0xffff); } inline u64 make_doubleword(u32 a, u32 b) noexcept { return (static_cast<u64>(a) << 32) | static_cast<u64>(b); } inline void unpack_doubleword(u64 doubleword, u32* a, u32* b) noexcept { *a = static_cast<u32>((doubleword >> 32) & 0xffffffff); *b = static_cast<u32>(doubleword & 0xffffffff); } template<typename Integer> constexpr typename std::make_unsigned<Integer>::type to_unsigned(Integer value) { irt_assert(value >= 0); return static_cast<typename std::make_unsigned<Integer>::type>(value); } template<class C> constexpr int length(const C& c) noexcept { return static_cast<int>(c.size()); } template<class T, size_t N> constexpr int length(const T (&array)[N]) noexcept { (void)array; return static_cast<int>(N); } template<typename Identifier> constexpr Identifier undefined() noexcept { static_assert( std::is_enum<Identifier>::value, "Identifier must be a enumeration: enum class id : unsigned {};"); return static_cast<Identifier>(0); } template<typename Identifier> constexpr bool is_undefined(Identifier id) noexcept { static_assert( std::is_enum<Identifier>::value, "Identifier must be a enumeration: enum class id : unsigned {};"); return id == undefined<Identifier>(); } template<typename Identifier> constexpr bool is_defined(Identifier id) noexcept { static_assert( std::is_enum<Identifier>::value, "Identifier must be a enumeration: enum class id : unsigned {};"); return id != undefined<Identifier>(); } /** * @brief Enummeration to integral */ template<class Enum, class Integer = typename std::underlying_type<Enum>::type> constexpr Integer ordinal(Enum e) noexcept { static_assert(std::is_enum<Enum>::value, "Identifier must be a enumeration"); return static_cast<Integer>(e); } /** * @brief Integral to enumeration */ template<class Enum, class Integer = typename std::underlying_type<Enum>::type> constexpr Enum enum_cast(Integer i) noexcept { static_assert(std::is_enum<Enum>::value, "Identifier must be a enumeration"); return static_cast<Enum>(i); } /** * @brief returns an iterator to the result or end if not found * * Binary search function which returns an iterator to the result or end if * not found using the lower_bound standard function. */ template<typename Iterator, typename T> Iterator binary_find(Iterator begin, Iterator end, const T& value) { Iterator i = std::lower_bound(begin, end, value); if (i != end && !(value < *i)) return i; else return end; } /** * @brief returns an iterator to the result or end if not found * * Binary search function which returns an iterator to the result or end if * not found using the lower_bound standard function. */ template<typename Iterator, typename T, typename Compare> Iterator binary_find(Iterator begin, Iterator end, const T& value, Compare comp) { Iterator i = std::lower_bound(begin, end, value, comp); if (i != end && !comp(*i, value)) return i; else return end; } /***************************************************************************** * * Return status of many function * ****************************************************************************/ enum class status { success, unknown_dynamics, block_allocator_bad_capacity, block_allocator_not_enough_memory, head_allocator_bad_capacity, head_allocator_not_enough_memory, simulation_not_enough_model, simulation_not_enough_memory_message_list_allocator, simulation_not_enough_memory_input_port_list_allocator, simulation_not_enough_memory_output_port_list_allocator, data_array_init_capacity_error, data_array_not_enough_memory, data_array_archive_init_capacity_error, data_array_archive_not_enough_memory, array_init_capacity_zero, array_init_capacity_too_big, array_init_not_enough_memory, vector_init_capacity_zero, vector_init_capacity_too_big, vector_init_not_enough_memory, source_unknown, source_empty, dynamics_unknown_id, dynamics_unknown_port_id, dynamics_not_enough_memory, model_connect_output_port_unknown, model_connect_input_port_unknown, model_connect_already_exist, model_connect_bad_dynamics, model_queue_bad_ta, model_queue_empty_allocator, model_queue_full, model_dynamic_queue_source_is_null, model_dynamic_queue_empty_allocator, model_dynamic_queue_full, model_priority_queue_source_is_null, model_priority_queue_empty_allocator, model_priority_queue_full, model_integrator_dq_error, model_integrator_X_error, model_integrator_internal_error, model_integrator_output_error, model_integrator_running_without_x_dot, model_integrator_ta_with_bad_x_dot, model_generator_null_ta_source, model_generator_empty_ta_source, model_generator_null_value_source, model_generator_empty_value_source, model_quantifier_bad_quantum_parameter, model_quantifier_bad_archive_length_parameter, model_quantifier_shifting_value_neg, model_quantifier_shifting_value_less_1, model_time_func_bad_init_message, model_flow_bad_samplerate, model_flow_bad_data, gui_not_enough_memory, io_not_enough_memory, io_file_format_error, io_file_format_source_number_error, io_file_source_full, io_file_format_model_error, io_file_format_model_number_error, io_file_format_model_unknown, io_file_format_dynamics_unknown, io_file_format_dynamics_limit_reach, io_file_format_dynamics_init_error }; constexpr i8 status_last() noexcept { return static_cast<i8>(status::io_file_format_dynamics_init_error); } constexpr sz status_size() noexcept { return static_cast<sz>(status_last() + static_cast<i8>(1)); } constexpr bool is_success(status s) noexcept { return s == status::success; } constexpr bool is_bad(status s) noexcept { return s != status::success; } template<typename... Args> constexpr bool is_status_equal(status s, Args... args) noexcept { return ((s == args) || ... || false); } inline status check_return(status s) noexcept { if (s != status::success) irt_breakpoint(); return s; } template<typename T, typename... Args> constexpr bool match(const T& s, Args... args) noexcept { return ((s == args) || ... || false); } template<class T, class... Rest> constexpr bool are_all_same() noexcept { return (std::is_same_v<T, Rest> && ...); } template<class T> typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type almost_equal(T x, T y, int ulp) { return std::fabs(x - y) <= std::numeric_limits<T>::epsilon() * std::fabs(x + y) * ulp || std::fabs(x - y) < std::numeric_limits<T>::min(); } /***************************************************************************** * * Definition of a lightweight std::function * ****************************************************************************/ template<class F> class function_ref; template<class R, class... Args> class function_ref<R(Args...)> { public: constexpr function_ref() noexcept = default; /// Creates a `function_ref` which refers to the same callable as `rhs`. constexpr function_ref(const function_ref<R(Args...)>& rhs) noexcept = default; /// Constructs a `function_ref` referring to `f`. /// /// \synopsis template <typename F> constexpr function_ref(F &&f) noexcept template< typename F, std::enable_if_t<!std::is_same<std::decay_t<F>, function_ref>::value && std::is_invocable_r<R, F&&, Args...>::value>* = nullptr> constexpr function_ref(F&& f) noexcept : obj(const_cast<void*>(reinterpret_cast<const void*>(std::addressof(f)))) { cb = [](void* obj, Args... args) -> R { return std::invoke( *reinterpret_cast<typename std::add_pointer<F>::type>(obj), std::forward<Args>(args)...); }; } /// Makes `*this` refer to the same callable as `rhs`. constexpr function_ref<R(Args...)>& operator=( const function_ref<R(Args...)>& rhs) noexcept = default; /// Makes `*this` refer to `f`. /// /// \synopsis template <typename F> constexpr function_ref &operator=(F &&f) /// noexcept; template< typename F, std::enable_if_t<std::is_invocable_r<R, F&&, Args...>::value>* = nullptr> constexpr function_ref<R(Args...)>& operator=(F&& f) noexcept { obj = reinterpret_cast<void*>(std::addressof(f)); cb = [](void* obj, Args... args) { return std::invoke( *reinterpret_cast<typename std::add_pointer<F>::type>(obj), std::forward<Args>(args)...); }; return *this; } constexpr void swap(function_ref<R(Args...)>& rhs) noexcept { std::swap(obj, rhs.obj); std::swap(cb, rhs.cb); } R operator()(Args... args) const { return cb(obj, std::forward<Args>(args)...); } constexpr bool empty() const noexcept { return obj == nullptr; } constexpr void reset() noexcept { obj = nullptr; cb = nullptr; } private: void* obj = nullptr; R (*cb)(void*, Args...) = nullptr; }; /// Swaps the referred callables of `lhs` and `rhs`. template<typename R, typename... Args> constexpr void swap(function_ref<R(Args...)>& lhs, function_ref<R(Args...)>& rhs) noexcept { lhs.swap(rhs); } template<typename R, typename... Args> function_ref(R (*)(Args...)) -> function_ref<R(Args...)>; template<typename R, typename... Args> function_ref(R (*)(Args...) noexcept) -> function_ref<R(Args...) noexcept>; /***************************************************************************** * * Allocator * ****************************************************************************/ using global_alloc_function_type = function_ref<void*(sz size)>; using global_free_function_type = function_ref<void(void* ptr)>; static inline void* malloc_wrapper(sz size) { return std::malloc(size); } static inline void free_wrapper(void* ptr) { if (ptr) std::free(ptr); } static inline global_alloc_function_type g_alloc_fn{ malloc_wrapper }; static inline global_free_function_type g_free_fn{ free_wrapper }; /***************************************************************************** * * Definition of Time * * TODO: * - enable template definition of float or [float|double,bool absolute] * representation of time? * ****************************************************************************/ using time = double; template<typename T> struct time_domain {}; template<> struct time_domain<time> { using time_type = time; static constexpr const double infinity = std::numeric_limits<double>::infinity(); static constexpr const double negative_infinity = -std::numeric_limits<double>::infinity(); static constexpr const double zero = 0; static constexpr bool is_infinity(time t) noexcept { return t == infinity || t == negative_infinity; } static constexpr bool is_zero(time t) noexcept { return t == zero; } }; /***************************************************************************** * * Small string * ****************************************************************************/ template<size_t length = 8> class small_string { char buffer_[length]; u8 size_; public: using iterator = char*; using const_iterator = const char*; using size_type = u8; static_assert(length > size_t{ 1 } && length < size_t{ 254 }); constexpr small_string() noexcept { clear(); } constexpr small_string(const small_string& str) noexcept { std::copy_n(str.buffer_, str.size_, buffer_); buffer_[str.size_] = '\0'; size_ = str.size_; } constexpr small_string(small_string&& str) noexcept { std::copy_n(str.buffer_, str.size_, buffer_); buffer_[str.size_] = '\0'; size_ = str.size_; str.clear(); } constexpr small_string& operator=(const small_string& str) noexcept { if (&str != this) { std::copy_n(str.buffer_, str.size_, buffer_); buffer_[str.size_] = '\0'; size_ = str.size_; } return *this; } constexpr small_string& operator=(small_string&& str) noexcept { if (&str != this) { std::copy_n(str.buffer_, str.size_, buffer_); buffer_[str.size_] = '\0'; size_ = str.size_; } return *this; } constexpr small_string(const char* str) noexcept { std::strncpy(buffer_, str, length - 1); buffer_[length - 1] = '\0'; size_ = static_cast<u8>(std::strlen(buffer_)); } constexpr small_string(const std::string_view str) noexcept { assign(str); } constexpr bool empty() const noexcept { constexpr unsigned char zero{ 0 }; return zero == size_; } constexpr void size(std::size_t sz) noexcept { size_ = static_cast<u8>(std::min(sz, length - 1)); buffer_[size_] = '\0'; } constexpr std::size_t size() const noexcept { return size_; } constexpr std::size_t capacity() const noexcept { return length; } constexpr void assign(const std::string_view str) noexcept { const size_t copy_length = std::min(str.size(), length - 1); std::memcpy(buffer_, str.data(), copy_length); buffer_[copy_length] = '\0'; size_ = static_cast<u8>(copy_length); } constexpr std::string_view sv() const noexcept { return { buffer_, size_ }; } constexpr void clear() noexcept { std::fill_n(buffer_, length, '\0'); size_ = 0; } constexpr const char* c_str() const noexcept { return buffer_; } constexpr iterator begin() noexcept { return buffer_; } constexpr iterator end() noexcept { return buffer_ + size_; } constexpr const_iterator begin() const noexcept { return buffer_; } constexpr const_iterator end() const noexcept { return buffer_ + size_; } constexpr bool operator==(const small_string& rhs) const noexcept { return std::strncmp(buffer_, rhs.buffer_, length) == 0; } constexpr bool operator!=(const small_string& rhs) const noexcept { return std::strncmp(buffer_, rhs.buffer_, length) != 0; } constexpr bool operator>(const small_string& rhs) const noexcept { return std::strncmp(buffer_, rhs.buffer_, length) > 0; } constexpr bool operator<(const small_string& rhs) const noexcept { return std::strncmp(buffer_, rhs.buffer_, length) < 0; } constexpr bool operator==(const char* rhs) const noexcept { return std::strncmp(buffer_, rhs, length) == 0; } constexpr bool operator!=(const char* rhs) const noexcept { return std::strncmp(buffer_, rhs, length) != 0; } constexpr bool operator>(const char* rhs) const noexcept { return std::strncmp(buffer_, rhs, length) > 0; } constexpr bool operator<(const char* rhs) const noexcept { return std::strncmp(buffer_, rhs, length) < 0; } }; /***************************************************************************** * * value * ****************************************************************************/ struct message { using size_type = std::size_t; using difference_type = std::ptrdiff_t; double real[4]; constexpr size_type size() const noexcept { return real[3] ? 4u : real[2] ? 3u : real[1] ? 2u : real[0] ? 1u : 0u; } constexpr difference_type ssize() const noexcept { return real[3] ? 4 : real[2] ? 3 : real[1] ? 2 : real[0] ? 1 : 0; } constexpr message() noexcept : real{ 0., 0., 0., 0. } {} template<typename... Args> constexpr message(Args&&... args) : real{ std::forward<Args>(args)... } { auto size = sizeof...(args); for (; size != std::size(real); ++size) real[size] = 0.; } constexpr double operator[](const difference_type i) const noexcept { return real[i]; } constexpr double& operator[](const difference_type i) noexcept { return real[i]; } constexpr void reset() noexcept { std::fill_n(std::data(real), std::size(real), 0.); } }; struct dated_message { using size_type = std::size_t; using difference_type = std::ptrdiff_t; double real[5]; constexpr dated_message() noexcept : real{ 0., 0., 0., 0., 0. } {} template<typename... Args> constexpr dated_message(Args&&... args) : real{ std::forward<Args>(args)... } { auto size = sizeof...(args); for (; size != std::size(real); ++size) real[size] = 0.; } constexpr double operator[](const difference_type i) const noexcept { return real[i]; } constexpr double& operator[](const difference_type i) noexcept { return real[i]; } constexpr void reset() noexcept { std::fill_n(std::data(real), std::size(real), 0.); } inline bool operator<(const dated_message& rhs) const noexcept { return real[0] < rhs.real[0]; } inline bool operator==(const dated_message& rhs) const noexcept { return real[0] == rhs.real[0]; } }; /***************************************************************************** * * Flat list * ****************************************************************************/ template<typename T> class block_allocator { public: using value_type = T; union block { block* next; typename std::aligned_storage<sizeof(T), alignof(T)>::type storage; }; private: block* blocks{ nullptr }; // contains all preallocated blocks block* free_head{ nullptr }; // a free list sz size{ 0 }; // number of active elements allocated sz max_size{ 0 }; // number of elements allocated (with free_head) sz capacity{ 0 }; // capacity of the allocator public: block_allocator() = default; block_allocator(const block_allocator&) = delete; block_allocator& operator=(const block_allocator&) = delete; ~block_allocator() noexcept { if (blocks) g_free_fn(blocks); } status init(std::size_t new_capacity) noexcept { if (new_capacity == 0) return status::block_allocator_bad_capacity; if (new_capacity != capacity) { if (blocks) g_free_fn(blocks); blocks = static_cast<block*>(g_alloc_fn(new_capacity * sizeof(block))); if (blocks == nullptr) return status::block_allocator_not_enough_memory; } size = 0; max_size = 0; capacity = new_capacity; free_head = nullptr; return status::success; } void reset() noexcept { if (capacity > 0) { size = 0; max_size = 0; free_head = nullptr; } } T* alloc() noexcept { block* new_block = nullptr; if (free_head != nullptr) { new_block = free_head; free_head = free_head->next; } else { irt_assert(max_size < capacity); new_block = reinterpret_cast<block*>(&blocks[max_size++]); } ++size; return reinterpret_cast<T*>(new_block); } bool can_alloc() noexcept { return free_head != nullptr || max_size < capacity; } void free(T* n) noexcept { irt_assert(n); block* ptr = reinterpret_cast<block*>(n); ptr->next = free_head; free_head = ptr; --size; if (size == 0) { // A special part: if it no longer exists max_size = 0; // we reset the free list and the number free_head = nullptr; // of elements allocated. } } bool can_alloc(size_t number) const noexcept { return number + size < capacity; } }; template<typename T> class shared_flat_list { public: struct node_type { T value; node_type* next = nullptr; }; public: using allocator_type = block_allocator<node_type>; using value_type = T; using reference = T&; using const_reference = const T&; using pointer = T*; class iterator { private: node_type* node{ nullptr }; public: using iterator_category = std::forward_iterator_tag; using value_type = T; using pointer = T*; using reference = T&; using difference_type = std::ptrdiff_t; iterator() noexcept = default; iterator(node_type* n) noexcept : node(n) {} iterator(const iterator& other) noexcept : node(other.node) {} iterator& operator=(const iterator& other) noexcept { node = other.node; return *this; } T& operator*() noexcept { return node->value; } T* operator->() noexcept { return &node->value; } iterator operator++() noexcept { if (node != nullptr) node = node->next; return *this; } iterator operator++(int) noexcept { iterator tmp(*this); if (node != nullptr) node = node->next; return tmp; } bool operator==(const iterator& other) const noexcept { return node == other.node; } bool operator!=(const iterator& other) const noexcept { return node != other.node; } void swap(iterator& other) noexcept { std::swap(node, other.node); } friend class shared_flat_list<T>; }; class const_iterator { private: const node_type* node{ nullptr }; public: using iterator_category = std::forward_iterator_tag; using value_type = T; using pointer = T*; using reference = T&; using difference_type = std::ptrdiff_t; const_iterator() noexcept = default; const_iterator(node_type* n) noexcept : node(n) {} const_iterator(const const_iterator& other) noexcept : node(other.node) {} const_iterator& operator=(const const_iterator& other) noexcept { node = other.node; return *this; } const T& operator*() noexcept { return node->value; } const T* operator->() noexcept { return &node->value; } const_iterator operator++() noexcept { if (node != nullptr) node = node->next; return *this; } const_iterator operator++(int) noexcept { const_iterator tmp(*this); if (node != nullptr) node = node->next; return tmp; } bool operator==(const const_iterator& other) const noexcept { return node == other.node; } bool operator!=(const const_iterator& other) const noexcept { return node != other.node; } void swap(const_iterator& other) noexcept { std::swap(node, other.node); } friend class shared_flat_list<T>; }; private: node_type* node{ nullptr }; public: shared_flat_list() = default; shared_flat_list(const shared_flat_list& other) = delete; shared_flat_list& operator=(const shared_flat_list& other) = delete; shared_flat_list(shared_flat_list&& other) = delete; shared_flat_list& operator=(shared_flat_list&& other) = delete; ~shared_flat_list() noexcept = default; void clear(allocator_type& allocator) noexcept { node_type* prev = node; while (node != nullptr) { node = node->next; allocator.free(prev); prev = node; } } bool empty() const noexcept { return node == nullptr; } iterator begin() noexcept { return iterator(node); } iterator end() noexcept { return iterator(nullptr); } const_iterator begin() const noexcept { return const_iterator(node); } const_iterator end() const noexcept { return const_iterator(nullptr); } reference front() noexcept { irt_assert(!empty()); return node->value; } const_reference front() const noexcept { irt_assert(!empty()); return node->value; } template<typename... Args> iterator emplace_front(allocator_type& allocator, Args&&... args) noexcept { node_type* new_node = allocator.alloc(); new (&new_node->value) T(std::forward<Args>(args)...); new_node->next = node; node = new_node; return begin(); } template<typename... Args> iterator emplace_after(allocator_type& allocator, iterator it, Args&&... args) noexcept { node_type* new_node = allocator.alloc(); new (&new_node->value) T(std::forward<Args>(args)...); if (it->node == nullptr) return emplace_front(std::forward<Args>(args)...); new_node->next = it->node->next; it->node->next = new_node; return iterator(new_node); } template<typename... Args> iterator try_emplace_front(allocator_type& allocator, Args&&... args) noexcept { auto [success, new_node] = allocator.try_alloc(); if (!success) return end(); new (&new_node->value) T(std::forward<Args>(args)...); new_node->next = node; node = new_node; return begin(); } template<typename... Args> iterator try_emplace_after(allocator_type& allocator, iterator it, Args&&... args) noexcept { auto [success, new_node] = allocator.try_alloc(); if (!success) return end(); new (&new_node->value) T(std::forward<Args>(args)...); if (it->node == nullptr) return emplace_front(std::forward<Args>(args)...); new_node->next = it->node->next; it->node->next = new_node; return iterator(new_node); } void pop_front(allocator_type& allocator) noexcept { if (node == nullptr) return; node_type* to_delete = node; node = node->next; if constexpr (!std::is_trivial_v<T>) to_delete->value.~T(); allocator.free(to_delete); } iterator erase_after(allocator_type& allocator, iterator it) noexcept { if (it.node == nullptr) return end(); node_type* to_delete = it.node->next; if (to_delete == nullptr) return end(); node_type* next = to_delete->next; it.node->next = next; if constexpr (!std::is_trivial_v<T>) to_delete->value.~T(); allocator.free(to_delete); return iterator(next); } }; template<typename T> class flat_list { public: struct node_type { T value; node_type* next = nullptr; }; public: using allocator_type = block_allocator<node_type>; using value_type = T; using reference = T&; using const_reference = const T&; using pointer = T*; class iterator { private: node_type* node{ nullptr }; public: using iterator_category = std::forward_iterator_tag; using value_type = T; using pointer = T*; using reference = T&; using difference_type = std::ptrdiff_t; iterator() noexcept = default; iterator(node_type* n) noexcept : node(n) {} iterator(const iterator& other) noexcept : node(other.node) {} iterator& operator=(const iterator& other) noexcept { node = other.node; return *this; } T& operator*() noexcept { return node->value; } T* operator->() noexcept { return &node->value; } iterator operator++() noexcept { if (node != nullptr) node = node->next; return *this; } iterator operator++(int) noexcept { iterator tmp(*this); if (node != nullptr) node = node->next; return tmp; } bool operator==(const iterator& other) const noexcept { return node == other.node; } bool operator!=(const iterator& other) const noexcept { return node != other.node; } void swap(iterator& other) noexcept { std::swap(node, other.node); } friend class flat_list<T>; }; class const_iterator { private: const node_type* node{ nullptr }; public: using iterator_category = std::forward_iterator_tag; using value_type = T; using pointer = T*; using reference = T&; using difference_type = std::ptrdiff_t; const_iterator() noexcept = default; const_iterator(node_type* n) noexcept : node(n) {} const_iterator(const const_iterator& other) noexcept : node(other.node) {} const_iterator& operator=(const const_iterator& other) noexcept { node = other.node; return *this; } const T& operator*() noexcept { return node->value; } const T* operator->() noexcept { return &node->value; } const_iterator operator++() noexcept { if (node != nullptr) node = node->next; return *this; } const_iterator operator++(int) noexcept { const_iterator tmp(*this); if (node != nullptr) node = node->next; return tmp; } bool operator==(const const_iterator& other) const noexcept { return node == other.node; } bool operator!=(const const_iterator& other) const noexcept { return node != other.node; } void swap(const_iterator& other) noexcept { std::swap(node, other.node); } friend class flat_list<T>; }; private: allocator_type* allocator{ nullptr }; node_type* node{ nullptr }; public: flat_list() = default; flat_list(allocator_type* allocator_new) noexcept : allocator(allocator_new) {} flat_list(const flat_list& other) = delete; flat_list& operator=(const flat_list& other) = delete; flat_list(flat_list&& other) noexcept : allocator(other.allocator) , node(other.node) { other.allocator = nullptr; other.node = nullptr; } void set_allocator(allocator_type* allocator_new) noexcept { clear(); allocator = allocator_new; node = nullptr; } flat_list& operator=(flat_list&& other) noexcept { if (this != &other) { clear(); allocator = other.allocator; other.allocator = nullptr; node = other.node; other.node = nullptr; } return *this; } ~flat_list() noexcept { clear(); } void clear() noexcept { node_type* prev = node; while (node != nullptr) { node = node->next; allocator->free(prev); prev = node; } } bool empty() const noexcept { return node == nullptr; } iterator begin() noexcept { return iterator(node); } iterator end() noexcept { return iterator(nullptr); } const_iterator begin() const noexcept { return const_iterator(node); } const_iterator end() const noexcept { return const_iterator(nullptr); } reference front() noexcept { irt_assert(!empty()); return node->value; } const_reference front() const noexcept { irt_assert(!empty()); return node->value; } template<typename... Args> iterator emplace_front(Args&&... args) noexcept { node_type* new_node = allocator->alloc(); new (&new_node->value) T(std::forward<Args>(args)...); new_node->next = node; node = new_node; return begin(); } template<typename... Args> iterator emplace_after(iterator it, Args&&... args) noexcept { node_type* new_node = allocator->alloc(); new (&new_node->value) T(std::forward<Args>(args)...); if (it->node == nullptr) return emplace_front(std::forward<Args>(args)...); new_node->next = it->node->next; it->node->next = new_node; return iterator(new_node); } template<typename... Args> iterator try_emplace_front(Args&&... args) noexcept { auto [success, new_node] = allocator->try_alloc(); if (!success) return end(); new (&new_node->value) T(std::forward<Args>(args)...); new_node->next = node; node = new_node; return begin(); } template<typename... Args> iterator try_emplace_after(iterator it, Args&&... args) noexcept { auto [success, new_node] = allocator->try_alloc(); if (!success) return end(); new (&new_node->value) T(std::forward<Args>(args)...); if (it->node == nullptr) return emplace_front(std::forward<Args>(args)...); new_node->next = it->node->next; it->node->next = new_node; return iterator(new_node); } void pop_front() noexcept { if (node == nullptr) return; node_type* to_delete = node; node = node->next; if constexpr (!std::is_trivial_v<T>) to_delete->value.~T(); allocator->free(to_delete); } iterator erase_after(iterator it) noexcept { irt_assert(allocator); if (it.node == nullptr) return end(); node_type* to_delete = it.node->next; if (to_delete == nullptr) return end(); node_type* next = to_delete->next; it.node->next = next; if constexpr (!std::is_trivial_v<T>) to_delete->value.~T(); allocator->free(to_delete); return iterator(next); } }; template<typename T> class flat_double_list { private: struct node_type { T value; node_type* next = nullptr; node_type* prev = nullptr; }; public: using allocator_type = block_allocator<node_type>; using value_type = T; using reference = T&; using pointer = T*; class iterator { private: flat_double_list* list{ nullptr }; node_type* node{ nullptr }; public: using iterator_category = std::bidirectional_iterator_tag; using value_type = T; using pointer = T*; using reference = T&; iterator() noexcept = default; iterator(flat_double_list* lst, node_type* n) noexcept : list(lst) , node(n) {} iterator(const iterator& other) noexcept : list(other.list) , node(other.node) {} iterator& operator=(const iterator& other) noexcept { list = other.list; node = other.node; return *this; } T& operator*() noexcept { return node->value; } T* operator*() const noexcept { return node->value; } pointer operator->() noexcept { return &(node->value); } pointer operator->() const noexcept { return &node->value; } iterator operator++() noexcept { node = (node == nullptr) ? list->m_front : node->next; return *this; } iterator operator++(int) noexcept { iterator tmp(*this); node = (node == nullptr) ? list->m_front : node->next; return tmp; } iterator operator--() noexcept { node = (node == nullptr) ? list->m_back : node->prev; return *this; } iterator operator--(int) noexcept { iterator tmp(*this); node = (node == nullptr) ? list->m_back : node->prev; return tmp; } bool operator==(const iterator& other) const noexcept { return node == other.node; } bool operator!=(const iterator& other) const noexcept { return node != other.node; } void swap(iterator& other) noexcept { std::swap(list, other.list); std::swap(node, other.node); } friend class flat_double_list<T>; }; class const_iterator { private: const flat_double_list* list{ nullptr }; node_type* node{ nullptr }; public: using const_iterator_category = std::bidirectional_iterator_tag; using value_type = T; using pointer = T*; using reference = T&; const_iterator() noexcept = default; const_iterator(const flat_double_list* lst, node_type* n) noexcept : list(lst) , node(n) {} const_iterator(const const_iterator& other) noexcept : list(other.list) , node(other.node) {} const_iterator& operator=(const const_iterator& other) noexcept { list = other.list; node = other.node; return *this; } const T& operator*() noexcept { return node->value; } const T* operator->() noexcept { return &(node->value); } const_iterator operator++() noexcept { node = (node == nullptr) ? list->m_front : node->next; return *this; } const_iterator operator++(int) noexcept { const_iterator tmp(*this); node = (node == nullptr) ? list->m_front : node->next; return tmp; } const_iterator operator--() noexcept { node = (node == nullptr) ? list->m_back : node->prev; return *this; } const_iterator operator--(int) noexcept { const_iterator tmp(*this); node = (node == nullptr) ? list->m_back : node->prev; return tmp; } bool operator==(const const_iterator& other) const noexcept { return node == other.node; } bool operator!=(const const_iterator& other) const noexcept { return node != other.node; } void swap(const_iterator& other) noexcept { std::swap(list, other.list); std::swap(node, other.node); } friend class flat_double_list<T>; }; private: allocator_type* m_allocator{ nullptr }; node_type* m_front{ nullptr }; node_type* m_back{ nullptr }; i64 m_size{ 0 }; public: flat_double_list() = default; flat_double_list(allocator_type* allocator) : m_allocator(allocator) {} flat_double_list(const flat_double_list& other) = delete; flat_double_list& operator=(const flat_double_list& other) = delete; flat_double_list(flat_double_list&& other) noexcept : m_allocator(other.m_allocator) , m_front(other.m_front) , m_back(other.m_back) , m_size(other.m_size) { other.m_allocator = nullptr; other.m_front = nullptr; other.m_back = nullptr; other.m_size = 0; } void set_allocator(allocator_type* allocator) noexcept { clear(); m_allocator = allocator; m_front = nullptr; m_back = nullptr; m_size = 0; } allocator_type* get_allocator() const noexcept { return m_allocator; } flat_double_list& operator=(flat_double_list&& other) noexcept { if (this != &other) { clear(); m_allocator = other.m_allocator; other.m_allocator = nullptr; m_front = other.m_front; other.m_front = nullptr; m_back = other.m_back; other.m_back = nullptr; m_size = other.m_size; other.m_size = 0; } return *this; } ~flat_double_list() noexcept { clear(); } void clear() noexcept { node_type* prev = m_front; while (m_front != nullptr) { m_front = m_front->next; m_allocator->free(prev); prev = m_front; } m_size = 0; m_back = nullptr; } iterator begin() noexcept { return iterator(this, m_front); } iterator end() noexcept { return iterator(this, nullptr); } const_iterator begin() const noexcept { return const_iterator(this, m_front); } const_iterator end() const noexcept { return const_iterator(this, nullptr); } reference front() noexcept { return m_front->value; } reference back() noexcept { return m_back->value; } reference front() const noexcept { return m_front->value; } reference back() const noexcept { return m_back->value; } /** * @brief Inserts a new element into the container directly before pos. * @tparam ...Args * @param pos * @param ...args * @return */ template<typename... Args> iterator emplace(iterator pos, Args&&... args) noexcept { if (!pos.node) return emplace_back(std::forward<Args>(args)...); if (!pos.node->prev) return emplace_front(std::forward<Args>(args)...); node_type* new_node = m_allocator->alloc(); new (&new_node->value) T(std::forward<Args>(args)...); ++m_size; new_node->prev = pos.node->prev; new_node->next = pos.node; pos.node->prev->next = new_node; pos.node->prev = new_node; return iterator(this, new_node); } template<typename... Args> iterator emplace_front(Args&&... args) noexcept { node_type* new_node = m_allocator->alloc(); new (&new_node->value) T(std::forward<Args>(args)...); ++m_size; if (m_front) { new_node->prev = nullptr; new_node->next = m_front; m_front->prev = new_node; m_front = new_node; } else { new_node->prev = nullptr; new_node->next = nullptr; m_front = new_node; m_back = new_node; } return begin(); } template<typename... Args> iterator emplace_back(Args&&... args) noexcept { node_type* new_node = m_allocator->alloc(); new (&new_node->value) T(std::forward<Args>(args)...); ++m_size; if (m_back) { new_node->prev = m_back; new_node->next = nullptr; m_back->next = new_node; m_back = new_node; } else { new_node->prev = nullptr; new_node->next = nullptr; m_front = new_node; m_back = new_node; } return iterator(this, new_node); } template<typename... Args> iterator try_emplace_front(Args&&... args) noexcept { auto [success, new_node] = m_allocator->try_alloc(); if (!success) return end(); new (&new_node->value) T(std::forward<Args>(args)...); ++m_size; if (m_front) { new_node->prev = nullptr; new_node->next = m_front; m_front->prev = new_node; m_front = new_node; } else { new_node->prev = nullptr; new_node->next = nullptr; m_front = new_node; m_back = new_node; } return begin(); } template<typename... Args> iterator try_emplace_back(Args&&... args) noexcept { auto [success, new_node] = m_allocator->try_alloc(); if (!success) return end(); new (&new_node->value) T(std::forward<Args>(args)...); ++m_size; if (m_back) { new_node->prev = m_back; new_node->next = nullptr; m_back->next = new_node; m_back = new_node; } else { new_node->prev = nullptr; new_node->next = nullptr; m_front = new_node; m_back = new_node; } return iterator(this, new_node); } void pop_front() noexcept { if (m_front == nullptr) return; node_type* to_delete = m_front; m_front = m_front->next; if (m_front) m_front->prev = nullptr; else m_back = nullptr; if constexpr (!std::is_trivial_v<T>) to_delete->value.~T(); m_allocator->free(to_delete); --m_size; } void pop_back() noexcept { if (m_back == nullptr) return; node_type* to_delete = m_back; m_back = m_back->prev; if (m_back) m_back->next = nullptr; else m_front = nullptr; if constexpr (!std::is_trivial_v<T>) to_delete->value.~T(); m_allocator->free(to_delete); --m_size; } bool empty() const noexcept { return m_size == 0; } i64 size() const noexcept { return m_size; } }; /***************************************************************************** * * data-array * ****************************************************************************/ enum class model_id : std::uint64_t; enum class dynamics_id : std::uint64_t; enum class message_id : std::uint64_t; enum class observer_id : std::uint64_t; template<typename T> constexpr u32 get_index(T identifier) noexcept { return static_cast<u32>( static_cast<typename std::underlying_type<T>::type>(identifier) & 0x00000000ffffffff); } template<typename T> constexpr u32 get_key(T identifier) noexcept { return static_cast<u32>( (static_cast<typename std::underlying_type<T>::type>(identifier) & 0xffffffff00000000) >> 32); } template<typename T> constexpr u32 get_max_key() noexcept { return static_cast<u32>(0xffffffff00000000 >> 32); } template<typename T> constexpr u32 get_max_size() noexcept { return std::numeric_limits<u32>::max(); } template<typename T> constexpr bool is_valid(T identifier) noexcept { return get_key(identifier) > 0; } template<typename T> constexpr T make_id(u32 key, u32 index) noexcept { u64 identifier = key; identifier <<= 32; identifier |= index; T ret{ identifier }; return ret; // return static_cast<T>(identifier); } template<typename T> constexpr u32 make_next_key(u32 key) noexcept { return key == get_max_key<T>() ? 1u : key + 1; } /** * @brief An optimized fixed size array for dynamics objects. * * A container to handle everything from trivial, pod or object. * - linear memory/iteration * - O(1) alloc/free * - stable indices * - weak references * - zero overhead dereferences * * @tparam T The type of object the data_array holds. * @tparam Identifier A enum class identifier to store identifier unsigned * number. * @todo Make Identifier split key|id automatically for all unsigned. */ template<typename T, typename Identifier> class data_array { private: static_assert( std::is_enum<Identifier>::value, "Identifier must be a enumeration: enum class id : unsigned {};"); struct item { T item; Identifier id; }; item* m_items = nullptr; // items vector. u32 m_max_size = 0; // total size u32 m_max_used = 0; // highest index ever allocated u32 m_capacity = 0; // num allocated items u32 m_next_key = 1; // [1..2^32] (don't let == 0) u32 m_free_head = none; // index of first free entry public: using identifier_type = Identifier; using value_type = T; static constexpr u32 none = std::numeric_limits<u32>::max(); data_array() = default; ~data_array() noexcept { clear(); if (m_items) g_free_fn(m_items); } /** * @brief Initialize the underlying byffer of T. * * @return @c is_success(status) or is_bad(status). */ status init(std::size_t capacity) noexcept { clear(); if (capacity > get_max_size<Identifier>()) return status::data_array_init_capacity_error; m_items = static_cast<item*>(g_alloc_fn(capacity * sizeof(item))); if (!m_items) return status::data_array_not_enough_memory; m_max_size = 0; m_max_used = 0; m_capacity = static_cast<u32>(capacity); m_next_key = 1; m_free_head = none; return status::success; } /** * @brief Resets data members * * Run destructor on outstanding items and re-initialize of size. */ void clear() noexcept { if constexpr (!std::is_trivial_v<T>) { for (u32 i = 0; i != m_max_used; ++i) { if (is_valid(m_items[i].id)) { m_items[i].item.~T(); m_items[i].id = static_cast<identifier_type>(0); } } } m_max_size = 0; m_max_used = 0; m_next_key = 1; m_free_head = none; } /** * @brief Alloc a new element. * * If allocator can not allocate new item, this function abort() if NDEBUG * macro is not defined. Before using this function, tries @c can_alloc() * for example. * * Use @c m_free_head if not empty or use a new items from buffer * (@m_item[max_used++]). The id is set to from @c next_key++ << 32) | * index to build unique identifier. * * @return A reference to the newly allocated element. */ template<typename... Args> T& alloc(Args&&... args) noexcept { assert(can_alloc(1) && "check alloc() with full() before using use."); u32 new_index; if (m_free_head != none) { new_index = m_free_head; if (is_valid(m_items[m_free_head].id)) m_free_head = none; else m_free_head = get_index(m_items[m_free_head].id); } else { new_index = m_max_used++; } new (&m_items[new_index].item) T(std::forward<Args>(args)...); m_items[new_index].id = make_id<Identifier>(m_next_key, new_index); m_next_key = make_next_key<Identifier>(m_next_key); ++m_max_size; return m_items[new_index].item; } /** * @brief Alloc a new element. * * Use @c m_free_head if not empty or use a new items from buffer * (@m_item[max_used++]). The id is set to from @c next_key++ << 32) | * index to build unique identifier. * * @return A pair with a boolean if the allocation success and a pointer to * the newly element. */ template<typename... Args> std::pair<bool, T*> try_alloc(Args&&... args) noexcept { if (!can_alloc(1)) return { false, nullptr }; u32 new_index; if (m_free_head != none) { new_index = m_free_head; if (is_valid(m_items[m_free_head].id)) m_free_head = none; else m_free_head = get_index(m_items[m_free_head].id); } else { new_index = m_max_used++; } new (&m_items[new_index].item) T(std::forward<Args>(args)...); m_items[new_index].id = make_id<Identifier>(m_next_key, new_index); m_next_key = make_next_key<Identifier>(m_next_key); ++m_max_size; return { true, &m_items[new_index].item }; } /** * @brief Free the element @c t. * * Internally, puts the elelent @c t entry on free list and use id to store * next. */ void free(T& t) noexcept { auto id = get_id(t); auto index = get_index(id); irt_assert(&m_items[index] == static_cast<void*>(&t)); irt_assert(m_items[index].id == id); irt_assert(is_valid(id)); if constexpr (!std::is_trivial_v<T>) m_items[index].item.~T(); m_items[index].id = static_cast<Identifier>(m_free_head); m_free_head = index; --m_max_size; } /** * @brief Free the element pointer by @c id. * * Internally, puts the elelent @c t entry on free list and use id to store * next. */ void free(Identifier id) noexcept { auto index = get_index(id); irt_assert(m_items[index].id == id); irt_assert(is_valid(id)); if constexpr (std::is_trivial_v<T>) m_items[index].item.~T(); m_items[index].id = static_cast<Identifier>(m_free_head); m_free_head = index; --m_max_size; } /** * @brief Accessor to the id part of the item * * @return @c Identifier. */ Identifier get_id(const T* t) const noexcept { irt_assert(t != nullptr); auto* ptr = reinterpret_cast<const item*>(t); return ptr->id; } /** * @brief Accessor to the id part of the item * * @return @c Identifier. */ Identifier get_id(const T& t) const noexcept { auto* ptr = reinterpret_cast<const item*>(&t); return ptr->id; } /** * @brief Accessor to the item part of the id. * * @return @c T */ T& get(Identifier id) noexcept { return m_items[get_index(id)].item; } /** * @brief Accessor to the item part of the id. * * @return @c T */ const T& get(Identifier id) const noexcept { return m_items[get_index(id)].item; } /** * @brief Get a T from an ID. * * @details Validates ID, then returns item, returns null if invalid. * For cases like AI references and others where 'the thing might have * been deleted out from under me. */ T* try_to_get(Identifier id) const noexcept { if (get_key(id)) { auto index = get_index(id); if (m_items[index].id == id) return &m_items[index].item; } return nullptr; } T* try_to_get(u32 index) const noexcept { if (is_valid(m_items[index].id)) return &m_items[index].item; return nullptr; } /** * @brief Return next valid item. * @code * data_array<int> d; * ... * int* value = nullptr; * while (d.next(value)) { * std::cout << *value; * } * @endcode * * Loop item where @c id & 0xffffffff00000000 != 0 (i.e. items not on free * list). * * @return true if the paramter @c t is valid false otherwise. */ bool next(T*& t) const noexcept { u32 index; if (t) { auto id = get_id(*t); index = get_index(id); ++index; for (; index < m_max_used; ++index) { if (is_valid(m_items[index].id)) { t = &m_items[index].item; return true; } } } else { for (index = 0; index < m_max_used; ++index) { if (is_valid(m_items[index].id)) { t = &m_items[index].item; return true; } } } return false; } constexpr bool full() const noexcept { return m_free_head == none && m_max_used == m_capacity; } constexpr std::size_t size() const noexcept { return m_max_size; } constexpr bool can_alloc(const sz nb) const noexcept { return m_capacity - m_max_size >= nb; } constexpr bool can_alloc() const noexcept { return m_capacity - m_max_size >= 1u; } constexpr u32 max_size() const noexcept { return m_max_size; } constexpr u32 max_used() const noexcept { return m_max_used; } constexpr u32 capacity() const noexcept { return m_capacity; } constexpr u32 next_key() const noexcept { return m_next_key; } constexpr bool is_free_list_empty() const noexcept { return m_free_head == none; } }; struct record { record() noexcept = default; record(double x_dot_, time date_) noexcept : x_dot{ x_dot_ } , date{ date_ } {} double x_dot{ 0 }; time date{ time_domain<time>::infinity }; }; /** * @brief Pairing heap implementation. * * A pairing heap is a type of heap data structure with relatively simple * implementation and excellent practical amortized performance, introduced by * Michael Fredman, Robert Sedgewick, Daniel Sleator, and Robert Tarjan in * 1986. * * https://en.wikipedia.org/wiki/Pairing_heap */ class heap { private: struct node { time tn; model_id id; node* prev; node* next; node* child; }; size_t m_size{ 0 }; size_t max_size{ 0 }; size_t capacity{ 0 }; node* root{ nullptr }; node* nodes{ nullptr }; node* free_list{ nullptr }; public: using handle = node*; heap() = default; ~heap() noexcept { if (nodes) g_free_fn(nodes); } status init(size_t new_capacity) noexcept { if (new_capacity == 0) return status::head_allocator_bad_capacity; if (new_capacity != capacity) { if (nodes) g_free_fn(nodes); nodes = static_cast<node*>(g_alloc_fn(new_capacity * sizeof(node))); if (nodes == nullptr) return status::head_allocator_not_enough_memory; } m_size = 0; max_size = 0; capacity = new_capacity; root = nullptr; free_list = nullptr; return status::success; } void clear() { m_size = 0; max_size = 0; root = nullptr; free_list = nullptr; } handle insert(time tn, model_id id) noexcept { node* new_node; if (free_list) { new_node = free_list; free_list = free_list->next; } else { new_node = &nodes[max_size++]; } new_node->tn = tn; new_node->id = id; new_node->prev = nullptr; new_node->next = nullptr; new_node->child = nullptr; insert(new_node); return new_node; } void destroy(handle elem) noexcept { irt_assert(elem); if (m_size == 0) { clear(); } else { elem->prev = nullptr; elem->child = nullptr; elem->id = static_cast<model_id>(0); elem->next = free_list; free_list = elem; } } void insert(handle elem) noexcept { elem->prev = nullptr; elem->next = nullptr; elem->child = nullptr; ++m_size; if (root == nullptr) root = elem; else root = merge(elem, root); } void remove(handle elem) noexcept { irt_assert(elem); if (elem == root) { pop(); return; } irt_assert(m_size > 0); m_size--; detach_subheap(elem); if (elem->prev) { /* Not use pop() before. Use in interactive code */ elem = merge_subheaps(elem); root = merge(root, elem); } } handle pop() noexcept { irt_assert(m_size > 0); m_size--; auto* top = root; if (top->child == nullptr) root = nullptr; else root = merge_subheaps(top); top->child = top->next = top->prev = nullptr; return top; } void decrease(handle elem) noexcept { if (elem->prev == nullptr) return; detach_subheap(elem); root = merge(root, elem); } void increase(handle elem) noexcept { remove(elem); insert(elem); } size_t size() const noexcept { return m_size; } size_t full() const noexcept { return m_size == capacity; } bool empty() const noexcept { return root == nullptr; } handle top() const noexcept { return root; } void merge(heap& src) noexcept { if (this == &src) return; if (root == nullptr) { root = src.root; return; } root = merge(root, src.root); m_size += src.m_size; } private: static node* merge(node* a, node* b) noexcept { if (a->tn < b->tn) { if (a->child != nullptr) a->child->prev = b; if (b->next != nullptr) b->next->prev = a; a->next = b->next; b->next = a->child; a->child = b; b->prev = a; return a; } if (b->child != nullptr) b->child->prev = a; if (a->prev != nullptr && a->prev->child != a) a->prev->next = b; b->prev = a->prev; a->prev = b; a->next = b->child; b->child = a; return b; } static node* merge_right(node* a) noexcept { node* b{ nullptr }; for (; a != nullptr; a = b->next) { if ((b = a->next) == nullptr) return a; b = merge(a, b); } return b; } static node* merge_left(node* a) noexcept { node* b = a->prev; for (; b != nullptr; b = a->prev) a = merge(b, a); return a; } static node* merge_subheaps(node* a) noexcept { a->child->prev = nullptr; node* e = merge_right(a->child); return merge_left(e); } void detach_subheap(node* elem) noexcept { if (elem->prev->child == elem) elem->prev->child = elem->next; else elem->prev->next = elem->next; if (elem->next != nullptr) elem->next->prev = elem->prev; elem->prev = nullptr; elem->next = nullptr; } }; struct simulation; /***************************************************************************** * * @c source and @c source_id are data from files or random generators. * ****************************************************************************/ struct source { enum class operation_type { initialize, // Use to initialize the buffer at simulation init step. update, // Use to update the buffer when all values are read. finalize // Use to clear the buffer at simulation finalize step. }; double* buffer = nullptr; u64 id = 0; // The identifier of the external source (see operation()) int type = -1; // The type of the external source (see operation()) int size = 0; int index = 0; void reset() noexcept { buffer = nullptr; size = 0; index = 0; type = -1; id = 0; } void clear() noexcept { buffer = nullptr; size = 0; index = 0; } bool next(double& value) noexcept { if (index >= size) return false; value = buffer[index++]; return true; } }; /** * @brief Call in the initialize function of the models. * @param sim The simulation. * @param src The sources. * @return */ inline status initialize_source(simulation& sim, source& src) noexcept; inline status update_source(simulation& sim, source& src, double& val) noexcept; inline status finalize_source(simulation& sim, source& src) noexcept; /***************************************************************************** * * DEVS Model / Simulation entities * ****************************************************************************/ enum class dynamics_type : i32 { none, qss1_integrator, qss1_multiplier, qss1_cross, qss1_power, qss1_square, qss1_sum_2, qss1_sum_3, qss1_sum_4, qss1_wsum_2, qss1_wsum_3, qss1_wsum_4, qss2_integrator, qss2_multiplier, qss2_cross, qss2_power, qss2_square, qss2_sum_2, qss2_sum_3, qss2_sum_4, qss2_wsum_2, qss2_wsum_3, qss2_wsum_4, qss3_integrator, qss3_multiplier, qss3_power, qss3_square, qss3_cross, qss3_sum_2, qss3_sum_3, qss3_sum_4, qss3_wsum_2, qss3_wsum_3, qss3_wsum_4, integrator, quantifier, adder_2, adder_3, adder_4, mult_2, mult_3, mult_4, counter, queue, dynamic_queue, priority_queue, generator, constant, cross, time_func, accumulator_2, flow }; constexpr i8 dynamics_type_last() noexcept { return static_cast<i8>(dynamics_type::flow); } constexpr sz dynamics_type_size() noexcept { return static_cast<sz>(dynamics_type_last() + 1); } struct observer; struct observer { enum class status { initialize, run, finalize }; using update_fn = function_ref<void(const observer&, const dynamics_type, const time, const time, const observer::status)>; observer(const char* name_, update_fn cb_) noexcept : cb(cb_) , name(name_) {} update_fn cb; small_string<8> name; model_id model = static_cast<model_id>(0); message msg; }; namespace detail { template<typename, template<typename...> class, typename...> struct is_detected : std::false_type {}; template<template<class...> class Operation, typename... Arguments> struct is_detected<std::void_t<Operation<Arguments...>>, Operation, Arguments...> : std::true_type {}; template<typename T, T> struct helper {}; } // namespace detail template<template<class...> class Operation, typename... Arguments> using is_detected = detail::is_detected<std::void_t<>, Operation, Arguments...>; template<template<class...> class Operation, typename... Arguments> constexpr bool is_detected_v = detail::is_detected<std::void_t<>, Operation, Arguments...>::value; template<class T> using lambda_function_t = decltype(detail::helper<status (T::*)(), &T::lambda>{}); template<class T> using transition_function_t = decltype(detail::helper<status (T::*)(time, time, time), &T::transition>{}); template<class T> using observation_function_t = decltype(detail::helper<message (T::*)(const time) const, &T::observation>{}); template<class T> using initialize_function_t = decltype(detail::helper<status (T::*)(), &T::initialize>{}); template<typename T> using has_input_port_t = decltype(&T::x); template<typename T> using has_output_port_t = decltype(&T::y); template<typename T> using has_init_port_t = decltype(&T::init); template<typename T> using has_sim_attribute_t = decltype(&T::sim); struct node { node() = default; node(const model_id model_, const int port_index_) noexcept : model(model_) , port_index(port_index_) {} model_id model = model_id{ 0 }; int port_index = 0; }; struct port { shared_flat_list<node> connections; flat_list<message> messages; // message* output = nullptr; // port& operator=(const double v) noexcept // { // output[0] = v; // return *this; // } // port& operator=(const std::initializer_list<double>& v) noexcept // { // std::copy_n(std::data(v), std::size(v), &output->real[0]); // return *this; // } }; struct none { time sigma = time_domain<time>::infinity; }; struct integrator { port x[3]; port y[1]; time sigma = time_domain<time>::zero; enum port_name { port_quanta, port_x_dot, port_reset }; enum class state { init, wait_for_quanta, wait_for_x_dot, wait_for_both, running }; double default_current_value = 0.0; double default_reset_value = 0.0; flat_double_list<record> archive; double current_value = 0.0; double reset_value = 0.0; double up_threshold = 0.0; double down_threshold = 0.0; double last_output_value = 0.0; double expected_value = 0.0; bool reset = false; state st = state::init; integrator() = default; integrator(const integrator& other) noexcept : default_current_value(other.default_current_value) , default_reset_value(other.default_reset_value) , archive(other.archive.get_allocator()) , current_value(other.current_value) , reset_value(other.reset_value) , up_threshold(other.up_threshold) , down_threshold(other.down_threshold) , last_output_value(other.last_output_value) , expected_value(other.expected_value) , reset(other.reset) , st(other.st) {} status initialize() noexcept { current_value = default_current_value; reset_value = default_reset_value; up_threshold = 0.0; down_threshold = 0.0; last_output_value = 0.0; expected_value = 0.0; reset = false; archive.clear(); st = state::init; sigma = time_domain<time>::zero; return status::success; } status external(port& port_quanta, port& port_x_dot, port& port_reset, time t) noexcept { for (const auto& msg : port_quanta.messages) { up_threshold = msg.real[0]; down_threshold = msg.real[1]; if (st == state::wait_for_quanta) st = state::running; if (st == state::wait_for_both) st = state::wait_for_x_dot; } for (const auto& msg : port_x_dot.messages) { archive.emplace_back(msg.real[0], t); if (st == state::wait_for_x_dot) st = state::running; if (st == state::wait_for_both) st = state::wait_for_quanta; } for (const auto& msg : port_reset.messages) { reset_value = msg.real[0]; reset = true; } if (st == state::running) { current_value = compute_current_value(t); expected_value = compute_expected_value(); } return status::success; } status internal(time t) noexcept { switch (st) { case state::running: { last_output_value = expected_value; const double last_derivative_value = archive.back().x_dot; archive.clear(); archive.emplace_back(last_derivative_value, t); current_value = expected_value; st = state::wait_for_quanta; return status::success; } case state::init: st = state::wait_for_both; last_output_value = current_value; return status::success; default: return status::model_integrator_internal_error; } } status transition(time t, time /*e*/, time r) noexcept { auto& port_1 = x[port_quanta]; auto& port_2 = x[port_x_dot]; auto& port_3 = x[port_reset]; if (port_1.messages.empty() && port_2.messages.empty() && port_3.messages.empty()) { irt_return_if_bad(internal(t)); } else { if (time_domain<time>::is_zero(r)) irt_return_if_bad(internal(t)); irt_return_if_bad(external(port_1, port_2, port_3, t)); } return ta(); } status lambda() noexcept { switch (st) { case state::running: y[0].messages.emplace_front(expected_value); return status::success; case state::init: y[0].messages.emplace_front(current_value); return status::success; default: return status::model_integrator_output_error; } return status::success; } message observation(const time /*e*/) const noexcept { return { last_output_value }; } status ta() noexcept { if (st == state::running) { irt_return_if_fail(!archive.empty(), status::model_integrator_running_without_x_dot); const auto current_derivative = archive.back().x_dot; if (current_derivative == time_domain<time>::zero) { sigma = time_domain<time>::infinity; return status::success; } if (current_derivative > 0) { irt_return_if_fail((up_threshold - current_value) >= 0, status::model_integrator_ta_with_bad_x_dot); sigma = (up_threshold - current_value) / current_derivative; return status::success; } irt_return_if_fail((down_threshold - current_value) <= 0, status::model_integrator_ta_with_bad_x_dot); sigma = (down_threshold - current_value) / current_derivative; return status::success; } sigma = time_domain<time>::infinity; return status::success; } double compute_current_value(time t) const noexcept { if (archive.empty()) return reset ? reset_value : last_output_value; auto val = reset ? reset_value : last_output_value; auto end = archive.end(); auto it = archive.begin(); auto next = archive.begin(); if (next != end) ++next; for (; next != end; it = next++) val += (next->date - it->date) * it->x_dot; val += (t - archive.back().date) * archive.back().x_dot; if (up_threshold < val) { return up_threshold; } else if (down_threshold > val) { return down_threshold; } else { return val; } } double compute_expected_value() const noexcept { const auto current_derivative = archive.back().x_dot; if (current_derivative == 0) return current_value; if (current_derivative > 0) return up_threshold; return down_threshold; } }; /***************************************************************************** * * Qss1 part * ****************************************************************************/ template<int QssLevel> struct abstract_integrator; template<> struct abstract_integrator<1> { port x[2]; port y[1]; double default_X = 0.; double default_dQ = 0.01; double X; double q; double u; time sigma = time_domain<time>::zero; enum port_name { port_x_dot, port_reset }; abstract_integrator() = default; abstract_integrator(const abstract_integrator& other) noexcept : default_X(other.default_X) , default_dQ(other.default_dQ) , X(other.X) , q(other.q) , u(other.u) , sigma(other.sigma) {} status initialize() noexcept { irt_return_if_fail(std::isfinite(default_X), status::model_integrator_X_error); irt_return_if_fail(std::isfinite(default_dQ) && default_dQ > 0., status::model_integrator_X_error); X = default_X; q = std::floor(X / default_dQ) * default_dQ; u = 0.; sigma = time_domain<time>::zero; return status::success; } status external(const double value_x, const time e) noexcept { X += e * u; u = value_x; if (sigma != 0.) { if (u == 0.) sigma = time_domain<time>::infinity; else if (u > 0.) sigma = (q + default_dQ - X) / u; else sigma = (q - default_dQ - X) / u; } return status::success; } status reset(const double value_reset) noexcept { X = value_reset; q = X; sigma = time_domain<time>::zero; return status::success; } status internal() noexcept { X += sigma * u; q = X; sigma = u == 0. ? time_domain<time>::infinity : default_dQ / std::abs(u); return status::success; } status transition(time /*t*/, time e, time /*r*/) noexcept { auto& port_x = x[port_x_dot]; auto& port_r = x[port_reset]; if (port_x.messages.empty() && port_r.messages.empty()) { irt_return_if_bad(internal()); } else { if (!port_r.messages.empty()) { irt_return_if_bad(reset(port_r.messages.front()[0])); } else { irt_return_if_bad(external(port_x.messages.front()[0], e)); } } return status::success; } status lambda() noexcept { y[0].messages.emplace_front(X + u * sigma); return status::success; } message observation(const time /*e*/) const noexcept { return { X, u }; } }; /***************************************************************************** * * Qss2 part * ****************************************************************************/ template<> struct abstract_integrator<2> { port x[2]; port y[1]; double default_X = 0.; double default_dQ = 0.01; double X; double u; double mu; double q; double mq; time sigma = time_domain<time>::zero; enum port_name { port_x_dot, port_reset }; abstract_integrator() = default; abstract_integrator(const abstract_integrator& other) noexcept : default_X(other.default_X) , default_dQ(other.default_dQ) , X(other.X) , u(other.u) , mu(other.mu) , q(other.q) , mq(other.mq) , sigma(other.sigma) {} status initialize() noexcept { irt_return_if_fail(std::isfinite(default_X), status::model_integrator_X_error); irt_return_if_fail(std::isfinite(default_dQ) && default_dQ > 0., status::model_integrator_X_error); X = default_X; u = 0.; mu = 0.; q = X; mq = 0.; sigma = time_domain<time>::zero; return status::success; } status external(const double value_x, const double value_slope, const time e) noexcept { X += (u * e) + (mu / 2.0) * (e * e); u = value_x; mu = value_slope; if (sigma != 0) { q += mq * e; const double a = mu / 2; const double b = u - mq; double c = X - q + default_dQ; double s; sigma = time_domain<time>::infinity; if (a == 0) { if (b != 0) { s = -c / b; if (s > 0) sigma = s; c = X - q - default_dQ; s = -c / b; if ((s > 0) && (s < sigma)) sigma = s; } } else { s = (-b + std::sqrt(b * b - 4. * a * c)) / 2. / a; if (s > 0.) sigma = s; s = (-b - std::sqrt(b * b - 4. * a * c)) / 2. / a; if ((s > 0.) && (s < sigma)) sigma = s; c = X - q - default_dQ; s = (-b + std::sqrt(b * b - 4. * a * c)) / 2. / a; if ((s > 0.) && (s < sigma)) sigma = s; s = (-b - std::sqrt(b * b - 4. * a * c)) / 2. / a; if ((s > 0.) && (s < sigma)) sigma = s; } if (((X - q) > default_dQ) || ((q - X) > default_dQ)) sigma = time_domain<time>::zero; } return status::success; } status internal() noexcept { X += u * sigma + mu / 2. * sigma * sigma; q = X; u += mu * sigma; mq = u; sigma = mu == 0. ? time_domain<time>::infinity : std::sqrt(2. * default_dQ / std::abs(mu)); return status::success; } status reset(const double value_reset) noexcept { X = value_reset; q = X; sigma = time_domain<time>::zero; return status::success; } status transition(time /*t*/, time e, time /*r*/) noexcept { auto& port_x = x[port_x_dot]; auto& port_r = x[port_reset]; if (port_x.messages.empty() && port_r.messages.empty()) irt_return_if_bad(internal()); else { if (!port_r.messages.empty()) { irt_return_if_bad(reset(port_r.messages.front()[0])); } else { irt_return_if_bad(external( port_x.messages.front()[0], port_x.messages.front()[1], e)); } } return status::success; } status lambda() noexcept { y[0].messages.emplace_front(X + u * sigma + mu * sigma * sigma / 2., u + mu * sigma); return status::success; } message observation(const time /*e*/) const noexcept { return { X, u, mu }; } }; template<> struct abstract_integrator<3> { port x[2]; port y[1]; double default_X = 0.; double default_dQ = 0.01; double X; double u; double mu; double pu; double q; double mq; double pq; time sigma = time_domain<time>::zero; enum port_name { port_x_dot, port_reset }; abstract_integrator() = default; status initialize() noexcept { irt_return_if_fail(std::isfinite(default_X), status::model_integrator_X_error); irt_return_if_fail(std::isfinite(default_dQ) && default_dQ > 0., status::model_integrator_X_error); X = default_X; u = 0; mu = 0; pu = 0; q = default_X; mq = 0; pq = 0; sigma = time_domain<time>::zero; return status::success; } status external(const double value_x, const double value_slope, const double value_derivative, const time e) noexcept { #if irt_have_numbers == 1 constexpr double pi_div_3 = std::numbers::pi_v<double> / 3.; #else constexpr double pi_div_3 = 1.0471975511965976; #endif X = X + u * e + (mu * e * e) / 2. + (pu * e * e * e) / 3.; u = value_x; mu = value_slope; pu = value_derivative; if (sigma != 0.) { q = q + mq * e + pq * e * e; mq = mq + 2. * pq * e; auto a = mu / 2. - pq; auto b = u - mq; auto c = X - q - default_dQ; auto s = 0.; if (pu != 0) { a = 3. * a / pu; b = 3. * b / pu; c = 3. * c / pu; auto v = b - a * a / 3.; auto w = c - b * a / 3. + 2. * a * a * a / 27.; auto i1 = -w / 2.; auto i2 = i1 * i1 + v * v * v / 27.; if (i2 > 0) { i2 = std::sqrt(i2); auto A = i1 + i2; auto B = i1 - i2; if (A > 0.) A = std::pow(A, 1. / 3.); else A = -std::pow(std::abs(A), 1. / 3.); if (B > 0.) B = std::pow(B, 1. / 3.); else B = -std::pow(std::abs(B), 1. / 3.); s = A + B - a / 3.; if (s < 0.) s = time_domain<time>::infinity; } else if (i2 == 0.) { auto A = i1; if (A > 0.) A = std::pow(A, 1. / 3.); else A = -std::pow(std::abs(A), 1. / 3.); auto x1 = 2. * A - a / 3.; auto x2 = -(A + a / 3.); if (x1 < 0.) { if (x2 < 0.) { s = time_domain<time>::infinity; } else { s = x2; } } else if (x2 < 0.) { s = x1; } else if (x1 < x2) { s = x1; } else { s = x2; } } else { auto arg = w * std::sqrt(27. / (-v)) / (2. * v); arg = std::acos(arg) / 3.; auto y1 = 2 * std::sqrt(-v / 3.); auto y2 = -y1 * std::cos(pi_div_3 - arg) - a / 3.; auto y3 = -y1 * std::cos(pi_div_3 + arg) - a / 3.; y1 = y1 * std::cos(arg) - a / 3.; if (y1 < 0.) { s = time_domain<time>::infinity; } else if (y3 < 0.) { s = y1; } else if (y2 < 0.) { s = y3; } else { s = y2; } } c = c + 6. * default_dQ / pu; w = c - b * a / 3. + 2. * a * a * a / 27.; i1 = -w / 2; i2 = i1 * i1 + v * v * v / 27.; if (i2 > 0.) { i2 = std::sqrt(i2); auto A = i1 + i2; auto B = i1 - i2; if (A > 0) A = std::pow(A, 1. / 3.); else A = -std::pow(std::abs(A), 1. / 3.); if (B > 0.) B = std::pow(B, 1. / 3.); else B = -std::pow(std::abs(B), 1. / 3.); sigma = A + B - a / 3.; if (s < sigma || sigma < 0.) { sigma = s; } } else if (i2 == 0.) { auto A = i1; if (A > 0.) A = std::pow(A, 1. / 3.); else A = -std::pow(std::abs(A), 1. / 3.); auto x1 = 2. * A - a / 3.; auto x2 = -(A + a / 3.); if (x1 < 0.) { if (x2 < 0.) { sigma = time_domain<time>::infinity; } else { sigma = x2; } } else if (x2 < 0.) { sigma = x1; } else if (x1 < x2) { sigma = x1; } else { sigma = x2; } if (s < sigma) { sigma = s; } } else { auto arg = w * std::sqrt(27. / (-v)) / (2. * v); arg = std::acos(arg) / 3.; auto y1 = 2. * std::sqrt(-v / 3.); auto y2 = -y1 * std::cos(pi_div_3 - arg) - a / 3.; auto y3 = -y1 * std::cos(pi_div_3 + arg) - a / 3.; y1 = y1 * std::cos(arg) - a / 3.; if (y1 < 0.) { sigma = time_domain<time>::infinity; } else if (y3 < 0.) { sigma = y1; } else if (y2 < 0.) { sigma = y3; } else { sigma = y2; } if (s < sigma) { sigma = s; } } } else { if (a != 0.) { auto x1 = b * b - 4 * a * c; if (x1 < 0.) { s = time_domain<time>::infinity; } else { x1 = std::sqrt(x1); auto x2 = (-b - x1) / 2. / a; x1 = (-b + x1) / 2. / a; if (x1 < 0.) { if (x2 < 0.) { s = time_domain<time>::infinity; } else { s = x2; } } else if (x2 < 0.) { s = x1; } else if (x1 < x2) { s = x1; } else { s = x2; } } c = c + 2. * default_dQ; x1 = b * b - 4. * a * c; if (x1 < 0.) { sigma = time_domain<time>::infinity; } else { x1 = std::sqrt(x1); auto x2 = (-b - x1) / 2. / a; x1 = (-b + x1) / 2. / a; if (x1 < 0.) { if (x2 < 0.) { sigma = time_domain<time>::infinity; } else { sigma = x2; } } else if (x2 < 0.) { sigma = x1; } else if (x1 < x2) { sigma = x1; } else { sigma = x2; } } if (s < sigma) sigma = s; } else { if (b != 0.) { auto x1 = -c / b; auto x2 = x1 - 2 * default_dQ / b; if (x1 < 0.) x1 = time_domain<time>::infinity; if (x2 < 0.) x2 = time_domain<time>::infinity; if (x1 < x2) { sigma = x1; } else { sigma = x2; } } } } if ((std::abs(X - q)) > default_dQ) sigma = time_domain<time>::zero; } return status::success; } status internal() noexcept { X = X + u * sigma + (mu * sigma * sigma) / 2. + (pu * sigma * sigma * sigma) / 3.; q = X; u = u + mu * sigma + pu * pow(sigma, 2); mq = u; mu = mu + 2 * pu * sigma; pq = mu / 2; sigma = pu == 0. ? time_domain<time>::infinity : std::pow(std::abs(3. * default_dQ / pu), 1. / 3.); return status::success; } status reset(const double value_reset) noexcept { X = value_reset; q = X; sigma = time_domain<time>::zero; return status::success; } status transition(time /*t*/, time e, time /*r*/) noexcept { auto& port_x = x[port_x_dot]; auto& port_r = x[port_reset]; if (port_x.messages.empty() && port_r.messages.empty()) irt_return_if_bad(internal()); else { if (!port_r.messages.empty()) irt_return_if_bad(reset(port_r.messages.front()[0])); else irt_return_if_bad(external(port_x.messages.front()[0], port_x.messages.front()[1], port_x.messages.front()[2], e)); } return status::success; } status lambda() noexcept { y[0].messages.emplace_front(X + u * sigma + (mu * sigma * sigma) / 2. + (pu * sigma * sigma * sigma) / 3., u + mu * sigma + pu * sigma * sigma, mu / 2. + pu * sigma); return status::success; } message observation(const time /*e*/) const noexcept { return { X, u, mu, pu }; } }; using qss1_integrator = abstract_integrator<1>; using qss2_integrator = abstract_integrator<2>; using qss3_integrator = abstract_integrator<3>; template<int QssLevel> struct abstract_power { static_assert(1 <= QssLevel && QssLevel <= 3, "Only for Qss1, 2 and 3"); port x[1]; port y[1]; time sigma; double value[QssLevel]; double default_n; abstract_power() noexcept = default; status initialize() noexcept { std::fill_n(value, QssLevel, 0.0); sigma = time_domain<time>::infinity; return status::success; } status lambda() noexcept { if constexpr (QssLevel == 1) { y[0].messages.emplace_front(std::pow(value[0], default_n)); } if constexpr (QssLevel == 2) { y[0].messages.emplace_front( std::pow(value[0], default_n), default_n * std::pow(value[0], default_n - 1) * value[1]); } if constexpr (QssLevel == 3) { y[0].messages.emplace_front( std::pow(value[0], default_n), default_n * std::pow(value[0], default_n - 1) * value[1], default_n * (default_n - 1) * std::pow(value[0], default_n - 2) * (value[1] * value[1] / 2.0) + default_n * std::pow(value[0], default_n - 1) * value[2]); } return status::success; } status transition(time /*t*/, time /*e*/, time /*r*/) noexcept { sigma = time_domain<time>::infinity; if (!x[0].messages.empty()) { auto& msg = x[0].messages.front(); if constexpr (QssLevel == 1) { value[0] = msg[0]; } if constexpr (QssLevel == 2) { value[0] = msg[0]; value[1] = msg[1]; } if constexpr (QssLevel == 3) { value[0] = msg[0]; value[1] = msg[1]; value[2] = msg[2]; } sigma = time_domain<time>::zero; } return status::success; } message observation(const time /*e*/) const noexcept { return { value[0] }; } }; using qss1_power = abstract_power<1>; using qss2_power = abstract_power<2>; using qss3_power = abstract_power<3>; template<int QssLevel> struct abstract_square { static_assert(1 <= QssLevel && QssLevel <= 3, "Only for Qss1, 2 and 3"); port x[1]; port y[1]; time sigma; double value[QssLevel]; abstract_square() noexcept = default; status initialize() noexcept { std::fill_n(value, QssLevel, 0.0); sigma = time_domain<time>::infinity; return status::success; } status lambda() noexcept { if constexpr (QssLevel == 1) { y[0].messages.emplace_front(value[0] * value[0]); } if constexpr (QssLevel == 2) { y[0].messages.emplace_front(value[0] * value[0], 2. * value[0] * value[1]); } if constexpr (QssLevel == 3) { y[0].messages.emplace_front(value[0] * value[0], 2. * value[0] * value[1], 2. * value[0] * value[2] + value[1] * value[1]); } return status::success; } status transition(time /*t*/, time /*e*/, time /*r*/) noexcept { sigma = time_domain<time>::infinity; if (!x[0].messages.empty()) { auto& msg = x[0].messages.front(); if constexpr (QssLevel == 1) { value[0] = msg[0]; } if constexpr (QssLevel == 2) { value[0] = msg[0]; value[1] = msg[1]; } if constexpr (QssLevel == 3) { value[0] = msg[0]; value[1] = msg[1]; value[2] = msg[2]; } sigma = time_domain<time>::zero; } return status::success; } message observation(const time /*e*/) const noexcept { return { value[0] }; } }; using qss1_square = abstract_square<1>; using qss2_square = abstract_square<2>; using qss3_square = abstract_square<3>; template<int QssLevel, int PortNumber> struct abstract_sum { static_assert(1 <= QssLevel && QssLevel <= 3, "Only for Qss1, 2 and 3"); static_assert(PortNumber > 1, "sum model need at least two input port"); port x[PortNumber]; port y[1]; time sigma; double values[QssLevel * PortNumber]; abstract_sum() noexcept = default; status initialize() noexcept { std::fill_n(values, QssLevel * PortNumber, 0.0); sigma = time_domain<time>::infinity; return status::success; } status lambda() noexcept { if constexpr (QssLevel == 1) { double value = 0.; for (int i = 0; i != PortNumber; ++i) value += values[i]; y[0].messages.emplace_front(value); } if constexpr (QssLevel == 2) { double value = 0.; double slope = 0.; for (int i = 0; i != PortNumber; ++i) { value += values[i]; slope += values[i + PortNumber]; } y[0].messages.emplace_front(value, slope); } if constexpr (QssLevel == 3) { double value = 0.; double slope = 0.; double derivative = 0.; for (size_t i = 0; i != PortNumber; ++i) { value += values[i]; slope += values[i + PortNumber]; derivative += values[i + PortNumber + PortNumber]; } y[0].messages.emplace_front(value, slope, derivative); } return status::success; } status transition(time /*t*/, [[maybe_unused]] time e, time /*r*/) noexcept { bool message = false; if constexpr (QssLevel == 1) { for (size_t i = 0; i != PortNumber; ++i) { for (const auto& msg : x[i].messages) { values[i] = msg[0]; message = true; } } } if constexpr (QssLevel == 2) { for (size_t i = 0; i != PortNumber; ++i) { if (x[i].messages.empty()) { values[i] += values[i + PortNumber] * e; } else { for (const auto& msg : x[i].messages) { values[i] = msg[0]; values[i + PortNumber] = msg[1]; message = true; } } } } if constexpr (QssLevel == 3) { for (size_t i = 0; i != PortNumber; ++i) { if (x[i].messages.empty()) { values[i] += values[i + PortNumber] * e + values[i + PortNumber + PortNumber] * e * e; values[i + PortNumber] += 2 * values[i + PortNumber + PortNumber] * e; } else { for (const auto& msg : x[i].messages) { values[i] = msg[0]; values[i + PortNumber] = msg[1]; values[i + PortNumber + PortNumber] = msg[2]; message = true; } } } } sigma = message ? time_domain<time>::zero : time_domain<time>::infinity; return status::success; } message observation([[maybe_unused]] const time e) const noexcept { double value = 0.; if constexpr (QssLevel == 1) { for (size_t i = 0; i != PortNumber; ++i) value += values[i]; } if constexpr (QssLevel >= 2) { for (size_t i = 0; i != PortNumber; ++i) value += values[i + PortNumber] * e; } if constexpr (QssLevel >= 3) { for (size_t i = 0; i != PortNumber; ++i) value += values[i + PortNumber + PortNumber] * e * e; } return { value }; } }; using qss1_sum_2 = abstract_sum<1, 2>; using qss1_sum_3 = abstract_sum<1, 3>; using qss1_sum_4 = abstract_sum<1, 4>; using qss2_sum_2 = abstract_sum<2, 2>; using qss2_sum_3 = abstract_sum<2, 3>; using qss2_sum_4 = abstract_sum<2, 4>; using qss3_sum_2 = abstract_sum<3, 2>; using qss3_sum_3 = abstract_sum<3, 3>; using qss3_sum_4 = abstract_sum<3, 4>; template<int QssLevel, int PortNumber> struct abstract_wsum { static_assert(1 <= QssLevel && QssLevel <= 3, "Only for Qss1, 2 and 3"); static_assert(PortNumber > 1, "sum model need at least two input port"); port x[PortNumber]; port y[1]; time sigma; double default_input_coeffs[PortNumber] = { 0 }; double values[QssLevel * PortNumber]; abstract_wsum() noexcept = default; status initialize() noexcept { std::fill_n(values, QssLevel * PortNumber, 0.); sigma = time_domain<time>::infinity; return status::success; } status lambda() noexcept { if constexpr (QssLevel == 1) { double value = 0.0; for (int i = 0; i != PortNumber; ++i) value += default_input_coeffs[i] * values[i]; y[0].messages.emplace_front(value); } if constexpr (QssLevel == 2) { double value = 0.; double slope = 0.; for (int i = 0; i != PortNumber; ++i) { value += default_input_coeffs[i] * values[i]; slope += default_input_coeffs[i] * values[i + PortNumber]; } y[0].messages.emplace_front(value, slope); } if constexpr (QssLevel == 3) { double value = 0.; double slope = 0.; double derivative = 0.; for (int i = 0; i != PortNumber; ++i) { value += default_input_coeffs[i] * values[i]; slope += default_input_coeffs[i] * values[i + PortNumber]; derivative += default_input_coeffs[i] * values[i + PortNumber + PortNumber]; } y[0].messages.emplace_front(value, slope, derivative); } return status::success; } status transition(time /*t*/, [[maybe_unused]] time e, time /*r*/) noexcept { bool message = false; if constexpr (QssLevel == 1) { for (size_t i = 0; i != PortNumber; ++i) { for (const auto& msg : x[i].messages) { values[i] = msg[0]; message = true; } } } if constexpr (QssLevel == 2) { for (size_t i = 0; i != PortNumber; ++i) { if (x[i].messages.empty()) { values[i] += values[i + PortNumber] * e; } else { for (const auto& msg : x[i].messages) { values[i] = msg[0]; values[i + PortNumber] = msg[1]; message = true; } } } } if constexpr (QssLevel == 3) { for (size_t i = 0; i != PortNumber; ++i) { if (x[i].messages.empty()) { values[i] += values[i + PortNumber] * e + values[i + PortNumber + PortNumber] * e * e; values[i + PortNumber] += 2 * values[i + PortNumber + PortNumber] * e; } else { for (const auto& msg : x[i].messages) { values[i] = msg[0]; values[i + PortNumber] = msg[1]; values[i + PortNumber + PortNumber] = msg[2]; message = true; } } } } sigma = message ? time_domain<time>::zero : time_domain<time>::infinity; return status::success; } message observation([[maybe_unused]] const time e) const noexcept { double value = 0.; if constexpr (QssLevel >= 1) { for (int i = 0; i != PortNumber; ++i) value += default_input_coeffs[i] * values[i]; } if constexpr (QssLevel >= 2) { for (int i = 0; i != PortNumber; ++i) value += default_input_coeffs[i] * values[i + PortNumber] * e; } if constexpr (QssLevel >= 3) { for (size_t i = 0; i != PortNumber; ++i) value += default_input_coeffs[i] * values[i + PortNumber + PortNumber] * e * e; } return { value }; } }; using qss1_wsum_2 = abstract_wsum<1, 2>; using qss1_wsum_3 = abstract_wsum<1, 3>; using qss1_wsum_4 = abstract_wsum<1, 4>; using qss2_wsum_2 = abstract_wsum<2, 2>; using qss2_wsum_3 = abstract_wsum<2, 3>; using qss2_wsum_4 = abstract_wsum<2, 4>; using qss3_wsum_2 = abstract_wsum<3, 2>; using qss3_wsum_3 = abstract_wsum<3, 3>; using qss3_wsum_4 = abstract_wsum<3, 4>; template<int QssLevel> struct abstract_multiplier { static_assert(1 <= QssLevel && QssLevel <= 3, "Only for Qss1, 2 and 3"); port x[2]; port y[1]; time sigma; double values[QssLevel * 2]; abstract_multiplier() noexcept = default; status initialize() noexcept { std::fill_n(values, QssLevel * 2, 0.); sigma = time_domain<time>::infinity; return status::success; } status lambda() noexcept { if constexpr (QssLevel == 1) { y[0].messages.emplace_front(values[0] * values[1]); } if constexpr (QssLevel == 2) { y[0].messages.emplace_front(values[0] * values[1], values[2 + 0] * values[1] + values[2 + 1] * values[0]); } if constexpr (QssLevel == 3) { y[0].messages.emplace_front( values[0] * values[1], values[2 + 0] * values[1] + values[2 + 1] * values[0], values[0] * values[2 + 2 + 1] + values[2 + 0] * values[2 + 1] + values[2 + 2 + 0] * values[1]); } return status::success; } status transition(time /*t*/, [[maybe_unused]] time e, time /*r*/) noexcept { bool message_port_0 = false; bool message_port_1 = false; sigma = time_domain<time>::infinity; for (const auto& msg : x[0].messages) { sigma = time_domain<time>::zero; message_port_0 = true; values[0] = msg[0]; if constexpr (QssLevel >= 2) values[2 + 0] = msg[1]; if constexpr (QssLevel == 3) values[2 + 2 + 0] = msg[2]; } for (const auto& msg : x[1].messages) { message_port_1 = true; sigma = time_domain<time>::zero; values[1] = msg[0]; if constexpr (QssLevel >= 2) values[2 + 1] = msg[1]; if constexpr (QssLevel == 3) values[2 + 2 + 1] = msg[2]; } if constexpr (QssLevel == 2) { if (!message_port_0) values[0] += e * values[2 + 0]; if (!message_port_1) values[1] += e * values[2 + 1]; } if constexpr (QssLevel == 3) { if (!message_port_0) { values[0] += e * values[2 + 0] + values[2 + 2 + 0] * e * e; values[2 + 0] += 2 * values[2 + 2 + 0] * e; } if (!message_port_1) { values[1] += e * values[2 + 1] + values[2 + 2 + 1] * e * e; values[2 + 1] += 2 * values[2 + 2 + 1] * e; } } return status::success; } message observation([[maybe_unused]] const time e) const noexcept { if constexpr (QssLevel == 1) return values[0] * values[1]; if constexpr (QssLevel == 2) return (values[0] + e * values[2 + 0]) * (values[1] + e * values[2 + 1]); if constexpr (QssLevel == 3) return (values[0] + e * values[2 + 0] + e * e * values[2 + 2 + 0]) * (values[1] + e * values[2 + 1] + e * e * values[2 + 2 + 1]); } }; using qss1_multiplier = abstract_multiplier<1>; using qss2_multiplier = abstract_multiplier<2>; using qss3_multiplier = abstract_multiplier<3>; struct quantifier { port x[1]; port y[1]; time sigma = time_domain<time>::infinity; enum class state { init, idle, response }; enum class adapt_state { impossible, possible, done }; enum class direction { up, down }; double default_step_size = 0.001; int default_past_length = 3; adapt_state default_adapt_state = adapt_state::possible; bool default_zero_init_offset = false; flat_double_list<record> archive; double m_upthreshold = 0.0; double m_downthreshold = 0.0; double m_offset = 0.0; double m_step_size = 0.0; int m_step_number = 0; int m_past_length = 0; bool m_zero_init_offset = false; state m_state = state::init; adapt_state m_adapt_state = adapt_state::possible; quantifier() noexcept = default; quantifier(const quantifier& other) noexcept : default_step_size(other.default_step_size) , default_past_length(other.default_past_length) , default_adapt_state(other.default_adapt_state) , default_zero_init_offset(other.default_zero_init_offset) , archive(other.archive.get_allocator()) , m_upthreshold(other.m_upthreshold) , m_downthreshold(other.m_downthreshold) , m_offset(other.m_offset) , m_step_size(other.m_step_size) , m_step_number(other.m_step_number) , m_past_length(other.m_past_length) , m_zero_init_offset(other.m_zero_init_offset) , m_state(other.m_state) , m_adapt_state(other.m_adapt_state) {} status initialize() noexcept { m_step_size = default_step_size; m_past_length = default_past_length; m_zero_init_offset = default_zero_init_offset; m_adapt_state = default_adapt_state; m_upthreshold = 0.0; m_downthreshold = 0.0; m_offset = 0.0; m_step_number = 0; archive.clear(); m_state = state::init; irt_return_if_fail(m_step_size > 0, status::model_quantifier_bad_quantum_parameter); irt_return_if_fail( m_past_length > 2, status::model_quantifier_bad_archive_length_parameter); sigma = time_domain<time>::infinity; return status::success; } status external(port& p, time t) noexcept { double val = 0.0, shifting_factor = 0.0; { double sum = 0.0; double nb = 0.0; for (const auto& msg : p.messages) { sum += msg.real[0]; ++nb; } val = sum / nb; } if (m_state == state::init) { init_step_number_and_offset(val); update_thresholds(); m_state = state::response; return status::success; } while ((val >= m_upthreshold) || (val <= m_downthreshold)) { m_step_number = val >= m_upthreshold ? m_step_number + 1 : m_step_number - 1; switch (m_adapt_state) { case adapt_state::impossible: update_thresholds(); break; case adapt_state::possible: store_change(val >= m_upthreshold ? m_step_size : -m_step_size, t); shifting_factor = shift_quanta(); irt_return_if_fail(shifting_factor >= 0, status::model_quantifier_shifting_value_neg); irt_return_if_fail( shifting_factor <= 1, status::model_quantifier_shifting_value_less_1); if ((0 != shifting_factor) && (1 != shifting_factor)) { update_thresholds(shifting_factor, val >= m_upthreshold ? direction::down : direction::up); m_adapt_state = adapt_state::done; } else { update_thresholds(); } break; case adapt_state::done: init_step_number_and_offset(val); m_adapt_state = adapt_state::possible; update_thresholds(); break; } } m_state = state::response; return status::success; } status internal() noexcept { if (m_state == state::response) m_state = state::idle; return status::success; } status transition(time t, time /*e*/, time r) noexcept { if (x[0].messages.empty()) { irt_return_if_bad(internal()); } else { if (time_domain<time>::is_zero(r)) irt_return_if_bad(internal()); irt_return_if_bad(external(x[0], t)); } return ta(); } status lambda() noexcept { y[0].messages.emplace_front(m_upthreshold, m_downthreshold); return status::success; } message observation(const time /*e*/) const noexcept { return { m_upthreshold, m_downthreshold }; } private: status ta() noexcept { sigma = m_state == state::response ? time_domain<time>::zero : time_domain<time>::infinity; return status::success; } void update_thresholds() noexcept { const auto step_number = static_cast<double>(m_step_number); m_upthreshold = m_offset + m_step_size * (step_number + 1.0); m_downthreshold = m_offset + m_step_size * (step_number - 1.0); } void update_thresholds(double factor) noexcept { const auto step_number = static_cast<double>(m_step_number); m_upthreshold = m_offset + m_step_size * (step_number + (1.0 - factor)); m_downthreshold = m_offset + m_step_size * (step_number - (1.0 - factor)); } void update_thresholds(double factor, direction d) noexcept { const auto step_number = static_cast<double>(m_step_number); if (d == direction::up) { m_upthreshold = m_offset + m_step_size * (step_number + (1.0 - factor)); m_downthreshold = m_offset + m_step_size * (step_number - 1.0); } else { m_upthreshold = m_offset + m_step_size * (step_number + 1.0); m_downthreshold = m_offset + m_step_size * (step_number - (1.0 - factor)); } } void init_step_number_and_offset(double value) noexcept { m_step_number = static_cast<int>(std::floor(value / m_step_size)); if (m_zero_init_offset) { m_offset = 0.0; } else { m_offset = value - static_cast<double>(m_step_number) * m_step_size; } } double shift_quanta() { double factor = 0.0; if (oscillating(m_past_length - 1) && ((archive.back().date - archive.front().date) != 0)) { double acc = 0.0; double local_estim; double cnt = 0; auto it_2 = archive.begin(); auto it_0 = it_2++; auto it_1 = it_2++; for (i64 i = 0; i < archive.size() - 2; ++i) { if ((it_2->date - it_0->date) != 0) { if ((archive.back().x_dot * it_1->x_dot) > 0.0) { local_estim = 1 - (it_1->date - it_0->date) / (it_2->date - it_0->date); } else { local_estim = (it_1->date - it_0->date) / (it_2->date - it_0->date); } acc += local_estim; cnt += 1.0; } } acc = acc / cnt; factor = acc; archive.clear(); } return factor; } void store_change(double val, time t) noexcept { archive.emplace_back(val, t); while (archive.size() > m_past_length) archive.pop_front(); } bool oscillating(const int range) noexcept { if ((range + 1) > archive.size()) return false; const i64 limit = archive.size() - range; auto it = --archive.end(); auto next = it--; for (int i = 0; i < limit; ++i, next = it--) if (it->x_dot * next->x_dot > 0) return false; return true; } bool monotonous(const int range) noexcept { if ((range + 1) > archive.size()) return false; auto it = archive.begin(); auto prev = it++; for (int i = 0; i < range; ++i, prev = it++) if ((prev->x_dot * it->x_dot) < 0) return false; return true; } }; template<size_t PortNumber> struct adder { static_assert(PortNumber > 1, "adder model need at least two input port"); port x[PortNumber]; port y[1]; time sigma; double default_values[PortNumber]; double default_input_coeffs[PortNumber]; double values[PortNumber]; double input_coeffs[PortNumber]; adder() noexcept { std::fill_n(std::begin(default_values), PortNumber, 1.0 / static_cast<double>(PortNumber)); std::fill_n(std::begin(default_input_coeffs), PortNumber, 0.0); } status initialize() noexcept { std::copy_n(std::begin(default_values), PortNumber, std::begin(values)); std::copy_n(std::begin(default_input_coeffs), PortNumber, std::begin(input_coeffs)); sigma = time_domain<time>::infinity; return status::success; } status lambda() noexcept { double to_send = 0.0; for (size_t i = 0; i != PortNumber; ++i) to_send += input_coeffs[i] * values[i]; y[0].messages.emplace_front(to_send); return status::success; } status transition(time /*t*/, time /*e*/, time /*r*/) noexcept { bool have_message = false; for (size_t i = 0; i != PortNumber; ++i) { for (const auto& msg : x[i].messages) { values[i] = msg.real[0]; have_message = true; } } sigma = have_message ? time_domain<time>::zero : time_domain<time>::infinity; return status::success; } message observation(const time /*e*/) const noexcept { double ret = 0.0; for (size_t i = 0; i != PortNumber; ++i) ret += input_coeffs[i] * values[i]; return { ret }; } }; template<size_t PortNumber> struct mult { static_assert(PortNumber > 1, "mult model need at least two input port"); port x[PortNumber]; port y[1]; time sigma; double default_values[PortNumber]; double default_input_coeffs[PortNumber]; double values[PortNumber]; double input_coeffs[PortNumber]; mult() noexcept { std::fill_n(std::begin(default_values), PortNumber, 1.0); std::fill_n(std::begin(default_input_coeffs), PortNumber, 0.0); } status initialize() noexcept { std::copy_n(std::begin(default_values), PortNumber, std::begin(values)); std::copy_n(std::begin(default_input_coeffs), PortNumber, std::begin(input_coeffs)); sigma = time_domain<time>::infinity; return status::success; } status lambda() noexcept { double to_send = 1.0; for (size_t i = 0; i != PortNumber; ++i) to_send *= std::pow(values[i], input_coeffs[i]); y[0].messages.emplace_front(to_send); return status::success; } status transition(time /*t*/, time /*e*/, time /*r*/) noexcept { bool have_message = false; for (size_t i = 0; i != PortNumber; ++i) { for (const auto& msg : x[i].messages) { values[i] = msg[0]; have_message = true; } } sigma = have_message ? time_domain<time>::zero : time_domain<time>::infinity; return status::success; } message observation(const time /*e*/) const noexcept { double ret = 1.0; for (size_t i = 0; i != PortNumber; ++i) ret *= std::pow(values[i], input_coeffs[i]); return { ret }; } }; struct counter { port x[1]; time sigma; i64 number; status initialize() noexcept { number = { 0 }; sigma = time_domain<time>::infinity; return status::success; } status transition(time /*t*/, time /*e*/, time /*r*/) noexcept { const auto diff = std::distance(std::begin(x[0].messages), std::end(x[0].messages)); number += static_cast<i64>(diff); return status::success; } message observation(const time /*e*/) const noexcept { return { static_cast<double>(number) }; } }; struct generator { port y[1]; time sigma; double value; simulation* sim = nullptr; double default_offset = 0.0; source default_source_ta; source default_source_value; bool stop_on_error = false; status initialize() noexcept { sigma = default_offset; if (stop_on_error) { irt_return_if_bad(initialize_source(*sim, default_source_ta)); irt_return_if_bad(initialize_source(*sim, default_source_value)); } else { (void)initialize_source(*sim, default_source_ta); (void)initialize_source(*sim, default_source_value); } return status::success; } status transition(time /*t*/, time /*e*/, time /*r*/) noexcept { if (stop_on_error) { irt_return_if_bad(update_source(*sim, default_source_ta, sigma)); irt_return_if_bad(update_source(*sim, default_source_value, value)); } else { if (is_bad(update_source(*sim, default_source_ta, sigma))) sigma = time_domain<time>::infinity; if (is_bad(update_source(*sim, default_source_value, value))) value = 0.0; } return status::success; } status lambda() noexcept { y[0].messages.emplace_front(value); return status::success; } message observation(const time /*e*/) const noexcept { return { value }; } }; struct constant { port y[1]; time sigma; double default_value = 0.0; double value = 0.0; status initialize() noexcept { sigma = time_domain<time>::zero; value = default_value; return status::success; } status transition(time /*t*/, time /*e*/, time /*r*/) noexcept { sigma = time_domain<time>::infinity; return status::success; } status lambda() noexcept { y[0].messages.emplace_front(value); return status::success; } message observation(const time /*e*/) const noexcept { return { value }; } }; struct flow { port y[1]; time sigma; double default_samplerate = 44100.0; double* default_data = nullptr; double* default_sigmas = nullptr; sz default_size = 0u; double accu_sigma; sz i; status initialize() noexcept { irt_return_if_fail(default_samplerate > 0., status::model_flow_bad_samplerate); irt_return_if_fail(default_data != nullptr && default_sigmas != nullptr && default_size > 1, status::model_flow_bad_data); sigma = 1.0 / default_samplerate; accu_sigma = 0.; i = 0; return status::success; } status transition(time t, time /*e*/, time /*r*/) noexcept { for (; i < default_size; ++i) { accu_sigma += default_sigmas[i]; if (accu_sigma > t) { sigma = default_sigmas[i]; return status::success; } } sigma = time_domain<time>::infinity; i = default_size - 1; return status::success; } status lambda() noexcept { y[0].messages.emplace_front(default_data[i]); return status::success; } message observation(const time /*e*/) const noexcept { return { default_data[i] }; } }; template<size_t PortNumber> struct accumulator { port x[2 * PortNumber]; time sigma; double number; double numbers[PortNumber]; status initialize() noexcept { number = 0.0; std::fill_n(numbers, PortNumber, 0.0); sigma = time_domain<time>::infinity; return status::success; } status transition(time /*t*/, time /*e*/, time /*r*/) noexcept { for (size_t i = 0; i != PortNumber; ++i) for (const auto& msg : x[i + PortNumber].messages) numbers[i] = msg[0]; for (size_t i = 0; i != PortNumber; ++i) for (const auto& msg : x[i].messages) if (msg[0] != 0.0) number += numbers[i]; return status::success; } }; struct cross { port x[4]; port y[2]; time sigma; double default_threshold = 0.0; double threshold; double value; double if_value; double else_value; double result; double event; enum port_name { port_value, port_if_value, port_else_value, port_threshold }; status initialize() noexcept { threshold = default_threshold; value = threshold - 1.0; if_value = 0.0; else_value = 0.0; result = 0.0; event = 0.0; sigma = time_domain<time>::zero; return status::success; } status transition(time /*t*/, time /*e*/, time /*r*/) noexcept { bool have_message = false; bool have_message_value = false; event = 0.0; for (const auto& msg : x[port_threshold].messages) { threshold = msg.real[0]; have_message = true; } for (const auto& msg : x[port_value].messages) { value = msg.real[0]; have_message_value = true; have_message = true; } for (const auto& msg : x[port_if_value].messages) { if_value = msg.real[0]; have_message = true; } for (const auto& msg : x[port_else_value].messages) { else_value = msg.real[0]; have_message = true; } if (have_message_value) { event = 0.0; if (value >= threshold) { else_value = if_value; event = 1.0; } } result = else_value; sigma = have_message ? time_domain<time>::zero : time_domain<time>::infinity; return status::success; } status lambda() noexcept { y[0].messages.emplace_front(result); y[1].messages.emplace_front(event); return status::success; } message observation(const time /*e*/) const noexcept { return { value, if_value, else_value }; } }; template<int QssLevel> struct abstract_cross { static_assert(1 <= QssLevel && QssLevel <= 3, "Only for Qss1, 2 and 3"); port x[4]; port y[3]; time sigma; double default_threshold = 0.0; bool default_detect_up = true; double threshold; double if_value[QssLevel]; double else_value[QssLevel]; double value[QssLevel]; double last_reset; bool reach_threshold; bool detect_up; enum port_name { port_value, port_if_value, port_else_value, port_threshold }; enum out_name { o_if_value, o_else_value, o_event }; status initialize() noexcept { std::fill_n(if_value, QssLevel, 0.); std::fill_n(else_value, QssLevel, 0.); std::fill_n(value, QssLevel, 0.); threshold = default_threshold; value[0] = threshold - 1.0; sigma = time_domain<time>::infinity; last_reset = time_domain<time>::infinity; detect_up = default_detect_up; reach_threshold = false; return status::success; } void compute_wake_up() noexcept { if constexpr (QssLevel == 1) { sigma = time_domain<time>::infinity; } if constexpr (QssLevel == 2) { sigma = time_domain<time>::infinity; if (value[1]) { const auto a = value[1]; const auto b = value[0] - threshold; const auto d = -b * a; if (d > 0.) sigma = d; } } if constexpr (QssLevel == 3) { sigma = time_domain<time>::infinity; if (value[1]) { if (value[2]) { const auto a = value[2]; const auto b = value[1]; const auto c = value[0] - threshold; const auto d = b * b - 4. * a * c; if (d > 0.) { const auto x1 = (-b + std::sqrt(d)) / (2. * a); const auto x2 = (-b - std::sqrt(d)) / (2. * a); if (x1 > 0.) { if (x2 > 0.) { sigma = std::min(x1, x2); } else { sigma = x1; } } else { if (x2 > 0) sigma = x2; } } if (d == 0.) { const auto x = -b / (2. * a); if (x > 0.) sigma = x; } } else { const auto a = value[1]; const auto b = value[0] - threshold; const auto d = -b * a; if (d > 0.) sigma = d; } } } } status transition(time t, [[maybe_unused]] time e, time /*r*/) noexcept { auto& p_threshold = x[port_threshold]; auto& p_if_value = x[port_if_value]; auto& p_else_value = x[port_else_value]; auto& p_value = x[port_value]; const auto old_else_value = else_value[0]; for (const auto& msg : p_threshold.messages) threshold = msg[0]; if (p_if_value.messages.empty()) { if constexpr (QssLevel == 2) if_value[0] += if_value[1] * e; if constexpr (QssLevel == 3) { if_value[0] += if_value[1] * e + if_value[2] * e * e; if_value[1] += 2. * if_value[2] * e; } } else { for (const auto& msg : p_if_value.messages) { if_value[0] = msg[0]; if constexpr (QssLevel >= 2) if_value[1] = msg[1]; if constexpr (QssLevel == 3) if_value[2] = msg[2]; } } if (p_else_value.messages.empty()) { if constexpr (QssLevel == 2) else_value[0] += else_value[1] * e; if constexpr (QssLevel == 3) { else_value[0] += else_value[1] * e + else_value[2] * e * e; else_value[1] += 2. * else_value[2] * e; } } else { for (const auto& msg : p_else_value.messages) { else_value[0] = msg[0]; if constexpr (QssLevel >= 2) else_value[1] = msg[1]; if constexpr (QssLevel == 3) else_value[2] = msg[2]; } } if (p_value.messages.empty()) { if constexpr (QssLevel == 2) value[0] += value[1] * e; if constexpr (QssLevel == 3) { value[0] += value[1] * e + value[2] * e * e; value[1] += 2. * value[2] * e; } } else { for (const auto& msg : p_value.messages) { value[0] = msg[0]; if constexpr (QssLevel >= 2) value[1] = msg[1]; if constexpr (QssLevel == 3) value[2] = msg[2]; } } reach_threshold = false; if ((detect_up && value[0] >= threshold) || (!detect_up && value[0] <= threshold)) { if (t != last_reset) { last_reset = t; reach_threshold = true; sigma = time_domain<time>::zero; } else sigma = time_domain<time>::infinity; } else if (old_else_value != else_value[0]) { sigma = time_domain<time>::zero; } else { compute_wake_up(); } return status::success; } status lambda() noexcept { if constexpr (QssLevel == 1) { y[o_else_value].messages.emplace_front(else_value[0]); if (reach_threshold) { y[o_if_value].messages.emplace_front(if_value[0]); y[o_event].messages.emplace_front(1.0); } } if constexpr (QssLevel == 2) { y[o_else_value].messages.emplace_front(else_value[0], else_value[1]); if (reach_threshold) { y[o_if_value].messages.emplace_front(if_value[0], if_value[1]); y[o_event].messages.emplace_front(1.0); } } if constexpr (QssLevel == 3) { y[o_else_value].messages.emplace_front( else_value[0], else_value[1], else_value[2]); if (reach_threshold) { y[o_if_value].messages.emplace_front( if_value[0], if_value[1], if_value[2]); y[o_event].messages.emplace_front(1.0); } } return status::success; } message observation(const time /*t*/) const noexcept { return { value[0], if_value[0], else_value[0] }; } }; using qss1_cross = abstract_cross<1>; using qss2_cross = abstract_cross<2>; using qss3_cross = abstract_cross<3>; inline double sin_time_function(double t) noexcept { const double f0 = 0.1; const double pi = std::acos(-1); return std::sin(2 * pi * f0 * t); } inline double square_time_function(double t) noexcept { return t * t; } inline double time_function(double t) noexcept { return t; } struct time_func { port y[1]; time sigma; double default_sigma = 0.01; double (*default_f)(double) = &time_function; double value; double (*f)(double) = nullptr; status initialize() noexcept { f = default_f; sigma = default_sigma; value = 0.0; return status::success; } status transition(time t, time /*e*/, time /*r*/) noexcept { value = (*f)(t); return status::success; } status lambda() noexcept { y[0].messages.emplace_front(value); return status::success; } message observation(const time /*t*/) const noexcept { return { value }; } }; using adder_2 = adder<2>; using adder_3 = adder<3>; using adder_4 = adder<4>; using mult_2 = mult<2>; using mult_3 = mult<3>; using mult_4 = mult<4>; using accumulator_2 = accumulator<2>; struct queue { port x[1]; port y[1]; time sigma; flat_double_list<dated_message> queue; double default_ta = 1.0; status initialize() noexcept { if (default_ta <= 0) irt_bad_return(status::model_queue_bad_ta); if (!queue.get_allocator()) irt_bad_return(status::model_queue_empty_allocator); sigma = time_domain<time>::infinity; queue.clear(); return status::success; } status transition(time t, time /*e*/, time /*r*/) noexcept { while (!queue.empty() && queue.front().real[0] <= t) queue.pop_front(); for (const auto& msg : x[0].messages) { if (!queue.get_allocator()->can_alloc(1u)) irt_bad_return(status::model_queue_full); queue.emplace_back(t + default_ta, msg[0], msg[1], msg[2], msg[3]); } if (!queue.empty()) { sigma = queue.front().real[0] - t; sigma = sigma <= 0. ? 0. : sigma; } else { sigma = time_domain<time>::infinity; } return status::success; } status lambda() noexcept { if (!queue.empty()) { auto it = queue.begin(); auto end = queue.end(); const auto t = it->real[0]; for (; it != end && it->real[0] <= t; ++it) y[0].messages.emplace_front( it->real[1], it->real[2], it->real[3], it->real[4]); } return status::success; } }; struct dynamic_queue { port x[1]; port y[1]; time sigma; flat_double_list<dated_message> queue; simulation* sim = nullptr; source default_source_ta; bool stop_on_error = false; status initialize() noexcept { sigma = time_domain<time>::infinity; queue.clear(); if (stop_on_error) irt_return_if_bad(initialize_source(*sim, default_source_ta)); else (void)initialize_source(*sim, default_source_ta); return status::success; } status transition(time t, time /*e*/, time /*r*/) noexcept { while (!queue.empty() && queue.front().real[0] <= t) queue.pop_front(); for (const auto& msg : x[0].messages) { if (!queue.get_allocator()->can_alloc(1u)) irt_bad_return(status::model_dynamic_queue_full); double ta; if (stop_on_error) { irt_return_if_bad(update_source(*sim, default_source_ta, ta)); queue.emplace_back(t + ta, msg[0], msg[1], msg[2], msg[3]); } else { if (is_success(update_source(*sim, default_source_ta, ta))) queue.emplace_back(t + ta, msg[0], msg[1], msg[2], msg[3]); } } if (!queue.empty()) { sigma = queue.front().real[0] - t; sigma = sigma <= 0. ? 0. : sigma; } else { sigma = time_domain<time>::infinity; } return status::success; } status lambda() noexcept { if (!queue.empty()) { auto it = queue.begin(); auto end = queue.end(); const auto t = it->real[0]; for (; it != end && it->real[0] <= t; ++it) y[0].messages.emplace_front( it->real[1], it->real[2], it->real[3], it->real[4]); } return status::success; } }; struct priority_queue { port x[1]; port y[1]; time sigma; flat_double_list<dated_message> queue; double default_ta = 1.0; simulation* sim = nullptr; source default_source_ta; bool stop_on_error = false; private: status try_to_insert(const time t, const message& msg) noexcept { if (!queue.get_allocator()->can_alloc(1u)) irt_bad_return(status::model_priority_queue_source_is_null); if (queue.empty() || queue.begin()->real[0] > t) { queue.emplace_front(t, msg[0], msg[1], msg[2], msg[3]); } else { auto it = queue.begin(); auto end = queue.end(); ++it; for (; it != end; ++it) { if (it->real[0] > t) { queue.emplace(it, t, msg[0], msg[1], msg[2], msg[3]); return status::success; } } } return status::success; } public: status initialize() noexcept { if (!queue.get_allocator()) irt_bad_return(status::model_priority_queue_empty_allocator); if (stop_on_error) irt_return_if_bad(initialize_source(*sim, default_source_ta)); else (void)initialize_source(*sim, default_source_ta); sigma = time_domain<time>::infinity; queue.clear(); return status::success; } status transition(time t, time /*e*/, time /*r*/) noexcept { while (!queue.empty() && queue.front().real[0] <= t) queue.pop_front(); for (const auto& msg : x[0].messages) { double value; if (stop_on_error) { irt_return_if_bad( update_source(*sim, default_source_ta, value)); if (auto ret = try_to_insert(value + t, msg); is_bad(ret)) irt_bad_return(status::model_priority_queue_full); } else { if (is_success(update_source(*sim, default_source_ta, value))) { if (auto ret = try_to_insert(value + t, msg); is_bad(ret)) irt_bad_return(status::model_priority_queue_full); } } } if (!queue.empty()) { sigma = queue.front().real[0] - t; sigma = sigma <= 0. ? 0. : sigma; } else { sigma = time_domain<time>::infinity; } return status::success; } status lambda() noexcept { if (!queue.empty()) { auto it = queue.begin(); auto end = queue.end(); const auto t = it->real[0]; for (; it != end && it->real[0] <= t; ++it) y[0].messages.emplace_front( it->real[1], it->real[2], it->real[3], it->real[4]); } return status::success; } }; constexpr sz max(sz a) { return a; } template<typename... Args> constexpr sz max(sz a, Args... args) { return std::max(max(args...), a); } constexpr sz max_size_in_bytes() noexcept { return max(sizeof(none), sizeof(qss1_integrator), sizeof(qss1_multiplier), sizeof(qss1_cross), sizeof(qss1_power), sizeof(qss1_square), sizeof(qss1_sum_2), sizeof(qss1_sum_3), sizeof(qss1_sum_4), sizeof(qss1_wsum_2), sizeof(qss1_wsum_3), sizeof(qss1_wsum_4), sizeof(qss2_integrator), sizeof(qss2_multiplier), sizeof(qss2_cross), sizeof(qss2_power), sizeof(qss2_square), sizeof(qss2_sum_2), sizeof(qss2_sum_3), sizeof(qss2_sum_4), sizeof(qss2_wsum_2), sizeof(qss2_wsum_3), sizeof(qss2_wsum_4), sizeof(qss3_integrator), sizeof(qss3_multiplier), sizeof(qss3_cross), sizeof(qss3_power), sizeof(qss3_square), sizeof(qss3_sum_2), sizeof(qss3_sum_3), sizeof(qss3_sum_4), sizeof(qss3_wsum_2), sizeof(qss3_wsum_3), sizeof(qss3_wsum_4), sizeof(integrator), sizeof(quantifier), sizeof(adder_2), sizeof(adder_3), sizeof(adder_4), sizeof(mult_2), sizeof(mult_3), sizeof(mult_4), sizeof(counter), sizeof(queue), sizeof(dynamic_queue), sizeof(priority_queue), sizeof(generator), sizeof(constant), sizeof(cross), sizeof(time_func), sizeof(accumulator_2), sizeof(flow)); } struct model { double tl = 0.0; double tn = time_domain<time>::infinity; heap::handle handle = nullptr; observer_id obs_id = observer_id{ 0 }; dynamics_type type{ dynamics_type::none }; std::byte dyn[max_size_in_bytes()]; }; /***************************************************************************** * * scheduller * ****************************************************************************/ class scheduller { private: using list = flat_list<model_id>; using allocator = typename list::allocator_type; allocator m_list_allocator; list m_list; heap m_heap; public: scheduller() = default; status init(size_t capacity) noexcept { irt_return_if_bad(m_heap.init(capacity)); irt_return_if_bad(m_list_allocator.init(capacity)); m_list.set_allocator(&m_list_allocator); return status::success; } void clear() { m_heap.clear(); m_list.clear(); } /** * @brief Insert a newly model into the scheduller. */ void insert(model& mdl, model_id id, time tn) noexcept { irt_assert(mdl.handle == nullptr); mdl.handle = m_heap.insert(tn, id); } /** * @brief Reintegrate or reinsert an old popped model into the * scheduller. */ void reintegrate(model& mdl, time tn) noexcept { irt_assert(mdl.handle != nullptr); mdl.handle->tn = tn; m_heap.insert(mdl.handle); } void erase(model& mdl) noexcept { if (mdl.handle) { m_heap.remove(mdl.handle); m_heap.destroy(mdl.handle); mdl.handle = nullptr; } } void update(model& mdl, time tn) noexcept { irt_assert(mdl.handle != nullptr); mdl.handle->tn = tn; irt_assert(tn <= mdl.tn); if (tn < mdl.tn) m_heap.decrease(mdl.handle); else if (tn > mdl.tn) m_heap.increase(mdl.handle); } const list& pop() noexcept { time t = tn(); m_list.clear(); m_list.emplace_front(m_heap.pop()->id); while (!m_heap.empty() && t == tn()) m_list.emplace_front(m_heap.pop()->id); return m_list; } const list& list_model_id() const noexcept { return m_list; } time tn() const noexcept { return m_heap.top()->tn; } bool empty() const noexcept { return m_heap.empty(); } size_t size() const noexcept { return m_heap.size(); } }; /***************************************************************************** * * simulation * ****************************************************************************/ template<typename Dynamics> static constexpr dynamics_type dynamics_typeof() noexcept { if constexpr (std::is_same_v<Dynamics, none>) return dynamics_type::none; if constexpr (std::is_same_v<Dynamics, qss1_integrator>) return dynamics_type::qss1_integrator; if constexpr (std::is_same_v<Dynamics, qss1_multiplier>) return dynamics_type::qss1_multiplier; if constexpr (std::is_same_v<Dynamics, qss1_cross>) return dynamics_type::qss1_cross; if constexpr (std::is_same_v<Dynamics, qss1_power>) return dynamics_type::qss1_power; if constexpr (std::is_same_v<Dynamics, qss1_square>) return dynamics_type::qss1_square; if constexpr (std::is_same_v<Dynamics, qss1_sum_2>) return dynamics_type::qss1_sum_2; if constexpr (std::is_same_v<Dynamics, qss1_sum_3>) return dynamics_type::qss1_sum_3; if constexpr (std::is_same_v<Dynamics, qss1_sum_4>) return dynamics_type::qss1_sum_4; if constexpr (std::is_same_v<Dynamics, qss1_wsum_2>) return dynamics_type::qss1_wsum_2; if constexpr (std::is_same_v<Dynamics, qss1_wsum_3>) return dynamics_type::qss1_wsum_3; if constexpr (std::is_same_v<Dynamics, qss1_wsum_4>) return dynamics_type::qss1_wsum_4; if constexpr (std::is_same_v<Dynamics, qss2_integrator>) return dynamics_type::qss2_integrator; if constexpr (std::is_same_v<Dynamics, qss2_multiplier>) return dynamics_type::qss2_multiplier; if constexpr (std::is_same_v<Dynamics, qss2_cross>) return dynamics_type::qss2_cross; if constexpr (std::is_same_v<Dynamics, qss2_power>) return dynamics_type::qss2_power; if constexpr (std::is_same_v<Dynamics, qss2_square>) return dynamics_type::qss2_square; if constexpr (std::is_same_v<Dynamics, qss2_sum_2>) return dynamics_type::qss2_sum_2; if constexpr (std::is_same_v<Dynamics, qss2_sum_3>) return dynamics_type::qss2_sum_3; if constexpr (std::is_same_v<Dynamics, qss2_sum_4>) return dynamics_type::qss2_sum_4; if constexpr (std::is_same_v<Dynamics, qss2_wsum_2>) return dynamics_type::qss2_wsum_2; if constexpr (std::is_same_v<Dynamics, qss2_wsum_3>) return dynamics_type::qss2_wsum_3; if constexpr (std::is_same_v<Dynamics, qss2_wsum_4>) return dynamics_type::qss2_wsum_4; if constexpr (std::is_same_v<Dynamics, qss3_integrator>) return dynamics_type::qss3_integrator; if constexpr (std::is_same_v<Dynamics, qss3_multiplier>) return dynamics_type::qss3_multiplier; if constexpr (std::is_same_v<Dynamics, qss3_cross>) return dynamics_type::qss3_cross; if constexpr (std::is_same_v<Dynamics, qss3_power>) return dynamics_type::qss3_power; if constexpr (std::is_same_v<Dynamics, qss3_square>) return dynamics_type::qss3_square; if constexpr (std::is_same_v<Dynamics, qss3_sum_2>) return dynamics_type::qss3_sum_2; if constexpr (std::is_same_v<Dynamics, qss3_sum_3>) return dynamics_type::qss3_sum_3; if constexpr (std::is_same_v<Dynamics, qss3_sum_4>) return dynamics_type::qss3_sum_4; if constexpr (std::is_same_v<Dynamics, qss3_wsum_2>) return dynamics_type::qss3_wsum_2; if constexpr (std::is_same_v<Dynamics, qss3_wsum_3>) return dynamics_type::qss3_wsum_3; if constexpr (std::is_same_v<Dynamics, qss3_wsum_4>) return dynamics_type::qss3_wsum_4; if constexpr (std::is_same_v<Dynamics, integrator>) return dynamics_type::integrator; if constexpr (std::is_same_v<Dynamics, quantifier>) return dynamics_type::quantifier; if constexpr (std::is_same_v<Dynamics, adder_2>) return dynamics_type::adder_2; if constexpr (std::is_same_v<Dynamics, adder_3>) return dynamics_type::adder_3; if constexpr (std::is_same_v<Dynamics, adder_4>) return dynamics_type::adder_4; if constexpr (std::is_same_v<Dynamics, mult_2>) return dynamics_type::mult_2; if constexpr (std::is_same_v<Dynamics, mult_3>) return dynamics_type::mult_3; if constexpr (std::is_same_v<Dynamics, mult_4>) return dynamics_type::mult_4; if constexpr (std::is_same_v<Dynamics, counter>) return dynamics_type::counter; if constexpr (std::is_same_v<Dynamics, queue>) return dynamics_type::queue; if constexpr (std::is_same_v<Dynamics, dynamic_queue>) return dynamics_type::dynamic_queue; if constexpr (std::is_same_v<Dynamics, priority_queue>) return dynamics_type::priority_queue; if constexpr (std::is_same_v<Dynamics, generator>) return dynamics_type::generator; if constexpr (std::is_same_v<Dynamics, constant>) return dynamics_type::constant; if constexpr (std::is_same_v<Dynamics, cross>) return dynamics_type::cross; if constexpr (std::is_same_v<Dynamics, time_func>) return dynamics_type::time_func; if constexpr (std::is_same_v<Dynamics, accumulator_2>) return dynamics_type::accumulator_2; if constexpr (std::is_same_v<Dynamics, flow>) return dynamics_type::flow; return dynamics_type::none; } template<typename Dynamics> Dynamics& get_dyn(model& mdl) noexcept { irt_assert(dynamics_typeof<Dynamics>() == mdl.type); return *reinterpret_cast<Dynamics*>(&mdl.dyn); } template<typename Dynamics> const Dynamics& get_dyn(const model& mdl) noexcept { irt_assert(dynamics_typeof<Dynamics>() == mdl.type); return *reinterpret_cast<const Dynamics*>(&mdl.dyn); } template<typename Dynamics> constexpr const model& get_model(const Dynamics& d) noexcept { const Dynamics* __mptr = &d; return *(const model*)((const char*)__mptr - offsetof(model, dyn)); } template<typename Dynamics> constexpr model& get_model(Dynamics& d) noexcept { Dynamics* __mptr = &d; return *(model*)((char*)__mptr - offsetof(model, dyn)); } struct simulation { flat_list<model_id>::allocator_type model_list_allocator; flat_list<message>::allocator_type message_list_allocator; shared_flat_list<node>::allocator_type node_list_allocator; flat_list<port*>::allocator_type emitting_output_port_allocator; flat_double_list<dated_message>::allocator_type dated_message_allocator; flat_double_list<record>::allocator_type flat_double_list_shared_allocator; data_array<model, model_id> models; data_array<message, message_id> messages; data_array<observer, observer_id> observers; scheduller sched; /** * @brief Use initialize, generate or finalize data from a source. * * See the @c external_source class for an implementation. */ function_ref<status(source&, const source::operation_type)> source_dispatch; time begin = time_domain<time>::zero; time end = time_domain<time>::infinity; template<typename Dynamics> constexpr model_id get_id(const Dynamics& dyn) const { return models.get_id(get_model(dyn)); } template<typename Function, typename... Args> constexpr auto dispatch(model& mdl, Function&& f, Args... args) noexcept { switch (mdl.type) { case dynamics_type::none: return f(*reinterpret_cast<none*>(&mdl.dyn), args...); case dynamics_type::qss1_integrator: return f(*reinterpret_cast<qss1_integrator*>(&mdl.dyn), args...); case dynamics_type::qss1_multiplier: return f(*reinterpret_cast<qss1_multiplier*>(&mdl.dyn), args...); case dynamics_type::qss1_cross: return f(*reinterpret_cast<qss1_cross*>(&mdl.dyn), args...); case dynamics_type::qss1_power: return f(*reinterpret_cast<qss1_power*>(&mdl.dyn), args...); case dynamics_type::qss1_square: return f(*reinterpret_cast<qss1_square*>(&mdl.dyn), args...); case dynamics_type::qss1_sum_2: return f(*reinterpret_cast<qss1_sum_2*>(&mdl.dyn), args...); case dynamics_type::qss1_sum_3: return f(*reinterpret_cast<qss1_sum_3*>(&mdl.dyn), args...); case dynamics_type::qss1_sum_4: return f(*reinterpret_cast<qss1_sum_4*>(&mdl.dyn), args...); case dynamics_type::qss1_wsum_2: return f(*reinterpret_cast<qss1_wsum_2*>(&mdl.dyn), args...); case dynamics_type::qss1_wsum_3: return f(*reinterpret_cast<qss1_wsum_3*>(&mdl.dyn), args...); case dynamics_type::qss1_wsum_4: return f(*reinterpret_cast<qss1_wsum_4*>(&mdl.dyn), args...); case dynamics_type::qss2_integrator: return f(*reinterpret_cast<qss2_integrator*>(&mdl.dyn), args...); case dynamics_type::qss2_multiplier: return f(*reinterpret_cast<qss2_multiplier*>(&mdl.dyn), args...); case dynamics_type::qss2_cross: return f(*reinterpret_cast<qss2_cross*>(&mdl.dyn), args...); case dynamics_type::qss2_power: return f(*reinterpret_cast<qss2_power*>(&mdl.dyn), args...); case dynamics_type::qss2_square: return f(*reinterpret_cast<qss2_square*>(&mdl.dyn), args...); case dynamics_type::qss2_sum_2: return f(*reinterpret_cast<qss2_sum_2*>(&mdl.dyn), args...); case dynamics_type::qss2_sum_3: return f(*reinterpret_cast<qss2_sum_3*>(&mdl.dyn), args...); case dynamics_type::qss2_sum_4: return f(*reinterpret_cast<qss2_sum_4*>(&mdl.dyn), args...); case dynamics_type::qss2_wsum_2: return f(*reinterpret_cast<qss2_wsum_2*>(&mdl.dyn), args...); case dynamics_type::qss2_wsum_3: return f(*reinterpret_cast<qss2_wsum_3*>(&mdl.dyn), args...); case dynamics_type::qss2_wsum_4: return f(*reinterpret_cast<qss2_wsum_4*>(&mdl.dyn), args...); case dynamics_type::qss3_integrator: return f(*reinterpret_cast<qss3_integrator*>(&mdl.dyn), args...); case dynamics_type::qss3_multiplier: return f(*reinterpret_cast<qss3_multiplier*>(&mdl.dyn), args...); case dynamics_type::qss3_cross: return f(*reinterpret_cast<qss3_cross*>(&mdl.dyn), args...); case dynamics_type::qss3_power: return f(*reinterpret_cast<qss3_power*>(&mdl.dyn), args...); case dynamics_type::qss3_square: return f(*reinterpret_cast<qss3_square*>(&mdl.dyn), args...); case dynamics_type::qss3_sum_2: return f(*reinterpret_cast<qss3_sum_2*>(&mdl.dyn), args...); case dynamics_type::qss3_sum_3: return f(*reinterpret_cast<qss3_sum_3*>(&mdl.dyn), args...); case dynamics_type::qss3_sum_4: return f(*reinterpret_cast<qss3_sum_4*>(&mdl.dyn), args...); case dynamics_type::qss3_wsum_2: return f(*reinterpret_cast<qss3_wsum_2*>(&mdl.dyn), args...); case dynamics_type::qss3_wsum_3: return f(*reinterpret_cast<qss3_wsum_3*>(&mdl.dyn), args...); case dynamics_type::qss3_wsum_4: return f(*reinterpret_cast<qss3_wsum_4*>(&mdl.dyn), args...); case dynamics_type::integrator: return f(*reinterpret_cast<integrator*>(&mdl.dyn), args...); case dynamics_type::quantifier: return f(*reinterpret_cast<quantifier*>(&mdl.dyn), args...); case dynamics_type::adder_2: return f(*reinterpret_cast<adder_2*>(&mdl.dyn), args...); case dynamics_type::adder_3: return f(*reinterpret_cast<adder_3*>(&mdl.dyn), args...); case dynamics_type::adder_4: return f(*reinterpret_cast<adder_4*>(&mdl.dyn), args...); case dynamics_type::mult_2: return f(*reinterpret_cast<mult_2*>(&mdl.dyn), args...); case dynamics_type::mult_3: return f(*reinterpret_cast<mult_3*>(&mdl.dyn), args...); case dynamics_type::mult_4: return f(*reinterpret_cast<mult_4*>(&mdl.dyn), args...); case dynamics_type::counter: return f(*reinterpret_cast<counter*>(&mdl.dyn), args...); case dynamics_type::queue: return f(*reinterpret_cast<queue*>(&mdl.dyn), args...); case dynamics_type::dynamic_queue: return f(*reinterpret_cast<dynamic_queue*>(&mdl.dyn), args...); case dynamics_type::priority_queue: return f(*reinterpret_cast<priority_queue*>(&mdl.dyn), args...); case dynamics_type::generator: return f(*reinterpret_cast<generator*>(&mdl.dyn), args...); case dynamics_type::constant: return f(*reinterpret_cast<constant*>(&mdl.dyn), args...); case dynamics_type::cross: return f(*reinterpret_cast<cross*>(&mdl.dyn), args...); case dynamics_type::accumulator_2: return f(*reinterpret_cast<accumulator_2*>(&mdl.dyn), args...); case dynamics_type::time_func: return f(*reinterpret_cast<time_func*>(&mdl.dyn), args...); case dynamics_type::flow: return f(*reinterpret_cast<flow*>(&mdl.dyn), args...); } irt_unreachable(); } template<typename Function, typename... Args> constexpr auto dispatch(const model& mdl, Function&& f, Args... args) const noexcept { switch (mdl.type) { case dynamics_type::none: return f(*reinterpret_cast<const none*>(&mdl.dyn), args...); case dynamics_type::qss1_integrator: return f(*reinterpret_cast<const qss1_integrator*>(&mdl.dyn), args...); case dynamics_type::qss1_multiplier: return f(*reinterpret_cast<const qss1_multiplier*>(&mdl.dyn), args...); case dynamics_type::qss1_cross: return f(*reinterpret_cast<const qss1_cross*>(&mdl.dyn), args...); case dynamics_type::qss1_power: return f(*reinterpret_cast<const qss1_power*>(&mdl.dyn), args...); case dynamics_type::qss1_square: return f(*reinterpret_cast<const qss1_square*>(&mdl.dyn), args...); case dynamics_type::qss1_sum_2: return f(*reinterpret_cast<const qss1_sum_2*>(&mdl.dyn), args...); case dynamics_type::qss1_sum_3: return f(*reinterpret_cast<const qss1_sum_3*>(&mdl.dyn), args...); case dynamics_type::qss1_sum_4: return f(*reinterpret_cast<const qss1_sum_4*>(&mdl.dyn), args...); case dynamics_type::qss1_wsum_2: return f(*reinterpret_cast<const qss1_wsum_2*>(&mdl.dyn), args...); case dynamics_type::qss1_wsum_3: return f(*reinterpret_cast<const qss1_wsum_3*>(&mdl.dyn), args...); case dynamics_type::qss1_wsum_4: return f(*reinterpret_cast<const qss1_wsum_4*>(&mdl.dyn), args...); case dynamics_type::qss2_integrator: return f(*reinterpret_cast<const qss2_integrator*>(&mdl.dyn), args...); case dynamics_type::qss2_multiplier: return f(*reinterpret_cast<const qss2_multiplier*>(&mdl.dyn), args...); case dynamics_type::qss2_cross: return f(*reinterpret_cast<const qss2_cross*>(&mdl.dyn), args...); case dynamics_type::qss2_power: return f(*reinterpret_cast<const qss2_power*>(&mdl.dyn), args...); case dynamics_type::qss2_square: return f(*reinterpret_cast<const qss2_square*>(&mdl.dyn), args...); case dynamics_type::qss2_sum_2: return f(*reinterpret_cast<const qss2_sum_2*>(&mdl.dyn), args...); case dynamics_type::qss2_sum_3: return f(*reinterpret_cast<const qss2_sum_3*>(&mdl.dyn), args...); case dynamics_type::qss2_sum_4: return f(*reinterpret_cast<const qss2_sum_4*>(&mdl.dyn), args...); case dynamics_type::qss2_wsum_2: return f(*reinterpret_cast<const qss2_wsum_2*>(&mdl.dyn), args...); case dynamics_type::qss2_wsum_3: return f(*reinterpret_cast<const qss2_wsum_3*>(&mdl.dyn), args...); case dynamics_type::qss2_wsum_4: return f(*reinterpret_cast<const qss2_wsum_4*>(&mdl.dyn), args...); case dynamics_type::qss3_integrator: return f(*reinterpret_cast<const qss3_integrator*>(&mdl.dyn), args...); case dynamics_type::qss3_multiplier: return f(*reinterpret_cast<const qss3_multiplier*>(&mdl.dyn), args...); case dynamics_type::qss3_cross: return f(*reinterpret_cast<const qss3_cross*>(&mdl.dyn), args...); case dynamics_type::qss3_power: return f(*reinterpret_cast<const qss3_power*>(&mdl.dyn), args...); case dynamics_type::qss3_square: return f(*reinterpret_cast<const qss3_square*>(&mdl.dyn), args...); case dynamics_type::qss3_sum_2: return f(*reinterpret_cast<const qss3_sum_2*>(&mdl.dyn), args...); case dynamics_type::qss3_sum_3: return f(*reinterpret_cast<const qss3_sum_3*>(&mdl.dyn), args...); case dynamics_type::qss3_sum_4: return f(*reinterpret_cast<const qss3_sum_4*>(&mdl.dyn), args...); case dynamics_type::qss3_wsum_2: return f(*reinterpret_cast<const qss3_wsum_2*>(&mdl.dyn), args...); case dynamics_type::qss3_wsum_3: return f(*reinterpret_cast<const qss3_wsum_3*>(&mdl.dyn), args...); case dynamics_type::qss3_wsum_4: return f(*reinterpret_cast<const qss3_wsum_4*>(&mdl.dyn), args...); case dynamics_type::integrator: return f(*reinterpret_cast<const integrator*>(&mdl.dyn), args...); case dynamics_type::quantifier: return f(*reinterpret_cast<const quantifier*>(&mdl.dyn), args...); case dynamics_type::adder_2: return f(*reinterpret_cast<const adder_2*>(&mdl.dyn), args...); case dynamics_type::adder_3: return f(*reinterpret_cast<const adder_3*>(&mdl.dyn), args...); case dynamics_type::adder_4: return f(*reinterpret_cast<const adder_4*>(&mdl.dyn), args...); case dynamics_type::mult_2: return f(*reinterpret_cast<const mult_2*>(&mdl.dyn), args...); case dynamics_type::mult_3: return f(*reinterpret_cast<const mult_3*>(&mdl.dyn), args...); case dynamics_type::mult_4: return f(*reinterpret_cast<const mult_4*>(&mdl.dyn), args...); case dynamics_type::counter: return f(*reinterpret_cast<const counter*>(&mdl.dyn), args...); case dynamics_type::queue: return f(*reinterpret_cast<const queue*>(&mdl.dyn), args...); case dynamics_type::dynamic_queue: return f(*reinterpret_cast<const dynamic_queue*>(&mdl.dyn), args...); case dynamics_type::priority_queue: return f(*reinterpret_cast<const priority_queue*>(&mdl.dyn), args...); case dynamics_type::generator: return f(*reinterpret_cast<const generator*>(&mdl.dyn), args...); case dynamics_type::constant: return f(*reinterpret_cast<const constant*>(&mdl.dyn), args...); case dynamics_type::cross: return f(*reinterpret_cast<const cross*>(&mdl.dyn), args...); case dynamics_type::accumulator_2: return f(*reinterpret_cast<const accumulator_2*>(&mdl.dyn), args...); case dynamics_type::time_func: return f(*reinterpret_cast<const time_func*>(&mdl.dyn), args...); case dynamics_type::flow: return f(*reinterpret_cast<const flow*>(&mdl.dyn), args...); } irt_unreachable(); } public: status init(size_t model_capacity, size_t messages_capacity) { constexpr size_t ten{ 10 }; irt_return_if_bad(model_list_allocator.init(model_capacity * ten)); irt_return_if_bad(message_list_allocator.init(messages_capacity * ten)); irt_return_if_bad(node_list_allocator.init(model_capacity * ten)); irt_return_if_bad(dated_message_allocator.init(model_capacity * ten * ten)); irt_return_if_bad(emitting_output_port_allocator.init(model_capacity)); irt_return_if_bad(sched.init(model_capacity)); irt_return_if_bad(models.init(model_capacity)); irt_return_if_bad(messages.init(messages_capacity)); irt_return_if_bad(observers.init(model_capacity)); irt_return_if_bad( flat_double_list_shared_allocator.init(model_capacity * ten)); return status::success; } bool can_alloc() const noexcept { return models.can_alloc(); } bool can_alloc(size_t place) const noexcept { return models.can_alloc(place); } /** * @brief cleanup simulation object * * Clean scheduller and input/output port from message. */ void clean() noexcept { sched.clear(); model* mdl = nullptr; while (models.next(mdl)) { dispatch( *mdl, []<typename Dynamics>([[maybe_unused]] Dynamics& dyn) -> void { if constexpr (is_detected_v<has_input_port_t, Dynamics>) { for (sz i = 0; i < std::size(dyn.x); ++i) dyn.x[i].messages.clear(); } if constexpr (is_detected_v<has_output_port_t, Dynamics>) { for (sz i = 0; i < std::size(dyn.y); ++i) dyn.y[i].messages.clear(); } }); } } /** * @brief cleanup simulation and destroy all models and connections */ void clear() noexcept { clean(); model_list_allocator.reset(); message_list_allocator.reset(); node_list_allocator.reset(); dated_message_allocator.reset(); emitting_output_port_allocator.reset(); models.clear(); messages.clear(); observers.clear(); begin = time_domain<time>::zero; end = time_domain<time>::infinity; } /** @brief This function allocates dynamics and models. * */ template<typename Dynamics> Dynamics& alloc() noexcept { /* Use can_alloc before using this function. */ irt_assert(!models.full()); auto& mdl = models.alloc(); mdl.type = dynamics_typeof<Dynamics>(); mdl.handle = nullptr; new (&mdl.dyn) Dynamics{}; Dynamics& dyn = get_dyn<Dynamics>(mdl); if constexpr (std::is_same_v<Dynamics, integrator>) dyn.archive.set_allocator(&flat_double_list_shared_allocator); if constexpr (std::is_same_v<Dynamics, quantifier>) dyn.archive.set_allocator(&flat_double_list_shared_allocator); if constexpr (is_detected_v<has_input_port_t, Dynamics>) { for (size_t i = 0, e = std::size(dyn.x); i != e; ++i) { dyn.x[i].messages.set_allocator(&message_list_allocator); } } if constexpr (is_detected_v<has_output_port_t, Dynamics>) { for (size_t i = 0, e = std::size(dyn.y); i != e; ++i) { dyn.y[i].messages.set_allocator(&message_list_allocator); } } return dyn; } /** @brief This function allocates dynamics and models. * */ model& alloc(dynamics_type type) noexcept { /* Use can_alloc before using this function. */ irt_assert(!models.full()); auto& mdl = models.alloc(); mdl.type = type; mdl.handle = nullptr; dispatch(mdl, [this]<typename Dynamics>(Dynamics& dyn) -> void { new (&dyn) Dynamics{}; if constexpr (std::is_same_v<Dynamics, integrator>) dyn.archive.set_allocator(&flat_double_list_shared_allocator); if constexpr (std::is_same_v<Dynamics, quantifier>) dyn.archive.set_allocator(&flat_double_list_shared_allocator); if constexpr (is_detected_v<has_input_port_t, Dynamics>) { for (size_t i = 0, e = std::size(dyn.x); i != e; ++i) { dyn.x[i].messages.set_allocator(&message_list_allocator); } } if constexpr (is_detected_v<has_output_port_t, Dynamics>) { for (size_t i = 0, e = std::size(dyn.y); i != e; ++i) { dyn.y[i].messages.set_allocator(&message_list_allocator); } } }); return mdl; } void observe(model& mdl, observer& obs) noexcept { mdl.obs_id = observers.get_id(obs); obs.model = models.get_id(mdl); } status deallocate(model_id id) { auto* mdl = models.try_to_get(id); irt_return_if_fail(mdl, status::unknown_dynamics); if (auto* obs = observers.try_to_get(mdl->obs_id); obs) { obs->model = static_cast<model_id>(0); mdl->obs_id = static_cast<observer_id>(0); observers.free(*obs); } dispatch(*mdl, [this]<typename Dynamics>(Dynamics& dyn) { this->do_deallocate<Dynamics>(dyn); }); sched.erase(*mdl); models.free(*mdl); return status::success; } template<typename Dynamics> void do_deallocate(Dynamics& dyn) noexcept { if constexpr (is_detected_v<has_output_port_t, Dynamics>) { auto& mdl_src = get_model(dyn); for (int i = 0, e = (int)std::size(dyn.y); i != e; ++i) { while (!dyn.y[i].connections.empty()) { auto* mdl_dst = models.try_to_get(dyn.y[i].connections.front().model); if (mdl_dst) { disconnect(mdl_src, i, *mdl_dst, dyn.y[i].connections.front().port_index); } } dyn.y[i].connections.clear(node_list_allocator); dyn.y[i].messages.clear(); } } if constexpr (is_detected_v<has_input_port_t, Dynamics>) { auto& mdl_dst = get_model(dyn); for (int i = 0, e = (int)std::size(dyn.x); i != e; ++i) { while (!dyn.x[i].connections.empty()) { auto* mdl_src = models.try_to_get(dyn.x[i].connections.front().model); if (mdl_src) { disconnect(*mdl_src, dyn.x[i].connections.front().port_index, mdl_dst, i); } } dyn.x[i].connections.clear(node_list_allocator); dyn.x[i].messages.clear(); } } dyn.~Dynamics(); } bool is_ports_compatible(const model& mdl_src, [[maybe_unused]] const int o_port_index, const model& mdl_dst, const int i_port_index) const noexcept { if (&mdl_src == &mdl_dst) return false; switch (mdl_src.type) { case dynamics_type::none: return false; case dynamics_type::quantifier: if (mdl_dst.type == dynamics_type::integrator && i_port_index == static_cast<int>(integrator::port_name::port_quanta)) return true; return false; case dynamics_type::qss1_integrator: case dynamics_type::qss1_multiplier: case dynamics_type::qss1_cross: case dynamics_type::qss1_power: case dynamics_type::qss1_square: case dynamics_type::qss1_sum_2: case dynamics_type::qss1_sum_3: case dynamics_type::qss1_sum_4: case dynamics_type::qss1_wsum_2: case dynamics_type::qss1_wsum_3: case dynamics_type::qss1_wsum_4: case dynamics_type::qss2_integrator: case dynamics_type::qss2_multiplier: case dynamics_type::qss2_cross: case dynamics_type::qss2_power: case dynamics_type::qss2_square: case dynamics_type::qss2_sum_2: case dynamics_type::qss2_sum_3: case dynamics_type::qss2_sum_4: case dynamics_type::qss2_wsum_2: case dynamics_type::qss2_wsum_3: case dynamics_type::qss2_wsum_4: case dynamics_type::qss3_integrator: case dynamics_type::qss3_multiplier: case dynamics_type::qss3_cross: case dynamics_type::qss3_power: case dynamics_type::qss3_square: case dynamics_type::qss3_sum_2: case dynamics_type::qss3_sum_3: case dynamics_type::qss3_sum_4: case dynamics_type::qss3_wsum_2: case dynamics_type::qss3_wsum_3: case dynamics_type::qss3_wsum_4: case dynamics_type::integrator: case dynamics_type::adder_2: case dynamics_type::adder_3: case dynamics_type::adder_4: case dynamics_type::mult_2: case dynamics_type::mult_3: case dynamics_type::mult_4: case dynamics_type::counter: case dynamics_type::queue: case dynamics_type::dynamic_queue: case dynamics_type::priority_queue: case dynamics_type::generator: case dynamics_type::constant: case dynamics_type::cross: case dynamics_type::time_func: case dynamics_type::flow: case dynamics_type::accumulator_2: if (mdl_dst.type == dynamics_type::integrator && i_port_index == static_cast<int>(integrator::port_name::port_quanta)) return false; return true; } return false; } bool can_connect(size_t number) const noexcept { return node_list_allocator.can_alloc(number); } status get_input_port(model& src, int port_src, port*& p) { return dispatch( src, [port_src, &p]<typename Dynamics>(Dynamics& dyn) -> status { if constexpr (is_detected_v<has_input_port_t, Dynamics>) { if (port_src >= 0 && port_src < (int)std::size(dyn.x)) { p = &dyn.x[port_src]; return status::success; } } return status::model_connect_output_port_unknown; }); } status get_output_port(model& dst, int port_dst, port*& p) { return dispatch( dst, [port_dst, &p]<typename Dynamics>(Dynamics& dyn) -> status { if constexpr (is_detected_v<has_output_port_t, Dynamics>) { if (port_dst >= 0 && port_dst < (int)std::size(dyn.y)) { p = &dyn.y[port_dst]; return status::success; } } return status::model_connect_output_port_unknown; }); } status connect(model& src, int port_src, model& dst, int port_dst) noexcept { port* src_port = nullptr; irt_return_if_bad(get_output_port(src, port_src, src_port)); port* dst_port = nullptr; irt_return_if_bad(get_input_port(dst, port_dst, dst_port)); auto model_src_id = models.get_id(src); auto model_dst_id = models.get_id(dst); auto it = src_port->connections.begin(); auto et = src_port->connections.end(); while (it != et) { irt_return_if_fail( !(it->model == model_dst_id && it->port_index == port_dst), status::model_connect_already_exist); ++it; }; irt_return_if_fail(is_ports_compatible(src, port_src, dst, port_dst), status::model_connect_bad_dynamics); src_port->connections.emplace_front( node_list_allocator, model_dst_id, port_dst); dst_port->connections.emplace_front( node_list_allocator, model_src_id, port_src); return status::success; } template<typename DynamicsSrc, typename DynamicsDst> status connect(DynamicsSrc& src, int port_src, DynamicsDst& dst, int port_dst) noexcept { model& src_model = get_model(src); model& dst_model = get_model(dst); model_id model_src_id = get_id(src); model_id model_dst_id = get_id(dst); auto it = std::begin(src.y[port_src].connections); auto et = std::end(src.y[port_src].connections); while (it != et) { irt_return_if_fail( !(it->model == model_dst_id && it->port_index == port_dst), status::model_connect_already_exist); ++it; } irt_return_if_fail( is_ports_compatible(src_model, port_src, dst_model, port_dst), status::model_connect_bad_dynamics); src.y[port_src].connections.emplace_front( node_list_allocator, model_dst_id, port_dst); dst.x[port_dst].connections.emplace_front( node_list_allocator, model_src_id, port_src); return status::success; } status disconnect(model& src, int port_src, model& dst, int port_dst) noexcept { port* src_port = nullptr; irt_return_if_bad(get_output_port(src, port_src, src_port)); port* dst_port = nullptr; irt_return_if_bad(get_input_port(dst, port_dst, dst_port)); { const auto end = std::end(src_port->connections); auto it = std::begin(src_port->connections); if (it->model == models.get_id(dst) && it->port_index == port_dst) { src_port->connections.pop_front(node_list_allocator); } else { auto prev = it++; while (it != end) { if (it->model == models.get_id(dst) && it->port_index == port_dst) { src_port->connections.erase_after(node_list_allocator, prev); break; } prev = it++; } } } { const auto end = std::end(dst_port->connections); auto it = std::begin(dst_port->connections); if (it->model == models.get_id(src) && it->port_index == port_src) { dst_port->connections.pop_front(node_list_allocator); } else { auto prev = it++; while (it != end) { if (it->model == models.get_id(src) && it->port_index == port_src) { dst_port->connections.erase_after(node_list_allocator, prev); break; } prev = it++; } } } return status::success; } status initialize(time t) noexcept { clean(); irt::model* mdl = nullptr; while (models.next(mdl)) irt_return_if_bad(make_initialize(*mdl, t)); irt::observer* obs = nullptr; while (observers.next(obs)) { if (auto* mdl = models.try_to_get(obs->model); mdl) { obs->msg.reset(); obs->cb( *obs, mdl->type, mdl->tl, t, observer::status::initialize); } } return status::success; } status run(time& t) noexcept { if (sched.empty()) { t = time_domain<time>::infinity; return status::success; } t = sched.tn(); const auto& bag = sched.pop(); flat_list<port*> emitting_output_ports(&emitting_output_port_allocator); for (const auto id : bag) if (auto* mdl = models.try_to_get(id); mdl) irt_return_if_bad( make_transition(*mdl, t, emitting_output_ports)); for (port* port_src : emitting_output_ports) { for (node& dst : port_src->connections) { if (auto* mdl = models.try_to_get(dst.model); mdl) { port* port_dst = nullptr; irt_return_if_bad( get_input_port(*mdl, dst.port_index, port_dst)); for (const message& msg : port_src->messages) { port_dst->messages.emplace_front(msg); sched.update(*mdl, t); } } } port_src->messages.clear(); } return status::success; } template<typename Dynamics> status make_initialize(model& mdl, Dynamics& dyn, time t) noexcept { if constexpr (std::is_same_v<Dynamics, queue> || std::is_same_v<Dynamics, dynamic_queue> || std::is_same_v<Dynamics, priority_queue>) dyn.queue.set_allocator(&dated_message_allocator); if constexpr (std::is_same_v<Dynamics, generator> || std::is_same_v<Dynamics, dynamic_queue> || std::is_same_v<Dynamics, priority_queue>) dyn.sim = this; if constexpr (is_detected_v<initialize_function_t, Dynamics>) irt_return_if_bad(dyn.initialize()); mdl.tl = t; mdl.tn = t + dyn.sigma; mdl.handle = nullptr; sched.insert(mdl, models.get_id(mdl), mdl.tn); return status::success; } status make_initialize(model& mdl, time t) noexcept { return dispatch(mdl, [this, &mdl, t]<typename Dynamics>(Dynamics& dyn) { return this->make_initialize(mdl, dyn, t); }); } template<typename Dynamics> status make_transition(model& mdl, Dynamics& dyn, time t, flat_list<port*>& emitting_output_ports) noexcept { if constexpr (is_detected_v<observation_function_t, Dynamics>) { if (mdl.obs_id != static_cast<observer_id>(0)) { if (auto* obs = observers.try_to_get(mdl.obs_id); obs) { obs->msg = dyn.observation(t - mdl.tl); obs->cb(*obs, mdl.type, mdl.tl, t, observer::status::run); } else { mdl.obs_id = static_cast<observer_id>(0); } } } if (mdl.tn == mdl.handle->tn) { if constexpr (is_detected_v<lambda_function_t, Dynamics>) { if constexpr (is_detected_v<has_output_port_t, Dynamics>) { irt_return_if_bad(dyn.lambda()); for (size_t i = 0, e = std::size(dyn.y); i != e; ++i) if (!dyn.y[i].messages.empty()) emitting_output_ports.emplace_front(&dyn.y[i]); } } } if constexpr (is_detected_v<transition_function_t, Dynamics>) irt_return_if_bad(dyn.transition(t, t - mdl.tl, mdl.tn - t)); if constexpr (is_detected_v<has_input_port_t, Dynamics>) for (size_t i = 0, e = std::size(dyn.x); i != e; ++i) dyn.x[i].messages.clear(); irt_assert(mdl.tn >= t); mdl.tl = t; mdl.tn = t + dyn.sigma; if (dyn.sigma && mdl.tn == t) mdl.tn = std::nextafter(t, t + 1.); sched.reintegrate(mdl, mdl.tn); return status::success; } status make_transition(model& mdl, time t, flat_list<port*>& o) noexcept { return dispatch(mdl, [this, &mdl, t, &o]<typename Dynamics>(Dynamics& dyn) { return this->make_transition(mdl, dyn, t, o); }); } template<typename Dynamics> void make_finalize(model& mdl, Dynamics& dyn, observer& obs, time t) noexcept { if constexpr (is_detected_v<observation_function_t, Dynamics>) { obs.msg = dyn.observation(t - mdl.tl); obs.cb(obs, mdl.type, mdl.tl, t, observer::status::finalize); } if constexpr (std::is_same_v<Dynamics, dynamic_queue> || std::is_same_v<Dynamics, priority_queue>) source_dispatch(dyn.default_source_ta, source::operation_type::finalize); if constexpr (std::is_same_v<Dynamics, generator>) { source_dispatch(dyn.default_source_ta, source::operation_type::finalize); source_dispatch(dyn.default_source_value, source::operation_type::finalize); } } /** * @brief Finalize and cleanup simulation objects. * * Clean: * - the scheduller nodes * - all input/output remaining messages * - call the observers' callback to finalize observation * * This function must be call at the end of the simulation. */ void finalize(time t) noexcept { model* mdl = nullptr; while (models.next(mdl)) { if (mdl->obs_id != static_cast<observer_id>(0)) { if (auto* obs = observers.try_to_get(mdl->obs_id); obs) { dispatch( *mdl, [this, mdl, obs, t]<typename Dynamics>(Dynamics& dyn) { this->make_finalize(*mdl, dyn, *obs, t); }); } } } } }; inline status initialize_source(simulation& sim, source& src) noexcept { return sim.source_dispatch(src, source::operation_type::initialize); } inline status update_source(simulation& sim, source& src, double& val) noexcept { if (src.next(val)) return status::success; if (auto ret = sim.source_dispatch(src, source::operation_type::update); is_bad(ret)) return ret; return src.next(val) ? status::success : status::source_empty; } } // namespace irt #endif
/* * (C) Copyright 1996- ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation nor * does it submit to any jurisdiction. */ #include "fdb5/database/EntryVisitMechanism.h" #include "eckit/io/AutoCloser.h" #include "fdb5/api/helpers/FDBToolRequest.h" #include "fdb5/database/Manager.h" #include "fdb5/LibFdb5.h" #include "fdb5/rules/Schema.h" using namespace eckit; namespace fdb5 { //---------------------------------------------------------------------------------------------------------------------- class FDBVisitException : public eckit::Exception { public: using Exception::Exception; }; //---------------------------------------------------------------------------------------------------------------------- EntryVisitor::EntryVisitor() : currentCatalogue_(nullptr), currentIndex_(nullptr) {} EntryVisitor::~EntryVisitor() {} bool EntryVisitor::visitDatabase(const Catalogue& catalogue, const Store& store) { currentCatalogue_ = &catalogue; currentStore_ = &store; return true; } void EntryVisitor::catalogueComplete(const Catalogue& catalogue) { if (currentCatalogue_ != nullptr) { ASSERT(currentCatalogue_ == &catalogue); } currentCatalogue_ = nullptr; currentStore_ = nullptr; currentIndex_ = nullptr; } bool EntryVisitor::visitIndex(const Index& index) { currentIndex_ = &index; return true; } void EntryVisitor::visitDatum(const Field& field, const std::string& keyFingerprint) { ASSERT(currentCatalogue_); ASSERT(currentIndex_); Key key(keyFingerprint, currentCatalogue_->schema().ruleFor(currentCatalogue_->key(), currentIndex_->key())); visitDatum(field, key); } time_t EntryVisitor::indexTimestamp() const { return currentIndex_ == nullptr ? 0 : currentIndex_->timestamp(); } //---------------------------------------------------------------------------------------------------------------------- EntryVisitMechanism::EntryVisitMechanism(const Config& config) : dbConfig_(config), fail_(true) {} void EntryVisitMechanism::visit(const FDBToolRequest& request, EntryVisitor& visitor) { if (visitor.visitEntries() && !visitor.visitIndexes()) { throw FDBVisitException("Cannot visit entries without visiting indexes", Here()); } // A request against all is the same as using an empty key in visitableLocations. ASSERT(request.all() == request.request().empty()); // TODO: Put minimim keys check into FDBToolRequest. Log::debug<LibFdb5>() << "REQUEST ====> " << request.request() << std::endl; try { std::vector<URI> uris(Manager(dbConfig_).visitableLocations(request.request(), request.all())); // n.b. it is not an error if nothing is found (especially in a sub-fdb). // And do the visitation for (URI uri : uris) { PathName path(uri.path()); if (path.exists()) { if (!path.isDir()) path = path.dirName(); path = path.realName(); Log::debug<LibFdb5>() << "FDB processing Path " << path << std::endl; std::unique_ptr<DB> db = DB::buildReader(eckit::URI(uri.scheme(), path)); ASSERT(db->open()); eckit::AutoCloser<DB> closer(*db); db->visitEntries(visitor, false); } } } catch (eckit::UserError&) { throw; } catch (eckit::Exception& e) { Log::warning() << e.what() << std::endl; if (fail_) throw; } } //---------------------------------------------------------------------------------------------------------------------- } // namespace fdb5
/* * 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. */ /*! * \brief Registration of transform operators * \file transform.cc */ #include <tvm/runtime/packed_func.h> #include <tvm/runtime/registry.h> #include <tvm/topi/einsum.h> #include <tvm/topi/transform.h> #include <tvm/topi/utils.h> namespace tvm { namespace topi { using namespace tvm; using namespace tvm::runtime; TVM_REGISTER_GLOBAL("topi.expand_dims").set_body([](TVMArgs args, TVMRetValue* rv) { *rv = expand_dims(args[0], args[1], args[2]); }); TVM_REGISTER_GLOBAL("topi.transpose").set_body([](TVMArgs args, TVMRetValue* rv) { *rv = transpose(args[0], args[1]); }); TVM_REGISTER_GLOBAL("topi.flip").set_body([](TVMArgs args, TVMRetValue* rv) { // pass empty seq_lengths tensor to reverse_sequence *rv = reverse_sequence(args[0], Tensor(), args[1]); }); TVM_REGISTER_GLOBAL("topi.reverse_sequence").set_body([](TVMArgs args, TVMRetValue* rv) { *rv = reverse_sequence(args[0], args[1], args[2], args[3]); }); TVM_REGISTER_GLOBAL("topi.reshape").set_body([](TVMArgs args, TVMRetValue* rv) { *rv = reshape(args[0], args[1]); }); TVM_REGISTER_GLOBAL("topi.squeeze").set_body([](TVMArgs args, TVMRetValue* rv) { *rv = squeeze(args[0], ArrayOrInt(args[1])); }); TVM_REGISTER_GLOBAL("topi.concatenate").set_body([](TVMArgs args, TVMRetValue* rv) { *rv = concatenate(args[0], args[1]); }); TVM_REGISTER_GLOBAL("topi.stack").set_body([](TVMArgs args, TVMRetValue* rv) { *rv = stack(args[0], args[1]); }); TVM_REGISTER_GLOBAL("topi.shape").set_body([](TVMArgs args, TVMRetValue* rv) { *rv = shape(args[0], args[1]); }); TVM_REGISTER_GLOBAL("topi.ndarray_size").set_body([](TVMArgs args, TVMRetValue* rv) { *rv = ndarray_size(args[0], args[1]); }); TVM_REGISTER_GLOBAL("topi.split").set_body([](TVMArgs args, TVMRetValue* rv) { if (args[1].type_code() == kDLInt || args[1].type_code() == kDLUInt) { *rv = split_sections(args[0], args[1], args[2]); } else { *rv = split(args[0], args[1], args[2]); } }); TVM_REGISTER_GLOBAL("topi.layout_transform").set_body([](TVMArgs args, TVMRetValue* rv) { *rv = layout_transform(args[0], args[1], args[2]); }); TVM_REGISTER_GLOBAL("topi.take").set_body([](TVMArgs args, TVMRetValue* rv) { if (args.size() == 3) { std::string mode = args[2]; *rv = take(args[0], args[1], mode); } else { int axis = args[2]; std::string mode = args[3]; *rv = take(args[0], args[1], axis, mode); } }); TVM_REGISTER_GLOBAL("topi.sequence_mask").set_body([](TVMArgs args, TVMRetValue* rv) { double pad_val = args[2]; int axis = args[3]; *rv = sequence_mask(args[0], args[1], pad_val, axis); }); TVM_REGISTER_GLOBAL("topi.where").set_body([](TVMArgs args, TVMRetValue* rv) { *rv = where(args[0], args[1], args[2]); }); TVM_REGISTER_GLOBAL("topi.arange").set_body([](TVMArgs args, TVMRetValue* rv) { *rv = arange(args[0], args[1], args[2], args[3]); }); TVM_REGISTER_GLOBAL("topi.meshgrid").set_body([](TVMArgs args, TVMRetValue* rv) { *rv = meshgrid(args[0], args[1]); }); TVM_REGISTER_GLOBAL("topi.repeat").set_body([](TVMArgs args, TVMRetValue* rv) { *rv = repeat(args[0], args[1], args[2]); }); TVM_REGISTER_GLOBAL("topi.tile").set_body([](TVMArgs args, TVMRetValue* rv) { *rv = tile(args[0], args[1]); }); TVM_REGISTER_GLOBAL("topi.gather").set_body([](TVMArgs args, TVMRetValue* rv) { *rv = gather(args[0], args[1], args[2]); }); TVM_REGISTER_GLOBAL("topi.gather_nd").set_body([](TVMArgs args, TVMRetValue* rv) { *rv = gather_nd(args[0], args[1]); }); TVM_REGISTER_GLOBAL("topi.unravel_index").set_body([](TVMArgs args, TVMRetValue* rv) { *rv = unravel_index(args[0], args[1]); }); TVM_REGISTER_GLOBAL("topi.sparse_to_dense").set_body([](TVMArgs args, TVMRetValue* rv) { *rv = sparse_to_dense(args[0], args[1], args[2], args[3]); }); TVM_REGISTER_GLOBAL("topi.matmul").set_body([](TVMArgs args, TVMRetValue* rv) { switch (args.size()) { case 2: *rv = matmul(args[0], args[1]); break; case 3: *rv = matmul(args[0], args[1], args[2]); break; case 4: *rv = matmul(args[0], args[1], args[2], args[3]); break; default: ICHECK(0) << "topi.matmul expects 2, 3 or 4 arguments"; } }); TVM_REGISTER_GLOBAL("topi.tensordot").set_body([](TVMArgs args, TVMRetValue* rv) { if (args.size() == 2) { *rv = tensordot(args[0], args[1]); } else if (args.size() == 3) { *rv = tensordot(args[0], args[1], args[2]); } else { Array<PrimExpr> axes = args[3]; *rv = tensordot(args[0], args[1], args[2], axes); } }); TVM_REGISTER_GLOBAL("topi.einsum").set_body([](TVMArgs args, TVMRetValue* rv) { *rv = einsum(args[0], args[1]); }); TVM_REGISTER_GLOBAL("topi.strided_slice").set_body([](TVMArgs args, TVMRetValue* rv) { *rv = strided_slice(args[0], args[1], args[2], args[3], args[4]); }); TVM_REGISTER_GLOBAL("topi.dynamic_strided_slice").set_body([](TVMArgs args, TVMRetValue* rv) { *rv = dynamic_strided_slice(args[0], args[1], args[2], args[3]); }); TVM_REGISTER_GLOBAL("topi.one_hot").set_body([](TVMArgs args, TVMRetValue* rv) { int depth = args[3]; int axis = args[4]; DataType dtype = args[5]; *rv = one_hot(args[0], args[1], args[2], depth, axis, dtype); }); TVM_REGISTER_GLOBAL("topi.matrix_set_diag").set_body([](TVMArgs args, TVMRetValue* rv) { int k1 = args[2]; int k2 = args[3]; bool super_diag_right_align = args[4]; bool sub_diag_right_align = args[5]; *rv = matrix_set_diag(args[0], args[1], k1, k2, super_diag_right_align, sub_diag_right_align); }); TVM_REGISTER_GLOBAL("topi.adv_index").set_body([](TVMArgs args, TVMRetValue* rv) { *rv = adv_index(args[0], args[1]); }); } // namespace topi } // namespace tvm
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <init.h> #include <addrman.h> #include <amount.h> #include <banman.h> #include <blockfilter.h> #include <chain.h> #include <chainparams.h> #include <compat/sanity.h> #include <consensus/validation.h> #include <fs.h> #include <hash.h> #include <httprpc.h> #include <httpserver.h> #include <index/blockfilterindex.h> #include <index/txindex.h> #include <interfaces/chain.h> #include <interfaces/node.h> #include <key.h> #include <mapport.h> #include <miner.h> #include <net.h> #include <net_permissions.h> #include <net_processing.h> #include <netbase.h> #include <node/context.h> #include <node/ui_interface.h> #include <policy/feerate.h> #include <policy/fees.h> #include <policy/policy.h> #include <policy/settings.h> #include <protocol.h> #include <rpc/blockchain.h> #include <rpc/register.h> #include <rpc/server.h> #include <rpc/util.h> #include <scheduler.h> #include <script/sigcache.h> #include <script/standard.h> #include <shutdown.h> #include <sync.h> #include <timedata.h> #include <torcontrol.h> #include <txdb.h> #include <txmempool.h> #include <util/asmap.h> #include <util/check.h> #include <util/moneystr.h> #include <util/string.h> #include <util/system.h> #include <util/threadnames.h> #include <util/translation.h> #include <validation.h> #include <validationinterface.h> #include <walletinitinterface.h> #include <functional> #include <set> #include <stdint.h> #include <stdio.h> #include <thread> #include <vector> #ifndef WIN32 #include <attributes.h> #include <cerrno> #include <signal.h> #include <sys/stat.h> #endif #include <boost/algorithm/string/replace.hpp> #include <boost/signals2/signal.hpp> #if ENABLE_ZMQ #include <zmq/zmqabstractnotifier.h> #include <zmq/zmqnotificationinterface.h> #include <zmq/zmqrpc.h> #endif static const bool DEFAULT_PROXYRANDOMIZE = true; static const bool DEFAULT_REST_ENABLE = false; static const bool DEFAULT_STOPAFTERBLOCKIMPORT = false; #ifdef WIN32 // Win32 LevelDB doesn't use filedescriptors, and the ones used for // accessing block files don't count towards the fd_set size limit // anyway. #define MIN_CORE_FILEDESCRIPTORS 0 #else #define MIN_CORE_FILEDESCRIPTORS 150 #endif static const char* DEFAULT_ASMAP_FILENAME="ip_asn.map"; /** * The PID file facilities. */ static const char* BITCOIN_PID_FILENAME = "bitcoind.pid"; static fs::path GetPidFile(const ArgsManager& args) { return AbsPathForConfigVal(fs::path(args.GetArg("-pid", BITCOIN_PID_FILENAME))); } [[nodiscard]] static bool CreatePidFile(const ArgsManager& args) { fsbridge::ofstream file{GetPidFile(args)}; if (file) { #ifdef WIN32 tfm::format(file, "%d\n", GetCurrentProcessId()); #else tfm::format(file, "%d\n", getpid()); #endif return true; } else { return InitError(strprintf(_("Unable to create the PID file '%s': %s"), GetPidFile(args).string(), std::strerror(errno))); } } ////////////////////////////////////////////////////////////////////////////// // // Shutdown // // // Thread management and startup/shutdown: // // The network-processing threads are all part of a thread group // created by AppInit() or the Qt main() function. // // A clean exit happens when StartShutdown() or the SIGTERM // signal handler sets ShutdownRequested(), which makes main thread's // WaitForShutdown() interrupts the thread group. // And then, WaitForShutdown() makes all other on-going threads // in the thread group join the main thread. // Shutdown() is then called to clean up database connections, and stop other // threads that should only be stopped after the main network-processing // threads have exited. // // Shutdown for Qt is very similar, only it uses a QTimer to detect // ShutdownRequested() getting set, and then does the normal Qt // shutdown thing. // static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle; static std::thread g_load_block; void Interrupt(NodeContext& node) { InterruptHTTPServer(); InterruptHTTPRPC(); InterruptRPC(); InterruptREST(); InterruptTorControl(); InterruptMapPort(); if (node.connman) node.connman->Interrupt(); if (g_txindex) { g_txindex->Interrupt(); } ForEachBlockFilterIndex([](BlockFilterIndex& index) { index.Interrupt(); }); } void Shutdown(NodeContext& node) { static Mutex g_shutdown_mutex; TRY_LOCK(g_shutdown_mutex, lock_shutdown); if (!lock_shutdown) return; LogPrintf("%s: In progress...\n", __func__); Assert(node.args); /// Note: Shutdown() must be able to handle cases in which initialization failed part of the way, /// for example if the data directory was found to be locked. /// Be sure that anything that writes files or flushes caches only does this if the respective /// module was initialized. util::ThreadRename("shutoff"); if (node.mempool) node.mempool->AddTransactionsUpdated(1); StopHTTPRPC(); StopREST(); StopRPC(); StopHTTPServer(); for (const auto& client : node.chain_clients) { client->flush(); } StopMapPort(); // Because these depend on each-other, we make sure that neither can be // using the other before destroying them. if (node.peerman) UnregisterValidationInterface(node.peerman.get()); // Follow the lock order requirements: // * CheckForStaleTipAndEvictPeers locks cs_main before indirectly calling GetExtraFullOutboundCount // which locks cs_vNodes. // * ProcessMessage locks cs_main and g_cs_orphans before indirectly calling ForEachNode which // locks cs_vNodes. // * CConnman::Stop calls DeleteNode, which calls FinalizeNode, which locks cs_main and calls // EraseOrphansFor, which locks g_cs_orphans. // // Thus the implicit locking order requirement is: (1) cs_main, (2) g_cs_orphans, (3) cs_vNodes. if (node.connman) { node.connman->StopThreads(); LOCK2(::cs_main, ::g_cs_orphans); node.connman->StopNodes(); } StopTorControl(); // After everything has been shut down, but before things get flushed, stop the // CScheduler/checkqueue, scheduler and load block thread. if (node.scheduler) node.scheduler->stop(); if (g_load_block.joinable()) g_load_block.join(); StopScriptCheckWorkerThreads(); // After the threads that potentially access these pointers have been stopped, // destruct and reset all to nullptr. node.peerman.reset(); node.connman.reset(); node.banman.reset(); if (node.mempool && node.mempool->IsLoaded() && node.args->GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) { DumpMempool(*node.mempool); } // Drop transactions we were still watching, and record fee estimations. if (node.fee_estimator) node.fee_estimator->Flush(); // FlushStateToDisk generates a ChainStateFlushed callback, which we should avoid missing if (node.chainman) { LOCK(cs_main); for (CChainState* chainstate : node.chainman->GetAll()) { if (chainstate->CanFlushToDisk()) { chainstate->ForceFlushStateToDisk(); } } } // After there are no more peers/RPC left to give us new data which may generate // CValidationInterface callbacks, flush them... GetMainSignals().FlushBackgroundCallbacks(); // Stop and delete all indexes only after flushing background callbacks. if (g_txindex) { g_txindex->Stop(); g_txindex.reset(); } ForEachBlockFilterIndex([](BlockFilterIndex& index) { index.Stop(); }); DestroyAllBlockFilterIndexes(); // Any future callbacks will be dropped. This should absolutely be safe - if // missing a callback results in an unrecoverable situation, unclean shutdown // would too. The only reason to do the above flushes is to let the wallet catch // up with our current chain to avoid any strange pruning edge cases and make // next startup faster by avoiding rescan. if (node.chainman) { LOCK(cs_main); for (CChainState* chainstate : node.chainman->GetAll()) { if (chainstate->CanFlushToDisk()) { chainstate->ForceFlushStateToDisk(); chainstate->ResetCoinsViews(); } } pblocktree.reset(); } for (const auto& client : node.chain_clients) { client->stop(); } #if ENABLE_ZMQ if (g_zmq_notification_interface) { UnregisterValidationInterface(g_zmq_notification_interface); delete g_zmq_notification_interface; g_zmq_notification_interface = nullptr; } #endif node.chain_clients.clear(); UnregisterAllValidationInterfaces(); GetMainSignals().UnregisterBackgroundSignalScheduler(); globalVerifyHandle.reset(); ECC_Stop(); node.mempool.reset(); node.fee_estimator.reset(); node.chainman = nullptr; node.scheduler.reset(); try { if (!fs::remove(GetPidFile(*node.args))) { LogPrintf("%s: Unable to remove PID file: File does not exist\n", __func__); } } catch (const fs::filesystem_error& e) { LogPrintf("%s: Unable to remove PID file: %s\n", __func__, fsbridge::get_filesystem_error_message(e)); } node.args = nullptr; LogPrintf("%s: done\n", __func__); } /** * Signal handlers are very limited in what they are allowed to do. * The execution context the handler is invoked in is not guaranteed, * so we restrict handler operations to just touching variables: */ #ifndef WIN32 static void HandleSIGTERM(int) { StartShutdown(); } static void HandleSIGHUP(int) { LogInstance().m_reopen_file = true; } #else static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType) { StartShutdown(); Sleep(INFINITE); return true; } #endif #ifndef WIN32 static void registerSignalHandler(int signal, void(*handler)(int)) { struct sigaction sa; sa.sa_handler = handler; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(signal, &sa, nullptr); } #endif static boost::signals2::connection rpc_notify_block_change_connection; static void OnRPCStarted() { rpc_notify_block_change_connection = uiInterface.NotifyBlockTip_connect(std::bind(RPCNotifyBlockChange, std::placeholders::_2)); } static void OnRPCStopped() { rpc_notify_block_change_connection.disconnect(); RPCNotifyBlockChange(nullptr); g_best_block_cv.notify_all(); LogPrint(BCLog::RPC, "RPC stopped.\n"); } void SetupServerArgs(NodeContext& node) { assert(!node.args); node.args = &gArgs; ArgsManager& argsman = *node.args; SetupHelpOptions(argsman); argsman.AddArg("-help-debug", "Print help message with debugging options and exit", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); // server-only for now const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN); const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET); const auto signetBaseParams = CreateBaseChainParams(CBaseChainParams::SIGNET); const auto regtestBaseParams = CreateBaseChainParams(CBaseChainParams::REGTEST); const auto defaultChainParams = CreateChainParams(argsman, CBaseChainParams::MAIN); const auto testnetChainParams = CreateChainParams(argsman, CBaseChainParams::TESTNET); const auto signetChainParams = CreateChainParams(argsman, CBaseChainParams::SIGNET); const auto regtestChainParams = CreateChainParams(argsman, CBaseChainParams::REGTEST); // Hidden Options std::vector<std::string> hidden_args = { "-dbcrashratio", "-forcecompactdb", // GUI args. These will be overwritten by SetupUIArgs for the GUI "-choosedatadir", "-lang=<lang>", "-min", "-resetguisettings", "-splash", "-uiplatform"}; argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); #if HAVE_SYSTEM argsman.AddArg("-alertnotify=<cmd>", "Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); #endif argsman.AddArg("-assumevalid=<hex>", strprintf("If this block is in the chain assume that it and its ancestors are valid and potentially skip their script verification (0 to verify all, default: %s, testnet: %s, signet: %s)", defaultChainParams->GetConsensus().defaultAssumeValid.GetHex(), testnetChainParams->GetConsensus().defaultAssumeValid.GetHex(), signetChainParams->GetConsensus().defaultAssumeValid.GetHex()), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-blocksdir=<dir>", "Specify directory to hold blocks subdirectory for *.dat files (default: <datadir>)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); #if HAVE_SYSTEM argsman.AddArg("-blocknotify=<cmd>", "Execute command when the best block changes (%s in cmd is replaced by block hash)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); #endif argsman.AddArg("-blockreconstructionextratxn=<n>", strprintf("Extra transactions to keep in memory for compact block reconstructions (default: %u)", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-blocksonly", strprintf("Whether to reject transactions from network peers. Automatic broadcast and rebroadcast of any transactions from inbound peers is disabled, unless the peer has the 'forcerelay' permission. RPC transactions are not affected. (default: %u)", DEFAULT_BLOCKSONLY), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-conf=<file>", strprintf("Specify path to read-only configuration file. Relative paths will be prefixed by datadir location. (default: %s)", BITCOIN_CONF_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-datadir=<dir>", "Specify data directory", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-dbbatchsize", strprintf("Maximum database write batch size in bytes (default: %u)", nDefaultDbBatchSize), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS); argsman.AddArg("-dbcache=<n>", strprintf("Maximum database cache size <n> MiB (%d to %d, default: %d). In addition, unused mempool memory is shared for this cache (see -maxmempool).", nMinDbCache, nMaxDbCache, nDefaultDbCache), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-debuglogfile=<file>", strprintf("Specify location of debug log file. Relative paths will be prefixed by a net-specific datadir location. (-nodebuglogfile to disable; default: %s)", DEFAULT_DEBUGLOGFILE), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-feefilter", strprintf("Tell other nodes to filter invs to us by our mempool min fee (default: %u)", DEFAULT_FEEFILTER), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS); argsman.AddArg("-includeconf=<file>", "Specify additional configuration file, relative to the -datadir path (only useable from configuration file, not command line)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-loadblock=<file>", "Imports blocks from external file on startup", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-maxmempool=<n>", strprintf("Keep the transaction memory pool below <n> megabytes (default: %u)", DEFAULT_MAX_MEMPOOL_SIZE), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-maxorphantx=<n>", strprintf("Keep at most <n> unconnectable transactions in memory (default: %u)", DEFAULT_MAX_ORPHAN_TRANSACTIONS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-mempoolexpiry=<n>", strprintf("Do not keep transactions in the mempool longer than <n> hours (default: %u)", DEFAULT_MEMPOOL_EXPIRY), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-minimumchainwork=<hex>", strprintf("Minimum work assumed to exist on a valid chain in hex (default: %s, testnet: %s, signet: %s)", defaultChainParams->GetConsensus().nMinimumChainWork.GetHex(), testnetChainParams->GetConsensus().nMinimumChainWork.GetHex(), signetChainParams->GetConsensus().nMinimumChainWork.GetHex()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS); argsman.AddArg("-par=<n>", strprintf("Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)", -GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-persistmempool", strprintf("Whether to save the mempool on shutdown and load on restart (default: %u)", DEFAULT_PERSIST_MEMPOOL), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-pid=<file>", strprintf("Specify pid file. Relative paths will be prefixed by a net-specific datadir location. (default: %s)", BITCOIN_PID_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-prune=<n>", strprintf("Reduce storage requirements by enabling pruning (deleting) of old blocks. This allows the pruneblockchain RPC to be called to delete specific blocks, and enables automatic pruning of old blocks if a target size in MiB is provided. This mode is incompatible with -txindex and -rescan. " "Warning: Reverting this setting requires re-downloading the entire blockchain. " "(default: 0 = disable pruning blocks, 1 = allow manual pruning via RPC, >=%u = automatically prune block files to stay under the specified target size in MiB)", MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-reindex", "Rebuild chain state and block index from the blk*.dat files on disk", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-reindex-chainstate", "Rebuild chain state from the currently indexed blocks. When in pruning mode or if blocks on disk might be corrupted, use full -reindex instead.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-settings=<file>", strprintf("Specify path to dynamic settings data file. Can be disabled with -nosettings. File is written at runtime and not meant to be edited by users (use %s instead for custom settings). Relative paths will be prefixed by datadir location. (default: %s)", BITCOIN_CONF_FILENAME, BITCOIN_SETTINGS_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); #if HAVE_SYSTEM argsman.AddArg("-startupnotify=<cmd>", "Execute command on startup.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); #endif #ifndef WIN32 argsman.AddArg("-sysperms", "Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); #else hidden_args.emplace_back("-sysperms"); #endif argsman.AddArg("-txindex", strprintf("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)", DEFAULT_TXINDEX), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-blockfilterindex=<type>", strprintf("Maintain an index of compact filters by block (default: %s, values: %s).", DEFAULT_BLOCKFILTERINDEX, ListBlockFilterTypes()) + " If <type> is not supplied or if <type> = 1, indexes for all known types are enabled.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-addnode=<ip>", "Add a node to connect to and attempt to keep the connection open (see the `addnode` RPC command help for more info). This option can be specified multiple times to add multiple nodes.", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION); argsman.AddArg("-asmap=<file>", strprintf("Specify asn mapping used for bucketing of the peers (default: %s). Relative paths will be prefixed by the net-specific datadir location.", DEFAULT_ASMAP_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-bantime=<n>", strprintf("Default duration (in seconds) of manually configured bans (default: %u)", DEFAULT_MISBEHAVING_BANTIME), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-bind=<addr>[:<port>][=onion]", strprintf("Bind to given address and always listen on it (default: 0.0.0.0). Use [host]:port notation for IPv6. Append =onion to tag any incoming connections to that address and port as incoming Tor connections (default: 127.0.0.1:%u=onion, testnet: 127.0.0.1:%u=onion, signet: 127.0.0.1:%u=onion, regtest: 127.0.0.1:%u=onion)", defaultBaseParams->OnionServiceTargetPort(), testnetBaseParams->OnionServiceTargetPort(), signetBaseParams->OnionServiceTargetPort(), regtestBaseParams->OnionServiceTargetPort()), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION); argsman.AddArg("-connect=<ip>", "Connect only to the specified node; -noconnect disables automatic connections (the rules for this peer are the same as for -addnode). This option can be specified multiple times to connect to multiple nodes.", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION); argsman.AddArg("-discover", "Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-dns", strprintf("Allow DNS lookups for -addnode, -seednode and -connect (default: %u)", DEFAULT_NAME_LOOKUP), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-dnsseed", strprintf("Query for peer addresses via DNS lookup, if low on addresses (default: %u unless -connect used)", DEFAULT_DNSSEED), ArgsManager::ALLOW_BOOL, OptionsCategory::CONNECTION); argsman.AddArg("-externalip=<ip>", "Specify your own public address", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-fixedseeds", strprintf("Allow fixed seeds if DNS seeds don't provide peers (default: %u)", DEFAULT_FIXEDSEEDS), ArgsManager::ALLOW_BOOL, OptionsCategory::CONNECTION); argsman.AddArg("-forcednsseed", strprintf("Always query for peer addresses via DNS lookup (default: %u)", DEFAULT_FORCEDNSSEED), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-listen", "Accept connections from outside (default: 1 if no -proxy or -connect)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-listenonion", strprintf("Automatically create Tor onion service (default: %d)", DEFAULT_LISTEN_ONION), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-maxconnections=<n>", strprintf("Maintain at most <n> connections to peers (default: %u)", DEFAULT_MAX_PEER_CONNECTIONS), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-maxreceivebuffer=<n>", strprintf("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)", DEFAULT_MAXRECEIVEBUFFER), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-maxsendbuffer=<n>", strprintf("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)", DEFAULT_MAXSENDBUFFER), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-maxtimeadjustment", strprintf("Maximum allowed median peer time offset adjustment. Local perspective of time may be influenced by peers forward or backward by this amount. (default: %u seconds)", DEFAULT_MAX_TIME_ADJUSTMENT), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-maxuploadtarget=<n>", strprintf("Tries to keep outbound traffic under the given target (in MiB per 24h). Limit does not apply to peers with 'download' permission. 0 = no limit (default: %d)", DEFAULT_MAX_UPLOAD_TARGET), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-onion=<ip:port>", "Use separate SOCKS5 proxy to reach peers via Tor onion services, set -noonion to disable (default: -proxy)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-onlynet=<net>", "Make outgoing connections only through network <net> (ipv4, ipv6 or onion). Incoming connections are not affected by this option. This option can be specified multiple times to allow multiple networks. Warning: if it is used with ipv4 or ipv6 but not onion and the -onion or -proxy option is set, then outbound onion connections will still be made; use -noonion or -onion=0 to disable outbound onion connections in this case.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-peerbloomfilters", strprintf("Support filtering of blocks and transaction with bloom filters (default: %u)", DEFAULT_PEERBLOOMFILTERS), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-peerblockfilters", strprintf("Serve compact block filters to peers per BIP 157 (default: %u)", DEFAULT_PEERBLOCKFILTERS), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-permitbaremultisig", strprintf("Relay non-P2SH multisig (default: %u)", DEFAULT_PERMIT_BAREMULTISIG), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-port=<port>", strprintf("Listen for connections on <port>. Nodes not using the default ports (default: %u, testnet: %u, signet: %u, regtest: %u) are unlikely to get incoming connections.", defaultChainParams->GetDefaultPort(), testnetChainParams->GetDefaultPort(), signetChainParams->GetDefaultPort(), regtestChainParams->GetDefaultPort()), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION); argsman.AddArg("-proxy=<ip:port>", "Connect through SOCKS5 proxy, set -noproxy to disable (default: disabled)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-proxyrandomize", strprintf("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)", DEFAULT_PROXYRANDOMIZE), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-seednode=<ip>", "Connect to a node to retrieve peer addresses, and disconnect. This option can be specified multiple times to connect to multiple nodes.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-networkactive", "Enable all P2P network activity (default: 1). Can be changed by the setnetworkactive RPC command", ArgsManager::ALLOW_BOOL, OptionsCategory::CONNECTION); argsman.AddArg("-timeout=<n>", strprintf("Specify socket connection timeout in milliseconds. If an initial attempt to connect is unsuccessful after this amount of time, drop it (minimum: 1, default: %d)", DEFAULT_CONNECT_TIMEOUT), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-peertimeout=<n>", strprintf("Specify a p2p connection timeout delay in seconds. After connecting to a peer, wait this amount of time before considering disconnection based on inactivity (minimum: 1, default: %d)", DEFAULT_PEER_CONNECT_TIMEOUT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CONNECTION); argsman.AddArg("-torcontrol=<ip>:<port>", strprintf("Tor control port to use if onion listening enabled (default: %s)", DEFAULT_TOR_CONTROL), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-torpassword=<pass>", "Tor control port password (default: empty)", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::CONNECTION); #ifdef USE_UPNP #if USE_UPNP argsman.AddArg("-upnp", "Use UPnP to map the listening port (default: 1 when listening and no -proxy)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); #else argsman.AddArg("-upnp", strprintf("Use UPnP to map the listening port (default: %u)", 0), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); #endif #else hidden_args.emplace_back("-upnp"); #endif #ifdef USE_NATPMP argsman.AddArg("-natpmp", strprintf("Use NAT-PMP to map the listening port (default: %s)", DEFAULT_NATPMP ? "1 when listening and no -proxy" : "0"), ArgsManager::ALLOW_BOOL, OptionsCategory::CONNECTION); #else hidden_args.emplace_back("-natpmp"); #endif // USE_NATPMP argsman.AddArg("-whitebind=<[permissions@]addr>", "Bind to the given address and add permission flags to the peers connecting to it. " "Use [host]:port notation for IPv6. Allowed permissions: " + Join(NET_PERMISSIONS_DOC, ", ") + ". " "Specify multiple permissions separated by commas (default: download,noban,mempool,relay). Can be specified multiple times.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-whitelist=<[permissions@]IP address or network>", "Add permission flags to the peers connecting from the given IP address (e.g. 1.2.3.4) or " "CIDR-notated network (e.g. 1.2.3.0/24). Uses the same permissions as " "-whitebind. Can be specified multiple times." , ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); g_wallet_init_interface.AddWalletOptions(argsman); #if ENABLE_ZMQ argsman.AddArg("-zmqpubhashblock=<address>", "Enable publish hash block in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ); argsman.AddArg("-zmqpubhashtx=<address>", "Enable publish hash transaction in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ); argsman.AddArg("-zmqpubrawblock=<address>", "Enable publish raw block in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ); argsman.AddArg("-zmqpubrawtx=<address>", "Enable publish raw transaction in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ); argsman.AddArg("-zmqpubsequence=<address>", "Enable publish hash block and tx sequence in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ); argsman.AddArg("-zmqpubhashblockhwm=<n>", strprintf("Set publish hash block outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ); argsman.AddArg("-zmqpubhashtxhwm=<n>", strprintf("Set publish hash transaction outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ); argsman.AddArg("-zmqpubrawblockhwm=<n>", strprintf("Set publish raw block outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ); argsman.AddArg("-zmqpubrawtxhwm=<n>", strprintf("Set publish raw transaction outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ); argsman.AddArg("-zmqpubsequencehwm=<n>", strprintf("Set publish hash sequence message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ); #else hidden_args.emplace_back("-zmqpubhashblock=<address>"); hidden_args.emplace_back("-zmqpubhashtx=<address>"); hidden_args.emplace_back("-zmqpubrawblock=<address>"); hidden_args.emplace_back("-zmqpubrawtx=<address>"); hidden_args.emplace_back("-zmqpubsequence=<n>"); hidden_args.emplace_back("-zmqpubhashblockhwm=<n>"); hidden_args.emplace_back("-zmqpubhashtxhwm=<n>"); hidden_args.emplace_back("-zmqpubrawblockhwm=<n>"); hidden_args.emplace_back("-zmqpubrawtxhwm=<n>"); hidden_args.emplace_back("-zmqpubsequencehwm=<n>"); #endif argsman.AddArg("-checkblocks=<n>", strprintf("How many blocks to check at startup (default: %u, 0 = all)", DEFAULT_CHECKBLOCKS), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-checklevel=<n>", strprintf("How thorough the block verification of -checkblocks is: %s (0-4, default: %u)", Join(CHECKLEVEL_DOC, ", "), DEFAULT_CHECKLEVEL), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-checkblockindex", strprintf("Do a consistency check for the block tree, chainstate, and other validation data structures occasionally. (default: %u, regtest: %u)", defaultChainParams->DefaultConsistencyChecks(), regtestChainParams->DefaultConsistencyChecks()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u, regtest: %u)", defaultChainParams->DefaultConsistencyChecks(), regtestChainParams->DefaultConsistencyChecks()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-checkpoints", strprintf("Enable rejection of any forks from the known historical chain until block %s (default: %u)", defaultChainParams->Checkpoints().GetHeight(), DEFAULT_CHECKPOINTS_ENABLED), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-deprecatedrpc=<method>", "Allows deprecated RPC method(s) to be used", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-stopatheight", strprintf("Stop running after reaching the given height in the main chain (default: %u)", DEFAULT_STOPATHEIGHT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-limitancestorcount=<n>", strprintf("Do not accept transactions if number of in-mempool ancestors is <n> or more (default: %u)", DEFAULT_ANCESTOR_LIMIT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-limitancestorsize=<n>", strprintf("Do not accept transactions whose size with all in-mempool ancestors exceeds <n> kilobytes (default: %u)", DEFAULT_ANCESTOR_SIZE_LIMIT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-limitdescendantcount=<n>", strprintf("Do not accept transactions if any ancestor would have <n> or more in-mempool descendants (default: %u)", DEFAULT_DESCENDANT_LIMIT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-limitdescendantsize=<n>", strprintf("Do not accept transactions if any ancestor would have more than <n> kilobytes of in-mempool descendants (default: %u).", DEFAULT_DESCENDANT_SIZE_LIMIT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-addrmantest", "Allows to test address relay on localhost", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-capturemessages", "Capture all P2P messages to disk", ArgsManager::ALLOW_BOOL | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-debug=<category>", "Output debugging information (default: -nodebug, supplying <category> is optional). " "If <category> is not supplied or if <category> = 1, output all debugging information. <category> can be: " + LogInstance().LogCategoriesString() + ". This option can be specified multiple times to output multiple categories.", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-debugexclude=<category>", strprintf("Exclude debugging information for a category. Can be used in conjunction with -debug=1 to output debug logs for all categories except the specified category. This option can be specified multiple times to exclude multiple categories."), ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-logips", strprintf("Include IP addresses in debug output (default: %u)", DEFAULT_LOGIPS), ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-logtimestamps", strprintf("Prepend debug output with timestamp (default: %u)", DEFAULT_LOGTIMESTAMPS), ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); #ifdef HAVE_THREAD_LOCAL argsman.AddArg("-logthreadnames", strprintf("Prepend debug output with name of the originating thread (only available on platforms supporting thread_local) (default: %u)", DEFAULT_LOGTHREADNAMES), ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); #else hidden_args.emplace_back("-logthreadnames"); #endif argsman.AddArg("-logtimemicros", strprintf("Add microsecond precision to debug timestamps (default: %u)", DEFAULT_LOGTIMEMICROS), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-mocktime=<n>", "Replace actual time with " + UNIX_EPOCH_TIME + " (default: 0)", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-maxsigcachesize=<n>", strprintf("Limit sum of signature cache and script execution cache sizes to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_SIZE), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-printpriority", strprintf("Log transaction fee per kB when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-printtoconsole", "Send trace/debug info to console (default: 1 when no -daemon. To disable logging to file, set -nodebuglogfile)", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-shrinkdebugfile", "Shrink debug.log file on client startup (default: 1 when no -debug)", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-uacomment=<cmt>", "Append comment to the user agent string", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); SetupChainParamsBaseOptions(argsman); argsman.AddArg("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", !testnetChainParams->RequireStandard()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::NODE_RELAY); argsman.AddArg("-incrementalrelayfee=<amt>", strprintf("Fee rate (in %s/kB) used to define cost of relay, used for mempool limiting and BIP 125 replacement. (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_INCREMENTAL_RELAY_FEE)), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::NODE_RELAY); argsman.AddArg("-dustrelayfee=<amt>", strprintf("Fee rate (in %s/kB) used to define dust, the value of an output such that it will cost more than its value in fees at this fee rate to spend it. (default: %s)", CURRENCY_UNIT, FormatMoney(DUST_RELAY_TX_FEE)), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::NODE_RELAY); argsman.AddArg("-bytespersigop", strprintf("Equivalent bytes per sigop in transactions for relay and mining (default: %u)", DEFAULT_BYTES_PER_SIGOP), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY); argsman.AddArg("-datacarrier", strprintf("Relay and mine data carrier transactions (default: %u)", DEFAULT_ACCEPT_DATACARRIER), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY); argsman.AddArg("-datacarriersize", strprintf("Maximum size of data in data carrier transactions we relay and mine (default: %u)", MAX_OP_RETURN_RELAY), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY); argsman.AddArg("-minrelaytxfee=<amt>", strprintf("Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_MIN_RELAY_TX_FEE)), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY); argsman.AddArg("-whitelistforcerelay", strprintf("Add 'forcerelay' permission to whitelisted inbound peers with default permissions. This will relay transactions even if the transactions were already in the mempool. (default: %d)", DEFAULT_WHITELISTFORCERELAY), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY); argsman.AddArg("-whitelistrelay", strprintf("Add 'relay' permission to whitelisted inbound peers with default permissions. This will accept relayed transactions even when not relaying transactions (default: %d)", DEFAULT_WHITELISTRELAY), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY); argsman.AddArg("-blockmaxweight=<n>", strprintf("Set maximum BIP141 block weight (default: %d)", DEFAULT_BLOCK_MAX_WEIGHT), ArgsManager::ALLOW_ANY, OptionsCategory::BLOCK_CREATION); argsman.AddArg("-blockmintxfee=<amt>", strprintf("Set lowest fee rate (in %s/kB) for transactions to be included in block creation. (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_BLOCK_MIN_TX_FEE)), ArgsManager::ALLOW_ANY, OptionsCategory::BLOCK_CREATION); argsman.AddArg("-blockversion=<n>", "Override block version to test forking scenarios", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::BLOCK_CREATION); argsman.AddArg("-rest", strprintf("Accept public REST requests (default: %u)", DEFAULT_REST_ENABLE), ArgsManager::ALLOW_ANY, OptionsCategory::RPC); argsman.AddArg("-rpcallowip=<ip>", "Allow JSON-RPC connections from specified source. Valid for <ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times", ArgsManager::ALLOW_ANY, OptionsCategory::RPC); argsman.AddArg("-rpcauth=<userpw>", "Username and HMAC-SHA-256 hashed password for JSON-RPC connections. The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A canonical python script is included in share/rpcauth. The client then connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> pair of arguments. This option can be specified multiple times", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::RPC); argsman.AddArg("-rpcbind=<addr>[:port]", "Bind to given address to listen for JSON-RPC connections. Do not expose the RPC server to untrusted networks such as the public internet! This option is ignored unless -rpcallowip is also passed. Port is optional and overrides -rpcport. Use [host]:port notation for IPv6. This option can be specified multiple times (default: 127.0.0.1 and ::1 i.e., localhost)", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY | ArgsManager::SENSITIVE, OptionsCategory::RPC); argsman.AddArg("-rpccookiefile=<loc>", "Location of the auth cookie. Relative paths will be prefixed by a net-specific datadir location. (default: data dir)", ArgsManager::ALLOW_ANY, OptionsCategory::RPC); argsman.AddArg("-rpcpassword=<pw>", "Password for JSON-RPC connections", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::RPC); argsman.AddArg("-rpcport=<port>", strprintf("Listen for JSON-RPC connections on <port> (default: %u, testnet: %u, signet: %u, regtest: %u)", defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort(), signetBaseParams->RPCPort(), regtestBaseParams->RPCPort()), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::RPC); argsman.AddArg("-rpcserialversion", strprintf("Sets the serialization of raw transaction or block hex returned in non-verbose mode, non-segwit(0) or segwit(1) (default: %d)", DEFAULT_RPC_SERIALIZE_VERSION), ArgsManager::ALLOW_ANY, OptionsCategory::RPC); argsman.AddArg("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::RPC); argsman.AddArg("-rpcthreads=<n>", strprintf("Set the number of threads to service RPC calls (default: %d)", DEFAULT_HTTP_THREADS), ArgsManager::ALLOW_ANY, OptionsCategory::RPC); argsman.AddArg("-rpcuser=<user>", "Username for JSON-RPC connections", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::RPC); argsman.AddArg("-rpcwhitelist=<whitelist>", "Set a whitelist to filter incoming RPC calls for a specific user. The field <whitelist> comes in the format: <USERNAME>:<rpc 1>,<rpc 2>,...,<rpc n>. If multiple whitelists are set for a given user, they are set-intersected. See -rpcwhitelistdefault documentation for information on default whitelist behavior.", ArgsManager::ALLOW_ANY, OptionsCategory::RPC); argsman.AddArg("-rpcwhitelistdefault", "Sets default behavior for rpc whitelisting. Unless rpcwhitelistdefault is set to 0, if any -rpcwhitelist is set, the rpc server acts as if all rpc users are subject to empty-unless-otherwise-specified whitelists. If rpcwhitelistdefault is set to 1 and no -rpcwhitelist is set, rpc server acts as if all rpc users are subject to empty whitelists.", ArgsManager::ALLOW_BOOL, OptionsCategory::RPC); argsman.AddArg("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::RPC); argsman.AddArg("-server", "Accept command line and JSON-RPC commands", ArgsManager::ALLOW_ANY, OptionsCategory::RPC); #if HAVE_DECL_DAEMON argsman.AddArg("-daemon", "Run in the background as a daemon and accept commands", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); #else hidden_args.emplace_back("-daemon"); #endif // Add the hidden options argsman.AddHiddenArgs(hidden_args); } std::string LicenseInfo() { const std::string URL_SOURCE_CODE = "<https://github.com/bitcoin/bitcoin>"; return CopyrightHolders(strprintf(_("Copyright (C) %i-%i").translated, 2009, COPYRIGHT_YEAR) + " ") + "\n" + "\n" + strprintf(_("Please contribute if you find %s useful. " "Visit %s for further information about the software.").translated, PACKAGE_NAME, "<" PACKAGE_URL ">") + "\n" + strprintf(_("The source code is available from %s.").translated, URL_SOURCE_CODE) + "\n" + "\n" + _("This is experimental software.").translated + "\n" + strprintf(_("Distributed under the MIT software license, see the accompanying file %s or %s").translated, "COPYING", "<https://opensource.org/licenses/MIT>") + "\n"; } static bool fHaveGenesis = false; static Mutex g_genesis_wait_mutex; static std::condition_variable g_genesis_wait_cv; static void BlockNotifyGenesisWait(const CBlockIndex* pBlockIndex) { if (pBlockIndex != nullptr) { { LOCK(g_genesis_wait_mutex); fHaveGenesis = true; } g_genesis_wait_cv.notify_all(); } } struct CImportingNow { CImportingNow() { assert(fImporting == false); fImporting = true; } ~CImportingNow() { assert(fImporting == true); fImporting = false; } }; // If we're using -prune with -reindex, then delete block files that will be ignored by the // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile // is missing, do the same here to delete any later block files after a gap. Also delete all // rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile // is in sync with what's actually on disk by the time we start downloading, so that pruning // works correctly. static void CleanupBlockRevFiles() { std::map<std::string, fs::path> mapBlockFiles; // Glob all blk?????.dat and rev?????.dat files from the blocks directory. // Remove the rev files immediately and insert the blk file paths into an // ordered map keyed by block file index. LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n"); fs::path blocksdir = GetBlocksDir(); for (fs::directory_iterator it(blocksdir); it != fs::directory_iterator(); it++) { if (fs::is_regular_file(*it) && it->path().filename().string().length() == 12 && it->path().filename().string().substr(8,4) == ".dat") { if (it->path().filename().string().substr(0,3) == "blk") mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path(); else if (it->path().filename().string().substr(0,3) == "rev") remove(it->path()); } } // Remove all block files that aren't part of a contiguous set starting at // zero by walking the ordered map (keys are block file indices) by // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist) // start removing block files. int nContigCounter = 0; for (const std::pair<const std::string, fs::path>& item : mapBlockFiles) { if (atoi(item.first) == nContigCounter) { nContigCounter++; continue; } remove(item.second); } } #if HAVE_SYSTEM static void StartupNotify(const ArgsManager& args) { std::string cmd = args.GetArg("-startupnotify", ""); if (!cmd.empty()) { std::thread t(runCommand, cmd); t.detach(); // thread runs free } } #endif static void ThreadImport(ChainstateManager& chainman, std::vector<fs::path> vImportFiles, const ArgsManager& args) { const CChainParams& chainparams = Params(); ScheduleBatchPriority(); { CImportingNow imp; // -reindex if (fReindex) { int nFile = 0; while (true) { FlatFilePos pos(nFile, 0); if (!fs::exists(GetBlockPosFilename(pos))) break; // No block files left to reindex FILE *file = OpenBlockFile(pos, true); if (!file) break; // This error is logged in OpenBlockFile LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile); ::ChainstateActive().LoadExternalBlockFile(chainparams, file, &pos); if (ShutdownRequested()) { LogPrintf("Shutdown requested. Exit %s\n", __func__); return; } nFile++; } pblocktree->WriteReindexing(false); fReindex = false; LogPrintf("Reindexing finished\n"); // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked): LoadGenesisBlock(chainparams); } // -loadblock= for (const fs::path& path : vImportFiles) { FILE *file = fsbridge::fopen(path, "rb"); if (file) { LogPrintf("Importing blocks file %s...\n", path.string()); ::ChainstateActive().LoadExternalBlockFile(chainparams, file); if (ShutdownRequested()) { LogPrintf("Shutdown requested. Exit %s\n", __func__); return; } } else { LogPrintf("Warning: Could not open blocks file %s\n", path.string()); } } // scan for better chains in the block chain database, that are not yet connected in the active best chain // We can't hold cs_main during ActivateBestChain even though we're accessing // the chainman unique_ptrs since ABC requires us not to be holding cs_main, so retrieve // the relevant pointers before the ABC call. for (CChainState* chainstate : WITH_LOCK(::cs_main, return chainman.GetAll())) { BlockValidationState state; if (!chainstate->ActivateBestChain(state, chainparams, nullptr)) { LogPrintf("Failed to connect best block (%s)\n", state.ToString()); StartShutdown(); return; } } if (args.GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) { LogPrintf("Stopping after block import\n"); StartShutdown(); return; } } // End scope of CImportingNow chainman.ActiveChainstate().LoadMempool(args); } /** Sanity checks * Ensure that Bitcoin is running in a usable environment with all * necessary library support. */ static bool InitSanityCheck() { if (!ECC_InitSanityCheck()) { return InitError(Untranslated("Elliptic curve cryptography sanity check failure. Aborting.")); } if (!glibc_sanity_test() || !glibcxx_sanity_test()) return false; if (!Random_SanityCheck()) { return InitError(Untranslated("OS cryptographic RNG sanity check failure. Aborting.")); } return true; } static bool AppInitServers(const util::Ref& context, NodeContext& node) { const ArgsManager& args = *Assert(node.args); RPCServer::OnStarted(&OnRPCStarted); RPCServer::OnStopped(&OnRPCStopped); if (!InitHTTPServer()) return false; StartRPC(); node.rpc_interruption_point = RpcInterruptionPoint; if (!StartHTTPRPC(context)) return false; if (args.GetBoolArg("-rest", DEFAULT_REST_ENABLE)) StartREST(context); StartHTTPServer(); return true; } // Parameter interaction based on rules void InitParameterInteraction(ArgsManager& args) { // when specifying an explicit binding address, you want to listen on it // even when -connect or -proxy is specified if (args.IsArgSet("-bind")) { if (args.SoftSetBoolArg("-listen", true)) LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__); } if (args.IsArgSet("-whitebind")) { if (args.SoftSetBoolArg("-listen", true)) LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__); } if (args.IsArgSet("-connect")) { // when only connecting to trusted nodes, do not seed via DNS, or listen by default if (args.SoftSetBoolArg("-dnsseed", false)) LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__); if (args.SoftSetBoolArg("-listen", false)) LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__); } if (args.IsArgSet("-proxy")) { // to protect privacy, do not listen by default if a default proxy server is specified if (args.SoftSetBoolArg("-listen", false)) LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__); // to protect privacy, do not map ports when a proxy is set. The user may still specify -listen=1 // to listen locally, so don't rely on this happening through -listen below. if (args.SoftSetBoolArg("-upnp", false)) LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__); if (args.SoftSetBoolArg("-natpmp", false)) { LogPrintf("%s: parameter interaction: -proxy set -> setting -natpmp=0\n", __func__); } // to protect privacy, do not discover addresses by default if (args.SoftSetBoolArg("-discover", false)) LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__); } if (!args.GetBoolArg("-listen", DEFAULT_LISTEN)) { // do not map ports or try to retrieve public IP when not listening (pointless) if (args.SoftSetBoolArg("-upnp", false)) LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__); if (args.SoftSetBoolArg("-natpmp", false)) { LogPrintf("%s: parameter interaction: -listen=0 -> setting -natpmp=0\n", __func__); } if (args.SoftSetBoolArg("-discover", false)) LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__); if (args.SoftSetBoolArg("-listenonion", false)) LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__); } if (args.IsArgSet("-externalip")) { // if an explicit public IP is specified, do not try to find others if (args.SoftSetBoolArg("-discover", false)) LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__); } // disable whitelistrelay in blocksonly mode if (args.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) { if (args.SoftSetBoolArg("-whitelistrelay", false)) LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__); } // Forcing relay from whitelisted hosts implies we will accept relays from them in the first place. if (args.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) { if (args.SoftSetBoolArg("-whitelistrelay", true)) LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__); } } /** * Initialize global loggers. * * Note that this is called very early in the process lifetime, so you should be * careful about what global state you rely on here. */ void InitLogging(const ArgsManager& args) { LogInstance().m_print_to_file = !args.IsArgNegated("-debuglogfile"); LogInstance().m_file_path = AbsPathForConfigVal(args.GetArg("-debuglogfile", DEFAULT_DEBUGLOGFILE)); LogInstance().m_print_to_console = args.GetBoolArg("-printtoconsole", !args.GetBoolArg("-daemon", false)); LogInstance().m_log_timestamps = args.GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS); LogInstance().m_log_time_micros = args.GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS); #ifdef HAVE_THREAD_LOCAL LogInstance().m_log_threadnames = args.GetBoolArg("-logthreadnames", DEFAULT_LOGTHREADNAMES); #endif fLogIPs = args.GetBoolArg("-logips", DEFAULT_LOGIPS); std::string version_string = FormatFullVersion(); #ifdef DEBUG version_string += " (debug build)"; #else version_string += " (release build)"; #endif LogPrintf(PACKAGE_NAME " version %s\n", version_string); } namespace { // Variables internal to initialization process only int nMaxConnections; int nUserMaxConnections; int nFD; ServiceFlags nLocalServices = ServiceFlags(NODE_NETWORK | NODE_NETWORK_LIMITED); int64_t peer_connect_timeout; std::set<BlockFilterType> g_enabled_filter_types; } // namespace [[noreturn]] static void new_handler_terminate() { // Rather than throwing std::bad-alloc if allocation fails, terminate // immediately to (try to) avoid chain corruption. // Since LogPrintf may itself allocate memory, set the handler directly // to terminate first. std::set_new_handler(std::terminate); LogPrintf("Error: Out of memory. Terminating.\n"); // The log was successful, terminate now. std::terminate(); }; bool AppInitBasicSetup(const ArgsManager& args) { // ********************************************************* Step 1: setup #ifdef _MSC_VER // Turn off Microsoft heap dump noise _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, 0)); // Disable confusing "helpful" text message on abort, Ctrl-C _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); #endif #ifdef WIN32 // Enable heap terminate-on-corruption HeapSetInformation(nullptr, HeapEnableTerminationOnCorruption, nullptr, 0); #endif if (!InitShutdownState()) { return InitError(Untranslated("Initializing wait-for-shutdown state failed.")); } if (!SetupNetworking()) { return InitError(Untranslated("Initializing networking failed.")); } #ifndef WIN32 if (!args.GetBoolArg("-sysperms", false)) { umask(077); } // Clean shutdown on SIGTERM registerSignalHandler(SIGTERM, HandleSIGTERM); registerSignalHandler(SIGINT, HandleSIGTERM); // Reopen debug.log on SIGHUP registerSignalHandler(SIGHUP, HandleSIGHUP); // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly signal(SIGPIPE, SIG_IGN); #else SetConsoleCtrlHandler(consoleCtrlHandler, true); #endif std::set_new_handler(new_handler_terminate); return true; } bool AppInitParameterInteraction(const ArgsManager& args) { const CChainParams& chainparams = Params(); // ********************************************************* Step 2: parameter interactions // also see: InitParameterInteraction() // Error if network-specific options (-addnode, -connect, etc) are // specified in default section of config file, but not overridden // on the command line or in this network's section of the config file. std::string network = args.GetChainName(); if (network == CBaseChainParams::SIGNET) { LogPrintf("Signet derived magic (message start): %s\n", HexStr(chainparams.MessageStart())); } bilingual_str errors; for (const auto& arg : args.GetUnsuitableSectionOnlyArgs()) { errors += strprintf(_("Config setting for %s only applied on %s network when in [%s] section.") + Untranslated("\n"), arg, network, network); } if (!errors.empty()) { return InitError(errors); } // Warn if unrecognized section name are present in the config file. bilingual_str warnings; for (const auto& section : args.GetUnrecognizedSections()) { warnings += strprintf(Untranslated("%s:%i ") + _("Section [%s] is not recognized.") + Untranslated("\n"), section.m_file, section.m_line, section.m_name); } if (!warnings.empty()) { InitWarning(warnings); } if (!fs::is_directory(GetBlocksDir())) { return InitError(strprintf(_("Specified blocks directory \"%s\" does not exist."), args.GetArg("-blocksdir", ""))); } // parse and validate enabled filter types std::string blockfilterindex_value = args.GetArg("-blockfilterindex", DEFAULT_BLOCKFILTERINDEX); if (blockfilterindex_value == "" || blockfilterindex_value == "1") { g_enabled_filter_types = AllBlockFilterTypes(); } else if (blockfilterindex_value != "0") { const std::vector<std::string> names = args.GetArgs("-blockfilterindex"); for (const auto& name : names) { BlockFilterType filter_type; if (!BlockFilterTypeByName(name, filter_type)) { return InitError(strprintf(_("Unknown -blockfilterindex value %s."), name)); } g_enabled_filter_types.insert(filter_type); } } // Signal NODE_COMPACT_FILTERS if peerblockfilters and basic filters index are both enabled. if (args.GetBoolArg("-peerblockfilters", DEFAULT_PEERBLOCKFILTERS)) { if (g_enabled_filter_types.count(BlockFilterType::BASIC) != 1) { return InitError(_("Cannot set -peerblockfilters without -blockfilterindex.")); } nLocalServices = ServiceFlags(nLocalServices | NODE_COMPACT_FILTERS); } // if using block pruning, then disallow txindex if (args.GetArg("-prune", 0)) { if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) return InitError(_("Prune mode is incompatible with -txindex.")); if (!g_enabled_filter_types.empty()) { return InitError(_("Prune mode is incompatible with -blockfilterindex.")); } } // -bind and -whitebind can't be set when not listening size_t nUserBind = args.GetArgs("-bind").size() + args.GetArgs("-whitebind").size(); if (nUserBind != 0 && !args.GetBoolArg("-listen", DEFAULT_LISTEN)) { return InitError(Untranslated("Cannot set -bind or -whitebind together with -listen=0")); } // Make sure enough file descriptors are available int nBind = std::max(nUserBind, size_t(1)); nUserMaxConnections = args.GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS); nMaxConnections = std::max(nUserMaxConnections, 0); // Trim requested connection counts, to fit into system limitations // <int> in std::min<int>(...) to work around FreeBSD compilation issue described in #2695 nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS + MAX_ADDNODE_CONNECTIONS + nBind + NUM_FDS_MESSAGE_CAPTURE); #ifdef USE_POLL int fd_max = nFD; #else int fd_max = FD_SETSIZE; #endif nMaxConnections = std::max(std::min<int>(nMaxConnections, fd_max - nBind - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS - NUM_FDS_MESSAGE_CAPTURE), 0); if (nFD < MIN_CORE_FILEDESCRIPTORS) return InitError(_("Not enough file descriptors available.")); nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS - NUM_FDS_MESSAGE_CAPTURE, nMaxConnections); if (nMaxConnections < nUserMaxConnections) InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections)); // ********************************************************* Step 3: parameter-to-internal-flags if (args.IsArgSet("-debug")) { // Special-case: if -debug=0/-nodebug is set, turn off debugging messages const std::vector<std::string> categories = args.GetArgs("-debug"); if (std::none_of(categories.begin(), categories.end(), [](std::string cat){return cat == "0" || cat == "none";})) { for (const auto& cat : categories) { if (!LogInstance().EnableCategory(cat)) { InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debug", cat)); } } } } // Now remove the logging categories which were explicitly excluded for (const std::string& cat : args.GetArgs("-debugexclude")) { if (!LogInstance().DisableCategory(cat)) { InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debugexclude", cat)); } } fCheckBlockIndex = args.GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks()); fCheckpointsEnabled = args.GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED); hashAssumeValid = uint256S(args.GetArg("-assumevalid", chainparams.GetConsensus().defaultAssumeValid.GetHex())); if (!hashAssumeValid.IsNull()) LogPrintf("Assuming ancestors of block %s have valid signatures.\n", hashAssumeValid.GetHex()); else LogPrintf("Validating signatures for all blocks.\n"); if (args.IsArgSet("-minimumchainwork")) { const std::string minChainWorkStr = args.GetArg("-minimumchainwork", ""); if (!IsHexNumber(minChainWorkStr)) { return InitError(strprintf(Untranslated("Invalid non-hex (%s) minimum chain work value specified"), minChainWorkStr)); } nMinimumChainWork = UintToArith256(uint256S(minChainWorkStr)); } else { nMinimumChainWork = UintToArith256(chainparams.GetConsensus().nMinimumChainWork); } LogPrintf("Setting nMinimumChainWork=%s\n", nMinimumChainWork.GetHex()); if (nMinimumChainWork < UintToArith256(chainparams.GetConsensus().nMinimumChainWork)) { LogPrintf("Warning: nMinimumChainWork set below default value of %s\n", chainparams.GetConsensus().nMinimumChainWork.GetHex()); } // mempool limits int64_t nMempoolSizeMax = args.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000; int64_t nMempoolSizeMin = args.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40; if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin) return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0))); // incremental relay fee sets the minimum feerate increase necessary for BIP 125 replacement in the mempool // and the amount the mempool min fee increases above the feerate of txs evicted due to mempool limiting. if (args.IsArgSet("-incrementalrelayfee")) { CAmount n = 0; if (!ParseMoney(args.GetArg("-incrementalrelayfee", ""), n)) return InitError(AmountErrMsg("incrementalrelayfee", args.GetArg("-incrementalrelayfee", ""))); incrementalRelayFee = CFeeRate(n); } // block pruning; get the amount of disk space (in MiB) to allot for block & undo files int64_t nPruneArg = args.GetArg("-prune", 0); if (nPruneArg < 0) { return InitError(_("Prune cannot be configured with a negative value.")); } nPruneTarget = (uint64_t) nPruneArg * 1024 * 1024; if (nPruneArg == 1) { // manual pruning: -prune=1 LogPrintf("Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n"); nPruneTarget = std::numeric_limits<uint64_t>::max(); fPruneMode = true; } else if (nPruneTarget) { if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) { return InitError(strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024)); } LogPrintf("Prune configured to target %u MiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024); fPruneMode = true; } nConnectTimeout = args.GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT); if (nConnectTimeout <= 0) { nConnectTimeout = DEFAULT_CONNECT_TIMEOUT; } peer_connect_timeout = args.GetArg("-peertimeout", DEFAULT_PEER_CONNECT_TIMEOUT); if (peer_connect_timeout <= 0) { return InitError(Untranslated("peertimeout cannot be configured with a negative value.")); } if (args.IsArgSet("-minrelaytxfee")) { CAmount n = 0; if (!ParseMoney(args.GetArg("-minrelaytxfee", ""), n)) { return InitError(AmountErrMsg("minrelaytxfee", args.GetArg("-minrelaytxfee", ""))); } // High fee check is done afterward in CWallet::Create() ::minRelayTxFee = CFeeRate(n); } else if (incrementalRelayFee > ::minRelayTxFee) { // Allow only setting incrementalRelayFee to control both ::minRelayTxFee = incrementalRelayFee; LogPrintf("Increasing minrelaytxfee to %s to match incrementalrelayfee\n",::minRelayTxFee.ToString()); } // Sanity check argument for min fee for including tx in block // TODO: Harmonize which arguments need sanity checking and where that happens if (args.IsArgSet("-blockmintxfee")) { CAmount n = 0; if (!ParseMoney(args.GetArg("-blockmintxfee", ""), n)) return InitError(AmountErrMsg("blockmintxfee", args.GetArg("-blockmintxfee", ""))); } // Feerate used to define dust. Shouldn't be changed lightly as old // implementations may inadvertently create non-standard transactions if (args.IsArgSet("-dustrelayfee")) { CAmount n = 0; if (!ParseMoney(args.GetArg("-dustrelayfee", ""), n)) return InitError(AmountErrMsg("dustrelayfee", args.GetArg("-dustrelayfee", ""))); dustRelayFee = CFeeRate(n); } fRequireStandard = !args.GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard()); if (!chainparams.IsTestChain() && !fRequireStandard) { return InitError(strprintf(Untranslated("acceptnonstdtxn is not currently supported for %s chain"), chainparams.NetworkIDString())); } nBytesPerSigOp = args.GetArg("-bytespersigop", nBytesPerSigOp); if (!g_wallet_init_interface.ParameterInteraction()) return false; fIsBareMultisigStd = args.GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG); fAcceptDatacarrier = args.GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER); nMaxDatacarrierBytes = args.GetArg("-datacarriersize", nMaxDatacarrierBytes); // Option to startup with mocktime set (used for regression testing): SetMockTime(args.GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op if (args.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS)) nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM); if (args.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0) return InitError(Untranslated("rpcserialversion must be non-negative.")); if (args.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1) return InitError(Untranslated("Unknown rpcserialversion requested.")); nMaxTipAge = args.GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE); if (args.IsArgSet("-proxy") && args.GetArg("-proxy", "").empty()) { return InitError(_("No proxy server specified. Use -proxy=<ip> or -proxy=<ip:port>.")); } return true; } static bool LockDataDirectory(bool probeOnly) { // Make sure only a single Bitcoin process is using the data directory. fs::path datadir = GetDataDir(); if (!DirIsWritable(datadir)) { return InitError(strprintf(_("Cannot write to data directory '%s'; check permissions."), datadir.string())); } if (!LockDirectory(datadir, ".lock", probeOnly)) { return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running."), datadir.string(), PACKAGE_NAME)); } return true; } bool AppInitSanityChecks() { // ********************************************************* Step 4: sanity checks // Initialize elliptic curve code std::string sha256_algo = SHA256AutoDetect(); LogPrintf("Using the '%s' SHA256 implementation\n", sha256_algo); RandomInit(); ECC_Start(); globalVerifyHandle.reset(new ECCVerifyHandle()); // Sanity check if (!InitSanityCheck()) return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), PACKAGE_NAME)); // Probe the data directory lock to give an early error message, if possible // We cannot hold the data directory lock here, as the forking for daemon() hasn't yet happened, // and a fork will cause weird behavior to it. return LockDataDirectory(true); } bool AppInitLockDataDirectory() { // After daemonization get the data directory lock again and hold on to it until exit // This creates a slight window for a race condition to happen, however this condition is harmless: it // will at most make us exit without printing a message to console. if (!LockDataDirectory(false)) { // Detailed error printed inside LockDataDirectory return false; } return true; } bool AppInitInterfaces(NodeContext& node) { node.chain = interfaces::MakeChain(node); // Create client interfaces for wallets that are supposed to be loaded // according to -wallet and -disablewallet options. This only constructs // the interfaces, it doesn't load wallet data. Wallets actually get loaded // when load() and start() interface methods are called below. g_wallet_init_interface.Construct(node); return true; } bool AppInitMain(const util::Ref& context, NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) { const ArgsManager& args = *Assert(node.args); const CChainParams& chainparams = Params(); // ********************************************************* Step 4a: application initialization if (!CreatePidFile(args)) { // Detailed error printed inside CreatePidFile(). return false; } if (LogInstance().m_print_to_file) { if (args.GetBoolArg("-shrinkdebugfile", LogInstance().DefaultShrinkDebugFile())) { // Do this first since it both loads a bunch of debug.log into memory, // and because this needs to happen before any other debug.log printing LogInstance().ShrinkDebugFile(); } } if (!LogInstance().StartLogging()) { return InitError(strprintf(Untranslated("Could not open debug log file %s"), LogInstance().m_file_path.string())); } if (!LogInstance().m_log_timestamps) LogPrintf("Startup time: %s\n", FormatISO8601DateTime(GetTime())); LogPrintf("Default data directory %s\n", GetDefaultDataDir().string()); LogPrintf("Using data directory %s\n", GetDataDir().string()); // Only log conf file usage message if conf file actually exists. fs::path config_file_path = GetConfigFile(args.GetArg("-conf", BITCOIN_CONF_FILENAME)); if (fs::exists(config_file_path)) { LogPrintf("Config file: %s\n", config_file_path.string()); } else if (args.IsArgSet("-conf")) { // Warn if no conf file exists at path provided by user InitWarning(strprintf(_("The specified config file %s does not exist\n"), config_file_path.string())); } else { // Not categorizing as "Warning" because it's the default behavior LogPrintf("Config file: %s (not found, skipping)\n", config_file_path.string()); } // Log the config arguments to debug.log args.LogArgs(); LogPrintf("Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD); // Warn about relative -datadir path. if (args.IsArgSet("-datadir") && !fs::path(args.GetArg("-datadir", "")).is_absolute()) { LogPrintf("Warning: relative datadir option '%s' specified, which will be interpreted relative to the " /* Continued */ "current working directory '%s'. This is fragile, because if bitcoin is started in the future " "from a different location, it will be unable to locate the current data files. There could " "also be data loss if bitcoin is started while in a temporary directory.\n", args.GetArg("-datadir", ""), fs::current_path().string()); } InitSignatureCache(); InitScriptExecutionCache(); int script_threads = args.GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS); if (script_threads <= 0) { // -par=0 means autodetect (number of cores - 1 script threads) // -par=-n means "leave n cores free" (number of cores - n - 1 script threads) script_threads += GetNumCores(); } // Subtract 1 because the main thread counts towards the par threads script_threads = std::max(script_threads - 1, 0); // Number of script-checking threads <= MAX_SCRIPTCHECK_THREADS script_threads = std::min(script_threads, MAX_SCRIPTCHECK_THREADS); LogPrintf("Script verification uses %d additional threads\n", script_threads); if (script_threads >= 1) { g_parallel_script_checks = true; StartScriptCheckWorkerThreads(script_threads); } assert(!node.scheduler); node.scheduler = MakeUnique<CScheduler>(); // Start the lightweight task scheduler thread node.scheduler->m_service_thread = std::thread([&] { TraceThread("scheduler", [&] { node.scheduler->serviceQueue(); }); }); // Gather some entropy once per minute. node.scheduler->scheduleEvery([]{ RandAddPeriodic(); }, std::chrono::minutes{1}); GetMainSignals().RegisterBackgroundSignalScheduler(*node.scheduler); /* Register RPC commands regardless of -server setting so they will be * available in the GUI RPC console even if external calls are disabled. */ RegisterAllCoreRPCCommands(tableRPC); for (const auto& client : node.chain_clients) { client->registerRpcs(); } #if ENABLE_ZMQ RegisterZMQRPCCommands(tableRPC); #endif /* Start the RPC server already. It will be started in "warmup" mode * and not really process calls already (but it will signify connections * that the server is there and will be ready later). Warmup mode will * be disabled when initialisation is finished. */ if (args.GetBoolArg("-server", false)) { uiInterface.InitMessage_connect(SetRPCWarmupStatus); if (!AppInitServers(context, node)) return InitError(_("Unable to start HTTP server. See debug log for details.")); } // ********************************************************* Step 5: verify wallet database integrity for (const auto& client : node.chain_clients) { if (!client->verify()) { return false; } } // ********************************************************* Step 6: network initialization // Note that we absolutely cannot open any actual connections // until the very end ("start node") as the UTXO/block state // is not yet setup and may end up being set up twice if we // need to reindex later. fListen = args.GetBoolArg("-listen", DEFAULT_LISTEN); fDiscover = args.GetBoolArg("-discover", true); const bool ignores_incoming_txs{args.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)}; assert(!node.banman); node.banman = MakeUnique<BanMan>(GetDataDir() / "banlist.dat", &uiInterface, args.GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME)); assert(!node.connman); node.connman = MakeUnique<CConnman>(GetRand(std::numeric_limits<uint64_t>::max()), GetRand(std::numeric_limits<uint64_t>::max()), args.GetBoolArg("-networkactive", true)); assert(!node.fee_estimator); // Don't initialize fee estimation with old data if we don't relay transactions, // as they would never get updated. if (!ignores_incoming_txs) node.fee_estimator = std::make_unique<CBlockPolicyEstimator>(); assert(!node.mempool); int check_ratio = std::min<int>(std::max<int>(args.GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000); node.mempool = std::make_unique<CTxMemPool>(node.fee_estimator.get(), check_ratio); assert(!node.chainman); node.chainman = &g_chainman; ChainstateManager& chainman = *Assert(node.chainman); assert(!node.peerman); node.peerman = PeerManager::make(chainparams, *node.connman, node.banman.get(), *node.scheduler, chainman, *node.mempool, ignores_incoming_txs); RegisterValidationInterface(node.peerman.get()); // sanitize comments per BIP-0014, format user agent and check total size std::vector<std::string> uacomments; for (const std::string& cmt : args.GetArgs("-uacomment")) { if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT)) return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt)); uacomments.push_back(cmt); } strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments); if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) { return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."), strSubVersion.size(), MAX_SUBVERSION_LENGTH)); } if (args.IsArgSet("-onlynet")) { std::set<enum Network> nets; for (const std::string& snet : args.GetArgs("-onlynet")) { enum Network net = ParseNetwork(snet); if (net == NET_UNROUTABLE) return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet)); nets.insert(net); } for (int n = 0; n < NET_MAX; n++) { enum Network net = (enum Network)n; if (!nets.count(net)) SetReachable(net, false); } } // Check for host lookup allowed before parsing any network related parameters fNameLookup = args.GetBoolArg("-dns", DEFAULT_NAME_LOOKUP); bool proxyRandomize = args.GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE); // -proxy sets a proxy for all outgoing network traffic // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default std::string proxyArg = args.GetArg("-proxy", ""); SetReachable(NET_ONION, false); if (proxyArg != "" && proxyArg != "0") { CService proxyAddr; if (!Lookup(proxyArg, proxyAddr, 9050, fNameLookup)) { return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg)); } proxyType addrProxy = proxyType(proxyAddr, proxyRandomize); if (!addrProxy.IsValid()) return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg)); SetProxy(NET_IPV4, addrProxy); SetProxy(NET_IPV6, addrProxy); SetProxy(NET_ONION, addrProxy); SetNameProxy(addrProxy); SetReachable(NET_ONION, true); // by default, -proxy sets onion as reachable, unless -noonion later } // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses // -noonion (or -onion=0) disables connecting to .onion entirely // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none) std::string onionArg = args.GetArg("-onion", ""); if (onionArg != "") { if (onionArg == "0") { // Handle -noonion/-onion=0 SetReachable(NET_ONION, false); } else { CService onionProxy; if (!Lookup(onionArg, onionProxy, 9050, fNameLookup)) { return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg)); } proxyType addrOnion = proxyType(onionProxy, proxyRandomize); if (!addrOnion.IsValid()) return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg)); SetProxy(NET_ONION, addrOnion); SetReachable(NET_ONION, true); } } for (const std::string& strAddr : args.GetArgs("-externalip")) { CService addrLocal; if (Lookup(strAddr, addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid()) AddLocal(addrLocal, LOCAL_MANUAL); else return InitError(ResolveErrMsg("externalip", strAddr)); } // Read asmap file if configured if (args.IsArgSet("-asmap")) { fs::path asmap_path = fs::path(args.GetArg("-asmap", "")); if (asmap_path.empty()) { asmap_path = DEFAULT_ASMAP_FILENAME; } if (!asmap_path.is_absolute()) { asmap_path = GetDataDir() / asmap_path; } if (!fs::exists(asmap_path)) { InitError(strprintf(_("Could not find asmap file %s"), asmap_path)); return false; } std::vector<bool> asmap = CAddrMan::DecodeAsmap(asmap_path); if (asmap.size() == 0) { InitError(strprintf(_("Could not parse asmap file %s"), asmap_path)); return false; } const uint256 asmap_version = SerializeHash(asmap); node.connman->SetAsmap(std::move(asmap)); LogPrintf("Using asmap version %s for IP bucketing\n", asmap_version.ToString()); } else { LogPrintf("Using /16 prefix for IP bucketing\n"); } #if ENABLE_ZMQ g_zmq_notification_interface = CZMQNotificationInterface::Create(); if (g_zmq_notification_interface) { RegisterValidationInterface(g_zmq_notification_interface); } #endif // ********************************************************* Step 7: load block chain fReindex = args.GetBoolArg("-reindex", false); bool fReindexChainState = args.GetBoolArg("-reindex-chainstate", false); // cache size calculations int64_t nTotalCache = (args.GetArg("-dbcache", nDefaultDbCache) << 20); nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache int64_t nBlockTreeDBCache = std::min(nTotalCache / 8, nMaxBlockDBCache << 20); nTotalCache -= nBlockTreeDBCache; int64_t nTxIndexCache = std::min(nTotalCache / 8, args.GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxTxIndexCache << 20 : 0); nTotalCache -= nTxIndexCache; int64_t filter_index_cache = 0; if (!g_enabled_filter_types.empty()) { size_t n_indexes = g_enabled_filter_types.size(); int64_t max_cache = std::min(nTotalCache / 8, max_filter_index_cache << 20); filter_index_cache = max_cache / n_indexes; nTotalCache -= filter_index_cache * n_indexes; } int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache nTotalCache -= nCoinDBCache; int64_t nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache int64_t nMempoolSizeMax = args.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000; LogPrintf("Cache configuration:\n"); LogPrintf("* Using %.1f MiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024)); if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) { LogPrintf("* Using %.1f MiB for transaction index database\n", nTxIndexCache * (1.0 / 1024 / 1024)); } for (BlockFilterType filter_type : g_enabled_filter_types) { LogPrintf("* Using %.1f MiB for %s block filter index database\n", filter_index_cache * (1.0 / 1024 / 1024), BlockFilterTypeName(filter_type)); } LogPrintf("* Using %.1f MiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024)); LogPrintf("* Using %.1f MiB for in-memory UTXO set (plus up to %.1f MiB of unused mempool space)\n", nCoinCacheUsage * (1.0 / 1024 / 1024), nMempoolSizeMax * (1.0 / 1024 / 1024)); bool fLoaded = false; while (!fLoaded && !ShutdownRequested()) { bool fReset = fReindex; auto is_coinsview_empty = [&](CChainState* chainstate) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { return fReset || fReindexChainState || chainstate->CoinsTip().GetBestBlock().IsNull(); }; bilingual_str strLoadError; uiInterface.InitMessage(_("Loading block index...").translated); do { const int64_t load_block_index_start_time = GetTimeMillis(); try { LOCK(cs_main); chainman.InitializeChainstate(*Assert(node.mempool)); chainman.m_total_coinstip_cache = nCoinCacheUsage; chainman.m_total_coinsdb_cache = nCoinDBCache; UnloadBlockIndex(node.mempool.get(), chainman); // new CBlockTreeDB tries to delete the existing file, which // fails if it's still open from the previous loop. Close it first: pblocktree.reset(); pblocktree.reset(new CBlockTreeDB(nBlockTreeDBCache, false, fReset)); if (fReset) { pblocktree->WriteReindexing(true); //If we're reindexing in prune mode, wipe away unusable block files and all undo data files if (fPruneMode) CleanupBlockRevFiles(); } if (ShutdownRequested()) break; // LoadBlockIndex will load fHavePruned if we've ever removed a // block file from disk. // Note that it also sets fReindex based on the disk flag! // From here on out fReindex and fReset mean something different! if (!chainman.LoadBlockIndex(chainparams)) { if (ShutdownRequested()) break; strLoadError = _("Error loading block database"); break; } // If the loaded chain has a wrong genesis, bail out immediately // (we're likely using a testnet datadir, or the other way around). if (!chainman.BlockIndex().empty() && !g_chainman.m_blockman.LookupBlockIndex(chainparams.GetConsensus().hashGenesisBlock)) { return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?")); } // Check for changed -prune state. What we are concerned about is a user who has pruned blocks // in the past, but is now trying to run unpruned. if (fHavePruned && !fPruneMode) { strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain"); break; } // At this point blocktree args are consistent with what's on disk. // If we're not mid-reindex (based on disk + args), add a genesis block on disk // (otherwise we use the one already on disk). // This is called again in ThreadImport after the reindex completes. if (!fReindex && !LoadGenesisBlock(chainparams)) { strLoadError = _("Error initializing block database"); break; } // At this point we're either in reindex or we've loaded a useful // block tree into BlockIndex()! bool failed_chainstate_init = false; for (CChainState* chainstate : chainman.GetAll()) { chainstate->InitCoinsDB( /* cache_size_bytes */ nCoinDBCache, /* in_memory */ false, /* should_wipe */ fReset || fReindexChainState); chainstate->CoinsErrorCatcher().AddReadErrCallback([]() { uiInterface.ThreadSafeMessageBox( _("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR); }); // If necessary, upgrade from older database format. // This is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate if (!chainstate->CoinsDB().Upgrade()) { strLoadError = _("Error upgrading chainstate database"); failed_chainstate_init = true; break; } // ReplayBlocks is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate if (!chainstate->ReplayBlocks(chainparams)) { strLoadError = _("Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate."); failed_chainstate_init = true; break; } // The on-disk coinsdb is now in a good state, create the cache chainstate->InitCoinsCache(nCoinCacheUsage); assert(chainstate->CanFlushToDisk()); if (!is_coinsview_empty(chainstate)) { // LoadChainTip initializes the chain based on CoinsTip()'s best block if (!chainstate->LoadChainTip(chainparams)) { strLoadError = _("Error initializing block database"); failed_chainstate_init = true; break; // out of the per-chainstate loop } assert(chainstate->m_chain.Tip() != nullptr); } } if (failed_chainstate_init) { break; // out of the chainstate activation do-while } } catch (const std::exception& e) { LogPrintf("%s\n", e.what()); strLoadError = _("Error opening block database"); break; } bool failed_rewind{false}; // Can't hold cs_main while calling RewindBlockIndex, so retrieve the relevant // chainstates beforehand. for (CChainState* chainstate : WITH_LOCK(::cs_main, return chainman.GetAll())) { if (!fReset) { // Note that RewindBlockIndex MUST run even if we're about to -reindex-chainstate. // It both disconnects blocks based on the chainstate, and drops block data in // BlockIndex() based on lack of available witness data. uiInterface.InitMessage(_("Rewinding blocks...").translated); if (!chainstate->RewindBlockIndex(chainparams)) { strLoadError = _( "Unable to rewind the database to a pre-fork state. " "You will need to redownload the blockchain"); failed_rewind = true; break; // out of the per-chainstate loop } } } if (failed_rewind) { break; // out of the chainstate activation do-while } bool failed_verification = false; try { LOCK(cs_main); for (CChainState* chainstate : chainman.GetAll()) { if (!is_coinsview_empty(chainstate)) { uiInterface.InitMessage(_("Verifying blocks...").translated); if (fHavePruned && args.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) { LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks\n", MIN_BLOCKS_TO_KEEP); } const CBlockIndex* tip = chainstate->m_chain.Tip(); RPCNotifyBlockChange(tip); if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) { strLoadError = _("The block database contains a block which appears to be from the future. " "This may be due to your computer's date and time being set incorrectly. " "Only rebuild the block database if you are sure that your computer's date and time are correct"); failed_verification = true; break; } // Only verify the DB of the active chainstate. This is fixed in later // work when we allow VerifyDB to be parameterized by chainstate. if (&::ChainstateActive() == chainstate && !CVerifyDB().VerifyDB( chainparams, &chainstate->CoinsDB(), args.GetArg("-checklevel", DEFAULT_CHECKLEVEL), args.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) { strLoadError = _("Corrupted block database detected"); failed_verification = true; break; } } } } catch (const std::exception& e) { LogPrintf("%s\n", e.what()); strLoadError = _("Error opening block database"); failed_verification = true; break; } if (!failed_verification) { fLoaded = true; LogPrintf(" block index %15dms\n", GetTimeMillis() - load_block_index_start_time); } } while(false); if (!fLoaded && !ShutdownRequested()) { // first suggest a reindex if (!fReset) { bool fRet = uiInterface.ThreadSafeQuestion( strLoadError + Untranslated(".\n\n") + _("Do you want to rebuild the block database now?"), strLoadError.original + ".\nPlease restart with -reindex or -reindex-chainstate to recover.", "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT); if (fRet) { fReindex = true; AbortShutdown(); } else { LogPrintf("Aborted block database rebuild. Exiting.\n"); return false; } } else { return InitError(strLoadError); } } } // As LoadBlockIndex can take several minutes, it's possible the user // requested to kill the GUI during the last operation. If so, exit. // As the program has not fully started yet, Shutdown() is possibly overkill. if (ShutdownRequested()) { LogPrintf("Shutdown requested. Exiting.\n"); return false; } // ********************************************************* Step 8: start indexers if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) { g_txindex = MakeUnique<TxIndex>(nTxIndexCache, false, fReindex); g_txindex->Start(); } for (const auto& filter_type : g_enabled_filter_types) { InitBlockFilterIndex(filter_type, filter_index_cache, false, fReindex); GetBlockFilterIndex(filter_type)->Start(); } // ********************************************************* Step 9: load wallet for (const auto& client : node.chain_clients) { if (!client->load()) { return false; } } // ********************************************************* Step 10: data directory maintenance // if pruning, unset the service bit and perform the initial blockstore prune // after any wallet rescanning has taken place. if (fPruneMode) { LogPrintf("Unsetting NODE_NETWORK on prune mode\n"); nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK); if (!fReindex) { LOCK(cs_main); for (CChainState* chainstate : chainman.GetAll()) { uiInterface.InitMessage(_("Pruning blockstore...").translated); chainstate->PruneAndFlush(); } } } if (chainparams.GetConsensus().SegwitHeight != std::numeric_limits<int>::max()) { // Advertise witness capabilities. // The option to not set NODE_WITNESS is only used in the tests and should be removed. nLocalServices = ServiceFlags(nLocalServices | NODE_WITNESS); } // ********************************************************* Step 11: import blocks if (!CheckDiskSpace(GetDataDir())) { InitError(strprintf(_("Error: Disk space is low for %s"), GetDataDir())); return false; } if (!CheckDiskSpace(GetBlocksDir())) { InitError(strprintf(_("Error: Disk space is low for %s"), GetBlocksDir())); return false; } // Either install a handler to notify us when genesis activates, or set fHaveGenesis directly. // No locking, as this happens before any background thread is started. boost::signals2::connection block_notify_genesis_wait_connection; if (::ChainActive().Tip() == nullptr) { block_notify_genesis_wait_connection = uiInterface.NotifyBlockTip_connect(std::bind(BlockNotifyGenesisWait, std::placeholders::_2)); } else { fHaveGenesis = true; } #if HAVE_SYSTEM const std::string block_notify = args.GetArg("-blocknotify", ""); if (!block_notify.empty()) { uiInterface.NotifyBlockTip_connect([block_notify](SynchronizationState sync_state, const CBlockIndex* pBlockIndex) { if (sync_state != SynchronizationState::POST_INIT || !pBlockIndex) return; std::string command = block_notify; boost::replace_all(command, "%s", pBlockIndex->GetBlockHash().GetHex()); std::thread t(runCommand, command); t.detach(); // thread runs free }); } #endif std::vector<fs::path> vImportFiles; for (const std::string& strFile : args.GetArgs("-loadblock")) { vImportFiles.push_back(strFile); } g_load_block = std::thread(&TraceThread<std::function<void()>>, "loadblk", [=, &chainman, &args] { ThreadImport(chainman, vImportFiles, args); }); // Wait for genesis block to be processed { WAIT_LOCK(g_genesis_wait_mutex, lock); // We previously could hang here if StartShutdown() is called prior to // ThreadImport getting started, so instead we just wait on a timer to // check ShutdownRequested() regularly. while (!fHaveGenesis && !ShutdownRequested()) { g_genesis_wait_cv.wait_for(lock, std::chrono::milliseconds(500)); } block_notify_genesis_wait_connection.disconnect(); } if (ShutdownRequested()) { return false; } // ********************************************************* Step 12: start node int chain_active_height; //// debug print { LOCK(cs_main); LogPrintf("block tree size = %u\n", chainman.BlockIndex().size()); chain_active_height = chainman.ActiveChain().Height(); if (tip_info) { tip_info->block_height = chain_active_height; tip_info->block_time = chainman.ActiveChain().Tip() ? chainman.ActiveChain().Tip()->GetBlockTime() : Params().GenesisBlock().GetBlockTime(); tip_info->verification_progress = GuessVerificationProgress(Params().TxData(), chainman.ActiveChain().Tip()); } if (tip_info && ::pindexBestHeader) { tip_info->header_height = ::pindexBestHeader->nHeight; tip_info->header_time = ::pindexBestHeader->GetBlockTime(); } } LogPrintf("nBestHeight = %d\n", chain_active_height); if (node.peerman) node.peerman->SetBestHeight(chain_active_height); Discover(); // Map ports with UPnP or NAT-PMP. StartMapPort(args.GetBoolArg("-upnp", DEFAULT_UPNP), gArgs.GetBoolArg("-natpmp", DEFAULT_NATPMP)); CConnman::Options connOptions; connOptions.nLocalServices = nLocalServices; connOptions.nMaxConnections = nMaxConnections; connOptions.m_max_outbound_full_relay = std::min(MAX_OUTBOUND_FULL_RELAY_CONNECTIONS, connOptions.nMaxConnections); connOptions.m_max_outbound_block_relay = std::min(MAX_BLOCK_RELAY_ONLY_CONNECTIONS, connOptions.nMaxConnections-connOptions.m_max_outbound_full_relay); connOptions.nMaxAddnode = MAX_ADDNODE_CONNECTIONS; connOptions.nMaxFeeler = MAX_FEELER_CONNECTIONS; connOptions.uiInterface = &uiInterface; connOptions.m_banman = node.banman.get(); connOptions.m_msgproc = node.peerman.get(); connOptions.nSendBufferMaxSize = 1000 * args.GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER); connOptions.nReceiveFloodSize = 1000 * args.GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER); connOptions.m_added_nodes = args.GetArgs("-addnode"); connOptions.nMaxOutboundLimit = 1024 * 1024 * args.GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET); connOptions.m_peer_connect_timeout = peer_connect_timeout; for (const std::string& bind_arg : args.GetArgs("-bind")) { CService bind_addr; const size_t index = bind_arg.rfind('='); if (index == std::string::npos) { if (Lookup(bind_arg, bind_addr, GetListenPort(), false)) { connOptions.vBinds.push_back(bind_addr); continue; } } else { const std::string network_type = bind_arg.substr(index + 1); if (network_type == "onion") { const std::string truncated_bind_arg = bind_arg.substr(0, index); if (Lookup(truncated_bind_arg, bind_addr, BaseParams().OnionServiceTargetPort(), false)) { connOptions.onion_binds.push_back(bind_addr); continue; } } } return InitError(ResolveErrMsg("bind", bind_arg)); } if (connOptions.onion_binds.empty()) { connOptions.onion_binds.push_back(DefaultOnionServiceTarget()); } if (args.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)) { const auto bind_addr = connOptions.onion_binds.front(); if (connOptions.onion_binds.size() > 1) { InitWarning(strprintf(_("More than one onion bind address is provided. Using %s for the automatically created Tor onion service."), bind_addr.ToStringIPPort())); } StartTorControl(bind_addr); } for (const std::string& strBind : args.GetArgs("-whitebind")) { NetWhitebindPermissions whitebind; bilingual_str error; if (!NetWhitebindPermissions::TryParse(strBind, whitebind, error)) return InitError(error); connOptions.vWhiteBinds.push_back(whitebind); } for (const auto& net : args.GetArgs("-whitelist")) { NetWhitelistPermissions subnet; bilingual_str error; if (!NetWhitelistPermissions::TryParse(net, subnet, error)) return InitError(error); connOptions.vWhitelistedRange.push_back(subnet); } connOptions.vSeedNodes = args.GetArgs("-seednode"); // Initiate outbound connections unless connect=0 connOptions.m_use_addrman_outgoing = !args.IsArgSet("-connect"); if (!connOptions.m_use_addrman_outgoing) { const auto connect = args.GetArgs("-connect"); if (connect.size() != 1 || connect[0] != "0") { connOptions.m_specified_outgoing = connect; } } if (!node.connman->Start(*node.scheduler, connOptions)) { return false; } // ********************************************************* Step 13: finished SetRPCWarmupFinished(); uiInterface.InitMessage(_("Done loading").translated); for (const auto& client : node.chain_clients) { client->start(*node.scheduler); } BanMan* banman = node.banman.get(); node.scheduler->scheduleEvery([banman]{ banman->DumpBanlist(); }, DUMP_BANS_INTERVAL); #if HAVE_SYSTEM StartupNotify(args); #endif return true; }
// Copyright (c) 2018, The TurtleCoin Developers // // Please see the included LICENSE file for more information. #include "CryptoNote.h" #include "CryptoTypes.h" #include "common/StringTools.h" #include "crypto/crypto.h" #include "crypto/multisig.h" #include <assert.h> #include <chrono> #include <config/CliHeader.h> #include <cxxopts.hpp> #include <iostream> #define PERFORMANCE_ITERATIONS 1000 #define PERFORMANCE_ITERATIONS_LONG_MULTIPLIER 10 using namespace Crypto; using namespace CryptoNote; const std::string INPUT_DATA = "0100fb8e8ac805899323371bb790db19218afd8db8e3755d8b90f39b3d5506a9abce4fa912244500000000e" "e8146d49fa93ee724deb57d12cbc6c6f3b924d946127c7a97418f9348828f0f02"; const std::string CN_FAST_HASH = "b542df5b6e7f5f05275c98e7345884e2ac726aeeb07e03e44e0389eb86cd05f0"; const std::string CN_SLOW_HASH_V0 = "1b606a3f4a07d6489a1bcd07697bd16696b61c8ae982f61a90160f4e52828a7f"; const std::string CN_SLOW_HASH_V1 = "c9fae8425d8688dc236bcdbc42fdb42d376c6ec190501aa84b04a4b4cf1ee122"; const std::string CN_SLOW_HASH_V2 = "871fcd6823f6a879bb3f33951c8e8e891d4043880b02dfa1bb3be498b50e7578"; const std::string CN_LITE_SLOW_HASH_V0 = "28a22bad3f93d1408fca472eb5ad1cbe75f21d053c8ce5b3af105a57713e21dd"; const std::string CN_LITE_SLOW_HASH_V1 = "87c4e570653eb4c2b42b7a0d546559452dfab573b82ec52f152b7ff98e79446f"; const std::string CN_LITE_SLOW_HASH_V2 = "b7e78fab22eb19cb8c9c3afe034fb53390321511bab6ab4915cd538a630c3c62"; const std::string CN_DARK_SLOW_HASH_V0 = "bea42eadd78614f875e55bb972aa5ec54a5edf2dd7068220fda26bf4b1080fb8"; const std::string CN_DARK_SLOW_HASH_V1 = "d18cb32bd5b465e5a7ba4763d60f88b5792f24e513306f1052954294b737e871"; const std::string CN_DARK_SLOW_HASH_V2 = "a18a14d94efea108757a42633a1b4d4dc11838084c3c4347850d39ab5211a91f"; const std::string CN_DARK_LITE_SLOW_HASH_V0 = "faa7884d9c08126eb164814aeba6547b5d6064277a09fb6b414f5dbc9d01eb2b"; const std::string CN_DARK_LITE_SLOW_HASH_V1 = "c75c010780fffd9d5e99838eb093b37c0dd015101c9d298217866daa2993d277"; const std::string CN_DARK_LITE_SLOW_HASH_V2 = "fdceb794c1055977a955f31c576a8be528a0356ee1b0a1f9b7f09e20185cda28"; const std::string CN_TURTLE_SLOW_HASH_V0 = "546c3f1badd7c1232c7a3b88cdb013f7f611b7bd3d1d2463540fccbd12997982"; const std::string CN_TURTLE_SLOW_HASH_V1 = "29e7831780a0ab930e0fe3b965f30e8a44d9b3f9ad2241d67cfbfea3ed62a64e"; const std::string CN_TURTLE_SLOW_HASH_V2 = "fc67dfccb5fc90d7855ae903361eabd76f1e40a22a72ad3ef2d6ad27b5a60ce5"; const std::string CN_TURTLE_LITE_SLOW_HASH_V0 = "5e1891a15d5d85c09baf4a3bbe33675cfa3f77229c8ad66c01779e590528d6d3"; const std::string CN_TURTLE_LITE_SLOW_HASH_V1 = "ae7f864a7a2f2b07dcef253581e60a014972b9655a152341cb989164761c180a"; const std::string CN_TURTLE_LITE_SLOW_HASH_V2 = "b2172ec9466e1aee70ec8572a14c233ee354582bcb93f869d429744de5726a26"; const std::string CHUKWA_V1 = "c0dad0eeb9c52e92a1c3aa5b76a3cb90bd7376c28dce191ceeb1096e3a390d2e"; const std::string CHUKWA_V2 = "3578c135261366a7bac407b8c0ff50f3ad96f096ec2813e9644e6e77a43f803d"; const std::string CN_SOFT_SHELL_V0[] = { "5e1891a15d5d85c09baf4a3bbe33675cfa3f77229c8ad66c01779e590528d6d3", "e1239347694df77cab780b7ec8920ec6f7e48ecef1d8c368e06708c08e1455f1", "118a03801c564d12f7e68972419303fe06f7a54ab8f44a8ce7deafbc6b1b5183", "8be48f7955eb3f9ac2275e445fe553f3ef359ea5c065cde98ff83011f407a0ec", "d33da3541960046e846530dcc9872b1914a62c09c7d732bff03bec481866ae48", "8be48f7955eb3f9ac2275e445fe553f3ef359ea5c065cde98ff83011f407a0ec", "118a03801c564d12f7e68972419303fe06f7a54ab8f44a8ce7deafbc6b1b5183", "e1239347694df77cab780b7ec8920ec6f7e48ecef1d8c368e06708c08e1455f1", "5e1891a15d5d85c09baf4a3bbe33675cfa3f77229c8ad66c01779e590528d6d3", "e1239347694df77cab780b7ec8920ec6f7e48ecef1d8c368e06708c08e1455f1", "118a03801c564d12f7e68972419303fe06f7a54ab8f44a8ce7deafbc6b1b5183", "8be48f7955eb3f9ac2275e445fe553f3ef359ea5c065cde98ff83011f407a0ec", "d33da3541960046e846530dcc9872b1914a62c09c7d732bff03bec481866ae48", "8be48f7955eb3f9ac2275e445fe553f3ef359ea5c065cde98ff83011f407a0ec", "118a03801c564d12f7e68972419303fe06f7a54ab8f44a8ce7deafbc6b1b5183", "e1239347694df77cab780b7ec8920ec6f7e48ecef1d8c368e06708c08e1455f1", "5e1891a15d5d85c09baf4a3bbe33675cfa3f77229c8ad66c01779e590528d6d3"}; const std::string CN_SOFT_SHELL_V1[] = { "ae7f864a7a2f2b07dcef253581e60a014972b9655a152341cb989164761c180a", "ce8687bdd08c49bd1da3a6a74bf28858670232c1a0173ceb2466655250f9c56d", "ddb6011d400ac8725995fb800af11646bb2fef0d8b6136b634368ad28272d7f4", "02576f9873dc9c8b1b0fc14962982734dfdd41630fc936137a3562b8841237e1", "d37e2785ab7b3d0a222940bf675248e7b96054de5c82c5f0b141014e136eadbc", "02576f9873dc9c8b1b0fc14962982734dfdd41630fc936137a3562b8841237e1", "ddb6011d400ac8725995fb800af11646bb2fef0d8b6136b634368ad28272d7f4", "ce8687bdd08c49bd1da3a6a74bf28858670232c1a0173ceb2466655250f9c56d", "ae7f864a7a2f2b07dcef253581e60a014972b9655a152341cb989164761c180a", "ce8687bdd08c49bd1da3a6a74bf28858670232c1a0173ceb2466655250f9c56d", "ddb6011d400ac8725995fb800af11646bb2fef0d8b6136b634368ad28272d7f4", "02576f9873dc9c8b1b0fc14962982734dfdd41630fc936137a3562b8841237e1", "d37e2785ab7b3d0a222940bf675248e7b96054de5c82c5f0b141014e136eadbc", "02576f9873dc9c8b1b0fc14962982734dfdd41630fc936137a3562b8841237e1", "ddb6011d400ac8725995fb800af11646bb2fef0d8b6136b634368ad28272d7f4", "ce8687bdd08c49bd1da3a6a74bf28858670232c1a0173ceb2466655250f9c56d", "ae7f864a7a2f2b07dcef253581e60a014972b9655a152341cb989164761c180a"}; const std::string CN_SOFT_SHELL_V2[] = { "b2172ec9466e1aee70ec8572a14c233ee354582bcb93f869d429744de5726a26", "b2623a2b041dc5ae3132b964b75e193558c7095e725d882a3946aae172179cf1", "141878a7b58b0f57d00b8fc2183cce3517d9d68becab6fee52abb3c1c7d0805b", "4646f9919791c28f0915bc0005ed619bee31d42359f7a8af5de5e1807e875364", "3fedc7ab0f8d14122fc26062de1af7a6165755fcecdf0f12fa3ccb3ff63629d0", "4646f9919791c28f0915bc0005ed619bee31d42359f7a8af5de5e1807e875364", "141878a7b58b0f57d00b8fc2183cce3517d9d68becab6fee52abb3c1c7d0805b", "b2623a2b041dc5ae3132b964b75e193558c7095e725d882a3946aae172179cf1", "b2172ec9466e1aee70ec8572a14c233ee354582bcb93f869d429744de5726a26", "b2623a2b041dc5ae3132b964b75e193558c7095e725d882a3946aae172179cf1", "141878a7b58b0f57d00b8fc2183cce3517d9d68becab6fee52abb3c1c7d0805b", "4646f9919791c28f0915bc0005ed619bee31d42359f7a8af5de5e1807e875364", "3fedc7ab0f8d14122fc26062de1af7a6165755fcecdf0f12fa3ccb3ff63629d0", "4646f9919791c28f0915bc0005ed619bee31d42359f7a8af5de5e1807e875364", "141878a7b58b0f57d00b8fc2183cce3517d9d68becab6fee52abb3c1c7d0805b", "b2623a2b041dc5ae3132b964b75e193558c7095e725d882a3946aae172179cf1", "b2172ec9466e1aee70ec8572a14c233ee354582bcb93f869d429744de5726a26"}; static inline bool CompareHashes(const Hash leftHash, const std::string right) { Hash rightHash = Hash(); if (!Common::podFromHex(right, rightHash)) { return false; } return (leftHash == rightHash); } /* Hacky way to check if we're testing a v1 hash and thus should skip data < 43 bytes */ bool need43BytesOfData(std::string hashFunctionName) { return hashFunctionName.find("v1") != std::string::npos; } /* Bit of hackery so we can get the variable name of the passed in function. This way we can print the test we are currently performing. */ #define TEST_HASH_FUNCTION(hashFunction, expectedOutput) \ testHashFunction(hashFunction, expectedOutput, #hashFunction, -1) #define TEST_HASH_FUNCTION_WITH_HEIGHT(hashFunction, expectedOutput, height) \ testHashFunction(hashFunction, expectedOutput, #hashFunction, height, height) template<typename T, typename... Args> void testHashFunction( T hashFunction, std::string expectedOutput, std::string hashFunctionName, int64_t height, Args &&... args) { const BinaryArray &rawData = Common::fromHex(INPUT_DATA); if (need43BytesOfData(hashFunctionName) && rawData.size() < 43) { return; } Hash hash = Hash(); /* Perform the hash, with a height if given */ hashFunction(rawData.data(), rawData.size(), hash, std::forward<Args>(args)...); if (height == -1) { std::cout << hashFunctionName << ": " << hash << std::endl; } else { std::cout << hashFunctionName << " (" << height << "): " << hash << std::endl; } /* Verify the hash is as expected */ if (!CompareHashes(hash, expectedOutput)) { std::cout << "Hashes are not equal!\n" << "Expected: " << expectedOutput << "\nActual: " << hash << "\nTerminating."; exit(1); } } /* Bit of hackery so we can get the variable name of the passed in function. This way we can print the test we are currently performing. */ #define BENCHMARK(hashFunction, iterations) benchmark(hashFunction, #hashFunction, iterations) template<typename T> void benchmark(T hashFunction, std::string hashFunctionName, uint64_t iterations) { const BinaryArray &rawData = Common::fromHex(INPUT_DATA); if (need43BytesOfData(hashFunctionName) && rawData.size() < 43) { return; } Hash hash = Hash(); auto startTimer = std::chrono::high_resolution_clock::now(); for (uint64_t i = 0; i < iterations; i++) { hashFunction(rawData.data(), rawData.size(), hash); } auto elapsedTime = std::chrono::high_resolution_clock::now() - startTimer; std::cout << hashFunctionName << ": " << (iterations / std::chrono::duration_cast<std::chrono::seconds>(elapsedTime).count()) << " H/s\n"; } void benchmarkUnderivePublicKey() { Crypto::KeyDerivation derivation; Crypto::PublicKey txPublicKey; Common::podFromHex("f235acd76ee38ec4f7d95123436200f9ed74f9eb291b1454fbc30742481be1ab", txPublicKey); Crypto::SecretKey privateViewKey; Common::podFromHex("89df8c4d34af41a51cfae0267e8254cadd2298f9256439fa1cfa7e25ee606606", privateViewKey); Crypto::generate_key_derivation(txPublicKey, privateViewKey, derivation); const uint64_t loopIterations = 600000; auto startTimer = std::chrono::high_resolution_clock::now(); Crypto::PublicKey spendKey; Crypto::PublicKey outputKey; Common::podFromHex("4a078e76cd41a3d3b534b83dc6f2ea2de500b653ca82273b7bfad8045d85a400", outputKey); for (uint64_t i = 0; i < loopIterations; i++) { /* Use i as output index to prevent optimization */ Crypto::underive_public_key(derivation, i, outputKey, spendKey); } auto elapsedTime = std::chrono::high_resolution_clock::now() - startTimer; /* Need to use microseconds here then divide by 1000 - otherwise we'll just get '0' */ const auto timePerDerivation = std::chrono::duration_cast<std::chrono::microseconds>(elapsedTime).count() / loopIterations; std::cout << "Time to perform underivePublicKey: " << timePerDerivation / 1000.0 << " ms" << std::endl; } void benchmarkGenerateKeyDerivation() { Crypto::KeyDerivation derivation; Crypto::PublicKey txPublicKey; Common::podFromHex("f235acd76ee38ec4f7d95123436200f9ed74f9eb291b1454fbc30742481be1ab", txPublicKey); Crypto::SecretKey privateViewKey; Common::podFromHex("89df8c4d34af41a51cfae0267e8254cadd2298f9256439fa1cfa7e25ee606606", privateViewKey); const uint64_t loopIterations = 60000; auto startTimer = std::chrono::high_resolution_clock::now(); for (uint64_t i = 0; i < loopIterations; i++) { Crypto::generate_key_derivation(txPublicKey, privateViewKey, derivation); } auto elapsedTime = std::chrono::high_resolution_clock::now() - startTimer; const auto timePerDerivation = std::chrono::duration_cast<std::chrono::microseconds>(elapsedTime).count() / loopIterations; std::cout << "Time to perform generateKeyDerivation: " << timePerDerivation / 1000.0 << " ms" << std::endl; } void TestDeterministicSubwalletCreation( const std::string baseSpendKey, const uint64_t subWalletIndex, const std::string expectedSpendKey) { Crypto::SecretKey f_baseSpendKey; if (!Common::podFromHex(baseSpendKey, f_baseSpendKey)) { std::cout << "Could not decode base private spend key!\nTerminating..."; exit(1); } Crypto::SecretKey f_expectedSpendKey; if (!Common::podFromHex(expectedSpendKey, f_expectedSpendKey)) { std::cout << "Could not decode expected private spend key!\nTerminating..."; exit(1); } const auto [subwalletPrivateKey, subwalletPublicKey] = Crypto::generate_deterministic_subwallet_keys(f_baseSpendKey, subWalletIndex); if (subwalletPrivateKey != f_expectedSpendKey) { std::cout << "Could not deterministically create subwallet spend keys!\n" << "Expected: " << expectedSpendKey << "\nActual: " << subwalletPrivateKey << "\nTerminating."; exit(1); } } int main(int argc, char **argv) { bool o_help, o_version, o_benchmark; int o_iterations; cxxopts::Options options(argv[0], getProjectCLIHeader()); options.add_options("Core")( "h,help", "Display this help message", cxxopts::value<bool>(o_help)->implicit_value("true"))( "v,version", "Output software version information", cxxopts::value<bool>(o_version)->default_value("false")->implicit_value("true")); options.add_options("Performance Testing")( "b,benchmark", "Run quick performance benchmark", cxxopts::value<bool>(o_benchmark)->default_value("false")->implicit_value("true"))( "i,iterations", "The number of iterations for the benchmark test. Minimum of 1,000 iterations required.", cxxopts::value<int>(o_iterations)->default_value(std::to_string(PERFORMANCE_ITERATIONS)), "#"); try { auto result = options.parse(argc, argv); } catch (const cxxopts::OptionException &e) { std::cout << "Error: Unable to parse command line argument options: " << e.what() << std::endl << std::endl; std::cout << options.help({}) << std::endl; exit(1); } if (o_help) // Do we want to display the help message? { std::cout << options.help({}) << std::endl; exit(0); } else if (o_version) // Do we want to display the software version? { std::cout << getProjectCLIHeader() << std::endl; exit(0); } if (o_iterations < 1000 && o_benchmark) { std::cout << std::endl << "Error: The number of --iterations should be at least 1,000 for reasonable accuracy" << std::endl; exit(1); } int o_iterations_long = o_iterations * PERFORMANCE_ITERATIONS_LONG_MULTIPLIER; try { std::cout << getProjectCLIHeader() << std::endl; std::cout << std::endl << "Test Crypto Primitives" << std::endl << std::endl; { std::cout << "Crypto::crypto_ops::prepareRingSignatures: "; Crypto::Hash txPrefixHash; Common::podFromHex("b542df5b6e7f5f05275c98e7345884e2ac726aeeb07e03e44e0389eb86cd05f0", txPrefixHash); Crypto::KeyImage keyImage("6865866ed8a25824e042e21dd36e946836b58b03366e489aecf979f444f599b0"); std::vector<Crypto::PublicKey> publicKeys; publicKeys.push_back(Crypto::PublicKey("492390897da1cabd3886e3eff43ad1d04aa510a905bec0acd31a0a2f260e7862")); publicKeys.push_back(Crypto::PublicKey("7644ccb5410cca2be18b033e5f7497aeeeafd1d8f317f29cba4803e4306aa402")); publicKeys.push_back(Crypto::PublicKey("bb9a956ffdf8159ad69474e6b0811316c44a17a540d5e39a44642d4d933a6460")); publicKeys.push_back(Crypto::PublicKey("e1cd9ccdfdf2b3a45ac2cfd1e29185d22c185742849f52368c3cdd1c0ce499c0")); Crypto::SecretKey privateEmpheremal("73a8e577d58f7c11992201d4014ac7eef39c1e9f6f6d78673103de60a0c3240b"); const auto [success, signatures, k] = Crypto::crypto_ops::prepareRingSignatures(txPrefixHash, keyImage, publicKeys, 3); if (!success) { std::cout << "failed" << std::endl; exit(1); } std::cout << "passed" << std::endl; } { std::cout << "Crypto::crypto_ops::generateRingSignatures: "; Crypto::Hash txPrefixHash; Common::podFromHex("b542df5b6e7f5f05275c98e7345884e2ac726aeeb07e03e44e0389eb86cd05f0", txPrefixHash); Crypto::KeyImage keyImage("6865866ed8a25824e042e21dd36e946836b58b03366e489aecf979f444f599b0"); std::vector<Crypto::PublicKey> publicKeys; publicKeys.push_back(Crypto::PublicKey("492390897da1cabd3886e3eff43ad1d04aa510a905bec0acd31a0a2f260e7862")); publicKeys.push_back(Crypto::PublicKey("7644ccb5410cca2be18b033e5f7497aeeeafd1d8f317f29cba4803e4306aa402")); publicKeys.push_back(Crypto::PublicKey("bb9a956ffdf8159ad69474e6b0811316c44a17a540d5e39a44642d4d933a6460")); publicKeys.push_back(Crypto::PublicKey("e1cd9ccdfdf2b3a45ac2cfd1e29185d22c185742849f52368c3cdd1c0ce499c0")); Crypto::SecretKey privateEmpheremal("73a8e577d58f7c11992201d4014ac7eef39c1e9f6f6d78673103de60a0c3240b"); const auto [success, signatures] = Crypto::crypto_ops::generateRingSignatures(txPrefixHash, keyImage, publicKeys, privateEmpheremal, 3); if (!success) { std::cout << "failed" << std::endl; exit(1); } bool check = Crypto::crypto_ops::checkRingSignature(txPrefixHash, keyImage, publicKeys, signatures); if (!check) { std::cout << "failed" << std::endl; exit(1); } std::cout << "passed" << std::endl; } { std::cout << "Crypto::generate_deterministic_subwallet_keys: "; TestDeterministicSubwalletCreation( "dd0c02d3202634821b4d9d91b63d919725f5c3e97e803f3512e52fb0dc2aab0c", 0, "dd0c02d3202634821b4d9d91b63d919725f5c3e97e803f3512e52fb0dc2aab0c"); TestDeterministicSubwalletCreation( "dd0c02d3202634821b4d9d91b63d919725f5c3e97e803f3512e52fb0dc2aab0c", 1, "c55cbe4fd1c49dca5958fa1c7b9212c2dbf3fd5bfec84de741d434056e298600"); TestDeterministicSubwalletCreation( "dd0c02d3202634821b4d9d91b63d919725f5c3e97e803f3512e52fb0dc2aab0c", 2, "9813c40428ed9b380a2f72bac1374a9d3852a974b0527e003cbc93afab764d01"); TestDeterministicSubwalletCreation( "dd0c02d3202634821b4d9d91b63d919725f5c3e97e803f3512e52fb0dc2aab0c", 64, "29c2afed13271e2bb3321c2483356fd8798f2709af4de3906b6627ec71727108"); TestDeterministicSubwalletCreation( "dd0c02d3202634821b4d9d91b63d919725f5c3e97e803f3512e52fb0dc2aab0c", 65, "0c6b5fff72260832558e35c38e690072503211af065056862288dc7fd992350a"); std::cout << "passed" << std::endl; } std::cout << std::endl << "Test Multisig Primitives" << std::endl << std::endl; { std::cout << "Crypto::Multisig::calculate_multisig_private_keys: "; Crypto::SecretKey privateKey("a0ba0cae34ce1133b9cb658e5d0a56440608622a64562ac360907a2c68ea130d"); std::vector<Crypto::PublicKey> publicKeys; publicKeys.push_back(Crypto::PublicKey("ba719ff6486ae5ab5ea0c7e05f6b42468f898bd366f83a4d165e396c1f7c5eec")); publicKeys.push_back(Crypto::PublicKey("fd524a5384bf5044feeb61f19866e11f74b8dbf5e7d050238046b04289a31849")); std::vector<Crypto::SecretKey> multisigKeys = Crypto::Multisig::calculate_multisig_private_keys(privateKey, publicKeys); if (multisigKeys[0] != Crypto::SecretKey("ca67bdeba4cc489c86b0e6be24ed86ee75fd7e4caaf6566ea3b241946f40f901") || multisigKeys[1] != Crypto::SecretKey("98c2625a77504c46fb4d83bdf2c5dee505d4e3d0d30005bac636b0d49f90420f")) { std::cout << "failed" << std::endl; exit(1); } std::cout << "passed" << std::endl; } { std::cout << "Crypto::Multisig::calculate_shared_public_key: "; std::vector<Crypto::PublicKey> publicKeys; publicKeys.push_back(Crypto::PublicKey("6bce43e0d797b9ee674db41c173f9b147fab6841fed36e97d434bd7c6f5b81d5")); publicKeys.push_back(Crypto::PublicKey("ba719ff6486ae5ab5ea0c7e05f6b42468f898bd366f83a4d165e396c1f7c5eec")); Crypto::PublicKey sharedPublicKey = Crypto::Multisig::calculate_shared_public_key(publicKeys); if (sharedPublicKey != Crypto::PublicKey("caa8f9aaf673ff2c055025942eeefde720a71281420ec8c42f0a817225db032b")) { std::cout << "failed" << std::endl; exit(1); } std::cout << "passed" << std::endl; } { std::cout << "Crypto::Multisig::calculate_shared_private_key: "; std::vector<Crypto::SecretKey> secretKeys; secretKeys.push_back(Crypto::SecretKey("01d85bf9ce5583c7a1039f2c2695cb562bf1ea97636bbaf9051af01dddc89e0b")); secretKeys.push_back(Crypto::SecretKey("650110a79f0353624f0fa14aaaf8c5af405ddb009c3127366e5b8591ecec9704")); Crypto::SecretKey sharedPrivateKey = Crypto::Multisig::calculate_shared_private_key(secretKeys); if (sharedPrivateKey != Crypto::SecretKey("7905764354f6c3d11a7648d4f193b2f16b4ec698ff9ce12f747575afc9b53600")) { std::cout << "failed" << std::endl; exit(1); } std::cout << "passed" << std::endl; } { std::cout << "Crypto::Multisig::restore_key_image: "; Crypto::PublicKey publicEphemeral("e1cd9ccdfdf2b3a45ac2cfd1e29185d22c185742849f52368c3cdd1c0ce499c0"); Crypto::KeyDerivation derivation("9475ebaa9f869b06d967aa0ca09d1632f4b8a383211c8a66e39021bc04d80fc4"); std::vector<Crypto::KeyImage> partialKeyImages; partialKeyImages.push_back( Crypto::KeyImage("f67f9a1a525d9f34386c8d8f2bfebe15e653b7fbbf561da8531eedbf5dd06317")); partialKeyImages.push_back( Crypto::KeyImage("b04a322530870398ce1f1bd4df2e40155425a8ed45fb8f4637f22c648cbac2f2")); Crypto::KeyImage keyImage = Crypto::Multisig::restore_key_image(publicEphemeral, derivation, 2, partialKeyImages); if (keyImage != Crypto::KeyImage("6865866ed8a25824e042e21dd36e946836b58b03366e489aecf979f444f599b0")) { std::cout << "failed" << std::endl; exit(1); } std::cout << "passed" << std::endl; } { std::cout << "Crypto::Multisig::generate_partial_signing_key: "; Crypto::Signature signature("d3b4f642eb7049e00b17130ec95d47e878c756a205766418687667fe4877920500000000000000" "00000000000000000000000000000000000000000000000000"); Crypto::SecretKey privateSpendKey("a0ba0cae34ce1133b9cb658e5d0a56440608622a64562ac360907a2c68ea130d"); Crypto::SecretKey partialKey = Crypto::Multisig::generate_partial_signing_key(signature, privateSpendKey); if (partialKey != Crypto::SecretKey("bea03f1dcdc3a6375d883afa86f88e4a43606bcc2b0c9b00e313813f7436ef03")) { std::cout << "failed" << std::endl; exit(1); } std::cout << "passed" << std::endl; } { std::cout << "Crypto::Multisig::restore_ring_signatures: "; Crypto::KeyDerivation derivation("9475ebaa9f869b06d967aa0ca09d1632f4b8a383211c8a66e39021bc04d80fc4"); std::vector<Crypto::SecretKey> partialSigningKeys; partialSigningKeys.push_back( Crypto::SecretKey("bea03f1dcdc3a6375d883afa86f88e4a43606bcc2b0c9b00e313813f7436ef03")); partialSigningKeys.push_back( Crypto::SecretKey("14c09b9e8186a405f66fcd695c7ca675018f355eb3e28c240e3e647913f3c506")); Crypto::EllipticCurveScalar k("80bd5c68a280c2071c0a11be82e83c0fd2539660b21f7d9ff54a654f2a73c40d"); std::vector<Crypto::Signature> signatures; signatures.push_back(Crypto::Signature("719afc6be33058758d3aea7c382c6bf9340b62b2297fb93b42d0c984af8c0f0b08d" "7973924dc379e9b75ae5135ed6f40efc7418d597eaabdb69ebbb2b7630b05")); signatures.push_back(Crypto::Signature("128bfd98170ea31dfdcc2214e14e66a08e4f66d581d2317ab0c583e4573c9103ec1" "1bc5dd9e7f734b3f0fbd3c29eddea102275b9f871cb96b658ca0787261607")); signatures.push_back(Crypto::Signature("ef602f4a07c2b643b456d5587f682a7d44cb360cd83bdb2d176f3ad687027c0bf38" "8ab6dbf91dcec2fdfab865dd065c02905f1fa6c7b778cb9773cfd839bd300")); signatures.push_back(Crypto::Signature("d3b4f642eb7049e00b17130ec95d47e878c756a205766418687667fe48779205000" "0000000000000000000000000000000000000000000000000000000000000")); const auto [success, restoredSignatures] = Crypto::Multisig::restore_ring_signatures(derivation, 2, partialSigningKeys, 3, k, signatures); if (!success) { std::cout << "failed" << std::endl; exit(1); } Crypto::Hash txPrefixHash; Common::podFromHex("b542df5b6e7f5f05275c98e7345884e2ac726aeeb07e03e44e0389eb86cd05f0", txPrefixHash); Crypto::KeyImage keyImage("6865866ed8a25824e042e21dd36e946836b58b03366e489aecf979f444f599b0"); std::vector<Crypto::PublicKey> publicKeys; publicKeys.push_back(Crypto::PublicKey("492390897da1cabd3886e3eff43ad1d04aa510a905bec0acd31a0a2f260e7862")); publicKeys.push_back(Crypto::PublicKey("7644ccb5410cca2be18b033e5f7497aeeeafd1d8f317f29cba4803e4306aa402")); publicKeys.push_back(Crypto::PublicKey("bb9a956ffdf8159ad69474e6b0811316c44a17a540d5e39a44642d4d933a6460")); publicKeys.push_back(Crypto::PublicKey("e1cd9ccdfdf2b3a45ac2cfd1e29185d22c185742849f52368c3cdd1c0ce499c0")); bool check = Crypto::crypto_ops::checkRingSignature(txPrefixHash, keyImage, publicKeys, restoredSignatures); if (!check) { std::cout << "failed" << std::endl; exit(1); } std::cout << "passed" << std::endl; } std::cout << std::endl << "Input: " << INPUT_DATA << std::endl << std::endl; TEST_HASH_FUNCTION(cn_slow_hash_v0, CN_SLOW_HASH_V0); TEST_HASH_FUNCTION(cn_slow_hash_v1, CN_SLOW_HASH_V1); TEST_HASH_FUNCTION(cn_slow_hash_v2, CN_SLOW_HASH_V2); std::cout << std::endl; TEST_HASH_FUNCTION(cn_lite_slow_hash_v0, CN_LITE_SLOW_HASH_V0); TEST_HASH_FUNCTION(cn_lite_slow_hash_v1, CN_LITE_SLOW_HASH_V1); TEST_HASH_FUNCTION(cn_lite_slow_hash_v2, CN_LITE_SLOW_HASH_V2); std::cout << std::endl; TEST_HASH_FUNCTION(cn_dark_slow_hash_v0, CN_DARK_SLOW_HASH_V0); TEST_HASH_FUNCTION(cn_dark_slow_hash_v1, CN_DARK_SLOW_HASH_V1); TEST_HASH_FUNCTION(cn_dark_slow_hash_v2, CN_DARK_SLOW_HASH_V2); std::cout << std::endl; TEST_HASH_FUNCTION(cn_dark_lite_slow_hash_v0, CN_DARK_LITE_SLOW_HASH_V0); TEST_HASH_FUNCTION(cn_dark_lite_slow_hash_v1, CN_DARK_LITE_SLOW_HASH_V1); TEST_HASH_FUNCTION(cn_dark_lite_slow_hash_v2, CN_DARK_LITE_SLOW_HASH_V2); std::cout << std::endl; TEST_HASH_FUNCTION(cn_turtle_slow_hash_v0, CN_TURTLE_SLOW_HASH_V0); TEST_HASH_FUNCTION(cn_turtle_slow_hash_v1, CN_TURTLE_SLOW_HASH_V1); TEST_HASH_FUNCTION(cn_turtle_slow_hash_v2, CN_TURTLE_SLOW_HASH_V2); std::cout << std::endl; TEST_HASH_FUNCTION(cn_turtle_lite_slow_hash_v0, CN_TURTLE_LITE_SLOW_HASH_V0); TEST_HASH_FUNCTION(cn_turtle_lite_slow_hash_v1, CN_TURTLE_LITE_SLOW_HASH_V1); TEST_HASH_FUNCTION(cn_turtle_lite_slow_hash_v2, CN_TURTLE_LITE_SLOW_HASH_V2); std::cout << std::endl; TEST_HASH_FUNCTION(chukwa_slow_hash_v1, CHUKWA_V1); TEST_HASH_FUNCTION(chukwa_slow_hash_v2, CHUKWA_V2); std::cout << std::endl; for (uint64_t height = 0; height <= 8192; height += 512) { TEST_HASH_FUNCTION_WITH_HEIGHT(cn_soft_shell_slow_hash_v0, CN_SOFT_SHELL_V0[height / 512], height); } std::cout << std::endl; for (uint64_t height = 0; height <= 8192; height += 512) { TEST_HASH_FUNCTION_WITH_HEIGHT(cn_soft_shell_slow_hash_v1, CN_SOFT_SHELL_V1[height / 512], height); } std::cout << std::endl; for (uint64_t height = 0; height <= 8192; height += 512) { TEST_HASH_FUNCTION_WITH_HEIGHT(cn_soft_shell_slow_hash_v2, CN_SOFT_SHELL_V2[height / 512], height); } if (o_benchmark) { std::cout << "\nPerformance Tests: Please wait, this may take a while depending on your system...\n\n"; benchmarkUnderivePublicKey(); benchmarkGenerateKeyDerivation(); BENCHMARK(cn_slow_hash_v0, o_iterations); BENCHMARK(cn_slow_hash_v1, o_iterations); BENCHMARK(cn_slow_hash_v2, o_iterations); BENCHMARK(cn_lite_slow_hash_v0, o_iterations); BENCHMARK(cn_lite_slow_hash_v1, o_iterations); BENCHMARK(cn_lite_slow_hash_v2, o_iterations); BENCHMARK(cn_dark_slow_hash_v0, o_iterations); BENCHMARK(cn_dark_slow_hash_v1, o_iterations); BENCHMARK(cn_dark_slow_hash_v2, o_iterations); BENCHMARK(cn_dark_lite_slow_hash_v0, o_iterations); BENCHMARK(cn_dark_lite_slow_hash_v1, o_iterations); BENCHMARK(cn_dark_lite_slow_hash_v2, o_iterations); BENCHMARK(cn_turtle_slow_hash_v0, o_iterations_long); BENCHMARK(cn_turtle_slow_hash_v1, o_iterations_long); BENCHMARK(cn_turtle_slow_hash_v2, o_iterations_long); BENCHMARK(cn_turtle_lite_slow_hash_v0, o_iterations_long); BENCHMARK(cn_turtle_lite_slow_hash_v1, o_iterations_long); BENCHMARK(cn_turtle_lite_slow_hash_v2, o_iterations_long); BENCHMARK(chukwa_slow_hash_v1, o_iterations_long); BENCHMARK(chukwa_slow_hash_v2, o_iterations_long); } } catch (std::exception &e) { std::cout << "Something went terribly wrong...\n" << e.what() << "\n\n"; } }
#include <math.h> #include <uWS/uWS.h> #include <iostream> #include <string> #include "json.hpp" #include "PID.h" // for convenience using nlohmann::json; using std::string; // For converting back and forth between radians and degrees. constexpr double pi() { return M_PI; } double deg2rad(double x) { return x * pi() / 180; } double rad2deg(double x) { return x * 180 / pi(); } // Checks if the SocketIO event has JSON data. // If there is data the JSON object in string format will be returned, // else the empty string "" will be returned. string hasData(string s) { auto found_null = s.find("null"); auto b1 = s.find_first_of("["); auto b2 = s.find_last_of("]"); if (found_null != string::npos) { return ""; } else if (b1 != string::npos && b2 != string::npos) { return s.substr(b1, b2 - b1 + 1); } return ""; } int main() { uWS::Hub h; PID pid; PID pid_throttle; /** * TODO: Initialize the pid variable. */ pid.Init(0.11, 0.00, 0.95); pid_throttle.Init(1, 0.0, 0.5); h.onMessage([&pid, &pid_throttle](uWS::WebSocket<uWS::SERVER> ws, char* data, size_t length, uWS::OpCode opCode) { // "42" at the start of the message means there's a websocket message event. // The 4 signifies a websocket message // The 2 signifies a websocket event if (length && length > 2 && data[0] == '4' && data[1] == '2') { auto s = hasData(string(data).substr(0, length)); if (s != "") { auto j = json::parse(s); string event = j[0].get<string>(); if (event == "telemetry") { // j[1] is the data JSON object double cte = std::stod(j[1]["cte"].get<string>()); double speed = std::stod(j[1]["speed"].get<string>()); double angle = std::stod(j[1]["steering_angle"].get<string>()); double steer_value; double throttle_value; /** * TODO: Calculate steering value here, remember the steering value is * [-1, 1]. * NOTE: Feel free to play around with the throttle and speed. * Maybe use another PID controller to control the speed! */ pid.UpdateError(cte); steer_value = pid.TotalError(); if (steer_value > 1.0) steer_value = 1.0; if (steer_value < -1.0) steer_value = -1.0; double speed_des = 50; double speed_error = speed - speed_des; pid_throttle.UpdateSpeedError(speed_error); throttle_value = pid_throttle.TotalSpeedError(); if (throttle_value > 1.0) throttle_value = 1.0; if (throttle_value < -1.0) throttle_value = -1.0; // DEBUG std::cout << "CTE: " << cte << " Steering Value: " << steer_value << std::endl; json msgJson; msgJson["steering_angle"] = steer_value; msgJson["throttle"] = throttle_value; auto msg = "42[\"steer\"," + msgJson.dump() + "]"; std::cout << msg << std::endl; ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT); } // end "telemetry" if } else { // Manual driving string msg = "42[\"manual\",{}]"; ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT); } } // end websocket message if }); // end h.onMessage h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) { std::cout << "Connected!!!" << std::endl; }); h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code, char* message, size_t length) { ws.close(); std::cout << "Disconnected" << std::endl; }); int port = 4567; if (h.listen(port)) { std::cout << "Listening to port " << port << std::endl; } else { std::cerr << "Failed to listen to port" << std::endl; return -1; } h.run(); }
//------------------------------------------------------------------------------ /* This file is part of rippled: https://github.com/ripple/rippled Copyright (c) 2012, 2013 Ripple Labs Inc. 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 <BeastConfig.h> #include <ripple/app/tx/impl/Payment.h> #include <ripple/app/paths/RippleCalc.h> #include <ripple/basics/Log.h> #include <ripple/core/Config.h> #include <ripple/protocol/st.h> #include <ripple/protocol/TxFlags.h> #include <ripple/protocol/JsonFields.h> namespace ripple { // See https://ripple.com/wiki/Transaction_Format#Payment_.280.29 BTAAmount Payment::calculateMaxSpend(STTx const& tx) { if (tx.isFieldPresent(sfSendMax)) { auto const& sendMax = tx[sfSendMax]; return sendMax.native() ? sendMax.bta() : beast::zero; } /* If there's no sfSendMax in BTA, and the sfAmount isn't in BTA, then the transaction can not send BTA. */ auto const& saDstAmount = tx.getFieldAmount(sfAmount); return saDstAmount.native() ? saDstAmount.bta() : beast::zero; } TER Payment::preflight (PreflightContext const& ctx) { auto const ret = preflight1 (ctx); if (!isTesSuccess (ret)) return ret; auto& tx = ctx.tx; auto& j = ctx.j; std::uint32_t const uTxFlags = tx.getFlags (); if (uTxFlags & tfPaymentMask) { JLOG(j.trace()) << "Malformed transaction: " << "Invalid flags set."; return temINVALID_FLAG; } bool const partialPaymentAllowed = uTxFlags & tfPartialPayment; bool const limitQuality = uTxFlags & tfLimitQuality; bool const defaultPathsAllowed = !(uTxFlags & tfNoRippleDirect); bool const bPaths = tx.isFieldPresent (sfPaths); bool const bMax = tx.isFieldPresent (sfSendMax); STAmount const saDstAmount (tx.getFieldAmount (sfAmount)); STAmount maxSourceAmount; auto const account = tx.getAccountID(sfAccount); if (bMax) maxSourceAmount = tx.getFieldAmount (sfSendMax); else if (saDstAmount.native ()) maxSourceAmount = saDstAmount; else maxSourceAmount = STAmount ( { saDstAmount.getCurrency (), account }, saDstAmount.mantissa(), saDstAmount.exponent (), saDstAmount < zero); auto const& uSrcCurrency = maxSourceAmount.getCurrency (); auto const& uDstCurrency = saDstAmount.getCurrency (); // isZero() is BTA. FIX! bool const bBTADirect = uSrcCurrency.isZero () && uDstCurrency.isZero (); if (!isLegalNet (saDstAmount) || !isLegalNet (maxSourceAmount)) return temBAD_AMOUNT; auto const uDstAccountID = tx.getAccountID (sfDestination); if (!uDstAccountID) { JLOG(j.trace()) << "Malformed transaction: " << "Payment destination account not specified."; return temDST_NEEDED; } if (bMax && maxSourceAmount <= zero) { JLOG(j.trace()) << "Malformed transaction: " << "bad max amount: " << maxSourceAmount.getFullText (); return temBAD_AMOUNT; } if (saDstAmount <= zero) { JLOG(j.trace()) << "Malformed transaction: "<< "bad dst amount: " << saDstAmount.getFullText (); return temBAD_AMOUNT; } if (badCurrency() == uSrcCurrency || badCurrency() == uDstCurrency) { JLOG(j.trace()) <<"Malformed transaction: " << "Bad currency."; return temBAD_CURRENCY; } if (account == uDstAccountID && uSrcCurrency == uDstCurrency && !bPaths) { // You're signing yourself a payment. // If bPaths is true, you might be trying some arbitrage. JLOG(j.trace()) << "Malformed transaction: " << "Redundant payment from " << to_string (account) << " to self without path for " << to_string (uDstCurrency); return temREDUNDANT; } if (bBTADirect && bMax) { // Consistent but redundant transaction. JLOG(j.trace()) << "Malformed transaction: " << "SendMax specified for BTA to BTA."; return temBAD_SEND_BTA_MAX; } if (bBTADirect && bPaths) { // BTA is sent without paths. JLOG(j.trace()) << "Malformed transaction: " << "Paths specified for BTA to BTA."; return temBAD_SEND_BTA_PATHS; } if (bBTADirect && partialPaymentAllowed) { // Consistent but redundant transaction. JLOG(j.trace()) << "Malformed transaction: " << "Partial payment specified for BTA to BTA."; return temBAD_SEND_BTA_PARTIAL; } if (bBTADirect && limitQuality) { // Consistent but redundant transaction. JLOG(j.trace()) << "Malformed transaction: " << "Limit quality specified for BTA to BTA."; return temBAD_SEND_BTA_LIMIT; } if (bBTADirect && !defaultPathsAllowed) { // Consistent but redundant transaction. JLOG(j.trace()) << "Malformed transaction: " << "No ripple direct specified for BTA to BTA."; return temBAD_SEND_BTA_NO_DIRECT; } auto const deliverMin = tx[~sfDeliverMin]; if (deliverMin) { if (! partialPaymentAllowed) { JLOG(j.trace()) << "Malformed transaction: Partial payment not " "specified for " << jss::DeliverMin.c_str() << "."; return temBAD_AMOUNT; } auto const dMin = *deliverMin; if (!isLegalNet(dMin) || dMin <= zero) { JLOG(j.trace()) << "Malformed transaction: Invalid " << jss::DeliverMin.c_str() << " amount. " << dMin.getFullText(); return temBAD_AMOUNT; } if (dMin.issue() != saDstAmount.issue()) { JLOG(j.trace()) << "Malformed transaction: Dst issue differs " "from " << jss::DeliverMin.c_str() << ". " << dMin.getFullText(); return temBAD_AMOUNT; } if (dMin > saDstAmount) { JLOG(j.trace()) << "Malformed transaction: Dst amount less than " << jss::DeliverMin.c_str() << ". " << dMin.getFullText(); return temBAD_AMOUNT; } } return preflight2 (ctx); } TER Payment::preclaim(PreclaimContext const& ctx) { // Ripple if source or destination is non-native or if there are paths. std::uint32_t const uTxFlags = ctx.tx.getFlags(); bool const partialPaymentAllowed = uTxFlags & tfPartialPayment; auto const paths = ctx.tx.isFieldPresent(sfPaths); auto const sendMax = ctx.tx[~sfSendMax]; AccountID const uDstAccountID(ctx.tx[sfDestination]); STAmount const saDstAmount(ctx.tx[sfAmount]); auto const k = keylet::account(uDstAccountID); auto const sleDst = ctx.view.read(k); if (!sleDst) { // Destination account does not exist. if (!saDstAmount.native()) { JLOG(ctx.j.trace()) << "Delay transaction: Destination account does not exist."; // Another transaction could create the account and then this // transaction would succeed. return tecNO_DST; } else if (ctx.view.open() && partialPaymentAllowed) { // You cannot fund an account with a partial payment. // Make retry work smaller, by rejecting this. JLOG(ctx.j.trace()) << "Delay transaction: Partial payment not allowed to create account."; // Another transaction could create the account and then this // transaction would succeed. return telNO_DST_PARTIAL; } else if (saDstAmount < STAmount(ctx.view.fees().accountReserve(0))) { // accountReserve is the minimum amount that an account can have. // Reserve is not scaled by load. JLOG(ctx.j.trace()) << "Delay transaction: Destination account does not exist. " << "Insufficent payment to create account."; // TODO: dedupe // Another transaction could create the account and then this // transaction would succeed. return tecNO_DST_INSUF_BTA; } } else if ((sleDst->getFlags() & lsfRequireDestTag) && !ctx.tx.isFieldPresent(sfDestinationTag)) { // The tag is basically account-specific information we don't // understand, but we can require someone to fill it in. // We didn't make this test for a newly-formed account because there's // no way for this field to be set. JLOG(ctx.j.trace()) << "Malformed transaction: DestinationTag required."; return tecDST_TAG_NEEDED; } if (paths || sendMax || !saDstAmount.native()) { // Ripple payment with at least one intermediate step and uses // transitive balances. // Copy paths into an editable class. STPathSet const spsPaths = ctx.tx.getFieldPathSet(sfPaths); auto pathTooBig = spsPaths.size() > MaxPathSize; if(!pathTooBig) for (auto const& path : spsPaths) if (path.size() > MaxPathLength) { pathTooBig = true; break; } if (ctx.view.open() && pathTooBig) { return telBAD_PATH_COUNT; // Too many paths for proposed ledger. } } return tesSUCCESS; } TER Payment::doApply () { auto const deliverMin = ctx_.tx[~sfDeliverMin]; // Ripple if source or destination is non-native or if there are paths. std::uint32_t const uTxFlags = ctx_.tx.getFlags (); bool const partialPaymentAllowed = uTxFlags & tfPartialPayment; bool const limitQuality = uTxFlags & tfLimitQuality; bool const defaultPathsAllowed = !(uTxFlags & tfNoRippleDirect); auto const paths = ctx_.tx.isFieldPresent(sfPaths); auto const sendMax = ctx_.tx[~sfSendMax]; AccountID const uDstAccountID (ctx_.tx.getAccountID (sfDestination)); STAmount const saDstAmount (ctx_.tx.getFieldAmount (sfAmount)); STAmount maxSourceAmount; if (sendMax) maxSourceAmount = *sendMax; else if (saDstAmount.native ()) maxSourceAmount = saDstAmount; else maxSourceAmount = STAmount ( {saDstAmount.getCurrency (), account_}, saDstAmount.mantissa(), saDstAmount.exponent (), saDstAmount < zero); JLOG(j_.trace()) << "maxSourceAmount=" << maxSourceAmount.getFullText () << " saDstAmount=" << saDstAmount.getFullText (); // Open a ledger for editing. auto const k = keylet::account(uDstAccountID); SLE::pointer sleDst = view().peek (k); if (!sleDst) { // Create the account. sleDst = std::make_shared<SLE>(k); sleDst->setAccountID(sfAccount, uDstAccountID); sleDst->setFieldU32(sfSequence, 1); view().insert(sleDst); } else { // Tell the engine that we are intending to change the destination // account. The source account gets always charged a fee so it's always // marked as modified. view().update (sleDst); } TER terResult; bool const bRipple = paths || sendMax || !saDstAmount.native (); // XXX Should sendMax be sufficient to imply ripple? if (bRipple) { // Ripple payment with at least one intermediate step and uses // transitive balances. // Copy paths into an editable class. STPathSet spsPaths = ctx_.tx.getFieldPathSet (sfPaths); path::RippleCalc::Input rcInput; rcInput.partialPaymentAllowed = partialPaymentAllowed; rcInput.defaultPathsAllowed = defaultPathsAllowed; rcInput.limitQuality = limitQuality; rcInput.isLedgerOpen = view().open(); path::RippleCalc::Output rc; { PaymentSandbox pv(&view()); JLOG(j_.debug()) << "Entering RippleCalc in payment: " << ctx_.tx.getTransactionID(); rc = path::RippleCalc::rippleCalculate ( pv, maxSourceAmount, saDstAmount, uDstAccountID, account_, spsPaths, ctx_.app.logs(), &rcInput); // VFALCO NOTE We might not need to apply, depending // on the TER. But always applying *should* // be safe. pv.apply(ctx_.rawView()); } // TODO: is this right? If the amount is the correct amount, was // the delivered amount previously set? if (rc.result () == tesSUCCESS && rc.actualAmountOut != saDstAmount) { if (deliverMin && rc.actualAmountOut < *deliverMin) rc.setResult (tecPATH_PARTIAL); else ctx_.deliver (rc.actualAmountOut); } terResult = rc.result (); // Because of its overhead, if RippleCalc // fails with a retry code, claim a fee // instead. Maybe the user will be more // careful with their path spec next time. if (isTerRetry (terResult)) terResult = tecPATH_DRY; } else { assert (saDstAmount.native ()); // Direct BTA payment. // uOwnerCount is the number of entries in this legder for this // account that require a reserve. auto const uOwnerCount = view().read( keylet::account(account_))->getFieldU32 (sfOwnerCount); // This is the total reserve in drops. auto const reserve = view().fees().accountReserve(uOwnerCount); // mPriorBalance is the balance on the sending account BEFORE the // fees were charged. We want to make sure we have enough reserve // to send. Allow final spend to use reserve for fee. auto const mmm = std::max(reserve, ctx_.tx.getFieldAmount (sfFee).bta ()); if (mPriorBalance < saDstAmount.bta () + mmm) { // Vote no. However the transaction might succeed, if applied in // a different order. JLOG(j_.trace()) << "Delay transaction: Insufficient funds: " << " " << to_string (mPriorBalance) << " / " << to_string (saDstAmount.bta () + mmm) << " (" << to_string (reserve) << ")"; terResult = tecUNFUNDED_PAYMENT; } else { // The source account does have enough money, so do the // arithmetic for the transfer and make the ledger change. view().peek(keylet::account(account_))->setFieldAmount (sfBalance, mSourceBalance - saDstAmount); sleDst->setFieldAmount (sfBalance, sleDst->getFieldAmount (sfBalance) + saDstAmount); // Re-arm the password change fee if we can and need to. if ((sleDst->getFlags () & lsfPasswordSpent)) sleDst->clearFlag (lsfPasswordSpent); terResult = tesSUCCESS; } } return terResult; } } // ripple
#pragma once #include <Register/Utility.hpp> namespace Kvasir { //Reset and clock control namespace RccCr{ ///<clock control register using Addr = Register::Address<0x40023800,0xf0f00004,0x00000000,unsigned>; ///PLLI2S clock ready flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> plli2srdy{}; ///PLLI2S enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> plli2son{}; ///Main PLL (PLL) clock ready flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> pllrdy{}; ///Main PLL (PLL) enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> pllon{}; ///Clock security system enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> csson{}; ///HSE clock bypass constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> hsebyp{}; ///HSE clock ready flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> hserdy{}; ///HSE clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> hseon{}; ///Internal high-speed clock calibration constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> hsical{}; ///Internal high-speed clock trimming constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,3),Register::ReadWriteAccess,unsigned> hsitrim{}; ///Internal high-speed clock ready flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> hsirdy{}; ///Internal high-speed clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> hsion{}; } namespace RccPllcfgr{ ///<PLL configuration register using Addr = Register::Address<0x40023804,0xf0bc8000,0x00000000,unsigned>; ///Main PLL (PLL) division factor for USB OTG FS, SDIO and random number generator clocks constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> pllq3{}; ///Main PLL (PLL) division factor for USB OTG FS, SDIO and random number generator clocks constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> pllq2{}; ///Main PLL (PLL) division factor for USB OTG FS, SDIO and random number generator clocks constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> pllq1{}; ///Main PLL (PLL) division factor for USB OTG FS, SDIO and random number generator clocks constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> pllq0{}; ///Main PLL(PLL) and audio PLL (PLLI2S) entry clock source constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> pllsrc{}; ///Main PLL (PLL) division factor for main system clock constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> pllp1{}; ///Main PLL (PLL) division factor for main system clock constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> pllp0{}; ///Main PLL (PLL) multiplication factor for VCO constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> plln8{}; ///Main PLL (PLL) multiplication factor for VCO constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> plln7{}; ///Main PLL (PLL) multiplication factor for VCO constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> plln6{}; ///Main PLL (PLL) multiplication factor for VCO constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> plln5{}; ///Main PLL (PLL) multiplication factor for VCO constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> plln4{}; ///Main PLL (PLL) multiplication factor for VCO constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> plln3{}; ///Main PLL (PLL) multiplication factor for VCO constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> plln2{}; ///Main PLL (PLL) multiplication factor for VCO constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> plln1{}; ///Main PLL (PLL) multiplication factor for VCO constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> plln0{}; ///Division factor for the main PLL (PLL) and audio PLL (PLLI2S) input clock constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> pllm5{}; ///Division factor for the main PLL (PLL) and audio PLL (PLLI2S) input clock constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> pllm4{}; ///Division factor for the main PLL (PLL) and audio PLL (PLLI2S) input clock constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> pllm3{}; ///Division factor for the main PLL (PLL) and audio PLL (PLLI2S) input clock constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> pllm2{}; ///Division factor for the main PLL (PLL) and audio PLL (PLLI2S) input clock constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> pllm1{}; ///Division factor for the main PLL (PLL) and audio PLL (PLLI2S) input clock constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> pllm0{}; } namespace RccCfgr{ ///<clock configuration register using Addr = Register::Address<0x40023808,0x00000300,0x00000000,unsigned>; ///Microcontroller clock output 2 constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,30),Register::ReadWriteAccess,unsigned> mco2{}; ///MCO2 prescaler constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,27),Register::ReadWriteAccess,unsigned> mco2pre{}; ///MCO1 prescaler constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,24),Register::ReadWriteAccess,unsigned> mco1pre{}; ///I2S clock selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> i2ssrc{}; ///Microcontroller clock output 1 constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,21),Register::ReadWriteAccess,unsigned> mco1{}; ///HSE division factor for RTC clock constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,16),Register::ReadWriteAccess,unsigned> rtcpre{}; ///APB high-speed prescaler (APB2) constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,13),Register::ReadWriteAccess,unsigned> ppre2{}; ///APB Low speed prescaler (APB1) constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,10),Register::ReadWriteAccess,unsigned> ppre1{}; ///AHB prescaler constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,4),Register::ReadWriteAccess,unsigned> hpre{}; ///System clock switch status constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> sws1{}; ///System clock switch status constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> sws0{}; ///System clock switch constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> sw1{}; ///System clock switch constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> sw0{}; } namespace RccCir{ ///<clock interrupt register using Addr = Register::Address<0x4002380c,0xff008000,0x00000000,unsigned>; ///Clock security system interrupt clear constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cssc{}; ///PLLSAI Ready Interrupt Clear constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> pllsairdyc{}; ///PLLI2S ready interrupt clear constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> plli2srdyc{}; ///Main PLL(PLL) ready interrupt clear constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> pllrdyc{}; ///HSE ready interrupt clear constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> hserdyc{}; ///HSI ready interrupt clear constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> hsirdyc{}; ///LSE ready interrupt clear constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> lserdyc{}; ///LSI ready interrupt clear constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> lsirdyc{}; ///PLLSAI Ready Interrupt Enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> pllsairdyie{}; ///PLLI2S ready interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> plli2srdyie{}; ///Main PLL (PLL) ready interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> pllrdyie{}; ///HSE ready interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> hserdyie{}; ///HSI ready interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> hsirdyie{}; ///LSE ready interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> lserdyie{}; ///LSI ready interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> lsirdyie{}; ///Clock security system interrupt flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cssf{}; ///PLLSAI ready interrupt flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> pllsairdyf{}; ///PLLI2S ready interrupt flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> plli2srdyf{}; ///Main PLL (PLL) ready interrupt flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> pllrdyf{}; ///HSE ready interrupt flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> hserdyf{}; ///HSI ready interrupt flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> hsirdyf{}; ///LSE ready interrupt flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> lserdyf{}; ///LSI ready interrupt flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> lsirdyf{}; } namespace RccAhb1rstr{ ///<AHB1 peripheral reset register using Addr = Register::Address<0x40023810,0xdf9fef00,0x00000000,unsigned>; ///USB OTG HS module reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> otghsrst{}; ///DMA2 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> dma2rst{}; ///DMA2 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> dma1rst{}; ///CRC reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> crcrst{}; ///IO port H reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> gpiohrst{}; ///IO port G reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> gpiogrst{}; ///IO port F reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> gpiofrst{}; ///IO port E reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> gpioerst{}; ///IO port D reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> gpiodrst{}; ///IO port C reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> gpiocrst{}; ///IO port B reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> gpiobrst{}; ///IO port A reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> gpioarst{}; } namespace RccAhb2rstr{ ///<AHB2 peripheral reset register using Addr = Register::Address<0x40023814,0xffffff7e,0x00000000,unsigned>; ///USB OTG FS module reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> otgfsrst{}; ///Camera interface reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> dcmirst{}; } namespace RccAhb3rstr{ ///<AHB3 peripheral reset register using Addr = Register::Address<0x40023818,0xfffffffc,0x00000000,unsigned>; ///Flexible memory controller module reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> fmcrst{}; ///QUADSPI module reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> qspirst{}; } namespace RccApb1rstr{ ///<APB1 peripheral reset register using Addr = Register::Address<0x40023820,0xc8003600,0x00000000,unsigned>; ///TIM2 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> tim2rst{}; ///TIM3 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> tim3rst{}; ///TIM4 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> tim4rst{}; ///TIM5 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> tim5rst{}; ///TIM6 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> tim6rst{}; ///TIM7 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> tim7rst{}; ///TIM12 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> tim12rst{}; ///TIM13 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> tim13rst{}; ///TIM14 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> tim14rst{}; ///Window watchdog reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> wwdgrst{}; ///SPI 2 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> spi2rst{}; ///SPI 3 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> spi3rst{}; ///SPDIF-IN reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> spdifrst{}; ///USART 2 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> uart2rst{}; ///USART 3 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> uart3rst{}; ///USART 4 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> uart4rst{}; ///USART 5 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> uart5rst{}; ///I2C 1 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> i2c1rst{}; ///I2C 2 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> i2c2rst{}; ///I2C3 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> i2c3rst{}; ///I2CFMP1 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> i2cfmp1rst{}; ///CAN1 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> can1rst{}; ///CAN2 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> can2rst{}; ///Power interface reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> pwrrst{}; ///DAC reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> dacrst{}; } namespace RccApb2rstr{ ///<APB2 peripheral reset register using Addr = Register::Address<0x40023824,0xff3886cc,0x00000000,unsigned>; ///TIM1 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> tim1rst{}; ///TIM8 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> tim8rst{}; ///USART1 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> usart1rst{}; ///USART6 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> usart6rst{}; ///ADC interface reset (common to all ADCs) constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> adcrst{}; ///SDIO reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> sdiorst{}; ///SPI 1 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> spi1rst{}; ///SPI4 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> spi4rst{}; ///System configuration controller reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> syscfgrst{}; ///TIM9 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> tim9rst{}; ///TIM10 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> tim10rst{}; ///TIM11 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> tim11rst{}; ///SAI1 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> sai1rst{}; ///SAI2 reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> sai2rst{}; } namespace RccAhb1enr{ ///<AHB1 peripheral clock register using Addr = Register::Address<0x40023830,0x9f9bef00,0x00000000,unsigned>; ///USB OTG HSULPI clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> otghsulpien{}; ///USB OTG HS clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> otghsen{}; ///DMA2 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> dma2en{}; ///DMA1 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> dma1en{}; ///Backup SRAM interface clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> bkpsramen{}; ///CRC clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> crcen{}; ///IO port H clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> gpiohen{}; ///IO port G clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> gpiogen{}; ///IO port F clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> gpiofen{}; ///IO port E clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> gpioeen{}; ///IO port D clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> gpioden{}; ///IO port C clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> gpiocen{}; ///IO port B clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> gpioben{}; ///IO port A clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> gpioaen{}; } namespace RccAhb2enr{ ///<AHB2 peripheral clock enable register using Addr = Register::Address<0x40023834,0xffffff7e,0x00000000,unsigned>; ///USB OTG FS clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> otgfsen{}; ///Camera interface enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> dcmien{}; } namespace RccAhb3enr{ ///<AHB3 peripheral clock enable register using Addr = Register::Address<0x40023838,0xfffffffc,0x00000000,unsigned>; ///Flexible memory controller module clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> fmcen{}; ///QUADSPI memory controller module clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> qspien{}; } namespace RccApb1enr{ ///<APB1 peripheral clock enable register using Addr = Register::Address<0x40023840,0xc0003600,0x00000000,unsigned>; ///TIM2 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> tim2en{}; ///TIM3 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> tim3en{}; ///TIM4 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> tim4en{}; ///TIM5 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> tim5en{}; ///TIM6 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> tim6en{}; ///TIM7 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> tim7en{}; ///TIM12 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> tim12en{}; ///TIM13 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> tim13en{}; ///TIM14 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> tim14en{}; ///Window watchdog clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> wwdgen{}; ///SPI2 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> spi2en{}; ///SPI3 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> spi3en{}; ///SPDIF-IN clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> spdifen{}; ///USART 2 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> usart2en{}; ///USART3 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> usart3en{}; ///UART4 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> uart4en{}; ///UART5 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> uart5en{}; ///I2C1 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> i2c1en{}; ///I2C2 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> i2c2en{}; ///I2C3 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> i2c3en{}; ///I2CFMP1 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> i2cfmp1en{}; ///CAN 1 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> can1en{}; ///CAN 2 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> can2en{}; ///CEC interface clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> cec{}; ///Power interface clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> pwren{}; ///DAC interface clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> dacen{}; } namespace RccApb2enr{ ///<APB2 peripheral clock enable register using Addr = Register::Address<0x40023844,0xff3880cc,0x00000000,unsigned>; ///TIM1 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> tim1en{}; ///TIM8 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> tim8en{}; ///USART1 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> usart1en{}; ///USART6 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> usart6en{}; ///ADC1 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> adc1en{}; ///ADC2 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> adc2en{}; ///ADC3 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> adc3en{}; ///SDIO clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> sdioen{}; ///SPI1 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> spi1en{}; ///SPI4 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> spi4enr{}; ///System configuration controller clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> syscfgen{}; ///TIM9 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> tim9en{}; ///TIM10 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> tim10en{}; ///TIM11 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> tim11en{}; ///SAI1 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> sai1en{}; ///SAI2 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> sai2en{}; } namespace RccAhb1lpenr{ ///<AHB1 peripheral clock enable in low power mode register using Addr = Register::Address<0x40023850,0x9f986f00,0x00000000,unsigned>; ///IO port A clock enable during sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> gpioalpen{}; ///IO port B clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> gpioblpen{}; ///IO port C clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> gpioclpen{}; ///IO port D clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> gpiodlpen{}; ///IO port E clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> gpioelpen{}; ///IO port F clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> gpioflpen{}; ///IO port G clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> gpioglpen{}; ///IO port H clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> gpiohlpen{}; ///CRC clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> crclpen{}; ///Flash interface clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> flitflpen{}; ///SRAM 1interface clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> sram1lpen{}; ///SRAM 2 interface clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> sram2lpen{}; ///Backup SRAM interface clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> bkpsramlpen{}; ///DMA1 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> dma1lpen{}; ///DMA2 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> dma2lpen{}; ///USB OTG HS clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> otghslpen{}; ///USB OTG HS ULPI clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> otghsulpilpen{}; } namespace RccAhb2lpenr{ ///<AHB2 peripheral clock enable in low power mode register using Addr = Register::Address<0x40023854,0xffffff7e,0x00000000,unsigned>; ///USB OTG FS clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> otgfslpen{}; ///Camera interface enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> dcmilpen{}; } namespace RccAhb3lpenr{ ///<AHB3 peripheral clock enable in low power mode register using Addr = Register::Address<0x40023858,0xfffffffc,0x00000000,unsigned>; ///Flexible memory controller module clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> fmclpen{}; ///QUADSPI memory controller module clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> qspilpen{}; } namespace RccApb1lpenr{ ///<APB1 peripheral clock enable in low power mode register using Addr = Register::Address<0x40023860,0xc0003600,0x00000000,unsigned>; ///TIM2 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> tim2lpen{}; ///TIM3 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> tim3lpen{}; ///TIM4 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> tim4lpen{}; ///TIM5 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> tim5lpen{}; ///TIM6 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> tim6lpen{}; ///TIM7 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> tim7lpen{}; ///TIM12 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> tim12lpen{}; ///TIM13 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> tim13lpen{}; ///TIM14 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> tim14lpen{}; ///Window watchdog clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> wwdglpen{}; ///SPI2 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> spi2lpen{}; ///SPI3 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> spi3lpen{}; ///SPDIF clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> spdiflpen{}; ///USART2 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> usart2lpen{}; ///USART3 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> usart3lpen{}; ///UART4 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> uart4lpen{}; ///UART5 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> uart5lpen{}; ///I2C1 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> i2c1lpen{}; ///I2C2 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> i2c2lpen{}; ///I2C3 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> i2c3lpen{}; ///I2CFMP1 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> i2cfmp1lpen{}; ///CAN 1 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> can1lpen{}; ///CAN 2 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> can2lpen{}; ///CEC clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> ceclpen{}; ///Power interface clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> pwrlpen{}; ///DAC interface clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> daclpen{}; } namespace RccApb2lpenr{ ///<APB2 peripheral clock enabled in low power mode register using Addr = Register::Address<0x40023864,0xff3880cc,0x00000000,unsigned>; ///TIM1 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> tim1lpen{}; ///TIM8 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> tim8lpen{}; ///USART1 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> usart1lpen{}; ///USART6 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> usart6lpen{}; ///ADC1 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> adc1lpen{}; ///ADC2 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> adc2lpen{}; ///ADC 3 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> adc3lpen{}; ///SDIO clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> sdiolpen{}; ///SPI 1 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> spi1lpen{}; ///SPI 4 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> spi4lpen{}; ///System configuration controller clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> syscfglpen{}; ///TIM9 clock enable during sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> tim9lpen{}; ///TIM10 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> tim10lpen{}; ///TIM11 clock enable during Sleep mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> tim11lpen{}; ///SAI1 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> sai1lpen{}; ///SAI2 clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> sai2lpen{}; } namespace RccBdcr{ ///<Backup domain control register using Addr = Register::Address<0x40023870,0xfffe7cf0,0x00000000,unsigned>; ///Backup domain software reset constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> bdrst{}; ///RTC clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> rtcen{}; ///RTC clock source selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,8),Register::ReadWriteAccess,unsigned> rtcsel{}; ///External low-speed oscillator mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> lsemod{}; ///External low-speed oscillator bypass constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> lsebyp{}; ///External low-speed oscillator ready constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> lserdy{}; ///External low-speed oscillator enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> lseon{}; } namespace RccCsr{ ///<clock control & status register using Addr = Register::Address<0x40023874,0x00fffffc,0x00000000,unsigned>; ///Low-power reset flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> lpwrrstf{}; ///Window watchdog reset flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> wwdgrstf{}; ///Independent watchdog reset flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> wdgrstf{}; ///Software reset flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> sftrstf{}; ///POR/PDR reset flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> porrstf{}; ///PIN reset flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> padrstf{}; ///BOR reset flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> borrstf{}; ///Remove reset flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> rmvf{}; ///Internal low-speed oscillator ready constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> lsirdy{}; ///Internal low-speed oscillator enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> lsion{}; } namespace RccSscgr{ ///<spread spectrum clock generation register using Addr = Register::Address<0x40023880,0x30000000,0x00000000,unsigned>; ///Spread spectrum modulation enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> sscgen{}; ///Spread Select constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> spreadsel{}; ///Incrementation step constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,13),Register::ReadWriteAccess,unsigned> incstep{}; ///Modulation period constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,0),Register::ReadWriteAccess,unsigned> modper{}; } namespace RccPlli2scfgr{ ///<PLLI2S configuration register using Addr = Register::Address<0x40023884,0x80fc8000,0x00000000,unsigned>; ///Division factor for audio PLL (PLLI2S) input clock constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,0),Register::ReadWriteAccess,unsigned> plli2sm{}; ///PLLI2S multiplication factor for VCO constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,6),Register::ReadWriteAccess,unsigned> plli2sn{}; ///PLLI2S division factor for SPDIF-IN clock constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,16),Register::ReadWriteAccess,unsigned> plli2sp{}; ///PLLI2S division factor for SAI1 clock constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,24),Register::ReadWriteAccess,unsigned> plli2sq{}; ///PLLI2S division factor for I2S clocks constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,28),Register::ReadWriteAccess,unsigned> plli2sr{}; } namespace RccPllsaicfgr{ ///<PLL configuration register using Addr = Register::Address<0x40023888,0xf0fc8000,0x00000000,unsigned>; ///Division factor for audio PLLSAI input clock constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,0),Register::ReadWriteAccess,unsigned> pllsaim{}; ///PLLSAI division factor for VCO constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,6),Register::ReadWriteAccess,unsigned> pllsain{}; ///PLLSAI division factor for 48 MHz clock constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,16),Register::ReadWriteAccess,unsigned> pllsaip{}; ///PLLSAI division factor for SAIs clock constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,24),Register::ReadWriteAccess,unsigned> pllsaiq{}; } namespace RccDckcfgr{ ///<Dedicated Clock Configuration Register using Addr = Register::Address<0x4002388c,0xe00fe0e0,0x00000000,unsigned>; ///PLLI2S division factor for SAIs clock constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,0),Register::ReadWriteAccess,unsigned> plli2sdivq{}; ///PLLSAI division factor for SAIs clock constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,8),Register::ReadWriteAccess,unsigned> pllsaidivq{}; ///SAI1 clock source selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,20),Register::ReadWriteAccess,unsigned> sai1src{}; ///SAI2 clock source selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,22),Register::ReadWriteAccess,unsigned> sai2src{}; ///Timers clocks prescalers selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> timpre{}; ///I2S APB1 clock source selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,25),Register::ReadWriteAccess,unsigned> i2s1src{}; ///I2S APB2 clock source selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,27),Register::ReadWriteAccess,unsigned> i2s2src{}; } namespace RccCkgatenr{ ///<clocks gated enable register using Addr = Register::Address<0x40023890,0xffffff80,0x00000000,unsigned>; ///AHB to APB1 Bridge clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> ahb2apb1Cken{}; ///AHB to APB2 Bridge clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> ahb2apb2Cken{}; ///Cortex M4 ETM clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> cm4dbgCken{}; ///Spare clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> spareCken{}; ///SRQAM controller clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> sramCken{}; ///Flash Interface clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> flitfCken{}; ///RCC clock enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> rccCken{}; } namespace RccDckcfgr2{ ///<dedicated clocks configuration register 2 using Addr = Register::Address<0x40023894,0xc33fffff,0x00000000,unsigned>; ///I2C4 kernel clock source selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,22),Register::ReadWriteAccess,unsigned> fmpi2c1sel{}; ///HDMI CEC clock source selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> cecsel{}; ///SDIO/USBFS/HS clock selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> ck48msel{}; ///SDIO clock selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> sdiosel{}; ///SPDIF clock selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> spdifsel{}; } }
// -------------------------------------------------------------------------- // SmartPeak -- Fast and Accurate CE-, GC- and LC-MS(/MS) Data Processing // -------------------------------------------------------------------------- // Copyright The SmartPeak Team -- Novo Nordisk Foundation // Center for Biosustainability, Technical University of Denmark 2018-2021. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // -------------------------------------------------------------------------- // $Maintainer: Douglas McCloskey $ // $Authors: Douglas McCloskey, Pasquale Domenico Colaianni $ // -------------------------------------------------------------------------- #include <SmartPeak/core/MetaDataHandler.h> #include <SmartPeak/core/SampleType.h> #include <iostream> #include <plog/Log.h> // required for strptime on Windows #ifdef _WIN32 #include <time.h> #include <iomanip> #include <sstream> #endif namespace SmartPeak { void MetaDataHandler::setSampleName(const std::string& sample_name_I) { sample_name = sample_name_I; } std::string& MetaDataHandler::getSampleName() { return sample_name; } const std::string& MetaDataHandler::getSampleName() const { return sample_name; } void MetaDataHandler::setSampleGroupName(const std::string& sample_group_name_I) { sample_group_name = sample_group_name_I; } std::string& MetaDataHandler::getSampleGroupName() { return sample_group_name; } const std::string& MetaDataHandler::getSampleGroupName() const { return sample_group_name; } void MetaDataHandler::setSequenceSegmentName(const std::string& sequence_segment_name_I) { sequence_segment_name = sequence_segment_name_I; } std::string& MetaDataHandler::getSequenceSegmentName() { return sequence_segment_name; } const std::string& MetaDataHandler::getSequenceSegmentName() const { return sequence_segment_name; } void MetaDataHandler::setFilename(const std::string& filename_I) { original_filename = filename_I; } std::string& MetaDataHandler::getFilename() { return original_filename; } const std::string& MetaDataHandler::getFilename() const { return original_filename; } void MetaDataHandler::setSampleType(SampleType sample_type_I) { sample_type = sample_type_I; } SampleType& MetaDataHandler::getSampleType() { return sample_type; } const SampleType& MetaDataHandler::getSampleType() const { return sample_type; } const std::string MetaDataHandler::getSampleTypeAsString() const { return sampleTypeToString.at(sample_type); } bool MetaDataHandler::validateMetaData(const MetaDataHandler& meta_data) { // std::vector<std::string> sample_types {"Unknown", "Standard", "QC", "Blank", "Double Blank", "Solvent"}; bool is_valid { true }; if (meta_data.getSampleName().empty()) { LOGE << "sample_name must be specified"; is_valid = false; } if (meta_data.getSampleGroupName().empty()) { LOGE << "sample_group_name must be specified"; is_valid = false; } if (meta_data.getSequenceSegmentName().empty()) { LOGE << "sequence_segment_name must be specified"; is_valid = false; } if (meta_data.getFilename().empty()) { LOGE << "original_filename must be specified"; is_valid = false; } if (meta_data.getSampleType() == SampleType::Unrecognized) { LOGE << "sample type could not be recognized"; is_valid = false; } if (meta_data.acq_method_name.empty()) { LOGE << "acq_method_name must be specified"; is_valid = false; } if (meta_data.inj_volume <= 0.0) { LOGE << "no value for inj_volume"; is_valid = false; } if (meta_data.inj_volume_units.empty()) { LOGE << "inj_volume_units must be specified"; is_valid = false; } if (meta_data.batch_name.empty()) { LOGE << "batch_name must be specified"; is_valid = false; } return is_valid; } void MetaDataHandler::clear() { sample_name.clear(); sample_group_name.clear(); sequence_segment_name.clear(); original_filename.clear(); sample_type = SampleType::Unknown; acq_method_name.clear(); inj_volume = -1.0; inj_volume_units.clear(); batch_name.clear(); // optional rack_number = -1; plate_number = -1; pos_number = -1; inj_number = -1; dilution_factor = 1.0; instrument.clear(); operator_name.clear(); proc_method_name.clear(); acquisition_date_and_time = { 0, 0, 0, 1, 0, 0, 0, 0, 0 }; scan_polarity = "Unknown"; scan_mass_low = 0.0; scan_mass_high = 1e12; } std::string MetaDataHandler::getInjectionName() const { std::string name(sample_name + "_" + std::to_string(inj_number) + "_" + batch_name + "_"); name.append(getAcquisitionDateAndTimeAsString()); return name; } #ifdef _WIN32 // https://stackoverflow.com/questions/321849/strptime-equivalent-on-windows char* strptime(const char* s, const char* f, std::tm* tm) { // Isn't the C++ standard lib nice? std::get_time is defined such that its // format parameters are the exact same as strptime. Of course, we have to // create a string stream first, and imbue it with the current C locale, and // we also have to make sure we return the right things if it fails, or // if it succeeds, but this is still far simpler an implementation than any // of the versions in any of the C standard libraries. std::istringstream input(s); input.imbue(std::locale(setlocale(LC_ALL, nullptr))); input >> std::get_time(tm, f); if (input.fail()) { return nullptr; } return (char*)(s + input.tellg()); } #endif void MetaDataHandler::setAcquisitionDateAndTimeFromString( const std::string& acquisition_datetime, const std::string& format ) { std::tm tm = { 0, 0, 0, 1, 0, 0, 0, 0, 0 }; if (strptime(acquisition_datetime.data(), format.data(), &tm) == NULL) { throw "Could not convert string to date time object."; } acquisition_date_and_time = tm; } std::string MetaDataHandler::getAcquisitionDateAndTimeAsString(const std::string& format) const { char time_repr[64]; // ISO 8601 date format, without colons (for Windows filesystems compatibility) // i.e. "2019-01-23_164055" const size_t bytes_written = strftime(time_repr, 64, format.data(), &acquisition_date_and_time); if (bytes_written != 17) { throw "Unexpected number of characters written into the array."; } std::string acquisition_datetime(time_repr); return acquisition_datetime; } }
// Copyright (c) 2011-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/test_bitcoin.h> #include <chainparams.h> #include <consensus/consensus.h> #include <consensus/validation.h> #include <crypto/sha256.h> #include <validation.h> #include <miner.h> #include <net_processing.h> #include <pow.h> #include <ui_interface.h> #include <streams.h> #include <rpc/server.h> #include <rpc/register.h> #include <script/sigcache.h> void CConnmanTest::AddNode(CNode& node) { LOCK(g_connman->cs_vNodes); g_connman->vNodes.push_back(&node); } void CConnmanTest::ClearNodes() { LOCK(g_connman->cs_vNodes); for (CNode* node : g_connman->vNodes) { delete node; } g_connman->vNodes.clear(); } uint256 insecure_rand_seed = GetRandHash(); FastRandomContext insecure_rand_ctx(insecure_rand_seed); extern bool fPrintToConsole; extern void noui_connect(); std::ostream& operator<<(std::ostream& os, const uint256& num) { os << num.ToString(); return os; } BasicTestingSetup::BasicTestingSetup(const std::string& chainName) : m_path_root(fs::temp_directory_path() / "test_litecoin" / strprintf("%lu_%i", (unsigned long)GetTime(), (int)(InsecureRandRange(1 << 30)))) { SHA256AutoDetect(); RandomInit(); ECC_Start(); SetupEnvironment(); SetupNetworking(); InitSignatureCache(); InitScriptExecutionCache(); fCheckBlockIndex = true; SelectParams(chainName); noui_connect(); } BasicTestingSetup::~BasicTestingSetup() { fs::remove_all(m_path_root); ECC_Stop(); } fs::path BasicTestingSetup::SetDataDir(const std::string& name) { fs::path ret = m_path_root / name; fs::create_directories(ret); gArgs.ForceSetArg("-datadir", ret.string()); return ret; } TestingSetup::TestingSetup(const std::string& chainName) : BasicTestingSetup(chainName) { SetDataDir("tempdir"); const CChainParams& chainparams = Params(); // Ideally we'd move all the RPC tests to the functional testing framework // instead of unit tests, but for now we need these here. RegisterAllCoreRPCCommands(tableRPC); ClearDatadirCache(); // We have to run a scheduler thread to prevent ActivateBestChain // from blocking due to queue overrun. threadGroup.create_thread(boost::bind(&CScheduler::serviceQueue, &scheduler)); GetMainSignals().RegisterBackgroundSignalScheduler(scheduler); mempool.setSanityCheck(1.0); pblocktree.reset(new CBlockTreeDB(1 << 20, true)); pcoinsdbview.reset(new CCoinsViewDB(1 << 23, true)); pcoinsTip.reset(new CCoinsViewCache(pcoinsdbview.get())); if (!LoadGenesisBlock(chainparams)) { throw std::runtime_error("LoadGenesisBlock failed."); } { CValidationState state; if (!ActivateBestChain(state, chainparams)) { throw std::runtime_error(strprintf("ActivateBestChain failed. (%s)", FormatStateMessage(state))); } } nScriptCheckThreads = 3; for (int i=0; i < nScriptCheckThreads-1; i++) threadGroup.create_thread(&ThreadScriptCheck); g_connman = std::unique_ptr<CConnman>(new CConnman(0x1337, 0x1337)); // Deterministic randomness for tests. connman = g_connman.get(); peerLogic.reset(new PeerLogicValidation(connman, scheduler, /*enable_bip61=*/true)); } TestingSetup::~TestingSetup() { threadGroup.interrupt_all(); threadGroup.join_all(); GetMainSignals().FlushBackgroundCallbacks(); GetMainSignals().UnregisterBackgroundSignalScheduler(); g_connman.reset(); peerLogic.reset(); UnloadBlockIndex(); pcoinsTip.reset(); pcoinsdbview.reset(); pblocktree.reset(); } TestChain100Setup::TestChain100Setup() : TestingSetup(CBaseChainParams::REGTEST) { // CreateAndProcessBlock() does not support building SegWit blocks, so don't activate in these tests. // TODO: fix the code to support SegWit blocks. UpdateVersionBitsParameters(Consensus::DEPLOYMENT_SEGWIT, 0, Consensus::BIP9Deployment::NO_TIMEOUT); // Generate a 100-block chain: coinbaseKey.MakeNewKey(true); CScript scriptPubKey = CScript() << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG; for (int i = 0; i < COINBASE_MATURITY; i++) { std::vector<CMutableTransaction> noTxns; CBlock b = CreateAndProcessBlock(noTxns, scriptPubKey); m_coinbase_txns.push_back(b.vtx[0]); } } // // Create a new block with just given transactions, coinbase paying to // scriptPubKey, and try to add it to the current chain. // CBlock TestChain100Setup::CreateAndProcessBlock(const std::vector<CMutableTransaction>& txns, const CScript& scriptPubKey) { const CChainParams& chainparams = Params(); std::unique_ptr<CBlockTemplate> pblocktemplate = BlockAssembler(chainparams).CreateNewBlock(scriptPubKey); CBlock& block = pblocktemplate->block; // Replace mempool-selected txns with just coinbase plus passed-in txns: block.vtx.resize(1); for (const CMutableTransaction& tx : txns) block.vtx.push_back(MakeTransactionRef(tx)); // IncrementExtraNonce creates a valid coinbase and merkleRoot { LOCK(cs_main); unsigned int extraNonce = 0; IncrementExtraNonce(&block, chainActive.Tip(), extraNonce); } while (!CheckProofOfWork(block.GetPoWHash(), block.nBits, chainparams.GetConsensus())) ++block.nNonce; std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(block); ProcessNewBlock(chainparams, shared_pblock, true, nullptr); CBlock result = block; return result; } TestChain100Setup::~TestChain100Setup() { } CTxMemPoolEntry TestMemPoolEntryHelper::FromTx(const CMutableTransaction &tx) { return FromTx(MakeTransactionRef(tx)); } CTxMemPoolEntry TestMemPoolEntryHelper::FromTx(const CTransactionRef& tx) { return CTxMemPoolEntry(tx, nFee, nTime, nHeight, spendsCoinbase, sigOpCost, lp); } /** * @returns a real block (0000000000013b8ab2cd513b0261a14096412195a72a0c4827d229dcc7e0f7af) * with 9 txs. */ CBlock getBlock13b8a() { CBlock block; CDataStream stream(ParseHex("0100000090f0a9f110702f808219ebea1173056042a714bad51b916cb6800000000000005275289558f51c9966699404ae2294730c3c9f9bda53523ce50e9b95e558da2fdb261b4d4c86041b1ab1bf930901000000010000000000000000000000000000000000000000000000000000000000000000ffffffff07044c86041b0146ffffffff0100f2052a01000000434104e18f7afbe4721580e81e8414fc8c24d7cfacf254bb5c7b949450c3e997c2dc1242487a8169507b631eb3771f2b425483fb13102c4eb5d858eef260fe70fbfae0ac00000000010000000196608ccbafa16abada902780da4dc35dafd7af05fa0da08cf833575f8cf9e836000000004a493046022100dab24889213caf43ae6adc41cf1c9396c08240c199f5225acf45416330fd7dbd022100fe37900e0644bf574493a07fc5edba06dbc07c311b947520c2d514bc5725dcb401ffffffff0100f2052a010000001976a914f15d1921f52e4007b146dfa60f369ed2fc393ce288ac000000000100000001fb766c1288458c2bafcfec81e48b24d98ec706de6b8af7c4e3c29419bfacb56d000000008c493046022100f268ba165ce0ad2e6d93f089cfcd3785de5c963bb5ea6b8c1b23f1ce3e517b9f022100da7c0f21adc6c401887f2bfd1922f11d76159cbc597fbd756a23dcbb00f4d7290141042b4e8625a96127826915a5b109852636ad0da753c9e1d5606a50480cd0c40f1f8b8d898235e571fe9357d9ec842bc4bba1827daaf4de06d71844d0057707966affffffff0280969800000000001976a9146963907531db72d0ed1a0cfb471ccb63923446f388ac80d6e34c000000001976a914f0688ba1c0d1ce182c7af6741e02658c7d4dfcd388ac000000000100000002c40297f730dd7b5a99567eb8d27b78758f607507c52292d02d4031895b52f2ff010000008b483045022100f7edfd4b0aac404e5bab4fd3889e0c6c41aa8d0e6fa122316f68eddd0a65013902205b09cc8b2d56e1cd1f7f2fafd60a129ed94504c4ac7bdc67b56fe67512658b3e014104732012cb962afa90d31b25d8fb0e32c94e513ab7a17805c14ca4c3423e18b4fb5d0e676841733cb83abaf975845c9f6f2a8097b7d04f4908b18368d6fc2d68ecffffffffca5065ff9617cbcba45eb23726df6498a9b9cafed4f54cbab9d227b0035ddefb000000008a473044022068010362a13c7f9919fa832b2dee4e788f61f6f5d344a7c2a0da6ae740605658022006d1af525b9a14a35c003b78b72bd59738cd676f845d1ff3fc25049e01003614014104732012cb962afa90d31b25d8fb0e32c94e513ab7a17805c14ca4c3423e18b4fb5d0e676841733cb83abaf975845c9f6f2a8097b7d04f4908b18368d6fc2d68ecffffffff01001ec4110200000043410469ab4181eceb28985b9b4e895c13fa5e68d85761b7eee311db5addef76fa8621865134a221bd01f28ec9999ee3e021e60766e9d1f3458c115fb28650605f11c9ac000000000100000001cdaf2f758e91c514655e2dc50633d1e4c84989f8aa90a0dbc883f0d23ed5c2fa010000008b48304502207ab51be6f12a1962ba0aaaf24a20e0b69b27a94fac5adf45aa7d2d18ffd9236102210086ae728b370e5329eead9accd880d0cb070aea0c96255fae6c4f1ddcce1fd56e014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff02404b4c00000000001976a9142b6ba7c9d796b75eef7942fc9288edd37c32f5c388ac002d3101000000001976a9141befba0cdc1ad56529371864d9f6cb042faa06b588ac000000000100000001b4a47603e71b61bc3326efd90111bf02d2f549b067f4c4a8fa183b57a0f800cb010000008a4730440220177c37f9a505c3f1a1f0ce2da777c339bd8339ffa02c7cb41f0a5804f473c9230220585b25a2ee80eb59292e52b987dad92acb0c64eced92ed9ee105ad153cdb12d001410443bd44f683467e549dae7d20d1d79cbdb6df985c6e9c029c8d0c6cb46cc1a4d3cf7923c5021b27f7a0b562ada113bc85d5fda5a1b41e87fe6e8802817cf69996ffffffff0280651406000000001976a9145505614859643ab7b547cd7f1f5e7e2a12322d3788ac00aa0271000000001976a914ea4720a7a52fc166c55ff2298e07baf70ae67e1b88ac00000000010000000586c62cd602d219bb60edb14a3e204de0705176f9022fe49a538054fb14abb49e010000008c493046022100f2bc2aba2534becbdf062eb993853a42bbbc282083d0daf9b4b585bd401aa8c9022100b1d7fd7ee0b95600db8535bbf331b19eed8d961f7a8e54159c53675d5f69df8c014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff03ad0e58ccdac3df9dc28a218bcf6f1997b0a93306faaa4b3a28ae83447b2179010000008b483045022100be12b2937179da88599e27bb31c3525097a07cdb52422d165b3ca2f2020ffcf702200971b51f853a53d644ebae9ec8f3512e442b1bcb6c315a5b491d119d10624c83014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff2acfcab629bbc8685792603762c921580030ba144af553d271716a95089e107b010000008b483045022100fa579a840ac258871365dd48cd7552f96c8eea69bd00d84f05b283a0dab311e102207e3c0ee9234814cfbb1b659b83671618f45abc1326b9edcc77d552a4f2a805c0014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffffdcdc6023bbc9944a658ddc588e61eacb737ddf0a3cd24f113b5a8634c517fcd2000000008b4830450221008d6df731df5d32267954bd7d2dda2302b74c6c2a6aa5c0ca64ecbabc1af03c75022010e55c571d65da7701ae2da1956c442df81bbf076cdbac25133f99d98a9ed34c014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffffe15557cd5ce258f479dfd6dc6514edf6d7ed5b21fcfa4a038fd69f06b83ac76e010000008b483045022023b3e0ab071eb11de2eb1cc3a67261b866f86bf6867d4558165f7c8c8aca2d86022100dc6e1f53a91de3efe8f63512850811f26284b62f850c70ca73ed5de8771fb451014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff01404b4c00000000001976a9142b6ba7c9d796b75eef7942fc9288edd37c32f5c388ac00000000010000000166d7577163c932b4f9690ca6a80b6e4eb001f0a2fa9023df5595602aae96ed8d000000008a4730440220262b42546302dfb654a229cefc86432b89628ff259dc87edd1154535b16a67e102207b4634c020a97c3e7bbd0d4d19da6aa2269ad9dded4026e896b213d73ca4b63f014104979b82d02226b3a4597523845754d44f13639e3bf2df5e82c6aab2bdc79687368b01b1ab8b19875ae3c90d661a3d0a33161dab29934edeb36aa01976be3baf8affffffff02404b4c00000000001976a9144854e695a02af0aeacb823ccbc272134561e0a1688ac40420f00000000001976a914abee93376d6b37b5c2940655a6fcaf1c8e74237988ac0000000001000000014e3f8ef2e91349a9059cb4f01e54ab2597c1387161d3da89919f7ea6acdbb371010000008c49304602210081f3183471a5ca22307c0800226f3ef9c353069e0773ac76bb580654d56aa523022100d4c56465bdc069060846f4fbf2f6b20520b2a80b08b168b31e66ddb9c694e240014104976c79848e18251612f8940875b2b08d06e6dc73b9840e8860c066b7e87432c477e9a59a453e71e6d76d5fe34058b800a098fc1740ce3012e8fc8a00c96af966ffffffff02c0e1e400000000001976a9144134e75a6fcb6042034aab5e18570cf1f844f54788ac404b4c00000000001976a9142b6ba7c9d796b75eef7942fc9288edd37c32f5c388ac00000000"), SER_NETWORK, PROTOCOL_VERSION); stream >> block; return block; }
/**************************************************************************** * ==> PSS_NumbersEqualizer -------------------------------------------------* **************************************************************************** * Description : Provides a numbers equalizer * * Developer : Processsoft * ****************************************************************************/ #include "stdafx.h" #include "PSS_NumbersEqualizer.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[] = __FILE__; #define new DEBUG_NEW #endif //--------------------------------------------------------------------------- // PSS_NumbersEqualizer //--------------------------------------------------------------------------- PSS_NumbersEqualizer& PSS_NumbersEqualizer::operator = (const PSS_NumbersEqualizer& other) { // reset the array Reset(); // copy objects PSS_EqNumberIterator it(&other.GetNumberSetConst()); for (PSS_NumberEqualizer* pNumber = it.GetFirst(); pNumber; pNumber = it.GetNext()) m_Set.Add(pNumber->Clone()); // copy member variables m_Total = other.m_Total; m_MinValue = other.m_MinValue; m_LockedTotal = other.m_LockedTotal; return *this; } //--------------------------------------------------------------------------- void PSS_NumbersEqualizer::SetTotalEqualizeNumbers(double total) { // set the new total SetTotal(total); // equalize all unlocked numbers function of percent PSS_EqNumberIterator it(&m_Set); for (PSS_NumberEqualizer* pNumber = it.GetFirst(); pNumber; pNumber = it.GetNext()) if (!pNumber->m_Locked) pNumber->m_Number = pNumber->m_Percent * total; } //--------------------------------------------------------------------------- void PSS_NumbersEqualizer::SetTotalReEqualizeNumbers(double total) { // calculate the amount to distribute, its the total less the sum of locked numbers which will not change const double remainingTotal = total - GetSumOfLockedNumbers(); // set the new total SetTotal(total); // equalize all unlocked numbers function of percent PSS_EqNumberIterator it(&m_Set); for (PSS_NumberEqualizer* pNumber = it.GetFirst(); pNumber; pNumber = it.GetNext()) if (!pNumber->m_Locked) pNumber->m_Number = pNumber->m_Percent * remainingTotal; } //--------------------------------------------------------------------------- void PSS_NumbersEqualizer::FillSet(PSS_EqNumberSet& set) { Reset(); PSS_EqNumberIterator it(&set); for (PSS_NumberEqualizer* pNumber = it.GetFirst(); pNumber; pNumber = it.GetNext()) m_Set.Add(pNumber); } //--------------------------------------------------------------------------- void PSS_NumbersEqualizer::FillSet(PSS_DoubleSet& set, bool locked) { Reset(); const int count = set.GetSize(); for (int i = 0; i < count; ++i) m_Set.Add(new PSS_NumberEqualizer(set.GetAt(i), locked)); } //--------------------------------------------------------------------------- void PSS_NumbersEqualizer::SetNumberAtEqualize(std::size_t index, double number) { const double countLocked = static_cast<double>(GetLockedCount()); const double countUnlocked = static_cast<double>(GetUnlockedCount()); double totalLocked = GetSumOfLockedNumbers(); double totalUnlocked = GetSumOfUnlockedNumbers(); bool error; const double previousNumber = GetNumberAt(index, error); if (error) return; // check that the minimum value is respected. If not, set the min value if (number < m_MinValue) number = m_MinValue; // this is what can be removed from elements const double maximumValue = totalUnlocked - previousNumber; // if the initial number is higher than the maximum value, set all elements to zero // and set the number to the maximum value if (number > totalUnlocked) { // set the new number SetNumberAt(index, totalUnlocked); // set all other unlocked value to zero SetValueToUnlockedNumbers(0, index); } else { // calculate the difference double diff = previousNumber - number; // set the new number SetNumberAt(index, number); do { const double valuePerElement = diff / (countUnlocked - 1); // add the difference per element, except for the current element AddDeltaToUnlockedNumbers(valuePerElement, index); // calculate the difference against the real sum diff = GetTotal() - GetSum(); } while (diff > 0.01 || diff < -0.01); } // recalculate all percentages CalculatePercents(); } //--------------------------------------------------------------------------- void PSS_NumbersEqualizer::SetPercentAtEqualize(std::size_t index, double percent) { // calculate the new number const double newNumber = percent * GetTotal(); // once calculated, call the SetNumberAtEqualize() function to assign its new value SetNumberAtEqualize(index, newNumber); } //--------------------------------------------------------------------------- void PSS_NumbersEqualizer::Reset() { const int count = m_Set.GetSize(); for (int i = 0; i < count; ++i) if (m_Set.GetAt(i)) delete m_Set.GetAt(i); m_Set.RemoveAll(); } //--------------------------------------------------------------------------- double PSS_NumbersEqualizer::GetSum() const { PSS_EqNumberIterator it(&m_Set); double sum = 0; for (PSS_NumberEqualizer* pNumber = it.GetFirst(); pNumber; pNumber = it.GetNext()) sum += pNumber->m_Number; return sum; } //--------------------------------------------------------------------------- double PSS_NumbersEqualizer::GetSumOfLockedNumbers() const { PSS_EqNumberIterator it(&m_Set); double sum = 0; for (PSS_NumberEqualizer* pNumber = it.GetFirst(); pNumber; pNumber = it.GetNext()) if (pNumber->m_Locked) sum += pNumber->m_Number; return sum; } //--------------------------------------------------------------------------- double PSS_NumbersEqualizer::GetSumOfUnlockedNumbers() const { PSS_EqNumberIterator it(&m_Set); double sum = 0; for (PSS_NumberEqualizer* pNumber = it.GetFirst(); pNumber; pNumber = it.GetNext()) if (!pNumber->m_Locked) sum += pNumber->m_Number; return sum; } //--------------------------------------------------------------------------- std::size_t PSS_NumbersEqualizer::GetLockedCount() const { PSS_EqNumberIterator it(&m_Set); std::size_t counter = 0; for (PSS_NumberEqualizer* pNumber = it.GetFirst(); pNumber; pNumber = it.GetNext()) if (pNumber->m_Locked) ++counter; return counter; } //--------------------------------------------------------------------------- std::size_t PSS_NumbersEqualizer::GetUnlockedCount() const { PSS_EqNumberIterator it(&m_Set); std::size_t counter = 0; for (PSS_NumberEqualizer* pNumber = it.GetFirst(); pNumber; pNumber = it.GetNext()) if (!pNumber->m_Locked) ++counter; return counter; } //--------------------------------------------------------------------------- void PSS_NumbersEqualizer::SetValueToLockedNumbers(double value, int indexToIgnore) { PSS_EqNumberIterator it(&m_Set); int n = 0; for (PSS_NumberEqualizer* pNumber = it.GetFirst(); pNumber; ++n, pNumber = it.GetNext()) if (pNumber->m_Locked && n != indexToIgnore) pNumber->m_Number = value; } //--------------------------------------------------------------------------- void PSS_NumbersEqualizer::SetValueToUnlockedNumbers(double value, int indexToIgnore) { PSS_EqNumberIterator it(&m_Set); int n = 0; for (PSS_NumberEqualizer* pNumber = it.GetFirst(); pNumber; ++n, pNumber = it.GetNext()) if (!pNumber->m_Locked && n != indexToIgnore) pNumber->m_Number = value; } //--------------------------------------------------------------------------- bool PSS_NumbersEqualizer::AddDeltaToLockedNumbers(double delta, int indexToIgnore) { PSS_EqNumberIterator it(&m_Set); int n = 0; bool deltaRespected = true; for (PSS_NumberEqualizer* pNumber = it.GetFirst(); pNumber; ++n, pNumber = it.GetNext()) if (pNumber->m_Locked && n != indexToIgnore) if ((pNumber->m_Number + delta) < m_MinValue) { pNumber->m_Number = m_MinValue; deltaRespected = false; } else pNumber->m_Number += delta; return deltaRespected; } //--------------------------------------------------------------------------- bool PSS_NumbersEqualizer::AddDeltaToUnlockedNumbers(double delta, int indexToIgnore) { PSS_EqNumberIterator it(&m_Set); int n = 0; bool deltaRespected = true; for (PSS_NumberEqualizer* pNumber = it.GetFirst(); pNumber; ++n, pNumber = it.GetNext()) if (!pNumber->m_Locked && n != indexToIgnore) if ((pNumber->m_Number + delta) < m_MinValue) { pNumber->m_Number = m_MinValue; deltaRespected = false; } else pNumber->m_Number += delta; return deltaRespected; } //--------------------------------------------------------------------------- bool PSS_NumbersEqualizer::SubstDeltaToLockedNumbers(double delta, int indexToIgnore) { PSS_EqNumberIterator it(&m_Set); int n = 0; bool deltaRespected = true; for (PSS_NumberEqualizer* pNumber = it.GetFirst(); pNumber; ++n, pNumber = it.GetNext()) if (pNumber->m_Locked && n != indexToIgnore) if ((pNumber->m_Number - delta) < m_MinValue) { pNumber->m_Number = m_MinValue; deltaRespected = false; } else pNumber->m_Number -= delta; return deltaRespected; } //--------------------------------------------------------------------------- bool PSS_NumbersEqualizer::SubstDeltaToUnlockedNumbers(double delta, int indexToIgnore) { PSS_EqNumberIterator it(&m_Set); int n = 0; bool deltaRespected = true; for (PSS_NumberEqualizer* pNumber = it.GetFirst(); pNumber; ++n, pNumber = it.GetNext()) if (!pNumber->m_Locked && n != indexToIgnore) if ((pNumber->m_Number - delta) < m_MinValue) { pNumber->m_Number = m_MinValue; deltaRespected = false; } else pNumber->m_Number -= delta; return deltaRespected; } //--------------------------------------------------------------------------- void PSS_NumbersEqualizer::CalculatePercents() { const double totalSum = GetTotal(); PSS_EqNumberIterator it(&m_Set); // iterate through the list of elements and calculate the percentage for (PSS_NumberEqualizer* pNumber = it.GetFirst(); pNumber; pNumber = it.GetNext()) if (totalSum > 0) pNumber->m_Percent = pNumber->m_Number / totalSum; else pNumber->m_Percent = 0; } //--------------------------------------------------------------------------- void PSS_NumbersEqualizer::CalculatePercent(std::size_t index) { if (index < GetCount()) { PSS_NumberEqualizer* pNumber = m_Set.GetAt(index); pNumber->m_Percent = pNumber->m_Number / GetTotal(); } } //---------------------------------------------------------------------------
/** * Copyright 2020 Huawei Technologies 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 <vector> #include <string> #include <utility> #include <algorithm> #include <functional> #include "src/tensor.h" #include "securec/include/securec.h" #include "include/errorcode.h" namespace mindspore { namespace lite { #define kMaxMallocSize 1024 * 1024 * 100 Tensor::Tensor(const TypeId data_type, std::vector<int> shape, const schema::Format &format, Category category) : data_type_(data_type), shape_(std::move(shape)), format_(format), category_(category) {} Tensor::Tensor(const std::string &name, enum TypeId type, const std::vector<int32_t> &shape, const void *data) : tensor_name_(name), data_type_(type), shape_(std::move(shape)), category_(VAR) { data_ = const_cast<void *>(data); } int Tensor::CopyTensorData(const Tensor &src_tensor, Tensor *dst_tensor) { if (dst_tensor == nullptr) { MS_LOG(ERROR) << "dst_tensor is nullptr"; return RET_PARAM_INVALID; } if (src_tensor.data_ == nullptr) { MS_LOG(ERROR) << "data of src tensor is nullptr"; return RET_PARAM_INVALID; } size_t data_size = dst_tensor->Size(); if (data_size != src_tensor.Size()) { MS_LOG(ERROR) << "Size of dst tensor is not compatible with src tensor"; return RET_ERROR; } if (dst_tensor->data_ == nullptr) { if (data_size > kMaxMallocSize) { MS_LOG(ERROR) << "Malloc size is too big while coping data, " << data_size << " bytes"; return RET_ERROR; } dst_tensor->data_ = malloc(data_size); if (dst_tensor->data_ == nullptr) { MS_LOG(ERROR) << "Malloc memory failed"; return RET_ERROR; } } memcpy(dst_tensor->data_, src_tensor.data_, data_size); return RET_OK; } Tensor *Tensor::CopyTensor(const Tensor &src_tensor, bool copy_data) { auto *result = new (std::nothrow) Tensor; if (result == nullptr) { MS_LOG(ERROR) << "New tensor failed"; return nullptr; } result->data_type_ = src_tensor.data_type_; result->shape_ = src_tensor.shape_; result->category_ = src_tensor.category_; result->format_ = src_tensor.format_; if (copy_data) { auto ret = CopyTensorData(src_tensor, result); if (ret != RET_OK) { MS_LOG(ERROR) << "CopyTensorData error"; return nullptr; } } return result; } Tensor::~Tensor() { if (nullptr != this->data_) { if (this->allocator_ != nullptr) { this->allocator_->Free(this->data_); } else { free(this->data_); } this->data_ = nullptr; } } bool Tensor::operator==(const Tensor &tensor) { return data_ == tensor.data_ && shape_ == tensor.shape_ && data_type_ == tensor.data_type_; } int32_t Tensor::Batch() const { if (this->shape_.size() != 4 && this->shape_.size() != 2) { MS_LOG(ERROR) << "Unsupported tensor shape: " << this->shape().size(); return RET_ERROR; } switch (this->format_) { case schema::Format::Format_NHWC: case schema::Format::Format_NHWC4: case schema::Format::Format_NCHW: case schema::Format::Format_NC4HW4: case schema::Format::Format_KCHW: case schema::Format::Format_KHWC: case schema::Format::Format_NC: case schema::Format::Format_NC4: return this->shape_[0]; case schema::Format::Format_HWCK: case schema::Format::Format_CHWK: return this->shape_[3]; case schema::Format::Format_HWKC: return this->shape_[2]; case schema::Format::Format_CKHW: return this->shape_[1]; default: MS_LOG(ERROR) << "Unsupported format: " << EnumNameFormat(this->format_); return RET_ERROR; } } int32_t Tensor::Channel() const { if (this->shape_.size() != 4 && this->shape_.size() != 2) { MS_LOG(ERROR) << "Unsupported tensor shape: " << this->shape().size(); return RET_ERROR; } switch (this->format_) { case schema::Format::Format_NCHW: case schema::Format::Format_KCHW: case schema::Format::Format_NC: case schema::Format::Format_NC4: return this->shape_[1]; case schema::Format::Format_HWCK: return this->shape_[2]; case schema::Format::Format_HWKC: case schema::Format::Format_NHWC: case schema::Format::Format_NHWC4: case schema::Format::Format_NC4HW4: case schema::Format::Format_KHWC: return this->shape_[3]; case schema::Format::Format_CKHW: case schema::Format::Format_CHWK: return this->shape_[0]; default: return RET_ERROR; } } int32_t Tensor::Height() const { if (this->shape_.size() != 4 && this->shape_.size() != 2) { MS_LOG(ERROR) << "Unsupported tensor shape: " << this->shape().size(); return RET_ERROR; } switch (this->format_) { case schema::Format::Format_NCHW: case schema::Format::Format_KCHW: case schema::Format::Format_CKHW: return this->shape_[2]; case schema::Format::Format_NHWC: case schema::Format::Format_NHWC4: case schema::Format::Format_NC4HW4: case schema::Format::Format_KHWC: case schema::Format::Format_CHWK: return this->shape_[1]; case schema::Format::Format_HWCK: case schema::Format::Format_HWKC: case schema::Format::Format_HW: case schema::Format::Format_HW4: return this->shape_[0]; default: MS_LOG(ERROR) << "Unsupported format: " << EnumNameFormat(this->format_); return RET_ERROR; } } int32_t Tensor::Width() const { if (this->shape_.size() != 4 && this->shape_.size() != 2) { MS_LOG(ERROR) << "Unsupported tensor shape: " << this->shape().size(); return -1; } switch (this->format_) { case schema::Format::Format_NCHW: case schema::Format::Format_KCHW: case schema::Format::Format_CKHW: return this->shape_[3]; case schema::Format::Format_KHWC: case schema::Format::Format_NHWC: case schema::Format::Format_NHWC4: case schema::Format::Format_NC4HW4: case schema::Format::Format_CHWK: return this->shape_[2]; case schema::Format::Format_HWCK: case schema::Format::Format_HWKC: case schema::Format::Format_HW: case schema::Format::Format_HW4: return this->shape_[1]; default: return RET_ERROR; } } size_t Tensor::Size() const { size_t element_size = DataTypeSize(this->data_type_); auto element_num = (format_ == schema::Format::Format_NC4HW4 || format_ == schema::Format::Format_NHWC4) ? ElementsC4Num() : ElementsNum(); if (element_num < 0) { MS_LOG(ERROR) << "Element number of tensor should large than 0 : " << element_num; return 0; } return element_size * element_num; } int Tensor::ElementsNum() const { if (this->category_ == CONST_SCALAR) { return 1; } return std::accumulate(shape_.begin(), shape_.end(), 1LL, std::multiplies<int>()); } int32_t Tensor::ElementsC4Num() const { if (this->category_ == CONST_SCALAR) { return 1; } int32_t result = 0; if (this->shape_.size() == 4) { result = Batch() * Height() * Width() * ((Channel() + 3) / 4 * 4); } else if (this->shape_.size() == 2) { result = this->shape_[0] * ((this->shape_[1] + 3) / 4 * 4); } return result; } int Tensor::DimensionSize(const size_t index) const { int dim_size = -1; if (index < shape_.size()) { dim_size = shape_[index]; } else { MS_LOG(ERROR) << "Dimension index is wrong: " << index; } return dim_size; } std::string Tensor::ToString() const { std::ostringstream oss; oss << "schema::Format: " << EnumNameFormat(this->format_); oss << " DataType: " << this->data_type_; oss << " Category: " << this->category_; oss << " Shape:"; for (auto &dim : this->shape()) { oss << " " << dim; } oss << std::endl << "Data:"; switch (this->data_type_) { case kNumberTypeFloat32: { oss << DataToString<float>(this->data_c(), this->ElementsNum()); } break; case kNumberTypeFloat16: { oss << DataToString<int16_t>(this->data_c(), this->ElementsNum()); } break; case kNumberTypeInt32: { oss << DataToString<int32_t>(this->data_c(), this->ElementsNum()); } break; case kNumberTypeInt16: { oss << DataToString<int16_t>(this->data_c(), this->ElementsNum()); } break; case kNumberTypeInt8: { oss << DataToString<int8_t>(this->data_c(), this->ElementsNum()); } break; default: oss << "Unsupported data type to print"; break; } return oss.str(); } int Tensor::set_root_tensor(Tensor *tensor) { this->root_tensor_ = tensor; if (this->root_tensor_ == this) { return RET_OK; } if (this->root_tensor_ == nullptr) { return RET_OK; } this->shape_ = this->root_tensor_->shape_; this->format_ = this->root_tensor_->format_; this->data_type_ = this->root_tensor_->data_type_; this->category_ = this->root_tensor_->category_; this->quant_params_ = this->root_tensor_->quant_params_; this->quant_clusters_ = this->root_tensor_->quant_clusters_; return RET_OK; } int Tensor::MallocData(const mindspore::lite::Allocator *allocator) { if (nullptr != this->data_) { return RET_OK; } if (allocator != nullptr) { allocator_ = const_cast<mindspore::lite::Allocator *>(allocator); } if (allocator_ == nullptr) { this->data_ = malloc(this->Size()); } else { this->data_ = allocator_->Malloc(this->Size()); } if (nullptr == this->data_) { MS_LOG(ERROR) << "Malloc tensor data failed, size=" << this->Size(); return RET_ERROR; } return RET_OK; } void Tensor::FreeData() { if (nullptr == this->data_) { return; } if (nullptr == allocator_) { free(this->data_); this->data_ = nullptr; } else { allocator_->Free(this->data_); this->data_ = nullptr; } } void *Tensor::MutableData() { if (this->root_tensor_ != nullptr) { if (this->root_tensor_ != this && this->root_tensor_->data_ == nullptr) { MS_LOG(ERROR) << "root tensor has not been malloced"; return nullptr; } else if (this->root_tensor_ != this && this->root_tensor_->data_ != nullptr) { return this->root_tensor_->data_; } else { // malloc self } } if (this->data_ == nullptr) { auto ret = this->MallocData(); if (ret != 0) { MS_LOG(WARNING) << "Malloc data failed"; } } Prepare(); return this->data_; } void Tensor::DecRefCount() { if (this->IsConst() || this->IsGraphInput()) { return; } this->ref_count_--; if (this->ref_count_ <= 0) { FreeData(); this->ref_count_ = 0; } } void Tensor::AddQuantParam(const QuantArg &quant_arg) { this->quant_params_.push_back(quant_arg); } std::vector<QuantArg> Tensor::quant_params() const { return this->quant_params_; } std::vector<float> Tensor::quant_clusters() const { return this->quant_clusters_; } void Tensor::set_quant_clusters(const std::vector<float> &clusters) { this->quant_clusters_ = clusters; } bool Tensor::enable_huffman_code() const { return enable_huffman_code_; } void Tensor::set_enable_huffman_code(bool enable_huffman_code) { this->enable_huffman_code_ = enable_huffman_code; } std::vector<tensor::MSTensor *> TensorVectorCast(const std::vector<Tensor *> &src) { std::vector<tensor::MSTensor *> target(src.size()); std::transform(src.begin(), src.end(), target.begin(), [](Tensor *t) { return dynamic_cast<tensor::MSTensor *>(t); }); return target; } } // namespace lite } // namespace mindspore
// // ContextRestorer.cpp // Chilli Source // Created by Scott Downie on 14/04/2014. // // The MIT License (MIT) // // Copyright (c) 2014 Tag Games Limited // // 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. // #ifdef CS_TARGETPLATFORM_ANDROID #include <CSBackend/Rendering/OpenGL/Base/ContextRestorer.h> #include <CSBackend/Rendering/OpenGL/Base/MeshBuffer.h> #include <CSBackend/Rendering/OpenGL/Texture/Cubemap.h> #include <CSBackend/Rendering/OpenGL/Texture/Texture.h> #include <ChilliSource/Core/Base/Application.h> #include <ChilliSource/Core/Resource/ResourcePool.h> #include <ChilliSource/Rendering/Shader/Shader.h> namespace CSBackend { namespace OpenGL { //----------------------------------------------------- /// Shaders and most textures can be recreated from file, /// however the mesh buffers must have a snap shot taken //----------------------------------------------------- void ContextRestorer::Backup() { if(m_hasContextBeenBackedUp == false) { for(auto& buffer : m_meshBuffers) { buffer->Backup(); } m_hasContextBeenBackedUp = true; } } //----------------------------------------------------- /// Rebuild the shaders and textures from file. Re-upload /// the mesh buffers //----------------------------------------------------- void ContextRestorer::Restore() { if(m_hasContextBeenBackedUp == true) { CSCore::ResourcePool* resourcePool = CSCore::Application::Get()->GetResourcePool(); //---Shaders auto allShaders = resourcePool->GetAllResources<CSRendering::Shader>(); for (const auto& shader : allShaders) { CS_ASSERT(shader->GetStorageLocation() != CSCore::StorageLocation::k_none, "Cannot restore Shader because restoration of OpenGL resources that were not loaded from file is not supported. To resolve this, manually release the resource on suspend and re-create it on resume."); } resourcePool->RefreshResources<CSRendering::Shader>(); //---Textures auto allTextures = resourcePool->GetAllResources<CSRendering::Texture>(); for (const auto& texture : allTextures) { if (texture->GetStorageLocation() == CSCore::StorageLocation::k_none) { Texture* glTexture = static_cast<Texture*>(const_cast<CSRendering::Texture*>(texture.get())); glTexture->Restore(); } } resourcePool->RefreshResources<CSRendering::Texture>(); //---Cubemaps auto allCubemaps = resourcePool->GetAllResources<CSRendering::Cubemap>(); for (const auto& cubemap : allCubemaps) { if (cubemap->GetStorageLocation() == CSCore::StorageLocation::k_none) { Cubemap* glCubemap = static_cast<Cubemap*>(const_cast<CSRendering::Cubemap*>(cubemap.get())); glCubemap->Restore(); } } resourcePool->RefreshResources<CSRendering::Cubemap>(); //---Meshes for(auto& buffer : m_meshBuffers) { buffer->Restore(); } m_hasContextBeenBackedUp = false; } } //----------------------------------------------------- //----------------------------------------------------- void ContextRestorer::AddMeshBuffer(MeshBuffer* in_meshBuffer) { m_meshBuffers.push_back(in_meshBuffer); } //----------------------------------------------------- //----------------------------------------------------- void ContextRestorer::RemoveMeshBuffer(MeshBuffer* in_meshBuffer) { for(u32 i=0; i<m_meshBuffers.size(); ++i) { if(m_meshBuffers[i] == in_meshBuffer) { m_meshBuffers[i] = m_meshBuffers.back(); m_meshBuffers.pop_back(); return; } } } } } #endif
/******************************************************** * * This test file will test RGB planar tiled tiff reading * *******************************************************/ //#define BOOST_TEST_MODULE tiff_tiled_rgb_planar_test_11_20_module #include <boost/test/unit_test.hpp> #include "tiff_tiled_read_macros.hpp" BOOST_AUTO_TEST_SUITE( tiff_test ) #ifdef BOOST_GIL_IO_USE_TIFF_GRAPHICSMAGICK_TEST_SUITE_IMAGES BOOST_PP_REPEAT_FROM_TO(11, 16, GENERATE_TILE_STRIP_COMPARISON_BIT_ALIGNED_RGB, (rgb,planar) ) BOOST_PP_REPEAT_FROM_TO(17, 21, GENERATE_TILE_STRIP_COMPARISON_BIT_ALIGNED_RGB, (rgb,planar) ) BOOST_AUTO_TEST_CASE( read_tile_and_compare_with_rgb_planar_strip_16 ) { using namespace std; using namespace boost; using namespace gil; string filename_strip( tiff_in_GM + "tiger-rgb-strip-planar-16.tif" ); string filename_tile ( tiff_in_GM + "tiger-rgb-tile-planar-16.tif" ); rgb16_image_t img_strip, img_tile; read_image( filename_strip, img_strip, tag_t() ); read_image( filename_tile, img_tile, tag_t() ); BOOST_CHECK_EQUAL( equal_pixels( const_view(img_strip), const_view(img_tile) ), true); } #endif // BOOST_GIL_IO_USE_TIFF_GRAPHICSMAGICK_TEST_SUITE_IMAGES BOOST_AUTO_TEST_SUITE_END()
#include <arrayfire.h> #ifdef WANT_CUDA #include <../cuda.h> #endif #ifdef WANT_OPENCL #include <../opencl.h> #endif // ^^^ TODO: probably not right! #include "../funcs.h" static const struct luaL_Reg interface_funcs[] = { #if AF_API_VERSION >= 32 #if WANT_OPENCL { // af_err afcl_get_context (cl_context * ctx, const bool retain); }, { // af_err afcl_get_device_id (cl_device_id * id); }, #endif #if WANT_CUDA { // af_err afcu_get_native_id (int * nativeid, int id); }, #endif #if WANT_OPENCL { // af_err afcl_get_queue (cl_command_queue * queue, const bool retain); }, #endif #if WANT_CUDA { // af_err afcu_get_stream (cudaStream_t * stream, int id); }, #endif #endif { NULL, NULL } }; int Interface (lua_State * L) { luaL_register(L, NULL, interface_funcs); return 0; }
// Copyright (c) 2021-present Sparky Studios. 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 <StdAfx.h> #include <SSBehaviorTreeComponent.h> #include <SparkyStudios/AI/BehaviorTree/Core/SSBehaviorTreeNode.h> #include <SparkyStudios/AI/BehaviorTree/SSBehaviorTreeBus.h> #include <AzCore/Asset/AssetSerializer.h> #include <AzCore/Serialization/EditContext.h> #include <AzCore/Serialization/SerializeContext.h> namespace SparkyStudios::AI::BehaviorTree { SSBehaviorTreeComponent::SSBehaviorTreeComponent() : m_behaviorTreeAsset(AZ::Data::AssetLoadBehavior::PreLoad) , m_running(false) , m_tree(BT::Tree()) , m_btBlackboard() { } SSBehaviorTreeComponent::~SSBehaviorTreeComponent() { //! Needed to avoid memory read access violation m_tree.nodes.clear(); m_tree.blackboard_stack.clear(); m_tree.manifests.clear(); } void SSBehaviorTreeComponent::SetBehaviorTree(const AZ::Data::Asset<Assets::SSBehaviorTreeAsset>& asset) { UpdateAsset(asset, !m_running); } void SSBehaviorTreeComponent::Init() { } void SSBehaviorTreeComponent::Activate() { AZ::TickBus::Handler::BusConnect(); // If we have valid asset listen for script asset events, like reload if (m_behaviorTreeAsset.GetId().IsValid()) { AZ::Data::AssetBus::Handler::BusConnect(m_behaviorTreeAsset.GetId()); m_behaviorTreeAsset.QueueLoad(); } // Set the attached entity's ID in the tree blackboard m_btBlackboard.m_blackboard->set<AZ::EntityId>("entityId", GetEntityId()); } void SSBehaviorTreeComponent::Deactivate() { UnloadBehaviorTree(); AZ::Data::AssetBus::Handler::BusDisconnect(m_behaviorTreeAsset.GetId()); AZ::TickBus::Handler::BusDisconnect(); } void SSBehaviorTreeComponent::OnAssetReady(AZ::Data::Asset<AZ::Data::AssetData> asset) { UpdateAsset(asset); } void SSBehaviorTreeComponent::OnAssetReloaded(AZ::Data::Asset<AZ::Data::AssetData> asset) { UpdateAsset(asset, true); } void SSBehaviorTreeComponent::OnTick(float deltaTime, AZ::ScriptTimePoint time) { AZ_UNUSED(time); AZ_UNUSED(deltaTime); // If the behavior tree is paused if (!m_running) return; // If the behavior tree is empty if (!m_tree.rootNode()) { AZ_Warning("SSBehaviorTree", false, "The behavior tree is empty for entity with ID: %s", GetEntityId()); return; } // Run the behavior tree m_tree.tickRoot(); } int SSBehaviorTreeComponent::GetTickOrder() { return AZ::TICK_GAME; } void SSBehaviorTreeComponent::LoadBehaviorTree() { auto* asset = m_behaviorTreeAsset.GetAs<Assets::SSBehaviorTreeAsset>(); const AZStd::vector<char>& buffer = asset->GetBuffer(); if (!buffer.empty()) { AZ_Printf("SSBehaviorTree", "Loading %s", m_behaviorTreeAsset.GetHint().c_str()); Core::SSBehaviorTreeFactory factory; EBUS_EVENT_RESULT(factory, SSBehaviorTreeRequestBus, GetFactory); LoadBlackboard(asset); AZStd::string data = AZStd::string(buffer.cbegin(), buffer.cend()); m_tree = factory.CreateTreeFromText(data, m_btBlackboard); AZ_Printf("SSBehaviorTree", "Loaded %s", m_behaviorTreeAsset.GetHint().c_str()); m_running = m_tree.rootNode() != nullptr; } } void SSBehaviorTreeComponent::UpdateAsset(const AZ::Data::Asset<Assets::SSBehaviorTreeAsset>& asset, bool force) { if (asset && (asset.GetId() != m_behaviorTreeAsset.GetId() || force)) { if (m_behaviorTreeAsset.GetId().IsValid()) { UnloadBehaviorTree(); AZ::Data::AssetBus::Handler::BusDisconnect(m_behaviorTreeAsset.GetId()); } m_behaviorTreeAsset = asset; if (m_behaviorTreeAsset.GetId().IsValid()) { AZ::Data::AssetBus::Handler::BusConnect(m_behaviorTreeAsset.GetId()); } } if (!m_running && m_behaviorTreeAsset.IsReady()) { LoadBehaviorTree(); } } void SSBehaviorTreeComponent::LoadBlackboard(const Assets::SSBehaviorTreeAsset* asset) const { AZ_UNUSED(asset); for (auto* prop : m_btBlackboard.m_properties) { prop->AddBlackboardEntry(m_btBlackboard); } } void SSBehaviorTreeComponent::UnloadBehaviorTree() { m_tree.haltTree(); m_running = false; } void SSBehaviorTreeComponent::Reflect(AZ::ReflectContext* context) { if (auto* sc = azrtti_cast<AZ::SerializeContext*>(context)) { // We may have been reflected by SSBehaviorTreeEditorComponent already, so check first if (sc->FindClassData(azrtti_typeid<SSBehaviorTreeComponent>()) == nullptr) { // Expose component fields sc->Class<SSBehaviorTreeComponent, AZ::Component>() ->Version(0) ->Field("blackboard", &SSBehaviorTreeComponent::m_btBlackboard) ->Field("behaviorTree", &SSBehaviorTreeComponent::m_behaviorTreeAsset); sc->Class<Blackboard::SSBehaviorTreeBlackboard>() ->Field("name", &Blackboard::SSBehaviorTreeBlackboard::m_name) ->Field("properties", &Blackboard::SSBehaviorTreeBlackboard::m_properties); // Reflect all properties Blackboard::SSBehaviorTreeBlackboardProperty::Reflect(context); Blackboard::SSBehaviorTreeBlackboardPropertyBoolean::Reflect(context); Blackboard::SSBehaviorTreeBlackboardPropertyNumber::Reflect(context); Blackboard::SSBehaviorTreeBlackboardPropertyString::Reflect(context); Blackboard::SSBehaviorTreeBlackboardPropertyEntityRef::Reflect(context); Blackboard::SSBehaviorTreeBlackboardPropertyVector2::Reflect(context); } } } } // namespace SparkyStudios::AI::BehaviorTree
/* * Copyright 2021 Google LLC * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "experimental/graphite/src/TextureProxy.h" #include "experimental/graphite/src/ResourceProvider.h" #include "experimental/graphite/src/Texture.h" namespace skgpu { TextureProxy::TextureProxy(SkISize dimensions, const TextureInfo& info) : fDimensions(dimensions), fInfo(info) {} TextureProxy::TextureProxy(sk_sp<Texture> texture) : fDimensions(texture->dimensions()) , fInfo(texture->textureInfo()) , fTexture(std::move(texture)) {} TextureProxy::~TextureProxy() {} bool TextureProxy::instantiate(ResourceProvider* resourceProvider) { if (fTexture) { return true; } fTexture = resourceProvider->findOrCreateTexture(fDimensions, fInfo); if (!fTexture) { return false; } SkDEBUGCODE(this->validateTexture(fTexture.get())); return true; } sk_sp<Texture> TextureProxy::refTexture() const { return fTexture; } const Texture* TextureProxy::texture() const { return fTexture.get(); } #ifdef SK_DEBUG void TextureProxy::validateTexture(const Texture* texture) { SkASSERT(fDimensions == texture->dimensions()); SkASSERT(fInfo == texture->textureInfo()); } #endif } // namespace skgpu
#include <string> #include <cstring> #include <stdint.h> #include <unistd.h> #include "playfile.h" //file_play::file_play(const char* f,int r,int s,int re, int cp) file_play::file_play() { std::shared_ptr<playfile_param_t> data_current = std::make_shared<playfile_param_t> (); // data_current->audiofile = new AudioFile<float>(); data_current->numSamples = 0; data_current->current_position_l=data_current->numSamples; data_current->current_position_r=data_current->numSamples; data_current->repeat=0; data_current->finish = true; releasePool.add (data_current); std::atomic_store (&currentParam, data_current); } void file_play::rtmha_play(int num_sample, float *out, int channel) { std::shared_ptr<playfile_param_t> data_current = std::atomic_load(&currentParam); int playback_channel = channel; int current_position; if (playback_channel == 0) { current_position = data_current->current_position_l; } else { current_position = data_current->current_position_r; } if (data_current->mono) playback_channel = 0; if (current_position + num_sample < data_current->numSamples && !data_current->finish) { memcpy(out, &data_current->audiofile->samples[playback_channel][current_position], sizeof(float) * num_sample); current_position = current_position + num_sample; } else if (!data_current->finish) { int temp = current_position + num_sample - data_current->numSamples; int remain = data_current->numSamples - current_position; if (data_current->repeat == 0) { memcpy(out, &data_current->audiofile->samples[playback_channel][current_position], sizeof(float) * remain); data_current->finish = 1; std::cout << "Played" << std::endl; } else { memcpy(out, &data_current->audiofile->samples[playback_channel][current_position], sizeof(float) * remain); memcpy(&out[remain], &data_current->audiofile->samples[playback_channel][0], sizeof(float) * temp); current_position = current_position + num_sample - data_current->numSamples; } } else { for (int i = 0; i < num_sample; i++) out[i] = 0; } if (playback_channel == 0) { data_current->current_position_l = current_position; } else { data_current->current_position_r = current_position; } } void file_play::get_params(int &finish) { std::shared_ptr<playfile_param_t> data_current = std::atomic_load(&currentParam); finish = data_current->finish; } void file_play::set_params(std::string file_, int reset_, int repeat_, int play_) { std::shared_ptr<playfile_param_t> data_next = std::make_shared<playfile_param_t>(); data_next->filename = file_; std::cout << "Play File: " << data_next->filename << std::endl; data_next->audiofile = new AudioFile<float>(); if (data_next->audiofile->load(data_next->filename) == false) { return; } data_next->audiofile->printSummary(); data_next->numSamples = data_next->audiofile->getNumSamplesPerChannel(); data_next->mono = data_next->audiofile->isMono(); data_next->reset = reset_; data_next->play = play_; if (data_next->play == 1) { data_next->current_position_l = 0; data_next->current_position_r = 0; std::cout << "Starting" << std::endl; data_next->finish = false; } else { data_next->current_position_l = data_next->numSamples; data_next->current_position_r = data_next->numSamples; data_next->finish = true; } data_next->repeat = repeat_; releasePool.add(data_next); std::atomic_store(&currentParam, data_next); releasePool.release(); } file_play::~file_play() { releasePool.release(); //delete audiofile; }
 #ifndef RUIN_UTILITY_VALUE_HOLDER_HPP_INCLUDED #define RUIN_UTILITY_VALUE_HOLDER_HPP_INCLUDED #include "ruin/utility/address_of.hpp" #include "ruin/utility/swap.hpp" namespace ruin { namespace detail { namespace value_holder { template < class T > struct helper { typedef T value_type; typedef T& reference; typedef T const& const_reference; typedef T* pointer; typedef T const* const_pointer; typedef T const& param_type; typedef T holder_type; static constexpr holder_type const& hold (param_type p) { return p; } static constexpr reference ref (holder_type& r) { return r; } static constexpr const_reference ref (holder_type const& r) { return r; } static constexpr pointer ptr (holder_type& r) { return ruin::address_of(r); } static constexpr const_pointer ptr (holder_type const& r) { return ruin::address_of(r); } }; template < class T > struct helper<T const> { typedef T value_type; typedef T const& reference; typedef T const& const_reference; typedef T const* pointer; typedef T const* const_pointer; typedef T const& param_type; typedef T holder_type; static constexpr holder_type const& hold (param_type p) { return p; } static constexpr reference ref (holder_type& r) { return r; } static constexpr const_reference ref (holder_type const& r) { return r; } static constexpr pointer ptr (holder_type& r) { return ruin::address_of(r); } static constexpr const_pointer ptr (holder_type const& r) { return ruin::address_of(r); } }; template < class T > struct helper<T&> { typedef T value_type; typedef T& reference; typedef T const& const_reference; typedef T* pointer; typedef T const* const_pointer; typedef T& param_type; typedef T* holder_type; static constexpr holder_type hold (param_type p) { return ruin::address_of(p); } static constexpr reference ref (holder_type r) { return *r; } static constexpr pointer ptr (holder_type r) { return r; } }; template < class T > struct helper<T const&> { typedef T value_type; typedef T const& reference; typedef T const& const_reference; typedef T const* pointer; typedef T const* const_pointer; typedef T const& param_type; typedef T const* holder_type; static constexpr holder_type hold (param_type p) { return ruin::address_of(p); } static constexpr reference ref (holder_type r) { return *r; } static constexpr pointer ptr (holder_type r) { return r; } }; }} // namespace detail::value_holder template < class T > class value_holder { public: typedef T type; private: typedef ruin::detail::value_holder::helper<type> helper_type; typedef typename helper_type::holder_type holder_type; public: typedef typename helper_type::value_type value_type; typedef typename helper_type::reference reference; typedef typename helper_type::const_reference const_reference; typedef typename helper_type::pointer pointer; typedef typename helper_type::const_pointer const_pointer; typedef typename helper_type::param_type param_type; private: holder_type holder_; public: value_holder () = default; explicit constexpr value_holder (param_type p) : holder_(helper_type::hold(p)) { } public: explicit operator reference () { return helper_type::ref(holder_); } explicit constexpr operator const_reference () const { return helper_type::ref(holder_); } reference get () { return helper_type::ref(holder_); } constexpr const_reference get () const { return helper_type::ref(holder_); } pointer get_ptr () { return helper_type::ptr(holder_); } constexpr const_pointer get_ptr () const { return helper_type::ptr(holder_); } void swap (value_holder& y) noexcept(noexcept(ruin::swap(value_holder::holder_, y.holder_))) { ruin::swap(holder_, y.holder_); } }; template < class T > void swap (ruin::value_holder<T>& x, ruin::value_holder<T>& y) noexcept(noexcept(x.swap(y))) { x.swap(y); } } #endif // RUIN_UTILITY_VALUE_HOLDER_HPP_INCLUDED
#include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <cstring> #include <string.h> #include <stdio.h> #include <cmath> #include <limits> #include <assert.h> #include <stdint.h> #include "il2cpp-class-internals.h" #include "codegen/il2cpp-codegen.h" #include "il2cpp-object-internals.h" // System.Byte[] struct ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821; // System.Char[] struct CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2; // System.Collections.ArrayList struct ArrayList_t4131E0C29C7E1B9BC9DFE37BEC41A5EB1481ADF4; // System.Collections.Generic.Dictionary`2<System.Int32,System.String> struct Dictionary_2_t4EFE6A1D6502662B911688316C6920444A18CF0C; // System.Collections.Generic.Dictionary`2<System.String,System.Int32> struct Dictionary_2_tD6E204872BA9FD506A0287EF68E285BEB9EC0DFB; // System.Collections.Generic.Dictionary`2<System.String,System.String> struct Dictionary_2_t931BF283048C4E74FC063C3036E5F3FE328861FC; // System.Collections.Generic.List`1<System.String> struct List_1_tE8032E48C661C350FF9550E9063D595C0AB25CD3; // System.Collections.Generic.List`1<System.Text.RegularExpressions.RegexCharClass/SingleRange> struct List_1_t560DEF47D3A9D65449EE74779102DDD3BF7B6724; // System.Collections.Generic.List`1<System.Text.RegularExpressions.RegexNode> struct List_1_tA5CDE89671B691180A7422F86077A0D047AD4059; // System.Collections.Generic.List`1<System.Text.RegularExpressions.RegexOptions> struct List_1_t85142A16ADC23C13E223599A626015FD40FF076A; // System.Collections.Hashtable struct Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9; // System.Collections.ICollection struct ICollection_tA3BAB2482E28132A7CA9E0E21393027353C28B54; // System.Collections.IDictionary struct IDictionary_t1BD5C1546718A374EA8122FBD6C6EE45331E8CE7; // System.ComponentModel.TypeConverter/StandardValuesCollection struct StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3; // System.Diagnostics.StackTrace[] struct StackTraceU5BU5D_t855F09649EA34DEE7C1B6F088E0538E3CCC3F196; // System.Globalization.CultureInfo struct CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F; // System.Int32[] struct Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83; // System.Int32[][] struct Int32U5BU5DU5BU5D_tCA34E042D233821D51B4DAFB480EE602F2DBEF43; // System.IntPtr[] struct IntPtrU5BU5D_t4DC01DCB9A6DF6C9792A6513595D7A11E637DCDD; // System.Net.EndPoint struct EndPoint_tD87FCEF2780A951E8CE8D808C345FBF2C088D980; // System.Runtime.Serialization.SafeSerializationManager struct SafeSerializationManager_t4A754D86B0F784B18CBC36C073BA564BED109770; // System.Security.Cryptography.AsnEncodedData struct AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65; // System.Security.Cryptography.Oid struct Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137; // System.Security.Cryptography.OidCollection struct OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E; // System.String struct String_t; // System.String[0...,0...] struct StringU5B0___U2C0___U5D_tE93164AE7893C771D8246C63F72E776F0207282B; // System.String[] struct StringU5BU5D_t933FB07893230EA91C40FF900D5400665E87B14E; // System.Text.RegularExpressions.Match struct Match_tE447871AB59EED3642F31EB9559D162C2977EBB5; // System.Text.RegularExpressions.Regex struct Regex_tFD46E63A462E852189FD6AB4E2B0B67C4D8FDBDF; // System.Text.RegularExpressions.RegexBoyerMoore struct RegexBoyerMoore_t37ED99A3CC25068E4D3DE4517835CFFCCF2FA1EB; // System.Text.RegularExpressions.RegexCharClass struct RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90; // System.Text.RegularExpressions.RegexCharClass/LowerCaseMapping[] struct LowerCaseMappingU5BU5D_t70011E1042888E1D071920A9171989A479C0618D; // System.Text.RegularExpressions.RegexCode struct RegexCode_t12846533CAD1E4221CEDF5A4D15D4D649EA688FA; // System.Text.RegularExpressions.RegexFC[] struct RegexFCU5BU5D_tCABE05C26F3229DFDD9C8A86F3BA828C18F02D72; // System.Text.RegularExpressions.RegexNode struct RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75; // System.Text.RegularExpressions.RegexPrefix struct RegexPrefix_tACADB52E91EFEB63B5EF7A1850634604F98FEE67; // System.Text.StringBuilder struct StringBuilder_t; // System.Type struct Type_t; // System.UInt16[] struct UInt16U5BU5D_t2D4BB1F8C486FF4359FFA7E4A76A8708A684543E; struct Exception_t_marshaled_com; struct Exception_t_marshaled_pinvoke; #ifndef U3CMODULEU3E_T239CA80C3AF3E763FA4B9A9F3CFADF0768B426EE_H #define U3CMODULEU3E_T239CA80C3AF3E763FA4B9A9F3CFADF0768B426EE_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <Module> struct U3CModuleU3E_t239CA80C3AF3E763FA4B9A9F3CFADF0768B426EE { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // U3CMODULEU3E_T239CA80C3AF3E763FA4B9A9F3CFADF0768B426EE_H #ifndef U3CMODULEU3E_T4F43141ACD9FFF670814886815EB7CDCD95E3951_H #define U3CMODULEU3E_T4F43141ACD9FFF670814886815EB7CDCD95E3951_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <Module> struct U3CModuleU3E_t4F43141ACD9FFF670814886815EB7CDCD95E3951 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // U3CMODULEU3E_T4F43141ACD9FFF670814886815EB7CDCD95E3951_H #ifndef RUNTIMEOBJECT_H #define RUNTIMEOBJECT_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Object #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RUNTIMEOBJECT_H #ifndef ASN1_T2B883D12D3493F8395B31D1F0ABD93F43948B27E_H #define ASN1_T2B883D12D3493F8395B31D1F0ABD93F43948B27E_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Mono.Security.ASN1 struct ASN1_t2B883D12D3493F8395B31D1F0ABD93F43948B27E : public RuntimeObject { public: // System.Byte Mono.Security.ASN1::m_nTag uint8_t ___m_nTag_0; // System.Byte[] Mono.Security.ASN1::m_aValue ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* ___m_aValue_1; // System.Collections.ArrayList Mono.Security.ASN1::elist ArrayList_t4131E0C29C7E1B9BC9DFE37BEC41A5EB1481ADF4 * ___elist_2; public: inline static int32_t get_offset_of_m_nTag_0() { return static_cast<int32_t>(offsetof(ASN1_t2B883D12D3493F8395B31D1F0ABD93F43948B27E, ___m_nTag_0)); } inline uint8_t get_m_nTag_0() const { return ___m_nTag_0; } inline uint8_t* get_address_of_m_nTag_0() { return &___m_nTag_0; } inline void set_m_nTag_0(uint8_t value) { ___m_nTag_0 = value; } inline static int32_t get_offset_of_m_aValue_1() { return static_cast<int32_t>(offsetof(ASN1_t2B883D12D3493F8395B31D1F0ABD93F43948B27E, ___m_aValue_1)); } inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* get_m_aValue_1() const { return ___m_aValue_1; } inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821** get_address_of_m_aValue_1() { return &___m_aValue_1; } inline void set_m_aValue_1(ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* value) { ___m_aValue_1 = value; Il2CppCodeGenWriteBarrier((&___m_aValue_1), value); } inline static int32_t get_offset_of_elist_2() { return static_cast<int32_t>(offsetof(ASN1_t2B883D12D3493F8395B31D1F0ABD93F43948B27E, ___elist_2)); } inline ArrayList_t4131E0C29C7E1B9BC9DFE37BEC41A5EB1481ADF4 * get_elist_2() const { return ___elist_2; } inline ArrayList_t4131E0C29C7E1B9BC9DFE37BEC41A5EB1481ADF4 ** get_address_of_elist_2() { return &___elist_2; } inline void set_elist_2(ArrayList_t4131E0C29C7E1B9BC9DFE37BEC41A5EB1481ADF4 * value) { ___elist_2 = value; Il2CppCodeGenWriteBarrier((&___elist_2), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ASN1_T2B883D12D3493F8395B31D1F0ABD93F43948B27E_H #ifndef ASN1CONVERT_T5F783CA2300717B94F27A342A75A0E57B73FCC05_H #define ASN1CONVERT_T5F783CA2300717B94F27A342A75A0E57B73FCC05_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Mono.Security.ASN1Convert struct ASN1Convert_t5F783CA2300717B94F27A342A75A0E57B73FCC05 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ASN1CONVERT_T5F783CA2300717B94F27A342A75A0E57B73FCC05_H #ifndef BITCONVERTERLE_T4CE9DF1164753ED72B6F4F33581C35FBCAEEC109_H #define BITCONVERTERLE_T4CE9DF1164753ED72B6F4F33581C35FBCAEEC109_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Mono.Security.BitConverterLE struct BitConverterLE_t4CE9DF1164753ED72B6F4F33581C35FBCAEEC109 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BITCONVERTERLE_T4CE9DF1164753ED72B6F4F33581C35FBCAEEC109_H #ifndef CRYPTOCONVERT_TF1F175C2F2C9E65FE7D5FBF0D434B964E4CAFF76_H #define CRYPTOCONVERT_TF1F175C2F2C9E65FE7D5FBF0D434B964E4CAFF76_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Mono.Security.Cryptography.CryptoConvert struct CryptoConvert_tF1F175C2F2C9E65FE7D5FBF0D434B964E4CAFF76 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CRYPTOCONVERT_TF1F175C2F2C9E65FE7D5FBF0D434B964E4CAFF76_H #ifndef ATTRIBUTE_TF048C13FB3C8CFCC53F82290E4A3F621089F9A74_H #define ATTRIBUTE_TF048C13FB3C8CFCC53F82290E4A3F621089F9A74_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Attribute struct Attribute_tF048C13FB3C8CFCC53F82290E4A3F621089F9A74 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ATTRIBUTE_TF048C13FB3C8CFCC53F82290E4A3F621089F9A74_H #ifndef STANDARDVALUESCOLLECTION_T929677712574EF02F5C4CF4C38E070841C20BDA3_H #define STANDARDVALUESCOLLECTION_T929677712574EF02F5C4CF4C38E070841C20BDA3_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ComponentModel.TypeConverter_StandardValuesCollection struct StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3 : public RuntimeObject { public: // System.Collections.ICollection System.ComponentModel.TypeConverter_StandardValuesCollection::values RuntimeObject* ___values_0; // System.Array System.ComponentModel.TypeConverter_StandardValuesCollection::valueArray RuntimeArray * ___valueArray_1; public: inline static int32_t get_offset_of_values_0() { return static_cast<int32_t>(offsetof(StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3, ___values_0)); } inline RuntimeObject* get_values_0() const { return ___values_0; } inline RuntimeObject** get_address_of_values_0() { return &___values_0; } inline void set_values_0(RuntimeObject* value) { ___values_0 = value; Il2CppCodeGenWriteBarrier((&___values_0), value); } inline static int32_t get_offset_of_valueArray_1() { return static_cast<int32_t>(offsetof(StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3, ___valueArray_1)); } inline RuntimeArray * get_valueArray_1() const { return ___valueArray_1; } inline RuntimeArray ** get_address_of_valueArray_1() { return &___valueArray_1; } inline void set_valueArray_1(RuntimeArray * value) { ___valueArray_1 = value; Il2CppCodeGenWriteBarrier((&___valueArray_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // STANDARDVALUESCOLLECTION_T929677712574EF02F5C4CF4C38E070841C20BDA3_H #ifndef CONFIGURATIONELEMENT_TF3ECE1CDFD3304CD9D595E758276F014321AD9FE_H #define CONFIGURATIONELEMENT_TF3ECE1CDFD3304CD9D595E758276F014321AD9FE_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Configuration.ConfigurationElement struct ConfigurationElement_tF3ECE1CDFD3304CD9D595E758276F014321AD9FE : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CONFIGURATIONELEMENT_TF3ECE1CDFD3304CD9D595E758276F014321AD9FE_H #ifndef CONFIGURATIONSECTIONGROUP_T64AC7C211E1F868ABF1BD604DA43815564D304E6_H #define CONFIGURATIONSECTIONGROUP_T64AC7C211E1F868ABF1BD604DA43815564D304E6_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Configuration.ConfigurationSectionGroup struct ConfigurationSectionGroup_t64AC7C211E1F868ABF1BD604DA43815564D304E6 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CONFIGURATIONSECTIONGROUP_T64AC7C211E1F868ABF1BD604DA43815564D304E6_H #ifndef DIAGNOSTICSCONFIGURATIONHANDLER_T885EAAD2DCF9678F16E3BB296E307868ECE68239_H #define DIAGNOSTICSCONFIGURATIONHANDLER_T885EAAD2DCF9678F16E3BB296E307868ECE68239_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Diagnostics.DiagnosticsConfigurationHandler struct DiagnosticsConfigurationHandler_t885EAAD2DCF9678F16E3BB296E307868ECE68239 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DIAGNOSTICSCONFIGURATIONHANDLER_T885EAAD2DCF9678F16E3BB296E307868ECE68239_H #ifndef EXCEPTION_T_H #define EXCEPTION_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Exception struct Exception_t : public RuntimeObject { public: // System.String System.Exception::_className String_t* ____className_1; // System.String System.Exception::_message String_t* ____message_2; // System.Collections.IDictionary System.Exception::_data RuntimeObject* ____data_3; // System.Exception System.Exception::_innerException Exception_t * ____innerException_4; // System.String System.Exception::_helpURL String_t* ____helpURL_5; // System.Object System.Exception::_stackTrace RuntimeObject * ____stackTrace_6; // System.String System.Exception::_stackTraceString String_t* ____stackTraceString_7; // System.String System.Exception::_remoteStackTraceString String_t* ____remoteStackTraceString_8; // System.Int32 System.Exception::_remoteStackIndex int32_t ____remoteStackIndex_9; // System.Object System.Exception::_dynamicMethods RuntimeObject * ____dynamicMethods_10; // System.Int32 System.Exception::_HResult int32_t ____HResult_11; // System.String System.Exception::_source String_t* ____source_12; // System.Runtime.Serialization.SafeSerializationManager System.Exception::_safeSerializationManager SafeSerializationManager_t4A754D86B0F784B18CBC36C073BA564BED109770 * ____safeSerializationManager_13; // System.Diagnostics.StackTrace[] System.Exception::captured_traces StackTraceU5BU5D_t855F09649EA34DEE7C1B6F088E0538E3CCC3F196* ___captured_traces_14; // System.IntPtr[] System.Exception::native_trace_ips IntPtrU5BU5D_t4DC01DCB9A6DF6C9792A6513595D7A11E637DCDD* ___native_trace_ips_15; public: inline static int32_t get_offset_of__className_1() { return static_cast<int32_t>(offsetof(Exception_t, ____className_1)); } inline String_t* get__className_1() const { return ____className_1; } inline String_t** get_address_of__className_1() { return &____className_1; } inline void set__className_1(String_t* value) { ____className_1 = value; Il2CppCodeGenWriteBarrier((&____className_1), value); } inline static int32_t get_offset_of__message_2() { return static_cast<int32_t>(offsetof(Exception_t, ____message_2)); } inline String_t* get__message_2() const { return ____message_2; } inline String_t** get_address_of__message_2() { return &____message_2; } inline void set__message_2(String_t* value) { ____message_2 = value; Il2CppCodeGenWriteBarrier((&____message_2), value); } inline static int32_t get_offset_of__data_3() { return static_cast<int32_t>(offsetof(Exception_t, ____data_3)); } inline RuntimeObject* get__data_3() const { return ____data_3; } inline RuntimeObject** get_address_of__data_3() { return &____data_3; } inline void set__data_3(RuntimeObject* value) { ____data_3 = value; Il2CppCodeGenWriteBarrier((&____data_3), value); } inline static int32_t get_offset_of__innerException_4() { return static_cast<int32_t>(offsetof(Exception_t, ____innerException_4)); } inline Exception_t * get__innerException_4() const { return ____innerException_4; } inline Exception_t ** get_address_of__innerException_4() { return &____innerException_4; } inline void set__innerException_4(Exception_t * value) { ____innerException_4 = value; Il2CppCodeGenWriteBarrier((&____innerException_4), value); } inline static int32_t get_offset_of__helpURL_5() { return static_cast<int32_t>(offsetof(Exception_t, ____helpURL_5)); } inline String_t* get__helpURL_5() const { return ____helpURL_5; } inline String_t** get_address_of__helpURL_5() { return &____helpURL_5; } inline void set__helpURL_5(String_t* value) { ____helpURL_5 = value; Il2CppCodeGenWriteBarrier((&____helpURL_5), value); } inline static int32_t get_offset_of__stackTrace_6() { return static_cast<int32_t>(offsetof(Exception_t, ____stackTrace_6)); } inline RuntimeObject * get__stackTrace_6() const { return ____stackTrace_6; } inline RuntimeObject ** get_address_of__stackTrace_6() { return &____stackTrace_6; } inline void set__stackTrace_6(RuntimeObject * value) { ____stackTrace_6 = value; Il2CppCodeGenWriteBarrier((&____stackTrace_6), value); } inline static int32_t get_offset_of__stackTraceString_7() { return static_cast<int32_t>(offsetof(Exception_t, ____stackTraceString_7)); } inline String_t* get__stackTraceString_7() const { return ____stackTraceString_7; } inline String_t** get_address_of__stackTraceString_7() { return &____stackTraceString_7; } inline void set__stackTraceString_7(String_t* value) { ____stackTraceString_7 = value; Il2CppCodeGenWriteBarrier((&____stackTraceString_7), value); } inline static int32_t get_offset_of__remoteStackTraceString_8() { return static_cast<int32_t>(offsetof(Exception_t, ____remoteStackTraceString_8)); } inline String_t* get__remoteStackTraceString_8() const { return ____remoteStackTraceString_8; } inline String_t** get_address_of__remoteStackTraceString_8() { return &____remoteStackTraceString_8; } inline void set__remoteStackTraceString_8(String_t* value) { ____remoteStackTraceString_8 = value; Il2CppCodeGenWriteBarrier((&____remoteStackTraceString_8), value); } inline static int32_t get_offset_of__remoteStackIndex_9() { return static_cast<int32_t>(offsetof(Exception_t, ____remoteStackIndex_9)); } inline int32_t get__remoteStackIndex_9() const { return ____remoteStackIndex_9; } inline int32_t* get_address_of__remoteStackIndex_9() { return &____remoteStackIndex_9; } inline void set__remoteStackIndex_9(int32_t value) { ____remoteStackIndex_9 = value; } inline static int32_t get_offset_of__dynamicMethods_10() { return static_cast<int32_t>(offsetof(Exception_t, ____dynamicMethods_10)); } inline RuntimeObject * get__dynamicMethods_10() const { return ____dynamicMethods_10; } inline RuntimeObject ** get_address_of__dynamicMethods_10() { return &____dynamicMethods_10; } inline void set__dynamicMethods_10(RuntimeObject * value) { ____dynamicMethods_10 = value; Il2CppCodeGenWriteBarrier((&____dynamicMethods_10), value); } inline static int32_t get_offset_of__HResult_11() { return static_cast<int32_t>(offsetof(Exception_t, ____HResult_11)); } inline int32_t get__HResult_11() const { return ____HResult_11; } inline int32_t* get_address_of__HResult_11() { return &____HResult_11; } inline void set__HResult_11(int32_t value) { ____HResult_11 = value; } inline static int32_t get_offset_of__source_12() { return static_cast<int32_t>(offsetof(Exception_t, ____source_12)); } inline String_t* get__source_12() const { return ____source_12; } inline String_t** get_address_of__source_12() { return &____source_12; } inline void set__source_12(String_t* value) { ____source_12 = value; Il2CppCodeGenWriteBarrier((&____source_12), value); } inline static int32_t get_offset_of__safeSerializationManager_13() { return static_cast<int32_t>(offsetof(Exception_t, ____safeSerializationManager_13)); } inline SafeSerializationManager_t4A754D86B0F784B18CBC36C073BA564BED109770 * get__safeSerializationManager_13() const { return ____safeSerializationManager_13; } inline SafeSerializationManager_t4A754D86B0F784B18CBC36C073BA564BED109770 ** get_address_of__safeSerializationManager_13() { return &____safeSerializationManager_13; } inline void set__safeSerializationManager_13(SafeSerializationManager_t4A754D86B0F784B18CBC36C073BA564BED109770 * value) { ____safeSerializationManager_13 = value; Il2CppCodeGenWriteBarrier((&____safeSerializationManager_13), value); } inline static int32_t get_offset_of_captured_traces_14() { return static_cast<int32_t>(offsetof(Exception_t, ___captured_traces_14)); } inline StackTraceU5BU5D_t855F09649EA34DEE7C1B6F088E0538E3CCC3F196* get_captured_traces_14() const { return ___captured_traces_14; } inline StackTraceU5BU5D_t855F09649EA34DEE7C1B6F088E0538E3CCC3F196** get_address_of_captured_traces_14() { return &___captured_traces_14; } inline void set_captured_traces_14(StackTraceU5BU5D_t855F09649EA34DEE7C1B6F088E0538E3CCC3F196* value) { ___captured_traces_14 = value; Il2CppCodeGenWriteBarrier((&___captured_traces_14), value); } inline static int32_t get_offset_of_native_trace_ips_15() { return static_cast<int32_t>(offsetof(Exception_t, ___native_trace_ips_15)); } inline IntPtrU5BU5D_t4DC01DCB9A6DF6C9792A6513595D7A11E637DCDD* get_native_trace_ips_15() const { return ___native_trace_ips_15; } inline IntPtrU5BU5D_t4DC01DCB9A6DF6C9792A6513595D7A11E637DCDD** get_address_of_native_trace_ips_15() { return &___native_trace_ips_15; } inline void set_native_trace_ips_15(IntPtrU5BU5D_t4DC01DCB9A6DF6C9792A6513595D7A11E637DCDD* value) { ___native_trace_ips_15 = value; Il2CppCodeGenWriteBarrier((&___native_trace_ips_15), value); } }; struct Exception_t_StaticFields { public: // System.Object System.Exception::s_EDILock RuntimeObject * ___s_EDILock_0; public: inline static int32_t get_offset_of_s_EDILock_0() { return static_cast<int32_t>(offsetof(Exception_t_StaticFields, ___s_EDILock_0)); } inline RuntimeObject * get_s_EDILock_0() const { return ___s_EDILock_0; } inline RuntimeObject ** get_address_of_s_EDILock_0() { return &___s_EDILock_0; } inline void set_s_EDILock_0(RuntimeObject * value) { ___s_EDILock_0 = value; Il2CppCodeGenWriteBarrier((&___s_EDILock_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Exception struct Exception_t_marshaled_pinvoke { char* ____className_1; char* ____message_2; RuntimeObject* ____data_3; Exception_t_marshaled_pinvoke* ____innerException_4; char* ____helpURL_5; Il2CppIUnknown* ____stackTrace_6; char* ____stackTraceString_7; char* ____remoteStackTraceString_8; int32_t ____remoteStackIndex_9; Il2CppIUnknown* ____dynamicMethods_10; int32_t ____HResult_11; char* ____source_12; SafeSerializationManager_t4A754D86B0F784B18CBC36C073BA564BED109770 * ____safeSerializationManager_13; StackTraceU5BU5D_t855F09649EA34DEE7C1B6F088E0538E3CCC3F196* ___captured_traces_14; intptr_t* ___native_trace_ips_15; }; // Native definition for COM marshalling of System.Exception struct Exception_t_marshaled_com { Il2CppChar* ____className_1; Il2CppChar* ____message_2; RuntimeObject* ____data_3; Exception_t_marshaled_com* ____innerException_4; Il2CppChar* ____helpURL_5; Il2CppIUnknown* ____stackTrace_6; Il2CppChar* ____stackTraceString_7; Il2CppChar* ____remoteStackTraceString_8; int32_t ____remoteStackIndex_9; Il2CppIUnknown* ____dynamicMethods_10; int32_t ____HResult_11; Il2CppChar* ____source_12; SafeSerializationManager_t4A754D86B0F784B18CBC36C073BA564BED109770 * ____safeSerializationManager_13; StackTraceU5BU5D_t855F09649EA34DEE7C1B6F088E0538E3CCC3F196* ___captured_traces_14; intptr_t* ___native_trace_ips_15; }; #endif // EXCEPTION_T_H #ifndef ENDPOINT_TD87FCEF2780A951E8CE8D808C345FBF2C088D980_H #define ENDPOINT_TD87FCEF2780A951E8CE8D808C345FBF2C088D980_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Net.EndPoint struct EndPoint_tD87FCEF2780A951E8CE8D808C345FBF2C088D980 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ENDPOINT_TD87FCEF2780A951E8CE8D808C345FBF2C088D980_H #ifndef ASNENCODEDDATA_T7D5EF5337DCAF507CAD7D750552C943F037A9D65_H #define ASNENCODEDDATA_T7D5EF5337DCAF507CAD7D750552C943F037A9D65_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Security.Cryptography.AsnEncodedData struct AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65 : public RuntimeObject { public: // System.Security.Cryptography.Oid System.Security.Cryptography.AsnEncodedData::_oid Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137 * ____oid_0; // System.Byte[] System.Security.Cryptography.AsnEncodedData::_raw ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* ____raw_1; public: inline static int32_t get_offset_of__oid_0() { return static_cast<int32_t>(offsetof(AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65, ____oid_0)); } inline Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137 * get__oid_0() const { return ____oid_0; } inline Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137 ** get_address_of__oid_0() { return &____oid_0; } inline void set__oid_0(Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137 * value) { ____oid_0 = value; Il2CppCodeGenWriteBarrier((&____oid_0), value); } inline static int32_t get_offset_of__raw_1() { return static_cast<int32_t>(offsetof(AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65, ____raw_1)); } inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* get__raw_1() const { return ____raw_1; } inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821** get_address_of__raw_1() { return &____raw_1; } inline void set__raw_1(ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* value) { ____raw_1 = value; Il2CppCodeGenWriteBarrier((&____raw_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ASNENCODEDDATA_T7D5EF5337DCAF507CAD7D750552C943F037A9D65_H #ifndef CAPI_TEA68010AC3470FFEBC91FC9D3C13E7D7064C3267_H #define CAPI_TEA68010AC3470FFEBC91FC9D3C13E7D7064C3267_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Security.Cryptography.CAPI struct CAPI_tEA68010AC3470FFEBC91FC9D3C13E7D7064C3267 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CAPI_TEA68010AC3470FFEBC91FC9D3C13E7D7064C3267_H #ifndef OIDCOLLECTION_TEB423F1150E53DCF513BF5A699F911586A31B94E_H #define OIDCOLLECTION_TEB423F1150E53DCF513BF5A699F911586A31B94E_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Security.Cryptography.OidCollection struct OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E : public RuntimeObject { public: // System.Collections.ArrayList System.Security.Cryptography.OidCollection::m_list ArrayList_t4131E0C29C7E1B9BC9DFE37BEC41A5EB1481ADF4 * ___m_list_0; public: inline static int32_t get_offset_of_m_list_0() { return static_cast<int32_t>(offsetof(OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E, ___m_list_0)); } inline ArrayList_t4131E0C29C7E1B9BC9DFE37BEC41A5EB1481ADF4 * get_m_list_0() const { return ___m_list_0; } inline ArrayList_t4131E0C29C7E1B9BC9DFE37BEC41A5EB1481ADF4 ** get_address_of_m_list_0() { return &___m_list_0; } inline void set_m_list_0(ArrayList_t4131E0C29C7E1B9BC9DFE37BEC41A5EB1481ADF4 * value) { ___m_list_0 = value; Il2CppCodeGenWriteBarrier((&___m_list_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // OIDCOLLECTION_TEB423F1150E53DCF513BF5A699F911586A31B94E_H #ifndef OIDENUMERATOR_TC2DB288576C575B69F7934274DDD8A5868CEF97C_H #define OIDENUMERATOR_TC2DB288576C575B69F7934274DDD8A5868CEF97C_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Security.Cryptography.OidEnumerator struct OidEnumerator_tC2DB288576C575B69F7934274DDD8A5868CEF97C : public RuntimeObject { public: // System.Security.Cryptography.OidCollection System.Security.Cryptography.OidEnumerator::m_oids OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E * ___m_oids_0; // System.Int32 System.Security.Cryptography.OidEnumerator::m_current int32_t ___m_current_1; public: inline static int32_t get_offset_of_m_oids_0() { return static_cast<int32_t>(offsetof(OidEnumerator_tC2DB288576C575B69F7934274DDD8A5868CEF97C, ___m_oids_0)); } inline OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E * get_m_oids_0() const { return ___m_oids_0; } inline OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E ** get_address_of_m_oids_0() { return &___m_oids_0; } inline void set_m_oids_0(OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E * value) { ___m_oids_0 = value; Il2CppCodeGenWriteBarrier((&___m_oids_0), value); } inline static int32_t get_offset_of_m_current_1() { return static_cast<int32_t>(offsetof(OidEnumerator_tC2DB288576C575B69F7934274DDD8A5868CEF97C, ___m_current_1)); } inline int32_t get_m_current_1() const { return ___m_current_1; } inline int32_t* get_address_of_m_current_1() { return &___m_current_1; } inline void set_m_current_1(int32_t value) { ___m_current_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // OIDENUMERATOR_TC2DB288576C575B69F7934274DDD8A5868CEF97C_H #ifndef PUBLICKEY_TBA8234EB603A903FCBBBE67D8247393D4CC8D620_H #define PUBLICKEY_TBA8234EB603A903FCBBBE67D8247393D4CC8D620_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Security.Cryptography.X509Certificates.PublicKey struct PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620 : public RuntimeObject { public: // System.Security.Cryptography.AsnEncodedData System.Security.Cryptography.X509Certificates.PublicKey::_keyValue AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65 * ____keyValue_0; // System.Security.Cryptography.AsnEncodedData System.Security.Cryptography.X509Certificates.PublicKey::_params AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65 * ____params_1; // System.Security.Cryptography.Oid System.Security.Cryptography.X509Certificates.PublicKey::_oid Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137 * ____oid_2; public: inline static int32_t get_offset_of__keyValue_0() { return static_cast<int32_t>(offsetof(PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620, ____keyValue_0)); } inline AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65 * get__keyValue_0() const { return ____keyValue_0; } inline AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65 ** get_address_of__keyValue_0() { return &____keyValue_0; } inline void set__keyValue_0(AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65 * value) { ____keyValue_0 = value; Il2CppCodeGenWriteBarrier((&____keyValue_0), value); } inline static int32_t get_offset_of__params_1() { return static_cast<int32_t>(offsetof(PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620, ____params_1)); } inline AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65 * get__params_1() const { return ____params_1; } inline AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65 ** get_address_of__params_1() { return &____params_1; } inline void set__params_1(AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65 * value) { ____params_1 = value; Il2CppCodeGenWriteBarrier((&____params_1), value); } inline static int32_t get_offset_of__oid_2() { return static_cast<int32_t>(offsetof(PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620, ____oid_2)); } inline Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137 * get__oid_2() const { return ____oid_2; } inline Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137 ** get_address_of__oid_2() { return &____oid_2; } inline void set__oid_2(Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137 * value) { ____oid_2 = value; Il2CppCodeGenWriteBarrier((&____oid_2), value); } }; struct PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620_StaticFields { public: // System.Byte[] System.Security.Cryptography.X509Certificates.PublicKey::Empty ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* ___Empty_3; public: inline static int32_t get_offset_of_Empty_3() { return static_cast<int32_t>(offsetof(PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620_StaticFields, ___Empty_3)); } inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* get_Empty_3() const { return ___Empty_3; } inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821** get_address_of_Empty_3() { return &___Empty_3; } inline void set_Empty_3(ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* value) { ___Empty_3 = value; Il2CppCodeGenWriteBarrier((&___Empty_3), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // PUBLICKEY_TBA8234EB603A903FCBBBE67D8247393D4CC8D620_H #ifndef X509UTILS_T596E1974703C7988010495E60F15BE9680FC71B8_H #define X509UTILS_T596E1974703C7988010495E60F15BE9680FC71B8_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Security.Cryptography.X509Certificates.X509Utils struct X509Utils_t596E1974703C7988010495E60F15BE9680FC71B8 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // X509UTILS_T596E1974703C7988010495E60F15BE9680FC71B8_H #ifndef CAPTURE_TF4475248CCF3EFF914844BE2C993FC609D41DB73_H #define CAPTURE_TF4475248CCF3EFF914844BE2C993FC609D41DB73_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Text.RegularExpressions.Capture struct Capture_tF4475248CCF3EFF914844BE2C993FC609D41DB73 : public RuntimeObject { public: // System.String System.Text.RegularExpressions.Capture::_text String_t* ____text_0; // System.Int32 System.Text.RegularExpressions.Capture::_index int32_t ____index_1; // System.Int32 System.Text.RegularExpressions.Capture::_length int32_t ____length_2; public: inline static int32_t get_offset_of__text_0() { return static_cast<int32_t>(offsetof(Capture_tF4475248CCF3EFF914844BE2C993FC609D41DB73, ____text_0)); } inline String_t* get__text_0() const { return ____text_0; } inline String_t** get_address_of__text_0() { return &____text_0; } inline void set__text_0(String_t* value) { ____text_0 = value; Il2CppCodeGenWriteBarrier((&____text_0), value); } inline static int32_t get_offset_of__index_1() { return static_cast<int32_t>(offsetof(Capture_tF4475248CCF3EFF914844BE2C993FC609D41DB73, ____index_1)); } inline int32_t get__index_1() const { return ____index_1; } inline int32_t* get_address_of__index_1() { return &____index_1; } inline void set__index_1(int32_t value) { ____index_1 = value; } inline static int32_t get_offset_of__length_2() { return static_cast<int32_t>(offsetof(Capture_tF4475248CCF3EFF914844BE2C993FC609D41DB73, ____length_2)); } inline int32_t get__length_2() const { return ____length_2; } inline int32_t* get_address_of__length_2() { return &____length_2; } inline void set__length_2(int32_t value) { ____length_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CAPTURE_TF4475248CCF3EFF914844BE2C993FC609D41DB73_H #ifndef REGEXCHARCLASS_T56409AACB9ADE95FA5333FC5D94FAADAF564AE90_H #define REGEXCHARCLASS_T56409AACB9ADE95FA5333FC5D94FAADAF564AE90_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Text.RegularExpressions.RegexCharClass struct RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90 : public RuntimeObject { public: // System.Collections.Generic.List`1<System.Text.RegularExpressions.RegexCharClass_SingleRange> System.Text.RegularExpressions.RegexCharClass::_rangelist List_1_t560DEF47D3A9D65449EE74779102DDD3BF7B6724 * ____rangelist_0; // System.Text.StringBuilder System.Text.RegularExpressions.RegexCharClass::_categories StringBuilder_t * ____categories_1; // System.Boolean System.Text.RegularExpressions.RegexCharClass::_canonical bool ____canonical_2; // System.Boolean System.Text.RegularExpressions.RegexCharClass::_negate bool ____negate_3; // System.Text.RegularExpressions.RegexCharClass System.Text.RegularExpressions.RegexCharClass::_subtractor RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90 * ____subtractor_4; public: inline static int32_t get_offset_of__rangelist_0() { return static_cast<int32_t>(offsetof(RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90, ____rangelist_0)); } inline List_1_t560DEF47D3A9D65449EE74779102DDD3BF7B6724 * get__rangelist_0() const { return ____rangelist_0; } inline List_1_t560DEF47D3A9D65449EE74779102DDD3BF7B6724 ** get_address_of__rangelist_0() { return &____rangelist_0; } inline void set__rangelist_0(List_1_t560DEF47D3A9D65449EE74779102DDD3BF7B6724 * value) { ____rangelist_0 = value; Il2CppCodeGenWriteBarrier((&____rangelist_0), value); } inline static int32_t get_offset_of__categories_1() { return static_cast<int32_t>(offsetof(RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90, ____categories_1)); } inline StringBuilder_t * get__categories_1() const { return ____categories_1; } inline StringBuilder_t ** get_address_of__categories_1() { return &____categories_1; } inline void set__categories_1(StringBuilder_t * value) { ____categories_1 = value; Il2CppCodeGenWriteBarrier((&____categories_1), value); } inline static int32_t get_offset_of__canonical_2() { return static_cast<int32_t>(offsetof(RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90, ____canonical_2)); } inline bool get__canonical_2() const { return ____canonical_2; } inline bool* get_address_of__canonical_2() { return &____canonical_2; } inline void set__canonical_2(bool value) { ____canonical_2 = value; } inline static int32_t get_offset_of__negate_3() { return static_cast<int32_t>(offsetof(RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90, ____negate_3)); } inline bool get__negate_3() const { return ____negate_3; } inline bool* get_address_of__negate_3() { return &____negate_3; } inline void set__negate_3(bool value) { ____negate_3 = value; } inline static int32_t get_offset_of__subtractor_4() { return static_cast<int32_t>(offsetof(RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90, ____subtractor_4)); } inline RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90 * get__subtractor_4() const { return ____subtractor_4; } inline RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90 ** get_address_of__subtractor_4() { return &____subtractor_4; } inline void set__subtractor_4(RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90 * value) { ____subtractor_4 = value; Il2CppCodeGenWriteBarrier((&____subtractor_4), value); } }; struct RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields { public: // System.String System.Text.RegularExpressions.RegexCharClass::InternalRegexIgnoreCase String_t* ___InternalRegexIgnoreCase_5; // System.String System.Text.RegularExpressions.RegexCharClass::Space String_t* ___Space_6; // System.String System.Text.RegularExpressions.RegexCharClass::NotSpace String_t* ___NotSpace_7; // System.String System.Text.RegularExpressions.RegexCharClass::Word String_t* ___Word_8; // System.String System.Text.RegularExpressions.RegexCharClass::NotWord String_t* ___NotWord_9; // System.String System.Text.RegularExpressions.RegexCharClass::SpaceClass String_t* ___SpaceClass_10; // System.String System.Text.RegularExpressions.RegexCharClass::NotSpaceClass String_t* ___NotSpaceClass_11; // System.String System.Text.RegularExpressions.RegexCharClass::WordClass String_t* ___WordClass_12; // System.String System.Text.RegularExpressions.RegexCharClass::NotWordClass String_t* ___NotWordClass_13; // System.String System.Text.RegularExpressions.RegexCharClass::DigitClass String_t* ___DigitClass_14; // System.String System.Text.RegularExpressions.RegexCharClass::NotDigitClass String_t* ___NotDigitClass_15; // System.Collections.Generic.Dictionary`2<System.String,System.String> System.Text.RegularExpressions.RegexCharClass::_definedCategories Dictionary_2_t931BF283048C4E74FC063C3036E5F3FE328861FC * ____definedCategories_16; // System.String[0...,0...] System.Text.RegularExpressions.RegexCharClass::_propTable StringU5B0___U2C0___U5D_tE93164AE7893C771D8246C63F72E776F0207282B* ____propTable_17; // System.Text.RegularExpressions.RegexCharClass_LowerCaseMapping[] System.Text.RegularExpressions.RegexCharClass::_lcTable LowerCaseMappingU5BU5D_t70011E1042888E1D071920A9171989A479C0618D* ____lcTable_18; public: inline static int32_t get_offset_of_InternalRegexIgnoreCase_5() { return static_cast<int32_t>(offsetof(RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields, ___InternalRegexIgnoreCase_5)); } inline String_t* get_InternalRegexIgnoreCase_5() const { return ___InternalRegexIgnoreCase_5; } inline String_t** get_address_of_InternalRegexIgnoreCase_5() { return &___InternalRegexIgnoreCase_5; } inline void set_InternalRegexIgnoreCase_5(String_t* value) { ___InternalRegexIgnoreCase_5 = value; Il2CppCodeGenWriteBarrier((&___InternalRegexIgnoreCase_5), value); } inline static int32_t get_offset_of_Space_6() { return static_cast<int32_t>(offsetof(RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields, ___Space_6)); } inline String_t* get_Space_6() const { return ___Space_6; } inline String_t** get_address_of_Space_6() { return &___Space_6; } inline void set_Space_6(String_t* value) { ___Space_6 = value; Il2CppCodeGenWriteBarrier((&___Space_6), value); } inline static int32_t get_offset_of_NotSpace_7() { return static_cast<int32_t>(offsetof(RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields, ___NotSpace_7)); } inline String_t* get_NotSpace_7() const { return ___NotSpace_7; } inline String_t** get_address_of_NotSpace_7() { return &___NotSpace_7; } inline void set_NotSpace_7(String_t* value) { ___NotSpace_7 = value; Il2CppCodeGenWriteBarrier((&___NotSpace_7), value); } inline static int32_t get_offset_of_Word_8() { return static_cast<int32_t>(offsetof(RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields, ___Word_8)); } inline String_t* get_Word_8() const { return ___Word_8; } inline String_t** get_address_of_Word_8() { return &___Word_8; } inline void set_Word_8(String_t* value) { ___Word_8 = value; Il2CppCodeGenWriteBarrier((&___Word_8), value); } inline static int32_t get_offset_of_NotWord_9() { return static_cast<int32_t>(offsetof(RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields, ___NotWord_9)); } inline String_t* get_NotWord_9() const { return ___NotWord_9; } inline String_t** get_address_of_NotWord_9() { return &___NotWord_9; } inline void set_NotWord_9(String_t* value) { ___NotWord_9 = value; Il2CppCodeGenWriteBarrier((&___NotWord_9), value); } inline static int32_t get_offset_of_SpaceClass_10() { return static_cast<int32_t>(offsetof(RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields, ___SpaceClass_10)); } inline String_t* get_SpaceClass_10() const { return ___SpaceClass_10; } inline String_t** get_address_of_SpaceClass_10() { return &___SpaceClass_10; } inline void set_SpaceClass_10(String_t* value) { ___SpaceClass_10 = value; Il2CppCodeGenWriteBarrier((&___SpaceClass_10), value); } inline static int32_t get_offset_of_NotSpaceClass_11() { return static_cast<int32_t>(offsetof(RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields, ___NotSpaceClass_11)); } inline String_t* get_NotSpaceClass_11() const { return ___NotSpaceClass_11; } inline String_t** get_address_of_NotSpaceClass_11() { return &___NotSpaceClass_11; } inline void set_NotSpaceClass_11(String_t* value) { ___NotSpaceClass_11 = value; Il2CppCodeGenWriteBarrier((&___NotSpaceClass_11), value); } inline static int32_t get_offset_of_WordClass_12() { return static_cast<int32_t>(offsetof(RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields, ___WordClass_12)); } inline String_t* get_WordClass_12() const { return ___WordClass_12; } inline String_t** get_address_of_WordClass_12() { return &___WordClass_12; } inline void set_WordClass_12(String_t* value) { ___WordClass_12 = value; Il2CppCodeGenWriteBarrier((&___WordClass_12), value); } inline static int32_t get_offset_of_NotWordClass_13() { return static_cast<int32_t>(offsetof(RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields, ___NotWordClass_13)); } inline String_t* get_NotWordClass_13() const { return ___NotWordClass_13; } inline String_t** get_address_of_NotWordClass_13() { return &___NotWordClass_13; } inline void set_NotWordClass_13(String_t* value) { ___NotWordClass_13 = value; Il2CppCodeGenWriteBarrier((&___NotWordClass_13), value); } inline static int32_t get_offset_of_DigitClass_14() { return static_cast<int32_t>(offsetof(RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields, ___DigitClass_14)); } inline String_t* get_DigitClass_14() const { return ___DigitClass_14; } inline String_t** get_address_of_DigitClass_14() { return &___DigitClass_14; } inline void set_DigitClass_14(String_t* value) { ___DigitClass_14 = value; Il2CppCodeGenWriteBarrier((&___DigitClass_14), value); } inline static int32_t get_offset_of_NotDigitClass_15() { return static_cast<int32_t>(offsetof(RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields, ___NotDigitClass_15)); } inline String_t* get_NotDigitClass_15() const { return ___NotDigitClass_15; } inline String_t** get_address_of_NotDigitClass_15() { return &___NotDigitClass_15; } inline void set_NotDigitClass_15(String_t* value) { ___NotDigitClass_15 = value; Il2CppCodeGenWriteBarrier((&___NotDigitClass_15), value); } inline static int32_t get_offset_of__definedCategories_16() { return static_cast<int32_t>(offsetof(RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields, ____definedCategories_16)); } inline Dictionary_2_t931BF283048C4E74FC063C3036E5F3FE328861FC * get__definedCategories_16() const { return ____definedCategories_16; } inline Dictionary_2_t931BF283048C4E74FC063C3036E5F3FE328861FC ** get_address_of__definedCategories_16() { return &____definedCategories_16; } inline void set__definedCategories_16(Dictionary_2_t931BF283048C4E74FC063C3036E5F3FE328861FC * value) { ____definedCategories_16 = value; Il2CppCodeGenWriteBarrier((&____definedCategories_16), value); } inline static int32_t get_offset_of__propTable_17() { return static_cast<int32_t>(offsetof(RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields, ____propTable_17)); } inline StringU5B0___U2C0___U5D_tE93164AE7893C771D8246C63F72E776F0207282B* get__propTable_17() const { return ____propTable_17; } inline StringU5B0___U2C0___U5D_tE93164AE7893C771D8246C63F72E776F0207282B** get_address_of__propTable_17() { return &____propTable_17; } inline void set__propTable_17(StringU5B0___U2C0___U5D_tE93164AE7893C771D8246C63F72E776F0207282B* value) { ____propTable_17 = value; Il2CppCodeGenWriteBarrier((&____propTable_17), value); } inline static int32_t get_offset_of__lcTable_18() { return static_cast<int32_t>(offsetof(RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields, ____lcTable_18)); } inline LowerCaseMappingU5BU5D_t70011E1042888E1D071920A9171989A479C0618D* get__lcTable_18() const { return ____lcTable_18; } inline LowerCaseMappingU5BU5D_t70011E1042888E1D071920A9171989A479C0618D** get_address_of__lcTable_18() { return &____lcTable_18; } inline void set__lcTable_18(LowerCaseMappingU5BU5D_t70011E1042888E1D071920A9171989A479C0618D* value) { ____lcTable_18 = value; Il2CppCodeGenWriteBarrier((&____lcTable_18), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // REGEXCHARCLASS_T56409AACB9ADE95FA5333FC5D94FAADAF564AE90_H #ifndef SINGLERANGE_T7B8E395E75FA456AB2834933C1ECA2007EEADEE0_H #define SINGLERANGE_T7B8E395E75FA456AB2834933C1ECA2007EEADEE0_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Text.RegularExpressions.RegexCharClass_SingleRange struct SingleRange_t7B8E395E75FA456AB2834933C1ECA2007EEADEE0 : public RuntimeObject { public: // System.Char System.Text.RegularExpressions.RegexCharClass_SingleRange::_first Il2CppChar ____first_0; // System.Char System.Text.RegularExpressions.RegexCharClass_SingleRange::_last Il2CppChar ____last_1; public: inline static int32_t get_offset_of__first_0() { return static_cast<int32_t>(offsetof(SingleRange_t7B8E395E75FA456AB2834933C1ECA2007EEADEE0, ____first_0)); } inline Il2CppChar get__first_0() const { return ____first_0; } inline Il2CppChar* get_address_of__first_0() { return &____first_0; } inline void set__first_0(Il2CppChar value) { ____first_0 = value; } inline static int32_t get_offset_of__last_1() { return static_cast<int32_t>(offsetof(SingleRange_t7B8E395E75FA456AB2834933C1ECA2007EEADEE0, ____last_1)); } inline Il2CppChar get__last_1() const { return ____last_1; } inline Il2CppChar* get_address_of__last_1() { return &____last_1; } inline void set__last_1(Il2CppChar value) { ____last_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SINGLERANGE_T7B8E395E75FA456AB2834933C1ECA2007EEADEE0_H #ifndef SINGLERANGECOMPARER_T6E5EF09D774335DD82A76997728AB97761B5984C_H #define SINGLERANGECOMPARER_T6E5EF09D774335DD82A76997728AB97761B5984C_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Text.RegularExpressions.RegexCharClass_SingleRangeComparer struct SingleRangeComparer_t6E5EF09D774335DD82A76997728AB97761B5984C : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SINGLERANGECOMPARER_T6E5EF09D774335DD82A76997728AB97761B5984C_H #ifndef REGEXCODE_T12846533CAD1E4221CEDF5A4D15D4D649EA688FA_H #define REGEXCODE_T12846533CAD1E4221CEDF5A4D15D4D649EA688FA_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Text.RegularExpressions.RegexCode struct RegexCode_t12846533CAD1E4221CEDF5A4D15D4D649EA688FA : public RuntimeObject { public: // System.Int32[] System.Text.RegularExpressions.RegexCode::_codes Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* ____codes_0; // System.String[] System.Text.RegularExpressions.RegexCode::_strings StringU5BU5D_t933FB07893230EA91C40FF900D5400665E87B14E* ____strings_1; // System.Int32 System.Text.RegularExpressions.RegexCode::_trackcount int32_t ____trackcount_2; // System.Collections.Hashtable System.Text.RegularExpressions.RegexCode::_caps Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 * ____caps_3; // System.Int32 System.Text.RegularExpressions.RegexCode::_capsize int32_t ____capsize_4; // System.Text.RegularExpressions.RegexPrefix System.Text.RegularExpressions.RegexCode::_fcPrefix RegexPrefix_tACADB52E91EFEB63B5EF7A1850634604F98FEE67 * ____fcPrefix_5; // System.Text.RegularExpressions.RegexBoyerMoore System.Text.RegularExpressions.RegexCode::_bmPrefix RegexBoyerMoore_t37ED99A3CC25068E4D3DE4517835CFFCCF2FA1EB * ____bmPrefix_6; // System.Int32 System.Text.RegularExpressions.RegexCode::_anchors int32_t ____anchors_7; // System.Boolean System.Text.RegularExpressions.RegexCode::_rightToLeft bool ____rightToLeft_8; public: inline static int32_t get_offset_of__codes_0() { return static_cast<int32_t>(offsetof(RegexCode_t12846533CAD1E4221CEDF5A4D15D4D649EA688FA, ____codes_0)); } inline Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* get__codes_0() const { return ____codes_0; } inline Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83** get_address_of__codes_0() { return &____codes_0; } inline void set__codes_0(Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* value) { ____codes_0 = value; Il2CppCodeGenWriteBarrier((&____codes_0), value); } inline static int32_t get_offset_of__strings_1() { return static_cast<int32_t>(offsetof(RegexCode_t12846533CAD1E4221CEDF5A4D15D4D649EA688FA, ____strings_1)); } inline StringU5BU5D_t933FB07893230EA91C40FF900D5400665E87B14E* get__strings_1() const { return ____strings_1; } inline StringU5BU5D_t933FB07893230EA91C40FF900D5400665E87B14E** get_address_of__strings_1() { return &____strings_1; } inline void set__strings_1(StringU5BU5D_t933FB07893230EA91C40FF900D5400665E87B14E* value) { ____strings_1 = value; Il2CppCodeGenWriteBarrier((&____strings_1), value); } inline static int32_t get_offset_of__trackcount_2() { return static_cast<int32_t>(offsetof(RegexCode_t12846533CAD1E4221CEDF5A4D15D4D649EA688FA, ____trackcount_2)); } inline int32_t get__trackcount_2() const { return ____trackcount_2; } inline int32_t* get_address_of__trackcount_2() { return &____trackcount_2; } inline void set__trackcount_2(int32_t value) { ____trackcount_2 = value; } inline static int32_t get_offset_of__caps_3() { return static_cast<int32_t>(offsetof(RegexCode_t12846533CAD1E4221CEDF5A4D15D4D649EA688FA, ____caps_3)); } inline Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 * get__caps_3() const { return ____caps_3; } inline Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 ** get_address_of__caps_3() { return &____caps_3; } inline void set__caps_3(Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 * value) { ____caps_3 = value; Il2CppCodeGenWriteBarrier((&____caps_3), value); } inline static int32_t get_offset_of__capsize_4() { return static_cast<int32_t>(offsetof(RegexCode_t12846533CAD1E4221CEDF5A4D15D4D649EA688FA, ____capsize_4)); } inline int32_t get__capsize_4() const { return ____capsize_4; } inline int32_t* get_address_of__capsize_4() { return &____capsize_4; } inline void set__capsize_4(int32_t value) { ____capsize_4 = value; } inline static int32_t get_offset_of__fcPrefix_5() { return static_cast<int32_t>(offsetof(RegexCode_t12846533CAD1E4221CEDF5A4D15D4D649EA688FA, ____fcPrefix_5)); } inline RegexPrefix_tACADB52E91EFEB63B5EF7A1850634604F98FEE67 * get__fcPrefix_5() const { return ____fcPrefix_5; } inline RegexPrefix_tACADB52E91EFEB63B5EF7A1850634604F98FEE67 ** get_address_of__fcPrefix_5() { return &____fcPrefix_5; } inline void set__fcPrefix_5(RegexPrefix_tACADB52E91EFEB63B5EF7A1850634604F98FEE67 * value) { ____fcPrefix_5 = value; Il2CppCodeGenWriteBarrier((&____fcPrefix_5), value); } inline static int32_t get_offset_of__bmPrefix_6() { return static_cast<int32_t>(offsetof(RegexCode_t12846533CAD1E4221CEDF5A4D15D4D649EA688FA, ____bmPrefix_6)); } inline RegexBoyerMoore_t37ED99A3CC25068E4D3DE4517835CFFCCF2FA1EB * get__bmPrefix_6() const { return ____bmPrefix_6; } inline RegexBoyerMoore_t37ED99A3CC25068E4D3DE4517835CFFCCF2FA1EB ** get_address_of__bmPrefix_6() { return &____bmPrefix_6; } inline void set__bmPrefix_6(RegexBoyerMoore_t37ED99A3CC25068E4D3DE4517835CFFCCF2FA1EB * value) { ____bmPrefix_6 = value; Il2CppCodeGenWriteBarrier((&____bmPrefix_6), value); } inline static int32_t get_offset_of__anchors_7() { return static_cast<int32_t>(offsetof(RegexCode_t12846533CAD1E4221CEDF5A4D15D4D649EA688FA, ____anchors_7)); } inline int32_t get__anchors_7() const { return ____anchors_7; } inline int32_t* get_address_of__anchors_7() { return &____anchors_7; } inline void set__anchors_7(int32_t value) { ____anchors_7 = value; } inline static int32_t get_offset_of__rightToLeft_8() { return static_cast<int32_t>(offsetof(RegexCode_t12846533CAD1E4221CEDF5A4D15D4D649EA688FA, ____rightToLeft_8)); } inline bool get__rightToLeft_8() const { return ____rightToLeft_8; } inline bool* get_address_of__rightToLeft_8() { return &____rightToLeft_8; } inline void set__rightToLeft_8(bool value) { ____rightToLeft_8 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // REGEXCODE_T12846533CAD1E4221CEDF5A4D15D4D649EA688FA_H #ifndef REGEXFC_T076AC007C0B19472DFC727FF856B5755332B8B52_H #define REGEXFC_T076AC007C0B19472DFC727FF856B5755332B8B52_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Text.RegularExpressions.RegexFC struct RegexFC_t076AC007C0B19472DFC727FF856B5755332B8B52 : public RuntimeObject { public: // System.Text.RegularExpressions.RegexCharClass System.Text.RegularExpressions.RegexFC::_cc RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90 * ____cc_0; // System.Boolean System.Text.RegularExpressions.RegexFC::_nullable bool ____nullable_1; // System.Boolean System.Text.RegularExpressions.RegexFC::_caseInsensitive bool ____caseInsensitive_2; public: inline static int32_t get_offset_of__cc_0() { return static_cast<int32_t>(offsetof(RegexFC_t076AC007C0B19472DFC727FF856B5755332B8B52, ____cc_0)); } inline RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90 * get__cc_0() const { return ____cc_0; } inline RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90 ** get_address_of__cc_0() { return &____cc_0; } inline void set__cc_0(RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90 * value) { ____cc_0 = value; Il2CppCodeGenWriteBarrier((&____cc_0), value); } inline static int32_t get_offset_of__nullable_1() { return static_cast<int32_t>(offsetof(RegexFC_t076AC007C0B19472DFC727FF856B5755332B8B52, ____nullable_1)); } inline bool get__nullable_1() const { return ____nullable_1; } inline bool* get_address_of__nullable_1() { return &____nullable_1; } inline void set__nullable_1(bool value) { ____nullable_1 = value; } inline static int32_t get_offset_of__caseInsensitive_2() { return static_cast<int32_t>(offsetof(RegexFC_t076AC007C0B19472DFC727FF856B5755332B8B52, ____caseInsensitive_2)); } inline bool get__caseInsensitive_2() const { return ____caseInsensitive_2; } inline bool* get_address_of__caseInsensitive_2() { return &____caseInsensitive_2; } inline void set__caseInsensitive_2(bool value) { ____caseInsensitive_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // REGEXFC_T076AC007C0B19472DFC727FF856B5755332B8B52_H #ifndef REGEXFCD_TCEDC8A19D3317F0856BC21A345C7E57A41FA568E_H #define REGEXFCD_TCEDC8A19D3317F0856BC21A345C7E57A41FA568E_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Text.RegularExpressions.RegexFCD struct RegexFCD_tCEDC8A19D3317F0856BC21A345C7E57A41FA568E : public RuntimeObject { public: // System.Int32[] System.Text.RegularExpressions.RegexFCD::_intStack Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* ____intStack_0; // System.Int32 System.Text.RegularExpressions.RegexFCD::_intDepth int32_t ____intDepth_1; // System.Text.RegularExpressions.RegexFC[] System.Text.RegularExpressions.RegexFCD::_fcStack RegexFCU5BU5D_tCABE05C26F3229DFDD9C8A86F3BA828C18F02D72* ____fcStack_2; // System.Int32 System.Text.RegularExpressions.RegexFCD::_fcDepth int32_t ____fcDepth_3; // System.Boolean System.Text.RegularExpressions.RegexFCD::_skipAllChildren bool ____skipAllChildren_4; // System.Boolean System.Text.RegularExpressions.RegexFCD::_skipchild bool ____skipchild_5; // System.Boolean System.Text.RegularExpressions.RegexFCD::_failed bool ____failed_6; public: inline static int32_t get_offset_of__intStack_0() { return static_cast<int32_t>(offsetof(RegexFCD_tCEDC8A19D3317F0856BC21A345C7E57A41FA568E, ____intStack_0)); } inline Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* get__intStack_0() const { return ____intStack_0; } inline Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83** get_address_of__intStack_0() { return &____intStack_0; } inline void set__intStack_0(Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* value) { ____intStack_0 = value; Il2CppCodeGenWriteBarrier((&____intStack_0), value); } inline static int32_t get_offset_of__intDepth_1() { return static_cast<int32_t>(offsetof(RegexFCD_tCEDC8A19D3317F0856BC21A345C7E57A41FA568E, ____intDepth_1)); } inline int32_t get__intDepth_1() const { return ____intDepth_1; } inline int32_t* get_address_of__intDepth_1() { return &____intDepth_1; } inline void set__intDepth_1(int32_t value) { ____intDepth_1 = value; } inline static int32_t get_offset_of__fcStack_2() { return static_cast<int32_t>(offsetof(RegexFCD_tCEDC8A19D3317F0856BC21A345C7E57A41FA568E, ____fcStack_2)); } inline RegexFCU5BU5D_tCABE05C26F3229DFDD9C8A86F3BA828C18F02D72* get__fcStack_2() const { return ____fcStack_2; } inline RegexFCU5BU5D_tCABE05C26F3229DFDD9C8A86F3BA828C18F02D72** get_address_of__fcStack_2() { return &____fcStack_2; } inline void set__fcStack_2(RegexFCU5BU5D_tCABE05C26F3229DFDD9C8A86F3BA828C18F02D72* value) { ____fcStack_2 = value; Il2CppCodeGenWriteBarrier((&____fcStack_2), value); } inline static int32_t get_offset_of__fcDepth_3() { return static_cast<int32_t>(offsetof(RegexFCD_tCEDC8A19D3317F0856BC21A345C7E57A41FA568E, ____fcDepth_3)); } inline int32_t get__fcDepth_3() const { return ____fcDepth_3; } inline int32_t* get_address_of__fcDepth_3() { return &____fcDepth_3; } inline void set__fcDepth_3(int32_t value) { ____fcDepth_3 = value; } inline static int32_t get_offset_of__skipAllChildren_4() { return static_cast<int32_t>(offsetof(RegexFCD_tCEDC8A19D3317F0856BC21A345C7E57A41FA568E, ____skipAllChildren_4)); } inline bool get__skipAllChildren_4() const { return ____skipAllChildren_4; } inline bool* get_address_of__skipAllChildren_4() { return &____skipAllChildren_4; } inline void set__skipAllChildren_4(bool value) { ____skipAllChildren_4 = value; } inline static int32_t get_offset_of__skipchild_5() { return static_cast<int32_t>(offsetof(RegexFCD_tCEDC8A19D3317F0856BC21A345C7E57A41FA568E, ____skipchild_5)); } inline bool get__skipchild_5() const { return ____skipchild_5; } inline bool* get_address_of__skipchild_5() { return &____skipchild_5; } inline void set__skipchild_5(bool value) { ____skipchild_5 = value; } inline static int32_t get_offset_of__failed_6() { return static_cast<int32_t>(offsetof(RegexFCD_tCEDC8A19D3317F0856BC21A345C7E57A41FA568E, ____failed_6)); } inline bool get__failed_6() const { return ____failed_6; } inline bool* get_address_of__failed_6() { return &____failed_6; } inline void set__failed_6(bool value) { ____failed_6 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // REGEXFCD_TCEDC8A19D3317F0856BC21A345C7E57A41FA568E_H #ifndef REGEXPREFIX_TACADB52E91EFEB63B5EF7A1850634604F98FEE67_H #define REGEXPREFIX_TACADB52E91EFEB63B5EF7A1850634604F98FEE67_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Text.RegularExpressions.RegexPrefix struct RegexPrefix_tACADB52E91EFEB63B5EF7A1850634604F98FEE67 : public RuntimeObject { public: // System.String System.Text.RegularExpressions.RegexPrefix::_prefix String_t* ____prefix_0; // System.Boolean System.Text.RegularExpressions.RegexPrefix::_caseInsensitive bool ____caseInsensitive_1; public: inline static int32_t get_offset_of__prefix_0() { return static_cast<int32_t>(offsetof(RegexPrefix_tACADB52E91EFEB63B5EF7A1850634604F98FEE67, ____prefix_0)); } inline String_t* get__prefix_0() const { return ____prefix_0; } inline String_t** get_address_of__prefix_0() { return &____prefix_0; } inline void set__prefix_0(String_t* value) { ____prefix_0 = value; Il2CppCodeGenWriteBarrier((&____prefix_0), value); } inline static int32_t get_offset_of__caseInsensitive_1() { return static_cast<int32_t>(offsetof(RegexPrefix_tACADB52E91EFEB63B5EF7A1850634604F98FEE67, ____caseInsensitive_1)); } inline bool get__caseInsensitive_1() const { return ____caseInsensitive_1; } inline bool* get_address_of__caseInsensitive_1() { return &____caseInsensitive_1; } inline void set__caseInsensitive_1(bool value) { ____caseInsensitive_1 = value; } }; struct RegexPrefix_tACADB52E91EFEB63B5EF7A1850634604F98FEE67_StaticFields { public: // System.Text.RegularExpressions.RegexPrefix System.Text.RegularExpressions.RegexPrefix::_empty RegexPrefix_tACADB52E91EFEB63B5EF7A1850634604F98FEE67 * ____empty_2; public: inline static int32_t get_offset_of__empty_2() { return static_cast<int32_t>(offsetof(RegexPrefix_tACADB52E91EFEB63B5EF7A1850634604F98FEE67_StaticFields, ____empty_2)); } inline RegexPrefix_tACADB52E91EFEB63B5EF7A1850634604F98FEE67 * get__empty_2() const { return ____empty_2; } inline RegexPrefix_tACADB52E91EFEB63B5EF7A1850634604F98FEE67 ** get_address_of__empty_2() { return &____empty_2; } inline void set__empty_2(RegexPrefix_tACADB52E91EFEB63B5EF7A1850634604F98FEE67 * value) { ____empty_2 = value; Il2CppCodeGenWriteBarrier((&____empty_2), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // REGEXPREFIX_TACADB52E91EFEB63B5EF7A1850634604F98FEE67_H #ifndef REGEXRUNNER_TBA888C4E3D3BA80EEE14878E4A330461730446B0_H #define REGEXRUNNER_TBA888C4E3D3BA80EEE14878E4A330461730446B0_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Text.RegularExpressions.RegexRunner struct RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0 : public RuntimeObject { public: // System.Int32 System.Text.RegularExpressions.RegexRunner::runtextbeg int32_t ___runtextbeg_0; // System.Int32 System.Text.RegularExpressions.RegexRunner::runtextend int32_t ___runtextend_1; // System.Int32 System.Text.RegularExpressions.RegexRunner::runtextstart int32_t ___runtextstart_2; // System.String System.Text.RegularExpressions.RegexRunner::runtext String_t* ___runtext_3; // System.Int32 System.Text.RegularExpressions.RegexRunner::runtextpos int32_t ___runtextpos_4; // System.Int32[] System.Text.RegularExpressions.RegexRunner::runtrack Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* ___runtrack_5; // System.Int32 System.Text.RegularExpressions.RegexRunner::runtrackpos int32_t ___runtrackpos_6; // System.Int32[] System.Text.RegularExpressions.RegexRunner::runstack Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* ___runstack_7; // System.Int32 System.Text.RegularExpressions.RegexRunner::runstackpos int32_t ___runstackpos_8; // System.Int32[] System.Text.RegularExpressions.RegexRunner::runcrawl Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* ___runcrawl_9; // System.Int32 System.Text.RegularExpressions.RegexRunner::runcrawlpos int32_t ___runcrawlpos_10; // System.Int32 System.Text.RegularExpressions.RegexRunner::runtrackcount int32_t ___runtrackcount_11; // System.Text.RegularExpressions.Match System.Text.RegularExpressions.RegexRunner::runmatch Match_tE447871AB59EED3642F31EB9559D162C2977EBB5 * ___runmatch_12; // System.Text.RegularExpressions.Regex System.Text.RegularExpressions.RegexRunner::runregex Regex_tFD46E63A462E852189FD6AB4E2B0B67C4D8FDBDF * ___runregex_13; // System.Int32 System.Text.RegularExpressions.RegexRunner::timeout int32_t ___timeout_14; // System.Boolean System.Text.RegularExpressions.RegexRunner::ignoreTimeout bool ___ignoreTimeout_15; // System.Int32 System.Text.RegularExpressions.RegexRunner::timeoutOccursAt int32_t ___timeoutOccursAt_16; // System.Int32 System.Text.RegularExpressions.RegexRunner::timeoutChecksToSkip int32_t ___timeoutChecksToSkip_17; public: inline static int32_t get_offset_of_runtextbeg_0() { return static_cast<int32_t>(offsetof(RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0, ___runtextbeg_0)); } inline int32_t get_runtextbeg_0() const { return ___runtextbeg_0; } inline int32_t* get_address_of_runtextbeg_0() { return &___runtextbeg_0; } inline void set_runtextbeg_0(int32_t value) { ___runtextbeg_0 = value; } inline static int32_t get_offset_of_runtextend_1() { return static_cast<int32_t>(offsetof(RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0, ___runtextend_1)); } inline int32_t get_runtextend_1() const { return ___runtextend_1; } inline int32_t* get_address_of_runtextend_1() { return &___runtextend_1; } inline void set_runtextend_1(int32_t value) { ___runtextend_1 = value; } inline static int32_t get_offset_of_runtextstart_2() { return static_cast<int32_t>(offsetof(RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0, ___runtextstart_2)); } inline int32_t get_runtextstart_2() const { return ___runtextstart_2; } inline int32_t* get_address_of_runtextstart_2() { return &___runtextstart_2; } inline void set_runtextstart_2(int32_t value) { ___runtextstart_2 = value; } inline static int32_t get_offset_of_runtext_3() { return static_cast<int32_t>(offsetof(RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0, ___runtext_3)); } inline String_t* get_runtext_3() const { return ___runtext_3; } inline String_t** get_address_of_runtext_3() { return &___runtext_3; } inline void set_runtext_3(String_t* value) { ___runtext_3 = value; Il2CppCodeGenWriteBarrier((&___runtext_3), value); } inline static int32_t get_offset_of_runtextpos_4() { return static_cast<int32_t>(offsetof(RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0, ___runtextpos_4)); } inline int32_t get_runtextpos_4() const { return ___runtextpos_4; } inline int32_t* get_address_of_runtextpos_4() { return &___runtextpos_4; } inline void set_runtextpos_4(int32_t value) { ___runtextpos_4 = value; } inline static int32_t get_offset_of_runtrack_5() { return static_cast<int32_t>(offsetof(RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0, ___runtrack_5)); } inline Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* get_runtrack_5() const { return ___runtrack_5; } inline Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83** get_address_of_runtrack_5() { return &___runtrack_5; } inline void set_runtrack_5(Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* value) { ___runtrack_5 = value; Il2CppCodeGenWriteBarrier((&___runtrack_5), value); } inline static int32_t get_offset_of_runtrackpos_6() { return static_cast<int32_t>(offsetof(RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0, ___runtrackpos_6)); } inline int32_t get_runtrackpos_6() const { return ___runtrackpos_6; } inline int32_t* get_address_of_runtrackpos_6() { return &___runtrackpos_6; } inline void set_runtrackpos_6(int32_t value) { ___runtrackpos_6 = value; } inline static int32_t get_offset_of_runstack_7() { return static_cast<int32_t>(offsetof(RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0, ___runstack_7)); } inline Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* get_runstack_7() const { return ___runstack_7; } inline Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83** get_address_of_runstack_7() { return &___runstack_7; } inline void set_runstack_7(Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* value) { ___runstack_7 = value; Il2CppCodeGenWriteBarrier((&___runstack_7), value); } inline static int32_t get_offset_of_runstackpos_8() { return static_cast<int32_t>(offsetof(RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0, ___runstackpos_8)); } inline int32_t get_runstackpos_8() const { return ___runstackpos_8; } inline int32_t* get_address_of_runstackpos_8() { return &___runstackpos_8; } inline void set_runstackpos_8(int32_t value) { ___runstackpos_8 = value; } inline static int32_t get_offset_of_runcrawl_9() { return static_cast<int32_t>(offsetof(RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0, ___runcrawl_9)); } inline Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* get_runcrawl_9() const { return ___runcrawl_9; } inline Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83** get_address_of_runcrawl_9() { return &___runcrawl_9; } inline void set_runcrawl_9(Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* value) { ___runcrawl_9 = value; Il2CppCodeGenWriteBarrier((&___runcrawl_9), value); } inline static int32_t get_offset_of_runcrawlpos_10() { return static_cast<int32_t>(offsetof(RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0, ___runcrawlpos_10)); } inline int32_t get_runcrawlpos_10() const { return ___runcrawlpos_10; } inline int32_t* get_address_of_runcrawlpos_10() { return &___runcrawlpos_10; } inline void set_runcrawlpos_10(int32_t value) { ___runcrawlpos_10 = value; } inline static int32_t get_offset_of_runtrackcount_11() { return static_cast<int32_t>(offsetof(RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0, ___runtrackcount_11)); } inline int32_t get_runtrackcount_11() const { return ___runtrackcount_11; } inline int32_t* get_address_of_runtrackcount_11() { return &___runtrackcount_11; } inline void set_runtrackcount_11(int32_t value) { ___runtrackcount_11 = value; } inline static int32_t get_offset_of_runmatch_12() { return static_cast<int32_t>(offsetof(RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0, ___runmatch_12)); } inline Match_tE447871AB59EED3642F31EB9559D162C2977EBB5 * get_runmatch_12() const { return ___runmatch_12; } inline Match_tE447871AB59EED3642F31EB9559D162C2977EBB5 ** get_address_of_runmatch_12() { return &___runmatch_12; } inline void set_runmatch_12(Match_tE447871AB59EED3642F31EB9559D162C2977EBB5 * value) { ___runmatch_12 = value; Il2CppCodeGenWriteBarrier((&___runmatch_12), value); } inline static int32_t get_offset_of_runregex_13() { return static_cast<int32_t>(offsetof(RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0, ___runregex_13)); } inline Regex_tFD46E63A462E852189FD6AB4E2B0B67C4D8FDBDF * get_runregex_13() const { return ___runregex_13; } inline Regex_tFD46E63A462E852189FD6AB4E2B0B67C4D8FDBDF ** get_address_of_runregex_13() { return &___runregex_13; } inline void set_runregex_13(Regex_tFD46E63A462E852189FD6AB4E2B0B67C4D8FDBDF * value) { ___runregex_13 = value; Il2CppCodeGenWriteBarrier((&___runregex_13), value); } inline static int32_t get_offset_of_timeout_14() { return static_cast<int32_t>(offsetof(RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0, ___timeout_14)); } inline int32_t get_timeout_14() const { return ___timeout_14; } inline int32_t* get_address_of_timeout_14() { return &___timeout_14; } inline void set_timeout_14(int32_t value) { ___timeout_14 = value; } inline static int32_t get_offset_of_ignoreTimeout_15() { return static_cast<int32_t>(offsetof(RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0, ___ignoreTimeout_15)); } inline bool get_ignoreTimeout_15() const { return ___ignoreTimeout_15; } inline bool* get_address_of_ignoreTimeout_15() { return &___ignoreTimeout_15; } inline void set_ignoreTimeout_15(bool value) { ___ignoreTimeout_15 = value; } inline static int32_t get_offset_of_timeoutOccursAt_16() { return static_cast<int32_t>(offsetof(RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0, ___timeoutOccursAt_16)); } inline int32_t get_timeoutOccursAt_16() const { return ___timeoutOccursAt_16; } inline int32_t* get_address_of_timeoutOccursAt_16() { return &___timeoutOccursAt_16; } inline void set_timeoutOccursAt_16(int32_t value) { ___timeoutOccursAt_16 = value; } inline static int32_t get_offset_of_timeoutChecksToSkip_17() { return static_cast<int32_t>(offsetof(RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0, ___timeoutChecksToSkip_17)); } inline int32_t get_timeoutChecksToSkip_17() const { return ___timeoutChecksToSkip_17; } inline int32_t* get_address_of_timeoutChecksToSkip_17() { return &___timeoutChecksToSkip_17; } inline void set_timeoutChecksToSkip_17(int32_t value) { ___timeoutChecksToSkip_17 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // REGEXRUNNER_TBA888C4E3D3BA80EEE14878E4A330461730446B0_H #ifndef REGEXRUNNERFACTORY_T0703F390E2102623B0189DEC095DB182698E404B_H #define REGEXRUNNERFACTORY_T0703F390E2102623B0189DEC095DB182698E404B_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Text.RegularExpressions.RegexRunnerFactory struct RegexRunnerFactory_t0703F390E2102623B0189DEC095DB182698E404B : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // REGEXRUNNERFACTORY_T0703F390E2102623B0189DEC095DB182698E404B_H #ifndef REGEXWRITER_T5F8CEA1FC9A4AC32A95BAC6E49EF51D7DF051AA6_H #define REGEXWRITER_T5F8CEA1FC9A4AC32A95BAC6E49EF51D7DF051AA6_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Text.RegularExpressions.RegexWriter struct RegexWriter_t5F8CEA1FC9A4AC32A95BAC6E49EF51D7DF051AA6 : public RuntimeObject { public: // System.Int32[] System.Text.RegularExpressions.RegexWriter::_intStack Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* ____intStack_0; // System.Int32 System.Text.RegularExpressions.RegexWriter::_depth int32_t ____depth_1; // System.Int32[] System.Text.RegularExpressions.RegexWriter::_emitted Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* ____emitted_2; // System.Int32 System.Text.RegularExpressions.RegexWriter::_curpos int32_t ____curpos_3; // System.Collections.Generic.Dictionary`2<System.String,System.Int32> System.Text.RegularExpressions.RegexWriter::_stringhash Dictionary_2_tD6E204872BA9FD506A0287EF68E285BEB9EC0DFB * ____stringhash_4; // System.Collections.Generic.List`1<System.String> System.Text.RegularExpressions.RegexWriter::_stringtable List_1_tE8032E48C661C350FF9550E9063D595C0AB25CD3 * ____stringtable_5; // System.Boolean System.Text.RegularExpressions.RegexWriter::_counting bool ____counting_6; // System.Int32 System.Text.RegularExpressions.RegexWriter::_count int32_t ____count_7; // System.Int32 System.Text.RegularExpressions.RegexWriter::_trackcount int32_t ____trackcount_8; // System.Collections.Hashtable System.Text.RegularExpressions.RegexWriter::_caps Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 * ____caps_9; public: inline static int32_t get_offset_of__intStack_0() { return static_cast<int32_t>(offsetof(RegexWriter_t5F8CEA1FC9A4AC32A95BAC6E49EF51D7DF051AA6, ____intStack_0)); } inline Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* get__intStack_0() const { return ____intStack_0; } inline Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83** get_address_of__intStack_0() { return &____intStack_0; } inline void set__intStack_0(Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* value) { ____intStack_0 = value; Il2CppCodeGenWriteBarrier((&____intStack_0), value); } inline static int32_t get_offset_of__depth_1() { return static_cast<int32_t>(offsetof(RegexWriter_t5F8CEA1FC9A4AC32A95BAC6E49EF51D7DF051AA6, ____depth_1)); } inline int32_t get__depth_1() const { return ____depth_1; } inline int32_t* get_address_of__depth_1() { return &____depth_1; } inline void set__depth_1(int32_t value) { ____depth_1 = value; } inline static int32_t get_offset_of__emitted_2() { return static_cast<int32_t>(offsetof(RegexWriter_t5F8CEA1FC9A4AC32A95BAC6E49EF51D7DF051AA6, ____emitted_2)); } inline Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* get__emitted_2() const { return ____emitted_2; } inline Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83** get_address_of__emitted_2() { return &____emitted_2; } inline void set__emitted_2(Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* value) { ____emitted_2 = value; Il2CppCodeGenWriteBarrier((&____emitted_2), value); } inline static int32_t get_offset_of__curpos_3() { return static_cast<int32_t>(offsetof(RegexWriter_t5F8CEA1FC9A4AC32A95BAC6E49EF51D7DF051AA6, ____curpos_3)); } inline int32_t get__curpos_3() const { return ____curpos_3; } inline int32_t* get_address_of__curpos_3() { return &____curpos_3; } inline void set__curpos_3(int32_t value) { ____curpos_3 = value; } inline static int32_t get_offset_of__stringhash_4() { return static_cast<int32_t>(offsetof(RegexWriter_t5F8CEA1FC9A4AC32A95BAC6E49EF51D7DF051AA6, ____stringhash_4)); } inline Dictionary_2_tD6E204872BA9FD506A0287EF68E285BEB9EC0DFB * get__stringhash_4() const { return ____stringhash_4; } inline Dictionary_2_tD6E204872BA9FD506A0287EF68E285BEB9EC0DFB ** get_address_of__stringhash_4() { return &____stringhash_4; } inline void set__stringhash_4(Dictionary_2_tD6E204872BA9FD506A0287EF68E285BEB9EC0DFB * value) { ____stringhash_4 = value; Il2CppCodeGenWriteBarrier((&____stringhash_4), value); } inline static int32_t get_offset_of__stringtable_5() { return static_cast<int32_t>(offsetof(RegexWriter_t5F8CEA1FC9A4AC32A95BAC6E49EF51D7DF051AA6, ____stringtable_5)); } inline List_1_tE8032E48C661C350FF9550E9063D595C0AB25CD3 * get__stringtable_5() const { return ____stringtable_5; } inline List_1_tE8032E48C661C350FF9550E9063D595C0AB25CD3 ** get_address_of__stringtable_5() { return &____stringtable_5; } inline void set__stringtable_5(List_1_tE8032E48C661C350FF9550E9063D595C0AB25CD3 * value) { ____stringtable_5 = value; Il2CppCodeGenWriteBarrier((&____stringtable_5), value); } inline static int32_t get_offset_of__counting_6() { return static_cast<int32_t>(offsetof(RegexWriter_t5F8CEA1FC9A4AC32A95BAC6E49EF51D7DF051AA6, ____counting_6)); } inline bool get__counting_6() const { return ____counting_6; } inline bool* get_address_of__counting_6() { return &____counting_6; } inline void set__counting_6(bool value) { ____counting_6 = value; } inline static int32_t get_offset_of__count_7() { return static_cast<int32_t>(offsetof(RegexWriter_t5F8CEA1FC9A4AC32A95BAC6E49EF51D7DF051AA6, ____count_7)); } inline int32_t get__count_7() const { return ____count_7; } inline int32_t* get_address_of__count_7() { return &____count_7; } inline void set__count_7(int32_t value) { ____count_7 = value; } inline static int32_t get_offset_of__trackcount_8() { return static_cast<int32_t>(offsetof(RegexWriter_t5F8CEA1FC9A4AC32A95BAC6E49EF51D7DF051AA6, ____trackcount_8)); } inline int32_t get__trackcount_8() const { return ____trackcount_8; } inline int32_t* get_address_of__trackcount_8() { return &____trackcount_8; } inline void set__trackcount_8(int32_t value) { ____trackcount_8 = value; } inline static int32_t get_offset_of__caps_9() { return static_cast<int32_t>(offsetof(RegexWriter_t5F8CEA1FC9A4AC32A95BAC6E49EF51D7DF051AA6, ____caps_9)); } inline Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 * get__caps_9() const { return ____caps_9; } inline Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 ** get_address_of__caps_9() { return &____caps_9; } inline void set__caps_9(Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 * value) { ____caps_9 = value; Il2CppCodeGenWriteBarrier((&____caps_9), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // REGEXWRITER_T5F8CEA1FC9A4AC32A95BAC6E49EF51D7DF051AA6_H #ifndef VALUETYPE_T4D0C27076F7C36E76190FB3328E232BCB1CD1FFF_H #define VALUETYPE_T4D0C27076F7C36E76190FB3328E232BCB1CD1FFF_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ValueType struct ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.ValueType struct ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF_marshaled_pinvoke { }; // Native definition for COM marshalling of System.ValueType struct ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF_marshaled_com { }; #endif // VALUETYPE_T4D0C27076F7C36E76190FB3328E232BCB1CD1FFF_H #ifndef __STATICARRAYINITTYPESIZEU3D128_T4A42759E6E25B0C61E6036A661F4344DE92C2905_H #define __STATICARRAYINITTYPESIZEU3D128_T4A42759E6E25B0C61E6036A661F4344DE92C2905_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <PrivateImplementationDetails>___StaticArrayInitTypeSizeU3D128 struct __StaticArrayInitTypeSizeU3D128_t4A42759E6E25B0C61E6036A661F4344DE92C2905 { public: union { struct { union { }; }; uint8_t __StaticArrayInitTypeSizeU3D128_t4A42759E6E25B0C61E6036A661F4344DE92C2905__padding[128]; }; public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // __STATICARRAYINITTYPESIZEU3D128_T4A42759E6E25B0C61E6036A661F4344DE92C2905_H #ifndef __STATICARRAYINITTYPESIZEU3D32_T5300E5FCBD58716E8A4EBB9470E4FAE1A0A964FA_H #define __STATICARRAYINITTYPESIZEU3D32_T5300E5FCBD58716E8A4EBB9470E4FAE1A0A964FA_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <PrivateImplementationDetails>___StaticArrayInitTypeSizeU3D32 struct __StaticArrayInitTypeSizeU3D32_t5300E5FCBD58716E8A4EBB9470E4FAE1A0A964FA { public: union { struct { union { }; }; uint8_t __StaticArrayInitTypeSizeU3D32_t5300E5FCBD58716E8A4EBB9470E4FAE1A0A964FA__padding[32]; }; public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // __STATICARRAYINITTYPESIZEU3D32_T5300E5FCBD58716E8A4EBB9470E4FAE1A0A964FA_H #ifndef BOOLEAN_TB53F6830F670160873277339AA58F15CAED4399C_H #define BOOLEAN_TB53F6830F670160873277339AA58F15CAED4399C_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Boolean struct Boolean_tB53F6830F670160873277339AA58F15CAED4399C { public: // System.Boolean System.Boolean::m_value bool ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Boolean_tB53F6830F670160873277339AA58F15CAED4399C, ___m_value_0)); } inline bool get_m_value_0() const { return ___m_value_0; } inline bool* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(bool value) { ___m_value_0 = value; } }; struct Boolean_tB53F6830F670160873277339AA58F15CAED4399C_StaticFields { public: // System.String System.Boolean::TrueString String_t* ___TrueString_5; // System.String System.Boolean::FalseString String_t* ___FalseString_6; public: inline static int32_t get_offset_of_TrueString_5() { return static_cast<int32_t>(offsetof(Boolean_tB53F6830F670160873277339AA58F15CAED4399C_StaticFields, ___TrueString_5)); } inline String_t* get_TrueString_5() const { return ___TrueString_5; } inline String_t** get_address_of_TrueString_5() { return &___TrueString_5; } inline void set_TrueString_5(String_t* value) { ___TrueString_5 = value; Il2CppCodeGenWriteBarrier((&___TrueString_5), value); } inline static int32_t get_offset_of_FalseString_6() { return static_cast<int32_t>(offsetof(Boolean_tB53F6830F670160873277339AA58F15CAED4399C_StaticFields, ___FalseString_6)); } inline String_t* get_FalseString_6() const { return ___FalseString_6; } inline String_t** get_address_of_FalseString_6() { return &___FalseString_6; } inline void set_FalseString_6(String_t* value) { ___FalseString_6 = value; Il2CppCodeGenWriteBarrier((&___FalseString_6), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BOOLEAN_TB53F6830F670160873277339AA58F15CAED4399C_H #ifndef TYPECONVERTERATTRIBUTE_TA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8_H #define TYPECONVERTERATTRIBUTE_TA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ComponentModel.TypeConverterAttribute struct TypeConverterAttribute_tA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8 : public Attribute_tF048C13FB3C8CFCC53F82290E4A3F621089F9A74 { public: // System.String System.ComponentModel.TypeConverterAttribute::typeName String_t* ___typeName_0; public: inline static int32_t get_offset_of_typeName_0() { return static_cast<int32_t>(offsetof(TypeConverterAttribute_tA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8, ___typeName_0)); } inline String_t* get_typeName_0() const { return ___typeName_0; } inline String_t** get_address_of_typeName_0() { return &___typeName_0; } inline void set_typeName_0(String_t* value) { ___typeName_0 = value; Il2CppCodeGenWriteBarrier((&___typeName_0), value); } }; struct TypeConverterAttribute_tA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8_StaticFields { public: // System.ComponentModel.TypeConverterAttribute System.ComponentModel.TypeConverterAttribute::Default TypeConverterAttribute_tA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8 * ___Default_1; public: inline static int32_t get_offset_of_Default_1() { return static_cast<int32_t>(offsetof(TypeConverterAttribute_tA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8_StaticFields, ___Default_1)); } inline TypeConverterAttribute_tA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8 * get_Default_1() const { return ___Default_1; } inline TypeConverterAttribute_tA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8 ** get_address_of_Default_1() { return &___Default_1; } inline void set_Default_1(TypeConverterAttribute_tA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8 * value) { ___Default_1 = value; Il2CppCodeGenWriteBarrier((&___Default_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TYPECONVERTERATTRIBUTE_TA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8_H #ifndef CONFIGURATIONELEMENTCOLLECTION_TB0DA3194B9C1528D2627B291C79B560C68A78FCC_H #define CONFIGURATIONELEMENTCOLLECTION_TB0DA3194B9C1528D2627B291C79B560C68A78FCC_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Configuration.ConfigurationElementCollection struct ConfigurationElementCollection_tB0DA3194B9C1528D2627B291C79B560C68A78FCC : public ConfigurationElement_tF3ECE1CDFD3304CD9D595E758276F014321AD9FE { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CONFIGURATIONELEMENTCOLLECTION_TB0DA3194B9C1528D2627B291C79B560C68A78FCC_H #ifndef CONFIGURATIONSECTION_T044F68052218C8000611AE9ADD5F66E62A632B34_H #define CONFIGURATIONSECTION_T044F68052218C8000611AE9ADD5F66E62A632B34_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Configuration.ConfigurationSection struct ConfigurationSection_t044F68052218C8000611AE9ADD5F66E62A632B34 : public ConfigurationElement_tF3ECE1CDFD3304CD9D595E758276F014321AD9FE { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CONFIGURATIONSECTION_T044F68052218C8000611AE9ADD5F66E62A632B34_H #ifndef ENUM_T2AF27C02B8653AE29442467390005ABC74D8F521_H #define ENUM_T2AF27C02B8653AE29442467390005ABC74D8F521_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Enum struct Enum_t2AF27C02B8653AE29442467390005ABC74D8F521 : public ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF { public: public: }; struct Enum_t2AF27C02B8653AE29442467390005ABC74D8F521_StaticFields { public: // System.Char[] System.Enum::enumSeperatorCharArray CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2* ___enumSeperatorCharArray_0; public: inline static int32_t get_offset_of_enumSeperatorCharArray_0() { return static_cast<int32_t>(offsetof(Enum_t2AF27C02B8653AE29442467390005ABC74D8F521_StaticFields, ___enumSeperatorCharArray_0)); } inline CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2* get_enumSeperatorCharArray_0() const { return ___enumSeperatorCharArray_0; } inline CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2** get_address_of_enumSeperatorCharArray_0() { return &___enumSeperatorCharArray_0; } inline void set_enumSeperatorCharArray_0(CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2* value) { ___enumSeperatorCharArray_0 = value; Il2CppCodeGenWriteBarrier((&___enumSeperatorCharArray_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Enum struct Enum_t2AF27C02B8653AE29442467390005ABC74D8F521_marshaled_pinvoke { }; // Native definition for COM marshalling of System.Enum struct Enum_t2AF27C02B8653AE29442467390005ABC74D8F521_marshaled_com { }; #endif // ENUM_T2AF27C02B8653AE29442467390005ABC74D8F521_H #ifndef BYPASSELEMENT_T89C59A549C7A25609AA5C200352CD9E310172BAF_H #define BYPASSELEMENT_T89C59A549C7A25609AA5C200352CD9E310172BAF_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Net.Configuration.BypassElement struct BypassElement_t89C59A549C7A25609AA5C200352CD9E310172BAF : public ConfigurationElement_tF3ECE1CDFD3304CD9D595E758276F014321AD9FE { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BYPASSELEMENT_T89C59A549C7A25609AA5C200352CD9E310172BAF_H #ifndef CONNECTIONMANAGEMENTELEMENT_TABDA95F63A9CBFC2720D7D3F15C5B352EC5CE7AD_H #define CONNECTIONMANAGEMENTELEMENT_TABDA95F63A9CBFC2720D7D3F15C5B352EC5CE7AD_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Net.Configuration.ConnectionManagementElement struct ConnectionManagementElement_tABDA95F63A9CBFC2720D7D3F15C5B352EC5CE7AD : public ConfigurationElement_tF3ECE1CDFD3304CD9D595E758276F014321AD9FE { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CONNECTIONMANAGEMENTELEMENT_TABDA95F63A9CBFC2720D7D3F15C5B352EC5CE7AD_H #ifndef HTTPWEBREQUESTELEMENT_T3E2FC0EB83C362CC92300949AF90A0B0BE01EA3D_H #define HTTPWEBREQUESTELEMENT_T3E2FC0EB83C362CC92300949AF90A0B0BE01EA3D_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Net.Configuration.HttpWebRequestElement struct HttpWebRequestElement_t3E2FC0EB83C362CC92300949AF90A0B0BE01EA3D : public ConfigurationElement_tF3ECE1CDFD3304CD9D595E758276F014321AD9FE { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // HTTPWEBREQUESTELEMENT_T3E2FC0EB83C362CC92300949AF90A0B0BE01EA3D_H #ifndef IPV6ELEMENT_TCA869DC79FE3740DBDECC47877F1676294DB4A23_H #define IPV6ELEMENT_TCA869DC79FE3740DBDECC47877F1676294DB4A23_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Net.Configuration.Ipv6Element struct Ipv6Element_tCA869DC79FE3740DBDECC47877F1676294DB4A23 : public ConfigurationElement_tF3ECE1CDFD3304CD9D595E758276F014321AD9FE { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // IPV6ELEMENT_TCA869DC79FE3740DBDECC47877F1676294DB4A23_H #ifndef NETSECTIONGROUP_TA4ACD82AFE8B5C11E509FA8623D554BB5B4DB591_H #define NETSECTIONGROUP_TA4ACD82AFE8B5C11E509FA8623D554BB5B4DB591_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Net.Configuration.NetSectionGroup struct NetSectionGroup_tA4ACD82AFE8B5C11E509FA8623D554BB5B4DB591 : public ConfigurationSectionGroup_t64AC7C211E1F868ABF1BD604DA43815564D304E6 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // NETSECTIONGROUP_TA4ACD82AFE8B5C11E509FA8623D554BB5B4DB591_H #ifndef PERFORMANCECOUNTERSELEMENT_TCE4CFF0A3503E44D7B8EC6E85FD3C50EB1A1B570_H #define PERFORMANCECOUNTERSELEMENT_TCE4CFF0A3503E44D7B8EC6E85FD3C50EB1A1B570_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Net.Configuration.PerformanceCountersElement struct PerformanceCountersElement_tCE4CFF0A3503E44D7B8EC6E85FD3C50EB1A1B570 : public ConfigurationElement_tF3ECE1CDFD3304CD9D595E758276F014321AD9FE { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // PERFORMANCECOUNTERSELEMENT_TCE4CFF0A3503E44D7B8EC6E85FD3C50EB1A1B570_H #ifndef PROXYELEMENT_TBD5D75620576BA5BB5521C11D09E0A6E996F9449_H #define PROXYELEMENT_TBD5D75620576BA5BB5521C11D09E0A6E996F9449_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Net.Configuration.ProxyElement struct ProxyElement_tBD5D75620576BA5BB5521C11D09E0A6E996F9449 : public ConfigurationElement_tF3ECE1CDFD3304CD9D595E758276F014321AD9FE { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // PROXYELEMENT_TBD5D75620576BA5BB5521C11D09E0A6E996F9449_H #ifndef SERVICEPOINTMANAGERELEMENT_TD8D1491569C963460C14DF4D42ED05DF34428CFC_H #define SERVICEPOINTMANAGERELEMENT_TD8D1491569C963460C14DF4D42ED05DF34428CFC_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Net.Configuration.ServicePointManagerElement struct ServicePointManagerElement_tD8D1491569C963460C14DF4D42ED05DF34428CFC : public ConfigurationElement_tF3ECE1CDFD3304CD9D595E758276F014321AD9FE { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SERVICEPOINTMANAGERELEMENT_TD8D1491569C963460C14DF4D42ED05DF34428CFC_H #ifndef SOCKETELEMENT_T32F016077CBED287B80063811E80BCCC7E8B1BF9_H #define SOCKETELEMENT_T32F016077CBED287B80063811E80BCCC7E8B1BF9_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Net.Configuration.SocketElement struct SocketElement_t32F016077CBED287B80063811E80BCCC7E8B1BF9 : public ConfigurationElement_tF3ECE1CDFD3304CD9D595E758276F014321AD9FE { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SOCKETELEMENT_T32F016077CBED287B80063811E80BCCC7E8B1BF9_H #ifndef WEBPROXYSCRIPTELEMENT_T4302A26A6D4E02146662B30E3452A5167966E6B3_H #define WEBPROXYSCRIPTELEMENT_T4302A26A6D4E02146662B30E3452A5167966E6B3_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Net.Configuration.WebProxyScriptElement struct WebProxyScriptElement_t4302A26A6D4E02146662B30E3452A5167966E6B3 : public ConfigurationElement_tF3ECE1CDFD3304CD9D595E758276F014321AD9FE { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // WEBPROXYSCRIPTELEMENT_T4302A26A6D4E02146662B30E3452A5167966E6B3_H #ifndef WEBREQUESTMODULEELEMENT_TE81A1FA5B9B4BCFB1ED015287A2D4F9EED37F3EC_H #define WEBREQUESTMODULEELEMENT_TE81A1FA5B9B4BCFB1ED015287A2D4F9EED37F3EC_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Net.Configuration.WebRequestModuleElement struct WebRequestModuleElement_tE81A1FA5B9B4BCFB1ED015287A2D4F9EED37F3EC : public ConfigurationElement_tF3ECE1CDFD3304CD9D595E758276F014321AD9FE { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // WEBREQUESTMODULEELEMENT_TE81A1FA5B9B4BCFB1ED015287A2D4F9EED37F3EC_H #ifndef IPV6ADDRESSFORMATTER_T451290B1C6FD64B6C59F95D99EDB4A9CC703BA90_H #define IPV6ADDRESSFORMATTER_T451290B1C6FD64B6C59F95D99EDB4A9CC703BA90_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Net.IPv6AddressFormatter struct IPv6AddressFormatter_t451290B1C6FD64B6C59F95D99EDB4A9CC703BA90 { public: // System.UInt16[] System.Net.IPv6AddressFormatter::address UInt16U5BU5D_t2D4BB1F8C486FF4359FFA7E4A76A8708A684543E* ___address_0; // System.Int64 System.Net.IPv6AddressFormatter::scopeId int64_t ___scopeId_1; public: inline static int32_t get_offset_of_address_0() { return static_cast<int32_t>(offsetof(IPv6AddressFormatter_t451290B1C6FD64B6C59F95D99EDB4A9CC703BA90, ___address_0)); } inline UInt16U5BU5D_t2D4BB1F8C486FF4359FFA7E4A76A8708A684543E* get_address_0() const { return ___address_0; } inline UInt16U5BU5D_t2D4BB1F8C486FF4359FFA7E4A76A8708A684543E** get_address_of_address_0() { return &___address_0; } inline void set_address_0(UInt16U5BU5D_t2D4BB1F8C486FF4359FFA7E4A76A8708A684543E* value) { ___address_0 = value; Il2CppCodeGenWriteBarrier((&___address_0), value); } inline static int32_t get_offset_of_scopeId_1() { return static_cast<int32_t>(offsetof(IPv6AddressFormatter_t451290B1C6FD64B6C59F95D99EDB4A9CC703BA90, ___scopeId_1)); } inline int64_t get_scopeId_1() const { return ___scopeId_1; } inline int64_t* get_address_of_scopeId_1() { return &___scopeId_1; } inline void set_scopeId_1(int64_t value) { ___scopeId_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // IPV6ADDRESSFORMATTER_T451290B1C6FD64B6C59F95D99EDB4A9CC703BA90_H #ifndef X509EXTENSION_T223237DF0C323CC455D3A2634D977773D2F3818A_H #define X509EXTENSION_T223237DF0C323CC455D3A2634D977773D2F3818A_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Security.Cryptography.X509Certificates.X509Extension struct X509Extension_t223237DF0C323CC455D3A2634D977773D2F3818A : public AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65 { public: // System.Boolean System.Security.Cryptography.X509Certificates.X509Extension::_critical bool ____critical_2; public: inline static int32_t get_offset_of__critical_2() { return static_cast<int32_t>(offsetof(X509Extension_t223237DF0C323CC455D3A2634D977773D2F3818A, ____critical_2)); } inline bool get__critical_2() const { return ____critical_2; } inline bool* get_address_of__critical_2() { return &____critical_2; } inline void set__critical_2(bool value) { ____critical_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // X509EXTENSION_T223237DF0C323CC455D3A2634D977773D2F3818A_H #ifndef SYSTEMEXCEPTION_T5380468142AA850BE4A341D7AF3EAB9C78746782_H #define SYSTEMEXCEPTION_T5380468142AA850BE4A341D7AF3EAB9C78746782_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.SystemException struct SystemException_t5380468142AA850BE4A341D7AF3EAB9C78746782 : public Exception_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SYSTEMEXCEPTION_T5380468142AA850BE4A341D7AF3EAB9C78746782_H #ifndef GROUP_TB4759D0385925B2C8C14ED3FCD5D2F43CFBD0443_H #define GROUP_TB4759D0385925B2C8C14ED3FCD5D2F43CFBD0443_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Text.RegularExpressions.Group struct Group_tB4759D0385925B2C8C14ED3FCD5D2F43CFBD0443 : public Capture_tF4475248CCF3EFF914844BE2C993FC609D41DB73 { public: // System.Int32[] System.Text.RegularExpressions.Group::_caps Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* ____caps_4; // System.Int32 System.Text.RegularExpressions.Group::_capcount int32_t ____capcount_5; // System.String System.Text.RegularExpressions.Group::_name String_t* ____name_6; public: inline static int32_t get_offset_of__caps_4() { return static_cast<int32_t>(offsetof(Group_tB4759D0385925B2C8C14ED3FCD5D2F43CFBD0443, ____caps_4)); } inline Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* get__caps_4() const { return ____caps_4; } inline Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83** get_address_of__caps_4() { return &____caps_4; } inline void set__caps_4(Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* value) { ____caps_4 = value; Il2CppCodeGenWriteBarrier((&____caps_4), value); } inline static int32_t get_offset_of__capcount_5() { return static_cast<int32_t>(offsetof(Group_tB4759D0385925B2C8C14ED3FCD5D2F43CFBD0443, ____capcount_5)); } inline int32_t get__capcount_5() const { return ____capcount_5; } inline int32_t* get_address_of__capcount_5() { return &____capcount_5; } inline void set__capcount_5(int32_t value) { ____capcount_5 = value; } inline static int32_t get_offset_of__name_6() { return static_cast<int32_t>(offsetof(Group_tB4759D0385925B2C8C14ED3FCD5D2F43CFBD0443, ____name_6)); } inline String_t* get__name_6() const { return ____name_6; } inline String_t** get_address_of__name_6() { return &____name_6; } inline void set__name_6(String_t* value) { ____name_6 = value; Il2CppCodeGenWriteBarrier((&____name_6), value); } }; struct Group_tB4759D0385925B2C8C14ED3FCD5D2F43CFBD0443_StaticFields { public: // System.Text.RegularExpressions.Group System.Text.RegularExpressions.Group::_emptygroup Group_tB4759D0385925B2C8C14ED3FCD5D2F43CFBD0443 * ____emptygroup_3; public: inline static int32_t get_offset_of__emptygroup_3() { return static_cast<int32_t>(offsetof(Group_tB4759D0385925B2C8C14ED3FCD5D2F43CFBD0443_StaticFields, ____emptygroup_3)); } inline Group_tB4759D0385925B2C8C14ED3FCD5D2F43CFBD0443 * get__emptygroup_3() const { return ____emptygroup_3; } inline Group_tB4759D0385925B2C8C14ED3FCD5D2F43CFBD0443 ** get_address_of__emptygroup_3() { return &____emptygroup_3; } inline void set__emptygroup_3(Group_tB4759D0385925B2C8C14ED3FCD5D2F43CFBD0443 * value) { ____emptygroup_3 = value; Il2CppCodeGenWriteBarrier((&____emptygroup_3), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // GROUP_TB4759D0385925B2C8C14ED3FCD5D2F43CFBD0443_H #ifndef LOWERCASEMAPPING_T3F087D71A4D7A309FD5492CE33501FD4F4709D7B_H #define LOWERCASEMAPPING_T3F087D71A4D7A309FD5492CE33501FD4F4709D7B_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Text.RegularExpressions.RegexCharClass_LowerCaseMapping struct LowerCaseMapping_t3F087D71A4D7A309FD5492CE33501FD4F4709D7B { public: // System.Char System.Text.RegularExpressions.RegexCharClass_LowerCaseMapping::_chMin Il2CppChar ____chMin_0; // System.Char System.Text.RegularExpressions.RegexCharClass_LowerCaseMapping::_chMax Il2CppChar ____chMax_1; // System.Int32 System.Text.RegularExpressions.RegexCharClass_LowerCaseMapping::_lcOp int32_t ____lcOp_2; // System.Int32 System.Text.RegularExpressions.RegexCharClass_LowerCaseMapping::_data int32_t ____data_3; public: inline static int32_t get_offset_of__chMin_0() { return static_cast<int32_t>(offsetof(LowerCaseMapping_t3F087D71A4D7A309FD5492CE33501FD4F4709D7B, ____chMin_0)); } inline Il2CppChar get__chMin_0() const { return ____chMin_0; } inline Il2CppChar* get_address_of__chMin_0() { return &____chMin_0; } inline void set__chMin_0(Il2CppChar value) { ____chMin_0 = value; } inline static int32_t get_offset_of__chMax_1() { return static_cast<int32_t>(offsetof(LowerCaseMapping_t3F087D71A4D7A309FD5492CE33501FD4F4709D7B, ____chMax_1)); } inline Il2CppChar get__chMax_1() const { return ____chMax_1; } inline Il2CppChar* get_address_of__chMax_1() { return &____chMax_1; } inline void set__chMax_1(Il2CppChar value) { ____chMax_1 = value; } inline static int32_t get_offset_of__lcOp_2() { return static_cast<int32_t>(offsetof(LowerCaseMapping_t3F087D71A4D7A309FD5492CE33501FD4F4709D7B, ____lcOp_2)); } inline int32_t get__lcOp_2() const { return ____lcOp_2; } inline int32_t* get_address_of__lcOp_2() { return &____lcOp_2; } inline void set__lcOp_2(int32_t value) { ____lcOp_2 = value; } inline static int32_t get_offset_of__data_3() { return static_cast<int32_t>(offsetof(LowerCaseMapping_t3F087D71A4D7A309FD5492CE33501FD4F4709D7B, ____data_3)); } inline int32_t get__data_3() const { return ____data_3; } inline int32_t* get_address_of__data_3() { return &____data_3; } inline void set__data_3(int32_t value) { ____data_3 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Text.RegularExpressions.RegexCharClass/LowerCaseMapping struct LowerCaseMapping_t3F087D71A4D7A309FD5492CE33501FD4F4709D7B_marshaled_pinvoke { uint8_t ____chMin_0; uint8_t ____chMax_1; int32_t ____lcOp_2; int32_t ____data_3; }; // Native definition for COM marshalling of System.Text.RegularExpressions.RegexCharClass/LowerCaseMapping struct LowerCaseMapping_t3F087D71A4D7A309FD5492CE33501FD4F4709D7B_marshaled_com { uint8_t ____chMin_0; uint8_t ____chMax_1; int32_t ____lcOp_2; int32_t ____data_3; }; #endif // LOWERCASEMAPPING_T3F087D71A4D7A309FD5492CE33501FD4F4709D7B_H #ifndef REGEXINTERPRETER_TCFD7D68662C4B174087DA02FB6119836DD2EA7DA_H #define REGEXINTERPRETER_TCFD7D68662C4B174087DA02FB6119836DD2EA7DA_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Text.RegularExpressions.RegexInterpreter struct RegexInterpreter_tCFD7D68662C4B174087DA02FB6119836DD2EA7DA : public RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0 { public: // System.Int32 System.Text.RegularExpressions.RegexInterpreter::runoperator int32_t ___runoperator_18; // System.Int32[] System.Text.RegularExpressions.RegexInterpreter::runcodes Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* ___runcodes_19; // System.Int32 System.Text.RegularExpressions.RegexInterpreter::runcodepos int32_t ___runcodepos_20; // System.String[] System.Text.RegularExpressions.RegexInterpreter::runstrings StringU5BU5D_t933FB07893230EA91C40FF900D5400665E87B14E* ___runstrings_21; // System.Text.RegularExpressions.RegexCode System.Text.RegularExpressions.RegexInterpreter::runcode RegexCode_t12846533CAD1E4221CEDF5A4D15D4D649EA688FA * ___runcode_22; // System.Text.RegularExpressions.RegexPrefix System.Text.RegularExpressions.RegexInterpreter::runfcPrefix RegexPrefix_tACADB52E91EFEB63B5EF7A1850634604F98FEE67 * ___runfcPrefix_23; // System.Text.RegularExpressions.RegexBoyerMoore System.Text.RegularExpressions.RegexInterpreter::runbmPrefix RegexBoyerMoore_t37ED99A3CC25068E4D3DE4517835CFFCCF2FA1EB * ___runbmPrefix_24; // System.Int32 System.Text.RegularExpressions.RegexInterpreter::runanchors int32_t ___runanchors_25; // System.Boolean System.Text.RegularExpressions.RegexInterpreter::runrtl bool ___runrtl_26; // System.Boolean System.Text.RegularExpressions.RegexInterpreter::runci bool ___runci_27; // System.Globalization.CultureInfo System.Text.RegularExpressions.RegexInterpreter::runculture CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F * ___runculture_28; public: inline static int32_t get_offset_of_runoperator_18() { return static_cast<int32_t>(offsetof(RegexInterpreter_tCFD7D68662C4B174087DA02FB6119836DD2EA7DA, ___runoperator_18)); } inline int32_t get_runoperator_18() const { return ___runoperator_18; } inline int32_t* get_address_of_runoperator_18() { return &___runoperator_18; } inline void set_runoperator_18(int32_t value) { ___runoperator_18 = value; } inline static int32_t get_offset_of_runcodes_19() { return static_cast<int32_t>(offsetof(RegexInterpreter_tCFD7D68662C4B174087DA02FB6119836DD2EA7DA, ___runcodes_19)); } inline Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* get_runcodes_19() const { return ___runcodes_19; } inline Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83** get_address_of_runcodes_19() { return &___runcodes_19; } inline void set_runcodes_19(Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* value) { ___runcodes_19 = value; Il2CppCodeGenWriteBarrier((&___runcodes_19), value); } inline static int32_t get_offset_of_runcodepos_20() { return static_cast<int32_t>(offsetof(RegexInterpreter_tCFD7D68662C4B174087DA02FB6119836DD2EA7DA, ___runcodepos_20)); } inline int32_t get_runcodepos_20() const { return ___runcodepos_20; } inline int32_t* get_address_of_runcodepos_20() { return &___runcodepos_20; } inline void set_runcodepos_20(int32_t value) { ___runcodepos_20 = value; } inline static int32_t get_offset_of_runstrings_21() { return static_cast<int32_t>(offsetof(RegexInterpreter_tCFD7D68662C4B174087DA02FB6119836DD2EA7DA, ___runstrings_21)); } inline StringU5BU5D_t933FB07893230EA91C40FF900D5400665E87B14E* get_runstrings_21() const { return ___runstrings_21; } inline StringU5BU5D_t933FB07893230EA91C40FF900D5400665E87B14E** get_address_of_runstrings_21() { return &___runstrings_21; } inline void set_runstrings_21(StringU5BU5D_t933FB07893230EA91C40FF900D5400665E87B14E* value) { ___runstrings_21 = value; Il2CppCodeGenWriteBarrier((&___runstrings_21), value); } inline static int32_t get_offset_of_runcode_22() { return static_cast<int32_t>(offsetof(RegexInterpreter_tCFD7D68662C4B174087DA02FB6119836DD2EA7DA, ___runcode_22)); } inline RegexCode_t12846533CAD1E4221CEDF5A4D15D4D649EA688FA * get_runcode_22() const { return ___runcode_22; } inline RegexCode_t12846533CAD1E4221CEDF5A4D15D4D649EA688FA ** get_address_of_runcode_22() { return &___runcode_22; } inline void set_runcode_22(RegexCode_t12846533CAD1E4221CEDF5A4D15D4D649EA688FA * value) { ___runcode_22 = value; Il2CppCodeGenWriteBarrier((&___runcode_22), value); } inline static int32_t get_offset_of_runfcPrefix_23() { return static_cast<int32_t>(offsetof(RegexInterpreter_tCFD7D68662C4B174087DA02FB6119836DD2EA7DA, ___runfcPrefix_23)); } inline RegexPrefix_tACADB52E91EFEB63B5EF7A1850634604F98FEE67 * get_runfcPrefix_23() const { return ___runfcPrefix_23; } inline RegexPrefix_tACADB52E91EFEB63B5EF7A1850634604F98FEE67 ** get_address_of_runfcPrefix_23() { return &___runfcPrefix_23; } inline void set_runfcPrefix_23(RegexPrefix_tACADB52E91EFEB63B5EF7A1850634604F98FEE67 * value) { ___runfcPrefix_23 = value; Il2CppCodeGenWriteBarrier((&___runfcPrefix_23), value); } inline static int32_t get_offset_of_runbmPrefix_24() { return static_cast<int32_t>(offsetof(RegexInterpreter_tCFD7D68662C4B174087DA02FB6119836DD2EA7DA, ___runbmPrefix_24)); } inline RegexBoyerMoore_t37ED99A3CC25068E4D3DE4517835CFFCCF2FA1EB * get_runbmPrefix_24() const { return ___runbmPrefix_24; } inline RegexBoyerMoore_t37ED99A3CC25068E4D3DE4517835CFFCCF2FA1EB ** get_address_of_runbmPrefix_24() { return &___runbmPrefix_24; } inline void set_runbmPrefix_24(RegexBoyerMoore_t37ED99A3CC25068E4D3DE4517835CFFCCF2FA1EB * value) { ___runbmPrefix_24 = value; Il2CppCodeGenWriteBarrier((&___runbmPrefix_24), value); } inline static int32_t get_offset_of_runanchors_25() { return static_cast<int32_t>(offsetof(RegexInterpreter_tCFD7D68662C4B174087DA02FB6119836DD2EA7DA, ___runanchors_25)); } inline int32_t get_runanchors_25() const { return ___runanchors_25; } inline int32_t* get_address_of_runanchors_25() { return &___runanchors_25; } inline void set_runanchors_25(int32_t value) { ___runanchors_25 = value; } inline static int32_t get_offset_of_runrtl_26() { return static_cast<int32_t>(offsetof(RegexInterpreter_tCFD7D68662C4B174087DA02FB6119836DD2EA7DA, ___runrtl_26)); } inline bool get_runrtl_26() const { return ___runrtl_26; } inline bool* get_address_of_runrtl_26() { return &___runrtl_26; } inline void set_runrtl_26(bool value) { ___runrtl_26 = value; } inline static int32_t get_offset_of_runci_27() { return static_cast<int32_t>(offsetof(RegexInterpreter_tCFD7D68662C4B174087DA02FB6119836DD2EA7DA, ___runci_27)); } inline bool get_runci_27() const { return ___runci_27; } inline bool* get_address_of_runci_27() { return &___runci_27; } inline void set_runci_27(bool value) { ___runci_27 = value; } inline static int32_t get_offset_of_runculture_28() { return static_cast<int32_t>(offsetof(RegexInterpreter_tCFD7D68662C4B174087DA02FB6119836DD2EA7DA, ___runculture_28)); } inline CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F * get_runculture_28() const { return ___runculture_28; } inline CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F ** get_address_of_runculture_28() { return &___runculture_28; } inline void set_runculture_28(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F * value) { ___runculture_28 = value; Il2CppCodeGenWriteBarrier((&___runculture_28), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // REGEXINTERPRETER_TCFD7D68662C4B174087DA02FB6119836DD2EA7DA_H #ifndef U3CPRIVATEIMPLEMENTATIONDETAILSU3E_TD3F45A95FC1F3A32916F221D83F290D182AD6291_H #define U3CPRIVATEIMPLEMENTATIONDETAILSU3E_TD3F45A95FC1F3A32916F221D83F290D182AD6291_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <PrivateImplementationDetails> struct U3CPrivateImplementationDetailsU3E_tD3F45A95FC1F3A32916F221D83F290D182AD6291 : public RuntimeObject { public: public: }; struct U3CPrivateImplementationDetailsU3E_tD3F45A95FC1F3A32916F221D83F290D182AD6291_StaticFields { public: // <PrivateImplementationDetails>___StaticArrayInitTypeSizeU3D32 <PrivateImplementationDetails>::59F5BD34B6C013DEACC784F69C67E95150033A84 __StaticArrayInitTypeSizeU3D32_t5300E5FCBD58716E8A4EBB9470E4FAE1A0A964FA ___59F5BD34B6C013DEACC784F69C67E95150033A84_0; // <PrivateImplementationDetails>___StaticArrayInitTypeSizeU3D32 <PrivateImplementationDetails>::C02C28AFEBE998F767E4AF43E3BE8F5E9FA11536 __StaticArrayInitTypeSizeU3D32_t5300E5FCBD58716E8A4EBB9470E4FAE1A0A964FA ___C02C28AFEBE998F767E4AF43E3BE8F5E9FA11536_1; // <PrivateImplementationDetails>___StaticArrayInitTypeSizeU3D128 <PrivateImplementationDetails>::CCEEADA43268372341F81AE0C9208C6856441C04 __StaticArrayInitTypeSizeU3D128_t4A42759E6E25B0C61E6036A661F4344DE92C2905 ___CCEEADA43268372341F81AE0C9208C6856441C04_2; // System.Int64 <PrivateImplementationDetails>::E5BC1BAFADE1862DD6E0B9FB632BFAA6C3873A78 int64_t ___E5BC1BAFADE1862DD6E0B9FB632BFAA6C3873A78_3; public: inline static int32_t get_offset_of_U359F5BD34B6C013DEACC784F69C67E95150033A84_0() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_tD3F45A95FC1F3A32916F221D83F290D182AD6291_StaticFields, ___59F5BD34B6C013DEACC784F69C67E95150033A84_0)); } inline __StaticArrayInitTypeSizeU3D32_t5300E5FCBD58716E8A4EBB9470E4FAE1A0A964FA get_U359F5BD34B6C013DEACC784F69C67E95150033A84_0() const { return ___59F5BD34B6C013DEACC784F69C67E95150033A84_0; } inline __StaticArrayInitTypeSizeU3D32_t5300E5FCBD58716E8A4EBB9470E4FAE1A0A964FA * get_address_of_U359F5BD34B6C013DEACC784F69C67E95150033A84_0() { return &___59F5BD34B6C013DEACC784F69C67E95150033A84_0; } inline void set_U359F5BD34B6C013DEACC784F69C67E95150033A84_0(__StaticArrayInitTypeSizeU3D32_t5300E5FCBD58716E8A4EBB9470E4FAE1A0A964FA value) { ___59F5BD34B6C013DEACC784F69C67E95150033A84_0 = value; } inline static int32_t get_offset_of_C02C28AFEBE998F767E4AF43E3BE8F5E9FA11536_1() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_tD3F45A95FC1F3A32916F221D83F290D182AD6291_StaticFields, ___C02C28AFEBE998F767E4AF43E3BE8F5E9FA11536_1)); } inline __StaticArrayInitTypeSizeU3D32_t5300E5FCBD58716E8A4EBB9470E4FAE1A0A964FA get_C02C28AFEBE998F767E4AF43E3BE8F5E9FA11536_1() const { return ___C02C28AFEBE998F767E4AF43E3BE8F5E9FA11536_1; } inline __StaticArrayInitTypeSizeU3D32_t5300E5FCBD58716E8A4EBB9470E4FAE1A0A964FA * get_address_of_C02C28AFEBE998F767E4AF43E3BE8F5E9FA11536_1() { return &___C02C28AFEBE998F767E4AF43E3BE8F5E9FA11536_1; } inline void set_C02C28AFEBE998F767E4AF43E3BE8F5E9FA11536_1(__StaticArrayInitTypeSizeU3D32_t5300E5FCBD58716E8A4EBB9470E4FAE1A0A964FA value) { ___C02C28AFEBE998F767E4AF43E3BE8F5E9FA11536_1 = value; } inline static int32_t get_offset_of_CCEEADA43268372341F81AE0C9208C6856441C04_2() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_tD3F45A95FC1F3A32916F221D83F290D182AD6291_StaticFields, ___CCEEADA43268372341F81AE0C9208C6856441C04_2)); } inline __StaticArrayInitTypeSizeU3D128_t4A42759E6E25B0C61E6036A661F4344DE92C2905 get_CCEEADA43268372341F81AE0C9208C6856441C04_2() const { return ___CCEEADA43268372341F81AE0C9208C6856441C04_2; } inline __StaticArrayInitTypeSizeU3D128_t4A42759E6E25B0C61E6036A661F4344DE92C2905 * get_address_of_CCEEADA43268372341F81AE0C9208C6856441C04_2() { return &___CCEEADA43268372341F81AE0C9208C6856441C04_2; } inline void set_CCEEADA43268372341F81AE0C9208C6856441C04_2(__StaticArrayInitTypeSizeU3D128_t4A42759E6E25B0C61E6036A661F4344DE92C2905 value) { ___CCEEADA43268372341F81AE0C9208C6856441C04_2 = value; } inline static int32_t get_offset_of_E5BC1BAFADE1862DD6E0B9FB632BFAA6C3873A78_3() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_tD3F45A95FC1F3A32916F221D83F290D182AD6291_StaticFields, ___E5BC1BAFADE1862DD6E0B9FB632BFAA6C3873A78_3)); } inline int64_t get_E5BC1BAFADE1862DD6E0B9FB632BFAA6C3873A78_3() const { return ___E5BC1BAFADE1862DD6E0B9FB632BFAA6C3873A78_3; } inline int64_t* get_address_of_E5BC1BAFADE1862DD6E0B9FB632BFAA6C3873A78_3() { return &___E5BC1BAFADE1862DD6E0B9FB632BFAA6C3873A78_3; } inline void set_E5BC1BAFADE1862DD6E0B9FB632BFAA6C3873A78_3(int64_t value) { ___E5BC1BAFADE1862DD6E0B9FB632BFAA6C3873A78_3 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // U3CPRIVATEIMPLEMENTATIONDETAILSU3E_TD3F45A95FC1F3A32916F221D83F290D182AD6291_H #ifndef EDITORBROWSABLESTATE_T8EAF9BADAAE7DA735C235280DF4B8974EAA39C1B_H #define EDITORBROWSABLESTATE_T8EAF9BADAAE7DA735C235280DF4B8974EAA39C1B_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ComponentModel.EditorBrowsableState struct EditorBrowsableState_t8EAF9BADAAE7DA735C235280DF4B8974EAA39C1B { public: // System.Int32 System.ComponentModel.EditorBrowsableState::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(EditorBrowsableState_t8EAF9BADAAE7DA735C235280DF4B8974EAA39C1B, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // EDITORBROWSABLESTATE_T8EAF9BADAAE7DA735C235280DF4B8974EAA39C1B_H #ifndef TYPECONVERTER_T8306AE03734853B551DDF089C1F17836A7764DBB_H #define TYPECONVERTER_T8306AE03734853B551DDF089C1F17836A7764DBB_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ComponentModel.TypeConverter struct TypeConverter_t8306AE03734853B551DDF089C1F17836A7764DBB : public RuntimeObject { public: public: }; struct TypeConverter_t8306AE03734853B551DDF089C1F17836A7764DBB_StaticFields { public: // System.Boolean modreq(System.Runtime.CompilerServices.IsVolatile) System.ComponentModel.TypeConverter::useCompatibleTypeConversion bool ___useCompatibleTypeConversion_1; public: inline static int32_t get_offset_of_useCompatibleTypeConversion_1() { return static_cast<int32_t>(offsetof(TypeConverter_t8306AE03734853B551DDF089C1F17836A7764DBB_StaticFields, ___useCompatibleTypeConversion_1)); } inline bool get_useCompatibleTypeConversion_1() const { return ___useCompatibleTypeConversion_1; } inline bool* get_address_of_useCompatibleTypeConversion_1() { return &___useCompatibleTypeConversion_1; } inline void set_useCompatibleTypeConversion_1(bool value) { ___useCompatibleTypeConversion_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TYPECONVERTER_T8306AE03734853B551DDF089C1F17836A7764DBB_H #ifndef INVALIDOPERATIONEXCEPTION_T0530E734D823F78310CAFAFA424CA5164D93A1F1_H #define INVALIDOPERATIONEXCEPTION_T0530E734D823F78310CAFAFA424CA5164D93A1F1_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.InvalidOperationException struct InvalidOperationException_t0530E734D823F78310CAFAFA424CA5164D93A1F1 : public SystemException_t5380468142AA850BE4A341D7AF3EAB9C78746782 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INVALIDOPERATIONEXCEPTION_T0530E734D823F78310CAFAFA424CA5164D93A1F1_H #ifndef BYPASSELEMENTCOLLECTION_T5CCE032F76311FCEFC3128DA5A88D25568A234A7_H #define BYPASSELEMENTCOLLECTION_T5CCE032F76311FCEFC3128DA5A88D25568A234A7_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Net.Configuration.BypassElementCollection struct BypassElementCollection_t5CCE032F76311FCEFC3128DA5A88D25568A234A7 : public ConfigurationElementCollection_tB0DA3194B9C1528D2627B291C79B560C68A78FCC { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BYPASSELEMENTCOLLECTION_T5CCE032F76311FCEFC3128DA5A88D25568A234A7_H #ifndef CONNECTIONMANAGEMENTELEMENTCOLLECTION_T83F843AEC2D2354836CC863E346FE2ECFEED2572_H #define CONNECTIONMANAGEMENTELEMENTCOLLECTION_T83F843AEC2D2354836CC863E346FE2ECFEED2572_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Net.Configuration.ConnectionManagementElementCollection struct ConnectionManagementElementCollection_t83F843AEC2D2354836CC863E346FE2ECFEED2572 : public ConfigurationElementCollection_tB0DA3194B9C1528D2627B291C79B560C68A78FCC { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CONNECTIONMANAGEMENTELEMENTCOLLECTION_T83F843AEC2D2354836CC863E346FE2ECFEED2572_H #ifndef CONNECTIONMANAGEMENTSECTION_TA88F9BAD144E401AB524A9579B50050140592447_H #define CONNECTIONMANAGEMENTSECTION_TA88F9BAD144E401AB524A9579B50050140592447_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Net.Configuration.ConnectionManagementSection struct ConnectionManagementSection_tA88F9BAD144E401AB524A9579B50050140592447 : public ConfigurationSection_t044F68052218C8000611AE9ADD5F66E62A632B34 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CONNECTIONMANAGEMENTSECTION_TA88F9BAD144E401AB524A9579B50050140592447_H #ifndef DEFAULTPROXYSECTION_TB752851846FC0CEBA83C36C2BF6553211029AA3B_H #define DEFAULTPROXYSECTION_TB752851846FC0CEBA83C36C2BF6553211029AA3B_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Net.Configuration.DefaultProxySection struct DefaultProxySection_tB752851846FC0CEBA83C36C2BF6553211029AA3B : public ConfigurationSection_t044F68052218C8000611AE9ADD5F66E62A632B34 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DEFAULTPROXYSECTION_TB752851846FC0CEBA83C36C2BF6553211029AA3B_H #ifndef SETTINGSSECTION_T8BECD0EB76F1865B33D072DD368676A8D51840B3_H #define SETTINGSSECTION_T8BECD0EB76F1865B33D072DD368676A8D51840B3_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Net.Configuration.SettingsSection struct SettingsSection_t8BECD0EB76F1865B33D072DD368676A8D51840B3 : public ConfigurationSection_t044F68052218C8000611AE9ADD5F66E62A632B34 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SETTINGSSECTION_T8BECD0EB76F1865B33D072DD368676A8D51840B3_H #ifndef WEBREQUESTMODULEELEMENTCOLLECTION_T2A993B681E96AAF6A96CCB0458F0F0B99BFF51BE_H #define WEBREQUESTMODULEELEMENTCOLLECTION_T2A993B681E96AAF6A96CCB0458F0F0B99BFF51BE_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Net.Configuration.WebRequestModuleElementCollection struct WebRequestModuleElementCollection_t2A993B681E96AAF6A96CCB0458F0F0B99BFF51BE : public ConfigurationElementCollection_tB0DA3194B9C1528D2627B291C79B560C68A78FCC { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // WEBREQUESTMODULEELEMENTCOLLECTION_T2A993B681E96AAF6A96CCB0458F0F0B99BFF51BE_H #ifndef WEBREQUESTMODULESSECTION_T5E031F632797D2C7F0D394BCEE4BD0DF0ECA81BC_H #define WEBREQUESTMODULESSECTION_T5E031F632797D2C7F0D394BCEE4BD0DF0ECA81BC_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Net.Configuration.WebRequestModulesSection struct WebRequestModulesSection_t5E031F632797D2C7F0D394BCEE4BD0DF0ECA81BC : public ConfigurationSection_t044F68052218C8000611AE9ADD5F66E62A632B34 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // WEBREQUESTMODULESSECTION_T5E031F632797D2C7F0D394BCEE4BD0DF0ECA81BC_H #ifndef ADDRESSFAMILY_TFA4F79FA7F299EBDF507F4811E6E5C3EEBF0850E_H #define ADDRESSFAMILY_TFA4F79FA7F299EBDF507F4811E6E5C3EEBF0850E_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Net.Sockets.AddressFamily struct AddressFamily_tFA4F79FA7F299EBDF507F4811E6E5C3EEBF0850E { public: // System.Int32 System.Net.Sockets.AddressFamily::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(AddressFamily_tFA4F79FA7F299EBDF507F4811E6E5C3EEBF0850E, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ADDRESSFAMILY_TFA4F79FA7F299EBDF507F4811E6E5C3EEBF0850E_H #ifndef SOCKETERROR_T0157BEC7F0A26C8FC31D392B2B7C6CFCD695D5E7_H #define SOCKETERROR_T0157BEC7F0A26C8FC31D392B2B7C6CFCD695D5E7_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Net.Sockets.SocketError struct SocketError_t0157BEC7F0A26C8FC31D392B2B7C6CFCD695D5E7 { public: // System.Int32 System.Net.Sockets.SocketError::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(SocketError_t0157BEC7F0A26C8FC31D392B2B7C6CFCD695D5E7, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SOCKETERROR_T0157BEC7F0A26C8FC31D392B2B7C6CFCD695D5E7_H #ifndef EXTERNALEXCEPTION_T68841FD169C0CB00CC950EDA7E2A59540D65B1CE_H #define EXTERNALEXCEPTION_T68841FD169C0CB00CC950EDA7E2A59540D65B1CE_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Runtime.InteropServices.ExternalException struct ExternalException_t68841FD169C0CB00CC950EDA7E2A59540D65B1CE : public SystemException_t5380468142AA850BE4A341D7AF3EAB9C78746782 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // EXTERNALEXCEPTION_T68841FD169C0CB00CC950EDA7E2A59540D65B1CE_H #ifndef ASNDECODESTATUS_T83139F58FFE08CE7DBCB990C9F30D2F2CA5BC0BB_H #define ASNDECODESTATUS_T83139F58FFE08CE7DBCB990C9F30D2F2CA5BC0BB_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Security.Cryptography.AsnDecodeStatus struct AsnDecodeStatus_t83139F58FFE08CE7DBCB990C9F30D2F2CA5BC0BB { public: // System.Int32 System.Security.Cryptography.AsnDecodeStatus::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(AsnDecodeStatus_t83139F58FFE08CE7DBCB990C9F30D2F2CA5BC0BB, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ASNDECODESTATUS_T83139F58FFE08CE7DBCB990C9F30D2F2CA5BC0BB_H #ifndef OIDGROUP_T9A99D3013C1B94CB060656F30C39E893E75FAD6B_H #define OIDGROUP_T9A99D3013C1B94CB060656F30C39E893E75FAD6B_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Security.Cryptography.OidGroup struct OidGroup_t9A99D3013C1B94CB060656F30C39E893E75FAD6B { public: // System.Int32 System.Security.Cryptography.OidGroup::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(OidGroup_t9A99D3013C1B94CB060656F30C39E893E75FAD6B, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // OIDGROUP_T9A99D3013C1B94CB060656F30C39E893E75FAD6B_H #ifndef X509KEYUSAGEFLAGS_TAD6560EDDEB746BA983AE4E7ABC237A6178D6437_H #define X509KEYUSAGEFLAGS_TAD6560EDDEB746BA983AE4E7ABC237A6178D6437_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Security.Cryptography.X509Certificates.X509KeyUsageFlags struct X509KeyUsageFlags_tAD6560EDDEB746BA983AE4E7ABC237A6178D6437 { public: // System.Int32 System.Security.Cryptography.X509Certificates.X509KeyUsageFlags::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(X509KeyUsageFlags_tAD6560EDDEB746BA983AE4E7ABC237A6178D6437, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // X509KEYUSAGEFLAGS_TAD6560EDDEB746BA983AE4E7ABC237A6178D6437_H #ifndef X509SUBJECTKEYIDENTIFIERHASHALGORITHM_T7928324BFDBB7B255970D50D0D8972FDFC981A0C_H #define X509SUBJECTKEYIDENTIFIERHASHALGORITHM_T7928324BFDBB7B255970D50D0D8972FDFC981A0C_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierHashAlgorithm struct X509SubjectKeyIdentifierHashAlgorithm_t7928324BFDBB7B255970D50D0D8972FDFC981A0C { public: // System.Int32 System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierHashAlgorithm::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(X509SubjectKeyIdentifierHashAlgorithm_t7928324BFDBB7B255970D50D0D8972FDFC981A0C, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // X509SUBJECTKEYIDENTIFIERHASHALGORITHM_T7928324BFDBB7B255970D50D0D8972FDFC981A0C_H #ifndef MATCH_TE447871AB59EED3642F31EB9559D162C2977EBB5_H #define MATCH_TE447871AB59EED3642F31EB9559D162C2977EBB5_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Text.RegularExpressions.Match struct Match_tE447871AB59EED3642F31EB9559D162C2977EBB5 : public Group_tB4759D0385925B2C8C14ED3FCD5D2F43CFBD0443 { public: // System.Text.RegularExpressions.Regex System.Text.RegularExpressions.Match::_regex Regex_tFD46E63A462E852189FD6AB4E2B0B67C4D8FDBDF * ____regex_8; // System.Int32 System.Text.RegularExpressions.Match::_textbeg int32_t ____textbeg_9; // System.Int32 System.Text.RegularExpressions.Match::_textpos int32_t ____textpos_10; // System.Int32 System.Text.RegularExpressions.Match::_textend int32_t ____textend_11; // System.Int32 System.Text.RegularExpressions.Match::_textstart int32_t ____textstart_12; // System.Int32[][] System.Text.RegularExpressions.Match::_matches Int32U5BU5DU5BU5D_tCA34E042D233821D51B4DAFB480EE602F2DBEF43* ____matches_13; // System.Int32[] System.Text.RegularExpressions.Match::_matchcount Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* ____matchcount_14; // System.Boolean System.Text.RegularExpressions.Match::_balancing bool ____balancing_15; public: inline static int32_t get_offset_of__regex_8() { return static_cast<int32_t>(offsetof(Match_tE447871AB59EED3642F31EB9559D162C2977EBB5, ____regex_8)); } inline Regex_tFD46E63A462E852189FD6AB4E2B0B67C4D8FDBDF * get__regex_8() const { return ____regex_8; } inline Regex_tFD46E63A462E852189FD6AB4E2B0B67C4D8FDBDF ** get_address_of__regex_8() { return &____regex_8; } inline void set__regex_8(Regex_tFD46E63A462E852189FD6AB4E2B0B67C4D8FDBDF * value) { ____regex_8 = value; Il2CppCodeGenWriteBarrier((&____regex_8), value); } inline static int32_t get_offset_of__textbeg_9() { return static_cast<int32_t>(offsetof(Match_tE447871AB59EED3642F31EB9559D162C2977EBB5, ____textbeg_9)); } inline int32_t get__textbeg_9() const { return ____textbeg_9; } inline int32_t* get_address_of__textbeg_9() { return &____textbeg_9; } inline void set__textbeg_9(int32_t value) { ____textbeg_9 = value; } inline static int32_t get_offset_of__textpos_10() { return static_cast<int32_t>(offsetof(Match_tE447871AB59EED3642F31EB9559D162C2977EBB5, ____textpos_10)); } inline int32_t get__textpos_10() const { return ____textpos_10; } inline int32_t* get_address_of__textpos_10() { return &____textpos_10; } inline void set__textpos_10(int32_t value) { ____textpos_10 = value; } inline static int32_t get_offset_of__textend_11() { return static_cast<int32_t>(offsetof(Match_tE447871AB59EED3642F31EB9559D162C2977EBB5, ____textend_11)); } inline int32_t get__textend_11() const { return ____textend_11; } inline int32_t* get_address_of__textend_11() { return &____textend_11; } inline void set__textend_11(int32_t value) { ____textend_11 = value; } inline static int32_t get_offset_of__textstart_12() { return static_cast<int32_t>(offsetof(Match_tE447871AB59EED3642F31EB9559D162C2977EBB5, ____textstart_12)); } inline int32_t get__textstart_12() const { return ____textstart_12; } inline int32_t* get_address_of__textstart_12() { return &____textstart_12; } inline void set__textstart_12(int32_t value) { ____textstart_12 = value; } inline static int32_t get_offset_of__matches_13() { return static_cast<int32_t>(offsetof(Match_tE447871AB59EED3642F31EB9559D162C2977EBB5, ____matches_13)); } inline Int32U5BU5DU5BU5D_tCA34E042D233821D51B4DAFB480EE602F2DBEF43* get__matches_13() const { return ____matches_13; } inline Int32U5BU5DU5BU5D_tCA34E042D233821D51B4DAFB480EE602F2DBEF43** get_address_of__matches_13() { return &____matches_13; } inline void set__matches_13(Int32U5BU5DU5BU5D_tCA34E042D233821D51B4DAFB480EE602F2DBEF43* value) { ____matches_13 = value; Il2CppCodeGenWriteBarrier((&____matches_13), value); } inline static int32_t get_offset_of__matchcount_14() { return static_cast<int32_t>(offsetof(Match_tE447871AB59EED3642F31EB9559D162C2977EBB5, ____matchcount_14)); } inline Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* get__matchcount_14() const { return ____matchcount_14; } inline Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83** get_address_of__matchcount_14() { return &____matchcount_14; } inline void set__matchcount_14(Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* value) { ____matchcount_14 = value; Il2CppCodeGenWriteBarrier((&____matchcount_14), value); } inline static int32_t get_offset_of__balancing_15() { return static_cast<int32_t>(offsetof(Match_tE447871AB59EED3642F31EB9559D162C2977EBB5, ____balancing_15)); } inline bool get__balancing_15() const { return ____balancing_15; } inline bool* get_address_of__balancing_15() { return &____balancing_15; } inline void set__balancing_15(bool value) { ____balancing_15 = value; } }; struct Match_tE447871AB59EED3642F31EB9559D162C2977EBB5_StaticFields { public: // System.Text.RegularExpressions.Match System.Text.RegularExpressions.Match::_empty Match_tE447871AB59EED3642F31EB9559D162C2977EBB5 * ____empty_7; public: inline static int32_t get_offset_of__empty_7() { return static_cast<int32_t>(offsetof(Match_tE447871AB59EED3642F31EB9559D162C2977EBB5_StaticFields, ____empty_7)); } inline Match_tE447871AB59EED3642F31EB9559D162C2977EBB5 * get__empty_7() const { return ____empty_7; } inline Match_tE447871AB59EED3642F31EB9559D162C2977EBB5 ** get_address_of__empty_7() { return &____empty_7; } inline void set__empty_7(Match_tE447871AB59EED3642F31EB9559D162C2977EBB5 * value) { ____empty_7 = value; Il2CppCodeGenWriteBarrier((&____empty_7), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // MATCH_TE447871AB59EED3642F31EB9559D162C2977EBB5_H #ifndef REGEXOPTIONS_T9A6138CDA9C60924D503C584095349F008C52EA1_H #define REGEXOPTIONS_T9A6138CDA9C60924D503C584095349F008C52EA1_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Text.RegularExpressions.RegexOptions struct RegexOptions_t9A6138CDA9C60924D503C584095349F008C52EA1 { public: // System.Int32 System.Text.RegularExpressions.RegexOptions::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(RegexOptions_t9A6138CDA9C60924D503C584095349F008C52EA1, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // REGEXOPTIONS_T9A6138CDA9C60924D503C584095349F008C52EA1_H #ifndef TIMESPAN_TA8069278ACE8A74D6DF7D514A9CD4432433F64C4_H #define TIMESPAN_TA8069278ACE8A74D6DF7D514A9CD4432433F64C4_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.TimeSpan struct TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 { public: // System.Int64 System.TimeSpan::_ticks int64_t ____ticks_3; public: inline static int32_t get_offset_of__ticks_3() { return static_cast<int32_t>(offsetof(TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4, ____ticks_3)); } inline int64_t get__ticks_3() const { return ____ticks_3; } inline int64_t* get_address_of__ticks_3() { return &____ticks_3; } inline void set__ticks_3(int64_t value) { ____ticks_3 = value; } }; struct TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4_StaticFields { public: // System.TimeSpan System.TimeSpan::Zero TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 ___Zero_0; // System.TimeSpan System.TimeSpan::MaxValue TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 ___MaxValue_1; // System.TimeSpan System.TimeSpan::MinValue TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 ___MinValue_2; // System.Boolean modreq(System.Runtime.CompilerServices.IsVolatile) System.TimeSpan::_legacyConfigChecked bool ____legacyConfigChecked_4; // System.Boolean modreq(System.Runtime.CompilerServices.IsVolatile) System.TimeSpan::_legacyMode bool ____legacyMode_5; public: inline static int32_t get_offset_of_Zero_0() { return static_cast<int32_t>(offsetof(TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4_StaticFields, ___Zero_0)); } inline TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 get_Zero_0() const { return ___Zero_0; } inline TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 * get_address_of_Zero_0() { return &___Zero_0; } inline void set_Zero_0(TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 value) { ___Zero_0 = value; } inline static int32_t get_offset_of_MaxValue_1() { return static_cast<int32_t>(offsetof(TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4_StaticFields, ___MaxValue_1)); } inline TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 get_MaxValue_1() const { return ___MaxValue_1; } inline TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 * get_address_of_MaxValue_1() { return &___MaxValue_1; } inline void set_MaxValue_1(TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 value) { ___MaxValue_1 = value; } inline static int32_t get_offset_of_MinValue_2() { return static_cast<int32_t>(offsetof(TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4_StaticFields, ___MinValue_2)); } inline TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 get_MinValue_2() const { return ___MinValue_2; } inline TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 * get_address_of_MinValue_2() { return &___MinValue_2; } inline void set_MinValue_2(TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 value) { ___MinValue_2 = value; } inline static int32_t get_offset_of__legacyConfigChecked_4() { return static_cast<int32_t>(offsetof(TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4_StaticFields, ____legacyConfigChecked_4)); } inline bool get__legacyConfigChecked_4() const { return ____legacyConfigChecked_4; } inline bool* get_address_of__legacyConfigChecked_4() { return &____legacyConfigChecked_4; } inline void set__legacyConfigChecked_4(bool value) { ____legacyConfigChecked_4 = value; } inline static int32_t get_offset_of__legacyMode_5() { return static_cast<int32_t>(offsetof(TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4_StaticFields, ____legacyMode_5)); } inline bool get__legacyMode_5() const { return ____legacyMode_5; } inline bool* get_address_of__legacyMode_5() { return &____legacyMode_5; } inline void set__legacyMode_5(bool value) { ____legacyMode_5 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TIMESPAN_TA8069278ACE8A74D6DF7D514A9CD4432433F64C4_H #ifndef TIMEOUTEXCEPTION_T15A6E9A2A5819966712B5CFAF756BAEA40E3B1B7_H #define TIMEOUTEXCEPTION_T15A6E9A2A5819966712B5CFAF756BAEA40E3B1B7_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.TimeoutException struct TimeoutException_t15A6E9A2A5819966712B5CFAF756BAEA40E3B1B7 : public SystemException_t5380468142AA850BE4A341D7AF3EAB9C78746782 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TIMEOUTEXCEPTION_T15A6E9A2A5819966712B5CFAF756BAEA40E3B1B7_H #ifndef BASENUMBERCONVERTER_T6AF36A2503E7BABF7FB9A8EC05DF8B828491AC63_H #define BASENUMBERCONVERTER_T6AF36A2503E7BABF7FB9A8EC05DF8B828491AC63_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ComponentModel.BaseNumberConverter struct BaseNumberConverter_t6AF36A2503E7BABF7FB9A8EC05DF8B828491AC63 : public TypeConverter_t8306AE03734853B551DDF089C1F17836A7764DBB { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BASENUMBERCONVERTER_T6AF36A2503E7BABF7FB9A8EC05DF8B828491AC63_H #ifndef BOOLEANCONVERTER_TD0D177A9F577915FAA9F6749229672CE8EBAA94C_H #define BOOLEANCONVERTER_TD0D177A9F577915FAA9F6749229672CE8EBAA94C_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ComponentModel.BooleanConverter struct BooleanConverter_tD0D177A9F577915FAA9F6749229672CE8EBAA94C : public TypeConverter_t8306AE03734853B551DDF089C1F17836A7764DBB { public: public: }; struct BooleanConverter_tD0D177A9F577915FAA9F6749229672CE8EBAA94C_StaticFields { public: // System.ComponentModel.TypeConverter_StandardValuesCollection modreq(System.Runtime.CompilerServices.IsVolatile) System.ComponentModel.BooleanConverter::values StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3 * ___values_2; public: inline static int32_t get_offset_of_values_2() { return static_cast<int32_t>(offsetof(BooleanConverter_tD0D177A9F577915FAA9F6749229672CE8EBAA94C_StaticFields, ___values_2)); } inline StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3 * get_values_2() const { return ___values_2; } inline StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3 ** get_address_of_values_2() { return &___values_2; } inline void set_values_2(StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3 * value) { ___values_2 = value; Il2CppCodeGenWriteBarrier((&___values_2), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BOOLEANCONVERTER_TD0D177A9F577915FAA9F6749229672CE8EBAA94C_H #ifndef COLLECTIONCONVERTER_T039E15C433996B0F0F0EB78BEE81F6DE0705F184_H #define COLLECTIONCONVERTER_T039E15C433996B0F0F0EB78BEE81F6DE0705F184_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ComponentModel.CollectionConverter struct CollectionConverter_t039E15C433996B0F0F0EB78BEE81F6DE0705F184 : public TypeConverter_t8306AE03734853B551DDF089C1F17836A7764DBB { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // COLLECTIONCONVERTER_T039E15C433996B0F0F0EB78BEE81F6DE0705F184_H #ifndef EDITORBROWSABLEATTRIBUTE_TF3507DF0AB82A8D54C70D6F7FB4D363DF729D516_H #define EDITORBROWSABLEATTRIBUTE_TF3507DF0AB82A8D54C70D6F7FB4D363DF729D516_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ComponentModel.EditorBrowsableAttribute struct EditorBrowsableAttribute_tF3507DF0AB82A8D54C70D6F7FB4D363DF729D516 : public Attribute_tF048C13FB3C8CFCC53F82290E4A3F621089F9A74 { public: // System.ComponentModel.EditorBrowsableState System.ComponentModel.EditorBrowsableAttribute::browsableState int32_t ___browsableState_0; public: inline static int32_t get_offset_of_browsableState_0() { return static_cast<int32_t>(offsetof(EditorBrowsableAttribute_tF3507DF0AB82A8D54C70D6F7FB4D363DF729D516, ___browsableState_0)); } inline int32_t get_browsableState_0() const { return ___browsableState_0; } inline int32_t* get_address_of_browsableState_0() { return &___browsableState_0; } inline void set_browsableState_0(int32_t value) { ___browsableState_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // EDITORBROWSABLEATTRIBUTE_TF3507DF0AB82A8D54C70D6F7FB4D363DF729D516_H #ifndef ENUMCONVERTER_T5DA4CB27C27A8C37C31B2A4DE0C4C37820638E12_H #define ENUMCONVERTER_T5DA4CB27C27A8C37C31B2A4DE0C4C37820638E12_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ComponentModel.EnumConverter struct EnumConverter_t5DA4CB27C27A8C37C31B2A4DE0C4C37820638E12 : public TypeConverter_t8306AE03734853B551DDF089C1F17836A7764DBB { public: // System.ComponentModel.TypeConverter_StandardValuesCollection System.ComponentModel.EnumConverter::values StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3 * ___values_2; // System.Type System.ComponentModel.EnumConverter::type Type_t * ___type_3; public: inline static int32_t get_offset_of_values_2() { return static_cast<int32_t>(offsetof(EnumConverter_t5DA4CB27C27A8C37C31B2A4DE0C4C37820638E12, ___values_2)); } inline StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3 * get_values_2() const { return ___values_2; } inline StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3 ** get_address_of_values_2() { return &___values_2; } inline void set_values_2(StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3 * value) { ___values_2 = value; Il2CppCodeGenWriteBarrier((&___values_2), value); } inline static int32_t get_offset_of_type_3() { return static_cast<int32_t>(offsetof(EnumConverter_t5DA4CB27C27A8C37C31B2A4DE0C4C37820638E12, ___type_3)); } inline Type_t * get_type_3() const { return ___type_3; } inline Type_t ** get_address_of_type_3() { return &___type_3; } inline void set_type_3(Type_t * value) { ___type_3 = value; Il2CppCodeGenWriteBarrier((&___type_3), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ENUMCONVERTER_T5DA4CB27C27A8C37C31B2A4DE0C4C37820638E12_H #ifndef STRINGCONVERTER_T054FA0796F4C8E951208AFA052D99BCB8E68BED7_H #define STRINGCONVERTER_T054FA0796F4C8E951208AFA052D99BCB8E68BED7_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ComponentModel.StringConverter struct StringConverter_t054FA0796F4C8E951208AFA052D99BCB8E68BED7 : public TypeConverter_t8306AE03734853B551DDF089C1F17836A7764DBB { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // STRINGCONVERTER_T054FA0796F4C8E951208AFA052D99BCB8E68BED7_H #ifndef TIMESPANCONVERTER_T4025A0861C52420BC73D837729E5EFA6ECDE07C7_H #define TIMESPANCONVERTER_T4025A0861C52420BC73D837729E5EFA6ECDE07C7_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ComponentModel.TimeSpanConverter struct TimeSpanConverter_t4025A0861C52420BC73D837729E5EFA6ECDE07C7 : public TypeConverter_t8306AE03734853B551DDF089C1F17836A7764DBB { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TIMESPANCONVERTER_T4025A0861C52420BC73D837729E5EFA6ECDE07C7_H #ifndef WIN32EXCEPTION_TB05BE97AB4CADD54DF96C0109689F0ECA7517668_H #define WIN32EXCEPTION_TB05BE97AB4CADD54DF96C0109689F0ECA7517668_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ComponentModel.Win32Exception struct Win32Exception_tB05BE97AB4CADD54DF96C0109689F0ECA7517668 : public ExternalException_t68841FD169C0CB00CC950EDA7E2A59540D65B1CE { public: // System.Int32 System.ComponentModel.Win32Exception::nativeErrorCode int32_t ___nativeErrorCode_17; public: inline static int32_t get_offset_of_nativeErrorCode_17() { return static_cast<int32_t>(offsetof(Win32Exception_tB05BE97AB4CADD54DF96C0109689F0ECA7517668, ___nativeErrorCode_17)); } inline int32_t get_nativeErrorCode_17() const { return ___nativeErrorCode_17; } inline int32_t* get_address_of_nativeErrorCode_17() { return &___nativeErrorCode_17; } inline void set_nativeErrorCode_17(int32_t value) { ___nativeErrorCode_17 = value; } }; struct Win32Exception_tB05BE97AB4CADD54DF96C0109689F0ECA7517668_StaticFields { public: // System.Boolean System.ComponentModel.Win32Exception::s_ErrorMessagesInitialized bool ___s_ErrorMessagesInitialized_18; // System.Collections.Generic.Dictionary`2<System.Int32,System.String> System.ComponentModel.Win32Exception::s_ErrorMessage Dictionary_2_t4EFE6A1D6502662B911688316C6920444A18CF0C * ___s_ErrorMessage_19; public: inline static int32_t get_offset_of_s_ErrorMessagesInitialized_18() { return static_cast<int32_t>(offsetof(Win32Exception_tB05BE97AB4CADD54DF96C0109689F0ECA7517668_StaticFields, ___s_ErrorMessagesInitialized_18)); } inline bool get_s_ErrorMessagesInitialized_18() const { return ___s_ErrorMessagesInitialized_18; } inline bool* get_address_of_s_ErrorMessagesInitialized_18() { return &___s_ErrorMessagesInitialized_18; } inline void set_s_ErrorMessagesInitialized_18(bool value) { ___s_ErrorMessagesInitialized_18 = value; } inline static int32_t get_offset_of_s_ErrorMessage_19() { return static_cast<int32_t>(offsetof(Win32Exception_tB05BE97AB4CADD54DF96C0109689F0ECA7517668_StaticFields, ___s_ErrorMessage_19)); } inline Dictionary_2_t4EFE6A1D6502662B911688316C6920444A18CF0C * get_s_ErrorMessage_19() const { return ___s_ErrorMessage_19; } inline Dictionary_2_t4EFE6A1D6502662B911688316C6920444A18CF0C ** get_address_of_s_ErrorMessage_19() { return &___s_ErrorMessage_19; } inline void set_s_ErrorMessage_19(Dictionary_2_t4EFE6A1D6502662B911688316C6920444A18CF0C * value) { ___s_ErrorMessage_19 = value; Il2CppCodeGenWriteBarrier((&___s_ErrorMessage_19), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // WIN32EXCEPTION_TB05BE97AB4CADD54DF96C0109689F0ECA7517668_H #ifndef IPADDRESS_T77F35D21A3027F0CE7B38EA9B56BFD31B28952CE_H #define IPADDRESS_T77F35D21A3027F0CE7B38EA9B56BFD31B28952CE_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Net.IPAddress struct IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE : public RuntimeObject { public: // System.Int64 System.Net.IPAddress::m_Address int64_t ___m_Address_5; // System.String System.Net.IPAddress::m_ToString String_t* ___m_ToString_6; // System.Net.Sockets.AddressFamily System.Net.IPAddress::m_Family int32_t ___m_Family_10; // System.UInt16[] System.Net.IPAddress::m_Numbers UInt16U5BU5D_t2D4BB1F8C486FF4359FFA7E4A76A8708A684543E* ___m_Numbers_11; // System.Int64 System.Net.IPAddress::m_ScopeId int64_t ___m_ScopeId_12; // System.Int32 System.Net.IPAddress::m_HashCode int32_t ___m_HashCode_13; public: inline static int32_t get_offset_of_m_Address_5() { return static_cast<int32_t>(offsetof(IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE, ___m_Address_5)); } inline int64_t get_m_Address_5() const { return ___m_Address_5; } inline int64_t* get_address_of_m_Address_5() { return &___m_Address_5; } inline void set_m_Address_5(int64_t value) { ___m_Address_5 = value; } inline static int32_t get_offset_of_m_ToString_6() { return static_cast<int32_t>(offsetof(IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE, ___m_ToString_6)); } inline String_t* get_m_ToString_6() const { return ___m_ToString_6; } inline String_t** get_address_of_m_ToString_6() { return &___m_ToString_6; } inline void set_m_ToString_6(String_t* value) { ___m_ToString_6 = value; Il2CppCodeGenWriteBarrier((&___m_ToString_6), value); } inline static int32_t get_offset_of_m_Family_10() { return static_cast<int32_t>(offsetof(IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE, ___m_Family_10)); } inline int32_t get_m_Family_10() const { return ___m_Family_10; } inline int32_t* get_address_of_m_Family_10() { return &___m_Family_10; } inline void set_m_Family_10(int32_t value) { ___m_Family_10 = value; } inline static int32_t get_offset_of_m_Numbers_11() { return static_cast<int32_t>(offsetof(IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE, ___m_Numbers_11)); } inline UInt16U5BU5D_t2D4BB1F8C486FF4359FFA7E4A76A8708A684543E* get_m_Numbers_11() const { return ___m_Numbers_11; } inline UInt16U5BU5D_t2D4BB1F8C486FF4359FFA7E4A76A8708A684543E** get_address_of_m_Numbers_11() { return &___m_Numbers_11; } inline void set_m_Numbers_11(UInt16U5BU5D_t2D4BB1F8C486FF4359FFA7E4A76A8708A684543E* value) { ___m_Numbers_11 = value; Il2CppCodeGenWriteBarrier((&___m_Numbers_11), value); } inline static int32_t get_offset_of_m_ScopeId_12() { return static_cast<int32_t>(offsetof(IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE, ___m_ScopeId_12)); } inline int64_t get_m_ScopeId_12() const { return ___m_ScopeId_12; } inline int64_t* get_address_of_m_ScopeId_12() { return &___m_ScopeId_12; } inline void set_m_ScopeId_12(int64_t value) { ___m_ScopeId_12 = value; } inline static int32_t get_offset_of_m_HashCode_13() { return static_cast<int32_t>(offsetof(IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE, ___m_HashCode_13)); } inline int32_t get_m_HashCode_13() const { return ___m_HashCode_13; } inline int32_t* get_address_of_m_HashCode_13() { return &___m_HashCode_13; } inline void set_m_HashCode_13(int32_t value) { ___m_HashCode_13 = value; } }; struct IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE_StaticFields { public: // System.Net.IPAddress System.Net.IPAddress::Any IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE * ___Any_0; // System.Net.IPAddress System.Net.IPAddress::Loopback IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE * ___Loopback_1; // System.Net.IPAddress System.Net.IPAddress::Broadcast IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE * ___Broadcast_2; // System.Net.IPAddress System.Net.IPAddress::None IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE * ___None_3; // System.Net.IPAddress System.Net.IPAddress::IPv6Any IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE * ___IPv6Any_7; // System.Net.IPAddress System.Net.IPAddress::IPv6Loopback IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE * ___IPv6Loopback_8; // System.Net.IPAddress System.Net.IPAddress::IPv6None IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE * ___IPv6None_9; public: inline static int32_t get_offset_of_Any_0() { return static_cast<int32_t>(offsetof(IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE_StaticFields, ___Any_0)); } inline IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE * get_Any_0() const { return ___Any_0; } inline IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE ** get_address_of_Any_0() { return &___Any_0; } inline void set_Any_0(IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE * value) { ___Any_0 = value; Il2CppCodeGenWriteBarrier((&___Any_0), value); } inline static int32_t get_offset_of_Loopback_1() { return static_cast<int32_t>(offsetof(IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE_StaticFields, ___Loopback_1)); } inline IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE * get_Loopback_1() const { return ___Loopback_1; } inline IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE ** get_address_of_Loopback_1() { return &___Loopback_1; } inline void set_Loopback_1(IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE * value) { ___Loopback_1 = value; Il2CppCodeGenWriteBarrier((&___Loopback_1), value); } inline static int32_t get_offset_of_Broadcast_2() { return static_cast<int32_t>(offsetof(IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE_StaticFields, ___Broadcast_2)); } inline IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE * get_Broadcast_2() const { return ___Broadcast_2; } inline IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE ** get_address_of_Broadcast_2() { return &___Broadcast_2; } inline void set_Broadcast_2(IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE * value) { ___Broadcast_2 = value; Il2CppCodeGenWriteBarrier((&___Broadcast_2), value); } inline static int32_t get_offset_of_None_3() { return static_cast<int32_t>(offsetof(IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE_StaticFields, ___None_3)); } inline IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE * get_None_3() const { return ___None_3; } inline IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE ** get_address_of_None_3() { return &___None_3; } inline void set_None_3(IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE * value) { ___None_3 = value; Il2CppCodeGenWriteBarrier((&___None_3), value); } inline static int32_t get_offset_of_IPv6Any_7() { return static_cast<int32_t>(offsetof(IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE_StaticFields, ___IPv6Any_7)); } inline IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE * get_IPv6Any_7() const { return ___IPv6Any_7; } inline IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE ** get_address_of_IPv6Any_7() { return &___IPv6Any_7; } inline void set_IPv6Any_7(IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE * value) { ___IPv6Any_7 = value; Il2CppCodeGenWriteBarrier((&___IPv6Any_7), value); } inline static int32_t get_offset_of_IPv6Loopback_8() { return static_cast<int32_t>(offsetof(IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE_StaticFields, ___IPv6Loopback_8)); } inline IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE * get_IPv6Loopback_8() const { return ___IPv6Loopback_8; } inline IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE ** get_address_of_IPv6Loopback_8() { return &___IPv6Loopback_8; } inline void set_IPv6Loopback_8(IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE * value) { ___IPv6Loopback_8 = value; Il2CppCodeGenWriteBarrier((&___IPv6Loopback_8), value); } inline static int32_t get_offset_of_IPv6None_9() { return static_cast<int32_t>(offsetof(IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE_StaticFields, ___IPv6None_9)); } inline IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE * get_IPv6None_9() const { return ___IPv6None_9; } inline IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE ** get_address_of_IPv6None_9() { return &___IPv6None_9; } inline void set_IPv6None_9(IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE * value) { ___IPv6None_9 = value; Il2CppCodeGenWriteBarrier((&___IPv6None_9), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // IPADDRESS_T77F35D21A3027F0CE7B38EA9B56BFD31B28952CE_H #ifndef OBJECTDISPOSEDEXCEPTION_TF68E471ECD1419AD7C51137B742837395F50B69A_H #define OBJECTDISPOSEDEXCEPTION_TF68E471ECD1419AD7C51137B742837395F50B69A_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ObjectDisposedException struct ObjectDisposedException_tF68E471ECD1419AD7C51137B742837395F50B69A : public InvalidOperationException_t0530E734D823F78310CAFAFA424CA5164D93A1F1 { public: // System.String System.ObjectDisposedException::objectName String_t* ___objectName_17; public: inline static int32_t get_offset_of_objectName_17() { return static_cast<int32_t>(offsetof(ObjectDisposedException_tF68E471ECD1419AD7C51137B742837395F50B69A, ___objectName_17)); } inline String_t* get_objectName_17() const { return ___objectName_17; } inline String_t** get_address_of_objectName_17() { return &___objectName_17; } inline void set_objectName_17(String_t* value) { ___objectName_17 = value; Il2CppCodeGenWriteBarrier((&___objectName_17), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // OBJECTDISPOSEDEXCEPTION_TF68E471ECD1419AD7C51137B742837395F50B69A_H #ifndef OID_TC00A10270EAF16BBF0F2619B9AEC883E0CFE6137_H #define OID_TC00A10270EAF16BBF0F2619B9AEC883E0CFE6137_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Security.Cryptography.Oid struct Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137 : public RuntimeObject { public: // System.String System.Security.Cryptography.Oid::m_value String_t* ___m_value_0; // System.String System.Security.Cryptography.Oid::m_friendlyName String_t* ___m_friendlyName_1; // System.Security.Cryptography.OidGroup System.Security.Cryptography.Oid::m_group int32_t ___m_group_2; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137, ___m_value_0)); } inline String_t* get_m_value_0() const { return ___m_value_0; } inline String_t** get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(String_t* value) { ___m_value_0 = value; Il2CppCodeGenWriteBarrier((&___m_value_0), value); } inline static int32_t get_offset_of_m_friendlyName_1() { return static_cast<int32_t>(offsetof(Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137, ___m_friendlyName_1)); } inline String_t* get_m_friendlyName_1() const { return ___m_friendlyName_1; } inline String_t** get_address_of_m_friendlyName_1() { return &___m_friendlyName_1; } inline void set_m_friendlyName_1(String_t* value) { ___m_friendlyName_1 = value; Il2CppCodeGenWriteBarrier((&___m_friendlyName_1), value); } inline static int32_t get_offset_of_m_group_2() { return static_cast<int32_t>(offsetof(Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137, ___m_group_2)); } inline int32_t get_m_group_2() const { return ___m_group_2; } inline int32_t* get_address_of_m_group_2() { return &___m_group_2; } inline void set_m_group_2(int32_t value) { ___m_group_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // OID_TC00A10270EAF16BBF0F2619B9AEC883E0CFE6137_H #ifndef X509BASICCONSTRAINTSEXTENSION_T091983B3CDCB686781B4853177610A22483B532C_H #define X509BASICCONSTRAINTSEXTENSION_T091983B3CDCB686781B4853177610A22483B532C_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension struct X509BasicConstraintsExtension_t091983B3CDCB686781B4853177610A22483B532C : public X509Extension_t223237DF0C323CC455D3A2634D977773D2F3818A { public: // System.Boolean System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension::_certificateAuthority bool ____certificateAuthority_5; // System.Boolean System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension::_hasPathLengthConstraint bool ____hasPathLengthConstraint_6; // System.Int32 System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension::_pathLengthConstraint int32_t ____pathLengthConstraint_7; // System.Security.Cryptography.AsnDecodeStatus System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension::_status int32_t ____status_8; public: inline static int32_t get_offset_of__certificateAuthority_5() { return static_cast<int32_t>(offsetof(X509BasicConstraintsExtension_t091983B3CDCB686781B4853177610A22483B532C, ____certificateAuthority_5)); } inline bool get__certificateAuthority_5() const { return ____certificateAuthority_5; } inline bool* get_address_of__certificateAuthority_5() { return &____certificateAuthority_5; } inline void set__certificateAuthority_5(bool value) { ____certificateAuthority_5 = value; } inline static int32_t get_offset_of__hasPathLengthConstraint_6() { return static_cast<int32_t>(offsetof(X509BasicConstraintsExtension_t091983B3CDCB686781B4853177610A22483B532C, ____hasPathLengthConstraint_6)); } inline bool get__hasPathLengthConstraint_6() const { return ____hasPathLengthConstraint_6; } inline bool* get_address_of__hasPathLengthConstraint_6() { return &____hasPathLengthConstraint_6; } inline void set__hasPathLengthConstraint_6(bool value) { ____hasPathLengthConstraint_6 = value; } inline static int32_t get_offset_of__pathLengthConstraint_7() { return static_cast<int32_t>(offsetof(X509BasicConstraintsExtension_t091983B3CDCB686781B4853177610A22483B532C, ____pathLengthConstraint_7)); } inline int32_t get__pathLengthConstraint_7() const { return ____pathLengthConstraint_7; } inline int32_t* get_address_of__pathLengthConstraint_7() { return &____pathLengthConstraint_7; } inline void set__pathLengthConstraint_7(int32_t value) { ____pathLengthConstraint_7 = value; } inline static int32_t get_offset_of__status_8() { return static_cast<int32_t>(offsetof(X509BasicConstraintsExtension_t091983B3CDCB686781B4853177610A22483B532C, ____status_8)); } inline int32_t get__status_8() const { return ____status_8; } inline int32_t* get_address_of__status_8() { return &____status_8; } inline void set__status_8(int32_t value) { ____status_8 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // X509BASICCONSTRAINTSEXTENSION_T091983B3CDCB686781B4853177610A22483B532C_H #ifndef X509ENHANCEDKEYUSAGEEXTENSION_T8B1FEC5814799207635A97EA878EA64688437254_H #define X509ENHANCEDKEYUSAGEEXTENSION_T8B1FEC5814799207635A97EA878EA64688437254_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension struct X509EnhancedKeyUsageExtension_t8B1FEC5814799207635A97EA878EA64688437254 : public X509Extension_t223237DF0C323CC455D3A2634D977773D2F3818A { public: // System.Security.Cryptography.OidCollection System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension::_enhKeyUsage OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E * ____enhKeyUsage_3; // System.Security.Cryptography.AsnDecodeStatus System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension::_status int32_t ____status_4; public: inline static int32_t get_offset_of__enhKeyUsage_3() { return static_cast<int32_t>(offsetof(X509EnhancedKeyUsageExtension_t8B1FEC5814799207635A97EA878EA64688437254, ____enhKeyUsage_3)); } inline OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E * get__enhKeyUsage_3() const { return ____enhKeyUsage_3; } inline OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E ** get_address_of__enhKeyUsage_3() { return &____enhKeyUsage_3; } inline void set__enhKeyUsage_3(OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E * value) { ____enhKeyUsage_3 = value; Il2CppCodeGenWriteBarrier((&____enhKeyUsage_3), value); } inline static int32_t get_offset_of__status_4() { return static_cast<int32_t>(offsetof(X509EnhancedKeyUsageExtension_t8B1FEC5814799207635A97EA878EA64688437254, ____status_4)); } inline int32_t get__status_4() const { return ____status_4; } inline int32_t* get_address_of__status_4() { return &____status_4; } inline void set__status_4(int32_t value) { ____status_4 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // X509ENHANCEDKEYUSAGEEXTENSION_T8B1FEC5814799207635A97EA878EA64688437254_H #ifndef X509KEYUSAGEEXTENSION_T9F740A60AD6DBEF9B09E946D4D8D67DB882C6E6E_H #define X509KEYUSAGEEXTENSION_T9F740A60AD6DBEF9B09E946D4D8D67DB882C6E6E_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Security.Cryptography.X509Certificates.X509KeyUsageExtension struct X509KeyUsageExtension_t9F740A60AD6DBEF9B09E946D4D8D67DB882C6E6E : public X509Extension_t223237DF0C323CC455D3A2634D977773D2F3818A { public: // System.Security.Cryptography.X509Certificates.X509KeyUsageFlags System.Security.Cryptography.X509Certificates.X509KeyUsageExtension::_keyUsages int32_t ____keyUsages_6; // System.Security.Cryptography.AsnDecodeStatus System.Security.Cryptography.X509Certificates.X509KeyUsageExtension::_status int32_t ____status_7; public: inline static int32_t get_offset_of__keyUsages_6() { return static_cast<int32_t>(offsetof(X509KeyUsageExtension_t9F740A60AD6DBEF9B09E946D4D8D67DB882C6E6E, ____keyUsages_6)); } inline int32_t get__keyUsages_6() const { return ____keyUsages_6; } inline int32_t* get_address_of__keyUsages_6() { return &____keyUsages_6; } inline void set__keyUsages_6(int32_t value) { ____keyUsages_6 = value; } inline static int32_t get_offset_of__status_7() { return static_cast<int32_t>(offsetof(X509KeyUsageExtension_t9F740A60AD6DBEF9B09E946D4D8D67DB882C6E6E, ____status_7)); } inline int32_t get__status_7() const { return ____status_7; } inline int32_t* get_address_of__status_7() { return &____status_7; } inline void set__status_7(int32_t value) { ____status_7 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // X509KEYUSAGEEXTENSION_T9F740A60AD6DBEF9B09E946D4D8D67DB882C6E6E_H #ifndef X509SUBJECTKEYIDENTIFIEREXTENSION_T200DBBEB1229862DAA5F56EA352B03D2EDAC4D8E_H #define X509SUBJECTKEYIDENTIFIEREXTENSION_T200DBBEB1229862DAA5F56EA352B03D2EDAC4D8E_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension struct X509SubjectKeyIdentifierExtension_t200DBBEB1229862DAA5F56EA352B03D2EDAC4D8E : public X509Extension_t223237DF0C323CC455D3A2634D977773D2F3818A { public: // System.Byte[] System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension::_subjectKeyIdentifier ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* ____subjectKeyIdentifier_5; // System.String System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension::_ski String_t* ____ski_6; // System.Security.Cryptography.AsnDecodeStatus System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension::_status int32_t ____status_7; public: inline static int32_t get_offset_of__subjectKeyIdentifier_5() { return static_cast<int32_t>(offsetof(X509SubjectKeyIdentifierExtension_t200DBBEB1229862DAA5F56EA352B03D2EDAC4D8E, ____subjectKeyIdentifier_5)); } inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* get__subjectKeyIdentifier_5() const { return ____subjectKeyIdentifier_5; } inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821** get_address_of__subjectKeyIdentifier_5() { return &____subjectKeyIdentifier_5; } inline void set__subjectKeyIdentifier_5(ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* value) { ____subjectKeyIdentifier_5 = value; Il2CppCodeGenWriteBarrier((&____subjectKeyIdentifier_5), value); } inline static int32_t get_offset_of__ski_6() { return static_cast<int32_t>(offsetof(X509SubjectKeyIdentifierExtension_t200DBBEB1229862DAA5F56EA352B03D2EDAC4D8E, ____ski_6)); } inline String_t* get__ski_6() const { return ____ski_6; } inline String_t** get_address_of__ski_6() { return &____ski_6; } inline void set__ski_6(String_t* value) { ____ski_6 = value; Il2CppCodeGenWriteBarrier((&____ski_6), value); } inline static int32_t get_offset_of__status_7() { return static_cast<int32_t>(offsetof(X509SubjectKeyIdentifierExtension_t200DBBEB1229862DAA5F56EA352B03D2EDAC4D8E, ____status_7)); } inline int32_t get__status_7() const { return ____status_7; } inline int32_t* get_address_of__status_7() { return &____status_7; } inline void set__status_7(int32_t value) { ____status_7 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // X509SUBJECTKEYIDENTIFIEREXTENSION_T200DBBEB1229862DAA5F56EA352B03D2EDAC4D8E_H #ifndef MATCHSPARSE_T73BEE39B7EBE30B7460558DCA846B704C94B571C_H #define MATCHSPARSE_T73BEE39B7EBE30B7460558DCA846B704C94B571C_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Text.RegularExpressions.MatchSparse struct MatchSparse_t73BEE39B7EBE30B7460558DCA846B704C94B571C : public Match_tE447871AB59EED3642F31EB9559D162C2977EBB5 { public: // System.Collections.Hashtable System.Text.RegularExpressions.MatchSparse::_caps Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 * ____caps_16; public: inline static int32_t get_offset_of__caps_16() { return static_cast<int32_t>(offsetof(MatchSparse_t73BEE39B7EBE30B7460558DCA846B704C94B571C, ____caps_16)); } inline Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 * get__caps_16() const { return ____caps_16; } inline Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 ** get_address_of__caps_16() { return &____caps_16; } inline void set__caps_16(Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 * value) { ____caps_16 = value; Il2CppCodeGenWriteBarrier((&____caps_16), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // MATCHSPARSE_T73BEE39B7EBE30B7460558DCA846B704C94B571C_H #ifndef REGEXMATCHTIMEOUTEXCEPTION_T78D3102CF3A9DEE18561827EDD878176482A6C7C_H #define REGEXMATCHTIMEOUTEXCEPTION_T78D3102CF3A9DEE18561827EDD878176482A6C7C_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Text.RegularExpressions.RegexMatchTimeoutException struct RegexMatchTimeoutException_t78D3102CF3A9DEE18561827EDD878176482A6C7C : public TimeoutException_t15A6E9A2A5819966712B5CFAF756BAEA40E3B1B7 { public: // System.String System.Text.RegularExpressions.RegexMatchTimeoutException::regexInput String_t* ___regexInput_17; // System.String System.Text.RegularExpressions.RegexMatchTimeoutException::regexPattern String_t* ___regexPattern_18; // System.TimeSpan System.Text.RegularExpressions.RegexMatchTimeoutException::matchTimeout TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 ___matchTimeout_19; public: inline static int32_t get_offset_of_regexInput_17() { return static_cast<int32_t>(offsetof(RegexMatchTimeoutException_t78D3102CF3A9DEE18561827EDD878176482A6C7C, ___regexInput_17)); } inline String_t* get_regexInput_17() const { return ___regexInput_17; } inline String_t** get_address_of_regexInput_17() { return &___regexInput_17; } inline void set_regexInput_17(String_t* value) { ___regexInput_17 = value; Il2CppCodeGenWriteBarrier((&___regexInput_17), value); } inline static int32_t get_offset_of_regexPattern_18() { return static_cast<int32_t>(offsetof(RegexMatchTimeoutException_t78D3102CF3A9DEE18561827EDD878176482A6C7C, ___regexPattern_18)); } inline String_t* get_regexPattern_18() const { return ___regexPattern_18; } inline String_t** get_address_of_regexPattern_18() { return &___regexPattern_18; } inline void set_regexPattern_18(String_t* value) { ___regexPattern_18 = value; Il2CppCodeGenWriteBarrier((&___regexPattern_18), value); } inline static int32_t get_offset_of_matchTimeout_19() { return static_cast<int32_t>(offsetof(RegexMatchTimeoutException_t78D3102CF3A9DEE18561827EDD878176482A6C7C, ___matchTimeout_19)); } inline TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 get_matchTimeout_19() const { return ___matchTimeout_19; } inline TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 * get_address_of_matchTimeout_19() { return &___matchTimeout_19; } inline void set_matchTimeout_19(TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 value) { ___matchTimeout_19 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // REGEXMATCHTIMEOUTEXCEPTION_T78D3102CF3A9DEE18561827EDD878176482A6C7C_H #ifndef REGEXNODE_TF92FC16590D5B00965BABFC709BA677DA0FC3F75_H #define REGEXNODE_TF92FC16590D5B00965BABFC709BA677DA0FC3F75_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Text.RegularExpressions.RegexNode struct RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 : public RuntimeObject { public: // System.Int32 System.Text.RegularExpressions.RegexNode::_type int32_t ____type_0; // System.Collections.Generic.List`1<System.Text.RegularExpressions.RegexNode> System.Text.RegularExpressions.RegexNode::_children List_1_tA5CDE89671B691180A7422F86077A0D047AD4059 * ____children_1; // System.String System.Text.RegularExpressions.RegexNode::_str String_t* ____str_2; // System.Char System.Text.RegularExpressions.RegexNode::_ch Il2CppChar ____ch_3; // System.Int32 System.Text.RegularExpressions.RegexNode::_m int32_t ____m_4; // System.Int32 System.Text.RegularExpressions.RegexNode::_n int32_t ____n_5; // System.Text.RegularExpressions.RegexOptions System.Text.RegularExpressions.RegexNode::_options int32_t ____options_6; // System.Text.RegularExpressions.RegexNode System.Text.RegularExpressions.RegexNode::_next RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 * ____next_7; public: inline static int32_t get_offset_of__type_0() { return static_cast<int32_t>(offsetof(RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75, ____type_0)); } inline int32_t get__type_0() const { return ____type_0; } inline int32_t* get_address_of__type_0() { return &____type_0; } inline void set__type_0(int32_t value) { ____type_0 = value; } inline static int32_t get_offset_of__children_1() { return static_cast<int32_t>(offsetof(RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75, ____children_1)); } inline List_1_tA5CDE89671B691180A7422F86077A0D047AD4059 * get__children_1() const { return ____children_1; } inline List_1_tA5CDE89671B691180A7422F86077A0D047AD4059 ** get_address_of__children_1() { return &____children_1; } inline void set__children_1(List_1_tA5CDE89671B691180A7422F86077A0D047AD4059 * value) { ____children_1 = value; Il2CppCodeGenWriteBarrier((&____children_1), value); } inline static int32_t get_offset_of__str_2() { return static_cast<int32_t>(offsetof(RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75, ____str_2)); } inline String_t* get__str_2() const { return ____str_2; } inline String_t** get_address_of__str_2() { return &____str_2; } inline void set__str_2(String_t* value) { ____str_2 = value; Il2CppCodeGenWriteBarrier((&____str_2), value); } inline static int32_t get_offset_of__ch_3() { return static_cast<int32_t>(offsetof(RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75, ____ch_3)); } inline Il2CppChar get__ch_3() const { return ____ch_3; } inline Il2CppChar* get_address_of__ch_3() { return &____ch_3; } inline void set__ch_3(Il2CppChar value) { ____ch_3 = value; } inline static int32_t get_offset_of__m_4() { return static_cast<int32_t>(offsetof(RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75, ____m_4)); } inline int32_t get__m_4() const { return ____m_4; } inline int32_t* get_address_of__m_4() { return &____m_4; } inline void set__m_4(int32_t value) { ____m_4 = value; } inline static int32_t get_offset_of__n_5() { return static_cast<int32_t>(offsetof(RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75, ____n_5)); } inline int32_t get__n_5() const { return ____n_5; } inline int32_t* get_address_of__n_5() { return &____n_5; } inline void set__n_5(int32_t value) { ____n_5 = value; } inline static int32_t get_offset_of__options_6() { return static_cast<int32_t>(offsetof(RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75, ____options_6)); } inline int32_t get__options_6() const { return ____options_6; } inline int32_t* get_address_of__options_6() { return &____options_6; } inline void set__options_6(int32_t value) { ____options_6 = value; } inline static int32_t get_offset_of__next_7() { return static_cast<int32_t>(offsetof(RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75, ____next_7)); } inline RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 * get__next_7() const { return ____next_7; } inline RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 ** get_address_of__next_7() { return &____next_7; } inline void set__next_7(RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 * value) { ____next_7 = value; Il2CppCodeGenWriteBarrier((&____next_7), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // REGEXNODE_TF92FC16590D5B00965BABFC709BA677DA0FC3F75_H #ifndef REGEXPARSER_T9576D89D31260EF04DE583287FFC127132051FEE_H #define REGEXPARSER_T9576D89D31260EF04DE583287FFC127132051FEE_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Text.RegularExpressions.RegexParser struct RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE : public RuntimeObject { public: // System.Text.RegularExpressions.RegexNode System.Text.RegularExpressions.RegexParser::_stack RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 * ____stack_0; // System.Text.RegularExpressions.RegexNode System.Text.RegularExpressions.RegexParser::_group RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 * ____group_1; // System.Text.RegularExpressions.RegexNode System.Text.RegularExpressions.RegexParser::_alternation RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 * ____alternation_2; // System.Text.RegularExpressions.RegexNode System.Text.RegularExpressions.RegexParser::_concatenation RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 * ____concatenation_3; // System.Text.RegularExpressions.RegexNode System.Text.RegularExpressions.RegexParser::_unit RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 * ____unit_4; // System.String System.Text.RegularExpressions.RegexParser::_pattern String_t* ____pattern_5; // System.Int32 System.Text.RegularExpressions.RegexParser::_currentPos int32_t ____currentPos_6; // System.Globalization.CultureInfo System.Text.RegularExpressions.RegexParser::_culture CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F * ____culture_7; // System.Int32 System.Text.RegularExpressions.RegexParser::_autocap int32_t ____autocap_8; // System.Int32 System.Text.RegularExpressions.RegexParser::_capcount int32_t ____capcount_9; // System.Int32 System.Text.RegularExpressions.RegexParser::_captop int32_t ____captop_10; // System.Int32 System.Text.RegularExpressions.RegexParser::_capsize int32_t ____capsize_11; // System.Collections.Hashtable System.Text.RegularExpressions.RegexParser::_caps Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 * ____caps_12; // System.Collections.Hashtable System.Text.RegularExpressions.RegexParser::_capnames Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 * ____capnames_13; // System.Int32[] System.Text.RegularExpressions.RegexParser::_capnumlist Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* ____capnumlist_14; // System.Collections.Generic.List`1<System.String> System.Text.RegularExpressions.RegexParser::_capnamelist List_1_tE8032E48C661C350FF9550E9063D595C0AB25CD3 * ____capnamelist_15; // System.Text.RegularExpressions.RegexOptions System.Text.RegularExpressions.RegexParser::_options int32_t ____options_16; // System.Collections.Generic.List`1<System.Text.RegularExpressions.RegexOptions> System.Text.RegularExpressions.RegexParser::_optionsStack List_1_t85142A16ADC23C13E223599A626015FD40FF076A * ____optionsStack_17; // System.Boolean System.Text.RegularExpressions.RegexParser::_ignoreNextParen bool ____ignoreNextParen_18; public: inline static int32_t get_offset_of__stack_0() { return static_cast<int32_t>(offsetof(RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE, ____stack_0)); } inline RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 * get__stack_0() const { return ____stack_0; } inline RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 ** get_address_of__stack_0() { return &____stack_0; } inline void set__stack_0(RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 * value) { ____stack_0 = value; Il2CppCodeGenWriteBarrier((&____stack_0), value); } inline static int32_t get_offset_of__group_1() { return static_cast<int32_t>(offsetof(RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE, ____group_1)); } inline RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 * get__group_1() const { return ____group_1; } inline RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 ** get_address_of__group_1() { return &____group_1; } inline void set__group_1(RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 * value) { ____group_1 = value; Il2CppCodeGenWriteBarrier((&____group_1), value); } inline static int32_t get_offset_of__alternation_2() { return static_cast<int32_t>(offsetof(RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE, ____alternation_2)); } inline RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 * get__alternation_2() const { return ____alternation_2; } inline RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 ** get_address_of__alternation_2() { return &____alternation_2; } inline void set__alternation_2(RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 * value) { ____alternation_2 = value; Il2CppCodeGenWriteBarrier((&____alternation_2), value); } inline static int32_t get_offset_of__concatenation_3() { return static_cast<int32_t>(offsetof(RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE, ____concatenation_3)); } inline RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 * get__concatenation_3() const { return ____concatenation_3; } inline RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 ** get_address_of__concatenation_3() { return &____concatenation_3; } inline void set__concatenation_3(RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 * value) { ____concatenation_3 = value; Il2CppCodeGenWriteBarrier((&____concatenation_3), value); } inline static int32_t get_offset_of__unit_4() { return static_cast<int32_t>(offsetof(RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE, ____unit_4)); } inline RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 * get__unit_4() const { return ____unit_4; } inline RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 ** get_address_of__unit_4() { return &____unit_4; } inline void set__unit_4(RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 * value) { ____unit_4 = value; Il2CppCodeGenWriteBarrier((&____unit_4), value); } inline static int32_t get_offset_of__pattern_5() { return static_cast<int32_t>(offsetof(RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE, ____pattern_5)); } inline String_t* get__pattern_5() const { return ____pattern_5; } inline String_t** get_address_of__pattern_5() { return &____pattern_5; } inline void set__pattern_5(String_t* value) { ____pattern_5 = value; Il2CppCodeGenWriteBarrier((&____pattern_5), value); } inline static int32_t get_offset_of__currentPos_6() { return static_cast<int32_t>(offsetof(RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE, ____currentPos_6)); } inline int32_t get__currentPos_6() const { return ____currentPos_6; } inline int32_t* get_address_of__currentPos_6() { return &____currentPos_6; } inline void set__currentPos_6(int32_t value) { ____currentPos_6 = value; } inline static int32_t get_offset_of__culture_7() { return static_cast<int32_t>(offsetof(RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE, ____culture_7)); } inline CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F * get__culture_7() const { return ____culture_7; } inline CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F ** get_address_of__culture_7() { return &____culture_7; } inline void set__culture_7(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F * value) { ____culture_7 = value; Il2CppCodeGenWriteBarrier((&____culture_7), value); } inline static int32_t get_offset_of__autocap_8() { return static_cast<int32_t>(offsetof(RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE, ____autocap_8)); } inline int32_t get__autocap_8() const { return ____autocap_8; } inline int32_t* get_address_of__autocap_8() { return &____autocap_8; } inline void set__autocap_8(int32_t value) { ____autocap_8 = value; } inline static int32_t get_offset_of__capcount_9() { return static_cast<int32_t>(offsetof(RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE, ____capcount_9)); } inline int32_t get__capcount_9() const { return ____capcount_9; } inline int32_t* get_address_of__capcount_9() { return &____capcount_9; } inline void set__capcount_9(int32_t value) { ____capcount_9 = value; } inline static int32_t get_offset_of__captop_10() { return static_cast<int32_t>(offsetof(RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE, ____captop_10)); } inline int32_t get__captop_10() const { return ____captop_10; } inline int32_t* get_address_of__captop_10() { return &____captop_10; } inline void set__captop_10(int32_t value) { ____captop_10 = value; } inline static int32_t get_offset_of__capsize_11() { return static_cast<int32_t>(offsetof(RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE, ____capsize_11)); } inline int32_t get__capsize_11() const { return ____capsize_11; } inline int32_t* get_address_of__capsize_11() { return &____capsize_11; } inline void set__capsize_11(int32_t value) { ____capsize_11 = value; } inline static int32_t get_offset_of__caps_12() { return static_cast<int32_t>(offsetof(RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE, ____caps_12)); } inline Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 * get__caps_12() const { return ____caps_12; } inline Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 ** get_address_of__caps_12() { return &____caps_12; } inline void set__caps_12(Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 * value) { ____caps_12 = value; Il2CppCodeGenWriteBarrier((&____caps_12), value); } inline static int32_t get_offset_of__capnames_13() { return static_cast<int32_t>(offsetof(RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE, ____capnames_13)); } inline Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 * get__capnames_13() const { return ____capnames_13; } inline Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 ** get_address_of__capnames_13() { return &____capnames_13; } inline void set__capnames_13(Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 * value) { ____capnames_13 = value; Il2CppCodeGenWriteBarrier((&____capnames_13), value); } inline static int32_t get_offset_of__capnumlist_14() { return static_cast<int32_t>(offsetof(RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE, ____capnumlist_14)); } inline Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* get__capnumlist_14() const { return ____capnumlist_14; } inline Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83** get_address_of__capnumlist_14() { return &____capnumlist_14; } inline void set__capnumlist_14(Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* value) { ____capnumlist_14 = value; Il2CppCodeGenWriteBarrier((&____capnumlist_14), value); } inline static int32_t get_offset_of__capnamelist_15() { return static_cast<int32_t>(offsetof(RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE, ____capnamelist_15)); } inline List_1_tE8032E48C661C350FF9550E9063D595C0AB25CD3 * get__capnamelist_15() const { return ____capnamelist_15; } inline List_1_tE8032E48C661C350FF9550E9063D595C0AB25CD3 ** get_address_of__capnamelist_15() { return &____capnamelist_15; } inline void set__capnamelist_15(List_1_tE8032E48C661C350FF9550E9063D595C0AB25CD3 * value) { ____capnamelist_15 = value; Il2CppCodeGenWriteBarrier((&____capnamelist_15), value); } inline static int32_t get_offset_of__options_16() { return static_cast<int32_t>(offsetof(RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE, ____options_16)); } inline int32_t get__options_16() const { return ____options_16; } inline int32_t* get_address_of__options_16() { return &____options_16; } inline void set__options_16(int32_t value) { ____options_16 = value; } inline static int32_t get_offset_of__optionsStack_17() { return static_cast<int32_t>(offsetof(RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE, ____optionsStack_17)); } inline List_1_t85142A16ADC23C13E223599A626015FD40FF076A * get__optionsStack_17() const { return ____optionsStack_17; } inline List_1_t85142A16ADC23C13E223599A626015FD40FF076A ** get_address_of__optionsStack_17() { return &____optionsStack_17; } inline void set__optionsStack_17(List_1_t85142A16ADC23C13E223599A626015FD40FF076A * value) { ____optionsStack_17 = value; Il2CppCodeGenWriteBarrier((&____optionsStack_17), value); } inline static int32_t get_offset_of__ignoreNextParen_18() { return static_cast<int32_t>(offsetof(RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE, ____ignoreNextParen_18)); } inline bool get__ignoreNextParen_18() const { return ____ignoreNextParen_18; } inline bool* get_address_of__ignoreNextParen_18() { return &____ignoreNextParen_18; } inline void set__ignoreNextParen_18(bool value) { ____ignoreNextParen_18 = value; } }; struct RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE_StaticFields { public: // System.Byte[] System.Text.RegularExpressions.RegexParser::_category ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* ____category_19; public: inline static int32_t get_offset_of__category_19() { return static_cast<int32_t>(offsetof(RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE_StaticFields, ____category_19)); } inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* get__category_19() const { return ____category_19; } inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821** get_address_of__category_19() { return &____category_19; } inline void set__category_19(ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* value) { ____category_19 = value; Il2CppCodeGenWriteBarrier((&____category_19), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // REGEXPARSER_T9576D89D31260EF04DE583287FFC127132051FEE_H #ifndef REGEXTREE_T8FE2EC649AB50FDA90239EA1410A881F278B47B6_H #define REGEXTREE_T8FE2EC649AB50FDA90239EA1410A881F278B47B6_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Text.RegularExpressions.RegexTree struct RegexTree_t8FE2EC649AB50FDA90239EA1410A881F278B47B6 : public RuntimeObject { public: // System.Text.RegularExpressions.RegexNode System.Text.RegularExpressions.RegexTree::_root RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 * ____root_0; // System.Collections.Hashtable System.Text.RegularExpressions.RegexTree::_caps Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 * ____caps_1; // System.Int32[] System.Text.RegularExpressions.RegexTree::_capnumlist Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* ____capnumlist_2; // System.Collections.Hashtable System.Text.RegularExpressions.RegexTree::_capnames Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 * ____capnames_3; // System.String[] System.Text.RegularExpressions.RegexTree::_capslist StringU5BU5D_t933FB07893230EA91C40FF900D5400665E87B14E* ____capslist_4; // System.Text.RegularExpressions.RegexOptions System.Text.RegularExpressions.RegexTree::_options int32_t ____options_5; // System.Int32 System.Text.RegularExpressions.RegexTree::_captop int32_t ____captop_6; public: inline static int32_t get_offset_of__root_0() { return static_cast<int32_t>(offsetof(RegexTree_t8FE2EC649AB50FDA90239EA1410A881F278B47B6, ____root_0)); } inline RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 * get__root_0() const { return ____root_0; } inline RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 ** get_address_of__root_0() { return &____root_0; } inline void set__root_0(RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75 * value) { ____root_0 = value; Il2CppCodeGenWriteBarrier((&____root_0), value); } inline static int32_t get_offset_of__caps_1() { return static_cast<int32_t>(offsetof(RegexTree_t8FE2EC649AB50FDA90239EA1410A881F278B47B6, ____caps_1)); } inline Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 * get__caps_1() const { return ____caps_1; } inline Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 ** get_address_of__caps_1() { return &____caps_1; } inline void set__caps_1(Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 * value) { ____caps_1 = value; Il2CppCodeGenWriteBarrier((&____caps_1), value); } inline static int32_t get_offset_of__capnumlist_2() { return static_cast<int32_t>(offsetof(RegexTree_t8FE2EC649AB50FDA90239EA1410A881F278B47B6, ____capnumlist_2)); } inline Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* get__capnumlist_2() const { return ____capnumlist_2; } inline Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83** get_address_of__capnumlist_2() { return &____capnumlist_2; } inline void set__capnumlist_2(Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* value) { ____capnumlist_2 = value; Il2CppCodeGenWriteBarrier((&____capnumlist_2), value); } inline static int32_t get_offset_of__capnames_3() { return static_cast<int32_t>(offsetof(RegexTree_t8FE2EC649AB50FDA90239EA1410A881F278B47B6, ____capnames_3)); } inline Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 * get__capnames_3() const { return ____capnames_3; } inline Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 ** get_address_of__capnames_3() { return &____capnames_3; } inline void set__capnames_3(Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 * value) { ____capnames_3 = value; Il2CppCodeGenWriteBarrier((&____capnames_3), value); } inline static int32_t get_offset_of__capslist_4() { return static_cast<int32_t>(offsetof(RegexTree_t8FE2EC649AB50FDA90239EA1410A881F278B47B6, ____capslist_4)); } inline StringU5BU5D_t933FB07893230EA91C40FF900D5400665E87B14E* get__capslist_4() const { return ____capslist_4; } inline StringU5BU5D_t933FB07893230EA91C40FF900D5400665E87B14E** get_address_of__capslist_4() { return &____capslist_4; } inline void set__capslist_4(StringU5BU5D_t933FB07893230EA91C40FF900D5400665E87B14E* value) { ____capslist_4 = value; Il2CppCodeGenWriteBarrier((&____capslist_4), value); } inline static int32_t get_offset_of__options_5() { return static_cast<int32_t>(offsetof(RegexTree_t8FE2EC649AB50FDA90239EA1410A881F278B47B6, ____options_5)); } inline int32_t get__options_5() const { return ____options_5; } inline int32_t* get_address_of__options_5() { return &____options_5; } inline void set__options_5(int32_t value) { ____options_5 = value; } inline static int32_t get_offset_of__captop_6() { return static_cast<int32_t>(offsetof(RegexTree_t8FE2EC649AB50FDA90239EA1410A881F278B47B6, ____captop_6)); } inline int32_t get__captop_6() const { return ____captop_6; } inline int32_t* get_address_of__captop_6() { return &____captop_6; } inline void set__captop_6(int32_t value) { ____captop_6 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // REGEXTREE_T8FE2EC649AB50FDA90239EA1410A881F278B47B6_H #ifndef ARRAYCONVERTER_TAAD8F39711C6ECD39D31226FA1D140DD38752B57_H #define ARRAYCONVERTER_TAAD8F39711C6ECD39D31226FA1D140DD38752B57_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ComponentModel.ArrayConverter struct ArrayConverter_tAAD8F39711C6ECD39D31226FA1D140DD38752B57 : public CollectionConverter_t039E15C433996B0F0F0EB78BEE81F6DE0705F184 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARRAYCONVERTER_TAAD8F39711C6ECD39D31226FA1D140DD38752B57_H #ifndef DECIMALCONVERTER_T10232B897580B6DE599BB375BE8C0F4E1C30B0C1_H #define DECIMALCONVERTER_T10232B897580B6DE599BB375BE8C0F4E1C30B0C1_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ComponentModel.DecimalConverter struct DecimalConverter_t10232B897580B6DE599BB375BE8C0F4E1C30B0C1 : public BaseNumberConverter_t6AF36A2503E7BABF7FB9A8EC05DF8B828491AC63 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DECIMALCONVERTER_T10232B897580B6DE599BB375BE8C0F4E1C30B0C1_H #ifndef DOUBLECONVERTER_T65A5D8B0C2736FC5469CE5DFA468D371DD5F9F75_H #define DOUBLECONVERTER_T65A5D8B0C2736FC5469CE5DFA468D371DD5F9F75_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ComponentModel.DoubleConverter struct DoubleConverter_t65A5D8B0C2736FC5469CE5DFA468D371DD5F9F75 : public BaseNumberConverter_t6AF36A2503E7BABF7FB9A8EC05DF8B828491AC63 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DOUBLECONVERTER_T65A5D8B0C2736FC5469CE5DFA468D371DD5F9F75_H #ifndef INT16CONVERTER_TA2223DDF2BE99AD79AD836FCEC90F2C12705433B_H #define INT16CONVERTER_TA2223DDF2BE99AD79AD836FCEC90F2C12705433B_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ComponentModel.Int16Converter struct Int16Converter_tA2223DDF2BE99AD79AD836FCEC90F2C12705433B : public BaseNumberConverter_t6AF36A2503E7BABF7FB9A8EC05DF8B828491AC63 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INT16CONVERTER_TA2223DDF2BE99AD79AD836FCEC90F2C12705433B_H #ifndef INT32CONVERTER_T73A6E403EBE01B56528CB227509954397A46BA22_H #define INT32CONVERTER_T73A6E403EBE01B56528CB227509954397A46BA22_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ComponentModel.Int32Converter struct Int32Converter_t73A6E403EBE01B56528CB227509954397A46BA22 : public BaseNumberConverter_t6AF36A2503E7BABF7FB9A8EC05DF8B828491AC63 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INT32CONVERTER_T73A6E403EBE01B56528CB227509954397A46BA22_H #ifndef INT64CONVERTER_TED09C98C409F894484943F8D4F9C6468A97F1447_H #define INT64CONVERTER_TED09C98C409F894484943F8D4F9C6468A97F1447_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ComponentModel.Int64Converter struct Int64Converter_tED09C98C409F894484943F8D4F9C6468A97F1447 : public BaseNumberConverter_t6AF36A2503E7BABF7FB9A8EC05DF8B828491AC63 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INT64CONVERTER_TED09C98C409F894484943F8D4F9C6468A97F1447_H #ifndef SINGLECONVERTER_T86A24FBD46D753B99344470E9566584F15538902_H #define SINGLECONVERTER_T86A24FBD46D753B99344470E9566584F15538902_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ComponentModel.SingleConverter struct SingleConverter_t86A24FBD46D753B99344470E9566584F15538902 : public BaseNumberConverter_t6AF36A2503E7BABF7FB9A8EC05DF8B828491AC63 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SINGLECONVERTER_T86A24FBD46D753B99344470E9566584F15538902_H #ifndef SOCKETEXCEPTION_T75481CF49BCAF5685A5A9E6933909E0B65E7E0A5_H #define SOCKETEXCEPTION_T75481CF49BCAF5685A5A9E6933909E0B65E7E0A5_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Net.Sockets.SocketException struct SocketException_t75481CF49BCAF5685A5A9E6933909E0B65E7E0A5 : public Win32Exception_tB05BE97AB4CADD54DF96C0109689F0ECA7517668 { public: // System.Net.EndPoint System.Net.Sockets.SocketException::m_EndPoint EndPoint_tD87FCEF2780A951E8CE8D808C345FBF2C088D980 * ___m_EndPoint_20; public: inline static int32_t get_offset_of_m_EndPoint_20() { return static_cast<int32_t>(offsetof(SocketException_t75481CF49BCAF5685A5A9E6933909E0B65E7E0A5, ___m_EndPoint_20)); } inline EndPoint_tD87FCEF2780A951E8CE8D808C345FBF2C088D980 * get_m_EndPoint_20() const { return ___m_EndPoint_20; } inline EndPoint_tD87FCEF2780A951E8CE8D808C345FBF2C088D980 ** get_address_of_m_EndPoint_20() { return &___m_EndPoint_20; } inline void set_m_EndPoint_20(EndPoint_tD87FCEF2780A951E8CE8D808C345FBF2C088D980 * value) { ___m_EndPoint_20 = value; Il2CppCodeGenWriteBarrier((&___m_EndPoint_20), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SOCKETEXCEPTION_T75481CF49BCAF5685A5A9E6933909E0B65E7E0A5_H #ifndef THROWSTUB_T03526C535287FADF58CBFA05084AE89A0ACFFEFA_H #define THROWSTUB_T03526C535287FADF58CBFA05084AE89A0ACFFEFA_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Unity.ThrowStub struct ThrowStub_t03526C535287FADF58CBFA05084AE89A0ACFFEFA : public ObjectDisposedException_tF68E471ECD1419AD7C51137B742837395F50B69A { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // THROWSTUB_T03526C535287FADF58CBFA05084AE89A0ACFFEFA_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1500 = { sizeof (RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90), -1, sizeof(RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1500[19] = { RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90::get_offset_of__rangelist_0(), RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90::get_offset_of__categories_1(), RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90::get_offset_of__canonical_2(), RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90::get_offset_of__negate_3(), RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90::get_offset_of__subtractor_4(), RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields::get_offset_of_InternalRegexIgnoreCase_5(), RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields::get_offset_of_Space_6(), RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields::get_offset_of_NotSpace_7(), RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields::get_offset_of_Word_8(), RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields::get_offset_of_NotWord_9(), RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields::get_offset_of_SpaceClass_10(), RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields::get_offset_of_NotSpaceClass_11(), RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields::get_offset_of_WordClass_12(), RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields::get_offset_of_NotWordClass_13(), RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields::get_offset_of_DigitClass_14(), RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields::get_offset_of_NotDigitClass_15(), RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields::get_offset_of__definedCategories_16(), RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields::get_offset_of__propTable_17(), RegexCharClass_t56409AACB9ADE95FA5333FC5D94FAADAF564AE90_StaticFields::get_offset_of__lcTable_18(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1501 = { sizeof (LowerCaseMapping_t3F087D71A4D7A309FD5492CE33501FD4F4709D7B)+ sizeof (RuntimeObject), sizeof(LowerCaseMapping_t3F087D71A4D7A309FD5492CE33501FD4F4709D7B_marshaled_pinvoke), 0, 0 }; extern const int32_t g_FieldOffsetTable1501[4] = { LowerCaseMapping_t3F087D71A4D7A309FD5492CE33501FD4F4709D7B::get_offset_of__chMin_0() + static_cast<int32_t>(sizeof(RuntimeObject)), LowerCaseMapping_t3F087D71A4D7A309FD5492CE33501FD4F4709D7B::get_offset_of__chMax_1() + static_cast<int32_t>(sizeof(RuntimeObject)), LowerCaseMapping_t3F087D71A4D7A309FD5492CE33501FD4F4709D7B::get_offset_of__lcOp_2() + static_cast<int32_t>(sizeof(RuntimeObject)), LowerCaseMapping_t3F087D71A4D7A309FD5492CE33501FD4F4709D7B::get_offset_of__data_3() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1502 = { sizeof (SingleRangeComparer_t6E5EF09D774335DD82A76997728AB97761B5984C), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1503 = { sizeof (SingleRange_t7B8E395E75FA456AB2834933C1ECA2007EEADEE0), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1503[2] = { SingleRange_t7B8E395E75FA456AB2834933C1ECA2007EEADEE0::get_offset_of__first_0(), SingleRange_t7B8E395E75FA456AB2834933C1ECA2007EEADEE0::get_offset_of__last_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1504 = { sizeof (RegexCode_t12846533CAD1E4221CEDF5A4D15D4D649EA688FA), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1504[9] = { RegexCode_t12846533CAD1E4221CEDF5A4D15D4D649EA688FA::get_offset_of__codes_0(), RegexCode_t12846533CAD1E4221CEDF5A4D15D4D649EA688FA::get_offset_of__strings_1(), RegexCode_t12846533CAD1E4221CEDF5A4D15D4D649EA688FA::get_offset_of__trackcount_2(), RegexCode_t12846533CAD1E4221CEDF5A4D15D4D649EA688FA::get_offset_of__caps_3(), RegexCode_t12846533CAD1E4221CEDF5A4D15D4D649EA688FA::get_offset_of__capsize_4(), RegexCode_t12846533CAD1E4221CEDF5A4D15D4D649EA688FA::get_offset_of__fcPrefix_5(), RegexCode_t12846533CAD1E4221CEDF5A4D15D4D649EA688FA::get_offset_of__bmPrefix_6(), RegexCode_t12846533CAD1E4221CEDF5A4D15D4D649EA688FA::get_offset_of__anchors_7(), RegexCode_t12846533CAD1E4221CEDF5A4D15D4D649EA688FA::get_offset_of__rightToLeft_8(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1505 = { sizeof (RegexFCD_tCEDC8A19D3317F0856BC21A345C7E57A41FA568E), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1505[7] = { RegexFCD_tCEDC8A19D3317F0856BC21A345C7E57A41FA568E::get_offset_of__intStack_0(), RegexFCD_tCEDC8A19D3317F0856BC21A345C7E57A41FA568E::get_offset_of__intDepth_1(), RegexFCD_tCEDC8A19D3317F0856BC21A345C7E57A41FA568E::get_offset_of__fcStack_2(), RegexFCD_tCEDC8A19D3317F0856BC21A345C7E57A41FA568E::get_offset_of__fcDepth_3(), RegexFCD_tCEDC8A19D3317F0856BC21A345C7E57A41FA568E::get_offset_of__skipAllChildren_4(), RegexFCD_tCEDC8A19D3317F0856BC21A345C7E57A41FA568E::get_offset_of__skipchild_5(), RegexFCD_tCEDC8A19D3317F0856BC21A345C7E57A41FA568E::get_offset_of__failed_6(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1506 = { sizeof (RegexFC_t076AC007C0B19472DFC727FF856B5755332B8B52), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1506[3] = { RegexFC_t076AC007C0B19472DFC727FF856B5755332B8B52::get_offset_of__cc_0(), RegexFC_t076AC007C0B19472DFC727FF856B5755332B8B52::get_offset_of__nullable_1(), RegexFC_t076AC007C0B19472DFC727FF856B5755332B8B52::get_offset_of__caseInsensitive_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1507 = { sizeof (RegexPrefix_tACADB52E91EFEB63B5EF7A1850634604F98FEE67), -1, sizeof(RegexPrefix_tACADB52E91EFEB63B5EF7A1850634604F98FEE67_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1507[3] = { RegexPrefix_tACADB52E91EFEB63B5EF7A1850634604F98FEE67::get_offset_of__prefix_0(), RegexPrefix_tACADB52E91EFEB63B5EF7A1850634604F98FEE67::get_offset_of__caseInsensitive_1(), RegexPrefix_tACADB52E91EFEB63B5EF7A1850634604F98FEE67_StaticFields::get_offset_of__empty_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1508 = { sizeof (Group_tB4759D0385925B2C8C14ED3FCD5D2F43CFBD0443), -1, sizeof(Group_tB4759D0385925B2C8C14ED3FCD5D2F43CFBD0443_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1508[4] = { Group_tB4759D0385925B2C8C14ED3FCD5D2F43CFBD0443_StaticFields::get_offset_of__emptygroup_3(), Group_tB4759D0385925B2C8C14ED3FCD5D2F43CFBD0443::get_offset_of__caps_4(), Group_tB4759D0385925B2C8C14ED3FCD5D2F43CFBD0443::get_offset_of__capcount_5(), Group_tB4759D0385925B2C8C14ED3FCD5D2F43CFBD0443::get_offset_of__name_6(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1509 = { sizeof (RegexInterpreter_tCFD7D68662C4B174087DA02FB6119836DD2EA7DA), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1509[11] = { RegexInterpreter_tCFD7D68662C4B174087DA02FB6119836DD2EA7DA::get_offset_of_runoperator_18(), RegexInterpreter_tCFD7D68662C4B174087DA02FB6119836DD2EA7DA::get_offset_of_runcodes_19(), RegexInterpreter_tCFD7D68662C4B174087DA02FB6119836DD2EA7DA::get_offset_of_runcodepos_20(), RegexInterpreter_tCFD7D68662C4B174087DA02FB6119836DD2EA7DA::get_offset_of_runstrings_21(), RegexInterpreter_tCFD7D68662C4B174087DA02FB6119836DD2EA7DA::get_offset_of_runcode_22(), RegexInterpreter_tCFD7D68662C4B174087DA02FB6119836DD2EA7DA::get_offset_of_runfcPrefix_23(), RegexInterpreter_tCFD7D68662C4B174087DA02FB6119836DD2EA7DA::get_offset_of_runbmPrefix_24(), RegexInterpreter_tCFD7D68662C4B174087DA02FB6119836DD2EA7DA::get_offset_of_runanchors_25(), RegexInterpreter_tCFD7D68662C4B174087DA02FB6119836DD2EA7DA::get_offset_of_runrtl_26(), RegexInterpreter_tCFD7D68662C4B174087DA02FB6119836DD2EA7DA::get_offset_of_runci_27(), RegexInterpreter_tCFD7D68662C4B174087DA02FB6119836DD2EA7DA::get_offset_of_runculture_28(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1510 = { sizeof (Match_tE447871AB59EED3642F31EB9559D162C2977EBB5), -1, sizeof(Match_tE447871AB59EED3642F31EB9559D162C2977EBB5_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1510[9] = { Match_tE447871AB59EED3642F31EB9559D162C2977EBB5_StaticFields::get_offset_of__empty_7(), Match_tE447871AB59EED3642F31EB9559D162C2977EBB5::get_offset_of__regex_8(), Match_tE447871AB59EED3642F31EB9559D162C2977EBB5::get_offset_of__textbeg_9(), Match_tE447871AB59EED3642F31EB9559D162C2977EBB5::get_offset_of__textpos_10(), Match_tE447871AB59EED3642F31EB9559D162C2977EBB5::get_offset_of__textend_11(), Match_tE447871AB59EED3642F31EB9559D162C2977EBB5::get_offset_of__textstart_12(), Match_tE447871AB59EED3642F31EB9559D162C2977EBB5::get_offset_of__matches_13(), Match_tE447871AB59EED3642F31EB9559D162C2977EBB5::get_offset_of__matchcount_14(), Match_tE447871AB59EED3642F31EB9559D162C2977EBB5::get_offset_of__balancing_15(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1511 = { sizeof (MatchSparse_t73BEE39B7EBE30B7460558DCA846B704C94B571C), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1511[1] = { MatchSparse_t73BEE39B7EBE30B7460558DCA846B704C94B571C::get_offset_of__caps_16(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1512 = { sizeof (RegexMatchTimeoutException_t78D3102CF3A9DEE18561827EDD878176482A6C7C), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1512[3] = { RegexMatchTimeoutException_t78D3102CF3A9DEE18561827EDD878176482A6C7C::get_offset_of_regexInput_17(), RegexMatchTimeoutException_t78D3102CF3A9DEE18561827EDD878176482A6C7C::get_offset_of_regexPattern_18(), RegexMatchTimeoutException_t78D3102CF3A9DEE18561827EDD878176482A6C7C::get_offset_of_matchTimeout_19(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1513 = { sizeof (RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1513[8] = { RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75::get_offset_of__type_0(), RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75::get_offset_of__children_1(), RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75::get_offset_of__str_2(), RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75::get_offset_of__ch_3(), RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75::get_offset_of__m_4(), RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75::get_offset_of__n_5(), RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75::get_offset_of__options_6(), RegexNode_tF92FC16590D5B00965BABFC709BA677DA0FC3F75::get_offset_of__next_7(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1514 = { sizeof (RegexOptions_t9A6138CDA9C60924D503C584095349F008C52EA1)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1514[11] = { RegexOptions_t9A6138CDA9C60924D503C584095349F008C52EA1::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1515 = { sizeof (RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE), -1, sizeof(RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1515[20] = { RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE::get_offset_of__stack_0(), RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE::get_offset_of__group_1(), RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE::get_offset_of__alternation_2(), RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE::get_offset_of__concatenation_3(), RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE::get_offset_of__unit_4(), RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE::get_offset_of__pattern_5(), RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE::get_offset_of__currentPos_6(), RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE::get_offset_of__culture_7(), RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE::get_offset_of__autocap_8(), RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE::get_offset_of__capcount_9(), RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE::get_offset_of__captop_10(), RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE::get_offset_of__capsize_11(), RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE::get_offset_of__caps_12(), RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE::get_offset_of__capnames_13(), RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE::get_offset_of__capnumlist_14(), RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE::get_offset_of__capnamelist_15(), RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE::get_offset_of__options_16(), RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE::get_offset_of__optionsStack_17(), RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE::get_offset_of__ignoreNextParen_18(), RegexParser_t9576D89D31260EF04DE583287FFC127132051FEE_StaticFields::get_offset_of__category_19(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1516 = { sizeof (RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1516[18] = { RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0::get_offset_of_runtextbeg_0(), RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0::get_offset_of_runtextend_1(), RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0::get_offset_of_runtextstart_2(), RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0::get_offset_of_runtext_3(), RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0::get_offset_of_runtextpos_4(), RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0::get_offset_of_runtrack_5(), RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0::get_offset_of_runtrackpos_6(), RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0::get_offset_of_runstack_7(), RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0::get_offset_of_runstackpos_8(), RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0::get_offset_of_runcrawl_9(), RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0::get_offset_of_runcrawlpos_10(), RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0::get_offset_of_runtrackcount_11(), RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0::get_offset_of_runmatch_12(), RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0::get_offset_of_runregex_13(), RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0::get_offset_of_timeout_14(), RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0::get_offset_of_ignoreTimeout_15(), RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0::get_offset_of_timeoutOccursAt_16(), RegexRunner_tBA888C4E3D3BA80EEE14878E4A330461730446B0::get_offset_of_timeoutChecksToSkip_17(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1517 = { sizeof (RegexRunnerFactory_t0703F390E2102623B0189DEC095DB182698E404B), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1518 = { sizeof (RegexTree_t8FE2EC649AB50FDA90239EA1410A881F278B47B6), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1518[7] = { RegexTree_t8FE2EC649AB50FDA90239EA1410A881F278B47B6::get_offset_of__root_0(), RegexTree_t8FE2EC649AB50FDA90239EA1410A881F278B47B6::get_offset_of__caps_1(), RegexTree_t8FE2EC649AB50FDA90239EA1410A881F278B47B6::get_offset_of__capnumlist_2(), RegexTree_t8FE2EC649AB50FDA90239EA1410A881F278B47B6::get_offset_of__capnames_3(), RegexTree_t8FE2EC649AB50FDA90239EA1410A881F278B47B6::get_offset_of__capslist_4(), RegexTree_t8FE2EC649AB50FDA90239EA1410A881F278B47B6::get_offset_of__options_5(), RegexTree_t8FE2EC649AB50FDA90239EA1410A881F278B47B6::get_offset_of__captop_6(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1519 = { sizeof (RegexWriter_t5F8CEA1FC9A4AC32A95BAC6E49EF51D7DF051AA6), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1519[10] = { RegexWriter_t5F8CEA1FC9A4AC32A95BAC6E49EF51D7DF051AA6::get_offset_of__intStack_0(), RegexWriter_t5F8CEA1FC9A4AC32A95BAC6E49EF51D7DF051AA6::get_offset_of__depth_1(), RegexWriter_t5F8CEA1FC9A4AC32A95BAC6E49EF51D7DF051AA6::get_offset_of__emitted_2(), RegexWriter_t5F8CEA1FC9A4AC32A95BAC6E49EF51D7DF051AA6::get_offset_of__curpos_3(), RegexWriter_t5F8CEA1FC9A4AC32A95BAC6E49EF51D7DF051AA6::get_offset_of__stringhash_4(), RegexWriter_t5F8CEA1FC9A4AC32A95BAC6E49EF51D7DF051AA6::get_offset_of__stringtable_5(), RegexWriter_t5F8CEA1FC9A4AC32A95BAC6E49EF51D7DF051AA6::get_offset_of__counting_6(), RegexWriter_t5F8CEA1FC9A4AC32A95BAC6E49EF51D7DF051AA6::get_offset_of__count_7(), RegexWriter_t5F8CEA1FC9A4AC32A95BAC6E49EF51D7DF051AA6::get_offset_of__trackcount_8(), RegexWriter_t5F8CEA1FC9A4AC32A95BAC6E49EF51D7DF051AA6::get_offset_of__caps_9(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1520 = { sizeof (ArrayConverter_tAAD8F39711C6ECD39D31226FA1D140DD38752B57), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1521 = { sizeof (BooleanConverter_tD0D177A9F577915FAA9F6749229672CE8EBAA94C), -1, sizeof(BooleanConverter_tD0D177A9F577915FAA9F6749229672CE8EBAA94C_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1521[1] = { BooleanConverter_tD0D177A9F577915FAA9F6749229672CE8EBAA94C_StaticFields::get_offset_of_values_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1522 = { sizeof (CollectionConverter_t039E15C433996B0F0F0EB78BEE81F6DE0705F184), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1523 = { sizeof (DecimalConverter_t10232B897580B6DE599BB375BE8C0F4E1C30B0C1), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1524 = { sizeof (DoubleConverter_t65A5D8B0C2736FC5469CE5DFA468D371DD5F9F75), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1525 = { sizeof (EditorBrowsableAttribute_tF3507DF0AB82A8D54C70D6F7FB4D363DF729D516), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1525[1] = { EditorBrowsableAttribute_tF3507DF0AB82A8D54C70D6F7FB4D363DF729D516::get_offset_of_browsableState_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1526 = { sizeof (EditorBrowsableState_t8EAF9BADAAE7DA735C235280DF4B8974EAA39C1B)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1526[4] = { EditorBrowsableState_t8EAF9BADAAE7DA735C235280DF4B8974EAA39C1B::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1527 = { sizeof (EnumConverter_t5DA4CB27C27A8C37C31B2A4DE0C4C37820638E12), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1527[2] = { EnumConverter_t5DA4CB27C27A8C37C31B2A4DE0C4C37820638E12::get_offset_of_values_2(), EnumConverter_t5DA4CB27C27A8C37C31B2A4DE0C4C37820638E12::get_offset_of_type_3(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1528 = { sizeof (Int16Converter_tA2223DDF2BE99AD79AD836FCEC90F2C12705433B), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1529 = { sizeof (Int32Converter_t73A6E403EBE01B56528CB227509954397A46BA22), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1530 = { sizeof (Int64Converter_tED09C98C409F894484943F8D4F9C6468A97F1447), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1531 = { sizeof (SingleConverter_t86A24FBD46D753B99344470E9566584F15538902), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1532 = { sizeof (StringConverter_t054FA0796F4C8E951208AFA052D99BCB8E68BED7), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1533 = { sizeof (TimeSpanConverter_t4025A0861C52420BC73D837729E5EFA6ECDE07C7), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1534 = { sizeof (TypeConverter_t8306AE03734853B551DDF089C1F17836A7764DBB), -1, sizeof(TypeConverter_t8306AE03734853B551DDF089C1F17836A7764DBB_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1534[2] = { 0, TypeConverter_t8306AE03734853B551DDF089C1F17836A7764DBB_StaticFields::get_offset_of_useCompatibleTypeConversion_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1535 = { sizeof (StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1535[2] = { StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3::get_offset_of_values_0(), StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3::get_offset_of_valueArray_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1536 = { sizeof (TypeConverterAttribute_tA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8), -1, sizeof(TypeConverterAttribute_tA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1536[2] = { TypeConverterAttribute_tA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8::get_offset_of_typeName_0(), TypeConverterAttribute_tA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8_StaticFields::get_offset_of_Default_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1537 = { sizeof (Win32Exception_tB05BE97AB4CADD54DF96C0109689F0ECA7517668), -1, sizeof(Win32Exception_tB05BE97AB4CADD54DF96C0109689F0ECA7517668_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1537[3] = { Win32Exception_tB05BE97AB4CADD54DF96C0109689F0ECA7517668::get_offset_of_nativeErrorCode_17(), Win32Exception_tB05BE97AB4CADD54DF96C0109689F0ECA7517668_StaticFields::get_offset_of_s_ErrorMessagesInitialized_18(), Win32Exception_tB05BE97AB4CADD54DF96C0109689F0ECA7517668_StaticFields::get_offset_of_s_ErrorMessage_19(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1538 = { sizeof (BaseNumberConverter_t6AF36A2503E7BABF7FB9A8EC05DF8B828491AC63), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1539 = { sizeof (OidGroup_t9A99D3013C1B94CB060656F30C39E893E75FAD6B)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1539[12] = { OidGroup_t9A99D3013C1B94CB060656F30C39E893E75FAD6B::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1540 = { sizeof (Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1540[3] = { Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137::get_offset_of_m_value_0(), Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137::get_offset_of_m_friendlyName_1(), Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137::get_offset_of_m_group_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1541 = { sizeof (OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1541[1] = { OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E::get_offset_of_m_list_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1542 = { sizeof (OidEnumerator_tC2DB288576C575B69F7934274DDD8A5868CEF97C), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1542[2] = { OidEnumerator_tC2DB288576C575B69F7934274DDD8A5868CEF97C::get_offset_of_m_oids_0(), OidEnumerator_tC2DB288576C575B69F7934274DDD8A5868CEF97C::get_offset_of_m_current_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1543 = { sizeof (CAPI_tEA68010AC3470FFEBC91FC9D3C13E7D7064C3267), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1544 = { sizeof (AsnDecodeStatus_t83139F58FFE08CE7DBCB990C9F30D2F2CA5BC0BB)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1544[7] = { AsnDecodeStatus_t83139F58FFE08CE7DBCB990C9F30D2F2CA5BC0BB::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1545 = { sizeof (AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1545[2] = { AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65::get_offset_of__oid_0(), AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65::get_offset_of__raw_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1546 = { sizeof (X509KeyUsageFlags_tAD6560EDDEB746BA983AE4E7ABC237A6178D6437)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1546[11] = { X509KeyUsageFlags_tAD6560EDDEB746BA983AE4E7ABC237A6178D6437::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1547 = { sizeof (X509SubjectKeyIdentifierHashAlgorithm_t7928324BFDBB7B255970D50D0D8972FDFC981A0C)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1547[4] = { X509SubjectKeyIdentifierHashAlgorithm_t7928324BFDBB7B255970D50D0D8972FDFC981A0C::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1548 = { sizeof (X509Utils_t596E1974703C7988010495E60F15BE9680FC71B8), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1549 = { sizeof (PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620), -1, sizeof(PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1549[4] = { PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620::get_offset_of__keyValue_0(), PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620::get_offset_of__params_1(), PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620::get_offset_of__oid_2(), PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620_StaticFields::get_offset_of_Empty_3(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1550 = { sizeof (X509BasicConstraintsExtension_t091983B3CDCB686781B4853177610A22483B532C), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1550[6] = { 0, 0, X509BasicConstraintsExtension_t091983B3CDCB686781B4853177610A22483B532C::get_offset_of__certificateAuthority_5(), X509BasicConstraintsExtension_t091983B3CDCB686781B4853177610A22483B532C::get_offset_of__hasPathLengthConstraint_6(), X509BasicConstraintsExtension_t091983B3CDCB686781B4853177610A22483B532C::get_offset_of__pathLengthConstraint_7(), X509BasicConstraintsExtension_t091983B3CDCB686781B4853177610A22483B532C::get_offset_of__status_8(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1551 = { sizeof (X509EnhancedKeyUsageExtension_t8B1FEC5814799207635A97EA878EA64688437254), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1551[2] = { X509EnhancedKeyUsageExtension_t8B1FEC5814799207635A97EA878EA64688437254::get_offset_of__enhKeyUsage_3(), X509EnhancedKeyUsageExtension_t8B1FEC5814799207635A97EA878EA64688437254::get_offset_of__status_4(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1552 = { sizeof (X509Extension_t223237DF0C323CC455D3A2634D977773D2F3818A), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1552[1] = { X509Extension_t223237DF0C323CC455D3A2634D977773D2F3818A::get_offset_of__critical_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1553 = { sizeof (X509KeyUsageExtension_t9F740A60AD6DBEF9B09E946D4D8D67DB882C6E6E), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1553[5] = { 0, 0, 0, X509KeyUsageExtension_t9F740A60AD6DBEF9B09E946D4D8D67DB882C6E6E::get_offset_of__keyUsages_6(), X509KeyUsageExtension_t9F740A60AD6DBEF9B09E946D4D8D67DB882C6E6E::get_offset_of__status_7(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1554 = { sizeof (X509SubjectKeyIdentifierExtension_t200DBBEB1229862DAA5F56EA352B03D2EDAC4D8E), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1554[5] = { 0, 0, X509SubjectKeyIdentifierExtension_t200DBBEB1229862DAA5F56EA352B03D2EDAC4D8E::get_offset_of__subjectKeyIdentifier_5(), X509SubjectKeyIdentifierExtension_t200DBBEB1229862DAA5F56EA352B03D2EDAC4D8E::get_offset_of__ski_6(), X509SubjectKeyIdentifierExtension_t200DBBEB1229862DAA5F56EA352B03D2EDAC4D8E::get_offset_of__status_7(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1555 = { sizeof (EndPoint_tD87FCEF2780A951E8CE8D808C345FBF2C088D980), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1556 = { sizeof (IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE), -1, sizeof(IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1556[17] = { IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE_StaticFields::get_offset_of_Any_0(), IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE_StaticFields::get_offset_of_Loopback_1(), IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE_StaticFields::get_offset_of_Broadcast_2(), IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE_StaticFields::get_offset_of_None_3(), 0, IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE::get_offset_of_m_Address_5(), IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE::get_offset_of_m_ToString_6(), IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE_StaticFields::get_offset_of_IPv6Any_7(), IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE_StaticFields::get_offset_of_IPv6Loopback_8(), IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE_StaticFields::get_offset_of_IPv6None_9(), IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE::get_offset_of_m_Family_10(), IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE::get_offset_of_m_Numbers_11(), IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE::get_offset_of_m_ScopeId_12(), IPAddress_t77F35D21A3027F0CE7B38EA9B56BFD31B28952CE::get_offset_of_m_HashCode_13(), 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1557 = { sizeof (IPv6AddressFormatter_t451290B1C6FD64B6C59F95D99EDB4A9CC703BA90)+ sizeof (RuntimeObject), sizeof(IPv6AddressFormatter_t451290B1C6FD64B6C59F95D99EDB4A9CC703BA90 ), 0, 0 }; extern const int32_t g_FieldOffsetTable1557[2] = { IPv6AddressFormatter_t451290B1C6FD64B6C59F95D99EDB4A9CC703BA90::get_offset_of_address_0() + static_cast<int32_t>(sizeof(RuntimeObject)), IPv6AddressFormatter_t451290B1C6FD64B6C59F95D99EDB4A9CC703BA90::get_offset_of_scopeId_1() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1558 = { sizeof (SocketException_t75481CF49BCAF5685A5A9E6933909E0B65E7E0A5), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1558[1] = { SocketException_t75481CF49BCAF5685A5A9E6933909E0B65E7E0A5::get_offset_of_m_EndPoint_20(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1559 = { sizeof (AddressFamily_tFA4F79FA7F299EBDF507F4811E6E5C3EEBF0850E)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1559[32] = { AddressFamily_tFA4F79FA7F299EBDF507F4811E6E5C3EEBF0850E::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1560 = { sizeof (SocketError_t0157BEC7F0A26C8FC31D392B2B7C6CFCD695D5E7)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1560[48] = { SocketError_t0157BEC7F0A26C8FC31D392B2B7C6CFCD695D5E7::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1561 = { 0, 0, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1562 = { 0, 0, 0, 0 }; extern const int32_t g_FieldOffsetTable1562[5] = { 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1563 = { 0, 0, 0, 0 }; extern const int32_t g_FieldOffsetTable1563[5] = { 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1564 = { 0, 0, 0, 0 }; extern const int32_t g_FieldOffsetTable1564[4] = { 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1565 = { 0, 0, 0, 0 }; extern const int32_t g_FieldOffsetTable1565[4] = { 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1566 = { 0, 0, 0, 0 }; extern const int32_t g_FieldOffsetTable1566[4] = { 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1567 = { 0, 0, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1568 = { 0, 0, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1569 = { sizeof (U3CPrivateImplementationDetailsU3E_tD3F45A95FC1F3A32916F221D83F290D182AD6291), -1, sizeof(U3CPrivateImplementationDetailsU3E_tD3F45A95FC1F3A32916F221D83F290D182AD6291_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1569[4] = { U3CPrivateImplementationDetailsU3E_tD3F45A95FC1F3A32916F221D83F290D182AD6291_StaticFields::get_offset_of_U359F5BD34B6C013DEACC784F69C67E95150033A84_0(), U3CPrivateImplementationDetailsU3E_tD3F45A95FC1F3A32916F221D83F290D182AD6291_StaticFields::get_offset_of_C02C28AFEBE998F767E4AF43E3BE8F5E9FA11536_1(), U3CPrivateImplementationDetailsU3E_tD3F45A95FC1F3A32916F221D83F290D182AD6291_StaticFields::get_offset_of_CCEEADA43268372341F81AE0C9208C6856441C04_2(), U3CPrivateImplementationDetailsU3E_tD3F45A95FC1F3A32916F221D83F290D182AD6291_StaticFields::get_offset_of_E5BC1BAFADE1862DD6E0B9FB632BFAA6C3873A78_3(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1570 = { sizeof (__StaticArrayInitTypeSizeU3D32_t5300E5FCBD58716E8A4EBB9470E4FAE1A0A964FA)+ sizeof (RuntimeObject), sizeof(__StaticArrayInitTypeSizeU3D32_t5300E5FCBD58716E8A4EBB9470E4FAE1A0A964FA ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1571 = { sizeof (__StaticArrayInitTypeSizeU3D128_t4A42759E6E25B0C61E6036A661F4344DE92C2905)+ sizeof (RuntimeObject), sizeof(__StaticArrayInitTypeSizeU3D128_t4A42759E6E25B0C61E6036A661F4344DE92C2905 ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1572 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1573 = { sizeof (BypassElement_t89C59A549C7A25609AA5C200352CD9E310172BAF), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1574 = { sizeof (BypassElementCollection_t5CCE032F76311FCEFC3128DA5A88D25568A234A7), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1575 = { sizeof (ConnectionManagementElement_tABDA95F63A9CBFC2720D7D3F15C5B352EC5CE7AD), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1576 = { sizeof (ConnectionManagementElementCollection_t83F843AEC2D2354836CC863E346FE2ECFEED2572), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1577 = { sizeof (ConnectionManagementSection_tA88F9BAD144E401AB524A9579B50050140592447), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1578 = { sizeof (DefaultProxySection_tB752851846FC0CEBA83C36C2BF6553211029AA3B), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1579 = { sizeof (ProxyElement_tBD5D75620576BA5BB5521C11D09E0A6E996F9449), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1580 = { sizeof (HttpWebRequestElement_t3E2FC0EB83C362CC92300949AF90A0B0BE01EA3D), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1581 = { sizeof (Ipv6Element_tCA869DC79FE3740DBDECC47877F1676294DB4A23), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1582 = { sizeof (NetSectionGroup_tA4ACD82AFE8B5C11E509FA8623D554BB5B4DB591), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1583 = { sizeof (SettingsSection_t8BECD0EB76F1865B33D072DD368676A8D51840B3), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1584 = { sizeof (PerformanceCountersElement_tCE4CFF0A3503E44D7B8EC6E85FD3C50EB1A1B570), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1585 = { sizeof (ServicePointManagerElement_tD8D1491569C963460C14DF4D42ED05DF34428CFC), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1586 = { sizeof (SocketElement_t32F016077CBED287B80063811E80BCCC7E8B1BF9), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1587 = { sizeof (WebProxyScriptElement_t4302A26A6D4E02146662B30E3452A5167966E6B3), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1588 = { sizeof (WebRequestModulesSection_t5E031F632797D2C7F0D394BCEE4BD0DF0ECA81BC), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1589 = { sizeof (WebRequestModuleElementCollection_t2A993B681E96AAF6A96CCB0458F0F0B99BFF51BE), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1590 = { sizeof (WebRequestModuleElement_tE81A1FA5B9B4BCFB1ED015287A2D4F9EED37F3EC), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1591 = { sizeof (DiagnosticsConfigurationHandler_t885EAAD2DCF9678F16E3BB296E307868ECE68239), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1592 = { sizeof (ThrowStub_t03526C535287FADF58CBFA05084AE89A0ACFFEFA), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1593 = { sizeof (U3CModuleU3E_t239CA80C3AF3E763FA4B9A9F3CFADF0768B426EE), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1594 = { sizeof (ASN1_t2B883D12D3493F8395B31D1F0ABD93F43948B27E), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1594[3] = { ASN1_t2B883D12D3493F8395B31D1F0ABD93F43948B27E::get_offset_of_m_nTag_0(), ASN1_t2B883D12D3493F8395B31D1F0ABD93F43948B27E::get_offset_of_m_aValue_1(), ASN1_t2B883D12D3493F8395B31D1F0ABD93F43948B27E::get_offset_of_elist_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1595 = { sizeof (ASN1Convert_t5F783CA2300717B94F27A342A75A0E57B73FCC05), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1596 = { sizeof (BitConverterLE_t4CE9DF1164753ED72B6F4F33581C35FBCAEEC109), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1597 = { sizeof (CryptoConvert_tF1F175C2F2C9E65FE7D5FBF0D434B964E4CAFF76), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1598 = { sizeof (U3CModuleU3E_t4F43141ACD9FFF670814886815EB7CDCD95E3951), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1599 = { sizeof (ConfigurationSection_t044F68052218C8000611AE9ADD5F66E62A632B34), -1, 0, 0 }; #ifdef __clang__ #pragma clang diagnostic pop #endif
#include "Includes.hpp" #include "EnvironmentMapConfig.h" namespace Prehistoric { namespace EnvironmentMapConfig { std::string environmentMapLocation; uint32_t environmentMapResolution; uint32_t irradianceMapResolution; uint32_t prefilterMapResolution; uint32_t prefilterLevels; Texture* environmentMap; Texture* irradianceMap; Texture* prefilterMap; Texture* brdfLUT; void EnvironmentMapConfig::LoadConfig(const std::string& path) { std::ifstream file; file.open(path.c_str()); std::string line; if (file.is_open()) { while (file.good()) { std::getline(file, line); std::vector<std::string> tokens = Util::Split(line, ' '); std::vector<std::string> nameTokens = Util::Split(tokens[0], '.'); if (line.substr(0, 1).c_str()[0] == '#') { continue; //This line is a comment then } else if (nameTokens[0] == "environment") { if (nameTokens[1] == "map") { if (nameTokens[2] == "location") { environmentMapLocation = tokens[1]; } else if (nameTokens[2] == "resolution") { environmentMapResolution = std::atoi(tokens[1].c_str()); } } } else if (nameTokens[0] == "irradiance") { if (nameTokens[1] == "map") { if (nameTokens[2] == "resolution") { irradianceMapResolution = std::atoi(tokens[1].c_str()); } } } else if (nameTokens[0] == "prefilter") { if (nameTokens[1] == "map") { if (nameTokens[2] == "resolution") { prefilterMapResolution = std::atoi(tokens[1].c_str()); } } else if (nameTokens[1] == "levels") { prefilterLevels = std::atoi(tokens[1].c_str()); } } } file.close(); } else { PR_LOG_ERROR("File %s cannot be opened!", path.c_str()); } } }; };
#include <cmath> #include "haven_types.h" #include <cpp11/protect.hpp> FileVendor extVendor(FileExt ext) { switch (ext) { case HAVEN_DTA: return HAVEN_STATA; case HAVEN_SAV: case HAVEN_POR: return HAVEN_SPSS; case HAVEN_SAS7BDAT: case HAVEN_SAS7BCAT: case HAVEN_XPT: return HAVEN_SAS; default: cpp11::stop("Unknown file extension"); } /* not actually reached */ return HAVEN_SAS; } std::string formatAttribute(FileVendor vendor) { switch (vendor) { case HAVEN_STATA: return "format.stata"; case HAVEN_SPSS: return "format.spss"; case HAVEN_SAS: return "format.sas"; } return ""; } bool hasPrefix(std::string x, std::string prefix) { return x.compare(0, prefix.size(), prefix) == 0; } VarType numType(SEXP x) { if (Rf_inherits(x, "Date")) { return HAVEN_DATE; } else if (Rf_inherits(x, "POSIXct")) { return HAVEN_DATETIME; } else if (Rf_inherits(x, "hms")) { return HAVEN_TIME; } else { return HAVEN_DEFAULT; } } VarType numType(FileVendor vendor, const char* var_format) { if (var_format == NULL) return HAVEN_DEFAULT; std::string format(var_format); switch(vendor) { case HAVEN_SAS: // http://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a000589916.htm if (hasPrefix(format,"DATETIME")) return HAVEN_DATETIME; else if (hasPrefix(format,"IS8601DT")) return HAVEN_DATETIME; else if (hasPrefix(format,"E8601DT")) return HAVEN_DATETIME; else if (hasPrefix(format,"B8601DT")) return HAVEN_DATETIME; else if (hasPrefix(format,"IS8601DA")) return HAVEN_DATE; else if (hasPrefix(format,"E8601DA")) return HAVEN_DATE; else if (hasPrefix(format,"B8601DA")) return HAVEN_DATE; else if (hasPrefix(format,"WEEKDATE")) return HAVEN_DATE; else if (hasPrefix(format,"MMDDYY")) return HAVEN_DATE; else if (hasPrefix(format,"DDMMYY")) return HAVEN_DATE; else if (hasPrefix(format,"YYMMDD")) return HAVEN_DATE; else if (hasPrefix(format,"DATE")) return HAVEN_DATE; else if (hasPrefix(format,"TIME")) return HAVEN_TIME; else if (hasPrefix(format,"HHMM")) return HAVEN_TIME; else if (hasPrefix(format,"IS8601TM")) return HAVEN_TIME; else if (hasPrefix(format,"E8601TM")) return HAVEN_TIME; else if (hasPrefix(format,"B8601TM")) return HAVEN_TIME; else return HAVEN_DEFAULT; case HAVEN_SPSS: // http://www-01.ibm.com/support/knowledgecenter/?lang=en#!/SSLVMB_20.0.0/com.ibm.spss.statistics.help/syn_date_and_time_date_time_formats.htm if (hasPrefix(format, "DATETIME")) return HAVEN_DATETIME; else if (hasPrefix(format, "DATE")) return HAVEN_DATE; else if (hasPrefix(format, "ADATE")) return HAVEN_DATE; else if (hasPrefix(format, "EDATE")) return HAVEN_DATE; else if (hasPrefix(format, "JDATE")) return HAVEN_DATE; else if (hasPrefix(format, "SDATE")) return HAVEN_DATE; else if (hasPrefix(format, "TIME")) return HAVEN_TIME; else if (hasPrefix(format, "DTIME")) return HAVEN_TIME; else return HAVEN_DEFAULT; case HAVEN_STATA: if (hasPrefix(format, "%tC")) return HAVEN_DATETIME; else if (hasPrefix(format, "%tc")) return HAVEN_DATETIME; else if (hasPrefix(format, "%td")) return HAVEN_DATE; else if (hasPrefix(format, "%d")) return HAVEN_DATE; else return HAVEN_DEFAULT; } return HAVEN_DEFAULT; } // Value conversion ----------------------------------------------------------- int daysOffset(FileVendor vendor) { switch(vendor) { case HAVEN_SAS: return 3653; // 1960-01-01 case HAVEN_STATA: return 3653; case HAVEN_SPSS: return 141428; // 1582-01-01 } return 0; } double adjustDatetimeToR(FileVendor vendor, VarType var, double value) { if (std::isnan(value)) return value; double offset = daysOffset(vendor); switch(var) { case HAVEN_DATETIME: if (vendor == HAVEN_STATA) // stored in milliseconds value /= 1000; return value - offset * 86400; case HAVEN_DATE: if (vendor == HAVEN_SPSS) // stored in seconds value /= 86400; return value - offset; default: return value; } } double adjustDatetimeFromR(FileVendor vendor, SEXP col, double value) { if (std::isnan(value)) return value; double offset = daysOffset(vendor); switch(numType(col)) { case HAVEN_DATETIME: value += offset * 86400; if (vendor == HAVEN_STATA) // stored in milliseconds value *= 1000; return value; case HAVEN_DATE: value += offset; if (vendor == HAVEN_SPSS) // stored in seconds value *= 86400; return value; default: return value; } }
/******************************************************************************** * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute, * Faculty of Engineering, University of Southern Denmark * * 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 RWSIM_UTIL_MOVINGAVERAGE_HPP_ #define RWSIM_UTIL_MOVINGAVERAGE_HPP_ #include <vector> namespace rwsim { namespace util { /** * @brief */ class MovingAverage { public: MovingAverage (int len) : _len (len), _invLen (1.0 / len), _cb (_len, 0.0), _sum (0.0), _idx (0) {} void addSample (double sample) { _sum -= _cb[_idx]; _sum += sample; _cb[_idx] = sample; _idx++; if (_idx == _len) _idx = 0; } double getAverage () { return _sum * _invLen; } private: const int _len; double _invLen; std::vector< double > _cb; double _sum; int _idx; }; }} // namespace rwsim::util #endif /* MOVINGAVERAGE_HPP_ */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\ * * * SHARED PTR * * * * Copyright © 2011+ Ángel Rodriguez Ballesteros * * * * Distributed under the Boost Software License, version 1.0 * * See documents/LICENSE.TXT or www.boost.org/LICENSE_1_0.txt * * * * angel.rodriguez@esne.edu * * * \* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef TOOLKIT_SHARED_PTR_HEADER #define TOOLKIT_SHARED_PTR_HEADER #include <memory> #include <cassert> #include "types.hpp" namespace toolkit { template< typename TYPE > class Shared_Ptr { template< typename ANY_TYPE > friend class Shared_Ptr; public: typedef TYPE element_type; typedef size_t counter_type; private: element_type * address; counter_type * counter; public: Shared_Ptr() { clear (); } Shared_Ptr(Null) { clear (); } explicit Shared_Ptr(element_type * given_address) : address(given_address), counter(new counter_type(1)) { } Shared_Ptr(const Shared_Ptr & other) { hold (other.address, other.counter); } public: explicit Shared_Ptr(std::auto_ptr< element_type > other_address) : address(other_address.release ()), counter(new counter_type(1)) { } public: template< typename RELATED_TYPE > explicit Shared_Ptr(RELATED_TYPE * given_address) : address(given_address), counter(new counter_type(1)) { } template< typename RELATED_TYPE > Shared_Ptr(const Shared_Ptr< RELATED_TYPE > & other) { hold (other.address, other.counter); } template< typename RELATED_TYPE > explicit Shared_Ptr(std::auto_ptr< RELATED_TYPE > pointer) : address(pointer.release ( )), counter(new counter_type(1)) { } public: ~Shared_Ptr() { reset (); } public: element_type * get () const { return (address); } size_t use_count () const { return (counter ? *counter : 0); } bool unique () const { return (counter && *counter == 1); } bool is_null () const { return (address == 0); } bool is_not_null () const { return (address != 0); } public: void reset () { release (); clear (); } template< typename RELATED_TYPE > void reset (RELATED_TYPE * new_address) { release (); if (new_address == 0) { clear (); } else { address = new_address; counter = new counter_type(1); } } public: Shared_Ptr & operator = (const Shared_Ptr & other) { if (other.address == 0) { reset (); } else if (other.address != this->address) { release (); this->address = other.address; *(this->counter = other.counter) += 1; } return (*this); } template< typename RELATED_TYPE > Shared_Ptr & operator = (const Shared_Ptr< RELATED_TYPE > & other) { if (other.address == 0) { reset (); } else if (other.address != this->address) { release (); this->address = other.address; *(this->counter = other.counter) += 1; } return (*this); } public: TYPE & operator * () const { assert (address); return *address; } TYPE * operator -> () const { assert (address); return (address); } operator bool () const { return (address != 0); } public: template< typename RELATED_TYPE > bool operator == (const Shared_Ptr< RELATED_TYPE > & other) const { return (this->address == other.address); } template< typename RELATED_TYPE > bool operator != (const Shared_Ptr< RELATED_TYPE > & other) const { return (this->address != other.address); } private: void hold (element_type * new_address, counter_type * new_counter) { address = new_address; counter = new_counter; if (new_address != 0) { ++(*counter); } } void release () { if (counter && --(*counter) == 0) { delete address; delete counter; } } void clear () { address = 0; counter = 0; } }; } #endif
//===-- llvm/MC/MCLinkerOptimizationHint.cpp ----- LOH handling -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/MC/MCLinkerOptimizationHint.h" #include "llvm/MC/MCAsmLayout.h" #include "llvm/MC/MCAssembler.h" #include "llvm/MC/MCMachObjectWriter.h" #include "llvm/Support/LEB128.h" using namespace llvm; // Each LOH is composed by, in this order (each field is encoded using ULEB128): // - Its kind. // - Its number of arguments (let say N). // - Its arg1. // - ... // - Its argN. // <arg1> to <argN> are absolute addresses in the object file, i.e., // relative addresses from the beginning of the object file. void MCLOHDirective::emit_impl(raw_ostream &OutStream, const MachObjectWriter &ObjWriter, const MCAsmLayout &Layout) const { encodeULEB128(Kind, OutStream); encodeULEB128(Args.size(), OutStream); for (const MCSymbol *Arg : Args) encodeULEB128(ObjWriter.getSymbolAddress(*Arg, Layout), OutStream); } void MCLOHDirective::emit(MachObjectWriter &ObjWriter, const MCAsmLayout &Layout) const { raw_ostream &OutStream = ObjWriter.getStream(); emit_impl(OutStream, ObjWriter, Layout); } uint64_t MCLOHDirective::getEmitSize(const MachObjectWriter &ObjWriter, const MCAsmLayout &Layout) const { class raw_counting_ostream : public raw_ostream { uint64_t Count; void write_impl(const char *, size_t size) override { Count += size; } uint64_t current_pos() const override { return Count; } public: raw_counting_ostream() : Count(0) {} ~raw_counting_ostream() override { flush(); } }; raw_counting_ostream OutStream; emit_impl(OutStream, ObjWriter, Layout); return OutStream.tell(); }
/* * Copyright 2016-present Facebook, 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 <folly/portability/Sockets.h> #ifdef _MSC_VER #include <errno.h> #include <fcntl.h> #include <MSWSock.h> // @manual #include <folly/ScopeGuard.h> #include <folly/net/NetworkSocket.h> #include <folly/net/detail/SocketFileDescriptorMap.h> namespace folly { namespace portability { namespace sockets { namespace { int network_socket_to_fd(NetworkSocket sock) { return socket_to_fd(sock.data); } NetworkSocket fd_to_network_socket(int fd) { return NetworkSocket(fd_to_socket(fd)); } } // namespace bool is_fh_socket(int fh) { SOCKET h = fd_to_socket(fh); constexpr long kDummyEvents = 0xABCDEF12; WSANETWORKEVENTS e; e.lNetworkEvents = kDummyEvents; WSAEnumNetworkEvents(h, nullptr, &e); return e.lNetworkEvents != kDummyEvents; } SOCKET fd_to_socket(int fd) { return netops::detail::SocketFileDescriptorMap::fdToSocket(fd); } int socket_to_fd(SOCKET s) { return netops::detail::SocketFileDescriptorMap::socketToFd(s); } template <class R, class F, class... Args> static R wrapSocketFunction(F f, int s, Args... args) { NetworkSocket h = fd_to_network_socket(s); return f(h, args...); } int accept(int s, struct sockaddr* addr, socklen_t* addrlen) { return network_socket_to_fd( wrapSocketFunction<NetworkSocket>(netops::accept, s, addr, addrlen)); } int bind(int s, const struct sockaddr* name, socklen_t namelen) { return wrapSocketFunction<int>(netops::bind, s, name, namelen); } int connect(int s, const struct sockaddr* name, socklen_t namelen) { return wrapSocketFunction<int>(netops::connect, s, name, namelen); } int getpeername(int s, struct sockaddr* name, socklen_t* namelen) { return wrapSocketFunction<int>(netops::getpeername, s, name, namelen); } int getsockname(int s, struct sockaddr* name, socklen_t* namelen) { return wrapSocketFunction<int>(netops::getsockname, s, name, namelen); } int getsockopt(int s, int level, int optname, char* optval, socklen_t* optlen) { return getsockopt(s, level, optname, (void*)optval, optlen); } int getsockopt(int s, int level, int optname, void* optval, socklen_t* optlen) { return wrapSocketFunction<int>( netops::getsockopt, s, level, optname, optval, optlen); } int inet_aton(const char* cp, struct in_addr* inp) { return netops::inet_aton(cp, inp); } const char* inet_ntop(int af, const void* src, char* dst, socklen_t size) { return ::inet_ntop(af, (char*)src, dst, size_t(size)); } int listen(int s, int backlog) { return wrapSocketFunction<int>(netops::listen, s, backlog); } int poll(struct pollfd fds[], nfds_t nfds, int timeout) { // NetOps already has the checks to ensure this is safe. netops::PollDescriptor* desc = reinterpret_cast<netops::PollDescriptor*>(reinterpret_cast<void*>(fds)); for (nfds_t i = 0; i < nfds; ++i) { desc[i].fd = fd_to_network_socket((int)desc[i].fd.data); } return netops::poll(desc, nfds, timeout); } ssize_t recv(int s, void* buf, size_t len, int flags) { return wrapSocketFunction<ssize_t>(netops::recv, s, buf, len, flags); } ssize_t recv(int s, char* buf, int len, int flags) { return recv(s, (void*)buf, (size_t)len, flags); } ssize_t recv(int s, void* buf, int len, int flags) { return recv(s, (void*)buf, (size_t)len, flags); } ssize_t recvfrom( int s, void* buf, size_t len, int flags, struct sockaddr* from, socklen_t* fromlen) { return wrapSocketFunction<ssize_t>( netops::recvfrom, s, buf, len, flags, from, fromlen); } ssize_t recvfrom( int s, char* buf, int len, int flags, struct sockaddr* from, socklen_t* fromlen) { return recvfrom(s, (void*)buf, (size_t)len, flags, from, fromlen); } ssize_t recvfrom( int s, void* buf, int len, int flags, struct sockaddr* from, socklen_t* fromlen) { return recvfrom(s, (void*)buf, (size_t)len, flags, from, fromlen); } ssize_t recvmsg(int s, struct msghdr* message, int flags) { return wrapSocketFunction<ssize_t>(netops::recvmsg, s, message, flags); } ssize_t send(int s, const void* buf, size_t len, int flags) { return wrapSocketFunction<ssize_t>(netops::send, s, buf, len, flags); } ssize_t send(int s, const char* buf, int len, int flags) { return send(s, (const void*)buf, (size_t)len, flags); } ssize_t send(int s, const void* buf, int len, int flags) { return send(s, (const void*)buf, (size_t)len, flags); } ssize_t sendmsg(int s, const struct msghdr* message, int flags) { return wrapSocketFunction<ssize_t>(netops::sendmsg, s, message, flags); } ssize_t sendto( int s, const void* buf, size_t len, int flags, const sockaddr* to, socklen_t tolen) { return wrapSocketFunction<ssize_t>( netops::sendto, s, buf, len, flags, to, tolen); } ssize_t sendto( int s, const char* buf, int len, int flags, const sockaddr* to, socklen_t tolen) { return sendto(s, (const void*)buf, (size_t)len, flags, to, tolen); } ssize_t sendto( int s, const void* buf, int len, int flags, const sockaddr* to, socklen_t tolen) { return sendto(s, buf, (size_t)len, flags, to, tolen); } int setsockopt( int s, int level, int optname, const void* optval, socklen_t optlen) { return wrapSocketFunction<int>( netops::setsockopt, s, level, optname, optval, optlen); } int setsockopt( int s, int level, int optname, const char* optval, socklen_t optlen) { return setsockopt(s, level, optname, (const void*)optval, optlen); } int shutdown(int s, int how) { return wrapSocketFunction<int>(netops::shutdown, s, how); } int socket(int af, int type, int protocol) { return network_socket_to_fd(netops::socket(af, type, protocol)); } int socketpair(int domain, int type, int protocol, int sv[2]) { NetworkSocket pair[2]; auto r = netops::socketpair(domain, type, protocol, pair); if (r == -1) { return r; } sv[0] = network_socket_to_fd(pair[0]); sv[1] = network_socket_to_fd(pair[1]); return 0; } } // namespace sockets } // namespace portability } // namespace folly #endif
/* ==================================================================== * The Vovida Software License, Version 1.0 * * Copyright (c) 2000 Vovida Networks, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "VOCAL", "Vovida Open Communication Application Library", * and "Vovida Open Communication Application Library (VOCAL)" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact vocal@vovida.org. * * 4. Products derived from this software may not be called "VOCAL", nor * may "VOCAL" appear in their name, without prior written * permission of Vovida Networks, Inc. * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND * NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL VOVIDA * NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES * IN EXCESS OF $1,000, NOR FOR ANY INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * * ==================================================================== * * This software consists of voluntary contributions made by Vovida * Networks, Inc. and many individuals on behalf of Vovida Networks, * Inc. For more information on Vovida Networks, Inc., please see * <http://www.vovida.org/>. * */ static const char* const SipBasicTest_cxx_Version = "$Id: SipBasicTest.cxx,v 1.1 2004/05/01 04:15:26 greear Exp $"; #include "SipBasic.hxx" #include "Verify.hxx" #include "SystemInfo.hxx" string host_addr = Vocal::theSystem.gethostAddress(); using namespace Vocal; int main() { Data user("Aladdin"); Data passwd("open sesame"); Data user2("sunitha"); Data passwd2("passwd"); Data user3("sunitha"); Data passwd3("passwd"); Data user4("sunitha"); Data passwd4("passwd2"); SipBasic first; SipBasic second; SipBasic third; SipBasic fourth; Data firstSum = first.formSIPBasic(user, passwd); Data secondSum = second.formSIPBasic(user2, passwd2); Data thirdSum = third.formSIPBasic(user3, passwd3); Data fourthSum = fourth.formSIPBasic(user4, passwd4); cout << "firstSum: " << firstSum.logData() << endl; cout << "secondSum: " << secondSum.logData() << endl; cout << "thirdSum: " << thirdSum.logData() << endl; test_verify(secondSum == thirdSum); test_verify(thirdSum != fourthSum); return test_return_code(2); }
// // BinaryReaderWriter.cpp // // $Id: //poco/1.4/Foundation/samples/BinaryReaderWriter/src/BinaryReaderWriter.cpp#1 $ // // This sample demonstrates the BinaryWriter and BinaryReader classes. // // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #include "Poco/BinaryWriter.h" #include "Poco/BinaryReader.h" #include <sstream> #include <iostream> using Poco::BinaryWriter; using Poco::BinaryReader; int main(int argc, char** argv) { std::stringstream str; BinaryWriter writer(str); writer << true << 'x' << 42 << 3.14159265 << "foo bar"; bool b; char c; int i; double d; std::string s; BinaryReader reader(str); reader >> b >> c >> i >> d >> s; std::cout << b << std::endl << c << std::endl << i << std::endl << d << std::endl << s << std::endl; return 0; }
/** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include <functional> #include <thread> #include <vector> #include "gloo/barrier_all_to_all.h" #include "gloo/barrier_all_to_one.h" #include "gloo/broadcast.h" #include "gloo/test/base_test.h" namespace gloo { namespace test { namespace { // Function to instantiate and run algorithm. using Func = void(std::shared_ptr<::gloo::Context>); // Test parameterization. using Param = std::tuple<int, std::function<Func>>; // Test fixture. class BarrierTest : public BaseTest, public ::testing::WithParamInterface<Param> {}; TEST_P(BarrierTest, SinglePointer) { auto contextSize = std::get<0>(GetParam()); auto fn = std::get<1>(GetParam()); spawn(contextSize, [&](std::shared_ptr<Context> context) { fn(context); }); } static std::function<Func> barrierAllToAll = [](std::shared_ptr<::gloo::Context> context) { ::gloo::BarrierAllToAll algorithm(context); algorithm.run(); }; INSTANTIATE_TEST_CASE_P( BarrierAllToAll, BarrierTest, ::testing::Combine( ::testing::Range(2, 16), ::testing::Values(barrierAllToAll))); static std::function<Func> barrierAllToOne = [](std::shared_ptr<::gloo::Context> context) { ::gloo::BarrierAllToOne algorithm(context); algorithm.run(); }; INSTANTIATE_TEST_CASE_P( BarrierAllToOne, BarrierTest, ::testing::Combine( ::testing::Range(2, 16), ::testing::Values(barrierAllToOne))); // Synchronized version of std::chrono::clock::now(). // All processes participating in the specified context will // see the same value. template <typename clock> std::chrono::time_point<clock> syncNow( std::shared_ptr<Context> context) { const typename clock::time_point now = clock::now(); typename clock::duration::rep count = now.time_since_epoch().count(); BroadcastOptions opts(context); opts.setRoot(0); opts.setOutput(&count, 1); broadcast(opts); return typename clock::time_point(typename clock::duration(count)); } using NewParam = std::tuple<int>; class BarrierNewTest : public BaseTest, public ::testing::WithParamInterface<NewParam> {}; TEST_P(BarrierNewTest, Default) { auto contextSize = std::get<0>(GetParam()); spawn(contextSize, [&](std::shared_ptr<Context> context) { BarrierOptions opts(context); // Run barrier to synchronize processes after starting. barrier(opts); // Take turns in sleeping for a bit and checking that all processes // saw that artificial delay through the barrier. auto singleProcessDelay = std::chrono::milliseconds(10); for (size_t i = 0; i < context->size; i++) { const auto start = syncNow<std::chrono::high_resolution_clock>(context); if (i == context->rank) { /* sleep override */ std::this_thread::sleep_for(singleProcessDelay); } barrier(opts); // Expect all processes to have taken at least as long as the sleep auto stop = std::chrono::high_resolution_clock::now(); auto delta = std::chrono::duration_cast<decltype(singleProcessDelay)>( stop - start); ASSERT_GE(delta.count(), singleProcessDelay.count()); } }); } INSTANTIATE_TEST_CASE_P( BarrierNewDefault, BarrierNewTest, ::testing::Values(2, 4, 7)); TEST_F(BarrierNewTest, TestTimeout) { spawn(2, [&](std::shared_ptr<Context> context) { BarrierOptions opts(context); opts.setTimeout(std::chrono::milliseconds(10)); if (context->rank == 0) { try { barrier(opts); FAIL() << "Expected exception to be thrown"; } catch (::gloo::IoException& e) { ASSERT_NE(std::string(e.what()).find("Timed out"), std::string::npos); } } }); } } // namespace } // namespace test } // namespace gloo
/*++ Copyright (c) 2016 Microsoft Corporation Module Name: bv_bound_chk_tactic.cpp Abstract: Author: Mikolas Janota Revision History: --*/ #include "tactic/bv/bv_bound_chk_tactic.h" #include "ast/ast.h" #include "ast/rewriter/rewriter.h" #include "ast/rewriter/rewriter_def.h" #include "ast/rewriter/bv_bounds.h" #include "ast/rewriter/rewriter_params.hpp" #include "ast/rewriter/bool_rewriter.h" struct bv_bound_chk_stats { unsigned m_unsats; unsigned m_singletons; unsigned m_reduces; bv_bound_chk_stats() : m_unsats(0), m_singletons(0), m_reduces(0) {}; }; struct bv_bound_chk_rewriter_cfg : public default_rewriter_cfg { ast_manager & m_m; unsigned m_bv_ineq_consistency_test_max; bool_rewriter m_b_rw; unsigned long long m_max_steps; unsigned long long m_max_memory; // in bytes bv_bound_chk_stats& m_stats; bv_bound_chk_rewriter_cfg(ast_manager & m, bv_bound_chk_stats& stats) : m_m(m), m_b_rw(m), m_stats(stats) {} ~bv_bound_chk_rewriter_cfg() {} void updt_params(params_ref const & _p) { rewriter_params p(_p); m_bv_ineq_consistency_test_max = p.bv_ineq_consistency_test_max(); m_max_memory = p.max_memory(); m_max_steps = p.max_steps(); } ast_manager & m() const { return m_m; } bool rewrite_patterns() const { return false; } bool flat_assoc(func_decl * f) const { return true; } br_status reduce_app(func_decl * f, unsigned num, expr * const * args, expr_ref & result, proof_ref & result_pr) { const br_status st = reduce_app_core(f, num, args, result, result_pr); CTRACE("bv_bound_chk_step", st != BR_FAILED, tout << f->get_name() << "\n"; for (unsigned i = 0; i < num; i++) tout << mk_ismt2_pp(args[i], m()) << "\n"; tout << "---------->\n" << mk_ismt2_pp(result, m()) << "\n";); return st; } br_status reduce_app_core(func_decl * f, unsigned num, expr * const * args, expr_ref & result, proof_ref & result_pr) { result_pr = nullptr; const family_id fid = f->get_family_id(); if (fid != m_b_rw.get_fid()) return BR_FAILED; bv_bounds bvb(m()); const br_status rv = bvb.rewrite(m_bv_ineq_consistency_test_max, f, num, args, result); if (rv != BR_FAILED && (m_m.is_false(result) || m_m.is_true(result))) m_stats.m_unsats++; else if (rv != BR_FAILED && !bvb.singletons().empty()) m_stats.m_singletons++; else if (rv != BR_FAILED && is_app(result) && to_app(result)->get_num_args() < num) m_stats.m_reduces++; return rv; } bool max_steps_exceeded(unsigned long long num_steps) const { if (num_steps > m_max_steps) return true; if (memory::get_allocation_size() > m_max_memory) throw tactic_exception(TACTIC_MAX_MEMORY_MSG); return false; } void reset_statistics() { m_stats.m_unsats = 0; m_stats.m_singletons = 0; m_stats.m_reduces = 0; } void collect_statistics(statistics & st) const { st.update("unsat bv bounds", m_stats.m_unsats); st.update("bv singletons", m_stats.m_singletons); st.update("bv reduces", m_stats.m_reduces); } }; struct bv_bound_chk_rewriter : public rewriter_tpl<bv_bound_chk_rewriter_cfg> { bv_bound_chk_rewriter_cfg m_cfg; bv_bound_chk_rewriter(ast_manager & m, params_ref const & p, bv_bound_chk_stats& stats) : rewriter_tpl<bv_bound_chk_rewriter_cfg>(m, false, m_cfg) , m_cfg(m, stats) { updt_params(p); } ~bv_bound_chk_rewriter() override {} void updt_params(params_ref const & _p) { m_cfg.updt_params(_p); } void collect_statistics(statistics & st) const { m_cfg.collect_statistics(st); } void reset_statistics() { m_cfg.reset_statistics(); } }; class bv_bound_chk_tactic : public tactic { class imp; imp * m_imp; params_ref m_params; bv_bound_chk_stats m_stats; public: bv_bound_chk_tactic(ast_manager & m, params_ref const & p); void operator()(goal_ref const & g, goal_ref_buffer & result) override; ~bv_bound_chk_tactic() override; tactic * translate(ast_manager & m) override; void updt_params(params_ref const & p) override; void cleanup() override; void collect_statistics(statistics & st) const override; void reset_statistics() override; }; class bv_bound_chk_tactic::imp { bv_bound_chk_rewriter m_rw; public: imp(ast_manager & m, params_ref const & p, bv_bound_chk_stats& stats) : m_rw(m, p, stats) { } virtual ~imp() { } ast_manager& m() { return m_rw.m(); } void operator()(goal_ref const & g) { SASSERT(g->is_well_sorted()); tactic_report report("bv-bound-chk", *g); ast_manager& m(g->m()); expr_ref new_curr(m); const unsigned size = g->size(); for (unsigned idx = 0; idx < size; idx++) { if (g->inconsistent()) break; expr * curr = g->form(idx); m_rw(curr, new_curr); g->update(idx, new_curr); } m_rw.m_cfg.cleanup(); } virtual void updt_params(params_ref const & p) { m_rw.updt_params(p); } void collect_statistics(statistics & st) const { m_rw.collect_statistics(st); } void reset_statistics() { m_rw.reset_statistics(); } }; bv_bound_chk_tactic::bv_bound_chk_tactic(ast_manager & m, params_ref const & p) : m_params(p) { m_imp = alloc(imp, m, p, m_stats); } bv_bound_chk_tactic::~bv_bound_chk_tactic() { dealloc(m_imp); } void bv_bound_chk_tactic::operator()(goal_ref const & g, goal_ref_buffer & result) { SASSERT(g->is_well_sorted()); fail_if_proof_generation("bv-bound-chk", g); fail_if_unsat_core_generation("bv-bound-chk", g); TRACE("bv-bound-chk", g->display(tout << "before:"); tout << std::endl;); result.reset(); m_imp->operator()(g); g->inc_depth(); result.push_back(g.get()); TRACE("bv-bound-chk", g->display(tout << "after:");); SASSERT(g->is_well_sorted()); } tactic * bv_bound_chk_tactic::translate(ast_manager & m) { return alloc(bv_bound_chk_tactic, m, m_params); } void bv_bound_chk_tactic::updt_params(params_ref const & p) { m_params = p; m_imp->updt_params(p); } void bv_bound_chk_tactic::cleanup() { imp * d = alloc(imp, m_imp->m(), m_params, m_stats); std::swap(d, m_imp); dealloc(d); } void bv_bound_chk_tactic::collect_statistics(statistics & st) const { m_imp->collect_statistics(st); } void bv_bound_chk_tactic::reset_statistics() { m_imp->reset_statistics(); } tactic* mk_bv_bound_chk_tactic(ast_manager & m, params_ref const & p) { return alloc(bv_bound_chk_tactic, m, p); }
/* This file should be refactored, it is a total mess !!!!! Hanoh */ #include <iostream> #include <unordered_set> #include <string> #include <fstream> #include <streambuf> #include <assert.h> #include <json/json.h> #include "common/base64.h" #include <string.h> #include "44bsd/tcp_socket.h" #include "tuple_gen.h" #include "astf/astf_template_db.h" #include "astf_db.h" #include "bp_sim.h" #include "44bsd/tcp_var.h" #include "utl_split.h" #include "inet_pton.h" #include "astf/astf_json_validator.h" #include "stx/astf/trex_astf_topo.h" #define MAX_TG_NAME_LENGTH 20 inline std::string methodName(const std::string& prettyFunction) { size_t colons = prettyFunction.find("::"); size_t begin = prettyFunction.substr(0,colons).rfind(" ") + 1; size_t end = prettyFunction.rfind("(") - begin; return prettyFunction.substr(begin,end) + "()"; } #define __METHOD_NAME__ methodName(__PRETTY_FUNCTION__) // make the class singleton astf_db_map_t CAstfDB::m_instances; CAstfJsonValidator* CAstfDB::m_validator = nullptr; void CAstfDB::Create(){ if (m_validator && m_topo_mngr) { return; } m_client_config_info=0; if (m_validator == nullptr) { m_validator = new CAstfJsonValidator(); if (!m_validator->Create("astf_schema.json")) { printf("Could not create ASTF validator using file astf_schema.json\n"); exit(-1); } } m_topo_mngr = new TopoMngr(); m_factor = -1.0; m_json_initiated = false; } void CAstfDB::Delete(){ if ( m_instances.empty() && m_validator ) { m_validator->Delete(); delete m_validator; m_validator = nullptr; } delete m_topo_mngr; m_topo_mngr = nullptr; for (auto it : m_smart_gen) { delete it.second; } m_smart_gen.clear(); } CAstfDB::~CAstfDB(){ this->Delete(); } CAstfDB* CAstfDB::get_instance(profile_id_t profile_id) { if (m_instances.find(profile_id) == m_instances.end()) { m_instances[profile_id] = new CAstfDB(); } return m_instances[profile_id]; } CAstfDB* CAstfDB::instance(profile_id_t profile_id) { if (m_instances.find(profile_id) == m_instances.end()) { return nullptr; } return m_instances[profile_id]; } CAstfDB* CAstfDB::instance() { if (!has_instance()) { CAstfDB* new_inst = get_instance(0); new_inst->Create(); return new_inst; } return instance(0); } void CAstfDB::free_instance(profile_id_t profile_id) { if ( m_instances.find(profile_id) != m_instances.end() ){ auto inst = m_instances[profile_id]; delete inst; m_instances.erase(profile_id); } } bool CAstfDB::validate_profile(Json::Value profile,std::string & err){ bool res=m_validator->validate_profile(profile, err); return (res); } double CAstfDB::cps_factor(double cps){ if (m_factor > 0.0) { return ( m_factor*cps ); } else { return ( CGlobalInfo::m_options.m_factor*cps ); } } void CTcpTuneables::dump(FILE *fd) { } CTcpServerInfo *CTcpDataAssocTranslation::get_server_info(const CTcpDataAssocParams &params) { if (m_vec.size() == 0) { assoc_map_it_t it = m_map.find(params); if (it == m_map.end()) { return NULL; } else { return it->second; } } for (int i = 0; i < m_vec.size(); i++) { if (params == m_vec[i].m_params) return &m_vec[i].m_server_info; } return NULL; } void CTcpDataAssocTranslation::dump(FILE *fd) { if (m_vec.size() != 0) { fprintf(fd, "CTcpDataAssocTranslation - Dumping vector:\n"); for (int i = 0; i < m_vec.size(); i++) { fprintf(fd, " port %d mapped to %p\n", m_vec[i].m_params.m_port, &m_vec[i].m_server_info); } } else { fprintf(fd, "CTcpDataAssocTranslation - Dumping map:\n"); // std::map<>::const_iterator assoc_map_it_t it; for (it = m_map.begin(); it != m_map.end(); it++) { fprintf(fd, " port %d mapped to %p\n", it->first.m_port, it->second); } } } CTcpServerInfo* CTcpDataAssocTranslation::insert_vec(const CTcpDataAssocParams &params, CEmulAppProgram *prog, CTcpTuneables *tune , uint32_t temp_idx) { CTcpDataAssocTransHelp trans_help(params, prog, tune, temp_idx); m_vec.push_back(trans_help); return &m_vec.back().m_server_info; } CTcpServerInfo* CTcpDataAssocTranslation::insert_hash(const CTcpDataAssocParams &params, CEmulAppProgram *prog, CTcpTuneables *tune , uint32_t temp_idx) { CTcpServerInfo *tcp_s_info = new CTcpServerInfo(prog, tune, temp_idx); assert(tcp_s_info); m_map.insert(std::pair<CTcpDataAssocParams, CTcpServerInfo *>(params, tcp_s_info)); return tcp_s_info; } void CTcpDataAssocTranslation::clear() { for (assoc_map_it_t it = m_map.begin(); it != m_map.end(); it++) { delete it->second; } m_map.clear(); m_vec.clear(); } void CTcpDataAssocTranslation::enumerate_server_ports(std::vector<CTcpDataAssocParams>& ports, std::vector<CTcpServerInfo*>& servers) { for (CTcpDataAssocTransHelp& trans_help : m_vec) { ports.push_back(trans_help.m_params); servers.push_back(&trans_help.m_server_info); } for (assoc_map_it_t it = m_map.begin(); it != m_map.end(); it++) { ports.push_back(it->first); servers.push_back(it->second); } } bool CAstfDB::start_profile_no_buffer(Json::Value msg){ /* free buffer */ clear_buffers(); set_profile_one_msg(msg); return (true); } /* clear buffers */ bool CAstfDB::clear_buffers(){ m_buffers = Json::nullValue; return (true); } bool CAstfDB::add_buffers(Json::Value msg,std::string & err){ if (!msg.isArray()){ std::stringstream ss; ss << "val should be an array of strings "; err = ss.str(); clear_buffers(); return (false); } int i; /* check val array type of string */ for (i=0; i<msg.size(); i++) { if (!msg[i].isString()){ std::stringstream ss; ss << "msg[x] should be an array of strings "; err = ss.str(); return (false); } m_buffers.append(msg[i]); } return(true); } bool CAstfDB::compile_profile(std::string & err){ if (!m_val.isObject()){ std::stringstream ss; ss << "val should be an object "; err = ss.str(); return (false); } if (!m_buffers.isArray()){ std::stringstream ss; ss << "buffers should be an array of strings "; err = ss.str(); return (false); } m_val["buf_list"]=m_buffers; return (true); } bool CAstfDB::compile_profile_dp(uint8_t socket_id){ return(true); } void CAstfDB::dump_profile(FILE *fd){ Json::StreamWriterBuilder builder; std::string output = Json::writeString(builder, m_val); fprintf(fd," %s ",output.c_str()); } void CAstfDB::set_profile_one_msg(Json::Value msg){ m_val =msg; } bool CAstfDB::set_profile_one_msg(const std::string &msg, std::string & err){ Json::Reader reader; err=""; bool rc = reader.parse(msg, m_val, false); if (!rc) { std::stringstream ss; ss << "Failed parsing json message : " << reader.getFormattedErrorMessages() ; err = ss.str(); return false; } // Disable verification on too large profiles (empiric size of sfr_full.py * 5) if ( msg.size() > 25e6 ) { return true; } return validate_profile(m_val, err); } bool CAstfDB::parse_file(std::string file) { std::ifstream t(file); if ( !t.is_open() ) { return false; } std::string msg((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); std::string err; bool rc = set_profile_one_msg(msg, err); if ( !rc ) { printf("Parsing ASTF JSON file failed, error:\n%s\n", err.c_str()); return false; } m_json_initiated = true; return true; } bool CAstfDB::convert_from_json(uint8_t socket_id) { if ( !convert_bufs(socket_id) ) { return false; } if ( !convert_progs(socket_id) ) { return false; } m_tcp_data[socket_id].m_init = 1; if ( !build_assoc_translation(socket_id) ) { return false; } m_tcp_data[socket_id].m_init = 2; return true; } void CAstfDB::dump() { std::cout << m_val << std::endl; } uint32_t CAstfDB::get_buf_index(uint32_t program_index, uint32_t cmd_index) { Json::Value cmd; try { cmd = m_val["program_list"][program_index]["commands"][cmd_index]; } catch(std::exception &e) { assert(0); } assert(cmd["name"] == "tx"); return cmd["buf_index"].asInt(); } std::string CAstfDB::get_buf(uint32_t temp_index, uint32_t cmd_index, int side) { std::string temp_str; Json::Value cmd; if (side == 0) { temp_str = "client_template"; } else if (side == 1) { temp_str = "server_template"; } else { fprintf(stderr, "Bad side value %d\n", side); assert(0); } try { uint32_t program_index = m_val["templates"][temp_index][temp_str]["program_index"].asInt(); cmd = m_val["program_list"][program_index]["commands"][cmd_index]; } catch(std::exception &e) { assert(0); } assert (cmd["name"] == "tx"); uint32_t buf_index = cmd["buf_index"].asInt(); std::string output = m_val["buf_list"][buf_index].asString(); return base64_decode(output); } bool CAstfDB::get_emul_stream(uint32_t program_index){ Json::Value cmd; try { cmd = m_val["program_list"][program_index]; } catch(std::exception &e) { return true; } if (cmd["stream"] == Json::nullValue){ return(true); } return(cmd["stream"].asBool()); } tcp_app_cmd_enum_t CAstfDB::get_cmd(uint32_t program_index, uint32_t cmd_index) { Json::Value cmd; try { cmd = m_val["program_list"][program_index]["commands"][cmd_index]; } catch(std::exception &e) { return tcNO_CMD; } if (cmd["name"] == "tx") { return tcTX_BUFFER; } if (cmd["name"] == "rx") return tcRX_BUFFER; if (cmd["name"] == "delay") return tcDELAY; if (cmd["name"] == "nc") return tcDONT_CLOSE; if (cmd["name"] == "reset") return tcRESET; if (cmd["name"] == "connect") return tcCONNECT_WAIT; if (cmd["name"] == "delay_rnd") return tcDELAY_RAND; if (cmd["name"] == "set_var") return tcSET_VAR; if (cmd["name"] == "set_tick_var") return tcSET_TICK_VAR; if (cmd["name"] == "jmp_nz") return tcJMPNZ; if (cmd["name"] == "jmp_dp") return tcJMPDP; if (cmd["name"] == "tx_msg") return tcTX_PKT; if (cmd["name"] == "rx_msg") return tcRX_PKT; if (cmd["name"] == "keepalive") return tcKEEPALIVE; if (cmd["name"] == "close_msg") return tcCLOSE_PKT; if (cmd["name"] == "tx_mode") return tcTX_MODE; /* TBD need to check the value and put an error !!! */ return tcNO_CMD; } uint32_t CAstfDB::get_delay_ticks(uint32_t program_index, uint32_t cmd_index) { Json::Value cmd; try { cmd = m_val["program_list"][program_index]["commands"][cmd_index]; } catch(std::exception &e) { assert(0); } assert (cmd["name"] == "delay"); return tw_time_usec_to_ticks(cmd["usec"].asUInt()); } void CAstfDB::assert_cmd(uint32_t program_index, uint32_t cmd_index, const std::string &cmd_name, Json::Value &cmd) { try { cmd = m_val["program_list"][program_index]["commands"][cmd_index]; } catch(std::exception &e) { assert(0); } assert (cmd["name"] == cmd_name); } void CAstfDB::fill_tx_mode(uint32_t program_index, uint32_t cmd_index, CEmulAppCmd &res) { Json::Value cmd; assert_cmd(program_index, cmd_index, "tx_mode", cmd); res.u.m_tx_mode.m_flags = cmd["flags"].asUInt(); } void CAstfDB::fill_delay_rnd(uint32_t program_index, uint32_t cmd_index, CEmulAppCmd &res) { Json::Value cmd; assert_cmd(program_index, cmd_index, "delay_rnd", cmd); res.u.m_delay_rnd.m_min_ticks = tw_time_usec_to_ticks(cmd["min_usec"].asUInt()); res.u.m_delay_rnd.m_max_ticks = tw_time_usec_to_ticks(cmd["max_usec"].asUInt()); } void CAstfDB::fill_set_var(uint32_t program_index, uint32_t cmd_index, CEmulAppCmd &res) { Json::Value cmd; assert_cmd(program_index, cmd_index, "set_var", cmd); res.u.m_var.m_var_id = cmd["id"].asUInt(); res.u.m_var.m_val = cmd["val"].asUInt64(); } void CAstfDB::fill_set_tick_var(uint32_t program_index, uint32_t cmd_index, CEmulAppCmd &res) { Json::Value cmd; assert_cmd(program_index, cmd_index, "set_tick_var", cmd); res.u.m_tick_var.m_var_id = cmd["id"].asUInt(); } void CAstfDB::fill_jmpnz(uint32_t program_index, uint32_t cmd_index, CEmulAppCmd &res) { Json::Value cmd; assert_cmd(program_index, cmd_index, "jmp_nz", cmd); res.u.m_jmpnz.m_var_id = cmd["id"].asUInt(); res.u.m_jmpnz.m_offset = cmd["offset"].asInt(); } void CAstfDB::fill_jmpdp(uint32_t program_index, uint32_t cmd_index, CEmulAppCmd &res) { Json::Value cmd; assert_cmd(program_index, cmd_index, "jmp_dp", cmd); res.u.m_jmpdp.m_var_id = cmd["id"].asUInt(); res.u.m_jmpdp.m_offset = cmd["offset"].asInt(); double duration = cmd["duration"].asDouble(); res.u.m_jmpdp.m_duration = (uint64_t)(duration * 1000L / CAstfTickCmdClock::TICK_MSEC); } void CAstfDB::fill_tx_pkt(uint32_t program_index, uint32_t cmd_index, uint8_t socket_id, CEmulAppCmd &res) { Json::Value cmd; assert_cmd(program_index, cmd_index, "tx_msg", cmd); uint32_t indx=cmd["buf_index"].asUInt(); res.u.m_tx_pkt.m_buf = m_tcp_data[socket_id].m_buf_list[indx]; } void CAstfDB::fill_rx_pkt(uint32_t program_index, uint32_t cmd_index, uint64_t& total_rx_wm, CEmulAppCmd &res) { Json::Value cmd; assert_cmd(program_index, cmd_index, "rx_msg", cmd); uint64_t min_pkts=cmd["min_pkts"].asUInt64(); if (unlikely(min_pkts < total_rx_wm)) { min_pkts = total_rx_wm; // to skip invalid min_pkts } res.u.m_rx_pkt.m_rx_pkts = min_pkts - total_rx_wm; res.u.m_rx_pkt.m_flags =CEmulAppCmdRxPkt::rxcmd_WAIT; total_rx_wm = min_pkts; if (cmd["clear"] != Json::nullValue) { if (cmd["clear"].asBool()) { res.u.m_rx_cmd.m_flags |= CEmulAppCmdRxPkt::rxcmd_CLEAR; total_rx_wm = 0; } } } void CAstfDB::fill_keepalive_pkt(uint32_t program_index, uint32_t cmd_index, CEmulAppCmd &res) { Json::Value cmd; assert_cmd(program_index, cmd_index, "keepalive", cmd); res.u.m_keepalive.m_keepalive_msec =cmd["msec"].asUInt(); if (cmd["rx_mode"] != Json::nullValue) { res.u.m_keepalive.m_rx_mode = cmd["rx_mode"].asBool(); } else { res.u.m_keepalive.m_rx_mode = false; } } void CAstfDB::get_rx_cmd(uint32_t program_index, uint32_t cmd_index, uint64_t& total_rx_wm, CEmulAppCmd &res) { Json::Value cmd; assert_cmd(program_index, cmd_index, "rx", cmd); uint64_t min_bytes = cmd["min_bytes"].asUInt64(); if (unlikely(min_bytes < total_rx_wm)) { min_bytes = total_rx_wm; // to skip invalid min_bytes } res.u.m_rx_cmd.m_rx_bytes_wm = min_bytes - total_rx_wm; total_rx_wm = min_bytes; if (cmd["clear"] != Json::nullValue) { if (cmd["clear"].asBool()) { res.u.m_rx_cmd.m_flags |= CEmulAppCmdRxPkt::rxcmd_CLEAR; total_rx_wm = 0; } } } // verify correctness of json data CJsonData_err CAstfDB::verify_data(uint16_t max_threads) { uint32_t ip_start; uint32_t ip_end; uint32_t num_ips; std::string err_str; const char* ip_start_str; const char* ip_end_str; std::string s; Json::Value ip_gen_list = m_val["ip_gen_dist_list"]; for (int i = 0; i < ip_gen_list.size(); i++) { s = ip_gen_list[i]["ip_start"].asString(); ip_start_str = s.c_str(); ip_start = ip_from_str(ip_start_str); s = ip_gen_list[i]["ip_end"].asString(); ip_end_str = s.c_str(); ip_end = ip_from_str(ip_end_str); if (ip_end < ip_start) { err_str = std::string("IP start: ") + ip_start_str + " is bigger than IP end: " + ip_end_str; return CJsonData_err(CJsonData_err_pool_err, err_str); } num_ips = ip_end - ip_start + 1; if (num_ips < max_threads) { err_str = "Pool:(" + ip_gen_list[i]["ip_start"].asString() + "-" + ip_gen_list[i]["ip_end"].asString() + ") has only " + std::to_string(num_ips) + " address" + ((num_ips == 1) ? "" : "es") + ". Number of IPs in each pool must exceed the number of" + " Data path threads, which is " + std::to_string(max_threads); return CJsonData_err(CJsonData_err_pool_too_small, err_str); } } return CJsonData_err(CJsonData_err_pool_ok, ""); } bool CAstfDB::verify_init(uint16_t socket_id) { bool success = true; if ( !m_tcp_data[socket_id].is_init() ) { // json data should not be accessed by multiple threads in parallel std::unique_lock<std::mutex> my_lock(m_global_mtx); if ( !m_tcp_data[socket_id].is_init() ) { success = convert_from_json(socket_id); } my_lock.unlock(); } return success; } void CAstfDB::clear_db_ro(uint8_t socket_id) { if ( m_tcp_data[socket_id].is_init() ) { // json data should not be accessed by multiple threads in parallel std::unique_lock<std::mutex> my_lock(m_global_mtx); if ( m_tcp_data[socket_id].is_init() ) { m_tcp_data[socket_id].Delete(); } my_lock.unlock(); } } CAstfDbRO *CAstfDB::get_db_ro(uint8_t socket_id) { if ( !verify_init(socket_id) ) { m_tcp_data[socket_id].Delete(); return nullptr; } return &m_tcp_data[socket_id]; } uint32_t CAstfDB::ip_from_str(const char *c_ip) { int rc; uint32_t ip_num; rc = my_inet_pton4(c_ip, (unsigned char *)&ip_num); if (! rc) { fprintf(stderr, "Error: Bad IP address %s in json. Exiting.", c_ip); exit(1); } return ntohl(ip_num); } bool CAstfDB::read_tunable_uint8(CTcpTuneables *tune, const Json::Value &parent, const std::string &param, uint32_t enum_val, uint8_t & val){ if (parent[param] == Json::nullValue){ return false; } Json::Value result; /* no value */ check_field_type(parent, param, FIELD_TYPE_BYTE, result); val = (uint8_t)parent[param].asUInt(); tune->add_value(enum_val); return true; } /* raise an Exception in case of an error */ bool CAstfDB::read_tunable_uint16(CTcpTuneables *tune, const Json::Value &parent, const std::string &param, uint32_t enum_val, uint16_t & val){ if (parent[param] == Json::nullValue){ return false; } Json::Value result; /* no value */ check_field_type(parent, param, FIELD_TYPE_UINT16, result); val = (uint16_t)parent[param].asUInt(); tune->add_value(enum_val); return true; } bool CAstfDB::read_tunable_uint32(CTcpTuneables *tune, const Json::Value &parent, const std::string &param, uint32_t enum_val, uint32_t & val){ if (parent[param] == Json::nullValue){ return false; } Json::Value result; /* no value */ check_field_type(parent, param, FIELD_TYPE_UINT32, result); val = (uint32_t)parent[param].asUInt(); tune->add_value(enum_val); return true; } bool CAstfDB::read_tunable_uint64(CTcpTuneables *tune, const Json::Value &parent, const std::string &param, uint32_t enum_val, uint64_t & val){ if (parent[param] == Json::nullValue){ return false; } Json::Value result; /* no value */ check_field_type(parent, param, FIELD_TYPE_UINT64, result); val = (uint64_t)parent[param].asUInt64(); tune->add_value(enum_val); return true; } bool CAstfDB::read_tunable_double(CTcpTuneables *tune, const Json::Value &parent, const std::string &param, uint32_t enum_val, double & val){ if (parent[param] == Json::nullValue){ return false; } Json::Value result; /* no value */ check_field_type(parent, param, FIELD_TYPE_DOUBLE, result); val = parent[param].asDouble(); tune->add_value(enum_val); return true; } bool CAstfDB::read_tunable_bool(CTcpTuneables *tune, const Json::Value &parent, const std::string &param, uint32_t enum_val, double & val){ if (parent[param] == Json::nullValue){ return false; } Json::Value result; /* no value */ check_field_type(parent, param, FIELD_TYPE_BOOL, result); val = parent[param].asBool(); tune->add_value(enum_val); return true; } void CAstfDB::tunable_min_max_u32(std::string param, uint32_t val, uint32_t min, uint32_t max){ Json::Value result; if (val<min) { generate_parse_err(result, "field '" + param + "' value " + std::to_string(val)+ " is smaller than " +std::to_string(min)); } if (val>max) { generate_parse_err(result, "field '" + param + "' value " + std::to_string(val)+ " is greater than " +std::to_string(max)); } } void CAstfDB::tunable_min_max_u64(std::string param, uint64_t val, uint64_t min, uint64_t max){ Json::Value result; if (val<min) { generate_parse_err(result, "field '" + param + "' value " + std::to_string(val)+ " is smaller than " +std::to_string(min)); } if (val>max) { generate_parse_err(result, "field '" + param + "' value " + std::to_string(val)+ " is greater than " +std::to_string(max)); } } void CAstfDB::tunable_min_max_d(std::string param, double val, double min, double max){ Json::Value result; if (val<min) { generate_parse_err(result, "field '" + param + "' value " + std::to_string(val)+ " is smaller than " +std::to_string(min)); } if (val>max) { generate_parse_err(result, "field '" + param + "' value " + std::to_string(val)+ " is greater than " +std::to_string(max)); } } bool CAstfDB::read_tunables_ipv6_field(CTcpTuneables *tune, Json::Value json, void *field, uint32_t enum_val){ if ( json == Json::nullValue) { return false; } Json::Value result; if ((json.type() != Json::arrayValue) || (json.size() !=16) ){ generate_parse_err(result, "ipv6 addr should have Json::arrayValue type with size of 16"); }else{ int i; uint8_t *p=(uint8_t *)field; for (i=0; i<16; i++) { p[i]=(uint8_t)(json[i].asUInt()); } tune->add_value(enum_val); } return(true); } bool CAstfDB::read_tunables(CTcpTuneables *tune, Json::Value tune_json) { /* TBD for now the exception is handeled only here in interactive mode should be in higher level. CAstfDB does not handle errors */ if (tune_json == Json::nullValue) { return true; } try { if (tune_json["scheduler"] != Json::nullValue) { Json::Value json = tune_json["scheduler"]; if (read_tunable_uint16(tune,json,"rampup_sec",CTcpTuneables::sched_rampup,tune->m_scheduler_rampup)){ tunable_min_max_u32("rampup_sec",tune->m_scheduler_rampup,3,60000); } } if (tune_json["ip"] != Json::nullValue) { Json::Value json = tune_json["ip"]; read_tunable_uint8(tune,json,"tos",CTcpTuneables::ip_tos,tune->m_ip_tos); /* some devices uses the LSB for filter */ if (tune->m_ip_tos&0x1) { tune->m_ip_tos &=(~0x1); } read_tunable_uint8(tune,json,"ttl",CTcpTuneables::ip_ttl,tune->m_ip_ttl); /* some devices uses the TTL for filters of low latency */ if (tune->m_ip_ttl>0x7f) { tune->m_ip_ttl = 0x7f; } if (read_tunable_uint8(tune,json,"dont_use_inbound_mac",CTcpTuneables::dont_use_inbound_mac,tune->m_dont_use_inbound_mac)){ tunable_min_max_u32("dont_use_inbound_mac",tune->m_dont_use_inbound_mac,0,1); } } if (tune_json["tcp"] != Json::nullValue) { Json::Value json = tune_json["tcp"]; if (read_tunable_uint16(tune,json,"mss",CTcpTuneables::tcp_mss_bit,tune->m_tcp_mss)){ tunable_min_max_u32("mss",tune->m_tcp_mss,10,9*1024); } if (read_tunable_uint16(tune,json,"initwnd",CTcpTuneables::tcp_initwnd_bit,tune->m_tcp_initwnd)){ tunable_min_max_u32("initwnd",tune->m_tcp_initwnd,1,20); } if (read_tunable_uint32(tune,json,"rxbufsize",CTcpTuneables::tcp_rx_buf_size,tune->m_tcp_rxbufsize)){ tunable_min_max_u32("rxbufsize",tune->m_tcp_rxbufsize,1*1024,1024*1024*1024); } if (read_tunable_uint32(tune,json,"txbufsize",CTcpTuneables::tcp_tx_buf_size,tune->m_tcp_txbufsize)){ tunable_min_max_u32("txbufsize",tune->m_tcp_txbufsize,1*1024,1024*1024*1024); } if (read_tunable_uint8(tune,json,"rexmtthresh",CTcpTuneables::tcp_rexmtthresh,tune->m_tcp_rexmtthresh)){ tunable_min_max_u32("rexmtthresh",tune->m_tcp_rexmtthresh,1,10); } if (read_tunable_uint8(tune,json,"do_rfc1323",CTcpTuneables::tcp_do_rfc1323,tune->m_tcp_do_rfc1323)){ tunable_min_max_u32("do_rfc1323",tune->m_tcp_do_rfc1323,0,1); } if (read_tunable_uint8(tune,json,"no_delay",CTcpTuneables::tcp_no_delay,tune->m_tcp_no_delay)){ tunable_min_max_u32("no_delay",tune->m_tcp_no_delay,0,3); } if (read_tunable_uint16(tune,json,"keepinit",CTcpTuneables::tcp_keepinit,tune->m_tcp_keepinit)){ tunable_min_max_u32("keepinit",tune->m_tcp_keepinit,2, 65533); } if (read_tunable_uint16(tune,json,"keepidle",CTcpTuneables::tcp_keepidle,tune->m_tcp_keepidle)){ tunable_min_max_u32("keepidle",tune->m_tcp_keepidle,2, 65533); } if (read_tunable_uint16(tune,json,"keepintvl",CTcpTuneables::tcp_keepintvl,tune->m_tcp_keepintvl)){ tunable_min_max_u32("keepintvl",tune->m_tcp_keepintvl,2, 65533); } if (read_tunable_uint8(tune,json,"blackhole",CTcpTuneables::tcp_blackhole,tune->m_tcp_blackhole)){ tunable_min_max_u32("blackhole",tune->m_tcp_blackhole,0,2); } if (read_tunable_uint16(tune,json,"delay_ack_msec",CTcpTuneables::tcp_delay_ack,tune->m_tcp_delay_ack_msec)){ tunable_min_max_u32("delay_ack_msec",tune->m_tcp_delay_ack_msec,20,50000); } if (read_tunable_uint16(tune, json, "no_delay_counter", CTcpTuneables::tcp_no_delay_counter,tune->m_tcp_no_delay_counter)){ tunable_min_max_u32("no_delay_counter", tune->m_tcp_no_delay_counter, 0, 65533); } } if (tune_json["ipv6"] != Json::nullValue) { Json::Value json = tune_json["ipv6"]; if (json["enable"] != Json::nullValue) { tune->set_ipv6_enable(json["enable"].asInt()); } Json::Value src_l=json["src_msb"]; read_tunables_ipv6_field(tune, src_l, (void *)tune->m_ipv6_src, CTcpTuneables::ipv6_src_addr); Json::Value dst_l=json["dst_msb"]; read_tunables_ipv6_field(tune, dst_l, (void *)tune->m_ipv6_dst, CTcpTuneables::ipv6_dst_addr); } } catch (TrexRpcCommandException &e) { printf(" ERROR !!! '%s' \n",e.what()); /* TBD need a better way to signal this */ return(true); } return true; } ClientCfgDB *CAstfDB::get_client_cfg_db() { static ClientCfgDB g_dummy; if (m_client_config_info==0) { return &g_dummy; }else{ return m_client_config_info; } } bool CAstfDB::get_latency_info(uint32_t & src_ipv4, uint32_t & dst_ipv4, uint32_t & dual_port_mask){ Json::Value ip_gen_list = m_val["ip_gen_dist_list"]; std::string s; if (ip_gen_list.size()<2){ return(false); } int i; uint32_t valid=0; for (i=0; i<2; i++) { Json::Value g=ip_gen_list[i]; if (g["dir"] == "c") { s = g["ip_offset"].asString(); dual_port_mask = ip_from_str(s.c_str()); s = g["ip_start"].asString(); src_ipv4 = ip_from_str(s.c_str()); valid|=1; } if (g["dir"] == "s") { s= g["ip_start"].asString(); dst_ipv4 = ip_from_str(s.c_str()); valid|=2; } } if (valid != 3) { return(false); } return(true); } void CAstfDB::get_tuple_info(CTupleGenYamlInfo & tuple_info){ Json::Value ip_gen_list = m_val["ip_gen_dist_list"]; struct CTupleGenPoolYaml pool; pool.m_dist = cdSEQ_DIST; pool.m_name = ""; pool.m_number_of_clients_per_gb=0; pool.m_min_clients=0; pool.m_dual_interface_mask=0; pool.m_tcp_aging_sec=0; pool.m_udp_aging_sec=0; pool.m_is_bundling=false; pool.m_per_core_distro =false; std::string s; for (int i = 0; i < ip_gen_list.size(); i++) { Json::Value g=ip_gen_list[i]; s = g["ip_start"].asString(); uint32_t ip_start = ip_from_str(s.c_str()); s = g["ip_end"].asString(); uint32_t ip_end = ip_from_str(s.c_str()); s = g["ip_offset"].asString(); uint32_t mask = ip_from_str(s.c_str()); /* backward compatible */ if (g["per_core_distribution"] != Json::nullValue){ if (g["per_core_distribution"] == "seq") { pool.m_per_core_distro =true; } } pool.m_ip_start = ip_start; pool.m_ip_end = ip_end; pool.m_dual_interface_mask = mask ; std::vector<CTupleGenPoolYaml> *lp; if (g["dir"] == "c") { lp =&tuple_info.m_client_pool; /* client */ }else{ /* server */ lp =&tuple_info.m_server_pool; } lp->push_back(pool); } } void fill_rss_vals(uint16_t thread_id, uint16_t &rss_thread_id, uint16_t &rss_thread_max) { rss_thread_id =0; rss_thread_max = CGlobalInfo::m_options.preview.getCores(); if ( rss_thread_max > 1 ) { rss_thread_id = thread_id / CGlobalInfo::m_options.get_expected_dual_ports(); } } void CAstfDB::get_thread_ip_range(uint16_t thread_id, uint16_t max_threads, uint16_t dual_port_id, std::string ip_start, std::string ip_end, std::string ip_offset, bool per_core_dist, CIpPortion &portion) { CTupleGenPoolYaml poolinfo; poolinfo.m_per_core_distro = per_core_dist; poolinfo.m_ip_start = ip_from_str(ip_start.c_str()); poolinfo.m_ip_end = ip_from_str(ip_end.c_str()); poolinfo.m_dual_interface_mask = ip_from_str(ip_offset.c_str()); if (poolinfo.m_per_core_distro) { uint16_t rss_thread_id, rss_thread_max; fill_rss_vals(thread_id, rss_thread_id, rss_thread_max); split_ips_v2(max_threads, rss_thread_id, rss_thread_max, CGlobalInfo::m_options.get_expected_dual_ports(), dual_port_id, poolinfo, portion); }else{ split_ips(thread_id, max_threads, dual_port_id, poolinfo, portion); } } CAstfTemplatesRW *CAstfDB::get_db_template_rw(uint8_t socket_id, CTupleGeneratorSmart *g_gen, uint16_t thread_id, uint16_t max_threads, uint16_t dual_port_id) { CAstfTemplatesRW *ret = new CAstfTemplatesRW(); assert(ret); ret->Create(thread_id,max_threads); // json data should not be accessed by multiple threads in parallel std::unique_lock<std::mutex> my_lock(m_global_mtx); if (g_gen == nullptr) { g_gen = get_smart_gen(thread_id); } g_gen->Create(0, thread_id); uint16_t rss_thread_id, rss_thread_max; fill_rss_vals(thread_id, rss_thread_id, rss_thread_max); if ( rss_thread_max > 1 ) { g_gen->set_astf_rss_mode(rss_thread_id ,rss_thread_max, CGlobalInfo::m_options.m_reta_mask); /* configure the generator */ } uint32_t active_flows_per_core; CIpPortion portion; CTupleGenPoolYaml poolinfo; uint32_t last_c_idx=0; uint32_t last_s_idx=0; std::vector<uint32_t> gen_idx_trans; std::string s; Json::Value ip_gen_list = m_val["ip_gen_dist_list"]; for (int i = 0; i < ip_gen_list.size(); i++) { IP_DIST_t dist; poolinfo.m_per_core_distro =false; s = ip_gen_list[i]["ip_start"].asString(); poolinfo.m_ip_start = ip_from_str(s.c_str()); s = ip_gen_list[i]["ip_end"].asString(); poolinfo.m_ip_end = ip_from_str(s.c_str()); s = ip_gen_list[i]["distribution"].asString(); if (! strncmp(s.c_str(), "seq", 3)) { dist = cdSEQ_DIST; } else if (! strncmp(s.c_str(), "rand", 4)) { dist = cdRANDOM_DIST; } else if (! strncmp(s.c_str(), "normal", 6)) { dist = cdNORMAL_DIST; } else { fprintf(stderr, "wrong distribution string %s in json\n", s.c_str()); my_lock.unlock(); return((CAstfTemplatesRW *)0); } if (ip_gen_list[i]["per_core_distribution"] != Json::nullValue){ if (ip_gen_list[i]["per_core_distribution"] == "seq") { poolinfo.m_per_core_distro =true; } } poolinfo.m_dist = dist; s= ip_gen_list[i]["ip_offset"].asString(); poolinfo.m_dual_interface_mask = ip_from_str(s.c_str()); if (poolinfo.m_per_core_distro) { split_ips_v2(max_threads, rss_thread_id,rss_thread_max, CGlobalInfo::m_options.get_expected_dual_ports(),dual_port_id, poolinfo, portion); }else{ split_ips(thread_id, max_threads, dual_port_id, poolinfo, portion); } active_flows_per_core = (portion.m_ip_end - portion.m_ip_start) * 32000; if (ip_gen_list[i]["dir"] == "c") { gen_idx_trans.push_back(last_c_idx); last_c_idx++; ClientCfgDB * cdb=get_client_cfg_db(); g_gen->add_client_pool(dist, portion.m_ip_start, portion.m_ip_end, active_flows_per_core, *cdb, 0, 0); } else { gen_idx_trans.push_back(last_s_idx); last_s_idx++; g_gen->add_server_pool(dist, portion.m_ip_start, portion.m_ip_end, active_flows_per_core, false); } #if 0 printf("Thread id:%d - orig ip(%s - %s) per thread ip (%s - %s) dist:%d\n", thread_id, ip_to_str(poolinfo.m_ip_start).c_str(), ip_to_str(poolinfo.m_ip_end).c_str(), ip_to_str(portion.m_ip_start).c_str(), ip_to_str(portion.m_ip_end).c_str(), dist); #endif } CTcpTuneables *c_tune = new CTcpTuneables(); assert (c_tune); CTcpTuneables *s_tune = new CTcpTuneables(); assert (s_tune); read_tunables(c_tune, m_val["c_glob_info"]); read_tunables(s_tune, m_val["s_glob_info"]); ret->set_tuneables(c_tune, s_tune); std::vector<double> dist; ret->set_flow_limited(true); // loop over all templates for (uint32_t index = 0; index < m_val["templates"].size(); index++) { CAstfPerTemplateRW *temp_rw = new CAstfPerTemplateRW(); assert(temp_rw); Json::Value c_temp = m_val["templates"][index]["client_template"]; CAstfPerTemplateRO template_ro; template_ro.m_dual_mask = poolinfo.m_dual_interface_mask; // Should be the same for all poolinfo, so just take from last one template_ro.m_client_pool_idx = gen_idx_trans[c_temp["ip_gen"]["dist_client"]["index"].asInt()]; template_ro.m_server_pool_idx = gen_idx_trans[c_temp["ip_gen"]["dist_server"]["index"].asInt()]; template_ro.m_one_app_server = false; template_ro.m_server_addr = 0; template_ro.m_w = 1; double cps = cps_factor (c_temp["cps"].asDouble() / max_threads); template_ro.m_k_cps = cps; dist.push_back(cps); template_ro.m_destination_port = c_temp["port"].asInt(); template_ro.m_stream = get_emul_stream(c_temp["program_index"].asInt()); temp_rw->Create(g_gen, index, thread_id, &template_ro, dual_port_id); bool is_cont = false; if (c_temp["cont"] != Json::nullValue ) { is_cont = c_temp["cont"].asBool(); // set continuous flows } if (c_temp["limit"] != Json::nullValue ){ uint32_t cnt= utl_split_int(c_temp["limit"].asUInt(), thread_id, max_threads); /* there is a limit */ temp_rw->set_limit(cnt, is_cont); if (is_cont) { ret->set_flow_limited(false); } } else { ret->set_flow_limited(false); } CTcpTuneables *s_tuneable; CTcpTuneables *c_tuneable = new CTcpTuneables(); assert(c_tuneable); s_tuneable = get_s_tune(index); assert(s_tuneable); if (!read_tunables(c_tuneable, m_val["templates"][index]["client_template"]["glob_info"])){ my_lock.unlock(); return((CAstfTemplatesRW *)0); } temp_rw->set_tuneables(c_tuneable, s_tuneable); ret->add_template(temp_rw); } /* init scheduler */ ret->init_scheduler(dist); m_rw_db.push_back(ret); my_lock.unlock(); return ret; } /* * Get program associated with template index and side * temp_index - template index * side - 0 - client, 1 - server * Return pointer to program */ CEmulAppProgram *CAstfDB::get_prog(uint32_t temp_index, int side, uint8_t socket_id) { std::string temp_str; uint32_t program_index; assert(m_tcp_data[socket_id].m_init > 0); if (side == 0) { temp_str = "client_template"; } else if (side == 1) { temp_str = "server_template"; } else { fprintf(stderr, "Bad side value %d\n", side); assert(0); } program_index = m_val["templates"][temp_index][temp_str]["program_index"].asInt(); return m_tcp_data[socket_id].m_prog_list[program_index]; } /* Building association translation, and all template related info. */ bool CAstfDB::build_assoc_translation(uint8_t socket_id) { bool is_hash_needed = false; double cps_sum=0; CTcpTemplateInfo one_template; uint32_t num_bytes_in_template=0; double template_cps; std::unordered_set<uint16_t> tcp_server_ports; std::unordered_set<uint16_t> udp_server_ports; assert(m_tcp_data[socket_id].m_init > 0); if ( m_val["templates"].size() == 0 ) { return false; } if (m_val["templates"].size() > 10) { is_hash_needed = true; } uint16_t num_of_tg_ids = m_val["tg_names"].size()+1; m_tcp_data[socket_id].m_num_of_tg_ids = num_of_tg_ids; // CAstfDBRo m_num_of_tg_ids updated. m_num_of_tg_ids = num_of_tg_ids; // CAstfDB m_num_of_tg_ids updated. auto tg_names = m_val["tg_names"]; m_tg_names.clear(); // To avoid multiple entry. for (uint16_t index = 0; index < num_of_tg_ids - 1; index++) { std::string tg_name = tg_names[index].asString(); if (tg_name.length() > MAX_TG_NAME_LENGTH) { throw TrexException("TG name too long. Please limit TG names to " + std::to_string(MAX_TG_NAME_LENGTH) + " characters"); } if ( tg_name.size() == 0 ) { throw TrexException("Empty TG name"); } m_tg_names.push_back(tg_name); } for (uint32_t index = 0; index < m_val["templates"].size(); index++) { // build association table uint16_t port = m_val["templates"][index]["server_template"]["assoc"][0]["port"].asInt(); bool is_stream = get_emul_stream(m_val["templates"][index]["server_template"]["program_index"].asInt()); CTcpDataAssocParams tcp_params(port,is_stream); CEmulAppProgram *prog_p = get_prog(index, 1, socket_id); assert(prog_p); CTcpTuneables *s_tuneable = new CTcpTuneables(); assert(s_tuneable); read_tunables(s_tuneable, m_val["templates"][index]["server_template"]["glob_info"]); CTcpServerInfo* server_info; if (is_hash_needed) { server_info = m_tcp_data[socket_id].m_assoc_trans.insert_hash(tcp_params, prog_p, s_tuneable, index); } else { server_info = m_tcp_data[socket_id].m_assoc_trans.insert_vec(tcp_params, prog_p, s_tuneable, index); } m_s_tuneables.push_back(s_tuneable); update_server_info(server_info); // build template info template_cps = cps_factor(m_val["templates"][index]["client_template"]["cps"].asDouble()); one_template.m_dport = m_val["templates"][index]["client_template"]["port"].asInt(); uint32_t c_prog_index = m_val["templates"][index]["client_template"]["program_index"].asInt(); uint32_t s_prog_index = m_val["templates"][index]["server_template"]["program_index"].asInt(); uint16_t tg_id = m_val["templates"][index]["tg_id"].asInt(); if ( tg_id > num_of_tg_ids || tg_id < 0 ) { throw TrexException("TG ID not in range, it should be between 0 and " + std::to_string(num_of_tg_ids)); } one_template.m_tg_id = tg_id; num_bytes_in_template += m_prog_lens[c_prog_index]; num_bytes_in_template += m_prog_lens[s_prog_index]; one_template.m_client_prog = m_tcp_data[socket_id].m_prog_list[c_prog_index]; one_template.m_num_bytes = num_bytes_in_template; m_exp_bps += template_cps * num_bytes_in_template * 8; num_bytes_in_template = 0; assert(one_template.m_client_prog); cps_sum += template_cps; m_tcp_data[socket_id].m_templates.push_back(one_template); } m_tcp_data[socket_id].m_cps_sum = cps_sum; return true; } void CAstfDB::update_server_info(CTcpServerInfo* server_info) { uint32_t temp_idx = server_info->get_temp_idx(); Json::Value temp = m_val["templates"][temp_idx]; Json::Value ip_gen_list = m_val["ip_gen_dist_list"]; /* update server ip range */ Json::Value assoc = temp["server_template"]["assoc"][0]; uint32_t ip_start = assoc["ip_start"] ? ip_from_str(assoc["ip_start"].asString().c_str()): 0; uint32_t ip_end = assoc["ip_end"] ? ip_from_str(assoc["ip_end"].asString().c_str()): UINT32_MAX; server_info->set_ip_start(ip_start); server_info->set_ip_end(ip_end); /* update payload params */ Json::Value l7_map = assoc["l7_map"]; if (l7_map == Json::nullValue || l7_map["offset"] == Json::nullValue) { return; } int c_prog_idx = temp["client_template"]["program_index"].asInt(); bool is_stream = get_emul_stream(c_prog_idx); // same as server_template /* prepare buf_list to get the value recursively by specified offset */ std::vector<std::string> buf_list; if (l7_map["value"] == Json::nullValue) { Json::Value c_cmds = m_val["program_list"][c_prog_idx]["commands"]; for (int cmd_idx = 0; cmd_idx < c_cmds.size(); cmd_idx++) { if (is_stream && c_cmds[cmd_idx]["name"] == "rx") { throw TrexException("client should send a message first to use l7_map."); } if (c_cmds[cmd_idx]["buf_index"] != Json::nullValue) { int buf_index = c_cmds[cmd_idx]["buf_index"].asInt(); Json::Value tmp_buf = m_val["buf_list"][buf_index]; if (tmp_buf.type() == Json::objectValue) { if (tmp_buf["base"] == Json::nullValue) { throw TrexException("base message is mandatory to use l7_map."); } tmp_buf = tmp_buf["base"]; } buf_list.push_back(base64_decode(tmp_buf.asString())); if (is_stream) // TCP should get the first payload only break; } } if (buf_list.size() == 0) { throw TrexException("l7_map value should be specified (no buffers to retrieve it by offset)"); } } else if (l7_map["offset"].size() != l7_map["value"].size()) { throw TrexException("l7_map value is not matched by offset"); } std::vector<uint8_t> l7_map_args; uint8_t last_offset = 0; for (int i = 0; i < l7_map["offset"].size(); i++) { uint8_t offset = (uint8_t)l7_map["offset"][i].asInt(); if (offset < last_offset) { throw TrexException("l7_map offset should be ascending order"); } l7_map_args.push_back(offset); last_offset = offset; uint8_t mask = (l7_map["mask"] && (l7_map["mask"].size() > i)) ? (uint8_t)l7_map["mask"][i].asInt() : UINT8_MAX; l7_map_args.push_back(mask); uint8_t value; if (l7_map["value"] == Json::nullValue) { if (offset >= buf_list[0].length()) { throw TrexException("packet length is short: " + std::to_string(offset) + " >= " + std::to_string(buf_list[0].length())); } value = buf_list[0].c_str()[offset] & mask; /* UDP should have the same value for all the packets */ if (!is_stream && buf_list.size() > 1) { for (int buf_index = 1; buf_index < buf_list.size(); buf_index++) { uint8_t _value = buf_list[buf_index].c_str()[offset] & mask; if (value != _value) { throw TrexException("UDP should have the same value for all the packets, " + std::to_string(value) + " != " + std::to_string(_value)); } } } } else { value = (uint8_t)l7_map["value"][i].asInt(); } l7_map_args.push_back(value); } server_info->append_payload_params(l7_map_args); } /* Convert list of buffers from json to CMbufBuffer */ bool CAstfDB::convert_bufs(uint8_t socket_id) { CMbufBuffer *tcp_buf; std::string json_buf; uint32_t buf_len; if (m_val["buf_list"].size() == 0) return true; for (int buf_index = 0; buf_index < m_val["buf_list"].size(); buf_index++) { tcp_buf = new CMbufBuffer(); assert(tcp_buf); std::string temp_str; if (m_val["buf_list"][buf_index].type() == Json::objectValue) { Json::Value buf_obj = m_val["buf_list"][buf_index]; if (buf_obj["base"] != Json::nullValue) { json_buf = buf_obj["base"].asString(); temp_str = base64_decode(json_buf); } if (buf_obj["size"] != Json::nullValue) { buf_len = buf_obj["size"].asUInt(); } else { buf_len = temp_str.size(); } std::string fill_data; if (buf_obj["fill"] != Json::nullValue) { fill_data = base64_decode(buf_obj["fill"].asString()); } utl_mbuf_buffer_create_and_copy(socket_id, tcp_buf, 2048, (uint8_t *)(temp_str.c_str()), temp_str.size(),buf_len,(uint8_t*)(fill_data.c_str()),fill_data.size(),true); } else { json_buf = m_val["buf_list"][buf_index].asString(); temp_str = base64_decode(json_buf); buf_len = temp_str.size(); utl_mbuf_buffer_create_and_copy(socket_id, tcp_buf, 2048, (uint8_t *)(temp_str.c_str()), buf_len,true); } m_tcp_data[socket_id].m_buf_list.push_back(tcp_buf); } return true; } /* Convert list of programs from json to CMbufBuffer */ bool CAstfDB::convert_progs(uint8_t socket_id) { CEmulAppCmd cmd; CEmulAppProgram *prog; uint32_t cmd_index; tcp_app_cmd_enum_t cmd_type; uint32_t prog_len=0; if (m_val["program_list"].size() == 0) return false; for (uint32_t program_index = 0; program_index < m_val["program_list"].size(); program_index++) { prog = new CEmulAppProgram(); assert(prog); bool is_stream = get_emul_stream(program_index); prog->set_stream(is_stream); uint64_t total_rx_wm = 0; cmd_index = 0; do { cmd_type = get_cmd(program_index, cmd_index); switch(cmd_type) { case tcNO_CMD: break; case tcTX_BUFFER: cmd.u.m_tx_cmd.m_buf = m_tcp_data[socket_id].m_buf_list[get_buf_index(program_index, cmd_index)]; cmd.m_cmd = tcTX_BUFFER; prog_len += cmd.u.m_tx_cmd.m_buf->len(); prog->add_cmd(cmd); break; case tcRX_BUFFER: cmd.m_cmd = tcRX_BUFFER; cmd.u.m_rx_cmd.m_flags = CEmulAppCmdRxBuffer::rxcmd_WAIT; get_rx_cmd(program_index, cmd_index,total_rx_wm,cmd); prog->add_cmd(cmd); break; case tcDELAY: cmd.m_cmd = tcDELAY; cmd.u.m_delay_cmd.m_ticks = get_delay_ticks(program_index, cmd_index); prog->add_cmd(cmd); break; case tcRESET: cmd.m_cmd = tcRESET; prog->add_cmd(cmd); break; case tcDONT_CLOSE: cmd.m_cmd = tcDONT_CLOSE; prog->add_cmd(cmd); break; case tcCONNECT_WAIT: cmd.m_cmd = tcCONNECT_WAIT; prog->add_cmd(cmd); break; case tcDELAY_RAND : cmd.m_cmd = tcDELAY_RAND; fill_delay_rnd(program_index, cmd_index,cmd); prog->add_cmd(cmd); break; case tcSET_VAR : cmd.m_cmd = tcSET_VAR; fill_set_var(program_index, cmd_index,cmd); prog->add_cmd(cmd); break; case tcSET_TICK_VAR: cmd.m_cmd = tcSET_TICK_VAR; fill_set_tick_var(program_index, cmd_index, cmd); prog->add_cmd(cmd); break; case tcJMPNZ : cmd.m_cmd = tcJMPNZ; fill_jmpnz(program_index, cmd_index,cmd); prog->add_cmd(cmd); break; case tcJMPDP : cmd.m_cmd = tcJMPDP; fill_jmpdp(program_index, cmd_index,cmd); prog->add_cmd(cmd); break; case tcTX_PKT : cmd.m_cmd = tcTX_PKT; fill_tx_pkt(program_index, cmd_index,socket_id,cmd); prog->add_cmd(cmd); break; case tcRX_PKT: cmd.m_cmd = tcRX_PKT; fill_rx_pkt(program_index, cmd_index,total_rx_wm,cmd); prog->add_cmd(cmd); break; case tcKEEPALIVE: cmd.m_cmd = tcKEEPALIVE; fill_keepalive_pkt(program_index, cmd_index,cmd); prog->add_cmd(cmd); break; case tcCLOSE_PKT: cmd.m_cmd = tcCLOSE_PKT; prog->add_cmd(cmd); break; case tcTX_MODE : cmd.m_cmd = tcTX_MODE; fill_tx_mode(program_index, cmd_index,cmd); prog->add_cmd(cmd); break; default: assert(0); } cmd_index++; } while (cmd_type != tcNO_CMD); std::string err; if (!prog->sanity_check(err)){ prog->Dump(stdout); fprintf(stdout,"ERROR program is not valid '%s' \n",err.c_str()); return(false); } m_tcp_data[socket_id].m_prog_list.push_back(prog); m_prog_lens.push_back(prog_len); prog_len = 0; } return true; } void CAstfDB::get_latency_params(CTcpLatency &lat) { Json::Value ip_gen_list = m_val["ip_gen_dist_list"]; bool client_set = false; bool server_set = false; std::string s; for (int i = 0; i < ip_gen_list.size(); i++) { if ((ip_gen_list[i]["dir"] == "c") && ! client_set) { client_set = true; s = ip_gen_list[i]["ip_start"].asString(); lat.m_c_ip = ip_from_str(s.c_str()); s = ip_gen_list[i]["ip_offset"].asString(); lat.m_dual_mask = ip_from_str(s.c_str()); } if ((ip_gen_list[i]["dir"] == "s") && ! server_set) { server_set = true; s = ip_gen_list[i]["ip_start"].asString(); lat.m_s_ip = ip_from_str(s.c_str()); } if (server_set && client_set) return; } } const std::vector<std::string>& CAstfDB::get_tg_names() { return m_tg_names; } void CAstfDB::clear_db_ro_rw(CTupleGeneratorSmart *g_gen, uint16_t thread_id) { std::unique_lock<std::mutex> my_lock(m_global_mtx); if (g_gen == nullptr) { remove_smart_gen(thread_id); } else { g_gen->Delete(); } /* to clear only when there is no thread generator */ if (m_smart_gen.size() == 0) { for ( auto &rw_db : m_rw_db) { if ( !rw_db ) { continue; } rw_db->Delete(); delete rw_db; } m_rw_db.clear(); for (auto &s_tuneables : m_s_tuneables) { delete s_tuneables; } m_s_tuneables.clear(); m_prog_lens.clear(); for (auto &tcp_data : m_tcp_data) { tcp_data.Delete(); } m_json_initiated = false; } my_lock.unlock(); } CTcpServerInfo * CAstfDbRO::get_server_info_by_port(uint16_t port,bool stream) { CTcpDataAssocParams params(port,stream); return m_assoc_trans.get_server_info(params); } void CAstfDbRO::dump(FILE *fd) { #if 0 fprintf(fd, "buf list:\n"); for (int i = 0; i < m_buf_list.size(); i++) { fprintf(fd, " *******%d*******\n", i); m_buf_list[i]->Dump(fd); } #endif } void CAstfDbRO::Delete() { if (m_init==0) return; int i; for (i = 0; i < m_buf_list.size(); i++) { m_buf_list[i]->Delete(); delete m_buf_list[i]; } m_buf_list.clear(); for (i = 0; i < m_prog_list.size(); i++) { delete m_prog_list[i]; } m_prog_list.clear(); for (i = 0; i < m_templates.size(); i++) { m_templates[i].Delete(); } m_templates.clear(); m_assoc_trans.clear(); m_init = 0; m_cps_sum=0.0; } void CAstfDbRO::set_test_assoc_table(uint16_t port, CEmulAppProgram *prog, CTcpTuneables *tune) { CTcpDataAssocParams params(port,true); CTcpTemplateInfo one_template; one_template.m_tg_id = 0; m_assoc_trans.insert_vec(params, prog, tune, 0); m_num_of_tg_ids = 1; m_templates.push_back(one_template); }
// // ALCUserClient.hpp // AppleALC // // Created by Nick on 10/14/20. // Copyright © 2020 vit9696. All rights reserved. // #ifndef ALCUserClient_hpp #define ALCUserClient_hpp #include <IOKit/IOService.h> #include <IOKit/IOUserClient.h> #include "UserKernelShared.h" #include "ALCUserClientProvider.hpp" class EXPORT ALCUserClient : public IOUserClient { using super = IOUserClient; OSDeclareDefaultStructors(ALCUserClient); ALCUserClientProvider* mProvider { nullptr }; task_t mTask {nullptr}; static const IOExternalMethodDispatch sMethods[kNumberOfMethods]; public: virtual bool start(IOService* provider) override; virtual bool initWithTask(task_t owningTask, void* securityToken, UInt32 type, OSDictionary* properties) override; virtual IOReturn clientClose() override; virtual IOReturn externalMethod(uint32_t selector, IOExternalMethodArguments* arguments, IOExternalMethodDispatch* dispatch, OSObject* target, void* reference) override; protected: static IOReturn methodExecuteVerb(ALCUserClientProvider* target, void* ref, IOExternalMethodArguments* args); }; #endif /* ALCUserClient_hpp */
#pragma once #include <cstdint> #include <string> constexpr uint8_t ELF_EI_MAG0 = 0; constexpr uint8_t ELF_EI_MAG1 = 1; constexpr uint8_t ELF_EI_MAG2 = 2; constexpr uint8_t ELF_EI_MAG3 = 3; constexpr uint8_t ELF_EI_CLASS = 4; constexpr uint8_t ELF_EI_DATA = 5; constexpr uint8_t ELF_EI_VERSION = 6; constexpr uint8_t ELF_EI_OSABI = 7; constexpr uint8_t ELF_EI_ABIVERSION = 8; constexpr uint8_t ELF_EI_PAD = 9; constexpr uint8_t ELF_EI_NIDENT = 16; constexpr uint8_t ELF_CLASS32 = 1; constexpr uint8_t ELF_CLASS64 = 2; constexpr uint8_t ELF_DATA2LSB = 1; constexpr uint8_t ELF_DATA2MSB = 2; constexpr uint8_t ELF_EV_CURRENT = 1; constexpr uint8_t ELF_OSABI_SYSV = 0; constexpr uint8_t ELF_OSABI_HPUX = 1; constexpr uint16_t ELF_ET_NONE = 0; constexpr uint16_t ELF_ET_REL = 1; constexpr uint16_t ELF_ET_EXEC = 2; constexpr uint16_t ELF_ET_DYN = 3; constexpr uint16_t ELF_ET_CORE = 4; constexpr uint16_t ELF_ET_LOOS = 0xfe00; constexpr uint16_t ELF_ET_HIOS = 0xfeff; constexpr uint16_t ELF_ET_LOPROC = 0xff00; constexpr uint16_t ELF_ET_HIPROC = 0xffff; constexpr uint32_t PT_NULL = 0; constexpr uint32_t PT_LOAD = 1; constexpr uint32_t PT_DYNAMIC = 2; constexpr uint32_t PT_INTERP = 3; constexpr uint32_t PT_NOTE = 4; constexpr uint32_t PT_SHLIB = 5; constexpr uint32_t PT_PHDR = 6; constexpr uint32_t PT_TLS = 7; constexpr uint32_t PT_LOOS = 0x60000000; constexpr uint32_t PT_GNU_EH_FRAME = 0x6474e550; constexpr uint32_t PT_GNU_STACK = 0x6474e551; constexpr uint32_t PT_GNU_RELRO = 0x6474e552; constexpr uint32_t PT_HIOS = 0x6fffffff; constexpr uint32_t PT_LOPROC = 0x70000000; constexpr uint32_t PT_HIPROC = 0x7fffffff; constexpr uint32_t PF_X = 0b001; constexpr uint32_t PF_W = 0b010; constexpr uint32_t PF_R = 0b100; constexpr uint32_t PF_MASKOS = 0x00ff0000; constexpr uint32_t PF_MASKPROC = 0xff000000; constexpr uint32_t NT_GNU_BUILD_ID = 0x3; constexpr uint16_t SHN_UNDEF = 0; constexpr uint32_t SHT_NULL = 0; constexpr uint32_t SHT_PROGBITS = 1; constexpr uint32_t SHT_SYMTAB = 2; constexpr uint32_t SHT_STRTAB = 3; constexpr uint32_t SHT_RELA = 4; constexpr uint32_t SHT_HASH = 5; constexpr uint32_t SHT_DYNAMIC = 6; constexpr uint32_t SHT_NOTE = 7; constexpr uint32_t SHT_NOBITS = 8; constexpr uint32_t SHT_REL = 9; constexpr uint32_t SHT_SHLIB = 10; constexpr uint32_t SHT_DYNSYM = 11; constexpr uint32_t SHT_INIT_ARRAY = 14; constexpr uint32_t SHT_FINI_ARRAY = 15; constexpr uint32_t SHT_LOOS = 0x60000000; constexpr uint32_t SHT_GNU_HASH = 0x6ffffff6; constexpr uint32_t SHT_VER_NEED = 0x6ffffffe; constexpr uint32_t SHT_HIOS = 0x6fffffff; constexpr uint32_t SHT_LOPROC = 0x70000000; constexpr uint32_t SHT_HIPROC = 0x7fffffff; constexpr uint64_t SHF_WRITE = 0b001; constexpr uint64_t SHF_ALLOC = 0b010; constexpr uint64_t SHF_EXECINSTR = 0b100; constexpr uint64_t SHF_MASKOS = 0x0f000000; constexpr uint64_t SHF_MASKPROC = 0xf0000000; std::string type_to_string(uint16_t e_type); std::string abi_to_string(uint8_t abi); std::string machine_to_string(uint16_t e_machine); std::string ptype_to_string(uint32_t ptype); std::string pflags_to_string(uint32_t flags); std::string shtype_to_string(uint32_t shtype); std::string shflags_to_string(uint64_t flags);
/* * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. 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 Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/dom/DocumentOrderedMap.h" #include "core/HTMLNames.h" #include "core/dom/Element.h" #include "core/dom/ElementTraversal.h" #include "core/dom/TreeScope.h" #include "core/html/HTMLMapElement.h" namespace blink { using namespace HTMLNames; inline bool keyMatchesId(const AtomicString& key, const Element& element) { return element.getIdAttribute() == key; } inline bool keyMatchesMapName(const AtomicString& key, const Element& element) { return isHTMLMapElement(element) && toHTMLMapElement(element).getName() == key; } inline bool keyMatchesLowercasedMapName(const AtomicString& key, const Element& element) { return isHTMLMapElement(element) && toHTMLMapElement(element).getName().lower() == key; } inline bool keyMatchesLabelForAttribute(const AtomicString& key, const Element& element) { return isHTMLLabelElement(element) && element.getAttribute(forAttr) == key; } PassOwnPtrWillBeRawPtr<DocumentOrderedMap> DocumentOrderedMap::create() { return adoptPtrWillBeNoop(new DocumentOrderedMap()); } void DocumentOrderedMap::add(const AtomicString& key, Element* element) { ASSERT(key); ASSERT(element); Map::AddResult addResult = m_map.add(key, adoptPtrWillBeNoop(new MapEntry(element))); if (addResult.isNewEntry) return; OwnPtrWillBeMember<MapEntry>& entry = addResult.storedValue->value; ASSERT(entry->count); entry->element = nullptr; entry->count++; entry->orderedList.clear(); } void DocumentOrderedMap::remove(const AtomicString& key, Element* element) { ASSERT(key); ASSERT(element); Map::iterator it = m_map.find(key); if (it == m_map.end()) return; OwnPtrWillBeMember<MapEntry>& entry = it->value; ASSERT(entry->count); if (entry->count == 1) { ASSERT(!entry->element || entry->element == element); m_map.remove(it); } else { if (entry->element == element) { ASSERT(entry->orderedList.isEmpty() || entry->orderedList.first() == element); entry->element = entry->orderedList.size() > 1 ? entry->orderedList[1] : nullptr; } entry->count--; entry->orderedList.clear(); } } template<bool keyMatches(const AtomicString&, const Element&)> inline Element* DocumentOrderedMap::get(const AtomicString& key, const TreeScope* scope) const { ASSERT(key); ASSERT(scope); MapEntry* entry = m_map.get(key); if (!entry) return 0; ASSERT(entry->count); if (entry->element) return entry->element; // We know there's at least one node that matches; iterate to find the first one. for (Element& element : ElementTraversal::startsAfter(scope->rootNode())) { if (!keyMatches(key, element)) continue; entry->element = &element; return &element; } ASSERT_NOT_REACHED(); return 0; } Element* DocumentOrderedMap::getElementById(const AtomicString& key, const TreeScope* scope) const { return get<keyMatchesId>(key, scope); } const WillBeHeapVector<RawPtrWillBeMember<Element> >& DocumentOrderedMap::getAllElementsById(const AtomicString& key, const TreeScope* scope) const { ASSERT(key); ASSERT(scope); DEFINE_STATIC_LOCAL(OwnPtrWillBePersistent<WillBeHeapVector<RawPtrWillBeMember<Element> > >, emptyVector, (adoptPtrWillBeNoop(new WillBeHeapVector<RawPtrWillBeMember<Element> >()))); Map::iterator it = m_map.find(key); if (it == m_map.end()) return *emptyVector; OwnPtrWillBeMember<MapEntry>& entry = it->value; ASSERT(entry->count); if (entry->orderedList.isEmpty()) { entry->orderedList.reserveCapacity(entry->count); for (Element* element = entry->element ? entry->element.get() : ElementTraversal::firstWithin(scope->rootNode()); entry->orderedList.size() < entry->count; element = ElementTraversal::next(*element)) { ASSERT(element); if (!keyMatchesId(key, *element)) continue; entry->orderedList.uncheckedAppend(element); } if (!entry->element) entry->element = entry->orderedList.first(); } return entry->orderedList; } Element* DocumentOrderedMap::getElementByMapName(const AtomicString& key, const TreeScope* scope) const { return get<keyMatchesMapName>(key, scope); } Element* DocumentOrderedMap::getElementByLowercasedMapName(const AtomicString& key, const TreeScope* scope) const { return get<keyMatchesLowercasedMapName>(key, scope); } Element* DocumentOrderedMap::getElementByLabelForAttribute(const AtomicString& key, const TreeScope* scope) const { return get<keyMatchesLabelForAttribute>(key, scope); } void DocumentOrderedMap::trace(Visitor* visitor) { #if ENABLE(OILPAN) visitor->trace(m_map); #endif } void DocumentOrderedMap::MapEntry::trace(Visitor* visitor) { visitor->trace(element); #if ENABLE(OILPAN) visitor->trace(orderedList); #endif } } // namespace blink
/* * Copyright (c) 2012-2013, 2015-2017 ARM Limited * All rights reserved. * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2002-2005 The Regents of The University of Michigan * Copyright (c) 2010 Advanced Micro Devices, Inc. * 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 holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @file * Miss Status and Handling Register (WriteQueueEntry) definitions. */ #include "mem/cache/write_queue_entry.hh" #include <cassert> #include <string> #include "base/logging.hh" #include "base/types.hh" #include "mem/cache/base.hh" #include "mem/request.hh" namespace gem5 { inline void WriteQueueEntry::TargetList::add(PacketPtr pkt, Tick readyTime, Counter order) { emplace_back(pkt, readyTime, order); } bool WriteQueueEntry::TargetList::trySatisfyFunctional(PacketPtr pkt) { for (auto& t : *this) { if (pkt->trySatisfyFunctional(t.pkt)) { return true; } } return false; } void WriteQueueEntry::TargetList::print(std::ostream &os, int verbosity, const std::string &prefix) const { for (auto& t : *this) { ccprintf(os, "%sFromCPU: ", prefix); t.pkt->print(os, verbosity, ""); } } void WriteQueueEntry::allocate(Addr blk_addr, unsigned blk_size, PacketPtr target, Tick when_ready, Counter _order) { blkAddr = blk_addr; blkSize = blk_size; isSecure = target->isSecure(); readyTime = when_ready; order = _order; assert(target); _isUncacheable = target->req->isUncacheable(); inService = false; // we should never have more than a single target for cacheable // writes (writebacks and clean evictions) panic_if(!_isUncacheable && !targets.empty(), "Write queue entry %#llx should never have more than one " "cacheable target", blkAddr); panic_if(!((target->isWrite() && _isUncacheable) || (target->isEviction() && !_isUncacheable) || target->cmd == MemCmd::WriteClean), "Write queue entry %#llx should be an uncacheable write or " "a cacheable eviction or a writeclean"); targets.add(target, when_ready, _order); // All targets must refer to the same block assert(target->matchBlockAddr(targets.front().pkt, blkSize)); } void WriteQueueEntry::deallocate() { assert(targets.empty()); inService = false; } bool WriteQueueEntry::trySatisfyFunctional(PacketPtr pkt) { // For printing, we treat the WriteQueueEntry as a whole as single // entity. For other requests, we iterate over the individual // targets since that's where the actual data lies. if (pkt->isPrint()) { pkt->trySatisfyFunctional(this, blkAddr, isSecure, blkSize, nullptr); return false; } else { return targets.trySatisfyFunctional(pkt); } } bool WriteQueueEntry::sendPacket(BaseCache &cache) { return cache.sendWriteQueuePacket(this); } bool WriteQueueEntry::matchBlockAddr(const Addr addr, const bool is_secure) const { assert(hasTargets()); return (blkAddr == addr) && (isSecure == is_secure); } bool WriteQueueEntry::matchBlockAddr(const PacketPtr pkt) const { assert(hasTargets()); return pkt->matchBlockAddr(blkAddr, isSecure, blkSize); } bool WriteQueueEntry::conflictAddr(const QueueEntry* entry) const { assert(hasTargets()); return entry->matchBlockAddr(blkAddr, isSecure); } void WriteQueueEntry::print(std::ostream &os, int verbosity, const std::string &prefix) const { ccprintf(os, "%s[%#llx:%#llx](%s) %s %s %s state: %s %s %s %s %s\n", prefix, blkAddr, blkAddr + blkSize - 1, isSecure ? "s" : "ns", _isUncacheable ? "Unc" : "", inService ? "InSvc" : ""); ccprintf(os, "%s Targets:\n", prefix); targets.print(os, verbosity, prefix + " "); } std::string WriteQueueEntry::print() const { std::ostringstream str; print(str); return str.str(); } } // namespace gem5
// SMsg_SetAvatarDescription.cpp -*- C++ -*- // $Id: SMsg_SetAvatarDescription.cpp,v 1.1 1998-04-17 16:32:00-07 jason Exp $ // Copyright 1996-1997 Lyra LLC, All rights reserved. // // message implementation #ifdef __GNUC__ #pragma implementation "SMsg_SetAvatarDescription.h" #endif #ifdef WIN32 #define STRICT #include "unix.h" #include <winsock.h> #else /* !WIN32 */ #include <sys/types.h> #include <netinet/in.h> #endif /* WIN32 */ #include <stdio.h> #include <string.h> #include "SMsg_SetAvatarDescription.h" #include "LyraDefs.h" #include "SMsg.h" #ifndef USE_INLINE #include "SMsg_SetAvatarDescription.i" #endif //// // constructor //// SMsg_SetAvatarDescription::SMsg_SetAvatarDescription() : LmMesg(SMsg::SETAVATARDESCRIPTION, sizeof(data_t), sizeof(data_t), &data_) { // initialize default message data values Init(Lyra::ID_UNKNOWN, _T("none")); } //// // destructor //// SMsg_SetAvatarDescription::~SMsg_SetAvatarDescription() { // empty } //// // Init //// void SMsg_SetAvatarDescription::Init(lyra_id_t playerid, const TCHAR* description) { SetPlayerID(playerid); SetDescription(description); } //// // hton //// void SMsg_SetAvatarDescription::hton() { HTONL(data_.playerid); // not converted: Description } //// // ntoh //// void SMsg_SetAvatarDescription::ntoh() { NTOHL(data_.playerid); // not converted: Description calc_size(); } //// // Dump: print to FILE stream //// #ifdef USE_DEBUG void SMsg_SetAvatarDescription::Dump(FILE* f, int indent) const { INDENT(indent, f); _ftprintf(f, _T("<SMsg_SetAvatarDescription[%p]: "), this); if (ByteOrder() == ByteOrder::HOST) { _ftprintf(f, _T("player=%u desc='%s'>\n"), PlayerID(), Description()); } else { _ftprintf(f, _T("(network order)>\n")); } // print out base class LmMesg::Dump(f, indent + 1); } #endif /* USE_DEBUG */ //// // SetDescription //// void SMsg_SetAvatarDescription::SetDescription(const TCHAR* description) { _tcsnccpy(data_.description, description, sizeof(data_.description)); TRUNC(data_.description, sizeof(data_.description)); calc_size(); } //// // calc_size //// void SMsg_SetAvatarDescription::calc_size() { // initial size: whole structure minus variable-length text int size = sizeof(data_t) - sizeof(data_.description); // add string length, plus 1 for null size += (_tcslen(data_.description) + 1); SetMessageSize(size); }
/* * 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: main.cpp * Author: Alex * * Created on 3 de abril de 2018, 09:11 AM */ #include <cstdlib> using namespace std; // 1. Definición de la clase class CEEmpleado{ private: int id; char nombre; char apellido; public: CEEmpleado(); // Constructor sin parámetros CEEmpleado(int); // Constructor con parámetros ~CEEmpleado(); // Destructor void imprimeSueldo(); void imprimeFicha(); }; // 2. Definición de la clase derivada class CEDirectivo:CEEmpleado{ private: long numeroEmpleados; long numeroAcciones; public: CEDirectivo(); // Constructor sin parámetros CEDirectivo(int); // Constructor con un parámetro CEDirectivo(float, double); // Constructor con dos parámetros void despideA(CEEmpleado *e); void reunionCon(CEDirectivo *d); void imprimeFicha(){ imprimeSueldo(); CEEmpleado::imprimeFicha(); } }; /* * */ int main(int argc, char** argv) { CEDirectivo d1, d2; CEEmpleado e1; d1.despideA(&e1); // El directivo puede despedir a un empleado d2.despideA(&d2); // o a otro directivo, ya que tambien es un empleado // e1.despideA(&d1); // Error un empleado no tiene definido el método d1.reunionCon(&d2); // Un directivo se reune con otro d1.reunionCon(&e1); // Error un empleado no se reunie con un directivo CEEmpleado *e2 = &d2; CEDirectivo *d3 = e1; // d3->numeroEmpleados = 3; d3 = (CEDirectivo *)e2.; // d1.imprimeSueldo(); error d1.imprimeFicha(); // d1.CEEmpleado::imprimeFicha(); error return 0; }
#pragma once //=====================================================================// /*! @file @brief RX66T プログラミング・プロトコル・クラス @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2019 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "rs232c_io.hpp" #include "rx_protocol.hpp" #include <vector> #include <set> #include <boost/format.hpp> namespace rx66t { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief RX64M プログラミング・プロトコル・クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class protocol { utils::rs232c_io rs232c_; bool verbose_ = false; bool connection_ = false; rx::protocol::device_type device_type_; uint32_t system_clock_ = 0; uint32_t device_clock_ = 0; uint32_t baud_speed_ = 0; speed_t baud_rate_ = B9600; bool enable_id_ = false; bool pe_turn_on_ = false; bool data_area_ = false; bool select_write_area_ = false; typedef std::set<uint32_t> erase_map; erase_map erase_map_; // uint8_t last_error_ = 0; static uint32_t get16_big_(const uint8_t* p) { uint32_t v; v = p[1]; v |= static_cast<uint32_t>(p[0]) << 8; return v; } static void put16_big_(uint8_t* p, uint32_t val) { p[0] = (val >> 8) & 0xff; p[1] = val & 0xff; } static uint32_t get32_big_(const uint8_t* p) { uint32_t v; v = p[3]; v |= static_cast<uint32_t>(p[2]) << 8; v |= static_cast<uint32_t>(p[1]) << 16; v |= static_cast<uint32_t>(p[0]) << 24; return v; } static void put32_big_(uint8_t* p, uint32_t val) { p[0] = (val >> 24) & 0xff; p[1] = (val >> 16) & 0xff; p[2] = (val >> 8) & 0xff; p[3] = val & 0xff; } static uint8_t sum_(const uint8_t* buff, uint32_t len) { uint16_t sum = 0; for(uint32_t i = 0; i < len; ++i) { sum += *buff++; } return (0 - sum) & 0xff; } bool read_(void* buff, uint32_t len, const timeval& tv) { return rs232c_.recv(buff, len, tv) == len; } bool read_(void* buff, uint32_t len) { timeval tv; tv.tv_sec = 5; tv.tv_usec = 0; return rs232c_.recv(buff, len, tv) == len; } bool write_(const void* buff, uint32_t len) { uint32_t wr = rs232c_.send(buff, len); rs232c_.sync_send(); return wr == len; } bool com_(uint8_t soh, uint8_t cmd, uint8_t ext, const uint8_t* src = nullptr, uint32_t len = 0) { uint8_t tmp[1 + 2 + 1 + len + 1 + 1]; tmp[0] = soh; put16_big_(&tmp[1], 1 + len); tmp[3] = cmd; if(len > 0) { std::memcpy(&tmp[4], src, len); } tmp[4 + len] = sum_(&tmp[1], 3 + len); tmp[4 + len + 1] = ext; uint32_t l = rs232c_.send(tmp, sizeof(tmp)); rs232c_.sync_send(); return l == sizeof(tmp); } bool command_(uint8_t cmd, const uint8_t* src = nullptr, uint32_t len = 0) { return com_(0x01, cmd, 0x03, src, len); } bool status_sub_(uint8_t* dst) { if(!read_(dst, 4)) { return false; } if(dst[0] != 0x81) { return false; } auto l = get16_big_(&dst[1]); if(l == 1 || l == 2) ; else { return false; } --l; if(!read_(&dst[4], l + 2)) { return false; } auto sum = sum_(&dst[1], 3 + l); if(sum != dst[4 + l]) { return false; } if(dst[4 + l + 1] != 0x03) { return false; } return true; } void dump_status_() { uint8_t tmp[4 + 1024 + 2]; if(!read_(tmp, 4)) { return; } auto l = get16_big_(&tmp[1]); if(!read_(&tmp[4], l + 1)) { return; } std::cout << boost::format("SOD: %02X") % static_cast<uint32_t>(tmp[0]) << std::endl; std::cout << boost::format("LEN: %d") % l << std::endl; std::cout << boost::format("RES: %02X") % static_cast<uint32_t>(tmp[3]) << std::endl; --l; if(l > 0) std::cout << "Dat: "; for(uint32_t i = 0; i < l; ++i) { boost::format(" %02X,") % static_cast<uint32_t>(tmp[4 + i]); } if(l > 0) std::cout << std::endl; std::cout << boost::format("SUM: %02X") % static_cast<uint32_t>(tmp[4 + l]) << std::endl; std::cout << boost::format("EXT: %02X") % static_cast<uint32_t>(tmp[4 + l + 1]) << std::endl; } bool status_(uint8_t res) { uint8_t tmp[4 + 1 + 1 + 1]; if(!status_sub_(tmp)) { return false; } return tmp[3] == res; } bool response_(uint8_t& res, uint8_t& err) { uint8_t tmp[4 + 1 + 1 + 1]; if(!status_sub_(tmp)) { return false; } res = tmp[3]; err = tmp[4]; return true; } bool status_back_(uint8_t res) { uint8_t tmp[4 + 1 + 1 + 1]; if(!status_sub_(tmp)) { return false; } if(tmp[3] != res) { return false; } if(!write_(tmp, sizeof(tmp))) { return false; } return true; } bool status_data_(uint8_t res, uint8_t* dst, uint32_t len) { uint8_t tmp[4 + len + 2]; if(!read_(tmp, 4)) { return false; } if(tmp[0] != 0x81) { return false; } if(tmp[3] != res) { return false; } auto l = get16_big_(&tmp[1]); if(l != (len + 1)) { return false; } if(!read_(&tmp[4], len + 2)) { return false; } auto sum = sum_(&tmp[1], len + 3); if(sum != tmp[4 + len]) { return false; } if(len > 0) { std::memcpy(dst, &tmp[4], len); } return true; } std::string out_section_(uint32_t n, uint32_t num) const { return (boost::format("#%02d/%02d: ") % n % num).str(); } public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// protocol() { } //-----------------------------------------------------------------// /*! @brief 接続 @param[in] path シリアルデバイスパス @param[in] brate ボーレート @param[in] rx CPU 設定 @return エラー無ければ「true」 */ //-----------------------------------------------------------------// bool bind(const std::string& path, uint32_t brate, const rx::protocol::rx_t& rx) { verbose_ = rx.verbose_; if(!start(path)) { std::cerr << "Can't open path: '" << path << "'" << std::endl; return false; } // コネクション if(!connection()) { std::cerr << "Can't connection." << std::endl; return false; } if(verbose_) { std::cout << "# Connection OK." << std::endl; } // デバイスタイプ取得 { if(!inquiry_device_type()) { std::cerr << "Inquiry device type error." << std::endl; return false; } auto a = get_device_type(); if(verbose_) { a.info(out_section_(1, 1)); } } // エンディアン通知コマンド { uint8_t endian = 0x01; if(!select_endian(endian)) { std::cerr << "Select endian error." << std::endl; } if(verbose_) { std::cout << out_section_(1, 1) << "Endian is " << (endian != 0 ? "little." : "big.") << std::endl; } } // 周波数設定コマンド { if(!select_frequency()) { std::cerr << "Select frequency error." << std::endl; } if(verbose_) { auto s = out_section_(1, 1); std::cout << s << boost::format("System clock: %d") % system_clock_ << std::endl; std::cout << s << boost::format("Device clock: %d") % device_clock_ << std::endl; } } // ボーレート変更 { if(!change_speed(rx, brate)) { std::cerr << "Can't change speed." << std::endl; return false; } if(verbose_) { auto sect = out_section_(1, 1); std::cout << sect << boost::format("Change baud rate: %d") % brate << std::endl; } } // ID 認証確認 { if(!inquiry_id()) { std::cerr << "Inquiry ID error." << std::endl; return false; } if(verbose_) { auto sect = out_section_(1, 1); std::cout << sect << boost::format("ID: %s") % (enable_id_ ? "Enable" : "Disable") << std::endl; } } // ID 認証が有効なら、ID コードチェックを行う if(enable_id_) { } pe_turn_on_ = true; erase_map_.clear(); return true; } //-----------------------------------------------------------------// /*! @brief 開始 @param[in] path シリアルデバイスパス @return エラー無ければ「true」 */ //-----------------------------------------------------------------// bool start(const std::string& path) { if(!rs232c_.open(path, B9600)) { return false; } if(!rs232c_.enable_RTS(false)) { return false; } if(!rs232c_.enable_DTR(false)) { return false; } return true; } //-----------------------------------------------------------------// /*! @brief コネクションの確立(startが成功したら呼ぶ) @return エラー無ければ「true」 */ //-----------------------------------------------------------------// bool connection() { bool ok = false; for(int i = 0; i < 30; ++i) { if(!rs232c_.send(0x00)) { return false; } timeval tv; tv.tv_sec = 0; tv.tv_usec = 10000; // 10ms int ch = rs232c_.recv(tv); if(ch == 0x00) { ok = true; break; } } if(!ok) return false; if(!rs232c_.send(0x55)) { return false; } timeval tv; tv.tv_sec = 1; tv.tv_usec = 0; int ch = rs232c_.recv(tv); if(ch == 0xC1) { connection_ = true; return true; } return false; } //-----------------------------------------------------------------// /*! @brief デバイス種別取得(connection が成功したら呼ぶ) @return エラー無ければ「true」 */ //-----------------------------------------------------------------// bool inquiry_device_type() { if(!connection_) return false; if(!command_(0x38)) { return false; } if(!status_back_(0x38)) { return false; } uint8_t tmp[24]; if(!status_data_(0x38, tmp, sizeof(tmp))) { return false; } std::memcpy(device_type_.TYP, &tmp[0], 8); device_type_.OSA = get32_big_(&tmp[8]); device_type_.OSI = get32_big_(&tmp[8 + 4]); device_type_.CPA = get32_big_(&tmp[8 + 4 + 4]); device_type_.CPI = get32_big_(&tmp[8 + 4 + 4 + 4]); return true; } //-----------------------------------------------------------------// /*! @brief デバイス種別を取得 @return デバイス */ //-----------------------------------------------------------------// const rx::protocol::device_type& get_device_type() const { return device_type_; } //-----------------------------------------------------------------// /*! @brief エンディアン通知コマンド @param[in] endian 0ならビッグ、1ならリトル @return エラー無ければ「true」 */ //-----------------------------------------------------------------// bool select_endian(uint8_t endian) { if(!connection_) return false; uint8_t tmp[1]; tmp[0] = endian; if(!command_(0x36, tmp, 1)) { return false; } if(!status_(0x36)) { return false; } return true; } //-----------------------------------------------------------------// /*! @brief 周波数設定コマンド @return エラー無ければ「true」 */ //-----------------------------------------------------------------// bool select_frequency() { if(!connection_) return false; uint8_t tmp[8]; put32_big_(&tmp[0], 16000000); put32_big_(&tmp[4], 120000000); if(!command_(0x32, tmp, sizeof(tmp))) { return false; } if(!status_back_(0x32)) { return false; } if(!status_data_(0x32, tmp, sizeof(tmp))) { return false; } system_clock_ = get32_big_(&tmp[0]); device_clock_ = get32_big_(&tmp[4]); return true; } //-----------------------------------------------------------------// /*! @brief 新ビットレート選択 @param[in] rx マイコン設定 @param[in] spped シリアル速度 @return エラー無ければ「true」 */ //-----------------------------------------------------------------// bool change_speed(const rx::protocol::rx_t& rx, uint32_t speed) { if(!connection_) return false; switch(speed) { case 19200: baud_rate_ = B19200; break; case 38400: baud_rate_ = B38400; break; case 57600: baud_rate_ = B57600; break; case 115200: baud_rate_ = B115200; break; case 230400: baud_rate_ = B230400; break; #ifdef WIN32 case 460800: baud_rate_ = B460800; break; case 500000: baud_rate_ = B500000; break; case 576000: baud_rate_ = B576000; break; #endif default: return false; } baud_speed_ = speed; uint8_t tmp[4]; put32_big_(&tmp[0], speed); if(!command_(0x34, tmp, sizeof(tmp))) { return false; } if(!status_(0x34)) { return false; } usleep(1000); // 1[ms] if(!rs232c_.change_speed(baud_rate_)) { return false; } // 同期コマンド if(!command_(0x00)) { return false; } if(!status_(0x00)) { return false; } return true; } //-----------------------------------------------------------------// /*! @brief ID 認証モード取得コマンド @return エラー無ければ「true」 */ //-----------------------------------------------------------------// bool inquiry_id() { if(!connection_) return false; if(!command_(0x2C)) { return false; } if(!status_back_(0x2C)) { return false; } uint8_t tmp[1]; if(!status_data_(0x2C, tmp, sizeof(tmp))) { return false; } if(tmp[0] == 0x00) enable_id_ = true; else if(tmp[0] == 0xFF) enable_id_ = false; else { return false; } return true; } //-----------------------------------------------------------------// /*! @brief イレース・ページ @param[in] address アドレス @return エラー無ければ「true」 */ //-----------------------------------------------------------------// bool erase_page(uint32_t address) { if(!connection_) return false; if(!pe_turn_on_) return false; // ブランク・チェックを行う uint8_t tmp[8]; auto org = address & 0xffffff00; put32_big_(&tmp[0], org); put32_big_(&tmp[4], org + 255); if(!command_(0x10, tmp, sizeof(tmp))) { return false; } uint8_t res; uint8_t err; if(!response_(res, err)) { return false; } if(res == 0x10) return true; // erase OK else if(res != 0x90) { return false; } else { if(err != 0xe0) { // do erase return false; } // erase NG; // std::cout << boost::format("Erase NG: %08X") % address << std::endl; if(address >= 0xFFFF0000) { // 8K block org = address & 0xFFFFE000; } else if(address >= 0xFFC00000) { // 32K block org = address & 0xFFFF8000; } put32_big_(&tmp[0], org); if(!command_(0x12, tmp, 4)) { // erase command return false; } if(!response_(res, err)) { return false; } if(res == 0x12) ; else if(res == 0x92) { std::cout << boost::format("Erase response: %02X") % static_cast<uint32_t>(err) << std::endl; return false; } else { return false; } } return true; } //-----------------------------------------------------------------// /*! @brief ユーザー・ブート/データ領域書き込み選択 @param[in] data ※常に、ユーザ/データ領域 @return エラー無ければ「true」 */ //-----------------------------------------------------------------// bool select_write_area(bool data) { if(!connection_) return false; if(!pe_turn_on_) return false; data_area_ = data; select_write_area_ = true; return true; } //-----------------------------------------------------------------// /*! @brief ライト・ページ(256バイト) @param[in] address アドレス @param[in] src ライト・データ @return エラー無ければ「true」 */ //-----------------------------------------------------------------// bool write_page(uint32_t address, const uint8_t* src) { if(!connection_) return false; if(!pe_turn_on_) return false; if(!select_write_area_) return false; // final method to pass... if(address == 0xFFFFFFFF || src == nullptr) { return true; } uint8_t tmp[8]; put32_big_(&tmp[0], address); put32_big_(&tmp[4], address + 255); if(!command_(0x13, tmp, sizeof(tmp))) { return false; } if(!status_(0x13)) { return false; } if(!com_(0x81, 0x13, 0x03, src, 256)) { return false; } uint8_t res; uint8_t err; if(!response_(res, err)) { return false; } if(res == 0x13) { // write OK return true; } else if(res == 0x93) { // write error std::cerr << std::endl; std::cerr << boost::format("Write error (%08X), status: %02X") % address % static_cast<uint32_t>(err) << std::endl; } return false; } //-----------------------------------------------------------------// /*! @brief リード・ページ(256バイト) @param[in] adr アドレス @param[out] dst リード・データ @return エラー無ければ「true」 */ //-----------------------------------------------------------------// bool read_page(uint32_t adr, uint8_t* dst) { if(!connection_) return false; if(!pe_turn_on_) return false; uint8_t tmp[8]; put32_big_(&tmp[0], adr); put32_big_(&tmp[4], adr + 255); if(!command_(0x15, tmp, sizeof(tmp))) { return false; } if(!status_(0x15)) { return false; } if(!com_(0x81, 0x15, 0x03)) { return false; } if(!status_data_(0x15, dst, 256)) { return false; } return true; } //-----------------------------------------------------------------// /*! @brief 終了 @return エラー無ければ「true」 */ //-----------------------------------------------------------------// bool end() { connection_ = false; pe_turn_on_ = false; select_write_area_ = false; return rs232c_.close(); } }; }
// Copyright (c) 2007-2021 Hartmut Kaiser // Copyright (c) 2014 Thomas Heller // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #pragma once #include <pika/config.hpp> #include <pika/concepts/has_member_xxx.hpp> #include <pika/functional/function.hpp> #include <pika/type_support/unused.hpp> #include <cstddef> #include <map> #include <memory> #ifdef PIKA_HAVE_VERIFY_LOCKS_BACKTRACE #include <string> #endif #include <type_traits> #include <utility> /////////////////////////////////////////////////////////////////////////////// namespace pika { namespace util { struct register_lock_data { }; // Always provide function exports, which guarantees ABI compatibility of // Debug and Release builds. #if defined(PIKA_HAVE_VERIFY_LOCKS) || defined(PIKA_EXPORTS) namespace detail { struct PIKA_EXPORT lock_data { #ifdef PIKA_HAVE_VERIFY_LOCKS lock_data(std::size_t trace_depth); lock_data(register_lock_data* data, std::size_t trace_depth); ~lock_data(); bool ignore_; register_lock_data* user_data_; #ifdef PIKA_HAVE_VERIFY_LOCKS_BACKTRACE std::string backtrace_; #endif #endif }; } // namespace detail struct held_locks_data { using held_locks_map = std::map<void const*, detail::lock_data>; held_locks_data() : enabled_(true) , ignore_all_locks_(false) { } held_locks_map map_; bool enabled_; bool ignore_all_locks_; }; /////////////////////////////////////////////////////////////////////////// PIKA_EXPORT bool register_lock( void const* lock, register_lock_data* data = nullptr); PIKA_EXPORT bool unregister_lock(void const* lock); PIKA_EXPORT void verify_no_locks(); PIKA_EXPORT void force_error_on_lock(); PIKA_EXPORT void enable_lock_detection(); PIKA_EXPORT void disable_lock_detection(); PIKA_EXPORT void trace_depth_lock_detection(std::size_t value); PIKA_EXPORT void ignore_lock(void const* lock); PIKA_EXPORT void reset_ignored(void const* lock); PIKA_EXPORT void ignore_all_locks(); PIKA_EXPORT void reset_ignored_all(); using registered_locks_error_handler_type = util::function_nonser<void()>; /// Sets a handler which gets called when verifying that no locks are held /// fails. Can be used to print information at the point of failure such as /// a backtrace. PIKA_EXPORT void set_registered_locks_error_handler( registered_locks_error_handler_type); using register_locks_predicate_type = util::function_nonser<bool()>; /// Sets a predicate which gets called each time a lock is registered, /// unregistered, or when locks are verified. If the predicate returns /// false, the corresponding function will not register, unregister, or /// verify locks. If it returns true the corresponding function may /// register, unregister, or verify locks, depending on other factors (such /// as if lock detection is enabled globally). The predicate may return /// different values depending on context. PIKA_EXPORT void set_register_locks_predicate( register_locks_predicate_type); /////////////////////////////////////////////////////////////////////////// struct ignore_all_while_checking { ignore_all_while_checking() { ignore_all_locks(); } ~ignore_all_while_checking() { reset_ignored_all(); } }; namespace detail { PIKA_HAS_MEMBER_XXX_TRAIT_DEF(mutex) } template <typename Lock, typename Enable = std::enable_if_t<detail::has_mutex_v<Lock>>> struct ignore_while_checking { explicit ignore_while_checking(Lock const* lock) : mtx_(lock->mutex()) { ignore_lock(mtx_); } ~ignore_while_checking() { reset_ignored(mtx_); } void const* mtx_; }; // The following functions are used to store the held locks information // during thread suspension. The data is stored on a thread_local basis, // so we must make sure that locks the are being ignored are restored // after suspension even if the thread is being resumed on a different core. // retrieve the current thread_local data about held locks PIKA_EXPORT std::unique_ptr<held_locks_data> get_held_locks_data(); // set the current thread_local data about held locks PIKA_EXPORT void set_held_locks_data( std::unique_ptr<held_locks_data>&& data); #else template <typename Lock, typename Enable = void> struct ignore_while_checking { explicit constexpr ignore_while_checking(Lock const* /*lock*/) noexcept { } }; struct ignore_all_while_checking { constexpr ignore_all_while_checking() noexcept {} }; constexpr inline bool register_lock( void const*, util::register_lock_data* = nullptr) noexcept { return true; } constexpr inline bool unregister_lock(void const*) noexcept { return true; } constexpr inline void verify_no_locks() noexcept {} constexpr inline void force_error_on_lock() noexcept {} constexpr inline void enable_lock_detection() noexcept {} constexpr inline void disable_lock_detection() noexcept {} constexpr inline void trace_depth_lock_detection( std::size_t /*value*/) noexcept { } constexpr inline void ignore_lock(void const* /*lock*/) noexcept {} constexpr inline void reset_ignored(void const* /*lock*/) noexcept {} constexpr inline void ignore_all_locks() noexcept {} constexpr inline void reset_ignored_all() noexcept {} struct held_locks_data { }; inline std::unique_ptr<held_locks_data> get_held_locks_data() { return std::unique_ptr<held_locks_data>(); } constexpr inline void set_held_locks_data( std::unique_ptr<held_locks_data>&& /*data*/) noexcept { } #endif }} // namespace pika::util
#ifndef POSIX_SUBSYSTEM_VFS_HPP #define POSIX_SUBSYSTEM_VFS_HPP #include <string.h> #include <iostream> #include <set> #include <deque> #include <async/result.hpp> #include <boost/intrusive/rbtree.hpp> #include <hel.h> #include "file.hpp" #include "fs.hpp" using ResolveFlags = uint32_t; inline constexpr ResolveFlags resolvePrefix = (1 << 4); inline constexpr ResolveFlags resolveDontFollow = (1 << 1); //! Represents a virtual view of the file system. //! We handle all mount point related logic in this class. struct MountView : std::enable_shared_from_this<MountView> { static std::shared_ptr<MountView> createRoot(std::shared_ptr<FsLink> origin); // TODO: This is an implementation detail that could be hidden. explicit MountView(std::shared_ptr<MountView> parent, std::shared_ptr<FsLink> anchor, std::shared_ptr<FsLink> origin) : _parent{std::move(parent)}, _anchor{std::move(anchor)}, _origin{std::move(origin)} { } std::shared_ptr<MountView> getParent() const; std::shared_ptr<FsLink> getAnchor() const; std::shared_ptr<FsLink> getOrigin() const; async::result<void> mount(std::shared_ptr<FsLink> anchor, std::shared_ptr<FsLink> origin); std::shared_ptr<MountView> getMount(std::shared_ptr<FsLink> link) const; private: struct Compare { struct is_transparent { }; bool operator() (const std::shared_ptr<MountView> &a, const std::shared_ptr<FsLink> &b) const { return a->getAnchor() < b; } bool operator() (const std::shared_ptr<FsLink> &a, const std::shared_ptr<MountView> &b) const { return a < b->getAnchor(); } bool operator() (const std::shared_ptr<MountView> &a, const std::shared_ptr<MountView> &b) const { return a->getAnchor() < b->getAnchor(); } }; std::shared_ptr<MountView> _parent; std::shared_ptr<FsLink> _anchor; std::shared_ptr<FsLink> _origin; std::set<std::shared_ptr<MountView>, Compare> _mounts; }; using ViewPath = std::pair<std::shared_ptr<MountView>, std::shared_ptr<FsLink>>; struct PathResolver { void setup(ViewPath root, ViewPath workdir, std::string string); async::result<frg::expected<protocols::fs::Error, void>> resolve(ResolveFlags flags = 0); std::string nextComponent() { assert(!_components.empty()); return _components.front(); } std::shared_ptr<MountView> currentView() { return _currentPath.first; } std::shared_ptr<FsLink> currentLink() { return _currentPath.second; } private: ViewPath _rootPath; std::deque<std::string> _components; ViewPath _currentPath; }; async::result<void> populateRootView(); ViewPath rootPath(); // TODO: Switch to PathResolver instead of using this function. async::result<frg::expected<protocols::fs::Error, ViewPath>> resolve(ViewPath root, ViewPath workdir, std::string name, ResolveFlags flags = 0); async::result<frg::expected<Error, smarter::shared_ptr<File, FileHandle>>> open(ViewPath root, ViewPath workdir, std::string name, ResolveFlags resolve_flags = 0, SemanticFlags semantic_flags = 0); #endif // POSIX_SUBSYSTEM_VFS_HPP
#include "pch.h" #include <vcpkg/base/checks.h> #include <vcpkg/base/system.h> #include <vcpkg/globalstate.h> #include <vcpkg/metrics.h> #include <time.h> #pragma comment(lib, "Advapi32") namespace vcpkg::System { tm get_current_date_time() { using std::chrono::system_clock; std::time_t now_time = system_clock::to_time_t(system_clock::now()); tm parts; #if defined(_WIN32) localtime_s(&parts, &now_time); #else parts = *localtime(&now_time); #endif return parts; } fs::path get_exe_path_of_current_process() { #if defined(_WIN32) wchar_t buf[_MAX_PATH]; const int bytes = GetModuleFileNameW(nullptr, buf, _MAX_PATH); if (bytes == 0) std::abort(); return fs::path(buf, buf + bytes); #else std::array<char, 1024 * 4> buf; auto written = readlink("/proc/self/exe", buf.data(), buf.size()); Checks::check_exit(VCPKG_LINE_INFO, written != -1, "Could not determine current executable path."); return fs::path(buf.data(), buf.data() + written); #endif } Optional<CPUArchitecture> to_cpu_architecture(const CStringView& arch) { if (Strings::case_insensitive_ascii_equals(arch, "x86")) return CPUArchitecture::X86; if (Strings::case_insensitive_ascii_equals(arch, "x64")) return CPUArchitecture::X64; if (Strings::case_insensitive_ascii_equals(arch, "amd64")) return CPUArchitecture::X64; if (Strings::case_insensitive_ascii_equals(arch, "arm")) return CPUArchitecture::ARM; if (Strings::case_insensitive_ascii_equals(arch, "arm64")) return CPUArchitecture::ARM64; return nullopt; } CPUArchitecture get_host_processor() { #if defined(_WIN32) auto w6432 = get_environment_variable("PROCESSOR_ARCHITEW6432"); if (const auto p = w6432.get()) return to_cpu_architecture(*p).value_or_exit(VCPKG_LINE_INFO); const auto procarch = get_environment_variable("PROCESSOR_ARCHITECTURE").value_or_exit(VCPKG_LINE_INFO); return to_cpu_architecture(procarch).value_or_exit(VCPKG_LINE_INFO); #else #if defined(__x86_64__) || defined(_M_X64) return CPUArchitecture::X64; #elif defined(__x86__) || defined(_M_X86) return CPUArchitecture::X86; #else #error "Unknown host architecture" #endif #endif } std::vector<CPUArchitecture> get_supported_host_architectures() { std::vector<CPUArchitecture> supported_architectures; supported_architectures.push_back(get_host_processor()); // AMD64 machines support to run x86 applications if (supported_architectures.back() == CPUArchitecture::X64) { supported_architectures.push_back(CPUArchitecture::X86); } return supported_architectures; } CMakeVariable::CMakeVariable(const CStringView varname, const char* varvalue) : s(Strings::format(R"("-D%s=%s")", varname, varvalue)) { } CMakeVariable::CMakeVariable(const CStringView varname, const std::string& varvalue) : CMakeVariable(varname, varvalue.c_str()) { } CMakeVariable::CMakeVariable(const CStringView varname, const fs::path& path) : CMakeVariable(varname, path.generic_u8string()) { } std::string make_cmake_cmd(const fs::path& cmake_exe, const fs::path& cmake_script, const std::vector<CMakeVariable>& pass_variables) { const std::string cmd_cmake_pass_variables = Strings::join(" ", pass_variables, [](auto&& v) { return v.s; }); return Strings::format( R"("%s" %s -P "%s")", cmake_exe.u8string(), cmd_cmake_pass_variables, cmake_script.generic_u8string()); } PowershellParameter::PowershellParameter(const CStringView varname, const char* varvalue) : s(Strings::format(R"(-%s '%s')", varname, varvalue)) { } PowershellParameter::PowershellParameter(const CStringView varname, const std::string& varvalue) : PowershellParameter(varname, varvalue.c_str()) { } PowershellParameter::PowershellParameter(const CStringView varname, const fs::path& path) : PowershellParameter(varname, path.generic_u8string()) { } static std::string make_powershell_cmd(const fs::path& script_path, const std::vector<PowershellParameter>& parameters) { const std::string args = Strings::join(" ", parameters, [](auto&& v) { return v.s; }); // TODO: switch out ExecutionPolicy Bypass with "Remove Mark Of The Web" code and restore RemoteSigned return Strings::format( R"(powershell -NoProfile -ExecutionPolicy Bypass -Command "& {& '%s' %s}")", script_path.u8string(), args); } int cmd_execute_clean(const CStringView cmd_line) { #if defined(_WIN32) static const std::string SYSTEM_ROOT = get_environment_variable("SystemRoot").value_or_exit(VCPKG_LINE_INFO); static const std::string SYSTEM_32 = SYSTEM_ROOT + R"(\system32)"; static const std::string NEW_PATH = Strings::format( R"(Path=%s;%s;%s\Wbem;%s\WindowsPowerShell\v1.0\)", SYSTEM_32, SYSTEM_ROOT, SYSTEM_32, SYSTEM_32); std::vector<std::wstring> env_wstrings = { L"ALLUSERSPROFILE", L"APPDATA", L"CommonProgramFiles", L"CommonProgramFiles(x86)", L"CommonProgramW6432", L"COMPUTERNAME", L"ComSpec", L"HOMEDRIVE", L"HOMEPATH", L"LOCALAPPDATA", L"LOGONSERVER", L"NUMBER_OF_PROCESSORS", L"OS", L"PATHEXT", L"PROCESSOR_ARCHITECTURE", L"PROCESSOR_ARCHITEW6432", L"PROCESSOR_IDENTIFIER", L"PROCESSOR_LEVEL", L"PROCESSOR_REVISION", L"ProgramData", L"ProgramFiles", L"ProgramFiles(x86)", L"ProgramW6432", L"PROMPT", L"PSModulePath", L"PUBLIC", L"SystemDrive", L"SystemRoot", L"TEMP", L"TMP", L"USERDNSDOMAIN", L"USERDOMAIN", L"USERDOMAIN_ROAMINGPROFILE", L"USERNAME", L"USERPROFILE", L"windir", // Enables proxy information to be passed to Curl, the underlying download library in cmake.exe L"http_proxy", L"https_proxy", // Enables find_package(CUDA) in CMake L"CUDA_PATH", // Environmental variable generated automatically by CUDA after installation L"NVCUDASAMPLES_ROOT", }; // Flush stdout before launching external process fflush(nullptr); std::wstring env_cstr; for (auto&& env_wstring : env_wstrings) { const Optional<std::string> value = System::get_environment_variable(Strings::to_utf8(env_wstring)); const auto v = value.get(); if (!v || v->empty()) continue; env_cstr.append(env_wstring); env_cstr.push_back(L'='); env_cstr.append(Strings::to_utf16(*v)); env_cstr.push_back(L'\0'); } env_cstr.append(Strings::to_utf16(NEW_PATH)); env_cstr.push_back(L'\0'); env_cstr.append(L"VSLANG=1033"); env_cstr.push_back(L'\0'); STARTUPINFOW startup_info; memset(&startup_info, 0, sizeof(STARTUPINFOW)); startup_info.cb = sizeof(STARTUPINFOW); PROCESS_INFORMATION process_info; memset(&process_info, 0, sizeof(PROCESS_INFORMATION)); // Basically we are wrapping it in quotes const std::string actual_cmd_line = Strings::format(R"###(cmd.exe /c "%s")###", cmd_line); Debug::println("CreateProcessW(%s)", actual_cmd_line); bool succeeded = TRUE == CreateProcessW(nullptr, Strings::to_utf16(actual_cmd_line).data(), nullptr, nullptr, FALSE, IDLE_PRIORITY_CLASS | CREATE_UNICODE_ENVIRONMENT, env_cstr.data(), nullptr, &startup_info, &process_info); Checks::check_exit(VCPKG_LINE_INFO, succeeded, "Process creation failed with error code: %lu", GetLastError()); CloseHandle(process_info.hThread); const DWORD result = WaitForSingleObject(process_info.hProcess, INFINITE); Checks::check_exit(VCPKG_LINE_INFO, result != WAIT_FAILED, "WaitForSingleObject failed"); DWORD exit_code = 0; GetExitCodeProcess(process_info.hProcess, &exit_code); Debug::println("CreateProcessW() returned %lu", exit_code); return static_cast<int>(exit_code); #else fflush(nullptr); return system(cmd_line.c_str()); #endif } int cmd_execute(const CStringView cmd_line) { // Flush stdout before launching external process fflush(nullptr); // Basically we are wrapping it in quotes const std::string& actual_cmd_line = Strings::format(R"###("%s")###", cmd_line); #if defined(_WIN32) Debug::println("_wsystem(%s)", actual_cmd_line); const int exit_code = _wsystem(Strings::to_utf16(actual_cmd_line).c_str()); Debug::println("_wsystem() returned %d", exit_code); #else Debug::println("_system(%s)", actual_cmd_line); const int exit_code = system(actual_cmd_line.c_str()); Debug::println("_system() returned %d", exit_code); #endif return exit_code; } // On Win7, output from powershell calls contain a byte order mark, so we strip it out if it is present static void remove_byte_order_marks(std::wstring* s) { const wchar_t* a = s->c_str(); // This is the UTF-8 byte-order mark while (s->size() >= 3 && a[0] == 0xEF && a[1] == 0xBB && a[2] == 0xBF) { s->erase(0, 3); } } ExitCodeAndOutput cmd_execute_and_capture_output(const CStringView cmd_line) { // Flush stdout before launching external process fflush(stdout); #if defined(_WIN32) const auto actual_cmd_line = Strings::format(R"###("%s 2>&1")###", cmd_line); Debug::println("_wpopen(%s)", actual_cmd_line); std::wstring output; wchar_t buf[1024]; const auto pipe = _wpopen(Strings::to_utf16(actual_cmd_line).c_str(), L"r"); if (pipe == nullptr) { return {1, Strings::to_utf8(output)}; } while (fgetws(buf, 1024, pipe)) { output.append(buf); } if (!feof(pipe)) { return {1, Strings::to_utf8(output)}; } const auto ec = _pclose(pipe); Debug::println("_pclose() returned %d", ec); remove_byte_order_marks(&output); return {ec, Strings::to_utf8(output)}; #else const auto actual_cmd_line = Strings::format(R"###(%s 2>&1)###", cmd_line); Debug::println("popen(%s)", actual_cmd_line); std::string output; char buf[1024]; const auto pipe = popen(actual_cmd_line.c_str(), "r"); if (pipe == nullptr) { return {1, output}; } while (fgets(buf, 1024, pipe)) { output.append(buf); } if (!feof(pipe)) { return {1, output}; } const auto ec = pclose(pipe); Debug::println("pclose() returned %d", ec); return {ec, output}; #endif } void powershell_execute(const std::string& title, const fs::path& script_path, const std::vector<PowershellParameter>& parameters) { const std::string cmd = make_powershell_cmd(script_path, parameters); const int rc = System::cmd_execute(cmd); if (rc) { System::println(Color::error, "%s\n" "Could not run:\n" " '%s'", title, script_path.generic_string()); { auto locked_metrics = Metrics::g_metrics.lock(); locked_metrics->track_property("error", "powershell script failed"); locked_metrics->track_property("title", title); } Checks::exit_with_code(VCPKG_LINE_INFO, rc); } } std::string powershell_execute_and_capture_output(const std::string& title, const fs::path& script_path, const std::vector<PowershellParameter>& parameters) { const std::string cmd = make_powershell_cmd(script_path, parameters); auto rc = System::cmd_execute_and_capture_output(cmd); if (rc.exit_code) { System::println(Color::error, "%s\n" "Could not run:\n" " '%s'\n" "Error message was:\n" " %s", title, script_path.generic_string(), rc.output); { auto locked_metrics = Metrics::g_metrics.lock(); locked_metrics->track_property("error", "powershell script failed"); locked_metrics->track_property("title", title); } Checks::exit_with_code(VCPKG_LINE_INFO, rc.exit_code); } // Remove newline from all output. // Powershell returns newlines when it hits the column count of the console. // For example, this is 80 in cmd on Windows 7. If the expected output is longer than 80 lines, we get // newlines in-between the data. // To solve this, we design our interaction with powershell to not depend on newlines, // and then strip all newlines here. rc.output = Strings::replace_all(std::move(rc.output), "\n", ""); return rc.output; } void println() { putchar('\n'); } void print(const CStringView message) { fputs(message.c_str(), stdout); } void println(const CStringView message) { print(message); println(); } void print(const Color c, const CStringView message) { #if defined(_WIN32) const HANDLE console_handle = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO console_screen_buffer_info{}; GetConsoleScreenBufferInfo(console_handle, &console_screen_buffer_info); const auto original_color = console_screen_buffer_info.wAttributes; SetConsoleTextAttribute(console_handle, static_cast<WORD>(c) | (original_color & 0xF0)); print(message); SetConsoleTextAttribute(console_handle, original_color); #else print(message); #endif } void println(const Color c, const CStringView message) { print(c, message); println(); } Optional<std::string> get_environment_variable(const CStringView varname) noexcept { #if defined(_WIN32) const auto w_varname = Strings::to_utf16(varname); const auto sz = GetEnvironmentVariableW(w_varname.c_str(), nullptr, 0); if (sz == 0) return nullopt; std::wstring ret(sz, L'\0'); Checks::check_exit(VCPKG_LINE_INFO, MAXDWORD >= ret.size()); const auto sz2 = GetEnvironmentVariableW(w_varname.c_str(), ret.data(), static_cast<DWORD>(ret.size())); Checks::check_exit(VCPKG_LINE_INFO, sz2 + 1 == sz); ret.pop_back(); return Strings::to_utf8(ret); #else auto v = getenv(varname.c_str()); if (!v) return nullopt; return std::string(v); #endif } #if defined(_WIN32) static bool is_string_keytype(const DWORD hkey_type) { return hkey_type == REG_SZ || hkey_type == REG_MULTI_SZ || hkey_type == REG_EXPAND_SZ; } Optional<std::string> get_registry_string(void* base_hkey, const CStringView sub_key, const CStringView valuename) { HKEY k = nullptr; const LSTATUS ec = RegOpenKeyExW(reinterpret_cast<HKEY>(base_hkey), Strings::to_utf16(sub_key).c_str(), NULL, KEY_READ, &k); if (ec != ERROR_SUCCESS) return nullopt; DWORD dw_buffer_size = 0; DWORD dw_type = 0; auto rc = RegQueryValueExW(k, Strings::to_utf16(valuename).c_str(), nullptr, &dw_type, nullptr, &dw_buffer_size); if (rc != ERROR_SUCCESS || !is_string_keytype(dw_type) || dw_buffer_size == 0 || dw_buffer_size % sizeof(wchar_t) != 0) return nullopt; std::wstring ret; ret.resize(dw_buffer_size / sizeof(wchar_t)); rc = RegQueryValueExW(k, Strings::to_utf16(valuename).c_str(), nullptr, &dw_type, reinterpret_cast<LPBYTE>(ret.data()), &dw_buffer_size); if (rc != ERROR_SUCCESS || !is_string_keytype(dw_type) || dw_buffer_size != sizeof(wchar_t) * ret.size()) return nullopt; ret.pop_back(); // remove extra trailing null byte return Strings::to_utf8(ret); } #else Optional<std::string> get_registry_string(void* base_hkey, const CStringView sub_key, const CStringView valuename) { return nullopt; } #endif static const fs::path& get_program_files() { static const fs::path PATH = System::get_environment_variable("PROGRAMFILES").value_or_exit(VCPKG_LINE_INFO); return PATH; } const fs::path& get_program_files_32_bit() { static const fs::path PATH = []() -> fs::path { auto value = System::get_environment_variable("ProgramFiles(x86)"); if (auto v = value.get()) { return std::move(*v); } return get_program_files(); }(); return PATH; } const fs::path& get_program_files_platform_bitness() { static const fs::path PATH = []() -> fs::path { auto value = System::get_environment_variable("ProgramW6432"); if (auto v = value.get()) { return std::move(*v); } return get_program_files(); }(); return PATH; } } namespace vcpkg::Debug { void println(const CStringView message) { if (GlobalState::debugging) { System::println("[DEBUG] %s", message); } } void println(const System::Color c, const CStringView message) { if (GlobalState::debugging) { System::println(c, "[DEBUG] %s", message); } } }
#include "glwidget.hpp" const std::string mesh_file("../mesh.1.1.1.0.8.8.sdm"); ///////////////////////////////////////////////////////////////////////////////////////////////////// //GLWidget::GLWidget ///////////////////////////////////////////////////////////////////////////////////////////////////// GLWidget::GLWidget(QWidget *parent) : QGLWidget(parent), show_wireframe(true), show_ids(true) { sdm_file = new SDM_MeshFile(mesh_file); sdm_file->read_sdm_file(); //render all element types and all entries by default for (size_t i = 0; i < sdm_file->number_vec_elements; i++) { Render_options_t opt; opt.index = -1; opt.render = true; this->render_vec_elements.push_back(opt); } x_rotation = 20.0f; y_rotation = 30.0f; } ///////////////////////////////////////////////////////////////////////////////////////////////////// //GLWidget::~GLWidget ///////////////////////////////////////////////////////////////////////////////////////////////////// GLWidget::~GLWidget() { delete sdm_file; } ///////////////////////////////////////////////////////////////////////////////////////////////////// //GLWidget::resizeGL ///////////////////////////////////////////////////////////////////////////////////////////////////// void GLWidget::resizeGL(int w, int h) { this->reshape(w, h); } ///////////////////////////////////////////////////////////////////////////////////////////////////// //GLWidget::initializeGL ///////////////////////////////////////////////////////////////////////////////////////////////////// void GLWidget::initializeGL() { } ///////////////////////////////////////////////////////////////////////////////////////////////////// //GLWidget::paintGL ///////////////////////////////////////////////////////////////////////////////////////////////////// void GLWidget::paintGL() { this->display(); } ///////////////////////////////////////////////////////////////////////////////////////////////////// //GLWidget::reshape ///////////////////////////////////////////////////////////////////////////////////////////////////// void GLWidget::reshape(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho (-1.0*(GLfloat)w/(GLfloat)h, 1.0*(GLfloat)w/(GLfloat)h, -1.0, 1.0, -1.0, 1.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } ///////////////////////////////////////////////////////////////////////////////////////////////////// //GLWidget::display ///////////////////////////////////////////////////////////////////////////////////////////////////// void GLWidget::display(void) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glLoadIdentity(); glRotatef(x_rotation, 1.0f, 0.0f, 0.0f); glRotatef(y_rotation, 0.0f, 1.0f, 0.0f); glTranslatef(-0.5f, -0.5f, 0.0f); render_mesh(); } ///////////////////////////////////////////////////////////////////////////////////////////////////// //GLWidget::keyPressEvent ///////////////////////////////////////////////////////////////////////////////////////////////////// void GLWidget::keyPressEvent(QKeyEvent *e) { switch (e->key()) { case Qt::Key_I: show_ids = ! show_ids; updateGL(); break; case Qt::Key_W: show_wireframe = ! show_wireframe; updateGL(); break; case Qt::Key_F1: if(this->render_vec_elements.size() >= 1) { this->render_vec_elements[ 0 ].render = ! this->render_vec_elements[ 0 ].render; updateGL(); } break; case Qt::Key_F2: if(this->render_vec_elements.size() >= 2) { this->render_vec_elements[ 1 ].render = ! this->render_vec_elements[ 1 ].render; updateGL(); } break; case Qt::Key_Right: increase_rendered_element(); updateGL(); break; default: QWidget::keyPressEvent(e); } } ///////////////////////////////////////////////////////////////////////////////////////////////////// //GLWidget::increase_rendered_element ///////////////////////////////////////////////////////////////////////////////////////////////////// void GLWidget::increase_rendered_element(void) { for (size_t k = 0; k < sdm_file->number_vec_elements; k++) { if (this->render_vec_elements[ k ].render) { this->render_vec_elements[ k ].index++; if(this->render_vec_elements[ k ].index >= sdm_file->vec_elements[ k ].size()) { this->render_vec_elements[ k ].index = 0; } size_t current_element = this->render_vec_elements[ k ].index; for (size_t i = 0; i < sdm_file->vec_elements[ k ].size(); i++) { if ( i != current_element ) { sdm_file->vec_elements[ k ].at(i).render = false; } else { sdm_file->vec_elements[ k ].at(i).render = true; } } } } } ///////////////////////////////////////////////////////////////////////////////////////////////////// //GLWidget::mousePressEvent ///////////////////////////////////////////////////////////////////////////////////////////////////// void GLWidget::mousePressEvent(QMouseEvent *e) { last_position = e->pos(); } ///////////////////////////////////////////////////////////////////////////////////////////////////// //GLWidget::mouseMoveEvent ///////////////////////////////////////////////////////////////////////////////////////////////////// void GLWidget::mouseMoveEvent(QMouseEvent *e) { int dx = e->x() - last_position.x(); int dy = e->y() - last_position.y(); if (e->buttons() & Qt::LeftButton) { x_rotation += dy; y_rotation += dx; updateGL(); } else if (e->buttons() & Qt::RightButton) { } last_position = e->pos(); } ///////////////////////////////////////////////////////////////////////////////////////////////////// //GLWidget::render_mesh ///////////////////////////////////////////////////////////////////////////////////////////////////// void GLWidget::render_mesh(void) { for (size_t k = 0; k < sdm_file->number_vec_elements; k++) { if (this->render_vec_elements[ k ].render) { for (size_t i = 0; i < sdm_file->vec_elements[k].size(); i++) { ELEMENT elm = sdm_file->vec_elements[k].at(i); if (elm.render) { std::vector<NODE> vertices(elm.number_nodes); for (size_t j = 0; j < elm.number_nodes; j++) { NODE node = sdm_file->vec_nodes.at(elm.nodes[j] - 1); //node ids are the zero based index vertices[j] = node; } render_element(vertices); } } } } } ///////////////////////////////////////////////////////////////////////////////////////////////////// //render_element ///////////////////////////////////////////////////////////////////////////////////////////////////// void GLWidget::render_ids(const std::vector<NODE> &v) { //render text (enable GL_FILL) glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); for (size_t i = 0; i < v.size(); i++) { char buf[2]; sprintf(buf, "%d", v[i].id); this->renderText(v[i].coord[0], v[i].coord[1], v[i].coord[2], buf); } } ///////////////////////////////////////////////////////////////////////////////////////////////////// //render_element ///////////////////////////////////////////////////////////////////////////////////////////////////// void GLWidget::render_element(const std::vector<NODE> &v) { if ( show_wireframe ) { glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); } else { glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); } ///////////////////////////////////////////////////////////////////////////////////////////////////// //hex08 ///////////////////////////////////////////////////////////////////////////////////////////////////// if ( v.size() == 8) { glColor4f(1.0f, 0.0f, 0.0f, 0.5f); // x, y back glBegin(GL_POLYGON); glVertex3f(v[0].coord[0], v[0].coord[1], v[0].coord[2]); glVertex3f(v[1].coord[0], v[1].coord[1], v[1].coord[2]); glVertex3f(v[2].coord[0], v[2].coord[1], v[2].coord[2]); glVertex3f(v[3].coord[0], v[3].coord[1], v[3].coord[2]); glEnd(); // x, y front glBegin(GL_POLYGON); glVertex3f(v[4].coord[0], v[4].coord[1], v[4].coord[2]); glVertex3f(v[5].coord[0], v[5].coord[1], v[5].coord[2]); glVertex3f(v[6].coord[0], v[6].coord[1], v[6].coord[2]); glVertex3f(v[7].coord[0], v[7].coord[1], v[7].coord[2]); glEnd(); // x, z right glBegin(GL_POLYGON); glVertex3f(v[5].coord[0], v[5].coord[1], v[5].coord[2]); glVertex3f(v[1].coord[0], v[1].coord[1], v[1].coord[2]); glVertex3f(v[2].coord[0], v[2].coord[1], v[2].coord[2]); glVertex3f(v[6].coord[0], v[6].coord[1], v[6].coord[2]); glEnd(); // x, z left glBegin(GL_POLYGON); glVertex3f(v[4].coord[0], v[4].coord[1], v[4].coord[2]); glVertex3f(v[0].coord[0], v[0].coord[1], v[0].coord[2]); glVertex3f(v[3].coord[0], v[3].coord[1], v[3].coord[2]); glVertex3f(v[7].coord[0], v[7].coord[1], v[7].coord[2]); glEnd(); if ( show_ids ) { this->render_ids(v); } } //hex08 ///////////////////////////////////////////////////////////////////////////////////////////////////// //psm06 ///////////////////////////////////////////////////////////////////////////////////////////////////// if ( v.size() == 6) { glColor4f(0.0f, 1.0f, 0.0f, 0.5f); //bottom triangle glBegin(GL_POLYGON); glVertex3f(v[0].coord[0], v[0].coord[1], v[0].coord[2]); glVertex3f(v[1].coord[0], v[1].coord[1], v[1].coord[2]); glVertex3f(v[2].coord[0], v[2].coord[1], v[2].coord[2]); glEnd(); //top triangle glBegin(GL_POLYGON); glVertex3f(v[3].coord[0], v[3].coord[1], v[3].coord[2]); glVertex3f(v[4].coord[0], v[4].coord[1], v[4].coord[2]); glVertex3f(v[5].coord[0], v[5].coord[1], v[5].coord[2]); glEnd(); //face glBegin(GL_POLYGON); glVertex3f(v[5].coord[0], v[5].coord[1], v[5].coord[2]); glVertex3f(v[4].coord[0], v[4].coord[1], v[4].coord[2]); glVertex3f(v[1].coord[0], v[1].coord[1], v[1].coord[2]); glVertex3f(v[2].coord[0], v[2].coord[1], v[2].coord[2]); glEnd(); //face glBegin(GL_POLYGON); glVertex3f(v[5].coord[0], v[5].coord[1], v[5].coord[2]); glVertex3f(v[3].coord[0], v[3].coord[1], v[3].coord[2]); glVertex3f(v[0].coord[0], v[0].coord[1], v[0].coord[2]); glVertex3f(v[2].coord[0], v[2].coord[1], v[2].coord[2]); glEnd(); if ( show_ids ) { this->render_ids(v); } } //psm06 }
// Copyright (c) 2018 The Eozi Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <crypto/siphash.h> #include <random.h> #include <util/bytevectorhash.h> ByteVectorHash::ByteVectorHash() { GetRandBytes(reinterpret_cast<unsigned char*>(&m_k0), sizeof(m_k0)); GetRandBytes(reinterpret_cast<unsigned char*>(&m_k1), sizeof(m_k1)); } size_t ByteVectorHash::operator()(const std::vector<unsigned char>& input) const { return CSipHasher(m_k0, m_k1).Write(input.data(), input.size()).Finalize(); }
// ====================================================================== // \title AssertFatalAdapterImpl.hpp // \author tcanham // \brief hpp file for AssertFatalAdapter component implementation class // // \copyright // Copyright 2009-2015, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #ifndef AssertFatalAdapter_HPP #define AssertFatalAdapter_HPP #include "Svc/AssertFatalAdapter/AssertFatalAdapterComponentAc.hpp" namespace Svc { class AssertFatalAdapterComponentImpl : public AssertFatalAdapterComponentBase { public: // ---------------------------------------------------------------------- // Construction, initialization, and destruction // ---------------------------------------------------------------------- //! Construct object AssertFatalAdapter //! AssertFatalAdapterComponentImpl( #if FW_OBJECT_NAMES == 1 const char *const compName /*!< The component name*/ #else void #endif ); //! Initialize object AssertFatalAdapter //! void init( const NATIVE_INT_TYPE instance = 0 /*!< The instance number*/ ); //! Destroy object AssertFatalAdapter //! ~AssertFatalAdapterComponentImpl(void); //! Report the assert as a FATAL void reportAssert( FILE_NAME_ARG file, NATIVE_UINT_TYPE lineNo, NATIVE_UINT_TYPE numArgs, AssertArg arg1, AssertArg arg2, AssertArg arg3, AssertArg arg4, AssertArg arg5, AssertArg arg6 ); private: class AssertFatalAdapter : public Fw::AssertHook { public: AssertFatalAdapter(); ~AssertFatalAdapter(); void regAssertReporter(AssertFatalAdapterComponentImpl* compPtr); private: void reportAssert( FILE_NAME_ARG file, NATIVE_UINT_TYPE lineNo, NATIVE_UINT_TYPE numArgs, AssertArg arg1, AssertArg arg2, AssertArg arg3, AssertArg arg4, AssertArg arg5, AssertArg arg6 ); // Prevent actual assert since FATAL handler will deal with it void doAssert(void); AssertFatalAdapterComponentImpl* m_compPtr; }; AssertFatalAdapter m_adapter; }; } // end namespace Svc #endif
/** * Copyright (C) 2016-2019 Xilinx, Inc * * 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://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. */ /** * Copyright (C) 2015 Xilinx, Inc */ #include "shim.h" #include "system_swemu.h" #include "xclbin.h" #include <errno.h> #include <unistd.h> namespace { static auto get_mem_topology(const axlf* top) { if (auto sec = xclbin::get_axlf_section(top, ASK_GROUP_TOPOLOGY)) return sec; return xclbin::get_axlf_section(top, MEM_TOPOLOGY); } } namespace xclcpuemhal2 { std::map<unsigned int, CpuemShim*> devices; unsigned int CpuemShim::mBufferCount = 0; std::map<int, std::tuple<std::string,int,void*> > CpuemShim::mFdToFileNameMap; bool CpuemShim::mFirstBinary = true; const unsigned CpuemShim::TAG = 0X586C0C6C; // XL OpenCL X->58(ASCII), L->6C(ASCII), O->0 C->C L->6C(ASCII); const unsigned CpuemShim::CONTROL_AP_START = 1; const unsigned CpuemShim::CONTROL_AP_DONE = 2; const unsigned CpuemShim::CONTROL_AP_IDLE = 4; const unsigned CpuemShim::CONTROL_AP_CONTINUE = 0x10; std::map<std::string, std::string> CpuemShim::mEnvironmentNameValueMap(xclemulation::getEnvironmentByReadingIni()); #define PRINTENDFUNC if (mLogStream.is_open()) mLogStream << __func__ << " ended " << std::endl; CpuemShim::CpuemShim(unsigned int deviceIndex, xclDeviceInfo2 &info, std::list<xclemulation::DDRBank>& DDRBankList, bool _unified, bool _xpr, FeatureRomHeader& fRomHeader) :mTag(TAG) ,mRAMSize(info.mDDRSize) ,mCoalesceThreshold(4) ,mDSAMajorVersion(DSA_MAJOR_VERSION) ,mDSAMinorVersion(DSA_MINOR_VERSION) ,mDeviceIndex(deviceIndex) { binaryCounter = 0; mReqCounter = 0; sock = nullptr; ci_msg.set_size(0); ci_msg.set_xcl_api(0); mCore = nullptr; mSWSch = nullptr; ci_buf = malloc(ci_msg.ByteSize()); ri_msg.set_size(0); ri_buf = malloc(ri_msg.ByteSize()); buf = nullptr; buf_size = 0; deviceName = "device"+std::to_string(deviceIndex); deviceDirectory = xclemulation::getRunDirectory() + "/"+std::to_string(getpid())+"/sw_emu/"+deviceName; simulator_started = false; mVerbosity = XCL_INFO; std::memset(&mDeviceInfo, 0, sizeof(xclDeviceInfo2)); fillDeviceInfo(&mDeviceInfo,&info); initMemoryManager(DDRBankList); std::memset(&mFeatureRom, 0, sizeof(FeatureRomHeader)); std::memcpy(&mFeatureRom, &fRomHeader, sizeof(FeatureRomHeader)); char* pack_size = getenv("SW_EMU_PACKET_SIZE"); if(pack_size) { unsigned int messageSize = strtoll(pack_size,nullptr,0); message_size = messageSize; } else { message_size = 0x800000; } mCloseAll = false; bUnified = _unified; bXPR = _xpr; mIsKdsSwEmu = (xclemulation::is_sw_emulation()) ? xrt_core::config::get_flag_kds_sw_emu() : false; } size_t CpuemShim::alloc_void(size_t new_size) { if (buf_size == 0) { buf = malloc(new_size); return new_size; } if (buf_size < new_size) { void *temp = buf; buf = (void*) realloc(buf,new_size); if (!buf) // prevent leak of original buf free(temp); return new_size; } return buf_size; } void CpuemShim::initMemoryManager(std::list<xclemulation::DDRBank>& DDRBankList) { std::list<xclemulation::DDRBank>::iterator start = DDRBankList.begin(); std::list<xclemulation::DDRBank>::iterator end = DDRBankList.end(); uint64_t base = 0; for(;start != end; start++) { const uint64_t bankSize = (*start).ddrSize; mDdrBanks.push_back(*start); //CR 966701: alignment to 4k (instead of mDeviceInfo.mDataAlignment) mDDRMemoryManager.push_back(new xclemulation::MemoryManager(bankSize, base , getpagesize())); base += bankSize; } } //private bool CpuemShim::isGood() const { // TODO: Add sanity check for card state return true; } CpuemShim *CpuemShim::handleCheck(void *handle) { // Sanity checks if (!handle) return 0; if (*(unsigned *)handle != TAG) return 0; if (!((CpuemShim *)handle)->isGood()) { return 0; } return (CpuemShim *)handle; } static void saveDeviceProcessOutputs() { std::map<unsigned int, CpuemShim*>::iterator start = devices.begin(); std::map<unsigned int, CpuemShim*>::iterator end = devices.end(); for(; start != end; start++) { CpuemShim* handle = (*start).second; if(!handle) continue; handle->saveDeviceProcessOutput(); } } static void sigHandler(int sn, siginfo_t *si, void *sc) { switch (sn) { case SIGSEGV: saveDeviceProcessOutputs(); kill(0, SIGSEGV); exit(1); break; case SIGFPE: saveDeviceProcessOutputs(); kill(0, SIGTERM); exit(1); break; case SIGABRT: saveDeviceProcessOutputs(); kill(0, SIGABRT); exit(1); break; case SIGCHLD: // Prevent infinite loop when the emulator dies if (si->si_code != CLD_KILLED && si->si_code != CLD_DUMPED) break; case SIGUSR1: // One of the spawned processes died for some reason, // kill all of the others and exit the host code saveDeviceProcessOutputs(); std::cerr << "Software emulation of compute unit(s) exited unexpectedly" << std::endl; kill(0, SIGTERM); exit(1); break; default: break; } } int CpuemShim::dumpXML(const xclBin* header, std::string& fileLocation) { if (!header) return 0 ; // We didn't dump it, but this isn't an error char* xclbininmemory = reinterpret_cast<char*>(const_cast<xclBin*>(header)) ; char* xmlfile = nullptr ; int xmllength = 0 ; if (memcmp(xclbininmemory, "xclbin0", 8) == 0) { if (mLogStream.is_open()) { mLogStream << __func__ << " unsupported Legacy XCLBIN header " << std::endl; } return -1; //xmlfile = xclbininmemory + (header->m_metadataOffset) ; //xmllength = (int)(header->m_metadataLength); } else if (memcmp(xclbininmemory,"xclbin2",7) == 0) { auto top = reinterpret_cast<const axlf*>(header); if (auto sec = xclbin::get_axlf_section(top,EMBEDDED_METADATA)) { xmlfile = xclbininmemory + sec->m_sectionOffset; xmllength = sec->m_sectionSize; } } else { // This was not a valid xclbin file if (mLogStream.is_open()) { mLogStream << __func__ << " invalid XCLBIN header " << std::endl; } return -1 ; } if (xmlfile == nullptr || xmllength == 0) { // This xclbin file did not contain any XML meta-data if (mLogStream.is_open()) { mLogStream << __func__ << " XCLBIN did not contain meta-data" << std::endl ; } return -1 ; } // First, create the device directory if it doesn't exist systemUtil::makeSystemCall(deviceDirectory, systemUtil::systemOperation::CREATE) ; // Second, create the binary directory if it doesn't exist std::stringstream binaryDirectory ; binaryDirectory << deviceDirectory << "/binary_" << binaryCounter ; std::string binDir = binaryDirectory.str() ; systemUtil::makeSystemCall(binDir, systemUtil::systemOperation::CREATE) ; systemUtil::makeSystemCall(binDir, systemUtil::systemOperation::PERMISSIONS, "777") ; // The XML file will exist in this binary directory fileLocation = binDir + "/xmltmp" ; // Keep appending underscore to the file name until we find // a file that does not exist. bool foundName = false ; while (!foundName) { FILE* fp = fopen(fileLocation.c_str(), "rb") ; if (fp == NULL) { // The file does not exist, so we can use this file location foundName = true ; } else { // The name we've chosen already exists, so append an underscore // and try again fclose(fp) ; fileLocation += "_" ; } } // The file name we've chosen does not exist, so attempt to // open it for writing FILE* fp = fopen(fileLocation.c_str(), "wb") ; if(fp==NULL) { if (mLogStream.is_open()) { mLogStream << __func__ << " failed to create temporary xml file " << std::endl; } return -1; } fwrite(xmlfile,xmllength,1,fp); fflush(fp); fclose(fp); return 0 ; } bool CpuemShim::parseIni(unsigned int& debugPort) { debugPort = xclemulation::config::getInstance()->getServerPort() ; if (debugPort == 0) { return false ; } return true ; } void CpuemShim::launchDeviceProcess(bool debuggable, std::string& binaryDirectory) { std::lock_guard<std::mutex> lk(mProcessLaunchMtx); systemUtil::makeSystemCall(deviceDirectory, systemUtil::systemOperation::CREATE); std::stringstream ss1; ss1<<deviceDirectory<<"/binary_"<<binaryCounter; binaryDirectory = ss1.str(); systemUtil::makeSystemCall(binaryDirectory, systemUtil::systemOperation::CREATE); systemUtil::makeSystemCall(binaryDirectory, systemUtil::systemOperation::PERMISSIONS, "777"); binaryCounter++; if(sock) { return; } struct sigaction s; memset(&s, 0, sizeof(s)); s.sa_flags = SA_SIGINFO; s.sa_sigaction = sigHandler; if (sigaction(SIGSEGV, &s, (struct sigaction *)0) || sigaction(SIGFPE , &s, (struct sigaction *)0) || sigaction(SIGABRT, &s, (struct sigaction *)0) || sigaction(SIGUSR1, &s, (struct sigaction *)0) || sigaction(SIGCHLD, &s, (struct sigaction *)0)) { //debug_print("unable to support all signals"); } // We also need to check the .ini file in order to determine // if the dynamic port on the sdx_server the child process // must connect to was specified unsigned int debugPort = 0 ; bool passPort = parseIni(debugPort) ; std::stringstream portStream ; portStream << debugPort ; // If debuggable, the child process also requires the PID of the parent (us) pid_t parentPid = getpid() ; std::stringstream pidStream ; pidStream << parentPid ; // Spawn off the process to run the stub bool simDontRun = xclemulation::config::getInstance()->isDontRun(); if(!simDontRun) { std::stringstream socket_id; socket_id << deviceName << "_" << binaryCounter << "_" << getpid(); setenv("EMULATION_SOCKETID",socket_id.str().c_str(),true); pid_t pid = fork(); assert(pid >= 0); if (pid == 0) { std::string childProcessPath(""); std::string xilinxInstall(""); //Added the latest ENV to get the install path char *vitisInstallEnvvar = getenv("XILINX_VITIS"); if (vitisInstallEnvvar != NULL) { xilinxInstall = std::string(vitisInstallEnvvar); } char *scoutInstallEnvvar = getenv("XILINX_SCOUT"); if(scoutInstallEnvvar != NULL && xilinxInstall.empty() ){ xilinxInstall = std::string(scoutInstallEnvvar); } char *installEnvvar = getenv("XILINX_SDX"); if (installEnvvar != NULL && xilinxInstall.empty()) { xilinxInstall = std::string(installEnvvar); } else { installEnvvar = getenv("XILINX_OPENCL"); if (installEnvvar != NULL && xilinxInstall.empty()) { xilinxInstall = std::string(installEnvvar); } } char *xilinxVivadoEnvvar = getenv("XILINX_VIVADO"); if(xilinxVivadoEnvvar) { std::string sHlsBinDir = xilinxVivadoEnvvar; std::string sLdLibs(""); std::string DS("/"); std::string sPlatform("lnx64"); char* sLdLib = getenv("LD_LIBRARY_PATH"); if (sLdLib) sLdLibs = std::string(sLdLib) + ":"; sLdLibs += sHlsBinDir + DS + sPlatform + DS + "tools" + DS + "fft_v9_1" + ":"; sLdLibs += sHlsBinDir + DS + sPlatform + DS + "tools" + DS + "fir_v7_0" + ":"; sLdLibs += sHlsBinDir + DS + sPlatform + DS + "tools" + DS + "fpo_v7_0" + ":"; sLdLibs += sHlsBinDir + DS + sPlatform + DS + "tools" + DS + "dds_v6_0" + ":"; sLdLibs += sHlsBinDir + DS + sPlatform + DS + "tools" + DS + "opencv" + ":"; sLdLibs += sHlsBinDir + DS + sPlatform + DS + "lib" + DS + "csim" + ":"; sLdLibs += sHlsBinDir + DS + "lib" + DS + "lnx64.o" + DS + "Default" + DS; setenv("LD_LIBRARY_PATH",sLdLibs.c_str(),true); } if (xilinxInstall.empty()) { std::cerr << "ERROR : [SW-EM 10] Please make sure that the XILINX_VITIS environment variable is set correctly" << std::endl; exit(1); } std::string modelDirectory(""); modelDirectory = xilinxInstall + "/data/emulation/unified/cpu_em/zynqu/model/genericpciemodel"; #if defined(__aarch64__) modelDirectory = xilinxInstall + "/data/emulation/unified/cpu_em/zynqu/model/genericpciemodel"; #elif defined(__arm__) modelDirectory = xilinxInstall + "/data/emulation/unified/cpu_em/zynq/model/genericpciemodel"; #endif FILE *filep; if ((filep = fopen(modelDirectory.c_str(), "r")) != nullptr) { // file exists fclose(filep); } else { //File not found, no memory leak since 'file' == NULL std::cerr << "ERROR : [SW-EM 11] Unable to launch Device process, Please make sure that the XILINX_VITIS environment variable is set correctly" << std::endl; exit(1); } const char* childArgv[6] = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr } ; childArgv[0] = modelDirectory.c_str() ; // If we determined this should be debuggable, pass the proper // arguments to the process if (debuggable) { childArgv[1] = "-debug" ; childArgv[2] = "-ppid" ; childArgv[3] = pidStream.str().c_str() ; if (passPort) { childArgv[4] = "-port" ; childArgv[5] = portStream.str().c_str() ; } } int r = execl(modelDirectory.c_str(), childArgv[0], childArgv[1], childArgv[2], childArgv[3], childArgv[4], childArgv[5], nullptr) ; //fclose (stdout); if(r == -1){std::cerr << "FATAL ERROR : child process did not launch : " << modelDirectory << std::endl; exit(1);} exit(0); } } sock = new unix_socket; } int CpuemShim::xclLoadXclBin(const xclBin *header) { if(mLogStream.is_open()) mLogStream << __func__ << " begin " << std::endl; std::string xmlFile = "" ; int result = dumpXML(header, xmlFile) ; if (result != 0) return result ; // Before we spawn off the child process, we must determine // if the process will be debuggable or not. We get that // by checking to see if there is a DEBUG_DATA section in // the xclbin file. Note, this only works with xclbin2 // files. Also, the GUI can overwrite this by setting an // environment variable bool debuggable = false ; if (getenv("ENABLE_KERNEL_DEBUG") != nullptr && strcmp("true", getenv("ENABLE_KERNEL_DEBUG")) == 0) { char* xclbininmemory = reinterpret_cast<char*>(const_cast<xclBin*>(header)) ; if (!memcmp(xclbininmemory, "xclbin2", 7)) { auto top = reinterpret_cast<const axlf*>(header) ; auto sec = xclbin::get_axlf_section(top, DEBUG_DATA) ; if (sec) { debuggable = true ; } } } std::string binaryDirectory(""); launchDeviceProcess(debuggable,binaryDirectory); if(header) { resetProgram(); if( mFirstBinary ) { mFirstBinary = false; } char *xclbininmemory = reinterpret_cast<char*> (const_cast<xclBin*> (header)); //parse header char *sharedlib = nullptr; int sharedliblength = 0; char* memTopology = nullptr; ssize_t memTopologySize = 0; //check header if (!memcmp(xclbininmemory, "xclbin0", 8)) { if (mLogStream.is_open()) { mLogStream << __func__ << " invalid XCLBIN header " << std::endl; } return -1; } else if (!memcmp(xclbininmemory,"xclbin2",7)) { auto top = reinterpret_cast<const axlf*>(header); if (auto sec = xclbin::get_axlf_section(top,BITSTREAM)) { sharedlib = xclbininmemory + sec->m_sectionOffset; sharedliblength = sec->m_sectionSize; } if (auto sec = get_mem_topology(top)) { memTopologySize = sec->m_sectionSize; memTopology = new char[memTopologySize]; memcpy(memTopology, xclbininmemory + sec->m_sectionOffset, memTopologySize); } } else { if (mLogStream.is_open()) { mLogStream << __func__ << " invalid XCLBIN header " << std::endl; mLogStream << __func__ << " header " << xclbininmemory[0] << xclbininmemory[1] << xclbininmemory[2] << xclbininmemory[3] << xclbininmemory[4] << xclbininmemory[5] << std::endl; } return -1; } //write out shared library to file for consumption with dlopen std::string tempdlopenfilename = binaryDirectory+"/dltmp"; { bool tempfilecreated = false; unsigned int counter = 0; while( !tempfilecreated ) { FILE *fp = fopen(tempdlopenfilename.c_str(),"rb"); if(fp== nullptr) { tempfilecreated = true; } else { fclose(fp); std::stringstream ss; ss << std::hex << counter; tempdlopenfilename+=ss.str(); counter = counter+1; } } FILE *fp = fopen(tempdlopenfilename.c_str(),"wb"); if( !fp ) { if(mLogStream.is_open()) mLogStream << __func__ << " failed to create temporary dlopen file" << std::endl; if(memTopology) { delete []memTopology; memTopology = NULL; } return -1; } fwrite(sharedlib,sharedliblength,1,fp); fflush(fp); fclose(fp); } if(memTopology) { const mem_topology* m_mem = (reinterpret_cast<const ::mem_topology*>(memTopology)); if(m_mem) { uint64_t argNum = 0; uint64_t prev_instanceBaseAddr = ULLONG_MAX; std::map<uint64_t, std::pair<uint64_t,std::string> > argFlowIdMap; for (int32_t i=0; i<m_mem->m_count; ++i) { uint64_t flow_id =m_mem->m_mem_data[i].flow_id;//base address + flow_id combo uint64_t instanceBaseAddr = 0xFFFF0000 & flow_id; if(prev_instanceBaseAddr != ULLONG_MAX && instanceBaseAddr != prev_instanceBaseAddr) { //RPC CALL bool success = false; xclSetupInstance_RPC_CALL(xclSetupInstance, prev_instanceBaseAddr , argFlowIdMap); if(mLogStream.is_open()) mLogStream << __func__ << " setup instance: " << prev_instanceBaseAddr <<" success "<< success << std::endl; argFlowIdMap.clear(); argNum = 0; } if(m_mem->m_mem_data[i].m_type == MEM_TYPE::MEM_STREAMING) { std::string m_tag (reinterpret_cast<const char*>(m_mem->m_mem_data[i].m_tag)); std::pair<uint64_t,std::string> mPair; mPair.first = flow_id; mPair.second = m_tag; argFlowIdMap[argNum] = mPair; } argNum++; prev_instanceBaseAddr = instanceBaseAddr; } bool success = false; xclSetupInstance_RPC_CALL(xclSetupInstance, prev_instanceBaseAddr, argFlowIdMap); if(mLogStream.is_open()) mLogStream << __func__ << " setup instance: " << prev_instanceBaseAddr <<" success "<< success << std::endl; } delete []memTopology; memTopology = NULL; } if (mIsKdsSwEmu) { mCore = new exec_core; mSWSch = new SWScheduler(this); mSWSch->init_scheduler_thread(); } bool ack = true; bool verbose = false; if(mLogStream.is_open()) verbose = true; xclLoadBitstream_RPC_CALL(xclLoadBitstream,xmlFile,tempdlopenfilename,deviceDirectory,binaryDirectory,verbose); if(!ack) return -1; } return 0; } int CpuemShim::xclGetDeviceInfo2(xclDeviceInfo2 *info) { std::memset(info, 0, sizeof(xclDeviceInfo2)); fillDeviceInfo(info,&mDeviceInfo); for (auto i : mDDRMemoryManager) { info->mDDRFreeSize += i->freeSize(); } return 0; } void CpuemShim::launchTempProcess() { std::string binaryDirectory(""); launchDeviceProcess(false,binaryDirectory); std::string xmlFile(""); std::string tempdlopenfilename(""); SHIM_UNUSED bool ack = true; bool verbose = false; if(mLogStream.is_open()) verbose = true; xclLoadBitstream_RPC_CALL(xclLoadBitstream,xmlFile,tempdlopenfilename,deviceDirectory,binaryDirectory,verbose); } uint64_t CpuemShim::xclAllocDeviceBuffer(size_t size) { size_t requestedSize = size; if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << size << std::endl; } if(!sock) { launchTempProcess(); } if (size == 0) size = DDR_BUFFER_ALIGNMENT; uint64_t result = xclemulation::MemoryManager::mNull; for (auto i : mDDRMemoryManager) { result = i->alloc(size); if (result != xclemulation::MemoryManager::mNull) break; } bool ack = false; // Memory Manager Has allocated aligned address, // size contains alignement + original size requested. // We are passing original size to device process for exact stats. bool noHostMemory = false; std::string sFileName(""); xclAllocDeviceBuffer_RPC_CALL(xclAllocDeviceBuffer,result,requestedSize,noHostMemory); if(!ack) { PRINTENDFUNC; return 0; } PRINTENDFUNC; return result; } uint64_t CpuemShim::xclAllocDeviceBuffer2(size_t& size, xclMemoryDomains domain, unsigned flags,bool noHostMemory,std::string &sFileName) { if (mLogStream.is_open()) { mLogStream << __func__ <<" , "<<std::this_thread::get_id() << ", " << size <<", "<<domain<<", "<< flags <<std::endl; } if(!sock) { launchTempProcess(); } //flags = flags % 32; if (domain != XCL_MEM_DEVICE_RAM) { return xclemulation::MemoryManager::mNull; } if (size == 0) size = DDR_BUFFER_ALIGNMENT; if (flags >= mDDRMemoryManager.size()) { return xclemulation::MemoryManager::mNull; } uint64_t result = mDDRMemoryManager[flags]->alloc(size); if (result == xclemulation::MemoryManager::mNull) { auto ddrSize = mDDRMemoryManager[flags]->size(); std::string ddrSizeStr = std::to_string(ddrSize); std::string initMsg = "ERROR: [SW-EM 12] OutOfMemoryError : Requested Global memory size exceeds DDR limit " + ddrSizeStr + " Bytes"; std::cout << initMsg << std::endl; return result; } bool ack = false; // Memory Manager Has allocated aligned address, // size contains alignement + original size requested. // We are passing original size to device process for exact stats. xclAllocDeviceBuffer_RPC_CALL(xclAllocDeviceBuffer,result,size,noHostMemory); if(!ack) { PRINTENDFUNC; return 0; } PRINTENDFUNC; return result; } void CpuemShim::xclFreeDeviceBuffer(uint64_t offset) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << offset << std::endl; } for (auto i : mDDRMemoryManager) { if (offset < i->start() + i->size()) { i->free(offset); } } bool ack = true; if(sock) { xclFreeDeviceBuffer_RPC_CALL(xclFreeDeviceBuffer,offset); } if(!ack) { PRINTENDFUNC; return; } PRINTENDFUNC; return; } size_t CpuemShim::xclWrite(xclAddressSpace space, uint64_t offset, const void *hostBuf, size_t size) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << offset<<", "<<hostBuf<<", "<< size<<std::endl; } if(!sock) return size; if(space != XCL_ADDR_KERNEL_CTRL) { if (mLogStream.is_open()) mLogStream << "xclWrite called with xclAddressSpace != XCL_ADDR_KERNEL_CTRL " << std::endl; return -1; } if(size%4) { if (mLogStream.is_open()) mLogStream << "xclWrite only supports 32-bit writes" << std::endl; return -1; } fflush(stdout); xclWriteAddrKernelCtrl_RPC_CALL(xclWriteAddrKernelCtrl,space,offset,hostBuf,size,kernelArgsInfo); PRINTENDFUNC; return size; } size_t CpuemShim::xclRead(xclAddressSpace space, uint64_t offset, void *hostBuf, size_t size) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << space << ", " << offset << ", " << hostBuf << ", " << size << std::endl; } if(!sock) { PRINTENDFUNC; return size; } if(space != XCL_ADDR_KERNEL_CTRL) { if (mLogStream.is_open()) mLogStream << "xclRead called with xclAddressSpace != XCL_ADDR_KERNEL_CTRL " << std::endl; PRINTENDFUNC; return -1; } if(size!=4) { if (mLogStream.is_open()) mLogStream << "xclRead called with size != 4 " << std::endl; PRINTENDFUNC; return -1; } xclReadAddrKernelCtrl_RPC_CALL(xclReadAddrKernelCtrl,space,offset,hostBuf,size); PRINTENDFUNC; return size; } size_t CpuemShim::xclCopyBufferHost2Device(uint64_t dest, const void *src, size_t size, size_t seek) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << dest << ", " << src << ", " << size << ", " << seek << std::endl; } if(!sock) { launchTempProcess(); } src = (unsigned char*)src + seek; dest += seek; void *handle = this; unsigned int messageSize = get_messagesize(); unsigned int c_size = messageSize; unsigned int processed_bytes = 0; while(processed_bytes < size){ if((size - processed_bytes) < messageSize){ c_size = size - processed_bytes; }else{ c_size = messageSize; } void* c_src = (((unsigned char*)(src)) + processed_bytes); uint64_t c_dest = dest + processed_bytes; #ifndef _WINDOWS uint32_t space =0; xclCopyBufferHost2Device_RPC_CALL(xclCopyBufferHost2Device,handle,c_dest,c_src,c_size,seek,space); #endif processed_bytes += c_size; } return size; } size_t CpuemShim::xclCopyBufferDevice2Host(void *dest, uint64_t src, size_t size, size_t skip) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << dest << ", " << src << ", " << size << ", " << skip << std::endl; } dest = ((unsigned char*)dest) + skip; if(!sock) { launchTempProcess(); } src += skip; void *handle = this; unsigned int messageSize = get_messagesize(); unsigned int c_size = messageSize; unsigned int processed_bytes = 0; while(processed_bytes < size){ if((size - processed_bytes) < messageSize){ c_size = size - processed_bytes; }else{ c_size = messageSize; } void* c_dest = (((unsigned char*)(dest)) + processed_bytes); uint64_t c_src = src + processed_bytes; #ifndef _WINDOWS uint32_t space =0; xclCopyBufferDevice2Host_RPC_CALL(xclCopyBufferDevice2Host,handle,c_dest,c_src,c_size,skip,space); #endif processed_bytes += c_size; } return size; } void CpuemShim::xclOpen(const char* logfileName) { xclemulation::config::getInstance()->populateEnvironmentSetup(mEnvironmentNameValueMap); std::string logFilePath = (logfileName && (logfileName[0] != '\0')) ? logfileName : xrt_core::config::get_hal_logging(); if (!logFilePath.empty()) { mLogStream.open(logFilePath); mLogStream << "FUNCTION, THREAD ID, ARG..." << std::endl; mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } // Shim object creation doesn't follow xclOpen/xclClose. // The core device must correspond to open and close, so // create here rather than in constructor mCoreDevice = xrt_core::swemu::get_userpf_device(this, mDeviceIndex); } void CpuemShim::fillDeviceInfo(xclDeviceInfo2* dest, xclDeviceInfo2* src) { std::strcpy(dest->mName, src->mName); dest->mMagic = src->mMagic ; dest->mHALMajorVersion = src->mHALMajorVersion; dest->mHALMinorVersion = src->mHALMinorVersion; dest->mVendorId = src->mVendorId; dest->mDeviceId = src->mDeviceId; dest->mSubsystemVendorId = src->mSubsystemVendorId; dest->mDeviceVersion = src->mDeviceVersion; dest->mDDRSize = src->mDDRSize; dest->mDataAlignment = src->mDataAlignment; dest->mDDRBankCount = src->mDDRBankCount; for(unsigned int i = 0; i < 4 ;i++) dest->mOCLFrequency[i] = src->mOCLFrequency[i]; } void CpuemShim::saveDeviceProcessOutput() { if(!sock) return; for(int i = binaryCounter-1; i >= 0; i--) { std::stringstream sw_emu_folder; sw_emu_folder <<deviceDirectory<<"/binary_"<<i; char path[FILENAME_MAX]; size_t size = PATH_MAX; char* pPath = GetCurrentDir(path,size); if(pPath) { std::string debugFilePath = sw_emu_folder.str()+"/genericpcieoutput"; std::string destPath = std::string(path) + "/genericpcieoutput_device"+ std::to_string(mDeviceIndex) + "_"+std::to_string(i); systemUtil::makeSystemCall(debugFilePath, systemUtil::systemOperation::COPY,destPath); } } } void CpuemShim::resetProgram(bool callingFromClose) { for (auto& it: mFdToFileNameMap) { int fd=it.first; int sSize = std::get<1>(it.second); void* addr = std::get<2>(it.second); munmap(addr,sSize); close(fd); } mFdToFileNameMap.clear(); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } if (!sock) { PRINTENDFUNC if (mIsKdsSwEmu && mSWSch && mCore) { mSWSch->fini_scheduler_thread(); delete mCore; mCore = nullptr; delete mSWSch; mSWSch = nullptr; } return; } std::string socketName = sock->get_name(); if(socketName.empty() == false)// device is active if socketName is non-empty { #ifndef _WINDOWS xclClose_RPC_CALL(xclClose,this); #endif } saveDeviceProcessOutput(); } void CpuemShim::xclClose() { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } // Shim object is not deleted as part of closing device. // The core device must correspond to open and close, so // reset here rather than in destructor mCoreDevice.reset(); if(!sock) { if( xclemulation::config::getInstance()->isKeepRunDirEnabled() == false) systemUtil::makeSystemCall(deviceDirectory, systemUtil::systemOperation::REMOVE); if (mIsKdsSwEmu && mSWSch && mCore) { mSWSch->fini_scheduler_thread(); delete mCore; mCore = nullptr; delete mSWSch; mSWSch = nullptr; } return; } for (auto& it: mFdToFileNameMap) { int fd=it.first; int sSize = std::get<1>(it.second); void* addr = std::get<2>(it.second); munmap(addr,sSize); close(fd); } mFdToFileNameMap.clear(); mCloseAll = true; std::string socketName = sock->get_name(); if(socketName.empty() == false)// device is active if socketName is non-empty { #ifndef _WINDOWS xclClose_RPC_CALL(xclClose,this); #endif } mCloseAll = false; int status = 0; bool simDontRun = xclemulation::config::getInstance()->isDontRun(); if(!simDontRun) while (-1 == waitpid(0, &status, 0)); systemUtil::makeSystemCall(socketName, systemUtil::systemOperation::REMOVE); delete sock; sock = nullptr; PRINTENDFUNC; if (mIsKdsSwEmu && mSWSch && mCore) { mSWSch->fini_scheduler_thread(); delete mCore; mCore = nullptr; delete mSWSch; mSWSch = nullptr; } //clean up directories which are created inside the driver if( xclemulation::config::getInstance()->isKeepRunDirEnabled() == false) { //TODO sleeping for some time sothat gdb releases the process and its contents sleep(5); systemUtil::makeSystemCall(deviceDirectory, systemUtil::systemOperation::REMOVE); } google::protobuf::ShutdownProtobufLibrary(); } CpuemShim::~CpuemShim() { if (mIsKdsSwEmu && mSWSch && mCore) { mSWSch->fini_scheduler_thread(); delete mCore; mCore = nullptr; delete mSWSch; mSWSch = nullptr; } if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } free(ci_buf); free(ri_buf); free(buf); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; mLogStream.close(); } if (mLogStream.is_open()) { mLogStream.close(); } } /**********************************************HAL2 API's START HERE **********************************************/ /*********************************** Utility ******************************************/ xclemulation::drm_xocl_bo* CpuemShim::xclGetBoByHandle(unsigned int boHandle) { auto it = mXoclObjMap.find(boHandle); if(it == mXoclObjMap.end()) return nullptr; xclemulation::drm_xocl_bo* bo = (*it).second; return bo; } inline unsigned short CpuemShim::xocl_ddr_channel_count() { return mDeviceInfo.mDDRBankCount; } inline unsigned long long CpuemShim::xocl_ddr_channel_size() { return 0; } int CpuemShim::xclGetBOProperties(unsigned int boHandle, xclBOProperties *properties) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << boHandle << std::endl; } xclemulation::drm_xocl_bo* bo = xclGetBoByHandle(boHandle); if (!bo) { PRINTENDFUNC; return -1; } properties->handle = bo->handle; properties->flags = bo->flags; properties->size = bo->size; properties->paddr = bo->base; PRINTENDFUNC; return 0; } /*****************************************************************************************/ /******************************** xclAllocBO *********************************************/ uint64_t CpuemShim::xoclCreateBo(xclemulation::xocl_create_bo* info) { size_t size = info->size; unsigned ddr = xclemulation::xocl_bo_ddr_idx(info->flags); if (!size) return -1; // system linker doesnt run in sw_emu. if ddr idx morethan ddr_count, then create it in 0 by considering all plrams in zero'th ddr const unsigned ddr_count = xocl_ddr_channel_count(); if(ddr_count <= ddr) { ddr = 0; } //struct xclemulation::drm_xocl_bo *xobj = new xclemulation::drm_xocl_bo; auto xobj = std::make_unique<xclemulation::drm_xocl_bo>(); xobj->flags=info->flags; /* check whether buffer is p2p or not*/ bool noHostMemory = xclemulation::no_host_memory(xobj.get()) || xclemulation::xocl_bo_host_only(xobj.get()); std::string sFileName(""); xobj->base = xclAllocDeviceBuffer2(size,XCL_MEM_DEVICE_RAM,ddr,noHostMemory,sFileName); xobj->filename = sFileName; xobj->size = size; xobj->userptr = nullptr; xobj->buf = nullptr; xobj->fd = -1; if (xobj->base == xclemulation::MemoryManager::mNull) { return xclemulation::MemoryManager::mNull; } info->handle = mBufferCount; mXoclObjMap[mBufferCount++] = xobj.release(); return 0; } unsigned int CpuemShim::xclAllocBO(size_t size, int unused, unsigned flags) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << size << std::dec << " , "<< unused <<" , "<< flags << std::endl; } xclemulation::xocl_create_bo info = {size, mNullBO, flags}; uint64_t result = xoclCreateBo(&info); PRINTENDFUNC; return result ? mNullBO : info.handle; } /***************************************************************************************/ /******************************** xclAllocUserPtrBO ************************************/ unsigned int CpuemShim::xclAllocUserPtrBO(void *userptr, size_t size, unsigned flags) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << userptr <<", " << std::hex << size << std::dec <<" , "<< flags << std::endl; } xclemulation::xocl_create_bo info = {size, mNullBO, flags}; uint64_t result = xoclCreateBo(&info); xclemulation::drm_xocl_bo* bo = xclGetBoByHandle(info.handle); if (bo) { bo->userptr = userptr; } PRINTENDFUNC; return result ? mNullBO : info.handle; } /***************************************************************************************/ /******************************** xclExportBO *******************************************/ int CpuemShim::xclExportBO(unsigned int boHandle) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << boHandle << std::endl; } xclemulation::drm_xocl_bo* bo = xclGetBoByHandle(boHandle); if(!bo) return -1; std::string sFileName = bo->filename; if(sFileName.empty()) { std::cout<<"Exported Buffer is not P2P "<<std::endl; PRINTENDFUNC; return -1; } uint64_t size = bo->size; int fd = open(sFileName.c_str(), (O_CREAT | O_RDWR), 0666); if (fd == -1) { printf("Error opening exported BO file.\n"); PRINTENDFUNC; return -1; }; char* data = (char*) mmap(0, bo->size , PROT_READ |PROT_WRITE |PROT_EXEC , MAP_SHARED, fd, 0); if(!data) { PRINTENDFUNC; return -1; } int fR = ftruncate(fd, bo->size); if(fR == -1) { close(fd); munmap(data,bo->size); return -1; } mFdToFileNameMap [fd] = std::make_tuple(sFileName,size,(void*)data); PRINTENDFUNC; return fd; } /***************************************************************************************/ /******************************** xclImportBO *******************************************/ unsigned int CpuemShim::xclImportBO(int boGlobalHandle, unsigned flags) { //TODO if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << boGlobalHandle << std::endl; } auto itr = mFdToFileNameMap.find(boGlobalHandle); if(itr != mFdToFileNameMap.end()) { const std::string& fileName = std::get<0>((*itr).second); int size = std::get<1>((*itr).second); unsigned int importedBo = xclAllocBO(size, 0,flags); xclemulation::drm_xocl_bo* bo = xclGetBoByHandle(importedBo); if(!bo) { std::cout<<"ERROR HERE in importBO "<<std::endl; return -1; } mImportedBOs.insert(importedBo); bo->fd = boGlobalHandle; bool ack; xclImportBO_RPC_CALL(xclImportBO,fileName,bo->base,size); if(!ack) return -1; PRINTENDFUNC; return importedBo; } return -1; } /***************************************************************************************/ /******************************** xclCopyBO *******************************************/ int CpuemShim::xclCopyBO(unsigned int dst_boHandle, unsigned int src_boHandle, size_t size, size_t dst_offset, size_t src_offset) { std::lock_guard<std::mutex> lk(mApiMtx); //TODO if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << dst_boHandle <<" , "<< src_boHandle << " , "<< size <<"," << dst_offset << "," <<src_offset<< std::endl; } xclemulation::drm_xocl_bo* sBO = xclGetBoByHandle(src_boHandle); if(!sBO) { PRINTENDFUNC; return -1; } xclemulation::drm_xocl_bo* dBO = xclGetBoByHandle(dst_boHandle); if(!dBO) { PRINTENDFUNC; return -1; } if(dBO->fd < 0) { std::cout<<"bo is not exported for copying"<<std::endl; return -1; } int ack = false; auto fItr = mFdToFileNameMap.find(dBO->fd); if(fItr != mFdToFileNameMap.end()) { const std::string& sFileName = std::get<0>((*fItr).second); xclCopyBO_RPC_CALL(xclCopyBO,sBO->base,sFileName,size,src_offset,dst_offset); } if(!ack) return -1; PRINTENDFUNC; return 0; } /***************************************************************************************/ /******************************** xclMapBO *********************************************/ void *CpuemShim::xclMapBO(unsigned int boHandle, bool write) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << boHandle << " , " << write << std::endl; } xclemulation::drm_xocl_bo* bo = xclGetBoByHandle(boHandle); if (!bo) { PRINTENDFUNC; return nullptr; } std::string sFileName = bo->filename; if(!sFileName.empty() ) { int fd = open(sFileName.c_str(), (O_CREAT | O_RDWR), 0666); if (fd == -1) { printf("Error opening exported BO file.\n"); return nullptr; }; char* data = (char*) mmap(0, bo->size , PROT_READ |PROT_WRITE |PROT_EXEC , MAP_SHARED, fd, 0); if(!data) return nullptr; int fR = ftruncate(fd, bo->size); if(fR == -1) { close(fd); munmap(data,bo->size); return nullptr; } mFdToFileNameMap [fd] = std::make_tuple(sFileName,bo->size,(void*)data); bo->buf = data; PRINTENDFUNC; return data; } void *pBuf=nullptr; if (posix_memalign(&pBuf, getpagesize(), bo->size)) { if (mLogStream.is_open()) mLogStream << "posix_memalign failed" << std::endl; pBuf=nullptr; } bo->buf = pBuf; PRINTENDFUNC; return pBuf; } int CpuemShim::xclUnmapBO(unsigned int boHandle, void* addr) { std::lock_guard<std::mutex> lk(mApiMtx); auto bo = xclGetBoByHandle(boHandle); return bo ? munmap(addr,bo->size) : -1; } /**************************************************************************************/ /******************************** xclSyncBO *******************************************/ int CpuemShim::xclSyncBO(unsigned int boHandle, xclBOSyncDirection dir, size_t size, size_t offset) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << boHandle << " , " << std::endl; } xclemulation::drm_xocl_bo* bo = xclGetBoByHandle(boHandle); if(!bo) { PRINTENDFUNC; return -1; } int returnVal = 0; if(dir == XCL_BO_SYNC_BO_TO_DEVICE) { void* buffer = bo->userptr ? bo->userptr : bo->buf; if (xclCopyBufferHost2Device(bo->base,buffer, size, offset) != size) { returnVal = EIO; } } else { void* buffer = bo->userptr ? bo->userptr : bo->buf; if (xclCopyBufferDevice2Host(buffer, bo->base, size, offset) != size) { returnVal = EIO; } } PRINTENDFUNC; return returnVal; } /***************************************************************************************/ /******************************** xclFreeBO *******************************************/ void CpuemShim::xclFreeBO(unsigned int boHandle) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << boHandle << std::endl; } auto it = mXoclObjMap.find(boHandle); if(it == mXoclObjMap.end()) { PRINTENDFUNC; return; } xclemulation::drm_xocl_bo* bo = (*it).second;; if(bo) { xclFreeDeviceBuffer(bo->base); mXoclObjMap.erase(it); } PRINTENDFUNC; } /***************************************************************************************/ /******************************** xclWriteBO *******************************************/ size_t CpuemShim::xclWriteBO(unsigned int boHandle, const void *src, size_t size, size_t seek) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << boHandle << " , "<< src <<" , "<< size << ", " << seek << std::endl; } xclemulation::drm_xocl_bo* bo = xclGetBoByHandle(boHandle); if(!bo) { PRINTENDFUNC; return -1; } size_t returnVal = 0; if (xclCopyBufferHost2Device(bo->base, src, size, seek) != size) { returnVal = EIO; } PRINTENDFUNC; return returnVal; } /***************************************************************************************/ /******************************** xclReadBO *******************************************/ size_t CpuemShim::xclReadBO(unsigned int boHandle, void *dst, size_t size, size_t skip) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << boHandle << " , "<< dst <<" , "<< size << ", " << skip << std::endl; } xclemulation::drm_xocl_bo* bo = xclGetBoByHandle(boHandle); if(!bo) { PRINTENDFUNC; return -1; } size_t returnVal = 0; if (xclCopyBufferDevice2Host(dst, bo->base, size, skip) != size) { returnVal = EIO; } PRINTENDFUNC; return returnVal; } /***************************************************************************************/ /********************************************** QDMA APIs IMPLEMENTATION START **********************************************/ /* * xclCreateWriteQueue() */ int CpuemShim::xclCreateWriteQueue(xclQueueContext *q_ctx, uint64_t *q_hdl) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; uint64_t q_handle = 0; xclCreateQueue_RPC_CALL(xclCreateQueue,q_ctx,true); if(q_handle <= 0) { if (mLogStream.is_open()) mLogStream << " unable to create write queue "<<std::endl; PRINTENDFUNC; return -1; } *q_hdl = q_handle; PRINTENDFUNC; return 0; } /* * xclCreateReadQueue() */ int CpuemShim::xclCreateReadQueue(xclQueueContext *q_ctx, uint64_t *q_hdl) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } uint64_t q_handle = 0; xclCreateQueue_RPC_CALL(xclCreateQueue,q_ctx,false); if(q_handle <= 0) { if (mLogStream.is_open()) mLogStream << " unable to create read queue "<<std::endl; PRINTENDFUNC; return -1; } *q_hdl = q_handle; PRINTENDFUNC; return 0; } /* * xclDestroyQueue() */ int CpuemShim::xclDestroyQueue(uint64_t q_hdl) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } uint64_t q_handle = q_hdl; bool success = false; xclDestroyQueue_RPC_CALL(xclDestroyQueue, q_handle); if(!success) { if (mLogStream.is_open()) mLogStream <<" unable to destroy the queue"<<std::endl; PRINTENDFUNC; return -1; } PRINTENDFUNC; return 0; } /* * xclWriteQueue() */ ssize_t CpuemShim::xclWriteQueue(uint64_t q_hdl, xclQueueRequest *wr) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } bool eot = false; if(wr->flag & XCL_QUEUE_REQ_EOT) eot = true; bool nonBlocking = false; if (wr->flag & XCL_QUEUE_REQ_NONBLOCKING) { std::map<uint64_t,uint64_t> vaLenMap; for (unsigned i = 0; i < wr->buf_num; i++) { vaLenMap[wr->bufs[i].va] = wr->bufs[i].len; } mReqList.push_back(std::make_tuple(mReqCounter, wr->priv_data, vaLenMap)); nonBlocking = true; } uint64_t fullSize = 0; for (unsigned i = 0; i < wr->buf_num; i++) { xclWriteQueue_RPC_CALL(xclWriteQueue,q_hdl, wr->bufs[i].va, wr->bufs[i].len); fullSize += written_size; } PRINTENDFUNC; mReqCounter++; return fullSize; } /* * xclReadQueue() */ ssize_t CpuemShim::xclReadQueue(uint64_t q_hdl, xclQueueRequest *rd) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } bool eot = false; if(rd->flag & XCL_QUEUE_REQ_EOT) eot = true; bool nonBlocking = false; if (rd->flag & XCL_QUEUE_REQ_NONBLOCKING) { nonBlocking = true; std::map<uint64_t,uint64_t> vaLenMap; for (unsigned i = 0; i < rd->buf_num; i++) { vaLenMap[rd->bufs[i].va] = rd->bufs[i].len; } mReqList.push_back(std::make_tuple(mReqCounter,rd->priv_data, vaLenMap)); } void *dest; uint64_t fullSize = 0; for (unsigned i = 0; i < rd->buf_num; i++) { dest = (void *)rd->bufs[i].va; uint64_t read_size = 0; do { xclReadQueue_RPC_CALL(xclReadQueue,q_hdl, dest , rd->bufs[i].len); } while (read_size == 0 && !nonBlocking); fullSize += read_size; } mReqCounter++; PRINTENDFUNC; return fullSize; } /* * xclPollCompletion */ int CpuemShim::xclPollCompletion(int min_compl, int max_compl, xclReqCompletion *comps, int* actual, int timeout) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << " , "<< max_compl <<", "<<min_compl<<" ," << *actual <<" ," << timeout << std::endl; } // struct timespec time, *ptime = NULL; // // if (timeout > 0) // { // memset(&time, 0, sizeof(time)); // time.tv_sec = timeout / 1000; // time.tv_nsec = (timeout % 1000) * 1000000; // ptime = &time; // } *actual = 0; while(*actual < min_compl) { std::list<std::tuple<uint64_t ,void*, std::map<uint64_t,uint64_t> > >::iterator it = mReqList.begin(); while ( it != mReqList.end() ) { unsigned numBytesProcessed = 0; uint64_t reqCounter = std::get<0>(*it); void* priv_data = std::get<1>(*it); std::map<uint64_t,uint64_t>vaLenMap = std::get<2>(*it); xclPollCompletion_RPC_CALL(xclPollCompletion,reqCounter,vaLenMap); if(numBytesProcessed > 0) { comps[*actual].priv_data = priv_data; comps[*actual].nbytes = numBytesProcessed; (*actual)++; mReqList.erase(it++); } else { it++; } } } PRINTENDFUNC; return (*actual); } /* * xclAllocQDMABuf() */ void * CpuemShim::xclAllocQDMABuf(size_t size, uint64_t *buf_hdl) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } void *pBuf=nullptr; if (posix_memalign(&pBuf, sizeof(double)*16, size)) { if (mLogStream.is_open()) mLogStream << "posix_memalign failed" << std::endl; pBuf=nullptr; return pBuf; } memset(pBuf, 0, size); PRINTENDFUNC; return pBuf; } /* * xclFreeQDMABuf() */ int CpuemShim::xclFreeQDMABuf(uint64_t buf_hdl) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } PRINTENDFUNC; return 0;//TODO } /* * xclLogMsg() */ int CpuemShim::xclLogMsg(xclDeviceHandle handle, xrtLogMsgLevel level, const char* tag, const char* format, va_list args1) { int len = std::vsnprintf(nullptr, 0, format, args1); if (len < 0) { //illegal arguments std::string err_str = "ERROR: Illegal arguments in log format string. "; err_str.append(std::string(format)); xrt_core::message::send((xrt_core::message::severity_level)level, tag, err_str.c_str()); return len; } len++; //To include null terminator std::vector<char> buf(len); len = std::vsnprintf(buf.data(), len, format, args1); if (len < 0) { //error processing arguments std::string err_str = "ERROR: When processing arguments in log format string. "; err_str.append(std::string(format)); xrt_core::message::send((xrt_core::message::severity_level)level, tag, err_str.c_str()); return len; } xrt_core::message::send((xrt_core::message::severity_level)level, tag, buf.data()); return 0; } /* * xclOpenContext */ int CpuemShim::xclOpenContext(const uuid_t xclbinId, unsigned int ipIndex, bool shared) const { return 0; } /* * xclExecWait */ int CpuemShim::xclExecWait(int timeoutMilliSec) { //unsigned int tSec = 0; //static bool bConfig = true; //tSec = timeoutMilliSec / 1000; //if (bConfig) //{ // tSec = timeoutMilliSec / 1000; // bConfig = false; //} //sleep(tSec); //PRINTENDFUNC; return 1; } /* * xclExecBuf */ int CpuemShim::xclExecBuf(unsigned int cmdBO) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << cmdBO << std::endl; } if (!mIsKdsSwEmu) return 0; xclemulation::drm_xocl_bo* bo = xclGetBoByHandle(cmdBO); if (!mSWSch || !bo) { PRINTENDFUNC; return -1; } int ret = mSWSch->add_exec_buffer(mCore, bo); PRINTENDFUNC; return ret; } /* * xclCloseContext */ int CpuemShim::xclCloseContext(const uuid_t xclbinId, unsigned int ipIndex) const { return 0; } /********************************************** QDMA APIs IMPLEMENTATION END**********************************************/ /**********************************************HAL2 API's END HERE **********************************************/ }
//+-------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1998. // // File: tstparam.hxx // // Synopsys: Test paramers container class definitions // // Classes: CTestParams, CParamNode // // Notes: The test parameter containers provide a layer of abstraction // above the particular ways to pass test parameters - // (command line, environment, registry...) // // History: 10-Sep-1998 georgis created // //--------------------------------------------------------------------------- #ifndef __TSTPARAM_HXX__ #define __TSTPARAM_HXX__ // Maximum registry string value length #define MAX_REGSTRLEN _MAX_PATH //+-------------------------------------------------------------------------- // // Macros: GETPARAM // // Synopsys: Get parameter from the default container // // Parameters: param: the parameter definition string // var: the variable which receives the result // // Notes: The parameter definition string must be in format "name:format" // where name is the name which identifies the parameter and // format shows how to read this parameter. // E.g. "my_int:%i" // // Formats may be of two types: // 1) Any standard sscanf formats starting with % // E.g. %i %u %d %lx %s ... // // 2) Custom formats // bool - read BOOL (*pTarget is BOOL) // cstr - read constant string (*pTarget is const char*) // astr - heap allocated ascii string (*pTarget is char*) // tstr - heap allocated TCHAR string (*pTarget is LPTSTR) // olestr - heap allocated OLESTR string (*pTarget is LPOLESTR) // // For the heap allocated formats the string obtained is writable, // and the caller is responsible for deleting it. // // History: 02-Oct-1998 georgis Created // //+-------------------------------------------------------------------------- #define GETPARAM(param,var) \ g_TestParams.GetParam(param,&var) //+-------------------------------------------------------------------------- // // Macros: GETPARAM_ABORTONERROR // // Synopsys: Get parameter from the default container // and abort on error // // Parameters: param: the parameter definition string // var: the variable which receives the result // // History: 20-Oct-1998 georgis Created // //+-------------------------------------------------------------------------- #define GETPARAM_ABORTONERROR(param,var) \ hr=g_TestParams.GetParam(param,&var); \ if (S_FALSE!=hr) \ { \ DH_HRCHECK_ABORT(hr,TEXT(param)); \ } \ hr=S_OK; //+-------------------------------------------------------------------------- // // Macros: GETPARAM_DEFINE // // Synopsys: Expands to definition of local variable, and // initialization by the parameter value or the default // // Parameters: type: the variable type // var: the variable which receives the result // param: the parameter definition string // defaultval: the defauilt value // // History: 02-Oct-1998 georgis Created // //+-------------------------------------------------------------------------- #define GETPARAM_DEFINE(type,var,param,defaultval) \ type var=defaultval; \ g_TestParams.GetParam(param,&var) //+-------------------------------------------------------------------------- // // Macros: GETPARAM_REQUIRED // // Synopsys: As GETPARAM, but aborts the current function on failure to // obtain the parameter (see DH_*ABORT macros) // // Parameters: param: the parameter definition string // var: the variable which receives the result // // History: 02-Oct-1998 georgis Created // //+-------------------------------------------------------------------------- #define GETPARAM_REQUIRED(param,var) \ hr=g_TestParams.GetParam(param,&var); \ DH_HRCHECK_ABORT(hr,TEXT(param)); //+-------------------------------------------------------------------------- // // Macros: GETPARAM_ENUM // // Synopsys: Gets the value of a parameter as enum (DWORD) // // Example: GETPARAM_ENUM( // "mode", // &dwMode, // "rw", STGM_READWRITE, // "r", STGM_READ, // "w", STGM_WRITE, // NULL); // // if e.g. there is command line switch /mode:r // the dwMode will be set to STGM_READ // // History: 02-Oct-1998 georgis Created // //+-------------------------------------------------------------------------- #define GETPARAM_ENUM g_TestParams.GetEnum //+-------------------------------------------------------------------------- // // Macros: GETPARAM_RANGE // // Synopsys: Gets the value of a parameter as range (min, max) // // Example: GETPARAM_RANGE("streamsize",ullMin,ullMax); // // Notes: The min and max can be ULONG or ULONGLONG // // History: 02-Oct-1998 georgis Created // //+-------------------------------------------------------------------------- #define GETPARAM_RANGE(param,min,max) \ g_TestParams.GetRange(param,&min,&max); //+-------------------------------------------------------------------------- // // Macros: GETPARAM_ISPRESENT // // Synopsys: Returns TRUE is the parameter is present in // the default container // // Parameters: param: the parameter definition string // // History: 02-Oct-1998 georgis Created // //+-------------------------------------------------------------------------- #define GETPARAM_ISPRESENT(param) \ g_TestParams.IsPresent(param) //+-------------------------------------------------------------------------- // // Macros: SETPARAM // // Synopsys: Set param in the global container (see SetParam method) // // History: 02-Oct-1998 georgis Created // //+-------------------------------------------------------------------------- #define SETPARAM g_TestParams.SetParam // Custom parameter types: #define PARAMFMT_BOOL L"bool" #define PARAMFMT_CSTR L"cstr" #define PARAMFMT_ASTR L"astr" #define PARAMFMT_TSTR L"tstr" #define PARAMFMT_OLESTR L"olestr" // Flags: Each parameter in CTestParams have name,value and flags (DWORD) #define PARAMMASK_PRIORITY 0x000000ff // The priority of the parameter #define PARAMMASK_SOURCE 0x0000ff00 // From where this param was read #define PARAMMASK_USAGE 0x00ff0000 // Who used this parameter #define PARAMMASK_OPTIONS 0xff000000 // Misc flags #define PARAMMASK_ALL 0xffffffff // Default priorities #define PARAMPRIORITY_RUNTIME 0x00000080 // Set using SetParam #define PARAMPRIORITY_CMDLINE 0x00000040 #define PARAMPRIORITY_ENVIRON 0x00000020 #define PARAMPRIORITY_REGISTRY 0x00000010 // Basic parameter sources #define PARAMSOURCE_RUNTIME 0x00008000 #define PARAMSOURCE_CMDLINE 0x00004000 #define PARAMSOURCE_ENVIRON 0x00002000 #define PARAMSOURCE_REGISTRY 0x00001000 #define PARAMSOURCE_ANY PARAMMASK_SOURCE // Parameter usage markers (Who used the parameter) #define PARAMUSAGE_GENERAL 0x00010000 // During initialization #define PARAMUSAGE_TESTCASE 0x00020000 // the current testcase #define PARAMUSAGE_DFLREPRO 0x000f0000 // what to include in repro by default #define PARAMUSAGE_TESTDRIVER 0x00100000 // exclude from single testcase repro #define PARAMUSAGE_SELECTOR_G 0x00200000 // reserved for global CSelector object #define PARAMUSAGE_SELECTOR_L 0x00400000 // reserved for local CSelector objects // General options #define PARAMFLAG_MUSTSET 0x01000000 // fail if can't override param #define PARAMFLAG_OVERRIDEUSED 0x02000000 // override even if used #define PARAMFLAG_REPROINFO 0x04000000 // e.g. "seed:%x" // Sources masks summary #define PARAMFLAGS_CMDLINE PARAMSOURCE_CMDLINE | PARAMPRIORITY_CMDLINE #define PARAMFLAGS_ENVIRON PARAMSOURCE_ENVIRON | PARAMPRIORITY_ENVIRON #define PARAMFLAGS_REGISTRY PARAMSOURCE_REGISTRY | PARAMPRIORITY_REGISTRY #define PARAMFLAGS_RUNTIME PARAMSOURCE_RUNTIME | PARAMPRIORITY_RUNTIME // Parameters which may be added at runtime (as seed). // They are added from the begining as "used", in the curent scope // and are deleted when the usage is cleared #define PARAMFLAGS_REPROINFO PARAMFLAG_REPROINFO|PARAMFLAG_OVERRIDEUSED| \ PARAMFLAG_MUSTSET|PARAMFLAGS_RUNTIME // Forward definition of the internal class class CParamNode; //+-------------------------------------------------------------------------- // // Class: CTestParams // // Synopsys: Test parameter container class. // // Purpose: To provide a level of abstraction above the specific ways // for passing the test parameters (command line, environment, // registry keys ...). // // History: 09-Sep-1998 georgis Created // //--------------------------------------------------------------------------- class CTestParams { public: // Constructor and Destructor CTestParams(); virtual ~CTestParams(); // Info function TRUE if the container is empty inline HRESULT IsEmpty() {return NULL==m_pParamsList;}; // Functions for extracting / adding parameters HRESULT GetParam( const char *pszName, void* pTarget); HRESULT SetParam( const char *pszName, void* pTarget, DWORD dwFlags=PARAMFLAGS_RUNTIME); BOOL __cdecl IsPresent( const char *pszName ,...); HRESULT DeleteParam( const char *ptszName); HRESULT __cdecl GetEnum( const char *pszParamName, DWORD *pdwValue,...); HRESULT GetRange( const char *pszParamName, ULONGLONG *pullMin, ULONGLONG *pullMax); HRESULT GetRange( const char *pszParamName, ULONG *pulMin, ULONG *pulMax); // Functions for handling flags void SetUsage( DWORD dwFlags) {m_dwUsageInfo=dwFlags;}; void ClearUsage( DWORD dwFlags); HRESULT ChangeFlags( DWORD dwOldFlags, DWORD dwNewFlags); // Functions to read from some parameter sources HRESULT ReadCommandLine( LPCTSTR ptszCtommandLine=NULL, DWORD dwFlags=PARAMFLAGS_CMDLINE); HRESULT ReadEnvironment( LPCWSTR pszPrefix=NULL, DWORD dwFlags=PARAMFLAGS_ENVIRON); HRESULT ReadRegistry( HKEY hBaseKey, LPCTSTR ptszKeyName, DWORD dwFlags=PARAMFLAGS_REGISTRY); // Handle the parameter set as whole HRESULT SaveParams( char **ppcBuffer, DWORD *pdwSize, DWORD dwMask=PARAMSOURCE_ANY); HRESULT LoadParams( char *pcBuffer, DWORD dwSize, DWORD dwChangeFlags=0); HRESULT GetReproLine(LPWSTR *ppwszReproLine, DWORD dwFlags); HRESULT GetReproLine(char **ppszReproLine, DWORD dwFlags); protected: virtual HRESULT NotifyOnFirstUse(){return S_OK;}; // use when inherit private: // Custom format params HRESULT SetCustomFmtParam( LPCWSTR pszFormat, LPCWSTR pszValue, void* pTarget, DWORD dwFlags); HRESULT GetCustomFmtParam( LPCWSTR pszName, LPCWSTR pszFormat, void* pTarget); CParamNode* FindParam( LPCWSTR Name, CParamNode** ppPrev); HRESULT AddParam( LPCWSTR pwszName, LPCWSTR pwszValue, DWORD dwFlags, BOOL bWasQuoted=FALSE); CParamNode *m_pParamsList; DWORD m_dwUsageInfo; BOOL m_bUsed; CRITICAL_SECTION m_sync; }; //+-------------------------------------------------------------------------- // // Class: CParamNode (internaly used in CTestParams) // // Synopsys: Single linked list node for one parameter info // // History: 29-Sep-1998 georgis Created // //--------------------------------------------------------------------------- class CParamNode { friend class CTestParams; DWORD m_dwHashValue; DWORD m_dwFlags; // source,priority,usage LPWSTR m_pwszName; LPWSTR m_pwszValue; CParamNode *m_pNext; CParamNode(DWORD dwFlags); ~CParamNode(); HRESULT Init( LPCWSTR pwszName, LPCWSTR pwszValue); HRESULT ChangeValue( LPCWSTR pwszValue, DWORD dwFlags); inline void MarkAsUsed(DWORD dwFlags) // Mark the param as used {m_dwFlags|=PARAMMASK_USAGE & dwFlags;}; inline void ClearUsage(DWORD dwFlags) // Clear given usage flags {m_dwFlags &=~(PARAMMASK_USAGE & dwFlags);}; inline void ChangeFlags(DWORD dwFlags) // Change all except usage {m_dwFlags = (dwFlags & ~PARAMMASK_USAGE)|(PARAMMASK_USAGE & m_dwFlags);}; }; // Utilities functions for converting Unicode strings to/from escaped ascii #define ESCAPE_CHARACTER '#' #define ESCAPED_MARKER ':' #define ESCAPE_NOTNEEDED(x)\ ((' '<=x)&&('~'>=x)) #define ESCAPEMODE_PREFIX_ALWAYS 0 #define ESCAPEMODE_PREFIX_NEVER 1 #define ESCAPEMODE_PREFIX_IFCHANGED 2 #define ESCAPE_MODE_DEFAULT ESCAPEMODE_PREFIX_ALWAYS HRESULT Unicode2Escaped( LPCWSTR pwszString, char ** ppszString, DWORD dwEscapeMode=ESCAPE_MODE_DEFAULT); HRESULT Unicode2Escaped( LPCWSTR pwszString, LPWSTR* ppwszString, DWORD dwEscapeMode=ESCAPE_MODE_DEFAULT); HRESULT Escaped2Unicode( const char * pszEscaped, LPWSTR *ppwszString, DWORD dwEscapeMode=ESCAPE_MODE_DEFAULT); HRESULT Escaped2Unicode( LPCWSTR pszEscaped, LPWSTR *ppwszString, DWORD dwEscapeMode=ESCAPE_MODE_DEFAULT); // CTOLESTG specific // parameters to affect the param handling itself #define PARAMDUMP "paramdump:%lx" // specify to dump on the first Get* #define STG_CMDLINEONLY "cmdonly:bool" // read only from command line // The only way to start using CTestParams in all the exisating suites // without modifications in to read parameters in the object's constructor class CStgParams : public CTestParams { protected: virtual HRESULT NotifyOnFirstUse(); }; extern CStgParams g_TestParams; #endif __TSTPARAM_HXX__
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* swapPairs(ListNode* head) { ListNode* parent = new ListNode(0); parent->next = head; head = parent; while(head) { ListNode *ch1, *ch2; if (head->next != NULL) { ch1 = head->next; if (ch1->next != NULL) ch2 = ch1->next; else break; } else break; ch1->next = ch2->next; ch2->next = ch1; head->next = ch2; head = ch1; } return parent->next; } };
#include "common/runtime/Types.hpp" #include <map> #include <tuple> using map21_t = std::map<std::tuple<types::Integer, types::Char<9>>, types::Numeric<18, 2>>; map21_t& q21_expected(); map21_t& q22_expected(); map21_t& q23_expected(); using map31_t = std::map<std::tuple<types::Char<15>, types::Char<15>, types::Integer>, types::Numeric<18, 2>>; using map32_t = std::map<std::tuple<types::Char<10>, types::Char<10>, types::Integer>, types::Numeric<18, 2>>; map31_t& q31_expected(); map32_t& q32_expected(); map32_t& q33_expected(); map32_t& q34_expected(); using map41_t = std::map<std::tuple<types::Integer, types::Char<15>>, types::Numeric<18, 2>>; using map42_t = std::map<std::tuple<types::Integer, types::Char<15>, types::Char<7>>, types::Numeric<18, 2>>; using map43_t = std::map<std::tuple<types::Integer, types::Char<10>, types::Char<9>>, types::Numeric<18, 2>>; map41_t& q41_expected(); map42_t& q42_expected(); map43_t& q43_expected();
#include "plan.h" plan::plan() { } plan::~plan() { } void plan::path() { /// PART 1 /// ros::Rate loop(100); turtlesim::Pose pose; cout << "Enter initial x: " << endl; cin >> pose.x; cout << "Enter initial y: " << endl; cin >> pose.y; goToDestination(pose, 0.01); loop.sleep(); /// PART 2 /// pose.x = 0; pose.y = 0; pose.theta = 0; goToDestination(pose, 0.01); loop.sleep(); /// PART 3 /// goToAngle(deg2rad(45)); loop.sleep(); /// PART 4 /// pose.x = 5.5; pose.y = 5.5; pose.theta = 0; goToDestination(pose, 0.01); loop.sleep(); cout << currentPosition.theta << endl; goToAngle(0); loop.sleep(); /// PART 5 /// double x = 1.0; for (int i = 0; i < 12; i++) { ros::Rate loop(100); if (i != 0 && i % 2 == 0) x++; cout << x << endl; linearMove(2.0, x); loop.sleep(); rotate(deg2rad(10), deg2rad(90)); loop.sleep(); } /// PART 6 /// geometry_msgs::Twist velocity_msg; goToAngle(0); do { double distance = getDistance(currentPosition.x, currentPosition.y, 5.5, 5.5); // double constSpeed = 1.0; double beta = atan2(currentPosition.y - 5.5, currentPosition.x - 5.5); double gama = currentPosition.theta; double e = beta + gama - PI / 2; velocity_msg.linear.x = distance; velocity_msg.linear.y = 0; velocity_msg.linear.z = 0; velocity_msg.angular.x = 0; velocity_msg.angular.y = 0; velocity_msg.angular.z = -1.0 * e; velocityCommand.publish(velocity_msg); ros::spinOnce(); } while (getDistance(currentPosition.x, currentPosition.y, 5.5, 5.5) > 0.01); loop.sleep(); } double plan::now() { return ros::Time::now().toSec(); } void plan::linearMove(double speed, double distance) { geometry_msgs::Twist velocity_msg; velocity_msg.linear.x = speed; velocity_msg.linear.y = 0; velocity_msg.linear.z = 0; velocity_msg.angular.x = 0; velocity_msg.angular.y = 0; velocity_msg.angular.z = 0; double current_distance = 0.0; ros::Rate loop(1000); double t0 = now(); do { velocityCommand.publish(velocity_msg); double t1 = now(); current_distance = speed * (t1 - t0); ros::spinOnce(); loop.sleep(); } while (current_distance < distance); velocity_msg.linear.x = 0; velocityCommand.publish(velocity_msg); } void plan::rotate(double angular_speed, double relative_angle) { geometry_msgs::Twist velocity_msg; velocity_msg.linear.x = 0; velocity_msg.linear.y = 0; velocity_msg.linear.z = 0; velocity_msg.angular.x = 0; velocity_msg.angular.y = 0; if (relative_angle > 0) velocity_msg.angular.z = angular_speed; else velocity_msg.angular.z = -angular_speed; double current_angle = 0.0; double t0 = now(); ros::Rate loop(100); do { velocityCommand.publish(velocity_msg); double t1 = now(); current_angle = angular_speed * (t1 - t0); ros::spinOnce(); loop.sleep(); } while (abs(current_angle) < abs(relative_angle)); velocity_msg.angular.z = 0; velocityCommand.publish(velocity_msg); } double plan::deg2rad(double degree) { return degree * PI / 180.0; } void plan::goToAngle(double desiredAngle) { double difference = desiredAngle - currentPosition.theta; rotate(deg2rad(10), difference); } void plan::updatePose(const turtlesim::Pose::ConstPtr &pose_msg) { currentPosition.x = pose_msg->x; currentPosition.y = pose_msg->y; currentPosition.theta = pose_msg->theta; } double plan::getDistance(double x1, double y1, double x2, double y2) { return sqrt(pow((x1 - x2), 2) + pow((y1 - y2), 2)); } void plan::goToDestination(turtlesim::Pose goal, double distance_tolerance) { geometry_msgs::Twist velocity_msg; ros::Rate loop(100); do { double e = getDistance(currentPosition.x, currentPosition.y, goal.x, goal.y); velocity_msg.linear.x = 0.5 * e; velocity_msg.linear.y = 0; velocity_msg.linear.z = 0; velocity_msg.angular.x = 0; velocity_msg.angular.y = 0; velocity_msg.angular.z = 4 * (atan2(goal.y - currentPosition.y, goal.x - currentPosition.x) - currentPosition.theta); velocityCommand.publish(velocity_msg); ros::spinOnce(); loop.sleep(); } while (getDistance(currentPosition.x, currentPosition.y, goal.x, goal.y) > distance_tolerance); cout << "Goal accomplished" << endl; velocity_msg.linear.x = 0; velocity_msg.angular.z = 0; velocityCommand.publish(velocity_msg); }
//===- Ops.cpp - Standard MLIR Operations ---------------------------------===// // // Copyright 2019 The MLIR Authors. // // 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 "mlir/Dialect/StandardOps/Ops.h" #include "mlir/IR/AffineExpr.h" #include "mlir/IR/AffineMap.h" #include "mlir/IR/Builders.h" #include "mlir/IR/Function.h" #include "mlir/IR/Matchers.h" #include "mlir/IR/Module.h" #include "mlir/IR/OpImplementation.h" #include "mlir/IR/PatternMatch.h" #include "mlir/IR/StandardTypes.h" #include "mlir/IR/TypeUtilities.h" #include "mlir/IR/Value.h" #include "mlir/Support/MathExtras.h" #include "mlir/Support/STLExtras.h" #include "mlir/Transforms/InliningUtils.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/FormatVariadic.h" #include "llvm/Support/raw_ostream.h" using namespace mlir; //===----------------------------------------------------------------------===// // StandardOpsDialect Interfaces //===----------------------------------------------------------------------===// namespace { struct StdOpAsmInterface : public OpAsmDialectInterface { using OpAsmDialectInterface::OpAsmDialectInterface; /// Get a special name to use when printing the given operation. The desired /// name should be streamed into 'os'. void getOpResultName(Operation *op, raw_ostream &os) const final { if (ConstantOp constant = dyn_cast<ConstantOp>(op)) return getConstantOpResultName(constant, os); } /// Get a special name to use when printing the given constant. static void getConstantOpResultName(ConstantOp op, raw_ostream &os) { Type type = op.getType(); Attribute value = op.getValue(); if (auto intCst = value.dyn_cast<IntegerAttr>()) { if (type.isIndex()) { os << 'c' << intCst.getInt(); } else if (type.cast<IntegerType>().isInteger(1)) { // i1 constants get special names. os << (intCst.getInt() ? "true" : "false"); } else { os << 'c' << intCst.getInt() << '_' << type; } } else if (type.isa<FunctionType>()) { os << 'f'; } else { os << "cst"; } } }; /// This class defines the interface for handling inlining with standard /// operations. struct StdInlinerInterface : public DialectInlinerInterface { using DialectInlinerInterface::DialectInlinerInterface; //===--------------------------------------------------------------------===// // Analysis Hooks //===--------------------------------------------------------------------===// /// All operations within standard ops can be inlined. bool isLegalToInline(Operation *, Region *, BlockAndValueMapping &) const final { return true; } //===--------------------------------------------------------------------===// // Transformation Hooks //===--------------------------------------------------------------------===// /// Handle the given inlined terminator by replacing it with a new operation /// as necessary. void handleTerminator(Operation *op, Block *newDest) const final { // Only "std.return" needs to be handled here. auto returnOp = dyn_cast<ReturnOp>(op); if (!returnOp) return; // Replace the return with a branch to the dest. OpBuilder builder(op); builder.create<BranchOp>(op->getLoc(), newDest, llvm::to_vector<4>(returnOp.getOperands())); op->erase(); } /// Handle the given inlined terminator by replacing it with a new operation /// as necessary. void handleTerminator(Operation *op, ArrayRef<Value *> valuesToRepl) const final { // Only "std.return" needs to be handled here. auto returnOp = cast<ReturnOp>(op); // Replace the values directly with the return operands. assert(returnOp.getNumOperands() == valuesToRepl.size()); for (const auto &it : llvm::enumerate(returnOp.getOperands())) valuesToRepl[it.index()]->replaceAllUsesWith(it.value()); } }; } // end anonymous namespace //===----------------------------------------------------------------------===// // StandardOpsDialect //===----------------------------------------------------------------------===// /// A custom binary operation printer that omits the "std." prefix from the /// operation names. static void printStandardBinaryOp(Operation *op, OpAsmPrinter &p) { assert(op->getNumOperands() == 2 && "binary op should have two operands"); assert(op->getNumResults() == 1 && "binary op should have one result"); // If not all the operand and result types are the same, just use the // generic assembly form to avoid omitting information in printing. auto resultType = op->getResult(0)->getType(); if (op->getOperand(0)->getType() != resultType || op->getOperand(1)->getType() != resultType) { p.printGenericOp(op); return; } p << op->getName().getStringRef().drop_front(strlen("std.")) << ' ' << *op->getOperand(0) << ", " << *op->getOperand(1); p.printOptionalAttrDict(op->getAttrs()); // Now we can output only one type for all operands and the result. p << " : " << op->getResult(0)->getType(); } /// A custom cast operation printer that omits the "std." prefix from the /// operation names. static void printStandardCastOp(Operation *op, OpAsmPrinter &p) { p << op->getName().getStringRef().drop_front(strlen("std.")) << ' ' << *op->getOperand(0) << " : " << op->getOperand(0)->getType() << " to " << op->getResult(0)->getType(); } /// A custom cast operation verifier. template <typename T> static LogicalResult verifyCastOp(T op) { auto opType = op.getOperand()->getType(); auto resType = op.getType(); if (!T::areCastCompatible(opType, resType)) return op.emitError("operand type ") << opType << " and result type " << resType << " are cast incompatible"; return success(); } StandardOpsDialect::StandardOpsDialect(MLIRContext *context) : Dialect(getDialectNamespace(), context) { addOperations<DmaStartOp, DmaWaitOp, #define GET_OP_LIST #include "mlir/Dialect/StandardOps/Ops.cpp.inc" >(); addInterfaces<StdInlinerInterface, StdOpAsmInterface>(); } void mlir::printDimAndSymbolList(Operation::operand_iterator begin, Operation::operand_iterator end, unsigned numDims, OpAsmPrinter &p) { p << '('; p.printOperands(begin, begin + numDims); p << ')'; if (begin + numDims != end) { p << '['; p.printOperands(begin + numDims, end); p << ']'; } } // Parses dimension and symbol list, and sets 'numDims' to the number of // dimension operands parsed. // Returns 'false' on success and 'true' on error. ParseResult mlir::parseDimAndSymbolList(OpAsmParser &parser, SmallVector<Value *, 4> &operands, unsigned &numDims) { SmallVector<OpAsmParser::OperandType, 8> opInfos; if (parser.parseOperandList(opInfos, OpAsmParser::Delimiter::Paren)) return failure(); // Store number of dimensions for validation by caller. numDims = opInfos.size(); // Parse the optional symbol operands. auto indexTy = parser.getBuilder().getIndexType(); if (parser.parseOperandList(opInfos, OpAsmParser::Delimiter::OptionalSquare) || parser.resolveOperands(opInfos, indexTy, operands)) return failure(); return success(); } /// Matches a ConstantIndexOp. /// TODO: This should probably just be a general matcher that uses m_Constant /// and checks the operation for an index type. static detail::op_matcher<ConstantIndexOp> m_ConstantIndex() { return detail::op_matcher<ConstantIndexOp>(); } //===----------------------------------------------------------------------===// // Common canonicalization pattern support logic //===----------------------------------------------------------------------===// namespace { /// This is a common class used for patterns of the form /// "someop(memrefcast) -> someop". It folds the source of any memref_cast /// into the root operation directly. struct MemRefCastFolder : public RewritePattern { /// The rootOpName is the name of the root operation to match against. MemRefCastFolder(StringRef rootOpName, MLIRContext *context) : RewritePattern(rootOpName, 1, context) {} PatternMatchResult match(Operation *op) const override { for (auto *operand : op->getOperands()) if (matchPattern(operand, m_Op<MemRefCastOp>())) return matchSuccess(); return matchFailure(); } void rewrite(Operation *op, PatternRewriter &rewriter) const override { for (unsigned i = 0, e = op->getNumOperands(); i != e; ++i) if (auto *memref = op->getOperand(i)->getDefiningOp()) if (auto cast = dyn_cast<MemRefCastOp>(memref)) op->setOperand(i, cast.getOperand()); rewriter.updatedRootInPlace(op); } }; /// Performs const folding `calculate` with element-wise behavior on the two /// attributes in `operands` and returns the result if possible. template <class AttrElementT, class ElementValueT = typename AttrElementT::ValueType, class CalculationT = std::function<ElementValueT(ElementValueT, ElementValueT)>> Attribute constFoldBinaryOp(ArrayRef<Attribute> operands, const CalculationT &calculate) { assert(operands.size() == 2 && "binary op takes two operands"); if (auto lhs = operands[0].dyn_cast_or_null<AttrElementT>()) { auto rhs = operands[1].dyn_cast_or_null<AttrElementT>(); if (!rhs || lhs.getType() != rhs.getType()) return {}; return AttrElementT::get(lhs.getType(), calculate(lhs.getValue(), rhs.getValue())); } else if (auto lhs = operands[0].dyn_cast_or_null<SplatElementsAttr>()) { auto rhs = operands[1].dyn_cast_or_null<SplatElementsAttr>(); if (!rhs || lhs.getType() != rhs.getType()) return {}; auto elementResult = constFoldBinaryOp<AttrElementT>( {lhs.getSplatValue(), rhs.getSplatValue()}, calculate); if (!elementResult) return {}; return DenseElementsAttr::get(lhs.getType(), elementResult); } return {}; } } // end anonymous namespace. //===----------------------------------------------------------------------===// // AddFOp //===----------------------------------------------------------------------===// OpFoldResult AddFOp::fold(ArrayRef<Attribute> operands) { return constFoldBinaryOp<FloatAttr>( operands, [](APFloat a, APFloat b) { return a + b; }); } //===----------------------------------------------------------------------===// // AddIOp //===----------------------------------------------------------------------===// OpFoldResult AddIOp::fold(ArrayRef<Attribute> operands) { /// addi(x, 0) -> x if (matchPattern(rhs(), m_Zero())) return lhs(); return constFoldBinaryOp<IntegerAttr>(operands, [](APInt a, APInt b) { return a + b; }); } //===----------------------------------------------------------------------===// // AllocOp //===----------------------------------------------------------------------===// static void print(OpAsmPrinter &p, AllocOp op) { p << "alloc"; // Print dynamic dimension operands. MemRefType type = op.getType(); printDimAndSymbolList(op.operand_begin(), op.operand_end(), type.getNumDynamicDims(), p); p.printOptionalAttrDict(op.getAttrs(), /*elidedAttrs=*/{"map"}); p << " : " << type; } static ParseResult parseAllocOp(OpAsmParser &parser, OperationState &result) { MemRefType type; // Parse the dimension operands and optional symbol operands, followed by a // memref type. unsigned numDimOperands; if (parseDimAndSymbolList(parser, result.operands, numDimOperands) || parser.parseOptionalAttributeDict(result.attributes) || parser.parseColonType(type)) return failure(); // Check numDynamicDims against number of question marks in memref type. // Note: this check remains here (instead of in verify()), because the // partition between dim operands and symbol operands is lost after parsing. // Verification still checks that the total number of operands matches // the number of symbols in the affine map, plus the number of dynamic // dimensions in the memref. if (numDimOperands != type.getNumDynamicDims()) return parser.emitError(parser.getNameLoc()) << "dimension operand count does not equal memref dynamic dimension " "count"; result.types.push_back(type); return success(); } static LogicalResult verify(AllocOp op) { auto memRefType = op.getResult()->getType().dyn_cast<MemRefType>(); if (!memRefType) return op.emitOpError("result must be a memref"); unsigned numSymbols = 0; if (!memRefType.getAffineMaps().empty()) { // Store number of symbols used in affine map (used in subsequent check). AffineMap affineMap = memRefType.getAffineMaps()[0]; numSymbols = affineMap.getNumSymbols(); } // Check that the total number of operands matches the number of symbols in // the affine map, plus the number of dynamic dimensions specified in the // memref type. unsigned numDynamicDims = memRefType.getNumDynamicDims(); if (op.getNumOperands() != numDynamicDims + numSymbols) return op.emitOpError( "operand count does not equal dimension plus symbol operand count"); // Verify that all operands are of type Index. for (auto operandType : op.getOperandTypes()) if (!operandType.isIndex()) return op.emitOpError("requires operands to be of type Index"); return success(); } namespace { /// Fold constant dimensions into an alloc operation. struct SimplifyAllocConst : public OpRewritePattern<AllocOp> { using OpRewritePattern<AllocOp>::OpRewritePattern; PatternMatchResult matchAndRewrite(AllocOp alloc, PatternRewriter &rewriter) const override { // Check to see if any dimensions operands are constants. If so, we can // substitute and drop them. if (llvm::none_of(alloc.getOperands(), [](Value *operand) { return matchPattern(operand, m_ConstantIndex()); })) return matchFailure(); auto memrefType = alloc.getType(); // Ok, we have one or more constant operands. Collect the non-constant ones // and keep track of the resultant memref type to build. SmallVector<int64_t, 4> newShapeConstants; newShapeConstants.reserve(memrefType.getRank()); SmallVector<Value *, 4> newOperands; SmallVector<Value *, 4> droppedOperands; unsigned dynamicDimPos = 0; for (unsigned dim = 0, e = memrefType.getRank(); dim < e; ++dim) { int64_t dimSize = memrefType.getDimSize(dim); // If this is already static dimension, keep it. if (dimSize != -1) { newShapeConstants.push_back(dimSize); continue; } auto *defOp = alloc.getOperand(dynamicDimPos)->getDefiningOp(); if (auto constantIndexOp = dyn_cast_or_null<ConstantIndexOp>(defOp)) { // Dynamic shape dimension will be folded. newShapeConstants.push_back(constantIndexOp.getValue()); // Record to check for zero uses later below. droppedOperands.push_back(constantIndexOp); } else { // Dynamic shape dimension not folded; copy operand from old memref. newShapeConstants.push_back(-1); newOperands.push_back(alloc.getOperand(dynamicDimPos)); } dynamicDimPos++; } // Create new memref type (which will have fewer dynamic dimensions). auto newMemRefType = MemRefType::get( newShapeConstants, memrefType.getElementType(), memrefType.getAffineMaps(), memrefType.getMemorySpace()); assert(static_cast<int64_t>(newOperands.size()) == newMemRefType.getNumDynamicDims()); // Create and insert the alloc op for the new memref. auto newAlloc = rewriter.create<AllocOp>(alloc.getLoc(), newMemRefType, newOperands); // Insert a cast so we have the same type as the old alloc. auto resultCast = rewriter.create<MemRefCastOp>(alloc.getLoc(), newAlloc, alloc.getType()); rewriter.replaceOp(alloc, {resultCast}, droppedOperands); return matchSuccess(); } }; /// Fold alloc operations with no uses. Alloc has side effects on the heap, /// but can still be deleted if it has zero uses. struct SimplifyDeadAlloc : public OpRewritePattern<AllocOp> { using OpRewritePattern<AllocOp>::OpRewritePattern; PatternMatchResult matchAndRewrite(AllocOp alloc, PatternRewriter &rewriter) const override { // Check if the alloc'ed value has any uses. if (!alloc.use_empty()) return matchFailure(); // If it doesn't, we can eliminate it. alloc.erase(); return matchSuccess(); } }; } // end anonymous namespace. void AllocOp::getCanonicalizationPatterns(OwningRewritePatternList &results, MLIRContext *context) { results.insert<SimplifyAllocConst, SimplifyDeadAlloc>(context); } //===----------------------------------------------------------------------===// // BranchOp //===----------------------------------------------------------------------===// static ParseResult parseBranchOp(OpAsmParser &parser, OperationState &result) { Block *dest; SmallVector<Value *, 4> destOperands; if (parser.parseSuccessorAndUseList(dest, destOperands)) return failure(); result.addSuccessor(dest, destOperands); return success(); } static void print(OpAsmPrinter &p, BranchOp op) { p << "br "; p.printSuccessorAndUseList(op.getOperation(), 0); } Block *BranchOp::getDest() { return getSuccessor(0); } void BranchOp::setDest(Block *block) { return setSuccessor(block, 0); } void BranchOp::eraseOperand(unsigned index) { getOperation()->eraseSuccessorOperand(0, index); } //===----------------------------------------------------------------------===// // CallOp //===----------------------------------------------------------------------===// static ParseResult parseCallOp(OpAsmParser &parser, OperationState &result) { SymbolRefAttr calleeAttr; FunctionType calleeType; SmallVector<OpAsmParser::OperandType, 4> operands; auto calleeLoc = parser.getNameLoc(); if (parser.parseAttribute(calleeAttr, "callee", result.attributes) || parser.parseOperandList(operands, OpAsmParser::Delimiter::Paren) || parser.parseOptionalAttributeDict(result.attributes) || parser.parseColonType(calleeType) || parser.addTypesToList(calleeType.getResults(), result.types) || parser.resolveOperands(operands, calleeType.getInputs(), calleeLoc, result.operands)) return failure(); return success(); } static void print(OpAsmPrinter &p, CallOp op) { p << "call " << op.getAttr("callee") << '('; p.printOperands(op.getOperands()); p << ')'; p.printOptionalAttrDict(op.getAttrs(), /*elidedAttrs=*/{"callee"}); p << " : "; p.printType(op.getCalleeType()); } static LogicalResult verify(CallOp op) { // Check that the callee attribute was specified. auto fnAttr = op.getAttrOfType<SymbolRefAttr>("callee"); if (!fnAttr) return op.emitOpError("requires a 'callee' symbol reference attribute"); auto fn = op.getParentOfType<ModuleOp>().lookupSymbol<FuncOp>(fnAttr.getValue()); if (!fn) return op.emitOpError() << "'" << fnAttr.getValue() << "' does not reference a valid function"; // Verify that the operand and result types match the callee. auto fnType = fn.getType(); if (fnType.getNumInputs() != op.getNumOperands()) return op.emitOpError("incorrect number of operands for callee"); for (unsigned i = 0, e = fnType.getNumInputs(); i != e; ++i) if (op.getOperand(i)->getType() != fnType.getInput(i)) return op.emitOpError("operand type mismatch"); if (fnType.getNumResults() != op.getNumResults()) return op.emitOpError("incorrect number of results for callee"); for (unsigned i = 0, e = fnType.getNumResults(); i != e; ++i) if (op.getResult(i)->getType() != fnType.getResult(i)) return op.emitOpError("result type mismatch"); return success(); } FunctionType CallOp::getCalleeType() { SmallVector<Type, 4> resultTypes(getResultTypes()); SmallVector<Type, 8> argTypes(getOperandTypes()); return FunctionType::get(argTypes, resultTypes, getContext()); } //===----------------------------------------------------------------------===// // CallIndirectOp //===----------------------------------------------------------------------===// namespace { /// Fold indirect calls that have a constant function as the callee operand. struct SimplifyIndirectCallWithKnownCallee : public OpRewritePattern<CallIndirectOp> { using OpRewritePattern<CallIndirectOp>::OpRewritePattern; PatternMatchResult matchAndRewrite(CallIndirectOp indirectCall, PatternRewriter &rewriter) const override { // Check that the callee is a constant callee. SymbolRefAttr calledFn; if (!matchPattern(indirectCall.getCallee(), m_Constant(&calledFn))) return matchFailure(); // Replace with a direct call. SmallVector<Type, 8> callResults(indirectCall.getResultTypes()); SmallVector<Value *, 8> callOperands(indirectCall.getArgOperands()); rewriter.replaceOpWithNewOp<CallOp>(indirectCall, calledFn.getValue(), callResults, callOperands); return matchSuccess(); } }; } // end anonymous namespace. static ParseResult parseCallIndirectOp(OpAsmParser &parser, OperationState &result) { FunctionType calleeType; OpAsmParser::OperandType callee; llvm::SMLoc operandsLoc; SmallVector<OpAsmParser::OperandType, 4> operands; return failure( parser.parseOperand(callee) || parser.getCurrentLocation(&operandsLoc) || parser.parseOperandList(operands, OpAsmParser::Delimiter::Paren) || parser.parseOptionalAttributeDict(result.attributes) || parser.parseColonType(calleeType) || parser.resolveOperand(callee, calleeType, result.operands) || parser.resolveOperands(operands, calleeType.getInputs(), operandsLoc, result.operands) || parser.addTypesToList(calleeType.getResults(), result.types)); } static void print(OpAsmPrinter &p, CallIndirectOp op) { p << "call_indirect "; p.printOperand(op.getCallee()); p << '('; p.printOperands(op.getArgOperands()); p << ')'; p.printOptionalAttrDict(op.getAttrs(), /*elidedAttrs=*/{"callee"}); p << " : " << op.getCallee()->getType(); } static LogicalResult verify(CallIndirectOp op) { // The callee must be a function. auto fnType = op.getCallee()->getType().dyn_cast<FunctionType>(); if (!fnType) return op.emitOpError("callee must have function type"); // Verify that the operand and result types match the callee. if (fnType.getNumInputs() != op.getNumOperands() - 1) return op.emitOpError("incorrect number of operands for callee"); for (unsigned i = 0, e = fnType.getNumInputs(); i != e; ++i) if (op.getOperand(i + 1)->getType() != fnType.getInput(i)) return op.emitOpError("operand type mismatch"); if (fnType.getNumResults() != op.getNumResults()) return op.emitOpError("incorrect number of results for callee"); for (unsigned i = 0, e = fnType.getNumResults(); i != e; ++i) if (op.getResult(i)->getType() != fnType.getResult(i)) return op.emitOpError("result type mismatch"); return success(); } void CallIndirectOp::getCanonicalizationPatterns( OwningRewritePatternList &results, MLIRContext *context) { results.insert<SimplifyIndirectCallWithKnownCallee>(context); } //===----------------------------------------------------------------------===// // General helpers for comparison ops //===----------------------------------------------------------------------===// // Return the type of the same shape (scalar, vector or tensor) containing i1. static Type getCheckedI1SameShape(Builder *build, Type type) { auto i1Type = build->getI1Type(); if (type.isIntOrIndexOrFloat()) return i1Type; if (auto tensorType = type.dyn_cast<RankedTensorType>()) return build->getTensorType(tensorType.getShape(), i1Type); if (type.isa<UnrankedTensorType>()) return build->getTensorType(i1Type); if (auto vectorType = type.dyn_cast<VectorType>()) return build->getVectorType(vectorType.getShape(), i1Type); return Type(); } static Type getI1SameShape(Builder *build, Type type) { Type res = getCheckedI1SameShape(build, type); assert(res && "expected type with valid i1 shape"); return res; } //===----------------------------------------------------------------------===// // CmpIOp //===----------------------------------------------------------------------===// // Returns an array of mnemonics for CmpIPredicates indexed by values thereof. static inline const char *const *getCmpIPredicateNames() { static const char *predicateNames[]{ /*EQ*/ "eq", /*NE*/ "ne", /*SLT*/ "slt", /*SLE*/ "sle", /*SGT*/ "sgt", /*SGE*/ "sge", /*ULT*/ "ult", /*ULE*/ "ule", /*UGT*/ "ugt", /*UGE*/ "uge", }; static_assert(std::extent<decltype(predicateNames)>::value == (size_t)CmpIPredicate::NumPredicates, "wrong number of predicate names"); return predicateNames; } // Returns a value of the predicate corresponding to the given mnemonic. // Returns NumPredicates (one-past-end) if there is no such mnemonic. CmpIPredicate CmpIOp::getPredicateByName(StringRef name) { return llvm::StringSwitch<CmpIPredicate>(name) .Case("eq", CmpIPredicate::EQ) .Case("ne", CmpIPredicate::NE) .Case("slt", CmpIPredicate::SLT) .Case("sle", CmpIPredicate::SLE) .Case("sgt", CmpIPredicate::SGT) .Case("sge", CmpIPredicate::SGE) .Case("ult", CmpIPredicate::ULT) .Case("ule", CmpIPredicate::ULE) .Case("ugt", CmpIPredicate::UGT) .Case("uge", CmpIPredicate::UGE) .Default(CmpIPredicate::NumPredicates); } static void buildCmpIOp(Builder *build, OperationState &result, CmpIPredicate predicate, Value *lhs, Value *rhs) { result.addOperands({lhs, rhs}); result.types.push_back(getI1SameShape(build, lhs->getType())); result.addAttribute( CmpIOp::getPredicateAttrName(), build->getI64IntegerAttr(static_cast<int64_t>(predicate))); } static ParseResult parseCmpIOp(OpAsmParser &parser, OperationState &result) { SmallVector<OpAsmParser::OperandType, 2> ops; SmallVector<NamedAttribute, 4> attrs; Attribute predicateNameAttr; Type type; if (parser.parseAttribute(predicateNameAttr, CmpIOp::getPredicateAttrName(), attrs) || parser.parseComma() || parser.parseOperandList(ops, 2) || parser.parseOptionalAttributeDict(attrs) || parser.parseColonType(type) || parser.resolveOperands(ops, type, result.operands)) return failure(); if (!predicateNameAttr.isa<StringAttr>()) return parser.emitError(parser.getNameLoc(), "expected string comparison predicate attribute"); // Rewrite string attribute to an enum value. StringRef predicateName = predicateNameAttr.cast<StringAttr>().getValue(); auto predicate = CmpIOp::getPredicateByName(predicateName); if (predicate == CmpIPredicate::NumPredicates) return parser.emitError(parser.getNameLoc()) << "unknown comparison predicate \"" << predicateName << "\""; auto builder = parser.getBuilder(); Type i1Type = getCheckedI1SameShape(&builder, type); if (!i1Type) return parser.emitError(parser.getNameLoc(), "expected type with valid i1 shape"); attrs[0].second = builder.getI64IntegerAttr(static_cast<int64_t>(predicate)); result.attributes = attrs; result.addTypes({i1Type}); return success(); } static void print(OpAsmPrinter &p, CmpIOp op) { p << "cmpi "; auto predicateValue = op.getAttrOfType<IntegerAttr>(CmpIOp::getPredicateAttrName()).getInt(); assert(predicateValue >= static_cast<int>(CmpIPredicate::FirstValidValue) && predicateValue < static_cast<int>(CmpIPredicate::NumPredicates) && "unknown predicate index"); Builder b(op.getContext()); auto predicateStringAttr = b.getStringAttr(getCmpIPredicateNames()[predicateValue]); p.printAttribute(predicateStringAttr); p << ", "; p.printOperand(op.lhs()); p << ", "; p.printOperand(op.rhs()); p.printOptionalAttrDict(op.getAttrs(), /*elidedAttrs=*/{CmpIOp::getPredicateAttrName()}); p << " : " << op.lhs()->getType(); } static LogicalResult verify(CmpIOp op) { auto predicateAttr = op.getAttrOfType<IntegerAttr>(CmpIOp::getPredicateAttrName()); if (!predicateAttr) return op.emitOpError("requires an integer attribute named 'predicate'"); auto predicate = predicateAttr.getInt(); if (predicate < (int64_t)CmpIPredicate::FirstValidValue || predicate >= (int64_t)CmpIPredicate::NumPredicates) return op.emitOpError("'predicate' attribute value out of range"); return success(); } // Compute `lhs` `pred` `rhs`, where `pred` is one of the known integer // comparison predicates. static bool applyCmpPredicate(CmpIPredicate predicate, const APInt &lhs, const APInt &rhs) { switch (predicate) { case CmpIPredicate::EQ: return lhs.eq(rhs); case CmpIPredicate::NE: return lhs.ne(rhs); case CmpIPredicate::SLT: return lhs.slt(rhs); case CmpIPredicate::SLE: return lhs.sle(rhs); case CmpIPredicate::SGT: return lhs.sgt(rhs); case CmpIPredicate::SGE: return lhs.sge(rhs); case CmpIPredicate::ULT: return lhs.ult(rhs); case CmpIPredicate::ULE: return lhs.ule(rhs); case CmpIPredicate::UGT: return lhs.ugt(rhs); case CmpIPredicate::UGE: return lhs.uge(rhs); default: llvm_unreachable("unknown comparison predicate"); } } // Constant folding hook for comparisons. OpFoldResult CmpIOp::fold(ArrayRef<Attribute> operands) { assert(operands.size() == 2 && "cmpi takes two arguments"); auto lhs = operands.front().dyn_cast_or_null<IntegerAttr>(); auto rhs = operands.back().dyn_cast_or_null<IntegerAttr>(); if (!lhs || !rhs) return {}; auto val = applyCmpPredicate(getPredicate(), lhs.getValue(), rhs.getValue()); return IntegerAttr::get(IntegerType::get(1, getContext()), APInt(1, val)); } //===----------------------------------------------------------------------===// // CmpFOp //===----------------------------------------------------------------------===// // Returns an array of mnemonics for CmpFPredicates indexed by values thereof. static inline const char *const *getCmpFPredicateNames() { static const char *predicateNames[] = { /*AlwaysFalse*/ "false", /*OEQ*/ "oeq", /*OGT*/ "ogt", /*OGE*/ "oge", /*OLT*/ "olt", /*OLE*/ "ole", /*ONE*/ "one", /*ORD*/ "ord", /*UEQ*/ "ueq", /*UGT*/ "ugt", /*UGE*/ "uge", /*ULT*/ "ult", /*ULE*/ "ule", /*UNE*/ "une", /*UNO*/ "uno", /*AlwaysTrue*/ "true", }; static_assert(std::extent<decltype(predicateNames)>::value == (size_t)CmpFPredicate::NumPredicates, "wrong number of predicate names"); return predicateNames; } // Returns a value of the predicate corresponding to the given mnemonic. // Returns NumPredicates (one-past-end) if there is no such mnemonic. CmpFPredicate CmpFOp::getPredicateByName(StringRef name) { return llvm::StringSwitch<CmpFPredicate>(name) .Case("false", CmpFPredicate::AlwaysFalse) .Case("oeq", CmpFPredicate::OEQ) .Case("ogt", CmpFPredicate::OGT) .Case("oge", CmpFPredicate::OGE) .Case("olt", CmpFPredicate::OLT) .Case("ole", CmpFPredicate::OLE) .Case("one", CmpFPredicate::ONE) .Case("ord", CmpFPredicate::ORD) .Case("ueq", CmpFPredicate::UEQ) .Case("ugt", CmpFPredicate::UGT) .Case("uge", CmpFPredicate::UGE) .Case("ult", CmpFPredicate::ULT) .Case("ule", CmpFPredicate::ULE) .Case("une", CmpFPredicate::UNE) .Case("uno", CmpFPredicate::UNO) .Case("true", CmpFPredicate::AlwaysTrue) .Default(CmpFPredicate::NumPredicates); } static void buildCmpFOp(Builder *build, OperationState &result, CmpFPredicate predicate, Value *lhs, Value *rhs) { result.addOperands({lhs, rhs}); result.types.push_back(getI1SameShape(build, lhs->getType())); result.addAttribute( CmpFOp::getPredicateAttrName(), build->getI64IntegerAttr(static_cast<int64_t>(predicate))); } static ParseResult parseCmpFOp(OpAsmParser &parser, OperationState &result) { SmallVector<OpAsmParser::OperandType, 2> ops; SmallVector<NamedAttribute, 4> attrs; Attribute predicateNameAttr; Type type; if (parser.parseAttribute(predicateNameAttr, CmpFOp::getPredicateAttrName(), attrs) || parser.parseComma() || parser.parseOperandList(ops, 2) || parser.parseOptionalAttributeDict(attrs) || parser.parseColonType(type) || parser.resolveOperands(ops, type, result.operands)) return failure(); if (!predicateNameAttr.isa<StringAttr>()) return parser.emitError(parser.getNameLoc(), "expected string comparison predicate attribute"); // Rewrite string attribute to an enum value. StringRef predicateName = predicateNameAttr.cast<StringAttr>().getValue(); auto predicate = CmpFOp::getPredicateByName(predicateName); if (predicate == CmpFPredicate::NumPredicates) return parser.emitError(parser.getNameLoc(), "unknown comparison predicate \"" + predicateName + "\""); auto builder = parser.getBuilder(); Type i1Type = getCheckedI1SameShape(&builder, type); if (!i1Type) return parser.emitError(parser.getNameLoc(), "expected type with valid i1 shape"); attrs[0].second = builder.getI64IntegerAttr(static_cast<int64_t>(predicate)); result.attributes = attrs; result.addTypes({i1Type}); return success(); } static void print(OpAsmPrinter &p, CmpFOp op) { p << "cmpf "; auto predicateValue = op.getAttrOfType<IntegerAttr>(CmpFOp::getPredicateAttrName()).getInt(); assert(predicateValue >= static_cast<int>(CmpFPredicate::FirstValidValue) && predicateValue < static_cast<int>(CmpFPredicate::NumPredicates) && "unknown predicate index"); Builder b(op.getContext()); auto predicateStringAttr = b.getStringAttr(getCmpFPredicateNames()[predicateValue]); p.printAttribute(predicateStringAttr); p << ", "; p.printOperand(op.lhs()); p << ", "; p.printOperand(op.rhs()); p.printOptionalAttrDict(op.getAttrs(), /*elidedAttrs=*/{CmpFOp::getPredicateAttrName()}); p << " : " << op.lhs()->getType(); } static LogicalResult verify(CmpFOp op) { auto predicateAttr = op.getAttrOfType<IntegerAttr>(CmpFOp::getPredicateAttrName()); if (!predicateAttr) return op.emitOpError("requires an integer attribute named 'predicate'"); auto predicate = predicateAttr.getInt(); if (predicate < (int64_t)CmpFPredicate::FirstValidValue || predicate >= (int64_t)CmpFPredicate::NumPredicates) return op.emitOpError("'predicate' attribute value out of range"); return success(); } // Compute `lhs` `pred` `rhs`, where `pred` is one of the known floating point // comparison predicates. static bool applyCmpPredicate(CmpFPredicate predicate, const APFloat &lhs, const APFloat &rhs) { auto cmpResult = lhs.compare(rhs); switch (predicate) { case CmpFPredicate::AlwaysFalse: return false; case CmpFPredicate::OEQ: return cmpResult == APFloat::cmpEqual; case CmpFPredicate::OGT: return cmpResult == APFloat::cmpGreaterThan; case CmpFPredicate::OGE: return cmpResult == APFloat::cmpGreaterThan || cmpResult == APFloat::cmpEqual; case CmpFPredicate::OLT: return cmpResult == APFloat::cmpLessThan; case CmpFPredicate::OLE: return cmpResult == APFloat::cmpLessThan || cmpResult == APFloat::cmpEqual; case CmpFPredicate::ONE: return cmpResult != APFloat::cmpUnordered && cmpResult != APFloat::cmpEqual; case CmpFPredicate::ORD: return cmpResult != APFloat::cmpUnordered; case CmpFPredicate::UEQ: return cmpResult == APFloat::cmpUnordered || cmpResult == APFloat::cmpEqual; case CmpFPredicate::UGT: return cmpResult == APFloat::cmpUnordered || cmpResult == APFloat::cmpGreaterThan; case CmpFPredicate::UGE: return cmpResult == APFloat::cmpUnordered || cmpResult == APFloat::cmpGreaterThan || cmpResult == APFloat::cmpEqual; case CmpFPredicate::ULT: return cmpResult == APFloat::cmpUnordered || cmpResult == APFloat::cmpLessThan; case CmpFPredicate::ULE: return cmpResult == APFloat::cmpUnordered || cmpResult == APFloat::cmpLessThan || cmpResult == APFloat::cmpEqual; case CmpFPredicate::UNE: return cmpResult != APFloat::cmpEqual; case CmpFPredicate::UNO: return cmpResult == APFloat::cmpUnordered; case CmpFPredicate::AlwaysTrue: return true; default: llvm_unreachable("unknown comparison predicate"); } } // Constant folding hook for comparisons. OpFoldResult CmpFOp::fold(ArrayRef<Attribute> operands) { assert(operands.size() == 2 && "cmpf takes two arguments"); auto lhs = operands.front().dyn_cast_or_null<FloatAttr>(); auto rhs = operands.back().dyn_cast_or_null<FloatAttr>(); // TODO(gcmn) We could actually do some intelligent things if we know only one // of the operands, but it's inf or nan. if (!lhs || !rhs) return {}; auto val = applyCmpPredicate(getPredicate(), lhs.getValue(), rhs.getValue()); return IntegerAttr::get(IntegerType::get(1, getContext()), APInt(1, val)); } //===----------------------------------------------------------------------===// // CondBranchOp //===----------------------------------------------------------------------===// namespace { /// cond_br true, ^bb1, ^bb2 -> br ^bb1 /// cond_br false, ^bb1, ^bb2 -> br ^bb2 /// struct SimplifyConstCondBranchPred : public OpRewritePattern<CondBranchOp> { using OpRewritePattern<CondBranchOp>::OpRewritePattern; PatternMatchResult matchAndRewrite(CondBranchOp condbr, PatternRewriter &rewriter) const override { // Check that the condition is a constant. if (!matchPattern(condbr.getCondition(), m_Op<ConstantOp>())) return matchFailure(); Block *foldedDest; SmallVector<Value *, 4> branchArgs; // If the condition is known to evaluate to false we fold to a branch to the // false destination. Otherwise, we fold to a branch to the true // destination. if (matchPattern(condbr.getCondition(), m_Zero())) { foldedDest = condbr.getFalseDest(); branchArgs.assign(condbr.false_operand_begin(), condbr.false_operand_end()); } else { foldedDest = condbr.getTrueDest(); branchArgs.assign(condbr.true_operand_begin(), condbr.true_operand_end()); } rewriter.replaceOpWithNewOp<BranchOp>(condbr, foldedDest, branchArgs); return matchSuccess(); } }; } // end anonymous namespace. static ParseResult parseCondBranchOp(OpAsmParser &parser, OperationState &result) { SmallVector<Value *, 4> destOperands; Block *dest; OpAsmParser::OperandType condInfo; // Parse the condition. Type int1Ty = parser.getBuilder().getI1Type(); if (parser.parseOperand(condInfo) || parser.parseComma() || parser.resolveOperand(condInfo, int1Ty, result.operands)) { return parser.emitError(parser.getNameLoc(), "expected condition type was boolean (i1)"); } // Parse the true successor. if (parser.parseSuccessorAndUseList(dest, destOperands)) return failure(); result.addSuccessor(dest, destOperands); // Parse the false successor. destOperands.clear(); if (parser.parseComma() || parser.parseSuccessorAndUseList(dest, destOperands)) return failure(); result.addSuccessor(dest, destOperands); return success(); } static void print(OpAsmPrinter &p, CondBranchOp op) { p << "cond_br "; p.printOperand(op.getCondition()); p << ", "; p.printSuccessorAndUseList(op.getOperation(), CondBranchOp::trueIndex); p << ", "; p.printSuccessorAndUseList(op.getOperation(), CondBranchOp::falseIndex); } void CondBranchOp::getCanonicalizationPatterns( OwningRewritePatternList &results, MLIRContext *context) { results.insert<SimplifyConstCondBranchPred>(context); } //===----------------------------------------------------------------------===// // Constant*Op //===----------------------------------------------------------------------===// static void print(OpAsmPrinter &p, ConstantOp &op) { p << "constant "; p.printOptionalAttrDict(op.getAttrs(), /*elidedAttrs=*/{"value"}); if (op.getAttrs().size() > 1) p << ' '; p.printAttribute(op.getValue()); // If the value is a symbol reference, print a trailing type. if (op.getValue().isa<SymbolRefAttr>()) p << " : " << op.getType(); } static ParseResult parseConstantOp(OpAsmParser &parser, OperationState &result) { Attribute valueAttr; if (parser.parseOptionalAttributeDict(result.attributes) || parser.parseAttribute(valueAttr, "value", result.attributes)) return failure(); // If the attribute is a symbol reference, then we expect a trailing type. Type type; if (!valueAttr.isa<SymbolRefAttr>()) type = valueAttr.getType(); else if (parser.parseColonType(type)) return failure(); // Add the attribute type to the list. return parser.addTypeToList(type, result.types); } /// The constant op requires an attribute, and furthermore requires that it /// matches the return type. static LogicalResult verify(ConstantOp &op) { auto value = op.getValue(); if (!value) return op.emitOpError("requires a 'value' attribute"); auto type = op.getType(); if (!value.getType().isa<NoneType>() && type != value.getType()) return op.emitOpError() << "requires attribute's type (" << value.getType() << ") to match op's return type (" << type << ")"; if (type.isa<IndexType>() || value.isa<BoolAttr>()) return success(); if (auto intAttr = value.dyn_cast<IntegerAttr>()) { // If the type has a known bitwidth we verify that the value can be // represented with the given bitwidth. auto bitwidth = type.cast<IntegerType>().getWidth(); auto intVal = intAttr.getValue(); if (!intVal.isSignedIntN(bitwidth) && !intVal.isIntN(bitwidth)) return op.emitOpError("requires 'value' to be an integer within the " "range of the integer result type"); return success(); } if (type.isa<FloatType>()) { if (!value.isa<FloatAttr>()) return op.emitOpError("requires 'value' to be a floating point constant"); return success(); } if (type.isa<ShapedType>()) { if (!value.isa<ElementsAttr>()) return op.emitOpError("requires 'value' to be a shaped constant"); return success(); } if (type.isa<FunctionType>()) { auto fnAttr = value.dyn_cast<SymbolRefAttr>(); if (!fnAttr) return op.emitOpError("requires 'value' to be a function reference"); // Try to find the referenced function. auto fn = op.getParentOfType<ModuleOp>().lookupSymbol<FuncOp>(fnAttr.getValue()); if (!fn) return op.emitOpError("reference to undefined function 'bar'"); // Check that the referenced function has the correct type. if (fn.getType() != type) return op.emitOpError("reference to function with mismatched type"); return success(); } if (type.isa<NoneType>() && value.isa<UnitAttr>()) return success(); return op.emitOpError("unsupported 'value' attribute: ") << value; } OpFoldResult ConstantOp::fold(ArrayRef<Attribute> operands) { assert(operands.empty() && "constant has no operands"); return getValue(); } /// Returns true if a constant operation can be built with the given value and /// result type. bool ConstantOp::isBuildableWith(Attribute value, Type type) { // SymbolRefAttr can only be used with a function type. if (value.isa<SymbolRefAttr>()) return type.isa<FunctionType>(); // Otherwise, the attribute must have the same type as 'type'. if (value.getType() != type) return false; // Finally, check that the attribute kind is handled. return value.isa<BoolAttr>() || value.isa<IntegerAttr>() || value.isa<FloatAttr>() || value.isa<ElementsAttr>() || value.isa<UnitAttr>(); } void ConstantFloatOp::build(Builder *builder, OperationState &result, const APFloat &value, FloatType type) { ConstantOp::build(builder, result, type, builder->getFloatAttr(type, value)); } bool ConstantFloatOp::classof(Operation *op) { return ConstantOp::classof(op) && op->getResult(0)->getType().isa<FloatType>(); } /// ConstantIntOp only matches values whose result type is an IntegerType. bool ConstantIntOp::classof(Operation *op) { return ConstantOp::classof(op) && op->getResult(0)->getType().isa<IntegerType>(); } void ConstantIntOp::build(Builder *builder, OperationState &result, int64_t value, unsigned width) { Type type = builder->getIntegerType(width); ConstantOp::build(builder, result, type, builder->getIntegerAttr(type, value)); } /// Build a constant int op producing an integer with the specified type, /// which must be an integer type. void ConstantIntOp::build(Builder *builder, OperationState &result, int64_t value, Type type) { assert(type.isa<IntegerType>() && "ConstantIntOp can only have integer type"); ConstantOp::build(builder, result, type, builder->getIntegerAttr(type, value)); } /// ConstantIndexOp only matches values whose result type is Index. bool ConstantIndexOp::classof(Operation *op) { return ConstantOp::classof(op) && op->getResult(0)->getType().isIndex(); } void ConstantIndexOp::build(Builder *builder, OperationState &result, int64_t value) { Type type = builder->getIndexType(); ConstantOp::build(builder, result, type, builder->getIntegerAttr(type, value)); } //===----------------------------------------------------------------------===// // DeallocOp //===----------------------------------------------------------------------===// namespace { /// Fold Dealloc operations that are deallocating an AllocOp that is only used /// by other Dealloc operations. struct SimplifyDeadDealloc : public OpRewritePattern<DeallocOp> { using OpRewritePattern<DeallocOp>::OpRewritePattern; PatternMatchResult matchAndRewrite(DeallocOp dealloc, PatternRewriter &rewriter) const override { // Check that the memref operand's defining operation is an AllocOp. Value *memref = dealloc.memref(); if (!isa_and_nonnull<AllocOp>(memref->getDefiningOp())) return matchFailure(); // Check that all of the uses of the AllocOp are other DeallocOps. for (auto *user : memref->getUsers()) if (!isa<DeallocOp>(user)) return matchFailure(); // Erase the dealloc operation. rewriter.replaceOp(dealloc, llvm::None); return matchSuccess(); } }; } // end anonymous namespace. static void print(OpAsmPrinter &p, DeallocOp op) { p << "dealloc " << *op.memref() << " : " << op.memref()->getType(); } static ParseResult parseDeallocOp(OpAsmParser &parser, OperationState &result) { OpAsmParser::OperandType memrefInfo; MemRefType type; return failure(parser.parseOperand(memrefInfo) || parser.parseColonType(type) || parser.resolveOperand(memrefInfo, type, result.operands)); } static LogicalResult verify(DeallocOp op) { if (!op.memref()->getType().isa<MemRefType>()) return op.emitOpError("operand must be a memref"); return success(); } void DeallocOp::getCanonicalizationPatterns(OwningRewritePatternList &results, MLIRContext *context) { /// dealloc(memrefcast) -> dealloc results.insert<MemRefCastFolder>(getOperationName(), context); results.insert<SimplifyDeadDealloc>(context); } //===----------------------------------------------------------------------===// // DimOp //===----------------------------------------------------------------------===// static void print(OpAsmPrinter &p, DimOp op) { p << "dim " << *op.getOperand() << ", " << op.getIndex(); p.printOptionalAttrDict(op.getAttrs(), /*elidedAttrs=*/{"index"}); p << " : " << op.getOperand()->getType(); } static ParseResult parseDimOp(OpAsmParser &parser, OperationState &result) { OpAsmParser::OperandType operandInfo; IntegerAttr indexAttr; Type type; Type indexType = parser.getBuilder().getIndexType(); return failure( parser.parseOperand(operandInfo) || parser.parseComma() || parser.parseAttribute(indexAttr, indexType, "index", result.attributes) || parser.parseOptionalAttributeDict(result.attributes) || parser.parseColonType(type) || parser.resolveOperand(operandInfo, type, result.operands) || parser.addTypeToList(indexType, result.types)); } static LogicalResult verify(DimOp op) { // Check that we have an integer index operand. auto indexAttr = op.getAttrOfType<IntegerAttr>("index"); if (!indexAttr) return op.emitOpError("requires an integer attribute named 'index'"); int64_t index = indexAttr.getValue().getSExtValue(); auto type = op.getOperand()->getType(); if (auto tensorType = type.dyn_cast<RankedTensorType>()) { if (index >= tensorType.getRank()) return op.emitOpError("index is out of range"); } else if (auto memrefType = type.dyn_cast<MemRefType>()) { if (index >= memrefType.getRank()) return op.emitOpError("index is out of range"); } else if (type.isa<UnrankedTensorType>()) { // ok, assumed to be in-range. } else { return op.emitOpError("requires an operand with tensor or memref type"); } return success(); } OpFoldResult DimOp::fold(ArrayRef<Attribute> operands) { // Constant fold dim when the size along the index referred to is a constant. auto opType = getOperand()->getType(); int64_t indexSize = -1; if (auto tensorType = opType.dyn_cast<RankedTensorType>()) indexSize = tensorType.getShape()[getIndex()]; else if (auto memrefType = opType.dyn_cast<MemRefType>()) indexSize = memrefType.getShape()[getIndex()]; if (indexSize >= 0) return IntegerAttr::get(IndexType::get(getContext()), indexSize); return {}; } void DimOp::getCanonicalizationPatterns(OwningRewritePatternList &results, MLIRContext *context) { /// dim(memrefcast) -> dim results.insert<MemRefCastFolder>(getOperationName(), context); } //===----------------------------------------------------------------------===// // DivISOp //===----------------------------------------------------------------------===// OpFoldResult DivISOp::fold(ArrayRef<Attribute> operands) { assert(operands.size() == 2 && "binary operation takes two operands"); auto lhs = operands.front().dyn_cast_or_null<IntegerAttr>(); auto rhs = operands.back().dyn_cast_or_null<IntegerAttr>(); if (!lhs || !rhs) return {}; // Don't fold if it requires division by zero. if (rhs.getValue().isNullValue()) return {}; // Don't fold if it would overflow. bool overflow; auto result = lhs.getValue().sdiv_ov(rhs.getValue(), overflow); return overflow ? IntegerAttr() : IntegerAttr::get(lhs.getType(), result); } //===----------------------------------------------------------------------===// // DivIUOp //===----------------------------------------------------------------------===// OpFoldResult DivIUOp::fold(ArrayRef<Attribute> operands) { assert(operands.size() == 2 && "binary operation takes two operands"); auto lhs = operands.front().dyn_cast_or_null<IntegerAttr>(); auto rhs = operands.back().dyn_cast_or_null<IntegerAttr>(); if (!lhs || !rhs) return {}; // Don't fold if it requires division by zero. auto rhsValue = rhs.getValue(); if (rhsValue.isNullValue()) return {}; return IntegerAttr::get(lhs.getType(), lhs.getValue().udiv(rhsValue)); } // --------------------------------------------------------------------------- // DmaStartOp // --------------------------------------------------------------------------- void DmaStartOp::build(Builder *builder, OperationState &result, Value *srcMemRef, ArrayRef<Value *> srcIndices, Value *destMemRef, ArrayRef<Value *> destIndices, Value *numElements, Value *tagMemRef, ArrayRef<Value *> tagIndices, Value *stride, Value *elementsPerStride) { result.addOperands(srcMemRef); result.addOperands(srcIndices); result.addOperands(destMemRef); result.addOperands(destIndices); result.addOperands({numElements, tagMemRef}); result.addOperands(tagIndices); if (stride) result.addOperands({stride, elementsPerStride}); } void DmaStartOp::print(OpAsmPrinter &p) { p << "dma_start " << *getSrcMemRef() << '['; p.printOperands(getSrcIndices()); p << "], " << *getDstMemRef() << '['; p.printOperands(getDstIndices()); p << "], " << *getNumElements(); p << ", " << *getTagMemRef() << '['; p.printOperands(getTagIndices()); p << ']'; if (isStrided()) { p << ", " << *getStride(); p << ", " << *getNumElementsPerStride(); } p.printOptionalAttrDict(getAttrs()); p << " : " << getSrcMemRef()->getType(); p << ", " << getDstMemRef()->getType(); p << ", " << getTagMemRef()->getType(); } // Parse DmaStartOp. // Ex: // %dma_id = dma_start %src[%i, %j], %dst[%k, %l], %size, // %tag[%index], %stride, %num_elt_per_stride : // : memref<3076 x f32, 0>, // memref<1024 x f32, 2>, // memref<1 x i32> // ParseResult DmaStartOp::parse(OpAsmParser &parser, OperationState &result) { OpAsmParser::OperandType srcMemRefInfo; SmallVector<OpAsmParser::OperandType, 4> srcIndexInfos; OpAsmParser::OperandType dstMemRefInfo; SmallVector<OpAsmParser::OperandType, 4> dstIndexInfos; OpAsmParser::OperandType numElementsInfo; OpAsmParser::OperandType tagMemrefInfo; SmallVector<OpAsmParser::OperandType, 4> tagIndexInfos; SmallVector<OpAsmParser::OperandType, 2> strideInfo; SmallVector<Type, 3> types; auto indexType = parser.getBuilder().getIndexType(); // Parse and resolve the following list of operands: // *) source memref followed by its indices (in square brackets). // *) destination memref followed by its indices (in square brackets). // *) dma size in KiB. if (parser.parseOperand(srcMemRefInfo) || parser.parseOperandList(srcIndexInfos, OpAsmParser::Delimiter::Square) || parser.parseComma() || parser.parseOperand(dstMemRefInfo) || parser.parseOperandList(dstIndexInfos, OpAsmParser::Delimiter::Square) || parser.parseComma() || parser.parseOperand(numElementsInfo) || parser.parseComma() || parser.parseOperand(tagMemrefInfo) || parser.parseOperandList(tagIndexInfos, OpAsmParser::Delimiter::Square)) return failure(); // Parse optional stride and elements per stride. if (parser.parseTrailingOperandList(strideInfo)) return failure(); bool isStrided = strideInfo.size() == 2; if (!strideInfo.empty() && !isStrided) { return parser.emitError(parser.getNameLoc(), "expected two stride related operands"); } if (parser.parseColonTypeList(types)) return failure(); if (types.size() != 3) return parser.emitError(parser.getNameLoc(), "fewer/more types expected"); if (parser.resolveOperand(srcMemRefInfo, types[0], result.operands) || parser.resolveOperands(srcIndexInfos, indexType, result.operands) || parser.resolveOperand(dstMemRefInfo, types[1], result.operands) || parser.resolveOperands(dstIndexInfos, indexType, result.operands) || // size should be an index. parser.resolveOperand(numElementsInfo, indexType, result.operands) || parser.resolveOperand(tagMemrefInfo, types[2], result.operands) || // tag indices should be index. parser.resolveOperands(tagIndexInfos, indexType, result.operands)) return failure(); auto memrefType0 = types[0].dyn_cast<MemRefType>(); if (!memrefType0) return parser.emitError(parser.getNameLoc(), "expected source to be of memref type"); auto memrefType1 = types[1].dyn_cast<MemRefType>(); if (!memrefType1) return parser.emitError(parser.getNameLoc(), "expected destination to be of memref type"); auto memrefType2 = types[2].dyn_cast<MemRefType>(); if (!memrefType2) return parser.emitError(parser.getNameLoc(), "expected tag to be of memref type"); if (isStrided) { if (parser.resolveOperands(strideInfo, indexType, result.operands)) return failure(); } // Check that source/destination index list size matches associated rank. if (static_cast<int64_t>(srcIndexInfos.size()) != memrefType0.getRank() || static_cast<int64_t>(dstIndexInfos.size()) != memrefType1.getRank()) return parser.emitError(parser.getNameLoc(), "memref rank not equal to indices count"); if (static_cast<int64_t>(tagIndexInfos.size()) != memrefType2.getRank()) return parser.emitError(parser.getNameLoc(), "tag memref rank not equal to indices count"); return success(); } LogicalResult DmaStartOp::verify() { // DMAs from different memory spaces supported. if (getSrcMemorySpace() == getDstMemorySpace()) return emitOpError("DMA should be between different memory spaces"); if (getNumOperands() != getTagMemRefRank() + getSrcMemRefRank() + getDstMemRefRank() + 3 + 1 && getNumOperands() != getTagMemRefRank() + getSrcMemRefRank() + getDstMemRefRank() + 3 + 1 + 2) { return emitOpError("incorrect number of operands"); } return success(); } void DmaStartOp::getCanonicalizationPatterns(OwningRewritePatternList &results, MLIRContext *context) { /// dma_start(memrefcast) -> dma_start results.insert<MemRefCastFolder>(getOperationName(), context); } // --------------------------------------------------------------------------- // DmaWaitOp // --------------------------------------------------------------------------- void DmaWaitOp::build(Builder *builder, OperationState &result, Value *tagMemRef, ArrayRef<Value *> tagIndices, Value *numElements) { result.addOperands(tagMemRef); result.addOperands(tagIndices); result.addOperands(numElements); } void DmaWaitOp::print(OpAsmPrinter &p) { p << "dma_wait "; p.printOperand(getTagMemRef()); p << '['; p.printOperands(getTagIndices()); p << "], "; p.printOperand(getNumElements()); p.printOptionalAttrDict(getAttrs()); p << " : " << getTagMemRef()->getType(); } // Parse DmaWaitOp. // Eg: // dma_wait %tag[%index], %num_elements : memref<1 x i32, (d0) -> (d0), 4> // ParseResult DmaWaitOp::parse(OpAsmParser &parser, OperationState &result) { OpAsmParser::OperandType tagMemrefInfo; SmallVector<OpAsmParser::OperandType, 2> tagIndexInfos; Type type; auto indexType = parser.getBuilder().getIndexType(); OpAsmParser::OperandType numElementsInfo; // Parse tag memref, its indices, and dma size. if (parser.parseOperand(tagMemrefInfo) || parser.parseOperandList(tagIndexInfos, OpAsmParser::Delimiter::Square) || parser.parseComma() || parser.parseOperand(numElementsInfo) || parser.parseColonType(type) || parser.resolveOperand(tagMemrefInfo, type, result.operands) || parser.resolveOperands(tagIndexInfos, indexType, result.operands) || parser.resolveOperand(numElementsInfo, indexType, result.operands)) return failure(); auto memrefType = type.dyn_cast<MemRefType>(); if (!memrefType) return parser.emitError(parser.getNameLoc(), "expected tag to be of memref type"); if (static_cast<int64_t>(tagIndexInfos.size()) != memrefType.getRank()) return parser.emitError(parser.getNameLoc(), "tag memref rank not equal to indices count"); return success(); } void DmaWaitOp::getCanonicalizationPatterns(OwningRewritePatternList &results, MLIRContext *context) { /// dma_wait(memrefcast) -> dma_wait results.insert<MemRefCastFolder>(getOperationName(), context); } //===----------------------------------------------------------------------===// // ExtractElementOp //===----------------------------------------------------------------------===// static void print(OpAsmPrinter &p, ExtractElementOp op) { p << "extract_element " << *op.getAggregate() << '['; p.printOperands(op.getIndices()); p << ']'; p.printOptionalAttrDict(op.getAttrs()); p << " : " << op.getAggregate()->getType(); } static ParseResult parseExtractElementOp(OpAsmParser &parser, OperationState &result) { OpAsmParser::OperandType aggregateInfo; SmallVector<OpAsmParser::OperandType, 4> indexInfo; ShapedType type; auto indexTy = parser.getBuilder().getIndexType(); return failure( parser.parseOperand(aggregateInfo) || parser.parseOperandList(indexInfo, OpAsmParser::Delimiter::Square) || parser.parseOptionalAttributeDict(result.attributes) || parser.parseColonType(type) || parser.resolveOperand(aggregateInfo, type, result.operands) || parser.resolveOperands(indexInfo, indexTy, result.operands) || parser.addTypeToList(type.getElementType(), result.types)); } static LogicalResult verify(ExtractElementOp op) { auto aggregateType = op.getAggregate()->getType().cast<ShapedType>(); // This should be possible with tablegen type constraints if (op.getType() != aggregateType.getElementType()) return op.emitOpError("result type must match element type of aggregate"); // Verify the # indices match if we have a ranked type. if (aggregateType.hasRank() && aggregateType.getRank() != op.getNumOperands() - 1) return op.emitOpError("incorrect number of indices for extract_element"); return success(); } OpFoldResult ExtractElementOp::fold(ArrayRef<Attribute> operands) { assert(!operands.empty() && "extract_element takes at least one operand"); // The aggregate operand must be a known constant. Attribute aggregate = operands.front(); if (!aggregate) return {}; // If this is a splat elements attribute, simply return the value. All of the // elements of a splat attribute are the same. if (auto splatAggregate = aggregate.dyn_cast<SplatElementsAttr>()) return splatAggregate.getSplatValue(); // Otherwise, collect the constant indices into the aggregate. SmallVector<uint64_t, 8> indices; for (Attribute indice : llvm::drop_begin(operands, 1)) { if (!indice || !indice.isa<IntegerAttr>()) return {}; indices.push_back(indice.cast<IntegerAttr>().getInt()); } // If this is an elements attribute, query the value at the given indices. auto elementsAttr = aggregate.dyn_cast<ElementsAttr>(); if (elementsAttr && elementsAttr.isValidIndex(indices)) return elementsAttr.getValue(indices); return {}; } //===----------------------------------------------------------------------===// // IndexCastOp //===----------------------------------------------------------------------===// // Index cast is applicable from index to integer and backwards. bool IndexCastOp::areCastCompatible(Type a, Type b) { return (a.isIndex() && b.isa<IntegerType>()) || (a.isa<IntegerType>() && b.isIndex()); } //===----------------------------------------------------------------------===// // LoadOp //===----------------------------------------------------------------------===// static void print(OpAsmPrinter &p, LoadOp op) { p << "load " << *op.getMemRef() << '['; p.printOperands(op.getIndices()); p << ']'; p.printOptionalAttrDict(op.getAttrs()); p << " : " << op.getMemRefType(); } static ParseResult parseLoadOp(OpAsmParser &parser, OperationState &result) { OpAsmParser::OperandType memrefInfo; SmallVector<OpAsmParser::OperandType, 4> indexInfo; MemRefType type; auto indexTy = parser.getBuilder().getIndexType(); return failure( parser.parseOperand(memrefInfo) || parser.parseOperandList(indexInfo, OpAsmParser::Delimiter::Square) || parser.parseOptionalAttributeDict(result.attributes) || parser.parseColonType(type) || parser.resolveOperand(memrefInfo, type, result.operands) || parser.resolveOperands(indexInfo, indexTy, result.operands) || parser.addTypeToList(type.getElementType(), result.types)); } static LogicalResult verify(LoadOp op) { if (op.getType() != op.getMemRefType().getElementType()) return op.emitOpError("result type must match element type of memref"); if (op.getNumOperands() != 1 + op.getMemRefType().getRank()) return op.emitOpError("incorrect number of indices for load"); return success(); } void LoadOp::getCanonicalizationPatterns(OwningRewritePatternList &results, MLIRContext *context) { /// load(memrefcast) -> load results.insert<MemRefCastFolder>(getOperationName(), context); } //===----------------------------------------------------------------------===// // MemRefCastOp //===----------------------------------------------------------------------===// bool MemRefCastOp::areCastCompatible(Type a, Type b) { auto aT = a.dyn_cast<MemRefType>(); auto bT = b.dyn_cast<MemRefType>(); if (!aT || !bT) return false; if (aT.getElementType() != bT.getElementType()) return false; if (aT.getAffineMaps() != bT.getAffineMaps()) return false; if (aT.getMemorySpace() != bT.getMemorySpace()) return false; // They must have the same rank, and any specified dimensions must match. if (aT.getRank() != bT.getRank()) return false; for (unsigned i = 0, e = aT.getRank(); i != e; ++i) { int64_t aDim = aT.getDimSize(i), bDim = bT.getDimSize(i); if (aDim != -1 && bDim != -1 && aDim != bDim) return false; } return true; } OpFoldResult MemRefCastOp::fold(ArrayRef<Attribute> operands) { return impl::foldCastOp(*this); } //===----------------------------------------------------------------------===// // MulFOp //===----------------------------------------------------------------------===// OpFoldResult MulFOp::fold(ArrayRef<Attribute> operands) { return constFoldBinaryOp<FloatAttr>( operands, [](APFloat a, APFloat b) { return a * b; }); } //===----------------------------------------------------------------------===// // MulIOp //===----------------------------------------------------------------------===// OpFoldResult MulIOp::fold(ArrayRef<Attribute> operands) { /// muli(x, 0) -> 0 if (matchPattern(rhs(), m_Zero())) return rhs(); /// muli(x, 1) -> x if (matchPattern(rhs(), m_One())) return getOperand(0); // TODO: Handle the overflow case. return constFoldBinaryOp<IntegerAttr>(operands, [](APInt a, APInt b) { return a * b; }); } //===----------------------------------------------------------------------===// // RankOp //===----------------------------------------------------------------------===// static void print(OpAsmPrinter &p, RankOp op) { p << "rank " << *op.getOperand() << " : " << op.getOperand()->getType(); } static ParseResult parseRankOp(OpAsmParser &parser, OperationState &result) { OpAsmParser::OperandType operandInfo; Type type; Type indexType = parser.getBuilder().getIndexType(); return failure(parser.parseOperand(operandInfo) || parser.parseColonType(type) || parser.resolveOperand(operandInfo, type, result.operands) || parser.addTypeToList(indexType, result.types)); } OpFoldResult RankOp::fold(ArrayRef<Attribute> operands) { // Constant fold rank when the rank of the tensor is known. auto type = getOperand()->getType(); if (auto tensorType = type.dyn_cast<RankedTensorType>()) return IntegerAttr::get(IndexType::get(getContext()), tensorType.getRank()); return IntegerAttr(); } //===----------------------------------------------------------------------===// // RemISOp //===----------------------------------------------------------------------===// OpFoldResult RemISOp::fold(ArrayRef<Attribute> operands) { assert(operands.size() == 2 && "remis takes two operands"); auto rhs = operands.back().dyn_cast_or_null<IntegerAttr>(); if (!rhs) return {}; auto rhsValue = rhs.getValue(); // x % 1 = 0 if (rhsValue.isOneValue()) return IntegerAttr::get(rhs.getType(), APInt(rhsValue.getBitWidth(), 0)); // Don't fold if it requires division by zero. if (rhsValue.isNullValue()) return {}; auto lhs = operands.front().dyn_cast_or_null<IntegerAttr>(); if (!lhs) return {}; return IntegerAttr::get(lhs.getType(), lhs.getValue().srem(rhsValue)); } //===----------------------------------------------------------------------===// // RemIUOp //===----------------------------------------------------------------------===// OpFoldResult RemIUOp::fold(ArrayRef<Attribute> operands) { assert(operands.size() == 2 && "remiu takes two operands"); auto rhs = operands.back().dyn_cast_or_null<IntegerAttr>(); if (!rhs) return {}; auto rhsValue = rhs.getValue(); // x % 1 = 0 if (rhsValue.isOneValue()) return IntegerAttr::get(rhs.getType(), APInt(rhsValue.getBitWidth(), 0)); // Don't fold if it requires division by zero. if (rhsValue.isNullValue()) return {}; auto lhs = operands.front().dyn_cast_or_null<IntegerAttr>(); if (!lhs) return {}; return IntegerAttr::get(lhs.getType(), lhs.getValue().urem(rhsValue)); } //===----------------------------------------------------------------------===// // ReturnOp //===----------------------------------------------------------------------===// static ParseResult parseReturnOp(OpAsmParser &parser, OperationState &result) { SmallVector<OpAsmParser::OperandType, 2> opInfo; SmallVector<Type, 2> types; llvm::SMLoc loc = parser.getCurrentLocation(); return failure(parser.parseOperandList(opInfo) || (!opInfo.empty() && parser.parseColonTypeList(types)) || parser.resolveOperands(opInfo, types, loc, result.operands)); } static void print(OpAsmPrinter &p, ReturnOp op) { p << "return"; if (op.getNumOperands() != 0) { p << ' '; p.printOperands(op.getOperands()); p << " : "; interleaveComma(op.getOperandTypes(), p); } } static LogicalResult verify(ReturnOp op) { auto function = cast<FuncOp>(op.getParentOp()); // The operand number and types must match the function signature. const auto &results = function.getType().getResults(); if (op.getNumOperands() != results.size()) return op.emitOpError("has ") << op.getNumOperands() << " operands, but enclosing function returns " << results.size(); for (unsigned i = 0, e = results.size(); i != e; ++i) if (op.getOperand(i)->getType() != results[i]) return op.emitError() << "type of return operand " << i << " (" << op.getOperand(i)->getType() << ") doesn't match function result type (" << results[i] << ")"; return success(); } //===----------------------------------------------------------------------===// // SIToFPOp //===----------------------------------------------------------------------===// // sitofp is applicable from integer types to float types. bool SIToFPOp::areCastCompatible(Type a, Type b) { return a.isa<IntegerType>() && b.isa<FloatType>(); } //===----------------------------------------------------------------------===// // SelectOp //===----------------------------------------------------------------------===// static ParseResult parseSelectOp(OpAsmParser &parser, OperationState &result) { SmallVector<OpAsmParser::OperandType, 3> ops; SmallVector<NamedAttribute, 4> attrs; Type type; if (parser.parseOperandList(ops, 3) || parser.parseOptionalAttributeDict(result.attributes) || parser.parseColonType(type)) return failure(); auto i1Type = getCheckedI1SameShape(&parser.getBuilder(), type); if (!i1Type) return parser.emitError(parser.getNameLoc(), "expected type with valid i1 shape"); SmallVector<Type, 3> types = {i1Type, type, type}; return failure(parser.resolveOperands(ops, types, parser.getNameLoc(), result.operands) || parser.addTypeToList(type, result.types)); } static void print(OpAsmPrinter &p, SelectOp op) { p << "select "; p.printOperands(op.getOperands()); p << " : " << op.getTrueValue()->getType(); p.printOptionalAttrDict(op.getAttrs()); } static LogicalResult verify(SelectOp op) { auto trueType = op.getTrueValue()->getType(); auto falseType = op.getFalseValue()->getType(); if (trueType != falseType) return op.emitOpError( "requires 'true' and 'false' arguments to be of the same type"); return success(); } OpFoldResult SelectOp::fold(ArrayRef<Attribute> operands) { auto *condition = getCondition(); // select true, %0, %1 => %0 if (matchPattern(condition, m_One())) return getTrueValue(); // select false, %0, %1 => %1 if (matchPattern(condition, m_Zero())) return getFalseValue(); return nullptr; } //===----------------------------------------------------------------------===// // SignExtendIOp //===----------------------------------------------------------------------===// static LogicalResult verify(SignExtendIOp op) { // Get the scalar type (which is either directly the type of the operand // or the vector's/tensor's element type. auto srcType = getElementTypeOrSelf(op.getOperand()->getType()); auto dstType = getElementTypeOrSelf(op.getType()); // For now, index is forbidden for the source and the destination type. if (srcType.isa<IndexType>()) return op.emitError() << srcType << " is not a valid operand type"; if (dstType.isa<IndexType>()) return op.emitError() << dstType << " is not a valid result type"; if (srcType.cast<IntegerType>().getWidth() >= dstType.cast<IntegerType>().getWidth()) return op.emitError("result type ") << dstType << " must be wider than operand type " << srcType; return success(); } //===----------------------------------------------------------------------===// // SplatOp //===----------------------------------------------------------------------===// static void print(OpAsmPrinter &p, SplatOp op) { p << "splat " << *op.getOperand(); p.printOptionalAttrDict(op.getAttrs()); p << " : " << op.getType(); } static ParseResult parseSplatOp(OpAsmParser &parser, OperationState &result) { OpAsmParser::OperandType splatValueInfo; ShapedType shapedType; return failure(parser.parseOperand(splatValueInfo) || parser.parseOptionalAttributeDict(result.attributes) || parser.parseColonType(shapedType) || parser.resolveOperand(splatValueInfo, shapedType.getElementType(), result.operands) || parser.addTypeToList(shapedType, result.types)); } static LogicalResult verify(SplatOp op) { // TODO: we could replace this by a trait. if (op.getOperand()->getType() != op.getType().cast<ShapedType>().getElementType()) return op.emitError("operand should be of elemental type of result type"); return success(); } // Constant folding hook for SplatOp. OpFoldResult SplatOp::fold(ArrayRef<Attribute> operands) { assert(operands.size() == 1 && "splat takes one operand"); auto constOperand = operands.front(); if (!constOperand || (!constOperand.isa<IntegerAttr>() && !constOperand.isa<FloatAttr>())) return {}; auto shapedType = getType().cast<ShapedType>(); assert(shapedType.getElementType() == constOperand.getType() && "incorrect input attribute type for folding"); // SplatElementsAttr::get treats single value for second arg as being a splat. return SplatElementsAttr::get(shapedType, {constOperand}); } //===----------------------------------------------------------------------===// // StoreOp //===----------------------------------------------------------------------===// static void print(OpAsmPrinter &p, StoreOp op) { p << "store " << *op.getValueToStore(); p << ", " << *op.getMemRef() << '['; p.printOperands(op.getIndices()); p << ']'; p.printOptionalAttrDict(op.getAttrs()); p << " : " << op.getMemRefType(); } static ParseResult parseStoreOp(OpAsmParser &parser, OperationState &result) { OpAsmParser::OperandType storeValueInfo; OpAsmParser::OperandType memrefInfo; SmallVector<OpAsmParser::OperandType, 4> indexInfo; MemRefType memrefType; auto indexTy = parser.getBuilder().getIndexType(); return failure( parser.parseOperand(storeValueInfo) || parser.parseComma() || parser.parseOperand(memrefInfo) || parser.parseOperandList(indexInfo, OpAsmParser::Delimiter::Square) || parser.parseOptionalAttributeDict(result.attributes) || parser.parseColonType(memrefType) || parser.resolveOperand(storeValueInfo, memrefType.getElementType(), result.operands) || parser.resolveOperand(memrefInfo, memrefType, result.operands) || parser.resolveOperands(indexInfo, indexTy, result.operands)); } static LogicalResult verify(StoreOp op) { // First operand must have same type as memref element type. if (op.getValueToStore()->getType() != op.getMemRefType().getElementType()) return op.emitOpError( "first operand must have same type memref element type"); if (op.getNumOperands() != 2 + op.getMemRefType().getRank()) return op.emitOpError("store index operand count not equal to memref rank"); return success(); } void StoreOp::getCanonicalizationPatterns(OwningRewritePatternList &results, MLIRContext *context) { /// store(memrefcast) -> store results.insert<MemRefCastFolder>(getOperationName(), context); } //===----------------------------------------------------------------------===// // SubFOp //===----------------------------------------------------------------------===// OpFoldResult SubFOp::fold(ArrayRef<Attribute> operands) { return constFoldBinaryOp<FloatAttr>( operands, [](APFloat a, APFloat b) { return a - b; }); } //===----------------------------------------------------------------------===// // SubIOp //===----------------------------------------------------------------------===// OpFoldResult SubIOp::fold(ArrayRef<Attribute> operands) { // subi(x,x) -> 0 if (getOperand(0) == getOperand(1)) return Builder(getContext()).getZeroAttr(getType()); return constFoldBinaryOp<IntegerAttr>(operands, [](APInt a, APInt b) { return a - b; }); } //===----------------------------------------------------------------------===// // AndOp //===----------------------------------------------------------------------===// OpFoldResult AndOp::fold(ArrayRef<Attribute> operands) { /// and(x, 0) -> 0 if (matchPattern(rhs(), m_Zero())) return rhs(); /// and(x,x) -> x if (lhs() == rhs()) return rhs(); return constFoldBinaryOp<IntegerAttr>(operands, [](APInt a, APInt b) { return a & b; }); } //===----------------------------------------------------------------------===// // OrOp //===----------------------------------------------------------------------===// OpFoldResult OrOp::fold(ArrayRef<Attribute> operands) { /// or(x, 0) -> x if (matchPattern(rhs(), m_Zero())) return lhs(); /// or(x,x) -> x if (lhs() == rhs()) return rhs(); return constFoldBinaryOp<IntegerAttr>(operands, [](APInt a, APInt b) { return a | b; }); } //===----------------------------------------------------------------------===// // XOrOp //===----------------------------------------------------------------------===// OpFoldResult XOrOp::fold(ArrayRef<Attribute> operands) { /// xor(x, 0) -> x if (matchPattern(rhs(), m_Zero())) return lhs(); /// xor(x,x) -> 0 if (lhs() == rhs()) return Builder(getContext()).getZeroAttr(getType()); return constFoldBinaryOp<IntegerAttr>(operands, [](APInt a, APInt b) { return a ^ b; }); } //===----------------------------------------------------------------------===// // TensorCastOp //===----------------------------------------------------------------------===// bool TensorCastOp::areCastCompatible(Type a, Type b) { auto aT = a.dyn_cast<TensorType>(); auto bT = b.dyn_cast<TensorType>(); if (!aT || !bT) return false; if (aT.getElementType() != bT.getElementType()) return false; // If the either are unranked, then the cast is valid. auto aRType = aT.dyn_cast<RankedTensorType>(); auto bRType = bT.dyn_cast<RankedTensorType>(); if (!aRType || !bRType) return true; // If they are both ranked, they have to have the same rank, and any specified // dimensions must match. if (aRType.getRank() != bRType.getRank()) return false; for (unsigned i = 0, e = aRType.getRank(); i != e; ++i) { int64_t aDim = aRType.getDimSize(i), bDim = bRType.getDimSize(i); if (aDim != -1 && bDim != -1 && aDim != bDim) return false; } return true; } OpFoldResult TensorCastOp::fold(ArrayRef<Attribute> operands) { return impl::foldCastOp(*this); } //===----------------------------------------------------------------------===// // Helpers for Tensor[Load|Store]Op //===----------------------------------------------------------------------===// static Type getTensorTypeFromMemRefType(Builder &b, Type type) { if (auto memref = type.dyn_cast<MemRefType>()) return b.getTensorType(memref.getShape(), memref.getElementType()); return b.getNoneType(); } //===----------------------------------------------------------------------===// // TensorLoadOp //===----------------------------------------------------------------------===// static void print(OpAsmPrinter &p, TensorLoadOp op) { p << "tensor_load " << *op.getOperand(); p.printOptionalAttrDict(op.getAttrs()); p << " : " << op.getOperand()->getType(); } static ParseResult parseTensorLoadOp(OpAsmParser &parser, OperationState &result) { OpAsmParser::OperandType op; Type type; return failure(parser.parseOperand(op) || parser.parseOptionalAttributeDict(result.attributes) || parser.parseColonType(type) || parser.resolveOperand(op, type, result.operands) || parser.addTypeToList( getTensorTypeFromMemRefType(parser.getBuilder(), type), result.types)); } //===----------------------------------------------------------------------===// // TensorStoreOp //===----------------------------------------------------------------------===// static void print(OpAsmPrinter &p, TensorStoreOp op) { p << "tensor_store " << *op.tensor() << ", " << *op.memref(); p.printOptionalAttrDict(op.getAttrs()); p << " : " << op.memref()->getType(); } static ParseResult parseTensorStoreOp(OpAsmParser &parser, OperationState &result) { SmallVector<OpAsmParser::OperandType, 2> ops; Type type; llvm::SMLoc loc = parser.getCurrentLocation(); return failure( parser.parseOperandList(ops, /*requiredOperandCount=*/2) || parser.parseOptionalAttributeDict(result.attributes) || parser.parseColonType(type) || parser.resolveOperands( ops, {getTensorTypeFromMemRefType(parser.getBuilder(), type), type}, loc, result.operands)); } //===----------------------------------------------------------------------===// // TruncateIOp //===----------------------------------------------------------------------===// static LogicalResult verify(TruncateIOp op) { auto srcType = getElementTypeOrSelf(op.getOperand()->getType()); auto dstType = getElementTypeOrSelf(op.getType()); if (srcType.isa<IndexType>()) return op.emitError() << srcType << " is not a valid operand type"; if (dstType.isa<IndexType>()) return op.emitError() << dstType << " is not a valid result type"; if (srcType.cast<IntegerType>().getWidth() <= dstType.cast<IntegerType>().getWidth()) return op.emitError("operand type ") << srcType << " must be wider than result type " << dstType; return success(); } //===----------------------------------------------------------------------===// // ZeroExtendIOp //===----------------------------------------------------------------------===// static LogicalResult verify(ZeroExtendIOp op) { auto srcType = getElementTypeOrSelf(op.getOperand()->getType()); auto dstType = getElementTypeOrSelf(op.getType()); if (srcType.isa<IndexType>()) return op.emitError() << srcType << " is not a valid operand type"; if (dstType.isa<IndexType>()) return op.emitError() << dstType << " is not a valid result type"; if (srcType.cast<IntegerType>().getWidth() >= dstType.cast<IntegerType>().getWidth()) return op.emitError("result type ") << dstType << " must be wider than operand type " << srcType; return success(); } //===----------------------------------------------------------------------===// // FPExtOp //===----------------------------------------------------------------------===// bool FPExtOp::areCastCompatible(Type a, Type b) { if (auto fa = a.dyn_cast<FloatType>()) if (auto fb = b.dyn_cast<FloatType>()) return fa.getWidth() < fb.getWidth(); return false; } //===----------------------------------------------------------------------===// // FPTruncOp //===----------------------------------------------------------------------===// bool FPTruncOp::areCastCompatible(Type a, Type b) { if (auto fa = a.dyn_cast<FloatType>()) if (auto fb = b.dyn_cast<FloatType>()) return fa.getWidth() > fb.getWidth(); return false; } //===----------------------------------------------------------------------===// // TableGen'd op method definitions //===----------------------------------------------------------------------===// #define GET_OP_CLASSES #include "mlir/Dialect/StandardOps/Ops.cpp.inc"
// generated from rosidl_generator_cpp/resource/msg.hpp.em // generated code does not contain a copyright notice #ifndef GEOMETRY_MSGS__MSG__POINT32_HPP_ #define GEOMETRY_MSGS__MSG__POINT32_HPP_ #include "geometry_msgs/msg/point32__struct.hpp" #include "geometry_msgs/msg/point32__traits.hpp" #endif // GEOMETRY_MSGS__MSG__POINT32_HPP_
#include "document.h" #include "algorithm.h" #include "construct.h" #include "cursor.h" #include "globals.h" #include "line.h" #include "parser.h" #include "text.h" #include <QCursor> #include <QFile> #include <QFileDialog> #include <QGraphicsRectItem> #include <QGraphicsSceneMouseEvent> #include <QKeyEvent> #include <QMenu> #include <QMessageBox> #include <QPainter> #include <QtMath> #include <QtSvg/QSvgGenerator> namespace Typeset{ Document::Document(bool allow_write, bool show_line_numbers, Line* f, Line* b, QString save_path) : save_path(save_path), front(f), back(b), allow_write(allow_write) { double_click_time = QTime::currentTime(); if(front==nullptr){ front = new Line(); front->next = nullptr; front->prev = nullptr; } if(back==nullptr) back = front; addItem(front); front->setPos(0, first_line_vspace); updateSize(); if(!show_line_numbers) setLineNumbersVisible(false); cursor = new Cursor(*this); cv = new CursorView(*this); cv->update(*cursor); undo_stack = new QUndoStack(); } Document::~Document(){ while(undo_stack->canRedo()) //QUndoStack deletion is FIFO, which causes crashes undo() is called undo_stack->redo(); //so that a latter redo() depends on data from an earlier one. delete undo_stack; delete cursor; delete cv; Line* curr = back; while(curr){ Line* prev = curr; curr = curr->prev; prev->deletePostorder(); } } void Document::save(){ if(save_path.isEmpty()) savePrompt(); else saveAs(save_path); } void Document::saveAs(QString save_path){ this->save_path = save_path; QFile file(save_path); if(!file.open(QIODevice::WriteOnly | QIODevice::Text)){ QMessageBox messageBox; messageBox.critical(nullptr, "Error", "Could not open \"" + save_path + "\" to write."); messageBox.setFixedSize(500,200); return; } QTextStream out(&file); out.setCodec("UTF-8"); write(out); } void Document::savePrompt(){ QString file_name = QFileDialog::getSaveFileName(nullptr, tr("Save File"), save_path.isEmpty() ? "./untitled" : save_path, tr("Text (*.txt)")); if(!file_name.isEmpty()) saveAs(file_name); } void Document::printSvgPrompt(){ QString prompt_name = "./" + save_path + ".svg"; QString file_name = QFileDialog::getSaveFileName(nullptr, tr("Export PDF"), prompt_name, tr("SVG (*.svg)")); if(file_name.isEmpty()) return; QRectF bounds = sceneRect(); int x = qCeil(bounds.x()); int y = qCeil(bounds.y()); int w = qCeil(bounds.width()); int h = qCeil(bounds.height()); QSvgGenerator svgGen; svgGen.setFileName(file_name); svgGen.setSize(QSize(w, h)); svgGen.setViewBox(QRect(x, y, w, h)); QPainter painter(&svgGen); render(&painter, bounds); } void Document::setLineNumbersVisible(bool show){ if(show_line_nums == show) return; show_line_nums = show; if(show){ update(); w = w + linebox_width + linebox_offet - horizontal_scroll_padding; setSceneRect(QRectF(-linebox_width-linebox_offet, -margin_top, w, h)); }else{ w = w - linebox_width - linebox_offet + horizontal_scroll_padding; setSceneRect(QRectF(-horizontal_scroll_padding, -margin_top, w, h)); } } void Document::write(QTextStream& out) const{ for(Line* l = front; l; l = l->next) l->write(out); } void Document::updateCursorView(){ cv->update(*cursor); } void Document::updateSize(){ h = margin_top + margin_bot + front->u + front->d; w = front->w; for(Line* l = front->next; l; l = l->next){ h += line_vspace + l->u + l->d; w = qMax(w, l->w); } qreal left_width = show_line_nums ? linebox_width+linebox_offet : horizontal_scroll_padding; w += horizontal_scroll_padding + left_width; setSceneRect(QRectF(-left_width, -margin_top, w, h)); } void Document::copyAsPng(qreal upscale){ QImage image(upscale*sceneRect().size().toSize(), QImage::Format_RGB16); image.fill(palette().base().color()); QPainter painter(&image); render(&painter); QApplication::clipboard()->setImage(image, QClipboard::Clipboard); } void Document::copySelectionAsPng(qreal upscale){ if(!cursor->hasSelection()) return; cursor->copy(); Document doc(true, false); doc.paste(); doc.copyAsPng(upscale); } void Document::drawBackground(QPainter* painter, const QRectF& rect){ QGraphicsScene::drawBackground(painter, rect); if(show_line_nums){ painter->setBrush(palette().window()); painter->setPen(palette().midlight().color()); painter->drawRect(QRectF(-1-linebox_width-linebox_offet, -margin_top-1, linebox_width+1, 1e8)); } } void Document::keyPressEvent(QKeyEvent* e){ #define MATCH(arg) e->matches(QKeySequence::arg) if(allow_write && MATCH(Undo)) undo_stack->undo(); else if(allow_write && MATCH(Redo)) undo_stack->redo(); else if(MATCH(MoveToNextChar)) cursor->moveToNextChar(); else if(MATCH(MoveToPreviousChar)) cursor->moveToPreviousChar(); else if(MATCH(MoveToNextWord)) cursor->moveToNextWord(); else if(MATCH(MoveToPreviousWord)) cursor->moveToPreviousWord(); else if(MATCH(MoveToNextLine)) cursor->moveToNextLine(); else if(MATCH(MoveToPreviousLine)) cursor->moveToPreviousLine(); else if(MATCH(MoveToStartOfLine)) cursor->moveToStartOfLine(); else if(MATCH(MoveToEndOfLine)) cursor->moveToEndOfLine(); else if(MATCH(MoveToStartOfBlock)) cursor->moveToStartOfBlock(); else if(MATCH(MoveToEndOfBlock)) cursor->moveToEndOfBlock(); else if(MATCH(MoveToStartOfDocument)) cursor->moveToStartOfDocument(); else if(MATCH(MoveToEndOfDocument)) cursor->moveToEndOfDocument(); else if(MATCH(SelectNextChar)) cursor->selectNextChar(); else if(MATCH(SelectPreviousChar)) cursor->selectPreviousChar(); else if(MATCH(SelectNextWord)) cursor->selectNextWord(); else if(MATCH(SelectPreviousWord)) cursor->selectPreviousWord(); else if(MATCH(SelectNextLine)) cursor->selectNextLine(); else if(MATCH(SelectPreviousLine)) cursor->selectPreviousLine(); else if(MATCH(SelectStartOfLine)) cursor->selectStartOfLine(); else if(MATCH(SelectEndOfLine)) cursor->selectEndOfLine(); else if(MATCH(SelectStartOfBlock)) cursor->selectStartOfBlock(); else if(MATCH(SelectEndOfBlock)) cursor->selectEndOfBlock(); else if(MATCH(SelectStartOfDocument)) cursor->selectStartOfDocument(); else if(MATCH(SelectEndOfDocument)) cursor->selectEndOfDocument(); else if(MATCH(SelectAll)) cursor->selectAll(); else if(MATCH(Deselect)) cursor->deselect(); else if(allow_write && MATCH(Delete)) cursor->del(); else if(allow_write && MATCH(DeleteEndOfWord)) cursor->deleteEndOfWord(); else if(allow_write && MATCH(DeleteStartOfWord)) cursor->deleteStartOfWord(); else if(allow_write && MATCH(DeleteEndOfLine)) cursor->deleteEndOfLine(); else if(allow_write && MATCH(DeleteCompleteLine)) cursor->deleteCompleteLine(); else if(allow_write && (MATCH(Backspace) || e->key() == 16777219)) cursor->backspace(); //Backspace detection is bugged else if(allow_write && MATCH(InsertLineSeparator)) cursor->insertLineSeparator(); else if(allow_write && MATCH(InsertParagraphSeparator)) cursor->insertParagraphSeparator(); else if(MATCH(Copy)) cursor->copy(); else if(allow_write && MATCH(Cut)) cursor->cut(); else if(allow_write && MATCH(Paste)) cursor->paste(); else if(MATCH(Find)) DO_THIS( "Find" ) else if(MATCH(FindNext)) DO_THIS( "FindNext" ) else if(MATCH(FindPrevious)) DO_THIS( "FindPrevious" ) else if(allow_write && MATCH(Replace)) DO_THIS( "Replace" ) else if(allow_write) processTextInput(e->text()); #undef MATCH cv->update(*cursor); } void Document::mousePressEvent(QGraphicsSceneMouseEvent* e){ double_clicked = false; triple_clicked = false; if(e->buttons() == Qt::LeftButton){ triple_clicked = testTripleClick(e->screenPos()); click_location = e->screenPos(); if(e->scenePos().x() < -linebox_offet) processLineSelection(e->scenePos().y()); else if(triple_clicked) cursor->tripleClick(); else if(e->modifiers() == Qt::ShiftModifier) processLeftShiftClick(e); else processLeftClick(e); }else if(e->buttons() == Qt::RightButton) contextClick(e); cv->update(*cursor); } void Document::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* e){ double_clicked = true; triple_clicked = false; if(e->buttons() != Qt::LeftButton) return; double_click_time = QTime::currentTime(); processLeftClick(e); cursor->doubleClick(); cv->update(*cursor); } void Document::mouseMoveEvent(QGraphicsSceneMouseEvent* e){ if(e->buttons() != Qt::LeftButton) return; if( (click_location - e->screenPos()).manhattanLength() < 2 ) return; bool drag_on_selection = false; //this would require complicated logic to wait for release or drag //when a selection is clicked if(triple_clicked) cursor->lineSelectPoint(e->scenePos()); else if(double_clicked) cursor->wordSelectPoint(e->scenePos()); else if(drag_on_selection) DO_THIS( "selection drag: drag-and-drops a selection" ) else processDrag(e); cv->update(*cursor); } bool Document::testTripleClick(QPointF click_location) const{ //Qt does not support triple-click detection out of the box, //so this defines a workaround based on timing and travel QPointF deviation = click_location - click_location; qreal L1_norm = deviation.x() + deviation.y(); return L1_norm < allowed_triple_click_travel && double_click_time.msecsTo(QTime::currentTime()) < triple_click_period; } void Document::processTextInput(const QString& text){ if(text.isEmpty()) return; const QChar& c = text.front(); if(c.isPrint()) cursor->keystroke(c); } void Document::processLeftClick(QGraphicsSceneMouseEvent* e){ QPointF p = e->scenePos(); QGraphicsItem* item = itemAt(p, QTransform()); if(item==nullptr) processClickMiss(p); else if(Text* t = dynamic_cast<Text*>(item)) cursor->clickText(*t, p.x()); else if(Construct* c = dynamic_cast<Construct*>(item)) cursor->clickConstruct(*c); else if(SubPhrase* sp = dynamic_cast<SubPhrase*>(item)){ if(sp->isEmpty()) cursor->clickText(*sp->front, p.x()); else processClickMiss(p); }else{ DO_THIS("Invalid items can be clicked") processClickMiss(p); } } void Document::processLeftShiftClick(QGraphicsSceneMouseEvent* e){ cursor->selectClickPoint(e->scenePos()); } void Document::contextClick(QGraphicsSceneMouseEvent* e){ QMenu menu; bool clicked_on_selection = cursor->contains(e->scenePos()); if(!clicked_on_selection){ processRightClick(e, menu); cv->update(*cursor); } menu.addSeparator(); QAction* undoAction = menu.addAction("Undo"); QAction* redoAction = menu.addAction("Redo"); connect(undoAction,SIGNAL(triggered()),undo_stack,SLOT(undo())); connect(redoAction,SIGNAL(triggered()),undo_stack,SLOT(redo())); undoAction->setEnabled(undo_stack->canUndo()); redoAction->setEnabled(undo_stack->canRedo()); menu.addSeparator(); QAction* cutAction = menu.addAction("Cut"); QAction* copyAction = menu.addAction("Copy"); QAction* copyImageAction = menu.addAction("Copy as PNG"); QAction* pasteAction = menu.addAction("Paste"); connect(cutAction,SIGNAL(triggered()),this,SLOT(cutSelection())); connect(copyAction,SIGNAL(triggered()),this,SLOT(copySelection())); connect(copyImageAction,SIGNAL(triggered()),this,SLOT(copySelectionAsPng())); connect(pasteAction,SIGNAL(triggered()),this,SLOT(paste())); cutAction->setEnabled(clicked_on_selection); copyAction->setEnabled(clicked_on_selection); copyImageAction->setEnabled(clicked_on_selection); menu.addSeparator(); QAction* selectAllAction = menu.addAction("Select All"); connect(selectAllAction,SIGNAL(triggered()),this,SLOT(selectAll())); menu.exec(e->screenPos()); } void Document::processRightClick(QGraphicsSceneMouseEvent* e, QMenu& menu){ QPointF p = e->scenePos(); QGraphicsItem* item = itemAt(p, QTransform()); if(item==nullptr) processClickMiss(p); else if(Text* t = dynamic_cast<Text*>(item)){ cursor->clickText(*t, p.x()); t->populateMenu(menu); }else if(Construct* c = dynamic_cast<Construct*>(item)){ cursor->clickConstruct(*c); c->populateMenu(menu); }else if(SubPhrase* sp = dynamic_cast<SubPhrase*>(item)){ if(sp->isEmpty()){ cursor->clickText(*sp->front, p.x()); sp->front->populateMenu(menu); } else processClickMiss(p); }else{ processClickMiss(p); DO_THIS("Invalid items can be clicked") } } void Document::processDrag(QGraphicsSceneMouseEvent* e){ click_location = e->screenPos(); cursor->selectClickPoint(e->scenePos()); } void Document::processWordDrag(QGraphicsSceneMouseEvent* e){ click_location = e->screenPos(); } void Document::processLineSelection(qreal y){ double_clicked = false; triple_clicked = true; cursor->tripleClick(Algorithm::lineAtY(*front, y)); } void Document::processClickMiss(QPointF scene_pos){ cursor->clickPoint(scene_pos); } void Document::cutSelection(){ cursor->cut(); } void Document::copySelection(){ cursor->copy(); } void Document::paste(){ cursor->paste(); } void Document::selectAll(){ cursor->selectAll(); } }
#include "catch.hpp" #include "tl/optional.hpp" // Old versions of GCC don't have the correct trait names. Could fix them up if needs be. #if (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ <= 9 && \ !defined(__clang__)) // nothing for now #else TEST_CASE("Triviality", "[bases.triviality]") { REQUIRE(std::is_trivially_copy_constructible<tl::optional<int>>::value); REQUIRE(std::is_trivially_copy_assignable<tl::optional<int>>::value); REQUIRE(std::is_trivially_move_constructible<tl::optional<int>>::value); REQUIRE(std::is_trivially_move_assignable<tl::optional<int>>::value); REQUIRE(std::is_trivially_destructible<tl::optional<int>>::value); { struct T { T(const T&) = default; T(T&&) = default; T& operator=(const T&) = default; T& operator=(T&&) = default; ~T() = default; }; REQUIRE(std::is_trivially_copy_constructible<tl::optional<T>>::value); REQUIRE(std::is_trivially_copy_assignable<tl::optional<T>>::value); REQUIRE(std::is_trivially_move_constructible<tl::optional<T>>::value); REQUIRE(std::is_trivially_move_assignable<tl::optional<T>>::value); REQUIRE(std::is_trivially_destructible<tl::optional<T>>::value); } { struct T { T(const T&){} T(T&&) {}; T& operator=(const T&) { return *this; } T& operator=(T&&) { return *this; }; ~T(){} }; REQUIRE(!std::is_trivially_copy_constructible<tl::optional<T>>::value); REQUIRE(!std::is_trivially_copy_assignable<tl::optional<T>>::value); REQUIRE(!std::is_trivially_move_constructible<tl::optional<T>>::value); REQUIRE(!std::is_trivially_move_assignable<tl::optional<T>>::value); REQUIRE(!std::is_trivially_destructible<tl::optional<T>>::value); } } TEST_CASE("Deletion", "[bases.deletion]") { REQUIRE(std::is_copy_constructible<tl::optional<int>>::value); REQUIRE(std::is_copy_assignable<tl::optional<int>>::value); REQUIRE(std::is_move_constructible<tl::optional<int>>::value); REQUIRE(std::is_move_assignable<tl::optional<int>>::value); REQUIRE(std::is_destructible<tl::optional<int>>::value); { struct T { T(const T&) = default; T(T&&) = default; T& operator=(const T&) = default; T& operator=(T&&) = default; ~T() = default; }; REQUIRE(std::is_copy_constructible<tl::optional<T>>::value); REQUIRE(std::is_copy_assignable<tl::optional<T>>::value); REQUIRE(std::is_move_constructible<tl::optional<T>>::value); REQUIRE(std::is_move_assignable<tl::optional<T>>::value); REQUIRE(std::is_destructible<tl::optional<T>>::value); } { struct T { T(const T&)=delete; T(T&&)=delete; T& operator=(const T&)=delete; T& operator=(T&&)=delete; }; REQUIRE(!std::is_copy_constructible<tl::optional<T>>::value); REQUIRE(!std::is_copy_assignable<tl::optional<T>>::value); REQUIRE(!std::is_move_constructible<tl::optional<T>>::value); REQUIRE(!std::is_move_assignable<tl::optional<T>>::value); } { struct T { T(const T&)=delete; T(T&&)=default; T& operator=(const T&)=delete; T& operator=(T&&)=default; }; REQUIRE(!std::is_copy_constructible<tl::optional<T>>::value); REQUIRE(!std::is_copy_assignable<tl::optional<T>>::value); REQUIRE(std::is_move_constructible<tl::optional<T>>::value); REQUIRE(std::is_move_assignable<tl::optional<T>>::value); } { struct T { T(const T&)=default; T(T&&)=delete; T& operator=(const T&)=default; T& operator=(T&&)=delete; }; REQUIRE(std::is_copy_constructible<tl::optional<T>>::value); REQUIRE(std::is_copy_assignable<tl::optional<T>>::value); } } #endif
#include "../../CK2ToEU4/Source/Mappers/CultureMapper/CultureMapper.h" #include "../../CK2ToEU4/Source/Mappers/RegionMapper/RegionMapper.h" #include "gtest/gtest.h" #include <sstream> TEST(Mappers_CultureMapperTests, nonMatchGivesEmptyOptional) { std::stringstream input; input << "link = { eu4 = culture ck2 = culture }"; const mappers::CultureMapper culMapper(input); ASSERT_FALSE(culMapper.cultureMatch("nonMatchingCulture", "", 0, "")); } TEST(Mappers_CultureMapperTests, simpleCultureMatches) { std::stringstream input; input << "link = { eu4 = culture ck2 = test }"; const mappers::CultureMapper culMapper(input); ASSERT_EQ(*culMapper.cultureMatch("test", "", 0, ""), "culture"); } TEST(Mappers_CultureMapperTests, simpleCultureCorrectlyMatches) { std::stringstream input; input << "link = { eu4 = culture ck2 = qwe ck2 = test ck2 = poi }"; const mappers::CultureMapper culMapper(input); ASSERT_EQ(*culMapper.cultureMatch("test", "", 0, ""), "culture"); } TEST(Mappers_CultureMapperTests, cultureMatchesWithReligion) { std::stringstream input; input << "link = { eu4 = culture ck2 = qwe ck2 = test ck2 = poi religion = thereligion }"; const mappers::CultureMapper culMapper(input); ASSERT_EQ(*culMapper.cultureMatch("test", "thereligion", 0, ""), "culture"); } TEST(Mappers_CultureMapperTests, cultureFailsWithWrongReligion) { std::stringstream input; input << "link = { eu4 = culture ck2 = qwe ck2 = test ck2 = poi religion = thereligion }"; const mappers::CultureMapper culMapper(input); ASSERT_FALSE(culMapper.cultureMatch("test", "unreligion", 0, "")); } TEST(Mappers_CultureMapperTests, cultureMatchesWithCapital) { std::stringstream input; input << "link = { eu4 = culture ck2 = qwe ck2 = test ck2 = poi religion = thereligion province = 4 }"; const mappers::CultureMapper culMapper(input); ASSERT_EQ(*culMapper.cultureMatch("test", "", 4, ""), "culture"); } TEST(Mappers_CultureMapperTests, cultureFailsWithWrongCapital) { std::stringstream input; input << "link = { eu4 = culture ck2 = qwe ck2 = test ck2 = poi religion = thereligion province = 4 }"; const mappers::CultureMapper culMapper(input); ASSERT_FALSE(culMapper.cultureMatch("test", "", 3, "")); } TEST(Mappers_CultureMapperTests, cultureMatchesWithOwnerTag) { std::stringstream input; input << "link = { eu4 = culture ck2 = qwe ck2 = test ck2 = poi religion = thereligion province = 4 owner = TAG }"; const mappers::CultureMapper culMapper(input); ASSERT_EQ(*culMapper.cultureMatch("test", "", 0, "TAG"), "culture"); } TEST(Mappers_CultureMapperTests, cultureFailsWithWrongTag) { std::stringstream input; input << "link = { eu4 = culture ck2 = qwe ck2 = test ck2 = poi religion = thereligion province = 4 owner = TAG }"; const mappers::CultureMapper culMapper(input); ASSERT_FALSE(culMapper.cultureMatch("test", "", 0, "GAT")); } TEST(Mappers_CultureMapperTests, cultureMapperThrowsExceptionWithoutRegionMapper) { std::stringstream input; input << "link = { eu4 = culture ck2 = qwe ck2 = test ck2 = poi religion = thereligion province = 4 owner = TAG region = atlantis }"; const mappers::CultureMapper culMapper(input); try { auto attempt = culMapper.cultureMatch("test", "", 4, ""); FAIL(); } catch (const std::runtime_error& e) { ASSERT_STREQ("Culture Mapper: Region Mapper is unloaded!", e.what()); } } TEST(Mappers_CultureMapperTests, cultureMapperFailsForInvalidRegion) { std::stringstream input; input << "link = { eu4 = culture ck2 = qwe ck2 = test ck2 = poi religion = thereligion owner = TAG region = atlantis }"; mappers::CultureMapper culMapper(input); auto theMapper = std::make_shared<mappers::RegionMapper>(); std::stringstream areaStream; areaStream << "test_area = { 1 2 3 } \n"; areaStream << "test_area2 = { 4 5 6 } "; std::stringstream regionStream; regionStream << "test_region = { areas = { test_area } }"; regionStream << "test_region2 = { areas = { test_area2 } }\n"; std::stringstream superRegionStream; superRegionStream << "test_superregion = { test_region }\n"; superRegionStream << "test_superregion2 = { test_region2 }"; theMapper->loadRegions(areaStream, regionStream, superRegionStream); culMapper.loadRegionMapper(theMapper); ASSERT_FALSE(culMapper.cultureMatch("test", "", 7, "")); } TEST(Mappers_CultureMapperTests, cultureMapperMatchesOnRegion) { std::stringstream input; input << "link = { eu4 = culture ck2 = qwe ck2 = test ck2 = poi religion = thereligion owner = TAG region = test_superregion }"; mappers::CultureMapper culMapper(input); auto theMapper = std::make_shared<mappers::RegionMapper>(); std::stringstream areaStream; areaStream << "test_area = { 1 2 3 } \n"; areaStream << "test_area2 = { 4 5 6 } "; std::stringstream regionStream; regionStream << "test_region = { areas = { test_area } }"; regionStream << "test_region2 = { areas = { test_area2 } }\n"; std::stringstream superRegionStream; superRegionStream << "test_superregion = { test_region }\n"; superRegionStream << "test_superregion2 = { test_region2 }"; theMapper->loadRegions(areaStream, regionStream, superRegionStream); culMapper.loadRegionMapper(theMapper); ASSERT_EQ(*culMapper.cultureMatch("test", "", 1, ""), "culture"); } TEST(Mappers_CultureMapperTests, cultureMapperFailsOnWrongRegion) { std::stringstream input; input << "link = { eu4 = culture ck2 = qwe ck2 = test ck2 = poi religion = thereligion owner = TAG region = test_superregion }"; mappers::CultureMapper culMapper(input); auto theMapper = std::make_shared<mappers::RegionMapper>(); std::stringstream areaStream; areaStream << "test_area = { 1 2 3 } \n"; areaStream << "test_area2 = { 4 5 6 } "; std::stringstream regionStream; regionStream << "test_region = { areas = { test_area } }"; regionStream << "test_region2 = { areas = { test_area2 } }\n"; std::stringstream superRegionStream; superRegionStream << "test_superregion = { test_region }\n"; superRegionStream << "test_superregion2 = { test_region2 }"; theMapper->loadRegions(areaStream, regionStream, superRegionStream); culMapper.loadRegionMapper(theMapper); ASSERT_FALSE(culMapper.cultureMatch("test", "", 6, "")); } TEST(Mappers_CultureMapperTests, TechGroupCanBeRetrieved) { std::stringstream input; input << "link = { eu4 = culture ck2 = qwe ck2 = test ck2 = poi religion = thereligion tech = the_tech }"; const mappers::CultureMapper culMapper(input); ASSERT_EQ(*culMapper.getTechGroup("culture"), "the_tech"); } TEST(Mappers_CultureMapperTests, techGroupFailsForNonsenseCulture) { std::stringstream input; input << "link = { eu4 = culture ck2 = qwe ck2 = test ck2 = poi religion = thereligion tech = the_tech }"; const mappers::CultureMapper culMapper(input); ASSERT_FALSE(culMapper.getTechGroup("nonsense")); } TEST(Mappers_CultureMapperTests, techGroupFailsForMissingTechEntry) { std::stringstream input; input << "link = { eu4 = culture ck2 = qwe ck2 = test ck2 = poi religion = thereligion }"; const mappers::CultureMapper culMapper(input); ASSERT_FALSE(culMapper.getTechGroup("culture")); } TEST(Mappers_CultureMapperTests, GFXCanBeRetrieved) { std::stringstream input; input << "link = { eu4 = culture ck2 = qwe ck2 = test ck2 = poi religion = thereligion gfx = gfxtest }"; const mappers::CultureMapper culMapper(input); ASSERT_EQ(*culMapper.getGFX("culture"), "gfxtest"); } TEST(Mappers_CultureMapperTests, GFXFailsForNonsenseCulture) { std::stringstream input; input << "link = { eu4 = culture ck2 = qwe ck2 = test ck2 = poi religion = thereligion gfx = gfxtest }"; const mappers::CultureMapper culMapper(input); ASSERT_FALSE(culMapper.getGFX("nonsense")); } TEST(Mappers_CultureMapperTests, GFXFailsForMissingTechEntry) { std::stringstream input; input << "link = { eu4 = culture ck2 = qwe ck2 = test ck2 = poi religion = thereligion}"; const mappers::CultureMapper culMapper(input); ASSERT_FALSE(culMapper.getGFX("culture")); }
#include <wayfire/plugin.hpp> #include "wayfire/view.hpp" #include "wayfire/view-transform.hpp" #include "wayfire/output.hpp" #include "wayfire/core.hpp" #include <linux/input.h> static double cross (double x1, double y1, double x2, double y2) // cross product { return x1 * y2 - x2 * y1; } static double vlen(double x1, double y1) // length of vector centered at the origin { return std::sqrt(x1 * x1 + y1 * y1); } class wf_wrot : public wf::plugin_interface_t { wf::button_callback call; int last_x, last_y; wayfire_view current_view; public: void init() override { grab_interface->name = "wrot"; grab_interface->capabilities = wf::CAPABILITY_GRAB_INPUT; call = [=] (uint32_t, int x, int y) { if (!output->activate_plugin(grab_interface)) return false; current_view = wf::get_core().get_cursor_focus_view(); if (!current_view || current_view->role != wf::VIEW_ROLE_TOPLEVEL) { output->deactivate_plugin(grab_interface); return false; } output->focus_view(current_view, true); grab_interface->grab(); last_x = x; last_y = y; return true; }; output->add_button( wf::option_wrapper_t<wf::buttonbinding_t>("wrot/activate"), &call); grab_interface->callbacks.pointer.motion = [=] (int x, int y) { if (!current_view->get_transformer("wrot")) current_view->add_transformer(std::make_unique<wf::view_2D> (current_view), "wrot"); auto tr = dynamic_cast<wf::view_2D*> (current_view->get_transformer("wrot").get()); assert(tr); current_view->damage(); auto g = current_view->get_wm_geometry(); double cx = g.x + g.width / 2.0; double cy = g.y + g.height / 2.0; double x1 = last_x - cx, y1 = last_y - cy; double x2 = x - cx, y2 = y - cy; if (vlen(x2, y2) <= 25) return current_view->pop_transformer("wrot"); /* cross(a, b) = |a| * |b| * sin(a, b) */ tr->angle -= std::asin(cross(x1, y1, x2, y2) / vlen(x1, y1) / vlen(x2, y2)); current_view->damage(); last_x = x; last_y = y; }; grab_interface->callbacks.pointer.button = [=] (uint32_t, uint32_t s) { if (s == WLR_BUTTON_RELEASED) input_released(); }; grab_interface->callbacks.cancel = [=] () { if (grab_interface->is_grabbed()) input_released(); }; } void input_released() { grab_interface->ungrab(); output->deactivate_plugin(grab_interface); } void fini() override { if (grab_interface->is_grabbed()) input_released(); output->rem_binding(&call); } }; DECLARE_WAYFIRE_PLUGIN(wf_wrot);
#include "stereoTools.h" #include <iostream> using D3D::Grid; Grid<double> D3D::computeAD(Mat img1, Mat img2, int minDisp, int maxDisp) { int numDisps = maxDisp-minDisp+1; int numChannels = img1.channels(); double accFact = 1/img1.channels(); Grid<double> ADs(img1.cols, img1.rows, numDisps); int dIdx = 0; for (int d = minDisp; d <= maxDisp; d++) { for (int y = 0; y < img1.rows; y++) { for (int x1 = 0; x1 < img1.cols; x1++) { int x2 = x1-d; if (x2 < 0) x2 = 0; if (x2 >= img2.cols) x2 = img2.cols-1; for (int c = 0; c < img1.channels(); c++) { ADs(x1,y,dIdx) += accFact*(std::abs((double)img1.at<unsigned char>(y,numChannels*x1) - (double)img2.at<unsigned char>(y,numChannels*x2))/(double)255); } } } dIdx++; } return ADs; } D3D::Grid<float> D3D::computeBTLeft(cv::Mat imgL, cv::Mat imgR, int minDisp, int maxDisp, int windowR) { int numDisps = maxDisp-minDisp+1; int numChannels = imgL.channels(); float accFact = 1.0f/numChannels; Grid<float> BTs(imgL.cols, imgR.rows, numDisps); D3D::Grid<float> ILmin(numChannels, imgL.cols); D3D::Grid<float> ILmax(numChannels, imgL.cols); D3D::Grid<float> IRmin(numChannels, imgR.cols); D3D::Grid<float> IRmax(numChannels, imgR.cols); for (int y = 0; y < imgL.rows; y++) { // compute I minus and I plus for (int x = 0; x < imgL.cols; x++) { int xM = (x-1 < 0) ? imgL.cols-1 : x-1; int xP = (x+1 == imgL.cols) ? 0 : x+1; for (int c = 0; c < numChannels; c++) { const float ILm = 0.5f*(imgL.at<unsigned char>(y, numChannels*x + c) + imgL.at<unsigned char>(y, numChannels*xM + c)); const float ILp = 0.5f*(imgL.at<unsigned char>(y, numChannels*x + c) + imgL.at<unsigned char>(y, numChannels*xP + c)); const float IL = imgL.at<unsigned char>(y, numChannels*x + c); ILmin(c,x) = std::min(std::min(ILm,ILp), IL); ILmax(c,x) = std::max(std::max(ILm,ILp), IL); const float IRm = 0.5f*(imgR.at<unsigned char>(y, numChannels*x + c) + imgR.at<unsigned char>(y, numChannels*xM + c)); const float IRp = 0.5f*(imgR.at<unsigned char>(y, numChannels*x + c) + imgR.at<unsigned char>(y, numChannels*xP + c)); const float IR = imgR.at<unsigned char>(y, numChannels*x + c); IRmin(c,x) = std::min(std::min(IRm, IRp), IR); IRmax(c,x) = std::max(std::max(IRm, IRp), IR); } // compute the actual costs float bestBT = 255; for (int d = 0; d < numDisps; d++) { const int disp = d + minDisp; if (x - disp >= 0) { int xR = x - disp; BTs(x,y,d) = 0; for (int c = 0; c < numChannels; c++) { const float dLR = std::max(std::max(0.0f,imgL.at<unsigned char>(y, numChannels*x + c) - IRmax(c,xR)), IRmin(c,xR) - imgL.at<unsigned char>(y, numChannels*x + c)); const float dRL = std::max(std::max(0.0f,imgR.at<unsigned char>(y, numChannels*xR + c) - ILmax(c,x)), ILmin(c,x) - imgR.at<unsigned char>(y, numChannels*xR + c)); BTs(x,y,d) += accFact*std::min(dLR, dRL); } if (BTs(x,y,d) < bestBT) { bestBT = BTs(x,y,d); } } else { BTs(x,y,d) = bestBT + std::min(std::abs(x - disp), 5); } } } } D3D::Grid<float> datacost(BTs.getWidth(), BTs.getHeight(), BTs.getDepth()); // sum up windows for (unsigned int z = 0; z < BTs.getDepth(); z++) for (unsigned int y = 0; y < BTs.getHeight(); y++) for (unsigned int x = 0; x < BTs.getWidth(); x++) { float datacostSum = 0; int numVal = 0; for (int wx = -windowR; wx <= windowR; wx++) for (int wy = -windowR; wy <= windowR; wy++) { const int X = (int) x + (int) wx; const int Y = (int) y + (int) wy; if (X >= 0 && X < (int) datacost.getWidth() && Y >= 0 && Y < (int) datacost.getHeight()) { numVal++; float bestBTInregion = BTs(X,Y,z); // for (int wz = -windowR; wz <= windowR; wz++) // { // const int Z = z + wz; // if (Z >= 0 && Z < (int) BTs.getDepth()) // { // if (wx != 0 && wy != 0 && BTs(X,Y,Z) < bestBTInregion) // { // bestBTInregion = BTs(X,Y,Z); // } // } // } datacostSum += bestBTInregion; } } if (numVal > 0) { datacost(x,y,z) = datacostSum/numVal; } else { datacost(x,y,z) = 0; } } return datacost; } D3D::Grid<float> D3D::computeCensusMatchLeft(cv::Mat imgL, cv::Mat imgR, int minDisp, int maxDisp, int windowR) { int numDisps = maxDisp-minDisp+1; int numChannels = imgL.channels(); // census transform both of the images D3D::Grid<unsigned char> censusLeft(imgL.cols, imgL.rows, numChannels, 0); D3D::Grid<unsigned char> censusRight(imgR.cols, imgR.rows, numChannels, 0); for (unsigned int y = 0; y < censusLeft.getHeight(); y++) for (unsigned int x = 0; x < censusLeft.getWidth(); x++) for (int c = 0; c < numChannels; c++) { int i = 0; for (int xw = -1; xw <= 1; xw++) for (int yw = -1; yw <= 1; yw++) { if (xw != (int) x && yw != (int) y) { const int X = x + xw; const int Y = y + yw; if (X >= 0 && X < (int) censusLeft.getWidth() && Y >= 0 && Y < (int) censusLeft.getHeight()) { if (imgL.at<unsigned char>(y,numChannels*x) > imgL.at<unsigned char>(Y,numChannels*X)) { censusLeft(x,y,c) |= 1 << i; } else { censusLeft(x,y,c) &= ~(1 << i); } if (imgR.at<unsigned char>(y,numChannels*x) > imgR.at<unsigned char>(Y,numChannels*X)) { censusRight(x,y,c) |= 1 << i; } else { censusRight(x,y,c) &= ~(1 << i); } } else { censusLeft(x,y,c) &= ~(1 << i); censusRight(x,y,c) &= ~(1 << i); } i++; } } } // census transform matching D3D::Grid<float> censusMatch(censusLeft.getWidth(), censusRight.getHeight(), numDisps, 0); for (int y = 0; y < imgL.rows; y++) { for (int x = 0; x < imgL.cols; x++) { int dIdx = 0; float bestCensusScore = numChannels*8; int bestCensusDisp = minDisp; for (int d = minDisp; d <= maxDisp; d++) { int xR = x-d; if (xR > 0 && xR < (int) censusLeft.getWidth()) { for (int c = 0; c < numChannels; c++) { unsigned char Xor = censusLeft(x,y,c) ^ censusRight(xR,y,c); censusMatch(x,y,dIdx) += 1.5*(float) __builtin_popcount(Xor); } if (censusMatch(x,y,dIdx) < bestCensusScore) { bestCensusScore = censusMatch(x,y,dIdx); bestCensusDisp = d; } } else { if (d - bestCensusDisp < 5 && bestCensusDisp - d > 0) { censusMatch(x,y,dIdx) = censusMatch(x,y,bestCensusDisp -d)+3.0f; } else { censusMatch(x,y,dIdx) = bestCensusScore +3.0f; } } dIdx++; } } } D3D::Grid<float> datacost(censusMatch.getWidth(), censusMatch.getHeight(), censusMatch.getDepth()); // sum up windows for (unsigned int z = 0; z < censusMatch.getDepth(); z++) for (unsigned int y = 0; y < censusMatch.getHeight(); y++) for (unsigned int x = 0; x < censusMatch.getWidth(); x++) { float datacostSum = 0; int numVal = 0; for (int wx = -windowR; wx <= windowR; wx++) for (int wy = -windowR; wy <= windowR; wy++) { const int X = (int) x + (int) wx; const int Y = (int) y + (int) wy; if (X >= 0 && X < (int) datacost.getWidth() && Y >= 0 && Y < (int) datacost.getHeight()) { numVal++; float bestCensusMatchInregion = censusMatch(X,Y,z); // for (int wz = -windowR; wz <= windowR; wz++) // { // const int Z = z + wz; // if (Z >= 0 && Z < (int) censusMatch.getDepth()) // { // if (wx != 0 && wy != 0 && censusMatch(X,Y,Z) < bestCensusMatchInregion) // { // bestCensusMatchInregion = censusMatch(X,Y,Z); // } // } // } datacostSum += bestCensusMatchInregion; } } if (numVal > 0) { datacost(x,y,z) = datacostSum/numVal; } else { datacost(x,y,z) = 0; } } return datacost; } D3D::Grid<float> D3D::computeSobelMatchLeft(cv::Mat imgL, cv::Mat imgR, int minDisp, int maxDisp, int windowR) { int numDisps = maxDisp-minDisp+1; int numChannels = imgL.channels(); // census transform both of the images D3D::Grid<float> sobelXLeft(imgL.cols, imgL.rows, numChannels, 0); D3D::Grid<float> sobelYLeft(imgL.cols, imgL.rows, numChannels, 0); D3D::Grid<float> sobelXRight(imgL.cols, imgL.rows, numChannels, 0); D3D::Grid<float> sobelYRight(imgL.cols, imgL.rows, numChannels, 0); Eigen::Matrix3f SobelX; SobelX(0,0) = -1; SobelX(0,1) = 0; SobelX(0,2) = 1; SobelX(1,0) = -2; SobelX(1,1) = 0; SobelX(1,2) = 2; SobelX(2,0) = -1; SobelX(2,1) = 0; SobelX(2,2) = 1; Eigen::Matrix3f SobelY = SobelX.transpose(); for (unsigned int y = 0; y < sobelXLeft.getHeight(); y++) for (unsigned int x = 0; x < sobelXLeft.getWidth(); x++) for (int c = 0; c < numChannels; c++) { for (int xw = -1; xw <= 1; xw++) for (int yw = -1; yw <= 1; yw++) { const int X = x + xw; const int Y = y + yw; if (X >= 0 && X < (int) sobelXLeft.getWidth() && Y >= 0 && Y < (int) sobelXLeft.getHeight()) { sobelXLeft(x,y,c) += SobelX(xw+1,yw+1)*imgL.at<unsigned char>(y,numChannels*X); sobelYLeft(x,y,c) += SobelY(xw+1,yw+1)*imgL.at<unsigned char>(y,numChannels*X); sobelXRight(x,y,c) += SobelX(xw+1,yw+1)*imgR.at<unsigned char>(y,numChannels*X); sobelYRight(x,y,c) += SobelY(xw+1,yw+1)*imgR.at<unsigned char>(y,numChannels*X); } } } // census transform matching D3D::Grid<float> sobelMatch(sobelXLeft.getWidth(), sobelXLeft.getHeight(), numDisps, 0); for (int y = 0; y < imgL.rows; y++) { for (int x = 0; x < imgL.cols; x++) { int dIdx = 0; float bestSobelScore = 1e10; int bestScoreDisp = minDisp; for (int d = minDisp; d <= maxDisp; d++) { int xR = x-d; if (xR > 0 && xR < (int) sobelXLeft.getWidth()) { for (int c = 0; c < numChannels; c++) { sobelMatch(x,y,dIdx) += 1/16.0f*(std::fabs(sobelXLeft(x,y) - sobelXRight(xR,y)) + std::fabs(sobelYLeft(x,y) - sobelYRight(xR,y))); } if (sobelMatch(x,y,dIdx) < bestSobelScore) { bestSobelScore = sobelMatch(x,y,dIdx); bestScoreDisp = d; } } else { if (d - bestScoreDisp < 5 && bestScoreDisp - d > 0) { sobelMatch(x,y,dIdx) = sobelMatch(x,y,bestScoreDisp-d)+3.0f; } else { sobelMatch(x,y,dIdx) = bestSobelScore+3.0f; } } dIdx++; } } } D3D::Grid<float> datacost(sobelMatch.getWidth(), sobelMatch.getHeight(), sobelMatch.getDepth()); // sum up windows for (unsigned int z = 0; z < sobelMatch.getDepth(); z++) for (unsigned int y = 0; y < sobelMatch.getHeight(); y++) for (unsigned int x = 0; x < sobelMatch.getWidth(); x++) { float datacostSum = 0; int numVal = 0; for (int wx = -windowR; wx <= windowR; wx++) for (int wy = -windowR; wy <= windowR; wy++) { const int X = (int) x + (int) wx; const int Y = (int) y + (int) wy; if (X >= 0 && X < (int) datacost.getWidth() && Y >= 0 && Y < (int) datacost.getHeight()) { numVal++; float bestSobelMatchInregion = sobelMatch(X,Y,z); // for (int wz = -windowR; wz <= windowR; wz++) // { // const int Z = z + wz; // if (Z >= 0 && Z < (int) sobelMatch.getDepth()) // { // if (wx != 0 && wy != 0 && sobelMatch(X,Y,Z) < bestSobelMatchInregion) // { // bestSobelMatchInregion = sobelMatch(X,Y,Z); // } // } // } datacostSum += bestSobelMatchInregion; } } if (numVal > 0) { datacost(x,y,z) = datacostSum/numVal; } else { datacost(x,y,z) = 0; } } return datacost; }
/* * 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/ListSkillsRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::AlexaForBusiness::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; ListSkillsRequest::ListSkillsRequest() : m_skillGroupArnHasBeenSet(false), m_enablementType(EnablementTypeFilter::NOT_SET), m_enablementTypeHasBeenSet(false), m_skillType(SkillTypeFilter::NOT_SET), m_skillTypeHasBeenSet(false), m_nextTokenHasBeenSet(false), m_maxResults(0), m_maxResultsHasBeenSet(false) { } Aws::String ListSkillsRequest::SerializePayload() const { JsonValue payload; if(m_skillGroupArnHasBeenSet) { payload.WithString("SkillGroupArn", m_skillGroupArn); } if(m_enablementTypeHasBeenSet) { payload.WithString("EnablementType", EnablementTypeFilterMapper::GetNameForEnablementTypeFilter(m_enablementType)); } if(m_skillTypeHasBeenSet) { payload.WithString("SkillType", SkillTypeFilterMapper::GetNameForSkillTypeFilter(m_skillType)); } if(m_nextTokenHasBeenSet) { payload.WithString("NextToken", m_nextToken); } if(m_maxResultsHasBeenSet) { payload.WithInteger("MaxResults", m_maxResults); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection ListSkillsRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AlexaForBusiness.ListSkills")); return headers; }
#include "testlib.h" #include <string> #include <vector> #include <sstream> using namespace std; bool compareWords(string a, string b) { vector<string> va, vb; stringstream sa; sa << a; string cur; while (sa >> cur) va.push_back(cur); stringstream sb; sb << b; while (sb >> cur) vb.push_back(cur); return (va == vb); } int main(int argc, char * argv[]) { setName("compare files as sequence of tokens in lines"); registerTestlibCmd(argc, argv); std::string strAnswer; int n = 0; while (!ans.eof()) { std::string j = ans.readString(); if (j == "" && ans.eof()) break; std::string p = ouf.readString(); strAnswer = p; n++; if (!compareWords(j, p)) quitf(_wa, "%d%s lines differ - expected: '%s', found: '%s'", n, englishEnding(n).c_str(), compress(j).c_str(), compress(p).c_str()); } if (n == 1) quitf(_ok, "single line: '%s'", compress(strAnswer).c_str()); quitf(_ok, "%d lines", n); }
#include "TransectStyleComplexItem.h" #include "MissionItem.h" #include "SettingsFact.h" #include "QGCLoggingCategory.h" #include "SurveyComplexItem.h" #ifndef PARCELLECOMPLEXITEM_H #define PARCELLECOMPLEXITEM_H #include <QObject> Q_DECLARE_LOGGING_CATEGORY(ParcelleComplexItemLog) class ParcelleComplexItem : public SurveyComplexItem { Q_OBJECT public: /// @param vehicle Vehicle which this is being contructed for /// @param flyView true: Created for use in the Fly View, false: Created for use in the Plan View /// @param kmlOrShpFile Polygon comes from this file, empty for default polygon ParcelleComplexItem(Vehicle* vehicle, bool flyView, const QString& kmlOrShpFile, QObject* parent); Q_PROPERTY(Fact* gridAngle READ gridAngle CONSTANT) Q_PROPERTY(Fact* flyAlternateTransects READ flyAlternateTransects CONSTANT) Q_PROPERTY(Fact* splitConcavePolygons READ splitConcavePolygons CONSTANT) Fact* gridAngle (void) { return &_gridAngleFact; } Fact* flyAlternateTransects (void) { return &_flyAlternateTransectsFact; } Fact* splitConcavePolygons (void) { return &_splitConcavePolygonsFact; } Q_INVOKABLE void rotateEntryPoint(void); // Must match json spec for GridEntryLocation enum EntryLocation { EntryLocationFirst, EntryLocationTopLeft = EntryLocationFirst, EntryLocationTopRight, EntryLocationBottomLeft, EntryLocationBottomRight, EntryLocationLast = EntryLocationBottomRight }; static const char* jsonComplexItemTypeValue; static const char* settingsGroup; static const char* gridAngleName; static const char* gridEntryLocationName; static const char* flyAlternateTransectsName; static const char* splitConcavePolygonsName; static const char* jsonV3ComplexItemTypeValue; signals: void refly90DegreesChanged(bool refly90Degrees); private slots: // Overrides from TransectStyleComplexItem // void _rebuildTransectsPhase1 (void) final; // void _recalcComplexDistance (void) final; // void _recalcCameraShots (void) final; private: enum CameraTriggerCode { CameraTriggerNone, CameraTriggerOn, CameraTriggerOff, CameraTriggerHoverAndCapture }; SettingsFact _gridAngleFact; SettingsFact _flyAlternateTransectsFact; SettingsFact _splitConcavePolygonsFact; int _entryPoint; QMap<QString, FactMetaData*> _metaDataMap; static const char* _jsonGridAngleKey; static const char* _jsonEntryPointKey; static const char* _jsonFlyAlternateTransectsKey; static const char* _jsonSplitConcavePolygonsKey; static const char* _jsonV3GridObjectKey; static const char* _jsonV3GridAltitudeKey; static const char* _jsonV3GridAltitudeRelativeKey; static const char* _jsonV3GridAngleKey; static const char* _jsonV3GridSpacingKey; static const char* _jsonV3EntryPointKey; static const char* _jsonV3TurnaroundDistKey; static const char* _jsonV3CameraTriggerDistanceKey; static const char* _jsonV3CameraTriggerInTurnaroundKey; static const char* _jsonV3HoverAndCaptureKey; static const char* _jsonV3GroundResolutionKey; static const char* _jsonV3FrontalOverlapKey; static const char* _jsonV3SideOverlapKey; static const char* _jsonV3CameraSensorWidthKey; static const char* _jsonV3CameraSensorHeightKey; static const char* _jsonV3CameraResolutionWidthKey; static const char* _jsonV3CameraResolutionHeightKey; static const char* _jsonV3CameraFocalLengthKey; static const char* _jsonV3CameraMinTriggerIntervalKey; static const char* _jsonV3ManualGridKey; static const char* _jsonV3CameraObjectKey; static const char* _jsonV3CameraNameKey; static const char* _jsonV3CameraOrientationLandscapeKey; static const char* _jsonV3FixedValueIsAltitudeKey; static const char* _jsonV3Refly90DegreesKey; static const int _hoverAndCaptureDelaySeconds = 4; }; #endif // PARCELLECOMPLEXITEM_H
/* This file is part of the VRender library. Copyright (C) 2005 Cyril Soler (Cyril.Soler@imag.fr) Version 1.0.0, released on June 27, 2005. http://artis.imag.fr/Members/Cyril.Soler/VRender VRender 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. VRender 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 VRender; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */ /**************************************************************************** Copyright (C) 2002-2014 Gilles Debunne. All rights reserved. This file is part of the QGLViewer library version 2.7.1. http://www.libqglviewer.com - contact@libqglviewer.com This file may be used under the terms of the GNU General Public License versions 2.0 or 3.0 as published by the Free Software Foundation and appearing in the LICENSE file included in the packaging of this file. In addition, as a special exception, Gilles Debunne gives you certain additional rights, described in the file GPL_EXCEPTION in this package. libQGLViewer uses dual licensing. Commercial/proprietary software must purchase a libQGLViewer Commercial License. This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. *****************************************************************************/ #ifdef WIN32 # include <windows.h> #endif #ifdef __APPLE__ # include <OpenGL/gl.h> #else # include <GL/gl.h> #endif #include <stdio.h> #include <vector> #include <stdlib.h> #include <string.h> #include "VRender.h" #include "ParserGL.h" #include "Exporter.h" #include "SortMethod.h" #include "Optimizer.h" using namespace vrender ; using namespace std ; void vrender::VectorialRender(RenderCB render_callback, void *callback_params, VRenderParams& vparams) { GLfloat *feedbackBuffer = NULL ; SortMethod *sort_method = NULL ; Exporter *exporter = NULL ; try { GLint returned = -1 ; vparams.error() = 0 ; int nb_renders = 0 ; vparams.progress(0.0, QGLViewer::tr("Rendering...")) ; while(returned < 0) { if(feedbackBuffer != NULL) delete[] feedbackBuffer ; feedbackBuffer = new GLfloat[vparams.size()] ; if(feedbackBuffer == NULL) throw std::runtime_error("Out of memory during feedback buffer allocation.") ; glFeedbackBuffer(vparams.size(), GL_3D_COLOR, feedbackBuffer); glRenderMode(GL_FEEDBACK); render_callback(callback_params); returned = glRenderMode(GL_RENDER); nb_renders++ ; if(returned < 0) vparams.size() *= 2 ; } #ifdef A_VOIR if(SortMethod != EPS_DONT_SORT) { GLint depth_bits ; glGetIntegerv(GL_DEPTH_BITS, &depth_bits) ; EGALITY_EPS = 2.0/(1 << depth_bits) ; LINE_EGALITY_EPS = 2.0/(1 << depth_bits) ; } #endif if (returned > vparams.size()) vparams.size() = returned; #ifdef _VRENDER_DEBUG cout << "Size = " << vparams.size() << ", returned=" << returned << endl ; #endif // On a un beau feedback buffer tout plein de saloperies. Faut aller // defricher tout ca. Ouaiiiis ! vector<PtrPrimitive> primitive_tab ; ParserGL parserGL ; parserGL.parseFeedbackBuffer(feedbackBuffer,returned,primitive_tab,vparams) ; if(feedbackBuffer != NULL) { delete[] feedbackBuffer ; feedbackBuffer = NULL ; } if(vparams.isEnabled(VRenderParams::OptimizeBackFaceCulling)) { BackFaceCullingOptimizer bfopt ; bfopt.optimize(primitive_tab,vparams) ; } // Lance la methode de sorting switch(vparams.sortMethod()) { case VRenderParams::AdvancedTopologicalSort: case VRenderParams::TopologicalSort: { TopologicalSortMethod *tsm = new TopologicalSortMethod() ; tsm->setBreakCycles(vparams.sortMethod() == VRenderParams::AdvancedTopologicalSort) ; sort_method = tsm ; } break ; case VRenderParams::BSPSort: sort_method = new BSPSortMethod() ; break ; case VRenderParams::NoSorting: sort_method = new DontSortMethod() ; break ; default: throw std::runtime_error("Unknown sorting method.") ; } sort_method->sortPrimitives(primitive_tab,vparams) ; // Lance les optimisations. L'ordre est important. if(vparams.isEnabled(VRenderParams::CullHiddenFaces)) { VisibilityOptimizer vopt ; vopt.optimize(primitive_tab,vparams) ; } #ifdef A_FAIRE if(vparams.isEnabled(VRenderParams::OptimizePrimitiveSplit)) { PrimitiveSplitOptimizer psopt ; psopt.optimize(primitive_tab) ; } #endif // Ecrit le fichier switch(vparams.format()) { case VRenderParams::EPS: exporter = new EPSExporter() ; break ; case VRenderParams::PS: exporter = new PSExporter() ; break ; case VRenderParams::XFIG:exporter = new FIGExporter() ; break ; #ifdef A_FAIRE case VRenderParams::SVG: exporter = new SVGExporter() ; break ; #endif default: throw std::runtime_error("Sorry, this output format is not handled now. Only EPS and PS are currently supported.") ; } // sets background and black & white options GLfloat viewport[4],clearColor[4],lineWidth,pointSize ; glGetFloatv(GL_COLOR_CLEAR_VALUE, clearColor); glGetFloatv(GL_LINE_WIDTH, &lineWidth); glGetFloatv(GL_POINT_SIZE, &pointSize); glGetFloatv(GL_VIEWPORT, viewport); lineWidth /= (float)max(viewport[2] - viewport[0],viewport[3]-viewport[1]) ; // Sets which bounding box to use. if(vparams.isEnabled(VRenderParams::TightenBoundingBox)) exporter->setBoundingBox(parserGL.xmin(),parserGL.ymin(),parserGL.xmax(),parserGL.ymax()) ; else exporter->setBoundingBox(viewport[0],viewport[1],viewport[0]+viewport[2],viewport[1]+viewport[3]) ; exporter->setBlackAndWhite(vparams.isEnabled(VRenderParams::RenderBlackAndWhite)) ; exporter->setClearBackground(vparams.isEnabled(VRenderParams::AddBackground)) ; exporter->setClearColor(clearColor[0],clearColor[1],clearColor[2]) ; exporter->exportToFile(vparams.filename(),primitive_tab,vparams) ; // deletes primitives for(unsigned int i=0;i<primitive_tab.size();++i) delete primitive_tab[i] ; if(exporter != NULL) delete exporter ; if(sort_method != NULL) delete sort_method ; } catch(exception& e) { cout << "Render aborted: " << e.what() << endl ; if(exporter != NULL) delete exporter ; if(sort_method != NULL) delete sort_method ; if(feedbackBuffer != NULL) delete[] feedbackBuffer ; throw e ; } } VRenderParams::VRenderParams() { _options = 0 ; _format = EPS ; _filename = "" ; _progress_function = NULL ; _sortMethod = BSPSort ; } VRenderParams::~VRenderParams() {} void VRenderParams::progress(float f, const QString& progress_string) { _progress_function(f,progress_string) ; } void VRenderParams::setFilename(const QString& filename) { _filename = filename; } void VRenderParams::setOption(VRenderOption opt,bool b) { if(b) _options |= opt ; else _options &= ~opt ; } bool VRenderParams::isEnabled(VRenderOption opt) { return (_options & opt) > 0 ; }
#pragma once #include <alc/ast/manager.hpp> #include <alc/ast/expressions.hpp> namespace ast { bool has_var(ast::expression* expr, ast::var* target); }
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "TimeAttack.h" #include "Modules/ModuleManager.h" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, TimeAttack, "TimeAttack" );
/* * Copyright (C) 2013 Google Inc. 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 Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "third_party/blink/renderer/core/layout/subtree_layout_scope.h" #include "third_party/blink/renderer/core/display_lock/display_lock_utilities.h" #include "third_party/blink/renderer/core/frame/local_frame_view.h" #include "third_party/blink/renderer/core/layout/layout_object.h" namespace blink { SubtreeLayoutScope::SubtreeLayoutScope(LayoutObject& root) : root_(root) { CHECK(root_.GetDocument().View()->IsInPerformLayout()); } SubtreeLayoutScope::~SubtreeLayoutScope() { CHECK(!root_.SelfNeedsLayout()); CHECK(!root_.NeedsLayout() || root_.ChildLayoutBlockedByDisplayLock()); #if DCHECK_IS_ON() for (const auto& layout_object : layout_objects_to_layout_) { // There are situations where the object to layout was never laid out, such // as if there was a display-locked descendant of the root and ancestor of // the object which prevented layout. This can happen in quirks mode, where // an ancestor can mark a descendant as dirty through its // PercentHeightDescendants() list, which will not get cleared because // traversal is blocked by a display lock. This finds such cases and allows // these objects to be dirty. if (!DisplayLockUtilities::LockedAncestorPreventingLayout(*layout_object)) layout_object->AssertLaidOut(); layout_object->AssertFragmentTree(); } #endif } void SubtreeLayoutScope::SetNeedsLayout( LayoutObject* descendant, LayoutInvalidationReasonForTracing reason) { DCHECK(descendant->IsDescendantOf(&root_)); descendant->SetNeedsLayout(reason, kMarkContainerChain, this); } void SubtreeLayoutScope::SetChildNeedsLayout(LayoutObject* descendant) { DCHECK(descendant->IsDescendantOf(&root_)); descendant->SetChildNeedsLayout(kMarkContainerChain, this); } void SubtreeLayoutScope::RecordObjectMarkedForLayout( LayoutObject* layout_object) { #if DCHECK_IS_ON() layout_objects_to_layout_.insert(layout_object); #endif } } // namespace blink
// Copyright 2017 The Fuchsia 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 <string.h> #include <cstdio> #include <deque> #include <iomanip> #include <iostream> #include <fuchsia/media/cpp/fidl.h> #include <lib/async-loop/cpp/loop.h> #include <lib/async/cpp/task.h> #include <lib/fit/function.h> #include "lib/component/cpp/startup_context.h" #include "lib/fidl/cpp/optional.h" #include "lib/fsl/tasks/fd_waiter.h" #include "lib/fxl/command_line.h" #include "lib/media/audio/perceived_level.h" namespace media { namespace { static constexpr int kLevelMax = 25; static constexpr char kClearEol[] = "\x1b[K"; static constexpr char kHideCursor[] = "\x1b[?25l"; static constexpr char kShowCursor[] = "\x1b[?25h"; } // namespace using AudioGainInfo = ::fuchsia::media::AudioGainInfo; using AudioDeviceInfo = ::fuchsia::media::AudioDeviceInfo; class EscapeDecoder { public: static constexpr int kUpArrow = -10; static constexpr int kDownArrow = -11; static constexpr int kRightArrow = -12; static constexpr int kLeftArrow = -13; EscapeDecoder() = default; EscapeDecoder(const EscapeDecoder&) = delete; EscapeDecoder(EscapeDecoder&&) = delete; EscapeDecoder& operator=(const EscapeDecoder&) = delete; EscapeDecoder& operator=(EscapeDecoder&&); int Decode(int c) { if (state_ == 2) { state_ = 0; // clang-format off switch (c) { case 'A': return kUpArrow; case 'B': return kDownArrow; case 'C': return kRightArrow; case 'D': return kLeftArrow; default: return 0; } // clang-format on } if (state_ == 1) { state_ = (c == kBracketChar) ? 2 : 0; return 0; } if (c == kEscChar) { state_ = 1; return 0; } return c; } private: static constexpr int kEscChar = 0x1b; static constexpr int kBracketChar = '['; uint32_t state_ = 0; }; class VolApp { public: VolApp(int argc, const char** argv, fit::closure quit_callback) : startup_context_(component::StartupContext::CreateFromStartupInfo()), quit_callback_(std::move(quit_callback)) { FXL_DCHECK(quit_callback_); fxl::CommandLine command_line = fxl::CommandLineFromArgcArgv(argc, argv); if (command_line.HasOption("help") || command_line.HasOption("?")) { Usage(); return; } bool uid_set = false; bool token_set = false; std::string string_value; if (command_line.GetOptionValue("uid", &string_value)) { if (!string_value.length()) { Usage(); return; } selected_uid_ = string_value; uid_set = true; } if (command_line.GetOptionValue("token", &string_value)) { if (uid_set || !Parse(string_value, &selected_token_) || (selected_token_ == ZX_KOID_INVALID)) { Usage(); return; } token_set = true; } if (command_line.HasOption("input")) { if (uid_set || token_set) { Usage(); return; } input_ = true; } if (command_line.HasOption("show")) { non_interactive_actions_.emplace_back([this]() { ShowAllDevices(); }); } if (command_line.GetOptionValue("mute", &string_value)) { BoolAction val; if (!Parse(string_value, &val)) { Usage(); return; } non_interactive_actions_.emplace_back( [this, val]() { SetDeviceMute(val); }); } if (command_line.GetOptionValue("agc", &string_value)) { BoolAction val; if (!Parse(string_value, &val)) { Usage(); return; } non_interactive_actions_.emplace_back( [this, val]() { SetDeviceAgc(val); }); } if (command_line.GetOptionValue("gain", &string_value)) { float val; if (!Parse(string_value, &val)) { Usage(); return; } non_interactive_actions_.emplace_back( [this, val]() { SetDeviceGain(val, false); }); } audio_ = startup_context_->ConnectToEnvironmentService< fuchsia::media::AudioDeviceEnumerator>(); audio_.set_error_handler([this]() { std::cout << "System error: audio service failure"; quit_callback_(); }); // Get this party started by fetching the current list of audio devices. audio_->GetDevices([this](std::vector<AudioDeviceInfo> devices) { OnGetDevices(std::move(devices)); }); } private: enum class BoolAction { kTrue, kFalse, kToggle, }; void InteractiveKeystrokes() { std::cout << " + increase device gain\n"; std::cout << " - decrease device gain\n"; std::cout << " m toggle device mute\n"; std::cout << " a toggle device Automatic Gain Control\n"; std::cout << " enter quit\n"; } void InteractiveUsage() { std::cout << "\ninteractive mode:\n"; InteractiveKeystrokes(); } void Usage() { std::cout << "\nThis tool queries and sets device-level gain/mute/AGC\n"; std::cout << "These changes persist after the tool is closed.\n"; std::cout << "\nvol <args>\n"; std::cout << " --show show system audio status by device\n"; std::cout << " --token=<id> select the device by token\n"; std::cout << " --uid=<uid> select the device by partial UID\n"; std::cout << " --input select the default input device\n"; std::cout << " --gain=<db> set this device's audio gain\n"; std::cout << " --mute=(on|off) mute/unmute this device\n"; std::cout << " --agc=(on|off) enable/disable AGC for this device\n\n"; std::cout << "Given no arguments, vol waits for the following keystrokes:\n"; InteractiveKeystrokes(); std::cout << "\n"; quit_callback_(); } bool Parse(const std::string& string_value, float* float_out) { FXL_DCHECK(float_out); std::istringstream istream(string_value); return (istream >> *float_out) && istream.eof(); } bool Parse(const std::string& string_value, uint64_t* uint_out) { FXL_DCHECK(uint_out); std::istringstream istream(string_value); return (istream >> *uint_out) && istream.eof(); } bool Parse(const std::string& string_value, BoolAction* bool_out) { FXL_DCHECK(bool_out); static const char* TRUE_STRINGS[] = {"yes", "on", "true"}; for (const char* s : TRUE_STRINGS) { if (!strcasecmp(string_value.c_str(), s)) { *bool_out = BoolAction::kTrue; return true; } } static const char* FALSE_STRINGS[] = {"no", "off", "false"}; for (const char* s : FALSE_STRINGS) { if (!strcasecmp(string_value.c_str(), s)) { *bool_out = BoolAction::kFalse; return true; } } return false; } void FormatGainMute(std::ostream& os, const AudioGainInfo& info) { int level = PerceivedLevel::GainToLevel(info.gain_db, kLevelMax); namespace flag = ::fuchsia::media; bool muted = (info.flags & flag::AudioGainInfoFlag_Mute) != 0; bool can_agc = (info.flags & flag::AudioGainInfoFlag_AgcSupported) != 0; bool agc = (info.flags & flag::AudioGainInfoFlag_AgcEnabled) != 0; os << std::string(level, '=') << "|" << std::string(kLevelMax - level, '-') << " :: [" << (muted ? " muted " : "unmuted") << "]" << (can_agc ? (agc ? "[agc]" : "[ ]") : "") << " " << std::fixed << std::setprecision(2) << info.gain_db << " dB"; } // Calls |HandleKeystroke| on the message loop when console input is ready. void WaitForKeystroke() { fd_waiter_.Wait( [this](zx_status_t status, uint32_t events) { HandleKeystroke(); }, 0, POLLIN); } // Handles a keystroke, possibly calling |WaitForKeystroke| to wait for the // next one. void HandleKeystroke() { int c = esc_decoder_.Decode(getc(stdin)); switch (c) { case '+': case EscapeDecoder::kUpArrow: case EscapeDecoder::kRightArrow: SetDeviceGain(1.0, true); break; case '-': case EscapeDecoder::kDownArrow: case EscapeDecoder::kLeftArrow: SetDeviceGain(-1.0, true); break; case 'a': case 'A': SetDeviceAgc(BoolAction::kToggle); break; case 'm': case 'M': SetDeviceMute(BoolAction::kToggle); break; case '\n': case '\r': case 'q': case 'Q': quit_callback_(); std::cout << kShowCursor << "\n" << std::endl; return; default: break; } WaitForKeystroke(); } void ShowAllDevices() { for (const auto& map_entry : devices_) { const auto& dev = map_entry.second; namespace flag = ::fuchsia::media; bool muted = (dev.gain_info.flags & flag::AudioGainInfoFlag_Mute) != 0; bool can_agc = (dev.gain_info.flags & flag::AudioGainInfoFlag_AgcSupported) != 0; bool agc_enb = (dev.gain_info.flags & flag::AudioGainInfoFlag_AgcEnabled) != 0; std::cout << "Audio " << (dev.is_input ? "Input" : "Output") << " (id " << dev.token_id << ")" << std::endl; std::cout << "Name : " << dev.name << std::endl; std::cout << "UID : " << dev.unique_id << std::endl; std::cout << "Default : " << (dev.is_default ? "yes" : "no") << std::endl; std::cout << "Gain : " << dev.gain_info.gain_db << " dB" << std::endl; std::cout << "Mute : " << (muted ? "yes" : "no") << std::endl; if (can_agc) { std::cout << "AGC : " << (agc_enb ? "yes" : "no") << std::endl; } } } void SetDeviceGain(float val, bool relative) { auto iter = devices_.find(control_token_); if (iter == devices_.end()) { if (!interactive()) { std::cout << "No appropriate device found for setting gain" << std::endl; } return; } const auto& dev_state = devices_[control_token_]; AudioGainInfo cmd = dev_state.gain_info; cmd.gain_db = relative ? (cmd.gain_db + val) : val; if (!interactive()) { std::cout << "Setting audio " << (dev_state.is_input ? "input" : "output") << " \"" << dev_state.name << "\" gain to " << std::setprecision(2) << cmd.gain_db << " dB" << std::endl; } audio_->SetDeviceGain(control_token_, std::move(cmd), ::fuchsia::media::SetAudioGainFlag_GainValid); } void SetDeviceMute(BoolAction action) { auto iter = devices_.find(control_token_); if (iter == devices_.end()) { if (!interactive()) { std::cout << "No appropriate device found for setting mute" << std::endl; } return; } const auto& dev_state = devices_[control_token_]; AudioGainInfo cmd = dev_state.gain_info; constexpr uint32_t flag = ::fuchsia::media::AudioGainInfoFlag_Mute; // clang-format off switch (action) { case BoolAction::kTrue: cmd.flags |= flag; break; case BoolAction::kFalse: cmd.flags &= ~flag; break; case BoolAction::kToggle: cmd.flags ^= flag; break; } // clang-format on if (!interactive()) { std::cout << "Setting audio " << (dev_state.is_input ? "input" : "output") << " \"" << dev_state.name << "\" mute to " << ((cmd.flags & flag) ? "on" : "off") << "." << std::endl; } audio_->SetDeviceGain(control_token_, std::move(cmd), ::fuchsia::media::SetAudioGainFlag_MuteValid); } void SetDeviceAgc(BoolAction action) { auto iter = devices_.find(control_token_); if (iter == devices_.end()) { if (!interactive()) { std::cout << "No appropriate device found for setting agc" << std::endl; } return; } const auto& dev_state = devices_[control_token_]; AudioGainInfo cmd = dev_state.gain_info; if (!(cmd.flags & ::fuchsia::media::AudioGainInfoFlag_AgcSupported)) { if (!interactive()) { std::cout << "Audio " << (dev_state.is_input ? "input" : "output") << " \"" << dev_state.name << "\" does not support AGC." << std::endl; } return; } constexpr uint32_t flag = ::fuchsia::media::AudioGainInfoFlag_AgcEnabled; // clang-format off switch (action) { case BoolAction::kTrue: cmd.flags |= flag; break; case BoolAction::kFalse: cmd.flags &= ~flag; break; case BoolAction::kToggle: cmd.flags ^= flag; break; } // clang-format on if (!interactive()) { std::cout << "Setting audio " << (dev_state.is_input ? "input" : "output") << " \"" << dev_state.name << "\" AGC to " << ((cmd.flags & flag) ? "on" : "off") << "." << std::endl; } audio_->SetDeviceGain(control_token_, std::move(cmd), ::fuchsia::media::SetAudioGainFlag_AgcValid); } void ShowSelectedDevice() { if (control_token_ != ZX_KOID_INVALID) { const auto& dev = devices_[control_token_]; std::cout << "\rCurrently controlling audio " << (input_ ? "input" : "output") << " (id " << dev.token_id << "): " << dev.name << std::endl; } else { std::cout << "\rNo appropriate audio " << (input_ ? "input" : "output") << " exists to control" << std::endl; } std::cout << kClearEol << std::flush; } void RedrawInteractiveState() { std::cout << "\r"; if (control_token_ != ZX_KOID_INVALID) { FormatGainMute(std::cout, devices_[control_token_].gain_info); } else { std::cout << "No device selected!"; } std::cout << kClearEol << std::flush; } template <typename T> bool ChooseDeviceToControl(const T& predicate) { uint64_t token = ZX_KOID_INVALID; uint64_t prev_token = control_token_; for (const auto& pair : devices_) { const auto& dev = pair.second; if (predicate(dev)) { token = dev.token_id; break; } } control_token_ = token; return prev_token != control_token_; } bool ChooseDeviceToControl() { if (selected_uid_.length()) { return ChooseDeviceToControl([uid_ptr = selected_uid_.c_str(), uid_len = selected_uid_.length()]( const AudioDeviceInfo& info) -> bool { return (strncmp(info.unique_id.get().c_str(), uid_ptr, uid_len) == 0); }); } else if (selected_token_ != ZX_KOID_INVALID) { return ChooseDeviceToControl( [token = selected_token_](const AudioDeviceInfo& info) -> bool { return info.token_id == token; }); } else { return ChooseDeviceToControl( [input = input_](const AudioDeviceInfo& info) -> bool { return (info.is_input == input) && info.is_default; }); } } void OnGetDevices(std::vector<AudioDeviceInfo> devices) { // Build our device map. for (auto& dev : devices) { auto result = devices_.emplace(std::make_pair(dev.token_id, std::move(dev))); if (!result.second) { std::cerr << "<WARNING>: Duplicate audio device token ID (" << dev.token_id << std::endl; continue; } } // Choose the device we want to control. ChooseDeviceToControl(); if (!interactive()) { // Take the actions requested by the user. for (const auto& action : non_interactive_actions_) { action(); } // Then exit. quit_callback_(); } else { InteractiveUsage(); std::cout << "\n" << kHideCursor; // Install our event hooks so we can keep up with any changes to our // device state. audio_.events().OnDeviceAdded = [this](AudioDeviceInfo dev) { OnDeviceAdded(std::move(dev)); }; audio_.events().OnDeviceRemoved = [this](uint64_t dev_token) { OnDeviceRemoved(dev_token); }; audio_.events().OnDeviceGainChanged = [this](uint64_t dev_token, AudioGainInfo info) { OnDeviceGainChanged(dev_token, info); }; audio_.events().OnDefaultDeviceChanged = [this](uint64_t old_id, uint64_t new_id) { OnDefaultDeviceChanged(old_id, new_id); }; setbuf(stdin, nullptr); WaitForKeystroke(); ShowSelectedDevice(); RedrawInteractiveState(); } } void OnDeviceAdded(AudioDeviceInfo device_to_add, bool skip_update = false) { uint64_t token = device_to_add.token_id; auto result = devices_.emplace(std::make_pair(token, std::move(device_to_add))); if (!result.second) { std::cerr << "\r<WARNING>: Duplicate audio device token ID (" << token << ")" << std::endl; return; } if (!skip_update) { if (ChooseDeviceToControl()) { ShowSelectedDevice(); RedrawInteractiveState(); } } } void OnDeviceRemoved(uint64_t dev_token) { auto iter = devices_.find(dev_token); if (iter == devices_.end()) { std::cerr << "\r<WARNING>: Invalid device token (" << dev_token << ") during device remove notification." << std::endl; return; } devices_.erase(iter); if (ChooseDeviceToControl()) { ShowSelectedDevice(); RedrawInteractiveState(); } } void OnDeviceGainChanged(uint64_t dev_token, AudioGainInfo info) { auto iter = devices_.find(dev_token); if (iter == devices_.end()) { std::cerr << "\r<WARNING>: Invalid device token (" << dev_token << ") during gain changed notification." << std::endl; return; } iter->second.gain_info = std::move(info); if (control_token_ == dev_token) { RedrawInteractiveState(); } } void OnDefaultDeviceChanged(uint64_t old_id, uint64_t new_id) { auto old_iter = devices_.find(old_id); if (old_iter != devices_.end()) { old_iter->second.is_default = false; } auto new_iter = devices_.find(new_id); if (new_iter != devices_.end()) { new_iter->second.is_default = true; } if (ChooseDeviceToControl()) { ShowSelectedDevice(); RedrawInteractiveState(); } } bool interactive() const { return non_interactive_actions_.empty(); } std::unique_ptr<component::StartupContext> startup_context_; fit::closure quit_callback_; std::deque<fit::closure> non_interactive_actions_; fuchsia::media::AudioDeviceEnumeratorPtr audio_; uint64_t control_token_ = ZX_KOID_INVALID; uint64_t selected_token_ = ZX_KOID_INVALID; std::string selected_uid_; bool input_ = false; std::map<uint64_t, AudioDeviceInfo> devices_; EscapeDecoder esc_decoder_; fsl::FDWaiter fd_waiter_; }; } // namespace media int main(int argc, const char** argv) { async::Loop loop(&kAsyncLoopConfigAttachToThread); media::VolApp app(argc, argv, [&loop]() { async::PostTask(loop.dispatcher(), [&loop]() { loop.Quit(); }); }); loop.Run(); return 0; }
#include "Capability.h" #include "LibCapWrapper.h" #include "PamLogging.h" #include <exception> #include <system_error> #include <memory> #include <string.h> Capability::Capability() : m_cap( libcap::cap_init() ) {} Capability::Capability(cap_t cap) : m_cap(cap) {} Capability::Capability(const Capability &rhs) : m_cap(nullptr) { if( rhs.m_cap ) m_cap = libcap::cap_dup(rhs.m_cap); } Capability::~Capability() { try { if(m_cap) destroy(); } catch (std::exception& ex) { pam_log->write_warn("Unable to destroy object capability."); pam_log->write_warn( ex.what()); } } void Capability::destroy() { if(m_cap) libcap::cap_free(m_cap); m_cap = nullptr; } inline cap_t Capability::get() noexcept { return m_cap; } inline const _cap_struct* Capability::get() const noexcept { return m_cap; } Capability& Capability::operator=(const Capability &rhs) { if(this == &rhs) return *this; cap_t old_cap = m_cap; try { if(rhs.m_cap) m_cap = libcap::cap_dup(rhs.m_cap); cap_free(old_cap); return *this; } catch (std::exception& ex) { m_cap = old_cap; throw; } } Capability Capability::from_proc(pid_t pid) { cap_t cap = cap_get_pid(pid); if( !cap ) throw std::system_error( std::error_code(errno, std::generic_category() ), "Unable to get capability for process." ); return Capability(cap); } Capability Capability::from_text(const std::string& text) { cap_t cap = cap_from_text( text.data() ); if( !cap ) throw std::system_error( std::error_code(errno, std::generic_category() ), "Unable to get capability from a text." ); return Capability(cap); } void Capability::set_proc( ) { if( cap_set_proc(m_cap) ) throw std::system_error( std::error_code(errno, std::generic_category() ), "Unable to set capability for process." ); } std::string Capability::to_text() const { ssize_t szText = 0; std::unique_ptr<char, decltype(::cap_free)*> ptrText(cap_to_text(m_cap, &szText), ::cap_free); if (!ptrText) throw std::system_error(std::error_code(errno, std::generic_category()), "Unable to convert capability to text."); return std::string(ptrText.get(), szText); } void Capability::set_inheritable_flag(cap_value_t cap_value) { libcap::cap_set_flag(m_cap, CAP_INHERITABLE, cap_value, CAP_SET); } void Capability::clear_inheritable_flag(cap_value_t cap_value) { libcap::cap_set_flag(m_cap, CAP_INHERITABLE, cap_value, CAP_CLEAR); } bool Capability::is_inheritable_flag_set(cap_value_t cap_value) const { return libcap::cap_is_flag_set(m_cap, cap_value, CAP_INHERITABLE ); } void Capability::set_effective_flag(cap_value_t cap_value) { libcap::cap_set_flag(m_cap, CAP_EFFECTIVE, cap_value, CAP_SET); } void Capability::clear_effective_flag(cap_value_t cap_value) { libcap::cap_set_flag(m_cap, CAP_EFFECTIVE, cap_value, CAP_CLEAR); } bool Capability::is_effective_flag_set(cap_value_t cap_value) const { return libcap::cap_is_flag_set(m_cap, cap_value, CAP_EFFECTIVE ); } void Capability::set_permitted_flag(cap_value_t cap_value) { libcap::cap_set_flag(m_cap, CAP_PERMITTED, cap_value, CAP_SET); } void Capability::clear_permitted_flag(cap_value_t cap_value) { libcap::cap_set_flag(m_cap, CAP_PERMITTED, cap_value, CAP_CLEAR); } bool Capability::is_permitted__flag_set(cap_value_t cap_value) const { return libcap::cap_is_flag_set(m_cap, cap_value, CAP_PERMITTED ); } bool operator == (const Capability& lhs, const Capability& rhs) { if( &lhs == &rhs ) return true; return !cap_compare(lhs.m_cap, rhs.m_cap); }
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2014-2020 The Dash Core developers // Copyright (c) 2020-2022 The Cosanta Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpc/client.h" #include "rpc/protocol.h" #include "util.h" #include <set> #include <stdint.h> #include <univalue.h> class CRPCConvertParam { public: std::string methodName; //!< method whose params want conversion int paramIdx; //!< 0-based idx of param to convert std::string paramName; //!< parameter name }; /** * Specify a (method, idx, name) here if the argument is a non-string RPC * argument and needs to be converted from JSON. * * @note Parameter indexes start from 0. */ static const CRPCConvertParam vRPCConvertParams[] = { { "setmocktime", 0, "timestamp" }, #if ENABLE_MINER { "generate", 0, "nblocks" }, { "generate", 1, "maxtries" }, { "generatetoaddress", 0, "nblocks" }, { "generatetoaddress", 2, "maxtries" }, { "setgenerate", 0, "generate"}, { "setgenerate", 1, "genproclimit"}, #endif // ENABLE_MINER { "getnetworkhashps", 0, "nblocks" }, { "getnetworkhashps", 1, "height" }, { "sendtoaddress", 1, "amount" }, { "sendtoaddress", 4, "subtractfeefromamount" }, { "sendtoaddress", 5, "use_is" }, { "sendtoaddress", 6, "use_ps" }, { "sendtoaddress", 7, "conf_target" }, { "instantsendtoaddress", 1, "address" }, { "instantsendtoaddress", 4, "comment_to" }, { "settxfee", 0, "amount" }, { "getreceivedbyaddress", 1, "minconf" }, { "getreceivedbyaddress", 2, "addlocked" }, { "getreceivedbyaccount", 1, "minconf" }, { "getreceivedbyaccount", 2, "addlocked" }, { "listaddressbalances", 0, "minamount" }, { "listreceivedbyaddress", 0, "minconf" }, { "listreceivedbyaddress", 1, "addlocked" }, { "listreceivedbyaddress", 2, "include_empty" }, { "listreceivedbyaddress", 3, "include_watchonly" }, { "listreceivedbyaccount", 0, "minconf" }, { "listreceivedbyaccount", 1, "addlocked" }, { "listreceivedbyaccount", 2, "include_empty" }, { "listreceivedbyaccount", 3, "include_watchonly" }, { "getbalance", 1, "minconf" }, { "getbalance", 2, "addlocked" }, { "getbalance", 3, "include_watchonly" }, { "getchaintips", 0, "count" }, { "getchaintips", 1, "branchlen" }, { "getblockhash", 0, "height" }, { "getsuperblockbudget", 0, "index" }, { "waitforblockheight", 0, "height" }, { "waitforblockheight", 1, "timeout" }, { "waitforblock", 1, "timeout" }, { "waitfornewblock", 0, "timeout" }, { "move", 2, "amount" }, { "move", 3, "minconf" }, { "sendfrom", 2, "amount" }, { "sendfrom", 3, "minconf" }, { "sendfrom", 4, "addlocked" }, { "listtransactions", 1, "count" }, { "listtransactions", 2, "skip" }, { "listtransactions", 3, "include_watchonly" }, { "listaccounts", 0, "minconf" }, { "listaccounts", 1, "addlocked" }, { "listaccounts", 2, "include_watchonly" }, { "walletpassphrase", 1, "timeout" }, { "walletpassphrase", 2, "mixingonly" }, { "getblocktemplate", 0, "template_request" }, { "listsinceblock", 1, "target_confirmations" }, { "listsinceblock", 2, "include_watchonly" }, { "listsinceblock", 3, "include_removed" }, { "sendmany", 1, "amounts" }, { "sendmany", 2, "minconf" }, { "sendmany", 3, "addlocked" }, { "sendmany", 5, "subtractfeefrom" }, { "sendmany", 6, "use_is" }, { "sendmany", 7, "use_ps" }, { "sendmany", 8, "conf_target" }, { "addmultisigaddress", 0, "nrequired" }, { "addmultisigaddress", 1, "keys" }, { "createmultisig", 0, "nrequired" }, { "createmultisig", 1, "keys" }, { "listunspent", 0, "minconf" }, { "listunspent", 1, "maxconf" }, { "listunspent", 2, "addresses" }, { "listunspent", 3, "include_unsafe" }, { "listunspent", 4, "query_options" }, { "getblock", 1, "verbosity" }, { "getblock", 1, "verbose" }, { "getblockheader", 1, "verbose" }, { "getblockheaders", 1, "count" }, { "getblockheaders", 2, "verbose" }, { "getchaintxstats", 0, "nblocks" }, { "getmerkleblocks", 2, "count" }, { "gettransaction", 1, "include_watchonly" }, { "getrawtransaction", 1, "verbose" }, { "createrawtransaction", 0, "inputs" }, { "createrawtransaction", 1, "outputs" }, { "createrawtransaction", 2, "locktime" }, { "signrawtransaction", 1, "prevtxs" }, { "signrawtransaction", 2, "privkeys" }, { "sendrawtransaction", 1, "allowhighfees" }, { "sendrawtransaction", 2, "instantsend" }, { "sendrawtransaction", 3, "bypasslimits" }, { "combinerawtransaction", 0, "txs" }, { "fundrawtransaction", 1, "options" }, { "gettxout", 1, "n" }, { "gettxout", 2, "include_mempool" }, { "gettxoutproof", 0, "txids" }, { "lockunspent", 0, "unlock" }, { "lockunspent", 1, "transactions" }, { "importprivkey", 2, "rescan" }, { "importelectrumwallet", 1, "index" }, { "importaddress", 2, "rescan" }, { "importaddress", 3, "p2sh" }, { "importpubkey", 2, "rescan" }, { "importmulti", 0, "requests" }, { "importmulti", 1, "options" }, { "verifychain", 0, "checklevel" }, { "verifychain", 1, "nblocks" }, { "getblockstats", 0, "hash_or_height" }, { "getblockstats", 1, "stats" }, { "pruneblockchain", 0, "height" }, { "keypoolrefill", 0, "newsize" }, { "getrawmempool", 0, "verbose" }, { "estimatefee", 0, "nblocks" }, { "estimatesmartfee", 0, "conf_target" }, { "estimaterawfee", 0, "conf_target" }, { "estimaterawfee", 1, "threshold" }, { "prioritisetransaction", 1, "fee_delta" }, { "setban", 2, "bantime" }, { "setban", 3, "absolute" }, { "setnetworkactive", 0, "state" }, { "setprivatesendrounds", 0, "rounds" }, { "setprivatesendamount", 0, "amount" }, { "getmempoolancestors", 1, "verbose" }, { "getmempooldescendants", 1, "verbose" }, { "logging", 0, "include" }, { "logging", 1, "exclude" }, { "spork", 1, "value" }, { "voteraw", 1, "tx_index" }, { "voteraw", 5, "time" }, { "getblockhashes", 0, "high"}, { "getblockhashes", 1, "low" }, { "getspentinfo", 0, "json" }, { "getaddresstxids", 0, "addresses" }, { "getaddressbalance", 0, "addresses" }, { "getaddressdeltas", 0, "addresses" }, { "getaddressutxos", 0, "addresses" }, { "getaddressmempool", 0, "addresses" }, { "getspecialtxes", 1, "type" }, { "getspecialtxes", 2, "count" }, { "getspecialtxes", 3, "skip" }, { "getspecialtxes", 4, "verbosity" }, { "disconnectnode", 1, "nodeid" }, // Echo with conversion (For testing only) { "echojson", 0, "arg0" }, { "echojson", 1, "arg1" }, { "echojson", 2, "arg2" }, { "echojson", 3, "arg3" }, { "echojson", 4, "arg4" }, { "echojson", 5, "arg5" }, { "echojson", 6, "arg6" }, { "echojson", 7, "arg7" }, { "echojson", 8, "arg8" }, { "echojson", 9, "arg9" }, { "reservebalance", 0, "reserve" }, { "reservebalance", 1, "amount" }, { "rescanblockchain", 0, "start_height"}, { "rescanblockchain", 1, "stop_height"}, { "stop", 0, "wait" }, }; class CRPCConvertTable { private: std::set<std::pair<std::string, int>> members; std::set<std::pair<std::string, std::string>> membersByName; public: CRPCConvertTable(); bool convert(const std::string& method, int idx) { return (members.count(std::make_pair(method, idx)) > 0); } bool convert(const std::string& method, const std::string& name) { return (membersByName.count(std::make_pair(method, name)) > 0); } }; CRPCConvertTable::CRPCConvertTable() { const unsigned int n_elem = (sizeof(vRPCConvertParams) / sizeof(vRPCConvertParams[0])); for (unsigned int i = 0; i < n_elem; i++) { members.insert(std::make_pair(vRPCConvertParams[i].methodName, vRPCConvertParams[i].paramIdx)); membersByName.insert(std::make_pair(vRPCConvertParams[i].methodName, vRPCConvertParams[i].paramName)); } } static CRPCConvertTable rpcCvtTable; /** Non-RFC4627 JSON parser, accepts internal values (such as numbers, true, false, null) * as well as objects and arrays. */ UniValue ParseNonRFCJSONValue(const std::string& strVal) { UniValue jVal; if (!jVal.read(std::string("[")+strVal+std::string("]")) || !jVal.isArray() || jVal.size()!=1) throw std::runtime_error(std::string("Error parsing JSON:")+strVal); return jVal[0]; } UniValue RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { UniValue params(UniValue::VARR); for (unsigned int idx = 0; idx < strParams.size(); idx++) { const std::string& strVal = strParams[idx]; if (!rpcCvtTable.convert(strMethod, idx)) { // insert string value directly params.push_back(strVal); } else { // parse string as JSON, insert bool/number/object/etc. value params.push_back(ParseNonRFCJSONValue(strVal)); } } return params; } UniValue RPCConvertNamedValues(const std::string &strMethod, const std::vector<std::string> &strParams) { UniValue params(UniValue::VOBJ); for (const std::string &s: strParams) { size_t pos = s.find('='); if (pos == std::string::npos) { throw(std::runtime_error("No '=' in named argument '"+s+"', this needs to be present for every argument (even if it is empty)")); } std::string name = s.substr(0, pos); std::string value = s.substr(pos+1); if (!rpcCvtTable.convert(strMethod, name)) { // insert string value directly params.pushKV(name, value); } else { // parse string as JSON, insert bool/number/object/etc. value params.pushKV(name, ParseNonRFCJSONValue(value)); } } return params; }
void add_lane_beta_1( beacls::FloatVec& lane, beacls::FloatVec xs, FLOAT_TYPE lane_offset, FLOAT_TYPE lane_width, FLOAT_TYPE theta_offset, FLOAT_TYPE vehicle_width, size_t dim, beacls::FloatVec thetarange, beacls::FloatVec vrange, beacls::FloatVec y2range){ FLOAT_TYPE enhance; enhance = 2.; if (dim == 0){ //reset the default values std::fill(lane.begin(),lane.end(),0.); std::transform(xs.cbegin(), xs.cend(), lane.begin(), lane.begin(), [lane_offset, lane_width, vehicle_width, enhance](const auto &xs_i, const auto &lane_i) { return lane_i + enhance*(1-std::pow(((xs_i - lane_offset)/((lane_width-vehicle_width)/2.)),2)); }); } else if (dim == 1) { // std::transform(xs.cbegin(), xs.cend(), lane.begin(), lane.begin(), // [dim_long_offset, lane_width, vehicle_width, enhance](const auto &xs_i, const auto &lane_i) { // return lane_i - std::pow((xs_i - .7)/1.4,2); }); } else if (dim == 2) { // std::transform(xs.cbegin(), xs.cend(), lane.begin(), lane.begin(), // [theta_offset,enhance](const auto &xs_i, const auto &lane_i) { // return (lane_i - std::pow((theta_diff(xs_i,theta_offset)/(M_PI)),2)); }); for (int i = 0; i <= lane.size()-1; ++i) { if (xs[i]<thetarange[0]-0.0001 || xs[i]>thetarange[1]+0.0001){ lane[i] = -3.; } } } else if (dim == 3) { for (int i = 0; i <= lane.size()-1; ++i) { if (xs[i]<vrange[0]-0.0001 || xs[i]>vrange[1]+0.0001){ lane[i] = -3.; } } } else if (dim == 4) { for (int i = 0; i <= lane.size()-1; ++i) { if (xs[i]<y2range[0]-0.0001 || xs[i]>y2range[1]+0.0001){ lane[i] = -3.;} } } }
/**************************************************************************** * In memory position search - find position in games without database index * Author: Bill Forster * License: MIT license. Full text of license is in associated file LICENSE * Copyright 2010-2014, Bill Forster <billforsternz at gmail dot com> ****************************************************************************/ #include <algorithm> #include <vector> #include <stdlib.h> #include <wx/utils.h> #include "AutoTimer.h" #include "ProgressBar.h" #include "MemoryPositionSearch.h" #include "CompressMoves.h" //temp testing // Note that much of this code duplicates the algorithms implemented // in class CompressMoves - This is because we want to play through games // encoded by CompressMoves extremely quickly - which precludes us using // the slow(ish) CompressMoves code. Well, actually it's not that slow // but it is organised around converting to and from thc::Move which we // don't want to do - we want to act as if the compressed moves are // the native move representation. So in a way we proved that the // ALLOW_CASTLING_EVEN_AFTER_KING_AND_ROOK_MOVES refinement makes sense. // Comment below from CompressMoves implementation; // The ALLOW_CASTLING_EVEN_AFTER_KING_AND_ROOK_MOVES algorithm // anticipates future optimised implementations - Such implementations // might implement making moves using thc::Move independently // and without reference to the thc classes until they are forced // to use slow_mode. Upon transition to slow_mode, such implementations // rely on move generation algorithms, which in turn need to // know whether the kings and rooks have ever moved. Relieve the // future implementation's responsibility of tracking this information // by always acting as if the kings and rooks haven't moved (if they // are on their home squares). This doesn't cause possible illegality // since Compress() only compresses legal moves, so reversing this // with Uncompress() only produces legal moves. #define CODE_KING 0x00 #define CODE_KNIGHT 0x10 #define CODE_ROOK_LO 0x20 #define CODE_ROOK_HI 0x30 #define CODE_BISHOP_DARK 0x40 #define CODE_BISHOP_LIGHT 0x50 #define CODE_QUEEN_ROOK 0x60 #define CODE_QUEEN_BISHOP 0x70 #define CODE_PAWN 0x80 #define CODE_PAWN_0 0x80 #define CODE_PAWN_1 0x90 #define CODE_PAWN_2 0xa0 #define CODE_PAWN_3 0xb0 #define CODE_PAWN_4 0xc0 #define CODE_PAWN_5 0xd0 #define CODE_PAWN_6 0xe0 #define CODE_PAWN_7 0xf0 #define K_VECTOR_N 0x01 #define K_VECTOR_NE 0x02 #define K_VECTOR_E 0x03 #define K_VECTOR_SE 0x04 #define K_VECTOR_S 0x05 #define K_VECTOR_SW 0x06 #define K_VECTOR_W 0x07 #define K_VECTOR_NW 0x08 #define K_K_CASTLING 0x09 #define K_Q_CASTLING 0x0b #define N_VECTOR_NNE 0x00 #define N_VECTOR_NEE 0x01 #define N_VECTOR_SEE 0x02 #define N_VECTOR_SSE 0x03 #define N_VECTOR_SSW 0x04 #define N_VECTOR_SWW 0x05 #define N_VECTOR_NWW 0x06 #define N_VECTOR_NNW 0x07 #define P_DOUBLE 0 // 0000 // 4 non promoting moves #define P_SINGLE 1 // 0001 #define P_LEFT 2 // 0010 #define P_RIGHT 3 // 0011 #define P_QUEEN 0 // dd00 // dd is direction of promoting move one of P_SINGLE, P_LEFT, P_RIGHT #define P_ROOK 1 // dd01 #define P_BISHOP 2 // dd10 #define P_KNIGHT 3 // dd11 #define R_RANK 8 // Rank or file (i.e. rook) codes, this bit set indicates same file (so remaining 3 bits encode rank) #define R_FILE 0 #define B_FALL 8 // Diagonal (i.e. bishop) codes, either RISE/ or FALL\, other 3 bits encode destination file #define B_RISE 0 #define N_HI 8 // CODE_KNIGHT encodes 8 vectors for each of 2 knights (HI and LO) #define N_LO 0 // We are moving towards '.' instead of ' ', but we can't rely on that until // thc.h uses '.' exclusively. So for now we still use space #define STILL_USING_SPACE #ifdef STILL_USING_SPACE #define EMPTY_CHARACTER ' ' #define START_POSITION "rnbqkdnrpppppppp PPPPPPPPRNDQKBNR" // note used of 'd'/'D' for dark squared bishop #else #define EMPTY_CHARACTER '.' #define START_POSITION "rnbqkdnrpppppppp................................PPPPPPPPRNDQKBNR" #endif void MemoryPositionSearch::Init() { in_memory_game_cache.clear(); search_position_set=false; search_source = &in_memory_game_cache; thc::ChessPosition *cp = static_cast<thc::ChessPosition *>(&msi.cr); cp->Init(); msi.cr.squares[ thc::c1 ] = 'D'; // Impose the distinct dark squared bishop = 'd'/'D' convention over the top msi.cr.squares[ thc::f8 ] = 'd'; MpsSide sides[2]; sides[0].white=true; sides[0].fast_mode=false; sides[1].white=false; sides[1].fast_mode=false; TryFastMode( &sides[0]); TryFastMode( &sides[1]); mqi_init.side_white = sides[0]; mqi_init.side_black = sides[1]; msi.sides[0] = sides[0]; msi.sides[1] = sides[0]; memcpy( mqi_init.squares, START_POSITION, 64 ); mq.rank8_ptr = reinterpret_cast<uint64_t*>(&mqi.squares[ 0]); mq.rank7_ptr = reinterpret_cast<uint64_t*>(&mqi.squares[ 8]); mq.rank6_ptr = reinterpret_cast<uint64_t*>(&mqi.squares[16]); mq.rank5_ptr = reinterpret_cast<uint64_t*>(&mqi.squares[24]); mq.rank4_ptr = reinterpret_cast<uint64_t*>(&mqi.squares[32]); mq.rank3_ptr = reinterpret_cast<uint64_t*>(&mqi.squares[40]); mq.rank2_ptr = reinterpret_cast<uint64_t*>(&mqi.squares[48]); mq.rank1_ptr = reinterpret_cast<uint64_t*>(&mqi.squares[56]); mq.rank8_target_ptr = reinterpret_cast<uint64_t*>(&mq.target_squares[ 0]); mq.rank7_target_ptr = reinterpret_cast<uint64_t*>(&mq.target_squares[ 8]); mq.rank6_target_ptr = reinterpret_cast<uint64_t*>(&mq.target_squares[16]); mq.rank5_target_ptr = reinterpret_cast<uint64_t*>(&mq.target_squares[24]); mq.rank4_target_ptr = reinterpret_cast<uint64_t*>(&mq.target_squares[32]); mq.rank3_target_ptr = reinterpret_cast<uint64_t*>(&mq.target_squares[40]); mq.rank2_target_ptr = reinterpret_cast<uint64_t*>(&mq.target_squares[48]); mq.rank1_target_ptr = reinterpret_cast<uint64_t*>(&mq.target_squares[56]); ms.slow_rank8_ptr = reinterpret_cast<uint64_t*>(&msi.cr.squares[ 0]); ms.slow_rank7_ptr = reinterpret_cast<uint64_t*>(&msi.cr.squares[ 8]); ms.slow_rank6_ptr = reinterpret_cast<uint64_t*>(&msi.cr.squares[16]); ms.slow_rank5_ptr = reinterpret_cast<uint64_t*>(&msi.cr.squares[24]); ms.slow_rank4_ptr = reinterpret_cast<uint64_t*>(&msi.cr.squares[32]); ms.slow_rank3_ptr = reinterpret_cast<uint64_t*>(&msi.cr.squares[40]); ms.slow_rank2_ptr = reinterpret_cast<uint64_t*>(&msi.cr.squares[48]); ms.slow_rank1_ptr = reinterpret_cast<uint64_t*>(&msi.cr.squares[56]); ms.slow_rank8_target_ptr = reinterpret_cast<uint64_t*>(&ms.slow_target_squares[ 0]); ms.slow_rank7_target_ptr = reinterpret_cast<uint64_t*>(&ms.slow_target_squares[ 8]); ms.slow_rank6_target_ptr = reinterpret_cast<uint64_t*>(&ms.slow_target_squares[16]); ms.slow_rank5_target_ptr = reinterpret_cast<uint64_t*>(&ms.slow_target_squares[24]); ms.slow_rank4_target_ptr = reinterpret_cast<uint64_t*>(&ms.slow_target_squares[32]); ms.slow_rank3_target_ptr = reinterpret_cast<uint64_t*>(&ms.slow_target_squares[40]); ms.slow_rank2_target_ptr = reinterpret_cast<uint64_t*>(&ms.slow_target_squares[48]); ms.slow_rank1_target_ptr = reinterpret_cast<uint64_t*>(&ms.slow_target_squares[56]); } // Pawns for each side are assigned logical numbers from 0 to nbr_pawns-1 // The ordering of the numbers is determined by consulting this table... static int pawn_ordering[64] = { 7, 15, 23, 31, 39, 47, 55, 63, 6, 14, 22, 30, 38, 46, 54, 62, 5, 13, 21, 29, 37, 45, 53, 61, 4, 12, 20, 28, 36, 44, 52, 60, 3, 11, 19, 27, 35, 43, 51, 59, 2, 10, 18, 26, 34, 42, 50, 58, 1, 9, 17, 25, 33, 41, 49, 57, 0, 8, 16, 24, 32, 40, 48, 56 }; // ...to initially assign logical pawn numbers according to pawn_ordering[] // above, traverse the squares in this order and assign 0,1,2... etc as each // pawn is found static thc::Square traverse_order[64] = { thc::a1, thc::a2, thc::a3, thc::a4, thc::a5, thc::a6, thc::a7, thc::a8, thc::b1, thc::b2, thc::b3, thc::b4, thc::b5, thc::b6, thc::b7, thc::b8, thc::c1, thc::c2, thc::c3, thc::c4, thc::c5, thc::c6, thc::c7, thc::c8, thc::d1, thc::d2, thc::d3, thc::d4, thc::d5, thc::d6, thc::d7, thc::d8, thc::e1, thc::e2, thc::e3, thc::e4, thc::e5, thc::e6, thc::e7, thc::e8, thc::f1, thc::f2, thc::f3, thc::f4, thc::f5, thc::f6, thc::f7, thc::f8, thc::g1, thc::g2, thc::g3, thc::g4, thc::g5, thc::g6, thc::g7, thc::g8, thc::h1, thc::h2, thc::h3, thc::h4, thc::h5, thc::h6, thc::h7, thc::h8 }; // Try to set fast mode, return bool okay bool MemoryPositionSearch::TryFastMode( MpsSide *side ) { bool okay = true; side->nbr_pawns = 0; side->nbr_knights = 0; side->nbr_rooks = 0; side->nbr_dark_bishops = 0; side->nbr_light_bishops = 0; side->nbr_queens = 0; for( int i=0; okay && i<64; i++ ) { // Pawns are traversed according to pawn_ordering[] int j = static_cast<int>(traverse_order[i]); if( msi.cr.squares[j] == (side->white?'P':'p') ) { if( side->nbr_pawns < 8 ) side->pawns[side->nbr_pawns++] = j; else okay = false; } // Other pieces are traversed in normal square convention order if( msi.cr.squares[i] == (side->white?'R':'r') ) { if( side->nbr_rooks < 2 ) side->rooks[side->nbr_rooks++] = i; else okay = false; } else if( msi.cr.squares[i] == (side->white?'N':'n') ) { if( side->nbr_knights < 2 ) side->knights[side->nbr_knights++] = i; else okay = false; } else if( msi.cr.squares[i] == (side->white?'D':'d') ) { side->bishop_dark = i; if( side->nbr_dark_bishops < 1 ) side->nbr_dark_bishops++; else okay = false; } else if( msi.cr.squares[i] == (side->white?'B':'b') ) { side->bishop_light = i; if( side->nbr_light_bishops < 1 ) side->nbr_light_bishops++; else okay = false; } else if( msi.cr.squares[i] == (side->white?'Q':'q') ) { if( side->nbr_queens < 2 ) side->queens[side->nbr_queens++] = i; else okay = false; } else if( msi.cr.squares[i] == (side->white?'K':'k') ) { side->king = i; } } if( side->nbr_queens==2 && side->nbr_pawns>6 ) okay = false; side->fast_mode = okay; return okay; } int MemoryPositionSearch::DoSearch( const thc::ChessPosition &cp, ProgressBar *progress ) { return DoSearch(cp,progress,&in_memory_game_cache); } int MemoryPositionSearch::DoSearch( const thc::ChessPosition &cp, ProgressBar *progress, std::vector< smart_ptr<ListableGame> > *source ) { games_found.clear(); search_position = cp; search_position_set = true; search_source = source; // Set up counts of total pieces, and individual pieces in the target position ms.total_count_target = 64; // reverse count non-pieces from 64 ms.black_count_target = 0; ms.black_pawn_count_target = 0; ms.white_count_target = 0; ms.white_pawn_count_target = 0; mq.white_pawn_target = 0; mq.white_rook_target = 0; mq.white_knight_target = 0; mq.white_light_bishop_target = 0; mq.white_dark_bishop_target = 0; mq.white_queen_target = 0; mq.black_pawn_target = 0; mq.black_rook_target = 0; mq.black_knight_target = 0; mq.black_light_bishop_target = 0; mq.black_dark_bishop_target = 0; mq.black_queen_target = 0; for( int i=0; i<64; i++ ) { char piece = cp.squares[i]; switch(piece) { case 'P': { ms.white_count_target++; ms.white_pawn_count_target++; mq.white_pawn_target++; break; } case 'R': { ms.white_count_target++; mq.white_rook_target++; break; } case 'N': { ms.white_count_target++; mq.white_knight_target++; break; } case 'B': { ms.white_count_target++; if( !is_dark(i) ) mq.white_light_bishop_target++; else { mq.white_dark_bishop_target++; piece = 'D'; } break; } case 'Q': { ms.white_count_target++; mq.white_queen_target++; break; } case 'K': { ms.total_count_target--; // kings don't count for this target break; } case 'p': { ms.black_count_target++; ms.black_pawn_count_target++; mq.black_pawn_target++; break; } case 'r': { ms.black_count_target++; mq.black_rook_target++; break; } case 'n': { ms.black_count_target++; mq.black_knight_target++; break; } case 'b': { ms.black_count_target++; if( !is_dark(i) ) mq.black_light_bishop_target++; else { mq.black_dark_bishop_target++; piece = 'd'; } break; } case 'q': { ms.black_count_target++; mq.black_queen_target++; break; } case 'k': { ms.total_count_target--; // kings don't count for this target break; } default: { piece = ' '; ms.total_count_target--; break; } } // Also set up a target position, with the refinement that D/d is a dark bishop B/b is a light bishop ms.slow_target_squares[i] = piece; mq.target_squares[i] = piece; } // Set up white_home_mask and white_home_pawns to support the following logic; // bool home_pawns_still_in_place = ((white_home_mask&*mq.rank2_ptr) == white_home_pawns ); // // A home row pawn from the target position must be in place in all positions leading // to the target position - if it's not then this game doesn't include the target position // e.g. After 1.e4 we can already conclude the game is never going to include a position // in which a white pawn is on e2 char *mask = reinterpret_cast<char *>(&white_home_mask); char *pawns = reinterpret_cast<char *>(&white_home_pawns); for( int i=0; i<8; i++ ) { if( mq.target_squares[48+i] == 'P' ) { mask[i] = '\x7f'; pawns[i] = 'P'; } else { mask[i] = 0; pawns[i] = 0; } } // Do the same for the black home row mask = reinterpret_cast<char *>(&black_home_mask); pawns = reinterpret_cast<char *>(&black_home_pawns); for( int i=0; i<8; i++ ) { if( mq.target_squares[8+i] == 'p' ) { mask[i] = '\x7f'; pawns[i] = 'p'; } else { mask[i] = 0; pawns[i] = 0; } } mq.rank3_target = *mq.rank3_target_ptr; mq.rank4_target = *mq.rank4_target_ptr; mq.rank5_target = *mq.rank5_target_ptr; mq.rank6_target = *mq.rank6_target_ptr; mq.rank7_target = *mq.rank7_target_ptr; mq.rank8_target = *mq.rank8_target_ptr; mq.rank1_target = *mq.rank1_target_ptr; mq.rank2_target = *mq.rank2_target_ptr; int nbr = source->size(); { AutoTimer at("Search time"); // Leave only one defined //#define CONSERVATIVE //#define NO_PROMOTIONS_FLAWED #define CORRECT_BEST_PRACTICE for( int i=0; i<nbr; i++ ) { smart_ptr<ListableGame> p = (*source)[i]; const char *fen = p->Fen(); if( fen && *fen ) continue; // a partial game in the clipboard DoSearchFoundGame dsfg; dsfg.idx = i; dsfg.game_id = p->game_id; dsfg.offset_first=0; dsfg.offset_last=0; /* Roster r = in_memory_game_cache[i]->RefRoster(); cprintf( "idx=%d, white=%s[%s], black=%s[%s], blob=%s\n", in_memory_game_cache[i]->game_id, in_memory_game_cache[i]->White(), r.white.c_str(), in_memory_game_cache[i]->Black(), r.black.c_str(), in_memory_game_cache[i]->CompressedMoves() ); */ bool promotion_in_game = p->TestPromotion(); bool game_found; #ifdef CONSERVATIVE game_found = SearchGameSlowPromotionAllowed( std::string(p->CompressedMoves()), dsfg.offset_first, dsfg.offset_last ); #endif #ifdef NO_PROMOTIONS_FLAWED game_found = SearchGameOptimisedNoPromotionAllowed( std::string(p->CompressedMoves()), dsfg.offset_first, dsfg.offset_last ); #endif #ifdef CORRECT_BEST_PRACTICE if( promotion_in_game ) game_found = SearchGameSlowPromotionAllowed( std::string(p->CompressedMoves()), dsfg.offset_first, dsfg.offset_last ); else game_found = SearchGameOptimisedNoPromotionAllowed( p->CompressedMoves(), dsfg.offset_first, dsfg.offset_last ); #endif if( game_found ) { games_found.push_back( dsfg ); } if( (i&0xff)==0 && progress ) progress->Perfraction( i, nbr ); } } return games_found.size(); } int MemoryPositionSearch::DoPatternSearch( PatternMatch &pm, ProgressBar *progress, PATTERN_STATS &stats ) { return DoPatternSearch(pm,progress,stats,&in_memory_game_cache); } //static bool debug_trigger; int MemoryPositionSearch::DoPatternSearch( PatternMatch &pm, ProgressBar *progress, PATTERN_STATS &stats, std::vector< smart_ptr<ListableGame> > *source ) { games_found.clear(); search_position = pm.parm.cp; search_position_set = true; search_source = source; // Set up counts of total pieces, and individual pieces in the target position ms.total_count_target = 64; // reverse count non-pieces from 64 ms.black_count_target = 0; ms.black_pawn_count_target = 0; ms.white_count_target = 0; ms.white_pawn_count_target = 0; mq.white_pawn_target = 0; mq.white_rook_target = 0; mq.white_knight_target = 0; mq.white_light_bishop_target = 0; mq.white_dark_bishop_target = 0; mq.white_queen_target = 0; mq.black_pawn_target = 0; mq.black_rook_target = 0; mq.black_knight_target = 0; mq.black_light_bishop_target = 0; mq.black_dark_bishop_target = 0; mq.black_queen_target = 0; for( int i=0; i<64; i++ ) { char piece = pm.parm.cp.squares[i]; switch(piece) { case 'P': { ms.white_count_target++; ms.white_pawn_count_target++; mq.white_pawn_target++; break; } case 'R': { ms.white_count_target++; mq.white_rook_target++; break; } case 'N': { ms.white_count_target++; mq.white_knight_target++; break; } case 'B': { ms.white_count_target++; if( !is_dark(i) ) mq.white_light_bishop_target++; else { mq.white_dark_bishop_target++; piece = 'D'; } break; } case 'Q': { ms.white_count_target++; mq.white_queen_target++; break; } case 'K': { ms.total_count_target--; // kings don't count for this target break; } case 'p': { ms.black_count_target++; ms.black_pawn_count_target++; mq.black_pawn_target++; break; } case 'r': { ms.black_count_target++; mq.black_rook_target++; break; } case 'n': { ms.black_count_target++; mq.black_knight_target++; break; } case 'b': { ms.black_count_target++; if( !is_dark(i) ) mq.black_light_bishop_target++; else { mq.black_dark_bishop_target++; piece = 'd'; } break; } case 'q': { ms.black_count_target++; mq.black_queen_target++; break; } case 'k': { ms.total_count_target--; // kings don't count for this target break; } default: { piece = ' '; ms.total_count_target--; break; } } // Also set up a target position, with the refinement that D/d is a dark bishop B/b is a light bishop mq.target_squares[i] = piece; ms.slow_target_squares[i] = piece; } cprintf( "total_count_target=%d\n", ms.total_count_target ); // Set up white_home_mask and white_home_pawns to support the following logic; // bool home_pawns_still_in_place = ((white_home_mask&*mq.rank2_ptr) == white_home_pawns ); // // A home row pawn from the target position must be in place in all positions leading // to the target position - if it's not then this game doesn't include the target position // e.g. After 1.e4 we can already conclude the game is never going to include a position // in which a white pawn is on e2 char *mask = reinterpret_cast<char *>(&white_home_mask); char *pawns = reinterpret_cast<char *>(&white_home_pawns); for( int i=0; i<8; i++ ) { if( mq.target_squares[48+i] == 'P' ) { mask[i] = '\x7f'; pawns[i] = 'P'; } else { mask[i] = 0; pawns[i] = 0; } } // Do the same for the black home row mask = reinterpret_cast<char *>(&black_home_mask); pawns = reinterpret_cast<char *>(&black_home_pawns); for( int i=0; i<8; i++ ) { if( mq.target_squares[8+i] == 'p' ) { mask[i] = '\x7f'; pawns[i] = 'p'; } else { mask[i] = 0; pawns[i] = 0; } } // Set up the pattern mask pm.Prime(&msi.cr); mq.rank3_target = *mq.rank3_target_ptr; mq.rank4_target = *mq.rank4_target_ptr; mq.rank5_target = *mq.rank5_target_ptr; mq.rank6_target = *mq.rank6_target_ptr; mq.rank7_target = *mq.rank7_target_ptr; mq.rank8_target = *mq.rank8_target_ptr; mq.rank1_target = *mq.rank1_target_ptr; mq.rank2_target = *mq.rank2_target_ptr; int nbr = source->size(); { AutoTimer at("Search time"); for( int i=0; i<nbr; i++ ) { smart_ptr<ListableGame> p = (*source)[i]; //if( 0 == strcmp(p->White(),"Gu, Xiaobing") && 0 == strcmp(p->Black(),"Ryjanova, Julia") ) // debug_trigger = true; DoSearchFoundGame dsfg; dsfg.idx = i; dsfg.game_id = p->game_id; dsfg.offset_first=0; dsfg.offset_last=0; bool promotion_in_game = p->TestPromotion(); bool game_found, reverse; pm.NewGame(); if( promotion_in_game ) game_found = PatternSearchGameSlowPromotionAllowed( pm, reverse, std::string(p->CompressedMoves()), dsfg.offset_first, dsfg.offset_last ); else game_found = PatternSearchGameOptimisedNoPromotionAllowed( pm, reverse, p->CompressedMoves(), dsfg.offset_first, dsfg.offset_last ); if( game_found ) { stats.nbr_games++; if( reverse ) { stats.nbr_reversed_games++; if( 0 == strcmp(p->Result(),"1-0") ) stats.black_wins++; else if( 0 == strcmp(p->Result(),"0-1") ) stats.white_wins++; else stats.draws++; } else { if( 0 == strcmp(p->Result(),"1-0") ) stats.white_wins++; else if( 0 == strcmp(p->Result(),"0-1") ) stats.black_wins++; else stats.draws++; } games_found.push_back( dsfg ); } if( (i&0xff)==0 && progress ) { double permill = (static_cast<double>(i) * 1000.0) / static_cast<double>(nbr); progress->Permill( static_cast<int>(permill) ); } } } return games_found.size(); } thc::Move MemoryPositionSearch::UncompressSlowMode( char code ) { // Horrible kludge necessitated by our 'd'/'D' = dark bishops stuff thc::ChessRules temp = msi.cr; for( int i=0; i<64; i++ ) { char c = msi.cr.squares[i]; if( c=='d' ) temp.squares[i] = 'b'; if( c=='D' ) temp.squares[i] = 'B'; } // Support algorithm ALLOW_CASTLING_EVEN_AFTER_KING_AND_ROOK_MOVES temp.wking = 1; temp.wqueen = 1; temp.bking = 1; temp.bqueen = 1; // Generate a list of all legal moves, in string form, sorted std::vector<thc::Move> moves; temp.GenLegalMoveList( moves ); std::vector<std::string> moves_alpha; // Coding scheme relies on 254 valid codes 0x02-0xff and one error code 0x01, size_t len = moves.size(); for( size_t i=0; i<len; i++ ) { std::string s = moves[i].TerseOut(); moves_alpha.push_back(s); } std::sort( moves_alpha.begin(), moves_alpha.end() ); // '\xff' (i.e. 255) is first move in list, '\fe' (i.e. 254) is second etc unsigned int ucode = static_cast<size_t>( code ); ucode &= 0xff; size_t idx = 255-ucode; // 255->0, 254->1 etc. if( idx >= len ) idx = 0; // all errors resolve to this - take first move from list std::string the_move = moves_alpha[idx]; thc::Move mv; mv.TerseIn( &temp, the_move.c_str() ); return mv; } thc::Move MemoryPositionSearch::UncompressFastMode( char code, MpsSide *side, MpsSide *other ) { int src=0; int dst=0; int hi_nibble = code&0xf0; thc::SPECIAL special = thc::NOT_SPECIAL; switch( hi_nibble ) { case CODE_KING: { special = thc::SPECIAL_KING_MOVE; src = side->king; int delta=0; switch( code&0x0f ) // 0, 1, 2 { // 8, 9, 10 // 16,17,18 case K_VECTOR_NW: delta = -9; break; // 0-9 case K_VECTOR_N: delta = -8; break; // 1-9 case K_VECTOR_NE: delta = -7; break; // 2-9 case K_VECTOR_W: delta = -1; break; // 8-9 case K_VECTOR_E: delta = 1; break; // 10-9 case K_VECTOR_SW: delta = 7; break; // 16-9 case K_VECTOR_S: delta = 8; break; // 17-9 case K_VECTOR_SE: delta = 9; break; // 18-9 case K_K_CASTLING: { special = msi.cr.white ? thc::SPECIAL_WK_CASTLING : thc::SPECIAL_BK_CASTLING; delta = 2; int rook_offset = (side->rooks[0]==src+3 ? 0 : 1); // a rook will be 3 squares to right of king side->rooks[rook_offset] = src+1; // that rook ends up 1 square right of king // note that there is no way the rooks ordering can swap during castling break; } case K_Q_CASTLING: { special = msi.cr.white ? thc::SPECIAL_WQ_CASTLING : thc::SPECIAL_BQ_CASTLING; delta = -2; int rook_offset = (side->rooks[0]==src-4 ? 0 : 1); // a rook will be 4 squares to left of king side->rooks[rook_offset] = src-1; // that rook ends up 1 square left of king // note that there is no way the rooks ordering can swap during castling break; } } side->king = dst = src+delta; break; } case CODE_ROOK_LO: case CODE_ROOK_HI: { int rook_offset = (hi_nibble==CODE_ROOK_LO ? 0 : 1 ); src = side->rooks[rook_offset]; if( code & R_RANK ) // code encodes rank ? { dst = ((code<<3)&0x38) | (src&7); // same file as src, rank from code } else { dst = (src&0x38) | (code&7); // same rank as src, file from code } side->rooks[rook_offset] = dst; // swap ? if( side->nbr_rooks==2 && side->rooks[0]>side->rooks[1] ) { int temp = side->rooks[0]; side->rooks[0] = side->rooks[1]; side->rooks[1] = temp; } break; } case CODE_BISHOP_DARK: { src = side->bishop_dark; int file_delta = (code&7) - (src&7); if( code & B_FALL ) // FALL\ + file dst = src + 9*file_delta; // eg src=b8(1), dst=h2(55), file_delta=6 -> 9*6 =54 else // RISE/ + file dst = src - 7*file_delta; // eg src=h8(7), dst=a1(56), file_delta=7 -> 7*7 =49 side->bishop_dark = dst; break; } case CODE_BISHOP_LIGHT: { src = side->bishop_light; int file_delta = (code&7) - (src&7); if( code & B_FALL ) // FALL\ + file dst = src + 9*file_delta; // eg src=a8(0), dst=h1(63), file_delta=7 -> 9*7 =63 else // RISE/ + file dst = src - 7*file_delta; // eg src=g8(6), dst=a2(48), file_delta=6 -> 7*6 =42 side->bishop_light = dst; break; } case CODE_QUEEN_ROOK: { src = side->queens[0]; if( code & R_RANK ) // code encodes rank ? dst = ((code<<3)&0x38) | (src&7); // same file as src, rank from code else dst = (src&0x38) | (code&7); // same rank as src, file from code side->queens[0] = dst; // swap ? if( side->nbr_queens==2 && side->queens[0]>side->queens[1] ) { int temp = side->queens[0]; side->queens[0] = side->queens[1]; side->queens[1] = temp; } break; } case CODE_QUEEN_BISHOP: { src = side->queens[0]; int file_delta = (code&7) - (src&7); if( code & B_FALL ) // FALL\ + file dst = src + 9*file_delta; // eg src=a8(0), dst=h1(63), file_delta=7 -> 9*7 =63 else // RISE/ + file dst = src - 7*file_delta; // eg src=h8(7), dst=a1(56), file_delta=7 -> 7*7 =49 side->queens[0] = dst; // swap ? if( side->nbr_queens==2 && side->queens[0]>side->queens[1] ) { int temp = side->queens[0]; side->queens[0] = side->queens[1]; side->queens[1] = temp; } break; } case CODE_KNIGHT: { int knight_offset = ((code&N_HI) ? 1 : 0 );; src = side->knights[knight_offset]; int delta=0; switch(code&7) // 0, 1, 2, 3 { // 8, 9, 10,11 // 16,17,18,19 // 24,25,26,27 case N_VECTOR_NNE: delta = -15; break; // 2-17 case N_VECTOR_NEE: delta = -6; break; // 11-17 case N_VECTOR_SEE: delta = 10; break; // 27-17 case N_VECTOR_SSE: delta = 17; break; // 27-10 case N_VECTOR_SSW: delta = 15; break; // 25-10 case N_VECTOR_SWW: delta = 6; break; // 16-10 case N_VECTOR_NWW: delta = -10; break; // 0-10 case N_VECTOR_NNW: delta = -17; break; // 0-17 } dst = src+delta; side->knights[knight_offset] = dst; // swap ? if( side->nbr_knights==2 && side->knights[0]>side->knights[1] ) { int temp = side->knights[0]; side->knights[0] = side->knights[1]; side->knights[1] = temp; } break; } case CODE_PAWN_6: // if nbr_queens==2 this is the hi QUEEN_ROOK { if( side->nbr_queens < 2 ) ; // fall through else { src = side->queens[1]; if( code & R_RANK ) // code encodes rank ? dst = ((code<<3)&0x38) | (src&7); // same file as src, rank from code else dst = (src&0x38) | (code&7); // same rank as src, file from code side->queens[1] = dst; // swap ? if( side->queens[0]>side->queens[1] ) { int temp = side->queens[0]; side->queens[0] = side->queens[1]; side->queens[1] = temp; } break; } } case CODE_PAWN_7: // if nbr_queens==2 this is the hi QUEEN_BISHOP: { if( side->nbr_queens < 2 ) ; // fall through else { src = side->queens[1]; int file_delta = (code&7) - (src&7); if( code & B_FALL ) // FALL\ + file dst = src + 9*file_delta; // eg src=a8(0), dst=h1(63), file_delta=7 -> 9*7 =63 else // RISE/ + file dst = src - 7*file_delta; // eg src=h8(7), dst=a1(56), file_delta=7 -> 7*7 =49 side->queens[1] = dst; // swap ? if( side->queens[0]>side->queens[1] ) { int temp = side->queens[0]; side->queens[0] = side->queens[1]; side->queens[1] = temp; } break; } } // PAWN default: { int pawn_offset = (code>>4)&0x07; bool promoting = false; src = side->pawns[pawn_offset]; bool reordering_possible = false; bool white = msi.cr.white; int delta=0; switch( code&0x0f ) { case P_DOUBLE: special = white ? thc::SPECIAL_WPAWN_2SQUARES : thc::SPECIAL_BPAWN_2SQUARES; delta = white?-16:16; break; case P_SINGLE: delta = white?-8:8; break; case P_LEFT: { reordering_possible = true; delta = white?-9:9; if( !isalpha(msi.cr.squares[src+delta]) ) special = (white ? thc::SPECIAL_WEN_PASSANT : thc::SPECIAL_BEN_PASSANT); break; } case P_RIGHT: { reordering_possible = true; delta = white?-7:7; if( !isalpha(msi.cr.squares[src+delta]) ) special = (white ? thc::SPECIAL_WEN_PASSANT : thc::SPECIAL_BEN_PASSANT); break; } default: { promoting = true; switch( (code>>2)&3 ) { case P_SINGLE: delta = white?-8:8; break; case P_LEFT: delta = white?-9:9; break; case P_RIGHT: delta = white?-7:7; break; } switch( code&3 ) { case P_QUEEN: special = thc::SPECIAL_PROMOTION_QUEEN; break; case P_ROOK: special = thc::SPECIAL_PROMOTION_ROOK; break; case P_BISHOP: special = thc::SPECIAL_PROMOTION_BISHOP; break; case P_KNIGHT: special = thc::SPECIAL_PROMOTION_KNIGHT; break; } break; } } side->pawns[pawn_offset] = dst = src+delta; // If promoting piece, force a reset and retry next time for this side. This // way we accommodate our pawn disappearing, and a new piece appearing in // its place, and the possibility that we cannot remain in fast mode // (because we now have too many queens or other pieces). If the reset // and retry fails this side will generate slow mode moves but keep // retrying until fast is possible again. if( promoting ) side->fast_mode = false; else if( reordering_possible ) { if( pawn_ordering[dst] > pawn_ordering[src] ) // increasing capture? { for( int i=pawn_offset; i+1<side->nbr_pawns && pawn_ordering[side->pawns[i]]>pawn_ordering[side->pawns[i+1]]; i++ ) { int temp = side->pawns[i]; side->pawns[i] = side->pawns[i+1]; side->pawns[i+1] = temp; } } else // else decreasing capture { for( int i=pawn_offset; i-1>=0 && pawn_ordering[side->pawns[i-1]]>pawn_ordering[side->pawns[i]]; i-- ) { int temp = side->pawns[i-1]; side->pawns[i-1] = side->pawns[i]; side->pawns[i] = temp; } } } break; } // end PAWN } // end switch on moving piece // Accomodate captured piece on other side, if other side is in fast mode int capture_location=dst; if( special == thc::SPECIAL_WEN_PASSANT ) capture_location = dst+8; else if( special == thc::SPECIAL_BEN_PASSANT ) capture_location = dst-8; char capture = msi.cr.squares[capture_location]; bool making_capture = (isalpha(capture) ? true : false); if( making_capture && other->fast_mode ) { switch( tolower(capture) ) { case 'n': { if( other->nbr_knights==2 && other->knights[0]==capture_location ) other->knights[0] = other->knights[1]; other->nbr_knights--; break; } case 'r': { if( other->nbr_rooks==2 && other->rooks[0]==capture_location ) other->rooks[0] = other->rooks[1]; other->nbr_rooks--; break; } case 'd': { other->nbr_dark_bishops--; break; } case 'b': { other->nbr_light_bishops--; break; } case 'q': { if( other->nbr_queens==2 && other->queens[0]==capture_location ) other->queens[0] = other->queens[1]; other->nbr_queens--; break; } case 'p': { int other_pawn_offset=0; for( int i=0; i<other->nbr_pawns; i++ ) { if( other->pawns[i] == capture_location ) { other_pawn_offset = i; break; } } for( int i=other_pawn_offset; i+1<other->nbr_pawns; i++ ) { other->pawns[i] = other->pawns[i+1]; } other->nbr_pawns--; } } } thc::Move mv; mv.src = static_cast<thc::Square>(src); mv.dst = static_cast<thc::Square>(dst); mv.special = special; mv.capture = capture; return mv; } #define WHITE_HOME_ROW_TEST ((*mq.rank2_ptr & white_home_mask) == white_home_pawns) #define BLACK_HOME_ROW_TEST ((*mq.rank7_ptr & black_home_mask) == black_home_pawns) #define SLOW_WHITE_HOME_ROW_TEST ((*ms.slow_rank2_ptr & white_home_mask) == white_home_pawns) #define SLOW_BLACK_HOME_ROW_TEST ((*ms.slow_rank7_ptr & black_home_mask) == black_home_pawns) bool MemoryPositionSearch::SearchGameOptimisedNoPromotionAllowed( const char *moves_in, unsigned short &offset_first, unsigned short &offset_last ) { unsigned short offset=0; bool target_white = search_position.white; // searching for position with white to move? QuickGameInit(); for(;;) { // Check for match before every move if( target_white && #if 1 *mq.rank3_ptr == mq.rank3_target && *mq.rank4_ptr == mq.rank4_target && *mq.rank5_ptr == mq.rank5_target && *mq.rank6_ptr == mq.rank6_target && *mq.rank7_ptr == mq.rank7_target && *mq.rank8_ptr == mq.rank8_target && *mq.rank1_ptr == mq.rank1_target && *mq.rank2_ptr == mq.rank2_target #else *mq.rank3_ptr == *mq.rank3_target_ptr && *mq.rank4_ptr == *mq.rank4_target_ptr && *mq.rank5_ptr == *mq.rank5_target_ptr && *mq.rank6_ptr == *mq.rank6_target_ptr && *mq.rank7_ptr == *mq.rank7_target_ptr && *mq.rank8_ptr == *mq.rank8_target_ptr && *mq.rank1_ptr == *mq.rank1_target_ptr && *mq.rank2_ptr == *mq.rank2_target_ptr #endif ) { offset_last = offset_first = offset; // later - separate offset_first and offset_last return true; } // White move char code = *moves_in++; offset++; int src=0; int dst=0; int hi_nibble = code&0xf0; char captured=EMPTY_CHARACTER; switch( hi_nibble ) { case CODE_KING: { src = mqi.side_white.king; int delta=0; switch( code&0x0f ) // 0, 1, 2 { // 8, 9, 10 // 16,17,18 case 0: return false; // CODE_KING = 0, so '\0' string terminator case K_VECTOR_NW: delta = -9; break; // 0-9 case K_VECTOR_N: delta = -8; break; // 1-9 case K_VECTOR_NE: delta = -7; break; // 2-9 case K_VECTOR_W: delta = -1; break; // 8-9 case K_VECTOR_E: delta = 1; break; // 10-9 case K_VECTOR_SW: delta = 7; break; // 16-9 case K_VECTOR_S: delta = 8; break; // 17-9 case K_VECTOR_SE: delta = 9; break; // 18-9 case K_K_CASTLING: { // Idea: replace this with a single 32 bit ptr store of ' RK ' delta = 2; int rook_offset = (mqi.side_white.rooks[0]==src+3 ? 0 : 1); // a rook will be 3 squares to right of king mqi.side_white.rooks[rook_offset] = src+1; // that rook ends up 1 square right of king // note that there is no way the rooks ordering can swap during castling mqi.squares[src+1] = 'R'; //f1 mqi.squares[src+3] = EMPTY_CHARACTER; //h1 break; } case K_Q_CASTLING: { delta = -2; int rook_offset = (mqi.side_white.rooks[0]==src-4 ? 0 : 1); // a rook will be 4 squares to left of king mqi.side_white.rooks[rook_offset] = src-1; // that rook ends up 1 square left of king // note that there is no way the rooks ordering can swap during castling mqi.squares[src-1] = 'R'; //d1 mqi.squares[src-4] = EMPTY_CHARACTER; //a1 break; } } mqi.side_white.king = dst = src+delta; captured = mqi.squares[dst]; mqi.squares[dst] = 'K'; mqi.squares[src] = EMPTY_CHARACTER; break; } case CODE_ROOK_LO: case CODE_ROOK_HI: { int rook_offset = (hi_nibble==CODE_ROOK_LO ? 0 : 1 ); src = mqi.side_white.rooks[rook_offset]; if( code & R_RANK ) // code encodes rank ? { dst = ((code<<3)&0x38) | (src&7); // same file as src, rank from code } else { dst = (src&0x38) | (code&7); // same rank as src, file from code } mqi.side_white.rooks[rook_offset] = dst; captured = mqi.squares[dst]; mqi.squares[dst] = 'R'; mqi.squares[src] = EMPTY_CHARACTER; // swap ? if( mqi.side_white.nbr_rooks==2 && mqi.side_white.rooks[0]>mqi.side_white.rooks[1] ) { int temp = mqi.side_white.rooks[0]; mqi.side_white.rooks[0] = mqi.side_white.rooks[1]; mqi.side_white.rooks[1] = temp; } break; } case CODE_BISHOP_DARK: { src = mqi.side_white.bishop_dark; int file_delta = (code&7) - (src&7); if( code & B_FALL ) // FALL\ + file dst = src + 9*file_delta; // eg src=b8(1), dst=h2(55), file_delta=6 -> 9*6 =54 else // RISE/ + file dst = src - 7*file_delta; // eg src=h8(7), dst=a1(56), file_delta=7 -> 7*7 =49 captured = mqi.squares[dst]; mqi.squares[dst] = 'D'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_white.bishop_dark = dst; break; } case CODE_BISHOP_LIGHT: { src = mqi.side_white.bishop_light; int file_delta = (code&7) - (src&7); if( code & B_FALL ) // FALL\ + file dst = src + 9*file_delta; // eg src=a8(0), dst=h1(63), file_delta=7 -> 9*7 =63 else // RISE/ + file dst = src - 7*file_delta; // eg src=g8(6), dst=a2(48), file_delta=6 -> 7*6 =42 captured = mqi.squares[dst]; mqi.squares[dst] = 'B'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_white.bishop_light = dst; break; } case CODE_QUEEN_ROOK: { src = mqi.side_white.queens[0]; if( code & R_RANK ) // code encodes rank ? dst = ((code<<3)&0x38) | (src&7); // same file as src, rank from code else dst = (src&0x38) | (code&7); // same rank as src, file from code captured = mqi.squares[dst]; mqi.squares[dst] = 'Q'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_white.queens[0] = dst; break; } case CODE_QUEEN_BISHOP: { src = mqi.side_white.queens[0]; int file_delta = (code&7) - (src&7); if( code & B_FALL ) // FALL\ + file dst = src + 9*file_delta; // eg src=a8(0), dst=h1(63), file_delta=7 -> 9*7 =63 else // RISE/ + file dst = src - 7*file_delta; // eg src=h8(7), dst=a1(56), file_delta=7 -> 7*7 =49 captured = mqi.squares[dst]; mqi.squares[dst] = 'Q'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_white.queens[0] = dst; break; } case CODE_KNIGHT: { int knight_offset = ((code&N_HI) ? 1 : 0 ); src = mqi.side_white.knights[knight_offset]; int delta=0; switch(code&7) // 0, 1, 2, 3 { // 8, 9, 10,11 // 16,17,18,19 // 24,25,26,27 case N_VECTOR_NNE: delta = -15; break; // 2-17 case N_VECTOR_NEE: delta = -6; break; // 11-17 case N_VECTOR_SEE: delta = 10; break; // 27-17 case N_VECTOR_SSE: delta = 17; break; // 27-10 case N_VECTOR_SSW: delta = 15; break; // 25-10 case N_VECTOR_SWW: delta = 6; break; // 16-10 case N_VECTOR_NWW: delta = -10; break; // 0-10 case N_VECTOR_NNW: delta = -17; break; // 0-17 } dst = src+delta; captured = mqi.squares[dst]; mqi.squares[dst] = 'N'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_white.knights[knight_offset] = dst; // swap ? if( mqi.side_white.nbr_knights==2 && mqi.side_white.knights[0]>mqi.side_white.knights[1] ) { int temp = mqi.side_white.knights[0]; mqi.side_white.knights[0] = mqi.side_white.knights[1]; mqi.side_white.knights[1] = temp; } break; } // PAWN default: { int pawn_offset = (code>>4)&0x07; src = mqi.side_white.pawns[pawn_offset]; int delta; switch( code&0x0f ) { default: { return false; // this code doesn't handle promotions } case P_DOUBLE: { delta = -16; dst = src+delta; mqi.squares[dst] = 'P'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_white.pawns[pawn_offset] = dst; if( !((*mq.rank2_ptr & white_home_mask) == white_home_pawns) ) //WHITE_HOME_ROW_TEST ) return false; break; } case P_SINGLE: { delta = -8; dst = src+delta; mqi.squares[dst] = 'P'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_white.pawns[pawn_offset] = dst; if( 48<=src && src<56 && !WHITE_HOME_ROW_TEST ) return false; break; } case P_LEFT: { delta = -9; dst = src+delta; captured = mqi.squares[dst]; mqi.squares[dst] = 'P'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_white.pawns[pawn_offset] = dst; if( captured == EMPTY_CHARACTER ) { captured = 'p'; // en-passant mqi.squares[dst=src-1] = EMPTY_CHARACTER; } else if( 48<=src && src<56 && !WHITE_HOME_ROW_TEST ) return false; // Decreasing capture possibly requires reordering White pawns for( int i=pawn_offset; i-1>=0 && pawn_ordering[mqi.side_white.pawns[i-1]]>pawn_ordering[mqi.side_white.pawns[i]]; i-- ) { int temp = mqi.side_white.pawns[i-1]; mqi.side_white.pawns[i-1] = mqi.side_white.pawns[i]; mqi.side_white.pawns[i] = temp; } break; } case P_RIGHT: { delta = -7; dst = src+delta; captured = mqi.squares[dst]; mqi.squares[dst] = 'P'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_white.pawns[pawn_offset] = dst; if( captured == EMPTY_CHARACTER ) { captured = 'p'; // en-passant mqi.squares[dst=src+1] = EMPTY_CHARACTER; } else if( 48<=src && src<56 && !WHITE_HOME_ROW_TEST ) // en-passant capture can't be from home row return false; // Increasing capture possibly requires reordering White pawns for( int i=pawn_offset; i+1<mqi.side_white.nbr_pawns && pawn_ordering[mqi.side_white.pawns[i]]>pawn_ordering[mqi.side_white.pawns[i+1]]; i++ ) { int temp = mqi.side_white.pawns[i]; mqi.side_white.pawns[i] = mqi.side_white.pawns[i+1]; mqi.side_white.pawns[i+1] = temp; } break; } } } // end switch on pawn types } // end switch all pieces // White captures black if( captured != EMPTY_CHARACTER ) { switch( captured ) { case 'p': { if( 8<=dst && dst<16 && !BLACK_HOME_ROW_TEST ) return false; bool zap=false; for( int i=0; i<mqi.side_black.nbr_pawns-1; i++ ) { if( zap ) mqi.side_black.pawns[i] = mqi.side_black.pawns[i+1]; else if( mqi.side_black.pawns[i] == dst ) { zap = true; mqi.side_black.pawns[i] = mqi.side_black.pawns[i+1]; } } if( --mqi.side_black.nbr_pawns < mq.black_pawn_target ) return false; break; } case 'q': { if( mq.black_queen_target == 1 ) return false; break; } case 'r': { if( mqi.side_black.nbr_rooks==2 && mqi.side_black.rooks[0]==dst ) mqi.side_black.rooks[0] = mqi.side_black.rooks[1]; if( --mqi.side_black.nbr_rooks < mq.black_rook_target ) return false; break; } case 'n': { if( mqi.side_black.nbr_knights==2 && mqi.side_black.knights[0]==dst ) mqi.side_black.knights[0] = mqi.side_black.knights[1]; if( --mqi.side_black.nbr_knights < mq.black_knight_target ) return false; break; } case 'b': { if( mq.black_light_bishop_target == 1 ) return false; break; } case 'd': { if( mq.black_dark_bishop_target == 1 ) return false; break; } } } if( !target_white && #if 1 *mq.rank3_ptr == mq.rank3_target && *mq.rank4_ptr == mq.rank4_target && *mq.rank5_ptr == mq.rank5_target && *mq.rank6_ptr == mq.rank6_target && *mq.rank7_ptr == mq.rank7_target && *mq.rank8_ptr == mq.rank8_target && *mq.rank1_ptr == mq.rank1_target && *mq.rank2_ptr == mq.rank2_target #else *mq.rank3_ptr == *mq.rank3_target_ptr && *mq.rank4_ptr == *mq.rank4_target_ptr && *mq.rank5_ptr == *mq.rank5_target_ptr && *mq.rank6_ptr == *mq.rank6_target_ptr && *mq.rank7_ptr == *mq.rank7_target_ptr && *mq.rank8_ptr == *mq.rank8_target_ptr && *mq.rank1_ptr == *mq.rank1_target_ptr && *mq.rank2_ptr == *mq.rank2_target_ptr #endif ) { offset_last = offset_first = offset; // later - separate offset_first and offset_last return true; } // Black move code = *moves_in++; offset++; src=0; dst=0; hi_nibble = code&0xf0; captured=EMPTY_CHARACTER; switch( hi_nibble ) { case CODE_KING: { src = mqi.side_black.king; int delta=0; switch( code&0x0f ) // 0, 1, 2 { // 8, 9, 10 // 16,17,18 case 0: return false; // CODE_KING = 0, so '\0' string terminator case K_VECTOR_NW: delta = -9; break; // 0-9 case K_VECTOR_N: delta = -8; break; // 1-9 case K_VECTOR_NE: delta = -7; break; // 2-9 case K_VECTOR_W: delta = -1; break; // 8-9 case K_VECTOR_E: delta = 1; break; // 10-9 case K_VECTOR_SW: delta = 7; break; // 16-9 case K_VECTOR_S: delta = 8; break; // 17-9 case K_VECTOR_SE: delta = 9; break; // 18-9 case K_K_CASTLING: { delta = 2; int rook_offset = (mqi.side_black.rooks[0]==src+3 ? 0 : 1); // a rook will be 3 squares to right of king mqi.side_black.rooks[rook_offset] = src+1; // that rook ends up 1 square right of king // note that there is no way the rooks ordering can swap during castling mqi.squares[src+1] = 'r'; //f8 mqi.squares[src+3] = EMPTY_CHARACTER; //h8 break; } case K_Q_CASTLING: { delta = -2; int rook_offset = (mqi.side_black.rooks[0]==src-4 ? 0 : 1); // a rook will be 4 squares to left of king mqi.side_black.rooks[rook_offset] = src-1; // that rook ends up 1 square left of king // note that there is no way the rooks ordering can swap during castling mqi.squares[src-1] = 'r'; //d8 mqi.squares[src-4] = EMPTY_CHARACTER; //a8 break; } } mqi.side_black.king = dst = src+delta; captured = mqi.squares[dst]; mqi.squares[dst] = 'k'; mqi.squares[src] = EMPTY_CHARACTER; break; } case CODE_ROOK_LO: case CODE_ROOK_HI: { int rook_offset = (hi_nibble==CODE_ROOK_LO ? 0 : 1 ); src = mqi.side_black.rooks[rook_offset]; if( code & R_RANK ) // code encodes rank ? { dst = ((code<<3)&0x38) | (src&7); // same file as src, rank from code } else { dst = (src&0x38) | (code&7); // same rank as src, file from code } mqi.side_black.rooks[rook_offset] = dst; captured = mqi.squares[dst]; mqi.squares[dst] = 'r'; mqi.squares[src] = EMPTY_CHARACTER; // swap ? if( mqi.side_black.nbr_rooks==2 && mqi.side_black.rooks[0]>mqi.side_black.rooks[1] ) { int temp = mqi.side_black.rooks[0]; mqi.side_black.rooks[0] = mqi.side_black.rooks[1]; mqi.side_black.rooks[1] = temp; } break; } case CODE_BISHOP_DARK: { src = mqi.side_black.bishop_dark; int file_delta = (code&7) - (src&7); if( code & B_FALL ) // FALL\ + file dst = src + 9*file_delta; // eg src=b8(1), dst=h2(55), file_delta=6 -> 9*6 =54 else // RISE/ + file dst = src - 7*file_delta; // eg src=h8(7), dst=a1(56), file_delta=7 -> 7*7 =49 captured = mqi.squares[dst]; mqi.squares[dst] = 'd'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_black.bishop_dark = dst; break; } case CODE_BISHOP_LIGHT: { src = mqi.side_black.bishop_light; int file_delta = (code&7) - (src&7); if( code & B_FALL ) // FALL\ + file dst = src + 9*file_delta; // eg src=a8(0), dst=h1(63), file_delta=7 -> 9*7 =63 else // RISE/ + file dst = src - 7*file_delta; // eg src=g8(6), dst=a2(48), file_delta=6 -> 7*6 =42 captured = mqi.squares[dst]; mqi.squares[dst] = 'b'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_black.bishop_light = dst; break; } case CODE_QUEEN_ROOK: { src = mqi.side_black.queens[0]; if( code & R_RANK ) // code encodes rank ? dst = ((code<<3)&0x38) | (src&7); // same file as src, rank from code else dst = (src&0x38) | (code&7); // same rank as src, file from code captured = mqi.squares[dst]; mqi.squares[dst] = 'q'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_black.queens[0] = dst; break; } case CODE_QUEEN_BISHOP: { src = mqi.side_black.queens[0]; int file_delta = (code&7) - (src&7); if( code & B_FALL ) // FALL\ + file dst = src + 9*file_delta; // eg src=a8(0), dst=h1(63), file_delta=7 -> 9*7 =63 else // RISE/ + file dst = src - 7*file_delta; // eg src=h8(7), dst=a1(56), file_delta=7 -> 7*7 =49 captured = mqi.squares[dst]; mqi.squares[dst] = 'q'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_black.queens[0] = dst; break; } case CODE_KNIGHT: { int knight_offset = ((code&N_HI) ? 1 : 0 ); src = mqi.side_black.knights[knight_offset]; int delta=0; switch(code&7) // 0, 1, 2, 3 { // 8, 9, 10,11 // 16,17,18,19 // 24,25,26,27 case N_VECTOR_NNE: delta = -15; break; // 2-17 case N_VECTOR_NEE: delta = -6; break; // 11-17 case N_VECTOR_SEE: delta = 10; break; // 27-17 case N_VECTOR_SSE: delta = 17; break; // 27-10 case N_VECTOR_SSW: delta = 15; break; // 25-10 case N_VECTOR_SWW: delta = 6; break; // 16-10 case N_VECTOR_NWW: delta = -10; break; // 0-10 case N_VECTOR_NNW: delta = -17; break; // 0-17 } dst = src+delta; captured = mqi.squares[dst]; mqi.squares[dst] = 'n'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_black.knights[knight_offset] = dst; // swap ? if( mqi.side_black.nbr_knights==2 && mqi.side_black.knights[0]>mqi.side_black.knights[1] ) { int temp = mqi.side_black.knights[0]; mqi.side_black.knights[0] = mqi.side_black.knights[1]; mqi.side_black.knights[1] = temp; } break; } // PAWN default: { int pawn_offset = (code>>4)&0x07; src = mqi.side_black.pawns[pawn_offset]; int delta; switch( code&0x0f ) { default: { return false; // this code doesn't handle promotions } case P_DOUBLE: { delta = 16; dst = src+delta; mqi.squares[dst] = 'p'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_black.pawns[pawn_offset] = dst; if( !BLACK_HOME_ROW_TEST ) return false; break; } case P_SINGLE: { delta = 8; dst = src+delta; mqi.squares[dst] = 'p'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_black.pawns[pawn_offset] = dst; if( 8<=src && src<16 && !BLACK_HOME_ROW_TEST ) return false; break; } case P_LEFT: { delta = 9; dst = src+delta; captured = mqi.squares[dst]; mqi.squares[dst] = 'p'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_black.pawns[pawn_offset] = dst; if( captured == EMPTY_CHARACTER ) { captured = 'P'; // en-passant mqi.squares[dst=src+1] = EMPTY_CHARACTER; } else if( 8<=src && src<16 && !BLACK_HOME_ROW_TEST ) return false; // Increasing capture possibly requires reordering Black pawns for( int i=pawn_offset; i+1<mqi.side_black.nbr_pawns && pawn_ordering[mqi.side_black.pawns[i]]>pawn_ordering[mqi.side_black.pawns[i+1]]; i++ ) { int temp = mqi.side_black.pawns[i]; mqi.side_black.pawns[i] = mqi.side_black.pawns[i+1]; mqi.side_black.pawns[i+1] = temp; } break; } case P_RIGHT: { delta = 7; dst = src+delta; captured = mqi.squares[dst]; mqi.squares[dst] = 'p'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_black.pawns[pawn_offset] = dst; if( captured == EMPTY_CHARACTER ) { captured = 'P'; // en-passant mqi.squares[dst=src-1] = EMPTY_CHARACTER; } else if( 8<=src && src<16 && !BLACK_HOME_ROW_TEST ) // en-passant capture can't be from home row return false; // Decreasing capture possibly requires reordering Black pawns for( int i=pawn_offset; i-1>=0 && pawn_ordering[mqi.side_black.pawns[i-1]]>pawn_ordering[mqi.side_black.pawns[i]]; i-- ) { int temp = mqi.side_black.pawns[i-1]; mqi.side_black.pawns[i-1] = mqi.side_black.pawns[i]; mqi.side_black.pawns[i] = temp; } break; } } } // end switch on pawn types } // end switch all pieces // Black captures white if( captured != EMPTY_CHARACTER ) { switch( captured ) { case 'P': { if( 48<=dst && dst<56 && !WHITE_HOME_ROW_TEST ) return false; bool zap=false; for( int i=0; i<mqi.side_white.nbr_pawns-1; i++ ) { if( zap ) mqi.side_white.pawns[i] = mqi.side_white.pawns[i+1]; else if( mqi.side_white.pawns[i] == dst ) { zap = true; mqi.side_white.pawns[i] = mqi.side_white.pawns[i+1]; } } if( --mqi.side_white.nbr_pawns < mq.white_pawn_target ) return false; break; } case 'Q': { if( mq.white_queen_target == 1 ) return false; break; } case 'R': { if( mqi.side_white.nbr_rooks==2 && mqi.side_white.rooks[0]==dst ) mqi.side_white.rooks[0] = mqi.side_white.rooks[1]; if( --mqi.side_white.nbr_rooks < mq.white_rook_target ) return false; break; } case 'N': { if( mqi.side_white.nbr_knights==2 && mqi.side_white.knights[0]==dst ) mqi.side_white.knights[0] = mqi.side_white.knights[1]; if( --mqi.side_white.nbr_knights < mq.white_knight_target ) return false; break; } case 'B': { if( mq.white_light_bishop_target == 1 ) return false; break; } case 'D': { if( mq.white_dark_bishop_target == 1 ) return false; break; } } } } //return false; // unreachable } bool MemoryPositionSearch::PatternSearchGameOptimisedNoPromotionAllowed( PatternMatch &pm, bool &reverse, const char *moves_in, unsigned short &offset_first, unsigned short &offset_last ) { unsigned short offset=0; QuickGameInit(); int total_count=30; // 32 - 2 kings for(;;) { // Check for match before every move /*if( debug_trigger ) { char buf[9]; buf[8] = '\0'; cprintf( "before\n" ); for( int i=0; i<64; i+=8 ) { memcpy(buf,&mqi.squares[i],8); for( int k=0; k<8; k++ ) if( buf[k] == ' ' ) buf[k]='.'; cprintf( "%s\n", buf ); } } */ bool match = pm.Test( reverse, &mqi.side_white, &mqi.side_black, true, mqi.squares, false ); if( match ) { /*if( debug_trigger ) { cprintf( "Match!\n" ); debug_trigger = false; } */ offset_last = offset_first = offset; // later - separate offset_first and offset_last return true; } #define SIMPLE_PATTERN_COUNT_OPTIMISATION #ifdef SIMPLE_PATTERN_COUNT_OPTIMISATION if( total_count < ms.total_count_target ) return false; #endif // White move char code = *moves_in++; offset++; int src=0; int dst=0; int hi_nibble = code&0xf0; char captured=EMPTY_CHARACTER; switch( hi_nibble ) { case CODE_KING: { src = mqi.side_white.king; int delta=0; switch( code&0x0f ) // 0, 1, 2 { // 8, 9, 10 // 16,17,18 case 0: return false; // CODE_KING = 0, so '\0' string terminator case K_VECTOR_NW: delta = -9; break; // 0-9 case K_VECTOR_N: delta = -8; break; // 1-9 case K_VECTOR_NE: delta = -7; break; // 2-9 case K_VECTOR_W: delta = -1; break; // 8-9 case K_VECTOR_E: delta = 1; break; // 10-9 case K_VECTOR_SW: delta = 7; break; // 16-9 case K_VECTOR_S: delta = 8; break; // 17-9 case K_VECTOR_SE: delta = 9; break; // 18-9 case K_K_CASTLING: { // Idea: replace this with a single 32 bit ptr store of ' RK ' delta = 2; int rook_offset = (mqi.side_white.rooks[0]==src+3 ? 0 : 1); // a rook will be 3 squares to right of king mqi.side_white.rooks[rook_offset] = src+1; // that rook ends up 1 square right of king // note that there is no way the rooks ordering can swap during castling mqi.squares[src+1] = 'R'; //f1 mqi.squares[src+3] = EMPTY_CHARACTER; //h1 break; } case K_Q_CASTLING: { delta = -2; int rook_offset = (mqi.side_white.rooks[0]==src-4 ? 0 : 1); // a rook will be 4 squares to left of king mqi.side_white.rooks[rook_offset] = src-1; // that rook ends up 1 square left of king // note that there is no way the rooks ordering can swap during castling mqi.squares[src-1] = 'R'; //d1 mqi.squares[src-4] = EMPTY_CHARACTER; //a1 break; } } mqi.side_white.king = dst = src+delta; captured = mqi.squares[dst]; mqi.squares[dst] = 'K'; mqi.squares[src] = EMPTY_CHARACTER; break; } case CODE_ROOK_LO: case CODE_ROOK_HI: { int rook_offset = (hi_nibble==CODE_ROOK_LO ? 0 : 1 ); src = mqi.side_white.rooks[rook_offset]; if( code & R_RANK ) // code encodes rank ? { dst = ((code<<3)&0x38) | (src&7); // same file as src, rank from code } else { dst = (src&0x38) | (code&7); // same rank as src, file from code } mqi.side_white.rooks[rook_offset] = dst; captured = mqi.squares[dst]; mqi.squares[dst] = 'R'; mqi.squares[src] = EMPTY_CHARACTER; // swap ? if( mqi.side_white.nbr_rooks==2 && mqi.side_white.rooks[0]>mqi.side_white.rooks[1] ) { int temp = mqi.side_white.rooks[0]; mqi.side_white.rooks[0] = mqi.side_white.rooks[1]; mqi.side_white.rooks[1] = temp; } break; } case CODE_BISHOP_DARK: { src = mqi.side_white.bishop_dark; int file_delta = (code&7) - (src&7); if( code & B_FALL ) // FALL\ + file dst = src + 9*file_delta; // eg src=b8(1), dst=h2(55), file_delta=6 -> 9*6 =54 else // RISE/ + file dst = src - 7*file_delta; // eg src=h8(7), dst=a1(56), file_delta=7 -> 7*7 =49 captured = mqi.squares[dst]; mqi.squares[dst] = 'D'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_white.bishop_dark = dst; break; } case CODE_BISHOP_LIGHT: { src = mqi.side_white.bishop_light; int file_delta = (code&7) - (src&7); if( code & B_FALL ) // FALL\ + file dst = src + 9*file_delta; // eg src=a8(0), dst=h1(63), file_delta=7 -> 9*7 =63 else // RISE/ + file dst = src - 7*file_delta; // eg src=g8(6), dst=a2(48), file_delta=6 -> 7*6 =42 captured = mqi.squares[dst]; mqi.squares[dst] = 'B'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_white.bishop_light = dst; break; } case CODE_QUEEN_ROOK: { src = mqi.side_white.queens[0]; if( code & R_RANK ) // code encodes rank ? dst = ((code<<3)&0x38) | (src&7); // same file as src, rank from code else dst = (src&0x38) | (code&7); // same rank as src, file from code captured = mqi.squares[dst]; mqi.squares[dst] = 'Q'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_white.queens[0] = dst; break; } case CODE_QUEEN_BISHOP: { src = mqi.side_white.queens[0]; int file_delta = (code&7) - (src&7); if( code & B_FALL ) // FALL\ + file dst = src + 9*file_delta; // eg src=a8(0), dst=h1(63), file_delta=7 -> 9*7 =63 else // RISE/ + file dst = src - 7*file_delta; // eg src=h8(7), dst=a1(56), file_delta=7 -> 7*7 =49 captured = mqi.squares[dst]; mqi.squares[dst] = 'Q'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_white.queens[0] = dst; break; } case CODE_KNIGHT: { int knight_offset = ((code&N_HI) ? 1 : 0 ); src = mqi.side_white.knights[knight_offset]; int delta=0; switch(code&7) // 0, 1, 2, 3 { // 8, 9, 10,11 // 16,17,18,19 // 24,25,26,27 case N_VECTOR_NNE: delta = -15; break; // 2-17 case N_VECTOR_NEE: delta = -6; break; // 11-17 case N_VECTOR_SEE: delta = 10; break; // 27-17 case N_VECTOR_SSE: delta = 17; break; // 27-10 case N_VECTOR_SSW: delta = 15; break; // 25-10 case N_VECTOR_SWW: delta = 6; break; // 16-10 case N_VECTOR_NWW: delta = -10; break; // 0-10 case N_VECTOR_NNW: delta = -17; break; // 0-17 } dst = src+delta; captured = mqi.squares[dst]; mqi.squares[dst] = 'N'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_white.knights[knight_offset] = dst; // swap ? if( mqi.side_white.nbr_knights==2 && mqi.side_white.knights[0]>mqi.side_white.knights[1] ) { int temp = mqi.side_white.knights[0]; mqi.side_white.knights[0] = mqi.side_white.knights[1]; mqi.side_white.knights[1] = temp; } break; } // PAWN default: { int pawn_offset = (code>>4)&0x07; src = mqi.side_white.pawns[pawn_offset]; int delta; switch( code&0x0f ) { default: { return false; // this code doesn't handle promotions } case P_DOUBLE: { delta = -16; dst = src+delta; mqi.squares[dst] = 'P'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_white.pawns[pawn_offset] = dst; break; } case P_SINGLE: { delta = -8; dst = src+delta; mqi.squares[dst] = 'P'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_white.pawns[pawn_offset] = dst; break; } case P_LEFT: { delta = -9; dst = src+delta; captured = mqi.squares[dst]; mqi.squares[dst] = 'P'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_white.pawns[pawn_offset] = dst; if( captured == EMPTY_CHARACTER ) { captured = 'p'; // en-passant mqi.squares[dst=src-1] = EMPTY_CHARACTER; } // Decreasing capture possibly requires reordering White pawns for( int i=pawn_offset; i-1>=0 && pawn_ordering[mqi.side_white.pawns[i-1]]>pawn_ordering[mqi.side_white.pawns[i]]; i-- ) { int temp = mqi.side_white.pawns[i-1]; mqi.side_white.pawns[i-1] = mqi.side_white.pawns[i]; mqi.side_white.pawns[i] = temp; } break; } case P_RIGHT: { delta = -7; dst = src+delta; captured = mqi.squares[dst]; mqi.squares[dst] = 'P'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_white.pawns[pawn_offset] = dst; if( captured == EMPTY_CHARACTER ) { captured = 'p'; // en-passant mqi.squares[dst=src+1] = EMPTY_CHARACTER; } // Increasing capture possibly requires reordering White pawns for( int i=pawn_offset; i+1<mqi.side_white.nbr_pawns && pawn_ordering[mqi.side_white.pawns[i]]>pawn_ordering[mqi.side_white.pawns[i+1]]; i++ ) { int temp = mqi.side_white.pawns[i]; mqi.side_white.pawns[i] = mqi.side_white.pawns[i+1]; mqi.side_white.pawns[i+1] = temp; } break; } } } // end switch on pawn types } // end switch all pieces // White captures black if( captured != EMPTY_CHARACTER ) { total_count--; switch( captured ) { case 'p': { bool zap=false; for( int i=0; i<mqi.side_black.nbr_pawns-1; i++ ) { if( zap ) mqi.side_black.pawns[i] = mqi.side_black.pawns[i+1]; else if( mqi.side_black.pawns[i] == dst ) { zap = true; mqi.side_black.pawns[i] = mqi.side_black.pawns[i+1]; } } --mqi.side_black.nbr_pawns; break; } case 'q': { --mqi.side_black.nbr_queens; break; } case 'r': { if( mqi.side_black.nbr_rooks==2 && mqi.side_black.rooks[0]==dst ) mqi.side_black.rooks[0] = mqi.side_black.rooks[1]; --mqi.side_black.nbr_rooks; break; } case 'n': { if( mqi.side_black.nbr_knights==2 && mqi.side_black.knights[0]==dst ) mqi.side_black.knights[0] = mqi.side_black.knights[1]; --mqi.side_black.nbr_knights; break; } case 'b': { --mqi.side_black.nbr_light_bishops; break; } case 'd': { --mqi.side_black.nbr_dark_bishops; break; } } } /*if( debug_trigger ) { char buf[9]; buf[8] = '\0'; cprintf( "before\n" ); for( int i=0; i<64; i+=8 ) { memcpy(buf,&mqi.squares[i],8); for( int k=0; k<8; k++ ) if( buf[k] == ' ' ) buf[k]='.'; cprintf( "%s\n", buf ); } } */ match = pm.Test( reverse, &mqi.side_white, &mqi.side_black, false, mqi.squares, false ); if( match ) { /*if( debug_trigger ) { cprintf( "Match!\n" ); debug_trigger = false; } */ offset_last = offset_first = offset; // later - separate offset_first and offset_last return true; } #ifdef SIMPLE_PATTERN_COUNT_OPTIMISATION if( total_count < ms.total_count_target ) return false; #endif // Black move code = *moves_in++; offset++; src=0; dst=0; hi_nibble = code&0xf0; captured=EMPTY_CHARACTER; switch( hi_nibble ) { case CODE_KING: { src = mqi.side_black.king; int delta=0; switch( code&0x0f ) // 0, 1, 2 { // 8, 9, 10 // 16,17,18 case 0: return false; // CODE_KING = 0, so '\0' string terminator case K_VECTOR_NW: delta = -9; break; // 0-9 case K_VECTOR_N: delta = -8; break; // 1-9 case K_VECTOR_NE: delta = -7; break; // 2-9 case K_VECTOR_W: delta = -1; break; // 8-9 case K_VECTOR_E: delta = 1; break; // 10-9 case K_VECTOR_SW: delta = 7; break; // 16-9 case K_VECTOR_S: delta = 8; break; // 17-9 case K_VECTOR_SE: delta = 9; break; // 18-9 case K_K_CASTLING: { delta = 2; int rook_offset = (mqi.side_black.rooks[0]==src+3 ? 0 : 1); // a rook will be 3 squares to right of king mqi.side_black.rooks[rook_offset] = src+1; // that rook ends up 1 square right of king // note that there is no way the rooks ordering can swap during castling mqi.squares[src+1] = 'r'; //f8 mqi.squares[src+3] = EMPTY_CHARACTER; //h8 break; } case K_Q_CASTLING: { delta = -2; int rook_offset = (mqi.side_black.rooks[0]==src-4 ? 0 : 1); // a rook will be 4 squares to left of king mqi.side_black.rooks[rook_offset] = src-1; // that rook ends up 1 square left of king // note that there is no way the rooks ordering can swap during castling mqi.squares[src-1] = 'r'; //d8 mqi.squares[src-4] = EMPTY_CHARACTER; //a8 break; } } mqi.side_black.king = dst = src+delta; captured = mqi.squares[dst]; mqi.squares[dst] = 'k'; mqi.squares[src] = EMPTY_CHARACTER; break; } case CODE_ROOK_LO: case CODE_ROOK_HI: { int rook_offset = (hi_nibble==CODE_ROOK_LO ? 0 : 1 ); src = mqi.side_black.rooks[rook_offset]; if( code & R_RANK ) // code encodes rank ? { dst = ((code<<3)&0x38) | (src&7); // same file as src, rank from code } else { dst = (src&0x38) | (code&7); // same rank as src, file from code } mqi.side_black.rooks[rook_offset] = dst; captured = mqi.squares[dst]; mqi.squares[dst] = 'r'; mqi.squares[src] = EMPTY_CHARACTER; // swap ? if( mqi.side_black.nbr_rooks==2 && mqi.side_black.rooks[0]>mqi.side_black.rooks[1] ) { int temp = mqi.side_black.rooks[0]; mqi.side_black.rooks[0] = mqi.side_black.rooks[1]; mqi.side_black.rooks[1] = temp; } break; } case CODE_BISHOP_DARK: { src = mqi.side_black.bishop_dark; int file_delta = (code&7) - (src&7); if( code & B_FALL ) // FALL\ + file dst = src + 9*file_delta; // eg src=b8(1), dst=h2(55), file_delta=6 -> 9*6 =54 else // RISE/ + file dst = src - 7*file_delta; // eg src=h8(7), dst=a1(56), file_delta=7 -> 7*7 =49 captured = mqi.squares[dst]; mqi.squares[dst] = 'd'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_black.bishop_dark = dst; break; } case CODE_BISHOP_LIGHT: { src = mqi.side_black.bishop_light; int file_delta = (code&7) - (src&7); if( code & B_FALL ) // FALL\ + file dst = src + 9*file_delta; // eg src=a8(0), dst=h1(63), file_delta=7 -> 9*7 =63 else // RISE/ + file dst = src - 7*file_delta; // eg src=g8(6), dst=a2(48), file_delta=6 -> 7*6 =42 captured = mqi.squares[dst]; mqi.squares[dst] = 'b'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_black.bishop_light = dst; break; } case CODE_QUEEN_ROOK: { src = mqi.side_black.queens[0]; if( code & R_RANK ) // code encodes rank ? dst = ((code<<3)&0x38) | (src&7); // same file as src, rank from code else dst = (src&0x38) | (code&7); // same rank as src, file from code captured = mqi.squares[dst]; mqi.squares[dst] = 'q'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_black.queens[0] = dst; break; } case CODE_QUEEN_BISHOP: { src = mqi.side_black.queens[0]; int file_delta = (code&7) - (src&7); if( code & B_FALL ) // FALL\ + file dst = src + 9*file_delta; // eg src=a8(0), dst=h1(63), file_delta=7 -> 9*7 =63 else // RISE/ + file dst = src - 7*file_delta; // eg src=h8(7), dst=a1(56), file_delta=7 -> 7*7 =49 captured = mqi.squares[dst]; mqi.squares[dst] = 'q'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_black.queens[0] = dst; break; } case CODE_KNIGHT: { int knight_offset = ((code&N_HI) ? 1 : 0 ); src = mqi.side_black.knights[knight_offset]; int delta=0; switch(code&7) // 0, 1, 2, 3 { // 8, 9, 10,11 // 16,17,18,19 // 24,25,26,27 case N_VECTOR_NNE: delta = -15; break; // 2-17 case N_VECTOR_NEE: delta = -6; break; // 11-17 case N_VECTOR_SEE: delta = 10; break; // 27-17 case N_VECTOR_SSE: delta = 17; break; // 27-10 case N_VECTOR_SSW: delta = 15; break; // 25-10 case N_VECTOR_SWW: delta = 6; break; // 16-10 case N_VECTOR_NWW: delta = -10; break; // 0-10 case N_VECTOR_NNW: delta = -17; break; // 0-17 } dst = src+delta; captured = mqi.squares[dst]; mqi.squares[dst] = 'n'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_black.knights[knight_offset] = dst; // swap ? if( mqi.side_black.nbr_knights==2 && mqi.side_black.knights[0]>mqi.side_black.knights[1] ) { int temp = mqi.side_black.knights[0]; mqi.side_black.knights[0] = mqi.side_black.knights[1]; mqi.side_black.knights[1] = temp; } break; } // PAWN default: { int pawn_offset = (code>>4)&0x07; src = mqi.side_black.pawns[pawn_offset]; int delta; switch( code&0x0f ) { default: { return false; // this code doesn't handle promotions } case P_DOUBLE: { delta = 16; dst = src+delta; mqi.squares[dst] = 'p'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_black.pawns[pawn_offset] = dst; break; } case P_SINGLE: { delta = 8; dst = src+delta; mqi.squares[dst] = 'p'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_black.pawns[pawn_offset] = dst; break; } case P_LEFT: { delta = 9; dst = src+delta; captured = mqi.squares[dst]; mqi.squares[dst] = 'p'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_black.pawns[pawn_offset] = dst; if( captured == EMPTY_CHARACTER ) { captured = 'P'; // en-passant mqi.squares[dst=src+1] = EMPTY_CHARACTER; } // Increasing capture possibly requires reordering Black pawns for( int i=pawn_offset; i+1<mqi.side_black.nbr_pawns && pawn_ordering[mqi.side_black.pawns[i]]>pawn_ordering[mqi.side_black.pawns[i+1]]; i++ ) { int temp = mqi.side_black.pawns[i]; mqi.side_black.pawns[i] = mqi.side_black.pawns[i+1]; mqi.side_black.pawns[i+1] = temp; } break; } case P_RIGHT: { delta = 7; dst = src+delta; captured = mqi.squares[dst]; mqi.squares[dst] = 'p'; mqi.squares[src] = EMPTY_CHARACTER; mqi.side_black.pawns[pawn_offset] = dst; if( captured == EMPTY_CHARACTER ) { captured = 'P'; // en-passant mqi.squares[dst=src-1] = EMPTY_CHARACTER; } // Decreasing capture possibly requires reordering Black pawns for( int i=pawn_offset; i-1>=0 && pawn_ordering[mqi.side_black.pawns[i-1]]>pawn_ordering[mqi.side_black.pawns[i]]; i-- ) { int temp = mqi.side_black.pawns[i-1]; mqi.side_black.pawns[i-1] = mqi.side_black.pawns[i]; mqi.side_black.pawns[i] = temp; } break; } } } // end switch on pawn types } // end switch all pieces // Black captures white if( captured != EMPTY_CHARACTER ) { total_count--; switch( captured ) { case 'P': { bool zap=false; for( int i=0; i<mqi.side_white.nbr_pawns-1; i++ ) { if( zap ) mqi.side_white.pawns[i] = mqi.side_white.pawns[i+1]; else if( mqi.side_white.pawns[i] == dst ) { zap = true; mqi.side_white.pawns[i] = mqi.side_white.pawns[i+1]; } } --mqi.side_white.nbr_pawns; break; } case 'Q': { --mqi.side_white.nbr_queens; break; } case 'R': { if( mqi.side_white.nbr_rooks==2 && mqi.side_white.rooks[0]==dst ) mqi.side_white.rooks[0] = mqi.side_white.rooks[1]; --mqi.side_white.nbr_rooks; break; } case 'N': { if( mqi.side_white.nbr_knights==2 && mqi.side_white.knights[0]==dst ) mqi.side_white.knights[0] = mqi.side_white.knights[1]; --mqi.side_white.nbr_knights; break; } case 'B': { --mqi.side_white.nbr_light_bishops; break; } case 'D': { --mqi.side_white.nbr_dark_bishops; break; } } } } //return false; // unreachable } bool MemoryPositionSearch::SearchGameSlowPromotionAllowed( const std::string &moves_in, unsigned short &offset_first, unsigned short &offset_last ) // semi fast { bool target_white = search_position.white; // searching for position with white to move? int black_count=16; int black_pawn_count=8; int white_count=16; int white_pawn_count=8; SlowGameInit(); int len = moves_in.size(); if( (msi.cr.white == target_white) && *ms.slow_rank3_ptr == *ms.slow_rank3_target_ptr && *ms.slow_rank4_ptr == *ms.slow_rank4_target_ptr && *ms.slow_rank5_ptr == *ms.slow_rank5_target_ptr && *ms.slow_rank6_ptr == *ms.slow_rank6_target_ptr && *ms.slow_rank7_ptr == *ms.slow_rank7_target_ptr && *ms.slow_rank8_ptr == *ms.slow_rank8_target_ptr && *ms.slow_rank1_ptr == *ms.slow_rank1_target_ptr && *ms.slow_rank2_ptr == *ms.slow_rank2_target_ptr ) { offset_last = offset_first = 0; // later - separate offset_first and offset_last return true; } for( int i=0; i<len; i++ ) { MpsSide *side = msi.cr.white ? &msi.sides[0] : &msi.sides[1]; MpsSide *other = msi.cr.white ? &msi.sides[1] : &msi.sides[0]; char code = moves_in[i]; thc::Move mv; if( side->fast_mode ) { mv = UncompressFastMode(code,side,other); } else if( TryFastMode(side) ) { mv = UncompressFastMode(code,side,other); } else { mv = UncompressSlowMode(code); other->fast_mode = false; // force other side to reset and retry } char mover = msi.cr.squares[mv.src]; //std::string mvs = mv.NaturalOut(&msi.cr); msi.cr.PlayMove(mv); if( mv.special == thc::SPECIAL_PROMOTION_BISHOP ) // Impose the distinct dark squared bishop = 'd'/'D' convention over the top { if( is_dark(mv.dst) ) { char c = msi.cr.squares[mv.dst]; if( c == 'B' ) c = 'D'; else if( c == 'b' ) c = 'd'; msi.cr.squares[mv.dst] = c; } } //std::string s = msi.cr.ToDebugStr(); //cprintf( "After %s\n%s\n", mvs.c_str(), s.c_str() ); if( (msi.cr.white == target_white) && *ms.slow_rank3_ptr == *ms.slow_rank3_target_ptr && *ms.slow_rank4_ptr == *ms.slow_rank4_target_ptr && *ms.slow_rank5_ptr == *ms.slow_rank5_target_ptr && *ms.slow_rank6_ptr == *ms.slow_rank6_target_ptr && *ms.slow_rank7_ptr == *ms.slow_rank7_target_ptr && *ms.slow_rank8_ptr == *ms.slow_rank8_target_ptr && *ms.slow_rank1_ptr == *ms.slow_rank1_target_ptr && *ms.slow_rank2_ptr == *ms.slow_rank2_target_ptr ) { offset_last = offset_first = (i+1); // later - separate offset_first and offset_last return true; } if( mover=='P' && 48<=mv.src && mv.src<56 && !SLOW_WHITE_HOME_ROW_TEST ) return false; if( mover=='p' && 8<=mv.src && mv.src<16 && !SLOW_BLACK_HOME_ROW_TEST ) return false; if( isalpha(mv.capture) ) { if( islower(mv.capture) ) { black_count--; if( black_count < ms.black_count_target ) return false; if( mv.capture == 'p' ) { black_pawn_count--; // pawns can also disappear at promotion time // disregarding that means we sometimes // continue searching unnecessarily but // doesn't cause errors if( black_pawn_count < ms.black_pawn_count_target ) return false; if( 8<=mv.dst && mv.dst<16 && !SLOW_BLACK_HOME_ROW_TEST ) return false; } } else { white_count--; if( white_count < ms.white_count_target ) return false; if( mv.capture == 'P' ) { white_pawn_count--; // pawns can also disappear at promotion time // disregarding that means we sometimes // continue searching unnecessarily but // doesn't cause errors if( white_pawn_count < ms.white_pawn_count_target ) return false; if( 48<=mv.dst && mv.dst<56 && !SLOW_WHITE_HOME_ROW_TEST ) return false; } } } } return false; } bool MemoryPositionSearch::PatternSearchGameSlowPromotionAllowed( PatternMatch &pm, bool &reverse, const std::string &moves_in, unsigned short &offset_first, unsigned short &offset_last ) // semi fast { int total_count=30; // 32 - 2 kings SlowGameInit(); int len = moves_in.size(); bool match = pm.Test( reverse, &msi.sides[0], &msi.sides[1], msi.cr.white, msi.cr.squares, false ); if( match ) { offset_last = offset_first = 0; // later - separate offset_first and offset_last return true; } for( int i=0; i<len; i++ ) { MpsSide *side = msi.cr.white ? &msi.sides[0] : &msi.sides[1]; MpsSide *other = msi.cr.white ? &msi.sides[1] : &msi.sides[0]; char code = moves_in[i]; thc::Move mv; if( side->fast_mode ) { mv = UncompressFastMode(code,side,other); } else if( TryFastMode(side) ) { mv = UncompressFastMode(code,side,other); } else { mv = UncompressSlowMode(code); other->fast_mode = false; // force other side to reset and retry } msi.cr.PlayMove(mv); if( mv.special == thc::SPECIAL_PROMOTION_BISHOP ) // Impose the distinct dark squared bishop = 'd'/'D' convention over the top { if( is_dark(mv.dst) ) { char c = msi.cr.squares[mv.dst]; if( c == 'B' ) c = 'D'; else if( c == 'b' ) c = 'd'; msi.cr.squares[mv.dst] = c; } } match = pm.Test( reverse, &msi.sides[0], &msi.sides[1], msi.cr.white, msi.cr.squares, true ); if( match ) { offset_last = offset_first = (i+1); // later - separate offset_first and offset_last return true; } #ifdef SIMPLE_PATTERN_COUNT_OPTIMISATION if( isalpha(mv.capture) ) { total_count--; if( total_count < ms.total_count_target ) return false; } #endif } return false; }
// Copyright (c) 2012-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "wallet/wallet.h" #include "wallet/walletdb.h" #include "test/test_linc.h" #include <stdint.h> #include <boost/foreach.hpp> #include <boost/test/unit_test.hpp> extern CWallet* pwalletMain; BOOST_FIXTURE_TEST_SUITE(accounting_tests, TestingSetup) static void GetResults(CWalletDB& walletdb, std::map<CAmount, CAccountingEntry>& results) { std::list<CAccountingEntry> aes; results.clear(); BOOST_CHECK(walletdb.ReorderTransactions(pwalletMain) == DB_LOAD_OK); walletdb.ListAccountCreditDebit("", aes); BOOST_FOREACH(CAccountingEntry& ae, aes) { results[ae.nOrderPos] = ae; } } BOOST_AUTO_TEST_CASE(acc_orderupgrade) { CWalletDB walletdb(pwalletMain->strWalletFile); std::vector<CWalletTx*> vpwtx; CWalletTx wtx; CAccountingEntry ae; std::map<CAmount, CAccountingEntry> results; LOCK(pwalletMain->cs_wallet); ae.strAccount = ""; ae.nCreditDebit = 1; ae.nTime = 1333333333; ae.strOtherAccount = "b"; ae.strComment = ""; pwalletMain->AddAccountingEntry(ae, walletdb); wtx.mapValue["comment"] = "z"; pwalletMain->AddToWallet(wtx, false, &walletdb); vpwtx.push_back(&pwalletMain->mapWallet[wtx.GetHash()]); vpwtx[0]->nTimeReceived = (unsigned int)1333333335; vpwtx[0]->nOrderPos = -1; ae.nTime = 1333333336; ae.strOtherAccount = "c"; pwalletMain->AddAccountingEntry(ae, walletdb); GetResults(walletdb, results); BOOST_CHECK(pwalletMain->nOrderPosNext == 3); BOOST_CHECK(2 == results.size()); BOOST_CHECK(results[0].nTime == 1333333333); BOOST_CHECK(results[0].strComment.empty()); BOOST_CHECK(1 == vpwtx[0]->nOrderPos); BOOST_CHECK(results[2].nTime == 1333333336); BOOST_CHECK(results[2].strOtherAccount == "c"); ae.nTime = 1333333330; ae.strOtherAccount = "d"; ae.nOrderPos = pwalletMain->IncOrderPosNext(); pwalletMain->AddAccountingEntry(ae, walletdb); GetResults(walletdb, results); BOOST_CHECK(results.size() == 3); BOOST_CHECK(pwalletMain->nOrderPosNext == 4); BOOST_CHECK(results[0].nTime == 1333333333); BOOST_CHECK(1 == vpwtx[0]->nOrderPos); BOOST_CHECK(results[2].nTime == 1333333336); BOOST_CHECK(results[3].nTime == 1333333330); BOOST_CHECK(results[3].strComment.empty()); wtx.mapValue["comment"] = "y"; { CMutableTransaction tx(wtx); --tx.nLockTime; // Just to change the hash :) *static_cast<CTransaction*>(&wtx) = CTransaction(tx); } pwalletMain->AddToWallet(wtx, false, &walletdb); vpwtx.push_back(&pwalletMain->mapWallet[wtx.GetHash()]); vpwtx[1]->nTimeReceived = (unsigned int)1333333336; wtx.mapValue["comment"] = "x"; { CMutableTransaction tx(wtx); --tx.nLockTime; // Just to change the hash :) *static_cast<CTransaction*>(&wtx) = CTransaction(tx); } pwalletMain->AddToWallet(wtx, false, &walletdb); vpwtx.push_back(&pwalletMain->mapWallet[wtx.GetHash()]); vpwtx[2]->nTimeReceived = (unsigned int)1333333329; vpwtx[2]->nOrderPos = -1; GetResults(walletdb, results); BOOST_CHECK(results.size() == 3); BOOST_CHECK(pwalletMain->nOrderPosNext == 6); BOOST_CHECK(0 == vpwtx[2]->nOrderPos); BOOST_CHECK(results[1].nTime == 1333333333); BOOST_CHECK(2 == vpwtx[0]->nOrderPos); BOOST_CHECK(results[3].nTime == 1333333336); BOOST_CHECK(results[4].nTime == 1333333330); BOOST_CHECK(results[4].strComment.empty()); BOOST_CHECK(5 == vpwtx[1]->nOrderPos); ae.nTime = 1333333334; ae.strOtherAccount = "e"; ae.nOrderPos = -1; pwalletMain->AddAccountingEntry(ae, walletdb); GetResults(walletdb, results); BOOST_CHECK(results.size() == 4); BOOST_CHECK(pwalletMain->nOrderPosNext == 7); BOOST_CHECK(0 == vpwtx[2]->nOrderPos); BOOST_CHECK(results[1].nTime == 1333333333); BOOST_CHECK(2 == vpwtx[0]->nOrderPos); BOOST_CHECK(results[3].nTime == 1333333336); BOOST_CHECK(results[3].strComment.empty()); BOOST_CHECK(results[4].nTime == 1333333330); BOOST_CHECK(results[4].strComment.empty()); BOOST_CHECK(results[5].nTime == 1333333334); BOOST_CHECK(6 == vpwtx[1]->nOrderPos); } BOOST_AUTO_TEST_SUITE_END()
#include <cassert> #include <climits> #include "memor.h" using namespace std; namespace MD { //class MEMOR memor::~memor() { for(int i = 0; i < memos.size(); ++i) myVectMemdel(memos.at(i)); } const memor& memor::operator =(const memor& sMemo) { if(memos.size() != sMemo.obNmemor()) { if(memos.size() < sMemo.obNmemor()) for(int i = 0; i < (sMemo.obNmemor() - memos.size()); ++i) memos.push_back(myVectMalloc(DIM)); if(memos.size() > sMemo.obNmemor()) for(int i = 0; i < (memos.size() - sMemo.obNmemor()); ++i) memos.pop_back(); } for(int i = 0; i < sMemo.obNmemor(); ++i) myVectCpy(memos.at(i), sMemo.obMemo(i)); mPos = sMemo.obMpos(); } void memor::adMemo(const int size) { assert(size >= 0 && size < INT_MAX); memos.clear(); for(int i = 0; i < size; ++i) memos.push_back(myVectMalloc(DIM)); mPos = memos.size(); } void memor::nwMemo(const myVect* sVect) { assert(memos.size() > 0); mPos = (mPos + 1) % memos.size(); myVectCpy(memos.at(mPos), sVect); } void memor::mkMemo(const myVect* sVect, const int indx) { assert(memos.size() > 0); int cPos = (mPos - indx) % ((signed int) memos.size()); myVectCpy(memos.at((cPos >= 0) ? cPos : (cPos + memos.size())), sVect); } const myVect* memor::obMemo(const int indx) const { assert(memos.size() > 0); int cPos = (mPos - indx) % ((signed int) memos.size()); return memos.at((cPos >= 0) ? cPos : (cPos + memos.size())); } //class DMEMO pmemo::pmemo() { mLen = 0; updt = false; } template <class type> void pmemo::adPmem(const int size, const vector<type>* objcs) { //void pmemo::adPmem(const int size, const vector<partk>* objcs) { assert(size >= 0 && size < INT_MAX); memos.clear(); for(int i = 0; i < (size * (*objcs).size() * ((*objcs).size() - 1) / 2); ++i) memos.push_back(myVectMalloc(DIM)); mLen = size; mPos = mLen; updt = true; } template void pmemo::adPmem(const int, const vector<partk>*); void pmemo::nwMpos() { assert(mLen > 0); mPos = (mPos + 1) % mLen; updt = true; } template <class type> void pmemo::nwPmem(const myVect* sVect, const vector<type>* parts, const type* atom1, const type* atom2) { //void pmemo::nwPmem(const myVect* sVect, const vector<partk>* parts, // const partk* atom1, const partk* atom2) { assert(mLen > 0); int pos1, pos2 = obPInd (parts, atom1, atom2); pos1 = (mPos + 1) % mLen; updt = false; myVectCpy(memos.at(pos1 + (pos2 * mLen)), sVect); } template void pmemo::nwPmem(const myVect*, const vector<partk>*, const partk*, const partk*); template <class type> void pmemo::mkPmem(const myVect* sVect, const vector<type>* parts, const type* atom1, const type* atom2, const int indx) { //void pmemo::mkPmem(const myVect* sVect, const vector<partk>* parts, // const partk* atom1, const partk* atom2, const int indx) { assert(mLen > 0); int pos1, pos2 = obPInd (parts, atom1, atom2); pos1 = (mPos - indx) % mLen; pos1 = (pos1 >= 0) ? pos1 : (pos1 + mLen); myVectCpy(memos.at(pos1 + (pos2 * mLen)), sVect); } template void pmemo::mkPmem(const myVect*, const vector<partk>*, const partk*, const partk*, const int); template <class type> const myVect* pmemo::obPmem(const vector<type>* parts, const type* atom1, const type* atom2, const int indx) const { //const myVect* pmemo::obPmem(const vector<partk>* parts, const partk* atom1, // const partk* atom2, const int indx) const { assert((mLen > 0) && updt); if(!updt) cerr << "Memory is not updated" << endl; int pos1, pos2 = obPInd (parts, atom1, atom2); pos1 = (mPos - indx) % mLen; pos1 = (pos1 >= 0) ? pos1 : (pos1 + mLen); return memos.at(pos1 + (pos2 * mLen)); } template const myVect* pmemo::obPmem(const vector<partk>*, const partk*, const partk*, const int) const; //class AUXMM //BUG: how do I know if post and velo haven't been pre-allocated //somewhere else auxMm::auxMm(const auxMm& sMemo) { post = myVectMalloc((*(sMemo.obPost())).size); velo = myVectMalloc((*(sMemo.obVelo())).size); myVectCpy(post, sMemo.obPost()); myVectCpy(velo, sMemo.obVelo()); } auxMm::auxMm(const int size) { assert(size >= 0 && size < INT_MAX); post = myVectMalloc(size); velo = myVectMalloc(size); } auxMm::~auxMm() { myVectMemdel(post); myVectMemdel(velo); } //BUG: if the target has not been pre-allocated, this gives segfault const auxMm& auxMm::operator =(const auxMm& sMemo) { if((*post).size != (*(sMemo.obPost())).size) { myVectMemdel(post); myVectMemdel(velo); post = myVectMalloc((*(sMemo.obPost())).size); velo = myVectMalloc((*(sMemo.obPost())).size); } myVectCpy(post, sMemo.obPost()); myVectCpy(velo, sMemo.obVelo()); } void auxMm::adMemo(const int size) { assert(size >= 0 && size < INT_MAX); myVectMemdel(post); myVectMemdel(velo); post = myVectMalloc(size); velo = myVectMalloc(size); } void auxMm::iniTrj(istream& iput) { myCoor n; for(int i = 0; i < (*post).size; ++i) { iput >> n; myVectSet(post, i, n); } } void auxMm::nxtStp() { myVectScl(velo, STPSZE); myVectAdd(post, velo); } void auxMm::wrTraj(ostream& oput) const { for(int i = 0; i < (*post).size; ++i) oput << myVectGet(post, i) << '\t'; oput << endl; } //NON-MEMBER FUNCTIONS }
#include "settings.h" namespace { const QString SETTINGS_FILE_NAME = "Settings.json"; } Settings& Settings::instance() { static Settings settings; return settings; } void Settings::setLastLogin(QString login) { lastFirstName = ""; lastSurname = ""; lastLogin = login; write(); } void Settings::setLastLogin(QString firstName, QString surname, QString login) { lastFirstName = firstName; lastSurname = surname; lastLogin = login; write(); } Settings::Settings() : TrainingSettings(SETTINGS_FILE_NAME) {}
/* * Copyright (c) 2012-2013, 2015 ARM Limited * All rights reserved. * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2002-2005 The Regents of The University of Michigan * Copyright (c) 2010 Advanced Micro Devices, Inc. * 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 holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Erik Hallnor * Dave Greene */ /** * @file * Miss Status and Handling Register (MSHR) definitions. */ #include <algorithm> #include <cassert> #include <string> #include <vector> #include "base/misc.hh" #include "base/types.hh" #include "debug/Cache.hh" #include "mem/cache/cache.hh" #include "mem/cache/mshr.hh" #include "sim/core.hh" using namespace std; MSHR::MSHR() : readyTime(0), _isUncacheable(false), downstreamPending(false), pendingDirty(false), postInvalidate(false), postDowngrade(false), queue(NULL), order(0), blkAddr(0), blkSize(0), isSecure(false), inService(false), isForward(false), threadNum(InvalidThreadID), data(NULL) { } MSHR::TargetList::TargetList() : needsExclusive(false), hasUpgrade(false) {} inline void MSHR::TargetList::add(PacketPtr pkt, Tick readyTime, Counter order, Target::Source source, bool markPending) { if (source != Target::FromSnoop) { if (pkt->needsExclusive()) { needsExclusive = true; } // StoreCondReq is effectively an upgrade if it's in an MSHR // since it would have been failed already if we didn't have a // read-only copy if (pkt->isUpgrade() || pkt->cmd == MemCmd::StoreCondReq) { hasUpgrade = true; } } if (markPending) { // Iterate over the SenderState stack and see if we find // an MSHR entry. If we do, set the downstreamPending // flag. Otherwise, do nothing. MSHR *mshr = pkt->findNextSenderState<MSHR>(); if (mshr != NULL) { assert(!mshr->downstreamPending); mshr->downstreamPending = true; } else { // No need to clear downstreamPending later markPending = false; } } emplace_back(pkt, readyTime, order, source, markPending); } static void replaceUpgrade(PacketPtr pkt) { if (pkt->cmd == MemCmd::UpgradeReq) { pkt->cmd = MemCmd::ReadExReq; DPRINTF(Cache, "Replacing UpgradeReq with ReadExReq\n"); } else if (pkt->cmd == MemCmd::SCUpgradeReq) { pkt->cmd = MemCmd::SCUpgradeFailReq; DPRINTF(Cache, "Replacing SCUpgradeReq with SCUpgradeFailReq\n"); } else if (pkt->cmd == MemCmd::StoreCondReq) { pkt->cmd = MemCmd::StoreCondFailReq; DPRINTF(Cache, "Replacing StoreCondReq with StoreCondFailReq\n"); } } void MSHR::TargetList::replaceUpgrades() { if (!hasUpgrade) return; for (auto& t : *this) { replaceUpgrade(t.pkt); } hasUpgrade = false; } void MSHR::TargetList::clearDownstreamPending() { for (auto& t : *this) { if (t.markedPending) { // Iterate over the SenderState stack and see if we find // an MSHR entry. If we find one, clear the // downstreamPending flag by calling // clearDownstreamPending(). This recursively clears the // downstreamPending flag in all caches this packet has // passed through. MSHR *mshr = t.pkt->findNextSenderState<MSHR>(); if (mshr != NULL) { mshr->clearDownstreamPending(); } } } } bool MSHR::TargetList::checkFunctional(PacketPtr pkt) { for (auto& t : *this) { if (pkt->checkFunctional(t.pkt)) { return true; } } return false; } void MSHR::TargetList::print(std::ostream &os, int verbosity, const std::string &prefix) const { for (auto& t : *this) { const char *s; switch (t.source) { case Target::FromCPU: s = "FromCPU"; break; case Target::FromSnoop: s = "FromSnoop"; break; case Target::FromPrefetcher: s = "FromPrefetcher"; break; default: s = ""; break; } ccprintf(os, "%s%s: ", prefix, s); t.pkt->print(os, verbosity, ""); } } void MSHR::allocate(Addr blk_addr, unsigned blk_size, PacketPtr target, Tick when_ready, Counter _order) { blkAddr = blk_addr; blkSize = blk_size; isSecure = target->isSecure(); readyTime = when_ready; order = _order; assert(target); isForward = false; _isUncacheable = target->req->isUncacheable(); inService = false; downstreamPending = false; threadNum = 0; assert(targets.isReset()); // Don't know of a case where we would allocate a new MSHR for a // snoop (mem-side request), so set source according to request here Target::Source source = (target->cmd == MemCmd::HardPFReq) ? Target::FromPrefetcher : Target::FromCPU; targets.add(target, when_ready, _order, source, true); assert(deferredTargets.isReset()); data = NULL; } void MSHR::clearDownstreamPending() { assert(downstreamPending); downstreamPending = false; // recursively clear flag on any MSHRs we will be forwarding // responses to targets.clearDownstreamPending(); } bool MSHR::markInService(bool pending_dirty_resp) { assert(!inService); if (isForwardNoResponse()) { // we just forwarded the request packet & don't expect a // response, so get rid of it assert(getNumTargets() == 1); popTarget(); return true; } inService = true; pendingDirty = targets.needsExclusive || pending_dirty_resp; postInvalidate = postDowngrade = false; if (!downstreamPending) { // let upstream caches know that the request has made it to a // level where it's going to get a response targets.clearDownstreamPending(); } return false; } void MSHR::deallocate() { assert(targets.empty()); targets.resetFlags(); assert(deferredTargets.isReset()); inService = false; } /* * Adds a target to an MSHR */ void MSHR::allocateTarget(PacketPtr pkt, Tick whenReady, Counter _order) { // assume we'd never issue a prefetch when we've got an // outstanding miss assert(pkt->cmd != MemCmd::HardPFReq); // uncacheable accesses always allocate a new MSHR, and cacheable // accesses ignore any uncacheable MSHRs, thus we should never // have targets addded if originally allocated uncacheable assert(!_isUncacheable); // if there's a request already in service for this MSHR, we will // have to defer the new target until after the response if any of // the following are true: // - there are other targets already deferred // - there's a pending invalidate to be applied after the response // comes back (but before this target is processed) // - this target requires an exclusive block and either we're not // getting an exclusive block back or we have already snooped // another read request that will downgrade our exclusive block // to shared if (inService && (!deferredTargets.empty() || hasPostInvalidate() || (pkt->needsExclusive() && (!isPendingDirty() || hasPostDowngrade() || isForward)))) { // need to put on deferred list if (hasPostInvalidate()) replaceUpgrade(pkt); deferredTargets.add(pkt, whenReady, _order, Target::FromCPU, true); } else { // No request outstanding, or still OK to append to // outstanding request: append to regular target list. Only // mark pending if current request hasn't been issued yet // (isn't in service). targets.add(pkt, whenReady, _order, Target::FromCPU, !inService); } } bool MSHR::handleSnoop(PacketPtr pkt, Counter _order) { DPRINTF(Cache, "%s for %s addr %#llx size %d\n", __func__, pkt->cmdString(), pkt->getAddr(), pkt->getSize()); if (!inService || (pkt->isExpressSnoop() && downstreamPending)) { // Request has not been issued yet, or it's been issued // locally but is buffered unissued at some downstream cache // which is forwarding us this snoop. Either way, the packet // we're snooping logically precedes this MSHR's request, so // the snoop has no impact on the MSHR, but must be processed // in the standard way by the cache. The only exception is // that if we're an L2+ cache buffering an UpgradeReq from a // higher-level cache, and the snoop is invalidating, then our // buffered upgrades must be converted to read exclusives, // since the upper-level cache no longer has a valid copy. // That is, even though the upper-level cache got out on its // local bus first, some other invalidating transaction // reached the global bus before the upgrade did. if (pkt->needsExclusive()) { targets.replaceUpgrades(); deferredTargets.replaceUpgrades(); } return false; } // From here on down, the request issued by this MSHR logically // precedes the request we're snooping. if (pkt->needsExclusive()) { // snooped request still precedes the re-request we'll have to // issue for deferred targets, if any... deferredTargets.replaceUpgrades(); } if (hasPostInvalidate()) { // a prior snoop has already appended an invalidation, so // logically we don't have the block anymore; no need for // further snooping. return true; } if (isPendingDirty() || pkt->isInvalidate()) { // We need to save and replay the packet in two cases: // 1. We're awaiting an exclusive copy, so ownership is pending, // and we need to respond after we receive data. // 2. It's an invalidation (e.g., UpgradeReq), and we need // to forward the snoop up the hierarchy after the current // transaction completes. // Actual target device (typ. a memory) will delete the // packet on reception, so we need to save a copy here. // Clear flags and also allocate new data as the original // packet data storage may have been deleted by the time we // get to send this packet. PacketPtr cp_pkt = nullptr; if (isPendingDirty()) { // Case 1: The new packet will need to get the response from the // MSHR already queued up here cp_pkt = new Packet(pkt, true, true); pkt->assertMemInhibit(); // in the case of an uncacheable request there is no need // to set the exclusive flag, but since the recipient does // not care there is no harm in doing so pkt->setSupplyExclusive(); } else { // Case 2: We only need to buffer the packet for information // purposes; the original request can proceed without waiting // => Create a copy of the request, as that may get deallocated as // well cp_pkt = new Packet(new Request(*pkt->req), pkt->cmd); DPRINTF(Cache, "Copying packet %p -> %p and request %p -> %p\n", pkt, cp_pkt, pkt->req, cp_pkt->req); } targets.add(cp_pkt, curTick(), _order, Target::FromSnoop, downstreamPending && targets.needsExclusive); if (pkt->needsExclusive()) { // This transaction will take away our pending copy postInvalidate = true; } } if (!pkt->needsExclusive() && !pkt->req->isUncacheable()) { // This transaction will get a read-shared copy, downgrading // our copy if we had an exclusive one postDowngrade = true; pkt->assertShared(); } return true; } bool MSHR::promoteDeferredTargets() { assert(targets.empty()); if (deferredTargets.empty()) { return false; } // swap targets & deferredTargets lists std::swap(targets, deferredTargets); // clear deferredTargets flags deferredTargets.resetFlags(); order = targets.front().order; readyTime = std::max(curTick(), targets.front().readyTime); return true; } void MSHR::promoteExclusive() { if (deferredTargets.needsExclusive && !(hasPostInvalidate() || hasPostDowngrade())) { // We got an exclusive response, but we have deferred targets // which are waiting to request an exclusive copy (not because // of a pending invalidate). This can happen if the original // request was for a read-only (non-exclusive) block, but we // got an exclusive copy anyway because of the E part of the // MOESI/MESI protocol. Since we got the exclusive copy // there's no need to defer the targets, so move them up to // the regular target list. assert(!targets.needsExclusive); targets.needsExclusive = true; // if any of the deferred targets were upper-level cache // requests marked downstreamPending, need to clear that assert(!downstreamPending); // not pending here anymore deferredTargets.clearDownstreamPending(); // this clears out deferredTargets too targets.splice(targets.end(), deferredTargets); deferredTargets.resetFlags(); } } bool MSHR::checkFunctional(PacketPtr pkt) { // For printing, we treat the MSHR as a whole as single entity. // For other requests, we iterate over the individual targets // since that's where the actual data lies. if (pkt->isPrint()) { pkt->checkFunctional(this, blkAddr, isSecure, blkSize, NULL); return false; } else { return (targets.checkFunctional(pkt) || deferredTargets.checkFunctional(pkt)); } } void MSHR::print(std::ostream &os, int verbosity, const std::string &prefix) const { ccprintf(os, "%s[%#llx:%#llx](%s) %s %s %s state: %s %s %s %s %s\n", prefix, blkAddr, blkAddr + blkSize - 1, isSecure ? "s" : "ns", isForward ? "Forward" : "", isForwardNoResponse() ? "ForwNoResp" : "", needsExclusive() ? "Excl" : "", _isUncacheable ? "Unc" : "", inService ? "InSvc" : "", downstreamPending ? "DwnPend" : "", hasPostInvalidate() ? "PostInv" : "", hasPostDowngrade() ? "PostDowngr" : ""); ccprintf(os, "%s Targets:\n", prefix); targets.print(os, verbosity, prefix + " "); if (!deferredTargets.empty()) { ccprintf(os, "%s Deferred Targets:\n", prefix); deferredTargets.print(os, verbosity, prefix + " "); } } std::string MSHR::print() const { ostringstream str; print(str); return str.str(); }
// Copyright information can be found in the file named COPYING // located in the root directory of this distribution. #include "platformX86UNIX/platformX86UNIX.h" #include "console/consoleTypes.h" #include "platform/event.h" #include "platform/gameInterface.h" #include "platformX86UNIX/x86UNIXState.h" #include "platformX86UNIX/x86UNIXInputManager.h" #include "math/mMathFn.h" #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xatom.h> #include <X11/keysym.h> #include <SDL/SDL.h> // ascii table AsciiData AsciiTable[NUM_KEYS]; // keymap table static const U32 SDLtoTKeyMapSize = SDLK_LAST; static U8 SDLtoTKeyMap[SDLtoTKeyMapSize]; static bool keyMapsInitialized = false; // helper functions static void MapKey(Uint16 SDLkey, U8 tkey, KeySym xkeysym); static void InitKeyMaps(); static inline U8 TranslateSDLKeytoTKey(SDLKey keysym); // unix platform state extern x86UNIXPlatformState * x86UNIXState; // constants static const U32 MouseMask = SDL_MOUSEEVENTMASK; static const U32 KeyboardMask = SDL_KEYUPMASK | SDL_KEYDOWNMASK; static const U32 JoystickMask = SDL_JOYEVENTMASK; static const U32 AllInputEvents = MouseMask | KeyboardMask | JoystickMask; // defined in SDL extern "C" Uint16 X11_KeyToUnicode( SDLKey keysym, SDLMod modifiers ); //============================================================================== // Static helper functions //============================================================================== static void MapKey(Uint16 SDLkey, U8 tkey, KeySym xkeysym) { DisplayPtrManager xdisplay; Display* display = xdisplay.getDisplayPointer(); SDLtoTKeyMap[SDLkey] = tkey; Uint16 key = 0; SDLKey skey = (SDLKey)SDLkey; SDLMod mod = KMOD_NONE; // lower case key = X11_KeyToUnicode( skey, mod ); AsciiTable[tkey].lower.ascii = key; // upper case mod = KMOD_LSHIFT; key = X11_KeyToUnicode( skey, mod ); AsciiTable[tkey].upper.ascii = key; // goofy (i18n) case mod = KMOD_MODE; key = X11_KeyToUnicode( skey, mod ); AsciiTable[tkey].goofy.ascii = key; #if 0 if (xkeysym == 0) return; XKeyPressedEvent fooKey; const int keybufSize = 256; char keybuf[keybufSize]; // find the x keycode for the keysym KeyCode xkeycode = XKeysymToKeycode( display, xkeysym); // Display *dpy = XOpenDisplay(NULL); // KeyCode xkeycode = XKeysymToKeycode( // dpy, xkeysym); if (!xkeycode) return; // create an event with the keycode dMemset(&fooKey, 0, sizeof(fooKey)); fooKey.type = KeyPress; fooKey.display = display; fooKey.window = DefaultRootWindow(display); fooKey.time = CurrentTime; fooKey.keycode = xkeycode; // translate the event with no modifiers (yields lowercase) KeySym dummyKeySym; int numChars = XLookupString( &fooKey, keybuf, keybufSize, &dummyKeySym, NULL); if (numChars) { //Con::printf("assigning lowercase string %c", *keybuf); // ignore everything but first char AsciiTable[tkey].lower.ascii = *keybuf; AsciiTable[tkey].goofy.ascii = *keybuf; } // translate the event with shift modifier (yields uppercase) fooKey.state |= ShiftMask; numChars = XLookupString(&fooKey, keybuf, keybufSize, &dummyKeySym, NULL); if (numChars) { //Con::printf("assigning uppercase string %c", *keybuf); // ignore everything but first char AsciiTable[tkey].upper.ascii = *keybuf; } #endif } //------------------------------------------------------------------------------ void InitKeyMaps() { dMemset( &AsciiTable, 0, sizeof( AsciiTable ) ); dMemset(SDLtoTKeyMap, KEY_NULL, SDLtoTKeyMapSize); // set up the X to Torque key map // stuff MapKey(SDLK_BACKSPACE, KEY_BACKSPACE, XK_BackSpace); MapKey(SDLK_TAB, KEY_TAB, XK_Tab); MapKey(SDLK_RETURN, KEY_RETURN, XK_Return); MapKey(SDLK_PAUSE, KEY_PAUSE, XK_Pause); MapKey(SDLK_CAPSLOCK, KEY_CAPSLOCK, XK_Caps_Lock); MapKey(SDLK_ESCAPE, KEY_ESCAPE, XK_Escape); // more stuff MapKey(SDLK_SPACE, KEY_SPACE, XK_space); MapKey(SDLK_PAGEDOWN, KEY_PAGE_DOWN, XK_Page_Down); MapKey(SDLK_PAGEUP, KEY_PAGE_UP, XK_Page_Up); MapKey(SDLK_END, KEY_END, XK_End); MapKey(SDLK_HOME, KEY_HOME, XK_Home); MapKey(SDLK_LEFT, KEY_LEFT, XK_Left); MapKey(SDLK_UP, KEY_UP, XK_Up); MapKey(SDLK_RIGHT, KEY_RIGHT, XK_Right); MapKey(SDLK_DOWN, KEY_DOWN, XK_Down); MapKey(SDLK_PRINT, KEY_PRINT, XK_Print); MapKey(SDLK_INSERT, KEY_INSERT, XK_Insert); MapKey(SDLK_DELETE, KEY_DELETE, XK_Delete); S32 keysym; S32 tkeycode; KeySym xkey; // main numeric keys for (keysym = SDLK_0, tkeycode = KEY_0, xkey = XK_0; keysym <= SDLK_9; ++keysym, ++tkeycode, ++xkey) MapKey(static_cast<SDLKey>(keysym), tkeycode, xkey); // lowercase letters for (keysym = SDLK_a, tkeycode = KEY_A, xkey = XK_a; keysym <= SDLK_z; ++keysym, ++tkeycode, ++xkey) MapKey(static_cast<SDLKey>(keysym), tkeycode, xkey); // various punctuation MapKey('|', KEY_TILDE, XK_grave); MapKey(SDLK_BACKQUOTE, KEY_TILDE, XK_grave); MapKey(SDLK_MINUS, KEY_MINUS, XK_minus); MapKey(SDLK_EQUALS, KEY_EQUALS, XK_equal); MapKey(SDLK_LEFTBRACKET, KEY_LBRACKET, XK_bracketleft); MapKey('{', KEY_LBRACKET, XK_bracketleft); MapKey(SDLK_RIGHTBRACKET, KEY_RBRACKET, XK_bracketright); MapKey('}', KEY_RBRACKET, XK_bracketright); MapKey(SDLK_BACKSLASH, KEY_BACKSLASH, XK_backslash); MapKey(SDLK_SEMICOLON, KEY_SEMICOLON, XK_semicolon); MapKey(SDLK_QUOTE, KEY_APOSTROPHE, XK_apostrophe); MapKey(SDLK_COMMA, KEY_COMMA, XK_comma); MapKey(SDLK_PERIOD, KEY_PERIOD, XK_period); MapKey(SDLK_SLASH, KEY_SLASH, XK_slash); // numpad numbers for (keysym = SDLK_KP0, tkeycode = KEY_NUMPAD0, xkey = XK_KP_0; keysym <= SDLK_KP9; ++keysym, ++tkeycode, ++xkey) MapKey(static_cast<SDLKey>(keysym), tkeycode, xkey); // other numpad stuff MapKey(SDLK_KP_MULTIPLY, KEY_MULTIPLY, XK_KP_Multiply); MapKey(SDLK_KP_PLUS, KEY_ADD, XK_KP_Add); MapKey(SDLK_KP_EQUALS, KEY_SEPARATOR, XK_KP_Separator); MapKey(SDLK_KP_MINUS, KEY_SUBTRACT, XK_KP_Subtract); MapKey(SDLK_KP_PERIOD, KEY_DECIMAL, XK_KP_Decimal); MapKey(SDLK_KP_DIVIDE, KEY_DIVIDE, XK_KP_Divide); MapKey(SDLK_KP_ENTER, KEY_NUMPADENTER, XK_KP_Enter); // F keys for (keysym = SDLK_F1, tkeycode = KEY_F1, xkey = XK_F1; keysym <= SDLK_F15; ++keysym, ++tkeycode, ++xkey) MapKey(static_cast<SDLKey>(keysym), tkeycode, xkey); // various modifiers MapKey(SDLK_NUMLOCK, KEY_NUMLOCK, XK_Num_Lock); MapKey(SDLK_SCROLLOCK, KEY_SCROLLLOCK, XK_Scroll_Lock); MapKey(SDLK_LCTRL, KEY_LCONTROL, XK_Control_L); MapKey(SDLK_RCTRL, KEY_RCONTROL, XK_Control_R); MapKey(SDLK_LALT, KEY_LALT, XK_Alt_L); MapKey(SDLK_RALT, KEY_RALT, XK_Alt_R); MapKey(313, KEY_RALT, XK_Alt_R); MapKey(SDLK_LSHIFT, KEY_LSHIFT, XK_Shift_L); MapKey(SDLK_RSHIFT, KEY_RSHIFT, XK_Shift_R); MapKey(SDLK_LSUPER, KEY_WIN_LWINDOW, 0); MapKey(SDLK_RSUPER, KEY_WIN_RWINDOW, 0); MapKey(SDLK_MENU, KEY_WIN_APPS, 0); MapKey(SDLK_MODE, KEY_OEM_102, 0); keyMapsInitialized = true; }; //------------------------------------------------------------------------------ U8 TranslateSDLKeytoTKey(SDLKey keysym) { if (!keyMapsInitialized) { Con::printf("WARNING: SDLkeysymMap is not initialized"); return 0; } if (keysym < 0 || static_cast<U32>(keysym) >= SDLtoTKeyMapSize) { Con::printf("WARNING: invalid keysym: %d", keysym); return 0; } return SDLtoTKeyMap[keysym]; } //------------------------------------------------------------------------------ // this shouldn't be used, use TranslateSDLKeytoTKey instead U8 TranslateOSKeyCode(U8 vcode) { Con::printf("WARNING: TranslateOSKeyCode is not supported in unix"); return 0; } //============================================================================== // UInputManager //============================================================================== UInputManager::UInputManager() { mActive = false; mEnabled = false; mLocking = true; // locking enabled by default mKeyboardEnabled = mMouseEnabled = mJoystickEnabled = false; mKeyboardActive = mMouseActive = mJoystickActive = false; } //------------------------------------------------------------------------------ void UInputManager::init() { Con::addVariable( "pref::Input::KeyboardEnabled", TypeBool, &mKeyboardEnabled ); Con::addVariable( "pref::Input::MouseEnabled", TypeBool, &mMouseEnabled ); Con::addVariable( "pref::Input::JoystickEnabled", TypeBool, &mJoystickEnabled ); } //------------------------------------------------------------------------------ bool UInputManager::enable() { disable(); #ifdef LOG_INPUT Input::log( "Enabling Input...\n" ); #endif mModifierKeys = 0; dMemset( mMouseButtonState, 0, sizeof( mMouseButtonState ) ); dMemset( mKeyboardState, 0, 256 ); InitKeyMaps(); mJoystickEnabled = false; initJoystick(); mEnabled = true; mMouseEnabled = true; mKeyboardEnabled = true; SDL_EnableKeyRepeat( SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL); return true; } //------------------------------------------------------------------------------ void UInputManager::disable() { deactivate(); mEnabled = false; return; } //------------------------------------------------------------------------------ void UInputManager::initJoystick() { mJoystickList.clear(); // initialize SDL joystick system if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) < 0) { Con::warnf(" Unable to initialize joystick: %s", SDL_GetError()); return; } int numJoysticks = SDL_NumJoysticks(); if (numJoysticks == 0) Con::printf(" No joysticks found."); // disable joystick events (use polling instead) SDL_JoystickEventState(SDL_IGNORE); // install joysticks for(int i = 0; i < numJoysticks; i++ ) { JoystickInputDevice* newDevice = new JoystickInputDevice(i); addObject(newDevice); mJoystickList.push_back(newDevice); Con::printf(" %s: %s", newDevice->getDeviceName(), newDevice->getName()); #ifdef LOG_INPUT Input::log(" %s: %s\n", newDevice->getDeviceName(), newDevice->getName()); #endif } mJoystickEnabled = true; } //------------------------------------------------------------------------------ void UInputManager::activate() { if (mEnabled && !isActive()) { mActive = true; SDL_ShowCursor(SDL_DISABLE); resetInputState(); // hack; if the mouse or keyboard has been disabled, re-enable them. // prevents scripts like default.cs from breaking our input, although // there is probably a better solution mMouseEnabled = mKeyboardEnabled = true; activateMouse(); activateKeyboard(); activateJoystick(); if (x86UNIXState->windowLocked()) lockInput(); } } //------------------------------------------------------------------------------ void UInputManager::deactivate() { if (mEnabled && isActive()) { unlockInput(); deactivateKeyboard(); deactivateMouse(); deactivateJoystick(); resetInputState(); SDL_ShowCursor(SDL_ENABLE); mActive = false; } } //------------------------------------------------------------------------------ void UInputManager::resetKeyboardState() { // unpress any pressed keys; in the future we may want // to actually sync with the keyboard state for (int i = 0; i < 256; ++i) { if (mKeyboardState[i]) { InputEvent event; event.deviceInst = 0; event.deviceType = KeyboardDeviceType; event.objType = SI_KEY; event.objInst = i; event.action = SI_BREAK; event.fValue = 0.0; Game->postEvent(event); } } dMemset(mKeyboardState, 0, 256); // clear modifier keys mModifierKeys = 0; } //------------------------------------------------------------------------------ void UInputManager::resetMouseState() { // unpress any buttons; in the future we may want // to actually sync with the mouse state for (int i = 0; i < 3; ++i) { if (mMouseButtonState[i]) { // add KEY_BUTTON0 to the index to get the real // button ID S32 buttonID = i + KEY_BUTTON0; InputEvent event; event.deviceInst = 0; event.deviceType = MouseDeviceType; event.objType = SI_BUTTON; event.objInst = buttonID; event.action = SI_BREAK; event.fValue = 0.0; Game->postEvent(event); } } dMemset(mMouseButtonState, 0, 3); } //------------------------------------------------------------------------------ void UInputManager::resetInputState() { resetKeyboardState(); resetMouseState(); // reset joysticks for (Vector<JoystickInputDevice*>::iterator iter = mJoystickList.begin(); iter != mJoystickList.end(); ++iter) { (*iter)->reset(); } // JMQTODO: make event arrays be members // dispose of any lingering SDL input events static const int MaxEvents = 255; static SDL_Event events[MaxEvents]; SDL_PumpEvents(); SDL_PeepEvents(events, MaxEvents, SDL_GETEVENT, AllInputEvents); } //------------------------------------------------------------------------------ void UInputManager::setLocking(bool enabled) { mLocking = enabled; if (mLocking) lockInput(); else unlockInput(); } //------------------------------------------------------------------------------ void UInputManager::lockInput() { if (x86UNIXState->windowActive() && x86UNIXState->windowLocked() && mLocking && SDL_WM_GrabInput(SDL_GRAB_QUERY) == SDL_GRAB_OFF) SDL_WM_GrabInput(SDL_GRAB_ON); } //------------------------------------------------------------------------------ void UInputManager::unlockInput() { if (SDL_WM_GrabInput(SDL_GRAB_QUERY) == SDL_GRAB_ON) SDL_WM_GrabInput(SDL_GRAB_OFF); } //------------------------------------------------------------------------------ void UInputManager::onDeleteNotify( SimObject* object ) { Parent::onDeleteNotify( object ); } //------------------------------------------------------------------------------ bool UInputManager::onAdd() { if ( !Parent::onAdd() ) return false; return true; } //------------------------------------------------------------------------------ void UInputManager::onRemove() { deactivate(); Parent::onRemove(); } //------------------------------------------------------------------------------ void UInputManager::mouseMotionEvent(const SDL_Event& event) { // Con::printf("motion event: %d %d %d %d", // event.motion.xrel, event.motion.yrel, // event.motion.x, event.motion.y); if (x86UNIXState->windowLocked()) { InputEvent ievent; ievent.deviceInst = 0; ievent.deviceType = MouseDeviceType; ievent.objInst = 0; ievent.modifier = mModifierKeys; ievent.ascii = 0; ievent.action = SI_MOVE; // post events if things have changed if (event.motion.xrel != 0) { ievent.objType = SI_XAXIS; ievent.fValue = event.motion.xrel; Game->postEvent(ievent); } if (event.motion.yrel != 0) { ievent.objType = SI_YAXIS; ievent.fValue = event.motion.yrel; Game->postEvent(ievent); } #ifdef LOG_INPUT #ifdef LOG_MOUSEMOVE Input::log( "EVENT (Input): Mouse relative move (%.1f, %.1f).\n", event.motion.xrel != 0 ? F32(event.motion.xrel) : 0.0, event.motion.yrel != 0 ? F32(event.motion.yrel) : 0.0); #endif #endif } else { MouseMoveEvent mmevent; mmevent.xPos = mLastMouseX = event.motion.x; mmevent.yPos = mLastMouseY = event.motion.y; mmevent.modifier = mModifierKeys; Game->postEvent(mmevent); #ifdef LOG_INPUT #ifdef LOG_MOUSEMOVE Input::log( "EVENT (Input): Mouse absolute move (%.1f, %.1f).\n", F32(event.motion.x), F32(event.motion.y)); #endif #endif } } //------------------------------------------------------------------------------ void UInputManager::joyButtonEvent(const SDL_Event& event) { joyButtonEvent(event.jbutton.which, event.jbutton.button, event.type == SDL_JOYBUTTONDOWN); } //------------------------------------------------------------------------------ void UInputManager::joyButtonEvent(U8 deviceID, U8 buttonNum, bool pressed) { S32 action = pressed ? SI_MAKE : SI_BREAK; S32 objInst = buttonNum + KEY_BUTTON0; InputEvent ievent; ievent.deviceInst = deviceID; ievent.deviceType = JoystickDeviceType; ievent.modifier = mModifierKeys; ievent.ascii = 0; ievent.objType = SI_BUTTON; ievent.objInst = objInst; ievent.action = action; ievent.fValue = (action == SI_MAKE) ? 1.0 : 0.0; Game->postEvent(ievent); #ifdef LOG_INPUT Input::log( "EVENT (Input): joystick%d button%d %s. MODS:%c%c%c \n", deviceID, buttonNum, pressed ? "pressed" : "released", ( mModifierKeys & SI_SHIFT ? 'S' : '.' ), ( mModifierKeys & SI_CTRL ? 'C' : '.' ), ( mModifierKeys & SI_ALT ? 'A' : '.' )); #endif } //------------------------------------------------------------------------------ void UInputManager::joyHatEvent(U8 deviceID, U8 hatNum, U8 prevHatState, U8 currHatState) { if (prevHatState == currHatState) return; InputEvent ievent; ievent.deviceInst = deviceID; ievent.deviceType = JoystickDeviceType; ievent.modifier = mModifierKeys; ievent.ascii = 0; ievent.objType = SI_POV; // first break any positions that are no longer valid ievent.action = SI_BREAK; ievent.fValue = 0.0; if (prevHatState & SDL_HAT_UP && !(currHatState & SDL_HAT_UP)) { #ifdef LOG_INPUT Input::log( "EVENT (Input): Up POV released.\n"); #endif ievent.objInst = SI_UPOV; Game->postEvent(ievent); } else if (prevHatState & SDL_HAT_DOWN && !(currHatState & SDL_HAT_DOWN)) { #ifdef LOG_INPUT Input::log( "EVENT (Input): Down POV released.\n"); #endif ievent.objInst = SI_DPOV; Game->postEvent(ievent); } if (prevHatState & SDL_HAT_LEFT && !(currHatState & SDL_HAT_LEFT)) { #ifdef LOG_INPUT Input::log( "EVENT (Input): Left POV released.\n"); #endif ievent.objInst = SI_LPOV; Game->postEvent(ievent); } else if (prevHatState & SDL_HAT_RIGHT && !(currHatState & SDL_HAT_RIGHT)) { #ifdef LOG_INPUT Input::log( "EVENT (Input): Right POV released.\n"); #endif ievent.objInst = SI_RPOV; Game->postEvent(ievent); } // now do the make events ievent.action = SI_MAKE; ievent.fValue = 1.0; if (!(prevHatState & SDL_HAT_UP) && currHatState & SDL_HAT_UP) { #ifdef LOG_INPUT Input::log( "EVENT (Input): Up POV pressed.\n"); #endif ievent.objInst = SI_UPOV; Game->postEvent(ievent); } else if (!(prevHatState & SDL_HAT_DOWN) && currHatState & SDL_HAT_DOWN) { #ifdef LOG_INPUT Input::log( "EVENT (Input): Down POV pressed.\n"); #endif ievent.objInst = SI_DPOV; Game->postEvent(ievent); } if (!(prevHatState & SDL_HAT_LEFT) && currHatState & SDL_HAT_LEFT) { #ifdef LOG_INPUT Input::log( "EVENT (Input): Left POV pressed.\n"); #endif ievent.objInst = SI_LPOV; Game->postEvent(ievent); } else if (!(prevHatState & SDL_HAT_RIGHT) && currHatState & SDL_HAT_RIGHT) { #ifdef LOG_INPUT Input::log( "EVENT (Input): Right POV pressed.\n"); #endif ievent.objInst = SI_RPOV; Game->postEvent(ievent); } } //------------------------------------------------------------------------------ void UInputManager::joyAxisEvent(const SDL_Event& event) { joyAxisEvent(event.jaxis.which, event.jaxis.axis, event.jaxis.value); } //------------------------------------------------------------------------------ void UInputManager::joyAxisEvent(U8 deviceID, U8 axisNum, S16 axisValue) { JoystickInputDevice* stick; stick = mJoystickList[deviceID]; AssertFatal(stick, "JoystickInputDevice* is NULL"); JoystickAxisInfo axisInfo = stick->getAxisInfo(axisNum); if (axisInfo.type == -1) return; // scale the value to [-1,1] F32 scaledValue = 0; if (axisValue < 0) scaledValue = -F32(axisValue) / axisInfo.minValue; else if (axisValue > 0) scaledValue = F32(axisValue) / axisInfo.maxValue; // F32 range = F32(axisInfo.maxValue - axisInfo.minValue); // F32 scaledValue = F32((2 * axisValue) - axisInfo.maxValue - // axisInfo.minValue) / range; if (scaledValue > 1.f) scaledValue = 1.f; else if (scaledValue < -1.f) scaledValue = -1.f; // create and post the event InputEvent ievent; ievent.deviceInst = deviceID; ievent.deviceType = JoystickDeviceType; ievent.modifier = mModifierKeys; ievent.ascii = 0; ievent.objType = axisInfo.type; ievent.objInst = 0; ievent.action = SI_MOVE; ievent.fValue = scaledValue; Game->postEvent(ievent); #ifdef LOG_INPUT Input::log( "EVENT (Input): joystick axis %d moved: %.1f.\n", axisNum, ievent.fValue); #endif } //------------------------------------------------------------------------------ void UInputManager::mouseButtonEvent(const SDL_Event& event) { S32 action = (event.type == SDL_MOUSEBUTTONDOWN) ? SI_MAKE : SI_BREAK; S32 objInst = -1; // JMQTODO: support wheel delta like windows version? // JMQTODO: make this value configurable? S32 wheelDelta = 10; bool wheel = false; switch (event.button.button) { case SDL_BUTTON_LEFT: objInst = KEY_BUTTON0; break; case SDL_BUTTON_RIGHT: objInst = KEY_BUTTON1; break; case SDL_BUTTON_MIDDLE: objInst = KEY_BUTTON2; break; case Button4: wheel = true; break; case Button5: wheel = true; wheelDelta = -wheelDelta; break; } if (objInst == -1 && !wheel) // unsupported button return; InputEvent ievent; ievent.deviceInst = 0; ievent.deviceType = MouseDeviceType; ievent.modifier = mModifierKeys; ievent.ascii = 0; if (wheel) { // SDL generates a button press/release for each wheel move, // so ignore breaks to translate those into a single event if (action == SI_BREAK) return; ievent.objType = SI_ZAXIS; ievent.objInst = 0; ievent.action = SI_MOVE; ievent.fValue = wheelDelta; #ifdef LOG_INPUT Input::log( "EVENT (Input): mouse wheel moved %s: %.1f. MODS:%c%c%c\n", wheelDelta > 0 ? "up" : "down", ievent.fValue, ( mModifierKeys & SI_SHIFT ? 'S' : '.' ), ( mModifierKeys & SI_CTRL ? 'C' : '.' ), ( mModifierKeys & SI_ALT ? 'A' : '.' )); #endif } else // regular button { S32 buttonID = (objInst - KEY_BUTTON0); if (buttonID < 3) mMouseButtonState[buttonID] = ( action == SI_MAKE ) ? true : false; ievent.objType = SI_BUTTON; ievent.objInst = objInst; ievent.action = action; ievent.fValue = (action == SI_MAKE) ? 1.0 : 0.0; #ifdef LOG_INPUT Input::log( "EVENT (Input): mouse button%d %s. MODS:%c%c%c\n", buttonID, action == SI_MAKE ? "pressed" : "released", ( mModifierKeys & SI_SHIFT ? 'S' : '.' ), ( mModifierKeys & SI_CTRL ? 'C' : '.' ), ( mModifierKeys & SI_ALT ? 'A' : '.' )); #endif } Game->postEvent(ievent); } //------------------------------------------------------------------------------ const char* getKeyName( U16 key ) { switch ( key ) { case KEY_BACKSPACE: return "Backspace"; case KEY_TAB: return "Tab"; case KEY_RETURN: return "Return"; case KEY_PAUSE: return "Pause"; case KEY_CAPSLOCK: return "CapsLock"; case KEY_ESCAPE: return "Esc"; case KEY_SPACE: return "SpaceBar"; case KEY_PAGE_DOWN: return "PageDown"; case KEY_PAGE_UP: return "PageUp"; case KEY_END: return "End"; case KEY_HOME: return "Home"; case KEY_LEFT: return "Left"; case KEY_UP: return "Up"; case KEY_RIGHT: return "Right"; case KEY_DOWN: return "Down"; case KEY_PRINT: return "PrintScreen"; case KEY_INSERT: return "Insert"; case KEY_DELETE: return "Delete"; case KEY_HELP: return "Help"; case KEY_NUMPAD0: return "Numpad 0"; case KEY_NUMPAD1: return "Numpad 1"; case KEY_NUMPAD2: return "Numpad 2"; case KEY_NUMPAD3: return "Numpad 3"; case KEY_NUMPAD4: return "Numpad 4"; case KEY_NUMPAD5: return "Numpad 5"; case KEY_NUMPAD6: return "Numpad 6"; case KEY_NUMPAD7: return "Numpad 7"; case KEY_NUMPAD8: return "Numpad 8"; case KEY_NUMPAD9: return "Numpad 9"; case KEY_MULTIPLY: return "Multiply"; case KEY_ADD: return "Add"; case KEY_SEPARATOR: return "Separator"; case KEY_SUBTRACT: return "Subtract"; case KEY_DECIMAL: return "Decimal"; case KEY_DIVIDE: return "Divide"; case KEY_NUMPADENTER: return "Numpad Enter"; case KEY_F1: return "F1"; case KEY_F2: return "F2"; case KEY_F3: return "F3"; case KEY_F4: return "F4"; case KEY_F5: return "F5"; case KEY_F6: return "F6"; case KEY_F7: return "F7"; case KEY_F8: return "F8"; case KEY_F9: return "F9"; case KEY_F10: return "F10"; case KEY_F11: return "F11"; case KEY_F12: return "F12"; case KEY_F13: return "F13"; case KEY_F14: return "F14"; case KEY_F15: return "F15"; case KEY_F16: return "F16"; case KEY_F17: return "F17"; case KEY_F18: return "F18"; case KEY_F19: return "F19"; case KEY_F20: return "F20"; case KEY_F21: return "F21"; case KEY_F22: return "F22"; case KEY_F23: return "F23"; case KEY_F24: return "F24"; case KEY_NUMLOCK: return "NumLock"; case KEY_SCROLLLOCK: return "ScrollLock"; case KEY_LCONTROL: return "LCtrl"; case KEY_RCONTROL: return "RCtrl"; case KEY_LALT: return "LAlt"; case KEY_RALT: return "RAlt"; case KEY_LSHIFT: return "LShift"; case KEY_RSHIFT: return "RShift"; case KEY_WIN_LWINDOW: return "LWin"; case KEY_WIN_RWINDOW: return "RWin"; case KEY_WIN_APPS: return "Apps"; } static char returnString[5]; dSprintf( returnString, sizeof( returnString ), "%c", Input::getAscii( key, STATE_UPPER ) ); return returnString; } //------------------------------------------------------------------------------ void UInputManager::keyEvent(const SDL_Event& event) { S32 action = (event.type == SDL_KEYDOWN) ? SI_MAKE : SI_BREAK; InputEvent ievent; ievent.deviceInst = 0; ievent.deviceType = KeyboardDeviceType; ievent.objType = SI_KEY; ievent.objInst = TranslateSDLKeytoTKey(event.key.keysym.sym); // if the action is a make but this key is already pressed, // count it as a repeat if (action == SI_MAKE && mKeyboardState[ievent.objInst]) action = SI_REPEAT; ievent.action = action; ievent.fValue = (action == SI_MAKE || action == SI_REPEAT) ? 1.0 : 0.0; processKeyEvent(ievent); Game->postEvent(ievent); #if 0 if (ievent.action == SI_MAKE) dPrintf("key event: : %s key pressed. MODS:%c%c%c\n", getKeyName(ievent.objInst), ( mModifierKeys & SI_SHIFT ? 'S' : '.' ), ( mModifierKeys & SI_CTRL ? 'C' : '.' ), ( mModifierKeys & SI_ALT ? 'A' : '.' )); else if (ievent.action == SI_REPEAT) dPrintf("key event: : %s key repeated. MODS:%c%c%c\n", getKeyName(ievent.objInst), ( mModifierKeys & SI_SHIFT ? 'S' : '.' ), ( mModifierKeys & SI_CTRL ? 'C' : '.' ), ( mModifierKeys & SI_ALT ? 'A' : '.' )); else if (ievent.action == SI_BREAK) dPrintf("key event: : %s key released. MODS:%c%c%c\n", getKeyName(ievent.objInst), ( mModifierKeys & SI_SHIFT ? 'S' : '.' ), ( mModifierKeys & SI_CTRL ? 'C' : '.' ), ( mModifierKeys & SI_ALT ? 'A' : '.' )); else dPrintf("unknown key event!\n"); #endif #ifdef LOG_INPUT Input::log( "EVENT (Input): %s key %s. MODS:%c%c%c\n", getKeyName(ievent.objInst), action == SI_MAKE ? "pressed" : "released", ( mModifierKeys & SI_SHIFT ? 'S' : '.' ), ( mModifierKeys & SI_CTRL ? 'C' : '.' ), ( mModifierKeys & SI_ALT ? 'A' : '.' )); #endif } //------------------------------------------------------------------------------ // This function was ripped from DInputDevice almost entirely intact. bool UInputManager::processKeyEvent( InputEvent &event ) { if ( event.deviceType != KeyboardDeviceType || event.objType != SI_KEY ) return false; bool modKey = false; U8 keyCode = event.objInst; if ( event.action == SI_MAKE || event.action == SI_REPEAT) { // Maintain the key structure: mKeyboardState[keyCode] = true; switch ( event.objInst ) { case KEY_LSHIFT: mModifierKeys |= SI_LSHIFT; modKey = true; break; case KEY_RSHIFT: mModifierKeys |= SI_RSHIFT; modKey = true; break; case KEY_LCONTROL: mModifierKeys |= SI_LCTRL; modKey = true; break; case KEY_RCONTROL: mModifierKeys |= SI_RCTRL; modKey = true; break; case KEY_LALT: mModifierKeys |= SI_LALT; modKey = true; break; case KEY_RALT: mModifierKeys |= SI_RALT; modKey = true; break; } } else { // Maintain the keys structure: mKeyboardState[keyCode] = false; switch ( event.objInst ) { case KEY_LSHIFT: mModifierKeys &= ~SI_LSHIFT; modKey = true; break; case KEY_RSHIFT: mModifierKeys &= ~SI_RSHIFT; modKey = true; break; case KEY_LCONTROL: mModifierKeys &= ~SI_LCTRL; modKey = true; break; case KEY_RCONTROL: mModifierKeys &= ~SI_RCTRL; modKey = true; break; case KEY_LALT: mModifierKeys &= ~SI_LALT; modKey = true; break; case KEY_RALT: mModifierKeys &= ~SI_RALT; modKey = true; break; } } if ( modKey ) event.modifier = 0; else event.modifier = mModifierKeys; // TODO: alter this getAscii call KEY_STATE state = STATE_LOWER; if (event.modifier & (SI_CTRL|SI_ALT) ) { state = STATE_GOOFY; } if ( event.modifier & SI_SHIFT ) { state = STATE_UPPER; } event.ascii = Input::getAscii( event.objInst, state ); return modKey; } //------------------------------------------------------------------------------ void UInputManager::setWindowLocked(bool locked) { if (locked) lockInput(); else { unlockInput(); // SDL keeps track of abs mouse position in fullscreen mode, which means // that if you switch to unlocked mode while fullscreen, the mouse will // suddenly warp to someplace unexpected on screen. To fix this, we // warp the mouse to the last known Torque abs mouse position. if (mLastMouseX != -1 && mLastMouseY != -1) SDL_WarpMouse(mLastMouseX, mLastMouseY); } } //------------------------------------------------------------------------------ void UInputManager::process() { if (!mEnabled || !isActive()) return; // JMQTODO: make these be class members static const int MaxEvents = 255; static SDL_Event events[MaxEvents]; U32 mask = 0; // process keyboard and mouse events if (mMouseActive) mask |= MouseMask; if (mKeyboardActive) mask |= KeyboardMask; if (mask != 0) { SDL_PumpEvents(); S32 numEvents = SDL_PeepEvents(events, MaxEvents, SDL_GETEVENT, mask); for (int i = 0; i < numEvents; ++i) { switch (events[i].type) { case SDL_MOUSEMOTION: mouseMotionEvent(events[i]); break; case SDL_MOUSEBUTTONUP: case SDL_MOUSEBUTTONDOWN: mouseButtonEvent(events[i]); break; case SDL_KEYDOWN: case SDL_KEYUP: keyEvent(events[i]); break; } } } // poll joysticks if (!mJoystickActive) return; SDL_JoystickUpdate(); for (Vector<JoystickInputDevice*>::iterator iter = mJoystickList.begin(); iter != mJoystickList.end(); ++iter) { (*iter)->process(); } } //------------------------------------------------------------------------------ bool UInputManager::enableKeyboard() { if ( !isEnabled() ) return( false ); if ( isKeyboardEnabled() && isKeyboardActive() ) return( true ); mKeyboardEnabled = true; if ( isActive() ) mKeyboardEnabled = activateKeyboard(); if ( mKeyboardEnabled ) { Con::printf( "Keyboard enabled." ); #ifdef LOG_INPUT Input::log( "Keyboard enabled.\n" ); #endif } else { Con::warnf( "Keyboard failed to enable!" ); #ifdef LOG_INPUT Input::log( "Keyboard failed to enable!\n" ); #endif } return( mKeyboardEnabled ); } //------------------------------------------------------------------------------ void UInputManager::disableKeyboard() { if ( !isEnabled() || !isKeyboardEnabled()) return; deactivateKeyboard(); mKeyboardEnabled = false; Con::printf( "Keyboard disabled." ); #ifdef LOG_INPUT Input::log( "Keyboard disabled.\n" ); #endif } //------------------------------------------------------------------------------ bool UInputManager::activateKeyboard() { if ( !isEnabled() || !isActive() || !isKeyboardEnabled() ) return( false ); mKeyboardActive = true; #ifdef LOG_INPUT Input::log( mKeyboardActive ? "Keyboard activated.\n" : "Keyboard failed to activate!\n" ); #endif return( mKeyboardActive ); } //------------------------------------------------------------------------------ void UInputManager::deactivateKeyboard() { if ( isEnabled() && isKeyboardActive() ) { mKeyboardActive = false; #ifdef LOG_INPUT Input::log( "Keyboard deactivated.\n" ); #endif } } //------------------------------------------------------------------------------ bool UInputManager::enableMouse() { if ( !isEnabled() ) return( false ); if ( isMouseEnabled() && isMouseActive() ) return( true ); mMouseEnabled = true; if ( isActive() ) mMouseEnabled = activateMouse(); if ( mMouseEnabled ) { Con::printf( "Mouse enabled." ); #ifdef LOG_INPUT Input::log( "Mouse enabled.\n" ); #endif } else { Con::warnf( "Mouse failed to enable!" ); #ifdef LOG_INPUT Input::log( "Mouse failed to enable!\n" ); #endif } return( mMouseEnabled ); } //------------------------------------------------------------------------------ void UInputManager::disableMouse() { if ( !isEnabled() || !isMouseEnabled()) return; deactivateMouse(); mMouseEnabled = false; Con::printf( "Mouse disabled." ); #ifdef LOG_INPUT Input::log( "Mouse disabled.\n" ); #endif } //------------------------------------------------------------------------------ bool UInputManager::activateMouse() { if ( !isEnabled() || !isActive() || !isMouseEnabled() ) return( false ); mMouseActive = true; #ifdef LOG_INPUT Input::log( mMouseActive ? "Mouse activated.\n" : "Mouse failed to activate!\n" ); #endif return( mMouseActive ); } //------------------------------------------------------------------------------ void UInputManager::deactivateMouse() { if ( isEnabled() && isMouseActive() ) { mMouseActive = false; #ifdef LOG_INPUT Input::log( "Mouse deactivated.\n" ); #endif } } //------------------------------------------------------------------------------ bool UInputManager::enableJoystick() { if ( !isEnabled() ) return( false ); if ( isJoystickEnabled() && isJoystickActive() ) return( true ); mJoystickEnabled = true; if ( isActive() ) mJoystickEnabled = activateJoystick(); if ( mJoystickEnabled ) { Con::printf( "Joystick enabled." ); #ifdef LOG_INPUT Input::log( "Joystick enabled.\n" ); #endif } else { Con::warnf( "Joystick failed to enable!" ); #ifdef LOG_INPUT Input::log( "Joystick failed to enable!\n" ); #endif } return( mJoystickEnabled ); } //------------------------------------------------------------------------------ void UInputManager::disableJoystick() { if ( !isEnabled() || !isJoystickEnabled()) return; deactivateJoystick(); mJoystickEnabled = false; Con::printf( "Joystick disabled." ); #ifdef LOG_INPUT Input::log( "Joystick disabled.\n" ); #endif } //------------------------------------------------------------------------------ bool UInputManager::activateJoystick() { if ( !isEnabled() || !isActive() || !isJoystickEnabled() ) return( false ); mJoystickActive = false; JoystickInputDevice* dptr; for ( iterator ptr = begin(); ptr != end(); ptr++ ) { dptr = dynamic_cast<JoystickInputDevice*>( *ptr ); if ( dptr && dptr->getDeviceType() == JoystickDeviceType) if ( dptr->activate() ) mJoystickActive = true; } #ifdef LOG_INPUT Input::log( mJoystickActive ? "Joystick activated.\n" : "Joystick failed to activate!\n" ); #endif return( mJoystickActive ); } //------------------------------------------------------------------------------ void UInputManager::deactivateJoystick() { if ( isEnabled() && isJoystickActive() ) { mJoystickActive = false; JoystickInputDevice* dptr; for ( iterator ptr = begin(); ptr != end(); ptr++ ) { dptr = dynamic_cast<JoystickInputDevice*>( *ptr ); if ( dptr && dptr->getDeviceType() == JoystickDeviceType) dptr->deactivate(); } #ifdef LOG_INPUT Input::log( "Joystick deactivated.\n" ); #endif } } //------------------------------------------------------------------------------ const char* UInputManager::getJoystickAxesString( U32 deviceID ) { for (Vector<JoystickInputDevice*>::iterator iter = mJoystickList.begin(); iter != mJoystickList.end(); ++iter) { if ((*iter)->getDeviceID() == deviceID) return (*iter)->getJoystickAxesString(); } return( "" ); } //============================================================================== // JoystickInputDevice //============================================================================== JoystickInputDevice::JoystickInputDevice(U8 deviceID) { mActive = false; mStick = NULL; mAxisList.clear(); mDeviceID = deviceID; dSprintf(mName, 29, "joystick%d", mDeviceID); mButtonState.clear(); mHatState.clear(); mNumAxes = mNumButtons = mNumHats = mNumBalls = 0; loadJoystickInfo(); // initialize state variables for (int i = 0; i < mNumButtons; ++i) mButtonState.push_back(false); // all buttons unpressed initially for (int i = 0; i < mNumHats; ++i) mHatState.push_back(SDL_HAT_CENTERED); // hats centered initially } //------------------------------------------------------------------------------ JoystickInputDevice::~JoystickInputDevice() { if (isActive()) deactivate(); } //------------------------------------------------------------------------------ bool JoystickInputDevice::activate() { if (isActive()) return true; // open the stick mStick = SDL_JoystickOpen(mDeviceID); if (mStick == NULL) { Con::printf("Unable to activate %s: %s", getDeviceName(), SDL_GetError()); return false; } // reload axis mapping info loadAxisInfo(); mActive = true; return true; } //------------------------------------------------------------------------------ bool JoystickInputDevice::deactivate() { if (!isActive()) return true; if (mStick != NULL) { SDL_JoystickClose(mStick); mStick = NULL; } mActive = false; return true; } //------------------------------------------------------------------------------ const char* JoystickInputDevice::getName() { return SDL_JoystickName(mDeviceID); } //------------------------------------------------------------------------------ void JoystickInputDevice::reset() { UInputManager* manager = dynamic_cast<UInputManager*>(Input::getManager()); if (!manager) return; // clear joystick state variables // buttons for (int i = 0; i < mButtonState.size(); ++i) if (mButtonState[i]) { manager->joyButtonEvent(mDeviceID, i, false); mButtonState[i] = false; } // hats for (int i = 0; i < mHatState.size(); ++i) if (mHatState[i] != SDL_HAT_CENTERED) { manager->joyHatEvent(mDeviceID, i, mHatState[i], SDL_HAT_CENTERED); mHatState[i] = SDL_HAT_CENTERED; } // axis and ball state is not maintained } //------------------------------------------------------------------------------ bool JoystickInputDevice::process() { if (!isActive()) return false; UInputManager* manager = dynamic_cast<UInputManager*>(Input::getManager()); if (!manager) return false; // axes for (int i = 0; i < mNumAxes; ++i) { // skip the axis if we don't have a mapping for it if (mAxisList[i].type == -1) continue; manager->joyAxisEvent(mDeviceID, i, SDL_JoystickGetAxis(mStick, i)); } // buttons for (int i = 0; i < mNumButtons; ++i) { if (bool(SDL_JoystickGetButton(mStick, i)) == mButtonState[i]) continue; mButtonState[i] = !mButtonState[i]; manager->joyButtonEvent(mDeviceID, i, mButtonState[i]); } // hats for (int i = 0; i < mNumHats; ++i) { U8 currHatState = SDL_JoystickGetHat(mStick, i); if (mHatState[i] == currHatState) continue; manager->joyHatEvent(mDeviceID, i, mHatState[i], currHatState); mHatState[i] = currHatState; } // ballz // JMQTODO: how to map ball events (xaxis,yaxis?) return true; } //------------------------------------------------------------------------------ static S32 GetAxisType(S32 axisNum, const char* namedType) { S32 axisType = -1; if (namedType != NULL) { if (dStricmp(namedType, "xaxis")==0) axisType = SI_XAXIS; else if (dStricmp(namedType, "yaxis")==0) axisType = SI_YAXIS; else if (dStricmp(namedType, "zaxis")==0) axisType = SI_ZAXIS; else if (dStricmp(namedType, "rxaxis")==0) axisType = SI_RXAXIS; else if (dStricmp(namedType, "ryaxis")==0) axisType = SI_RYAXIS; else if (dStricmp(namedType, "rzaxis")==0) axisType = SI_RZAXIS; else if (dStricmp(namedType, "slider")==0) axisType = SI_SLIDER; } if (axisType == -1) { // use a hardcoded default mapping if possible switch (axisNum) { case 0: axisType = SI_XAXIS; break; case 1: axisType = SI_YAXIS; break; case 2: axisType = SI_RZAXIS; break; case 3: axisType = SI_SLIDER; break; } } return axisType; } //------------------------------------------------------------------------------ void JoystickInputDevice::loadJoystickInfo() { bool opened = false; if (mStick == NULL) { mStick = SDL_JoystickOpen(mDeviceID); if (mStick == NULL) { Con::printf("Unable to open %s: %s", getDeviceName(), SDL_GetError()); return; } opened = true; } // get the number of thingies on this joystick mNumAxes = SDL_JoystickNumAxes(mStick); mNumButtons = SDL_JoystickNumButtons(mStick); mNumHats = SDL_JoystickNumHats(mStick); mNumBalls = SDL_JoystickNumBalls(mStick); // load axis mapping info loadAxisInfo(); if (opened) SDL_JoystickClose(mStick); } //------------------------------------------------------------------------------ // for each axis on a joystick, torque needs to know the type of the axis // (SI_XAXIS, etc), the minimum value, and the maximum value. However none of // this information is generally available with the unix/linux api. All you // get is a device and axis number and a value. Therefore, // we allow the user to specify these values in preferences. hopefully // someday we can implement a gui joystick calibrator that takes care of this // cruft for the user. void JoystickInputDevice::loadAxisInfo() { mAxisList.clear(); AssertFatal(mStick, "mStick is NULL"); static int AxisDefaults[] = { SI_XAXIS, SI_YAXIS, SI_ZAXIS, SI_RXAXIS, SI_RYAXIS, SI_RZAXIS, SI_SLIDER }; int numAxis = SDL_JoystickNumAxes(mStick); for (int i = 0; i < numAxis; ++i) { JoystickAxisInfo axisInfo; // defaults axisInfo.type = -1; axisInfo.minValue = -32768; axisInfo.maxValue = 32767; // look in console to see if there is mapping information for this axis const int TempBufSize = 1024; char tempBuf[TempBufSize]; dSprintf(tempBuf, TempBufSize, "$Pref::Input::Joystick%d::Axis%d", mDeviceID, i); const char* axisStr = Con::getVariable(tempBuf); if (axisStr == NULL || dStrlen(axisStr) == 0) { if (i < sizeof(AxisDefaults)) axisInfo.type = AxisDefaults[i]; } else { // format is "TorqueAxisName MinValue MaxValue"; dStrncpy(tempBuf, axisStr, TempBufSize); char* temp = dStrtok( tempBuf, " \0" ); if (temp) { axisInfo.type = GetAxisType(i, temp); temp = dStrtok( NULL, " \0" ); if (temp) { axisInfo.minValue = dAtoi(temp); temp = dStrtok( NULL, "\0" ); if (temp) { axisInfo.maxValue = dAtoi(temp); } } } } mAxisList.push_back(axisInfo); } } //------------------------------------------------------------------------------ const char* JoystickInputDevice::getJoystickAxesString() { char buf[64]; dSprintf( buf, sizeof( buf ), "%d", mAxisList.size()); for (Vector<JoystickAxisInfo>::iterator iter = mAxisList.begin(); iter != mAxisList.end(); ++iter) { switch ((*iter).type) { case SI_XAXIS: dStrcat( buf, "\tX" ); break; case SI_YAXIS: dStrcat( buf, "\tY" ); break; case SI_ZAXIS: dStrcat( buf, "\tZ" ); break; case SI_RXAXIS: dStrcat( buf, "\tR" ); break; case SI_RYAXIS: dStrcat( buf, "\tU" ); break; case SI_RZAXIS: dStrcat( buf, "\tV" ); break; case SI_SLIDER: dStrcat( buf, "\tS" ); break; } } char* returnString = Con::getReturnBuffer( dStrlen( buf ) + 1 ); dStrcpy( returnString, buf ); return( returnString ); } //============================================================================== // Console Functions //============================================================================== ConsoleFunction( activateKeyboard, bool, 1, 1, "activateKeyboard()" ) { UInputManager* mgr = dynamic_cast<UInputManager*>( Input::getManager() ); if ( mgr ) return( mgr->activateKeyboard() ); return( false ); } // JMQ: disabled deactivateKeyboard since the script calls it but there is // no fallback keyboard input in unix, resulting in a permanently disabled // keyboard //------------------------------------------------------------------------------ ConsoleFunction( deactivateKeyboard, void, 1, 1, "deactivateKeyboard()" ) { #if 0 UInputManager* mgr = dynamic_cast<UInputManager*>( Input::getManager() ); if ( mgr ) mgr->deactivateKeyboard(); #endif } //------------------------------------------------------------------------------ ConsoleFunction( enableMouse, bool, 1, 1, "enableMouse()" ) { UInputManager* mgr = dynamic_cast<UInputManager*>( Input::getManager() ); if ( mgr ) return( mgr->enableMouse() ); return ( false ); } //------------------------------------------------------------------------------ ConsoleFunction( disableMouse, void, 1, 1, "disableMouse()" ) { UInputManager* mgr = dynamic_cast<UInputManager*>( Input::getManager() ); if ( mgr ) mgr->disableMouse(); } //------------------------------------------------------------------------------ ConsoleFunction( enableJoystick, bool, 1, 1, "enableJoystick()" ) { UInputManager* mgr = dynamic_cast<UInputManager*>( Input::getManager() ); if ( mgr ) return( mgr->enableJoystick() ); return ( false ); } //------------------------------------------------------------------------------ ConsoleFunction( disableJoystick, void, 1, 1, "disableJoystick()" ) { UInputManager* mgr = dynamic_cast<UInputManager*>( Input::getManager() ); if ( mgr ) mgr->disableJoystick(); } //------------------------------------------------------------------------------ ConsoleFunction( enableLocking, void, 1, 1, "enableLocking()" ) { UInputManager* mgr = dynamic_cast<UInputManager*>( Input::getManager() ); if ( mgr ) mgr->setLocking(true); } //------------------------------------------------------------------------------ ConsoleFunction( disableLocking, void, 1, 1, "disableLocking()" ) { UInputManager* mgr = dynamic_cast<UInputManager*>( Input::getManager() ); if ( mgr ) mgr->setLocking(false); } //------------------------------------------------------------------------------ ConsoleFunction( toggleLocking, void, 1, 1, "toggleLocking()" ) { UInputManager* mgr = dynamic_cast<UInputManager*>( Input::getManager() ); if ( mgr ) mgr->setLocking(!mgr->getLocking()); } //------------------------------------------------------------------------------ ConsoleFunction( echoInputState, void, 1, 1, "echoInputState()" ) { UInputManager* mgr = dynamic_cast<UInputManager*>( Input::getManager() ); if ( mgr && mgr->isEnabled() ) { Con::printf( "Input is enabled %s.", mgr->isActive() ? "and active" : "but inactive" ); Con::printf( "- Keyboard is %sabled and %sactive.", mgr->isKeyboardEnabled() ? "en" : "dis", mgr->isKeyboardActive() ? "" : "in" ); Con::printf( "- Mouse is %sabled and %sactive.", mgr->isMouseEnabled() ? "en" : "dis", mgr->isMouseActive() ? "" : "in" ); Con::printf( "- Joystick is %sabled and %sactive.", mgr->isJoystickEnabled() ? "en" : "dis", mgr->isJoystickActive() ? "" : "in" ); } else Con::printf( "Input is not enabled." ); }
/******************************************************************************* * Copyright 2017-2021 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 <cstring> #include <float.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include "oneapi/dnnl/dnnl.h" #include "tests/test_thread.hpp" #include "compare.hpp" #include "dnnl_common.hpp" #include "dnnl_memory.hpp" #include "binary/binary.hpp" #include "ip/ip.hpp" namespace ip { static int init_pd(dnnl_engine_t engine, const prb_t *prb, dnnl_primitive_desc_t &ippd, res_t *res, dir_t dir, const_dnnl_primitive_desc_t hint) { dnnl_inner_product_desc_t ipd; dnnl_memory_desc_t src_d, wei_d, bia_d, dst_d; dnnl_dims_t src_dims_0d = {prb->mb, prb->ic}; dnnl_dims_t src_dims_1d = {prb->mb, prb->ic, prb->iw}; dnnl_dims_t src_dims_2d = {prb->mb, prb->ic, prb->ih, prb->iw}; dnnl_dims_t src_dims_3d = {prb->mb, prb->ic, prb->id, prb->ih, prb->iw}; dnnl_dims_t wei_dims_0d = {prb->oc, prb->ic}; dnnl_dims_t wei_dims_1d = {prb->oc, prb->ic, prb->iw}; dnnl_dims_t wei_dims_2d = {prb->oc, prb->ic, prb->ih, prb->iw}; dnnl_dims_t wei_dims_3d = {prb->oc, prb->ic, prb->id, prb->ih, prb->iw}; dnnl_dims_t bia_dims = {prb->oc}; dnnl_dims_t dst_dims = {prb->mb, prb->oc}; dnnl_dim_t *src_dims = prb->ndims == 5 ? src_dims_3d : prb->ndims == 4 ? src_dims_2d : prb->ndims == 3 ? src_dims_1d : src_dims_0d; dnnl_dim_t *wei_dims = prb->ndims == 5 ? wei_dims_3d : prb->ndims == 4 ? wei_dims_2d : prb->ndims == 3 ? wei_dims_1d : wei_dims_0d; SAFE(init_md(&src_d, prb->ndims, src_dims, prb->cfg[SRC].dt, prb->stag), CRIT); SAFE(init_md(&wei_d, prb->ndims, wei_dims, prb->cfg[WEI].dt, prb->wtag), CRIT); DNN_SAFE(dnnl_memory_desc_init_by_tag(&bia_d, 1, bia_dims, prb->cfg[BIA].dt, dnnl_format_tag_any), WARN); SAFE(init_md(&dst_d, 2, dst_dims, prb->cfg[DST].dt, prb->dtag), CRIT); switch (prb->dir) { case FWD_D: case FWD_B: case FWD_I: DNN_SAFE(dnnl_inner_product_forward_desc_init(&ipd, prb->dir == FWD_I ? dnnl_forward_inference : dnnl_forward_training, &src_d, &wei_d, prb->dir == FWD_B ? &bia_d : nullptr, &dst_d), WARN); break; case BWD_D: DNN_SAFE(dnnl_inner_product_backward_data_desc_init( &ipd, &src_d, &wei_d, &dst_d), WARN); break; case BWD_W: case BWD_WB: DNN_SAFE(dnnl_inner_product_backward_weights_desc_init(&ipd, &src_d, &wei_d, prb->dir == BWD_W ? nullptr : &bia_d, &dst_d), WARN); break; default: DNN_SAFE(dnnl_invalid_arguments, CRIT); } DNN_SAFE(ipd.accum_data_type == prb->cfg[ACC].dt ? dnnl_success : dnnl_unimplemented, CRIT); attr_args_t attr_args; attr_args.prepare_output_scales(prb->attr, prb->scales, prb->oc); attr_args.prepare_binary_post_op_mds(prb->attr, 2, dst_dims); auto dnnl_attr = create_dnnl_attr(prb->attr, attr_args); dnnl_status_t init_status = dnnl_success; init_status = dnnl_primitive_desc_create( &ippd, &ipd, dnnl_attr, engine, nullptr); dnnl_primitive_attr_destroy(dnnl_attr); if (init_status == dnnl_unimplemented) return res->state = UNIMPLEMENTED, OK; else SAFE(init_status, WARN); res->impl_name = query_impl_info(ippd); if (maybe_skip(res->impl_name)) { BENCHDNN_PRINT(2, "SKIPPED: oneDNN implementation: %s\n", res->impl_name.c_str()); DNN_SAFE(dnnl_primitive_desc_destroy(ippd), WARN); return res->state = SKIPPED, res->reason = SKIP_IMPL_HIT, OK; } else { BENCHDNN_PRINT( 5, "oneDNN implementation: %s\n", res->impl_name.c_str()); } return OK; } int fill_src( const prb_t *prb, dnn_mem_t &mem_dt, dnn_mem_t &mem_fp, res_t *res) { const auto &c = prb->cfg[SRC]; const int range = c.f_max - c.f_min + 1; dnnl::impl::parallel_nd(prb->mb, prb->ic, prb->id, prb->ih, prb->iw, [&](int mb, int ic, int id, int ih, int iw) { const int gen = 101 * id + 103 * ih + 107 * iw + 109 * mb + 113 * ic; const float sparsity = prb->ic < 5 ? 1.f : c.f_sparsity; const bool non_base = flip_coin(gen, sparsity); const float value = non_base ? c.f_min + gen * 1 % range : c.f_base; ((float *)mem_fp)[src_off_f(prb, mb, ic, id, ih, iw)] = value; }); SAFE(mem_dt.reorder(mem_fp), WARN); return OK; } int fill_wei( const prb_t *prb, dnn_mem_t &mem_dt, dnn_mem_t &mem_fp, res_t *res) { const bool s8_s8 = prb->cfg[WEI].dt == dnnl_s8 && prb->cfg[SRC].dt == dnnl_s8; const auto &c = prb->cfg[WEI]; const int range = c.f_max - c.f_min + 1; dnnl::impl::parallel_nd(prb->oc, prb->ic, prb->id, prb->ih, prb->iw, [&](int oc, int ic, int kd, int kh, int kw) { const int gen = 127 * kd + 131 * kh + 137 * kw + 139 * oc + 149 * ic + 7; const float sparsity = prb->ic < 5 ? 1.f : c.f_sparsity; const bool non_base = flip_coin(gen, sparsity); const float value = non_base ? c.f_min + gen * 1 % range : c.f_base; ((float *)mem_fp)[wei_off_f(prb, oc, ic, kd, kh, kw)] = value; }); SAFE(mem_dt.reorder(mem_fp), WARN); if (s8_s8 && is_cpu()) { // Check that s8 -> s8_comp exists in the library since users may have // already quantized data. dnn_mem_t mem_fp_s8(mem_fp.md_, dnnl_s8, get_test_engine()); dnn_mem_t mem_dt_s8(mem_dt.md_, dnnl_s8, get_test_engine()); SAFE(mem_fp_s8.reorder(mem_fp), WARN); SAFE(mem_dt_s8.reorder(mem_fp_s8), WARN); SAFE(mem_dt.size() == mem_dt_s8.size() ? OK : FAIL, WARN); int rc = std::memcmp((void *)mem_dt, (void *)mem_dt_s8, mem_dt.size()); SAFE(rc == 0 ? OK : FAIL, WARN); } return OK; } int fill_bia( const prb_t *prb, dnn_mem_t &mem_dt, dnn_mem_t &mem_fp, res_t *res) { const size_t nelems = mem_fp.nelems(); if (nelems == 0) return OK; const auto &c = prb->cfg[BIA]; const int range = c.f_max - c.f_min + 1; for (size_t i = 0; i < nelems; ++i) { const int gen = (int)(151 * i + 11); const bool non_base = flip_coin(gen, c.f_sparsity); const float value = non_base ? c.f_min + gen * 1 % range : c.f_base; ((float *)mem_fp)[i] = value; } SAFE(mem_dt.reorder(mem_fp), WARN); return OK; } int fill_dst( const prb_t *prb, dnn_mem_t &mem_dt, dnn_mem_t &mem_fp, res_t *res) { const auto &c = prb->cfg[DST]; const int range = c.f_max - c.f_min + 1; dnnl::impl::parallel_nd(prb->mb, prb->oc, [&](int mb, int oc) { const int gen = 173 * mb + 179 * oc; const bool non_base = flip_coin(gen, c.f_sparsity); const float value = non_base ? c.f_min + gen * 1 % range : c.f_base; ((float *)mem_fp)[dst_off_f(prb, mb, oc)] = value; }); SAFE(mem_dt.reorder(mem_fp), WARN); return OK; } void check_known_skipped_case(const prb_t *prb, res_t *res) { check_known_skipped_case_common( {prb->cfg[SRC].dt, prb->cfg[WEI].dt, prb->cfg[DST].dt}, prb->dir, res); if (res->state == SKIPPED) return; if (is_nvidia_gpu()) { const auto &po = prb->attr.post_ops; bool post_ops_ok = true; for (int i = 0; i < po.len(); ++i) { const auto &e = po.entry[i]; if (e.is_sum_kind()) continue; else if (e.is_eltwise_kind()) post_ops_ok = post_ops_ok && is_nvidia_eltwise_ok(prb->dir, e); else if (e.is_binary_kind() || e.is_convolution_kind()) post_ops_ok = false; else assert(!"unknown post-op type"); } const bool oscale_ok = prb->attr.oscale.policy == policy_t::COMMON; if (!post_ops_ok || !oscale_ok) { res->state = SKIPPED, res->reason = CASE_NOT_SUPPORTED; return; } } } int doit(const prb_t *prb, res_t *res) { if (bench_mode == LIST) return res->state = LISTED, OK; check_known_skipped_case(prb, res); if (res->state == SKIPPED) return OK; dnnl_primitive_t ip {}; SAFE(init_prim(&ip, init_pd, prb, res), WARN); if (res->state == SKIPPED || res->state == UNIMPLEMENTED) return OK; const_dnnl_primitive_desc_t const_pd; DNN_SAFE(dnnl_primitive_get_primitive_desc(ip, &const_pd), CRIT); if (check_mem_size(const_pd) != OK) { DNN_SAFE_V(dnnl_primitive_destroy(ip)); return res->state = SKIPPED, res->reason = NOT_ENOUGH_RAM, OK; } const auto q = [&](int index = 0) -> const dnnl_memory_desc_t & { return *dnnl_primitive_desc_query_md( const_pd, dnnl_query_exec_arg_md, index); }; const auto &src_md = prb->dir == BWD_D ? q(DNNL_ARG_DIFF_SRC) : q(DNNL_ARG_SRC); const auto &wei_md = prb->dir & FLAG_WEI ? q(DNNL_ARG_DIFF_WEIGHTS) : q(DNNL_ARG_WEIGHTS); const auto &bia_md = prb->dir & FLAG_WEI ? q(DNNL_ARG_DIFF_BIAS) : q(DNNL_ARG_BIAS); const auto &dst_md = prb->dir & FLAG_BWD ? q(DNNL_ARG_DIFF_DST) : q(DNNL_ARG_DST); const auto &scratchpad_md = q(DNNL_ARG_SCRATCHPAD); const auto fp = dnnl_f32; const auto src_tag = tag::abx; const auto wei_tag = tag::abx; const auto &test_engine = get_test_engine(); dnn_mem_t src_dt(src_md, test_engine); dnn_mem_t wei_dt(wei_md, test_engine); dnn_mem_t bia_dt(bia_md, test_engine); dnn_mem_t dst_dt(dst_md, test_engine); dnn_mem_t scratchpad_dt(scratchpad_md, test_engine); std::vector<dnn_mem_t> binary_po_fp, binary_po_dt; std::vector<int> binary_po_args; SAFE(binary::setup_binary_po( const_pd, binary_po_args, binary_po_dt, binary_po_fp), WARN); dnn_mem_t src_fp(src_md, fp, src_tag, test_engine); dnn_mem_t wei_fp(wei_md, fp, wei_tag, test_engine); dnn_mem_t bia_fp(bia_md, fp, tag::x, test_engine); dnn_mem_t dst_fp(dst_md, fp, tag::abx, test_engine); SAFE(fill_src(prb, src_dt, src_fp, res), WARN); SAFE(fill_wei(prb, wei_dt, wei_fp, res), WARN); SAFE(fill_bia(prb, bia_dt, bia_fp, res), WARN); SAFE(fill_dst(prb, dst_dt, dst_fp, res), WARN); args_t args; if (prb->dir & FLAG_FWD) { args.set(DNNL_ARG_SRC, src_dt); args.set(DNNL_ARG_WEIGHTS, wei_dt); args.set(DNNL_ARG_BIAS, bia_dt); args.set(DNNL_ARG_DST, dst_dt); args.set(DNNL_ARG_SCRATCHPAD, scratchpad_dt); args.set(binary_po_args, binary_po_dt); SAFE(execute_and_wait(ip, args), WARN); if (bench_mode & CORR) { compute_ref_fwd(test_engine, prb, src_fp, wei_fp, bia_fp, binary_po_fp, dst_fp); compare::compare_t cmp; cmp.set_threshold(prb->cfg[DST].eps); cmp.set_data_kind(DST); cmp.set_zero_trust_percent(80.f); // TODO: why so bad filling? SAFE(cmp.compare(dst_fp, dst_dt, prb->attr, res), WARN); } } else if (prb->dir == BWD_D) { args.set(DNNL_ARG_DIFF_DST, dst_dt); args.set(DNNL_ARG_WEIGHTS, wei_dt); args.set(DNNL_ARG_DIFF_SRC, src_dt); args.set(DNNL_ARG_SCRATCHPAD, scratchpad_dt); SAFE(execute_and_wait(ip, args), WARN); if (bench_mode & CORR) { compute_ref_bwd_d(prb, src_fp, wei_fp, dst_fp); compare::compare_t cmp; cmp.set_threshold(prb->cfg[SRC].eps); cmp.set_data_kind(SRC); cmp.set_zero_trust_percent(80.f); // TODO: why so bad filling? SAFE(cmp.compare(src_fp, src_dt, prb->attr, res), WARN); } } else if (prb->dir & FLAG_BWD && prb->dir & FLAG_WEI) { args.set(DNNL_ARG_SRC, src_dt); args.set(DNNL_ARG_DIFF_DST, dst_dt); args.set(DNNL_ARG_DIFF_WEIGHTS, wei_dt); args.set(DNNL_ARG_DIFF_BIAS, bia_dt); args.set(DNNL_ARG_SCRATCHPAD, scratchpad_dt); SAFE(execute_and_wait(ip, args), WARN); if (bench_mode & CORR) { compute_ref_bwd_w(prb, src_fp, wei_fp, bia_fp, dst_fp); compare::compare_t cmp; cmp.set_threshold(prb->cfg[WEI].eps); cmp.set_data_kind(WEI); cmp.set_zero_trust_percent(90.f); // TODO: why so bad filling? SAFE(cmp.compare(wei_fp, wei_dt, prb->attr, res), WARN); if (prb->dir & FLAG_BIA) { cmp.set_threshold(prb->cfg[BIA].eps); cmp.set_data_kind(BIA); cmp.set_zero_trust_percent(90.f); // TODO: why so bad filling? SAFE(cmp.compare(bia_fp, bia_dt, prb->attr, res), WARN); } } } measure_perf(res->timer, ip, args); DNN_SAFE_V(dnnl_primitive_destroy(ip)); return OK; } } // namespace ip
/*************************************************************************/ /* visual_shader_editor_plugin.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* 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 "visual_shader_editor_plugin.h" #include "core/io/resource_loader.h" #include "core/os/input.h" #include "core/os/keyboard.h" #include "core/project_settings.h" #include "editor/editor_properties.h" #include "scene/animation/animation_player.h" #include "scene/gui/menu_button.h" #include "scene/gui/panel.h" #include "scene/main/viewport.h" #include "scene/resources/visual_shader_nodes.h" Control *VisualShaderNodePlugin::create_editor(const Ref<VisualShaderNode> &p_node) { if (get_script_instance()) { return get_script_instance()->call("create_editor", p_node); } return NULL; } void VisualShaderNodePlugin::_bind_methods() { BIND_VMETHOD(MethodInfo(Variant::OBJECT, "create_editor", PropertyInfo(Variant::OBJECT, "for_node", PROPERTY_HINT_RESOURCE_TYPE, "VisualShaderNode"))); } /////////////////// void VisualShaderEditor::edit(VisualShader *p_visual_shader) { if (p_visual_shader) { visual_shader = Ref<VisualShader>(p_visual_shader); } else { visual_shader.unref(); } if (visual_shader.is_null()) { hide(); } else { _update_graph(); } } void VisualShaderEditor::add_plugin(const Ref<VisualShaderNodePlugin> &p_plugin) { if (plugins.find(p_plugin) != -1) return; plugins.push_back(p_plugin); } void VisualShaderEditor::remove_plugin(const Ref<VisualShaderNodePlugin> &p_plugin) { plugins.erase(p_plugin); } void VisualShaderEditor::add_custom_type(const String &p_name, const String &p_category, const Ref<Script> &p_script) { for (int i = 0; i < add_options.size(); i++) { ERR_FAIL_COND(add_options[i].script == p_script); } AddOption ao; ao.name = p_name; ao.script = p_script; ao.category = p_category; add_options.push_back(ao); _update_options_menu(); } void VisualShaderEditor::remove_custom_type(const Ref<Script> &p_script) { for (int i = 0; i < add_options.size(); i++) { if (add_options[i].script == p_script) { add_options.remove(i); return; } } _update_options_menu(); } bool VisualShaderEditor::_is_available(int p_mode) { int current_mode = edit_type->get_selected(); if (p_mode != -1) { switch (current_mode) { case VisualShader::TYPE_VERTEX: current_mode = 1; break; case VisualShader::TYPE_FRAGMENT: current_mode = 2; break; case VisualShader::TYPE_LIGHT: current_mode = 4; break; default: break; } int temp_mode = 0; if (p_mode & VisualShader::TYPE_FRAGMENT) { temp_mode |= 2; } if (p_mode & VisualShader::TYPE_LIGHT) { temp_mode |= 4; } if (temp_mode == 0) { temp_mode |= 1; } p_mode = temp_mode; } if (p_mode != -1 && ((p_mode & current_mode) == 0)) { return false; } return true; } void VisualShaderEditor::_update_options_menu() { node_desc->set_text(""); members_dialog->get_ok()->set_disabled(true); String prev_category; String prev_sub_category; members->clear(); TreeItem *root = members->create_item(); TreeItem *category = NULL; TreeItem *sub_category = NULL; String filter = node_filter->get_text().strip_edges(); bool use_filter = !filter.empty(); Vector<String> categories; Vector<String> sub_categories; int item_count = 0; int item_count2 = 0; for (int i = 0; i < add_options.size() + 1; i++) { if (i == add_options.size()) { if (sub_category != NULL && item_count2 == 0) { memdelete(sub_category); --item_count; } if (category != NULL && item_count == 0) { memdelete(category); } break; } if (!use_filter || add_options[i].name.findn(filter) != -1) { if (prev_category != add_options[i].category) { if (category != NULL && item_count == 0) { memdelete(category); } item_count = 0; prev_sub_category = ""; category = members->create_item(root); category->set_text(0, add_options[i].category); if (!use_filter) category->set_collapsed(true); } if (add_options[i].sub_category != "") { if (prev_sub_category != add_options[i].sub_category) { if (category != NULL) { if (sub_category != NULL && item_count2 == 0) { memdelete(sub_category); --item_count; } ++item_count; item_count2 = 0; sub_category = members->create_item(category); sub_category->set_text(0, add_options[i].sub_category); if (!use_filter) sub_category->set_collapsed(true); } } if (sub_category != NULL) { if (_is_available(add_options[i].mode)) { ++item_count2; TreeItem *item = members->create_item(sub_category); item->set_text(0, add_options[i].name); switch (add_options[i].return_type) { case VisualShaderNode::PORT_TYPE_SCALAR: item->set_icon(0, EditorNode::get_singleton()->get_gui_base()->get_icon("float", "EditorIcons")); break; case VisualShaderNode::PORT_TYPE_VECTOR: item->set_icon(0, EditorNode::get_singleton()->get_gui_base()->get_icon("Vector3", "EditorIcons")); break; case VisualShaderNode::PORT_TYPE_BOOLEAN: item->set_icon(0, EditorNode::get_singleton()->get_gui_base()->get_icon("bool", "EditorIcons")); break; case VisualShaderNode::PORT_TYPE_TRANSFORM: item->set_icon(0, EditorNode::get_singleton()->get_gui_base()->get_icon("Transform", "EditorIcons")); break; case VisualShaderNode::PORT_TYPE_COLOR: item->set_icon(0, EditorNode::get_singleton()->get_gui_base()->get_icon("Color", "EditorIcons")); break; default: break; } item->set_meta("id", i); } } } else { if (category != NULL) { if (_is_available(add_options[i].mode)) { ++item_count; TreeItem *item = members->create_item(category); item->set_text(0, add_options[i].name); switch (add_options[i].return_type) { case VisualShaderNode::PORT_TYPE_SCALAR: item->set_icon(0, EditorNode::get_singleton()->get_gui_base()->get_icon("float", "EditorIcons")); break; case VisualShaderNode::PORT_TYPE_VECTOR: item->set_icon(0, EditorNode::get_singleton()->get_gui_base()->get_icon("Vector3", "EditorIcons")); break; case VisualShaderNode::PORT_TYPE_BOOLEAN: item->set_icon(0, EditorNode::get_singleton()->get_gui_base()->get_icon("bool", "EditorIcons")); break; case VisualShaderNode::PORT_TYPE_TRANSFORM: item->set_icon(0, EditorNode::get_singleton()->get_gui_base()->get_icon("Transform", "EditorIcons")); break; case VisualShaderNode::PORT_TYPE_COLOR: item->set_icon(0, EditorNode::get_singleton()->get_gui_base()->get_icon("Color", "EditorIcons")); break; default: break; } item->set_meta("id", i); } } } prev_sub_category = add_options[i].sub_category; prev_category = add_options[i].category; } } } Size2 VisualShaderEditor::get_minimum_size() const { return Size2(10, 200); } void VisualShaderEditor::_draw_color_over_button(Object *obj, Color p_color) { Button *button = Object::cast_to<Button>(obj); if (!button) return; Ref<StyleBox> normal = get_stylebox("normal", "Button"); button->draw_rect(Rect2(normal->get_offset(), button->get_size() - normal->get_minimum_size()), p_color); } static Ref<StyleBoxEmpty> make_empty_stylebox(float p_margin_left = -1, float p_margin_top = -1, float p_margin_right = -1, float p_margin_bottom = -1) { Ref<StyleBoxEmpty> style(memnew(StyleBoxEmpty)); style->set_default_margin(MARGIN_LEFT, p_margin_left * EDSCALE); style->set_default_margin(MARGIN_RIGHT, p_margin_right * EDSCALE); style->set_default_margin(MARGIN_BOTTOM, p_margin_bottom * EDSCALE); style->set_default_margin(MARGIN_TOP, p_margin_top * EDSCALE); return style; } void VisualShaderEditor::_update_graph() { if (updating) return; if (visual_shader.is_null()) return; graph->set_scroll_ofs(visual_shader->get_graph_offset() * EDSCALE); VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); graph->clear_connections(); //erase all nodes for (int i = 0; i < graph->get_child_count(); i++) { if (Object::cast_to<GraphNode>(graph->get_child(i))) { memdelete(graph->get_child(i)); i--; } } static const Color type_color[4] = { Color::html("#61daf4"), // scalar Color::html("#d67dee"), // vector Color::html("#8da6f0"), // boolean Color::html("#f6a86e") // transform }; List<VisualShader::Connection> connections; visual_shader->get_node_connections(type, &connections); Ref<StyleBoxEmpty> label_style = make_empty_stylebox(2, 1, 2, 1); Vector<int> nodes = visual_shader->get_node_list(type); for (int n_i = 0; n_i < nodes.size(); n_i++) { Vector2 position = visual_shader->get_node_position(type, nodes[n_i]); Ref<VisualShaderNode> vsnode = visual_shader->get_node(type, nodes[n_i]); GraphNode *node = memnew(GraphNode); graph->add_child(node); /*if (!vsnode->is_connected("changed", this, "_node_changed")) { vsnode->connect("changed", this, "_node_changed", varray(vsnode->get_instance_id()), CONNECT_DEFERRED); }*/ node->set_offset(position); node->set_title(vsnode->get_caption()); node->set_name(itos(nodes[n_i])); if (nodes[n_i] >= 2) { node->set_show_close_button(true); node->connect("close_request", this, "_delete_request", varray(nodes[n_i]), CONNECT_DEFERRED); } node->connect("dragged", this, "_node_dragged", varray(nodes[n_i])); Control *custom_editor = NULL; int port_offset = 0; Ref<VisualShaderNodeUniform> uniform = vsnode; if (uniform.is_valid()) { LineEdit *uniform_name = memnew(LineEdit); uniform_name->set_text(uniform->get_uniform_name()); node->add_child(uniform_name); uniform_name->connect("text_entered", this, "_line_edit_changed", varray(uniform_name, nodes[n_i])); uniform_name->connect("focus_exited", this, "_line_edit_focus_out", varray(uniform_name, nodes[n_i])); if (vsnode->get_input_port_count() == 0 && vsnode->get_output_port_count() == 1 && vsnode->get_output_port_name(0) == "") { //shortcut VisualShaderNode::PortType port_right = vsnode->get_output_port_type(0); node->set_slot(0, false, VisualShaderNode::PORT_TYPE_SCALAR, Color(), true, port_right, type_color[port_right]); continue; } port_offset++; } for (int i = 0; i < plugins.size(); i++) { custom_editor = plugins.write[i]->create_editor(vsnode); if (custom_editor) { break; } } if (custom_editor && vsnode->get_output_port_count() > 0 && vsnode->get_output_port_name(0) == "" && (vsnode->get_input_port_count() == 0 || vsnode->get_input_port_name(0) == "")) { //will be embedded in first port } else if (custom_editor) { port_offset++; node->add_child(custom_editor); custom_editor = NULL; } for (int i = 0; i < MAX(vsnode->get_input_port_count(), vsnode->get_output_port_count()); i++) { if (vsnode->is_port_separator(i)) { node->add_child(memnew(HSeparator)); port_offset++; } bool valid_left = i < vsnode->get_input_port_count(); VisualShaderNode::PortType port_left = VisualShaderNode::PORT_TYPE_SCALAR; bool port_left_used = false; String name_left; if (valid_left) { name_left = vsnode->get_input_port_name(i); port_left = vsnode->get_input_port_type(i); for (List<VisualShader::Connection>::Element *E = connections.front(); E; E = E->next()) { if (E->get().to_node == nodes[n_i] && E->get().to_port == i) { port_left_used = true; } } } bool valid_right = i < vsnode->get_output_port_count(); VisualShaderNode::PortType port_right = VisualShaderNode::PORT_TYPE_SCALAR; String name_right; if (valid_right) { name_right = vsnode->get_output_port_name(i); port_right = vsnode->get_output_port_type(i); } HBoxContainer *hb = memnew(HBoxContainer); Variant default_value; if (valid_left && !port_left_used) { default_value = vsnode->get_input_port_default_value(i); } if (default_value.get_type() != Variant::NIL) { // only a label Button *button = memnew(Button); hb->add_child(button); button->connect("pressed", this, "_edit_port_default_input", varray(button, nodes[n_i], i)); switch (default_value.get_type()) { case Variant::COLOR: { button->set_custom_minimum_size(Size2(30, 0) * EDSCALE); button->connect("draw", this, "_draw_color_over_button", varray(button, default_value)); } break; case Variant::INT: case Variant::REAL: { button->set_text(String::num(default_value, 4)); } break; case Variant::VECTOR3: { Vector3 v = default_value; button->set_text(String::num(v.x, 3) + "," + String::num(v.y, 3) + "," + String::num(v.z, 3)); } break; default: {} } } if (i == 0 && custom_editor) { hb->add_child(custom_editor); custom_editor->set_h_size_flags(SIZE_EXPAND_FILL); } else { if (valid_left) { Label *label = memnew(Label); label->set_text(name_left); label->add_style_override("normal", label_style); //more compact hb->add_child(label); } hb->add_spacer(); if (valid_right) { Label *label = memnew(Label); label->set_text(name_right); label->set_align(Label::ALIGN_RIGHT); label->add_style_override("normal", label_style); //more compact hb->add_child(label); } } if (valid_right && edit_type->get_selected() == VisualShader::TYPE_FRAGMENT) { TextureButton *preview = memnew(TextureButton); preview->set_toggle_mode(true); preview->set_normal_texture(get_icon("GuiVisibilityHidden", "EditorIcons")); preview->set_pressed_texture(get_icon("GuiVisibilityVisible", "EditorIcons")); preview->set_v_size_flags(SIZE_SHRINK_CENTER); if (vsnode->get_output_port_for_preview() == i) { preview->set_pressed(true); } preview->connect("pressed", this, "_preview_select_port", varray(nodes[n_i], i), CONNECT_DEFERRED); hb->add_child(preview); } node->add_child(hb); node->set_slot(i + port_offset, valid_left, port_left, type_color[port_left], valid_right, port_right, type_color[port_right]); if (EditorSettings::get_singleton()->get("interface/theme/use_graph_node_headers")) { Ref<StyleBoxFlat> sb = node->get_stylebox("frame", "GraphNode"); Color c = sb->get_border_color(); Color mono_color = ((c.r + c.g + c.b) / 3) < 0.7 ? Color(1.0, 1.0, 1.0) : Color(0.0, 0.0, 0.0); mono_color.a = 0.85; c = mono_color; node->add_color_override("title_color", c); c.a = 0.7; node->add_color_override("close_color", c); } } if (vsnode->get_output_port_for_preview() >= 0) { VisualShaderNodePortPreview *port_preview = memnew(VisualShaderNodePortPreview); port_preview->setup(visual_shader, type, nodes[n_i], vsnode->get_output_port_for_preview()); port_preview->set_h_size_flags(SIZE_SHRINK_CENTER); node->add_child(port_preview); } String error = vsnode->get_warning(visual_shader->get_mode(), type); if (error != String()) { Label *error_label = memnew(Label); error_label->add_color_override("font_color", get_color("error_color", "Editor")); error_label->set_text(error); node->add_child(error_label); } } for (List<VisualShader::Connection>::Element *E = connections.front(); E; E = E->next()) { int from = E->get().from_node; int from_idx = E->get().from_port; int to = E->get().to_node; int to_idx = E->get().to_port; graph->connect_node(itos(from), from_idx, itos(to), to_idx); } } void VisualShaderEditor::_preview_select_port(int p_node, int p_port) { VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); Ref<VisualShaderNode> node = visual_shader->get_node(type, p_node); if (node.is_null()) { return; } if (node->get_output_port_for_preview() == p_port) { p_port = -1; //toggle it } undo_redo->create_action(TTR("Set Uniform Name")); undo_redo->add_do_method(node.ptr(), "set_output_port_for_preview", p_port); undo_redo->add_undo_method(node.ptr(), "set_output_port_for_preview", node->get_output_port_for_preview()); undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); undo_redo->commit_action(); } void VisualShaderEditor::_line_edit_changed(const String &p_text, Object *line_edit, int p_node_id) { VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); Ref<VisualShaderNodeUniform> node = visual_shader->get_node(type, p_node_id); ERR_FAIL_COND(!node.is_valid()); String validated_name = visual_shader->validate_uniform_name(p_text, node); updating = true; undo_redo->create_action(TTR("Set Uniform Name")); undo_redo->add_do_method(node.ptr(), "set_uniform_name", validated_name); undo_redo->add_undo_method(node.ptr(), "set_uniform_name", node->get_uniform_name()); undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); undo_redo->commit_action(); updating = false; Object::cast_to<LineEdit>(line_edit)->set_text(validated_name); } void VisualShaderEditor::_line_edit_focus_out(Object *line_edit, int p_node_id) { String text = Object::cast_to<LineEdit>(line_edit)->get_text(); _line_edit_changed(text, line_edit, p_node_id); } void VisualShaderEditor::_port_edited() { VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); Variant value = property_editor->get_variant(); Ref<VisualShaderNode> vsn = visual_shader->get_node(type, editing_node); ERR_FAIL_COND(!vsn.is_valid()); undo_redo->create_action(TTR("Set Input Default Port")); undo_redo->add_do_method(vsn.ptr(), "set_input_port_default_value", editing_port, value); undo_redo->add_undo_method(vsn.ptr(), "set_input_port_default_value", editing_port, vsn->get_input_port_default_value(editing_port)); undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); undo_redo->commit_action(); property_editor->hide(); } void VisualShaderEditor::_edit_port_default_input(Object *p_button, int p_node, int p_port) { VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); Ref<VisualShaderNode> vsn = visual_shader->get_node(type, p_node); Button *button = Object::cast_to<Button>(p_button); ERR_FAIL_COND(!button); Variant value = vsn->get_input_port_default_value(p_port); property_editor->set_global_position(button->get_global_position() + Vector2(0, button->get_size().height)); property_editor->edit(NULL, "", value.get_type(), value, 0, ""); property_editor->popup(); editing_node = p_node; editing_port = p_port; } void VisualShaderEditor::_add_node(int p_idx, int p_op_idx) { ERR_FAIL_INDEX(p_idx, add_options.size()); Ref<VisualShaderNode> vsnode; if (add_options[p_idx].type != String()) { VisualShaderNode *vsn = Object::cast_to<VisualShaderNode>(ClassDB::instance(add_options[p_idx].type)); ERR_FAIL_COND(!vsn); if (p_op_idx != -1) { VisualShaderNodeInput *input = Object::cast_to<VisualShaderNodeInput>(vsn); if (input) { input->set_input_name(add_options[p_idx].sub_func_str); } VisualShaderNodeColorOp *colorOp = Object::cast_to<VisualShaderNodeColorOp>(vsn); if (colorOp) { colorOp->set_operator((VisualShaderNodeColorOp::Operator)p_op_idx); } VisualShaderNodeColorFunc *colorFunc = Object::cast_to<VisualShaderNodeColorFunc>(vsn); if (colorFunc) { colorFunc->set_function((VisualShaderNodeColorFunc::Function)p_op_idx); } VisualShaderNodeScalarOp *scalarOp = Object::cast_to<VisualShaderNodeScalarOp>(vsn); if (scalarOp) { scalarOp->set_operator((VisualShaderNodeScalarOp::Operator)p_op_idx); } VisualShaderNodeScalarFunc *scalarFunc = Object::cast_to<VisualShaderNodeScalarFunc>(vsn); if (scalarFunc) { scalarFunc->set_function((VisualShaderNodeScalarFunc::Function)p_op_idx); } VisualShaderNodeVectorOp *vecOp = Object::cast_to<VisualShaderNodeVectorOp>(vsn); if (vecOp) { vecOp->set_operator((VisualShaderNodeVectorOp::Operator)p_op_idx); } VisualShaderNodeVectorFunc *vecFunc = Object::cast_to<VisualShaderNodeVectorFunc>(vsn); if (vecFunc) { vecFunc->set_function((VisualShaderNodeVectorFunc::Function)p_op_idx); } VisualShaderNodeTransformFunc *matFunc = Object::cast_to<VisualShaderNodeTransformFunc>(vsn); if (matFunc) { matFunc->set_function((VisualShaderNodeTransformFunc::Function)p_op_idx); } VisualShaderNodeScalarDerivativeFunc *sderFunc = Object::cast_to<VisualShaderNodeScalarDerivativeFunc>(vsn); if (sderFunc) { sderFunc->set_function((VisualShaderNodeScalarDerivativeFunc::Function)p_op_idx); } VisualShaderNodeVectorDerivativeFunc *vderFunc = Object::cast_to<VisualShaderNodeVectorDerivativeFunc>(vsn); if (vderFunc) { vderFunc->set_function((VisualShaderNodeVectorDerivativeFunc::Function)p_op_idx); } } vsnode = Ref<VisualShaderNode>(vsn); } else { ERR_FAIL_COND(add_options[p_idx].script.is_null()); String base_type = add_options[p_idx].script->get_instance_base_type(); VisualShaderNode *vsn = Object::cast_to<VisualShaderNode>(ClassDB::instance(base_type)); ERR_FAIL_COND(!vsn); vsnode = Ref<VisualShaderNode>(vsn); vsnode->set_script(add_options[p_idx].script.get_ref_ptr()); } Point2 position = graph->get_scroll_ofs(); if (saved_node_pos_dirty) { position += saved_node_pos; } else { position += graph->get_size() * 0.5; position /= EDSCALE; } saved_node_pos_dirty = false; VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); int id_to_use = visual_shader->get_valid_node_id(type); undo_redo->create_action(TTR("Add Node to Visual Shader")); undo_redo->add_do_method(visual_shader.ptr(), "add_node", type, vsnode, position, id_to_use); undo_redo->add_undo_method(visual_shader.ptr(), "remove_node", type, id_to_use); undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); undo_redo->commit_action(); } void VisualShaderEditor::_node_dragged(const Vector2 &p_from, const Vector2 &p_to, int p_node) { VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); updating = true; undo_redo->create_action(TTR("Node Moved")); undo_redo->add_do_method(visual_shader.ptr(), "set_node_position", type, p_node, p_to); undo_redo->add_undo_method(visual_shader.ptr(), "set_node_position", type, p_node, p_from); undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); undo_redo->commit_action(); updating = false; } void VisualShaderEditor::_connection_request(const String &p_from, int p_from_index, const String &p_to, int p_to_index) { VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); int from = p_from.to_int(); int to = p_to.to_int(); if (!visual_shader->can_connect_nodes(type, from, p_from_index, to, p_to_index)) { EditorNode::get_singleton()->show_warning(TTR("Unable to connect, port may be in use or connection may be invalid.")); return; } undo_redo->create_action(TTR("Nodes Connected")); List<VisualShader::Connection> conns; visual_shader->get_node_connections(type, &conns); for (List<VisualShader::Connection>::Element *E = conns.front(); E; E = E->next()) { if (E->get().to_node == to && E->get().to_port == p_to_index) { undo_redo->add_do_method(visual_shader.ptr(), "disconnect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); undo_redo->add_undo_method(visual_shader.ptr(), "connect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); } } undo_redo->add_do_method(visual_shader.ptr(), "connect_nodes", type, from, p_from_index, to, p_to_index); undo_redo->add_undo_method(visual_shader.ptr(), "disconnect_nodes", type, from, p_from_index, to, p_to_index); undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); undo_redo->commit_action(); } void VisualShaderEditor::_disconnection_request(const String &p_from, int p_from_index, const String &p_to, int p_to_index) { graph->disconnect_node(p_from, p_from_index, p_to, p_to_index); VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); int from = p_from.to_int(); int to = p_to.to_int(); //updating = true; seems graph edit can handle this, no need to protect undo_redo->create_action(TTR("Nodes Disconnected")); undo_redo->add_do_method(visual_shader.ptr(), "disconnect_nodes", type, from, p_from_index, to, p_to_index); undo_redo->add_undo_method(visual_shader.ptr(), "connect_nodes", type, from, p_from_index, to, p_to_index); undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); undo_redo->commit_action(); //updating = false; } void VisualShaderEditor::_connection_to_empty(const String &p_from, int p_from_slot, const Vector2 &p_release_position) { } void VisualShaderEditor::_delete_request(int which) { VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); undo_redo->create_action(TTR("Delete Node")); undo_redo->add_do_method(visual_shader.ptr(), "remove_node", type, which); undo_redo->add_undo_method(visual_shader.ptr(), "add_node", type, visual_shader->get_node(type, which), visual_shader->get_node_position(type, which), which); List<VisualShader::Connection> conns; visual_shader->get_node_connections(type, &conns); for (List<VisualShader::Connection>::Element *E = conns.front(); E; E = E->next()) { if (E->get().from_node == which || E->get().to_node == which) { undo_redo->add_undo_method(visual_shader.ptr(), "connect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); } } undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); undo_redo->commit_action(); } void VisualShaderEditor::_node_selected(Object *p_node) { VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); GraphNode *gn = Object::cast_to<GraphNode>(p_node); ERR_FAIL_COND(!gn); int id = String(gn->get_name()).to_int(); Ref<VisualShaderNode> vsnode = visual_shader->get_node(type, id); ERR_FAIL_COND(!vsnode.is_valid()); //do not rely on this, makes editor more complex //EditorNode::get_singleton()->push_item(vsnode.ptr(), "", true); } void VisualShaderEditor::_member_gui_input(const Ref<InputEvent> p_event) { Ref<InputEventMouseButton> mb = p_event; Ref<InputEventKey> key = p_event; if (mb.is_valid()) { if (mb->is_pressed() && mb->get_button_index() == BUTTON_LEFT && mb->is_doubleclick()) { _member_create(); } } else if (key.is_valid()) { if (key->is_pressed() && key->get_scancode() == KEY_ENTER) { _member_create(); } } } void VisualShaderEditor::_input(const Ref<InputEvent> p_event) { if (graph->has_focus()) { Ref<InputEventMouseButton> mb = p_event; if (mb.is_valid() && mb->is_pressed() && mb->get_button_index() == BUTTON_RIGHT) { saved_node_pos_dirty = true; saved_node_pos = graph->get_local_mouse_position(); Point2 gpos = Input::get_singleton()->get_mouse_position(); members_dialog->popup(); members_dialog->set_position(gpos); } } } void VisualShaderEditor::_show_members_dialog() { saved_node_pos_dirty = false; members_dialog->popup(); members_dialog->set_position(graph->get_global_position() + Point2(5 * EDSCALE, 65 * EDSCALE)); } void VisualShaderEditor::_notification(int p_what) { if (p_what == NOTIFICATION_ENTER_TREE) { node_filter->set_clear_button_enabled(true); // collapse tree by default TreeItem *category = members->get_root()->get_children(); while (category) { category->set_collapsed(true); TreeItem *sub_category = category->get_children(); while (sub_category) { sub_category->set_collapsed(true); sub_category = sub_category->get_next(); } category = category->get_next(); } } if (p_what == NOTIFICATION_DRAG_BEGIN) { Dictionary dd = get_viewport()->gui_get_drag_data(); if (members->is_visible_in_tree() && dd.has("id")) { members->set_drop_mode_flags(Tree::DROP_MODE_ON_ITEM); } } else if (p_what == NOTIFICATION_DRAG_END) { members->set_drop_mode_flags(0); } if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) { error_panel->add_style_override("panel", get_stylebox("bg", "Tree")); error_label->add_color_override("font_color", get_color("error_color", "Editor")); node_filter->set_right_icon(Control::get_icon("Search", "EditorIcons")); tools->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("Tools", "EditorIcons")); if (p_what == NOTIFICATION_THEME_CHANGED && is_visible_in_tree()) _update_graph(); } else if (p_what == NOTIFICATION_PROCESS) { } } void VisualShaderEditor::_scroll_changed(const Vector2 &p_scroll) { if (updating) return; updating = true; visual_shader->set_graph_offset(p_scroll / EDSCALE); updating = false; } void VisualShaderEditor::_node_changed(int p_id) { if (updating) return; if (is_visible_in_tree()) { _update_graph(); } } void VisualShaderEditor::_duplicate_nodes() { VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); List<int> nodes; Set<int> excluded; for (int i = 0; i < graph->get_child_count(); i++) { GraphNode *gn = Object::cast_to<GraphNode>(graph->get_child(i)); if (gn) { int id = String(gn->get_name()).to_int(); Ref<VisualShaderNode> node = visual_shader->get_node(type, id); Ref<VisualShaderNodeOutput> output = node; if (output.is_valid()) { // can't duplicate output excluded.insert(id); continue; } if (node.is_valid() && gn->is_selected()) { nodes.push_back(id); } excluded.insert(id); } } if (nodes.empty()) return; undo_redo->create_action(TTR("Duplicate Nodes")); int base_id = visual_shader->get_valid_node_id(type); int id_from = base_id; Map<int, int> connection_remap; for (List<int>::Element *E = nodes.front(); E; E = E->next()) { connection_remap[E->get()] = id_from; Ref<VisualShaderNode> node = visual_shader->get_node(type, E->get()); Ref<VisualShaderNode> dupli = node->duplicate(); undo_redo->add_do_method(visual_shader.ptr(), "add_node", type, dupli, visual_shader->get_node_position(type, E->get()) + Vector2(10, 10) * EDSCALE, id_from); undo_redo->add_undo_method(visual_shader.ptr(), "remove_node", type, id_from); id_from++; } List<VisualShader::Connection> conns; visual_shader->get_node_connections(type, &conns); for (List<VisualShader::Connection>::Element *E = conns.front(); E; E = E->next()) { if (connection_remap.has(E->get().from_node) && connection_remap.has(E->get().to_node)) { undo_redo->add_do_method(visual_shader.ptr(), "connect_nodes", type, connection_remap[E->get().from_node], E->get().from_port, connection_remap[E->get().to_node], E->get().to_port); } } undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); undo_redo->commit_action(); // reselect duplicated nodes by excluding the other ones for (int i = 0; i < graph->get_child_count(); i++) { GraphNode *gn = Object::cast_to<GraphNode>(graph->get_child(i)); if (gn) { int id = String(gn->get_name()).to_int(); if (!excluded.has(id)) { gn->set_selected(true); } else { gn->set_selected(false); } } } } void VisualShaderEditor::_mode_selected(int p_id) { _update_options_menu(); _update_graph(); } void VisualShaderEditor::_input_select_item(Ref<VisualShaderNodeInput> input, String name) { String prev_name = input->get_input_name(); if (name == prev_name) return; bool type_changed = input->get_input_type_by_name(name) != input->get_input_type_by_name(prev_name); UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo(); undo_redo->create_action(TTR("Visual Shader Input Type Changed")); undo_redo->add_do_method(input.ptr(), "set_input_name", name); undo_redo->add_undo_method(input.ptr(), "set_input_name", prev_name); if (type_changed) { //restore connections if type changed VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); int id = visual_shader->find_node_id(type, input); List<VisualShader::Connection> conns; visual_shader->get_node_connections(type, &conns); for (List<VisualShader::Connection>::Element *E = conns.front(); E; E = E->next()) { if (E->get().from_node == id) { undo_redo->add_undo_method(visual_shader.ptr(), "connect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); } } } undo_redo->add_do_method(VisualShaderEditor::get_singleton(), "_update_graph"); undo_redo->add_undo_method(VisualShaderEditor::get_singleton(), "_update_graph"); undo_redo->commit_action(); } void VisualShaderEditor::_member_filter_changed(const String &p_text) { _update_options_menu(); } void VisualShaderEditor::_member_selected() { TreeItem *item = members->get_selected(); if (item != NULL && item->has_meta("id")) { members_dialog->get_ok()->set_disabled(false); node_desc->set_text(add_options[item->get_meta("id")].description); } else { members_dialog->get_ok()->set_disabled(true); node_desc->set_text(""); } } void VisualShaderEditor::_member_unselected() { } void VisualShaderEditor::_member_create() { TreeItem *item = members->get_selected(); if (item != NULL && item->has_meta("id")) { int idx = members->get_selected()->get_meta("id"); _add_node(idx, add_options[idx].sub_func); members_dialog->hide(); } } void VisualShaderEditor::_tools_menu_option(int p_idx) { TreeItem *category = members->get_root()->get_children(); switch (p_idx) { case EXPAND_ALL: while (category) { category->set_collapsed(false); TreeItem *sub_category = category->get_children(); while (sub_category) { sub_category->set_collapsed(false); sub_category = sub_category->get_next(); } category = category->get_next(); } break; case COLLAPSE_ALL: while (category) { category->set_collapsed(true); TreeItem *sub_category = category->get_children(); while (sub_category) { sub_category->set_collapsed(true); sub_category = sub_category->get_next(); } category = category->get_next(); } break; default: break; } } Variant VisualShaderEditor::get_drag_data_fw(const Point2 &p_point, Control *p_from) { if (p_from == members) { TreeItem *it = members->get_item_at_position(p_point); if (!it) return Variant(); if (!it->has_meta("id")) return Variant(); int id = it->get_meta("id"); AddOption op = add_options[id]; Dictionary d; d["id"] = id; if (op.sub_func == -1) { d["sub_func"] = op.sub_func_str; } else { d["sub_func"] = op.sub_func; } Label *label = memnew(Label); label->set_text(it->get_text(0)); set_drag_preview(label); return d; } return Variant(); } bool VisualShaderEditor::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const { if (p_from == graph) { Dictionary d = p_data; if (d.has("id")) { return true; } } return false; } void VisualShaderEditor::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) { if (p_from == graph) { Dictionary d = p_data; if (d.has("id")) { int idx = d["id"]; saved_node_pos = p_point; saved_node_pos_dirty = true; _add_node(idx, add_options[idx].sub_func); } } } void VisualShaderEditor::_bind_methods() { ClassDB::bind_method("_update_graph", &VisualShaderEditor::_update_graph); ClassDB::bind_method("_add_node", &VisualShaderEditor::_add_node); ClassDB::bind_method("_node_dragged", &VisualShaderEditor::_node_dragged); ClassDB::bind_method("_connection_request", &VisualShaderEditor::_connection_request); ClassDB::bind_method("_disconnection_request", &VisualShaderEditor::_disconnection_request); ClassDB::bind_method("_node_selected", &VisualShaderEditor::_node_selected); ClassDB::bind_method("_scroll_changed", &VisualShaderEditor::_scroll_changed); ClassDB::bind_method("_delete_request", &VisualShaderEditor::_delete_request); ClassDB::bind_method("_node_changed", &VisualShaderEditor::_node_changed); ClassDB::bind_method("_edit_port_default_input", &VisualShaderEditor::_edit_port_default_input); ClassDB::bind_method("_port_edited", &VisualShaderEditor::_port_edited); ClassDB::bind_method("_connection_to_empty", &VisualShaderEditor::_connection_to_empty); ClassDB::bind_method("_line_edit_focus_out", &VisualShaderEditor::_line_edit_focus_out); ClassDB::bind_method("_line_edit_changed", &VisualShaderEditor::_line_edit_changed); ClassDB::bind_method("_duplicate_nodes", &VisualShaderEditor::_duplicate_nodes); ClassDB::bind_method("_mode_selected", &VisualShaderEditor::_mode_selected); ClassDB::bind_method("_input_select_item", &VisualShaderEditor::_input_select_item); ClassDB::bind_method("_preview_select_port", &VisualShaderEditor::_preview_select_port); ClassDB::bind_method("_input", &VisualShaderEditor::_input); ClassDB::bind_method(D_METHOD("get_drag_data_fw"), &VisualShaderEditor::get_drag_data_fw); ClassDB::bind_method(D_METHOD("can_drop_data_fw"), &VisualShaderEditor::can_drop_data_fw); ClassDB::bind_method(D_METHOD("drop_data_fw"), &VisualShaderEditor::drop_data_fw); ClassDB::bind_method("_is_available", &VisualShaderEditor::_is_available); ClassDB::bind_method("_tools_menu_option", &VisualShaderEditor::_tools_menu_option); ClassDB::bind_method("_show_members_dialog", &VisualShaderEditor::_show_members_dialog); ClassDB::bind_method("_member_gui_input", &VisualShaderEditor::_member_gui_input); ClassDB::bind_method("_member_filter_changed", &VisualShaderEditor::_member_filter_changed); ClassDB::bind_method("_member_selected", &VisualShaderEditor::_member_selected); ClassDB::bind_method("_member_unselected", &VisualShaderEditor::_member_unselected); ClassDB::bind_method("_member_create", &VisualShaderEditor::_member_create); } VisualShaderEditor *VisualShaderEditor::singleton = NULL; VisualShaderEditor::VisualShaderEditor() { singleton = this; updating = false; saved_node_pos_dirty = false; saved_node_pos = Point2(0, 0); graph = memnew(GraphEdit); add_child(graph); graph->set_drag_forwarding(this); graph->add_valid_right_disconnect_type(VisualShaderNode::PORT_TYPE_SCALAR); graph->add_valid_right_disconnect_type(VisualShaderNode::PORT_TYPE_BOOLEAN); graph->add_valid_right_disconnect_type(VisualShaderNode::PORT_TYPE_VECTOR); graph->add_valid_right_disconnect_type(VisualShaderNode::PORT_TYPE_TRANSFORM); //graph->add_valid_left_disconnect_type(0); graph->set_v_size_flags(SIZE_EXPAND_FILL); graph->connect("connection_request", this, "_connection_request", varray(), CONNECT_DEFERRED); graph->connect("disconnection_request", this, "_disconnection_request", varray(), CONNECT_DEFERRED); graph->connect("node_selected", this, "_node_selected"); graph->connect("scroll_offset_changed", this, "_scroll_changed"); graph->connect("duplicate_nodes_request", this, "_duplicate_nodes"); graph->add_valid_connection_type(VisualShaderNode::PORT_TYPE_SCALAR, VisualShaderNode::PORT_TYPE_SCALAR); graph->add_valid_connection_type(VisualShaderNode::PORT_TYPE_SCALAR, VisualShaderNode::PORT_TYPE_VECTOR); graph->add_valid_connection_type(VisualShaderNode::PORT_TYPE_SCALAR, VisualShaderNode::PORT_TYPE_BOOLEAN); graph->add_valid_connection_type(VisualShaderNode::PORT_TYPE_VECTOR, VisualShaderNode::PORT_TYPE_SCALAR); graph->add_valid_connection_type(VisualShaderNode::PORT_TYPE_VECTOR, VisualShaderNode::PORT_TYPE_VECTOR); graph->add_valid_connection_type(VisualShaderNode::PORT_TYPE_VECTOR, VisualShaderNode::PORT_TYPE_BOOLEAN); graph->add_valid_connection_type(VisualShaderNode::PORT_TYPE_BOOLEAN, VisualShaderNode::PORT_TYPE_SCALAR); graph->add_valid_connection_type(VisualShaderNode::PORT_TYPE_BOOLEAN, VisualShaderNode::PORT_TYPE_VECTOR); graph->add_valid_connection_type(VisualShaderNode::PORT_TYPE_BOOLEAN, VisualShaderNode::PORT_TYPE_BOOLEAN); graph->add_valid_connection_type(VisualShaderNode::PORT_TYPE_TRANSFORM, VisualShaderNode::PORT_TYPE_TRANSFORM); VSeparator *vs = memnew(VSeparator); graph->get_zoom_hbox()->add_child(vs); graph->get_zoom_hbox()->move_child(vs, 0); edit_type = memnew(OptionButton); edit_type->add_item(TTR("Vertex")); edit_type->add_item(TTR("Fragment")); edit_type->add_item(TTR("Light")); edit_type->select(1); edit_type->connect("item_selected", this, "_mode_selected"); graph->get_zoom_hbox()->add_child(edit_type); graph->get_zoom_hbox()->move_child(edit_type, 0); add_node = memnew(ToolButton); graph->get_zoom_hbox()->add_child(add_node); add_node->set_text(TTR("Add Node...")); graph->get_zoom_hbox()->move_child(add_node, 0); add_node->connect("pressed", this, "_show_members_dialog"); /////////////////////////////////////// // SHADER NODES TREE /////////////////////////////////////// VBoxContainer *members_vb = memnew(VBoxContainer); members_vb->set_v_size_flags(SIZE_EXPAND_FILL); HBoxContainer *filter_hb = memnew(HBoxContainer); members_vb->add_child(filter_hb); node_filter = memnew(LineEdit); filter_hb->add_child(node_filter); node_filter->connect("text_changed", this, "_member_filter_changed"); node_filter->set_h_size_flags(SIZE_EXPAND_FILL); node_filter->set_placeholder(TTR("Search")); tools = memnew(MenuButton); filter_hb->add_child(tools); tools->set_tooltip(TTR("Options")); tools->get_popup()->connect("id_pressed", this, "_tools_menu_option"); tools->get_popup()->add_item(TTR("Expand All"), EXPAND_ALL); tools->get_popup()->add_item(TTR("Collapse All"), COLLAPSE_ALL); members = memnew(Tree); members_vb->add_child(members); members->set_drag_forwarding(this); members->set_h_size_flags(SIZE_EXPAND_FILL); members->set_v_size_flags(SIZE_EXPAND_FILL); members->set_hide_root(true); members->set_allow_reselect(true); members->set_hide_folding(false); members->set_custom_minimum_size(Size2(180 * EDSCALE, 200 * EDSCALE)); members->connect("item_selected", this, "_member_selected"); members->connect("nothing_selected", this, "_member_unselected"); members->connect("gui_input", this, "_member_gui_input"); Label *desc_label = memnew(Label); members_vb->add_child(desc_label); desc_label->set_text(TTR("Description:")); node_desc = memnew(RichTextLabel); members_vb->add_child(node_desc); node_desc->set_h_size_flags(SIZE_EXPAND_FILL); node_desc->set_v_size_flags(SIZE_FILL); node_desc->set_custom_minimum_size(Size2(0, 70 * EDSCALE)); members_dialog = memnew(ConfirmationDialog); members_dialog->set_title(TTR("Create Shader Node")); members_dialog->add_child(members_vb); members_dialog->get_ok()->set_text(TTR("Create")); members_dialog->get_ok()->connect("pressed", this, "_member_create"); members_dialog->get_ok()->set_disabled(true); members_dialog->set_resizable(true); members_dialog->set_as_minsize(); add_child(members_dialog); alert = memnew(AcceptDialog); alert->set_as_minsize(); alert->get_label()->set_autowrap(true); alert->get_label()->set_align(Label::ALIGN_CENTER); alert->get_label()->set_valign(Label::VALIGN_CENTER); alert->get_label()->set_custom_minimum_size(Size2(400, 60) * EDSCALE); add_child(alert); /////////////////////////////////////// // SHADER NODES TREE OPTIONS /////////////////////////////////////// // COLOR add_options.push_back(AddOption("ColorFunc", "Color", "Common", "VisualShaderNodeColorFunc", TTR("Color function."), -1, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("ColorOp", "Color", "Common", "VisualShaderNodeColorOp", TTR("Color operator."), -1, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Grayscale", "Color", "Functions", "VisualShaderNodeColorFunc", TTR("Grayscale function."), VisualShaderNodeColorFunc::FUNC_GRAYSCALE, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("HSV2RGB", "Color", "Functions", "VisualShaderNodeVectorFunc", TTR("Converts HSV vector to RGB equivalent."), VisualShaderNodeVectorFunc::FUNC_HSV2RGB, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("RGB2HSV", "Color", "Functions", "VisualShaderNodeVectorFunc", TTR("Converts RGB vector to HSV equivalent."), VisualShaderNodeVectorFunc::FUNC_RGB2HSV, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Sepia", "Color", "Functions", "VisualShaderNodeColorFunc", TTR("Sepia function."), VisualShaderNodeColorFunc::FUNC_SEPIA, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Burn", "Color", "Operators", "VisualShaderNodeColorOp", TTR("Burn operator."), VisualShaderNodeColorOp::OP_BURN, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Darken", "Color", "Operators", "VisualShaderNodeColorOp", TTR("Darken operator."), VisualShaderNodeColorOp::OP_DARKEN, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Difference", "Color", "Operators", "VisualShaderNodeColorOp", TTR("Difference operator."), VisualShaderNodeColorOp::OP_DIFFERENCE, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Dodge", "Color", "Operators", "VisualShaderNodeColorOp", TTR("Dodge operator."), VisualShaderNodeColorOp::OP_DODGE, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("HardLight", "Color", "Operators", "VisualShaderNodeColorOp", TTR("HardLight operator"), VisualShaderNodeColorOp::OP_HARD_LIGHT, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Lighten", "Color", "Operators", "VisualShaderNodeColorOp", TTR("Lighten operator."), VisualShaderNodeColorOp::OP_LIGHTEN, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Overlay", "Color", "Operators", "VisualShaderNodeColorOp", TTR("Overlay operator."), VisualShaderNodeColorOp::OP_OVERLAY, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Screen", "Color", "Operators", "VisualShaderNodeColorOp", TTR("Screen operator."), VisualShaderNodeColorOp::OP_SCREEN, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("SoftLight", "Color", "Operators", "VisualShaderNodeColorOp", TTR("SoftLight operator."), VisualShaderNodeColorOp::OP_SOFT_LIGHT, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("ColorConstant", "Color", "Variables", "VisualShaderNodeColorConstant", TTR("Color constant."), -1, VisualShaderNode::PORT_TYPE_COLOR)); add_options.push_back(AddOption("ColorUniform", "Color", "Variables", "VisualShaderNodeColorUniform", TTR("Color uniform."), -1, VisualShaderNode::PORT_TYPE_COLOR)); // BOOLEAN add_options.push_back(AddOption("BooleanConstant", "Boolean", "Variables", "VisualShaderNodeBooleanConstant", TTR("Boolean constant."), -1, VisualShaderNode::PORT_TYPE_BOOLEAN)); add_options.push_back(AddOption("BooleanUniform", "Boolean", "Variables", "VisualShaderNodeBooleanUniform", TTR("Boolean uniform."), -1, VisualShaderNode::PORT_TYPE_BOOLEAN)); // INPUT add_options.push_back(AddOption("Camera", "Input", "All", "VisualShaderNodeInput", TTR("'camera' input parameter for all shader modes."), "camera", VisualShaderNode::PORT_TYPE_TRANSFORM)); add_options.push_back(AddOption("InvCamera", "Input", "All", "VisualShaderNodeInput", TTR("'inv_camera' input parameter for all shader modes."), "inv_camera", VisualShaderNode::PORT_TYPE_TRANSFORM)); add_options.push_back(AddOption("InvProjection", "Input", "All", "VisualShaderNodeInput", TTR("'inv_projection' input parameter for all shader modes."), "inv_projection", VisualShaderNode::PORT_TYPE_TRANSFORM)); add_options.push_back(AddOption("Normal", "Input", "All", "VisualShaderNodeInput", TTR("'normal' input parameter for all shader modes."), "normal", VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Projection", "Input", "All", "VisualShaderNodeInput", TTR("'projection' input parameter for all shader modes."), "projection", VisualShaderNode::PORT_TYPE_TRANSFORM)); add_options.push_back(AddOption("Time", "Input", "All", "VisualShaderNodeInput", TTR("'time' input parameter for all shader modes."), "time", VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("ViewportSize", "Input", "All", "VisualShaderNodeInput", TTR("'viewport_size' input parameter for all shader modes."), "viewport_size", VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("World", "Input", "All", "VisualShaderNodeInput", TTR("'world' input parameter for all shader modes."), "world", VisualShaderNode::PORT_TYPE_TRANSFORM)); add_options.push_back(AddOption("Input", "Input", "Common", "VisualShaderNodeInput", TTR("Input parameter."))); add_options.push_back(AddOption("Alpha", "Input", "Fragment", "VisualShaderNodeInput", TTR("'alpha' input parameter for fragment shader mode."), "alpha", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_FRAGMENT)); add_options.push_back(AddOption("Binormal", "Input", "Fragment", "VisualShaderNodeInput", TTR("'binormal' input parameter for fragment shader mode."), "binormal", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT)); add_options.push_back(AddOption("Color", "Input", "Fragment", "VisualShaderNodeInput", TTR("'color' input parameter for fragment shader mode."), "color", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT)); add_options.push_back(AddOption("FragCoord", "Input", "Fragment", "VisualShaderNodeInput", TTR("'fragcoord' input parameter for fragment shader mode."), "fragcoord", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT)); add_options.push_back(AddOption("PointCoord", "Input", "Fragment", "VisualShaderNodeInput", TTR("'point_coord' input parameter for fragment shader mode."), "point_coord", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT)); add_options.push_back(AddOption("ScreenUV", "Input", "Fragment", "VisualShaderNodeInput", TTR("'screen_uv' input parameter for fragment shader mode."), "screen_uv", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT)); add_options.push_back(AddOption("Side", "Input", "Fragment", "VisualShaderNodeInput", TTR("'side' input parameter for fragment shader mode."), "side", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_FRAGMENT)); add_options.push_back(AddOption("Tangent", "Input", "Fragment", "VisualShaderNodeInput", TTR("'tangent' input parameter for fragment shader mode."), "tangent", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT)); add_options.push_back(AddOption("UV", "Input", "Fragment", "VisualShaderNodeInput", TTR("'uv' input parameter for fragment shader mode."), "uv", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT)); add_options.push_back(AddOption("UV2", "Input", "Fragment", "VisualShaderNodeInput", TTR("'uv2' input parameter for fragment shader mode."), "uv2", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT)); add_options.push_back(AddOption("Vertex", "Input", "Fragment", "VisualShaderNodeInput", TTR("'vertex' input parameter for fragment shader mode."), "vertex", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT)); add_options.push_back(AddOption("View", "Input", "Fragment", "VisualShaderNodeInput", TTR("'view' input parameter for fragment shader mode."), "view", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT)); add_options.push_back(AddOption("Albedo", "Input", "Light", "VisualShaderNodeInput", TTR("'albedo' input parameter for light shader mode."), "albedo", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_LIGHT)); add_options.push_back(AddOption("Attenuation", "Input", "Light", "VisualShaderNodeInput", TTR("'attenuation' input parameter for light shader mode."), "attenuation", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_LIGHT)); add_options.push_back(AddOption("Diffuse", "Input", "Light", "VisualShaderNodeInput", TTR("'diffuse' input parameter for light shader mode."), "diffuse", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_LIGHT)); add_options.push_back(AddOption("FragCoord", "Input", "Light", "VisualShaderNodeInput", TTR("'fragcoord' input parameter for light shader mode."), "fragcoord", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_LIGHT)); add_options.push_back(AddOption("Light", "Input", "Light", "VisualShaderNodeInput", TTR("'light' input parameter for light shader mode."), "light", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_LIGHT)); add_options.push_back(AddOption("LightColor", "Input", "Light", "VisualShaderNodeInput", TTR("'light_color' input parameter for light shader mode."), "light_color", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_LIGHT)); add_options.push_back(AddOption("Roughness", "Input", "Light", "VisualShaderNodeInput", TTR("'roughness' input parameter for light shader mode."), "roughness", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_LIGHT)); add_options.push_back(AddOption("Specular", "Input", "Light", "VisualShaderNodeInput", TTR("'specular' input parameter for light shader mode."), "specular", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_LIGHT)); add_options.push_back(AddOption("Transmission", "Input", "Light", "VisualShaderNodeInput", TTR("'transmission' input parameter for light shader mode."), "transmission", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_LIGHT)); add_options.push_back(AddOption("View", "Input", "Light", "VisualShaderNodeInput", TTR("'view' input parameter for light shader mode."), "view", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_LIGHT)); add_options.push_back(AddOption("Alpha", "Input", "Vertex", "VisualShaderNodeInput", TTR("'alpha' input parameter for vertex shader mode."), "alpha", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_VERTEX)); add_options.push_back(AddOption("Binormal", "Input", "Vertex", "VisualShaderNodeInput", TTR("'binormal' input parameter for vertex shader mode."), "binormal", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_VERTEX)); add_options.push_back(AddOption("Color", "Input", "Vertex", "VisualShaderNodeInput", TTR("'color' input parameter for vertex shader mode."), "color", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_VERTEX)); add_options.push_back(AddOption("ModelView", "Input", "Vertex", "VisualShaderNodeInput", TTR("'modelview' input parameter for vertex shader mode."), "modelview", VisualShaderNode::PORT_TYPE_TRANSFORM, VisualShader::TYPE_VERTEX)); add_options.push_back(AddOption("PointSize", "Input", "Vertex", "VisualShaderNodeInput", TTR("'point_size' input parameter for vertex shader mode."), "point_size", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_VERTEX)); add_options.push_back(AddOption("Tangent", "Input", "Vertex", "VisualShaderNodeInput", TTR("'tangent' input parameter for vertex shader mode."), "tangent", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_VERTEX)); add_options.push_back(AddOption("UV", "Input", "Vertex", "VisualShaderNodeInput", TTR("'uv' input parameter for vertex shader mode."), "uv", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_VERTEX)); add_options.push_back(AddOption("UV2", "Input", "Vertex", "VisualShaderNodeInput", TTR("'uv2' input parameter for vertex shader mode."), "uv2", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_VERTEX)); add_options.push_back(AddOption("Vertex", "Input", "Vertex", "VisualShaderNodeInput", TTR("'vertex' input parameter for vertex shader mode."), "vertex", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_VERTEX)); // SCALAR add_options.push_back(AddOption("ScalarFunc", "Scalar", "Common", "VisualShaderNodeScalarFunc", TTR("Scalar function."), -1, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("ScalarOp", "Scalar", "Common", "VisualShaderNodeScalarOp", TTR("Scalar operator."), -1, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Abs", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("Returns the absolute value of the parameter."), VisualShaderNodeScalarFunc::FUNC_ABS, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("ACos", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("Returns the arc-cosine of the parameter."), VisualShaderNodeScalarFunc::FUNC_ACOS, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("ACosH", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("(GLES3 only) Returns the inverse hyperbolic cosine of the parameter."), VisualShaderNodeScalarFunc::FUNC_ACOSH, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("ASin", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("Returns the arc-sine of the parameter."), VisualShaderNodeScalarFunc::FUNC_ASIN, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("ASinH", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("(GLES3 only) Returns the inverse hyperbolic sine of the parameter."), VisualShaderNodeScalarFunc::FUNC_ASINH, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("ATan", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("Returns the arc-tangent of the parameter."), VisualShaderNodeScalarFunc::FUNC_ATAN, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("ATan2", "Scalar", "Functions", "VisualShaderNodeScalarOp", TTR("Returns the arc-tangent of the parameters."), VisualShaderNodeScalarOp::OP_ATAN2, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("ATanH", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("(GLES3 only) Returns the inverse hyperbolic tangent of the parameter."), VisualShaderNodeScalarFunc::FUNC_ATANH, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Ceil", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("Finds the nearest integer that is greater than or equal to the parameter."), VisualShaderNodeScalarFunc::FUNC_CEIL, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Clamp", "Scalar", "Functions", "VisualShaderNodeScalarClamp", TTR("Constrains a value to lie between two further values."), -1, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Cos", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("Returns the cosine of the parameter."), VisualShaderNodeScalarFunc::FUNC_COS, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("CosH", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("(GLES3 only) Returns the hyperbolic cosine of the parameter."), VisualShaderNodeScalarFunc::FUNC_COSH, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Degrees", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("Converts a quantity in radians to degrees."), VisualShaderNodeScalarFunc::FUNC_DEGREES, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Exp", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("Base-e Exponential."), VisualShaderNodeScalarFunc::FUNC_EXP, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Exp2", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("Base-2 Exponential."), VisualShaderNodeScalarFunc::FUNC_EXP2, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Floor", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("Finds the nearest integer less than or equal to the parameter."), VisualShaderNodeScalarFunc::FUNC_FLOOR, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Fract", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("Computes the fractional part of the argument."), VisualShaderNodeScalarFunc::FUNC_FRAC, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("InverseSqrt", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("Returns the inverse of the square root of the parameter."), VisualShaderNodeScalarFunc::FUNC_INVERSE_SQRT, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Log", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("Natural logarithm."), VisualShaderNodeScalarFunc::FUNC_LOG, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Log2", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("Base-2 logarithm."), VisualShaderNodeScalarFunc::FUNC_LOG2, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Max", "Scalar", "Functions", "VisualShaderNodeScalarOp", TTR("Returns the greater of two values."), VisualShaderNodeScalarOp::OP_MAX, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Min", "Scalar", "Functions", "VisualShaderNodeScalarOp", TTR("Returns the lesser of two values."), VisualShaderNodeScalarOp::OP_MIN, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Mix", "Scalar", "Functions", "VisualShaderNodeScalarInterp", TTR("Linear interpolation between two scalars."), -1, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Negate", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("Returns the opposite value of the parameter."), VisualShaderNodeScalarFunc::FUNC_NEGATE, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Pow", "Scalar", "Functions", "VisualShaderNodeScalarOp", TTR("Returns the value of the first parameter raised to the power of the second."), VisualShaderNodeScalarOp::OP_POW, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Radians", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("Converts a quantity in degrees to radians."), VisualShaderNodeScalarFunc::FUNC_RADIANS, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Reciprocal", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("1.0 / scalar"), VisualShaderNodeScalarFunc::FUNC_RECIPROCAL, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Round", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("(GLES3 only) Finds the nearest integer to the parameter."), VisualShaderNodeScalarFunc::FUNC_ROUND, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("RoundEven", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("(GLES3 only) Finds the nearest even integer to the parameter."), VisualShaderNodeScalarFunc::FUNC_ROUNDEVEN, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Saturate", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("Clamps the value between 0.0 and 1.0."), VisualShaderNodeScalarFunc::FUNC_SATURATE, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Sign", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("Extracts the sign of the parameter."), VisualShaderNodeScalarFunc::FUNC_SIGN, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Sin", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("Returns the sine of the parameter."), VisualShaderNodeScalarFunc::FUNC_SIN, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("SinH", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("(GLES3 only) Returns the hyperbolic sine of the parameter."), VisualShaderNodeScalarFunc::FUNC_SINH, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Sqrt", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("Returns the square root of the parameter."), VisualShaderNodeScalarFunc::FUNC_SQRT, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("SmoothStep", "Scalar", "Functions", "VisualShaderNodeScalarSmoothStep", TTR("SmoothStep function( scalar(edge0), scalar(edge1), scalar(x) ).\n\nReturns 0.0 if 'x' is smaller then 'edge0' and 1.0 if x is larger than 'edge1'. Otherwise the return value is interpolated between 0.0 and 1.0 using Hermite polynomials."), -1, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Step", "Scalar", "Functions", "VisualShaderNodeScalarOp", TTR("Step function( scalar(edge), scalar(x) ).\n\nReturns 0.0 if 'x' is smaller then 'edge' and otherwise 1.0."), VisualShaderNodeScalarOp::OP_STEP, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Tan", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("Returns the tangent of the parameter."), VisualShaderNodeScalarFunc::FUNC_TAN, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("TanH", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("(GLES3 only) Returns the hyperbolic tangent of the parameter."), VisualShaderNodeScalarFunc::FUNC_TANH, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Trunc", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("(GLES3 only) Finds the truncated value of the parameter."), VisualShaderNodeScalarFunc::FUNC_TRUNC, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Add", "Scalar", "Operators", "VisualShaderNodeScalarOp", TTR("Adds scalar to scalar."), VisualShaderNodeScalarOp::OP_ADD, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Divide", "Scalar", "Operators", "VisualShaderNodeScalarOp", TTR("Divides scalar by scalar."), VisualShaderNodeScalarOp::OP_DIV, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Multiply", "Scalar", "Operators", "VisualShaderNodeScalarOp", TTR("Multiplies scalar by scalar."), VisualShaderNodeScalarOp::OP_MUL, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Remainder", "Scalar", "Operators", "VisualShaderNodeScalarOp", TTR("Returns the remainder of the two scalars."), VisualShaderNodeScalarOp::OP_MOD, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Subtract", "Scalar", "Operators", "VisualShaderNodeScalarOp", TTR("Subtracts scalar from scalar."), VisualShaderNodeScalarOp::OP_SUB, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("ScalarConstant", "Scalar", "Variables", "VisualShaderNodeScalarConstant", TTR("Scalar constant."), -1, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("ScalarUniform", "Scalar", "Variables", "VisualShaderNodeScalarUniform", TTR("Scalar uniform."), -1, VisualShaderNode::PORT_TYPE_SCALAR)); // TEXTURES add_options.push_back(AddOption("CubeMap", "Textures", "Functions", "VisualShaderNodeCubeMap", TTR("Perform the cubic texture lookup."), -1, VisualShaderNode::PORT_TYPE_COLOR)); add_options.push_back(AddOption("Texture", "Textures", "Functions", "VisualShaderNodeTexture", TTR("Perform the texture lookup."), -1, VisualShaderNode::PORT_TYPE_COLOR)); add_options.push_back(AddOption("CubeMapUniform", "Textures", "Variables", "VisualShaderNodeCubeMapUniform", TTR("Cubic texture uniform."), -1, VisualShaderNode::PORT_TYPE_COLOR)); add_options.push_back(AddOption("TextureUniform", "Textures", "Variables", "VisualShaderNodeTextureUniform", TTR("2D texture uniform."), -1, VisualShaderNode::PORT_TYPE_COLOR)); // TRANSFORM add_options.push_back(AddOption("TransformFunc", "Transform", "Common", "VisualShaderNodeTransformFunc", TTR("Transform function."), -1, VisualShaderNode::PORT_TYPE_TRANSFORM)); add_options.push_back(AddOption("OuterProduct", "Transform", "Composition", "VisualShaderNodeOuterProduct", TTR("(GLES3 only) Calculate the outer product of a pair of vectors.\n\nOuterProduct treats the first parameter 'c' as a column vector (matrix with one column) and the second parameter 'r' as a row vector (matrix with one row) and does a linear algebraic matrix multiply 'c * r', yielding a matrix whose number of rows is the number of components in 'c' and whose number of columns is the number of components in 'r'."), -1, VisualShaderNode::PORT_TYPE_TRANSFORM)); add_options.push_back(AddOption("TransformCompose", "Transform", "Composition", "VisualShaderNodeTransformCompose", TTR("Composes transform from four vectors."), -1, VisualShaderNode::PORT_TYPE_TRANSFORM)); add_options.push_back(AddOption("TransformDecompose", "Transform", "Composition", "VisualShaderNodeTransformDecompose", TTR("Decomposes transform to four vectors."))); add_options.push_back(AddOption("Determinant", "Transform", "Functions", "VisualShaderNodeDeterminant", TTR("(GLES3 only) Calculates the determinant of a transform."), -1, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Inverse", "Transform", "Functions", "VisualShaderNodeTransformFunc", TTR("(GLES3 only) Calculates the inverse of a transform."), VisualShaderNodeTransformFunc::FUNC_INVERSE, VisualShaderNode::PORT_TYPE_TRANSFORM)); add_options.push_back(AddOption("Transpose", "Transform", "Functions", "VisualShaderNodeTransformFunc", TTR("(GLES3 only) Calculates the transpose of a transform."), VisualShaderNodeTransformFunc::FUNC_TRANSPOSE, VisualShaderNode::PORT_TYPE_TRANSFORM)); add_options.push_back(AddOption("TransformMult", "Transform", "Operators", "VisualShaderNodeTransformMult", TTR("Multiplies transform by transform."), -1, VisualShaderNode::PORT_TYPE_TRANSFORM)); add_options.push_back(AddOption("TransformVectorMult", "Transform", "Operators", "VisualShaderNodeTransformVecMult", TTR("Multiplies vector by transform."), -1, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("TransformConstant", "Transform", "Variables", "VisualShaderNodeTransformConstant", TTR("Transform constant."), -1, VisualShaderNode::PORT_TYPE_TRANSFORM)); add_options.push_back(AddOption("TransformUniform", "Transform", "Variables", "VisualShaderNodeTransformUniform", TTR("Transform uniform."), -1, VisualShaderNode::PORT_TYPE_TRANSFORM)); // VECTOR add_options.push_back(AddOption("VectorFunc", "Vector", "Common", "VisualShaderNodeVectorFunc", TTR("Vector function."), -1, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("VectorOp", "Vector", "Common", "VisualShaderNodeVectorOp", TTR("Vector operator."), -1, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("VectorCompose", "Vector", "Composition", "VisualShaderNodeVectorCompose", TTR("Composes vector from three scalars."), -1, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("VectorDecompose", "Vector", "Composition", "VisualShaderNodeVectorDecompose", TTR("Decomposes vector to three scalars."))); add_options.push_back(AddOption("Abs", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Returns the absolute value of the parameter."), VisualShaderNodeVectorFunc::FUNC_ABS, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("ACos", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Returns the arc-cosine of the parameter."), VisualShaderNodeVectorFunc::FUNC_ACOS, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("ACosH", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("(GLES3 only) Returns the inverse hyperbolic cosine of the parameter."), VisualShaderNodeVectorFunc::FUNC_ACOSH, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("ASin", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Returns the arc-sine of the parameter."), VisualShaderNodeVectorFunc::FUNC_ASIN, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("ASinH", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("(GLES3 only) Returns the inverse hyperbolic sine of the parameter."), VisualShaderNodeVectorFunc::FUNC_ASINH, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("ATan", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Returns the arc-tangent of the parameter."), VisualShaderNodeVectorFunc::FUNC_ATAN, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("ATan2", "Vector", "Functions", "VisualShaderNodeVectorOp", TTR("Returns the arc-tangent of the parameters."), VisualShaderNodeVectorOp::OP_ATAN2, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("ATanH", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("(GLES3 only) Returns the inverse hyperbolic tangent of the parameter."), VisualShaderNodeVectorFunc::FUNC_ATANH, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Ceil", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Finds the nearest integer that is greater than or equal to the parameter."), VisualShaderNodeVectorFunc::FUNC_CEIL, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Clamp", "Vector", "Functions", "VisualShaderNodeVectorClamp", TTR("Constrains a value to lie between two further values."), -1, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Cos", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Returns the cosine of the parameter."), VisualShaderNodeVectorFunc::FUNC_COS, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("CosH", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("(GLES3 only) Returns the hyperbolic cosine of the parameter."), VisualShaderNodeVectorFunc::FUNC_COSH, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Cross", "Vector", "Functions", "VisualShaderNodeVectorOp", TTR("Calculates the cross product of two vectors."), VisualShaderNodeVectorOp::OP_CROSS, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Degrees", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Converts a quantity in radians to degrees."), VisualShaderNodeVectorFunc::FUNC_DEGREES, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Distance", "Vector", "Functions", "VisualShaderNodeVectorDistance", TTR("Returns the distance between two points."), -1, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Dot", "Vector", "Functions", "VisualShaderNodeDotProduct", TTR("Calculates the dot product of two vectors."), -1, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Exp", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Base-e Exponential."), VisualShaderNodeVectorFunc::FUNC_EXP, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Exp2", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Base-2 Exponential."), VisualShaderNodeVectorFunc::FUNC_EXP2, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("FaceForward", "Vector", "Functions", "VisualShaderNodeFaceForward", TTR("Returns a vector that points in the same direction as a reference vector. The function has three vector parameters : N, the vector to orient, I, the incident vector, and Nref, the reference vector. If the dot product of I and Nref is smaller than zero the return value is N. Otherwise -N is returned."), -1, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Floor", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Finds the nearest integer less than or equal to the parameter."), VisualShaderNodeVectorFunc::FUNC_FLOOR, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Fract", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Computes the fractional part of the argument."), VisualShaderNodeVectorFunc::FUNC_FRAC, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("InverseSqrt", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Returns the inverse of the square root of the parameter."), VisualShaderNodeVectorFunc::FUNC_INVERSE_SQRT, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Length", "Vector", "Functions", "VisualShaderNodeVectorLen", TTR("Calculates the length of a vector."), -1, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Log", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Natural logarithm."), VisualShaderNodeVectorFunc::FUNC_LOG, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Log2", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Base-2 logarithm."), VisualShaderNodeVectorFunc::FUNC_LOG2, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Max", "Vector", "Functions", "VisualShaderNodeVectorOp", TTR("Returns the greater of two values."), VisualShaderNodeVectorOp::OP_MAX, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Min", "Vector", "Functions", "VisualShaderNodeVectorOp", TTR("Returns the lesser of two values."), VisualShaderNodeVectorOp::OP_MIN, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Mix", "Vector", "Functions", "VisualShaderNodeVectorInterp", TTR("Linear interpolation between two vectors."), -1, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Negate", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Returns the opposite value of the parameter."), VisualShaderNodeVectorFunc::FUNC_NEGATE, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Normalize", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Calculates the normalize product of vector."), VisualShaderNodeVectorFunc::FUNC_NORMALIZE, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Pow", "Vector", "Functions", "VisualShaderNodeVectorOp", TTR("Returns the value of the first parameter raised to the power of the second."), VisualShaderNodeVectorOp::OP_POW, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Radians", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Converts a quantity in degrees to radians."), VisualShaderNodeVectorFunc::FUNC_RADIANS, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Reciprocal", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("1.0 / vector"), VisualShaderNodeVectorFunc::FUNC_RECIPROCAL, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Reflect", "Vector", "Functions", "VisualShaderNodeVectorOp", TTR("Returns a vector that points in the direction of reflection ( a : incident vector, b : normal vector )."), VisualShaderNodeVectorOp::OP_REFLECT, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Refract", "Vector", "Functions", "VisualShaderNodeVectorRefract", TTR("Returns a vector that points in the direction of refraction."), -1, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Round", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("(GLES3 only) Finds the nearest integer to the parameter."), VisualShaderNodeVectorFunc::FUNC_ROUND, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("RoundEven", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("(GLES3 only) Finds the nearest even integer to the parameter."), VisualShaderNodeVectorFunc::FUNC_ROUNDEVEN, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Saturate", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Clamps the value between 0.0 and 1.0."), VisualShaderNodeVectorFunc::FUNC_SATURATE, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Sign", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Extracts the sign of the parameter."), VisualShaderNodeVectorFunc::FUNC_SIGN, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Sin", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Returns the sine of the parameter."), VisualShaderNodeVectorFunc::FUNC_SIN, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("SinH", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("(GLES3 only) Returns the hyperbolic sine of the parameter."), VisualShaderNodeVectorFunc::FUNC_SINH, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Sqrt", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Returns the square root of the parameter."), VisualShaderNodeVectorFunc::FUNC_SQRT, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("SmoothStep", "Vector", "Functions", "VisualShaderNodeVectorSmoothStep", TTR("SmoothStep function( vector(edge0), vector(edge1), vector(x) ).\n\nReturns 0.0 if 'x' is smaller then 'edge0' and 1.0 if 'x' is larger than 'edge1'. Otherwise the return value is interpolated between 0.0 and 1.0 using Hermite polynomials."), -1, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("SmoothStepS", "Vector", "Functions", "VisualShaderNodeVectorScalarSmoothStep", TTR("SmoothStep function( scalar(edge0), scalar(edge1), vector(x) ).\n\nReturns 0.0 if 'x' is smaller then 'edge0' and 1.0 if 'x' is larger than 'edge1'. Otherwise the return value is interpolated between 0.0 and 1.0 using Hermite polynomials."), -1, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Step", "Vector", "Functions", "VisualShaderNodeVectorOp", TTR("Step function( vector(edge), vector(x) ).\n\nReturns 0.0 if 'x' is smaller then 'edge' and otherwise 1.0."), VisualShaderNodeVectorOp::OP_STEP, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("StepS", "Vector", "Functions", "VisualShaderNodeVectorScalarStep", TTR("Step function( scalar(edge), vector(x) ).\n\nReturns 0.0 if 'x' is smaller then 'edge' and otherwise 1.0."), -1, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Tan", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Returns the tangent of the parameter."), VisualShaderNodeVectorFunc::FUNC_TAN, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("TanH", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("(GLES3 only) Returns the hyperbolic tangent of the parameter."), VisualShaderNodeVectorFunc::FUNC_TANH, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Trunc", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("(GLES3 only) Finds the truncated value of the parameter."), VisualShaderNodeVectorFunc::FUNC_TRUNC, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Add", "Vector", "Operators", "VisualShaderNodeVectorOp", TTR("Adds vector to vector."), VisualShaderNodeVectorOp::OP_ADD, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Divide", "Vector", "Operators", "VisualShaderNodeVectorOp", TTR("Divides vector by vector."), VisualShaderNodeVectorOp::OP_DIV, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Multiply", "Vector", "Operators", "VisualShaderNodeVectorOp", TTR("Multiplies vector by vector."), VisualShaderNodeVectorOp::OP_MUL, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Remainder", "Vector", "Operators", "VisualShaderNodeVectorOp", TTR("Returns the remainder of the two vectors."), VisualShaderNodeVectorOp::OP_MOD, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Subtract", "Vector", "Operators", "VisualShaderNodeVectorOp", TTR("Subtracts vector from vector."), VisualShaderNodeVectorOp::OP_SUB, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("VectorConstant", "Vector", "Variables", "VisualShaderNodeVec3Constant", TTR("Vector constant."), -1, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("VectorUniform", "Vector", "Variables", "VisualShaderNodeVec3Uniform", TTR("Vector uniform."), -1, VisualShaderNode::PORT_TYPE_VECTOR)); // SPECIAL add_options.push_back(AddOption("ScalarDerivativeFunc", "Special", "Common", "VisualShaderNodeScalarDerivativeFunc", TTR("(GLES3 only) (Fragment/Light mode only) Scalar derivative function."), -1, VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_FRAGMENT | VisualShader::TYPE_LIGHT)); add_options.push_back(AddOption("VectorDerivativeFunc", "Special", "Common", "VisualShaderNodeVectorDerivativeFunc", TTR("(GLES3 only) (Fragment/Light mode only) Vector derivative function."), -1, VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT | VisualShader::TYPE_LIGHT)); add_options.push_back(AddOption("DdX", "Special", "Derivative", "VisualShaderNodeVectorDerivativeFunc", TTR("(GLES3 only) (Fragment/Light mode only) (Vector) Derivative in 'x' using local differencing."), VisualShaderNodeVectorDerivativeFunc::FUNC_X, VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT | VisualShader::TYPE_LIGHT)); add_options.push_back(AddOption("DdXS", "Special", "Derivative", "VisualShaderNodeScalarDerivativeFunc", TTR("(GLES3 only) (Fragment/Light mode only) (Scalar) Derivative in 'x' using local differencing."), VisualShaderNodeScalarDerivativeFunc::FUNC_X, VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_FRAGMENT | VisualShader::TYPE_LIGHT)); add_options.push_back(AddOption("DdY", "Special", "Derivative", "VisualShaderNodeVectorDerivativeFunc", TTR("(GLES3 only) (Fragment/Light mode only) (Vector) Derivative in 'y' using local differencing."), VisualShaderNodeVectorDerivativeFunc::FUNC_Y, VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT | VisualShader::TYPE_LIGHT)); add_options.push_back(AddOption("DdYS", "Special", "Derivative", "VisualShaderNodeScalarDerivativeFunc", TTR("(GLES3 only) (Fragment/Light mode only) (Scalar) Derivative in 'y' using local differencing."), VisualShaderNodeScalarDerivativeFunc::FUNC_Y, VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_FRAGMENT | VisualShader::TYPE_LIGHT)); add_options.push_back(AddOption("Sum", "Special", "Derivative", "VisualShaderNodeVectorDerivativeFunc", TTR("(GLES3 only) (Fragment/Light mode only) (Vector) Sum of absolute derivative in 'x' and 'y'."), VisualShaderNodeVectorDerivativeFunc::FUNC_SUM, VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT | VisualShader::TYPE_LIGHT)); add_options.push_back(AddOption("SumS", "Special", "Derivative", "VisualShaderNodeScalarDerivativeFunc", TTR("(GLES3 only) (Fragment/Light mode only) (Scalar) Sum of absolute derivative in 'x' and 'y'."), VisualShaderNodeScalarDerivativeFunc::FUNC_SUM, VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_FRAGMENT | VisualShader::TYPE_LIGHT)); ///////////////////////////////////////////////////////////////////// _update_options_menu(); error_panel = memnew(PanelContainer); add_child(error_panel); error_label = memnew(Label); error_panel->add_child(error_label); error_label->set_text("eh"); error_panel->hide(); undo_redo = EditorNode::get_singleton()->get_undo_redo(); Ref<VisualShaderNodePluginDefault> default_plugin; default_plugin.instance(); add_plugin(default_plugin); property_editor = memnew(CustomPropertyEditor); add_child(property_editor); property_editor->connect("variant_changed", this, "_port_edited"); } void VisualShaderEditorPlugin::edit(Object *p_object) { visual_shader_editor->edit(Object::cast_to<VisualShader>(p_object)); } bool VisualShaderEditorPlugin::handles(Object *p_object) const { return p_object->is_class("VisualShader"); } void VisualShaderEditorPlugin::make_visible(bool p_visible) { if (p_visible) { //editor->hide_animation_player_editors(); //editor->animation_panel_make_visible(true); button->show(); editor->make_bottom_panel_item_visible(visual_shader_editor); visual_shader_editor->set_process_input(true); //visual_shader_editor->set_process(true); } else { if (visual_shader_editor->is_visible_in_tree()) editor->hide_bottom_panel(); button->hide(); visual_shader_editor->set_process_input(false); //visual_shader_editor->set_process(false); } } VisualShaderEditorPlugin::VisualShaderEditorPlugin(EditorNode *p_node) { editor = p_node; visual_shader_editor = memnew(VisualShaderEditor); visual_shader_editor->set_custom_minimum_size(Size2(0, 300)); button = editor->add_bottom_panel_item(TTR("VisualShader"), visual_shader_editor); button->hide(); } VisualShaderEditorPlugin::~VisualShaderEditorPlugin() { } //////////////// class VisualShaderNodePluginInputEditor : public OptionButton { GDCLASS(VisualShaderNodePluginInputEditor, OptionButton) Ref<VisualShaderNodeInput> input; protected: static void _bind_methods() { ClassDB::bind_method("_item_selected", &VisualShaderNodePluginInputEditor::_item_selected); } public: void _notification(int p_what) { if (p_what == NOTIFICATION_READY) { connect("item_selected", this, "_item_selected"); } } void _item_selected(int p_item) { VisualShaderEditor::get_singleton()->call_deferred("_input_select_item", input, get_item_text(p_item)); } void setup(const Ref<VisualShaderNodeInput> &p_input) { input = p_input; Ref<Texture> type_icon[4] = { EditorNode::get_singleton()->get_gui_base()->get_icon("float", "EditorIcons"), EditorNode::get_singleton()->get_gui_base()->get_icon("Vector3", "EditorIcons"), EditorNode::get_singleton()->get_gui_base()->get_icon("bool", "EditorIcons"), EditorNode::get_singleton()->get_gui_base()->get_icon("Transform", "EditorIcons"), }; add_item("[None]"); int to_select = -1; for (int i = 0; i < input->get_input_index_count(); i++) { if (input->get_input_name() == input->get_input_index_name(i)) { to_select = i + 1; } add_icon_item(type_icon[input->get_input_index_type(i)], input->get_input_index_name(i)); } if (to_select >= 0) { select(to_select); } } }; class VisualShaderNodePluginDefaultEditor : public VBoxContainer { GDCLASS(VisualShaderNodePluginDefaultEditor, VBoxContainer) public: void _property_changed(const String &prop, const Variant &p_value, const String &p_field, bool p_changing = false) { if (p_changing) return; UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo(); updating = true; undo_redo->create_action(TTR("Edit Visual Property") + ": " + prop, UndoRedo::MERGE_ENDS); undo_redo->add_do_property(node.ptr(), prop, p_value); undo_redo->add_undo_property(node.ptr(), prop, node->get(prop)); undo_redo->commit_action(); updating = false; } void _node_changed() { if (updating) return; for (int i = 0; i < properties.size(); i++) { properties[i]->update_property(); } } void _refresh_request() { VisualShaderEditor::get_singleton()->call_deferred("_update_graph"); } bool updating; Ref<VisualShaderNode> node; Vector<EditorProperty *> properties; void setup(Vector<EditorProperty *> p_properties, const Vector<StringName> &p_names, Ref<VisualShaderNode> p_node) { updating = false; node = p_node; properties = p_properties; for (int i = 0; i < p_properties.size(); i++) { add_child(p_properties[i]); properties[i]->connect("property_changed", this, "_property_changed"); properties[i]->set_object_and_property(node.ptr(), p_names[i]); properties[i]->update_property(); properties[i]->set_name_split_ratio(0); } node->connect("changed", this, "_node_changed"); node->connect("editor_refresh_request", this, "_refresh_request", varray(), CONNECT_DEFERRED); } static void _bind_methods() { ClassDB::bind_method("_property_changed", &VisualShaderNodePluginDefaultEditor::_property_changed, DEFVAL(String()), DEFVAL(false)); ClassDB::bind_method("_node_changed", &VisualShaderNodePluginDefaultEditor::_node_changed); ClassDB::bind_method("_refresh_request", &VisualShaderNodePluginDefaultEditor::_refresh_request); } }; Control *VisualShaderNodePluginDefault::create_editor(const Ref<VisualShaderNode> &p_node) { if (p_node->is_class("VisualShaderNodeInput")) { //create input VisualShaderNodePluginInputEditor *input_editor = memnew(VisualShaderNodePluginInputEditor); input_editor->setup(p_node); return input_editor; } Vector<StringName> properties = p_node->get_editable_properties(); if (properties.size() == 0) { return NULL; } List<PropertyInfo> props; p_node->get_property_list(&props); Vector<PropertyInfo> pinfo; for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { for (int i = 0; i < properties.size(); i++) { if (E->get().name == String(properties[i])) { pinfo.push_back(E->get()); } } } if (pinfo.size() == 0) return NULL; properties.clear(); Ref<VisualShaderNode> node = p_node; Vector<EditorProperty *> editors; for (int i = 0; i < pinfo.size(); i++) { EditorProperty *prop = EditorInspector::instantiate_property_editor(node.ptr(), pinfo[i].type, pinfo[i].name, pinfo[i].hint, pinfo[i].hint_string, pinfo[i].usage); if (!prop) return NULL; if (Object::cast_to<EditorPropertyResource>(prop)) { Object::cast_to<EditorPropertyResource>(prop)->set_use_sub_inspector(false); prop->set_custom_minimum_size(Size2(100 * EDSCALE, 0)); } else if (Object::cast_to<EditorPropertyTransform>(prop)) { prop->set_custom_minimum_size(Size2(250 * EDSCALE, 0)); } else if (Object::cast_to<EditorPropertyFloat>(prop) || Object::cast_to<EditorPropertyVector3>(prop)) { prop->set_custom_minimum_size(Size2(100 * EDSCALE, 0)); } else if (Object::cast_to<EditorPropertyEnum>(prop)) { prop->set_custom_minimum_size(Size2(100 * EDSCALE, 0)); Object::cast_to<EditorPropertyEnum>(prop)->set_option_button_clip(false); } editors.push_back(prop); properties.push_back(pinfo[i].name); } VisualShaderNodePluginDefaultEditor *editor = memnew(VisualShaderNodePluginDefaultEditor); editor->setup(editors, properties, p_node); return editor; } void EditorPropertyShaderMode::_option_selected(int p_which) { //will not use this, instead will do all the logic setting manually //emit_signal("property_changed", get_edited_property(), p_which); Ref<VisualShader> visual_shader(Object::cast_to<VisualShader>(get_edited_object())); if (visual_shader->get_mode() == p_which) return; UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo(); undo_redo->create_action(TTR("Visual Shader Mode Changed")); //do is easy undo_redo->add_do_method(visual_shader.ptr(), "set_mode", p_which); undo_redo->add_undo_method(visual_shader.ptr(), "set_mode", visual_shader->get_mode()); //now undo is hell //1. restore connections to output for (int i = 0; i < VisualShader::TYPE_MAX; i++) { VisualShader::Type type = VisualShader::Type(i); List<VisualShader::Connection> conns; visual_shader->get_node_connections(type, &conns); for (List<VisualShader::Connection>::Element *E = conns.front(); E; E = E->next()) { if (E->get().to_node == VisualShader::NODE_ID_OUTPUT) { undo_redo->add_undo_method(visual_shader.ptr(), "connect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); } } } //2. restore input indices for (int i = 0; i < VisualShader::TYPE_MAX; i++) { VisualShader::Type type = VisualShader::Type(i); Vector<int> nodes = visual_shader->get_node_list(type); for (int j = 0; j < nodes.size(); j++) { Ref<VisualShaderNodeInput> input = visual_shader->get_node(type, nodes[j]); if (!input.is_valid()) { continue; } undo_redo->add_undo_method(input.ptr(), "set_input_name", input->get_input_name()); } } //3. restore enums and flags List<PropertyInfo> props; visual_shader->get_property_list(&props); for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { if (E->get().name.begins_with("flags/") || E->get().name.begins_with("modes/")) { undo_redo->add_undo_property(visual_shader.ptr(), E->get().name, visual_shader->get(E->get().name)); } } //update graph undo_redo->add_do_method(VisualShaderEditor::get_singleton(), "_update_graph"); undo_redo->add_undo_method(VisualShaderEditor::get_singleton(), "_update_graph"); undo_redo->commit_action(); } void EditorPropertyShaderMode::update_property() { int which = get_edited_object()->get(get_edited_property()); options->select(which); } void EditorPropertyShaderMode::setup(const Vector<String> &p_options) { for (int i = 0; i < p_options.size(); i++) { options->add_item(p_options[i], i); } } void EditorPropertyShaderMode::set_option_button_clip(bool p_enable) { options->set_clip_text(p_enable); } void EditorPropertyShaderMode::_bind_methods() { ClassDB::bind_method(D_METHOD("_option_selected"), &EditorPropertyShaderMode::_option_selected); } EditorPropertyShaderMode::EditorPropertyShaderMode() { options = memnew(OptionButton); options->set_clip_text(true); add_child(options); add_focusable(options); options->connect("item_selected", this, "_option_selected"); } bool EditorInspectorShaderModePlugin::can_handle(Object *p_object) { return true; //can handle everything } void EditorInspectorShaderModePlugin::parse_begin(Object *p_object) { //do none } bool EditorInspectorShaderModePlugin::parse_property(Object *p_object, Variant::Type p_type, const String &p_path, PropertyHint p_hint, const String &p_hint_text, int p_usage) { if (p_path == "mode" && p_object->is_class("VisualShader") && p_type == Variant::INT) { EditorPropertyShaderMode *editor = memnew(EditorPropertyShaderMode); Vector<String> options = p_hint_text.split(","); editor->setup(options); add_property_editor(p_path, editor); return true; } return false; //can be overridden, although it will most likely be last anyway } void EditorInspectorShaderModePlugin::parse_end() { //do none } ////////////////////////////////// void VisualShaderNodePortPreview::_shader_changed() { if (shader.is_null()) { return; } Vector<VisualShader::DefaultTextureParam> default_textures; String shader_code = shader->generate_preview_shader(type, node, port, default_textures); Ref<Shader> preview_shader; preview_shader.instance(); preview_shader->set_code(shader_code); for (int i = 0; i < default_textures.size(); i++) { preview_shader->set_default_texture_param(default_textures[i].name, default_textures[i].param); } Ref<ShaderMaterial> material; material.instance(); material->set_shader(preview_shader); //find if a material is also being edited and copy parameters to this one for (int i = EditorNode::get_singleton()->get_editor_history()->get_path_size() - 1; i >= 0; i--) { Object *object = ObjectDB::get_instance(EditorNode::get_singleton()->get_editor_history()->get_path_object(i)); if (!object) continue; ShaderMaterial *src_mat = Object::cast_to<ShaderMaterial>(object); if (src_mat && src_mat->get_shader().is_valid()) { List<PropertyInfo> params; src_mat->get_shader()->get_param_list(&params); for (List<PropertyInfo>::Element *E = params.front(); E; E = E->next()) { material->set(E->get().name, src_mat->get(E->get().name)); } } } set_material(material); } void VisualShaderNodePortPreview::setup(const Ref<VisualShader> &p_shader, VisualShader::Type p_type, int p_node, int p_port) { shader = p_shader; shader->connect("changed", this, "_shader_changed"); type = p_type; port = p_port; node = p_node; update(); _shader_changed(); } Size2 VisualShaderNodePortPreview::get_minimum_size() const { return Size2(100, 100) * EDSCALE; } void VisualShaderNodePortPreview::_notification(int p_what) { if (p_what == NOTIFICATION_DRAW) { Vector<Vector2> points; Vector<Vector2> uvs; Vector<Color> colors; points.push_back(Vector2()); uvs.push_back(Vector2(0, 0)); colors.push_back(Color(1, 1, 1, 1)); points.push_back(Vector2(get_size().width, 0)); uvs.push_back(Vector2(1, 0)); colors.push_back(Color(1, 1, 1, 1)); points.push_back(get_size()); uvs.push_back(Vector2(1, 1)); colors.push_back(Color(1, 1, 1, 1)); points.push_back(Vector2(0, get_size().height)); uvs.push_back(Vector2(0, 1)); colors.push_back(Color(1, 1, 1, 1)); draw_primitive(points, colors, uvs); } } void VisualShaderNodePortPreview::_bind_methods() { ClassDB::bind_method("_shader_changed", &VisualShaderNodePortPreview::_shader_changed); } VisualShaderNodePortPreview::VisualShaderNodePortPreview() { }
// Copyright 2015-2021 Carnegie Mellon University. See LICENSE file for terms. #include <boost/graph/graph_traits.hpp> #include <boost/graph/adjacency_list.hpp> #include <boost/property_map/property_map.hpp> #include <boost/graph/depth_first_search.hpp> #include <boost/graph/visitors.hpp> #include <boost/graph/named_function_params.hpp> #include <boost/range/adaptors.hpp> #include <boost/algorithm/string.hpp> #include <boost/filesystem.hpp> #include "rose.hpp" #include <AstTraversal.h> #include "misc.hpp" #include "descriptors.hpp" #include "pdg.hpp" #include "apidb.hpp" #include "partitioner.hpp" #include "vftable.hpp" #include "imports.hpp" #include "masm.hpp" #include "threads.hpp" #include <mutex> namespace bf = boost::filesystem; namespace pharos { size_t global_arch_bytes = 4; void set_global_arch_bytes(size_t arch_bytes) { static bool initialized = false; static std_mutex mutex; write_guard<decltype(mutex)> lock(mutex); if (initialized) { if (arch_bytes != global_arch_bytes) { GFATAL << "Cannot analyze a binary with a pointer-size of " << arch_bytes << " when already analyzing binaries with a pointer size of " << global_arch_bytes << ".\n" << "This is a limitation with the current code that will may" << " go away in a future version." << LEND; throw std::runtime_error("Architecture size mismatch"); } } else { global_arch_bytes = arch_bytes; initialized = true; } if (arch_bytes != 4 and arch_bytes != 8) { GFATAL << "Architecture has unrecognized word size of " << arch_bytes << " bytes." << LEND; // We should probably throw or exit, here since it's very unlikely that continuing will end // well. On the other hand, nothing terrible has happened yet, so we can continue. } } ImportDescriptor *DescriptorSet::add_import( rose_addr_t addr, std::string dll, std::string name, size_t ord) { ImportDescriptor * nid = &map_emplace_or_replace( import_descriptors, addr, *this, addr, dll, name, ord); // Get the expresison for the variable that was filled in by the loader. TreeNodePtr tn = nid->get_loader_variable()->get_expression(); assert(tn != NULL); // The expression should always be a LeafNode, or our code is inconsistent. LeafNodePtr ln = tn->isLeafNode(); assert(ln != NULL); // Key the import variable map by just the unique number of the variable. uint64_t vnum = ln->nameId(); // The import variables map is just a pointer to the object in the other map. import_variables[vnum] = nid; return nid; } template <typename... Args> FunctionDescriptor *DescriptorSet::add_function_descriptor(rose_addr_t addr, Args &&... args) { FunctionDescriptor & fd = map_emplace_or_replace( function_descriptors, addr, *this, std::forward<Args>(args)...); if (apidb) { // If the address of this function has an API DB entry, incorporate it here. auto apidef = apidb->get_api_definition(addr); if (!apidef.empty()) { fd.set_api(*apidef.front()); } } return &fd; } namespace { // The following include has the following definitions: // // unsigned char tags_yaml[]; // YAML tag definitions // unsigned int tags_yaml_len; // length of tags_yaml #include "tags.yaml.ii" } std::shared_ptr<TagManager> DescriptorSet::create_tag_manager(ProgOptVarMap const & vm) { // Currently we don't have a reason to have multiple tag managers, so we just maintain a // global one here. static std::shared_ptr<TagManager> global_manager; if (!global_manager) { // Create the global tag manager, initialize its built-in defaults, and load any user // modifications on top of that. global_manager = std::make_shared<TagManager>(); global_manager->merge(reinterpret_cast<char const *>(tags_yaml), tags_yaml_len); auto const & config = vm.config().path_get("pharos.function_tags"); if (config.IsMap()) { global_manager->merge(config); } } return global_manager; } RegisterVector DescriptorSet::get_usual_registers() { RegisterDictionary const & rd = get_regdict(); if (arch_name == "i386" || arch_name == "amd64") { SymbolicValuePtr protoval = SymbolicValue::instance(); SymbolicRegisterStatePtr rstate = SymbolicRegisterState::instance(protoval, &rd); SymbolicMemoryMapStatePtr mstate = SymbolicMemoryMapState::instance(); SymbolicStatePtr state = SymbolicState::instance(rstate, mstate); SymbolicRiscOperatorsPtr lrops = SymbolicRiscOperators::instance(*this, state); DispatcherPtr dispatcher = RoseDispatcherX86::instance(lrops, get_arch_bits(), NULL); return dispatcher->get_usual_registers(); } else { return get_regdict().get_largest_registers(); } } // This is called by all the DescriptorSet::DescriptorSet() constructors (including the "usual" // one and the version in tracesem where we pass in an already built engine) but NOT by the // super ancient constructor where we "build" a function manually. void DescriptorSet::init() { apidb = APIDictionary::create_standard(vm); tag_manager = create_tag_manager(vm); interp = engine->interpretation(); if (interp == NULL) { throw std::runtime_error("Unable to analyze file (no executable content found)."); } // Populate the file and memmap object so that we can read the program image. SgAsmGenericHeader *hdr = interp->get_headers()->get_headers()[0]; auto file = SageInterface::getEnclosingNode < SgAsmGenericFile > (hdr); memory.set_memmap(interp->get_map()); assert(memory); // The recommended way to determine the architecture size is ask the disassembler. RoseDisassembler *disassembler = engine->obtainDisassembler(); arch_bytes = disassembler->wordSizeBytes(); set_global_arch_bytes(arch_bytes); // OINFO << "Input file is a " << get_arch_bits() << "-bit Windows PE executable!" << LEND; // Set the architecture name. arch_name = disassembler->name(); // This needs to be set before we do any emulation, and after we know our architecture size. // Perhaps it's time to move this _into_ the global descriptor set (or eliminate it completely). global_rops = NULL; if (get_arch_name() != "i386" && get_arch_name() != "amd64") { GWARN << "Analyzing executable with unsupported architecture '" << get_arch_name() << "', results may be incorrect." << LEND; } else { global_rops = SymbolicRiscOperators::instance(*this); } // Find all SgAsmPEImportDirectory objects in the project. Walk these, extracting the DLL // name, and the names of the imported functions. Create an import descriptor for each. // BUG? I'd prefer that this method not use querySubTree to obtain this list. std::vector<SgNode*> impdirs = NodeQuery::querySubTree(file, V_SgAsmPEImportDirectory); for (std::vector<SgNode*>::iterator it = impdirs.begin(); it != impdirs.end(); it++) { SgAsmPEImportDirectory* impdir = isSgAsmPEImportDirectory(*it); std::string dll = impdir->get_dll_name()->get_string(); SgAsmPEImportItemPtrList& impitems = impdir->get_imports()->get_vector(); for (SgAsmPEImportItemPtrList::iterator iit = impitems.begin(); iit != impitems.end(); iit++) { SgAsmPEImportItem* item = isSgAsmPEImportItem(*iit); rose_addr_t iat_va = item->get_iat_entry_va(); if (iat_va != 0) { add_import(iat_va, dll, item->get_name()->get_string(), item->get_ordinal()); } } } // Experimental new code to create "imports" based on ELF RelocEntry objects. SgAsmElfFileHeader* elfHeader = isSgAsmElfFileHeader(hdr); if (elfHeader) { for (SgAsmGenericSection *section : elfHeader->get_sections()->get_sections()) { if (SgAsmElfRelocSection *relocSection = isSgAsmElfRelocSection(section)) { SgAsmElfSymbolSection *symbolSection = isSgAsmElfSymbolSection(relocSection->get_linked_section()); if (SgAsmElfSymbolList *symbols = symbolSection ? symbolSection->get_symbols() : NULL) { for (SgAsmElfRelocEntry *rel : relocSection->get_entries()->get_entries()) { if (rel->get_type() == SgAsmElfRelocEntry::R_X86_64_JUMP_SLOT || rel->get_type() == SgAsmElfRelocEntry::R_386_JMP_SLOT) { rose_addr_t raddr = rel->get_r_offset(); // ELF files don't say explicltly which files contain which symbols. They're std::string dll("ELF"); // Start with a NULL name. The import descriptor constructor will change it to // '*INVALID*' if we're unable to find the symbol. std::string name; // But if there's a name in the ELF (and there should be) use it. unsigned long symbolIdx = rel->get_sym(); if (symbolIdx < symbols->get_symbols().size()) { SgAsmElfSymbol *symbol = symbols->get_symbols()[symbolIdx]; name = symbol->get_name()->get_string(); } add_import(raddr, dll, name); //OINFO << "Added ELF 'import':" << addr_str(raddr) << " " << name << LEND; } } } } } } using clock = std::chrono::steady_clock; using time_point = std::chrono::time_point<clock>; using duration = std::chrono::duration<double>; time_point start_ts = clock::now(); GDEBUG << "Creating the whole-program function call graph..." << LEND; function_call_graph = partitioner.functionCallGraph(P2::AllowParallelEdges::NO); duration secs = clock::now() - start_ts; GDEBUG << "Creation of the whole-program function call graph took " << secs.count() << " seconds." << LEND; // Create function descriptors, call descriptors, and global memory descriptors... create(); // Since we need the call descriptors to create the new PDG graph, this seems like the right // place to do that for now. In the future, this might be better someplace else. pdg_graph.populate(*this, partitioner); // Now make any connections that couldn't be made easily until we had complete data. update_connections(); //dump(std::cout); } // When passed a NULL interpretation, we'll analyze the file specified in the program options. // This is the standard way of constructing the descriptor set, despite the implementation // being the other way around. This is because there are some special constraints in tracesem // that should really just be eliminated. DescriptorSet::DescriptorSet(const ProgOptVarMap& povm) : DescriptorSet(povm, povm.count("file") ? std::vector<std::string>({povm["file"].as<bf::path>().native()}) : std::vector<std::string>()) {} void partition(const ProgOptVarMap & vm) { using namespace std::string_literals; if (!vm.count("file")) { OFATAL << "No file to partition" << LEND; exit(EXIT_FAILURE); } auto pfile = vm["file"].as<bf::path>(); auto file = pfile.native(); if (!vm.count("serialize")) { auto filename = pfile.filename().native(); auto sername = filename + ".serialized"; auto vmcopy = vm; vmcopy.emplace("serialize"s, boost::program_options::variable_value{boost::any{sername}, false}); DescriptorSet ds{vmcopy, {file}, true}; } else { DescriptorSet ds{vm, {file}, true}; } } DescriptorSet::DescriptorSet( const ProgOptVarMap& povm, std::vector<std::string> const & specimens, bool partition_only) : vm(povm), specimen_names(specimens) { // Instantiate a partitioning engine as requested by the options/configuration. boost::optional<std::string> pname = vm.get<std::string>("partitioner", "pharos.partitioner"); if (!pname) { *pname = "pharos"; } // The --stockpart option is deprecated, please use "--partitioner=rose" instead. bool sp = vm.count("stockpart"); if (sp) { *pname = "rose"; OWARN << "The option --stockpart has been deprecated. Use --partitioner=rose instead." << LEND; } if (boost::iequals(*pname, "rose")) { engine = new P2::Engine(); GINFO << "Using the standard ROSE function partitioner." << LEND; } else if (boost::iequals(*pname, "superset")) { engine = new SupersetEngine(); GINFO << "Using the Pharos superset disassembly algorithm." << LEND; } else if (boost::iequals(*pname, "pharos")) { engine = new CERTEngine(); GINFO << "Using the default Pharos function partitioner." << LEND; } else { engine = new CERTEngine(); OERROR << "The partitioner '" << *pname << "' is not recognized, " << "using the Pharos function partitioner." << LEND; } // And then partition... partitioner = create_partitioner(vm, engine, specimen_names); if (!partition_only) { // Call communal init init(); } } // This version of the constructor is only used by tracesem, which wants to pass in its own // engine. Pharos programs should always call the first constructor. I'm currently passing // both the engine and the partitioner in tracesem, but perhaps we don't really need both. DescriptorSet::DescriptorSet(const ProgOptVarMap& povm, P2::Engine& eng, P2::Partitioner&& par) : vm(povm), partitioner(std::move(par)) { engine = &eng; init(); } std::string DescriptorSet::get_filename() const { return vm["file"].as<bf::path>().filename().native(); } // Wes needed to be able to create a DescriptorSet from a single function because Wes loaded the // function from an assembly source file, and made the SgAsgInstruction objects himself. DescriptorSet::DescriptorSet(const ProgOptVarMap& povm, SgAsmFunction *func) : vm(povm) { // Because the function based approach is so wildly hacked, just hard-code 32-bits and // construct our global_rops now. arch_bytes = 4; global_rops = SymbolicRiscOperators::instance(*this); // We want to load API data for an imports in the created code. WARNING! We have no imports // in this view of the world, so attempts to resolve imports will always fail. apidb = APIDictionary::create_standard(vm); // The fact that these three values are NULL is very likely to be problematic. In // particular, the lack of a memory map will cause us to be very confused about what // addresses are defined in memory if we ever try to use that functionality. interp = nullptr; // Create a function descriptor for theone function. add_function_descriptor(func); // Add call descriptors, for each call instruction, even though the call targets don't // actually exist. SgAsmStatementPtrList &blocks = func->get_statementList(); for (size_t x = 0; x < blocks.size(); x++) { SgAsmBlock *bb = isSgAsmBlock(blocks[x]); if (!bb) continue; SgAsmStatementPtrList &ilist = bb->get_statementList(); for (size_t y = 0; y < ilist.size(); y++) { SgAsmX86Instruction *insn = isSgAsmX86Instruction(ilist[y]); if (insn_is_call(insn)) { call_descriptors.add(insn->get_address(), *this, insn); } } } } DescriptorSet::~DescriptorSet() { if (engine != NULL) delete engine; } RegisterDictionary const & DescriptorSet::get_regdict() const { return *partitioner.instructionProvider().registerDictionary(); } void DescriptorSet::create() { // Create function descriptors first, because we need them to determine whether some jump // instructions are really tail-optimized calls or not. const P2::AstConstructionSettings &settings = P2::AstConstructionSettings::strict(); for (const P2::Function::Ptr &function : partitioner.functions()) { SgAsmFunction* func = P2::Modules::buildFunctionAst(partitioner, function, settings); if (func) { add_function_descriptor(func); } } // Now create the other descriptors (by looking at individual instructions). for (P2::BasicBlock::Ptr b : partitioner.basicBlocks()) { for (SgAsmInstruction* insn : b->instructions()) { GTRACE << "INSN: " << debug_instruction(insn, 5, NULL) << LEND; SgAsmX86Instruction *xinsn = isSgAsmX86Instruction(insn); if (isSgAsmX86Instruction(insn) == NULL) continue; // Look for references to absolute addresses, in order to create global memory // descriptors. This code is very similar to what we do to detect calls as well, but // it's not clear that we can do much better than to just duplicate it here. SgAsmOperandList *oplist = xinsn->get_operandList(); SgAsmExpressionPtrList& elist = oplist->get_operands(); for (SgAsmExpression * expr : elist) { // The value of the constant expression. uint64_t v = 0; //bool known_memory = false; if (isSgAsmValueExpression (expr)) { // Don't create global memory descriptors for calls and jumps to immediate addresses. // We know that these are code references, not data references. if (!insn_is_control_flow(xinsn)) { v = SageInterface::getAsmConstant(isSgAsmValueExpression(expr)); } } else if (isSgAsmMemoryReferenceExpression(expr)) { //known_memory = true; SgAsmMemoryReferenceExpression* mr = isSgAsmMemoryReferenceExpression(expr); SgAsmExpression *addr_expr = mr->get_address(); // This case handles expressions like [403123] if (isSgAsmValueExpression(addr_expr)) { v = SageInterface::getAsmConstant(isSgAsmValueExpression(addr_expr)); } // This is the case for expressions like [eax+403123] and [ecx*4+403123] else if (isSgAsmBinaryExpression(addr_expr)) { // Is the constant always the right hand side? SgAsmExpression *const_expr = isSgAsmBinaryExpression(addr_expr)->get_rhs(); if (isSgAsmValueExpression(const_expr)) { v = SageInterface::getAsmConstant(isSgAsmValueExpression(const_expr)); } else { // In all of the cases that I looked at, these expressions were of the form [ecx+edx*2] GTRACE << "Right hand side of add expression is not constant!" << " insn=" << debug_instruction(xinsn, 0) << " expr=" << unparseExpression(const_expr, NULL, NULL) << LEND;} } // The remaning cases appear to be register dereferences e.g. "[eax]". It appears // that V_SgAsmBinarySubtract is not actually used (at least on X86). } // The determination of which addresses to include is a total hack, and it probably // needs to be replaced with something more intelligent. On the other hand, it would // be nice if something this general caused no significant downstream problems, because // it would be nice for this criteria to be sufficiently broad to catch all possible // memory refs. rose_addr_t addr = (rose_addr_t) v; if (possible_global_address(addr)) { // But don't create global memory descriptors for the imports. We should probably be // checking that no-one writes to the import table as well, perhaps the rigth place to // do that is during emulation? ImportDescriptor *id = import_descriptors.get_import(v); if (id == NULL) { // Do we already have a global memory descriptor for this address? GlobalMemoryDescriptor* gmd = get_rw_global(addr); // add_ref() // If not, then create one. if (gmd == NULL) { map_emplace_or_replace(global_descriptors, addr, addr, get_arch_bits()); gmd = get_rw_global(addr); // add_ref(), just created } // Either way, this instruction references the address... gmd->add_ref(xinsn); // We don't actually know if the reference was a read or a write, so this is WRONG! // But it'll do for my current testing needs. // if (known_memory) gmd->add_read(xinsn); } } } // We're only interested in call and jmp instructions for creating call descriptors. if (!insn_is_call_or_jmp(xinsn)) continue; // If the instruction was a jump, it also needs to be a jump to a function entry. if (insn_is_jmp(xinsn)) { boost::optional<rose_addr_t> taddr = insn_get_branch_target(insn); if (!taddr) continue; if (!get_func(*taddr)) continue; } // Create a call descriptor for the call, or the tail-call optimized jump instruction. map_emplace_or_replace(call_descriptors, insn->get_address(), *this, xinsn); } } } void DescriptorSet::update_connections() { for (CallDescriptorMap::value_type & pair : call_descriptors) { CallDescriptor& cd = pair.second; cd.update_connections(); } for (FunctionDescriptorMap::value_type & pair : function_descriptors) { FunctionDescriptor& fd = pair.second; fd.update_connections(function_descriptors); } // Cory doesn't like the way this worked out, but propagating thunk info has to follow the // pass in the main update_connections() method. This really needs to be some kind of a pass // based architecture. for (FunctionDescriptorMap::value_type & pair : function_descriptors) { FunctionDescriptor& fd = pair.second; fd.propagate_thunk_info(); } } void DescriptorSet::validate(std::ostream &o) { for (CallDescriptorMap::value_type & pair : call_descriptors) { CallDescriptor& cd = pair.second; cd.validate(o, function_descriptors); } for (FunctionDescriptorMap::value_type & pair : function_descriptors) { FunctionDescriptor& fd = pair.second; fd.validate(o); } for (ImportDescriptorMap::value_type & pair : import_descriptors) { ImportDescriptor& id = pair.second; id.validate(o); } // I should probably be doing something here for globals... } void DescriptorSet::dump(std::ostream &o) const { for (const CallDescriptorMap::value_type & pair : call_descriptors) { o << pair.second << LEND; } for (const FunctionDescriptorMap::value_type & pair : function_descriptors) { o << pair.second << LEND; } for (const ImportDescriptorMap::value_type & pair : import_descriptors) { o << pair.second << LEND; } for (const GlobalMemoryDescriptorMap::value_type & pair : global_descriptors) { o << pair.second << LEND; } } void DescriptorSet::resolve_imports() { // For each import in our file... for (auto & pair : import_descriptors) { ImportDescriptor &id = pair.second; if (!id.is_dll_valid()) { continue; } auto root = id.get_dll_root(); GDEBUG << "Resolving imports for: " << id << " in DLL root: " << root << LEND; // If the user specified a delta in the user config file, we don't need to load a delta // from the DLL config files. This also serves to eliminate the warnings when the entry is // not found in the DLL config files. StackDelta isd = id.get_stack_delta(); if (isd.confidence == ConfidenceUser) continue; APIDefinitionList fdesc; if (id.is_name_valid()) { fdesc = apidb->get_api_definition(root, id.get_name()); } if (fdesc.empty() && id.get_ordinal() != 0) { fdesc = apidb->get_api_definition(root, id.get_ordinal()); } if (!fdesc.empty()) { id.merge_api_definition(*fdesc.front()); } else { GWARN << "No stack delta information for: " << id.get_best_name() << LEND; } // This is where we can first report the full prototypes of the imported functions that // actually occur in the program being analyzed... if (GTRACE) { const ParameterList& params = id.get_function_descriptor()->get_parameters(); GTRACE << "Import " << id.get_long_name() << " has parameters: "; params.debug(); } } // Now update the connections... I'm not sure if this is really needed or not. update_connections(); } // Find an import descriptor given the symbolic value that the loader filled in for that // import. This is primarily used when resolving ImportDescriptor* DescriptorSet::get_import_by_variable(SymbolicValuePtr v) { // Get the expression provided by the caller. TreeNodePtr tn = v->get_expression(); if (tn == NULL) return NULL; // The expression should always be a LeafNode, or it's not really an import. LeafNodePtr ln = tn->isLeafNode(); if (ln == NULL) return NULL; // Get the unique variable number. uint64_t vnum = ln->nameId(); // Attempt to lookup the import by that variable number in the map. ImportVariableMap::iterator finder = import_variables.find(vnum); // If it wasn't found, we're not an import. if (finder == import_variables.end()) return NULL; // If it was, return it. return finder->second; } void DescriptorSet::update_import_target(SymbolicValuePtr& v, SgAsmX86Instruction* insn) { SDEBUG << "Call target is to loader defined value: " << *v << LEND; ImportDescriptor* id = get_import_by_variable(v); // Yes, it's a call to an import. Update the call target list with a new target. if (id != NULL) { SDEBUG << "The call " << debug_instruction(insn) << " was to import " << id->get_long_name() << LEND; CallDescriptor* cd = get_rw_call(insn->get_address()); // add_import_target() cd->add_import_target(id); } else { SDEBUG << "The constant call target was not resolved." << LEND; } } const FunctionDescriptor* DescriptorSet::get_func_containing_address(rose_addr_t addr) const { std::vector<const FunctionDescriptor*> fds = get_funcs_containing_address(addr); if (fds.size() == 0) { return NULL; } // This is not intended to be a permanent warning because there's nothing the end user can // act on! while it might be appropriate to keep this function as a "helper", it would // probably be better to eliminate it entirely in favor of newer get_funcs_containg_address() // API. else if (fds.size() > 1) { OWARN << "Address " << addr_str(addr) << " was used by more than one function!" << LEND; } return fds[0]; } std::vector<const FunctionDescriptor*> DescriptorSet::get_funcs_containing_address(rose_addr_t addr) const { std::vector<const FunctionDescriptor*> funcs; const AddressInterval ai(addr); for (const P2::Function::Ptr & func : partitioner.functionsOverlapping(ai)) { const FunctionDescriptor* fd = get_func(func->address()); if (fd) { funcs.push_back(fd); } // If there was a P2::Function::Ptr, but not a FunctionDescriptor that's an assertion // worthy level programming error, but let's not exit needlessly. else { GERROR << "No function found at address " << addr_str(addr) << LEND; } } // This list might be empty, and that's not an unexpected condition. return funcs; } std::vector<FunctionDescriptor*> DescriptorSet::get_rw_funcs_containing_address(rose_addr_t addr) { std::vector<FunctionDescriptor*> funcs; const AddressInterval ai(addr); for (const P2::Function::Ptr & func : partitioner.functionsOverlapping(ai)) { FunctionDescriptor* fd = get_rw_func(func->address()); if (fd) { funcs.push_back(fd); } // If there was a P2::Function::Ptr, but not a FunctionDescriptor that's an assertion // worthy level programming error, but let's not exit needlessly. else { GERROR << "No function found at address " << addr_str(addr) << LEND; } } // This list might be empty, and that's not an unexpected condition. return funcs; } // Find a general purpose register in an semi-architecture independent way. // Now implemented in terms of a method in misc.cpp that does the heavy lifting. RegisterDescriptor DescriptorSet::get_arch_reg(const std::string & name) const { return pharos::get_arch_reg(get_regdict(), name, arch_bytes); } unsigned int DescriptorSet::get_concurrency_level(ProgOptVarMap const & vm) { auto level_opt = vm.get<int>("threads", "concurrency_level"); if (!level_opt) { return 1; } #ifdef PHAROS_BROKEN_THREADS GWARN << "Multi-threading has been disabled in this binary." << LEND; return 1; #else auto level = *level_opt; if (level > 0) { return unsigned(level); } auto hwc = std::thread::hardware_concurrency(); if (level == 0) { return hwc; } auto inverted_level = unsigned(-level); if (hwc <= inverted_level) { return 1; } return hwc - inverted_level; #endif } } // namespace pharos /* Local Variables: */ /* mode: c++ */ /* fill-column: 95 */ /* comment-column: 0 */ /* End: */
/* Copyright (c) 2015-2016 The Khronos Group Inc. * Copyright (c) 2015-2016 Valve Corporation * Copyright (c) 2015-2016 LunarG, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and/or associated documentation files (the "Materials"), to * deal in the Materials without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Materials, and to permit persons to whom the Materials * are furnished to do so, subject to the following conditions: * * The above copyright notice(s) and this permission notice shall be included * in all copies or substantial portions of the Materials. * * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE * USE OR OTHER DEALINGS IN THE MATERIALS * * Author: Tobin Ehlis <tobin@lunarg.com> */ #include <assert.h> #include <unordered_map> #include "vulkan/vk_debug_marker_layer.h" std::unordered_map<void *, VkLayerDebugMarkerDispatchTable *> tableDebugMarkerMap; /* Various dispatchable objects will use the same underlying dispatch table if * they * are created from that "parent" object. Thus use pointer to dispatch table * as the key to these table maps. * Instance -> PhysicalDevice * Device -> CommandBuffer or Queue * If use the object themselves as key to map then implies Create entrypoints * have to be intercepted * and a new key inserted into map */ VkLayerDebugMarkerDispatchTable *initDebugMarkerTable(VkDevice device) { VkLayerDebugMarkerDispatchTable *pDebugMarkerTable; assert(device); VkLayerDispatchTable *pDisp = *(VkLayerDispatchTable **)device; std::unordered_map<void *, VkLayerDebugMarkerDispatchTable *>::const_iterator it = tableDebugMarkerMap.find((void *)pDisp); if (it == tableDebugMarkerMap.end()) { pDebugMarkerTable = new VkLayerDebugMarkerDispatchTable; tableDebugMarkerMap[(void *)pDisp] = pDebugMarkerTable; } else { return it->second; } pDebugMarkerTable->CmdDbgMarkerBegin = (PFN_vkCmdDbgMarkerBegin)pDisp->GetDeviceProcAddr( device, "vkCmdDbgMarkerBegin"); pDebugMarkerTable->CmdDbgMarkerEnd = (PFN_vkCmdDbgMarkerEnd)pDisp->GetDeviceProcAddr(device, "vkCmdDbgMarkerEnd"); pDebugMarkerTable->DbgSetObjectTag = (PFN_vkDbgSetObjectTag)pDisp->GetDeviceProcAddr(device, "vkDbgSetObjectTag"); pDebugMarkerTable->DbgSetObjectName = (PFN_vkDbgSetObjectName)pDisp->GetDeviceProcAddr(device, "vkDbgSetObjectName"); return pDebugMarkerTable; }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. #include "pch.h" #include "Terminal.hpp" #include "../../terminal/parser/OutputStateMachineEngine.hpp" #include "TerminalDispatch.hpp" #include "../../inc/unicode.hpp" #include "../../inc/DefaultSettings.h" #include "../../inc/argb.h" #include "../../types/inc/utils.hpp" #include "winrt/Microsoft.Terminal.Settings.h" using namespace winrt::Microsoft::Terminal::Settings; using namespace Microsoft::Terminal::Core; using namespace Microsoft::Console; using namespace Microsoft::Console::Render; using namespace Microsoft::Console::Types; using namespace Microsoft::Console::VirtualTerminal; static std::wstring _KeyEventsToText(std::deque<std::unique_ptr<IInputEvent>>& inEventsToWrite) { std::wstring wstr = L""; for (const auto& ev : inEventsToWrite) { if (ev->EventType() == InputEventType::KeyEvent) { const auto& k = static_cast<KeyEvent&>(*ev); const auto wch = k.GetCharData(); wstr += wch; } } return wstr; } #pragma warning(suppress : 26455) // default constructor is throwing, too much effort to rearrange at this time. Terminal::Terminal() : _mutableViewport{ Viewport::Empty() }, _title{}, _colorTable{}, _defaultFg{ RGB(255, 255, 255) }, _defaultBg{ ARGB(0, 0, 0, 0) }, _pfnWriteInput{ nullptr }, _scrollOffset{ 0 }, _snapOnInput{ true }, _boxSelection{ false }, _selectionActive{ false }, _allowSingleCharSelection{ true }, _copyOnSelect{ false }, _selectionAnchor{ 0, 0 }, _endSelectionPosition{ 0, 0 } { auto dispatch = std::make_unique<TerminalDispatch>(*this); auto engine = std::make_unique<OutputStateMachineEngine>(std::move(dispatch)); _stateMachine = std::make_unique<StateMachine>(std::move(engine)); auto passAlongInput = [&](std::deque<std::unique_ptr<IInputEvent>>& inEventsToWrite) { if (!_pfnWriteInput) { return; } std::wstring wstr = _KeyEventsToText(inEventsToWrite); _pfnWriteInput(wstr); }; _terminalInput = std::make_unique<TerminalInput>(passAlongInput); _InitializeColorTable(); } void Terminal::Create(COORD viewportSize, SHORT scrollbackLines, IRenderTarget& renderTarget) { _mutableViewport = Viewport::FromDimensions({ 0, 0 }, viewportSize); _scrollbackLines = scrollbackLines; const COORD bufferSize{ viewportSize.X, Utils::ClampToShortMax(viewportSize.Y + scrollbackLines, 1) }; const TextAttribute attr{}; const UINT cursorSize = 12; _buffer = std::make_unique<TextBuffer>(bufferSize, attr, cursorSize, renderTarget); } // Method Description: // - Initializes the Terminal from the given set of settings. // Arguments: // - settings: the set of CoreSettings we need to use to initialize the terminal // - renderTarget: A render target the terminal can use for paint invalidation. void Terminal::CreateFromSettings(winrt::Microsoft::Terminal::Settings::ICoreSettings settings, Microsoft::Console::Render::IRenderTarget& renderTarget) { const COORD viewportSize{ Utils::ClampToShortMax(settings.InitialCols(), 1), Utils::ClampToShortMax(settings.InitialRows(), 1) }; // TODO:MSFT:20642297 - Support infinite scrollback here, if HistorySize is -1 Create(viewportSize, Utils::ClampToShortMax(settings.HistorySize(), 0), renderTarget); UpdateSettings(settings); if (_suppressApplicationTitle) { _title = _startingTitle; } } // Method Description: // - Update our internal properties to match the new values in the provided // CoreSettings object. // Arguments: // - settings: an ICoreSettings with new settings values for us to use. void Terminal::UpdateSettings(winrt::Microsoft::Terminal::Settings::ICoreSettings settings) { _defaultFg = settings.DefaultForeground(); _defaultBg = settings.DefaultBackground(); CursorType cursorShape = CursorType::VerticalBar; switch (settings.CursorShape()) { case CursorStyle::Underscore: cursorShape = CursorType::Underscore; break; case CursorStyle::FilledBox: cursorShape = CursorType::FullBox; break; case CursorStyle::EmptyBox: cursorShape = CursorType::EmptyBox; break; case CursorStyle::Vintage: cursorShape = CursorType::Legacy; break; default: case CursorStyle::Bar: cursorShape = CursorType::VerticalBar; break; } _buffer->GetCursor().SetStyle(settings.CursorHeight(), settings.CursorColor(), cursorShape); for (int i = 0; i < 16; i++) { _colorTable.at(i) = settings.GetColorTableEntry(i); } _snapOnInput = settings.SnapOnInput(); _wordDelimiters = settings.WordDelimiters(); _copyOnSelect = settings.CopyOnSelect(); _suppressApplicationTitle = settings.SuppressApplicationTitle(); _startingTitle = settings.StartingTitle(); // TODO:MSFT:21327402 - if HistorySize has changed, resize the buffer so we // have a smaller scrollback. We should do this carefully - if the new buffer // size is smaller than where the mutable viewport currently is, we'll want // to make sure to rotate the buffer contents upwards, so the mutable viewport // remains at the bottom of the buffer. } // Method Description: // - Resize the terminal as the result of some user interaction. // Arguments: // - viewportSize: the new size of the viewport, in chars // Return Value: // - S_OK if we successfully resized the terminal, S_FALSE if there was // nothing to do (the viewportSize is the same as our current size), or an // appropriate HRESULT for failing to resize. [[nodiscard]] HRESULT Terminal::UserResize(const COORD viewportSize) noexcept { const auto oldDimensions = _mutableViewport.Dimensions(); if (viewportSize == oldDimensions) { return S_FALSE; } const auto oldTop = _mutableViewport.Top(); const short newBufferHeight = viewportSize.Y + _scrollbackLines; COORD bufferSize{ viewportSize.X, newBufferHeight }; RETURN_IF_FAILED(_buffer->ResizeTraditional(bufferSize)); auto proposedTop = oldTop; const auto newView = Viewport::FromDimensions({ 0, proposedTop }, viewportSize); const auto proposedBottom = newView.BottomExclusive(); // If the new bottom would be below the bottom of the buffer, then slide the // top up so that we'll still fit within the buffer. if (proposedBottom > bufferSize.Y) { proposedTop -= (proposedBottom - bufferSize.Y); } _mutableViewport = Viewport::FromDimensions({ 0, proposedTop }, viewportSize); _scrollOffset = 0; _NotifyScrollEvent(); return S_OK; } void Terminal::Write(std::wstring_view stringView) { auto lock = LockForWriting(); _stateMachine->ProcessString(stringView); } // Method Description: // - Attempts to snap to the bottom of the buffer, if SnapOnInput is true. Does // nothing if SnapOnInput is set to false, or we're already at the bottom of // the buffer. // Arguments: // - <none> // Return Value: // - <none> void Terminal::TrySnapOnInput() { if (_snapOnInput && _scrollOffset != 0) { auto lock = LockForWriting(); _scrollOffset = 0; _NotifyScrollEvent(); } } // Method Description: // - Send this particular key event to the terminal. The terminal will translate // the key and the modifiers pressed into the appropriate VT sequence for that // key chord. If we do translate the key, we'll return true. In that case, the // event should NOT be processed any further. If we return false, the event // was NOT translated, and we should instead use the event to try and get the // real character out of the event. // Arguments: // - vkey: The vkey of the key pressed. // - states: The Microsoft::Terminal::Core::ControlKeyStates representing the modifier key states. // Return Value: // - true if we translated the key event, and it should not be processed any further. // - false if we did not translate the key, and it should be processed into a character. bool Terminal::SendKeyEvent(const WORD vkey, const WORD scanCode, const ControlKeyStates states) { TrySnapOnInput(); // Alt key sequences _require_ the char to be in the keyevent. If alt is // pressed, manually get the character that's being typed, and put it in the // KeyEvent. // DON'T manually handle Alt+Space - the system will use this to bring up // the system menu for restore, min/maximimize, size, move, close wchar_t ch = UNICODE_NULL; if (states.IsAltPressed() && vkey != VK_SPACE) { ch = _CharacterFromKeyEvent(vkey, scanCode, states); } if (states.IsCtrlPressed()) { switch (vkey) { case 0x48: // Manually handle Ctrl+H. Ctrl+H should be handled as Backspace. To do this // correctly, the keyEvents's char needs to be set to Backspace. // 0x48 is the VKEY for 'H', which isn't named ch = UNICODE_BACKSPACE; break; case VK_SPACE: // Manually handle Ctrl+Space here. The terminalInput translator requires // the char to be set to Space for space handling to work correctly. ch = UNICODE_SPACE; break; } } // Manually handle Escape here. If we let it fall through, it'll come // back up through the character handler. It's registered as a translation // in TerminalInput, so we'll let TerminalInput control it. if (vkey == VK_ESCAPE) { ch = UNICODE_ESC; } const bool manuallyHandled = ch != UNICODE_NULL; KeyEvent keyEv{ true, 0, vkey, scanCode, ch, states.Value() }; const bool translated = _terminalInput->HandleKey(&keyEv); return translated && manuallyHandled; } bool Terminal::SendCharEvent(const wchar_t ch) { return _terminalInput->HandleChar(ch); } // Method Description: // - Returns the keyboard's scan code for the given virtual key code. // Arguments: // - vkey: The virtual key code. // Return Value: // - The keyboard's scan code. WORD Terminal::_ScanCodeFromVirtualKey(const WORD vkey) noexcept { return LOWORD(MapVirtualKeyW(vkey, MAPVK_VK_TO_VSC)); } // Method Description: // - Translates the specified virtual key code and keyboard state to the corresponding character. // Arguments: // - vkey: The virtual key code that initiated this keyboard event. // - scanCode: The scan code that initiated this keyboard event. // - states: The current keyboard state. // Return Value: // - The character that would result from this virtual key code and keyboard state. wchar_t Terminal::_CharacterFromKeyEvent(const WORD vkey, const WORD scanCode, const ControlKeyStates states) noexcept try { const auto sc = scanCode != 0 ? scanCode : _ScanCodeFromVirtualKey(vkey); // We might want to use GetKeyboardState() instead of building our own keyState. // The question is whether that's necessary though. For now it seems to work fine as it is. std::array<BYTE, 256> keyState = {}; keyState.at(VK_SHIFT) = states.IsShiftPressed() ? 0x80 : 0; keyState.at(VK_CONTROL) = states.IsCtrlPressed() ? 0x80 : 0; keyState.at(VK_MENU) = states.IsAltPressed() ? 0x80 : 0; // For the following use of ToUnicodeEx() please look here: // https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-tounicodeex // Technically ToUnicodeEx() can produce arbitrarily long sequences of diacritics etc. // Since we only handle the case of a single UTF-16 code point, we can set the buffer size to 2 though. std::array<wchar_t, 2> buffer; // wFlags: // * If bit 0 is set, a menu is active. // If this flag is not specified ToUnicodeEx will send us character events on certain Alt+Key combinations (e.g. Alt+Arrow-Up). // * If bit 2 is set, keyboard state is not changed (Windows 10, version 1607 and newer) const auto result = ToUnicodeEx(vkey, sc, keyState.data(), buffer.data(), gsl::narrow_cast<int>(buffer.size()), 0b101, nullptr); // TODO:GH#2853 We're only handling single UTF-16 code points right now, since that's the only thing KeyEvent supports. return result == 1 || result == -1 ? buffer.at(0) : 0; } catch (...) { LOG_CAUGHT_EXCEPTION(); return UNICODE_INVALID; } // Method Description: // - Aquire a read lock on the terminal. // Return Value: // - a shared_lock which can be used to unlock the terminal. The shared_lock // will release this lock when it's destructed. [[nodiscard]] std::shared_lock<std::shared_mutex> Terminal::LockForReading() { return std::shared_lock<std::shared_mutex>(_readWriteLock); } // Method Description: // - Aquire a write lock on the terminal. // Return Value: // - a unique_lock which can be used to unlock the terminal. The unique_lock // will release this lock when it's destructed. [[nodiscard]] std::unique_lock<std::shared_mutex> Terminal::LockForWriting() { return std::unique_lock<std::shared_mutex>(_readWriteLock); } Viewport Terminal::_GetMutableViewport() const noexcept { return _mutableViewport; } short Terminal::GetBufferHeight() const noexcept { return _mutableViewport.BottomExclusive(); } // ViewStartIndex is also the length of the scrollback int Terminal::ViewStartIndex() const noexcept { return _mutableViewport.Top(); } int Terminal::ViewEndIndex() const noexcept { return _mutableViewport.BottomInclusive(); } // _VisibleStartIndex is the first visible line of the buffer int Terminal::_VisibleStartIndex() const noexcept { return std::max(0, ViewStartIndex() - _scrollOffset); } int Terminal::_VisibleEndIndex() const noexcept { return std::max(0, ViewEndIndex() - _scrollOffset); } Viewport Terminal::_GetVisibleViewport() const noexcept { const COORD origin{ 0, gsl::narrow<short>(_VisibleStartIndex()) }; return Viewport::FromDimensions(origin, _mutableViewport.Dimensions()); } // Writes a string of text to the buffer, then moves the cursor (and viewport) // in accordance with the written text. // This method is our proverbial `WriteCharsLegacy`, and great care should be made to // keep it minimal and orderly, lest it become WriteCharsLegacy2ElectricBoogaloo // TODO: MSFT 21006766 // This needs to become stream logic on the buffer itself sooner rather than later // because it's otherwise impossible to avoid the Electric Boogaloo-ness here. // I had to make a bunch of hacks to get Japanese and emoji to work-ish. void Terminal::_WriteBuffer(const std::wstring_view& stringView) { auto& cursor = _buffer->GetCursor(); const Viewport bufferSize = _buffer->GetSize(); // Defer the cursor drawing while we are iterating the string, for a better performance. // We can not waste time displaying a cursor event when we know more text is coming right behind it. cursor.StartDeferDrawing(); for (size_t i = 0; i < stringView.size(); i++) { const auto wch = stringView.at(i); const COORD cursorPosBefore = cursor.GetPosition(); COORD proposedCursorPosition = cursorPosBefore; bool notifyScroll = false; if (wch == UNICODE_LINEFEED) { proposedCursorPosition.Y++; } else if (wch == UNICODE_CARRIAGERETURN) { proposedCursorPosition.X = 0; } else if (wch == UNICODE_BACKSPACE) { if (cursorPosBefore.X == 0) { proposedCursorPosition.X = bufferSize.Width() - 1; proposedCursorPosition.Y--; } else { proposedCursorPosition.X--; } } else if (wch == UNICODE_BEL) { // TODO: GitHub #1883 // For now its empty just so we don't try to write the BEL character } else { // TODO: MSFT 21006766 // This is not great but I need it demoable. Fix by making a buffer stream writer. // // If wch is a surrogate character we need to read 2 code units // from the stringView to form a single code point. const auto isSurrogate = wch >= 0xD800 && wch <= 0xDFFF; const auto view = stringView.substr(i, isSurrogate ? 2 : 1); const OutputCellIterator it{ view, _buffer->GetCurrentAttributes() }; const auto end = _buffer->Write(it); const auto cellDistance = end.GetCellDistance(it); const auto inputDistance = end.GetInputDistance(it); if (inputDistance > 0) { // If "wch" was a surrogate character, we just consumed 2 code units above. // -> Increment "i" by 1 in that case and thus by 2 in total in this iteration. proposedCursorPosition.X += gsl::narrow<SHORT>(cellDistance); i += inputDistance - 1; } else { // If _WriteBuffer() is called with a consecutive string longer than the viewport/buffer width // the call to _buffer->Write() will refuse to write anything on the current line. // GetInputDistance() thus returns 0, which would in turn cause i to be // decremented by 1 below and force the outer loop to loop forever. // This if() basically behaves as if "\r\n" had been encountered above and retries the write. // With well behaving shells during normal operation this safeguard should normally not be encountered. proposedCursorPosition.X = 0; proposedCursorPosition.Y++; } } // If we're about to scroll past the bottom of the buffer, instead cycle the buffer. const auto newRows = proposedCursorPosition.Y - bufferSize.Height() + 1; if (newRows > 0) { for (auto dy = 0; dy < newRows; dy++) { _buffer->IncrementCircularBuffer(); proposedCursorPosition.Y--; } notifyScroll = true; } // This section is essentially equivalent to `AdjustCursorPosition` // Update Cursor Position cursor.SetPosition(proposedCursorPosition); const COORD cursorPosAfter = cursor.GetPosition(); // Move the viewport down if the cursor moved below the viewport. if (cursorPosAfter.Y > _mutableViewport.BottomInclusive()) { const auto newViewTop = std::max(0, cursorPosAfter.Y - (_mutableViewport.Height() - 1)); if (newViewTop != _mutableViewport.Top()) { _mutableViewport = Viewport::FromDimensions({ 0, gsl::narrow<short>(newViewTop) }, _mutableViewport.Dimensions()); notifyScroll = true; } } if (notifyScroll) { _buffer->GetRenderTarget().TriggerRedrawAll(); _NotifyScrollEvent(); } } cursor.EndDeferDrawing(); } void Terminal::UserScrollViewport(const int viewTop) { const auto clampedNewTop = std::max(0, viewTop); const auto realTop = ViewStartIndex(); const auto newDelta = realTop - clampedNewTop; // if viewTop > realTop, we want the offset to be 0. _scrollOffset = std::max(0, newDelta); _buffer->GetRenderTarget().TriggerRedrawAll(); } int Terminal::GetScrollOffset() noexcept { return _VisibleStartIndex(); } void Terminal::_NotifyScrollEvent() noexcept try { if (_pfnScrollPositionChanged) { const auto visible = _GetVisibleViewport(); const auto top = visible.Top(); const auto height = visible.Height(); const auto bottom = this->GetBufferHeight(); _pfnScrollPositionChanged(top, height, bottom); } } CATCH_LOG() void Terminal::SetWriteInputCallback(std::function<void(std::wstring&)> pfn) noexcept { _pfnWriteInput.swap(pfn); } void Terminal::SetTitleChangedCallback(std::function<void(const std::wstring_view&)> pfn) noexcept { _pfnTitleChanged.swap(pfn); } void Terminal::SetScrollPositionChangedCallback(std::function<void(const int, const int, const int)> pfn) noexcept { _pfnScrollPositionChanged.swap(pfn); } // Method Description: // - Allows setting a callback for when the background color is changed // Arguments: // - pfn: a function callback that takes a uint32 (DWORD COLORREF) color in the format 0x00BBGGRR void Terminal::SetBackgroundCallback(std::function<void(const uint32_t)> pfn) noexcept { _pfnBackgroundColorChanged.swap(pfn); } void Terminal::_InitializeColorTable() try { const gsl::span<COLORREF> tableView = { _colorTable.data(), gsl::narrow<ptrdiff_t>(_colorTable.size()) }; // First set up the basic 256 colors Utils::Initialize256ColorTable(tableView); // Then use fill the first 16 values with the Campbell scheme Utils::InitializeCampbellColorTable(tableView); // Then make sure all the values have an alpha of 255 Utils::SetColorTableAlpha(tableView, 0xff); } CATCH_LOG() // Method Description: // - Sets the visibility of the text cursor. // Arguments: // - isVisible: whether the cursor should be visible void Terminal::SetCursorVisible(const bool isVisible) noexcept { auto& cursor = _buffer->GetCursor(); cursor.SetIsVisible(isVisible); } bool Terminal::IsCursorBlinkingAllowed() const noexcept { const auto& cursor = _buffer->GetCursor(); return cursor.IsBlinkingAllowed(); }
// Copyright (c) 2013, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. // // Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "db/version_set.h" #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #include <inttypes.h> #include <stdio.h> #include <algorithm> #include <map> #include <set> #include <climits> #include <unordered_map> #include <vector> #include <string> #include "db/filename.h" #include "db/log_reader.h" #include "db/log_writer.h" #include "db/memtable.h" #include "db/merge_context.h" #include "db/table_cache.h" #include "db/compaction.h" #include "db/version_builder.h" #include "rocksdb/env.h" #include "rocksdb/merge_operator.h" #include "table/table_reader.h" #include "table/merger.h" #include "table/two_level_iterator.h" #include "table/format.h" #include "table/plain_table_factory.h" #include "table/meta_blocks.h" #include "table/get_context.h" #include "util/coding.h" #include "util/logging.h" #include "util/stop_watch.h" namespace rocksdb { namespace { // Find File in LevelFilesBrief data structure // Within an index range defined by left and right int FindFileInRange(const InternalKeyComparator& icmp, const LevelFilesBrief& file_level, const Slice& key, uint32_t left, uint32_t right) { while (left < right) { uint32_t mid = (left + right) / 2; const FdWithKeyRange& f = file_level.files[mid]; if (icmp.InternalKeyComparator::Compare(f.largest_key, key) < 0) { // Key at "mid.largest" is < "target". Therefore all // files at or before "mid" are uninteresting. left = mid + 1; } else { // Key at "mid.largest" is >= "target". Therefore all files // after "mid" are uninteresting. right = mid; } } return right; } // Class to help choose the next file to search for the particular key. // Searches and returns files level by level. // We can search level-by-level since entries never hop across // levels. Therefore we are guaranteed that if we find data // in a smaller level, later levels are irrelevant (unless we // are MergeInProgress). class FilePicker { public: FilePicker( std::vector<FileMetaData*>* files, const Slice& user_key, const Slice& ikey, autovector<LevelFilesBrief>* file_levels, unsigned int num_levels, FileIndexer* file_indexer, const Comparator* user_comparator, const InternalKeyComparator* internal_comparator) : num_levels_(num_levels), curr_level_(-1), search_left_bound_(0), search_right_bound_(FileIndexer::kLevelMaxIndex), #ifndef NDEBUG files_(files), #endif level_files_brief_(file_levels), user_key_(user_key), ikey_(ikey), file_indexer_(file_indexer), user_comparator_(user_comparator), internal_comparator_(internal_comparator) { // Setup member variables to search first level. search_ended_ = !PrepareNextLevel(); if (!search_ended_) { // Prefetch Level 0 table data to avoid cache miss if possible. for (unsigned int i = 0; i < (*level_files_brief_)[0].num_files; ++i) { auto* r = (*level_files_brief_)[0].files[i].fd.table_reader; if (r) { r->Prepare(ikey); } } } } FdWithKeyRange* GetNextFile() { while (!search_ended_) { // Loops over different levels. while (curr_index_in_curr_level_ < curr_file_level_->num_files) { // Loops over all files in current level. FdWithKeyRange* f = &curr_file_level_->files[curr_index_in_curr_level_]; int cmp_largest = -1; // Do key range filtering of files or/and fractional cascading if: // (1) not all the files are in level 0, or // (2) there are more than 3 Level 0 files // If there are only 3 or less level 0 files in the system, we skip // the key range filtering. In this case, more likely, the system is // highly tuned to minimize number of tables queried by each query, // so it is unlikely that key range filtering is more efficient than // querying the files. if (num_levels_ > 1 || curr_file_level_->num_files > 3) { // Check if key is within a file's range. If search left bound and // right bound point to the same find, we are sure key falls in // range. assert( curr_level_ == 0 || curr_index_in_curr_level_ == start_index_in_curr_level_ || user_comparator_->Compare(user_key_, ExtractUserKey(f->smallest_key)) <= 0); int cmp_smallest = user_comparator_->Compare(user_key_, ExtractUserKey(f->smallest_key)); if (cmp_smallest >= 0) { cmp_largest = user_comparator_->Compare(user_key_, ExtractUserKey(f->largest_key)); } // Setup file search bound for the next level based on the // comparison results if (curr_level_ > 0) { file_indexer_->GetNextLevelIndex(curr_level_, curr_index_in_curr_level_, cmp_smallest, cmp_largest, &search_left_bound_, &search_right_bound_); } // Key falls out of current file's range if (cmp_smallest < 0 || cmp_largest > 0) { if (curr_level_ == 0) { ++curr_index_in_curr_level_; continue; } else { // Search next level. break; } } } #ifndef NDEBUG // Sanity check to make sure that the files are correctly sorted if (prev_file_) { if (curr_level_ != 0) { int comp_sign = internal_comparator_->Compare( prev_file_->largest_key, f->smallest_key); assert(comp_sign < 0); } else { // level == 0, the current file cannot be newer than the previous // one. Use compressed data structure, has no attribute seqNo assert(curr_index_in_curr_level_ > 0); assert(!NewestFirstBySeqNo(files_[0][curr_index_in_curr_level_], files_[0][curr_index_in_curr_level_-1])); } } prev_file_ = f; #endif if (curr_level_ > 0 && cmp_largest < 0) { // No more files to search in this level. search_ended_ = !PrepareNextLevel(); } else { ++curr_index_in_curr_level_; } return f; } // Start searching next level. search_ended_ = !PrepareNextLevel(); } // Search ended. return nullptr; } private: unsigned int num_levels_; unsigned int curr_level_; int32_t search_left_bound_; int32_t search_right_bound_; #ifndef NDEBUG std::vector<FileMetaData*>* files_; #endif autovector<LevelFilesBrief>* level_files_brief_; bool search_ended_; LevelFilesBrief* curr_file_level_; unsigned int curr_index_in_curr_level_; unsigned int start_index_in_curr_level_; Slice user_key_; Slice ikey_; FileIndexer* file_indexer_; const Comparator* user_comparator_; const InternalKeyComparator* internal_comparator_; #ifndef NDEBUG FdWithKeyRange* prev_file_; #endif // Setup local variables to search next level. // Returns false if there are no more levels to search. bool PrepareNextLevel() { curr_level_++; while (curr_level_ < num_levels_) { curr_file_level_ = &(*level_files_brief_)[curr_level_]; if (curr_file_level_->num_files == 0) { // When current level is empty, the search bound generated from upper // level must be [0, -1] or [0, FileIndexer::kLevelMaxIndex] if it is // also empty. assert(search_left_bound_ == 0); assert(search_right_bound_ == -1 || search_right_bound_ == FileIndexer::kLevelMaxIndex); // Since current level is empty, it will need to search all files in // the next level search_left_bound_ = 0; search_right_bound_ = FileIndexer::kLevelMaxIndex; curr_level_++; continue; } // Some files may overlap each other. We find // all files that overlap user_key and process them in order from // newest to oldest. In the context of merge-operator, this can occur at // any level. Otherwise, it only occurs at Level-0 (since Put/Deletes // are always compacted into a single entry). int32_t start_index; if (curr_level_ == 0) { // On Level-0, we read through all files to check for overlap. start_index = 0; } else { // On Level-n (n>=1), files are sorted. Binary search to find the // earliest file whose largest key >= ikey. Search left bound and // right bound are used to narrow the range. if (search_left_bound_ == search_right_bound_) { start_index = search_left_bound_; } else if (search_left_bound_ < search_right_bound_) { if (search_right_bound_ == FileIndexer::kLevelMaxIndex) { search_right_bound_ = static_cast<int32_t>(curr_file_level_->num_files) - 1; } start_index = FindFileInRange(*internal_comparator_, *curr_file_level_, ikey_, static_cast<uint32_t>(search_left_bound_), static_cast<uint32_t>(search_right_bound_)); } else { // search_left_bound > search_right_bound, key does not exist in // this level. Since no comparision is done in this level, it will // need to search all files in the next level. search_left_bound_ = 0; search_right_bound_ = FileIndexer::kLevelMaxIndex; curr_level_++; continue; } } start_index_in_curr_level_ = start_index; curr_index_in_curr_level_ = start_index; #ifndef NDEBUG prev_file_ = nullptr; #endif return true; } // curr_level_ = num_levels_. So, no more levels to search. return false; } }; } // anonymous namespace VersionStorageInfo::~VersionStorageInfo() { delete[] files_; } Version::~Version() { assert(refs_ == 0); // Remove from linked list prev_->next_ = next_; next_->prev_ = prev_; // Drop references to files for (int level = 0; level < storage_info_.num_levels_; level++) { for (size_t i = 0; i < storage_info_.files_[level].size(); i++) { FileMetaData* f = storage_info_.files_[level][i]; assert(f->refs > 0); f->refs--; if (f->refs <= 0) { if (f->table_reader_handle) { cfd_->table_cache()->ReleaseHandle(f->table_reader_handle); f->table_reader_handle = nullptr; } vset_->obsolete_files_.push_back(f); } } } } int FindFile(const InternalKeyComparator& icmp, const LevelFilesBrief& file_level, const Slice& key) { return FindFileInRange(icmp, file_level, key, 0, static_cast<uint32_t>(file_level.num_files)); } void DoGenerateLevelFilesBrief(LevelFilesBrief* file_level, const std::vector<FileMetaData*>& files, Arena* arena) { assert(file_level); assert(files.size() >= 0); assert(arena); size_t num = files.size(); file_level->num_files = num; char* mem = arena->AllocateAligned(num * sizeof(FdWithKeyRange)); file_level->files = new (mem)FdWithKeyRange[num]; for (size_t i = 0; i < num; i++) { Slice smallest_key = files[i]->smallest.Encode(); Slice largest_key = files[i]->largest.Encode(); // Copy key slice to sequential memory size_t smallest_size = smallest_key.size(); size_t largest_size = largest_key.size(); mem = arena->AllocateAligned(smallest_size + largest_size); memcpy(mem, smallest_key.data(), smallest_size); memcpy(mem + smallest_size, largest_key.data(), largest_size); FdWithKeyRange& f = file_level->files[i]; f.fd = files[i]->fd; f.smallest_key = Slice(mem, smallest_size); f.largest_key = Slice(mem + smallest_size, largest_size); } } static bool AfterFile(const Comparator* ucmp, const Slice* user_key, const FdWithKeyRange* f) { // nullptr user_key occurs before all keys and is therefore never after *f return (user_key != nullptr && ucmp->Compare(*user_key, ExtractUserKey(f->largest_key)) > 0); } static bool BeforeFile(const Comparator* ucmp, const Slice* user_key, const FdWithKeyRange* f) { // nullptr user_key occurs after all keys and is therefore never before *f return (user_key != nullptr && ucmp->Compare(*user_key, ExtractUserKey(f->smallest_key)) < 0); } bool SomeFileOverlapsRange( const InternalKeyComparator& icmp, bool disjoint_sorted_files, const LevelFilesBrief& file_level, const Slice* smallest_user_key, const Slice* largest_user_key) { const Comparator* ucmp = icmp.user_comparator(); if (!disjoint_sorted_files) { // Need to check against all files for (size_t i = 0; i < file_level.num_files; i++) { const FdWithKeyRange* f = &(file_level.files[i]); if (AfterFile(ucmp, smallest_user_key, f) || BeforeFile(ucmp, largest_user_key, f)) { // No overlap } else { return true; // Overlap } } return false; } // Binary search over file list uint32_t index = 0; if (smallest_user_key != nullptr) { // Find the earliest possible internal key for smallest_user_key InternalKey small(*smallest_user_key, kMaxSequenceNumber,kValueTypeForSeek); index = FindFile(icmp, file_level, small.Encode()); } if (index >= file_level.num_files) { // beginning of range is after all files, so no overlap. return false; } return !BeforeFile(ucmp, largest_user_key, &file_level.files[index]); } namespace { // An internal iterator. For a given version/level pair, yields // information about the files in the level. For a given entry, key() // is the largest key that occurs in the file, and value() is an // 16-byte value containing the file number and file size, both // encoded using EncodeFixed64. class LevelFileNumIterator : public Iterator { public: LevelFileNumIterator(const InternalKeyComparator& icmp, const LevelFilesBrief* flevel) : icmp_(icmp), flevel_(flevel), index_(static_cast<uint32_t>(flevel->num_files)), current_value_(0, 0, 0) { // Marks as invalid } virtual bool Valid() const { return index_ < flevel_->num_files; } virtual void Seek(const Slice& target) { index_ = FindFile(icmp_, *flevel_, target); } virtual void SeekToFirst() { index_ = 0; } virtual void SeekToLast() { index_ = (flevel_->num_files == 0) ? 0 : static_cast<uint32_t>(flevel_->num_files) - 1; } virtual void Next() { assert(Valid()); index_++; } virtual void Prev() { assert(Valid()); if (index_ == 0) { index_ = static_cast<uint32_t>(flevel_->num_files); // Marks as invalid } else { index_--; } } Slice key() const { assert(Valid()); return flevel_->files[index_].largest_key; } Slice value() const { assert(Valid()); auto file_meta = flevel_->files[index_]; current_value_ = file_meta.fd; return Slice(reinterpret_cast<const char*>(&current_value_), sizeof(FileDescriptor)); } virtual Status status() const { return Status::OK(); } private: const InternalKeyComparator icmp_; const LevelFilesBrief* flevel_; uint32_t index_; mutable FileDescriptor current_value_; }; class LevelFileIteratorState : public TwoLevelIteratorState { public: LevelFileIteratorState(TableCache* table_cache, const ReadOptions& read_options, const EnvOptions& env_options, const InternalKeyComparator& icomparator, bool for_compaction, bool prefix_enabled) : TwoLevelIteratorState(prefix_enabled), table_cache_(table_cache), read_options_(read_options), env_options_(env_options), icomparator_(icomparator), for_compaction_(for_compaction) {} Iterator* NewSecondaryIterator(const Slice& meta_handle) override { if (meta_handle.size() != sizeof(FileDescriptor)) { return NewErrorIterator( Status::Corruption("FileReader invoked with unexpected value")); } else { const FileDescriptor* fd = reinterpret_cast<const FileDescriptor*>(meta_handle.data()); return table_cache_->NewIterator( read_options_, env_options_, icomparator_, *fd, nullptr /* don't need reference to table*/, for_compaction_); } } bool PrefixMayMatch(const Slice& internal_key) override { return true; } private: TableCache* table_cache_; const ReadOptions read_options_; const EnvOptions& env_options_; const InternalKeyComparator& icomparator_; bool for_compaction_; }; // A wrapper of version builder which references the current version in // constructor and unref it in the destructor. // Both of the constructor and destructor need to be called inside DB Mutex. class BaseReferencedVersionBuilder { public: explicit BaseReferencedVersionBuilder(ColumnFamilyData* cfd) : version_builder_(new VersionBuilder( cfd->current()->version_set()->env_options(), cfd->table_cache(), cfd->current()->storage_info())), version_(cfd->current()) { version_->Ref(); } ~BaseReferencedVersionBuilder() { delete version_builder_; version_->Unref(); } VersionBuilder* version_builder() { return version_builder_; } private: VersionBuilder* version_builder_; Version* version_; }; } // anonymous namespace Status Version::GetTableProperties(std::shared_ptr<const TableProperties>* tp, const FileMetaData* file_meta, const std::string* fname) { auto table_cache = cfd_->table_cache(); auto ioptions = cfd_->ioptions(); Status s = table_cache->GetTableProperties( vset_->env_options_, cfd_->internal_comparator(), file_meta->fd, tp, true /* no io */); if (s.ok()) { return s; } // We only ignore error type `Incomplete` since it's by design that we // disallow table when it's not in table cache. if (!s.IsIncomplete()) { return s; } // 2. Table is not present in table cache, we'll read the table properties // directly from the properties block in the file. std::unique_ptr<RandomAccessFile> file; if (fname != nullptr) { s = ioptions->env->NewRandomAccessFile( *fname, &file, vset_->env_options_); } else { s = ioptions->env->NewRandomAccessFile( TableFileName(vset_->db_options_->db_paths, file_meta->fd.GetNumber(), file_meta->fd.GetPathId()), &file, vset_->env_options_); } if (!s.ok()) { return s; } TableProperties* raw_table_properties; // By setting the magic number to kInvalidTableMagicNumber, we can by // pass the magic number check in the footer. s = ReadTableProperties( file.get(), file_meta->fd.GetFileSize(), Footer::kInvalidTableMagicNumber /* table's magic number */, vset_->env_, ioptions->info_log, &raw_table_properties); if (!s.ok()) { return s; } RecordTick(ioptions->statistics, NUMBER_DIRECT_LOAD_TABLE_PROPERTIES); *tp = std::shared_ptr<const TableProperties>(raw_table_properties); return s; } Status Version::GetPropertiesOfAllTables(TablePropertiesCollection* props) { for (int level = 0; level < storage_info_.num_levels_; level++) { for (const auto& file_meta : storage_info_.files_[level]) { auto fname = TableFileName(vset_->db_options_->db_paths, file_meta->fd.GetNumber(), file_meta->fd.GetPathId()); // 1. If the table is already present in table cache, load table // properties from there. std::shared_ptr<const TableProperties> table_properties; Status s = GetTableProperties(&table_properties, file_meta, &fname); if (s.ok()) { props->insert({fname, table_properties}); } else { return s; } } } return Status::OK(); } size_t Version::GetMemoryUsageByTableReaders() { size_t total_usage = 0; for (auto& file_level : storage_info_.level_files_brief_) { for (size_t i = 0; i < file_level.num_files; i++) { total_usage += cfd_->table_cache()->GetMemoryUsageByTableReader( vset_->env_options_, cfd_->internal_comparator(), file_level.files[i].fd); } } return total_usage; } void Version::GetColumnFamilyMetaData(ColumnFamilyMetaData* cf_meta) { assert(cf_meta); assert(cfd_); cf_meta->name = cfd_->GetName(); cf_meta->size = 0; cf_meta->file_count = 0; cf_meta->levels.clear(); auto* ioptions = cfd_->ioptions(); auto* vstorage = storage_info(); for (int level = 0; level < cfd_->NumberLevels(); level++) { uint64_t level_size = 0; cf_meta->file_count += vstorage->LevelFiles(level).size(); std::vector<SstFileMetaData> files; for (const auto& file : vstorage->LevelFiles(level)) { uint32_t path_id = file->fd.GetPathId(); std::string file_path; if (path_id < ioptions->db_paths.size()) { file_path = ioptions->db_paths[path_id].path; } else { assert(!ioptions->db_paths.empty()); file_path = ioptions->db_paths.back().path; } files.emplace_back( MakeTableFileName("", file->fd.GetNumber()), file_path, file->fd.GetFileSize(), file->smallest_seqno, file->largest_seqno, file->smallest.user_key().ToString(), file->largest.user_key().ToString(), file->being_compacted); level_size += file->fd.GetFileSize(); } cf_meta->levels.emplace_back( level, level_size, std::move(files)); cf_meta->size += level_size; } } uint64_t VersionStorageInfo::GetEstimatedActiveKeys() const { // Estimation will be not accurate when: // (1) there is merge keys // (2) keys are directly overwritten // (3) deletion on non-existing keys // (4) low number of samples if (num_samples_ == 0) { return 0; } uint64_t file_count = 0; for (int level = 0; level < num_levels_; ++level) { file_count += files_[level].size(); } if (num_samples_ < file_count) { // casting to avoid overflowing return static_cast<uint64_t>(static_cast<double>( accumulated_num_non_deletions_ - accumulated_num_deletions_) * static_cast<double>(file_count) / num_samples_); } else { return accumulated_num_non_deletions_ - accumulated_num_deletions_; } } void Version::AddIterators(const ReadOptions& read_options, const EnvOptions& soptions, MergeIteratorBuilder* merge_iter_builder) { assert(storage_info_.finalized_); if (storage_info_.num_non_empty_levels() == 0) { // No file in the Version. return; } // Merge all level zero files together since they may overlap for (size_t i = 0; i < storage_info_.LevelFilesBrief(0).num_files; i++) { const auto& file = storage_info_.LevelFilesBrief(0).files[i]; merge_iter_builder->AddIterator(cfd_->table_cache()->NewIterator( read_options, soptions, cfd_->internal_comparator(), file.fd, nullptr, false, merge_iter_builder->GetArena())); } // For levels > 0, we can use a concatenating iterator that sequentially // walks through the non-overlapping files in the level, opening them // lazily. for (int level = 1; level < storage_info_.num_non_empty_levels(); level++) { if (storage_info_.LevelFilesBrief(level).num_files != 0) { merge_iter_builder->AddIterator(NewTwoLevelIterator( new LevelFileIteratorState( cfd_->table_cache(), read_options, soptions, cfd_->internal_comparator(), false /* for_compaction */, cfd_->ioptions()->prefix_extractor != nullptr), new LevelFileNumIterator(cfd_->internal_comparator(), &storage_info_.LevelFilesBrief(level)), merge_iter_builder->GetArena())); } } } VersionStorageInfo::VersionStorageInfo( const InternalKeyComparator* internal_comparator, const Comparator* user_comparator, int levels, CompactionStyle compaction_style, VersionStorageInfo* ref_vstorage) : internal_comparator_(internal_comparator), user_comparator_(user_comparator), // cfd is nullptr if Version is dummy num_levels_(levels), num_non_empty_levels_(0), file_indexer_(user_comparator), compaction_style_(compaction_style), files_(new std::vector<FileMetaData*>[num_levels_]), files_by_size_(num_levels_), next_file_to_compact_by_size_(num_levels_), compaction_score_(num_levels_), compaction_level_(num_levels_), accumulated_file_size_(0), accumulated_raw_key_size_(0), accumulated_raw_value_size_(0), accumulated_num_non_deletions_(0), accumulated_num_deletions_(0), num_samples_(0), finalized_(false) { if (ref_vstorage != nullptr) { accumulated_file_size_ = ref_vstorage->accumulated_file_size_; accumulated_raw_key_size_ = ref_vstorage->accumulated_raw_key_size_; accumulated_raw_value_size_ = ref_vstorage->accumulated_raw_value_size_; accumulated_num_non_deletions_ = ref_vstorage->accumulated_num_non_deletions_; accumulated_num_deletions_ = ref_vstorage->accumulated_num_deletions_; num_samples_ = ref_vstorage->num_samples_; } } Version::Version(ColumnFamilyData* column_family_data, VersionSet* vset, uint64_t version_number) : cfd_(column_family_data), info_log_((cfd_ == nullptr) ? nullptr : cfd_->ioptions()->info_log), db_statistics_((cfd_ == nullptr) ? nullptr : cfd_->ioptions()->statistics), table_cache_((cfd_ == nullptr) ? nullptr : cfd_->table_cache()), merge_operator_((cfd_ == nullptr) ? nullptr : cfd_->ioptions()->merge_operator), storage_info_((cfd_ == nullptr) ? nullptr : &cfd_->internal_comparator(), (cfd_ == nullptr) ? nullptr : cfd_->user_comparator(), cfd_ == nullptr ? 0 : cfd_->NumberLevels(), cfd_ == nullptr ? kCompactionStyleLevel : cfd_->ioptions()->compaction_style, (cfd_ == nullptr || cfd_->current() == nullptr) ? nullptr : cfd_->current()->storage_info()), vset_(vset), next_(this), prev_(this), refs_(0), version_number_(version_number) {} void Version::Get(const ReadOptions& read_options, const LookupKey& k, std::string* value, Status* status, MergeContext* merge_context, bool* value_found) { Slice ikey = k.internal_key(); Slice user_key = k.user_key(); assert(status->ok() || status->IsMergeInProgress()); GetContext get_context( user_comparator(), merge_operator_, info_log_, db_statistics_, status->ok() ? GetContext::kNotFound : GetContext::kMerge, user_key, value, value_found, merge_context); FilePicker fp( storage_info_.files_, user_key, ikey, &storage_info_.level_files_brief_, storage_info_.num_non_empty_levels_, &storage_info_.file_indexer_, user_comparator(), internal_comparator()); FdWithKeyRange* f = fp.GetNextFile(); while (f != nullptr) { *status = table_cache_->Get(read_options, *internal_comparator(), f->fd, ikey, &get_context); // TODO: examine the behavior for corrupted key if (!status->ok()) { return; } switch (get_context.State()) { case GetContext::kNotFound: // Keep searching in other files break; case GetContext::kFound: return; case GetContext::kDeleted: // Use empty error message for speed *status = Status::NotFound(); return; case GetContext::kCorrupt: *status = Status::Corruption("corrupted key for ", user_key); return; case GetContext::kMerge: break; } f = fp.GetNextFile(); } if (GetContext::kMerge == get_context.State()) { if (!merge_operator_) { *status = Status::InvalidArgument( "merge_operator is not properly initialized."); return; } // merge_operands are in saver and we hit the beginning of the key history // do a final merge of nullptr and operands; if (merge_operator_->FullMerge(user_key, nullptr, merge_context->GetOperands(), value, info_log_)) { *status = Status::OK(); } else { RecordTick(db_statistics_, NUMBER_MERGE_FAILURES); *status = Status::Corruption("could not perform end-of-key merge for ", user_key); } } else { *status = Status::NotFound(); // Use an empty error message for speed } } void VersionStorageInfo::GenerateLevelFilesBrief() { level_files_brief_.resize(num_non_empty_levels_); for (int level = 0; level < num_non_empty_levels_; level++) { DoGenerateLevelFilesBrief( &level_files_brief_[level], files_[level], &arena_); } } void Version::PrepareApply(const MutableCFOptions& mutable_cf_options, std::vector<uint64_t>& size_being_compacted) { UpdateAccumulatedStats(); storage_info_.ComputeCompactionScore( mutable_cf_options, cfd_->ioptions()->compaction_options_fifo, size_being_compacted); storage_info_.UpdateFilesBySize(); storage_info_.UpdateNumNonEmptyLevels(); storage_info_.GenerateFileIndexer(); storage_info_.GenerateLevelFilesBrief(); } bool Version::MaybeInitializeFileMetaData(FileMetaData* file_meta) { if (file_meta->init_stats_from_file || file_meta->compensated_file_size > 0) { return false; } std::shared_ptr<const TableProperties> tp; Status s = GetTableProperties(&tp, file_meta); file_meta->init_stats_from_file = true; if (!s.ok()) { Log(InfoLogLevel::ERROR_LEVEL, vset_->db_options_->info_log, "Unable to load table properties for file %" PRIu64 " --- %s\n", file_meta->fd.GetNumber(), s.ToString().c_str()); return false; } if (tp.get() == nullptr) return false; file_meta->num_entries = tp->num_entries; file_meta->num_deletions = GetDeletedKeys(tp->user_collected_properties); file_meta->raw_value_size = tp->raw_value_size; file_meta->raw_key_size = tp->raw_key_size; return true; } void VersionStorageInfo::UpdateAccumulatedStats(FileMetaData* file_meta) { assert(file_meta->init_stats_from_file); accumulated_file_size_ += file_meta->fd.GetFileSize(); accumulated_raw_key_size_ += file_meta->raw_key_size; accumulated_raw_value_size_ += file_meta->raw_value_size; accumulated_num_non_deletions_ += file_meta->num_entries - file_meta->num_deletions; accumulated_num_deletions_ += file_meta->num_deletions; num_samples_++; } void Version::UpdateAccumulatedStats() { // maximum number of table properties loaded from files. const int kMaxInitCount = 20; int init_count = 0; // here only the first kMaxInitCount files which haven't been // initialized from file will be updated with num_deletions. // The motivation here is to cap the maximum I/O per Version creation. // The reason for choosing files from lower-level instead of higher-level // is that such design is able to propagate the initialization from // lower-level to higher-level: When the num_deletions of lower-level // files are updated, it will make the lower-level files have accurate // compensated_file_size, making lower-level to higher-level compaction // will be triggered, which creates higher-level files whose num_deletions // will be updated here. for (int level = 0; level < storage_info_.num_levels_ && init_count < kMaxInitCount; ++level) { for (auto* file_meta : storage_info_.files_[level]) { if (MaybeInitializeFileMetaData(file_meta)) { // each FileMeta will be initialized only once. storage_info_.UpdateAccumulatedStats(file_meta); if (++init_count >= kMaxInitCount) { break; } } } } // In case all sampled-files contain only deletion entries, then we // load the table-property of a file in higher-level to initialize // that value. for (int level = storage_info_.num_levels_ - 1; storage_info_.accumulated_raw_value_size_ == 0 && level >= 0; --level) { for (int i = static_cast<int>(storage_info_.files_[level].size()) - 1; storage_info_.accumulated_raw_value_size_ == 0 && i >= 0; --i) { if (MaybeInitializeFileMetaData(storage_info_.files_[level][i])) { storage_info_.UpdateAccumulatedStats(storage_info_.files_[level][i]); } } } storage_info_.ComputeCompensatedSizes(); } void VersionStorageInfo::ComputeCompensatedSizes() { static const int kDeletionWeightOnCompaction = 2; uint64_t average_value_size = GetAverageValueSize(); // compute the compensated size for (int level = 0; level < num_levels_; level++) { for (auto* file_meta : files_[level]) { // Here we only compute compensated_file_size for those file_meta // which compensated_file_size is uninitialized (== 0). if (file_meta->compensated_file_size == 0) { file_meta->compensated_file_size = file_meta->fd.GetFileSize() + file_meta->num_deletions * average_value_size * kDeletionWeightOnCompaction; } } } } int VersionStorageInfo::MaxInputLevel() const { if (compaction_style_ == kCompactionStyleLevel) { return num_levels() - 2; } return 0; } void VersionStorageInfo::ComputeCompactionScore( const MutableCFOptions& mutable_cf_options, const CompactionOptionsFIFO& compaction_options_fifo, std::vector<uint64_t>& size_being_compacted) { double max_score = 0; int max_score_level = 0; for (int level = 0; level <= MaxInputLevel(); level++) { double score; if (level == 0) { // We treat level-0 specially by bounding the number of files // instead of number of bytes for two reasons: // // (1) With larger write-buffer sizes, it is nice not to do too // many level-0 compactions. // // (2) The files in level-0 are merged on every read and // therefore we wish to avoid too many files when the individual // file size is small (perhaps because of a small write-buffer // setting, or very high compression ratios, or lots of // overwrites/deletions). int numfiles = 0; uint64_t total_size = 0; for (unsigned int i = 0; i < files_[level].size(); i++) { if (!files_[level][i]->being_compacted) { total_size += files_[level][i]->compensated_file_size; numfiles++; } } if (compaction_style_ == kCompactionStyleFIFO) { score = static_cast<double>(total_size) / compaction_options_fifo.max_table_files_size; } else if (numfiles >= mutable_cf_options.level0_stop_writes_trigger) { // If we are slowing down writes, then we better compact that first score = 1000000; } else if (numfiles >= mutable_cf_options.level0_slowdown_writes_trigger) { score = 10000; } else { score = static_cast<double>(numfiles) / mutable_cf_options.level0_file_num_compaction_trigger; } } else { // Compute the ratio of current size to size limit. const uint64_t level_bytes = TotalCompensatedFileSize(files_[level]) - size_being_compacted[level]; score = static_cast<double>(level_bytes) / mutable_cf_options.MaxBytesForLevel(level); if (max_score < score) { max_score = score; max_score_level = level; } } compaction_level_[level] = level; compaction_score_[level] = score; } // update the max compaction score in levels 1 to n-1 max_compaction_score_ = max_score; max_compaction_score_level_ = max_score_level; // sort all the levels based on their score. Higher scores get listed // first. Use bubble sort because the number of entries are small. for (int i = 0; i < num_levels() - 2; i++) { for (int j = i + 1; j < num_levels() - 1; j++) { if (compaction_score_[i] < compaction_score_[j]) { double score = compaction_score_[i]; int level = compaction_level_[i]; compaction_score_[i] = compaction_score_[j]; compaction_level_[i] = compaction_level_[j]; compaction_score_[j] = score; compaction_level_[j] = level; } } } } namespace { // used to sort files by size struct Fsize { int index; FileMetaData* file; }; // Compator that is used to sort files based on their size // In normal mode: descending size bool CompareCompensatedSizeDescending(const Fsize& first, const Fsize& second) { return (first.file->compensated_file_size > second.file->compensated_file_size); } } // anonymous namespace void VersionStorageInfo::AddFile(int level, FileMetaData* f) { assert(level < num_levels()); auto* level_files = &files_[level]; // Must not overlap assert(level <= 0 || level_files->empty() || internal_comparator_->Compare( (*level_files)[level_files->size() - 1]->largest, f->smallest) < 0); f->refs++; level_files->push_back(f); } void VersionStorageInfo::UpdateNumNonEmptyLevels() { num_non_empty_levels_ = num_levels_; for (int i = num_levels_ - 1; i >= 0; i--) { if (files_[i].size() != 0) { return; } else { num_non_empty_levels_ = i; } } } void VersionStorageInfo::UpdateFilesBySize() { if (compaction_style_ == kCompactionStyleFIFO || compaction_style_ == kCompactionStyleUniversal) { // don't need this return; } // No need to sort the highest level because it is never compacted. for (int level = 0; level < num_levels() - 1; level++) { const std::vector<FileMetaData*>& files = files_[level]; auto& files_by_size = files_by_size_[level]; assert(files_by_size.size() == 0); // populate a temp vector for sorting based on size std::vector<Fsize> temp(files.size()); for (unsigned int i = 0; i < files.size(); i++) { temp[i].index = i; temp[i].file = files[i]; } // sort the top number_of_files_to_sort_ based on file size size_t num = VersionStorageInfo::kNumberFilesToSort; if (num > temp.size()) { num = temp.size(); } std::partial_sort(temp.begin(), temp.begin() + num, temp.end(), CompareCompensatedSizeDescending); assert(temp.size() == files.size()); // initialize files_by_size_ for (unsigned int i = 0; i < temp.size(); i++) { files_by_size.push_back(temp[i].index); } next_file_to_compact_by_size_[level] = 0; assert(files_[level].size() == files_by_size_[level].size()); } } void Version::Ref() { ++refs_; } bool Version::Unref() { assert(refs_ >= 1); --refs_; if (refs_ == 0) { delete this; return true; } return false; } bool VersionStorageInfo::OverlapInLevel(int level, const Slice* smallest_user_key, const Slice* largest_user_key) { return SomeFileOverlapsRange(*internal_comparator_, (level > 0), level_files_brief_[level], smallest_user_key, largest_user_key); } int VersionStorageInfo::PickLevelForMemTableOutput( const MutableCFOptions& mutable_cf_options, const Slice& smallest_user_key, const Slice& largest_user_key) { int level = 0; if (!OverlapInLevel(0, &smallest_user_key, &largest_user_key)) { // Push to next level if there is no overlap in next level, // and the #bytes overlapping in the level after that are limited. InternalKey start(smallest_user_key, kMaxSequenceNumber, kValueTypeForSeek); InternalKey limit(largest_user_key, 0, static_cast<ValueType>(0)); std::vector<FileMetaData*> overlaps; while (mutable_cf_options.max_mem_compaction_level > 0 && level < mutable_cf_options.max_mem_compaction_level) { if (OverlapInLevel(level + 1, &smallest_user_key, &largest_user_key)) { break; } if (level + 2 >= num_levels_) { level++; break; } GetOverlappingInputs(level + 2, &start, &limit, &overlaps); const uint64_t sum = TotalFileSize(overlaps); if (sum > mutable_cf_options.MaxGrandParentOverlapBytes(level)) { break; } level++; } } return level; } // Store in "*inputs" all files in "level" that overlap [begin,end] // If hint_index is specified, then it points to a file in the // overlapping range. // The file_index returns a pointer to any file in an overlapping range. void VersionStorageInfo::GetOverlappingInputs( int level, const InternalKey* begin, const InternalKey* end, std::vector<FileMetaData*>* inputs, int hint_index, int* file_index) { inputs->clear(); Slice user_begin, user_end; if (begin != nullptr) { user_begin = begin->user_key(); } if (end != nullptr) { user_end = end->user_key(); } if (file_index) { *file_index = -1; } const Comparator* user_cmp = user_comparator_; if (begin != nullptr && end != nullptr && level > 0) { GetOverlappingInputsBinarySearch(level, user_begin, user_end, inputs, hint_index, file_index); return; } for (size_t i = 0; i < level_files_brief_[level].num_files; ) { FdWithKeyRange* f = &(level_files_brief_[level].files[i++]); const Slice file_start = ExtractUserKey(f->smallest_key); const Slice file_limit = ExtractUserKey(f->largest_key); if (begin != nullptr && user_cmp->Compare(file_limit, user_begin) < 0) { // "f" is completely before specified range; skip it } else if (end != nullptr && user_cmp->Compare(file_start, user_end) > 0) { // "f" is completely after specified range; skip it } else { inputs->push_back(files_[level][i-1]); if (level == 0) { // Level-0 files may overlap each other. So check if the newly // added file has expanded the range. If so, restart search. if (begin != nullptr && user_cmp->Compare(file_start, user_begin) < 0) { user_begin = file_start; inputs->clear(); i = 0; } else if (end != nullptr && user_cmp->Compare(file_limit, user_end) > 0) { user_end = file_limit; inputs->clear(); i = 0; } } else if (file_index) { *file_index = static_cast<int>(i) - 1; } } } } // Store in "*inputs" all files in "level" that overlap [begin,end] // Employ binary search to find at least one file that overlaps the // specified range. From that file, iterate backwards and // forwards to find all overlapping files. void VersionStorageInfo::GetOverlappingInputsBinarySearch( int level, const Slice& user_begin, const Slice& user_end, std::vector<FileMetaData*>* inputs, int hint_index, int* file_index) { assert(level > 0); int min = 0; int mid = 0; int max = static_cast<int>(files_[level].size()) - 1; bool foundOverlap = false; const Comparator* user_cmp = user_comparator_; // if the caller already knows the index of a file that has overlap, // then we can skip the binary search. if (hint_index != -1) { mid = hint_index; foundOverlap = true; } while (!foundOverlap && min <= max) { mid = (min + max)/2; FdWithKeyRange* f = &(level_files_brief_[level].files[mid]); const Slice file_start = ExtractUserKey(f->smallest_key); const Slice file_limit = ExtractUserKey(f->largest_key); if (user_cmp->Compare(file_limit, user_begin) < 0) { min = mid + 1; } else if (user_cmp->Compare(user_end, file_start) < 0) { max = mid - 1; } else { foundOverlap = true; break; } } // If there were no overlapping files, return immediately. if (!foundOverlap) { return; } // returns the index where an overlap is found if (file_index) { *file_index = mid; } ExtendOverlappingInputs(level, user_begin, user_end, inputs, mid); } // Store in "*inputs" all files in "level" that overlap [begin,end] // The midIndex specifies the index of at least one file that // overlaps the specified range. From that file, iterate backward // and forward to find all overlapping files. // Use FileLevel in searching, make it faster void VersionStorageInfo::ExtendOverlappingInputs( int level, const Slice& user_begin, const Slice& user_end, std::vector<FileMetaData*>* inputs, unsigned int midIndex) { const Comparator* user_cmp = user_comparator_; const FdWithKeyRange* files = level_files_brief_[level].files; #ifndef NDEBUG { // assert that the file at midIndex overlaps with the range assert(midIndex < level_files_brief_[level].num_files); const FdWithKeyRange* f = &files[midIndex]; const Slice fstart = ExtractUserKey(f->smallest_key); const Slice flimit = ExtractUserKey(f->largest_key); if (user_cmp->Compare(fstart, user_begin) >= 0) { assert(user_cmp->Compare(fstart, user_end) <= 0); } else { assert(user_cmp->Compare(flimit, user_begin) >= 0); } } #endif int startIndex = midIndex + 1; int endIndex = midIndex; int count __attribute__((unused)) = 0; // check backwards from 'mid' to lower indices for (int i = midIndex; i >= 0 ; i--) { const FdWithKeyRange* f = &files[i]; const Slice file_limit = ExtractUserKey(f->largest_key); if (user_cmp->Compare(file_limit, user_begin) >= 0) { startIndex = i; assert((count++, true)); } else { break; } } // check forward from 'mid+1' to higher indices for (unsigned int i = midIndex+1; i < level_files_brief_[level].num_files; i++) { const FdWithKeyRange* f = &files[i]; const Slice file_start = ExtractUserKey(f->smallest_key); if (user_cmp->Compare(file_start, user_end) <= 0) { assert((count++, true)); endIndex = i; } else { break; } } assert(count == endIndex - startIndex + 1); // insert overlapping files into vector for (int i = startIndex; i <= endIndex; i++) { FileMetaData* f = files_[level][i]; inputs->push_back(f); } } // Returns true iff the first or last file in inputs contains // an overlapping user key to the file "just outside" of it (i.e. // just after the last file, or just before the first file) // REQUIRES: "*inputs" is a sorted list of non-overlapping files bool VersionStorageInfo::HasOverlappingUserKey( const std::vector<FileMetaData*>* inputs, int level) { // If inputs empty, there is no overlap. // If level == 0, it is assumed that all needed files were already included. if (inputs->empty() || level == 0){ return false; } const Comparator* user_cmp = user_comparator_; const rocksdb::LevelFilesBrief& file_level = level_files_brief_[level]; const FdWithKeyRange* files = level_files_brief_[level].files; const size_t kNumFiles = file_level.num_files; // Check the last file in inputs against the file after it size_t last_file = FindFile(*internal_comparator_, file_level, inputs->back()->largest.Encode()); assert(last_file < kNumFiles); // File should exist! if (last_file < kNumFiles-1) { // If not the last file const Slice last_key_in_input = ExtractUserKey( files[last_file].largest_key); const Slice first_key_after = ExtractUserKey( files[last_file+1].smallest_key); if (user_cmp->Compare(last_key_in_input, first_key_after) == 0) { // The last user key in input overlaps with the next file's first key return true; } } // Check the first file in inputs against the file just before it size_t first_file = FindFile(*internal_comparator_, file_level, inputs->front()->smallest.Encode()); assert(first_file <= last_file); // File should exist! if (first_file > 0) { // If not first file const Slice& first_key_in_input = ExtractUserKey( files[first_file].smallest_key); const Slice& last_key_before = ExtractUserKey( files[first_file-1].largest_key); if (user_cmp->Compare(first_key_in_input, last_key_before) == 0) { // The first user key in input overlaps with the previous file's last key return true; } } return false; } uint64_t VersionStorageInfo::NumLevelBytes(int level) const { assert(level >= 0); assert(level < num_levels()); return TotalFileSize(files_[level]); } const char* VersionStorageInfo::LevelSummary( LevelSummaryStorage* scratch) const { int len = snprintf(scratch->buffer, sizeof(scratch->buffer), "files["); for (int i = 0; i < num_levels(); i++) { int sz = sizeof(scratch->buffer) - len; int ret = snprintf(scratch->buffer + len, sz, "%d ", int(files_[i].size())); if (ret < 0 || ret >= sz) break; len += ret; } if (len > 0) { // overwrite the last space --len; } snprintf(scratch->buffer + len, sizeof(scratch->buffer) - len, "]"); return scratch->buffer; } const char* VersionStorageInfo::LevelFileSummary(FileSummaryStorage* scratch, int level) const { int len = snprintf(scratch->buffer, sizeof(scratch->buffer), "files_size["); for (const auto& f : files_[level]) { int sz = sizeof(scratch->buffer) - len; char sztxt[16]; AppendHumanBytes(f->fd.GetFileSize(), sztxt, sizeof(sztxt)); int ret = snprintf(scratch->buffer + len, sz, "#%" PRIu64 "(seq=%" PRIu64 ",sz=%s,%d) ", f->fd.GetNumber(), f->smallest_seqno, sztxt, static_cast<int>(f->being_compacted)); if (ret < 0 || ret >= sz) break; len += ret; } // overwrite the last space (only if files_[level].size() is non-zero) if (files_[level].size() && len > 0) { --len; } snprintf(scratch->buffer + len, sizeof(scratch->buffer) - len, "]"); return scratch->buffer; } int64_t VersionStorageInfo::MaxNextLevelOverlappingBytes() { uint64_t result = 0; std::vector<FileMetaData*> overlaps; for (int level = 1; level < num_levels() - 1; level++) { for (const auto& f : files_[level]) { GetOverlappingInputs(level + 1, &f->smallest, &f->largest, &overlaps); const uint64_t sum = TotalFileSize(overlaps); if (sum > result) { result = sum; } } } return result; } void Version::AddLiveFiles(std::vector<FileDescriptor>* live) { for (int level = 0; level < storage_info_.num_levels(); level++) { const std::vector<FileMetaData*>& files = storage_info_.files_[level]; for (const auto& file : files) { live->push_back(file->fd); } } } std::string Version::DebugString(bool hex) const { std::string r; for (int level = 0; level < storage_info_.num_levels_; level++) { // E.g., // --- level 1 --- // 17:123['a' .. 'd'] // 20:43['e' .. 'g'] r.append("--- level "); AppendNumberTo(&r, level); r.append(" --- version# "); AppendNumberTo(&r, version_number_); r.append(" ---\n"); const std::vector<FileMetaData*>& files = storage_info_.files_[level]; for (size_t i = 0; i < files.size(); i++) { r.push_back(' '); AppendNumberTo(&r, files[i]->fd.GetNumber()); r.push_back(':'); AppendNumberTo(&r, files[i]->fd.GetFileSize()); r.append("["); r.append(files[i]->smallest.DebugString(hex)); r.append(" .. "); r.append(files[i]->largest.DebugString(hex)); r.append("]\n"); } } return r; } // this is used to batch writes to the manifest file struct VersionSet::ManifestWriter { Status status; bool done; port::CondVar cv; ColumnFamilyData* cfd; VersionEdit* edit; explicit ManifestWriter(port::Mutex* mu, ColumnFamilyData* _cfd, VersionEdit* e) : done(false), cv(mu), cfd(_cfd), edit(e) {} }; VersionSet::VersionSet(const std::string& dbname, const DBOptions* db_options, const EnvOptions& storage_options, Cache* table_cache, WriteController* write_controller) : column_family_set_(new ColumnFamilySet( dbname, db_options, storage_options, table_cache, write_controller)), env_(db_options->env), dbname_(dbname), db_options_(db_options), next_file_number_(2), manifest_file_number_(0), // Filled by Recover() pending_manifest_file_number_(0), last_sequence_(0), prev_log_number_(0), current_version_number_(0), manifest_file_size_(0), env_options_(storage_options), env_options_compactions_(env_options_) {} VersionSet::~VersionSet() { // we need to delete column_family_set_ because its destructor depends on // VersionSet column_family_set_.reset(); for (auto file : obsolete_files_) { delete file; } obsolete_files_.clear(); } void VersionSet::AppendVersion(ColumnFamilyData* column_family_data, Version* v) { // Mark v finalized v->storage_info_.SetFinalized(); // Make "v" current assert(v->refs_ == 0); Version* current = column_family_data->current(); assert(v != current); if (current != nullptr) { assert(current->refs_ > 0); current->Unref(); } column_family_data->SetCurrent(v); v->Ref(); // Append to linked list v->prev_ = column_family_data->dummy_versions()->prev_; v->next_ = column_family_data->dummy_versions(); v->prev_->next_ = v; v->next_->prev_ = v; } Status VersionSet::LogAndApply(ColumnFamilyData* column_family_data, const MutableCFOptions& mutable_cf_options, VersionEdit* edit, port::Mutex* mu, Directory* db_directory, bool new_descriptor_log, const ColumnFamilyOptions* new_cf_options) { mu->AssertHeld(); // column_family_data can be nullptr only if this is column_family_add. // in that case, we also need to specify ColumnFamilyOptions if (column_family_data == nullptr) { assert(edit->is_column_family_add_); assert(new_cf_options != nullptr); } // queue our request ManifestWriter w(mu, column_family_data, edit); manifest_writers_.push_back(&w); while (!w.done && &w != manifest_writers_.front()) { w.cv.Wait(); } if (w.done) { return w.status; } if (column_family_data != nullptr && column_family_data->IsDropped()) { // if column family is dropped by the time we get here, no need to write // anything to the manifest manifest_writers_.pop_front(); // Notify new head of write queue if (!manifest_writers_.empty()) { manifest_writers_.front()->cv.Signal(); } return Status::OK(); } std::vector<VersionEdit*> batch_edits; Version* v = nullptr; std::unique_ptr<BaseReferencedVersionBuilder> builder_guard(nullptr); // process all requests in the queue ManifestWriter* last_writer = &w; assert(!manifest_writers_.empty()); assert(manifest_writers_.front() == &w); if (edit->IsColumnFamilyManipulation()) { // no group commits for column family add or drop LogAndApplyCFHelper(edit); batch_edits.push_back(edit); } else { v = new Version(column_family_data, this, current_version_number_++); builder_guard.reset(new BaseReferencedVersionBuilder(column_family_data)); auto* builder = builder_guard->version_builder(); for (const auto& writer : manifest_writers_) { if (writer->edit->IsColumnFamilyManipulation() || writer->cfd->GetID() != column_family_data->GetID()) { // no group commits for column family add or drop // also, group commits across column families are not supported break; } last_writer = writer; LogAndApplyHelper(column_family_data, builder, v, last_writer->edit, mu); batch_edits.push_back(last_writer->edit); } builder->SaveTo(v->storage_info()); } // Initialize new descriptor log file if necessary by creating // a temporary file that contains a snapshot of the current version. uint64_t new_manifest_file_size = 0; Status s; assert(pending_manifest_file_number_ == 0); if (!descriptor_log_ || manifest_file_size_ > db_options_->max_manifest_file_size) { pending_manifest_file_number_ = NewFileNumber(); batch_edits.back()->SetNextFile(next_file_number_.load()); new_descriptor_log = true; } else { pending_manifest_file_number_ = manifest_file_number_; } if (new_descriptor_log) { // if we're writing out new snapshot make sure to persist max column family if (column_family_set_->GetMaxColumnFamily() > 0) { edit->SetMaxColumnFamily(column_family_set_->GetMaxColumnFamily()); } } // Unlock during expensive operations. New writes cannot get here // because &w is ensuring that all new writes get queued. { std::vector<uint64_t> size_being_compacted; if (!edit->IsColumnFamilyManipulation()) { size_being_compacted.resize(v->storage_info()->num_levels() - 1); // calculate the amount of data being compacted at every level column_family_data->compaction_picker()->SizeBeingCompacted( size_being_compacted); } mu->Unlock(); if (!edit->IsColumnFamilyManipulation() && db_options_->max_open_files == -1) { // unlimited table cache. Pre-load table handle now. // Need to do it out of the mutex. builder_guard->version_builder()->LoadTableHandlers(); } // This is fine because everything inside of this block is serialized -- // only one thread can be here at the same time if (new_descriptor_log) { // create manifest file Log(InfoLogLevel::INFO_LEVEL, db_options_->info_log, "Creating manifest %" PRIu64 "\n", pending_manifest_file_number_); unique_ptr<WritableFile> descriptor_file; s = env_->NewWritableFile( DescriptorFileName(dbname_, pending_manifest_file_number_), &descriptor_file, env_->OptimizeForManifestWrite(env_options_)); if (s.ok()) { descriptor_file->SetPreallocationBlockSize( db_options_->manifest_preallocation_size); descriptor_log_.reset(new log::Writer(std::move(descriptor_file))); s = WriteSnapshot(descriptor_log_.get()); } } if (!edit->IsColumnFamilyManipulation()) { // This is cpu-heavy operations, which should be called outside mutex. v->PrepareApply(mutable_cf_options, size_being_compacted); } // Write new record to MANIFEST log if (s.ok()) { for (auto& e : batch_edits) { std::string record; if (!e->EncodeTo(&record)) { s = Status::Corruption( "Unable to Encode VersionEdit:" + e->DebugString(true)); break; } s = descriptor_log_->AddRecord(record); if (!s.ok()) { break; } } if (s.ok() && db_options_->disableDataSync == false) { if (db_options_->use_fsync) { StopWatch sw(env_, db_options_->statistics.get(), MANIFEST_FILE_SYNC_MICROS); s = descriptor_log_->file()->Fsync(); } else { StopWatch sw(env_, db_options_->statistics.get(), MANIFEST_FILE_SYNC_MICROS); s = descriptor_log_->file()->Sync(); } } if (!s.ok()) { Log(InfoLogLevel::ERROR_LEVEL, db_options_->info_log, "MANIFEST write: %s\n", s.ToString().c_str()); bool all_records_in = true; for (auto& e : batch_edits) { std::string record; if (!e->EncodeTo(&record)) { s = Status::Corruption( "Unable to Encode VersionEdit:" + e->DebugString(true)); all_records_in = false; break; } if (!ManifestContains(pending_manifest_file_number_, record)) { all_records_in = false; break; } } if (all_records_in) { Log(InfoLogLevel::WARN_LEVEL, db_options_->info_log, "MANIFEST contains log record despite error; advancing to new " "version to prevent mismatch between in-memory and logged state" " If paranoid is set, then the db is now in readonly mode."); s = Status::OK(); } } } // If we just created a new descriptor file, install it by writing a // new CURRENT file that points to it. if (s.ok() && new_descriptor_log) { s = SetCurrentFile(env_, dbname_, pending_manifest_file_number_, db_options_->disableDataSync ? nullptr : db_directory); if (s.ok() && pending_manifest_file_number_ > manifest_file_number_) { // delete old manifest file Log(InfoLogLevel::INFO_LEVEL, db_options_->info_log, "Deleting manifest %" PRIu64 " current manifest %" PRIu64 "\n", manifest_file_number_, pending_manifest_file_number_); // we don't care about an error here, PurgeObsoleteFiles will take care // of it later env_->DeleteFile(DescriptorFileName(dbname_, manifest_file_number_)); } } if (s.ok()) { // find offset in manifest file where this version is stored. new_manifest_file_size = descriptor_log_->file()->GetFileSize(); } LogFlush(db_options_->info_log); mu->Lock(); } // Install the new version if (s.ok()) { if (edit->is_column_family_add_) { // no group commit on column family add assert(batch_edits.size() == 1); assert(new_cf_options != nullptr); CreateColumnFamily(*new_cf_options, edit); } else if (edit->is_column_family_drop_) { assert(batch_edits.size() == 1); column_family_data->SetDropped(); if (column_family_data->Unref()) { delete column_family_data; } } else { uint64_t max_log_number_in_batch = 0; for (auto& e : batch_edits) { if (e->has_log_number_) { max_log_number_in_batch = std::max(max_log_number_in_batch, e->log_number_); } } if (max_log_number_in_batch != 0) { assert(column_family_data->GetLogNumber() <= max_log_number_in_batch); column_family_data->SetLogNumber(max_log_number_in_batch); } AppendVersion(column_family_data, v); } manifest_file_number_ = pending_manifest_file_number_; manifest_file_size_ = new_manifest_file_size; prev_log_number_ = edit->prev_log_number_; } else { Log(InfoLogLevel::ERROR_LEVEL, db_options_->info_log, "Error in committing version %lu to [%s]", (unsigned long)v->GetVersionNumber(), column_family_data->GetName().c_str()); delete v; if (new_descriptor_log) { Log(InfoLogLevel::INFO_LEVEL, db_options_->info_log, "Deleting manifest %" PRIu64 " current manifest %" PRIu64 "\n", manifest_file_number_, pending_manifest_file_number_); descriptor_log_.reset(); env_->DeleteFile( DescriptorFileName(dbname_, pending_manifest_file_number_)); } } pending_manifest_file_number_ = 0; // wake up all the waiting writers while (true) { ManifestWriter* ready = manifest_writers_.front(); manifest_writers_.pop_front(); if (ready != &w) { ready->status = s; ready->done = true; ready->cv.Signal(); } if (ready == last_writer) break; } // Notify new head of write queue if (!manifest_writers_.empty()) { manifest_writers_.front()->cv.Signal(); } return s; } void VersionSet::LogAndApplyCFHelper(VersionEdit* edit) { assert(edit->IsColumnFamilyManipulation()); edit->SetNextFile(next_file_number_.load()); edit->SetLastSequence(last_sequence_); if (edit->is_column_family_drop_) { // if we drop column family, we have to make sure to save max column family, // so that we don't reuse existing ID edit->SetMaxColumnFamily(column_family_set_->GetMaxColumnFamily()); } } void VersionSet::LogAndApplyHelper(ColumnFamilyData* cfd, VersionBuilder* builder, Version* v, VersionEdit* edit, port::Mutex* mu) { mu->AssertHeld(); assert(!edit->IsColumnFamilyManipulation()); if (edit->has_log_number_) { assert(edit->log_number_ >= cfd->GetLogNumber()); assert(edit->log_number_ < next_file_number_.load()); } if (!edit->has_prev_log_number_) { edit->SetPrevLogNumber(prev_log_number_); } edit->SetNextFile(next_file_number_.load()); edit->SetLastSequence(last_sequence_); builder->Apply(edit); } Status VersionSet::Recover( const std::vector<ColumnFamilyDescriptor>& column_families, bool read_only) { std::unordered_map<std::string, ColumnFamilyOptions> cf_name_to_options; for (auto cf : column_families) { cf_name_to_options.insert({cf.name, cf.options}); } // keeps track of column families in manifest that were not found in // column families parameters. if those column families are not dropped // by subsequent manifest records, Recover() will return failure status std::unordered_map<int, std::string> column_families_not_found; // Read "CURRENT" file, which contains a pointer to the current manifest file std::string manifest_filename; Status s = ReadFileToString( env_, CurrentFileName(dbname_), &manifest_filename ); if (!s.ok()) { return s; } if (manifest_filename.empty() || manifest_filename.back() != '\n') { return Status::Corruption("CURRENT file does not end with newline"); } // remove the trailing '\n' manifest_filename.resize(manifest_filename.size() - 1); FileType type; bool parse_ok = ParseFileName(manifest_filename, &manifest_file_number_, &type); if (!parse_ok || type != kDescriptorFile) { return Status::Corruption("CURRENT file corrupted"); } Log(InfoLogLevel::INFO_LEVEL, db_options_->info_log, "Recovering from manifest file: %s\n", manifest_filename.c_str()); manifest_filename = dbname_ + "/" + manifest_filename; unique_ptr<SequentialFile> manifest_file; s = env_->NewSequentialFile(manifest_filename, &manifest_file, env_options_); if (!s.ok()) { return s; } uint64_t current_manifest_file_size; s = env_->GetFileSize(manifest_filename, &current_manifest_file_size); if (!s.ok()) { return s; } bool have_log_number = false; bool have_prev_log_number = false; bool have_next_file = false; bool have_last_sequence = false; uint64_t next_file = 0; uint64_t last_sequence = 0; uint64_t log_number = 0; uint64_t previous_log_number = 0; uint32_t max_column_family = 0; std::unordered_map<uint32_t, BaseReferencedVersionBuilder*> builders; // add default column family auto default_cf_iter = cf_name_to_options.find(kDefaultColumnFamilyName); if (default_cf_iter == cf_name_to_options.end()) { return Status::InvalidArgument("Default column family not specified"); } VersionEdit default_cf_edit; default_cf_edit.AddColumnFamily(kDefaultColumnFamilyName); default_cf_edit.SetColumnFamily(0); ColumnFamilyData* default_cfd = CreateColumnFamily(default_cf_iter->second, &default_cf_edit); builders.insert({0, new BaseReferencedVersionBuilder(default_cfd)}); { VersionSet::LogReporter reporter; reporter.status = &s; log::Reader reader(std::move(manifest_file), &reporter, true /*checksum*/, 0 /*initial_offset*/); Slice record; std::string scratch; while (reader.ReadRecord(&record, &scratch) && s.ok()) { VersionEdit edit; s = edit.DecodeFrom(record); if (!s.ok()) { break; } // Not found means that user didn't supply that column // family option AND we encountered column family add // record. Once we encounter column family drop record, // we will delete the column family from // column_families_not_found. bool cf_in_not_found = column_families_not_found.find(edit.column_family_) != column_families_not_found.end(); // in builders means that user supplied that column family // option AND that we encountered column family add record bool cf_in_builders = builders.find(edit.column_family_) != builders.end(); // they can't both be true assert(!(cf_in_not_found && cf_in_builders)); ColumnFamilyData* cfd = nullptr; if (edit.is_column_family_add_) { if (cf_in_builders || cf_in_not_found) { s = Status::Corruption( "Manifest adding the same column family twice"); break; } auto cf_options = cf_name_to_options.find(edit.column_family_name_); if (cf_options == cf_name_to_options.end()) { column_families_not_found.insert( {edit.column_family_, edit.column_family_name_}); } else { cfd = CreateColumnFamily(cf_options->second, &edit); builders.insert( {edit.column_family_, new BaseReferencedVersionBuilder(cfd)}); } } else if (edit.is_column_family_drop_) { if (cf_in_builders) { auto builder = builders.find(edit.column_family_); assert(builder != builders.end()); delete builder->second; builders.erase(builder); cfd = column_family_set_->GetColumnFamily(edit.column_family_); if (cfd->Unref()) { delete cfd; cfd = nullptr; } else { // who else can have reference to cfd!? assert(false); } } else if (cf_in_not_found) { column_families_not_found.erase(edit.column_family_); } else { s = Status::Corruption( "Manifest - dropping non-existing column family"); break; } } else if (!cf_in_not_found) { if (!cf_in_builders) { s = Status::Corruption( "Manifest record referencing unknown column family"); break; } cfd = column_family_set_->GetColumnFamily(edit.column_family_); // this should never happen since cf_in_builders is true assert(cfd != nullptr); if (edit.max_level_ >= cfd->current()->storage_info()->num_levels()) { s = Status::InvalidArgument( "db has more levels than options.num_levels"); break; } // if it is not column family add or column family drop, // then it's a file add/delete, which should be forwarded // to builder auto builder = builders.find(edit.column_family_); assert(builder != builders.end()); builder->second->version_builder()->Apply(&edit); } if (cfd != nullptr) { if (edit.has_log_number_) { if (cfd->GetLogNumber() > edit.log_number_) { Log(InfoLogLevel::WARN_LEVEL, db_options_->info_log, "MANIFEST corruption detected, but ignored - Log numbers in " "records NOT monotonically increasing"); } else { cfd->SetLogNumber(edit.log_number_); have_log_number = true; } } if (edit.has_comparator_ && edit.comparator_ != cfd->user_comparator()->Name()) { s = Status::InvalidArgument( cfd->user_comparator()->Name(), "does not match existing comparator " + edit.comparator_); break; } } if (edit.has_prev_log_number_) { previous_log_number = edit.prev_log_number_; have_prev_log_number = true; } if (edit.has_next_file_number_) { next_file = edit.next_file_number_; have_next_file = true; } if (edit.has_max_column_family_) { max_column_family = edit.max_column_family_; } if (edit.has_last_sequence_) { last_sequence = edit.last_sequence_; have_last_sequence = true; } } } if (s.ok()) { if (!have_next_file) { s = Status::Corruption("no meta-nextfile entry in descriptor"); } else if (!have_log_number) { s = Status::Corruption("no meta-lognumber entry in descriptor"); } else if (!have_last_sequence) { s = Status::Corruption("no last-sequence-number entry in descriptor"); } if (!have_prev_log_number) { previous_log_number = 0; } column_family_set_->UpdateMaxColumnFamily(max_column_family); MarkFileNumberUsedDuringRecovery(previous_log_number); MarkFileNumberUsedDuringRecovery(log_number); } // there were some column families in the MANIFEST that weren't specified // in the argument. This is OK in read_only mode if (read_only == false && !column_families_not_found.empty()) { std::string list_of_not_found; for (const auto& cf : column_families_not_found) { list_of_not_found += ", " + cf.second; } list_of_not_found = list_of_not_found.substr(2); s = Status::InvalidArgument( "You have to open all column families. Column families not opened: " + list_of_not_found); } if (s.ok()) { for (auto cfd : *column_family_set_) { auto builders_iter = builders.find(cfd->GetID()); assert(builders_iter != builders.end()); auto* builder = builders_iter->second->version_builder(); if (db_options_->max_open_files == -1) { // unlimited table cache. Pre-load table handle now. // Need to do it out of the mutex. builder->LoadTableHandlers(); } Version* v = new Version(cfd, this, current_version_number_++); builder->SaveTo(v->storage_info()); // Install recovered version std::vector<uint64_t> size_being_compacted( v->storage_info()->num_levels() - 1); cfd->compaction_picker()->SizeBeingCompacted(size_being_compacted); v->PrepareApply(*cfd->GetLatestMutableCFOptions(), size_being_compacted); AppendVersion(cfd, v); } manifest_file_size_ = current_manifest_file_size; next_file_number_.store(next_file + 1); last_sequence_ = last_sequence; prev_log_number_ = previous_log_number; Log(InfoLogLevel::INFO_LEVEL, db_options_->info_log, "Recovered from manifest file:%s succeeded," "manifest_file_number is %lu, next_file_number is %lu, " "last_sequence is %lu, log_number is %lu," "prev_log_number is %lu," "max_column_family is %u\n", manifest_filename.c_str(), (unsigned long)manifest_file_number_, (unsigned long)next_file_number_.load(), (unsigned long)last_sequence_, (unsigned long)log_number, (unsigned long)prev_log_number_, column_family_set_->GetMaxColumnFamily()); for (auto cfd : *column_family_set_) { Log(InfoLogLevel::INFO_LEVEL, db_options_->info_log, "Column family [%s] (ID %u), log number is %" PRIu64 "\n", cfd->GetName().c_str(), cfd->GetID(), cfd->GetLogNumber()); } } for (auto builder : builders) { delete builder.second; } return s; } Status VersionSet::ListColumnFamilies(std::vector<std::string>* column_families, const std::string& dbname, Env* env) { // these are just for performance reasons, not correcntes, // so we're fine using the defaults EnvOptions soptions; // Read "CURRENT" file, which contains a pointer to the current manifest file std::string current; Status s = ReadFileToString(env, CurrentFileName(dbname), &current); if (!s.ok()) { return s; } if (current.empty() || current[current.size()-1] != '\n') { return Status::Corruption("CURRENT file does not end with newline"); } current.resize(current.size() - 1); std::string dscname = dbname + "/" + current; unique_ptr<SequentialFile> file; s = env->NewSequentialFile(dscname, &file, soptions); if (!s.ok()) { return s; } std::map<uint32_t, std::string> column_family_names; // default column family is always implicitly there column_family_names.insert({0, kDefaultColumnFamilyName}); VersionSet::LogReporter reporter; reporter.status = &s; log::Reader reader(std::move(file), &reporter, true /*checksum*/, 0 /*initial_offset*/); Slice record; std::string scratch; while (reader.ReadRecord(&record, &scratch) && s.ok()) { VersionEdit edit; s = edit.DecodeFrom(record); if (!s.ok()) { break; } if (edit.is_column_family_add_) { if (column_family_names.find(edit.column_family_) != column_family_names.end()) { s = Status::Corruption("Manifest adding the same column family twice"); break; } column_family_names.insert( {edit.column_family_, edit.column_family_name_}); } else if (edit.is_column_family_drop_) { if (column_family_names.find(edit.column_family_) == column_family_names.end()) { s = Status::Corruption( "Manifest - dropping non-existing column family"); break; } column_family_names.erase(edit.column_family_); } } column_families->clear(); if (s.ok()) { for (const auto& iter : column_family_names) { column_families->push_back(iter.second); } } return s; } #ifndef ROCKSDB_LITE Status VersionSet::ReduceNumberOfLevels(const std::string& dbname, const Options* options, const EnvOptions& env_options, int new_levels) { if (new_levels <= 1) { return Status::InvalidArgument( "Number of levels needs to be bigger than 1"); } ColumnFamilyOptions cf_options(*options); std::shared_ptr<Cache> tc(NewLRUCache( options->max_open_files - 10, options->table_cache_numshardbits, options->table_cache_remove_scan_count_limit)); WriteController wc; VersionSet versions(dbname, options, env_options, tc.get(), &wc); Status status; std::vector<ColumnFamilyDescriptor> dummy; ColumnFamilyDescriptor dummy_descriptor(kDefaultColumnFamilyName, ColumnFamilyOptions(*options)); dummy.push_back(dummy_descriptor); status = versions.Recover(dummy); if (!status.ok()) { return status; } Version* current_version = versions.GetColumnFamilySet()->GetDefault()->current(); auto* vstorage = current_version->storage_info(); int current_levels = vstorage->num_levels(); if (current_levels <= new_levels) { return Status::OK(); } // Make sure there are file only on one level from // (new_levels-1) to (current_levels-1) int first_nonempty_level = -1; int first_nonempty_level_filenum = 0; for (int i = new_levels - 1; i < current_levels; i++) { int file_num = vstorage->NumLevelFiles(i); if (file_num != 0) { if (first_nonempty_level < 0) { first_nonempty_level = i; first_nonempty_level_filenum = file_num; } else { char msg[255]; snprintf(msg, sizeof(msg), "Found at least two levels containing files: " "[%d:%d],[%d:%d].\n", first_nonempty_level, first_nonempty_level_filenum, i, file_num); return Status::InvalidArgument(msg); } } } // we need to allocate an array with the old number of levels size to // avoid SIGSEGV in WriteSnapshot() // however, all levels bigger or equal to new_levels will be empty std::vector<FileMetaData*>* new_files_list = new std::vector<FileMetaData*>[current_levels]; for (int i = 0; i < new_levels - 1; i++) { new_files_list[i] = vstorage->LevelFiles(i); } if (first_nonempty_level > 0) { new_files_list[new_levels - 1] = vstorage->LevelFiles(first_nonempty_level); } delete[] vstorage -> files_; vstorage->files_ = new_files_list; vstorage->num_levels_ = new_levels; MutableCFOptions mutable_cf_options(*options, ImmutableCFOptions(*options)); VersionEdit ve; port::Mutex dummy_mutex; MutexLock l(&dummy_mutex); return versions.LogAndApply( versions.GetColumnFamilySet()->GetDefault(), mutable_cf_options, &ve, &dummy_mutex, nullptr, true); } Status VersionSet::DumpManifest(Options& options, std::string& dscname, bool verbose, bool hex) { // Open the specified manifest file. unique_ptr<SequentialFile> file; Status s = options.env->NewSequentialFile(dscname, &file, env_options_); if (!s.ok()) { return s; } bool have_prev_log_number = false; bool have_next_file = false; bool have_last_sequence = false; uint64_t next_file = 0; uint64_t last_sequence = 0; uint64_t previous_log_number = 0; int count = 0; std::unordered_map<uint32_t, std::string> comparators; std::unordered_map<uint32_t, BaseReferencedVersionBuilder*> builders; // add default column family VersionEdit default_cf_edit; default_cf_edit.AddColumnFamily(kDefaultColumnFamilyName); default_cf_edit.SetColumnFamily(0); ColumnFamilyData* default_cfd = CreateColumnFamily(ColumnFamilyOptions(options), &default_cf_edit); builders.insert({0, new BaseReferencedVersionBuilder(default_cfd)}); { VersionSet::LogReporter reporter; reporter.status = &s; log::Reader reader(std::move(file), &reporter, true/*checksum*/, 0/*initial_offset*/); Slice record; std::string scratch; while (reader.ReadRecord(&record, &scratch) && s.ok()) { VersionEdit edit; s = edit.DecodeFrom(record); if (!s.ok()) { break; } // Write out each individual edit if (verbose) { printf("*************************Edit[%d] = %s\n", count, edit.DebugString(hex).c_str()); } count++; bool cf_in_builders = builders.find(edit.column_family_) != builders.end(); if (edit.has_comparator_) { comparators.insert({edit.column_family_, edit.comparator_}); } ColumnFamilyData* cfd = nullptr; if (edit.is_column_family_add_) { if (cf_in_builders) { s = Status::Corruption( "Manifest adding the same column family twice"); break; } cfd = CreateColumnFamily(ColumnFamilyOptions(options), &edit); builders.insert( {edit.column_family_, new BaseReferencedVersionBuilder(cfd)}); } else if (edit.is_column_family_drop_) { if (!cf_in_builders) { s = Status::Corruption( "Manifest - dropping non-existing column family"); break; } auto builder_iter = builders.find(edit.column_family_); delete builder_iter->second; builders.erase(builder_iter); comparators.erase(edit.column_family_); cfd = column_family_set_->GetColumnFamily(edit.column_family_); assert(cfd != nullptr); cfd->Unref(); delete cfd; cfd = nullptr; } else { if (!cf_in_builders) { s = Status::Corruption( "Manifest record referencing unknown column family"); break; } cfd = column_family_set_->GetColumnFamily(edit.column_family_); // this should never happen since cf_in_builders is true assert(cfd != nullptr); // if it is not column family add or column family drop, // then it's a file add/delete, which should be forwarded // to builder auto builder = builders.find(edit.column_family_); assert(builder != builders.end()); builder->second->version_builder()->Apply(&edit); } if (cfd != nullptr && edit.has_log_number_) { cfd->SetLogNumber(edit.log_number_); } if (edit.has_prev_log_number_) { previous_log_number = edit.prev_log_number_; have_prev_log_number = true; } if (edit.has_next_file_number_) { next_file = edit.next_file_number_; have_next_file = true; } if (edit.has_last_sequence_) { last_sequence = edit.last_sequence_; have_last_sequence = true; } if (edit.has_max_column_family_) { column_family_set_->UpdateMaxColumnFamily(edit.max_column_family_); } } } file.reset(); if (s.ok()) { if (!have_next_file) { s = Status::Corruption("no meta-nextfile entry in descriptor"); printf("no meta-nextfile entry in descriptor"); } else if (!have_last_sequence) { printf("no last-sequence-number entry in descriptor"); s = Status::Corruption("no last-sequence-number entry in descriptor"); } if (!have_prev_log_number) { previous_log_number = 0; } } if (s.ok()) { for (auto cfd : *column_family_set_) { auto builders_iter = builders.find(cfd->GetID()); assert(builders_iter != builders.end()); auto builder = builders_iter->second->version_builder(); Version* v = new Version(cfd, this, current_version_number_++); builder->SaveTo(v->storage_info()); std::vector<uint64_t> size_being_compacted( v->storage_info()->num_levels() - 1); cfd->compaction_picker()->SizeBeingCompacted(size_being_compacted); v->PrepareApply(*cfd->GetLatestMutableCFOptions(), size_being_compacted); printf("--------------- Column family \"%s\" (ID %u) --------------\n", cfd->GetName().c_str(), (unsigned int)cfd->GetID()); printf("log number: %lu\n", (unsigned long)cfd->GetLogNumber()); auto comparator = comparators.find(cfd->GetID()); if (comparator != comparators.end()) { printf("comparator: %s\n", comparator->second.c_str()); } else { printf("comparator: <NO COMPARATOR>\n"); } printf("%s \n", v->DebugString(hex).c_str()); delete v; } // Free builders for (auto& builder : builders) { delete builder.second; } next_file_number_.store(next_file + 1); last_sequence_ = last_sequence; prev_log_number_ = previous_log_number; printf( "next_file_number %lu last_sequence " "%lu prev_log_number %lu max_column_family %u\n", (unsigned long)next_file_number_.load(), (unsigned long)last_sequence, (unsigned long)previous_log_number, column_family_set_->GetMaxColumnFamily()); } return s; } #endif // ROCKSDB_LITE void VersionSet::MarkFileNumberUsedDuringRecovery(uint64_t number) { // only called during recovery which is single threaded, so this works because // there can't be concurrent calls if (next_file_number_.load(std::memory_order_relaxed) <= number) { next_file_number_.store(number + 1, std::memory_order_relaxed); } } Status VersionSet::WriteSnapshot(log::Writer* log) { // TODO: Break up into multiple records to reduce memory usage on recovery? // WARNING: This method doesn't hold a mutex!! // This is done without DB mutex lock held, but only within single-threaded // LogAndApply. Column family manipulations can only happen within LogAndApply // (the same single thread), so we're safe to iterate. for (auto cfd : *column_family_set_) { { // Store column family info VersionEdit edit; if (cfd->GetID() != 0) { // default column family is always there, // no need to explicitly write it edit.AddColumnFamily(cfd->GetName()); edit.SetColumnFamily(cfd->GetID()); } edit.SetComparatorName( cfd->internal_comparator().user_comparator()->Name()); std::string record; if (!edit.EncodeTo(&record)) { return Status::Corruption( "Unable to Encode VersionEdit:" + edit.DebugString(true)); } Status s = log->AddRecord(record); if (!s.ok()) { return s; } } { // Save files VersionEdit edit; edit.SetColumnFamily(cfd->GetID()); for (int level = 0; level < cfd->NumberLevels(); level++) { for (const auto& f : cfd->current()->storage_info()->LevelFiles(level)) { edit.AddFile(level, f->fd.GetNumber(), f->fd.GetPathId(), f->fd.GetFileSize(), f->smallest, f->largest, f->smallest_seqno, f->largest_seqno); } } edit.SetLogNumber(cfd->GetLogNumber()); std::string record; if (!edit.EncodeTo(&record)) { return Status::Corruption( "Unable to Encode VersionEdit:" + edit.DebugString(true)); } Status s = log->AddRecord(record); if (!s.ok()) { return s; } } } return Status::OK(); } // Opens the mainfest file and reads all records // till it finds the record we are looking for. bool VersionSet::ManifestContains(uint64_t manifest_file_num, const std::string& record) const { std::string fname = DescriptorFileName(dbname_, manifest_file_num); Log(InfoLogLevel::INFO_LEVEL, db_options_->info_log, "ManifestContains: checking %s\n", fname.c_str()); unique_ptr<SequentialFile> file; Status s = env_->NewSequentialFile(fname, &file, env_options_); if (!s.ok()) { Log(InfoLogLevel::INFO_LEVEL, db_options_->info_log, "ManifestContains: %s\n", s.ToString().c_str()); Log(InfoLogLevel::INFO_LEVEL, db_options_->info_log, "ManifestContains: is unable to reopen the manifest file %s", fname.c_str()); return false; } log::Reader reader(std::move(file), nullptr, true/*checksum*/, 0); Slice r; std::string scratch; bool result = false; while (reader.ReadRecord(&r, &scratch)) { if (r == Slice(record)) { result = true; break; } } Log(InfoLogLevel::INFO_LEVEL, db_options_->info_log, "ManifestContains: result = %d\n", result ? 1 : 0); return result; } uint64_t VersionSet::ApproximateOffsetOf(Version* v, const InternalKey& ikey) { uint64_t result = 0; const auto* vstorage = v->storage_info(); for (int level = 0; level < vstorage->num_levels(); level++) { const std::vector<FileMetaData*>& files = vstorage->LevelFiles(level); for (size_t i = 0; i < files.size(); i++) { if (v->cfd_->internal_comparator().Compare(files[i]->largest, ikey) <= 0) { // Entire file is before "ikey", so just add the file size result += files[i]->fd.GetFileSize(); } else if (v->cfd_->internal_comparator().Compare(files[i]->smallest, ikey) > 0) { // Entire file is after "ikey", so ignore if (level > 0) { // Files other than level 0 are sorted by meta->smallest, so // no further files in this level will contain data for // "ikey". break; } } else { // "ikey" falls in the range for this table. Add the // approximate offset of "ikey" within the table. TableReader* table_reader_ptr; Iterator* iter = v->cfd_->table_cache()->NewIterator( ReadOptions(), env_options_, v->cfd_->internal_comparator(), files[i]->fd, &table_reader_ptr); if (table_reader_ptr != nullptr) { result += table_reader_ptr->ApproximateOffsetOf(ikey.Encode()); } delete iter; } } } return result; } void VersionSet::AddLiveFiles(std::vector<FileDescriptor>* live_list) { // pre-calculate space requirement int64_t total_files = 0; for (auto cfd : *column_family_set_) { Version* dummy_versions = cfd->dummy_versions(); for (Version* v = dummy_versions->next_; v != dummy_versions; v = v->next_) { const auto* vstorage = v->storage_info(); for (int level = 0; level < vstorage->num_levels(); level++) { total_files += vstorage->LevelFiles(level).size(); } } } // just one time extension to the right size live_list->reserve(live_list->size() + static_cast<size_t>(total_files)); for (auto cfd : *column_family_set_) { Version* dummy_versions = cfd->dummy_versions(); for (Version* v = dummy_versions->next_; v != dummy_versions; v = v->next_) { const auto* vstorage = v->storage_info(); for (int level = 0; level < vstorage->num_levels(); level++) { for (const auto& f : vstorage->LevelFiles(level)) { live_list->push_back(f->fd); } } } } } Iterator* VersionSet::MakeInputIterator(Compaction* c) { auto cfd = c->column_family_data(); ReadOptions read_options; read_options.verify_checksums = c->mutable_cf_options()->verify_checksums_in_compaction; read_options.fill_cache = false; // Level-0 files have to be merged together. For other levels, // we will make a concatenating iterator per level. // TODO(opt): use concatenating iterator for level-0 if there is no overlap const size_t space = (c->level() == 0 ? c->input_levels(0)->num_files + c->num_input_levels() - 1 : c->num_input_levels()); Iterator** list = new Iterator* [space]; size_t num = 0; for (size_t which = 0; which < c->num_input_levels(); which++) { if (c->input_levels(which)->num_files != 0) { if (c->level(which) == 0) { const LevelFilesBrief* flevel = c->input_levels(which); for (size_t i = 0; i < flevel->num_files; i++) { list[num++] = cfd->table_cache()->NewIterator( read_options, env_options_compactions_, cfd->internal_comparator(), flevel->files[i].fd, nullptr, true /* for compaction */); } } else { // Create concatenating iterator for the files from this level list[num++] = NewTwoLevelIterator(new LevelFileIteratorState( cfd->table_cache(), read_options, env_options_, cfd->internal_comparator(), true /* for_compaction */, false /* prefix enabled */), new LevelFileNumIterator(cfd->internal_comparator(), c->input_levels(which))); } } } assert(num <= space); Iterator* result = NewMergingIterator(&c->column_family_data()->internal_comparator(), list, static_cast<int>(num)); delete[] list; return result; } // verify that the files listed in this compaction are present // in the current version bool VersionSet::VerifyCompactionFileConsistency(Compaction* c) { #ifndef NDEBUG Version* version = c->column_family_data()->current(); const VersionStorageInfo* vstorage = version->storage_info(); if (c->input_version() != version) { Log(InfoLogLevel::ERROR_LEVEL, db_options_->info_log, "[%s] VerifyCompactionFileConsistency version mismatch", c->column_family_data()->GetName().c_str()); } for (size_t input = 0; input < c->num_input_levels(); ++input) { int level = c->level(input); for (size_t i = 0; i < c->num_input_files(input); ++i) { uint64_t number = c->input(input, i)->fd.GetNumber(); bool found = false; for (unsigned int j = 0; j < vstorage->files_[level].size(); j++) { FileMetaData* f = vstorage->files_[level][j]; if (f->fd.GetNumber() == number) { found = true; break; } } if (!found) { return false; // input files non existent in current version } } } #endif return true; // everything good } Status VersionSet::GetMetadataForFile(uint64_t number, int* filelevel, FileMetaData** meta, ColumnFamilyData** cfd) { for (auto cfd_iter : *column_family_set_) { Version* version = cfd_iter->current(); const auto* vstorage = version->storage_info(); for (int level = 0; level < vstorage->num_levels(); level++) { for (const auto& file : vstorage->LevelFiles(level)) { if (file->fd.GetNumber() == number) { *meta = file; *filelevel = level; *cfd = cfd_iter; return Status::OK(); } } } } return Status::NotFound("File not present in any level"); } void VersionSet::GetLiveFilesMetaData(std::vector<LiveFileMetaData>* metadata) { for (auto cfd : *column_family_set_) { for (int level = 0; level < cfd->NumberLevels(); level++) { for (const auto& file : cfd->current()->storage_info()->LevelFiles(level)) { LiveFileMetaData filemetadata; filemetadata.column_family_name = cfd->GetName(); uint32_t path_id = file->fd.GetPathId(); if (path_id < db_options_->db_paths.size()) { filemetadata.db_path = db_options_->db_paths[path_id].path; } else { assert(!db_options_->db_paths.empty()); filemetadata.db_path = db_options_->db_paths.back().path; } filemetadata.name = MakeTableFileName("", file->fd.GetNumber()); filemetadata.level = level; filemetadata.size = file->fd.GetFileSize(); filemetadata.smallestkey = file->smallest.user_key().ToString(); filemetadata.largestkey = file->largest.user_key().ToString(); filemetadata.smallest_seqno = file->smallest_seqno; filemetadata.largest_seqno = file->largest_seqno; metadata->push_back(filemetadata); } } } } void VersionSet::GetObsoleteFiles(std::vector<FileMetaData*>* files) { files->insert(files->end(), obsolete_files_.begin(), obsolete_files_.end()); obsolete_files_.clear(); } ColumnFamilyData* VersionSet::CreateColumnFamily( const ColumnFamilyOptions& cf_options, VersionEdit* edit) { assert(edit->is_column_family_add_); Version* dummy_versions = new Version(nullptr, this); // Ref() dummy version once so that later we can call Unref() to delete it // by avoiding calling "delete" explicitly (~Version is private) dummy_versions->Ref(); auto new_cfd = column_family_set_->CreateColumnFamily( edit->column_family_name_, edit->column_family_, dummy_versions, cf_options); Version* v = new Version(new_cfd, this, current_version_number_++); AppendVersion(new_cfd, v); // GetLatestMutableCFOptions() is safe here without mutex since the // cfd is not available to client new_cfd->CreateNewMemtable(*new_cfd->GetLatestMutableCFOptions()); new_cfd->SetLogNumber(edit->log_number_); return new_cfd; } } // namespace rocksdb