hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a1e5b7f8bd26367ca383772e733c8fe56d66b807 | 21,498 | hpp | C++ | Source/AllProjects/CQCWebSrv/Client/CQCWebSrvC_WebSockHandler.hpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 51 | 2020-12-26T18:17:16.000Z | 2022-03-15T04:29:35.000Z | Source/AllProjects/CQCWebSrv/Client/CQCWebSrvC_WebSockHandler.hpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | null | null | null | Source/AllProjects/CQCWebSrv/Client/CQCWebSrvC_WebSockHandler.hpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 4 | 2020-12-28T07:24:39.000Z | 2021-12-29T12:09:37.000Z | //
// FILE NAME: CQCWebSrvC_WorkerThread.hpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 091/17/2014
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2020
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This class implements a base class for Websocket based handlers on the Web Server
// side. We currently have two derivatives, one C++ one for our browser based RIVA
// client, and one that is for user written CML based handlers.
//
// Because of the event driven nature of Websockets, and the fact that CML handlers
// must be handled in a single threaded nature, while C++ ones may create various
// threads, all of which are sending messages, this class just handles the sending
// and receiving of messages on behalf of the derived class.
//
// 1. We have an output msg queue
// 2. This base handler's thread manages the socket and the queue.
// 3. We associate an event with the socket and have another event for the output queue.
// 4. Our thread will then block on both those events all the time, waiting for either
// data available on the socket, or messages available in the output queue.
// 5. When it wakes up, if it didn't timeout, it will process either an incoming msg
// our outgoing, depending on which event was triggered. It only does one per round
// so that it keeps things smooth and balances the load.
// 6. All sending of messages happens through us, so our public message sending methods
// will add an item to the queue and trigger the out msg event. This tells our thread
// that there is data to send.
// 7. For each incoming msg we call ProcessMsg(). This is done synchronously so the derived
// class must handle it very quickly or queue it for later processing.
//
// Though most handlers will never need to worry about it, since they tend to be more
// call and response style, if the handler sends a lot of unacked messages it needs to
// make sure there's room in the outgoing queue and wait a bit for room to become available
// if not. We provide a method to do that.
//
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
#pragma once
#pragma CIDLIB_PACK(CIDLIBPACK)
// ---------------------------------------------------------------------------
// CLASS: TWebSockBuf
// PREFIX: wsb
// ---------------------------------------------------------------------------
class TWebSockBuf
{
public :
// -------------------------------------------------------------------
// Constructors and Destructor
// -------------------------------------------------------------------
TWebSockBuf();
TWebSockBuf
(
const tCIDLib::TCard4 c4InitSz
);
TWebSockBuf
(
TMemBuf* const pmbufToAdopt
, const tCIDLib::TCard4 c4Size
);
TWebSockBuf(const TWebSockBuf&) = delete;
TWebSockBuf(TWebSockBuf&&) = delete;
~TWebSockBuf();
// -------------------------------------------------------------------
// Public constructors
// -------------------------------------------------------------------
TWebSockBuf& operator=(const TWebSockBuf&) = delete;
TWebSockBuf& operator=(TWebSockBuf&&) = delete;
// -------------------------------------------------------------------
// Public, non-virtual methods
// -------------------------------------------------------------------
tCIDLib::TVoid Reset();
// -------------------------------------------------------------------
// Public data members
//
// m_c1Type
// The Websocket msg type indicator, so that we can support the various
// types, but have them all just flattened down to buffers and queued up
// to be sent. The sender just passes this flag along.
//
// m_c4CurBytes
// The number of bytes in the buffer actually used.
//
// m_pmbufData
// The data buffer, which we own and will release.
// -------------------------------------------------------------------
tCIDLib::TCard1 m_c1Type;
tCIDLib::TCard4 m_c4CurBytes;
TMemBuf* m_pmbufData;
};
// ---------------------------------------------------------------------------
// CLASS: TWebsockThread
// PREFIX: thr
// ---------------------------------------------------------------------------
class TWebsockThread : public TThread
{
public :
// --------------------------------------------------------------------
// Public class types
//
// We need a current state. Because control frames can come in the middle
// of fragmented data msgs, and because we have to deal differently with
// close messages depending on whether we initiated or the other side did
// (via a ctrl msg that could also come in the middle of a fragmented
// msg, we need to be able to remember state changes for when we get back
// to the main loop.
//
// Connecting
// We need to call the virtual method that lets the derived class know
// we are now connected and let him initialize as required. This is done
// before we enter our loop, so if it fails we never go further. If it
// works we enter the loop in Ready state.
//
// Ready
// We are in ready state, which means we are waiting for msgs to come in
// or be ready to send out.
//
// InMsg
// We are processing a non-final message, i.e. during Ready we got a non
// final frame, and we need to now wait for the remaining fragments. This
// is the same as Ready in terms of what we do.
//
// WaitClientEnd
// Either we or a derivative has asked to shutdown. So we will have sent
// our close and need to wait for the client to respond with his own
// close before we exit. We will only wait so long.
//
// End
// Causes the main loop to exit.
// --------------------------------------------------------------------
enum class EStates
{
Connecting
, Ready
, InMsg
, WaitClientEnd
, End
};
// --------------------------------------------------------------------
// Public, static methods
// --------------------------------------------------------------------
static tCIDLib::TBoolean bControlType
(
const tCIDLib::TCard1 c1Type
);
static tCIDLib::TBoolean bValidateReqInfo
(
TCIDDataSrc& cdsData
, const TString& strResource
, const tCIDLib::TKVPList& colHdrLines
, const TString& strType
, TString& strSecKey
);
// --------------------------------------------------------------------
// Constructors and Destructor
// --------------------------------------------------------------------
TWebsockThread() = delete ;
TWebsockThread(const TWebsockThread&) = delete;
TWebsockThread(TWebsockThread&&) = delete;
~TWebsockThread();
// --------------------------------------------------------------------
// Public operators
// --------------------------------------------------------------------
TWebsockThread& operator=(const TWebsockThread&) = delete;
TWebsockThread& operator=(TWebsockThread&&) = delete;
// --------------------------------------------------------------------
// Public, non-virtual methods
// --------------------------------------------------------------------
tCIDLib::TBoolean bFindQParam
(
const TString& strKey
, TString& strValue
) const;
tCIDLib::TBoolean bIsReady() const;
tCIDLib::TBoolean bSimMode() const;
tCIDLib::TBoolean bValidateLogin
(
const TString& strUser
, const TString& strPassword
, TCQCSecToken& sectToFill
, TCQCUserAccount& uaccToFill
, TString& strFailReason
);
tCIDLib::TCard4 c4QParamCnt() const;
tCIDLib::EExitCodes eServiceClient();
tCQCWebSrvC::EWSockTypes eType() const;
tCIDLib::TVoid EnableMsgLogging
(
const tCIDLib::TBoolean bState
);
const TKeyValuePair& kvalQParamAt
(
const tCIDLib::TCard4 c4At
) const;
tCIDLib::TVoid PauseOutput
(
const tCIDLib::TBoolean bState
);
tCIDLib::TVoid Reset
(
TCIDDataSrcJan& janSrc
, const TURL& urlReq
, const TString& strSecKey
);
tCIDLib::TVoid SetFieldList
(
const tCIDLib::TStrList& colToSet
);
tCIDLib::TVoid StartShutdown
(
const tCIDLib::TCard2 c2Err
);
tCIDLib::TVoid WaitOutSpaceAvail
(
const tCIDLib::TCard4 c4WaitMSs
);
protected :
// --------------------------------------------------------------------
// Hidden constructors
// --------------------------------------------------------------------
TWebsockThread
(
const tCQCWebSrvC::EWSockTypes eType
, const tCIDLib::TBoolean bSimMode
);
// --------------------------------------------------------------------
// Protected, inherited methods
// --------------------------------------------------------------------
tCIDLib::EExitCodes eProcess() final;
// --------------------------------------------------------------------
// Protected, virtual methods
// --------------------------------------------------------------------
virtual tCIDLib::TCard4 c4WSInitialize
(
const TURL& urlReq
, TString& strRepText
, TString& strErrText
) = 0;
virtual tCIDLib::TVoid CheckShutdownReq() const = 0;
virtual tCIDLib::TVoid Connected() = 0;
virtual tCIDLib::TVoid Disconnected() = 0;
virtual tCIDLib::TVoid FieldChanged
(
const TString& strMon
, const TString& strField
, const tCIDLib::TBoolean bGoodValue
, const TCQCFldValue& fvValue
) = 0;
virtual tCIDLib::TVoid Idle() = 0;
virtual tCIDLib::TVoid ProcessMsg
(
const TString& strMsg
) = 0;
virtual tCIDLib::TVoid WSTerminate() = 0;
// --------------------------------------------------------------------
// Protected, non-virtual methods
// --------------------------------------------------------------------
tCIDLib::TVoid QueueTextMsg
(
const TString& strText
);
tCIDLib::TVoid QueueTextMsg
(
TMemBuf* const pmbufToAdopt
, const tCIDLib::TCard4 c4Size
);
tCIDLib::TVoid SendCtrlMsg
(
const tCIDLib::TCard1 c1Type
, const tCIDLib::TCard2 c2Payload
);
tCIDLib::TVoid SendMsg
(
const tCIDLib::TCard1 c1Type
, const TMemBuf& mbufData
, const tCIDLib::TCard4 c4DataCnt
);
tCIDLib::TVoid SendMsg
(
const tCIDLib::TCard1 c1Type
, const tCIDLib::TVoid* const pData
, const tCIDLib::TCard4 c4DataCnt
);
const TURL& urlReq() const;
private :
// --------------------------------------------------------------------
// Private data types
// --------------------------------------------------------------------
using TPollInfoList = TVector<TCQCFldPollInfo>;
using TOutMsgQ = TRefQueue<TWebSockBuf>;
// --------------------------------------------------------------------
// Protected, non-virtual methods
// --------------------------------------------------------------------
tCIDLib::TBoolean bGetFragment
(
tCIDLib::TCard1& c1Type
, tCIDLib::TBoolean& bFinal
, TMemBuf& mbufToFill
, tCIDLib::TCard4& c4MsgBytes
);
tCIDLib::TVoid Cleanup
(
const tCIDLib::TBoolean bCallDiscon
);
tCIDLib::TVoid ClearOutQ();
tCIDLib::TVoid HandleMsg
(
const tCIDLib::TCard1 c1Type
, const THeapBuf& mbufData
, const tCIDLib::TCard4 c4DataCnt
);
tCIDLib::TVoid PollFields();
tCIDLib::TVoid SendAccept();
tCIDLib::TVoid SendClose
(
const tCIDLib::TCard2 c2Code
);
tCIDLib::TVoid SendPing();
// --------------------------------------------------------------------
// Private data members
//
// m_bLogStateInfo
// The client can set this via a query parameter, logstateinfo=1.
//
// m_bSimMode
// We can be put into 'simulator' mode, which is used to support debugging
// CML based websocket handlers, and possibly other derived classes might
// make use of it. For us, we just avoid doing a few things when in
// simulator mode. For instance, we won't be spun up as a separate thread
// in that case, but our eServiceClient() method will just be called in
// the context of a simulator thread. So we can't do some thread oriented
// stuff.
//
// m_bPauseOutput
// The derived class can ask us to stop sending out msgs from the output
// queue. For instance, in the RIVA handler it has to get an ack from the
// client at least every so many msgs sent. Once it hits that point it will
// ask us to stop sending until it sees an ack. If our queue fills up, then
// we will error out this session, so he can't do it for too long relative to
// the bulk he's sending.
// m_bWaitPong
// m_c4PingVal
// Remember if we are waiting for a pong response to a ping we have sent.
// We send a 32 bit value in each ping, which we increment each time, so
// this is the value we should get back in the pong. The byte order doesn't
// matter since the client doesn't interpret it, it just echoes it back.
//
// m_colFields
// The derived class can ask us to monitor fields. We set up these fields
// on the poll engine. We get back a poll info object for each field
// which we use to check for changes.
//
// m_colOutMsgQ
// The outgoing message queue. All sent messages are queued up here and
// then sent by out this thread. It is thread safe, and really the only thing
// that needs any sync.
//
// m_colQParams
// Any query parms in the original URL. We make these available to the derived
// class in case it needs them.
//
// m_enctEndTimer
// When we start a close from our side, we will wait for up to a certain
// amount of time for the other side to respond. Else we'll give up.
//
// m_enctLastInMsg
// m_enctLastOutMsg
// We track the last time we sent a message (on behalf of the derived class
// primarily) and the last time we got one from the client. If we haven't
// sent a message in the last 30 seconds, we'll send a ping so that the
// client doesn't give up on us.
//
// m_evOutQ
// This event is used to indicate when new data is available in the outgoing
// message queue. It is used in conjunction with the event socket below to
// provide smooth processing of incoming and outgoing messages. We have to
// synchronize access to it to avoid race conditions. We use the output msg
// queue's mutex for that, since they are used together.
//
// m_evSock
// We associate an event with our socket so that we can block on either
// msgs to send entering the queue, or incoming data to process.
//
// m_eState
// Our current state, which the main loop uses to know what to do. It
// starts out in Connecting state and moves towards eventually one of the
// close states.
//
// m_eType
// The derived type provides us a type indicator, so that we don't have
// to use RTTI for the simple typing needs we have.
//
// m_mbufReadFrag
// This is used for reading in fragments. It's passed to eGetFragment()
// get any incoming fragement content. This is used by the main processing
// loop.
//
// m_mbufReadMsg
// We need a buffer to build up fragments into to create the final msg. This
// is used by the main processing loop, which just adds fragements into it
// until the final one.
//
// m_pcdsServer
// We are given the data source. In the case of a normal (non-simulator)
// invocation, our eProcess() method immediately puts a janitor on it,
// which insures it gets cleaned up. In simulator mode, the base CML class
// handler, which creates us, insures it gets cleaned up.
//
// Only this thread (or the simulator thread) deals with this object so it
// doesn't require any sync. Outgoing messages are queued on this thread for
// transmission by our thread. And thread does the reading of incoming msgs.
//
// m_pstrmLog
// The derived class can enable a log of messages exchanged. If enabled
// this is set, else it's null.
//
// m_strSecKey
// The websock security key that was sent by the client, which we need
// for the ugrade acceptance reply.
//
// m_strTextDispatch
// A temp string to use for transcoding text messages to a string to pass
// on to the derived class.
//
// m_tcvtMsgs
// A converter to convert messages to/from UTF-8.
//
// m_tmLog
// A time object we use in logging. We pre-set it up for the desired time
// format, and just set it to the current time any time we want to output
// it to the log.
//
// m_urlReq
// The original request URL from the first HTTP line. We keep it around so
// that we can make it available to the derived class if needed.
// --------------------------------------------------------------------
tCIDLib::TBoolean m_bLogStateInfo;
tCIDLib::TBoolean m_bPauseOutput;
tCIDLib::TBoolean m_bSimMode;
tCIDLib::TBoolean m_bWaitPong;
tCIDLib::TCard4 m_c4PingVal;
TPollInfoList m_colFields;
TOutMsgQ m_colOutMsgQ;
tCIDLib::TKVPList m_colQParams;
tCIDLib::TEncodedTime m_enctEndTimer;
tCIDLib::TEncodedTime m_enctLastInMsg;
tCIDLib::TEncodedTime m_enctLastOutMsg;
TEvent m_evOutMsgQ;
TEvent m_evSock;
EStates m_eState;
tCQCWebSrvC::EWSockTypes m_eType;
THeapBuf m_mbufReadFrag;
THeapBuf m_mbufReadMsg;
TMutex m_mtxSync;
TCIDSockStreamBasedDataSrc* m_pcdsServer;
TTextFileOutStream* m_pstrmLog;
TString m_strSecKey;
TString m_strTextDispatch;
TUTF8Converter m_tcvtMsgs;
TTime m_tmLog;
TURL m_urlReq;
};
#pragma CIDLIB_POPPACK
| 38.805054 | 92 | 0.480789 | MarkStega |
a1ea663a89960f519afbf0257153d3e5f45d352f | 6,411 | cpp | C++ | jen/src/jen/parsing.cpp | BrunoSilvaFreire/JenErator | 65f93d4a4324643acf0386c1516bc6a3505522ff | [
"MIT"
] | 1 | 2019-04-30T22:03:26.000Z | 2019-04-30T22:03:26.000Z | jen/src/jen/parsing.cpp | BrunoSilvaFreire/JenErator | 65f93d4a4324643acf0386c1516bc6a3505522ff | [
"MIT"
] | null | null | null | jen/src/jen/parsing.cpp | BrunoSilvaFreire/JenErator | 65f93d4a4324643acf0386c1516bc6a3505522ff | [
"MIT"
] | null | null | null | #include <utility>
#include <cassert>
#include <fstream>
#include "tokenization.cpp"
#include <jen/cpp/preprocessors.h>
#include <vector>
#include <functional>
#include <jen/utilities/strings.h>
namespace jen {
#define PARSING_STATE_PARAMS size_t &i, std::vector<CXXToken> &tokens, CXXTranslationUnit &unit, const ParseOptions &options
#define CREATE_DELIMITERS(...) std::vector<const char *>({ __VA_ARGS__ })
void consume_whitespace(size_t &i, std::vector<CXXToken> &tokens) {
for (; i < tokens.size(); ++i) {
if (tokens[i].getCharacterType() != CXXCharacterType::eWhiteSpace) {
break;
}
}
}
void consume_whitespace_nonewline(size_t &i, std::vector<CXXToken> &tokens) {
for (; i < tokens.size(); ++i) {
const auto &t = tokens[i];
if (t.getCharacterType() != CXXCharacterType::eWhiteSpace || t.hasNewLine()) {
break;
}
}
}
std::string join_until_encounter(size_t &i, const std::vector<CXXToken> &tokens,
const std::vector<const char *> &delimiters) {
auto str = std::string();
for (; i < tokens.size(); i++) {
auto c = tokens[i].getContent();
if (std::any_of(delimiters.begin(), delimiters.end(), [&](const char *d) {
return jen::strings::starts_with(c, d);
})) {
break;
}
str += c;
}
return str;
}
std::string readMacroValue(size_t &i, std::vector<CXXToken> &tokens) {
auto str = std::string();
consume_whitespace_nonewline(i, tokens);
for (; i < tokens.size(); i++) {
auto &t = tokens[i];
auto &c = t.getContent();
if (t.hasNewLine()) {
break;
}
str += c;
}
return str;
}
std::vector<std::string> readMacroParameters(size_t &i, std::vector<CXXToken> &tokens) {
auto params = std::vector<std::string>();
std::string str;
for (; i < tokens.size(); i++) {
auto &t = tokens[i];
auto &c = t.getContent();
if (c == ")") {
params.emplace_back(str);
break;
}
if (c == ",") {
params.emplace_back(str);
str = "";
} else {
str += c;
}
}
return params;
}
void try_parse_define(PARSING_STATE_PARAMS) {
consume_whitespace(i, tokens);
const auto ¯oName = join_until_encounter(i, tokens, CREATE_DELIMITERS(" ", "(", "\n"));
auto &post = tokens[i];
const auto &postCt = post.getContent();
if (jen::strings::starts_with(postCt, "(")) {
// is macro function
std::vector<std::string> parameters;
if (!jen::strings::contains(postCt, ")")) {
parameters = readMacroParameters(++i, tokens);
}
unit.getElements().emplace_back(
new jen::CXXMacroFunctionDefinition(macroName, parameters)
);
} else {
std::string value = readMacroValue(i, tokens);
unit.getElements().emplace_back(
new jen::CXXMacroConstantDefinition(macroName, value)
);
}
}
bool try_include_file(PARSING_STATE_PARAMS) {
consume_whitespace(i, tokens);
const auto &token = tokens[i++];
const auto &file = join_until_encounter(i, tokens, CREATE_DELIMITERS(">"));
std::filesystem::path found;
jen::CXXInclude::Type type;
switch (token.getContent()[0]) {
case '<':
type = CXXInclude::Type::eBrackets;
break;
case '"':
type = CXXInclude::Type::eQuotes;
break;
default:
throw std::runtime_error("Unknown include character");
}
if (!options.tryFindFile(file, found)) {
std::cout << "Unable to find file '" << file << "'" << std::endl;
return false;
}
auto stream = std::ifstream(found);
auto newTokens = jen::parse(stream, options);
unit.getElements().emplace_back(new jen::CXXInclude(file, type, newTokens));
stream.close();
return true;
}
void parse_preprocessor(PARSING_STATE_PARAMS) {
const CXXToken &initial = tokens[i++];
const auto &ct = initial.getContent();
if (ct == "include") {
try_include_file(i, tokens, unit, options);
return;
}
if (ct == "define") {
try_parse_define(i, tokens, unit, options);
return;
}
}
CXXTranslationUnit parse(std::istream &stream, const ParseOptions &parseOptions) {
auto tokens = tokenize(stream);
CXXTranslationUnit translationUnit;
for (size_t i = 0; i < tokens.size(); i++) {
const CXXToken &token = tokens[i];
const std::string &content = token.getContent();
switch (token.getCharacterType()) {
case eNone:
break;
case eWhiteSpace:
break;
case eSymbol:
if (content == "#") {
parse_preprocessor(++i, tokens, translationUnit, parseOptions);
}
break;
case eNumber:
break;
case eWord:
break;
}
}
return translationUnit;
}
ParseOptions::ParseOptions(
std::vector<std::filesystem::path> headersSearchPaths
) : headersSearchPaths(std::move(headersSearchPaths)) {
}
const ParseOptions::HeaderPaths &ParseOptions::getHeadersSearchPaths() const {
return headersSearchPaths;
}
bool ParseOptions::tryFindFile(const std::string &file, std::filesystem::path &result) const {
for (const std::filesystem::path &path : headersSearchPaths) {
std::filesystem::path potential = std::filesystem::absolute(path / file);
if (std::filesystem::exists(potential)) {
result = potential;
return true;
}
}
return false;
}
} | 33.565445 | 125 | 0.518172 | BrunoSilvaFreire |
a1eba7956acba4fa1010653e468a6c7223506b36 | 52,932 | cpp | C++ | src/ledger/LedgerTxn.cpp | iotbda/iotchain-core | 74094a7853d2591cdfa79aa4a9459f6036008b2d | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | src/ledger/LedgerTxn.cpp | iotbda/iotchain-core | 74094a7853d2591cdfa79aa4a9459f6036008b2d | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | src/ledger/LedgerTxn.cpp | iotbda/iotchain-core | 74094a7853d2591cdfa79aa4a9459f6036008b2d | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 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 "ledger/LedgerTxn.h"
#include "crypto/Hex.h"
#include "crypto/KeyUtils.h"
#include "crypto/SecretKey.h"
#include "database/Database.h"
#include "ledger/LedgerRange.h"
#include "ledger/LedgerTxnEntry.h"
#include "ledger/LedgerTxnHeader.h"
#include "ledger/LedgerTxnImpl.h"
#include "util/GlobalChecks.h"
#include "util/XDROperators.h"
#include "util/types.h"
#include "xdr/IOTChain-ledger-entries.h"
#include "xdrpp/marshal.h"
#include <soci.h>
namespace iotchain
{
std::unordered_map<LedgerKey, std::shared_ptr<LedgerEntry const>>
populateLoadedEntries(std::unordered_set<LedgerKey> const& keys,
std::vector<LedgerEntry> const& entries)
{
std::unordered_map<LedgerKey, std::shared_ptr<LedgerEntry const>> res;
for (auto const& le : entries)
{
auto key = LedgerEntryKey(le);
// Check that the key associated to this entry
// - appears in keys
// - does not appear in res (which implies it has not already appeared
// in entries)
// These conditions imply that the keys associated with entries are
// unique and constitute a subset of keys
assert(keys.find(key) != keys.end());
assert(res.find(key) == res.end());
res.emplace(key, std::make_shared<LedgerEntry const>(le));
}
for (auto const& key : keys)
{
if (res.find(key) == res.end())
{
res.emplace(key, nullptr);
}
}
return res;
}
// Implementation of AbstractLedgerTxnParent --------------------------------
AbstractLedgerTxnParent::~AbstractLedgerTxnParent()
{
}
// Implementation of EntryIterator --------------------------------------------
EntryIterator::EntryIterator(std::unique_ptr<AbstractImpl>&& impl)
: mImpl(std::move(impl))
{
}
EntryIterator::EntryIterator(EntryIterator&& other)
: mImpl(std::move(other.mImpl))
{
}
EntryIterator::EntryIterator(EntryIterator const& other)
: mImpl(other.mImpl->clone())
{
}
std::unique_ptr<EntryIterator::AbstractImpl> const&
EntryIterator::getImpl() const
{
if (!mImpl)
{
throw std::runtime_error("Iterator is empty");
}
return mImpl;
}
EntryIterator& EntryIterator::operator++()
{
getImpl()->advance();
return *this;
}
EntryIterator::operator bool() const
{
return !getImpl()->atEnd();
}
LedgerEntry const&
EntryIterator::entry() const
{
return getImpl()->entry();
}
bool
EntryIterator::entryExists() const
{
return getImpl()->entryExists();
}
LedgerKey const&
EntryIterator::key() const
{
return getImpl()->key();
}
// Implementation of AbstractLedgerTxn --------------------------------------
AbstractLedgerTxn::~AbstractLedgerTxn()
{
}
// Implementation of LedgerTxn ----------------------------------------------
LedgerTxn::LedgerTxn(AbstractLedgerTxnParent& parent,
bool shouldUpdateLastModified)
: mImpl(std::make_unique<Impl>(*this, parent, shouldUpdateLastModified))
{
}
LedgerTxn::LedgerTxn(LedgerTxn& parent, bool shouldUpdateLastModified)
: LedgerTxn((AbstractLedgerTxnParent&)parent, shouldUpdateLastModified)
{
}
LedgerTxn::Impl::Impl(LedgerTxn& self, AbstractLedgerTxnParent& parent,
bool shouldUpdateLastModified)
: mParent(parent)
, mChild(nullptr)
, mHeader(std::make_unique<LedgerHeader>(mParent.getHeader()))
, mShouldUpdateLastModified(shouldUpdateLastModified)
, mIsSealed(false)
, mConsistency(LedgerTxnConsistency::EXACT)
{
mParent.addChild(self);
}
LedgerTxn::~LedgerTxn()
{
if (mImpl)
{
rollback();
}
}
std::unique_ptr<LedgerTxn::Impl> const&
LedgerTxn::getImpl() const
{
if (!mImpl)
{
throw std::runtime_error("LedgerTxnEntry was handled");
}
return mImpl;
}
void
LedgerTxn::addChild(AbstractLedgerTxn& child)
{
getImpl()->addChild(child);
}
void
LedgerTxn::Impl::addChild(AbstractLedgerTxn& child)
{
throwIfSealed();
throwIfChild();
mChild = &child;
// std::set<...>::clear is noexcept
mActive.clear();
// std::shared_ptr<...>::reset is noexcept
mActiveHeader.reset();
}
void
LedgerTxn::Impl::throwIfChild() const
{
if (mChild)
{
throw std::runtime_error("LedgerTxn has child");
}
}
void
LedgerTxn::Impl::throwIfSealed() const
{
if (mIsSealed)
{
throw std::runtime_error("LedgerTxn is sealed");
}
}
void
LedgerTxn::Impl::throwIfNotExactConsistency() const
{
if (mConsistency != LedgerTxnConsistency::EXACT)
{
throw std::runtime_error("LedgerTxn consistency level is not exact");
}
}
void
LedgerTxn::commit()
{
getImpl()->commit();
mImpl.reset();
}
void
LedgerTxn::Impl::commit()
{
maybeUpdateLastModifiedThenInvokeThenSeal([&](EntryMap const& entries) {
// getEntryIterator has the strong exception safety guarantee
// commitChild has the strong exception safety guarantee
mParent.commitChild(getEntryIterator(entries), mConsistency);
});
}
void
LedgerTxn::commitChild(EntryIterator iter, LedgerTxnConsistency cons)
{
getImpl()->commitChild(std::move(iter), cons);
}
static LedgerTxnConsistency
joinConsistencyLevels(LedgerTxnConsistency c1, LedgerTxnConsistency c2)
{
switch (c1)
{
case LedgerTxnConsistency::EXACT:
return c2;
case LedgerTxnConsistency::EXTRA_DELETES:
return LedgerTxnConsistency::EXTRA_DELETES;
default:
abort();
}
}
void
LedgerTxn::Impl::commitChild(EntryIterator iter, LedgerTxnConsistency cons)
{
// Assignment of xdrpp objects does not have the strong exception safety
// guarantee, so use std::unique_ptr<...>::swap to achieve it
auto childHeader = std::make_unique<LedgerHeader>(mChild->getHeader());
mConsistency = joinConsistencyLevels(mConsistency, cons);
try
{
for (; (bool)iter; ++iter)
{
auto const& key = iter.key();
if (iter.entryExists())
{
mEntry[key] = std::make_shared<LedgerEntry>(iter.entry());
}
else if (!mParent.getNewestVersion(key))
{ // Created in this LedgerTxn
mEntry.erase(key);
}
else
{ // Existed in a previous LedgerTxn
mEntry[key] = nullptr;
}
}
}
catch (std::exception& e)
{
printErrorAndAbort("fatal error during commit to LedgerTxn: ",
e.what());
}
catch (...)
{
printErrorAndAbort("unknown fatal error during commit to LedgerTxn");
}
// std::unique_ptr<...>::swap does not throw
mHeader.swap(childHeader);
mChild = nullptr;
}
LedgerTxnEntry
LedgerTxn::create(LedgerEntry const& entry)
{
return getImpl()->create(*this, entry);
}
LedgerTxnEntry
LedgerTxn::Impl::create(LedgerTxn& self, LedgerEntry const& entry)
{
throwIfSealed();
throwIfChild();
auto key = LedgerEntryKey(entry);
if (getNewestVersion(key))
{
throw std::runtime_error("Key already exists");
}
auto current = std::make_shared<LedgerEntry>(entry);
auto impl = LedgerTxnEntry::makeSharedImpl(self, *current);
// Set the key to active before constructing the LedgerTxnEntry, as this
// can throw and the LedgerTxnEntry destructor requires that mActive
// contains key. LedgerTxnEntry constructor does not throw so this is
// still exception safe.
mActive.emplace(key, toEntryImplBase(impl));
LedgerTxnEntry ltxe(impl);
// std::shared_ptr assignment is noexcept
mEntry[key] = current;
return ltxe;
}
void
LedgerTxn::createOrUpdateWithoutLoading(LedgerEntry const& entry)
{
return getImpl()->createOrUpdateWithoutLoading(*this, entry);
}
void
LedgerTxn::Impl::createOrUpdateWithoutLoading(LedgerTxn& self,
LedgerEntry const& entry)
{
throwIfSealed();
throwIfChild();
auto key = LedgerEntryKey(entry);
auto iter = mActive.find(key);
if (iter != mActive.end())
{
throw std::runtime_error("Key is already active");
}
// std::shared_ptr assignment is noexcept, and map
// index on a single key is strong-guarantee.
mEntry[key] = std::make_shared<LedgerEntry>(entry);
}
void
LedgerTxn::deactivate(LedgerKey const& key)
{
getImpl()->deactivate(key);
}
void
LedgerTxn::Impl::deactivate(LedgerKey const& key)
{
auto iter = mActive.find(key);
if (iter == mActive.end())
{
throw std::runtime_error("Key is not active");
}
mActive.erase(iter);
}
void
LedgerTxn::deactivateHeader()
{
getImpl()->deactivateHeader();
}
void
LedgerTxn::Impl::deactivateHeader()
{
if (!mActiveHeader)
{
throw std::runtime_error("LedgerTxnHeader is not active");
}
mActiveHeader.reset();
}
void
LedgerTxn::erase(LedgerKey const& key)
{
getImpl()->erase(key);
}
void
LedgerTxn::Impl::erase(LedgerKey const& key)
{
throwIfSealed();
throwIfChild();
auto newest = getNewestVersion(key);
if (!newest)
{
throw std::runtime_error("Key does not exist");
}
auto activeIter = mActive.find(key);
bool isActive = activeIter != mActive.end();
if (!mParent.getNewestVersion(key))
{ // Created in this LedgerTxn
mEntry.erase(key);
}
else
{ // Existed in a previous LedgerTxn
auto iter = mEntry.find(key);
if (iter != mEntry.end())
{
iter->second.reset();
}
else
{
// C++14 requirements for exception safety of associative containers
// guarantee that if emplace throws when inserting a single element
// then the insertion has no effect
mEntry.emplace(key, nullptr);
}
}
// Note: Cannot throw after this point because the entry will not be
// deactivated in that case
if (isActive)
{
// C++14 requirements for exception safety of containers guarantee that
// erase(iter) does not throw
mActive.erase(activeIter);
}
}
void
LedgerTxn::eraseWithoutLoading(LedgerKey const& key)
{
getImpl()->eraseWithoutLoading(key);
}
void
LedgerTxn::Impl::eraseWithoutLoading(LedgerKey const& key)
{
throwIfSealed();
throwIfChild();
auto activeIter = mActive.find(key);
bool isActive = activeIter != mActive.end();
auto iter = mEntry.find(key);
if (iter != mEntry.end())
{
iter->second.reset();
}
else
{
// C++14 requirements for exception safety of associative containers
// guarantee that if emplace throws when inserting a single element
// then the insertion has no effect
mEntry.emplace(key, nullptr);
}
// Note: Cannot throw after this point because the entry will not be
// deactivated in that case
if (isActive)
{
// C++14 requirements for exception safety of containers guarantee that
// erase(iter) does not throw
mActive.erase(activeIter);
}
mConsistency = LedgerTxnConsistency::EXTRA_DELETES;
}
std::unordered_map<LedgerKey, LedgerEntry>
LedgerTxn::getAllOffers()
{
return getImpl()->getAllOffers();
}
std::unordered_map<LedgerKey, LedgerEntry>
LedgerTxn::Impl::getAllOffers()
{
auto offers = mParent.getAllOffers();
for (auto const& kv : mEntry)
{
auto const& key = kv.first;
auto const& entry = kv.second;
if (key.type() != OFFER)
{
continue;
}
if (!entry)
{
offers.erase(key);
continue;
}
offers[key] = *entry;
}
return offers;
}
std::shared_ptr<LedgerEntry const>
LedgerTxn::getBestOffer(Asset const& buying, Asset const& selling,
std::unordered_set<LedgerKey>& exclude)
{
return getImpl()->getBestOffer(buying, selling, exclude);
}
std::shared_ptr<LedgerEntry const>
LedgerTxn::Impl::getBestOffer(Asset const& buying, Asset const& selling,
std::unordered_set<LedgerKey>& exclude)
{
auto end = mEntry.cend();
auto bestOfferIter = end;
if (exclude.size() + mEntry.size() > exclude.bucket_count())
{
// taking a best guess as a starting point for how big exclude can get
// this avoids rehashing when processing transactions after a lot of
// changes already occured
exclude.reserve(exclude.size() + mEntry.size());
}
for (auto iter = mEntry.cbegin(); iter != end; ++iter)
{
auto const& key = iter->first;
auto const& entry = iter->second;
if (key.type() != OFFER)
{
continue;
}
if (!exclude.insert(key).second)
{
continue;
}
if (!(entry && entry->data.offer().buying == buying &&
entry->data.offer().selling == selling))
{
continue;
}
if ((bestOfferIter == end) ||
isBetterOffer(*entry, *bestOfferIter->second))
{
bestOfferIter = iter;
}
}
std::shared_ptr<LedgerEntry const> bestOffer;
if (bestOfferIter != end)
{
bestOffer = std::make_shared<LedgerEntry const>(*bestOfferIter->second);
}
auto parentBestOffer = mParent.getBestOffer(buying, selling, exclude);
if (bestOffer && parentBestOffer)
{
return isBetterOffer(*bestOffer, *parentBestOffer) ? bestOffer
: parentBestOffer;
}
else
{
return bestOffer ? bestOffer : parentBestOffer;
}
}
LedgerEntryChanges
LedgerTxn::getChanges()
{
return getImpl()->getChanges();
}
LedgerEntryChanges
LedgerTxn::Impl::getChanges()
{
throwIfNotExactConsistency();
LedgerEntryChanges changes;
changes.reserve(mEntry.size() * 2);
maybeUpdateLastModifiedThenInvokeThenSeal([&](EntryMap const& entries) {
for (auto const& kv : entries)
{
auto const& key = kv.first;
auto const& entry = kv.second;
auto previous = mParent.getNewestVersion(key);
if (previous)
{
changes.emplace_back(LEDGER_ENTRY_STATE);
changes.back().state() = *previous;
if (entry)
{
changes.emplace_back(LEDGER_ENTRY_UPDATED);
changes.back().updated() = *entry;
}
else
{
changes.emplace_back(LEDGER_ENTRY_REMOVED);
changes.back().removed() = key;
}
}
else
{
// If !entry and !previous.entry then the entry was created and
// erased in this LedgerTxn, in which case it should not still
// be in this LedgerTxn
assert(entry);
changes.emplace_back(LEDGER_ENTRY_CREATED);
changes.back().created() = *entry;
}
}
});
return changes;
}
LedgerTxnDelta
LedgerTxn::getDelta()
{
return getImpl()->getDelta();
}
LedgerTxnDelta
LedgerTxn::Impl::getDelta()
{
throwIfNotExactConsistency();
LedgerTxnDelta delta;
delta.entry.reserve(mEntry.size());
maybeUpdateLastModifiedThenInvokeThenSeal([&](EntryMap const& entries) {
for (auto const& kv : entries)
{
auto const& key = kv.first;
auto previous = mParent.getNewestVersion(key);
// Deep copy is not required here because getDelta causes
// LedgerTxn to enter the sealed state, meaning subsequent
// modifications are impossible.
delta.entry[key] = {kv.second, previous};
}
delta.header = {*mHeader, mParent.getHeader()};
});
return delta;
}
EntryIterator
LedgerTxn::Impl::getEntryIterator(EntryMap const& entries) const
{
auto iterImpl =
std::make_unique<EntryIteratorImpl>(entries.cbegin(), entries.cend());
return EntryIterator(std::move(iterImpl));
}
LedgerHeader const&
LedgerTxn::getHeader() const
{
return getImpl()->getHeader();
}
LedgerHeader const&
LedgerTxn::Impl::getHeader() const
{
return *mHeader;
}
std::vector<InflationWinner>
LedgerTxn::getInflationWinners(size_t maxWinners, int64_t minVotes)
{
return getImpl()->getInflationWinners(maxWinners, minVotes);
}
std::map<AccountID, int64_t>
LedgerTxn::Impl::getDeltaVotes() const
{
int64_t const MIN_VOTES_TO_INCLUDE = 1000000000;
std::map<AccountID, int64_t> deltaVotes;
for (auto const& kv : mEntry)
{
auto const& key = kv.first;
auto const& entry = kv.second;
if (key.type() != ACCOUNT)
{
continue;
}
if (entry)
{
auto const& acc = entry->data.account();
if (acc.inflationDest && acc.balance >= MIN_VOTES_TO_INCLUDE)
{
deltaVotes[*acc.inflationDest] += acc.balance;
}
}
auto previous = mParent.getNewestVersion(key);
if (previous)
{
auto const& acc = previous->data.account();
if (acc.inflationDest && acc.balance >= MIN_VOTES_TO_INCLUDE)
{
deltaVotes[*acc.inflationDest] -= acc.balance;
}
}
}
return deltaVotes;
}
std::map<AccountID, int64_t>
LedgerTxn::Impl::getTotalVotes(
std::vector<InflationWinner> const& parentWinners,
std::map<AccountID, int64_t> const& deltaVotes, int64_t minVotes) const
{
std::map<AccountID, int64_t> totalVotes;
for (auto const& winner : parentWinners)
{
totalVotes.emplace(winner.accountID, winner.votes);
}
for (auto const& delta : deltaVotes)
{
auto const& accountID = delta.first;
auto const& voteDelta = delta.second;
if ((totalVotes.find(accountID) != totalVotes.end()) ||
voteDelta >= minVotes)
{
totalVotes[accountID] += voteDelta;
}
}
return totalVotes;
}
std::vector<InflationWinner>
LedgerTxn::Impl::enumerateInflationWinners(
std::map<AccountID, int64_t> const& totalVotes, size_t maxWinners,
int64_t minVotes) const
{
std::vector<InflationWinner> winners;
for (auto const& total : totalVotes)
{
auto const& accountID = total.first;
auto const& voteTotal = total.second;
if (voteTotal >= minVotes)
{
winners.push_back({accountID, voteTotal});
}
}
// Sort the new winners and remove the excess
std::sort(winners.begin(), winners.end(),
[](auto const& lhs, auto const& rhs) {
if (lhs.votes == rhs.votes)
{
return KeyUtils::toStrKey(lhs.accountID) >
KeyUtils::toStrKey(rhs.accountID);
}
return lhs.votes > rhs.votes;
});
if (winners.size() > maxWinners)
{
winners.resize(maxWinners);
}
return winners;
}
std::vector<InflationWinner>
LedgerTxn::Impl::getInflationWinners(size_t maxWinners, int64_t minVotes)
{
// Calculate vote changes relative to parent
auto deltaVotes = getDeltaVotes();
// Have to load extra winners corresponding to the number of accounts that
// have had their vote totals change
size_t numChanged =
std::count_if(deltaVotes.cbegin(), deltaVotes.cend(),
[](auto const& val) { return val.second != 0; });
// Equivalent to maxWinners + numChanged > MAX
if (std::numeric_limits<size_t>::max() - numChanged < maxWinners)
{
throw std::runtime_error("max winners overflowed");
}
size_t newMaxWinners = maxWinners + numChanged;
// Have to load accounts that could be winners after accounting for the
// change in their vote totals
auto maxIncreaseIter =
std::max_element(deltaVotes.cbegin(), deltaVotes.cend(),
[](auto const& lhs, auto const& rhs) {
return lhs.second < rhs.second;
});
int64_t maxIncrease = (maxIncreaseIter != deltaVotes.cend())
? std::max<int64_t>(0, maxIncreaseIter->second)
: 0;
int64_t newMinVotes =
(minVotes > maxIncrease) ? (minVotes - maxIncrease) : 0;
// Get winners from parent, update votes, and add potential new winners
// Note: It is possible that there are new winners in the case where an
// account was receiving no votes before this ledger but now some accounts
// are voting for it
auto totalVotes =
getTotalVotes(mParent.getInflationWinners(newMaxWinners, newMinVotes),
deltaVotes, minVotes);
// Enumerate the new winners in sorted order
return enumerateInflationWinners(totalVotes, maxWinners, minVotes);
}
std::vector<InflationWinner>
LedgerTxn::queryInflationWinners(size_t maxWinners, int64_t minVotes)
{
return getImpl()->queryInflationWinners(maxWinners, minVotes);
}
std::vector<InflationWinner>
LedgerTxn::Impl::queryInflationWinners(size_t maxWinners, int64_t minVotes)
{
throwIfSealed();
throwIfChild();
return getInflationWinners(maxWinners, minVotes);
}
void
LedgerTxn::getAllEntries(std::vector<LedgerEntry>& initEntries,
std::vector<LedgerEntry>& liveEntries,
std::vector<LedgerKey>& deadEntries)
{
getImpl()->getAllEntries(initEntries, liveEntries, deadEntries);
}
void
LedgerTxn::Impl::getAllEntries(std::vector<LedgerEntry>& initEntries,
std::vector<LedgerEntry>& liveEntries,
std::vector<LedgerKey>& deadEntries)
{
std::vector<LedgerEntry> resInit, resLive;
std::vector<LedgerKey> resDead;
resInit.reserve(mEntry.size());
resLive.reserve(mEntry.size());
resDead.reserve(mEntry.size());
maybeUpdateLastModifiedThenInvokeThenSeal([&](EntryMap const& entries) {
for (auto const& kv : entries)
{
auto const& key = kv.first;
auto const& entry = kv.second;
if (entry)
{
auto previous = mParent.getNewestVersion(key);
if (previous)
{
resLive.emplace_back(*entry);
}
else
{
resInit.emplace_back(*entry);
}
}
else
{
resDead.emplace_back(key);
}
}
});
initEntries.swap(resInit);
liveEntries.swap(resLive);
deadEntries.swap(resDead);
}
std::shared_ptr<LedgerEntry const>
LedgerTxn::getNewestVersion(LedgerKey const& key) const
{
return getImpl()->getNewestVersion(key);
}
std::shared_ptr<LedgerEntry const>
LedgerTxn::Impl::getNewestVersion(LedgerKey const& key) const
{
auto iter = mEntry.find(key);
if (iter != mEntry.end())
{
return iter->second;
}
return mParent.getNewestVersion(key);
}
std::unordered_map<LedgerKey, LedgerEntry>
LedgerTxn::getOffersByAccountAndAsset(AccountID const& account,
Asset const& asset)
{
return getImpl()->getOffersByAccountAndAsset(account, asset);
}
std::unordered_map<LedgerKey, LedgerEntry>
LedgerTxn::Impl::getOffersByAccountAndAsset(AccountID const& account,
Asset const& asset)
{
auto offers = mParent.getOffersByAccountAndAsset(account, asset);
for (auto const& kv : mEntry)
{
auto const& key = kv.first;
auto const& entry = kv.second;
if (key.type() != OFFER)
{
continue;
}
if (!entry)
{
offers.erase(key);
continue;
}
auto const& oe = entry->data.offer();
if (oe.sellerID == account &&
(oe.selling == asset || oe.buying == asset))
{
offers[key] = *entry;
}
else
{
offers.erase(key);
}
}
return offers;
}
LedgerTxnEntry
LedgerTxn::load(LedgerKey const& key)
{
return getImpl()->load(*this, key);
}
LedgerTxnEntry
LedgerTxn::Impl::load(LedgerTxn& self, LedgerKey const& key)
{
throwIfSealed();
throwIfChild();
if (mActive.find(key) != mActive.end())
{
throw std::runtime_error("Key is active");
}
auto newest = getNewestVersion(key);
if (!newest)
{
return {};
}
auto current = std::make_shared<LedgerEntry>(*newest);
auto impl = LedgerTxnEntry::makeSharedImpl(self, *current);
// Set the key to active before constructing the LedgerTxnEntry, as this
// can throw and the LedgerTxnEntry destructor requires that mActive
// contains key. LedgerTxnEntry constructor does not throw so this is
// still exception safe.
mActive.emplace(key, toEntryImplBase(impl));
LedgerTxnEntry ltxe(impl);
// std::shared_ptr assignment is noexcept
mEntry[key] = current;
return ltxe;
}
std::map<AccountID, std::vector<LedgerTxnEntry>>
LedgerTxn::loadAllOffers()
{
return getImpl()->loadAllOffers(*this);
}
std::map<AccountID, std::vector<LedgerTxnEntry>>
LedgerTxn::Impl::loadAllOffers(LedgerTxn& self)
{
throwIfSealed();
throwIfChild();
auto previousEntries = mEntry;
auto offers = getAllOffers();
try
{
std::map<AccountID, std::vector<LedgerTxnEntry>> offersByAccount;
for (auto const& kv : offers)
{
auto const& key = kv.first;
auto const& sellerID = key.offer().sellerID;
offersByAccount[sellerID].emplace_back(load(self, key));
}
return offersByAccount;
}
catch (...)
{
// For associative containers, swap does not throw unless the exception
// is thrown by the swap of the Compare object (which is of type
// std::less<LedgerKey>, so this should not throw when swapped)
mEntry.swap(previousEntries);
throw;
}
}
LedgerTxnEntry
LedgerTxn::loadBestOffer(Asset const& buying, Asset const& selling)
{
return getImpl()->loadBestOffer(*this, buying, selling);
}
LedgerTxnEntry
LedgerTxn::Impl::loadBestOffer(LedgerTxn& self, Asset const& buying,
Asset const& selling)
{
throwIfSealed();
throwIfChild();
std::unordered_set<LedgerKey> exclude;
auto le = getBestOffer(buying, selling, exclude);
return le ? load(self, LedgerEntryKey(*le)) : LedgerTxnEntry();
}
LedgerTxnHeader
LedgerTxn::loadHeader()
{
return getImpl()->loadHeader(*this);
}
LedgerTxnHeader
LedgerTxn::Impl::loadHeader(LedgerTxn& self)
{
throwIfSealed();
throwIfChild();
if (mActiveHeader)
{
throw std::runtime_error("LedgerTxnHeader is active");
}
// Set the key to active before constructing the LedgerTxnHeader, as this
// can throw and the LedgerTxnHeader destructor requires that
// mActiveHeader is not empty. LedgerTxnHeader constructor does not throw
// so this is still exception safe.
mActiveHeader = LedgerTxnHeader::makeSharedImpl(self, *mHeader);
return LedgerTxnHeader(mActiveHeader);
}
std::vector<LedgerTxnEntry>
LedgerTxn::loadOffersByAccountAndAsset(AccountID const& accountID,
Asset const& asset)
{
return getImpl()->loadOffersByAccountAndAsset(*this, accountID, asset);
}
std::vector<LedgerTxnEntry>
LedgerTxn::Impl::loadOffersByAccountAndAsset(LedgerTxn& self,
AccountID const& accountID,
Asset const& asset)
{
throwIfSealed();
throwIfChild();
auto previousEntries = mEntry;
auto offers = getOffersByAccountAndAsset(accountID, asset);
try
{
std::vector<LedgerTxnEntry> res;
res.reserve(offers.size());
for (auto const& kv : offers)
{
auto const& key = kv.first;
res.emplace_back(load(self, key));
}
return res;
}
catch (...)
{
// For associative containers, swap does not throw unless the exception
// is thrown by the swap of the Compare object (which is of type
// std::less<LedgerKey>, so this should not throw when swapped)
mEntry.swap(previousEntries);
throw;
}
}
ConstLedgerTxnEntry
LedgerTxn::loadWithoutRecord(LedgerKey const& key)
{
return getImpl()->loadWithoutRecord(*this, key);
}
ConstLedgerTxnEntry
LedgerTxn::Impl::loadWithoutRecord(LedgerTxn& self, LedgerKey const& key)
{
throwIfSealed();
throwIfChild();
if (mActive.find(key) != mActive.end())
{
throw std::runtime_error("Key is active");
}
auto newest = getNewestVersion(key);
if (!newest)
{
return {};
}
auto impl = ConstLedgerTxnEntry::makeSharedImpl(self, *newest);
// Set the key to active before constructing the ConstLedgerTxnEntry, as
// this can throw and the LedgerTxnEntry destructor requires that mActive
// contains key. ConstLedgerTxnEntry constructor does not throw so this is
// still exception safe.
mActive.emplace(key, toEntryImplBase(impl));
return ConstLedgerTxnEntry(impl);
}
void
LedgerTxn::rollback()
{
getImpl()->rollback();
mImpl.reset();
}
void
LedgerTxn::Impl::rollback()
{
if (mChild)
{
mChild->rollback();
}
mActive.clear();
mActiveHeader.reset();
mParent.rollbackChild();
}
void
LedgerTxn::rollbackChild()
{
getImpl()->rollbackChild();
}
void
LedgerTxn::Impl::rollbackChild()
{
mChild = nullptr;
}
void
LedgerTxn::unsealHeader(std::function<void(LedgerHeader&)> f)
{
getImpl()->unsealHeader(*this, f);
}
void
LedgerTxn::Impl::unsealHeader(LedgerTxn& self,
std::function<void(LedgerHeader&)> f)
{
if (!mIsSealed)
{
throw std::runtime_error("LedgerTxn is not sealed");
}
if (mActiveHeader)
{
throw std::runtime_error("LedgerTxnHeader is active");
}
mActiveHeader = LedgerTxnHeader::makeSharedImpl(self, *mHeader);
LedgerTxnHeader header(mActiveHeader);
f(header.current());
}
LedgerTxn::Impl::EntryMap
LedgerTxn::Impl::maybeUpdateLastModified() const
{
throwIfSealed();
throwIfChild();
// Note: We do a deep copy here since a shallow copy would not be exception
// safe.
EntryMap entries;
entries.reserve(mEntry.size());
for (auto const& kv : mEntry)
{
auto const& key = kv.first;
std::shared_ptr<LedgerEntry> entry;
if (kv.second)
{
entry = std::make_shared<LedgerEntry>(*kv.second);
if (mShouldUpdateLastModified)
{
entry->lastModifiedLedgerSeq = mHeader->ledgerSeq;
}
}
entries.emplace(key, entry);
}
return entries;
}
void
LedgerTxn::Impl::maybeUpdateLastModifiedThenInvokeThenSeal(
std::function<void(EntryMap const&)> f)
{
if (!mIsSealed)
{
// Invokes throwIfChild and throwIfSealed
auto entries = maybeUpdateLastModified();
f(entries);
// For associative containers, swap does not throw unless the exception
// is thrown by the swap of the Compare object (which is of type
// std::less<LedgerKey>, so this should not throw when swapped)
mEntry.swap(entries);
// std::set<...>::clear does not throw
// std::shared_ptr<...>::reset does not throw
mActive.clear();
mActiveHeader.reset();
mIsSealed = true;
}
else // Note: can't have child if sealed
{
f(mEntry);
}
}
// Implementation of LedgerTxn::Impl::EntryIteratorImpl ---------------------
LedgerTxn::Impl::EntryIteratorImpl::EntryIteratorImpl(IteratorType const& begin,
IteratorType const& end)
: mIter(begin), mEnd(end)
{
}
void
LedgerTxn::Impl::EntryIteratorImpl::advance()
{
++mIter;
}
bool
LedgerTxn::Impl::EntryIteratorImpl::atEnd() const
{
return mIter == mEnd;
}
LedgerEntry const&
LedgerTxn::Impl::EntryIteratorImpl::entry() const
{
return *(mIter->second);
}
bool
LedgerTxn::Impl::EntryIteratorImpl::entryExists() const
{
return (bool)(mIter->second);
}
LedgerKey const&
LedgerTxn::Impl::EntryIteratorImpl::key() const
{
return mIter->first;
}
std::unique_ptr<EntryIterator::AbstractImpl>
LedgerTxn::Impl::EntryIteratorImpl::clone() const
{
return std::make_unique<EntryIteratorImpl>(mIter, mEnd);
}
// Implementation of LedgerTxnRoot ------------------------------------------
LedgerTxnRoot::LedgerTxnRoot(Database& db, size_t entryCacheSize,
size_t bestOfferCacheSize,
size_t prefetchBatchSize)
: mImpl(std::make_unique<Impl>(db, entryCacheSize, bestOfferCacheSize,
prefetchBatchSize))
{
}
LedgerTxnRoot::Impl::Impl(Database& db, size_t entryCacheSize,
size_t bestOfferCacheSize, size_t prefetchBatchSize)
: mDatabase(db)
, mHeader(std::make_unique<LedgerHeader>())
, mEntryCache(entryCacheSize)
, mBestOffersCache(bestOfferCacheSize)
, mMaxCacheSize(entryCacheSize)
, mBulkLoadBatchSize(prefetchBatchSize)
, mChild(nullptr)
{
}
LedgerTxnRoot::~LedgerTxnRoot()
{
}
LedgerTxnRoot::Impl::~Impl()
{
if (mChild)
{
mChild->rollback();
}
}
void
LedgerTxnRoot::addChild(AbstractLedgerTxn& child)
{
mImpl->addChild(child);
}
void
LedgerTxnRoot::Impl::addChild(AbstractLedgerTxn& child)
{
if (mChild)
{
throw std::runtime_error("LedgerTxnRoot already has child");
}
mTransaction = std::make_unique<soci::transaction>(mDatabase.getSession());
mChild = &child;
}
void
LedgerTxnRoot::Impl::throwIfChild() const
{
if (mChild)
{
throw std::runtime_error("LedgerTxnRoot has child");
}
}
void
LedgerTxnRoot::commitChild(EntryIterator iter, LedgerTxnConsistency cons)
{
mImpl->commitChild(std::move(iter), cons);
}
static void
accum(EntryIterator const& iter, std::vector<EntryIterator>& upsertBuffer,
std::vector<EntryIterator>& deleteBuffer)
{
if (iter.entryExists())
upsertBuffer.emplace_back(iter);
else
deleteBuffer.emplace_back(iter);
}
void
BulkLedgerEntryChangeAccumulator::accumulate(EntryIterator const& iter)
{
switch (iter.key().type())
{
case ACCOUNT:
accum(iter, mAccountsToUpsert, mAccountsToDelete);
break;
case TRUSTLINE:
accum(iter, mTrustLinesToUpsert, mTrustLinesToDelete);
break;
case OFFER:
accum(iter, mOffersToUpsert, mOffersToDelete);
break;
case DATA:
accum(iter, mAccountDataToUpsert, mAccountDataToDelete);
break;
default:
abort();
}
}
void
LedgerTxnRoot::Impl::bulkApply(BulkLedgerEntryChangeAccumulator& bleca,
size_t bufferThreshold,
LedgerTxnConsistency cons)
{
auto& upsertAccounts = bleca.getAccountsToUpsert();
if (upsertAccounts.size() > bufferThreshold)
{
bulkUpsertAccounts(upsertAccounts);
upsertAccounts.clear();
}
auto& deleteAccounts = bleca.getAccountsToDelete();
if (deleteAccounts.size() > bufferThreshold)
{
bulkDeleteAccounts(deleteAccounts, cons);
deleteAccounts.clear();
}
auto& upsertTrustLines = bleca.getTrustLinesToUpsert();
if (upsertTrustLines.size() > bufferThreshold)
{
bulkUpsertTrustLines(upsertTrustLines);
upsertTrustLines.clear();
}
auto& deleteTrustLines = bleca.getTrustLinesToDelete();
if (deleteTrustLines.size() > bufferThreshold)
{
bulkDeleteTrustLines(deleteTrustLines, cons);
deleteTrustLines.clear();
}
auto& upsertOffers = bleca.getOffersToUpsert();
if (upsertOffers.size() > bufferThreshold)
{
bulkUpsertOffers(upsertOffers);
upsertOffers.clear();
}
auto& deleteOffers = bleca.getOffersToDelete();
if (deleteOffers.size() > bufferThreshold)
{
bulkDeleteOffers(deleteOffers, cons);
deleteOffers.clear();
}
auto& upsertAccountData = bleca.getAccountDataToUpsert();
if (upsertAccountData.size() > bufferThreshold)
{
bulkUpsertAccountData(upsertAccountData);
upsertAccountData.clear();
}
auto& deleteAccountData = bleca.getAccountDataToDelete();
if (deleteAccountData.size() > bufferThreshold)
{
bulkDeleteAccountData(deleteAccountData, cons);
deleteAccountData.clear();
}
}
void
LedgerTxnRoot::Impl::commitChild(EntryIterator iter, LedgerTxnConsistency cons)
{
// Assignment of xdrpp objects does not have the strong exception safety
// guarantee, so use std::unique_ptr<...>::swap to achieve it
auto childHeader = std::make_unique<LedgerHeader>(mChild->getHeader());
auto bleca = BulkLedgerEntryChangeAccumulator();
try
{
while ((bool)iter)
{
bleca.accumulate(iter);
++iter;
size_t bufferThreshold =
(bool)iter ? LEDGER_ENTRY_BATCH_COMMIT_SIZE : 0;
bulkApply(bleca, bufferThreshold, cons);
}
// NB: we want to clear the prepared statement cache _before_
// committing; on postgres this doesn't matter but on SQLite the passive
// WAL-auto-checkpointing-at-commit behaviour will starve if there are
// still prepared statements open at commit time.
mDatabase.clearPreparedStatementCache();
mTransaction->commit();
}
catch (std::exception& e)
{
printErrorAndAbort("fatal error during commit to LedgerTxnRoot: ",
e.what());
}
catch (...)
{
printErrorAndAbort(
"unknown fatal error during commit to LedgerTxnRoot");
}
// Clearing the cache does not throw
mBestOffersCache.clear();
mEntryCache.clear();
mPrefetchMetrics.clear();
// std::unique_ptr<...>::reset does not throw
mTransaction.reset();
// std::unique_ptr<...>::swap does not throw
mHeader.swap(childHeader);
mChild = nullptr;
}
std::string
LedgerTxnRoot::Impl::tableFromLedgerEntryType(LedgerEntryType let)
{
switch (let)
{
case ACCOUNT:
return "accounts";
case DATA:
return "accountdata";
case OFFER:
return "offers";
case TRUSTLINE:
return "trustlines";
default:
throw std::runtime_error("Unknown ledger entry type");
}
}
uint64_t
LedgerTxnRoot::countObjects(LedgerEntryType let) const
{
return mImpl->countObjects(let);
}
uint64_t
LedgerTxnRoot::Impl::countObjects(LedgerEntryType let) const
{
using namespace soci;
throwIfChild();
std::string query =
"SELECT COUNT(*) FROM " + tableFromLedgerEntryType(let) + ";";
uint64_t count = 0;
mDatabase.getSession() << query, into(count);
return count;
}
uint64_t
LedgerTxnRoot::countObjects(LedgerEntryType let,
LedgerRange const& ledgers) const
{
return mImpl->countObjects(let, ledgers);
}
uint64_t
LedgerTxnRoot::Impl::countObjects(LedgerEntryType let,
LedgerRange const& ledgers) const
{
using namespace soci;
throwIfChild();
std::string query = "SELECT COUNT(*) FROM " +
tableFromLedgerEntryType(let) +
" WHERE lastmodified >= :v1 AND lastmodified <= :v2;";
uint64_t count = 0;
int first = static_cast<int>(ledgers.mFirst);
int last = static_cast<int>(ledgers.mLast);
mDatabase.getSession() << query, into(count), use(first), use(last);
return count;
}
void
LedgerTxnRoot::deleteObjectsModifiedOnOrAfterLedger(uint32_t ledger) const
{
return mImpl->deleteObjectsModifiedOnOrAfterLedger(ledger);
}
void
LedgerTxnRoot::Impl::deleteObjectsModifiedOnOrAfterLedger(uint32_t ledger) const
{
using namespace soci;
throwIfChild();
mEntryCache.clear();
mBestOffersCache.clear();
for (auto let : {ACCOUNT, DATA, TRUSTLINE, OFFER})
{
std::string query = "DELETE FROM " + tableFromLedgerEntryType(let) +
" WHERE lastmodified >= :v1";
mDatabase.getSession() << query, use(ledger);
}
}
void
LedgerTxnRoot::dropAccounts()
{
mImpl->dropAccounts();
}
void
LedgerTxnRoot::dropData()
{
mImpl->dropData();
}
void
LedgerTxnRoot::dropOffers()
{
mImpl->dropOffers();
}
void
LedgerTxnRoot::dropTrustLines()
{
mImpl->dropTrustLines();
}
uint32_t
LedgerTxnRoot::prefetch(std::unordered_set<LedgerKey> const& keys)
{
return mImpl->prefetch(keys);
}
uint32_t
LedgerTxnRoot::Impl::prefetch(std::unordered_set<LedgerKey> const& keys)
{
uint32_t total = 0;
std::unordered_set<LedgerKey> accounts;
std::unordered_set<LedgerKey> offers;
std::unordered_set<LedgerKey> trustlines;
std::unordered_set<LedgerKey> data;
auto cacheResult =
[&](std::unordered_map<LedgerKey,
std::shared_ptr<LedgerEntry const>> const& res) {
for (auto const& item : res)
{
putInEntryCache(item.first, item.second, LoadType::PREFETCH);
++total;
}
};
auto insertIfNotLoaded = [&](std::unordered_set<LedgerKey>& keys,
LedgerKey const& key) {
if (!mEntryCache.exists(key, false))
{
keys.insert(key);
}
};
for (auto const& key : keys)
{
if ((static_cast<double>(mEntryCache.size()) / mMaxCacheSize) >=
ENTRY_CACHE_FILL_RATIO)
{
return total;
}
switch (key.type())
{
case ACCOUNT:
insertIfNotLoaded(accounts, key);
if (accounts.size() == mBulkLoadBatchSize)
{
cacheResult(bulkLoadAccounts(accounts));
accounts.clear();
}
break;
case OFFER:
insertIfNotLoaded(offers, key);
if (offers.size() == mBulkLoadBatchSize)
{
cacheResult(bulkLoadOffers(offers));
offers.clear();
}
break;
case TRUSTLINE:
insertIfNotLoaded(trustlines, key);
if (trustlines.size() == mBulkLoadBatchSize)
{
cacheResult(bulkLoadTrustLines(trustlines));
trustlines.clear();
}
break;
case DATA:
insertIfNotLoaded(data, key);
if (data.size() == mBulkLoadBatchSize)
{
cacheResult(bulkLoadData(data));
data.clear();
}
break;
}
}
// Prefetch whatever is remaining
cacheResult(bulkLoadAccounts(accounts));
cacheResult(bulkLoadOffers(offers));
cacheResult(bulkLoadTrustLines(trustlines));
cacheResult(bulkLoadData(data));
return total;
}
double
LedgerTxnRoot::getPrefetchHitRate() const
{
return mImpl->getPrefetchHitRate();
}
double
LedgerTxnRoot::Impl::getPrefetchHitRate() const
{
auto totalMisses = mEntryCache.getCounters().mMisses;
if (totalMisses == 0 && mTotalPrefetchHits == 0)
{
return 0;
}
return static_cast<double>(mTotalPrefetchHits) /
(totalMisses + mTotalPrefetchHits);
}
std::unordered_map<LedgerKey, LedgerEntry>
LedgerTxnRoot::getAllOffers()
{
return mImpl->getAllOffers();
}
std::unordered_map<LedgerKey, LedgerEntry>
LedgerTxnRoot::Impl::getAllOffers()
{
std::vector<LedgerEntry> offers;
try
{
offers = loadAllOffers();
}
catch (std::exception& e)
{
printErrorAndAbort(
"fatal error when getting all offers from LedgerTxnRoot: ",
e.what());
}
catch (...)
{
printErrorAndAbort(
"unknown fatal error when getting all offers from LedgerTxnRoot");
}
std::unordered_map<LedgerKey, LedgerEntry> offersByKey(offers.size());
for (auto const& offer : offers)
{
offersByKey.emplace(LedgerEntryKey(offer), offer);
}
return offersByKey;
}
std::shared_ptr<LedgerEntry const>
LedgerTxnRoot::getBestOffer(Asset const& buying, Asset const& selling,
std::unordered_set<LedgerKey>& exclude)
{
return mImpl->getBestOffer(buying, selling, exclude);
}
static std::shared_ptr<LedgerEntry const>
findIncludedOffer(std::list<LedgerEntry>::const_iterator iter,
std::list<LedgerEntry>::const_iterator const& end,
std::unordered_set<LedgerKey> const& exclude)
{
for (; iter != end; ++iter)
{
auto key = LedgerEntryKey(*iter);
if (exclude.find(key) == exclude.end())
{
return std::make_shared<LedgerEntry const>(*iter);
}
}
return {};
}
std::shared_ptr<LedgerEntry const>
LedgerTxnRoot::Impl::getBestOffer(Asset const& buying, Asset const& selling,
std::unordered_set<LedgerKey>& exclude)
{
// Note: Elements of mBestOffersCache are properly sorted lists of the best
// offers for a certain asset pair. This function maintaints the invariant
// that the lists of best offers remain properly sorted. The sort order is
// that determined by loadBestOffers and isBetterOffer (both induce the same
// order).
BestOffersCacheEntry emptyCacheEntry{{}, false};
auto& cached = getFromBestOffersCache(buying, selling, emptyCacheEntry);
auto& offers = cached.bestOffers;
auto res = findIncludedOffer(offers.cbegin(), offers.cend(), exclude);
size_t const BATCH_SIZE = 5;
while (!res && !cached.allLoaded)
{
std::list<LedgerEntry>::const_iterator newOfferIter;
try
{
newOfferIter = loadBestOffers(offers, buying, selling, BATCH_SIZE,
offers.size());
}
catch (std::exception& e)
{
printErrorAndAbort(
"fatal error when getting best offer from LedgerTxnRoot: ",
e.what());
}
catch (...)
{
printErrorAndAbort("unknown fatal error when getting best offer "
"from LedgerTxnRoot");
}
if (std::distance(newOfferIter, offers.cend()) < BATCH_SIZE)
{
cached.allLoaded = true;
}
res = findIncludedOffer(newOfferIter, offers.cend(), exclude);
}
if (res)
{
putInEntryCache(LedgerEntryKey(*res), res, LoadType::IMMEDIATE);
}
return res;
}
std::unordered_map<LedgerKey, LedgerEntry>
LedgerTxnRoot::getOffersByAccountAndAsset(AccountID const& account,
Asset const& asset)
{
return mImpl->getOffersByAccountAndAsset(account, asset);
}
std::unordered_map<LedgerKey, LedgerEntry>
LedgerTxnRoot::Impl::getOffersByAccountAndAsset(AccountID const& account,
Asset const& asset)
{
std::vector<LedgerEntry> offers;
try
{
offers = loadOffersByAccountAndAsset(account, asset);
}
catch (std::exception& e)
{
printErrorAndAbort("fatal error when getting offers by account and "
"asset from LedgerTxnRoot: ",
e.what());
}
catch (...)
{
printErrorAndAbort("unknown fatal error when getting offers by account "
"and asset from LedgerTxnRoot");
}
std::unordered_map<LedgerKey, LedgerEntry> res(offers.size());
for (auto const& offer : offers)
{
res.emplace(LedgerEntryKey(offer), offer);
}
return res;
}
LedgerHeader const&
LedgerTxnRoot::getHeader() const
{
return mImpl->getHeader();
}
LedgerHeader const&
LedgerTxnRoot::Impl::getHeader() const
{
return *mHeader;
}
std::vector<InflationWinner>
LedgerTxnRoot::getInflationWinners(size_t maxWinners, int64_t minVotes)
{
return mImpl->getInflationWinners(maxWinners, minVotes);
}
std::vector<InflationWinner>
LedgerTxnRoot::Impl::getInflationWinners(size_t maxWinners, int64_t minVotes)
{
try
{
return loadInflationWinners(maxWinners, minVotes);
}
catch (std::exception& e)
{
printErrorAndAbort(
"fatal error when getting inflation winners from LedgerTxnRoot: ",
e.what());
}
catch (...)
{
printErrorAndAbort("unknown fatal error when getting inflation winners "
"from LedgerTxnRoot");
}
}
std::shared_ptr<LedgerEntry const>
LedgerTxnRoot::getNewestVersion(LedgerKey const& key) const
{
return mImpl->getNewestVersion(key);
}
std::shared_ptr<LedgerEntry const>
LedgerTxnRoot::Impl::getNewestVersion(LedgerKey const& key) const
{
if (mEntryCache.exists(key))
{
return getFromEntryCache(key);
}
else
{
auto& metrics = mPrefetchMetrics[key];
++metrics.misses;
}
std::shared_ptr<LedgerEntry const> entry;
try
{
switch (key.type())
{
case ACCOUNT:
entry = loadAccount(key);
break;
case DATA:
entry = loadData(key);
break;
case OFFER:
entry = loadOffer(key);
break;
case TRUSTLINE:
entry = loadTrustLine(key);
break;
default:
throw std::runtime_error("Unknown key type");
}
}
catch (std::exception& e)
{
printErrorAndAbort(
"fatal error when loading ledger entry from LedgerTxnRoot: ",
e.what());
}
catch (...)
{
printErrorAndAbort("unknown fatal error when loading ledger entry from "
"LedgerTxnRoot");
}
putInEntryCache(key, entry, LoadType::IMMEDIATE);
return entry;
}
void
LedgerTxnRoot::rollbackChild()
{
mImpl->rollbackChild();
}
void
LedgerTxnRoot::Impl::rollbackChild()
{
try
{
mTransaction->rollback();
mTransaction.reset();
}
catch (std::exception& e)
{
printErrorAndAbort(
"fatal error when rolling back child of LedgerTxnRoot: ", e.what());
}
catch (...)
{
printErrorAndAbort(
"unknown fatal error when rolling back child of LedgerTxnRoot");
}
mChild = nullptr;
}
std::shared_ptr<LedgerEntry const>
LedgerTxnRoot::Impl::getFromEntryCache(LedgerKey const& key) const
{
try
{
auto cached = mEntryCache.get(key);
if (cached.type == LoadType::PREFETCH)
{
auto metric = mPrefetchMetrics.find(key);
if (metric == mPrefetchMetrics.end())
{
throw std::runtime_error(
"Inconsistent state when retrieving entry from cache");
}
++metric->second.hits;
++mTotalPrefetchHits;
}
return cached.entry;
}
catch (...)
{
mEntryCache.clear();
throw;
}
}
void
LedgerTxnRoot::Impl::putInEntryCache(
LedgerKey const& key, std::shared_ptr<LedgerEntry const> const& entry,
LoadType type) const
{
try
{
mEntryCache.put(key, {entry, type});
if (type == LoadType::PREFETCH)
{
if (mPrefetchMetrics.find(key) != mPrefetchMetrics.end())
{
throw std::runtime_error(
"Inconsistent state when putting entry into cache");
}
mPrefetchMetrics.emplace(key, KeyAccesses{});
}
}
catch (...)
{
mEntryCache.clear();
throw;
}
}
LedgerTxnRoot::Impl::BestOffersCacheEntry&
LedgerTxnRoot::Impl::getFromBestOffersCache(
Asset const& buying, Asset const& selling,
BestOffersCacheEntry& defaultValue) const
{
try
{
auto cacheKey = binToHex(xdr::xdr_to_opaque(buying)) +
binToHex(xdr::xdr_to_opaque(selling));
if (!mBestOffersCache.exists(cacheKey))
{
mBestOffersCache.put(cacheKey, defaultValue);
}
return mBestOffersCache.exists(cacheKey)
? mBestOffersCache.get(cacheKey)
: defaultValue;
}
catch (...)
{
mBestOffersCache.clear();
throw;
}
}
}
| 26.308151 | 80 | 0.614298 | iotbda |
a1ece040b78f3331820ba38d3599e78508bee0d0 | 4,916 | cpp | C++ | pre-main/provision/COMPONENT_AWSIOT_PKCS11PSA/provision_psa.cpp | OpenNuvoton/NuMaker-mbed-AWS-IoT-CSDK-OTA-example | 81e535a84d42811f63cd2a53280e5292e877d914 | [
"Apache-2.0"
] | 2 | 2021-09-21T08:18:03.000Z | 2022-01-25T00:56:11.000Z | pre-main/provision/COMPONENT_AWSIOT_PKCS11PSA/provision_psa.cpp | OpenNuvoton/NuMaker-mbed-AWS-IoT-CSDK-OTA-example | 81e535a84d42811f63cd2a53280e5292e877d914 | [
"Apache-2.0"
] | null | null | null | pre-main/provision/COMPONENT_AWSIOT_PKCS11PSA/provision_psa.cpp | OpenNuvoton/NuMaker-mbed-AWS-IoT-CSDK-OTA-example | 81e535a84d42811f63cd2a53280e5292e877d914 | [
"Apache-2.0"
] | 3 | 2021-09-30T09:35:00.000Z | 2022-03-25T09:12:04.000Z | /*
* AWS IoT Device SDK for Embedded C 202012.01
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* 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.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/* Standard includes */
#include <stdio.h>
#include <string.h>
/* Mbed includes */
#include "mbed.h"
/* AWS credentials includes */
#include "aws_credentials.h"
/* PKCS11 includes */
#include "core_pkcs11_config.h"
#include "core_pkcs11.h"
#include "iot_pkcs11_psa_object_management.h"
#include "iot_pkcs11_psa_input_format.h"
#include "provision_psa_utils.h"
/* Check weak reference/definition at the link:
* http://www.keil.com/support/man/docs/ARMLINK/armlink_pge1362065917715.htm */
extern "C" {
MBED_USED void provision(void);
}
static void provision_install_rootca_crt(void);
static void provision_install_device_crt(void);
static void provision_install_device_pubkey(void);
static void provision_install_device_pvtkey(void);
static void provision_install_codever_pubkey(void);
void provision(void)
{
provision_install_rootca_crt();
provision_install_device_crt();
provision_install_device_pubkey();
provision_install_device_pvtkey();
provision_install_codever_pubkey();
}
/* Install root CA certificate */
void provision_install_rootca_crt(void)
{
printf("PROV: Install root CA certificate...\r\n");
provpsa_install_nonconf((const unsigned char *) aws_rootCACrt,
strlen(aws_rootCACrt) + 1,
PSA_ROOT_CERTIFICATE_UID);
printf("PROV: Install root CA certificate...OK\r\n");
}
/* Install device certificate */
void provision_install_device_crt(void)
{
printf("PROV: Install device certificate...\r\n");
provpsa_install_nonconf((const unsigned char *) aws_deviceCrt,
strlen(aws_deviceCrt) + 1,
PSA_DEVICE_CERTIFICATE_UID);
printf("PROV: Install device certificate...OK\r\n");
}
/* Install device public key */
void provision_install_device_pubkey(void)
{
printf("PROV: Install device public key...\r\n");
provpsa_install_pvtpub((const unsigned char *) aws_devicePubKey,
strlen(aws_devicePubKey) + 1,
PSA_DEVICE_PUBLIC_KEY_ID,
false);
printf("PROV: Install device public key...OK\r\n");
}
/* Install device private key */
void provision_install_device_pvtkey(void)
{
printf("PROV: Install device private key...\r\n");
provpsa_install_pvtpub((const unsigned char *) aws_devicePvtKey,
strlen(aws_devicePvtKey) + 1,
PSA_DEVICE_PRIVATE_KEY_ID,
true);
provpsa_install_pvtpub_extra_nonconf((const unsigned char *) aws_devicePvtKey,
strlen(aws_devicePvtKey) + 1,
PSA_DEVICE_PRIVATE_KEY_ID,
PSA_DEVICE_PRIVATE_KEY_UID);
printf("PROV: Install device private key...OK\r\n");
}
void provision_install_codever_crt(void)
{
printf("PROV: Install code verification certificate...\r\n");
provpsa_install_nonconf((const unsigned char *) aws_codeVerCrt,
strlen(aws_codeVerCrt) + 1,
PSA_CODE_VERIFICATION_CERTIFICATE_UID);
printf("PROV: Install code verification certificate...OK\r\n");
}
/* Install code verification public key */
void provision_install_codever_pubkey(void)
{
printf("PROV: Install code verification public key...\r\n");
provpsa_install_pubkey_by_crt((const unsigned char *) aws_codeVerCrt,
strlen(aws_codeVerCrt) + 1,
PSA_CODE_VERIFICATION_KEY_ID);
printf("PROV: Install code verification public key...OK\r\n");
}
| 38.108527 | 83 | 0.682059 | OpenNuvoton |
a1ed99a949bae294bc8d8e06284c85325597642c | 2,435 | cc | C++ | src/foundation/memory/allocators/eastl_allocator.cc | ProjectSulphur/ProjectSulphur | cb9ee8298f5020fda4a9130802e72034408f050f | [
"Apache-2.0"
] | 11 | 2017-12-19T14:33:02.000Z | 2022-03-26T00:34:48.000Z | src/foundation/memory/allocators/eastl_allocator.cc | ProjectSulphur/ProjectSulphur | cb9ee8298f5020fda4a9130802e72034408f050f | [
"Apache-2.0"
] | 1 | 2018-05-28T10:32:32.000Z | 2018-05-28T10:32:35.000Z | src/foundation/memory/allocators/eastl_allocator.cc | ProjectSulphur/ProjectSulphur | cb9ee8298f5020fda4a9130802e72034408f050f | [
"Apache-2.0"
] | 1 | 2021-01-25T11:31:57.000Z | 2021-01-25T11:31:57.000Z | #include "eastl_allocator.h"
#include "allocator.h"
#include "../memory.h"
#include "foundation/utils/macro.h"
namespace sulphur
{
namespace foundation
{
//--------------------------------------------------------------------------
EASTLAllocator::EASTLAllocator(const char* pName) :
allocator_(&Memory::default_allocator())
{
PS_UNUSED_IN_RELEASE(pName);
#if EASTL_NAME_ENABLED
name_ = pName ? pName : EASTL_ALLOCATOR_DEFAULT_NAME;
#endif
}
//--------------------------------------------------------------------------
EASTLAllocator::EASTLAllocator(const eastl::allocator&, const char* pName) :
allocator_(&Memory::default_allocator())
{
PS_UNUSED_IN_RELEASE(pName);
#if EASTL_NAME_ENABLED
name_ = pName ? pName : EASTL_ALLOCATOR_DEFAULT_NAME;
#endif
}
//--------------------------------------------------------------------------
EASTLAllocator::~EASTLAllocator()
{
}
//--------------------------------------------------------------------------
EASTLAllocator& EASTLAllocator::operator=(const EASTLAllocator& x)
{
allocator_ = x.allocator_;
return *this;
}
//--------------------------------------------------------------------------
bool EASTLAllocator::operator==(const EASTLAllocator&)
{
return true;
}
//--------------------------------------------------------------------------
void* EASTLAllocator::allocate(size_t n, int)
{
return allocate(n, 16u, 0, 0);
}
//--------------------------------------------------------------------------
void* EASTLAllocator::allocate(size_t n, size_t alignment, size_t, int)
{
return foundation::Memory::Allocate(n, alignment, allocator_);
}
//--------------------------------------------------------------------------
void EASTLAllocator::deallocate(void* ptr, size_t)
{
foundation::Memory::Deallocate(ptr);
}
//--------------------------------------------------------------------------
void EASTLAllocator::set_name(const char* name)
{
PS_UNUSED_IN_RELEASE(name);
#if EASTL_NAME_ENABLED
name_ = name;
#endif
}
//--------------------------------------------------------------------------
const char* EASTLAllocator::name() const
{
#if EASTL_NAME_ENABLED
return name_;
#else
return "Custom EASTL allocator";
#endif
}
}
}
| 27.055556 | 80 | 0.439425 | ProjectSulphur |
a1f02e2c05ff3c1e0d7d91a180bb903d8659241d | 917 | cpp | C++ | ext/emsdk_portable/clang/tag-e1.34.1/src/lib/Transforms/MinSFI/Utils.cpp | slightperturbation/Cobalt | 7b398d155d28f7ddf4068a6c25c8aa6aaae486d4 | [
"Apache-2.0"
] | null | null | null | ext/emsdk_portable/clang/tag-e1.34.1/src/lib/Transforms/MinSFI/Utils.cpp | slightperturbation/Cobalt | 7b398d155d28f7ddf4068a6c25c8aa6aaae486d4 | [
"Apache-2.0"
] | null | null | null | ext/emsdk_portable/clang/tag-e1.34.1/src/lib/Transforms/MinSFI/Utils.cpp | slightperturbation/Cobalt | 7b398d155d28f7ddf4068a6c25c8aa6aaae486d4 | [
"Apache-2.0"
] | null | null | null | //===-- Utils.cpp - Helper functions for MinSFI passes --------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/CommandLine.h"
#include "llvm/Transforms/MinSFI.h"
using namespace llvm;
static cl::opt<uint32_t>
PointerSizeInBits("minsfi-ptrsize", cl::init(32),
cl::desc("Size of the address subspace in bits"));
uint32_t minsfi::GetPointerSizeInBits() {
if (PointerSizeInBits < 20 || PointerSizeInBits > 32)
report_fatal_error("MinSFI: Size of the sandboxed pointers is out of "
"bounds (20-32)");
return PointerSizeInBits;
}
uint64_t minsfi::GetAddressSubspaceSize() {
return 1LL << GetPointerSizeInBits();
}
| 31.62069 | 80 | 0.604144 | slightperturbation |
a1f15fa1142745877dfecc1ffc9baba9c8a3e427 | 3,785 | cpp | C++ | src/OpenSpaceToolkit/Physics/Time/Scale.cpp | robinpdm/open-space-toolkit-physics | b53e5d4287fa6568d700cb8942c9a56d57b8d7cf | [
"Apache-2.0"
] | 7 | 2020-03-30T11:51:11.000Z | 2022-02-02T15:20:44.000Z | src/OpenSpaceToolkit/Physics/Time/Scale.cpp | robinpdm/open-space-toolkit-physics | b53e5d4287fa6568d700cb8942c9a56d57b8d7cf | [
"Apache-2.0"
] | 24 | 2018-06-25T08:06:39.000Z | 2020-01-05T20:34:02.000Z | src/OpenSpaceToolkit/Physics/Time/Scale.cpp | robinpdm/open-space-toolkit-physics | b53e5d4287fa6568d700cb8942c9a56d57b8d7cf | [
"Apache-2.0"
] | 3 | 2020-03-05T18:18:38.000Z | 2020-07-02T05:06:53.000Z | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @project Open Space Toolkit ▸ Physics
/// @file OpenSpaceToolkit/Physics/Time/Scale.cpp
/// @author Lucas Brémond <lucas@loftorbital.com>
/// @license Apache License 2.0
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <OpenSpaceToolkit/Physics/Time/Scale.hpp>
#include <OpenSpaceToolkit/Core/Error.hpp>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace ostk
{
namespace physics
{
namespace time
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
String StringFromScale ( const Scale& aScale )
{
switch (aScale)
{
case Scale::Undefined:
return "Undefined" ;
case Scale::UTC:
return "UTC" ;
case Scale::TT:
return "TT" ;
case Scale::TAI:
return "TAI" ;
case Scale::UT1:
return "UT1" ;
case Scale::TCG:
return "TCG" ;
case Scale::TCB:
return "TCB" ;
case Scale::TDB:
return "TDB" ;
case Scale::GMST:
return "GMST" ;
case Scale::GPST:
return "GPST" ;
case Scale::GST:
return "GST" ;
case Scale::GLST:
return "GLST" ;
case Scale::BDT:
return "BDT" ;
case Scale::QZSST:
return "QZSST" ;
case Scale::IRNSST:
return "IRNSST" ;
default:
throw ostk::core::error::runtime::Wrong("Scale") ;
break ;
}
return String::Empty() ;
}
Scale ScaleFromString ( const String& aString )
{
if (aString == "Undefined")
{
return Scale::Undefined ;
}
if (aString == "UTC")
{
return Scale::UTC ;
}
if (aString == "TT")
{
return Scale::TT ;
}
if (aString == "TAI")
{
return Scale::TAI ;
}
if (aString == "UT1")
{
return Scale::UT1 ;
}
if (aString == "TCG")
{
return Scale::TCG ;
}
if (aString == "TCB")
{
return Scale::TCB ;
}
if (aString == "TDB")
{
return Scale::TDB ;
}
if (aString == "GMST")
{
return Scale::GMST ;
}
if (aString == "GPST")
{
return Scale::GPST ;
}
if (aString == "GST")
{
return Scale::GST ;
}
if (aString == "GLST")
{
return Scale::GLST ;
}
if (aString == "BDT")
{
return Scale::BDT ;
}
if (aString == "QZSST")
{
return Scale::QZSST ;
}
if (aString == "IRNSST")
{
return Scale::IRNSST ;
}
throw ostk::core::error::runtime::Wrong("Scale", aString) ;
return Scale::Undefined ;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| 21.384181 | 161 | 0.321532 | robinpdm |
a1f32114d46d4b4ca99ed7d8e7b1031fa61e501e | 30,239 | cpp | C++ | code/engine.vc2008/xrGame/ActorCondition.cpp | Pavel3333/xray-oxygen | 42331cd5f30511214c704d6ca9d919c209363eea | [
"Apache-2.0"
] | null | null | null | code/engine.vc2008/xrGame/ActorCondition.cpp | Pavel3333/xray-oxygen | 42331cd5f30511214c704d6ca9d919c209363eea | [
"Apache-2.0"
] | null | null | null | code/engine.vc2008/xrGame/ActorCondition.cpp | Pavel3333/xray-oxygen | 42331cd5f30511214c704d6ca9d919c209363eea | [
"Apache-2.0"
] | null | null | null | #include "stdafx.h"
#include "actorcondition.h"
#include "actor.h"
#include "actorEffector.h"
#include "inventory.h"
#include "level.h"
#include "sleepeffector.h"
#include "game_base.h"
#include "xrserver.h"
#include "ai_space.h"
#include "script_callback_ex.h"
#include "script_game_object.h"
#include "game_object_space.h"
#include "script_callback_ex.h"
#include "object_broker.h"
#include "weapon.h"
#include "PDA.h"
#include "ai/monsters/basemonster/base_monster.h"
#include "UIGame.h"
#include "ui/UIMainIngameWnd.h"
#include "ui/UIStatic.h"
BOOL GodMode()
{
return psActorFlags.test(AF_GODMODE);
}
CActorCondition::CActorCondition(CActor *object) :
inherited (object)
{
m_fJumpPower = 0.f;
m_fStandPower = 0.f;
m_fWalkPower = 0.f;
m_fJumpWeightPower = 0.f;
m_fWalkWeightPower = 0.f;
m_fOverweightWalkK = 0.f;
m_fOverweightJumpK = 0.f;
m_fAccelK = 0.f;
m_fSprintK = 0.f;
m_fAlcohol = 0.f;
m_fSatiety = 1.0f;
m_fThirst = 1.0f;
// m_vecBoosts.clear();
VERIFY (object);
m_object = object;
m_condition_flags.zero ();
m_death_effector = nullptr;
m_zone_max_power[ALife::infl_rad] = 1.0f;
m_zone_max_power[ALife::infl_fire] = 1.0f;
m_zone_max_power[ALife::infl_acid] = 1.0f;
m_zone_max_power[ALife::infl_psi] = 1.0f;
m_zone_max_power[ALife::infl_electra]= 1.0f;
m_zone_danger[ALife::infl_rad] = 0.0f;
m_zone_danger[ALife::infl_fire] = 0.0f;
m_zone_danger[ALife::infl_acid] = 0.0f;
m_zone_danger[ALife::infl_psi] = 0.0f;
m_zone_danger[ALife::infl_electra]= 0.0f;
m_f_time_affected = Device.fTimeGlobal;
m_max_power_restore_speed = 0.0f;
m_max_wound_protection = 0.0f;
m_max_fire_wound_protection = 0.0f;
}
CActorCondition::~CActorCondition()
{
xr_delete( m_death_effector );
}
void CActorCondition::LoadCondition(LPCSTR entity_section)
{
inherited::LoadCondition(entity_section);
LPCSTR section = READ_IF_EXISTS(pSettings,r_string,entity_section,"condition_sect",entity_section);
m_fJumpPower = pSettings->r_float(section,"jump_power");
m_fStandPower = pSettings->r_float(section,"stand_power");
m_fWalkPower = pSettings->r_float(section,"walk_power");
m_fJumpWeightPower = pSettings->r_float(section,"jump_weight_power");
m_fWalkWeightPower = pSettings->r_float(section,"walk_weight_power");
m_fOverweightWalkK = pSettings->r_float(section,"overweight_walk_k");
m_fOverweightJumpK = pSettings->r_float(section,"overweight_jump_k");
m_fAccelK = pSettings->r_float(section,"accel_k");
m_fSprintK = pSettings->r_float(section,"sprint_k");
//порог силы и здоровья меньше которого актер начинает хромать
m_fLimpingHealthBegin = pSettings->r_float(section, "limping_health_begin");
m_fLimpingHealthEnd = pSettings->r_float(section, "limping_health_end");
R_ASSERT (m_fLimpingHealthBegin<=m_fLimpingHealthEnd);
m_fLimpingPowerBegin = pSettings->r_float(section, "limping_power_begin");
m_fLimpingPowerEnd = pSettings->r_float(section, "limping_power_end");
R_ASSERT (m_fLimpingPowerBegin<=m_fLimpingPowerEnd);
m_fCantWalkPowerBegin = pSettings->r_float(section, "cant_walk_power_begin");
m_fCantWalkPowerEnd = pSettings->r_float(section, "cant_walk_power_end");
R_ASSERT (m_fCantWalkPowerBegin<=m_fCantWalkPowerEnd);
m_fCantSprintPowerBegin = pSettings->r_float(section, "cant_sprint_power_begin");
m_fCantSprintPowerEnd = pSettings->r_float(section, "cant_sprint_power_end");
R_ASSERT (m_fCantSprintPowerBegin<=m_fCantSprintPowerEnd);
m_fPowerLeakSpeed = pSettings->r_float(section,"max_power_leak_speed");
m_fV_Alcohol = pSettings->r_float(section,"alcohol_v");
m_fSatietyCritical = pSettings->r_float(section,"satiety_critical");
clamp (m_fSatietyCritical, 0.0f, 1.0f);
m_fV_Satiety = pSettings->r_float(section,"satiety_v");
m_fV_SatietyPower = pSettings->r_float(section,"satiety_power_v");
m_fV_SatietyHealth = pSettings->r_float(section,"satiety_health_v");
if (g_extraFeatures.is(GAME_EXTRA_THIRST))
{
m_fThirstCritical = pSettings->r_float(section, "thirst_critical");
clamp(m_fThirstCritical, 0.0f, 1.0f);
m_fV_Thirst = pSettings->r_float(section, "thirst_v");
m_fV_ThirstPower = pSettings->r_float(section, "thirst_power_v");
m_fV_ThirstHealth = pSettings->r_float(section, "thirst_health_v");
}
m_MaxWalkWeight = pSettings->r_float(section,"max_walk_weight");
m_zone_max_power[ALife::infl_rad] = pSettings->r_float(section, "radio_zone_max_power" );
m_zone_max_power[ALife::infl_fire] = pSettings->r_float(section, "fire_zone_max_power" );
m_zone_max_power[ALife::infl_acid] = pSettings->r_float(section, "acid_zone_max_power" );
m_zone_max_power[ALife::infl_psi] = pSettings->r_float(section, "psi_zone_max_power" );
m_zone_max_power[ALife::infl_electra]= pSettings->r_float(section, "electra_zone_max_power" );
m_max_power_restore_speed = pSettings->r_float(section, "max_power_restore_speed" );
m_max_wound_protection = READ_IF_EXISTS(pSettings,r_float,section,"max_wound_protection",1.0f);
m_max_fire_wound_protection = READ_IF_EXISTS(pSettings,r_float,section,"max_fire_wound_protection",1.0f);
VERIFY( !fis_zero(m_zone_max_power[ALife::infl_rad]) );
VERIFY( !fis_zero(m_zone_max_power[ALife::infl_fire]) );
VERIFY( !fis_zero(m_zone_max_power[ALife::infl_acid]) );
VERIFY( !fis_zero(m_zone_max_power[ALife::infl_psi]) );
VERIFY( !fis_zero(m_zone_max_power[ALife::infl_electra]) );
VERIFY( !fis_zero(m_max_power_restore_speed) );
}
float CActorCondition::GetZoneMaxPower( ALife::EInfluenceType type) const
{
if ( type < ALife::infl_rad || ALife::infl_electra < type )
{
return 1.0f;
}
return m_zone_max_power[type];
}
float CActorCondition::GetZoneMaxPower( ALife::EHitType hit_type ) const
{
ALife::EInfluenceType iz_type = ALife::infl_max_count;
switch( hit_type )
{
case ALife::eHitTypeRadiation: iz_type = ALife::infl_rad; break;
case ALife::eHitTypeLightBurn: iz_type = ALife::infl_fire; break;
case ALife::eHitTypeBurn: iz_type = ALife::infl_fire; break;
case ALife::eHitTypeChemicalBurn: iz_type = ALife::infl_acid; break;
case ALife::eHitTypeTelepatic: iz_type = ALife::infl_psi; break;
case ALife::eHitTypeShock: iz_type = ALife::infl_electra; break;
case ALife::eHitTypeStrike:
case ALife::eHitTypeExplosion:
case ALife::eHitTypeFireWound:
case ALife::eHitTypeWound_2:
// case ALife::eHitTypePhysicStrike:
return 1.0f;
case ALife::eHitTypeWound:
return m_max_wound_protection;
default:
NODEFAULT;
}
return GetZoneMaxPower( iz_type );
}
float CActorCondition::GetBoosterValueByType(EBoostParams type) const
{
auto BoostInfluenceIter = m_booster_influences.find(type);
if (BoostInfluenceIter != m_booster_influences.end())
{
return BoostInfluenceIter->second.fBoostValue;
}
return 0.0f;
}
void CActorCondition::UpdateCondition()
{
if (GodMode())
{
UpdateSatiety();
UpdateBoosters();
if (g_extraFeatures.is(GAME_EXTRA_THIRST))
UpdateThirst();
m_fAlcohol += m_fV_Alcohol * m_fDeltaTime;
clamp(m_fAlcohol, 0.0f, 1.0f);
CEffectorCam* ce = Actor()->Cameras().GetCamEffector((ECamEffectorType)effAlcohol);
if (ce)
RemoveEffector(m_object, effAlcohol);
return;
}
if (!object().g_Alive())
return;
if (!object().Local() && m_object != Level().CurrentViewEntity())
return;
float base_weight = object().MaxCarryWeight();
float cur_weight = object().inventory().TotalWeight();
if ((object().mstate_real & mcAnyMove))
{
ConditionWalk(cur_weight / base_weight,
isActorAccelerated(object().mstate_real, object().IsZoomAimingMode()),
(object().mstate_real & mcSprint) != 0);
}
else
ConditionStand(cur_weight / base_weight);
float k_max_power = 1.0f + std::min(cur_weight, base_weight) / base_weight + std::max(0.0f, (cur_weight - base_weight) / 10.0f);
SetMaxPower(GetMaxPower() - m_fPowerLeakSpeed * m_fDeltaTime * k_max_power);
m_fAlcohol += m_fV_Alcohol * m_fDeltaTime;
clamp(m_fAlcohol, 0.0f, 1.0f);
CEffectorCam* ce = Actor()->Cameras().GetCamEffector((ECamEffectorType)effAlcohol);
if (m_fAlcohol > 0.01f)
{
if (!ce)
AddEffector(m_object, effAlcohol, "effector_alcohol", GET_KOEFF_FUNC(this, &CActorCondition::GetAlcohol));
}
else
{
if (ce)
RemoveEffector(m_object, effAlcohol);
}
string512 pp_sect_name;
shared_str ln = Level().name();
if (ln.size())
{
CEffectorPP* ppe = object().Cameras().GetPPEffector((EEffectorPPType)effPsyHealth);
strconcat(sizeof(pp_sect_name), pp_sect_name, "effector_psy_health", "_", *ln);
if (!pSettings->section_exist(pp_sect_name))
xr_strcpy(pp_sect_name, "effector_psy_health");
if (!fsimilar(GetPsyHealth(), 1.0f, 0.05f))
{
if (!ppe)
AddEffector(m_object, effPsyHealth, pp_sect_name, GET_KOEFF_FUNC(this, &CActorCondition::GetPsy));
}
else
{
if (ppe)
RemoveEffector(m_object, effPsyHealth);
}
}
UpdateSatiety();
UpdateBoosters();
if (g_extraFeatures.is(GAME_EXTRA_THIRST))
UpdateThirst();
inherited::UpdateCondition();
UpdateTutorialThresholds();
if (GetHealth() < 0.05f && !m_death_effector)
{
if (pSettings->section_exist("actor_death_effector"))
m_death_effector = xr_new<CActorDeathEffector>(this, "actor_death_effector");
}
if (m_death_effector && m_death_effector->IsActual())
{
m_death_effector->UpdateCL();
if (!m_death_effector->IsActual())
m_death_effector->Stop();
}
AffectDamage_InjuriousMaterialAndMonstersInfluence();
}
void CActorCondition::UpdateBoosters()
{
for(u8 i=0;i<eBoostMaxCount;i++)
{
BOOSTER_MAP::iterator it = m_booster_influences.find((EBoostParams)i);
if(it!=m_booster_influences.end())
{
it->second.fBoostTime -= m_fDeltaTime / Level().GetGameTimeFactor();
if(it->second.fBoostTime<=0.0f)
{
DisableBoostParameters(it->second);
m_booster_influences.erase(it);
}
}
}
if(m_object == Level().CurrentViewEntity())
GameUI()->UIMainIngameWnd->UpdateBoosterIndicators(m_booster_influences);
}
void CActorCondition::AffectDamage_InjuriousMaterialAndMonstersInfluence()
{
float one = 0.1f;
float tg = Device.fTimeGlobal;
if ( m_f_time_affected + one > tg )
{
return;
}
clamp( m_f_time_affected, tg - (one * 3), tg );
float psy_influence = 0;
float fire_influence = 0;
float radiation_influence = GetInjuriousMaterialDamage(); // Get Radiation from Material
// Add Radiation and Psy Level from Monsters
CPda* const pda = m_object->GetPDA();
if ( pda )
{
using monsters = xr_vector<CObject*>;
for ( monsters::const_iterator it = pda->feel_touch.begin();
it != pda->feel_touch.end();
++it )
{
CBaseMonster* const monster = smart_cast<CBaseMonster*>(*it);
if ( !monster || !monster->g_Alive() ) continue;
psy_influence += monster->get_psy_influence();
radiation_influence += monster->get_radiation_influence();
fire_influence += monster->get_fire_influence();
}
}
struct
{
ALife::EHitType type;
float value;
} hits[] = { { ALife::eHitTypeRadiation, radiation_influence * one },
{ ALife::eHitTypeTelepatic, psy_influence * one },
{ ALife::eHitTypeBurn, fire_influence * one } };
NET_Packet np;
while ( m_f_time_affected + one < tg )
{
m_f_time_affected += one;
for (auto & hit : hits)
{
float damage = hit.value;
ALife::EHitType type = hit.type;
if ( damage > EPS )
{
SHit HDS = SHit(damage,
//. 0.0f,
Fvector().set(0,1,0),
nullptr,
BI_NONE,
Fvector().set(0,0,0),
0.0f,
type,
0.0f,
false);
HDS.GenHeader(GE_HIT, m_object->ID());
HDS.Write_Packet( np );
CGameObject::u_EventSend( np );
}
} // for
}//while
}
#include "characterphysicssupport.h"
float CActorCondition::GetInjuriousMaterialDamage()
{
u16 mat_injurios = m_object->character_physics_support()->movement()->injurious_material_idx();
if(mat_injurios!=GAMEMTL_NONE_IDX)
{
const SGameMtl* mtl = GMLib.GetMaterialByIdx(mat_injurios);
return mtl->fInjuriousSpeed;
}else
return 0.0f;
}
void CActorCondition::SetZoneDanger( float danger, ALife::EInfluenceType type )
{
VERIFY( type != ALife::infl_max_count );
m_zone_danger[type] = danger;
clamp( m_zone_danger[type], 0.0f, 1.0f );
}
float CActorCondition::GetZoneDanger() const
{
float sum = 0.0f;
for ( u8 i = 1; i < ALife::infl_max_count; ++i )
{
sum += m_zone_danger[i];
}
clamp( sum, 0.0f, 1.5f );
return sum;
}
void CActorCondition::UpdateRadiation()
{
inherited::UpdateRadiation();
}
void CActorCondition::UpdateSatiety()
{
if (m_fSatiety > 0.f)
{
m_fSatiety -= m_fV_Satiety * m_fDeltaTime;
clamp(m_fSatiety, 0.0f, 1.0f);
}
float satiety_health_koef = (m_fSatiety - m_fSatietyCritical) / (m_fSatiety >= m_fSatietyCritical ? 1 - m_fSatietyCritical : m_fSatietyCritical);
if (CanBeHarmed() && !GodMode())
{
m_fDeltaHealth += m_fV_SatietyHealth * satiety_health_koef*m_fDeltaTime;
m_fDeltaPower += m_fV_SatietyPower * m_fSatiety*m_fDeltaTime;
}
}
void CActorCondition::UpdateThirst()
{
if (m_fThirst>0)
{
m_fThirst -= m_fV_Thirst*m_fDeltaTime;
clamp(m_fThirst, 0.0f, 1.0f);
}
float thirst_health_koef = (m_fThirst - m_fThirstCritical) / (m_fThirst >= m_fThirstCritical ? 1 - m_fThirstCritical : m_fThirstCritical);
if (CanBeHarmed())
{
m_fDeltaHealth += m_fV_ThirstHealth*thirst_health_koef*m_fDeltaTime;
m_fDeltaPower += m_fV_ThirstPower*m_fThirst*m_fDeltaTime;
}
}
CWound* CActorCondition::ConditionHit(SHit* pHDS)
{
if (GodMode()) return nullptr;
return inherited::ConditionHit(pHDS);
}
void CActorCondition::PowerHit(float power, bool apply_outfit)
{
m_fPower -= apply_outfit ? HitPowerEffect(power) : power;
clamp (m_fPower, 0.f, 1.f);
}
//weight - "удельный" вес от 0..1
void CActorCondition::ConditionJump(float weight)
{
float power = m_fJumpPower;
power += m_fJumpWeightPower*weight*(weight>1.f?m_fOverweightJumpK:1.f);
m_fPower -= HitPowerEffect(power);
}
void CActorCondition::ConditionWalk(float weight, bool accel, bool sprint)
{
float power = m_fWalkPower;
power += m_fWalkWeightPower*weight*(weight>1.f?m_fOverweightWalkK:1.f);
power *= m_fDeltaTime*(accel?(sprint?m_fSprintK:m_fAccelK):1.f);
m_fPower -= HitPowerEffect(power);
}
void CActorCondition::ConditionStand(float weight)
{
float power = m_fStandPower;
power *= m_fDeltaTime;
m_fPower -= power;
}
bool CActorCondition::IsCantWalk() const
{
if(m_fPower< m_fCantWalkPowerBegin)
m_bCantWalk = true;
else if(m_fPower > m_fCantWalkPowerEnd)
m_bCantWalk = false;
return m_bCantWalk;
}
bool CActorCondition::IsCantWalkWeight()
{
if(!GodMode())
{
float max_w = m_object->MaxWalkWeight();
if( object().inventory().TotalWeight() > max_w )
{
m_condition_flags.set (eCantWalkWeight, true);
return true;
}
}
m_condition_flags.set (eCantWalkWeight, false);
return false;
}
bool CActorCondition::IsCantSprint() const
{
if(m_fPower< m_fCantSprintPowerBegin)
m_bCantSprint = true;
else if(m_fPower > m_fCantSprintPowerEnd)
m_bCantSprint = false;
return m_bCantSprint;
}
bool CActorCondition::IsLimping() const
{
if(m_fPower< m_fLimpingPowerBegin || GetHealth() < m_fLimpingHealthBegin)
m_bLimping = true;
else if(m_fPower > m_fLimpingPowerEnd && GetHealth() > m_fLimpingHealthEnd)
m_bLimping = false;
return m_bLimping;
}
extern bool g_bShowHudInfo;
void CActorCondition::save(NET_Packet &output_packet)
{
inherited::save (output_packet);
save_data (m_fAlcohol, output_packet);
save_data (m_condition_flags, output_packet);
save_data (m_fSatiety, output_packet);
if (g_extraFeatures.is(GAME_EXTRA_THIRST))
{
save_data (m_fThirst, output_packet);
}
save_data (m_curr_medicine_influence.fHealth, output_packet);
save_data (m_curr_medicine_influence.fPower, output_packet);
save_data (m_curr_medicine_influence.fSatiety, output_packet);
if (g_extraFeatures.is(GAME_EXTRA_THIRST))
{
save_data (m_curr_medicine_influence.fThirst, output_packet);
}
save_data (m_curr_medicine_influence.fRadiation, output_packet);
save_data (m_curr_medicine_influence.fWoundsHeal, output_packet);
save_data (m_curr_medicine_influence.fMaxPowerUp, output_packet);
save_data (m_curr_medicine_influence.fAlcohol, output_packet);
save_data (m_curr_medicine_influence.fTimeTotal, output_packet);
save_data (m_curr_medicine_influence.fTimeCurrent, output_packet);
output_packet.w_u8((u8)m_booster_influences.size());
BOOSTER_MAP::iterator b = m_booster_influences.begin(), e = m_booster_influences.end();
for(; b != e; ++b)
{
output_packet.w_u8((u8)b->second.m_type);
output_packet.w_float(b->second.fBoostValue);
output_packet.w_float(b->second.fBoostTime);
}
}
void CActorCondition::load(IReader &input_packet)
{
inherited::load (input_packet);
load_data (m_fAlcohol, input_packet);
load_data (m_condition_flags, input_packet);
load_data (m_fSatiety, input_packet);
if (g_extraFeatures.is(GAME_EXTRA_THIRST))
{
load_data (m_fThirst, input_packet);
}
load_data (m_curr_medicine_influence.fHealth, input_packet);
load_data (m_curr_medicine_influence.fPower, input_packet);
load_data (m_curr_medicine_influence.fSatiety, input_packet);
if (g_extraFeatures.is(GAME_EXTRA_THIRST))
{
load_data (m_curr_medicine_influence.fThirst, input_packet);
}
load_data (m_curr_medicine_influence.fRadiation, input_packet);
load_data (m_curr_medicine_influence.fWoundsHeal, input_packet);
load_data (m_curr_medicine_influence.fMaxPowerUp, input_packet);
load_data (m_curr_medicine_influence.fAlcohol, input_packet);
load_data (m_curr_medicine_influence.fTimeTotal, input_packet);
load_data (m_curr_medicine_influence.fTimeCurrent, input_packet);
u8 cntr = input_packet.r_u8();
for(; cntr>0; cntr--)
{
SBooster B;
B.m_type = (EBoostParams)input_packet.r_u8();
B.fBoostValue = input_packet.r_float();
B.fBoostTime = input_packet.r_float();
m_booster_influences[B.m_type] = B;
BoostParameters(B);
}
}
void CActorCondition::reinit ()
{
inherited::reinit ();
m_bLimping = false;
m_fSatiety = 1.f;
m_fThirst = 1.f;
}
void CActorCondition::ChangeAlcohol (float value)
{
m_fAlcohol += value;
}
void CActorCondition::ChangeSatiety(float value)
{
m_fSatiety += value;
clamp (m_fSatiety, 0.0f, 1.0f);
}
void CActorCondition::ChangeThirst(float value)
{
m_fThirst += value;
clamp(m_fThirst, 0.0f, 1.0f);
}
void CActorCondition::BoostParameters(const SBooster& B)
{
switch (B.m_type)
{
case eBoostHpRestore: BoostHpRestore(B.fBoostValue); break;
case eBoostPowerRestore: BoostPowerRestore(B.fBoostValue); break;
case eBoostRadiationRestore: BoostRadiationRestore(B.fBoostValue); break;
case eBoostBleedingRestore: BoostBleedingRestore(B.fBoostValue); break;
case eBoostMaxWeight: BoostMaxWeight(B.fBoostValue); break;
case eBoostBurnImmunity: BoostBurnImmunity(B.fBoostValue); break;
case eBoostShockImmunity: BoostShockImmunity(B.fBoostValue); break;
case eBoostRadiationImmunity: BoostRadiationImmunity(B.fBoostValue); break;
case eBoostTelepaticImmunity: BoostTelepaticImmunity(B.fBoostValue); break;
case eBoostChemicalBurnImmunity: BoostChemicalBurnImmunity(B.fBoostValue); break;
case eBoostExplImmunity: BoostExplImmunity(B.fBoostValue); break;
case eBoostStrikeImmunity: BoostStrikeImmunity(B.fBoostValue); break;
case eBoostFireWoundImmunity: BoostFireWoundImmunity(B.fBoostValue); break;
case eBoostWoundImmunity: BoostWoundImmunity(B.fBoostValue); break;
case eBoostRadiationProtection: BoostRadiationProtection(B.fBoostValue); break;
case eBoostTelepaticProtection: BoostTelepaticProtection(B.fBoostValue); break;
case eBoostChemicalBurnProtection: BoostChemicalBurnProtection(B.fBoostValue); break;
default: NODEFAULT;
}
}
void CActorCondition::DisableBoostParameters(const SBooster& B)
{
switch(B.m_type)
{
case eBoostHpRestore: BoostHpRestore(-B.fBoostValue); break;
case eBoostPowerRestore: BoostPowerRestore(-B.fBoostValue); break;
case eBoostRadiationRestore: BoostRadiationRestore(-B.fBoostValue); break;
case eBoostBleedingRestore: BoostBleedingRestore(-B.fBoostValue); break;
case eBoostMaxWeight: BoostMaxWeight(-B.fBoostValue); break;
case eBoostBurnImmunity: BoostBurnImmunity(-B.fBoostValue); break;
case eBoostShockImmunity: BoostShockImmunity(-B.fBoostValue); break;
case eBoostRadiationImmunity: BoostRadiationImmunity(-B.fBoostValue); break;
case eBoostTelepaticImmunity: BoostTelepaticImmunity(-B.fBoostValue); break;
case eBoostChemicalBurnImmunity: BoostChemicalBurnImmunity(-B.fBoostValue); break;
case eBoostExplImmunity: BoostExplImmunity(-B.fBoostValue); break;
case eBoostStrikeImmunity: BoostStrikeImmunity(-B.fBoostValue); break;
case eBoostFireWoundImmunity: BoostFireWoundImmunity(-B.fBoostValue); break;
case eBoostWoundImmunity: BoostWoundImmunity(-B.fBoostValue); break;
case eBoostRadiationProtection: BoostRadiationProtection(-B.fBoostValue); break;
case eBoostTelepaticProtection: BoostTelepaticProtection(-B.fBoostValue); break;
case eBoostChemicalBurnProtection: BoostChemicalBurnProtection(-B.fBoostValue); break;
default: NODEFAULT;
}
}
void CActorCondition::BoostHpRestore(const float value)
{
m_change_v.m_fV_HealthRestore += value;
}
void CActorCondition::BoostPowerRestore(const float value)
{
m_fV_SatietyPower += value;
}
void CActorCondition::BoostRadiationRestore(const float value)
{
m_change_v.m_fV_Radiation += value;
}
void CActorCondition::BoostBleedingRestore(const float value)
{
m_change_v.m_fV_WoundIncarnation += value;
}
void CActorCondition::BoostMaxWeight(const float value)
{
m_object->inventory().SetMaxWeight(object().inventory().GetMaxWeight()+value);
m_MaxWalkWeight += value;
}
void CActorCondition::BoostBurnImmunity(const float value)
{
m_fBoostBurnImmunity += value;
}
void CActorCondition::BoostShockImmunity(const float value)
{
m_fBoostShockImmunity += value;
}
void CActorCondition::BoostRadiationImmunity(const float value)
{
m_fBoostRadiationImmunity += value;
}
void CActorCondition::BoostTelepaticImmunity(const float value)
{
m_fBoostTelepaticImmunity += value;
}
void CActorCondition::BoostChemicalBurnImmunity(const float value)
{
m_fBoostChemicalBurnImmunity += value;
}
void CActorCondition::BoostExplImmunity(const float value)
{
m_fBoostExplImmunity += value;
}
void CActorCondition::BoostStrikeImmunity(const float value)
{
m_fBoostStrikeImmunity += value;
}
void CActorCondition::BoostFireWoundImmunity(const float value)
{
m_fBoostFireWoundImmunity += value;
}
void CActorCondition::BoostWoundImmunity(const float value)
{
m_fBoostWoundImmunity += value;
}
void CActorCondition::BoostRadiationProtection(const float value)
{
m_fBoostRadiationProtection += value;
}
void CActorCondition::BoostTelepaticProtection(const float value)
{
m_fBoostTelepaticProtection += value;
}
void CActorCondition::BoostChemicalBurnProtection(const float value)
{
m_fBoostChemicalBurnProtection += value;
}
void CActorCondition::UpdateTutorialThresholds()
{
string256 cb_name;
static float _cPowerThr = pSettings->r_float("tutorial_conditions_thresholds","power");
static float _cPowerMaxThr = pSettings->r_float("tutorial_conditions_thresholds","max_power");
static float _cBleeding = pSettings->r_float("tutorial_conditions_thresholds","bleeding");
static float _cSatiety = pSettings->r_float("tutorial_conditions_thresholds","satiety");
static float _cThirst = 0.0f;
if (g_extraFeatures.is(GAME_EXTRA_THIRST))
{
_cThirst = pSettings->r_float("tutorial_conditions_thresholds", "thirst");
}
static float _cRadiation = pSettings->r_float("tutorial_conditions_thresholds","radiation");
static float _cWpnCondition = pSettings->r_float("tutorial_conditions_thresholds","weapon_jammed");
static float _cPsyHealthThr = pSettings->r_float("tutorial_conditions_thresholds","psy_health");
bool b = true;
if(b && !m_condition_flags.test(eCriticalPowerReached) && GetPower()<_cPowerThr){
m_condition_flags.set (eCriticalPowerReached, true);
b=false;
xr_strcpy(cb_name,"_G.on_actor_critical_power");
}
if(b && !m_condition_flags.test(eCriticalMaxPowerReached) && GetMaxPower()<_cPowerMaxThr){
m_condition_flags.set (eCriticalMaxPowerReached, true);
b=false;
xr_strcpy(cb_name,"_G.on_actor_critical_max_power");
}
if(b && !m_condition_flags.test(eCriticalBleedingSpeed) && BleedingSpeed()>_cBleeding){
m_condition_flags.set (eCriticalBleedingSpeed, true);
b=false;
xr_strcpy(cb_name,"_G.on_actor_bleeding");
}
if(b && !m_condition_flags.test(eCriticalSatietyReached) && GetSatiety()<_cSatiety){
m_condition_flags.set (eCriticalSatietyReached, true);
b=false;
xr_strcpy(cb_name,"_G.on_actor_satiety");
}
if(g_extraFeatures.is(GAME_EXTRA_THIRST))
{
if (b && !m_condition_flags.test(eCriticalThirstReached) && GetThirst()<_cThirst) {
m_condition_flags.set(eCriticalThirstReached, true);
b = false;
xr_strcpy(cb_name, "_G.on_actor_thirst");
}
}
if(b && !m_condition_flags.test(eCriticalRadiationReached) && GetRadiation()>_cRadiation){
m_condition_flags.set (eCriticalRadiationReached, true);
b=false;
xr_strcpy(cb_name,"_G.on_actor_radiation");
}
if(b && !m_condition_flags.test(ePhyHealthMinReached) && GetPsyHealth()<_cPsyHealthThr){
m_condition_flags.set (ePhyHealthMinReached, true);
b=false;
xr_strcpy(cb_name,"_G.on_actor_psy");
}
if(b && m_condition_flags.test(eCantWalkWeight) && !m_condition_flags.test(eCantWalkWeightReached)){
m_condition_flags.set (eCantWalkWeightReached, true);
b=false;
xr_strcpy(cb_name,"_G.on_actor_cant_walk_weight");
}
if(b && !m_condition_flags.test(eWeaponJammedReached)&&m_object->inventory().GetActiveSlot()!=NO_ACTIVE_SLOT){
PIItem item = m_object->inventory().ItemFromSlot(m_object->inventory().GetActiveSlot());
CWeapon* pWeapon = smart_cast<CWeapon*>(item);
if(pWeapon&&pWeapon->GetCondition()<_cWpnCondition){
m_condition_flags.set (eWeaponJammedReached, true);b=false;
xr_strcpy(cb_name,"_G.on_actor_weapon_jammed");
}
}
if(!b){
luabind::functor<LPCSTR> fl;
R_ASSERT (ai().script_engine().functor<LPCSTR>(cb_name,fl));
fl ();
}
}
bool CActorCondition::DisableSprint(SHit* pHDS)
{
return (pHDS->hit_type != ALife::eHitTypeTelepatic) &&
(pHDS->hit_type != ALife::eHitTypeChemicalBurn) &&
(pHDS->hit_type != ALife::eHitTypeBurn) &&
(pHDS->hit_type != ALife::eHitTypeLightBurn) &&
(pHDS->hit_type != ALife::eHitTypeRadiation) ;
}
bool CActorCondition::PlayHitSound(SHit* pHDS)
{
switch (pHDS->hit_type)
{
case ALife::eHitTypeTelepatic:
return false;
break;
case ALife::eHitTypeShock:
case ALife::eHitTypeStrike:
case ALife::eHitTypeWound:
case ALife::eHitTypeExplosion:
case ALife::eHitTypeFireWound:
case ALife::eHitTypeWound_2:
// case ALife::eHitTypePhysicStrike:
return true;
break;
case ALife::eHitTypeRadiation:
case ALife::eHitTypeBurn:
case ALife::eHitTypeLightBurn:
case ALife::eHitTypeChemicalBurn:
return (pHDS->damage()>0.017f); //field zone threshold
break;
default:
return true;
}
}
float CActorCondition::HitSlowmo(SHit* pHDS)
{
float ret;
if(pHDS->hit_type==ALife::eHitTypeWound || pHDS->hit_type==ALife::eHitTypeStrike )
{
ret = pHDS->damage();
clamp (ret,0.0f,1.f);
}else
ret = 0.0f;
return ret;
}
bool CActorCondition::ApplyInfluence(const SMedicineInfluenceValues& V, const shared_str& sect)
{
if(m_curr_medicine_influence.InProcess())
return false;
if (m_object->Local() && m_object == Level().CurrentViewEntity())
{
if(pSettings->line_exist(sect, "use_sound"))
{
if(m_use_sound._feedback())
m_use_sound.stop ();
shared_str snd_name = pSettings->r_string(sect, "use_sound");
m_use_sound.create (snd_name.c_str(), st_Effect, sg_SourceType);
m_use_sound.play (nullptr, sm_2D);
}
}
if(V.fTimeTotal<0.0f)
return inherited::ApplyInfluence (V, sect);
m_curr_medicine_influence = V;
m_curr_medicine_influence.fTimeCurrent = m_curr_medicine_influence.fTimeTotal;
return true;
}
bool CActorCondition::ApplyBooster(const SBooster& B, const shared_str& sect)
{
if(B.fBoostValue>0.0f)
{
if (m_object->Local() && m_object == Level().CurrentViewEntity())
{
if(pSettings->line_exist(sect, "use_sound"))
{
if(m_use_sound._feedback())
m_use_sound.stop ();
shared_str snd_name = pSettings->r_string(sect, "use_sound");
m_use_sound.create (snd_name.c_str(), st_Effect, sg_SourceType);
m_use_sound.play (nullptr, sm_2D);
}
}
BOOSTER_MAP::iterator it = m_booster_influences.find(B.m_type);
if(it!=m_booster_influences.end())
DisableBoostParameters((*it).second);
m_booster_influences[B.m_type] = B;
BoostParameters(B);
}
return true;
}
void disable_input();
void enable_input();
void hide_indicators();
void show_indicators();
CActorDeathEffector::CActorDeathEffector (CActorCondition* parent, LPCSTR sect) // -((
:m_pParent(parent)
{
Actor()->SetWeaponHideState(INV_STATE_BLOCK_ALL,true);
hide_indicators ();
AddEffector (Actor(), effActorDeath, sect);
disable_input ();
LPCSTR snd = pSettings->r_string(sect, "snd");
m_death_sound.create (snd,st_Effect,0);
m_death_sound.play_at_pos(nullptr,Fvector().set(0,0,0),sm_2D);
SBaseEffector* pe = Actor()->Cameras().GetPPEffector((EEffectorPPType)effActorDeath);
pe->m_on_b_remove_callback = SBaseEffector::CB_ON_B_REMOVE(this, &CActorDeathEffector::OnPPEffectorReleased);
m_b_actual = true;
m_start_health = m_pParent->health();
}
CActorDeathEffector::~CActorDeathEffector()
{}
void CActorDeathEffector::UpdateCL()
{
m_pParent->SetHealth( m_start_health );
}
void CActorDeathEffector::OnPPEffectorReleased()
{
m_b_actual = false;
Msg("111");
//m_pParent->health() = -1.0f;
m_pParent->SetHealth (-1.0f);
}
void CActorDeathEffector::Stop()
{
RemoveEffector (Actor(),effActorDeath);
m_death_sound.destroy ();
enable_input ();
show_indicators ();
}
| 30.058648 | 146 | 0.742518 | Pavel3333 |
a1f4f7725b51ad6793e983719ea643a489d8cd04 | 790 | cpp | C++ | main2.cpp | if025-pm-unpsjb/tp4-2019-lpc1768-LucasAbella29 | 0af6a6a7f35536269347a6229c62cee309a2fe38 | [
"MIT"
] | null | null | null | main2.cpp | if025-pm-unpsjb/tp4-2019-lpc1768-LucasAbella29 | 0af6a6a7f35536269347a6229c62cee309a2fe38 | [
"MIT"
] | null | null | null | main2.cpp | if025-pm-unpsjb/tp4-2019-lpc1768-LucasAbella29 | 0af6a6a7f35536269347a6229c62cee309a2fe38 | [
"MIT"
] | null | null | null | /*
* main2.cpp
*
* Created on: Nov 12, 2019
* Author: lucas
*/
#include "mbed.h"
Serial pc(USBTX, USBRX); // tx, rx
DigitalOut turningLed(LED1);
int main() {
DigitalOut leds[] = {LED1,LED2,LED3,LED4};
int selectedLed = 0;
pc.printf("Programa iniciado!\n");
while(1) {
if(pc.readable()){
char readedChar = pc.getc();
if(readedChar >= '1' && readedChar <= '4'){
selectedLed = readedChar - '1';
}
else{
pc.putc(readedChar);
}
}
wait(0.25);
for(int i = 0;i < 4; i++){
if(i == selectedLed){
leds[i] = (leds[i] == 1) ? 0 : 1;
continue;
}
leds[i] = 0;
}
}
}
| 18.809524 | 55 | 0.424051 | if025-pm-unpsjb |
a1f5246c375442961850889b23ae3f4ea7593837 | 5,960 | cpp | C++ | src/mongo/s/type_collection.cpp | sl33nyc/mongo | 29b847376258b1fabb117e7da66b2f6ad7b58a25 | [
"Apache-2.0"
] | null | null | null | src/mongo/s/type_collection.cpp | sl33nyc/mongo | 29b847376258b1fabb117e7da66b2f6ad7b58a25 | [
"Apache-2.0"
] | null | null | null | src/mongo/s/type_collection.cpp | sl33nyc/mongo | 29b847376258b1fabb117e7da66b2f6ad7b58a25 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2012 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mongo/s/type_collection.h"
#include "mongo/s/field_parser.h"
#include "mongo/util/mongoutils/str.h"
namespace mongo {
using mongoutils::str::stream;
const std::string CollectionType::ConfigNS = "config.collections";
BSONField<std::string> CollectionType::ns("_id");
BSONField<std::string> CollectionType::primary("primary");
BSONField<BSONObj> CollectionType::keyPattern("key");
BSONField<bool> CollectionType::unique("unique");
BSONField<Date_t> CollectionType::updatedAt("updatedAt");
BSONField<bool> CollectionType::noBalance("noBalance");
BSONField<OID> CollectionType::epoch("epoch");
// To-be-deprecated, not yet
BSONField<bool> CollectionType::dropped("dropped");
BSONField<OID> CollectionType::DEPRECATED_lastmodEpoch("lastmodEpoch");
BSONField<Date_t> CollectionType::DEPRECATED_lastmod("lastmod");
CollectionType::CollectionType() {
clear();
}
CollectionType::~CollectionType() {
}
bool CollectionType::isValid(std::string* errMsg) const {
std::string dummy;
if (errMsg == NULL) errMsg = &dummy;
// All the mandatory fields must be present.
if (_ns.empty()) {
*errMsg = stream() << "missing " << ns.name() << " field";
return false;
}
if (_updatedAt.millis == 0) {
*errMsg = stream() << "missing " << updatedAt.name() << " field";
return false;
}
if (!_epoch.isSet()) {
*errMsg = stream() << "missing " << epoch.name() << " field";
return false;
}
// Either sharding or primary information should be filled.
if (_primary.empty() == (_keyPattern.nFields() == 0)) {
*errMsg = stream() << "either " << primary.name() << " or " << keyPattern.name()
<< " should be filled";
return false;
}
// Sharding related fields may only be set if the sharding key pattern is present.
if ((_unique || _noBalance) && (_keyPattern.nFields() == 0)) {
*errMsg = stream() << "missing " << keyPattern.name() << " field";
return false;
}
return true;
}
BSONObj CollectionType::toBSON() const {
BSONObjBuilder builder;
builder.append(ns(), _ns);
if (!_primary.empty()) builder.append(primary(), _primary);
if (_keyPattern.nFields()) builder.append(keyPattern(), _keyPattern);
if (_unique) builder.append(unique(), _unique);
builder.append(updatedAt(), _updatedAt);
builder.append(DEPRECATED_lastmod(), _updatedAt);
if (_noBalance) builder.append(noBalance(), _noBalance);
if (_epoch.isSet()) {
builder.append(epoch(), _epoch);
builder.append(DEPRECATED_lastmodEpoch(), _epoch);
}
// Always need to write dropped for compatibility w/ 2.0/2.2
builder.append(dropped(), _dropped);
return builder.obj();
}
bool CollectionType::parseBSON(BSONObj source, string* errMsg) {
clear();
string dummy;
if (!errMsg) errMsg = &dummy;
if (!FieldParser::extract(source, ns, "", &_ns, errMsg)) return false;
if (!FieldParser::extract(source, primary, "", &_primary, errMsg)) return false;
if (!FieldParser::extract(source, keyPattern, BSONObj(), &_keyPattern, errMsg)) return false;
if (!FieldParser::extract(source, unique, false, &_unique, errMsg)) return false;
if (!FieldParser::extract(source, updatedAt, 0ULL, &_updatedAt, errMsg)) return false;
if (!FieldParser::extract(source, noBalance, false, &_noBalance, errMsg)) return false;
if (!FieldParser::extract(source, epoch, OID(), &_epoch, errMsg)) return false;
if (!FieldParser::extract(source, dropped, false, &_dropped, errMsg)) return false;
//
// backward compatibility
//
// 'createAt' used to be called 'lastmod' up to 2.2.
Date_t lastmod;
if (!FieldParser::extract(source, DEPRECATED_lastmod, 0ULL, &lastmod, errMsg)) return false;
if (lastmod != 0ULL) {
_updatedAt = lastmod;
}
// 'lastmodEpoch' was a transition format to 'epoch', up to 2.2
OID lastmodEpoch;
if (!FieldParser::extract(source, DEPRECATED_lastmodEpoch, OID(), &lastmodEpoch, errMsg)) return false;
if (lastmodEpoch.isSet()) {
_epoch = lastmodEpoch;
}
return true;
}
void CollectionType::clear() {
_ns.clear();
_primary.clear();
_keyPattern = BSONObj();
_unique = false;
_updatedAt = 0ULL;
_noBalance = false;
_epoch = OID();
_dropped = false;
}
void CollectionType::cloneTo(CollectionType* other) const {
other->clear();
other->_ns = _ns;
other->_primary = _primary;
other->_keyPattern = _keyPattern;
other->_unique = _unique;
other->_updatedAt = _updatedAt;
other->_noBalance = _noBalance;
other->_epoch = _epoch;
other->_dropped = _dropped;
}
std::string CollectionType::toString() const {
return toBSON().toString();
}
} // namespace mongo
| 35.903614 | 111 | 0.609899 | sl33nyc |
a1f592f9152a3a3afa4b020679845bdce3a37e25 | 228,972 | cpp | C++ | td/telegram/Td.cpp | luckydonald-backup/td | 71d03f39c364367a8a7c51f783a41099297de826 | [
"BSL-1.0"
] | 1 | 2021-04-18T08:59:02.000Z | 2021-04-18T08:59:02.000Z | td/telegram/Td.cpp | devitsyn/td | 71d03f39c364367a8a7c51f783a41099297de826 | [
"BSL-1.0"
] | null | null | null | td/telegram/Td.cpp | devitsyn/td | 71d03f39c364367a8a7c51f783a41099297de826 | [
"BSL-1.0"
] | null | null | null | //
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2017
//
// 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)
//
#include "td/telegram/Td.h"
#include "td/db/binlog/BinlogEvent.h"
#include "td/telegram/net/ConnectionCreator.h"
#include "td/telegram/net/MtprotoHeader.h"
#include "td/telegram/net/NetQuery.h"
#include "td/telegram/net/NetQueryDelayer.h"
#include "td/telegram/net/NetQueryDispatcher.h"
#include "td/telegram/net/NetStatsManager.h"
#include "td/telegram/net/TempAuthKeyWatchdog.h"
#include "td/telegram/AccessRights.h"
#include "td/telegram/AnimationsManager.h"
#include "td/telegram/AudiosManager.h"
#include "td/telegram/AuthManager.h"
#include "td/telegram/CallbackQueriesManager.h"
#include "td/telegram/CallId.h"
#include "td/telegram/CallManager.h"
#include "td/telegram/ChannelId.h"
#include "td/telegram/ChatId.h"
#include "td/telegram/ConfigManager.h"
#include "td/telegram/ConfigShared.h"
#include "td/telegram/ContactsManager.h"
#include "td/telegram/DeviceTokenManager.h"
#include "td/telegram/DialogId.h"
#include "td/telegram/DialogParticipant.h"
#include "td/telegram/DocumentsManager.h"
#include "td/telegram/files/FileGcParameters.h"
#include "td/telegram/files/FileId.h"
#include "td/telegram/files/FileManager.h"
#include "td/telegram/Global.h"
#include "td/telegram/HashtagHints.h"
#include "td/telegram/InlineQueriesManager.h"
#include "td/telegram/MessageEntity.h"
#include "td/telegram/MessageId.h"
#include "td/telegram/MessagesManager.h"
#include "td/telegram/misc.h"
#include "td/telegram/PasswordManager.h"
#include "td/telegram/PrivacyManager.h"
#include "td/telegram/SecretChatId.h"
#include "td/telegram/SecretChatsManager.h"
#include "td/telegram/StateManager.h"
#include "td/telegram/StickersManager.h"
#include "td/telegram/StorageManager.h"
#include "td/telegram/TdDb.h"
#include "td/telegram/TopDialogManager.h"
#include "td/telegram/UpdatesManager.h"
#include "td/telegram/VideoNotesManager.h"
#include "td/telegram/VideosManager.h"
#include "td/telegram/VoiceNotesManager.h"
#include "td/telegram/WebPageId.h"
#include "td/telegram/WebPagesManager.h"
#include "td/telegram/td_api.hpp"
#include "td/telegram/telegram_api.h"
#include "td/actor/actor.h"
#include "td/actor/PromiseFuture.h"
#include "td/mtproto/utils.h" // for create_storer, fetch_result, etc, TODO
#include "td/utils/buffer.h"
#include "td/utils/format.h"
#include "td/utils/MimeType.h"
#include "td/utils/misc.h"
#include "td/utils/PathView.h"
#include "td/utils/port/path.h"
#include "td/utils/Slice.h"
#include "td/utils/Status.h"
#include "td/utils/Timer.h"
#include "td/utils/tl_parsers.h"
#include "td/utils/utf8.h"
#include <algorithm>
#include <limits>
#include <tuple>
#include <type_traits>
namespace td {
namespace {
DbKey as_db_key(string key) {
// Database will still be effectively not encrypted, but
// 1. sqlite db will be protected from corruption, because that's how sqlcipher works
// 2. security through obscurity
// 3. no need for reencryption of sqlite db
if (key.empty()) {
return DbKey::raw_key("cucumber");
}
return DbKey::raw_key(std::move(key));
}
} // namespace
void Td::ResultHandler::set_td(Td *new_td) {
CHECK(td == nullptr);
td = new_td;
}
void Td::ResultHandler::on_result(NetQueryPtr query) {
CHECK(query->is_ready());
if (query->is_ok()) {
on_result(query->id(), std::move(query->ok()));
} else {
on_error(query->id(), std::move(query->error()));
}
query->clear();
}
void Td::ResultHandler::send_query(NetQueryPtr query) {
td->add_handler(query->id(), shared_from_this());
td->send(std::move(query));
}
class GetNearestDcQuery : public Td::ResultHandler {
public:
void send() {
send_query(G()->net_query_creator().create(create_storer(telegram_api::help_getNearestDc()), DcId::main(),
NetQuery::Type::Common, NetQuery::AuthFlag::Off));
}
void on_result(uint64 id, BufferSlice packet) override {
auto result_ptr = fetch_result<telegram_api::help_getNearestDc>(packet);
if (result_ptr.is_error()) {
return on_error(id, result_ptr.move_as_error());
}
}
void on_error(uint64 id, Status status) override {
LOG(ERROR) << "GetNearestDc returned " << status;
status.ignore();
}
};
class GetWallpapersQuery : public Td::ResultHandler {
Promise<tl_object_ptr<td_api::wallpapers>> promise_;
public:
explicit GetWallpapersQuery(Promise<tl_object_ptr<td_api::wallpapers>> &&promise) : promise_(std::move(promise)) {
}
void send() {
send_query(G()->net_query_creator().create(create_storer(telegram_api::account_getWallPapers())));
}
void on_result(uint64 id, BufferSlice packet) override {
auto result_ptr = fetch_result<telegram_api::account_getWallPapers>(packet);
if (result_ptr.is_error()) {
return on_error(id, result_ptr.move_as_error());
}
auto wallpapers = result_ptr.move_as_ok();
auto results = make_tl_object<td_api::wallpapers>();
results->wallpapers_.reserve(wallpapers.size());
for (auto &wallpaper_ptr : wallpapers) {
CHECK(wallpaper_ptr != nullptr);
switch (wallpaper_ptr->get_id()) {
case telegram_api::wallPaper::ID: {
auto wallpaper = move_tl_object_as<telegram_api::wallPaper>(wallpaper_ptr);
vector<tl_object_ptr<td_api::photoSize>> sizes;
sizes.reserve(wallpaper->sizes_.size());
for (auto &size_ptr : wallpaper->sizes_) {
auto photo_size =
get_photo_size(td->file_manager_.get(), FileType::Wallpaper, 0, 0, DialogId(), std::move(size_ptr));
sizes.push_back(get_photo_size_object(td->file_manager_.get(), &photo_size));
}
results->wallpapers_.push_back(
make_tl_object<td_api::wallpaper>(wallpaper->id_, std::move(sizes), wallpaper->color_));
break;
}
case telegram_api::wallPaperSolid::ID: {
auto wallpaper = move_tl_object_as<telegram_api::wallPaperSolid>(wallpaper_ptr);
results->wallpapers_.push_back(make_tl_object<td_api::wallpaper>(
wallpaper->id_, vector<tl_object_ptr<td_api::photoSize>>(), wallpaper->bg_color_));
break;
}
default:
UNREACHABLE();
}
}
promise_.set_value(std::move(results));
}
void on_error(uint64 id, Status status) override {
promise_.set_error(std::move(status));
}
};
class GetRecentMeUrlsQuery : public Td::ResultHandler {
Promise<tl_object_ptr<td_api::tMeUrls>> promise_;
public:
explicit GetRecentMeUrlsQuery(Promise<tl_object_ptr<td_api::tMeUrls>> &&promise) : promise_(std::move(promise)) {
}
void send(const string &referrer) {
send_query(G()->net_query_creator().create(create_storer(telegram_api::help_getRecentMeUrls(referrer))));
}
void on_result(uint64 id, BufferSlice packet) override {
auto result_ptr = fetch_result<telegram_api::help_getRecentMeUrls>(packet);
if (result_ptr.is_error()) {
return on_error(id, result_ptr.move_as_error());
}
auto urls_full = result_ptr.move_as_ok();
td->contacts_manager_->on_get_users(std::move(urls_full->users_));
td->contacts_manager_->on_get_chats(std::move(urls_full->chats_));
auto urls = std::move(urls_full->urls_);
auto results = make_tl_object<td_api::tMeUrls>();
results->urls_.reserve(urls.size());
for (auto &url_ptr : urls) {
CHECK(url_ptr != nullptr);
tl_object_ptr<td_api::tMeUrl> result = make_tl_object<td_api::tMeUrl>();
switch (url_ptr->get_id()) {
case telegram_api::recentMeUrlUser::ID: {
auto url = move_tl_object_as<telegram_api::recentMeUrlUser>(url_ptr);
result->url_ = std::move(url->url_);
UserId user_id(url->user_id_);
if (!user_id.is_valid()) {
LOG(ERROR) << "Receive invalid " << user_id;
result = nullptr;
break;
}
result->type_ = make_tl_object<td_api::tMeUrlTypeUser>(user_id.get());
break;
}
case telegram_api::recentMeUrlChat::ID: {
auto url = move_tl_object_as<telegram_api::recentMeUrlChat>(url_ptr);
result->url_ = std::move(url->url_);
ChannelId channel_id(url->chat_id_);
if (!channel_id.is_valid()) {
LOG(ERROR) << "Receive invalid " << channel_id;
result = nullptr;
break;
}
result->type_ = make_tl_object<td_api::tMeUrlTypeSupergroup>(channel_id.get());
break;
}
case telegram_api::recentMeUrlChatInvite::ID: {
auto url = move_tl_object_as<telegram_api::recentMeUrlChatInvite>(url_ptr);
result->url_ = std::move(url->url_);
td->contacts_manager_->on_get_dialog_invite_link_info(result->url_, std::move(url->chat_invite_));
result->type_ = make_tl_object<td_api::tMeUrlTypeChatInvite>(
td->contacts_manager_->get_chat_invite_link_info_object(result->url_));
break;
}
case telegram_api::recentMeUrlStickerSet::ID: {
auto url = move_tl_object_as<telegram_api::recentMeUrlStickerSet>(url_ptr);
result->url_ = std::move(url->url_);
auto sticker_set_id = td->stickers_manager_->on_get_sticker_set_covered(std::move(url->set_), false);
if (sticker_set_id == 0) {
LOG(ERROR) << "Receive invalid sticker set";
result = nullptr;
break;
}
result->type_ = make_tl_object<td_api::tMeUrlTypeStickerSet>(sticker_set_id);
break;
}
case telegram_api::recentMeUrlUnknown::ID:
// skip
result = nullptr;
break;
default:
UNREACHABLE();
}
if (result != nullptr) {
results->urls_.push_back(std::move(result));
}
}
promise_.set_value(std::move(results));
}
void on_error(uint64 id, Status status) override {
promise_.set_error(std::move(status));
}
};
class SendCustomRequestQuery : public Td::ResultHandler {
Promise<string> promise_;
public:
explicit SendCustomRequestQuery(Promise<string> &&promise) : promise_(std::move(promise)) {
}
void send(const string &method, const string ¶meters) {
send_query(G()->net_query_creator().create(create_storer(
telegram_api::bots_sendCustomRequest(method, make_tl_object<telegram_api::dataJSON>(parameters)))));
}
void on_result(uint64 id, BufferSlice packet) override {
auto result_ptr = fetch_result<telegram_api::bots_sendCustomRequest>(packet);
if (result_ptr.is_error()) {
return on_error(id, result_ptr.move_as_error());
}
promise_.set_value(std::move(result_ptr.ok()->data_));
}
void on_error(uint64 id, Status status) override {
promise_.set_error(std::move(status));
}
};
class AnswerCustomQueryQuery : public Td::ResultHandler {
Promise<Unit> promise_;
public:
explicit AnswerCustomQueryQuery(Promise<Unit> &&promise) : promise_(std::move(promise)) {
}
void send(int64 custom_query_id, const string &data) {
send_query(G()->net_query_creator().create(create_storer(
telegram_api::bots_answerWebhookJSONQuery(custom_query_id, make_tl_object<telegram_api::dataJSON>(data)))));
}
void on_result(uint64 id, BufferSlice packet) override {
auto result_ptr = fetch_result<telegram_api::bots_answerWebhookJSONQuery>(packet);
if (result_ptr.is_error()) {
return on_error(id, result_ptr.move_as_error());
}
bool result = result_ptr.ok();
if (!result) {
LOG(INFO) << "Sending answer to a custom query has failed";
}
promise_.set_value(Unit());
}
void on_error(uint64 id, Status status) override {
promise_.set_error(std::move(status));
}
};
class SetBotUpdatesStatusQuery : public Td::ResultHandler {
public:
void send(int32 pending_update_count, const string &error_message) {
send_query(G()->net_query_creator().create(
create_storer(telegram_api::help_setBotUpdatesStatus(pending_update_count, error_message))));
}
void on_result(uint64 id, BufferSlice packet) override {
auto result_ptr = fetch_result<telegram_api::help_setBotUpdatesStatus>(packet);
if (result_ptr.is_error()) {
return on_error(id, result_ptr.move_as_error());
}
bool result = result_ptr.ok();
LOG_IF(WARNING, !result) << "Set bot updates status has failed";
}
void on_error(uint64 id, Status status) override {
LOG(WARNING) << "Receive error for SetBotUpdatesStatus: " << status;
status.ignore();
}
};
class UpdateStatusQuery : public Td::ResultHandler {
public:
void send(bool is_offline) {
send_query(G()->net_query_creator().create(create_storer(telegram_api::account_updateStatus(is_offline))));
}
void on_result(uint64 id, BufferSlice packet) override {
auto result_ptr = fetch_result<telegram_api::account_updateStatus>(packet);
if (result_ptr.is_error()) {
return on_error(id, result_ptr.move_as_error());
}
bool result = result_ptr.ok();
LOG(INFO) << "UpdateStatus returned " << result;
}
void on_error(uint64 id, Status status) override {
LOG(ERROR) << "Receive error for UpdateStatusQuery: " << status;
status.ignore();
}
};
class GetInviteTextQuery : public Td::ResultHandler {
Promise<string> promise_;
public:
explicit GetInviteTextQuery(Promise<string> &&promise) : promise_(std::move(promise)) {
}
void send() {
send_query(G()->net_query_creator().create(create_storer(telegram_api::help_getInviteText())));
}
void on_result(uint64 id, BufferSlice packet) override {
auto result_ptr = fetch_result<telegram_api::help_getInviteText>(packet);
if (result_ptr.is_error()) {
return on_error(id, result_ptr.move_as_error());
}
promise_.set_value(std::move(result_ptr.ok()->message_));
}
void on_error(uint64 id, Status status) override {
promise_.set_error(std::move(status));
}
};
class GetTermsOfServiceQuery : public Td::ResultHandler {
Promise<string> promise_;
public:
explicit GetTermsOfServiceQuery(Promise<string> &&promise) : promise_(std::move(promise)) {
}
void send() {
send_query(G()->net_query_creator().create(create_storer(telegram_api::help_getTermsOfService())));
}
void on_result(uint64 id, BufferSlice packet) override {
auto result_ptr = fetch_result<telegram_api::help_getTermsOfService>(packet);
if (result_ptr.is_error()) {
return on_error(id, result_ptr.move_as_error());
}
promise_.set_value(std::move(result_ptr.ok()->text_));
}
void on_error(uint64 id, Status status) override {
promise_.set_error(std::move(status));
}
};
template <class T = Unit>
class RequestActor : public Actor {
public:
RequestActor(ActorShared<Td> td_id, uint64 request_id)
: td_id_(std::move(td_id)), td(td_id_.get().get_actor_unsafe()), request_id_(request_id) {
}
void loop() override {
PromiseActor<T> promise;
FutureActor<T> future;
init_promise_future(&promise, &future);
do_run(PromiseCreator::from_promise_actor(std::move(promise)));
if (future.is_ready()) {
if (future.is_error()) {
do_send_error(future.move_as_error());
} else {
do_set_result(future.move_as_ok());
do_send_result();
}
stop();
} else {
if (--tries_left_ == 0) {
future.close();
do_send_error(Status::Error(400, "Requested data is unaccessible"));
return stop();
}
future.set_event(EventCreator::raw(actor_id(), nullptr));
future_ = std::move(future);
}
}
void raw_event(const Event::Raw &event) override {
if (future_.is_error()) {
auto error = future_.move_as_error();
if (error == Status::Hangup()) {
// dropping query due to lost authorization or lost promise
// td may be already closed, so we should check is auth_manager_ is empty
bool is_authorized = td->auth_manager_ && td->auth_manager_->is_authorized();
if (is_authorized) {
LOG(ERROR) << "Promise was lost";
do_send_error(Status::Error(500, "Query can't be answered due to bug in the TDLib"));
} else {
do_send_error(Status::Error(401, "Unauthorized"));
}
return stop();
}
do_send_error(std::move(error));
stop();
} else {
do_set_result(future_.move_as_ok());
loop();
}
}
void on_start_migrate(int32 /*sched_id*/) override {
UNREACHABLE();
}
void on_finish_migrate() override {
UNREACHABLE();
}
int get_tries() const {
return tries_left_;
}
void set_tries(int32 tries) {
tries_left_ = tries;
}
protected:
ActorShared<Td> td_id_;
Td *td;
void send_result(tl_object_ptr<td_api::Object> &&result) {
send_closure(td_id_, &Td::send_result, request_id_, std::move(result));
}
void send_error(Status &&status) {
LOG(INFO) << "Receive error for query: " << status;
send_closure(td_id_, &Td::send_error, request_id_, std::move(status));
}
private:
virtual void do_run(Promise<T> &&promise) = 0;
virtual void do_send_result() {
send_result(make_tl_object<td_api::ok>());
}
virtual void do_send_error(Status &&status) {
send_error(std::move(status));
}
virtual void do_set_result(T &&result) {
CHECK((std::is_same<T, Unit>::value)); // all other results should be implicitly handled by overriding this method
}
void hangup() override {
do_send_error(Status::Error(500, "Request aborted"));
stop();
}
friend class RequestOnceActor;
uint64 request_id_;
int tries_left_ = 2;
FutureActor<T> future_;
};
class RequestOnceActor : public RequestActor<> {
public:
RequestOnceActor(ActorShared<Td> td_id, uint64 request_id) : RequestActor(std::move(td_id), request_id) {
}
void loop() override {
if (get_tries() < 2) {
do_send_result();
stop();
return;
}
RequestActor::loop();
}
};
/*** Td ***/
/** Td queries **/
class TestQuery : public Td::ResultHandler {
public:
explicit TestQuery(uint64 request_id) : request_id_(request_id) {
}
void send() {
send_query(G()->net_query_creator().create(create_storer(telegram_api::help_getConfig())));
}
void on_result(uint64 id, BufferSlice packet) override {
auto result_ptr = fetch_result<telegram_api::help_getConfig>(packet);
if (result_ptr.is_error()) {
return on_error(id, Status::Error(500, "Fetch failed"));
}
LOG(DEBUG) << "TestOK: " << to_string(result_ptr.ok());
send_closure(G()->td(), &Td::send_result, request_id_, make_tl_object<td_api::ok>());
}
void on_error(uint64 id, Status status) override {
status.ignore();
LOG(ERROR) << "Test query failed: " << status;
}
private:
uint64 request_id_;
};
class GetAccountTtlRequest : public RequestActor<int32> {
int32 account_ttl_;
void do_run(Promise<int32> &&promise) override {
if (get_tries() < 2) {
promise.set_value(std::move(account_ttl_));
return;
}
td->contacts_manager_->get_account_ttl(std::move(promise));
}
void do_set_result(int32 &&result) override {
account_ttl_ = result;
}
void do_send_result() override {
send_result(make_tl_object<td_api::accountTtl>(account_ttl_));
}
public:
GetAccountTtlRequest(ActorShared<Td> td, uint64 request_id) : RequestActor(std::move(td), request_id) {
}
};
class SetAccountTtlRequest : public RequestOnceActor {
int32 account_ttl_;
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->set_account_ttl(account_ttl_, std::move(promise));
}
public:
SetAccountTtlRequest(ActorShared<Td> td, uint64 request_id, int32 account_ttl)
: RequestOnceActor(std::move(td), request_id), account_ttl_(account_ttl) {
}
};
class GetActiveSessionsRequest : public RequestActor<tl_object_ptr<td_api::sessions>> {
tl_object_ptr<td_api::sessions> sessions_;
void do_run(Promise<tl_object_ptr<td_api::sessions>> &&promise) override {
if (get_tries() < 2) {
promise.set_value(std::move(sessions_));
return;
}
td->contacts_manager_->get_active_sessions(std::move(promise));
}
void do_set_result(tl_object_ptr<td_api::sessions> &&result) override {
sessions_ = std::move(result);
}
void do_send_result() override {
CHECK(sessions_ != nullptr);
send_result(std::move(sessions_));
}
public:
GetActiveSessionsRequest(ActorShared<Td> td, uint64 request_id) : RequestActor(std::move(td), request_id) {
}
};
class TerminateSessionRequest : public RequestOnceActor {
int64 session_id_;
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->terminate_session(session_id_, std::move(promise));
}
public:
TerminateSessionRequest(ActorShared<Td> td, uint64 request_id, int64 session_id)
: RequestOnceActor(std::move(td), request_id), session_id_(session_id) {
}
};
class TerminateAllOtherSessionsRequest : public RequestOnceActor {
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->terminate_all_other_sessions(std::move(promise));
}
public:
TerminateAllOtherSessionsRequest(ActorShared<Td> td, uint64 request_id)
: RequestOnceActor(std::move(td), request_id) {
}
};
class GetUserRequest : public RequestActor<> {
UserId user_id_;
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->get_user(user_id_, get_tries(), std::move(promise));
}
void do_send_result() override {
send_result(td->contacts_manager_->get_user_object(user_id_));
}
public:
GetUserRequest(ActorShared<Td> td, uint64 request_id, int32 user_id)
: RequestActor(std::move(td), request_id), user_id_(user_id) {
set_tries(3);
}
};
class GetUserFullInfoRequest : public RequestActor<> {
UserId user_id_;
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->get_user_full(user_id_, std::move(promise));
}
void do_send_result() override {
send_result(td->contacts_manager_->get_user_full_info_object(user_id_));
}
public:
GetUserFullInfoRequest(ActorShared<Td> td, uint64 request_id, int32 user_id)
: RequestActor(std::move(td), request_id), user_id_(user_id) {
}
};
class GetGroupRequest : public RequestActor<> {
ChatId chat_id_;
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->get_chat(chat_id_, get_tries(), std::move(promise));
}
void do_send_result() override {
send_result(td->contacts_manager_->get_basic_group_object(chat_id_));
}
public:
GetGroupRequest(ActorShared<Td> td, uint64 request_id, int32 chat_id)
: RequestActor(std::move(td), request_id), chat_id_(chat_id) {
set_tries(3);
}
};
class GetGroupFullInfoRequest : public RequestActor<> {
ChatId chat_id_;
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->get_chat_full(chat_id_, std::move(promise));
}
void do_send_result() override {
send_result(td->contacts_manager_->get_basic_group_full_info_object(chat_id_));
}
public:
GetGroupFullInfoRequest(ActorShared<Td> td, uint64 request_id, int32 chat_id)
: RequestActor(std::move(td), request_id), chat_id_(chat_id) {
}
};
class GetSupergroupRequest : public RequestActor<> {
ChannelId channel_id_;
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->get_channel(channel_id_, get_tries(), std::move(promise));
}
void do_send_result() override {
send_result(td->contacts_manager_->get_supergroup_object(channel_id_));
}
public:
GetSupergroupRequest(ActorShared<Td> td, uint64 request_id, int32 channel_id)
: RequestActor(std::move(td), request_id), channel_id_(channel_id) {
set_tries(3);
}
};
class GetSupergroupFullInfoRequest : public RequestActor<> {
ChannelId channel_id_;
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->get_channel_full(channel_id_, std::move(promise));
}
void do_send_result() override {
send_result(td->contacts_manager_->get_channel_full_info_object(channel_id_));
}
public:
GetSupergroupFullInfoRequest(ActorShared<Td> td, uint64 request_id, int32 channel_id)
: RequestActor(std::move(td), request_id), channel_id_(channel_id) {
}
};
class GetSecretChatRequest : public RequestActor<> {
SecretChatId secret_chat_id_;
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->get_secret_chat(secret_chat_id_, get_tries() < 2, std::move(promise));
}
void do_send_result() override {
send_result(td->contacts_manager_->get_secret_chat_object(secret_chat_id_));
}
public:
GetSecretChatRequest(ActorShared<Td> td, uint64 request_id, int32 secret_chat_id)
: RequestActor(std::move(td), request_id), secret_chat_id_(secret_chat_id) {
}
};
class GetChatRequest : public RequestActor<> {
DialogId dialog_id_;
bool dialog_found_ = false;
void do_run(Promise<Unit> &&promise) override {
dialog_found_ = td->messages_manager_->load_dialog(dialog_id_, get_tries(), std::move(promise));
}
void do_send_result() override {
if (!dialog_found_) {
send_error(Status::Error(400, "Chat is not accessible"));
} else {
send_result(td->messages_manager_->get_chat_object(dialog_id_));
}
}
public:
GetChatRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id)
: RequestActor(std::move(td), request_id), dialog_id_(dialog_id) {
set_tries(3);
}
};
class GetChatsRequest : public RequestActor<> {
DialogDate offset_;
int32 limit_;
vector<DialogId> dialog_ids_;
void do_run(Promise<Unit> &&promise) override {
dialog_ids_ = td->messages_manager_->get_dialogs(offset_, limit_, get_tries() < 2, std::move(promise));
}
void do_send_result() override {
send_result(MessagesManager::get_chats_object(dialog_ids_));
}
public:
GetChatsRequest(ActorShared<Td> td, uint64 request_id, int64 offset_order, int64 offset_dialog_id, int32 limit)
: RequestActor(std::move(td), request_id), offset_(offset_order, DialogId(offset_dialog_id)), limit_(limit) {
// 1 for database + 1 for server request + 1 for server request at the end + 1 for return + 1 just in case
set_tries(5);
}
};
class SearchPublicChatRequest : public RequestActor<> {
string username_;
DialogId dialog_id_;
void do_run(Promise<Unit> &&promise) override {
dialog_id_ = td->messages_manager_->search_public_dialog(username_, get_tries() < 3, std::move(promise));
}
void do_send_result() override {
send_result(td->messages_manager_->get_chat_object(dialog_id_));
}
public:
SearchPublicChatRequest(ActorShared<Td> td, uint64 request_id, string username)
: RequestActor(std::move(td), request_id), username_(std::move(username)) {
set_tries(3);
}
};
class SearchPublicChatsRequest : public RequestActor<> {
string query_;
vector<DialogId> dialog_ids_;
void do_run(Promise<Unit> &&promise) override {
dialog_ids_ = td->messages_manager_->search_public_dialogs(query_, std::move(promise));
}
void do_send_result() override {
send_result(MessagesManager::get_chats_object(dialog_ids_));
}
public:
SearchPublicChatsRequest(ActorShared<Td> td, uint64 request_id, string query)
: RequestActor(std::move(td), request_id), query_(std::move(query)) {
}
};
class SearchChatsRequest : public RequestActor<> {
string query_;
int32 limit_;
vector<DialogId> dialog_ids_;
void do_run(Promise<Unit> &&promise) override {
dialog_ids_ = td->messages_manager_->search_dialogs(query_, limit_, std::move(promise)).second;
}
void do_send_result() override {
send_result(MessagesManager::get_chats_object(dialog_ids_));
}
public:
SearchChatsRequest(ActorShared<Td> td, uint64 request_id, string query, int32 limit)
: RequestActor(std::move(td), request_id), query_(std::move(query)), limit_(limit) {
}
};
class GetGroupsInCommonRequest : public RequestActor<> {
UserId user_id_;
DialogId offset_dialog_id_;
int32 limit_;
vector<DialogId> dialog_ids_;
void do_run(Promise<Unit> &&promise) override {
dialog_ids_ = td->messages_manager_->get_common_dialogs(user_id_, offset_dialog_id_, limit_, get_tries() < 2,
std::move(promise));
}
void do_send_result() override {
send_result(MessagesManager::get_chats_object(dialog_ids_));
}
public:
GetGroupsInCommonRequest(ActorShared<Td> td, uint64 request_id, int32 user_id, int64 offset_dialog_id, int32 limit)
: RequestActor(std::move(td), request_id), user_id_(user_id), offset_dialog_id_(offset_dialog_id), limit_(limit) {
}
};
class GetCreatedPublicChatsRequest : public RequestActor<> {
vector<DialogId> dialog_ids_;
void do_run(Promise<Unit> &&promise) override {
dialog_ids_ = td->contacts_manager_->get_created_public_dialogs(std::move(promise));
}
void do_send_result() override {
send_result(MessagesManager::get_chats_object(dialog_ids_));
}
public:
GetCreatedPublicChatsRequest(ActorShared<Td> td, uint64 request_id) : RequestActor(std::move(td), request_id) {
}
};
class GetMessageRequest : public RequestOnceActor {
FullMessageId full_message_id_;
void do_run(Promise<Unit> &&promise) override {
td->messages_manager_->get_message(full_message_id_, std::move(promise));
}
void do_send_result() override {
send_result(td->messages_manager_->get_message_object(full_message_id_));
}
public:
GetMessageRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, int64 message_id)
: RequestOnceActor(std::move(td), request_id), full_message_id_(DialogId(dialog_id), MessageId(message_id)) {
}
};
class GetMessagesRequest : public RequestOnceActor {
DialogId dialog_id_;
vector<MessageId> message_ids_;
void do_run(Promise<Unit> &&promise) override {
td->messages_manager_->get_messages(dialog_id_, message_ids_, std::move(promise));
}
void do_send_result() override {
send_result(td->messages_manager_->get_messages_object(-1, dialog_id_, message_ids_));
}
public:
GetMessagesRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, const vector<int64> &message_ids)
: RequestOnceActor(std::move(td), request_id)
, dialog_id_(dialog_id)
, message_ids_(MessagesManager::get_message_ids(message_ids)) {
}
};
class GetPublicMessageLinkRequest : public RequestActor<> {
FullMessageId full_message_id_;
string link_;
void do_run(Promise<Unit> &&promise) override {
link_ = td->messages_manager_->get_public_message_link(full_message_id_, std::move(promise));
}
void do_send_result() override {
send_result(make_tl_object<td_api::publicMessageLink>(link_));
}
public:
GetPublicMessageLinkRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, int64 message_id)
: RequestActor(std::move(td), request_id), full_message_id_(DialogId(dialog_id), MessageId(message_id)) {
}
};
class EditMessageTextRequest : public RequestOnceActor {
FullMessageId full_message_id_;
tl_object_ptr<td_api::ReplyMarkup> reply_markup_;
tl_object_ptr<td_api::InputMessageContent> input_message_content_;
void do_run(Promise<Unit> &&promise) override {
td->messages_manager_->edit_message_text(full_message_id_, std::move(reply_markup_),
std::move(input_message_content_), std::move(promise));
}
void do_send_result() override {
send_result(td->messages_manager_->get_message_object(full_message_id_));
}
public:
EditMessageTextRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, int64 message_id,
tl_object_ptr<td_api::ReplyMarkup> reply_markup,
tl_object_ptr<td_api::InputMessageContent> input_message_content)
: RequestOnceActor(std::move(td), request_id)
, full_message_id_(DialogId(dialog_id), MessageId(message_id))
, reply_markup_(std::move(reply_markup))
, input_message_content_(std::move(input_message_content)) {
}
};
class EditMessageLiveLocationRequest : public RequestOnceActor {
FullMessageId full_message_id_;
tl_object_ptr<td_api::ReplyMarkup> reply_markup_;
tl_object_ptr<td_api::location> location_;
void do_run(Promise<Unit> &&promise) override {
td->messages_manager_->edit_message_live_location(full_message_id_, std::move(reply_markup_), std::move(location_),
std::move(promise));
}
void do_send_result() override {
send_result(td->messages_manager_->get_message_object(full_message_id_));
}
public:
EditMessageLiveLocationRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, int64 message_id,
tl_object_ptr<td_api::ReplyMarkup> reply_markup,
tl_object_ptr<td_api::location> location)
: RequestOnceActor(std::move(td), request_id)
, full_message_id_(DialogId(dialog_id), MessageId(message_id))
, reply_markup_(std::move(reply_markup))
, location_(std::move(location)) {
}
};
class EditMessageCaptionRequest : public RequestOnceActor {
FullMessageId full_message_id_;
tl_object_ptr<td_api::ReplyMarkup> reply_markup_;
string caption_;
void do_run(Promise<Unit> &&promise) override {
td->messages_manager_->edit_message_caption(full_message_id_, std::move(reply_markup_), caption_,
std::move(promise));
}
void do_send_result() override {
send_result(td->messages_manager_->get_message_object(full_message_id_));
}
public:
EditMessageCaptionRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, int64 message_id,
tl_object_ptr<td_api::ReplyMarkup> reply_markup, string caption)
: RequestOnceActor(std::move(td), request_id)
, full_message_id_(DialogId(dialog_id), MessageId(message_id))
, reply_markup_(std::move(reply_markup))
, caption_(std::move(caption)) {
}
};
class EditMessageReplyMarkupRequest : public RequestOnceActor {
FullMessageId full_message_id_;
tl_object_ptr<td_api::ReplyMarkup> reply_markup_;
void do_run(Promise<Unit> &&promise) override {
td->messages_manager_->edit_message_reply_markup(full_message_id_, std::move(reply_markup_), std::move(promise));
}
void do_send_result() override {
send_result(td->messages_manager_->get_message_object(full_message_id_));
}
public:
EditMessageReplyMarkupRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, int64 message_id,
tl_object_ptr<td_api::ReplyMarkup> reply_markup)
: RequestOnceActor(std::move(td), request_id)
, full_message_id_(DialogId(dialog_id), MessageId(message_id))
, reply_markup_(std::move(reply_markup)) {
}
};
class EditInlineMessageTextRequest : public RequestOnceActor {
string inline_message_id_;
tl_object_ptr<td_api::ReplyMarkup> reply_markup_;
tl_object_ptr<td_api::InputMessageContent> input_message_content_;
void do_run(Promise<Unit> &&promise) override {
td->messages_manager_->edit_inline_message_text(inline_message_id_, std::move(reply_markup_),
std::move(input_message_content_), std::move(promise));
}
public:
EditInlineMessageTextRequest(ActorShared<Td> td, uint64 request_id, string inline_message_id,
tl_object_ptr<td_api::ReplyMarkup> reply_markup,
tl_object_ptr<td_api::InputMessageContent> input_message_content)
: RequestOnceActor(std::move(td), request_id)
, inline_message_id_(std::move(inline_message_id))
, reply_markup_(std::move(reply_markup))
, input_message_content_(std::move(input_message_content)) {
}
};
class EditInlineMessageLiveLocationRequest : public RequestOnceActor {
string inline_message_id_;
tl_object_ptr<td_api::ReplyMarkup> reply_markup_;
tl_object_ptr<td_api::location> location_;
void do_run(Promise<Unit> &&promise) override {
td->messages_manager_->edit_inline_message_live_location(inline_message_id_, std::move(reply_markup_),
std::move(location_), std::move(promise));
}
public:
EditInlineMessageLiveLocationRequest(ActorShared<Td> td, uint64 request_id, string inline_message_id,
tl_object_ptr<td_api::ReplyMarkup> reply_markup,
tl_object_ptr<td_api::location> location)
: RequestOnceActor(std::move(td), request_id)
, inline_message_id_(std::move(inline_message_id))
, reply_markup_(std::move(reply_markup))
, location_(std::move(location)) {
}
};
class EditInlineMessageCaptionRequest : public RequestOnceActor {
string inline_message_id_;
tl_object_ptr<td_api::ReplyMarkup> reply_markup_;
string caption_;
void do_run(Promise<Unit> &&promise) override {
td->messages_manager_->edit_inline_message_caption(inline_message_id_, std::move(reply_markup_), caption_,
std::move(promise));
}
public:
EditInlineMessageCaptionRequest(ActorShared<Td> td, uint64 request_id, string inline_message_id,
tl_object_ptr<td_api::ReplyMarkup> reply_markup, string caption)
: RequestOnceActor(std::move(td), request_id)
, inline_message_id_(std::move(inline_message_id))
, reply_markup_(std::move(reply_markup))
, caption_(std::move(caption)) {
}
};
class EditInlineMessageReplyMarkupRequest : public RequestOnceActor {
string inline_message_id_;
tl_object_ptr<td_api::ReplyMarkup> reply_markup_;
void do_run(Promise<Unit> &&promise) override {
td->messages_manager_->edit_inline_message_reply_markup(inline_message_id_, std::move(reply_markup_),
std::move(promise));
}
public:
EditInlineMessageReplyMarkupRequest(ActorShared<Td> td, uint64 request_id, string inline_message_id,
tl_object_ptr<td_api::ReplyMarkup> reply_markup)
: RequestOnceActor(std::move(td), request_id)
, inline_message_id_(std::move(inline_message_id))
, reply_markup_(std::move(reply_markup)) {
}
};
class SetGameScoreRequest : public RequestOnceActor {
FullMessageId full_message_id_;
bool edit_message_;
UserId user_id_;
int32 score_;
bool force_;
void do_run(Promise<Unit> &&promise) override {
td->messages_manager_->set_game_score(full_message_id_, edit_message_, user_id_, score_, force_,
std::move(promise));
}
void do_send_result() override {
send_result(td->messages_manager_->get_message_object(full_message_id_));
}
public:
SetGameScoreRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, int64 message_id, bool edit_message,
int32 user_id, int32 score, bool force)
: RequestOnceActor(std::move(td), request_id)
, full_message_id_(DialogId(dialog_id), MessageId(message_id))
, edit_message_(edit_message)
, user_id_(user_id)
, score_(score)
, force_(force) {
}
};
class SetInlineGameScoreRequest : public RequestOnceActor {
string inline_message_id_;
bool edit_message_;
UserId user_id_;
int32 score_;
bool force_;
void do_run(Promise<Unit> &&promise) override {
td->messages_manager_->set_inline_game_score(inline_message_id_, edit_message_, user_id_, score_, force_,
std::move(promise));
}
public:
SetInlineGameScoreRequest(ActorShared<Td> td, uint64 request_id, string inline_message_id, bool edit_message,
int32 user_id, int32 score, bool force)
: RequestOnceActor(std::move(td), request_id)
, inline_message_id_(std::move(inline_message_id))
, edit_message_(edit_message)
, user_id_(user_id)
, score_(score)
, force_(force) {
}
};
class GetGameHighScoresRequest : public RequestOnceActor {
FullMessageId full_message_id_;
UserId user_id_;
int64 random_id_;
void do_run(Promise<Unit> &&promise) override {
random_id_ = td->messages_manager_->get_game_high_scores(full_message_id_, user_id_, std::move(promise));
}
void do_send_result() override {
CHECK(random_id_ != 0);
send_result(td->messages_manager_->get_game_high_scores_object(random_id_));
}
public:
GetGameHighScoresRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, int64 message_id, int32 user_id)
: RequestOnceActor(std::move(td), request_id)
, full_message_id_(DialogId(dialog_id), MessageId(message_id))
, user_id_(user_id)
, random_id_(0) {
}
};
class GetInlineGameHighScoresRequest : public RequestOnceActor {
string inline_message_id_;
UserId user_id_;
int64 random_id_;
void do_run(Promise<Unit> &&promise) override {
random_id_ = td->messages_manager_->get_inline_game_high_scores(inline_message_id_, user_id_, std::move(promise));
}
void do_send_result() override {
CHECK(random_id_ != 0);
send_result(td->messages_manager_->get_game_high_scores_object(random_id_));
}
public:
GetInlineGameHighScoresRequest(ActorShared<Td> td, uint64 request_id, string inline_message_id, int32 user_id)
: RequestOnceActor(std::move(td), request_id)
, inline_message_id_(std::move(inline_message_id))
, user_id_(user_id)
, random_id_(0) {
}
};
class SendChatActionRequest : public RequestOnceActor {
DialogId dialog_id_;
tl_object_ptr<td_api::ChatAction> action_;
void do_run(Promise<Unit> &&promise) override {
td->messages_manager_->send_dialog_action(dialog_id_, action_, std::move(promise));
}
public:
SendChatActionRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id,
tl_object_ptr<td_api::ChatAction> &&action)
: RequestOnceActor(std::move(td), request_id), dialog_id_(dialog_id), action_(std::move(action)) {
}
};
class GetChatHistoryRequest : public RequestActor<> {
DialogId dialog_id_;
MessageId from_message_id_;
int32 offset_;
int32 limit_;
bool only_local_;
tl_object_ptr<td_api::messages> messages_;
void do_run(Promise<Unit> &&promise) override {
messages_ = td->messages_manager_->get_dialog_history(dialog_id_, from_message_id_, offset_, limit_,
get_tries() - 1, only_local_, std::move(promise));
}
void do_send_result() override {
send_result(std::move(messages_));
}
public:
GetChatHistoryRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, int64 from_message_id, int32 offset,
int32 limit, bool only_local)
: RequestActor(std::move(td), request_id)
, dialog_id_(dialog_id)
, from_message_id_(from_message_id)
, offset_(offset)
, limit_(limit)
, only_local_(only_local) {
if (!only_local_) {
set_tries(4);
}
}
};
class DeleteChatHistoryRequest : public RequestOnceActor {
DialogId dialog_id_;
bool remove_from_chat_list_;
void do_run(Promise<Unit> &&promise) override {
td->messages_manager_->delete_dialog_history(dialog_id_, remove_from_chat_list_, std::move(promise));
}
public:
DeleteChatHistoryRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, bool remove_from_chat_list)
: RequestOnceActor(std::move(td), request_id)
, dialog_id_(dialog_id)
, remove_from_chat_list_(remove_from_chat_list) {
}
};
class SearchChatMessagesRequest : public RequestActor<> {
DialogId dialog_id_;
string query_;
UserId sender_user_id_;
MessageId from_message_id_;
int32 offset_;
int32 limit_;
tl_object_ptr<td_api::SearchMessagesFilter> filter_;
int64 random_id_;
std::pair<int32, vector<MessageId>> messages_;
void do_run(Promise<Unit> &&promise) override {
messages_ = td->messages_manager_->search_dialog_messages(dialog_id_, query_, sender_user_id_, from_message_id_,
offset_, limit_, filter_, random_id_, get_tries() == 3,
std::move(promise));
}
void do_send_result() override {
send_result(td->messages_manager_->get_messages_object(messages_.first, dialog_id_, messages_.second));
}
void do_send_error(Status &&status) override {
if (status.message() == "SEARCH_QUERY_EMPTY") {
messages_.first = 0;
messages_.second.clear();
return do_send_result();
}
send_error(std::move(status));
}
public:
SearchChatMessagesRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, string query, int32 user_id,
int64 from_message_id, int32 offset, int32 limit,
tl_object_ptr<td_api::SearchMessagesFilter> filter)
: RequestActor(std::move(td), request_id)
, dialog_id_(dialog_id)
, query_(std::move(query))
, sender_user_id_(user_id)
, from_message_id_(from_message_id)
, offset_(offset)
, limit_(limit)
, filter_(std::move(filter))
, random_id_(0) {
set_tries(3);
}
};
class OfflineSearchMessagesRequest : public RequestActor<> {
DialogId dialog_id_;
string query_;
int64 from_search_id_;
int32 limit_;
tl_object_ptr<td_api::SearchMessagesFilter> filter_;
int64 random_id_;
std::pair<int64, vector<FullMessageId>> messages_;
void do_run(Promise<Unit> &&promise) override {
messages_ = td->messages_manager_->offline_search_messages(dialog_id_, query_, from_search_id_, limit_, filter_,
random_id_, std::move(promise));
}
void do_send_result() override {
vector<tl_object_ptr<td_api::message>> result;
result.reserve(messages_.second.size());
for (auto full_message_id : messages_.second) {
result.push_back(td->messages_manager_->get_message_object(full_message_id));
}
send_result(make_tl_object<td_api::foundMessages>(std::move(result), messages_.first));
}
public:
OfflineSearchMessagesRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, string query,
int64 from_search_id, int32 limit, tl_object_ptr<td_api::SearchMessagesFilter> filter)
: RequestActor(std::move(td), request_id)
, dialog_id_(dialog_id)
, query_(std::move(query))
, from_search_id_(from_search_id)
, limit_(limit)
, filter_(std::move(filter))
, random_id_(0) {
}
};
class SearchMessagesRequest : public RequestActor<> {
string query_;
int32 offset_date_;
DialogId offset_dialog_id_;
MessageId offset_message_id_;
int32 limit_;
int64 random_id_;
std::pair<int32, vector<FullMessageId>> messages_;
void do_run(Promise<Unit> &&promise) override {
messages_ = td->messages_manager_->search_messages(query_, offset_date_, offset_dialog_id_, offset_message_id_,
limit_, random_id_, std::move(promise));
}
void do_send_result() override {
send_result(td->messages_manager_->get_messages_object(messages_.first, messages_.second));
}
void do_send_error(Status &&status) override {
if (status.message() == "SEARCH_QUERY_EMPTY") {
messages_.first = 0;
messages_.second.clear();
return do_send_result();
}
send_error(std::move(status));
}
public:
SearchMessagesRequest(ActorShared<Td> td, uint64 request_id, string query, int32 offset_date, int64 offset_dialog_id,
int64 offset_message_id, int32 limit)
: RequestActor(std::move(td), request_id)
, query_(std::move(query))
, offset_date_(offset_date)
, offset_dialog_id_(offset_dialog_id)
, offset_message_id_(offset_message_id)
, limit_(limit)
, random_id_(0) {
}
};
class SearchCallMessagesRequest : public RequestActor<> {
MessageId from_message_id_;
int32 limit_;
bool only_missed_;
int64 random_id_;
std::pair<int32, vector<FullMessageId>> messages_;
void do_run(Promise<Unit> &&promise) override {
messages_ = td->messages_manager_->search_call_messages(from_message_id_, limit_, only_missed_, random_id_,
get_tries() == 3, std::move(promise));
}
void do_send_result() override {
send_result(td->messages_manager_->get_messages_object(messages_.first, messages_.second));
}
public:
SearchCallMessagesRequest(ActorShared<Td> td, uint64 request_id, int64 from_message_id, int32 limit, bool only_missed)
: RequestActor(std::move(td), request_id)
, from_message_id_(from_message_id)
, limit_(limit)
, only_missed_(only_missed)
, random_id_(0) {
set_tries(3);
}
};
class SearchChatRecentLocationMessagesRequest : public RequestActor<> {
DialogId dialog_id_;
int32 limit_;
int64 random_id_;
std::pair<int32, vector<MessageId>> messages_;
void do_run(Promise<Unit> &&promise) override {
messages_ = td->messages_manager_->search_dialog_recent_location_messages(dialog_id_, limit_, random_id_,
std::move(promise));
}
void do_send_result() override {
send_result(td->messages_manager_->get_messages_object(messages_.first, dialog_id_, messages_.second));
}
public:
SearchChatRecentLocationMessagesRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, int32 limit)
: RequestActor(std::move(td), request_id), dialog_id_(dialog_id), limit_(limit), random_id_(0) {
}
};
class GetActiveLiveLocationMessagesRequest : public RequestActor<> {
vector<FullMessageId> full_message_ids_;
void do_run(Promise<Unit> &&promise) override {
full_message_ids_ = td->messages_manager_->get_active_live_location_messages(std::move(promise));
}
void do_send_result() override {
send_result(td->messages_manager_->get_messages_object(-1, full_message_ids_));
}
public:
GetActiveLiveLocationMessagesRequest(ActorShared<Td> td, uint64 request_id)
: RequestActor(std::move(td), request_id) {
}
};
class GetChatMessageByDateRequest : public RequestOnceActor {
DialogId dialog_id_;
int32 date_;
int64 random_id_;
void do_run(Promise<Unit> &&promise) override {
random_id_ = td->messages_manager_->get_dialog_message_by_date(dialog_id_, date_, std::move(promise));
}
void do_send_result() override {
send_result(td->messages_manager_->get_dialog_message_by_date_object(random_id_));
}
public:
GetChatMessageByDateRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, int32 date)
: RequestOnceActor(std::move(td), request_id), dialog_id_(dialog_id), date_(date), random_id_(0) {
}
};
class DeleteMessagesRequest : public RequestOnceActor {
DialogId dialog_id_;
vector<MessageId> message_ids_;
bool revoke_;
void do_run(Promise<Unit> &&promise) override {
td->messages_manager_->delete_messages(dialog_id_, message_ids_, revoke_, std::move(promise));
}
public:
DeleteMessagesRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, vector<int64> message_ids, bool revoke)
: RequestOnceActor(std::move(td), request_id)
, dialog_id_(dialog_id)
, message_ids_(MessagesManager::get_message_ids(message_ids))
, revoke_(revoke) {
}
};
class DeleteChatMessagesFromUserRequest : public RequestOnceActor {
DialogId dialog_id_;
UserId user_id_;
void do_run(Promise<Unit> &&promise) override {
td->messages_manager_->delete_dialog_messages_from_user(dialog_id_, user_id_, std::move(promise));
}
public:
DeleteChatMessagesFromUserRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, int32 user_id)
: RequestOnceActor(std::move(td), request_id), dialog_id_(dialog_id), user_id_(user_id) {
}
};
class ReadAllChatMentionsRequest : public RequestOnceActor {
DialogId dialog_id_;
void do_run(Promise<Unit> &&promise) override {
td->messages_manager_->read_all_dialog_mentions(dialog_id_, std::move(promise));
}
public:
ReadAllChatMentionsRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id)
: RequestOnceActor(std::move(td), request_id), dialog_id_(dialog_id) {
}
};
class GetWebPagePreviewRequest : public RequestActor<> {
string message_text_;
WebPageId web_page_id_;
void do_run(Promise<Unit> &&promise) override {
web_page_id_ = td->web_pages_manager_->get_web_page_preview(message_text_, std::move(promise));
}
void do_send_result() override {
send_result(td->web_pages_manager_->get_web_page_object(web_page_id_));
}
public:
GetWebPagePreviewRequest(ActorShared<Td> td, uint64 request_id, string message_text)
: RequestActor(std::move(td), request_id), message_text_(std::move(message_text)) {
}
};
class GetWebPageInstantViewRequest : public RequestActor<> {
string url_;
bool force_full_;
WebPageId web_page_id_;
void do_run(Promise<Unit> &&promise) override {
web_page_id_ = td->web_pages_manager_->get_web_page_instant_view(url_, force_full_, std::move(promise));
}
void do_send_result() override {
send_result(td->web_pages_manager_->get_web_page_instant_view_object(web_page_id_));
}
public:
GetWebPageInstantViewRequest(ActorShared<Td> td, uint64 request_id, string url, bool force_full)
: RequestActor(std::move(td), request_id), url_(std::move(url)), force_full_(force_full) {
set_tries(3);
}
};
class CreateChatRequest : public RequestActor<> {
DialogId dialog_id_;
void do_run(Promise<Unit> &&promise) override {
td->messages_manager_->create_dialog(dialog_id_, std::move(promise));
}
void do_send_result() override {
send_result(td->messages_manager_->get_chat_object(dialog_id_));
}
public:
CreateChatRequest(ActorShared<Td> td, uint64 request_id, DialogId dialog_id)
: RequestActor<>(std::move(td), request_id), dialog_id_(dialog_id) {
}
};
class CreateNewGroupChatRequest : public RequestActor<> {
vector<UserId> user_ids_;
string title_;
int64 random_id_;
DialogId dialog_id_;
void do_run(Promise<Unit> &&promise) override {
dialog_id_ = td->messages_manager_->create_new_group_chat(user_ids_, title_, random_id_, std::move(promise));
}
void do_send_result() override {
CHECK(dialog_id_.is_valid());
send_result(td->messages_manager_->get_chat_object(dialog_id_));
}
public:
CreateNewGroupChatRequest(ActorShared<Td> td, uint64 request_id, vector<int32> user_ids, string title)
: RequestActor(std::move(td), request_id), title_(std::move(title)), random_id_(0) {
for (auto user_id : user_ids) {
user_ids_.emplace_back(user_id);
}
}
};
class CreateNewSecretChatRequest : public RequestActor<SecretChatId> {
UserId user_id_;
SecretChatId secret_chat_id_;
void do_run(Promise<SecretChatId> &&promise) override {
if (get_tries() < 2) {
promise.set_value(std::move(secret_chat_id_));
return;
}
td->messages_manager_->create_new_secret_chat(user_id_, std::move(promise));
}
void do_set_result(SecretChatId &&result) override {
secret_chat_id_ = result;
LOG(INFO) << "New " << secret_chat_id_ << " created";
}
void do_send_result() override {
CHECK(secret_chat_id_.is_valid());
// SecretChatActor will send this update by himself.
// But since the update may still be on its way, we will update essential fields here.
td->contacts_manager_->on_update_secret_chat(
secret_chat_id_, 0 /* no access_hash */, user_id_, SecretChatState::Unknown, true /* it is outbound chat */,
-1 /* unknown ttl */, 0 /* unknown creation date */, "" /* no key_hash */, 0);
DialogId dialog_id(secret_chat_id_);
td->messages_manager_->force_create_dialog(dialog_id, "create new secret chat");
send_result(td->messages_manager_->get_chat_object(dialog_id));
}
public:
CreateNewSecretChatRequest(ActorShared<Td> td, uint64 request_id, int32 user_id)
: RequestActor(std::move(td), request_id), user_id_(user_id) {
}
};
class CreateNewSupergroupChatRequest : public RequestActor<> {
string title_;
bool is_megagroup_;
string description_;
int64 random_id_;
DialogId dialog_id_;
void do_run(Promise<Unit> &&promise) override {
dialog_id_ = td->messages_manager_->create_new_channel_chat(title_, is_megagroup_, description_, random_id_,
std::move(promise));
}
void do_send_result() override {
CHECK(dialog_id_.is_valid());
send_result(td->messages_manager_->get_chat_object(dialog_id_));
}
public:
CreateNewSupergroupChatRequest(ActorShared<Td> td, uint64 request_id, string title, bool is_megagroup,
string description)
: RequestActor(std::move(td), request_id)
, title_(std::move(title))
, is_megagroup_(is_megagroup)
, description_(std::move(description))
, random_id_(0) {
}
};
class UpgradeGroupChatToSupergroupChatRequest : public RequestActor<> {
string title_;
DialogId dialog_id_;
DialogId result_dialog_id_;
void do_run(Promise<Unit> &&promise) override {
result_dialog_id_ = td->messages_manager_->migrate_dialog_to_megagroup(dialog_id_, std::move(promise));
}
void do_send_result() override {
CHECK(result_dialog_id_.is_valid());
send_result(td->messages_manager_->get_chat_object(result_dialog_id_));
}
public:
UpgradeGroupChatToSupergroupChatRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id)
: RequestActor(std::move(td), request_id), dialog_id_(dialog_id) {
}
};
class SetChatPhotoRequest : public RequestOnceActor {
DialogId dialog_id_;
tl_object_ptr<td_api::InputFile> input_file_;
void do_run(Promise<Unit> &&promise) override {
td->messages_manager_->set_dialog_photo(dialog_id_, input_file_, std::move(promise));
}
public:
SetChatPhotoRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id,
tl_object_ptr<td_api::InputFile> &&input_file)
: RequestOnceActor(std::move(td), request_id), dialog_id_(dialog_id), input_file_(std::move(input_file)) {
}
};
class SetChatTitleRequest : public RequestOnceActor {
DialogId dialog_id_;
string title_;
void do_run(Promise<Unit> &&promise) override {
td->messages_manager_->set_dialog_title(dialog_id_, title_, std::move(promise));
}
public:
SetChatTitleRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, string &&title)
: RequestOnceActor(std::move(td), request_id), dialog_id_(dialog_id), title_(std::move(title)) {
}
};
class AddChatMemberRequest : public RequestOnceActor {
DialogId dialog_id_;
UserId user_id_;
int32 forward_limit_;
void do_run(Promise<Unit> &&promise) override {
td->messages_manager_->add_dialog_participant(dialog_id_, user_id_, forward_limit_, std::move(promise));
}
public:
AddChatMemberRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, int32 user_id, int32 forward_limit)
: RequestOnceActor(std::move(td), request_id)
, dialog_id_(dialog_id)
, user_id_(user_id)
, forward_limit_(forward_limit) {
}
};
class AddChatMembersRequest : public RequestOnceActor {
DialogId dialog_id_;
vector<UserId> user_ids_;
void do_run(Promise<Unit> &&promise) override {
td->messages_manager_->add_dialog_participants(dialog_id_, user_ids_, std::move(promise));
}
public:
AddChatMembersRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, const vector<int32> &user_ids)
: RequestOnceActor(std::move(td), request_id), dialog_id_(dialog_id) {
for (auto &user_id : user_ids) {
user_ids_.emplace_back(user_id);
}
}
};
class SetChatMemberStatusRequest : public RequestOnceActor {
DialogId dialog_id_;
UserId user_id_;
tl_object_ptr<td_api::ChatMemberStatus> status_;
void do_run(Promise<Unit> &&promise) override {
td->messages_manager_->set_dialog_participant_status(dialog_id_, user_id_, status_, std::move(promise));
}
public:
SetChatMemberStatusRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, int32 user_id,
tl_object_ptr<td_api::ChatMemberStatus> &&status)
: RequestOnceActor(std::move(td), request_id)
, dialog_id_(dialog_id)
, user_id_(user_id)
, status_(std::move(status)) {
}
};
class GetChatMemberRequest : public RequestActor<> {
DialogId dialog_id_;
UserId user_id_;
int64 random_id_;
DialogParticipant dialog_participant_;
void do_run(Promise<Unit> &&promise) override {
dialog_participant_ = td->messages_manager_->get_dialog_participant(dialog_id_, user_id_, random_id_,
get_tries() < 3, std::move(promise));
}
void do_send_result() override {
if (!td->contacts_manager_->have_user(user_id_)) {
return send_error(Status::Error(3, "User not found"));
}
send_result(td->contacts_manager_->get_chat_member_object(dialog_participant_));
}
void do_send_error(Status &&status) override {
send_error(std::move(status));
}
public:
GetChatMemberRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, int32 user_id)
: RequestActor(std::move(td), request_id), dialog_id_(dialog_id), user_id_(user_id), random_id_(0) {
set_tries(3);
}
};
class SearchChatMembersRequest : public RequestActor<> {
DialogId dialog_id_;
string query_;
int32 limit_;
int64 random_id_ = 0;
std::pair<int32, vector<DialogParticipant>> participants_;
void do_run(Promise<Unit> &&promise) override {
participants_ = td->messages_manager_->search_dialog_participants(dialog_id_, query_, limit_, random_id_,
get_tries() < 3, std::move(promise));
}
void do_send_result() override {
// TODO create function get_chat_members_object
vector<tl_object_ptr<td_api::chatMember>> result;
result.reserve(participants_.second.size());
for (auto participant : participants_.second) {
result.push_back(td->contacts_manager_->get_chat_member_object(participant));
}
send_result(make_tl_object<td_api::chatMembers>(participants_.first, std::move(result)));
}
public:
SearchChatMembersRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, string &&query, int32 limit)
: RequestActor(std::move(td), request_id), dialog_id_(dialog_id), query_(std::move(query)), limit_(limit) {
set_tries(3);
}
};
class GetChatAdministratorsRequest : public RequestActor<> {
DialogId dialog_id_;
vector<UserId> user_ids_;
void do_run(Promise<Unit> &&promise) override {
user_ids_ = td->messages_manager_->get_dialog_administrators(dialog_id_, get_tries(), std::move(promise));
}
void do_send_result() override {
send_result(ContactsManager::get_users_object(-1, user_ids_));
}
public:
GetChatAdministratorsRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id)
: RequestActor(std::move(td), request_id), dialog_id_(dialog_id) {
set_tries(3);
}
};
class GenerateChatInviteLinkRequest : public RequestOnceActor {
DialogId dialog_id_;
void do_run(Promise<Unit> &&promise) override {
td->messages_manager_->export_dialog_invite_link(dialog_id_, std::move(promise));
}
void do_send_result() override {
send_result(make_tl_object<td_api::chatInviteLink>(td->messages_manager_->get_dialog_invite_link(dialog_id_)));
}
public:
GenerateChatInviteLinkRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id)
: RequestOnceActor(std::move(td), request_id), dialog_id_(dialog_id) {
}
};
class CheckChatInviteLinkRequest : public RequestActor<> {
string invite_link_;
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->check_dialog_invite_link(invite_link_, std::move(promise));
}
void do_send_result() override {
auto result = td->contacts_manager_->get_chat_invite_link_info_object(invite_link_);
CHECK(result != nullptr);
send_result(std::move(result));
}
public:
CheckChatInviteLinkRequest(ActorShared<Td> td, uint64 request_id, string invite_link)
: RequestActor(std::move(td), request_id), invite_link_(std::move(invite_link)) {
}
};
class JoinChatByInviteLinkRequest : public RequestOnceActor {
string invite_link_;
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->import_dialog_invite_link(invite_link_, std::move(promise));
}
public:
JoinChatByInviteLinkRequest(ActorShared<Td> td, uint64 request_id, string invite_link)
: RequestOnceActor(std::move(td), request_id), invite_link_(std::move(invite_link)) {
}
};
class GetChatEventLogRequest : public RequestOnceActor {
DialogId dialog_id_;
string query_;
int64 from_event_id_;
int32 limit_;
tl_object_ptr<td_api::chatEventLogFilters> filters_;
vector<UserId> user_ids_;
int64 random_id_ = 0;
void do_run(Promise<Unit> &&promise) override {
random_id_ = td->messages_manager_->get_dialog_event_log(dialog_id_, query_, from_event_id_, limit_, filters_,
user_ids_, std::move(promise));
}
void do_send_result() override {
CHECK(random_id_ != 0);
send_result(td->messages_manager_->get_chat_events_object(random_id_));
}
public:
GetChatEventLogRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, string &&query, int64 from_event_id,
int32 limit, tl_object_ptr<td_api::chatEventLogFilters> &&filters, vector<int32> user_ids)
: RequestOnceActor(std::move(td), request_id)
, dialog_id_(dialog_id)
, query_(std::move(query))
, from_event_id_(from_event_id)
, limit_(limit)
, filters_(std::move(filters)) {
for (auto user_id : user_ids) {
user_ids_.emplace_back(user_id);
}
}
};
class GetBlockedUsersRequest : public RequestOnceActor {
int32 offset_;
int32 limit_;
int64 random_id_;
void do_run(Promise<Unit> &&promise) override {
random_id_ = td->contacts_manager_->get_blocked_users(offset_, limit_, std::move(promise));
}
void do_send_result() override {
send_result(td->contacts_manager_->get_blocked_users_object(random_id_));
}
public:
GetBlockedUsersRequest(ActorShared<Td> td, uint64 request_id, int32 offset, int32 limit)
: RequestOnceActor(std::move(td), request_id), offset_(offset), limit_(limit), random_id_(0) {
}
};
class ImportContactsRequest : public RequestActor<> {
vector<tl_object_ptr<td_api::contact>> contacts_;
int64 random_id_;
std::pair<vector<UserId>, vector<int32>> imported_contacts_;
void do_run(Promise<Unit> &&promise) override {
imported_contacts_ = td->contacts_manager_->import_contacts(contacts_, random_id_, std::move(promise));
}
void do_send_result() override {
CHECK(imported_contacts_.first.size() == contacts_.size());
CHECK(imported_contacts_.second.size() == contacts_.size());
send_result(make_tl_object<td_api::importedContacts>(
transform(imported_contacts_.first, [](UserId user_id) { return user_id.get(); }),
std::move(imported_contacts_.second)));
}
public:
ImportContactsRequest(ActorShared<Td> td, uint64 request_id, vector<tl_object_ptr<td_api::contact>> &&contacts)
: RequestActor(std::move(td), request_id), contacts_(std::move(contacts)), random_id_(0) {
set_tries(3); // load_contacts + import_contacts
}
};
class SearchContactsRequest : public RequestActor<> {
string query_;
int32 limit_;
std::pair<int32, vector<UserId>> user_ids_;
void do_run(Promise<Unit> &&promise) override {
user_ids_ = td->contacts_manager_->search_contacts(query_, limit_, std::move(promise));
}
void do_send_result() override {
send_result(ContactsManager::get_users_object(user_ids_.first, user_ids_.second));
}
public:
SearchContactsRequest(ActorShared<Td> td, uint64 request_id, string query, int32 limit)
: RequestActor(std::move(td), request_id), query_(std::move(query)), limit_(limit) {
}
};
class RemoveContactsRequest : public RequestActor<> {
vector<UserId> user_ids_;
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->remove_contacts(user_ids_, std::move(promise));
}
public:
RemoveContactsRequest(ActorShared<Td> td, uint64 request_id, vector<int32> &&user_ids)
: RequestActor(std::move(td), request_id) {
for (auto user_id : user_ids) {
user_ids_.emplace_back(user_id);
}
set_tries(3); // load_contacts + delete_contacts
}
};
class GetImportedContactCountRequest : public RequestActor<> {
int32 imported_contact_count_ = 0;
void do_run(Promise<Unit> &&promise) override {
imported_contact_count_ = td->contacts_manager_->get_imported_contact_count(std::move(promise));
}
void do_send_result() override {
send_result(td_api::make_object<td_api::count>(imported_contact_count_));
}
public:
GetImportedContactCountRequest(ActorShared<Td> td, uint64 request_id) : RequestActor(std::move(td), request_id) {
}
};
class ChangeImportedContactsRequest : public RequestActor<> {
vector<tl_object_ptr<td_api::contact>> contacts_;
size_t contacts_size_;
int64 random_id_;
std::pair<vector<UserId>, vector<int32>> imported_contacts_;
void do_run(Promise<Unit> &&promise) override {
imported_contacts_ =
td->contacts_manager_->change_imported_contacts(std::move(contacts_), random_id_, std::move(promise));
}
void do_send_result() override {
CHECK(imported_contacts_.first.size() == contacts_size_);
CHECK(imported_contacts_.second.size() == contacts_size_);
send_result(make_tl_object<td_api::importedContacts>(
transform(imported_contacts_.first, [](UserId user_id) { return user_id.get(); }),
std::move(imported_contacts_.second)));
}
public:
ChangeImportedContactsRequest(ActorShared<Td> td, uint64 request_id,
vector<tl_object_ptr<td_api::contact>> &&contacts)
: RequestActor(std::move(td), request_id)
, contacts_(std::move(contacts))
, contacts_size_(contacts_.size())
, random_id_(0) {
set_tries(4); // load_contacts + load_local_contacts + (import_contacts + delete_contacts)
}
};
class ClearImportedContactsRequest : public RequestActor<> {
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->clear_imported_contacts(std::move(promise));
}
public:
ClearImportedContactsRequest(ActorShared<Td> td, uint64 request_id) : RequestActor(std::move(td), request_id) {
set_tries(3); // load_contacts + clear
}
};
class GetRecentInlineBotsRequest : public RequestActor<> {
vector<UserId> user_ids_;
void do_run(Promise<Unit> &&promise) override {
user_ids_ = td->inline_queries_manager_->get_recent_inline_bots(std::move(promise));
}
void do_send_result() override {
send_result(ContactsManager::get_users_object(-1, user_ids_));
}
public:
GetRecentInlineBotsRequest(ActorShared<Td> td, uint64 request_id) : RequestActor(std::move(td), request_id) {
}
};
class SetNameRequest : public RequestOnceActor {
string first_name_;
string last_name_;
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->set_name(first_name_, last_name_, std::move(promise));
}
public:
SetNameRequest(ActorShared<Td> td, uint64 request_id, string first_name, string last_name)
: RequestOnceActor(std::move(td), request_id)
, first_name_(std::move(first_name))
, last_name_(std::move(last_name)) {
}
};
class SetBioRequest : public RequestOnceActor {
string bio_;
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->set_bio(bio_, std::move(promise));
}
public:
SetBioRequest(ActorShared<Td> td, uint64 request_id, string bio)
: RequestOnceActor(std::move(td), request_id), bio_(std::move(bio)) {
}
};
class SetUsernameRequest : public RequestOnceActor {
string username_;
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->set_username(username_, std::move(promise));
}
public:
SetUsernameRequest(ActorShared<Td> td, uint64 request_id, string username)
: RequestOnceActor(std::move(td), request_id), username_(std::move(username)) {
}
};
class SetProfilePhotoRequest : public RequestOnceActor {
tl_object_ptr<td_api::InputFile> input_file_;
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->set_profile_photo(input_file_, std::move(promise));
}
public:
SetProfilePhotoRequest(ActorShared<Td> td, uint64 request_id, tl_object_ptr<td_api::InputFile> &&input_file)
: RequestOnceActor(std::move(td), request_id), input_file_(std::move(input_file)) {
}
};
class DeleteProfilePhotoRequest : public RequestOnceActor {
int64 profile_photo_id_;
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->delete_profile_photo(profile_photo_id_, std::move(promise));
}
public:
DeleteProfilePhotoRequest(ActorShared<Td> td, uint64 request_id, int64 profile_photo_id)
: RequestOnceActor(std::move(td), request_id), profile_photo_id_(profile_photo_id) {
}
};
class ToggleGroupAdministratorsRequest : public RequestOnceActor {
ChatId chat_id_;
bool everyone_is_administrator_;
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->toggle_chat_administrators(chat_id_, everyone_is_administrator_, std::move(promise));
}
public:
ToggleGroupAdministratorsRequest(ActorShared<Td> td, uint64 request_id, int32 chat_id, bool everyone_is_administrator)
: RequestOnceActor(std::move(td), request_id)
, chat_id_(chat_id)
, everyone_is_administrator_(everyone_is_administrator) {
}
};
class SetSupergroupUsernameRequest : public RequestOnceActor {
ChannelId channel_id_;
string username_;
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->set_channel_username(channel_id_, username_, std::move(promise));
}
public:
SetSupergroupUsernameRequest(ActorShared<Td> td, uint64 request_id, int32 channel_id, string username)
: RequestOnceActor(std::move(td), request_id), channel_id_(channel_id), username_(std::move(username)) {
}
};
class SetSupergroupStickerSetRequest : public RequestOnceActor {
ChannelId channel_id_;
int64 sticker_set_id_;
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->set_channel_sticker_set(channel_id_, sticker_set_id_, std::move(promise));
}
public:
SetSupergroupStickerSetRequest(ActorShared<Td> td, uint64 request_id, int32 channel_id, int64 sticker_set_id)
: RequestOnceActor(std::move(td), request_id), channel_id_(channel_id), sticker_set_id_(sticker_set_id) {
}
};
class ToggleSupergroupInvitesRequest : public RequestOnceActor {
ChannelId channel_id_;
bool anyone_can_invite_;
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->toggle_channel_invites(channel_id_, anyone_can_invite_, std::move(promise));
}
public:
ToggleSupergroupInvitesRequest(ActorShared<Td> td, uint64 request_id, int32 channel_id, bool anyone_can_invite)
: RequestOnceActor(std::move(td), request_id), channel_id_(channel_id), anyone_can_invite_(anyone_can_invite) {
}
};
class ToggleSupergroupSignMessagesRequest : public RequestOnceActor {
ChannelId channel_id_;
bool sign_messages_;
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->toggle_channel_sign_messages(channel_id_, sign_messages_, std::move(promise));
}
public:
ToggleSupergroupSignMessagesRequest(ActorShared<Td> td, uint64 request_id, int32 channel_id, bool sign_messages)
: RequestOnceActor(std::move(td), request_id), channel_id_(channel_id), sign_messages_(sign_messages) {
}
};
class ToggleSupergroupIsAllHistoryAvailableRequest : public RequestOnceActor {
ChannelId channel_id_;
bool is_all_history_available_;
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->toggle_channel_is_all_history_available(channel_id_, is_all_history_available_,
std::move(promise));
}
public:
ToggleSupergroupIsAllHistoryAvailableRequest(ActorShared<Td> td, uint64 request_id, int32 channel_id,
bool is_all_history_available)
: RequestOnceActor(std::move(td), request_id)
, channel_id_(channel_id)
, is_all_history_available_(is_all_history_available) {
}
};
class SetSupergroupDescriptionRequest : public RequestOnceActor {
ChannelId channel_id_;
string description_;
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->set_channel_description(channel_id_, description_, std::move(promise));
}
public:
SetSupergroupDescriptionRequest(ActorShared<Td> td, uint64 request_id, int32 channel_id, string description)
: RequestOnceActor(std::move(td), request_id), channel_id_(channel_id), description_(std::move(description)) {
}
};
class PinSupergroupMessageRequest : public RequestOnceActor {
ChannelId channel_id_;
MessageId message_id_;
bool disable_notification_;
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->pin_channel_message(channel_id_, message_id_, disable_notification_, std::move(promise));
}
public:
PinSupergroupMessageRequest(ActorShared<Td> td, uint64 request_id, int32 channel_id, int64 message_id,
bool disable_notification)
: RequestOnceActor(std::move(td), request_id)
, channel_id_(channel_id)
, message_id_(message_id)
, disable_notification_(disable_notification) {
}
};
class UnpinSupergroupMessageRequest : public RequestOnceActor {
ChannelId channel_id_;
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->unpin_channel_message(channel_id_, std::move(promise));
}
public:
UnpinSupergroupMessageRequest(ActorShared<Td> td, uint64 request_id, int32 channel_id)
: RequestOnceActor(std::move(td), request_id), channel_id_(channel_id) {
}
};
class ReportSupergroupSpamRequest : public RequestOnceActor {
ChannelId channel_id_;
UserId user_id_;
vector<MessageId> message_ids_;
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->report_channel_spam(channel_id_, user_id_, message_ids_, std::move(promise));
}
public:
ReportSupergroupSpamRequest(ActorShared<Td> td, uint64 request_id, int32 channel_id, int32 user_id,
const vector<int64> &message_ids)
: RequestOnceActor(std::move(td), request_id)
, channel_id_(channel_id)
, user_id_(user_id)
, message_ids_(MessagesManager::get_message_ids(message_ids)) {
}
};
class GetSupergroupMembersRequest : public RequestActor<> {
ChannelId channel_id_;
tl_object_ptr<td_api::SupergroupMembersFilter> filter_;
int32 offset_;
int32 limit_;
int64 random_id_ = 0;
std::pair<int32, vector<DialogParticipant>> participants_;
void do_run(Promise<Unit> &&promise) override {
participants_ = td->contacts_manager_->get_channel_participants(channel_id_, filter_, offset_, limit_, random_id_,
get_tries() < 3, std::move(promise));
}
void do_send_result() override {
// TODO create function get_chat_members_object
vector<tl_object_ptr<td_api::chatMember>> result;
result.reserve(participants_.second.size());
for (auto participant : participants_.second) {
result.push_back(td->contacts_manager_->get_chat_member_object(participant));
}
send_result(make_tl_object<td_api::chatMembers>(participants_.first, std::move(result)));
}
public:
GetSupergroupMembersRequest(ActorShared<Td> td, uint64 request_id, int32 channel_id,
tl_object_ptr<td_api::SupergroupMembersFilter> &&filter, int32 offset, int32 limit)
: RequestActor(std::move(td), request_id)
, channel_id_(channel_id)
, filter_(std::move(filter))
, offset_(offset)
, limit_(limit) {
set_tries(3);
}
};
class DeleteSupergroupRequest : public RequestOnceActor {
ChannelId channel_id_;
void do_run(Promise<Unit> &&promise) override {
td->contacts_manager_->delete_channel(channel_id_, std::move(promise));
}
public:
DeleteSupergroupRequest(ActorShared<Td> td, uint64 request_id, int32 channel_id)
: RequestOnceActor(std::move(td), request_id), channel_id_(channel_id) {
}
};
class GetUserProfilePhotosRequest : public RequestActor<> {
UserId user_id_;
int32 offset_;
int32 limit_;
std::pair<int32, vector<const Photo *>> photos;
void do_run(Promise<Unit> &&promise) override {
photos = td->contacts_manager_->get_user_profile_photos(user_id_, offset_, limit_, std::move(promise));
}
void do_send_result() override {
// TODO create function get_user_profile_photos_object
vector<tl_object_ptr<td_api::photo>> result;
result.reserve(photos.second.size());
for (auto photo : photos.second) {
result.push_back(get_photo_object(td->file_manager_.get(), photo));
}
send_result(make_tl_object<td_api::userProfilePhotos>(photos.first, std::move(result)));
}
public:
GetUserProfilePhotosRequest(ActorShared<Td> td, uint64 request_id, int32 user_id, int32 offset, int32 limit)
: RequestActor(std::move(td), request_id), user_id_(user_id), offset_(offset), limit_(limit) {
}
};
class GetNotificationSettingsRequest : public RequestActor<> {
NotificationSettingsScope scope_;
const NotificationSettings *notification_settings_ = nullptr;
void do_run(Promise<Unit> &&promise) override {
notification_settings_ = td->messages_manager_->get_notification_settings(scope_, std::move(promise));
}
void do_send_result() override {
CHECK(notification_settings_ != nullptr);
send_result(td->messages_manager_->get_notification_settings_object(notification_settings_));
}
public:
GetNotificationSettingsRequest(ActorShared<Td> td, uint64 request_id, NotificationSettingsScope scope)
: RequestActor(std::move(td), request_id), scope_(scope) {
}
};
class GetChatReportSpamStateRequest : public RequestActor<> {
DialogId dialog_id_;
bool can_report_spam_ = false;
void do_run(Promise<Unit> &&promise) override {
can_report_spam_ = td->messages_manager_->get_dialog_report_spam_state(dialog_id_, std::move(promise));
}
void do_send_result() override {
send_result(make_tl_object<td_api::chatReportSpamState>(can_report_spam_));
}
public:
GetChatReportSpamStateRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id)
: RequestActor(std::move(td), request_id), dialog_id_(dialog_id) {
}
};
class ChangeChatReportSpamStateRequest : public RequestOnceActor {
DialogId dialog_id_;
bool is_spam_dialog_;
void do_run(Promise<Unit> &&promise) override {
td->messages_manager_->change_dialog_report_spam_state(dialog_id_, is_spam_dialog_, std::move(promise));
}
public:
ChangeChatReportSpamStateRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, bool is_spam_dialog)
: RequestOnceActor(std::move(td), request_id), dialog_id_(dialog_id), is_spam_dialog_(is_spam_dialog) {
}
};
class ReportChatRequest : public RequestOnceActor {
DialogId dialog_id_;
tl_object_ptr<td_api::ChatReportReason> reason_;
void do_run(Promise<Unit> &&promise) override {
td->messages_manager_->report_dialog(dialog_id_, reason_, std::move(promise));
}
public:
ReportChatRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id,
tl_object_ptr<td_api::ChatReportReason> reason)
: RequestOnceActor(std::move(td), request_id), dialog_id_(dialog_id), reason_(std::move(reason)) {
}
};
class GetStickersRequest : public RequestActor<> {
string emoji_;
int32 limit_;
vector<FileId> sticker_ids_;
void do_run(Promise<Unit> &&promise) override {
sticker_ids_ = td->stickers_manager_->get_stickers(emoji_, limit_, get_tries() < 2, std::move(promise));
}
void do_send_result() override {
send_result(td->stickers_manager_->get_stickers_object(sticker_ids_));
}
public:
GetStickersRequest(ActorShared<Td> td, uint64 request_id, string &&emoji, int32 limit)
: RequestActor(std::move(td), request_id), emoji_(std::move(emoji)), limit_(limit) {
set_tries(5);
}
};
class GetInstalledStickerSetsRequest : public RequestActor<> {
bool is_masks_;
vector<int64> sticker_set_ids_;
void do_run(Promise<Unit> &&promise) override {
sticker_set_ids_ = td->stickers_manager_->get_installed_sticker_sets(is_masks_, std::move(promise));
}
void do_send_result() override {
send_result(td->stickers_manager_->get_sticker_sets_object(narrow_cast<int32>(sticker_set_ids_.size()),
sticker_set_ids_, 1));
}
public:
GetInstalledStickerSetsRequest(ActorShared<Td> td, uint64 request_id, bool is_masks)
: RequestActor(std::move(td), request_id), is_masks_(is_masks) {
}
};
class GetArchivedStickerSetsRequest : public RequestActor<> {
bool is_masks_;
int64 offset_sticker_set_id_;
int32 limit_;
int32 total_count_;
vector<int64> sticker_set_ids_;
void do_run(Promise<Unit> &&promise) override {
std::tie(total_count_, sticker_set_ids_) = td->stickers_manager_->get_archived_sticker_sets(
is_masks_, offset_sticker_set_id_, limit_, get_tries() < 2, std::move(promise));
}
void do_send_result() override {
send_result(td->stickers_manager_->get_sticker_sets_object(total_count_, sticker_set_ids_, 1));
}
public:
GetArchivedStickerSetsRequest(ActorShared<Td> td, uint64 request_id, bool is_masks, int64 offset_sticker_set_id,
int32 limit)
: RequestActor(std::move(td), request_id)
, is_masks_(is_masks)
, offset_sticker_set_id_(offset_sticker_set_id)
, limit_(limit) {
}
};
class GetTrendingStickerSetsRequest : public RequestActor<> {
vector<int64> sticker_set_ids_;
void do_run(Promise<Unit> &&promise) override {
sticker_set_ids_ = td->stickers_manager_->get_featured_sticker_sets(std::move(promise));
}
void do_send_result() override {
send_result(td->stickers_manager_->get_sticker_sets_object(narrow_cast<int32>(sticker_set_ids_.size()),
sticker_set_ids_, 5));
}
public:
GetTrendingStickerSetsRequest(ActorShared<Td> td, uint64 request_id) : RequestActor(std::move(td), request_id) {
}
};
class GetAttachedStickerSetsRequest : public RequestActor<> {
FileId file_id_;
vector<int64> sticker_set_ids_;
void do_run(Promise<Unit> &&promise) override {
sticker_set_ids_ = td->stickers_manager_->get_attached_sticker_sets(file_id_, std::move(promise));
}
void do_send_result() override {
send_result(td->stickers_manager_->get_sticker_sets_object(narrow_cast<int32>(sticker_set_ids_.size()),
sticker_set_ids_, 5));
}
public:
GetAttachedStickerSetsRequest(ActorShared<Td> td, uint64 request_id, int32 file_id)
: RequestActor(std::move(td), request_id), file_id_(file_id) {
}
};
class GetStickerSetRequest : public RequestActor<> {
int64 set_id_;
int64 sticker_set_id_;
void do_run(Promise<Unit> &&promise) override {
sticker_set_id_ = td->stickers_manager_->get_sticker_set(set_id_, std::move(promise));
}
void do_send_result() override {
send_result(td->stickers_manager_->get_sticker_set_object(sticker_set_id_));
}
public:
GetStickerSetRequest(ActorShared<Td> td, uint64 request_id, int64 set_id)
: RequestActor(std::move(td), request_id), set_id_(set_id) {
set_tries(3);
}
};
class SearchStickerSetRequest : public RequestActor<> {
string name_;
int64 sticker_set_id_;
void do_run(Promise<Unit> &&promise) override {
sticker_set_id_ = td->stickers_manager_->search_sticker_set(name_, std::move(promise));
}
void do_send_result() override {
send_result(td->stickers_manager_->get_sticker_set_object(sticker_set_id_));
}
public:
SearchStickerSetRequest(ActorShared<Td> td, uint64 request_id, string &&name)
: RequestActor(std::move(td), request_id), name_(std::move(name)) {
set_tries(3);
}
};
class ChangeStickerSetRequest : public RequestOnceActor {
int64 set_id_;
bool is_installed_;
bool is_archived_;
void do_run(Promise<Unit> &&promise) override {
td->stickers_manager_->change_sticker_set(set_id_, is_installed_, is_archived_, std::move(promise));
}
public:
ChangeStickerSetRequest(ActorShared<Td> td, uint64 request_id, int64 set_id, bool is_installed, bool is_archived)
: RequestOnceActor(std::move(td), request_id)
, set_id_(set_id)
, is_installed_(is_installed)
, is_archived_(is_archived) {
set_tries(3);
}
};
class ReorderInstalledStickerSetsRequest : public RequestOnceActor {
bool is_masks_;
vector<int64> sticker_set_ids_;
void do_run(Promise<Unit> &&promise) override {
td->stickers_manager_->reorder_installed_sticker_sets(is_masks_, sticker_set_ids_, std::move(promise));
}
public:
ReorderInstalledStickerSetsRequest(ActorShared<Td> td, uint64 request_id, bool is_masks,
vector<int64> &&sticker_set_ids)
: RequestOnceActor(std::move(td), request_id), is_masks_(is_masks), sticker_set_ids_(std::move(sticker_set_ids)) {
}
};
class UploadStickerFileRequest : public RequestOnceActor {
UserId user_id_;
tl_object_ptr<td_api::InputFile> sticker_;
FileId file_id;
void do_run(Promise<Unit> &&promise) override {
file_id = td->stickers_manager_->upload_sticker_file(user_id_, sticker_, std::move(promise));
}
void do_send_result() override {
send_result(td->file_manager_->get_file_object(file_id));
}
public:
UploadStickerFileRequest(ActorShared<Td> td, uint64 request_id, int32 user_id,
tl_object_ptr<td_api::InputFile> &&sticker)
: RequestOnceActor(std::move(td), request_id), user_id_(user_id), sticker_(std::move(sticker)) {
}
};
class CreateNewStickerSetRequest : public RequestOnceActor {
UserId user_id_;
string title_;
string name_;
bool is_masks_;
vector<tl_object_ptr<td_api::inputSticker>> stickers_;
void do_run(Promise<Unit> &&promise) override {
td->stickers_manager_->create_new_sticker_set(user_id_, title_, name_, is_masks_, std::move(stickers_),
std::move(promise));
}
void do_send_result() override {
auto set_id = td->stickers_manager_->search_sticker_set(name_, Auto());
if (set_id == 0) {
return send_error(Status::Error(500, "Created sticker set not found"));
}
send_result(td->stickers_manager_->get_sticker_set_object(set_id));
}
public:
CreateNewStickerSetRequest(ActorShared<Td> td, uint64 request_id, int32 user_id, string &&title, string &&name,
bool is_masks, vector<tl_object_ptr<td_api::inputSticker>> &&stickers)
: RequestOnceActor(std::move(td), request_id)
, user_id_(user_id)
, title_(std::move(title))
, name_(std::move(name))
, is_masks_(is_masks)
, stickers_(std::move(stickers)) {
}
};
class AddStickerToSetRequest : public RequestOnceActor {
UserId user_id_;
string name_;
tl_object_ptr<td_api::inputSticker> sticker_;
void do_run(Promise<Unit> &&promise) override {
td->stickers_manager_->add_sticker_to_set(user_id_, name_, std::move(sticker_), std::move(promise));
}
void do_send_result() override {
auto set_id = td->stickers_manager_->search_sticker_set(name_, Auto());
if (set_id == 0) {
return send_error(Status::Error(500, "Sticker set not found"));
}
send_result(td->stickers_manager_->get_sticker_set_object(set_id));
}
public:
AddStickerToSetRequest(ActorShared<Td> td, uint64 request_id, int32 user_id, string &&name,
tl_object_ptr<td_api::inputSticker> &&sticker)
: RequestOnceActor(std::move(td), request_id)
, user_id_(user_id)
, name_(std::move(name))
, sticker_(std::move(sticker)) {
}
};
class SetStickerPositionInSetRequest : public RequestOnceActor {
tl_object_ptr<td_api::InputFile> sticker_;
int32 position_;
void do_run(Promise<Unit> &&promise) override {
td->stickers_manager_->set_sticker_position_in_set(sticker_, position_, std::move(promise));
}
public:
SetStickerPositionInSetRequest(ActorShared<Td> td, uint64 request_id, tl_object_ptr<td_api::InputFile> &&sticker,
int32 position)
: RequestOnceActor(std::move(td), request_id), sticker_(std::move(sticker)), position_(position) {
}
};
class RemoveStickerFromSetRequest : public RequestOnceActor {
tl_object_ptr<td_api::InputFile> sticker_;
void do_run(Promise<Unit> &&promise) override {
td->stickers_manager_->remove_sticker_from_set(sticker_, std::move(promise));
}
public:
RemoveStickerFromSetRequest(ActorShared<Td> td, uint64 request_id, tl_object_ptr<td_api::InputFile> &&sticker)
: RequestOnceActor(std::move(td), request_id), sticker_(std::move(sticker)) {
}
};
class GetRecentStickersRequest : public RequestActor<> {
bool is_attached_;
vector<FileId> sticker_ids_;
void do_run(Promise<Unit> &&promise) override {
sticker_ids_ = td->stickers_manager_->get_recent_stickers(is_attached_, std::move(promise));
}
void do_send_result() override {
send_result(td->stickers_manager_->get_stickers_object(sticker_ids_));
}
public:
GetRecentStickersRequest(ActorShared<Td> td, uint64 request_id, bool is_attached)
: RequestActor(std::move(td), request_id), is_attached_(is_attached) {
}
};
class AddRecentStickerRequest : public RequestActor<> {
bool is_attached_;
tl_object_ptr<td_api::InputFile> input_file_;
void do_run(Promise<Unit> &&promise) override {
td->stickers_manager_->add_recent_sticker(is_attached_, input_file_, std::move(promise));
}
public:
AddRecentStickerRequest(ActorShared<Td> td, uint64 request_id, bool is_attached,
tl_object_ptr<td_api::InputFile> &&input_file)
: RequestActor(std::move(td), request_id), is_attached_(is_attached), input_file_(std::move(input_file)) {
set_tries(3);
}
};
class RemoveRecentStickerRequest : public RequestActor<> {
bool is_attached_;
tl_object_ptr<td_api::InputFile> input_file_;
void do_run(Promise<Unit> &&promise) override {
td->stickers_manager_->remove_recent_sticker(is_attached_, input_file_, std::move(promise));
}
public:
RemoveRecentStickerRequest(ActorShared<Td> td, uint64 request_id, bool is_attached,
tl_object_ptr<td_api::InputFile> &&input_file)
: RequestActor(std::move(td), request_id), is_attached_(is_attached), input_file_(std::move(input_file)) {
set_tries(3);
}
};
class ClearRecentStickersRequest : public RequestActor<> {
bool is_attached_;
void do_run(Promise<Unit> &&promise) override {
td->stickers_manager_->clear_recent_stickers(is_attached_, std::move(promise));
}
public:
ClearRecentStickersRequest(ActorShared<Td> td, uint64 request_id, bool is_attached)
: RequestActor(std::move(td), request_id), is_attached_(is_attached) {
set_tries(3);
}
};
class GetFavoriteStickersRequest : public RequestActor<> {
vector<FileId> sticker_ids_;
void do_run(Promise<Unit> &&promise) override {
sticker_ids_ = td->stickers_manager_->get_favorite_stickers(std::move(promise));
}
void do_send_result() override {
send_result(td->stickers_manager_->get_stickers_object(sticker_ids_));
}
public:
GetFavoriteStickersRequest(ActorShared<Td> td, uint64 request_id) : RequestActor(std::move(td), request_id) {
}
};
class AddFavoriteStickerRequest : public RequestOnceActor {
tl_object_ptr<td_api::InputFile> input_file_;
void do_run(Promise<Unit> &&promise) override {
td->stickers_manager_->add_favorite_sticker(input_file_, std::move(promise));
}
public:
AddFavoriteStickerRequest(ActorShared<Td> td, uint64 request_id, tl_object_ptr<td_api::InputFile> &&input_file)
: RequestOnceActor(std::move(td), request_id), input_file_(std::move(input_file)) {
set_tries(3);
}
};
class RemoveFavoriteStickerRequest : public RequestOnceActor {
tl_object_ptr<td_api::InputFile> input_file_;
void do_run(Promise<Unit> &&promise) override {
td->stickers_manager_->remove_favorite_sticker(input_file_, std::move(promise));
}
public:
RemoveFavoriteStickerRequest(ActorShared<Td> td, uint64 request_id, tl_object_ptr<td_api::InputFile> &&input_file)
: RequestOnceActor(std::move(td), request_id), input_file_(std::move(input_file)) {
set_tries(3);
}
};
class GetStickerEmojisRequest : public RequestActor<> {
tl_object_ptr<td_api::InputFile> input_file_;
vector<string> emojis_;
void do_run(Promise<Unit> &&promise) override {
emojis_ = td->stickers_manager_->get_sticker_emojis(input_file_, std::move(promise));
}
void do_send_result() override {
send_result(make_tl_object<td_api::stickerEmojis>(std::move(emojis_)));
}
public:
GetStickerEmojisRequest(ActorShared<Td> td, uint64 request_id, tl_object_ptr<td_api::InputFile> &&input_file)
: RequestActor(std::move(td), request_id), input_file_(std::move(input_file)) {
set_tries(3);
}
};
class GetSavedAnimationsRequest : public RequestActor<> {
vector<FileId> animation_ids_;
void do_run(Promise<Unit> &&promise) override {
animation_ids_ = td->animations_manager_->get_saved_animations(std::move(promise));
}
void do_send_result() override {
send_result(make_tl_object<td_api::animations>(transform(std::move(animation_ids_), [td = td](FileId animation_id) {
return td->animations_manager_->get_animation_object(animation_id, "GetSavedAnimationsRequest");
})));
}
public:
GetSavedAnimationsRequest(ActorShared<Td> td, uint64 request_id) : RequestActor(std::move(td), request_id) {
}
};
class AddSavedAnimationRequest : public RequestOnceActor {
tl_object_ptr<td_api::InputFile> input_file_;
void do_run(Promise<Unit> &&promise) override {
td->animations_manager_->add_saved_animation(input_file_, std::move(promise));
}
public:
AddSavedAnimationRequest(ActorShared<Td> td, uint64 request_id, tl_object_ptr<td_api::InputFile> &&input_file)
: RequestOnceActor(std::move(td), request_id), input_file_(std::move(input_file)) {
set_tries(3);
}
};
class RemoveSavedAnimationRequest : public RequestOnceActor {
tl_object_ptr<td_api::InputFile> input_file_;
void do_run(Promise<Unit> &&promise) override {
td->animations_manager_->remove_saved_animation(input_file_, std::move(promise));
}
public:
RemoveSavedAnimationRequest(ActorShared<Td> td, uint64 request_id, tl_object_ptr<td_api::InputFile> &&input_file)
: RequestOnceActor(std::move(td), request_id), input_file_(std::move(input_file)) {
set_tries(3);
}
};
class GetInlineQueryResultsRequest : public RequestOnceActor {
UserId bot_user_id_;
DialogId dialog_id_;
Location user_location_;
string query_;
string offset_;
uint64 query_hash_;
void do_run(Promise<Unit> &&promise) override {
query_hash_ = td->inline_queries_manager_->send_inline_query(bot_user_id_, dialog_id_, user_location_, query_,
offset_, std::move(promise));
}
void do_send_result() override {
send_result(td->inline_queries_manager_->get_inline_query_results_object(query_hash_));
}
public:
GetInlineQueryResultsRequest(ActorShared<Td> td, uint64 request_id, int32 bot_user_id, int64 dialog_id,
const tl_object_ptr<td_api::location> &user_location, string query, string offset)
: RequestOnceActor(std::move(td), request_id)
, bot_user_id_(bot_user_id)
, dialog_id_(dialog_id)
, user_location_(user_location)
, query_(std::move(query))
, offset_(std::move(offset))
, query_hash_(0) {
}
};
class AnswerInlineQueryRequest : public RequestOnceActor {
int64 inline_query_id_;
bool is_personal_;
vector<tl_object_ptr<td_api::InputInlineQueryResult>> results_;
int32 cache_time_;
string next_offset_;
string switch_pm_text_;
string switch_pm_parameter_;
void do_run(Promise<Unit> &&promise) override {
td->inline_queries_manager_->answer_inline_query(inline_query_id_, is_personal_, std::move(results_), cache_time_,
next_offset_, switch_pm_text_, switch_pm_parameter_,
std::move(promise));
}
public:
AnswerInlineQueryRequest(ActorShared<Td> td, uint64 request_id, int64 inline_query_id, bool is_personal,
vector<tl_object_ptr<td_api::InputInlineQueryResult>> &&results, int32 cache_time,
string next_offset, string switch_pm_text, string switch_pm_parameter)
: RequestOnceActor(std::move(td), request_id)
, inline_query_id_(inline_query_id)
, is_personal_(is_personal)
, results_(std::move(results))
, cache_time_(cache_time)
, next_offset_(std::move(next_offset))
, switch_pm_text_(std::move(switch_pm_text))
, switch_pm_parameter_(std::move(switch_pm_parameter)) {
}
};
class GetCallbackQueryAnswerRequest : public RequestOnceActor {
FullMessageId full_message_id_;
tl_object_ptr<td_api::CallbackQueryPayload> payload_;
int64 result_id_;
void do_run(Promise<Unit> &&promise) override {
result_id_ = td->callback_queries_manager_->send_callback_query(full_message_id_, payload_, std::move(promise));
}
void do_send_result() override {
send_result(td->callback_queries_manager_->get_callback_query_answer_object(result_id_));
}
void do_send_error(Status &&status) override {
if (status.code() == 502 && td->messages_manager_->is_message_edited_recently(full_message_id_, 31)) {
return send_result(make_tl_object<td_api::callbackQueryAnswer>());
}
send_error(std::move(status));
}
public:
GetCallbackQueryAnswerRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, int64 message_id,
tl_object_ptr<td_api::CallbackQueryPayload> payload)
: RequestOnceActor(std::move(td), request_id)
, full_message_id_(DialogId(dialog_id), MessageId(message_id))
, payload_(std::move(payload))
, result_id_(0) {
}
};
class AnswerCallbackQueryRequest : public RequestOnceActor {
int64 callback_query_id_;
string text_;
bool show_alert_;
string url_;
int32 cache_time_;
void do_run(Promise<Unit> &&promise) override {
td->callback_queries_manager_->answer_callback_query(callback_query_id_, text_, show_alert_, url_, cache_time_,
std::move(promise));
}
public:
AnswerCallbackQueryRequest(ActorShared<Td> td, uint64 request_id, int64 callback_query_id, string text,
bool show_alert, string url, int32 cache_time)
: RequestOnceActor(std::move(td), request_id)
, callback_query_id_(callback_query_id)
, text_(std::move(text))
, show_alert_(show_alert)
, url_(std::move(url))
, cache_time_(cache_time) {
}
};
class AnswerShippingQueryRequest : public RequestOnceActor {
int64 shipping_query_id_;
vector<tl_object_ptr<td_api::shippingOption>> shipping_options_;
string error_message_;
void do_run(Promise<Unit> &&promise) override {
answer_shipping_query(shipping_query_id_, std::move(shipping_options_), error_message_, std::move(promise));
}
public:
AnswerShippingQueryRequest(ActorShared<Td> td, uint64 request_id, int64 shipping_query_id,
vector<tl_object_ptr<td_api::shippingOption>> shipping_options, string error_message)
: RequestOnceActor(std::move(td), request_id)
, shipping_query_id_(shipping_query_id)
, shipping_options_(std::move(shipping_options))
, error_message_(std::move(error_message)) {
}
};
class AnswerPreCheckoutQueryRequest : public RequestOnceActor {
int64 pre_checkout_query_id_;
string error_message_;
void do_run(Promise<Unit> &&promise) override {
answer_pre_checkout_query(pre_checkout_query_id_, error_message_, std::move(promise));
}
public:
AnswerPreCheckoutQueryRequest(ActorShared<Td> td, uint64 request_id, int64 pre_checkout_query_id,
string error_message)
: RequestOnceActor(std::move(td), request_id)
, pre_checkout_query_id_(pre_checkout_query_id)
, error_message_(std::move(error_message)) {
}
};
class GetPaymentFormRequest : public RequestActor<tl_object_ptr<td_api::paymentForm>> {
FullMessageId full_message_id_;
tl_object_ptr<td_api::paymentForm> payment_form_;
void do_run(Promise<tl_object_ptr<td_api::paymentForm>> &&promise) override {
if (get_tries() < 2) {
promise.set_value(std::move(payment_form_));
return;
}
td->messages_manager_->get_payment_form(full_message_id_, std::move(promise));
}
void do_set_result(tl_object_ptr<td_api::paymentForm> &&result) override {
payment_form_ = std::move(result);
}
void do_send_result() override {
CHECK(payment_form_ != nullptr);
send_result(std::move(payment_form_));
}
public:
GetPaymentFormRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, int64 message_id)
: RequestActor(std::move(td), request_id), full_message_id_(DialogId(dialog_id), MessageId(message_id)) {
}
};
class ValidateOrderInfoRequest : public RequestActor<tl_object_ptr<td_api::validatedOrderInfo>> {
FullMessageId full_message_id_;
tl_object_ptr<td_api::orderInfo> order_info_;
bool allow_save_;
tl_object_ptr<td_api::validatedOrderInfo> validated_order_info_;
void do_run(Promise<tl_object_ptr<td_api::validatedOrderInfo>> &&promise) override {
if (get_tries() < 2) {
promise.set_value(std::move(validated_order_info_));
return;
}
td->messages_manager_->validate_order_info(full_message_id_, std::move(order_info_), allow_save_,
std::move(promise));
}
void do_set_result(tl_object_ptr<td_api::validatedOrderInfo> &&result) override {
validated_order_info_ = std::move(result);
}
void do_send_result() override {
CHECK(validated_order_info_ != nullptr);
send_result(std::move(validated_order_info_));
}
public:
ValidateOrderInfoRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, int64 message_id,
tl_object_ptr<td_api::orderInfo> order_info, bool allow_save)
: RequestActor(std::move(td), request_id)
, full_message_id_(DialogId(dialog_id), MessageId(message_id))
, order_info_(std::move(order_info))
, allow_save_(allow_save) {
}
};
class SendPaymentFormRequest : public RequestActor<tl_object_ptr<td_api::paymentResult>> {
FullMessageId full_message_id_;
string order_info_id_;
string shipping_option_id_;
tl_object_ptr<td_api::InputCredentials> credentials_;
tl_object_ptr<td_api::paymentResult> payment_result_;
void do_run(Promise<tl_object_ptr<td_api::paymentResult>> &&promise) override {
if (get_tries() < 2) {
promise.set_value(std::move(payment_result_));
return;
}
td->messages_manager_->send_payment_form(full_message_id_, order_info_id_, shipping_option_id_, credentials_,
std::move(promise));
}
void do_set_result(tl_object_ptr<td_api::paymentResult> &&result) override {
payment_result_ = std::move(result);
}
void do_send_result() override {
CHECK(payment_result_ != nullptr);
send_result(std::move(payment_result_));
}
public:
SendPaymentFormRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, int64 message_id, string order_info_id,
string shipping_option_id, tl_object_ptr<td_api::InputCredentials> credentials)
: RequestActor(std::move(td), request_id)
, full_message_id_(DialogId(dialog_id), MessageId(message_id))
, order_info_id_(std::move(order_info_id))
, shipping_option_id_(std::move(shipping_option_id))
, credentials_(std::move(credentials)) {
}
};
class GetPaymentReceiptRequest : public RequestActor<tl_object_ptr<td_api::paymentReceipt>> {
FullMessageId full_message_id_;
tl_object_ptr<td_api::paymentReceipt> payment_receipt_;
void do_run(Promise<tl_object_ptr<td_api::paymentReceipt>> &&promise) override {
if (get_tries() < 2) {
promise.set_value(std::move(payment_receipt_));
return;
}
td->messages_manager_->get_payment_receipt(full_message_id_, std::move(promise));
}
void do_set_result(tl_object_ptr<td_api::paymentReceipt> &&result) override {
payment_receipt_ = std::move(result);
}
void do_send_result() override {
CHECK(payment_receipt_ != nullptr);
send_result(std::move(payment_receipt_));
}
public:
GetPaymentReceiptRequest(ActorShared<Td> td, uint64 request_id, int64 dialog_id, int64 message_id)
: RequestActor(std::move(td), request_id), full_message_id_(DialogId(dialog_id), MessageId(message_id)) {
}
};
class GetSavedOrderInfoRequest : public RequestActor<tl_object_ptr<td_api::orderInfo>> {
tl_object_ptr<td_api::orderInfo> order_info_;
void do_run(Promise<tl_object_ptr<td_api::orderInfo>> &&promise) override {
if (get_tries() < 2) {
promise.set_value(std::move(order_info_));
return;
}
get_saved_order_info(std::move(promise));
}
void do_set_result(tl_object_ptr<td_api::orderInfo> &&result) override {
order_info_ = std::move(result);
}
void do_send_result() override {
send_result(std::move(order_info_));
}
public:
GetSavedOrderInfoRequest(ActorShared<Td> td, uint64 request_id) : RequestActor(std::move(td), request_id) {
}
};
class DeleteSavedOrderInfoRequest : public RequestOnceActor {
void do_run(Promise<Unit> &&promise) override {
delete_saved_order_info(std::move(promise));
}
public:
DeleteSavedOrderInfoRequest(ActorShared<Td> td, uint64 request_id) : RequestOnceActor(std::move(td), request_id) {
}
};
class DeleteSavedCredentialsRequest : public RequestOnceActor {
void do_run(Promise<Unit> &&promise) override {
delete_saved_credentials(std::move(promise));
}
public:
DeleteSavedCredentialsRequest(ActorShared<Td> td, uint64 request_id) : RequestOnceActor(std::move(td), request_id) {
}
};
class GetSupportUserRequest : public RequestActor<> {
UserId user_id_;
void do_run(Promise<Unit> &&promise) override {
user_id_ = td->contacts_manager_->get_support_user(std::move(promise));
}
void do_send_result() override {
send_result(td->contacts_manager_->get_user_object(user_id_));
}
public:
GetSupportUserRequest(ActorShared<Td> td, uint64 request_id) : RequestActor(std::move(td), request_id) {
}
};
class GetWallpapersRequest : public RequestActor<tl_object_ptr<td_api::wallpapers>> {
tl_object_ptr<td_api::wallpapers> wallpapers_;
void do_run(Promise<tl_object_ptr<td_api::wallpapers>> &&promise) override {
if (get_tries() < 2) {
promise.set_value(std::move(wallpapers_));
return;
}
td->create_handler<GetWallpapersQuery>(std::move(promise))->send();
}
void do_set_result(tl_object_ptr<td_api::wallpapers> &&result) override {
wallpapers_ = std::move(result);
}
void do_send_result() override {
CHECK(wallpapers_ != nullptr);
send_result(std::move(wallpapers_));
}
public:
GetWallpapersRequest(ActorShared<Td> td, uint64 request_id) : RequestActor(std::move(td), request_id) {
}
};
class GetRecentlyVisitedTMeUrlsRequest : public RequestActor<tl_object_ptr<td_api::tMeUrls>> {
string referrer_;
tl_object_ptr<td_api::tMeUrls> urls_;
void do_run(Promise<tl_object_ptr<td_api::tMeUrls>> &&promise) override {
if (get_tries() < 2) {
promise.set_value(std::move(urls_));
return;
}
td->create_handler<GetRecentMeUrlsQuery>(std::move(promise))->send(referrer_);
}
void do_set_result(tl_object_ptr<td_api::tMeUrls> &&result) override {
urls_ = std::move(result);
}
void do_send_result() override {
CHECK(urls_ != nullptr);
send_result(std::move(urls_));
}
public:
GetRecentlyVisitedTMeUrlsRequest(ActorShared<Td> td, uint64 request_id, string referrer)
: RequestActor(std::move(td), request_id), referrer_(std::move(referrer)) {
}
};
class SendCustomRequestRequest : public RequestActor<string> {
string method_;
string parameters_;
string request_result_;
void do_run(Promise<string> &&promise) override {
if (get_tries() < 2) {
promise.set_value(std::move(request_result_));
return;
}
td->create_handler<SendCustomRequestQuery>(std::move(promise))->send(method_, parameters_);
}
void do_set_result(string &&result) override {
request_result_ = std::move(result);
}
void do_send_result() override {
send_result(make_tl_object<td_api::customRequestResult>(request_result_));
}
public:
SendCustomRequestRequest(ActorShared<Td> td, uint64 request_id, string &&method, string &¶meters)
: RequestActor(std::move(td), request_id), method_(method), parameters_(parameters) {
}
};
class AnswerCustomQueryRequest : public RequestOnceActor {
int64 custom_query_id_;
string data_;
void do_run(Promise<Unit> &&promise) override {
td->create_handler<AnswerCustomQueryQuery>(std::move(promise))->send(custom_query_id_, data_);
}
public:
AnswerCustomQueryRequest(ActorShared<Td> td, uint64 request_id, int64 custom_query_id, string data)
: RequestOnceActor(std::move(td), request_id), custom_query_id_(custom_query_id), data_(std::move(data)) {
}
};
class GetInviteTextRequest : public RequestActor<string> {
string text_;
void do_run(Promise<string> &&promise) override {
if (get_tries() < 2) {
promise.set_value(std::move(text_));
return;
}
td->create_handler<GetInviteTextQuery>(std::move(promise))->send();
}
void do_set_result(string &&result) override {
text_ = std::move(result);
}
void do_send_result() override {
send_result(make_tl_object<td_api::text>(text_));
}
public:
GetInviteTextRequest(ActorShared<Td> td, uint64 request_id) : RequestActor(std::move(td), request_id) {
}
};
class GetTermsOfServiceRequest : public RequestActor<string> {
string text_;
void do_run(Promise<string> &&promise) override {
if (get_tries() < 2) {
promise.set_value(std::move(text_));
return;
}
td->create_handler<GetTermsOfServiceQuery>(std::move(promise))->send();
}
void do_set_result(string &&result) override {
text_ = std::move(result);
}
void do_send_result() override {
send_result(make_tl_object<td_api::text>(text_));
}
public:
GetTermsOfServiceRequest(ActorShared<Td> td, uint64 request_id) : RequestActor(std::move(td), request_id) {
}
};
/** Td **/
Td::Td(std::unique_ptr<TdCallback> callback) : callback_(std::move(callback)) {
}
void Td::on_alarm_timeout_callback(void *td_ptr, int64 request_id) {
auto td = static_cast<Td *>(td_ptr);
auto td_id = td->actor_id(td);
send_closure(td_id, &Td::on_alarm_timeout, request_id);
}
void Td::on_alarm_timeout(int64 request_id) {
if (request_id == 0) {
on_online_updated(false, true);
return;
}
send_result(static_cast<uint64>(request_id), make_tl_object<td_api::ok>());
}
void Td::on_online_updated(bool force, bool send_update) {
if (auth_manager_->is_bot()) {
return;
}
if (!auth_manager_->is_authorized()) {
return;
}
if (force || is_online_) {
contacts_manager_->set_my_online_status(is_online_, send_update);
create_handler<UpdateStatusQuery>()->send(!is_online_);
}
if (is_online_) {
alarm_timeout_.set_timeout_in(0, ONLINE_TIMEOUT);
} else {
alarm_timeout_.cancel_timeout(0);
}
}
void Td::request(uint64 id, tl_object_ptr<td_api::Function> function) {
request_set_.insert(id);
if (id == 0) {
LOG(ERROR) << "Receive request with id == 0";
return send_error_raw(id, 400, "Wrong request id == 0");
}
if (function == nullptr) {
LOG(ERROR) << "Receive empty request";
return send_error_raw(id, 400, "Request is empty");
}
switch (state_) {
case State::WaitParameters: {
switch (function->get_id()) {
case td_api::getAuthorizationState::ID:
return send_result(id, td_api::make_object<td_api::authorizationStateWaitTdlibParameters>());
case td_api::setTdlibParameters::ID:
return answer_ok_query(
id, set_td_parameters(std::move(move_tl_object_as<td_api::setTdlibParameters>(function)->parameters_)));
default:
return send_error_raw(id, 401, "Initialization parameters are needed");
}
break;
}
case State::Decrypt: {
string encryption_key;
switch (function->get_id()) {
case td_api::getAuthorizationState::ID:
return send_result(
id, td_api::make_object<td_api::authorizationStateWaitEncryptionKey>(encryption_info_.is_encrypted));
case td_api::checkDatabaseEncryptionKey::ID: {
auto check_key = move_tl_object_as<td_api::checkDatabaseEncryptionKey>(function);
encryption_key = std::move(check_key->encryption_key_);
break;
}
case td_api::setDatabaseEncryptionKey::ID: {
auto set_key = move_tl_object_as<td_api::setDatabaseEncryptionKey>(function);
encryption_key = std::move(set_key->new_encryption_key_);
break;
}
case td_api::close::ID:
return close();
case td_api::destroy::ID:
return destroy();
default:
return send_error_raw(id, 401, "Database encryption key is needed");
}
return answer_ok_query(id, init(as_db_key(encryption_key)));
}
case State::Close: {
if (function->get_id() == td_api::getAuthorizationState::ID) {
if (close_flag_ == 5) {
return send_result(id, td_api::make_object<td_api::authorizationStateClosed>());
} else {
return send_result(id, td_api::make_object<td_api::authorizationStateClosing>());
}
}
return send_error_raw(id, 401, "Unauthorized");
}
case State::Run:
break;
}
VLOG(td_requests) << "Receive request " << id << ": " << to_string(function);
downcast_call(*function, [this, id](auto &request) { this->on_request(id, request); });
}
td_api::object_ptr<td_api::Object> Td::static_request(td_api::object_ptr<td_api::Function> function) {
VLOG(td_requests) << "Receive static request: " << to_string(function);
td_api::object_ptr<td_api::Object> response;
downcast_call(*function, [&response](auto &request) { response = Td::do_static_request(request); });
VLOG(td_requests) << "Sending result for static request: " << to_string(response);
return response;
}
void Td::add_handler(uint64 id, std::shared_ptr<ResultHandler> handler) {
result_handlers_.emplace_back(id, handler);
}
std::shared_ptr<Td::ResultHandler> Td::extract_handler(uint64 id) {
std::shared_ptr<Td::ResultHandler> result;
for (size_t i = 0; i < result_handlers_.size(); i++) {
if (result_handlers_[i].first == id) {
result = std::move(result_handlers_[i].second);
result_handlers_.erase(result_handlers_.begin() + i);
break;
}
}
return result;
}
void Td::invalidate_handler(ResultHandler *handler) {
for (size_t i = 0; i < result_handlers_.size(); i++) {
if (result_handlers_[i].second.get() == handler) {
result_handlers_.erase(result_handlers_.begin() + i);
i--;
}
}
}
void Td::send(NetQueryPtr &&query) {
VLOG(net_query) << "Send " << query << " to dispatcher";
query->debug("Td: send to NetQueryDispatcher");
query->set_callback(actor_shared(this, 1));
G()->net_query_dispatcher().dispatch(std::move(query));
}
void Td::update_qts(int32 qts) {
if (close_flag_ > 1) {
return;
}
updates_manager_->set_qts(qts);
}
void Td::force_get_difference() {
if (close_flag_) {
return;
}
updates_manager_->get_difference("force_get_difference");
}
void Td::on_result(NetQueryPtr query) {
query->debug("Td: received from DcManager");
VLOG(net_query) << "on_result " << query;
if (close_flag_ > 1) {
return;
}
if (query->id() == 0) {
if (query->is_error()) {
query->clear();
updates_manager_->schedule_get_difference("error in update");
LOG(ERROR) << "Error in update";
return;
}
auto ok = query->move_as_ok();
TlBufferParser parser(&ok);
auto ptr = telegram_api::Updates::fetch(parser);
if (parser.get_error()) {
LOG(ERROR) << "Failed to fetch update: " << parser.get_error() << format::as_hex_dump<4>(ok.as_slice());
updates_manager_->schedule_get_difference("failed to fetch update");
} else {
updates_manager_->on_get_updates(std::move(ptr));
}
return;
}
auto handler = extract_handler(query->id());
if (handler == nullptr) {
query->clear();
LOG_IF(WARNING, !query->is_ok() || query->ok_tl_constructor() != telegram_api::upload_file::ID)
<< tag("NetQuery", query) << " is ignored: no handlers found";
return;
}
handler->on_result(std::move(query));
}
void Td::on_config_option_updated(const string &name) {
if (close_flag_) {
return;
}
if (name == "auth") {
on_authorization_lost();
return;
} else if (name == "saved_animations_limit") {
return animations_manager_->on_update_saved_animations_limit(G()->shared_config().get_option_integer(name));
} else if (name == "favorite_stickers_limit") {
stickers_manager_->on_update_favorite_stickers_limit(G()->shared_config().get_option_integer(name));
} else if (name == "my_id") {
G()->set_my_id(G()->shared_config().get_option_integer(name));
} else if (name == "session_count") {
G()->net_query_dispatcher().update_session_count();
} else if (name == "use_pfs") {
G()->net_query_dispatcher().update_use_pfs();
} else if (name == "use_storage_optimizer") {
send_closure(storage_manager_, &StorageManager::update_use_storage_optimizer);
} else if (name == "rating_e_decay") {
return send_closure(top_dialog_manager_, &TopDialogManager::update_rating_e_decay);
} else if (name == "call_ring_timeout_ms" || name == "call_receive_timeout_ms" ||
name == "channels_read_media_period") {
return;
}
send_update(make_tl_object<td_api::updateOption>(name, G()->shared_config().get_option_value(name)));
}
tl_object_ptr<td_api::ConnectionState> Td::get_connection_state_object(StateManager::State state) {
switch (state) {
case StateManager::State::Empty:
UNREACHABLE();
return nullptr;
case StateManager::State::WaitingForNetwork:
return make_tl_object<td_api::connectionStateWaitingForNetwork>();
case StateManager::State::ConnectingToProxy:
return make_tl_object<td_api::connectionStateConnectingToProxy>();
case StateManager::State::Connecting:
return make_tl_object<td_api::connectionStateConnecting>();
case StateManager::State::Updating:
return make_tl_object<td_api::connectionStateUpdating>();
case StateManager::State::Ready:
return make_tl_object<td_api::connectionStateReady>();
default:
UNREACHABLE();
return nullptr;
}
}
void Td::on_connection_state_changed(StateManager::State new_state) {
if (new_state == connection_state_) {
LOG(ERROR) << "State manager sends update about unchanged state " << static_cast<int32>(new_state);
return;
}
connection_state_ = new_state;
send_update(make_tl_object<td_api::updateConnectionState>(get_connection_state_object(connection_state_)));
}
void Td::on_authorization_lost() {
LOG(WARNING) << "on_authorization_lost";
destroy();
}
void Td::start_up() {
uint64 check_endianness = 0x0706050403020100;
auto check_endianness_raw = reinterpret_cast<const unsigned char *>(&check_endianness);
for (unsigned char c = 0; c < 8; c++) {
auto symbol = check_endianness_raw[static_cast<size_t>(c)];
LOG_IF(FATAL, symbol != c) << "TDLib requires little-endian platform";
}
CHECK(state_ == State::WaitParameters);
send_update(td_api::make_object<td_api::updateAuthorizationState>(
td_api::make_object<td_api::authorizationStateWaitTdlibParameters>()));
}
void Td::tear_down() {
CHECK(close_flag_ == 5);
}
void Td::hangup_shared() {
auto token = get_link_token();
auto type = Container<int>::type_from_id(token);
if (type == RequestActorIdType) {
request_actors_.erase(get_link_token());
dec_request_actor_refcnt();
} else if (type == ActorIdType) {
dec_actor_refcnt();
} else {
LOG(FATAL, "Unknown hangup_shared ") << tag("type", type);
}
}
void Td::hangup() {
close();
dec_stop_cnt();
}
ActorShared<Td> Td::create_reference() {
inc_actor_refcnt();
return actor_shared(this, ActorIdType);
}
void Td::inc_actor_refcnt() {
actor_refcnt_++;
}
void Td::dec_actor_refcnt() {
actor_refcnt_--;
if (actor_refcnt_ == 0) {
if (close_flag_ == 2) {
create_reference();
close_flag_ = 3;
} else if (close_flag_ == 3) {
LOG(WARNING) << "ON_ACTORS_CLOSED";
Timer timer;
animations_manager_.reset();
LOG(DEBUG) << "AnimationsManager was cleared " << timer;
audios_manager_.reset();
LOG(DEBUG) << "AudiosManager was cleared " << timer;
auth_manager_.reset();
LOG(DEBUG) << "AuthManager was cleared " << timer;
change_phone_number_manager_.reset();
LOG(DEBUG) << "ChangePhoneNumberManager was cleared " << timer;
contacts_manager_.reset();
LOG(DEBUG) << "ContactsManager was cleared " << timer;
documents_manager_.reset();
LOG(DEBUG) << "DocumentsManager was cleared " << timer;
file_manager_.reset();
LOG(DEBUG) << "FileManager was cleared " << timer;
inline_queries_manager_.reset();
LOG(DEBUG) << "InlineQueriesManager was cleared " << timer;
messages_manager_.reset();
LOG(DEBUG) << "MessagesManager was cleared " << timer;
stickers_manager_.reset();
LOG(DEBUG) << "StickersManager was cleared " << timer;
updates_manager_.reset();
LOG(DEBUG) << "UpdatesManager was cleared " << timer;
video_notes_manager_.reset();
LOG(DEBUG) << "VideoNotesManager was cleared " << timer;
videos_manager_.reset();
LOG(DEBUG) << "VideosManager was cleared " << timer;
voice_notes_manager_.reset();
LOG(DEBUG) << "VoiceNotesManager was cleared " << timer;
web_pages_manager_.reset();
LOG(DEBUG) << "WebPagesManager was cleared " << timer;
Promise<> promise = PromiseCreator::lambda([actor_id = create_reference()](Unit) mutable { actor_id.reset(); });
if (destroy_flag_) {
G()->close_and_destroy_all(std::move(promise));
} else {
G()->close_all(std::move(promise));
}
// NetQueryDispatcher will be closed automatically
close_flag_ = 4;
} else if (close_flag_ == 4) {
LOG(WARNING) << "ON_CLOSED";
close_flag_ = 5;
send_update(td_api::make_object<td_api::updateAuthorizationState>(
td_api::make_object<td_api::authorizationStateClosed>()));
callback_->on_closed();
dec_stop_cnt();
} else {
UNREACHABLE();
}
}
}
void Td::dec_stop_cnt() {
stop_cnt_--;
if (stop_cnt_ == 0) {
stop();
}
}
void Td::inc_request_actor_refcnt() {
request_actor_refcnt_++;
}
void Td::dec_request_actor_refcnt() {
request_actor_refcnt_--;
if (request_actor_refcnt_ == 0) {
LOG(WARNING) << "no request actors";
clear();
dec_actor_refcnt(); // remove guard
}
}
void Td::clear_handlers() {
result_handlers_.clear();
}
void Td::clear() {
if (close_flag_ >= 2) {
return;
}
close_flag_ = 2;
Timer timer;
if (destroy_flag_) {
for (auto &option : G()->shared_config().get_options()) {
if (option.first == "rating_e_decay" || option.first == "saved_animations_limit" ||
option.first == "call_receive_timeout_ms" || option.first == "call_ring_timeout_ms" ||
option.first == "channels_read_media_period" || option.first == "auth") {
continue;
}
send_update(make_tl_object<td_api::updateOption>(option.first, make_tl_object<td_api::optionValueEmpty>()));
}
}
LOG(DEBUG) << "Options was cleared " << timer;
G()->net_query_creator().stop_check();
clear_handlers();
LOG(DEBUG) << "Handlers was cleared " << timer;
G()->net_query_dispatcher().stop();
LOG(DEBUG) << "NetQueryDispatcher was stopped " << timer;
state_manager_.reset();
LOG(DEBUG) << "StateManager was cleared " << timer;
while (!request_set_.empty()) {
uint64 id = *request_set_.begin();
if (destroy_flag_) {
send_error_raw(id, 401, "Unauthorized");
} else {
send_error_raw(id, 500, "Internal Server Error: closing");
}
alarm_timeout_.cancel_timeout(static_cast<int64>(id));
}
if (is_online_) {
is_online_ = false;
alarm_timeout_.cancel_timeout(0);
}
LOG(DEBUG) << "Requests was answered " << timer;
// close all pure actors
call_manager_.reset();
LOG(DEBUG) << "CallManager was cleared " << timer;
config_manager_.reset();
LOG(DEBUG) << "ConfigManager was cleared " << timer;
device_token_manager_.reset();
LOG(DEBUG) << "DeviceTokenManager was cleared " << timer;
hashtag_hints_.reset();
LOG(DEBUG) << "HashtagHints was cleared " << timer;
net_stats_manager_.reset();
LOG(DEBUG) << "NetStatsManager was cleared " << timer;
password_manager_.reset();
LOG(DEBUG) << "PasswordManager was cleared " << timer;
privacy_manager_.reset();
LOG(DEBUG) << "PrivacyManager was cleared " << timer;
secret_chats_manager_.reset();
LOG(DEBUG) << "SecretChatsManager was cleared " << timer;
storage_manager_.reset();
LOG(DEBUG) << "StorageManager was cleared " << timer;
top_dialog_manager_.reset();
LOG(DEBUG) << "TopDialogManager was cleared " << timer;
G()->set_connection_creator(ActorOwn<ConnectionCreator>());
LOG(DEBUG) << "ConnectionCreator was cleared " << timer;
// clear actors which are unique pointers
animations_manager_actor_.reset();
LOG(DEBUG) << "AnimationsManager actor was cleared " << timer;
auth_manager_actor_.reset();
LOG(DEBUG) << "AuthManager actor was cleared " << timer;
change_phone_number_manager_actor_.reset();
LOG(DEBUG) << "ChangePhoneNumberManager actor was cleared " << timer;
contacts_manager_actor_.reset();
LOG(DEBUG) << "ContactsManager actor was cleared " << timer;
file_manager_actor_.reset();
LOG(DEBUG) << "FileManager actor was cleared " << timer;
inline_queries_manager_actor_.reset();
LOG(DEBUG) << "InlineQueriesManager actor was cleared " << timer;
messages_manager_actor_.reset(); // TODO: Stop silent
LOG(DEBUG) << "MessagesManager actor was cleared " << timer;
stickers_manager_actor_.reset();
LOG(DEBUG) << "StickersManager actor was cleared " << timer;
updates_manager_actor_.reset();
LOG(DEBUG) << "UpdatesManager actor was cleared " << timer;
web_pages_manager_actor_.reset();
LOG(DEBUG) << "WebPagesManager actor was cleared " << timer;
}
void Td::close() {
close_impl(false);
}
void Td::destroy() {
close_impl(true);
}
void Td::close_impl(bool destroy_flag) {
destroy_flag_ |= destroy_flag;
if (close_flag_) {
return;
}
if (state_ == State::Decrypt) {
if (destroy_flag) {
TdDb::destroy(parameters_);
}
state_ = State::Close;
close_flag_ = 4;
return dec_actor_refcnt();
}
state_ = State::Close;
close_flag_ = 1;
G()->set_close_flag();
send_closure(auth_manager_actor_, &AuthManager::on_closing);
close_flag_ = 1;
LOG(WARNING) << "Close " << tag("destroy", destroy_flag);
// wait till all request_actors will stop.
request_actors_.clear();
G()->td_db()->flush_all();
send_closure_later(actor_id(this), &Td::dec_request_actor_refcnt); // remove guard
}
class Td::DownloadFileCallback : public FileManager::DownloadCallback {
public:
void on_progress(FileId file_id) override {
}
void on_download_ok(FileId file_id) override {
}
void on_download_error(FileId file_id, Status error) override {
}
};
class Td::UploadFileCallback : public FileManager::UploadCallback {
public:
void on_progress(FileId file_id) override {
}
void on_upload_ok(FileId file_id, tl_object_ptr<telegram_api::InputFile> input_file) override {
// cancel file upload of the file to allow next upload with the same file to succeed
send_closure(G()->file_manager(), &FileManager::upload, file_id, nullptr, 0, 0);
}
void on_upload_encrypted_ok(FileId file_id, tl_object_ptr<telegram_api::InputEncryptedFile> input_file) override {
// cancel file upload of the file to allow next upload with the same file to succeed
send_closure(G()->file_manager(), &FileManager::upload, file_id, nullptr, 0, 0);
}
void on_upload_error(FileId file_id, Status error) override {
}
};
Status Td::init(DbKey key) {
auto current_scheduler_id = Scheduler::instance()->sched_id();
auto scheduler_count = Scheduler::instance()->sched_count();
TdDb::Events events;
TRY_RESULT(td_db,
TdDb::open(std::min(current_scheduler_id + 1, scheduler_count - 1), parameters_, std::move(key), events));
LOG(INFO) << "Successfully inited database in " << tag("database_directory", parameters_.database_directory)
<< " and " << tag("files_directory", parameters_.files_directory);
G()->init(parameters_, actor_id(this), std::move(td_db)).ensure();
// Init all managers and actors
class StateManagerCallback : public StateManager::Callback {
public:
explicit StateManagerCallback(ActorShared<Td> td) : td_(std::move(td)) {
}
bool on_state(StateManager::State state) override {
send_closure(td_, &Td::on_connection_state_changed, state);
return td_.is_alive();
}
private:
ActorShared<Td> td_;
};
state_manager_ = create_actor<StateManager>("State manager");
send_closure(state_manager_, &StateManager::add_callback, make_unique<StateManagerCallback>(create_reference()));
G()->set_state_manager(state_manager_.get());
connection_state_ = StateManager::State::Empty;
{
auto connection_creator = create_actor<ConnectionCreator>("ConnectionCreator", create_reference());
auto net_stats_manager = create_actor<NetStatsManager>("NetStatsManager", create_reference());
// How else could I let two actor know about each other, without quite complex async logic?
auto net_stats_manager_ptr = net_stats_manager->get_actor_unsafe();
net_stats_manager_ptr->init();
connection_creator->get_actor_unsafe()->set_net_stats_callback(net_stats_manager_ptr->get_common_stats_callback(),
net_stats_manager_ptr->get_media_stats_callback());
G()->set_net_stats_file_callbacks(net_stats_manager_ptr->get_file_stats_callbacks());
G()->set_connection_creator(std::move(connection_creator));
net_stats_manager_ = std::move(net_stats_manager);
}
auto temp_auth_key_watchdog = create_actor<TempAuthKeyWatchdog>("TempAuthKeyWatchdog");
G()->set_temp_auth_key_watchdog(std::move(temp_auth_key_watchdog));
// create ConfigManager and ConfigShared
class ConfigSharedCallback : public ConfigShared::Callback {
public:
void on_option_updated(const string &name) override {
send_closure(G()->td(), &Td::on_config_option_updated, name);
}
};
send_update(
make_tl_object<td_api::updateOption>("version", make_tl_object<td_api::optionValueString>(tdlib_version)));
G()->set_shared_config(
std::make_unique<ConfigShared>(G()->td_db()->get_config_pmc(), std::make_unique<ConfigSharedCallback>()));
config_manager_ = create_actor<ConfigManager>("ConfigManager", create_reference());
G()->set_config_manager(config_manager_.get());
auto net_query_dispatcher = std::make_unique<NetQueryDispatcher>([&] { return create_reference(); });
G()->set_net_query_dispatcher(std::move(net_query_dispatcher));
auth_manager_ = std::make_unique<AuthManager>(parameters_.api_id, parameters_.api_hash, create_reference());
auth_manager_actor_ = register_actor("AuthManager", auth_manager_.get());
download_file_callback_ = std::make_shared<DownloadFileCallback>();
upload_file_callback_ = std::make_shared<UploadFileCallback>();
class FileManagerContext : public FileManager::Context {
public:
explicit FileManagerContext(Td *td) : td_(td) {
}
void on_new_file(int64 size) final {
send_closure(G()->storage_manager(), &StorageManager::on_new_file, size);
}
void on_file_updated(FileId file_id) final {
send_closure(G()->td(), &Td::send_update,
make_tl_object<td_api::updateFile>(td_->file_manager_->get_file_object(file_id)));
}
ActorShared<> create_reference() final {
return td_->create_reference();
}
private:
Td *td_;
};
file_manager_ = std::make_unique<FileManager>(std::make_unique<FileManagerContext>(this));
file_manager_actor_ = register_actor("FileManager", file_manager_.get());
file_manager_->init_actor();
G()->set_file_manager(file_manager_actor_.get());
audios_manager_ = make_unique<AudiosManager>(this);
callback_queries_manager_ = make_unique<CallbackQueriesManager>(this);
documents_manager_ = make_unique<DocumentsManager>(this);
video_notes_manager_ = make_unique<VideoNotesManager>(this);
videos_manager_ = make_unique<VideosManager>(this);
voice_notes_manager_ = make_unique<VoiceNotesManager>(this);
animations_manager_ = std::make_unique<AnimationsManager>(this, create_reference());
animations_manager_actor_ = register_actor("AnimationsManager", animations_manager_.get());
G()->set_animations_manager(animations_manager_actor_.get());
change_phone_number_manager_ = std::make_unique<ChangePhoneNumberManager>(create_reference());
change_phone_number_manager_actor_ = register_actor("ChangePhoneNumberManager", change_phone_number_manager_.get());
contacts_manager_ = std::make_unique<ContactsManager>(this, create_reference());
contacts_manager_actor_ = register_actor("ContactsManager", contacts_manager_.get());
G()->set_contacts_manager(contacts_manager_actor_.get());
inline_queries_manager_ = std::make_unique<InlineQueriesManager>(this, create_reference());
inline_queries_manager_actor_ = register_actor("InlineQueriesManager", inline_queries_manager_.get());
messages_manager_ = std::make_unique<MessagesManager>(this, create_reference());
messages_manager_actor_ = register_actor("MessagesManager", messages_manager_.get());
G()->set_messages_manager(messages_manager_actor_.get());
stickers_manager_ = std::make_unique<StickersManager>(this, create_reference());
stickers_manager_actor_ = register_actor("StickersManager", stickers_manager_.get());
G()->set_stickers_manager(stickers_manager_actor_.get());
updates_manager_ = std::make_unique<UpdatesManager>(this, create_reference());
updates_manager_actor_ = register_actor("UpdatesManager", updates_manager_.get());
G()->set_updates_manager(updates_manager_actor_.get());
web_pages_manager_ = std::make_unique<WebPagesManager>(this, create_reference());
web_pages_manager_actor_ = register_actor("WebPagesManager", web_pages_manager_.get());
G()->set_web_pages_manager(web_pages_manager_actor_.get());
call_manager_ = create_actor<CallManager>("CallManager", create_reference());
G()->set_call_manager(call_manager_.get());
device_token_manager_ = create_actor<DeviceTokenManager>("DeviceTokenManager", create_reference());
hashtag_hints_ = create_actor<HashtagHints>("HashtagHints", "text", create_reference());
password_manager_ = create_actor<PasswordManager>("PasswordManager", create_reference());
privacy_manager_ = create_actor<PrivacyManager>("PrivacyManager", create_reference());
secret_chats_manager_ = create_actor<SecretChatsManager>("SecretChatsManager", create_reference());
G()->set_secret_chats_manager(secret_chats_manager_.get());
storage_manager_ = create_actor<StorageManager>("StorageManager", create_reference(),
std::min(current_scheduler_id + 2, scheduler_count - 1));
G()->set_storage_manager(storage_manager_.get());
top_dialog_manager_ = create_actor<TopDialogManager>("TopDialogManager", create_reference());
G()->set_top_dialog_manager(top_dialog_manager_.get());
for (auto &event : events.user_events) {
contacts_manager_->on_binlog_user_event(std::move(event));
}
for (auto &event : events.chat_events) {
contacts_manager_->on_binlog_chat_event(std::move(event));
}
for (auto &event : events.channel_events) {
contacts_manager_->on_binlog_channel_event(std::move(event));
}
for (auto &event : events.secret_chat_events) {
contacts_manager_->on_binlog_secret_chat_event(std::move(event));
}
for (auto &event : events.web_page_events) {
web_pages_manager_->on_binlog_web_page_event(std::move(event));
}
// Send binlog events to managers
//
// 1. Actors must receive all binlog events before other queries.
//
// -- All actors have one "entry point". So there is only one way to send query to them. So all queries are ordered
// for each Actor.
//
//
// 2. An actor must not make some decisions before all binlog events are processed.
// For example, SecretChatActor must not send RequestKey, before it receives logevent with RequestKey and understands
// that RequestKey was already sent.
//
// -- G()->wait_binlog_replay_finish(Promise<>);
//
// 3. During replay of binlog some queries may be sent to other actors. They shouldn't process such events before all
// their binlog events are processed. So actor may receive some old queries. It must be in it's actual state in
// orded to handle them properly.
//
// -- Use send_closure_later, so actors don't even start process binlog events, before all binlog events are sent
for (auto &event : events.to_secret_chats_manager) {
send_closure_later(secret_chats_manager_, &SecretChatsManager::replay_binlog_event, std::move(event));
}
send_closure_later(messages_manager_actor_, &MessagesManager::on_binlog_events,
std::move(events.to_messages_manager));
// NB: be very careful. This notification may be received before all binlog events are.
G()->on_binlog_replay_finish();
send_closure(secret_chats_manager_, &SecretChatsManager::binlog_replay_finish);
if (!auth_manager_->is_authorized()) {
create_handler<GetNearestDcQuery>()->send();
} else {
updates_manager_->get_difference("init");
}
state_ = State::Run;
return Status::OK();
}
void Td::send_update(tl_object_ptr<td_api::Update> &&object) {
switch (object->get_id()) {
case td_api::updateFavoriteStickers::ID:
case td_api::updateInstalledStickerSets::ID:
case td_api::updateRecentStickers::ID:
case td_api::updateSavedAnimations::ID:
case td_api::updateUserStatus::ID:
VLOG(td_requests) << "Sending update: " << oneline(to_string(object));
break;
case td_api::updateTrendingStickerSets::ID:
VLOG(td_requests) << "Sending update: updateTrendingStickerSets { ... }";
break;
default:
VLOG(td_requests) << "Sending update: " << to_string(object);
}
callback_->on_result(0, std::move(object));
}
void Td::send_result(uint64 id, tl_object_ptr<td_api::Object> object) {
LOG_IF(ERROR, id == 0) << "Sending " << to_string(object) << " through send_result";
if (id == 0 || request_set_.erase(id)) {
VLOG(td_requests) << "Sending result for request " << id << ": " << to_string(object);
if (object == nullptr) {
object = make_tl_object<td_api::error>(404, "Not Found");
}
callback_->on_result(id, std::move(object));
}
}
void Td::send_error_impl(uint64 id, tl_object_ptr<td_api::error> error) {
CHECK(id != 0);
CHECK(callback_ != nullptr);
CHECK(error != nullptr);
if (request_set_.erase(id)) {
VLOG(td_requests) << "Sending error for request " << id << ": " << oneline(to_string(error));
callback_->on_error(id, std::move(error));
}
}
void Td::send_error(uint64 id, Status error) {
send_error_impl(id, make_tl_object<td_api::error>(error.code(), error.message().str()));
error.ignore();
}
namespace {
auto create_error_raw(int32 code, CSlice error) {
return make_tl_object<td_api::error>(code, error.str());
}
} // namespace
void Td::send_error_raw(uint64 id, int32 code, CSlice error) {
send_error_impl(id, create_error_raw(code, error));
}
void Td::answer_ok_query(uint64 id, Status status) {
if (status.is_error()) {
send_closure(actor_id(this), &Td::send_error, id, std::move(status));
} else {
send_closure(actor_id(this), &Td::send_result, id, make_tl_object<td_api::ok>());
}
}
#define CLEAN_INPUT_STRING(field_name) \
if (!clean_input_string(field_name)) { \
return send_error_raw(id, 400, "Strings must be encoded in UTF-8"); \
}
#define CHECK_AUTH() \
if (!auth_manager_->is_authorized()) { \
return send_error_raw(id, 401, "Unauthorized"); \
}
#define CHECK_IS_BOT() \
if (!auth_manager_->is_bot()) { \
return send_error_raw(id, 400, "Only bots can use the method"); \
}
#define CHECK_IS_USER() \
if (auth_manager_->is_bot()) { \
return send_error_raw(id, 400, "The method is not available for bots"); \
}
#define CREATE_NO_ARGS_REQUEST(name) \
auto slot_id = request_actors_.create(ActorOwn<>(), RequestActorIdType); \
inc_request_actor_refcnt(); \
*request_actors_.get(slot_id) = create_actor<name>(#name, actor_shared(this, slot_id), id);
#define CREATE_REQUEST(name, ...) \
auto slot_id = request_actors_.create(ActorOwn<>(), RequestActorIdType); \
inc_request_actor_refcnt(); \
*request_actors_.get(slot_id) = create_actor<name>(#name, actor_shared(this, slot_id), id, __VA_ARGS__);
#define CREATE_REQUEST_PROMISE(name) \
auto name = create_request_promise<std::decay_t<decltype(request)>::ReturnType>(id);
Status Td::fix_parameters(TdParameters ¶meters) {
if (parameters.database_directory.empty()) {
parameters.database_directory = ".";
}
if (parameters.files_directory.empty()) {
parameters.files_directory = parameters.database_directory;
}
if (parameters.use_message_db) {
parameters.use_chat_info_db = true;
}
if (parameters.use_chat_info_db) {
parameters.use_file_db = true;
}
if (parameters.api_id == 0) {
return Status::Error(400, "Valid api_id must be provided. Can be obtained at https://my.telegram.org");
}
if (parameters.api_hash.empty()) {
return Status::Error(400, "Valid api_hash must be provided. Can be obtained at https://my.telegram.org");
}
auto prepare_dir = [](string dir) -> Result<string> {
CHECK(!dir.empty());
if (dir.back() != TD_DIR_SLASH) {
dir += TD_DIR_SLASH;
}
TRY_STATUS(mkpath(dir, 0750));
TRY_RESULT(real_dir, realpath(dir));
if (dir.back() != TD_DIR_SLASH) {
dir += TD_DIR_SLASH;
}
return real_dir;
};
auto r_database_directory = prepare_dir(parameters.database_directory);
if (r_database_directory.is_error()) {
return Status::Error(400, PSLICE() << "Can't init database in the directory \"" << parameters.database_directory
<< "\": " << r_database_directory.error());
}
parameters.database_directory = r_database_directory.move_as_ok();
auto r_files_directory = prepare_dir(parameters.files_directory);
if (r_files_directory.is_error()) {
return Status::Error(400, PSLICE() << "Can't init files directory \"" << parameters.files_directory
<< "\": " << r_files_directory.error());
}
parameters.files_directory = r_files_directory.move_as_ok();
return Status::OK();
}
Status Td::set_td_parameters(td_api::object_ptr<td_api::tdlibParameters> parameters) {
if (!clean_input_string(parameters->api_hash_) && !clean_input_string(parameters->system_language_code_) &&
!clean_input_string(parameters->device_model_) && !clean_input_string(parameters->system_version_) &&
!clean_input_string(parameters->application_version_)) {
return Status::Error(400, "Strings must be encoded in UTF-8");
}
parameters_.use_test_dc = parameters->use_test_dc_;
parameters_.database_directory = parameters->database_directory_;
parameters_.files_directory = parameters->files_directory_;
parameters_.api_id = parameters->api_id_;
parameters_.api_hash = parameters->api_hash_;
parameters_.use_file_db = parameters->use_file_database_;
parameters_.enable_storage_optimizer = parameters->enable_storage_optimizer_;
parameters_.ignore_file_names = parameters->ignore_file_names_;
parameters_.use_secret_chats = parameters->use_secret_chats_;
parameters_.use_chat_info_db = parameters->use_chat_info_database_;
parameters_.use_message_db = parameters->use_message_database_;
TRY_STATUS(fix_parameters(parameters_));
TRY_RESULT(encryption_info, TdDb::check_encryption(parameters_));
encryption_info_ = std::move(encryption_info);
alarm_timeout_.set_callback(on_alarm_timeout_callback);
alarm_timeout_.set_callback_data(static_cast<void *>(this));
set_context(std::make_shared<Global>());
inc_request_actor_refcnt(); // guard
inc_actor_refcnt(); // guard
MtprotoHeader::Options options;
options.api_id = parameters->api_id_;
options.system_language_code = parameters->system_language_code_;
options.device_model = parameters->device_model_;
options.system_version = parameters->system_version_;
options.application_version = parameters->application_version_;
if (options.api_id != 21724) {
options.application_version += ", TDLib ";
options.application_version += tdlib_version;
}
G()->set_mtproto_header(std::make_unique<MtprotoHeader>(options));
state_ = State::Decrypt;
send_update(td_api::make_object<td_api::updateAuthorizationState>(
td_api::make_object<td_api::authorizationStateWaitEncryptionKey>(encryption_info_.is_encrypted)));
return Status::OK();
}
void Td::on_request(uint64 id, const td_api::setTdlibParameters &request) {
send_error_raw(id, 400, "Unexpected setTdlibParameters");
}
void Td::on_request(uint64 id, const td_api::checkDatabaseEncryptionKey &request) {
send_error_raw(id, 400, "Unexpected checkDatabaseEncryptionKey");
}
void Td::on_request(uint64 id, td_api::setDatabaseEncryptionKey &request) {
CREATE_REQUEST_PROMISE(promise);
auto query_promise = PromiseCreator::lambda([promise = std::move(promise)](Result<> result) mutable {
if (result.is_error()) {
promise.set_error(result.move_as_error());
} else {
promise.set_value(make_tl_object<td_api::ok>());
}
});
G()->td_db()->get_binlog()->change_key(as_db_key(std::move(request.new_encryption_key_)), std::move(query_promise));
}
void Td::on_request(uint64 id, const td_api::getAuthorizationState &request) {
send_closure(auth_manager_actor_, &AuthManager::get_state, id);
}
void Td::on_request(uint64 id, td_api::setAuthenticationPhoneNumber &request) {
CLEAN_INPUT_STRING(request.phone_number_);
send_closure(auth_manager_actor_, &AuthManager::set_phone_number, id, std::move(request.phone_number_),
request.allow_flash_call_, request.is_current_phone_number_);
}
void Td::on_request(uint64 id, const td_api::resendAuthenticationCode &) {
send_closure(auth_manager_actor_, &AuthManager::resend_authentication_code, id);
}
void Td::on_request(uint64 id, td_api::checkAuthenticationCode &request) {
CLEAN_INPUT_STRING(request.code_);
CLEAN_INPUT_STRING(request.first_name_);
CLEAN_INPUT_STRING(request.last_name_);
send_closure(auth_manager_actor_, &AuthManager::check_code, id, std::move(request.code_),
std::move(request.first_name_), std::move(request.last_name_));
}
void Td::on_request(uint64 id, td_api::checkAuthenticationPassword &request) {
CLEAN_INPUT_STRING(request.password_);
send_closure(auth_manager_actor_, &AuthManager::check_password, id, std::move(request.password_));
}
void Td::on_request(uint64 id, const td_api::requestAuthenticationPasswordRecovery &request) {
send_closure(auth_manager_actor_, &AuthManager::request_password_recovery, id);
}
void Td::on_request(uint64 id, td_api::recoverAuthenticationPassword &request) {
CLEAN_INPUT_STRING(request.recovery_code_);
send_closure(auth_manager_actor_, &AuthManager::recover_password, id, std::move(request.recovery_code_));
}
void Td::on_request(uint64 id, const td_api::logOut &request) {
// will call Td::destroy later
send_closure(auth_manager_actor_, &AuthManager::logout, id);
}
void Td::on_request(uint64 id, const td_api::close &request) {
close();
send_result(id, td_api::make_object<td_api::ok>());
}
void Td::on_request(uint64 id, const td_api::destroy &request) {
destroy();
send_result(id, td_api::make_object<td_api::ok>());
}
void Td::on_request(uint64 id, td_api::checkAuthenticationBotToken &request) {
CLEAN_INPUT_STRING(request.token_);
send_closure(auth_manager_actor_, &AuthManager::check_bot_token, id, std::move(request.token_));
}
void Td::on_request(uint64 id, td_api::getPasswordState &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST_PROMISE(promise);
send_closure(password_manager_, &PasswordManager::get_state, std::move(promise));
}
void Td::on_request(uint64 id, td_api::setPassword &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.old_password_);
CLEAN_INPUT_STRING(request.new_password_);
CLEAN_INPUT_STRING(request.new_hint_);
CLEAN_INPUT_STRING(request.new_recovery_email_address_);
CREATE_REQUEST_PROMISE(promise);
send_closure(password_manager_, &PasswordManager::set_password, std::move(request.old_password_),
std::move(request.new_password_), std::move(request.new_hint_), request.set_recovery_email_address_,
std::move(request.new_recovery_email_address_), std::move(promise));
}
void Td::on_request(uint64 id, td_api::setRecoveryEmailAddress &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.password_);
CLEAN_INPUT_STRING(request.new_recovery_email_address_);
CREATE_REQUEST_PROMISE(promise);
send_closure(password_manager_, &PasswordManager::set_recovery_email_address, std::move(request.password_),
std::move(request.new_recovery_email_address_), std::move(promise));
}
void Td::on_request(uint64 id, td_api::getRecoveryEmailAddress &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.password_);
CREATE_REQUEST_PROMISE(promise);
send_closure(password_manager_, &PasswordManager::get_recovery_email_address, std::move(request.password_),
std::move(promise));
}
void Td::on_request(uint64 id, td_api::requestPasswordRecovery &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST_PROMISE(promise);
send_closure(password_manager_, &PasswordManager::request_password_recovery, std::move(promise));
}
void Td::on_request(uint64 id, td_api::recoverPassword &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.recovery_code_);
CREATE_REQUEST_PROMISE(promise);
send_closure(password_manager_, &PasswordManager::recover_password, std::move(request.recovery_code_),
std::move(promise));
}
void Td::on_request(uint64 id, td_api::getTemporaryPasswordState &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST_PROMISE(promise);
send_closure(password_manager_, &PasswordManager::get_temp_password_state, std::move(promise));
}
void Td::on_request(uint64 id, td_api::createTemporaryPassword &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.password_);
CREATE_REQUEST_PROMISE(promise);
send_closure(password_manager_, &PasswordManager::create_temp_password, std::move(request.password_),
request.valid_for_, std::move(promise));
}
void Td::on_request(uint64 id, td_api::processDcUpdate &request) {
CREATE_REQUEST_PROMISE(promise);
CLEAN_INPUT_STRING(request.dc_);
CLEAN_INPUT_STRING(request.addr_);
auto query_promise = PromiseCreator::lambda([promise = std::move(promise)](Result<> result) mutable {
if (result.is_error()) {
promise.set_error(result.move_as_error());
} else {
promise.set_value(make_tl_object<td_api::ok>());
}
});
auto dc_id_raw = to_integer<int32>(request.dc_);
if (!DcId::is_valid(dc_id_raw)) {
promise.set_error(Status::Error("Invalid dc id"));
return;
}
send_closure(G()->connection_creator(), &ConnectionCreator::on_dc_update, DcId::internal(dc_id_raw), request.addr_,
std::move(query_promise));
}
void Td::on_request(uint64 id, td_api::registerDevice &request) {
CHECK_AUTH();
CHECK_IS_USER();
if (request.device_token_ == nullptr) {
return send_error_raw(id, 400, "Device token should not be empty");
}
CREATE_REQUEST_PROMISE(promise);
send_closure(device_token_manager_, &DeviceTokenManager::register_device, std::move(request.device_token_),
std::move(promise));
}
void Td::on_request(uint64 id, td_api::getUserPrivacySettingRules &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST_PROMISE(promise);
send_closure(privacy_manager_, &PrivacyManager::get_privacy, std::move(request.setting_), std::move(promise));
}
void Td::on_request(uint64 id, td_api::setUserPrivacySettingRules &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST_PROMISE(promise);
send_closure(privacy_manager_, &PrivacyManager::set_privacy, std::move(request.setting_), std::move(request.rules_),
std::move(promise));
}
void Td::on_request(uint64 id, const td_api::getAccountTtl &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_NO_ARGS_REQUEST(GetAccountTtlRequest);
}
void Td::on_request(uint64 id, const td_api::setAccountTtl &request) {
CHECK_AUTH();
CHECK_IS_USER();
if (request.ttl_ == nullptr) {
return send_error_raw(id, 400, "New account TTL should not be empty");
}
CREATE_REQUEST(SetAccountTtlRequest, request.ttl_->days_);
}
void Td::on_request(uint64 id, td_api::deleteAccount &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.reason_);
send_closure(auth_manager_actor_, &AuthManager::delete_account, id, request.reason_);
}
void Td::on_request(uint64 id, td_api::changePhoneNumber &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.phone_number_);
change_phone_number_manager_->change_phone_number(id, std::move(request.phone_number_), request.allow_flash_call_,
request.is_current_phone_number_);
}
void Td::on_request(uint64 id, td_api::checkChangePhoneNumberCode &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.code_);
change_phone_number_manager_->check_code(id, std::move(request.code_));
}
void Td::on_request(uint64 id, td_api::resendChangePhoneNumberCode &request) {
CHECK_AUTH();
CHECK_IS_USER();
change_phone_number_manager_->resend_authentication_code(id);
}
void Td::on_request(uint64 id, const td_api::getActiveSessions &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_NO_ARGS_REQUEST(GetActiveSessionsRequest);
}
void Td::on_request(uint64 id, const td_api::terminateSession &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(TerminateSessionRequest, request.session_id_);
}
void Td::on_request(uint64 id, const td_api::terminateAllOtherSessions &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_NO_ARGS_REQUEST(TerminateAllOtherSessionsRequest);
}
void Td::on_request(uint64 id, const td_api::getMe &) {
CHECK_AUTH();
UserId my_id = contacts_manager_->get_my_id("getMe");
CHECK(my_id.is_valid());
CREATE_REQUEST(GetUserRequest, my_id.get());
}
void Td::on_request(uint64 id, const td_api::getUser &request) {
CHECK_AUTH();
CREATE_REQUEST(GetUserRequest, request.user_id_);
}
void Td::on_request(uint64 id, const td_api::getUserFullInfo &request) {
CHECK_AUTH();
CREATE_REQUEST(GetUserFullInfoRequest, request.user_id_);
}
void Td::on_request(uint64 id, const td_api::getBasicGroup &request) {
CHECK_AUTH();
CREATE_REQUEST(GetGroupRequest, request.basic_group_id_);
}
void Td::on_request(uint64 id, const td_api::getBasicGroupFullInfo &request) {
CHECK_AUTH();
CREATE_REQUEST(GetGroupFullInfoRequest, request.basic_group_id_);
}
void Td::on_request(uint64 id, const td_api::getSupergroup &request) {
CHECK_AUTH();
CREATE_REQUEST(GetSupergroupRequest, request.supergroup_id_);
}
void Td::on_request(uint64 id, const td_api::getSupergroupFullInfo &request) {
CHECK_AUTH();
CREATE_REQUEST(GetSupergroupFullInfoRequest, request.supergroup_id_);
}
void Td::on_request(uint64 id, const td_api::getSecretChat &request) {
CHECK_AUTH();
CREATE_REQUEST(GetSecretChatRequest, request.secret_chat_id_);
}
void Td::on_request(uint64 id, const td_api::getChat &request) {
CHECK_AUTH();
CREATE_REQUEST(GetChatRequest, request.chat_id_);
}
void Td::on_request(uint64 id, const td_api::getMessage &request) {
CHECK_AUTH();
CREATE_REQUEST(GetMessageRequest, request.chat_id_, request.message_id_);
}
void Td::on_request(uint64 id, const td_api::getMessages &request) {
CHECK_AUTH();
CREATE_REQUEST(GetMessagesRequest, request.chat_id_, request.message_ids_);
}
void Td::on_request(uint64 id, const td_api::getPublicMessageLink &request) {
CHECK_AUTH();
CREATE_REQUEST(GetPublicMessageLinkRequest, request.chat_id_, request.message_id_);
}
void Td::on_request(uint64 id, const td_api::getFile &request) {
CHECK_AUTH();
send_closure(actor_id(this), &Td::send_result, id, file_manager_->get_file_object(FileId(request.file_id_)));
}
void Td::on_request(uint64 id, td_api::getRemoteFile &request) {
CHECK_AUTH();
CLEAN_INPUT_STRING(request.remote_file_id_);
auto r_file_id = file_manager_->from_persistent_id(
request.remote_file_id_, request.file_type_ == nullptr ? FileType::Temp : from_td_api(*request.file_type_));
if (r_file_id.is_error()) {
auto error = r_file_id.move_as_error();
send_closure(actor_id(this), &Td::send_error, id, std::move(error));
} else {
send_closure(actor_id(this), &Td::send_result, id, file_manager_->get_file_object(r_file_id.ok()));
}
}
void Td::on_request(uint64 id, td_api::getStorageStatistics &request) {
CHECK_AUTH();
CREATE_REQUEST_PROMISE(promise);
auto query_promise = PromiseCreator::lambda([promise = std::move(promise)](Result<FileStats> result) mutable {
if (result.is_error()) {
promise.set_error(result.move_as_error());
} else {
promise.set_value(result.ok().as_td_api());
}
});
send_closure(storage_manager_, &StorageManager::get_storage_stats, request.chat_limit_, std::move(query_promise));
}
void Td::on_request(uint64 id, td_api::getStorageStatisticsFast &request) {
CHECK_AUTH();
CREATE_REQUEST_PROMISE(promise);
auto query_promise = PromiseCreator::lambda([promise = std::move(promise)](Result<FileStatsFast> result) mutable {
if (result.is_error()) {
promise.set_error(result.move_as_error());
} else {
promise.set_value(result.ok().as_td_api());
}
});
send_closure(storage_manager_, &StorageManager::get_storage_stats_fast, std::move(query_promise));
}
void Td::on_request(uint64 id, td_api::optimizeStorage &request) {
CHECK_AUTH();
std::vector<FileType> file_types;
for (auto &file_type : request.file_types_) {
if (file_type == nullptr) {
return send_error_raw(id, 400, "File type should not be empty");
}
file_types.push_back(from_td_api(*file_type));
}
std::vector<DialogId> owner_dialog_ids;
for (auto chat_id : request.chat_ids_) {
DialogId dialog_id(chat_id);
if (!dialog_id.is_valid() && dialog_id != DialogId()) {
return send_error_raw(id, 400, "Wrong chat id");
}
owner_dialog_ids.push_back(dialog_id);
}
std::vector<DialogId> exclude_owner_dialog_ids;
for (auto chat_id : request.exclude_chat_ids_) {
DialogId dialog_id(chat_id);
if (!dialog_id.is_valid() && dialog_id != DialogId()) {
return send_error_raw(id, 400, "Wrong chat id");
}
exclude_owner_dialog_ids.push_back(dialog_id);
}
FileGcParameters parameters(request.size_, request.ttl_, request.count_, request.immunity_delay_,
std::move(file_types), std::move(owner_dialog_ids), std::move(exclude_owner_dialog_ids),
request.chat_limit_);
CREATE_REQUEST_PROMISE(promise);
auto query_promise = PromiseCreator::lambda([promise = std::move(promise)](Result<FileStats> result) mutable {
if (result.is_error()) {
promise.set_error(result.move_as_error());
} else {
promise.set_value(result.ok().as_td_api());
}
});
send_closure(storage_manager_, &StorageManager::run_gc, std::move(parameters), std::move(query_promise));
}
void Td::on_request(uint64 id, td_api::getNetworkStatistics &request) {
CREATE_REQUEST_PROMISE(promise);
auto query_promise = PromiseCreator::lambda([promise = std::move(promise)](Result<NetworkStats> result) mutable {
if (result.is_error()) {
promise.set_error(result.move_as_error());
} else {
promise.set_value(result.ok().as_td_api());
}
});
send_closure(net_stats_manager_, &NetStatsManager::get_network_stats, request.only_current_,
std::move(query_promise));
}
void Td::on_request(uint64 id, td_api::resetNetworkStatistics &request) {
CREATE_REQUEST_PROMISE(promise);
send_closure(net_stats_manager_, &NetStatsManager::reset_network_stats);
promise.set_value(make_tl_object<td_api::ok>());
}
void Td::on_request(uint64 id, td_api::addNetworkStatistics &request) {
CREATE_REQUEST_PROMISE(promise);
if (request.entry_ == nullptr) {
return send_error_raw(id, 400, "Network statistics entry should not be empty");
}
NetworkStatsEntry entry;
switch (request.entry_->get_id()) {
case td_api::networkStatisticsEntryFile::ID: {
auto file_entry = move_tl_object_as<td_api::networkStatisticsEntryFile>(request.entry_);
entry.is_call = false;
if (file_entry->file_type_ != nullptr) {
entry.file_type = from_td_api(*file_entry->file_type_);
}
entry.net_type = from_td_api(file_entry->network_type_);
entry.rx = file_entry->received_bytes_;
entry.tx = file_entry->sent_bytes_;
break;
}
case td_api::networkStatisticsEntryCall::ID: {
auto call_entry = move_tl_object_as<td_api::networkStatisticsEntryCall>(request.entry_);
entry.is_call = true;
entry.net_type = from_td_api(call_entry->network_type_);
entry.rx = call_entry->received_bytes_;
entry.tx = call_entry->sent_bytes_;
entry.duration = call_entry->duration_;
break;
}
default:
UNREACHABLE();
}
if (entry.net_type == NetType::None) {
return send_error_raw(id, 400, "Network statistics entry can't be increased for NetworkTypeNone");
}
if (entry.rx > (1ll << 40) || entry.rx < 0) {
return send_error_raw(id, 400, "Wrong received bytes value");
}
if (entry.tx > (1ll << 40) || entry.tx < 0) {
return send_error_raw(id, 400, "Wrong sent bytes value");
}
if (entry.count > (1 << 30) || entry.count < 0) {
return send_error_raw(id, 400, "Wrong count value");
}
if (entry.duration > (1 << 30) || entry.duration < 0) {
return send_error_raw(id, 400, "Wrong duration value");
}
send_closure(net_stats_manager_, &NetStatsManager::add_network_stats, entry);
send_closure(actor_id(this), &Td::send_result, id, make_tl_object<td_api::ok>());
}
void Td::on_request(uint64 id, td_api::setNetworkType &request) {
CREATE_REQUEST_PROMISE(promise);
send_closure(state_manager_, &StateManager::on_network, from_td_api(request.type_));
promise.set_value(make_tl_object<td_api::ok>());
}
void Td::on_request(uint64 id, td_api::getTopChats &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST_PROMISE(promise);
if (request.category_ == nullptr) {
promise.set_error(Status::Error(400, "Top chat category should not be empty"));
return;
}
if (request.limit_ <= 0) {
promise.set_error(Status::Error(400, "Limit must be positive"));
return;
}
auto query_promise = PromiseCreator::lambda([promise = std::move(promise)](Result<vector<DialogId>> result) mutable {
if (result.is_error()) {
promise.set_error(result.move_as_error());
} else {
promise.set_value(MessagesManager::get_chats_object(result.ok()));
}
});
send_closure(top_dialog_manager_, &TopDialogManager::get_top_dialogs,
top_dialog_category_from_td_api(*request.category_), request.limit_, std::move(query_promise));
}
void Td::on_request(uint64 id, const td_api::removeTopChat &request) {
CHECK_AUTH();
CHECK_IS_USER();
if (request.category_ == nullptr) {
return send_error_raw(id, 400, "Top chat category should not be empty");
}
send_closure(top_dialog_manager_, &TopDialogManager::remove_dialog,
top_dialog_category_from_td_api(*request.category_), DialogId(request.chat_id_),
messages_manager_->get_input_peer(DialogId(request.chat_id_), AccessRights::Read));
send_closure(actor_id(this), &Td::send_result, id, make_tl_object<td_api::ok>());
}
void Td::on_request(uint64 id, const td_api::getChats &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(GetChatsRequest, request.offset_order_, request.offset_chat_id_, request.limit_);
}
void Td::on_request(uint64 id, td_api::searchPublicChat &request) {
CHECK_AUTH();
CLEAN_INPUT_STRING(request.username_);
CREATE_REQUEST(SearchPublicChatRequest, request.username_);
}
void Td::on_request(uint64 id, td_api::searchPublicChats &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.query_);
CREATE_REQUEST(SearchPublicChatsRequest, request.query_);
}
void Td::on_request(uint64 id, td_api::searchChats &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.query_);
CREATE_REQUEST(SearchChatsRequest, request.query_, request.limit_);
}
void Td::on_request(uint64 id, const td_api::getGroupsInCommon &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(GetGroupsInCommonRequest, request.user_id_, request.offset_chat_id_, request.limit_);
}
void Td::on_request(uint64 id, const td_api::getCreatedPublicChats &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_NO_ARGS_REQUEST(GetCreatedPublicChatsRequest);
}
void Td::on_request(uint64 id, const td_api::addRecentlyFoundChat &request) {
CHECK_AUTH();
CHECK_IS_USER();
answer_ok_query(id, messages_manager_->add_recently_found_dialog(DialogId(request.chat_id_)));
}
void Td::on_request(uint64 id, const td_api::removeRecentlyFoundChat &request) {
CHECK_AUTH();
CHECK_IS_USER();
answer_ok_query(id, messages_manager_->remove_recently_found_dialog(DialogId(request.chat_id_)));
}
void Td::on_request(uint64 id, const td_api::clearRecentlyFoundChats &request) {
CHECK_AUTH();
CHECK_IS_USER();
messages_manager_->clear_recently_found_dialogs();
send_closure(actor_id(this), &Td::send_result, id, make_tl_object<td_api::ok>());
}
void Td::on_request(uint64 id, const td_api::openChat &request) {
CHECK_AUTH();
CHECK_IS_USER();
answer_ok_query(id, messages_manager_->open_dialog(DialogId(request.chat_id_)));
}
void Td::on_request(uint64 id, const td_api::closeChat &request) {
CHECK_AUTH();
CHECK_IS_USER();
answer_ok_query(id, messages_manager_->close_dialog(DialogId(request.chat_id_)));
}
void Td::on_request(uint64 id, const td_api::viewMessages &request) {
CHECK_AUTH();
CHECK_IS_USER();
answer_ok_query(
id, messages_manager_->view_messages(
DialogId(request.chat_id_), MessagesManager::get_message_ids(request.message_ids_), request.force_read_));
}
void Td::on_request(uint64 id, const td_api::openMessageContent &request) {
CHECK_AUTH();
CHECK_IS_USER();
answer_ok_query(
id, messages_manager_->open_message_content({DialogId(request.chat_id_), MessageId(request.message_id_)}));
}
void Td::on_request(uint64 id, const td_api::getChatHistory &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(GetChatHistoryRequest, request.chat_id_, request.from_message_id_, request.offset_, request.limit_,
request.only_local_);
}
void Td::on_request(uint64 id, const td_api::deleteChatHistory &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(DeleteChatHistoryRequest, request.chat_id_, request.remove_from_chat_list_);
}
void Td::on_request(uint64 id, td_api::searchChatMessages &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.query_);
CREATE_REQUEST(SearchChatMessagesRequest, request.chat_id_, std::move(request.query_), request.sender_user_id_,
request.from_message_id_, request.offset_, request.limit_, std::move(request.filter_));
}
void Td::on_request(uint64 id, td_api::searchSecretMessages &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.query_);
CREATE_REQUEST(OfflineSearchMessagesRequest, request.chat_id_, std::move(request.query_), request.from_search_id_,
request.limit_, std::move(request.filter_));
}
void Td::on_request(uint64 id, td_api::searchMessages &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.query_);
CREATE_REQUEST(SearchMessagesRequest, std::move(request.query_), request.offset_date_, request.offset_chat_id_,
request.offset_message_id_, request.limit_);
}
void Td::on_request(uint64 id, td_api::searchCallMessages &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(SearchCallMessagesRequest, request.from_message_id_, request.limit_, request.only_missed_);
}
void Td::on_request(uint64 id, const td_api::searchChatRecentLocationMessages &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(SearchChatRecentLocationMessagesRequest, request.chat_id_, request.limit_);
}
void Td::on_request(uint64 id, const td_api::getActiveLiveLocationMessages &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_NO_ARGS_REQUEST(GetActiveLiveLocationMessagesRequest);
}
void Td::on_request(uint64 id, const td_api::getChatMessageByDate &request) {
CHECK_AUTH();
CREATE_REQUEST(GetChatMessageByDateRequest, request.chat_id_, request.date_);
}
void Td::on_request(uint64 id, const td_api::deleteMessages &request) {
CHECK_AUTH();
CREATE_REQUEST(DeleteMessagesRequest, request.chat_id_, request.message_ids_, request.revoke_);
}
void Td::on_request(uint64 id, const td_api::deleteChatMessagesFromUser &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(DeleteChatMessagesFromUserRequest, request.chat_id_, request.user_id_);
}
void Td::on_request(uint64 id, const td_api::readAllChatMentions &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(ReadAllChatMentionsRequest, request.chat_id_);
}
void Td::on_request(uint64 id, td_api::sendMessage &request) {
CHECK_AUTH();
DialogId dialog_id(request.chat_id_);
auto r_new_message_id = messages_manager_->send_message(
dialog_id, MessageId(request.reply_to_message_id_), request.disable_notification_, request.from_background_,
std::move(request.reply_markup_), std::move(request.input_message_content_));
if (r_new_message_id.is_error()) {
return send_closure(actor_id(this), &Td::send_error, id, r_new_message_id.move_as_error());
}
CHECK(r_new_message_id.ok().is_valid());
send_closure(actor_id(this), &Td::send_result, id,
messages_manager_->get_message_object({dialog_id, r_new_message_id.ok()}));
}
void Td::on_request(uint64 id, td_api::sendMessageAlbum &request) {
CHECK_AUTH();
DialogId dialog_id(request.chat_id_);
auto r_message_ids = messages_manager_->send_message_group(dialog_id, MessageId(request.reply_to_message_id_),
request.disable_notification_, request.from_background_,
std::move(request.input_message_contents_));
if (r_message_ids.is_error()) {
return send_closure(actor_id(this), &Td::send_error, id, r_message_ids.move_as_error());
}
send_closure(actor_id(this), &Td::send_result, id,
messages_manager_->get_messages_object(-1, dialog_id, r_message_ids.ok()));
}
void Td::on_request(uint64 id, td_api::sendBotStartMessage &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.parameter_);
DialogId dialog_id(request.chat_id_);
auto r_new_message_id =
messages_manager_->send_bot_start_message(UserId(request.bot_user_id_), dialog_id, request.parameter_);
if (r_new_message_id.is_error()) {
return send_closure(actor_id(this), &Td::send_error, id, r_new_message_id.move_as_error());
}
CHECK(r_new_message_id.ok().is_valid());
send_closure(actor_id(this), &Td::send_result, id,
messages_manager_->get_message_object({dialog_id, r_new_message_id.ok()}));
}
void Td::on_request(uint64 id, td_api::sendInlineQueryResultMessage &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.result_id_);
DialogId dialog_id(request.chat_id_);
auto r_new_message_id = messages_manager_->send_inline_query_result_message(
dialog_id, MessageId(request.reply_to_message_id_), request.disable_notification_, request.from_background_,
request.query_id_, request.result_id_);
if (r_new_message_id.is_error()) {
return send_closure(actor_id(this), &Td::send_error, id, r_new_message_id.move_as_error());
}
CHECK(r_new_message_id.ok().is_valid());
send_closure(actor_id(this), &Td::send_result, id,
messages_manager_->get_message_object({dialog_id, r_new_message_id.ok()}));
}
void Td::on_request(uint64 id, const td_api::sendChatSetTtlMessage &request) {
CHECK_AUTH();
DialogId dialog_id(request.chat_id_);
auto r_new_message_id = messages_manager_->send_dialog_set_ttl_message(dialog_id, request.ttl_);
if (r_new_message_id.is_error()) {
return send_closure(actor_id(this), &Td::send_error, id, r_new_message_id.move_as_error());
}
CHECK(r_new_message_id.ok().is_valid());
send_closure(actor_id(this), &Td::send_result, id,
messages_manager_->get_message_object({dialog_id, r_new_message_id.ok()}));
}
void Td::on_request(uint64 id, td_api::editMessageText &request) {
CHECK_AUTH();
CREATE_REQUEST(EditMessageTextRequest, request.chat_id_, request.message_id_, std::move(request.reply_markup_),
std::move(request.input_message_content_));
}
void Td::on_request(uint64 id, td_api::editMessageLiveLocation &request) {
CHECK_AUTH();
CREATE_REQUEST(EditMessageLiveLocationRequest, request.chat_id_, request.message_id_,
std::move(request.reply_markup_), std::move(request.location_));
}
void Td::on_request(uint64 id, td_api::editMessageCaption &request) {
CHECK_AUTH();
CLEAN_INPUT_STRING(request.caption_);
CREATE_REQUEST(EditMessageCaptionRequest, request.chat_id_, request.message_id_, std::move(request.reply_markup_),
std::move(request.caption_));
}
void Td::on_request(uint64 id, td_api::editMessageReplyMarkup &request) {
CHECK_AUTH();
CHECK_IS_BOT();
CREATE_REQUEST(EditMessageReplyMarkupRequest, request.chat_id_, request.message_id_,
std::move(request.reply_markup_));
}
void Td::on_request(uint64 id, td_api::editInlineMessageText &request) {
CHECK_AUTH();
CHECK_IS_BOT();
CLEAN_INPUT_STRING(request.inline_message_id_);
CREATE_REQUEST(EditInlineMessageTextRequest, std::move(request.inline_message_id_), std::move(request.reply_markup_),
std::move(request.input_message_content_));
}
void Td::on_request(uint64 id, td_api::editInlineMessageLiveLocation &request) {
CHECK_AUTH();
CHECK_IS_BOT();
CLEAN_INPUT_STRING(request.inline_message_id_);
CREATE_REQUEST(EditInlineMessageLiveLocationRequest, std::move(request.inline_message_id_),
std::move(request.reply_markup_), std::move(request.location_));
}
void Td::on_request(uint64 id, td_api::editInlineMessageCaption &request) {
CHECK_AUTH();
CHECK_IS_BOT();
CLEAN_INPUT_STRING(request.inline_message_id_);
CLEAN_INPUT_STRING(request.caption_);
CREATE_REQUEST(EditInlineMessageCaptionRequest, std::move(request.inline_message_id_),
std::move(request.reply_markup_), std::move(request.caption_));
}
void Td::on_request(uint64 id, td_api::editInlineMessageReplyMarkup &request) {
CHECK_AUTH();
CHECK_IS_BOT();
CLEAN_INPUT_STRING(request.inline_message_id_);
CREATE_REQUEST(EditInlineMessageReplyMarkupRequest, std::move(request.inline_message_id_),
std::move(request.reply_markup_));
}
void Td::on_request(uint64 id, td_api::setGameScore &request) {
CHECK_AUTH();
CHECK_IS_BOT();
CREATE_REQUEST(SetGameScoreRequest, request.chat_id_, request.message_id_, request.edit_message_, request.user_id_,
request.score_, request.force_);
}
void Td::on_request(uint64 id, td_api::setInlineGameScore &request) {
CHECK_AUTH();
CHECK_IS_BOT();
CLEAN_INPUT_STRING(request.inline_message_id_);
CREATE_REQUEST(SetInlineGameScoreRequest, std::move(request.inline_message_id_), request.edit_message_,
request.user_id_, request.score_, request.force_);
}
void Td::on_request(uint64 id, td_api::getGameHighScores &request) {
CHECK_AUTH();
CHECK_IS_BOT();
CREATE_REQUEST(GetGameHighScoresRequest, request.chat_id_, request.message_id_, request.user_id_);
}
void Td::on_request(uint64 id, td_api::getInlineGameHighScores &request) {
CHECK_AUTH();
CHECK_IS_BOT();
CLEAN_INPUT_STRING(request.inline_message_id_);
CREATE_REQUEST(GetInlineGameHighScoresRequest, std::move(request.inline_message_id_), request.user_id_);
}
void Td::on_request(uint64 id, const td_api::deleteChatReplyMarkup &request) {
CHECK_AUTH();
CHECK_IS_USER();
answer_ok_query(
id, messages_manager_->delete_dialog_reply_markup(DialogId(request.chat_id_), MessageId(request.message_id_)));
}
void Td::on_request(uint64 id, td_api::sendChatAction &request) {
CHECK_AUTH();
CREATE_REQUEST(SendChatActionRequest, request.chat_id_, std::move(request.action_));
}
void Td::on_request(uint64 id, td_api::sendChatScreenshotTakenNotification &request) {
CHECK_AUTH();
CHECK_IS_USER();
answer_ok_query(id, messages_manager_->send_screenshot_taken_notification_message(DialogId(request.chat_id_)));
}
void Td::on_request(uint64 id, const td_api::forwardMessages &request) {
CHECK_AUTH();
DialogId dialog_id(request.chat_id_);
auto r_message_ids = messages_manager_->forward_messages(
dialog_id, DialogId(request.from_chat_id_), MessagesManager::get_message_ids(request.message_ids_),
request.disable_notification_, request.from_background_, false, request.as_album_);
if (r_message_ids.is_error()) {
return send_closure(actor_id(this), &Td::send_error, id, r_message_ids.move_as_error());
}
send_closure(actor_id(this), &Td::send_result, id,
messages_manager_->get_messages_object(-1, dialog_id, r_message_ids.ok()));
}
void Td::on_request(uint64 id, td_api::getWebPagePreview &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.message_text_);
CREATE_REQUEST(GetWebPagePreviewRequest, std::move(request.message_text_));
}
void Td::on_request(uint64 id, td_api::getWebPageInstantView &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.url_);
CREATE_REQUEST(GetWebPageInstantViewRequest, std::move(request.url_), request.force_full_);
}
void Td::on_request(uint64 id, const td_api::createPrivateChat &request) {
CHECK_AUTH();
CREATE_REQUEST(CreateChatRequest, DialogId(UserId(request.user_id_)));
}
void Td::on_request(uint64 id, const td_api::createBasicGroupChat &request) {
CHECK_AUTH();
CREATE_REQUEST(CreateChatRequest, DialogId(ChatId(request.basic_group_id_)));
}
void Td::on_request(uint64 id, const td_api::createSupergroupChat &request) {
CHECK_AUTH();
CREATE_REQUEST(CreateChatRequest, DialogId(ChannelId(request.supergroup_id_)));
}
void Td::on_request(uint64 id, td_api::createSecretChat &request) {
CHECK_AUTH();
CREATE_REQUEST(CreateChatRequest, DialogId(SecretChatId(request.secret_chat_id_)));
}
void Td::on_request(uint64 id, td_api::createNewBasicGroupChat &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.title_);
CREATE_REQUEST(CreateNewGroupChatRequest, request.user_ids_, std::move(request.title_));
}
void Td::on_request(uint64 id, td_api::createNewSupergroupChat &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.title_);
CLEAN_INPUT_STRING(request.description_);
CREATE_REQUEST(CreateNewSupergroupChatRequest, std::move(request.title_), !request.is_channel_,
std::move(request.description_));
}
void Td::on_request(uint64 id, td_api::createNewSecretChat &request) {
CHECK_AUTH();
CREATE_REQUEST(CreateNewSecretChatRequest, request.user_id_);
}
void Td::on_request(uint64 id, td_api::createCall &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST_PROMISE(promise);
auto query_promise = PromiseCreator::lambda([promise = std::move(promise)](Result<CallId> result) mutable {
if (result.is_error()) {
promise.set_error(result.move_as_error());
} else {
promise.set_value(result.ok().as_td_api());
}
});
if (!request.protocol_) {
return query_promise.set_error(Status::Error(5, "CallProtocol must not be empty"));
}
UserId user_id(request.user_id_);
auto input_user = contacts_manager_->get_input_user(user_id);
if (input_user == nullptr) {
return query_promise.set_error(Status::Error(6, "User not found"));
}
if (!G()->shared_config().get_option_boolean("calls_enabled")) {
return query_promise.set_error(Status::Error(7, "Calls are not enabled for the current user"));
}
send_closure(G()->call_manager(), &CallManager::create_call, user_id, std::move(input_user),
CallProtocol::from_td_api(*request.protocol_), std::move(query_promise));
}
void Td::on_request(uint64 id, td_api::discardCall &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST_PROMISE(promise);
auto query_promise = PromiseCreator::lambda([promise = std::move(promise)](Result<> result) mutable {
if (result.is_error()) {
promise.set_error(result.move_as_error());
} else {
promise.set_value(make_tl_object<td_api::ok>());
}
});
send_closure(G()->call_manager(), &CallManager::discard_call, CallId(request.call_id_), request.is_disconnected_,
request.duration_, request.connection_id_, std::move(query_promise));
}
void Td::on_request(uint64 id, td_api::acceptCall &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST_PROMISE(promise);
auto query_promise = PromiseCreator::lambda([promise = std::move(promise)](Result<> result) mutable {
if (result.is_error()) {
promise.set_error(result.move_as_error());
} else {
promise.set_value(make_tl_object<td_api::ok>());
}
});
if (!request.protocol_) {
return query_promise.set_error(Status::Error(5, "Call protocol must not be empty"));
}
send_closure(G()->call_manager(), &CallManager::accept_call, CallId(request.call_id_),
CallProtocol::from_td_api(*request.protocol_), std::move(query_promise));
}
void Td::on_request(uint64 id, td_api::sendCallRating &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.comment_);
CREATE_REQUEST_PROMISE(promise);
auto query_promise = PromiseCreator::lambda([promise = std::move(promise)](Result<> result) mutable {
if (result.is_error()) {
promise.set_error(result.move_as_error());
} else {
promise.set_value(make_tl_object<td_api::ok>());
}
});
send_closure(G()->call_manager(), &CallManager::rate_call, CallId(request.call_id_), request.rating_,
std::move(request.comment_), std::move(query_promise));
}
void Td::on_request(uint64 id, td_api::sendCallDebugInformation &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.debug_information_);
CREATE_REQUEST_PROMISE(promise);
auto query_promise = PromiseCreator::lambda([promise = std::move(promise)](Result<> result) mutable {
if (result.is_error()) {
promise.set_error(result.move_as_error());
} else {
promise.set_value(make_tl_object<td_api::ok>());
}
});
send_closure(G()->call_manager(), &CallManager::send_call_debug_information, CallId(request.call_id_),
std::move(request.debug_information_), std::move(query_promise));
}
void Td::on_request(uint64 id, const td_api::upgradeBasicGroupChatToSupergroupChat &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(UpgradeGroupChatToSupergroupChatRequest, request.chat_id_);
}
void Td::on_request(uint64 id, td_api::setChatTitle &request) {
CHECK_AUTH();
CLEAN_INPUT_STRING(request.title_);
CREATE_REQUEST(SetChatTitleRequest, request.chat_id_, std::move(request.title_));
}
void Td::on_request(uint64 id, td_api::setChatPhoto &request) {
CHECK_AUTH();
CREATE_REQUEST(SetChatPhotoRequest, request.chat_id_, std::move(request.photo_));
}
void Td::on_request(uint64 id, td_api::setChatDraftMessage &request) {
CHECK_AUTH();
CHECK_IS_USER();
answer_ok_query(
id, messages_manager_->set_dialog_draft_message(DialogId(request.chat_id_), std::move(request.draft_message_)));
}
void Td::on_request(uint64 id, const td_api::toggleChatIsPinned &request) {
CHECK_AUTH();
CHECK_IS_USER();
answer_ok_query(id, messages_manager_->toggle_dialog_is_pinned(DialogId(request.chat_id_), request.is_pinned_));
}
void Td::on_request(uint64 id, const td_api::setPinnedChats &request) {
CHECK_AUTH();
CHECK_IS_USER();
answer_ok_query(id, messages_manager_->set_pinned_dialogs(
transform(request.chat_ids_, [](int64 chat_id) { return DialogId(chat_id); })));
}
void Td::on_request(uint64 id, td_api::setChatClientData &request) {
CHECK_AUTH();
answer_ok_query(
id, messages_manager_->set_dialog_client_data(DialogId(request.chat_id_), std::move(request.client_data_)));
}
void Td::on_request(uint64 id, const td_api::addChatMember &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(AddChatMemberRequest, request.chat_id_, request.user_id_, request.forward_limit_);
}
void Td::on_request(uint64 id, const td_api::addChatMembers &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(AddChatMembersRequest, request.chat_id_, request.user_ids_);
}
void Td::on_request(uint64 id, td_api::setChatMemberStatus &request) {
CHECK_AUTH();
CREATE_REQUEST(SetChatMemberStatusRequest, request.chat_id_, request.user_id_, std::move(request.status_));
}
void Td::on_request(uint64 id, const td_api::getChatMember &request) {
CHECK_AUTH();
CREATE_REQUEST(GetChatMemberRequest, request.chat_id_, request.user_id_);
}
void Td::on_request(uint64 id, td_api::searchChatMembers &request) {
CHECK_AUTH();
CLEAN_INPUT_STRING(request.query_);
CREATE_REQUEST(SearchChatMembersRequest, request.chat_id_, std::move(request.query_), request.limit_);
}
void Td::on_request(uint64 id, td_api::getChatAdministrators &request) {
CHECK_AUTH();
CREATE_REQUEST(GetChatAdministratorsRequest, request.chat_id_);
}
void Td::on_request(uint64 id, const td_api::generateChatInviteLink &request) {
CHECK_AUTH();
CREATE_REQUEST(GenerateChatInviteLinkRequest, request.chat_id_);
}
void Td::on_request(uint64 id, td_api::checkChatInviteLink &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.invite_link_);
CREATE_REQUEST(CheckChatInviteLinkRequest, request.invite_link_);
}
void Td::on_request(uint64 id, td_api::joinChatByInviteLink &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.invite_link_);
CREATE_REQUEST(JoinChatByInviteLinkRequest, request.invite_link_);
}
void Td::on_request(uint64 id, td_api::getChatEventLog &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.query_);
CREATE_REQUEST(GetChatEventLogRequest, request.chat_id_, std::move(request.query_), request.from_event_id_,
request.limit_, std::move(request.filters_), std::move(request.user_ids_));
}
void Td::on_request(uint64 id, const td_api::downloadFile &request) {
CHECK_AUTH();
auto priority = request.priority_;
if (!(1 <= priority && priority <= 32)) {
return send_error_raw(id, 5, "Download priority must be in [1;32] range");
}
file_manager_->download(FileId(request.file_id_), download_file_callback_, priority);
auto file = file_manager_->get_file_object(FileId(request.file_id_), false);
if (file->id_ == 0) {
return send_error_raw(id, 400, "Invalid file id");
}
send_closure(actor_id(this), &Td::send_result, id, std::move(file));
}
void Td::on_request(uint64 id, const td_api::cancelDownloadFile &request) {
CHECK_AUTH();
file_manager_->download(FileId(request.file_id_), nullptr, 0);
send_closure(actor_id(this), &Td::send_result, id, make_tl_object<td_api::ok>());
}
void Td::on_request(uint64 id, td_api::uploadFile &request) {
CHECK_AUTH();
auto priority = request.priority_;
if (!(1 <= priority && priority <= 32)) {
return send_error_raw(id, 5, "Upload priority must be in [1;32] range");
}
auto file_type = request.file_type_ == nullptr ? FileType::Temp : from_td_api(*request.file_type_);
bool is_secret = file_type == FileType::Encrypted || file_type == FileType::EncryptedThumbnail;
auto r_file_id = file_manager_->get_input_file_id(file_type, request.file_, DialogId(), false, is_secret, true);
if (r_file_id.is_error()) {
return send_error_raw(id, 400, r_file_id.error().message());
}
auto file_id = r_file_id.ok();
auto upload_file_id = file_manager_->dup_file_id(file_id);
file_manager_->upload(upload_file_id, upload_file_callback_, priority, 0);
send_closure(actor_id(this), &Td::send_result, id, file_manager_->get_file_object(upload_file_id, false));
}
void Td::on_request(uint64 id, const td_api::cancelUploadFile &request) {
CHECK_AUTH();
file_manager_->upload(FileId(request.file_id_), nullptr, 0, 0);
send_closure(actor_id(this), &Td::send_result, id, make_tl_object<td_api::ok>());
}
void Td::on_request(uint64 id, const td_api::setFileGenerationProgress &request) {
CHECK_AUTH();
CREATE_REQUEST_PROMISE(promise);
auto query_promise = PromiseCreator::lambda([promise = std::move(promise)](Result<> result) mutable {
if (result.is_error()) {
promise.set_error(result.move_as_error());
} else {
promise.set_value(make_tl_object<td_api::ok>());
}
});
send_closure(file_manager_actor_, &FileManager::external_file_generate_progress, request.generation_id_,
request.expected_size_, request.local_prefix_size_, std::move(query_promise));
}
void Td::on_request(uint64 id, td_api::finishFileGeneration &request) {
CHECK_AUTH();
Status status;
if (request.error_ != nullptr) {
CLEAN_INPUT_STRING(request.error_->message_);
status = Status::Error(request.error_->code_, request.error_->message_);
}
CREATE_REQUEST_PROMISE(promise);
auto query_promise = PromiseCreator::lambda([promise = std::move(promise)](Result<> result) mutable {
if (result.is_error()) {
promise.set_error(result.move_as_error());
} else {
promise.set_value(make_tl_object<td_api::ok>());
}
});
send_closure(file_manager_actor_, &FileManager::external_file_generate_finish, request.generation_id_,
std::move(status), std::move(query_promise));
}
void Td::on_request(uint64 id, const td_api::deleteFile &request) {
CHECK_AUTH();
CREATE_REQUEST_PROMISE(promise);
auto query_promise = PromiseCreator::lambda([promise = std::move(promise)](Result<> result) mutable {
if (result.is_error()) {
promise.set_error(result.move_as_error());
} else {
promise.set_value(make_tl_object<td_api::ok>());
}
});
send_closure(file_manager_actor_, &FileManager::delete_file, FileId(request.file_id_), std::move(query_promise),
"td_api::deleteFile");
}
void Td::on_request(uint64 id, const td_api::blockUser &request) {
CHECK_AUTH();
CHECK_IS_USER();
answer_ok_query(id, contacts_manager_->block_user(UserId(request.user_id_)));
}
void Td::on_request(uint64 id, const td_api::unblockUser &request) {
CHECK_AUTH();
CHECK_IS_USER();
answer_ok_query(id, contacts_manager_->unblock_user(UserId(request.user_id_)));
}
void Td::on_request(uint64 id, const td_api::getBlockedUsers &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(GetBlockedUsersRequest, request.offset_, request.limit_);
}
void Td::on_request(uint64 id, td_api::importContacts &request) {
CHECK_AUTH();
CHECK_IS_USER();
for (auto &contact : request.contacts_) {
if (contact == nullptr) {
return send_error_raw(id, 5, "Contact must not be empty");
}
CLEAN_INPUT_STRING(contact->phone_number_);
CLEAN_INPUT_STRING(contact->first_name_);
CLEAN_INPUT_STRING(contact->last_name_);
}
CREATE_REQUEST(ImportContactsRequest, std::move(request.contacts_));
}
void Td::on_request(uint64 id, td_api::searchContacts &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.query_);
CREATE_REQUEST(SearchContactsRequest, request.query_, request.limit_);
}
void Td::on_request(uint64 id, td_api::removeContacts &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(RemoveContactsRequest, std::move(request.user_ids_));
}
void Td::on_request(uint64 id, const td_api::getImportedContactCount &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_NO_ARGS_REQUEST(GetImportedContactCountRequest);
}
void Td::on_request(uint64 id, td_api::changeImportedContacts &request) {
CHECK_AUTH();
CHECK_IS_USER();
for (auto &contact : request.contacts_) {
if (contact == nullptr) {
return send_error_raw(id, 5, "Contact must not be empty");
}
CLEAN_INPUT_STRING(contact->phone_number_);
CLEAN_INPUT_STRING(contact->first_name_);
CLEAN_INPUT_STRING(contact->last_name_);
}
CREATE_REQUEST(ChangeImportedContactsRequest, std::move(request.contacts_));
}
void Td::on_request(uint64 id, const td_api::clearImportedContacts &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_NO_ARGS_REQUEST(ClearImportedContactsRequest);
}
void Td::on_request(uint64 id, const td_api::getRecentInlineBots &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_NO_ARGS_REQUEST(GetRecentInlineBotsRequest);
}
void Td::on_request(uint64 id, td_api::setName &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.first_name_);
CLEAN_INPUT_STRING(request.last_name_);
CREATE_REQUEST(SetNameRequest, std::move(request.first_name_), std::move(request.last_name_));
}
void Td::on_request(uint64 id, td_api::setBio &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.bio_);
CREATE_REQUEST(SetBioRequest, std::move(request.bio_));
}
void Td::on_request(uint64 id, td_api::setUsername &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.username_);
CREATE_REQUEST(SetUsernameRequest, std::move(request.username_));
}
void Td::on_request(uint64 id, td_api::setProfilePhoto &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(SetProfilePhotoRequest, std::move(request.photo_));
}
void Td::on_request(uint64 id, const td_api::deleteProfilePhoto &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(DeleteProfilePhotoRequest, request.profile_photo_id_);
}
void Td::on_request(uint64 id, const td_api::getUserProfilePhotos &request) {
CHECK_AUTH();
CREATE_REQUEST(GetUserProfilePhotosRequest, request.user_id_, request.offset_, request.limit_);
}
void Td::on_request(uint64 id, const td_api::toggleBasicGroupAdministrators &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(ToggleGroupAdministratorsRequest, request.basic_group_id_, request.everyone_is_administrator_);
}
void Td::on_request(uint64 id, td_api::setSupergroupUsername &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.username_);
CREATE_REQUEST(SetSupergroupUsernameRequest, request.supergroup_id_, std::move(request.username_));
}
void Td::on_request(uint64 id, const td_api::setSupergroupStickerSet &request) {
CHECK_AUTH();
CREATE_REQUEST(SetSupergroupStickerSetRequest, request.supergroup_id_, request.sticker_set_id_);
}
void Td::on_request(uint64 id, const td_api::toggleSupergroupInvites &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(ToggleSupergroupInvitesRequest, request.supergroup_id_, request.anyone_can_invite_);
}
void Td::on_request(uint64 id, const td_api::toggleSupergroupSignMessages &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(ToggleSupergroupSignMessagesRequest, request.supergroup_id_, request.sign_messages_);
}
void Td::on_request(uint64 id, const td_api::toggleSupergroupIsAllHistoryAvailable &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(ToggleSupergroupIsAllHistoryAvailableRequest, request.supergroup_id_,
request.is_all_history_available_);
}
void Td::on_request(uint64 id, td_api::setSupergroupDescription &request) {
CHECK_AUTH();
CLEAN_INPUT_STRING(request.description_);
CREATE_REQUEST(SetSupergroupDescriptionRequest, request.supergroup_id_, std::move(request.description_));
}
void Td::on_request(uint64 id, const td_api::pinSupergroupMessage &request) {
CHECK_AUTH();
CREATE_REQUEST(PinSupergroupMessageRequest, request.supergroup_id_, request.message_id_,
request.disable_notification_);
}
void Td::on_request(uint64 id, const td_api::unpinSupergroupMessage &request) {
CHECK_AUTH();
CREATE_REQUEST(UnpinSupergroupMessageRequest, request.supergroup_id_);
}
void Td::on_request(uint64 id, const td_api::reportSupergroupSpam &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(ReportSupergroupSpamRequest, request.supergroup_id_, request.user_id_, request.message_ids_);
}
void Td::on_request(uint64 id, td_api::getSupergroupMembers &request) {
CHECK_AUTH();
CREATE_REQUEST(GetSupergroupMembersRequest, request.supergroup_id_, std::move(request.filter_), request.offset_,
request.limit_);
}
void Td::on_request(uint64 id, const td_api::deleteSupergroup &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(DeleteSupergroupRequest, request.supergroup_id_);
}
void Td::on_request(uint64 id, td_api::closeSecretChat &request) {
CHECK_AUTH();
CREATE_REQUEST_PROMISE(promise);
auto query_promise = PromiseCreator::lambda([promise = std::move(promise)](Result<> result) mutable {
if (result.is_error()) {
promise.set_error(result.move_as_error());
} else {
promise.set_value(make_tl_object<td_api::ok>());
}
});
send_closure(secret_chats_manager_, &SecretChatsManager::cancel_chat, SecretChatId(request.secret_chat_id_),
std::move(query_promise));
}
void Td::on_request(uint64 id, td_api::getStickers &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.emoji_);
CREATE_REQUEST(GetStickersRequest, std::move(request.emoji_), request.limit_);
}
void Td::on_request(uint64 id, const td_api::getInstalledStickerSets &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(GetInstalledStickerSetsRequest, request.is_masks_);
}
void Td::on_request(uint64 id, const td_api::getArchivedStickerSets &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(GetArchivedStickerSetsRequest, request.is_masks_, request.offset_sticker_set_id_, request.limit_);
}
void Td::on_request(uint64 id, const td_api::getTrendingStickerSets &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_NO_ARGS_REQUEST(GetTrendingStickerSetsRequest);
}
void Td::on_request(uint64 id, const td_api::getAttachedStickerSets &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(GetAttachedStickerSetsRequest, request.file_id_);
}
void Td::on_request(uint64 id, const td_api::getStickerSet &request) {
CHECK_AUTH();
CREATE_REQUEST(GetStickerSetRequest, request.set_id_);
}
void Td::on_request(uint64 id, td_api::searchStickerSet &request) {
CHECK_AUTH();
CLEAN_INPUT_STRING(request.name_);
CREATE_REQUEST(SearchStickerSetRequest, std::move(request.name_));
}
void Td::on_request(uint64 id, const td_api::changeStickerSet &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(ChangeStickerSetRequest, request.set_id_, request.is_installed_, request.is_archived_);
}
void Td::on_request(uint64 id, const td_api::viewTrendingStickerSets &request) {
CHECK_AUTH();
CHECK_IS_USER();
stickers_manager_->view_featured_sticker_sets(request.sticker_set_ids_);
send_closure(actor_id(this), &Td::send_result, id, make_tl_object<td_api::ok>());
}
void Td::on_request(uint64 id, td_api::reorderInstalledStickerSets &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(ReorderInstalledStickerSetsRequest, request.is_masks_, std::move(request.sticker_set_ids_));
}
void Td::on_request(uint64 id, td_api::uploadStickerFile &request) {
CHECK_AUTH();
CHECK_IS_BOT();
CREATE_REQUEST(UploadStickerFileRequest, request.user_id_, std::move(request.png_sticker_));
}
void Td::on_request(uint64 id, td_api::createNewStickerSet &request) {
CHECK_AUTH();
CHECK_IS_BOT();
CLEAN_INPUT_STRING(request.title_);
CLEAN_INPUT_STRING(request.name_);
CREATE_REQUEST(CreateNewStickerSetRequest, request.user_id_, std::move(request.title_), std::move(request.name_),
request.is_masks_, std::move(request.stickers_));
}
void Td::on_request(uint64 id, td_api::addStickerToSet &request) {
CHECK_AUTH();
CHECK_IS_BOT();
CLEAN_INPUT_STRING(request.name_);
CREATE_REQUEST(AddStickerToSetRequest, request.user_id_, std::move(request.name_), std::move(request.sticker_));
}
void Td::on_request(uint64 id, td_api::setStickerPositionInSet &request) {
CHECK_AUTH();
CHECK_IS_BOT();
CREATE_REQUEST(SetStickerPositionInSetRequest, std::move(request.sticker_), request.position_);
}
void Td::on_request(uint64 id, td_api::removeStickerFromSet &request) {
CHECK_AUTH();
CHECK_IS_BOT();
CREATE_REQUEST(RemoveStickerFromSetRequest, std::move(request.sticker_));
}
void Td::on_request(uint64 id, const td_api::getRecentStickers &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(GetRecentStickersRequest, request.is_attached_);
}
void Td::on_request(uint64 id, td_api::addRecentSticker &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(AddRecentStickerRequest, request.is_attached_, std::move(request.sticker_));
}
void Td::on_request(uint64 id, td_api::removeRecentSticker &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(RemoveRecentStickerRequest, request.is_attached_, std::move(request.sticker_));
}
void Td::on_request(uint64 id, td_api::clearRecentStickers &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(ClearRecentStickersRequest, request.is_attached_);
}
void Td::on_request(uint64 id, const td_api::getFavoriteStickers &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_NO_ARGS_REQUEST(GetFavoriteStickersRequest);
}
void Td::on_request(uint64 id, td_api::addFavoriteSticker &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(AddFavoriteStickerRequest, std::move(request.sticker_));
}
void Td::on_request(uint64 id, td_api::removeFavoriteSticker &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(RemoveFavoriteStickerRequest, std::move(request.sticker_));
}
void Td::on_request(uint64 id, td_api::getStickerEmojis &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(GetStickerEmojisRequest, std::move(request.sticker_));
}
void Td::on_request(uint64 id, const td_api::getSavedAnimations &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_NO_ARGS_REQUEST(GetSavedAnimationsRequest);
}
void Td::on_request(uint64 id, td_api::addSavedAnimation &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(AddSavedAnimationRequest, std::move(request.animation_));
}
void Td::on_request(uint64 id, td_api::removeSavedAnimation &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(RemoveSavedAnimationRequest, std::move(request.animation_));
}
void Td::on_request(uint64 id, const td_api::getNotificationSettings &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(GetNotificationSettingsRequest, messages_manager_->get_notification_settings_scope(request.scope_));
}
void Td::on_request(uint64 id, const td_api::getChatReportSpamState &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(GetChatReportSpamStateRequest, request.chat_id_);
}
void Td::on_request(uint64 id, const td_api::changeChatReportSpamState &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(ChangeChatReportSpamStateRequest, request.chat_id_, request.is_spam_chat_);
}
void Td::on_request(uint64 id, td_api::reportChat &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(ReportChatRequest, request.chat_id_, std::move(request.reason_));
}
void Td::on_request(uint64 id, td_api::setNotificationSettings &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.notification_settings_->sound_);
answer_ok_query(id, messages_manager_->set_notification_settings(
messages_manager_->get_notification_settings_scope(request.scope_),
std::move(request.notification_settings_)));
}
void Td::on_request(uint64 id, const td_api::resetAllNotificationSettings &request) {
CHECK_AUTH();
CHECK_IS_USER();
messages_manager_->reset_all_notification_settings();
send_closure(actor_id(this), &Td::send_result, id, make_tl_object<td_api::ok>());
}
void Td::on_request(uint64 id, td_api::getOption &request) {
CLEAN_INPUT_STRING(request.name_);
tl_object_ptr<td_api::OptionValue> option_value;
switch (request.name_[0]) {
case 'o':
if (request.name_ == "online") {
option_value = make_tl_object<td_api::optionValueBoolean>(is_online_);
}
break;
case 'v':
if (request.name_ == "version") {
option_value = make_tl_object<td_api::optionValueString>(tdlib_version);
}
break;
}
if (option_value == nullptr) {
option_value = G()->shared_config().get_option_value(request.name_);
}
send_closure(actor_id(this), &Td::send_result, id, std::move(option_value));
}
void Td::on_request(uint64 id, td_api::setOption &request) {
CLEAN_INPUT_STRING(request.name_);
int32 value_constructor_id = request.value_ == nullptr ? td_api::optionValueEmpty::ID : request.value_->get_id();
auto set_integer_option = [&](Slice name, int32 min = 0, int32 max = std::numeric_limits<int32>::max()) {
if (request.name_ == name) {
if (value_constructor_id != td_api::optionValueInteger::ID &&
value_constructor_id != td_api::optionValueEmpty::ID) {
send_error_raw(id, 3, PSLICE() << "Option \"" << name << "\" must have integer value");
return true;
}
if (value_constructor_id == td_api::optionValueEmpty::ID) {
G()->shared_config().set_option_empty(name);
} else {
int32 value = static_cast<td_api::optionValueInteger *>(request.value_.get())->value_;
if (value < min || value > max) {
send_error_raw(id, 3,
PSLICE() << "Option's \"" << name << "\" value " << value << " is outside of a valid range ["
<< min << ", " << max << "]");
return true;
}
G()->shared_config().set_option_integer(name, std::max(std::min(value, max), min));
}
send_closure(actor_id(this), &Td::send_result, id, make_tl_object<td_api::ok>());
return true;
}
return false;
};
auto set_boolean_option = [&](Slice name) {
if (request.name_ == name) {
if (value_constructor_id != td_api::optionValueBoolean::ID &&
value_constructor_id != td_api::optionValueEmpty::ID) {
send_error_raw(id, 3, PSLICE() << "Option \"" << name << "\" must have boolean value");
return true;
}
if (value_constructor_id == td_api::optionValueEmpty::ID) {
G()->shared_config().set_option_empty(name);
} else {
bool value = static_cast<td_api::optionValueBoolean *>(request.value_.get())->value_;
G()->shared_config().set_option_boolean(name, value);
}
send_closure(actor_id(this), &Td::send_result, id, make_tl_object<td_api::ok>());
return true;
}
return false;
};
switch (request.name_[0]) {
case 'd':
if (set_boolean_option("disable_contact_registered_notifications")) {
return;
}
break;
case 'o':
if (request.name_ == "online") {
if (value_constructor_id != td_api::optionValueBoolean::ID &&
value_constructor_id != td_api::optionValueEmpty::ID) {
return send_error_raw(id, 3, "Option \"online\" must have boolean value");
}
bool is_online = value_constructor_id == td_api::optionValueEmpty::ID ||
static_cast<const td_api::optionValueBoolean *>(request.value_.get())->value_;
if (!auth_manager_->is_bot()) {
send_closure(G()->state_manager(), &StateManager::on_online, is_online);
}
if (is_online != is_online_) {
is_online_ = is_online;
on_online_updated(true, true);
}
return send_closure(actor_id(this), &Td::send_result, id, make_tl_object<td_api::ok>());
}
break;
case 's':
if (set_integer_option("session_count", 0, 50)) {
return;
}
if (set_integer_option("storage_max_files_size")) {
return;
}
if (set_integer_option("storage_max_time_from_last_access")) {
return;
}
if (set_integer_option("storage_max_file_count")) {
return;
}
if (set_integer_option("storage_immunity_delay")) {
return;
}
break;
case 'X':
case 'x': {
if (request.name_.size() > 255) {
return send_error_raw(id, 3, "Option name is too long");
}
switch (value_constructor_id) {
case td_api::optionValueBoolean::ID:
G()->shared_config().set_option_boolean(
request.name_, static_cast<const td_api::optionValueBoolean *>(request.value_.get())->value_);
break;
case td_api::optionValueEmpty::ID:
G()->shared_config().set_option_empty(request.name_);
break;
case td_api::optionValueInteger::ID:
G()->shared_config().set_option_integer(
request.name_, static_cast<const td_api::optionValueInteger *>(request.value_.get())->value_);
break;
case td_api::optionValueString::ID:
G()->shared_config().set_option_string(
request.name_, static_cast<const td_api::optionValueString *>(request.value_.get())->value_);
break;
default:
UNREACHABLE();
}
return send_closure(actor_id(this), &Td::send_result, id, make_tl_object<td_api::ok>());
}
case 'u':
if (set_boolean_option("use_pfs")) {
return;
}
if (set_boolean_option("use_quick_ack")) {
return;
}
if (set_boolean_option("use_storage_optimizer")) {
return;
}
break;
}
return send_error_raw(id, 3, "Option can't be set");
}
void Td::on_request(uint64 id, td_api::getInlineQueryResults &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.query_);
CLEAN_INPUT_STRING(request.offset_);
CREATE_REQUEST(GetInlineQueryResultsRequest, request.bot_user_id_, request.chat_id_, request.user_location_,
std::move(request.query_), std::move(request.offset_));
}
void Td::on_request(uint64 id, td_api::answerInlineQuery &request) {
CHECK_AUTH();
CHECK_IS_BOT();
CLEAN_INPUT_STRING(request.next_offset_);
CLEAN_INPUT_STRING(request.switch_pm_text_);
CLEAN_INPUT_STRING(request.switch_pm_parameter_);
CREATE_REQUEST(AnswerInlineQueryRequest, request.inline_query_id_, request.is_personal_, std::move(request.results_),
request.cache_time_, std::move(request.next_offset_), std::move(request.switch_pm_text_),
std::move(request.switch_pm_parameter_));
}
void Td::on_request(uint64 id, td_api::getCallbackQueryAnswer &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(GetCallbackQueryAnswerRequest, request.chat_id_, request.message_id_, std::move(request.payload_));
}
void Td::on_request(uint64 id, td_api::answerCallbackQuery &request) {
CHECK_AUTH();
CHECK_IS_BOT();
CLEAN_INPUT_STRING(request.text_);
CLEAN_INPUT_STRING(request.url_);
CREATE_REQUEST(AnswerCallbackQueryRequest, request.callback_query_id_, std::move(request.text_), request.show_alert_,
std::move(request.url_), request.cache_time_);
}
void Td::on_request(uint64 id, td_api::answerShippingQuery &request) {
CHECK_AUTH();
CHECK_IS_BOT();
CLEAN_INPUT_STRING(request.error_message_);
CREATE_REQUEST(AnswerShippingQueryRequest, request.shipping_query_id_, std::move(request.shipping_options_),
std::move(request.error_message_));
}
void Td::on_request(uint64 id, td_api::answerPreCheckoutQuery &request) {
CHECK_AUTH();
CHECK_IS_BOT();
CLEAN_INPUT_STRING(request.error_message_);
CREATE_REQUEST(AnswerPreCheckoutQueryRequest, request.pre_checkout_query_id_, std::move(request.error_message_));
}
void Td::on_request(uint64 id, const td_api::getPaymentForm &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(GetPaymentFormRequest, request.chat_id_, request.message_id_);
}
void Td::on_request(uint64 id, td_api::validateOrderInfo &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(ValidateOrderInfoRequest, request.chat_id_, request.message_id_, std::move(request.order_info_),
request.allow_save_);
}
void Td::on_request(uint64 id, td_api::sendPaymentForm &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.order_info_id_);
CLEAN_INPUT_STRING(request.shipping_option_id_);
if (request.credentials_ == nullptr) {
return send_error_raw(id, 400, "Input payments credentials must not be empty");
}
CREATE_REQUEST(SendPaymentFormRequest, request.chat_id_, request.message_id_, std::move(request.order_info_id_),
std::move(request.shipping_option_id_), std::move(request.credentials_));
}
void Td::on_request(uint64 id, const td_api::getPaymentReceipt &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_REQUEST(GetPaymentReceiptRequest, request.chat_id_, request.message_id_);
}
void Td::on_request(uint64 id, const td_api::getSavedOrderInfo &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_NO_ARGS_REQUEST(GetSavedOrderInfoRequest);
}
void Td::on_request(uint64 id, const td_api::deleteSavedOrderInfo &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_NO_ARGS_REQUEST(DeleteSavedOrderInfoRequest);
}
void Td::on_request(uint64 id, const td_api::deleteSavedCredentials &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_NO_ARGS_REQUEST(DeleteSavedCredentialsRequest);
}
void Td::on_request(uint64 id, const td_api::getSupportUser &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_NO_ARGS_REQUEST(GetSupportUserRequest);
}
void Td::on_request(uint64 id, const td_api::getWallpapers &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_NO_ARGS_REQUEST(GetWallpapersRequest);
}
void Td::on_request(uint64 id, td_api::getRecentlyVisitedTMeUrls &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.referrer_);
CREATE_REQUEST(GetRecentlyVisitedTMeUrlsRequest, std::move(request.referrer_));
}
void Td::on_request(uint64 id, td_api::setBotUpdatesStatus &request) {
CHECK_AUTH();
CHECK_IS_BOT();
CLEAN_INPUT_STRING(request.error_message_);
create_handler<SetBotUpdatesStatusQuery>()->send(request.pending_update_count_, request.error_message_);
send_closure(actor_id(this), &Td::send_result, id, make_tl_object<td_api::ok>());
}
void Td::on_request(uint64 id, td_api::sendCustomRequest &request) {
CHECK_AUTH();
CHECK_IS_BOT();
CLEAN_INPUT_STRING(request.method_);
CLEAN_INPUT_STRING(request.parameters_);
CREATE_REQUEST(SendCustomRequestRequest, std::move(request.method_), std::move(request.parameters_));
}
void Td::on_request(uint64 id, td_api::answerCustomQuery &request) {
CHECK_AUTH();
CHECK_IS_BOT();
CLEAN_INPUT_STRING(request.data_);
CREATE_REQUEST(AnswerCustomQueryRequest, request.custom_query_id_, std::move(request.data_));
}
void Td::on_request(uint64 id, const td_api::setAlarm &request) {
if (request.seconds_ < 0 || request.seconds_ > 3e9) {
return send_error_raw(id, 400, "Wrong parameter seconds specified");
}
alarm_timeout_.set_timeout_in(static_cast<int64>(id), request.seconds_);
}
void Td::on_request(uint64 id, td_api::searchHashtags &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.prefix_);
CREATE_REQUEST_PROMISE(promise);
auto query_promise =
PromiseCreator::lambda([promise = std::move(promise)](Result<std::vector<string>> result) mutable {
if (result.is_error()) {
promise.set_error(result.move_as_error());
} else {
promise.set_value(make_tl_object<td_api::hashtags>(result.move_as_ok()));
}
});
send_closure(hashtag_hints_, &HashtagHints::query, std::move(request.prefix_), request.limit_,
std::move(query_promise));
}
void Td::on_request(uint64 id, td_api::removeRecentHashtag &request) {
CHECK_AUTH();
CHECK_IS_USER();
CLEAN_INPUT_STRING(request.hashtag_);
CREATE_REQUEST_PROMISE(promise);
auto query_promise = PromiseCreator::lambda([promise = std::move(promise)](Result<> result) mutable {
if (result.is_error()) {
promise.set_error(result.move_as_error());
} else {
promise.set_value(make_tl_object<td_api::ok>());
}
});
send_closure(hashtag_hints_, &HashtagHints::remove_hashtag, std::move(request.hashtag_), std::move(query_promise));
}
void Td::on_request(uint64 id, const td_api::getInviteText &request) {
CHECK_AUTH();
CHECK_IS_USER();
CREATE_NO_ARGS_REQUEST(GetInviteTextRequest);
}
void Td::on_request(uint64 id, const td_api::getTermsOfService &request) {
CREATE_NO_ARGS_REQUEST(GetTermsOfServiceRequest);
}
void Td::on_request(uint64 id, const td_api::getProxy &request) {
CREATE_REQUEST_PROMISE(promise);
auto query_promise = PromiseCreator::lambda([promise = std::move(promise)](Result<Proxy> result) mutable {
if (result.is_error()) {
promise.set_error(result.move_as_error());
} else {
promise.set_value(result.move_as_ok().as_td_api());
}
});
send_closure(G()->connection_creator(), &ConnectionCreator::get_proxy, std::move(query_promise));
}
void Td::on_request(uint64 id, const td_api::setProxy &request) {
CREATE_REQUEST_PROMISE(promise);
send_closure(G()->connection_creator(), &ConnectionCreator::set_proxy, Proxy::from_td_api(request.proxy_));
promise.set_value(make_tl_object<td_api::ok>());
}
void Td::on_request(uint64 id, const td_api::getTextEntities &request) {
// don't check authorization state
send_result(id, do_static_request(request));
}
void Td::on_request(uint64 id, const td_api::getFileMimeType &request) {
// don't check authorization state
send_result(id, do_static_request(request));
}
void Td::on_request(uint64 id, const td_api::getFileExtension &request) {
// don't check authorization state
send_result(id, do_static_request(request));
}
template <class T>
td_api::object_ptr<td_api::Object> Td::do_static_request(const T &) {
return create_error_raw(400, "Function can't be executed synchronously");
}
td_api::object_ptr<td_api::Object> Td::do_static_request(const td_api::getTextEntities &request) {
if (!check_utf8(request.text_)) {
return create_error_raw(400, "Text must be encoded in UTF-8");
}
auto text_entities = find_entities(request.text_, false);
return make_tl_object<td_api::textEntities>(get_text_entities_object(text_entities));
}
td_api::object_ptr<td_api::Object> Td::do_static_request(const td_api::getFileMimeType &request) {
// don't check file name UTF-8 correctness
return make_tl_object<td_api::text>(MimeType::from_extension(PathView(request.file_name_).extension()));
}
td_api::object_ptr<td_api::Object> Td::do_static_request(const td_api::getFileExtension &request) {
// don't check MIME type UTF-8 correctness
return make_tl_object<td_api::text>(MimeType::to_extension(request.mime_type_));
}
// test
void Td::on_request(uint64 id, td_api::testNetwork &request) {
create_handler<TestQuery>(id)->send();
}
void Td::on_request(uint64 id, td_api::testGetDifference &request) {
CHECK_AUTH();
updates_manager_->get_difference("testGetDifference");
send_closure(actor_id(this), &Td::send_result, id, make_tl_object<td_api::ok>());
}
void Td::on_request(uint64 id, td_api::testUseUpdate &request) {
send_closure(actor_id(this), &Td::send_result, id, nullptr);
}
void Td::on_request(uint64 id, td_api::testUseError &request) {
send_closure(actor_id(this), &Td::send_result, id, nullptr);
}
void Td::on_request(uint64 id, td_api::testCallEmpty &request) {
send_closure(actor_id(this), &Td::send_result, id, make_tl_object<td_api::ok>());
}
void Td::on_request(uint64 id, td_api::testSquareInt &request) {
send_closure(actor_id(this), &Td::send_result, id, make_tl_object<td_api::testInt>(request.x_ * request.x_));
}
void Td::on_request(uint64 id, td_api::testCallString &request) {
send_closure(actor_id(this), &Td::send_result, id, make_tl_object<td_api::testString>(std::move(request.x_)));
}
void Td::on_request(uint64 id, td_api::testCallBytes &request) {
send_closure(actor_id(this), &Td::send_result, id, make_tl_object<td_api::testBytes>(std::move(request.x_)));
}
void Td::on_request(uint64 id, td_api::testCallVectorInt &request) {
send_closure(actor_id(this), &Td::send_result, id, make_tl_object<td_api::testVectorInt>(std::move(request.x_)));
}
void Td::on_request(uint64 id, td_api::testCallVectorIntObject &request) {
send_closure(actor_id(this), &Td::send_result, id,
make_tl_object<td_api::testVectorIntObject>(std::move(request.x_)));
}
void Td::on_request(uint64 id, td_api::testCallVectorString &request) {
send_closure(actor_id(this), &Td::send_result, id, make_tl_object<td_api::testVectorString>(std::move(request.x_)));
}
void Td::on_request(uint64 id, td_api::testCallVectorStringObject &request) {
send_closure(actor_id(this), &Td::send_result, id,
make_tl_object<td_api::testVectorStringObject>(std::move(request.x_)));
}
#undef CLEAN_INPUT_STRING
#undef CHECK_AUTH
#undef CHECK_IS_BOT
#undef CHECK_IS_USER
#undef CREATE_NO_ARGS_REQUEST
#undef CREATE_REQUEST
#undef CREATE_REQUEST_PROMISE
constexpr const char *Td::tdlib_version;
} // namespace td
| 35.080742 | 120 | 0.717433 | luckydonald-backup |
a1f67b8bccc32c13947f4ec52684de0baea78821 | 1,797 | cpp | C++ | src/utils.cpp | sethbrin/cpp-htslib | cc216955c0cac3ac4d57e5d6e86f09037e3cffb6 | [
"MIT"
] | null | null | null | src/utils.cpp | sethbrin/cpp-htslib | cc216955c0cac3ac4d57e5d6e86f09037e3cffb6 | [
"MIT"
] | null | null | null | src/utils.cpp | sethbrin/cpp-htslib | cc216955c0cac3ac4d57e5d6e86f09037e3cffb6 | [
"MIT"
] | null | null | null | //
// Created by zp on 9/3/16.
//
#include "easehts/utils.h"
#include <algorithm>
#include <random>
namespace ncic {
namespace easehts {
namespace utils {
void tokenize(const std::string &s, char c, std::vector<std::string> *res) {
auto end = s.end();
auto start = end;
for (auto it = s.begin(); it != end; ++it) {
if (*it != c) {
if (start == end)
start = it;
continue;
}
if (start != end) {
res->emplace_back(start, it);
start = end;
}
}
if (start != end)
res->emplace_back(start, end);
}
std::vector<int> SampleIndicesWithoutReplacemement(int n, int k,
ThreadLocalRandom& rnd) {
std::vector<int> chosen_balls;
chosen_balls.reserve(n);
for (int i = 0; i < n; i++) {
chosen_balls.push_back(i);
}
Shuffle(chosen_balls, rnd);
return std::vector<int>(chosen_balls.begin(), chosen_balls.begin() + k);
}
// Random
const long long ThreadLocalRandom::kMultiplier = 0x5DEECE66DLL;
const long long ThreadLocalRandom::kAddend = 0xBLL;
const long long ThreadLocalRandom::kMask = (1LL << 48) - 1;
std::string RoundNearestFormat(double val, size_t max_digits) {
double EPS = std::pow(10.0, -1.0 * (max_digits + 1)) * 5;
// if val equals to -0.0000000000003, then just print 0
// while the following print that -0
if (std::fabs(val) < EPS) return "0";
char str[80];
for (int i = 0; i < max_digits; i++) {
double round_val = RoundNearest(val, i);
if (std::fabs(round_val - val) < EPS) {
std::sprintf(str, ("%." + std::to_string(i) + "lf").c_str(), round_val);
return std::string(str);
}
}
std::sprintf(str, ("%." + std::to_string(max_digits) + "lf").c_str(), val);
return std::string(str);
}
} // util
} // easehts
} // ncic
| 23.96 | 78 | 0.597663 | sethbrin |
a1f739442df74203f5fddd5b9c8ec7027eb4a6f3 | 1,013 | cpp | C++ | project/Test/Singleton.cpp | harayuu9/CppLinq | 483c177bf1f89e3959079d0f6baec839eb7e1829 | [
"MIT"
] | 1 | 2021-05-13T11:33:35.000Z | 2021-05-13T11:33:35.000Z | project/Test/Singleton.cpp | harayuu9/LinqForCpp | 483c177bf1f89e3959079d0f6baec839eb7e1829 | [
"MIT"
] | null | null | null | project/Test/Singleton.cpp | harayuu9/LinqForCpp | 483c177bf1f89e3959079d0f6baec839eb7e1829 | [
"MIT"
] | null | null | null | #include "Test.h"
TEST( Singleton, Normal )
{
std::vector<int> range;
range.push_back( 10 );
const auto result = linq::Singleton( 10 ) << linq::ToVector();
ASSERT_EQ( range, result );
}
#if ENABLE_PERF
static void NativeSingleton( benchmark::State& state )
{
while ( state.KeepRunning() )
{
MEM_RESET();
std::vector<int> range;
range.push_back( 10 );
MEM_COUNTER( state );
}
}
static void LinqForCppSingleton( benchmark::State& state )
{
while ( state.KeepRunning() )
{
MEM_RESET();
const auto result = linq::Singleton( 10 ) << linq::ToVector();
MEM_COUNTER( state );
}
}
static void CppLinqSingleton( benchmark::State& state )
{
while ( state.KeepRunning() )
{
MEM_RESET();
const auto result = cpplinq::singleton( 10 ) >> cpplinq::to_vector();
MEM_COUNTER( state );
}
}
BENCHMARK( NativeSingleton );
BENCHMARK( LinqForCppSingleton );
BENCHMARK( CppLinqSingleton );
#endif
| 20.673469 | 77 | 0.612043 | harayuu9 |
a1f76527deead17589c5773d179e40c6e0e8c5da | 1,323 | cpp | C++ | solved/r-t/traffic/lightoj/gen.cpp | abuasifkhan/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | 13 | 2015-09-30T19:18:04.000Z | 2021-06-26T21:11:30.000Z | solved/r-t/traffic/lightoj/gen.cpp | sbmaruf/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | null | null | null | solved/r-t/traffic/lightoj/gen.cpp | sbmaruf/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | 13 | 2015-01-04T09:49:54.000Z | 2021-06-03T13:18:44.000Z | /*
Author :
Problem Name :
Algorithm :
Complexity :
*/
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cmath>
#include <iostream>
#include <stack>
#include <queue>
#include <algorithm>
#include <list>
#include <map>
#include <set>
#include <vector>
#include <cassert>
using namespace std;
int main() {
//freopen("e.in", "w", stdout);
srand(time(NULL));
int cases = 45;
printf("%d\n", cases);
while( cases-- ) {
puts("");
int m, n;
while(1) {
n = rand() % 201;
if( n > 1 ) break;
}
if( cases % 10 == 0 ) n = 200;
int A[1000];
printf("%d\n", n);
for( int i = 1; i <= n; i++ ) {
if( i > 1 ) putchar(' ');
A[i] = rand() % 20 + 1;
A[1] = 1;
printf("%d", A[i]);
}
puts("");
m = rand() % (n*n) + 5*n;
if( cases % 3 == 0 ) m = rand() % (n);
set < pair <int, int> > S;
while( m-- ) {
int u, v;
u = rand() % n + 1;
v = rand() % n + 1;
if( u != v ) {
if( A[u] <= A[v] || ( cases % 10 == 0 && rand() % 100 == 2 ) )
S.insert( make_pair( u, v ) );
}
}
printf("%d\n", S.size());
for( set < pair <int, int> >::iterator s = S.begin(); s != S.end(); s++ ) {
printf("%d %d\n", s->first, s->second);
}
printf("%d\n", n - 1);
for( int i = 2; i <= n; i++ ) printf("%d\n", i);
}
return 0;
}
| 17.407895 | 77 | 0.473923 | abuasifkhan |
a1fa2e284103b93228d5a40a7950a4346624a945 | 1,426 | cc | C++ | game/src/gui/uifw/tab_view.cc | chunseoklee/mengde | 7261e45dab9e02d4bf18b4542767f4b50a5616a0 | [
"MIT"
] | 1 | 2018-03-02T03:36:59.000Z | 2018-03-02T03:36:59.000Z | game/src/gui/uifw/tab_view.cc | chunseoklee/mengde | 7261e45dab9e02d4bf18b4542767f4b50a5616a0 | [
"MIT"
] | 1 | 2018-04-17T01:43:02.000Z | 2018-04-17T01:43:02.000Z | game/src/gui/uifw/tab_view.cc | chunseoklee/mengde | 7261e45dab9e02d4bf18b4542767f4b50a5616a0 | [
"MIT"
] | null | null | null | #include "tab_view.h"
#include "button_view.h"
#include "layout_helper.h"
#include "util/common.h"
namespace mengde {
namespace gui {
namespace uifw {
TabView::TabView(const Rect* frame) : CompositeView(frame), view_index_(0) {
bg_color(COLOR("darkgray"));
padding(LayoutHelper::kDefaultSpace);
}
void TabView::SetViewIndex(int idx) {
ASSERT(idx < GetNumTabs());
// Uncheck
v_tab_buttons_[view_index_]->check(false);
v_tabs_[view_index_]->visible(false);
// Check
v_tab_buttons_[idx]->check(true);
v_tabs_[idx]->visible(true);
view_index_ = idx;
}
void TabView::AddTab(const string& button_text, View* view) {
// Generate a button for the new tab
const int kButtonWidth = 60;
const int kButtonHeight = 20;
const int index = GetNumTabs();
Rect btn_frame = {(kButtonWidth + LayoutHelper::kDefaultSpace / 2) * index, 0, kButtonWidth, kButtonHeight};
ButtonView* tab_button = new ButtonView(&btn_frame, button_text);
tab_button->SetMouseButtonHandler([=](const foundation::MouseButtonEvent e) -> bool {
if (e.IsLeftButtonDown()) {
this->SetViewIndex(index);
}
return true;
});
view->visible(false);
v_tab_buttons_.push_back(tab_button);
v_tabs_.push_back(view);
AddChild(tab_button);
AddChild(view);
if (index == view_index_) {
SetViewIndex(view_index_);
}
}
} // namespace uifw
} // namespace gui
} // namespace mengde
| 24.169492 | 118 | 0.690743 | chunseoklee |
a1fc71780fe9fb4ce16939bdcb4c5bcd263e7fb8 | 627 | hpp | C++ | src/systems/visible.hpp | hexoctal/zenith | eeef065ed62f35723da87c8e73a6716e50d34060 | [
"MIT"
] | 2 | 2021-03-18T16:25:04.000Z | 2021-11-13T00:29:27.000Z | src/systems/visible.hpp | hexoctal/zenith | eeef065ed62f35723da87c8e73a6716e50d34060 | [
"MIT"
] | null | null | null | src/systems/visible.hpp | hexoctal/zenith | eeef065ed62f35723da87c8e73a6716e50d34060 | [
"MIT"
] | 1 | 2021-11-13T00:29:30.000Z | 2021-11-13T00:29:30.000Z | /**
* @file
* @author __AUTHOR_NAME__ <mail@host.com>
* @copyright 2021 __COMPANY_LTD__
* @license <a href="https://opensource.org/licenses/MIT">MIT License</a>
*/
#ifndef ZEN_SYSTEMS_VISIBLE_HPP
#define ZEN_SYSTEMS_VISIBLE_HPP
#include "../ecs/entity.hpp"
namespace Zen {
/**
* Returns the visibility of this Entity.
*
* @since 0.0.0
*
* @return The visible state of this Entity.
*/
bool GetVisible (Entity entity);
/**
* Sets the visibility of this Entity.
*
* @since 0.0.0
*
* @param value The visible state of this Entity.
*/
void SetVisible (Entity entity, bool value);
} // namespace Zen
#endif
| 17.416667 | 74 | 0.685805 | hexoctal |
a1fcffea7eddd28266fed51e457a857ad5ad381c | 266 | cpp | C++ | Algorithm/0191 (Easy)Number of 01 Bits/Bit.cpp | ZexinLi0w0/LeetCode | cf3988620ccdcc3d54b9beafd04c517c96f01bb9 | [
"MIT"
] | 1 | 2020-12-03T10:10:15.000Z | 2020-12-03T10:10:15.000Z | Algorithm/0191 (Easy)Number of 01 Bits/Bit.cpp | ZexinLi0w0/LeetCode | cf3988620ccdcc3d54b9beafd04c517c96f01bb9 | [
"MIT"
] | null | null | null | Algorithm/0191 (Easy)Number of 01 Bits/Bit.cpp | ZexinLi0w0/LeetCode | cf3988620ccdcc3d54b9beafd04c517c96f01bb9 | [
"MIT"
] | null | null | null | class Solution {
public:
int hammingWeight(uint32_t n) {
int bit = 32;
int count = 0;
while(bit)
{
if(n % 2 == 1)
count++;
n /= 2;
bit--;
}
return count;
}
}; | 17.733333 | 35 | 0.357143 | ZexinLi0w0 |
b80024a35deccea674b456ac25c97bdc5eb0d30c | 1,112 | hpp | C++ | src/string_editor.hpp | michiya-lab/utility | 2fe9f848efd1506bbfeebc40a35e7ab3c3977ea5 | [
"MIT"
] | 2 | 2020-10-14T15:09:43.000Z | 2020-10-14T15:09:45.000Z | src/string_editor.hpp | michiya-lab/utility | 2fe9f848efd1506bbfeebc40a35e7ab3c3977ea5 | [
"MIT"
] | null | null | null | src/string_editor.hpp | michiya-lab/utility | 2fe9f848efd1506bbfeebc40a35e7ab3c3977ea5 | [
"MIT"
] | null | null | null | #ifndef STRING_EDITOR_HPP
#define STRING_EDITOR_HPP
#include <string>
#include <sstream>
#include <vector>
#include <iostream>
namespace michiya
{
namespace utility
{
class string_editor
{
public:
string_editor() { ; }
virtual ~string_editor() { ; }
static std::vector<std::string> split(const std::string &, const char &);
static std::string trim_right(const std::string &, const char &);
static std::string trim_right(const std::string &, const std::string &);
static std::string trim_left(const std::string &, const char &);
static std::string trim_left(const std::string &, const std::string &);
static std::string trim_both(const std::string &, const char &);
static std::string trim_both(const std::string &, const std::string &);
static std::string remove(const std::string &, const char &);
private:
/* code */
}; // class string_editor
} // namespace utility
} // namespace michiya
#endif // STRING_EDITOR_HPP
| 32.705882 | 85 | 0.600719 | michiya-lab |
b8024110cb323ae025923f7e6552ac8387f5a888 | 13,216 | cpp | C++ | src/broadphase/interval_tree.cpp | tgn3000/fcl | dd0dce5023c88c5f98b39234ba8296b15f818e41 | [
"BSD-3-Clause"
] | 2 | 2020-08-13T02:38:13.000Z | 2021-08-13T08:03:17.000Z | src/broadphase/interval_tree.cpp | tgn3000/fcl | dd0dce5023c88c5f98b39234ba8296b15f818e41 | [
"BSD-3-Clause"
] | 1 | 2019-06-03T11:44:53.000Z | 2019-06-03T11:44:53.000Z | src/broadphase/interval_tree.cpp | tgn3000/fcl | dd0dce5023c88c5f98b39234ba8296b15f818e41 | [
"BSD-3-Clause"
] | 4 | 2019-05-31T09:22:58.000Z | 2019-12-30T03:19:24.000Z | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011-2014, Willow Garage, Inc.
* Copyright (c) 2014-2015, Open Source Robotics Foundation
* 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 Open Source Robotics Foundation 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.
*/
/** \author Jia Pan */
#include "fcl/broadphase/interval_tree.h"
#include <iostream>
#include <cstdlib>
#include <algorithm>
namespace fcl
{
IntervalTreeNode::IntervalTreeNode(){}
IntervalTreeNode::IntervalTreeNode(SimpleInterval* new_interval) :
stored_interval (new_interval),
key(new_interval->low),
high(new_interval->high),
max_high(high) {}
IntervalTreeNode::~IntervalTreeNode() {}
/// @brief Class describes the information needed when we take the
/// right branch in searching for intervals but possibly come back
/// and check the left branch as well.
struct it_recursion_node
{
public:
IntervalTreeNode* start_node;
unsigned int parent_index;
bool try_right_branch;
};
IntervalTree::IntervalTree()
{
nil = new IntervalTreeNode;
nil->left = nil->right = nil->parent = nil;
nil->red = false;
nil->key = nil->high = nil->max_high = -std::numeric_limits<double>::max();
nil->stored_interval = NULL;
root = new IntervalTreeNode;
root->parent = root->left = root->right = nil;
root->key = root->high = root->max_high = std::numeric_limits<double>::max();
root->red = false;
root->stored_interval = NULL;
/// the following are used for the query function
recursion_node_stack_size = 128;
recursion_node_stack = (it_recursion_node*)malloc(recursion_node_stack_size*sizeof(it_recursion_node));
recursion_node_stack_top = 1;
recursion_node_stack[0].start_node = NULL;
}
IntervalTree::~IntervalTree()
{
IntervalTreeNode* x = root->left;
std::deque<IntervalTreeNode*> nodes_to_free;
if(x != nil)
{
if(x->left != nil)
{
nodes_to_free.push_back(x->left);
}
if(x->right != nil)
{
nodes_to_free.push_back(x->right);
}
delete x;
while( nodes_to_free.size() > 0)
{
x = nodes_to_free.back();
nodes_to_free.pop_back();
if(x->left != nil)
{
nodes_to_free.push_back(x->left);
}
if(x->right != nil)
{
nodes_to_free.push_back(x->right);
}
delete x;
}
}
delete nil;
delete root;
free(recursion_node_stack);
}
void IntervalTree::leftRotate(IntervalTreeNode* x)
{
IntervalTreeNode* y;
y = x->right;
x->right = y->left;
if(y->left != nil) y->left->parent = x;
y->parent = x->parent;
if(x == x->parent->left)
x->parent->left = y;
else
x->parent->right = y;
y->left = x;
x->parent = y;
x->max_high = std::max(x->left->max_high, std::max(x->right->max_high, x->high));
y->max_high = std::max(x->max_high, std::max(y->right->max_high, y->high));
}
void IntervalTree::rightRotate(IntervalTreeNode* y)
{
IntervalTreeNode* x;
x = y->left;
y->left = x->right;
if(nil != x->right) x->right->parent = y;
x->parent = y->parent;
if(y == y->parent->left)
y->parent->left = x;
else
y->parent->right = x;
x->right = y;
y->parent = x;
y->max_high = std::max(y->left->max_high, std::max(y->right->max_high, y->high));
x->max_high = std::max(x->left->max_high, std::max(y->max_high, x->high));
}
/// @brief Inserts z into the tree as if it were a regular binary tree
void IntervalTree::recursiveInsert(IntervalTreeNode* z)
{
IntervalTreeNode* x;
IntervalTreeNode* y;
z->left = z->right = nil;
y = root;
x = root->left;
while(x != nil)
{
y = x;
if(x->key > z->key)
x = x->left;
else
x = x->right;
}
z->parent = y;
if((y == root) || (y->key > z->key))
y->left = z;
else
y->right = z;
}
void IntervalTree::fixupMaxHigh(IntervalTreeNode* x)
{
while(x != root)
{
x->max_high = std::max(x->high, std::max(x->left->max_high, x->right->max_high));
x = x->parent;
}
}
IntervalTreeNode* IntervalTree::insert(SimpleInterval* new_interval)
{
IntervalTreeNode* y;
IntervalTreeNode* x;
IntervalTreeNode* new_node;
x = new IntervalTreeNode(new_interval);
recursiveInsert(x);
fixupMaxHigh(x->parent);
new_node = x;
x->red = true;
while(x->parent->red)
{
/// use sentinel instead of checking for root
if(x->parent == x->parent->parent->left)
{
y = x->parent->parent->right;
if(y->red)
{
x->parent->red = true;
y->red = true;
x->parent->parent->red = true;
x = x->parent->parent;
}
else
{
if(x == x->parent->right)
{
x = x->parent;
leftRotate(x);
}
x->parent->red = false;
x->parent->parent->red = true;
rightRotate(x->parent->parent);
}
}
else
{
y = x->parent->parent->left;
if(y->red)
{
x->parent->red = false;
y->red = false;
x->parent->parent->red = true;
x = x->parent->parent;
}
else
{
if(x == x->parent->left)
{
x = x->parent;
rightRotate(x);
}
x->parent->red = false;
x->parent->parent->red = true;
leftRotate(x->parent->parent);
}
}
}
root->left->red = false;
return new_node;
}
IntervalTreeNode* IntervalTree::getSuccessor(IntervalTreeNode* x) const
{
IntervalTreeNode* y;
if(nil != (y = x->right))
{
while(y->left != nil)
y = y->left;
return y;
}
else
{
y = x->parent;
while(x == y->right)
{
x = y;
y = y->parent;
}
if(y == root) return nil;
return y;
}
}
IntervalTreeNode* IntervalTree::getPredecessor(IntervalTreeNode* x) const
{
IntervalTreeNode* y;
if(nil != (y = x->left))
{
while(y->right != nil)
y = y->right;
return y;
}
else
{
y = x->parent;
while(x == y->left)
{
if(y == root) return nil;
x = y;
y = y->parent;
}
return y;
}
}
void IntervalTreeNode::print(IntervalTreeNode* nil, IntervalTreeNode* root) const
{
stored_interval->print();
std::cout << ", k = " << key << ", h = " << high << ", mH = " << max_high;
std::cout << " l->key = ";
if(left == nil) std::cout << "NULL"; else std::cout << left->key;
std::cout << " r->key = ";
if(right == nil) std::cout << "NULL"; else std::cout << right->key;
std::cout << " p->key = ";
if(parent == root) std::cout << "NULL"; else std::cout << parent->key;
std::cout << " red = " << (int)red << std::endl;
}
void IntervalTree::recursivePrint(IntervalTreeNode* x) const
{
if(x != nil)
{
recursivePrint(x->left);
x->print(nil,root);
recursivePrint(x->right);
}
}
void IntervalTree::print() const
{
recursivePrint(root->left);
}
void IntervalTree::deleteFixup(IntervalTreeNode* x)
{
IntervalTreeNode* w;
IntervalTreeNode* root_left_node = root->left;
while((!x->red) && (root_left_node != x))
{
if(x == x->parent->left)
{
w = x->parent->right;
if(w->red)
{
w->red = false;
x->parent->red = true;
leftRotate(x->parent);
w = x->parent->right;
}
if((!w->right->red) && (!w->left->red))
{
w->red = true;
x = x->parent;
}
else
{
if(!w->right->red)
{
w->left->red = false;
w->red = true;
rightRotate(w);
w = x->parent->right;
}
w->red = x->parent->red;
x->parent->red = false;
w->right->red = false;
leftRotate(x->parent);
x = root_left_node;
}
}
else
{
w = x->parent->left;
if(w->red)
{
w->red = false;
x->parent->red = true;
rightRotate(x->parent);
w = x->parent->left;
}
if((!w->right->red) && (!w->left->red))
{
w->red = true;
x = x->parent;
}
else
{
if(!w->left->red)
{
w->right->red = false;
w->red = true;
leftRotate(w);
w = x->parent->left;
}
w->red = x->parent->red;
x->parent->red = false;
w->left->red = false;
rightRotate(x->parent);
x = root_left_node;
}
}
}
x->red = false;
}
void IntervalTree::deleteNode(SimpleInterval* ivl)
{
IntervalTreeNode* node = recursiveSearch(root, ivl);
if(node)
deleteNode(node);
}
IntervalTreeNode* IntervalTree::recursiveSearch(IntervalTreeNode* node, SimpleInterval* ivl) const
{
if(node != nil)
{
if(node->stored_interval == ivl)
return node;
IntervalTreeNode* left = recursiveSearch(node->left, ivl);
if(left != nil) return left;
IntervalTreeNode* right = recursiveSearch(node->right, ivl);
if(right != nil) return right;
}
return nil;
}
SimpleInterval* IntervalTree::deleteNode(IntervalTreeNode* z)
{
IntervalTreeNode* y;
IntervalTreeNode* x;
SimpleInterval* node_to_delete = z->stored_interval;
y= ((z->left == nil) || (z->right == nil)) ? z : getSuccessor(z);
x= (y->left == nil) ? y->right : y->left;
if(root == (x->parent = y->parent))
{
root->left = x;
}
else
{
if(y == y->parent->left)
{
y->parent->left = x;
}
else
{
y->parent->right = x;
}
}
/// @brief y should not be nil in this case
/// y is the node to splice out and x is its child
if(y != z)
{
y->max_high = -std::numeric_limits<double>::max();
y->left = z->left;
y->right = z->right;
y->parent = z->parent;
z->left->parent = z->right->parent = y;
if(z == z->parent->left)
z->parent->left = y;
else
z->parent->right = y;
fixupMaxHigh(x->parent);
if(!(y->red))
{
y->red = z->red;
deleteFixup(x);
}
else
y->red = z->red;
delete z;
}
else
{
fixupMaxHigh(x->parent);
if(!(y->red)) deleteFixup(x);
delete y;
}
return node_to_delete;
}
/// @brief returns 1 if the intervals overlap, and 0 otherwise
bool overlap(double a1, double a2, double b1, double b2)
{
if(a1 <= b1)
{
return (b1 <= a2);
}
else
{
return (a1 <= b2);
}
}
std::deque<SimpleInterval*> IntervalTree::query(double low, double high)
{
std::deque<SimpleInterval*> result_stack;
IntervalTreeNode* x = root->left;
bool run = (x != nil);
current_parent = 0;
while(run)
{
if(overlap(low,high,x->key,x->high))
{
result_stack.push_back(x->stored_interval);
recursion_node_stack[current_parent].try_right_branch = true;
}
if(x->left->max_high >= low)
{
if(recursion_node_stack_top == recursion_node_stack_size)
{
recursion_node_stack_size *= 2;
recursion_node_stack = (it_recursion_node *)realloc(recursion_node_stack, recursion_node_stack_size * sizeof(it_recursion_node));
if(recursion_node_stack == NULL)
exit(1);
}
recursion_node_stack[recursion_node_stack_top].start_node = x;
recursion_node_stack[recursion_node_stack_top].try_right_branch = false;
recursion_node_stack[recursion_node_stack_top].parent_index = current_parent;
current_parent = recursion_node_stack_top++;
x = x->left;
}
else
x = x->right;
run = (x != nil);
while((!run) && (recursion_node_stack_top > 1))
{
if(recursion_node_stack[--recursion_node_stack_top].try_right_branch)
{
x=recursion_node_stack[recursion_node_stack_top].start_node->right;
current_parent=recursion_node_stack[recursion_node_stack_top].parent_index;
recursion_node_stack[current_parent].try_right_branch = true;
run = (x != nil);
}
}
}
return result_stack;
}
}
| 23.267606 | 137 | 0.595869 | tgn3000 |
b802fae902163ed03574511bd14795b4f917ca21 | 6,911 | hpp | C++ | include/xsimd/types/xsimd_traits.hpp | melton1968/xsimd | f212f3c3801924bf218bc39705230a747467edcb | [
"BSD-3-Clause"
] | null | null | null | include/xsimd/types/xsimd_traits.hpp | melton1968/xsimd | f212f3c3801924bf218bc39705230a747467edcb | [
"BSD-3-Clause"
] | null | null | null | include/xsimd/types/xsimd_traits.hpp | melton1968/xsimd | f212f3c3801924bf218bc39705230a747467edcb | [
"BSD-3-Clause"
] | null | null | null | /***************************************************************************
* Copyright (c) Johan Mabille, Sylvain Corlay, Wolf Vollprecht and *
* Martin Renou *
* Copyright (c) QuantStack *
* Copyright (c) Serge Guelton *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XSIMD_TRAITS_HPP
#define XSIMD_TRAITS_HPP
#include <type_traits>
#include "xsimd_api.hpp"
namespace xsimd
{
/**************************************
* simd_traits and revert_simd_traits *
**************************************/
template <class T, class A = default_arch>
struct has_simd_register : types::has_simd_register<T, A>
{
};
namespace detail
{
template <class T, bool>
struct simd_traits_impl;
template <class T>
struct simd_traits_impl<T, false>
{
using type = T;
using bool_type = bool;
static constexpr size_t size = 1;
};
template <class T>
constexpr size_t simd_traits_impl<T, false>::size;
template <class T>
struct simd_traits_impl<T, true>
{
using type = batch<T>;
using bool_type = typename type::batch_bool_type;
static constexpr size_t size = type::size;
};
template <class T>
constexpr size_t simd_traits_impl<T, true>::size;
}
template <class T>
struct simd_traits : detail::simd_traits_impl<T, has_simd_register<T>::value>
{
};
template <class T>
struct simd_traits<std::complex<T>>
: detail::simd_traits_impl<std::complex<T>, has_simd_register<T>::value>
{
};
#ifdef XSIMD_ENABLE_XTL_COMPLEX
template <class T, bool i3ec>
struct simd_traits<xtl::xcomplex<T, T, i3ec>>
: detail::simd_traits_impl<std::complex<T>, has_simd_register<T>::value>
{
};
#endif
template <class T>
struct revert_simd_traits
{
using type = T;
static constexpr size_t size = simd_traits<type>::size;
};
template <class T>
constexpr size_t revert_simd_traits<T>::size;
template <class T>
struct revert_simd_traits<batch<T>>
{
using type = T;
static constexpr size_t size = batch<T>::size;
};
template <class T>
constexpr size_t revert_simd_traits<batch<T>>::size;
template <class T>
using simd_type = typename simd_traits<T>::type;
template <class T>
using simd_bool_type = typename simd_traits<T>::bool_type;
template <class T>
using revert_simd_type = typename revert_simd_traits<T>::type;
/********************
* simd_return_type *
********************/
namespace detail
{
template <class T1, class T2>
struct simd_condition
{
static constexpr bool value =
(std::is_same<T1, T2>::value && !std::is_same<T1, bool>::value) ||
(std::is_same<T1, bool>::value && !std::is_same<T2, bool>::value) ||
std::is_same<T1, float>::value ||
std::is_same<T1, double>::value ||
std::is_same<T1, int8_t>::value ||
std::is_same<T1, uint8_t>::value ||
std::is_same<T1, int16_t>::value ||
std::is_same<T1, uint16_t>::value ||
std::is_same<T1, int32_t>::value ||
std::is_same<T1, uint32_t>::value ||
std::is_same<T1, int64_t>::value ||
std::is_same<T1, uint64_t>::value ||
std::is_same<T1, char>::value ||
detail::is_complex<T1>::value;
};
template <class T1, class T2, class A>
struct simd_return_type_impl
: std::enable_if<simd_condition<T1, T2>::value, batch<T2, A>>
{
};
template <class A>
struct simd_return_type_impl<char, char, A>
: std::conditional<std::is_signed<char>::value,
simd_return_type_impl<int8_t, int8_t, A>,
simd_return_type_impl<uint8_t, uint8_t, A>>::type
{
};
template <class T2, class A>
struct simd_return_type_impl<bool, T2, A>
: std::enable_if<simd_condition<bool, T2>::value, batch_bool<T2, A>>
{
};
template <class T2, class A>
struct simd_return_type_impl<bool, std::complex<T2>, A>
: std::enable_if<simd_condition<bool, T2>::value, batch_bool<T2, A>>
{
};
template <class T1, class T2, class A>
struct simd_return_type_impl<std::complex<T1>, T2, A>
: std::enable_if<simd_condition<T1, T2>::value, batch<std::complex<T2>, A>>
{
};
template <class T1, class T2, class A>
struct simd_return_type_impl<std::complex<T1>, std::complex<T2>, A>
: std::enable_if<simd_condition<T1, T2>::value, batch<std::complex<T2>, A>>
{
};
#if XSIMD_ENABLE_XTL_COMPLEX
template <class T1, class T2, bool I3EC, class A>
struct simd_return_type_impl<xtl::xcomplex<T1, T1, I3EC>, T2, A>
: std::enable_if<simd_condition<T1, T2>::value, batch<std::complex<T2>, A>>
{
};
template <class T1, class T2, bool I3EC, class A>
struct simd_return_type_impl<xtl::xcomplex<T1, T1, I3EC>, xtl::xcomplex<T2, T2, I3EC>, A>
: std::enable_if<simd_condition<T1, T2>::value, batch<std::complex<T2>, A>>
{
};
#endif
}
template <class T1, class T2, class A = default_arch>
using simd_return_type = typename detail::simd_return_type_impl<T1, T2, A>::type;
/************
* is_batch *
************/
template <class V>
struct is_batch : std::false_type
{
};
template <class T, class A>
struct is_batch<batch<T, A>> : std::true_type
{
};
/*****************
* is_batch_bool *
*****************/
template <class V>
struct is_batch_bool : std::false_type
{
};
template <class T, class A>
struct is_batch_bool<batch_bool<T, A>> : std::true_type
{
};
/********************
* is_batch_complex *
********************/
template <class V>
struct is_batch_complex : std::false_type
{
};
template <class T, class A>
struct is_batch_complex<batch<std::complex<T>, A>> : std::true_type
{
};
}
#endif
| 29.788793 | 97 | 0.518883 | melton1968 |
b806e38458b49e708fe32eeadc932062f1fdbb7c | 11,847 | hpp | C++ | src/PDE/CGPDE.hpp | franjgonzalez/Quinoa | 411eb8815e92618c563881b784e287e2dd916f89 | [
"RSA-MD"
] | null | null | null | src/PDE/CGPDE.hpp | franjgonzalez/Quinoa | 411eb8815e92618c563881b784e287e2dd916f89 | [
"RSA-MD"
] | null | null | null | src/PDE/CGPDE.hpp | franjgonzalez/Quinoa | 411eb8815e92618c563881b784e287e2dd916f89 | [
"RSA-MD"
] | null | null | null | // *****************************************************************************
/*!
\file src/PDE/CGPDE.hpp
\copyright 2012-2015 J. Bakosi,
2016-2018 Los Alamos National Security, LLC.,
2019 Triad National Security, LLC.
All rights reserved. See the LICENSE file for details.
\brief Partial differential equation base for continuous Galerkin PDEs
\details This file defines a generic partial differential equation (PDE)
class for PDEs that use continuous Galerkin spatial discretization.
The class uses runtime polymorphism without client-side inheritance:
inheritance is confined to the internals of the class, invisible to
client-code. The class exclusively deals with ownership enabling client-side
value semantics. Credit goes to Sean Parent at Adobe:
https://github.com/sean-parent/sean-parent.github.com/wiki/
Papers-and-Presentations.
*/
// *****************************************************************************
#ifndef CGPDE_h
#define CGPDE_h
#include <array>
#include <string>
#include <vector>
#include <functional>
#include <unordered_set>
#include <unordered_map>
#include "Types.hpp"
#include "Make_unique.hpp"
#include "Fields.hpp"
namespace inciter {
//! \brief Partial differential equation base for continuous Galerkin PDEs
//! \details This class uses runtime polymorphism without client-side
//! inheritance: inheritance is confined to the internals of the this class,
//! invisible to client-code. The class exclusively deals with ownership
//! enabling client-side value semantics. Credit goes to Sean Parent at Adobe:
//! https://github.com/sean-parent/sean-parent.github.com/wiki/
//! Papers-and-Presentations. For example client code that models a CGPDE,
//! see inciter::CompFlow.
class CGPDE {
private:
using ncomp_t = kw::ncomp::info::expect::type;
public:
//! \brief Constructor taking an object modeling Concept.
//! \details The object of class T comes pre-constructed.
//! \param[in] x Instantiated object of type T given by the template
//! argument.
template< typename T > explicit CGPDE( T x ) :
self( tk::make_unique< Model<T> >( std::move(x) ) ) {}
//! \brief Constructor taking a function pointer to a constructor of an
//! object modeling Concept.
//! \details Passing std::function allows late execution of the constructor,
//! i.e., as late as inside this class' constructor, and thus usage from
//! a factory. Note that there are at least two different ways of using
//! this constructor:
//! - Bind T's constructor arguments and place it in std::function<T()>
//! and passing no arguments as args.... This case then instantiates the
//! model via its constructor and stores it in here.
//! - Bind a single placeholder argument to T's constructor and pass it in
//! as host's args..., which then forwards it to model's constructor. This
//! allows late binding, i.e., binding the argument only here.
//! \see See also the wrapper tk::recordModel() which does the former and
//! tk::recordModelLate() which does the latter, both defined in
//! src/Base/Factory.h.
//! \param[in] x Function pointer to a constructor of an object modeling
//! Concept.
//! \param[in] args Zero or more constructor arguments
template< typename T, typename...Args >
explicit CGPDE( std::function<T(Args...)> x, Args&&... args ) :
self( tk::make_unique< Model<T> >(
std::move( x( std::forward<Args>(args)... ) ) ) ) {}
//! Public interface to setting the initial conditions for the diff eq
void initialize( const std::array< std::vector< tk::real >, 3 >& coord,
tk::Fields& unk,
tk::real t ) const
{ self->initialize( coord, unk, t ); }
//! Public interface to computing the left-hand side matrix for the diff eq
void lhs( const std::array< std::vector< tk::real >, 3 >& coord,
const std::vector< std::size_t >& inpoel,
const std::pair< std::vector< std::size_t >,
std::vector< std::size_t > >& psup,
tk::Fields& lhsd,
tk::Fields& lhso ) const
{ self->lhs( coord, inpoel, psup, lhsd, lhso ); }
//! Public interface to computing the right-hand side vector for the diff eq
void rhs( tk::real t,
tk::real deltat,
const std::array< std::vector< tk::real >, 3 >& coord,
const std::vector< std::size_t >& inpoel,
const tk::Fields& U,
tk::Fields& Ue,
tk::Fields& R ) const
{ self->rhs( t, deltat, coord, inpoel, U, Ue, R ); }
//! Public interface for computing the minimum time step size
tk::real dt( const std::array< std::vector< tk::real >, 3 >& coord,
const std::vector< std::size_t >& inpoel,
const tk::Fields& U ) const
{ return self->dt( coord, inpoel, U ); }
//! \brief Public interface for collecting all side set IDs the user has
//! configured for all components of a PDE system
void side( std::unordered_set< int >& conf ) const { self->side( conf ); }
//! \brief Public interface for querying Dirichlet boundary condition values
//! set by the user on a given side set for all components in a PDE system
std::map< std::size_t, std::vector< std::pair<bool,tk::real> > >
dirbc( tk::real t,
tk::real deltat,
const std::pair< const int, std::vector< std::size_t > >& sides,
const std::array< std::vector< tk::real >, 3 >& coord ) const
{ return self->dirbc( t, deltat, sides, coord ); }
//! Public interface to returning field output labels
std::vector< std::string > fieldNames() const { return self->fieldNames(); }
//! Public interface to returning variable names
std::vector< std::string > names() const { return self->names(); }
//! Public interface to returning field output
std::vector< std::vector< tk::real > > fieldOutput(
tk::real t,
tk::real V,
const std::array< std::vector< tk::real >, 3 >& coord,
const std::vector< tk::real >& v,
tk::Fields& U ) const
{ return self->fieldOutput( t, V, coord, v, U ); }
//! Public interface to returning analytic solution
std::vector< tk::real >
analyticSolution( tk::real xi, tk::real yi, tk::real zi, tk::real t ) const
{ return self->analyticSolution( xi, yi, zi, t ); }
//! Copy assignment
CGPDE& operator=( const CGPDE& x )
{ CGPDE tmp(x); *this = std::move(tmp); return *this; }
//! Copy constructor
CGPDE( const CGPDE& x ) : self( x.self->copy() ) {}
//! Move assignment
CGPDE& operator=( CGPDE&& ) noexcept = default;
//! Move constructor
CGPDE( CGPDE&& ) noexcept = default;
private:
//! \brief Concept is a pure virtual base class specifying the requirements
//! of polymorphic objects deriving from it
struct Concept {
Concept() = default;
Concept( const Concept& ) = default;
virtual ~Concept() = default;
virtual Concept* copy() const = 0;
virtual void initialize( const std::array< std::vector< tk::real >, 3 >&,
tk::Fields&,
tk::real ) const = 0;
virtual void lhs( const std::array< std::vector< tk::real >, 3 >&,
const std::vector< std::size_t >&,
const std::pair< std::vector< std::size_t >,
std::vector< std::size_t > >&,
tk::Fields&, tk::Fields& ) const = 0;
virtual void rhs( tk::real,
tk::real,
const std::array< std::vector< tk::real >, 3 >&,
const std::vector< std::size_t >&,
const tk::Fields&,
tk::Fields&,
tk::Fields& ) const = 0;
virtual tk::real dt( const std::array< std::vector< tk::real >, 3 >&,
const std::vector< std::size_t >&,
const tk::Fields& ) const = 0;
virtual void side( std::unordered_set< int >& conf ) const = 0;
virtual
std::map< std::size_t, std::vector< std::pair<bool,tk::real> > >
dirbc( tk::real,
tk::real,
const std::pair< const int, std::vector< std::size_t > >&,
const std::array< std::vector< tk::real >, 3 >& ) const = 0;
virtual std::vector< std::string > fieldNames() const = 0;
virtual std::vector< std::string > names() const = 0;
virtual std::vector< std::vector< tk::real > > fieldOutput(
tk::real,
tk::real,
const std::array< std::vector< tk::real >, 3 >&,
const std::vector< tk::real >&,
tk::Fields& ) const = 0;
virtual std::vector< tk::real > analyticSolution(
tk::real xi, tk::real yi, tk::real zi, tk::real t ) const = 0;
};
//! \brief Model models the Concept above by deriving from it and overriding
//! the virtual functions required by Concept
template< typename T >
struct Model : Concept {
explicit Model( T x ) : data( std::move(x) ) {}
Concept* copy() const override { return new Model( *this ); }
void initialize( const std::array< std::vector< tk::real >, 3 >& coord,
tk::Fields& unk,
tk::real t )
const override { data.initialize( coord, unk, t ); }
void lhs( const std::array< std::vector< tk::real >, 3 >& coord,
const std::vector< std::size_t >& inpoel,
const std::pair< std::vector< std::size_t >,
std::vector< std::size_t > >& psup,
tk::Fields& lhsd, tk::Fields& lhso ) const override
{ data.lhs( coord, inpoel, psup, lhsd, lhso ); }
void rhs( tk::real t,
tk::real deltat,
const std::array< std::vector< tk::real >, 3 >& coord,
const std::vector< std::size_t >& inpoel,
const tk::Fields& U,
tk::Fields& Ue,
tk::Fields& R ) const override
{ data.rhs( t, deltat, coord, inpoel, U, Ue, R ); }
tk::real dt( const std::array< std::vector< tk::real >, 3 >& coord,
const std::vector< std::size_t >& inpoel,
const tk::Fields& U ) const override
{ return data.dt( coord, inpoel, U ); }
void side( std::unordered_set< int >& conf ) const override
{ data.side( conf ); }
std::map< std::size_t, std::vector< std::pair<bool,tk::real> > >
dirbc( tk::real t,
tk::real deltat,
const std::pair< const int, std::vector< std::size_t > >& sides,
const std::array< std::vector< tk::real >, 3 >& coord ) const
override { return data.dirbc( t, deltat, sides, coord ); }
std::vector< std::string > fieldNames() const override
{ return data.fieldNames(); }
std::vector< std::string > names() const override
{ return data.names(); }
std::vector< std::vector< tk::real > > fieldOutput(
tk::real t,
tk::real V,
const std::array< std::vector< tk::real >, 3 >& coord,
const std::vector< tk::real >& v,
tk::Fields& U ) const override
{ return data.fieldOutput( t, V, coord, v, U ); }
std::vector< tk::real >
analyticSolution( tk::real xi, tk::real yi, tk::real zi, tk::real t )
const override { return data.analyticSolution( xi, yi, zi, t ); }
T data;
};
std::unique_ptr< Concept > self; //!< Base pointer used polymorphically
};
} // inciter::
#endif // CGPDE_h
| 46.097276 | 80 | 0.576517 | franjgonzalez |
b80c332c692f492a9189ddf9c1077069d4e5a5c4 | 452 | cpp | C++ | 18_Overloading/2_2_Predef/Deleted.cpp | Gridelen/cpp-prog-lang-ex | 70c40967f0d0ec07eaf2dc0bc6aac052a35f0631 | [
"MIT"
] | 2 | 2020-07-04T17:56:50.000Z | 2021-08-19T18:28:15.000Z | 18_Overloading/2_2_Predef/Deleted.cpp | Gridelen/cpp-prog-lang-ex | 70c40967f0d0ec07eaf2dc0bc6aac052a35f0631 | [
"MIT"
] | null | null | null | 18_Overloading/2_2_Predef/Deleted.cpp | Gridelen/cpp-prog-lang-ex | 70c40967f0d0ec07eaf2dc0bc6aac052a35f0631 | [
"MIT"
] | 1 | 2019-07-27T08:11:25.000Z | 2019-07-27T08:11:25.000Z | class X
{
public:
void operator=(const X&) = delete;
void operator&() = delete;
void operator,(const X&) = delete;
};
void f(X a, X b)
{
a = b; // Error C2280 'void X::operator =(const X &)': attempting to reference a deleted function
&a; // Error C2280 'void X::operator &(void)': attempting to reference a deleted function
a, b; // Error C2280 'void X::operator ,(const X &)': attempting to reference a deleted function
}
int main()
{
} | 25.111111 | 99 | 0.652655 | Gridelen |
b80e260885d7498ac47d178cacb406b8e805a070 | 21,668 | cpp | C++ | CreaturePluginOld/CreatureCore.cpp | kestrelm/Creature_UE4 | 62740b56722948cdacbd5977b00d81537ab051f1 | [
"Apache-2.0"
] | 208 | 2015-06-15T05:28:16.000Z | 2022-03-28T06:32:26.000Z | CreaturePluginOld/CreatureCore.cpp | kestrelm/Creature_UE4 | 62740b56722948cdacbd5977b00d81537ab051f1 | [
"Apache-2.0"
] | 4 | 2015-12-07T22:19:13.000Z | 2020-01-13T09:15:24.000Z | CreaturePluginOld/CreatureCore.cpp | kestrelm/Creature_UE4 | 62740b56722948cdacbd5977b00d81537ab051f1 | [
"Apache-2.0"
] | 70 | 2015-06-21T14:06:53.000Z | 2022-02-19T04:19:09.000Z | #include "CustomProceduralMesh.h"
#include "CreatureCore.h"
static std::map<std::string, std::shared_ptr<CreatureModule::CreatureAnimation> > global_animations;
static std::map<std::string, std::shared_ptr<CreatureModule::CreatureLoadDataPacket> > global_load_data_packets;
static std::string GetAnimationToken(const std::string& filename_in, const std::string& name_in)
{
return filename_in + std::string("_") + name_in;
}
static std::string ConvertToString(FString str)
{
std::string t = TCHAR_TO_UTF8(*str);
return t;
}
typedef std::chrono::high_resolution_clock Time;
static auto profileTimeStart = Time::now();
static auto profileTimeEnd = Time::now();
static void StartProfileTimer()
{
typedef std::chrono::milliseconds ms;
typedef std::chrono::duration<float> fsec;
profileTimeStart = Time::now();
}
static float StopProfileTimer()
{
typedef std::chrono::milliseconds ms;
typedef std::chrono::duration<float> fsec;
profileTimeEnd = Time::now();
fsec fs = profileTimeEnd - profileTimeStart;
ms d = std::chrono::duration_cast<ms>(fs);
auto time_passed_fs = fs.count();
return time_passed_fs * 1000.0f;
}
CreatureCore::CreatureCore()
{
smooth_transitions = false;
bone_data_size = 0.01f;
bone_data_length_factor = 0.02f;
should_play = true;
region_overlap_z_delta = 0.01f;
is_looping = true;
play_start_done = false;
play_end_done = false;
is_disabled = false;
is_driven = false;
is_ready_play = false;
should_process_animation_start = false;
should_process_animation_end = false;
update_lock = new std::mutex();
}
bool
CreatureCore::GetAndClearShouldAnimStart()
{
bool retval = should_process_animation_start;
should_process_animation_start = false;
return retval;
}
bool
CreatureCore::GetAndClearShouldAnimEnd()
{
bool retval = should_process_animation_end;
should_process_animation_end = false;
return retval;
}
FProceduralMeshTriData
CreatureCore::GetProcMeshData()
{
if (!creature_manager)
{
FProceduralMeshTriData ret_data(nullptr,
nullptr, nullptr,
0, 0,
®ion_alphas,
update_lock);
return ret_data;
}
auto cur_creature = creature_manager->GetCreature();
int32 num_points = cur_creature->GetTotalNumPoints();
int32 num_indices = cur_creature->GetTotalNumIndices();
glm::uint32 * cur_idx = cur_creature->GetGlobalIndices();
glm::float32 * cur_pts = cur_creature->GetRenderPts();
glm::float32 * cur_uvs = cur_creature->GetGlobalUvs();
if (region_alphas.Num() != num_points)
{
region_alphas.SetNum(num_points);
}
FProceduralMeshTriData ret_data(cur_idx,
cur_pts, cur_uvs,
num_points, num_indices,
®ion_alphas,
update_lock);
return ret_data;
}
void CreatureCore::UpdateCreatureRender()
{
auto cur_creature = creature_manager->GetCreature();
int num_triangles = cur_creature->GetTotalNumIndices() / 3;
glm::uint32 * cur_idx = cur_creature->GetGlobalIndices();
glm::float32 * cur_pts = cur_creature->GetRenderPts();
glm::float32 * cur_uvs = cur_creature->GetGlobalUvs();
// Update depth per region
std::vector<meshRenderRegion *>& cur_regions =
cur_creature->GetRenderComposition()->getRegions();
float region_z = 0.0f, delta_z = region_overlap_z_delta;
if (region_custom_order.Num() != cur_regions.size())
{
// Normal update in default order
for (auto& single_region : cur_regions)
{
glm::float32 * region_pts = cur_pts + (single_region->getStartPtIndex() * 3);
for (size_t i = 0; i < single_region->getNumPts(); i++)
{
region_pts[2] = region_z;
region_pts += 3;
}
region_z += delta_z;
}
}
else {
// Custom order update
auto& regions_map = cur_creature->GetRenderComposition()->getRegionsMap();
for (auto& custom_region_name : region_custom_order)
{
auto real_name = ConvertToString(custom_region_name);
if (regions_map.count(real_name) > 0)
{
auto single_region = regions_map[real_name];
glm::float32 * region_pts = cur_pts + (single_region->getStartPtIndex() * 3);
for (size_t i = 0; i < single_region->getNumPts(); i++)
{
region_pts[2] = region_z;
region_pts += 3;
}
region_z += delta_z;
}
}
}
// Build render triangles
/*
TArray<FProceduralMeshTriangle>& write_triangles = draw_tris;
static const FColor White(255, 255, 255, 255);
int cur_pt_idx = 0, cur_uv_idx = 0;
const int x_id = 0;
const int y_id = 2;
const int z_id = 1;
for (int i = 0; i < num_triangles; i++)
{
int real_idx_1 = cur_idx[0];
int real_idx_2 = cur_idx[1];
int real_idx_3 = cur_idx[2];
FProceduralMeshTriangle triangle;
cur_pt_idx = real_idx_1 * 3;
cur_uv_idx = real_idx_1 * 2;
triangle.Vertex0.Position.Set(cur_pts[cur_pt_idx + x_id], cur_pts[cur_pt_idx + y_id], cur_pts[cur_pt_idx + z_id]);
triangle.Vertex0.Color = White;
triangle.Vertex0.U = cur_uvs[cur_uv_idx];
triangle.Vertex0.V = cur_uvs[cur_uv_idx + 1];
cur_pt_idx = real_idx_2 * 3;
cur_uv_idx = real_idx_2 * 2;
triangle.Vertex1.Position.Set(cur_pts[cur_pt_idx + x_id], cur_pts[cur_pt_idx + y_id], cur_pts[cur_pt_idx + z_id]);
triangle.Vertex1.Color = White;
triangle.Vertex1.U = cur_uvs[cur_uv_idx];
triangle.Vertex1.V = cur_uvs[cur_uv_idx + 1];
cur_pt_idx = real_idx_3 * 3;
cur_uv_idx = real_idx_3 * 2;
triangle.Vertex2.Position.Set(cur_pts[cur_pt_idx + x_id], cur_pts[cur_pt_idx + y_id], cur_pts[cur_pt_idx + z_id]);
triangle.Vertex2.Color = White;
triangle.Vertex2.U = cur_uvs[cur_uv_idx];
triangle.Vertex2.V = cur_uvs[cur_uv_idx + 1];
write_triangles[i] = triangle;
cur_idx += 3;
}
*/
// process the render regions
ProcessRenderRegions();
}
bool CreatureCore::InitCreatureRender()
{
FString cur_creature_filename = creature_filename;
bool does_exist = FPlatformFileManager::Get().GetPlatformFile().FileExists(*cur_creature_filename);
if (!does_exist)
{
// see if it is in the content directory
cur_creature_filename = FPaths::GameContentDir() + FString(TEXT("/")) + cur_creature_filename;
does_exist = FPlatformFileManager::Get().GetPlatformFile().FileExists(*cur_creature_filename);
}
if (does_exist)
{
absolute_creature_filename = cur_creature_filename;
auto load_filename = ConvertToString(cur_creature_filename);
// try to load creature
CreatureCore::LoadDataPacket(load_filename);
LoadCreature(load_filename);
// try to load all animations
auto all_animation_names = creature_manager->GetCreature()->GetAnimationNames();
auto first_animation_name = all_animation_names[0];
for (auto& cur_name : all_animation_names)
{
CreatureCore::LoadAnimation(load_filename, cur_name);
AddLoadedAnimation(load_filename, cur_name);
}
auto cur_str = ConvertToString(start_animation_name);
for (auto& cur_name : all_animation_names)
{
if (cur_name == cur_str)
{
first_animation_name = cur_name;
break;
}
}
SetActiveAnimation(first_animation_name);
if (smooth_transitions)
{
creature_manager->SetAutoBlending(true);
}
FillBoneData();
return true;
}
else {
UE_LOG(LogTemp, Warning, TEXT("ACreatureActor::BeginPlay() - ERROR! Could not load creature file: %s"), *creature_filename);
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("ACreatureActor::BeginPlay() - ERROR! Could not load creature file: %s"), *creature_filename));
}
return false;
}
void CreatureCore::FillBoneData()
{
auto render_composition = creature_manager->GetCreature()->GetRenderComposition();
auto& bones_map = render_composition->getBonesMap();
if (bone_data.Num() == 0)
{
bone_data.SetNum(bones_map.size());
}
int i = 0;
for (auto& cur_data : bones_map)
{
bone_data[i].name = FString(cur_data.first.c_str());
auto pt1 = cur_data.second->getWorldStartPt();
auto pt2 = cur_data.second->getWorldEndPt();
/* Id References
const int x_id = 0;
const int y_id = 2;
const int z_id = 1;
*/
bone_data[i].point1 = FVector(pt1.x, pt1.y, pt1.z);
bone_data[i].point2 = FVector(pt2.x, pt2.y, pt2.z);
// figure out bone transform
auto cur_bone = cur_data.second;
auto bone_start_pt = pt1;
auto bone_end_pt = pt2;
auto bone_vec = bone_end_pt - bone_start_pt;
auto bone_length = glm::length(bone_vec);
auto bone_unit_vec = bone_vec / bone_length;
// quick rotation by 90 degrees
auto bone_unit_normal_vec = bone_unit_vec;
bone_unit_normal_vec.x = -bone_unit_vec.y;
bone_unit_normal_vec.y = bone_unit_vec.x;
FVector bone_midpt = (bone_data[i].point1 + bone_data[i].point2) * 0.5f;
FVector bone_axis_x(bone_unit_vec.x, bone_unit_vec.y, 0);
FVector bone_axis_y(bone_unit_normal_vec.x, bone_unit_normal_vec.y, 0);
FVector bone_axis_z(0, 0, 1);
FTransform scaleXform(FVector(0, 0, 0));
scaleXform.SetScale3D(FVector(bone_length * bone_data_length_factor, bone_data_size, bone_data_size));
//std::swap(bone_midpt.Y, bone_midpt.Z);
FTransform fixXform;
fixXform.SetRotation(FQuat::MakeFromEuler(FVector(-90, 0, 0)));
FTransform rotXform(bone_axis_x, bone_axis_y, bone_axis_z, FVector(0, 0, 0));
FTransform posXform, posStartXform, posEndXform;
posXform.SetTranslation(bone_midpt);
posStartXform.SetTranslation(bone_data[i].point1);
posEndXform.SetTranslation(bone_data[i].point2);
// bone_data[i].xform = scaleXform * FTransform(bone_axis_x, bone_axis_y, bone_axis_z, bone_midpt);
bone_data[i].xform = scaleXform * rotXform * posXform * fixXform;
bone_data[i].startXform = scaleXform * rotXform * posStartXform * fixXform;
bone_data[i].endXform = scaleXform * rotXform * posEndXform * fixXform;
i++;
}
}
void CreatureCore::ParseEvents(float deltaTime)
{
float cur_runtime = (creature_manager->getActualRunTime());
animation_frame = cur_runtime;
auto load_filename = ConvertToString(absolute_creature_filename);
auto cur_animation_name = creature_manager->GetActiveAnimationName();
auto cur_token = GetAnimationToken(load_filename, cur_animation_name);
CreatureModule::CreatureAnimation * cur_animation = NULL;
if (global_animations.count(cur_token) > 0)
{
cur_animation = global_animations[cur_token].get();
}
if (cur_animation)
{
int cur_start_time = cur_animation->getStartTime();
int cur_end_time = cur_animation->getEndTime();
float diff_val_start = fabs(cur_runtime - cur_start_time);
const float cutoff = 0.01f;
if ((diff_val_start <= cutoff)
&& !is_looping
&& !play_start_done
&& should_play)
{
play_start_done = true;
should_process_animation_start = true;
}
if ((cur_runtime + 1.0f >= cur_end_time)
&& !is_looping
&& !play_end_done
&& should_play)
{
play_end_done = true;
should_play = false;
should_process_animation_end = true;
}
}
}
void CreatureCore::ProcessRenderRegions()
{
auto cur_creature = creature_manager->GetCreature();
auto& regions_map = cur_creature->GetRenderComposition()->getRegionsMap();
int num_triangles = cur_creature->GetTotalNumIndices() / 3;
// process alphas
if (region_alphas.Num() != cur_creature->GetTotalNumPoints())
{
region_alphas.Init(255, cur_creature->GetTotalNumPoints());
}
// fill up animation alphas
for (auto& cur_region_pair : regions_map)
{
auto cur_region = cur_region_pair.second;
auto start_pt_index = cur_region->getStartPtIndex();
auto end_pt_index = cur_region->getEndPtIndex();
auto cur_alpha = FMath::Clamp(cur_region->getOpacity() / 100.0f, 0.0f, 1.0f) * 255.0f;
for (auto i = start_pt_index; i <= end_pt_index; i++)
{
region_alphas[i] = (uint8)cur_alpha;
}
}
// user overwrite alphas
if (region_alpha_map.Num() > 0)
{
// fill up the alphas for specific regions with alpha overwrites
for (auto cur_iter : region_alpha_map)
{
auto cur_name = ConvertToString(cur_iter.Key);
auto cur_alpha = cur_iter.Value;
if (regions_map.count(cur_name) > 0)
{
meshRenderRegion * cur_region = regions_map[cur_name];
auto start_pt_index = cur_region->getStartPtIndex();
auto end_pt_index = cur_region->getEndPtIndex();
for (auto i = start_pt_index; i <= end_pt_index; i++)
{
region_alphas[i] = cur_alpha;
}
}
}
}
// now write out alphas into render triangles
/*
glm::uint32 * cur_idx = cur_creature->GetGlobalIndices();
for (int i = 0; i < num_triangles; i++)
{
int real_idx_1 = cur_idx[0];
int real_idx_2 = cur_idx[1];
int real_idx_3 = cur_idx[2];
auto& cur_tri = draw_tris[i];
auto set_alpha_1 = region_alphas[real_idx_1];
auto set_alpha_2 = region_alphas[real_idx_2];
auto set_alpha_3 = region_alphas[real_idx_3];
cur_tri.Vertex0.Color = FColor(set_alpha_1, set_alpha_1, set_alpha_1, set_alpha_1);
cur_tri.Vertex1.Color = FColor(set_alpha_2, set_alpha_2, set_alpha_1, set_alpha_2);
cur_tri.Vertex2.Color = FColor(set_alpha_3, set_alpha_3, set_alpha_1, set_alpha_3);
cur_idx += 3;
}
*/
}
void
CreatureCore::LoadDataPacket(const std::string& filename_in)
{
if (global_load_data_packets.count(filename_in) > 0)
{
// file already loaded, just return
return;
}
std::shared_ptr<CreatureModule::CreatureLoadDataPacket> new_packet =
std::make_shared<CreatureModule::CreatureLoadDataPacket>();
bool is_zip = false;
if (filename_in.substr(filename_in.find_last_of(".") + 1) == "zip") {
is_zip = true;
}
if (is_zip)
{
// load zip archive
CreatureModule::LoadCreatureZipJSONData(filename_in, *new_packet);
}
else {
// load regular JSON
CreatureModule::LoadCreatureJSONData(filename_in, *new_packet);
}
global_load_data_packets[filename_in] = new_packet;
}
void
CreatureCore::LoadAnimation(const std::string& filename_in, const std::string& name_in)
{
auto cur_token = GetAnimationToken(filename_in, name_in);
if (global_animations.count(cur_token) > 0)
{
// animation already exists, just return
return;
}
auto load_data = global_load_data_packets[filename_in];
std::shared_ptr<CreatureModule::CreatureAnimation> new_animation =
std::make_shared<CreatureModule::CreatureAnimation>(*load_data, name_in);
global_animations[cur_token] = new_animation;
}
TArray<FProceduralMeshTriangle>&
CreatureCore::LoadCreature(const std::string& filename_in)
{
auto load_data = global_load_data_packets[filename_in];
std::shared_ptr<CreatureModule::Creature> new_creature =
std::make_shared<CreatureModule::Creature>(*load_data);
creature_manager = std::make_shared<CreatureModule::CreatureManager>(new_creature);
draw_triangles.SetNum(creature_manager->GetCreature()->GetTotalNumIndices() / 3, true);
return draw_triangles;
}
bool
CreatureCore::AddLoadedAnimation(const std::string& filename_in, const std::string& name_in)
{
auto cur_token = GetAnimationToken(filename_in, name_in);
if (global_animations.count(cur_token) > 0)
{
creature_manager->AddAnimation(global_animations[cur_token]);
creature_manager->SetIsPlaying(true);
creature_manager->SetShouldLoop(is_looping);
return true;
}
else {
std::cout << "ERROR! ACreatureActor::AddLoadedAnimation() Animation with filename: " << filename_in << " and name: " << name_in << " not loaded!" << std::endl;
}
return false;
}
CreatureModule::CreatureManager *
CreatureCore::GetCreatureManager()
{
return creature_manager.get();
}
void
CreatureCore::SetBluePrintActiveAnimation(FString name_in)
{
auto cur_str = ConvertToString(name_in);
SetActiveAnimation(cur_str);
}
void
CreatureCore::SetBluePrintBlendActiveAnimation(FString name_in, float factor)
{
auto cur_str = ConvertToString(name_in);
SetAutoBlendActiveAnimation(cur_str, factor);
}
void
CreatureCore::SetBluePrintAnimationCustomTimeRange(FString name_in, int32 start_time, int32 end_time)
{
auto cur_str = ConvertToString(name_in);
auto all_animations = creature_manager->GetAllAnimations();
if (all_animations.count(cur_str) > 0)
{
all_animations[cur_str]->setStartTime(start_time);
all_animations[cur_str]->setEndTime(end_time);
}
}
void
CreatureCore::MakeBluePrintPointCache(FString name_in, int32 approximation_level)
{
auto cur_creature_manager = GetCreatureManager();
if (!cur_creature_manager)
{
UE_LOG(LogTemp, Warning, TEXT("ACreatureActor::MakeBluePrintPointCache() - ERROR! Could not generate point cache for %s"), *name_in);
return;
}
int32 real_approximation_level = approximation_level;
if (real_approximation_level <= 0)
{
real_approximation_level = 1;
}
else if (real_approximation_level > 10)
{
real_approximation_level = 10;
}
cur_creature_manager->MakePointCache(ConvertToString(name_in), real_approximation_level);
}
void
CreatureCore::ClearBluePrintPointCache(FString name_in, int32 approximation_level)
{
auto cur_creature_manager = GetCreatureManager();
if (!cur_creature_manager)
{
UE_LOG(LogTemp, Warning, TEXT("ACreatureActor::MakeBluePrintPointCache() - ERROR! Could not generate point cache for %s"), *name_in);
return;
}
cur_creature_manager->ClearPointCache(ConvertToString(name_in));
}
FTransform
CreatureCore::GetBluePrintBoneXform(FString name_in, bool world_transform, float position_slide_factor, FTransform base_transform)
{
FTransform ret_xform;
for (size_t i = 0; i < bone_data.Num(); i++)
{
if (bone_data[i].name == name_in)
{
ret_xform = bone_data[i].xform;
float diff_slide_factor = fabs(position_slide_factor);
const float diff_cutoff = 0.01f;
if (diff_slide_factor > diff_cutoff)
{
// interpolate between start and end
ret_xform.Blend(bone_data[i].startXform, bone_data[i].endXform, position_slide_factor + 0.5f);
}
if (world_transform)
{
FTransform xform = base_transform;
/*
FVector world_location = xform.GetTranslation();
ret_data.point1 = xform.TransformPosition(ret_data.point1);
ret_data.point2 = xform.TransformPosition(ret_data.point2);
*/
//FMatrix no_scale = xform.ToMatrixNoScale();
ret_xform = ret_xform * xform;
}
break;
}
}
return ret_xform;
}
bool
CreatureCore::IsBluePrintBonesCollide(FVector test_point, float bone_size, FTransform base_transform)
{
if (bone_size <= 0)
{
bone_size = 1.0f;
}
FTransform xform = base_transform;
FVector local_test_point = xform.InverseTransformPosition(test_point);
auto render_composition = creature_manager->GetCreature()->GetRenderComposition();
auto& bones_map = render_composition->getBonesMap();
glm::vec4 real_test_pt(local_test_point.X, local_test_point.Y, local_test_point.Z, 1.0f);
for (auto cur_data : bones_map)
{
auto cur_bone = cur_data.second;
auto bone_start_pt = cur_bone->getWorldStartPt();
auto bone_end_pt = cur_bone->getWorldEndPt();
auto bone_vec = bone_end_pt - bone_start_pt;
auto bone_length = glm::length(bone_vec);
auto bone_unit_vec = bone_vec / bone_length;
auto rel_vec = real_test_pt - bone_start_pt;
float proj_length_u = glm::dot(rel_vec, bone_unit_vec);
if (proj_length_u >= 0 && proj_length_u <= bone_length)
{
// quick rotation by 90 degrees
auto bone_unit_normal_vec = bone_unit_vec;
bone_unit_normal_vec.x = -bone_unit_vec.y;
bone_unit_normal_vec.y = bone_unit_vec.x;
float proj_length_v = fabs(glm::dot(rel_vec, bone_unit_normal_vec));
if (proj_length_v <= bone_size)
{
return true;
}
}
}
return false;
}
bool
CreatureCore::RunTick(float delta_time)
{
std::lock_guard<std::mutex> scope_lock(*update_lock);
if (is_driven)
{
UpdateCreatureRender();
FillBoneData();
return true;
}
if (is_disabled)
{
return false;
}
if (creature_manager)
{
ParseEvents(delta_time);
if (should_play) {
creature_manager->Update(delta_time);
}
UpdateCreatureRender();
FillBoneData();
}
return true;
}
void
CreatureCore::SetBluePrintAnimationLoop(bool flag_in)
{
is_looping = flag_in;
if (creature_manager) {
creature_manager->SetShouldLoop(is_looping);
}
}
void
CreatureCore::SetBluePrintAnimationPlay(bool flag_in)
{
should_play = flag_in;
play_start_done = false;
play_end_done = false;
}
void
CreatureCore::SetBluePrintAnimationPlayFromStart()
{
SetBluePrintAnimationResetToStart();
SetBluePrintAnimationPlay(true);
}
void
CreatureCore::SetBluePrintAnimationResetToStart()
{
if (creature_manager) {
creature_manager->ResetToStartTimes();
float cur_runtime = (creature_manager->getActualRunTime());
animation_frame = cur_runtime;
creature_manager->Update(0.001f);
}
play_start_done = false;
play_end_done = false;
}
float
CreatureCore::GetBluePrintAnimationFrame()
{
return animation_frame;
}
void
CreatureCore::SetBluePrintRegionAlpha(FString region_name_in, uint8 alpha_in)
{
if (region_name_in.IsEmpty())
{
return;
}
region_alpha_map.Add(region_name_in, alpha_in);
}
void
CreatureCore::SetBluePrintRegionCustomOrder(TArray<FString> order_in)
{
region_custom_order = order_in;
}
void
CreatureCore::ClearBluePrintRegionCustomOrder()
{
region_custom_order.Empty();
}
void
CreatureCore::SetActiveAnimation(const std::string& name_in)
{
creature_manager->SetActiveAnimationName(name_in);
}
void
CreatureCore::SetAutoBlendActiveAnimation(const std::string& name_in, float factor)
{
auto all_animations = creature_manager->GetAllAnimations();
if (all_animations.count(name_in) <= 0)
{
return;
}
if (factor < 0.001f)
{
factor = 0.001f;
}
else if (factor > 1.0f)
{
factor = 1.0f;
}
if (smooth_transitions == false)
{
smooth_transitions = true;
creature_manager->SetAutoBlending(true);
}
creature_manager->AutoBlendTo(name_in, factor);
}
void
CreatureCore::SetIsDisabled(bool flag_in)
{
is_disabled = flag_in;
}
void
CreatureCore::SetDriven(bool flag_in)
{
is_driven = flag_in;
}
bool
CreatureCore::GetIsReadyPlay() const
{
return is_ready_play;
}
void
CreatureCore::RunBeginPlay()
{
is_ready_play = false;
InitCreatureRender();
is_ready_play = true;
region_alpha_map.Empty();
}
| 25.136891 | 173 | 0.738601 | kestrelm |
b8131b3a5f8c8cd6e485deaeb9a8db4fcd8918c7 | 7,838 | cpp | C++ | libraries/protocol/credit_offer.cpp | blockops-de/bitshares-core | ac1cfc058633de8cfd0355fad207e5fa6e9d65f3 | [
"MIT"
] | 147 | 2015-10-13T02:46:23.000Z | 2017-01-12T14:42:32.000Z | libraries/protocol/credit_offer.cpp | blockops-de/bitshares-core | ac1cfc058633de8cfd0355fad207e5fa6e9d65f3 | [
"MIT"
] | 35 | 2015-11-02T15:50:00.000Z | 2017-01-17T22:11:01.000Z | libraries/protocol/credit_offer.cpp | blockchainprojects/bitshares-core | ac1cfc058633de8cfd0355fad207e5fa6e9d65f3 | [
"MIT"
] | 67 | 2015-10-14T21:26:18.000Z | 2017-01-16T14:20:45.000Z | /*
* Copyright (c) 2021 Abit More, and contributors.
*
* The MIT License
*
* 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 <graphene/protocol/credit_offer.hpp>
#include <fc/io/raw.hpp>
namespace graphene { namespace protocol {
static void validate_acceptable_collateral( const flat_map<asset_id_type, price>& acceptable_collateral,
const asset_id_type* p_asset_type = nullptr )
{
FC_ASSERT( !acceptable_collateral.empty(), "Acceptable collateral list should not be empty" );
asset_id_type asset_type = ( p_asset_type != nullptr ) ? *p_asset_type
: acceptable_collateral.begin()->second.base.asset_id;
for( const auto& collateral : acceptable_collateral )
{
const auto& collateral_asset_type = collateral.first;
const auto& collateral_price = collateral.second;
FC_ASSERT( collateral_price.base.asset_id == asset_type,
"Base asset ID in price of acceptable collateral should be same as offer asset type" );
FC_ASSERT( collateral_price.quote.asset_id == collateral_asset_type,
"Quote asset ID in price of acceptable collateral should be same as collateral asset type" );
collateral_price.validate( true );
}
}
static void validate_acceptable_borrowers( const flat_map<account_id_type, share_type>& acceptable_borrowers )
{
for( const auto& borrower : acceptable_borrowers )
{
const auto& max_borrow_amount = borrower.second.value;
FC_ASSERT( max_borrow_amount >= 0,
"Maximum amount to borrow for acceptable borrowers should not be negative" );
FC_ASSERT( max_borrow_amount <= GRAPHENE_MAX_SHARE_SUPPLY,
"Maximum amount to borrow for acceptable borrowers should not be greater than ${max}",
("max", GRAPHENE_MAX_SHARE_SUPPLY) );
}
}
void credit_offer_create_operation::validate()const
{
FC_ASSERT( fee.amount >= 0, "Fee should not be negative" );
FC_ASSERT( balance > 0, "Balance should be positive" );
FC_ASSERT( max_duration_seconds <= GRAPHENE_MAX_CREDIT_DEAL_SECS,
"Maximum duration should not be greater than ${d} days",
("d", GRAPHENE_MAX_CREDIT_DEAL_DAYS) );
FC_ASSERT( min_deal_amount >= 0, "Minimum deal amount should not be negative" );
FC_ASSERT( min_deal_amount <= GRAPHENE_MAX_SHARE_SUPPLY,
"Minimum deal amount should not be greater than ${max}",
("max", GRAPHENE_MAX_SHARE_SUPPLY) );
validate_acceptable_collateral( acceptable_collateral, &asset_type );
validate_acceptable_borrowers( acceptable_borrowers );
}
share_type credit_offer_create_operation::calculate_fee( const fee_parameters_type& schedule )const
{
share_type core_fee_required = schedule.fee;
core_fee_required += calculate_data_fee( fc::raw::pack_size(*this), schedule.price_per_kbyte );
return core_fee_required;
}
void credit_offer_delete_operation::validate()const
{
FC_ASSERT( fee.amount >= 0, "Fee should not be negative" );
}
void credit_offer_update_operation::validate()const
{
FC_ASSERT( fee.amount >= 0, "Fee should not be negative" );
bool updating_something = false;
if( delta_amount.valid() )
{
updating_something = true;
FC_ASSERT( delta_amount->amount != 0, "Delta amount should not be zero" );
}
if( fee_rate.valid() )
updating_something = true;
if( max_duration_seconds.valid() )
{
updating_something = true;
FC_ASSERT( *max_duration_seconds <= GRAPHENE_MAX_CREDIT_DEAL_SECS,
"Maximum duration should not be greater than ${d} days",
("d", GRAPHENE_MAX_CREDIT_DEAL_DAYS) );
}
if( min_deal_amount.valid() )
{
updating_something = true;
FC_ASSERT( *min_deal_amount >= 0, "Minimum deal amount should not be negative" );
FC_ASSERT( *min_deal_amount <= GRAPHENE_MAX_SHARE_SUPPLY,
"Minimum deal amount should not be greater than ${max}",
("max", GRAPHENE_MAX_SHARE_SUPPLY) );
}
if( enabled.valid() )
updating_something = true;
if( auto_disable_time.valid() )
updating_something = true;
if( acceptable_collateral.valid() )
{
updating_something = true;
validate_acceptable_collateral( *acceptable_collateral ); // Note: check base asset ID in evaluator
}
if( acceptable_borrowers.valid() )
{
updating_something = true;
validate_acceptable_borrowers( *acceptable_borrowers );
}
FC_ASSERT( updating_something,
"Should change something - at least one of the optional data fields should be present" );
}
share_type credit_offer_update_operation::calculate_fee( const fee_parameters_type& schedule )const
{
share_type core_fee_required = schedule.fee;
core_fee_required += calculate_data_fee( fc::raw::pack_size(*this), schedule.price_per_kbyte );
return core_fee_required;
}
void credit_offer_accept_operation::validate()const
{
FC_ASSERT( fee.amount >= 0, "Fee should not be negative" );
FC_ASSERT( borrow_amount.amount > 0, "Amount to borrow should be positive" );
FC_ASSERT( collateral.amount > 0, "Collateral amount should be positive" );
}
void credit_deal_repay_operation::validate()const
{
FC_ASSERT( fee.amount >= 0, "Fee should not be negative" );
FC_ASSERT( repay_amount.amount > 0, "Amount to repay should be positive" );
FC_ASSERT( credit_fee.amount >= 0, "Credit fee should not be negative" );
FC_ASSERT( repay_amount.asset_id == credit_fee.asset_id,
"Asset type of repay amount and credit fee should be the same" );
}
} } // graphene::protocol
GRAPHENE_IMPLEMENT_EXTERNAL_SERIALIZATION( graphene::protocol::credit_offer_create_operation::fee_parameters_type )
GRAPHENE_IMPLEMENT_EXTERNAL_SERIALIZATION( graphene::protocol::credit_offer_delete_operation::fee_parameters_type )
GRAPHENE_IMPLEMENT_EXTERNAL_SERIALIZATION( graphene::protocol::credit_offer_update_operation::fee_parameters_type )
GRAPHENE_IMPLEMENT_EXTERNAL_SERIALIZATION( graphene::protocol::credit_offer_accept_operation::fee_parameters_type )
GRAPHENE_IMPLEMENT_EXTERNAL_SERIALIZATION( graphene::protocol::credit_deal_repay_operation::fee_parameters_type )
GRAPHENE_IMPLEMENT_EXTERNAL_SERIALIZATION( graphene::protocol::credit_offer_create_operation )
GRAPHENE_IMPLEMENT_EXTERNAL_SERIALIZATION( graphene::protocol::credit_offer_delete_operation )
GRAPHENE_IMPLEMENT_EXTERNAL_SERIALIZATION( graphene::protocol::credit_offer_update_operation )
GRAPHENE_IMPLEMENT_EXTERNAL_SERIALIZATION( graphene::protocol::credit_offer_accept_operation )
GRAPHENE_IMPLEMENT_EXTERNAL_SERIALIZATION( graphene::protocol::credit_deal_repay_operation )
GRAPHENE_IMPLEMENT_EXTERNAL_SERIALIZATION( graphene::protocol::credit_deal_expired_operation )
| 45.045977 | 115 | 0.737688 | blockops-de |
b816927d5346d18684ff72fc71e2c3f6553c1aee | 6,503 | cc | C++ | ns-allinone-2.35/ns-2.35/common/misc.cc | nitishk017/ns2project | f037b796ff10300ffe0422580be5855c37d0b140 | [
"MIT"
] | 1 | 2018-03-05T15:23:27.000Z | 2018-03-05T15:23:27.000Z | ns-allinone-2.35/ns-2.35/common/misc.cc | nitishk017/ns2project | f037b796ff10300ffe0422580be5855c37d0b140 | [
"MIT"
] | 1 | 2019-01-20T17:35:23.000Z | 2019-01-22T21:41:38.000Z | ns-allinone-2.35/ns-2.35/common/misc.cc | nitishk017/ns2project | f037b796ff10300ffe0422580be5855c37d0b140 | [
"MIT"
] | 1 | 2021-09-29T16:06:57.000Z | 2021-09-29T16:06:57.000Z | /* -*- Mode:C++; c-basic-offset:8; tab-width:8; indent-tabs-mode:t -*- */
/*
* Copyright (c) 1994 Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the Computer Systems
* Engineering Group at Lawrence Berkeley Laboratory.
* 4. Neither the name of the University nor of the Laboratory may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* miscellaneous "ns" commands
*/
#ifndef lint
static const char rcsid[] =
"@(#) $Header: /cvsroot/nsnam/ns-2/common/misc.cc,v 1.15 2010/03/08 05:54:49 tom_henderson Exp $ (LBL)";
#endif
#include <stdlib.h>
#include <math.h>
#ifndef WIN32
#include <sys/time.h>
#endif
#include <ctype.h>
#include "config.h"
#include "scheduler.h"
#include "random.h"
#if defined(HAVE_INT64)
class Add64Command : public TclCommand {
public:
Add64Command() : TclCommand("ns-add64") {}
virtual int command(int argc, const char*const* argv);
};
int Add64Command::command(int argc, const char*const* argv)
{
Tcl& tcl = Tcl::instance();
if (argc == 3) {
char res[22]; /* A 64 bit int at most 20 digits */
int64_t d1 = STRTOI64(argv[1], NULL, 0);
int64_t d2 = STRTOI64(argv[2], NULL, 0);
sprintf(res, STRTOI64_FMTSTR, d1+d2);
tcl.resultf("%s", res);
return (TCL_OK);
}
tcl.add_error("ns-add64 requires two arguments.");
return (TCL_ERROR);
}
class Mult64Command : public TclCommand {
public:
Mult64Command() : TclCommand("ns-mult64") {}
virtual int command(int argc, const char*const* argv);
};
int Mult64Command::command(int argc, const char*const* argv)
{
Tcl& tcl = Tcl::instance();
if (argc == 3) {
char res[22]; /* A 64 bit int at most 20 digits */
int64_t d1 = STRTOI64(argv[1], NULL, 0);
int64_t d2 = STRTOI64(argv[2], NULL, 0);
sprintf(res, STRTOI64_FMTSTR, d1*d2);
tcl.resultf("%s", res);
return (TCL_OK);
}
tcl.add_error("ns-mult64 requires two arguments.");
return (TCL_ERROR);
}
class Int64ToDoubleCommand : public TclCommand {
public:
Int64ToDoubleCommand() : TclCommand("ns-int64todbl") {}
virtual int command(int argc, const char*const* argv);
};
int Int64ToDoubleCommand::command(int argc, const char*const* argv)
{
Tcl& tcl = Tcl::instance();
if (argc == 2) {
char res[22]; /* A 64 bit int at most 20 digits */
int64_t d1 = STRTOI64(argv[1], NULL, 0);
double d2 = d1;
sprintf(res, "%.1f",d2);
tcl.resultf("%s", res);
return (TCL_OK);
}
tcl.add_error("ns-int64todbl requires only one arguments.");
return (TCL_ERROR);
}
#endif
class HasInt64Command : public TclCommand {
public:
HasInt64Command() : TclCommand("ns-hasint64") {}
virtual int command(int argc, const char*const* argv);
};
int HasInt64Command::command(int, const char*const*)
{
Tcl& tcl = Tcl::instance();
char res[2];
int flag = 0;
#if defined(HAVE_INT64)
flag = 1;
#endif
sprintf(res, "%d", flag);
tcl.resultf("%s", res);
return (TCL_OK);
}
class RandomCommand : public TclCommand {
public:
RandomCommand() : TclCommand("ns-random") { }
virtual int command(int argc, const char*const* argv);
};
/*
* ns-random
* ns-random $seed
*/
int RandomCommand::command(int argc, const char*const* argv)
{
Tcl& tcl = Tcl::instance();
if (argc == 1) {
sprintf(tcl.buffer(), "%u", Random::random());
tcl.result(tcl.buffer());
} else if (argc == 2) {
int seed = atoi(argv[1]);
if (seed == 0)
seed = Random::seed_heuristically();
else
Random::seed(seed);
tcl.resultf("%d", seed);
}
return (TCL_OK);
}
extern "C" char version_string[];
class VersionCommand : public TclCommand {
public:
VersionCommand() : TclCommand("ns-version") { }
virtual int command(int, const char*const*) {
Tcl::instance().result(version_string);
return (TCL_OK);
}
};
class HasSTLCommand : public TclCommand {
public:
HasSTLCommand() : TclCommand("ns-hasSTL") {}
virtual int command(int argc, const char*const* argv);
};
int HasSTLCommand::command(int, const char*const*)
{
Tcl& tcl = Tcl::instance();
char res[2];
int flag = 0;
#if defined(HAVE_STL)
flag = 1;
#endif
sprintf(res, "%d", flag);
tcl.resultf("%s", res);
return (TCL_OK);
}
class TimeAtofCommand : public TclCommand {
public:
TimeAtofCommand() : TclCommand("time_atof") { }
virtual int command(int argc, const char*const* argv) {
if (argc != 2)
return (TCL_ERROR);
char* s = (char*) argv[1];
char wrk[32];
char* cp = wrk;
while (isdigit(*s) || *s == 'e' ||
*s == '+' || *s == '-' || *s == '.')
*cp++ = *s++;
*cp = 0;
double v = atof(wrk);
switch (*s) {
case 'm':
v *= 1e-3;
break;
case 'u':
v *= 1e-6;
break;
case 'n':
v *= 1e-9;
break;
case 'p':
v *= 1e-12;
break;
}
Tcl::instance().resultf("%g", v);
return (TCL_OK);
}
};
void init_misc(void)
{
(void)new VersionCommand;
(void)new RandomCommand;
(void)new TimeAtofCommand;
(void)new HasInt64Command;
(void)new HasSTLCommand;
#if defined(HAVE_INT64)
(void)new Add64Command;
(void)new Mult64Command;
(void)new Int64ToDoubleCommand;
#endif
}
| 26.871901 | 108 | 0.67984 | nitishk017 |
b81a3917d25741187f06ef718c134601ca3f5430 | 415 | hpp | C++ | src/sfmlib/solver.hpp | stianfauskanger/simplerfastmurty | e4571edd5e83388220ebe002a15488cb7f52181d | [
"MIT"
] | null | null | null | src/sfmlib/solver.hpp | stianfauskanger/simplerfastmurty | e4571edd5e83388220ebe002a15488cb7f52181d | [
"MIT"
] | null | null | null | src/sfmlib/solver.hpp | stianfauskanger/simplerfastmurty | e4571edd5e83388220ebe002a15488cb7f52181d | [
"MIT"
] | null | null | null | #ifndef SFMLIB_SOLVER_HPP
#define SFMLIB_SOLVER_HPP
#include <iostream>
#include "../fastmurty/da.hpp"
#include "result.hpp"
#include "problem.hpp"
namespace sfmlib {
class solver {
public:
static sfmlib::result solve(sfmlib::problem problem);
[[nodiscard]] std::string to_string() const;
friend std::ostream &operator<<(std::ostream &os, const solver &solver);
};
}
#endif
| 19.761905 | 80 | 0.674699 | stianfauskanger |
b81afaa6246428fdc663c8d4759dc42d47c5b381 | 4,335 | cpp | C++ | src/GameClient/Windows/Controls/Layouts/Layouts.cpp | vitek-karas/WarPlusPlus | 3abb26ff30dc0e93de906ab6141b89c2fa301ae4 | [
"MIT"
] | 4 | 2019-06-17T13:44:49.000Z | 2021-01-19T10:39:48.000Z | src/GameClient/Windows/Controls/Layouts/Layouts.cpp | vitek-karas/WarPlusPlus | 3abb26ff30dc0e93de906ab6141b89c2fa301ae4 | [
"MIT"
] | null | null | null | src/GameClient/Windows/Controls/Layouts/Layouts.cpp | vitek-karas/WarPlusPlus | 3abb26ff30dc0e93de906ab6141b89c2fa301ae4 | [
"MIT"
] | 4 | 2019-06-17T16:03:20.000Z | 2020-02-15T09:14:30.000Z | // Layouts.cpp: implementation of the CLayouts class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Layouts.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
IMPLEMENT_DYNAMIC(CLayouts, CObject)
CLayouts *CLayouts::m_pDefaults = NULL;
CLayouts::CLayouts()
{
m_bLoaded = FALSE;
}
CLayouts::~CLayouts()
{
}
#ifdef _DEBUG
void CLayouts::AssertValid() const
{
CObject::AssertValid();
ASSERT(m_bLoaded);
}
void CLayouts::Dump(CDumpContext &dc) const
{
CObject::Dump(dc);
}
#endif
BOOL CLayouts::Create(CArchiveFile CfgFile)
{
CConfigFile Config;
BOOL bResult = TRUE;
// create the config file
Config.Create(CfgFile);
if(!Create(&Config)){
bResult = FALSE;
}
Config.Delete();
return bResult;
}
BOOL CLayouts::Create(CConfigFile *pCfgFile)
{
CFG_BEGIN(pCfgFile);
CString strConfig;
strConfig = cfg_Section.GetString("CaptionWindowLayout");
m_CaptionWindowLayout.Create(cfg_Archive.CreateFile(cfg_strPath + strConfig));
strConfig = cfg_Section.GetString("DialogWindowLayout");
m_DialogWindowLayout.Create(cfg_Archive.CreateFile(cfg_strPath + strConfig));
strConfig = cfg_Section.GetString("EditBoxLayout");
m_EditBoxLayout.Create(cfg_Archive.CreateFile(cfg_strPath + strConfig));
strConfig = cfg_Section.GetString("ListControlLayout");
m_ListControlLayout.Create(cfg_Archive.CreateFile(cfg_strPath + strConfig));
strConfig = cfg_Section.GetString("VerticalScrollControlLayout");
m_VerticalScrollControlLayout.Create(cfg_Archive.CreateFile(cfg_strPath + strConfig));
strConfig = cfg_Section.GetString("HorizontalScrollControlLayout");
m_HorizontalScrollControlLayout.Create(cfg_Archive.CreateFile(cfg_strPath + strConfig));
strConfig = cfg_Section.GetString("StaticTextLayout");
m_StaticTextLayout.Create(cfg_Archive.CreateFile(cfg_strPath + strConfig));
strConfig = cfg_Section.GetString("TextButtonLayout");
m_TextButtonLayout.Create(cfg_Archive.CreateFile(cfg_strPath + strConfig));
strConfig = cfg_Section.GetString("PopupMenuLayout");
m_PopupMenuLayout.Create(cfg_Archive.CreateFile(cfg_strPath + strConfig));
strConfig = cfg_Section.GetString("ToolTipLayout");
m_ToolTipLayout.Create(cfg_Archive.CreateFile(cfg_strPath + strConfig));
CFG_END();
m_bLoaded = TRUE;
return TRUE;
}
void CLayouts::Delete()
{
m_bLoaded = FALSE;
m_CaptionWindowLayout.Delete();
m_DialogWindowLayout.Delete();
m_EditBoxLayout.Delete();
m_ListControlLayout.Delete();
m_VerticalScrollControlLayout.Delete();
m_HorizontalScrollControlLayout.Delete();
m_StaticTextLayout.Delete();
m_TextButtonLayout.Delete();
m_PopupMenuLayout.Delete();
m_ToolTipLayout.Delete();
}
CCaptionWindowLayout * CLayouts::GetCaptionWindowLayout()
{
ASSERT_VALID(this);
return &m_CaptionWindowLayout;
}
CDialogWindowLayout * CLayouts::GetDialogWindowLayout()
{
ASSERT_VALID(this);
return &m_DialogWindowLayout;
}
CEditBoxLayout * CLayouts::GetEditBoxLayout()
{
ASSERT_VALID(this);
return &m_EditBoxLayout;
}
CListControlLayout * CLayouts::GetListControlLayout()
{
ASSERT_VALID(this);
return &m_ListControlLayout;
}
CScrollControlLayout * CLayouts::GetVerticalScrollControlLayout()
{
ASSERT_VALID(this);
return &m_VerticalScrollControlLayout;
}
CScrollControlLayout * CLayouts::GetHorizontalScrollControlLayout()
{
ASSERT_VALID(this);
return &m_HorizontalScrollControlLayout;
}
CStaticTextLayout * CLayouts::GetStaticTextLayout()
{
ASSERT_VALID(this);
return &m_StaticTextLayout;
}
CTextButtonLayout * CLayouts::GetTextButtonLayout()
{
ASSERT_VALID(this);
return &m_TextButtonLayout;
}
CFrameWindowLayout * CLayouts::GetPopupMenuLayout()
{
ASSERT_VALID(this);
return &m_PopupMenuLayout;
}
CToolTipLayout * CLayouts::GetToolTipLayout()
{
ASSERT_VALID(this);
return &m_ToolTipLayout;
}
BOOL CLayouts::Init(CArchiveFile CfgFile)
{
ASSERT(m_pDefaults == NULL);
m_pDefaults = new CLayouts();
if(!m_pDefaults->Create(CfgFile)){
delete m_pDefaults;
return FALSE;
}
return TRUE;
}
void CLayouts::Close()
{
if(m_pDefaults != NULL){
m_pDefaults->Delete();
delete m_pDefaults;
m_pDefaults = NULL;
}
}
| 22.005076 | 90 | 0.72549 | vitek-karas |
b823e0fca04cb1d0da0b60c41bf9b2b313c7879e | 1,407 | hpp | C++ | thread/common/src/states/base_configure.hpp | chacal/arduino | 6b77e59138a36d0627ab6f529e6f2ea7e65bcdfd | [
"Apache-2.0"
] | 4 | 2016-12-10T13:20:52.000Z | 2019-10-25T19:47:44.000Z | thread/common/src/states/base_configure.hpp | chacal/arduino | 6b77e59138a36d0627ab6f529e6f2ea7e65bcdfd | [
"Apache-2.0"
] | null | null | null | thread/common/src/states/base_configure.hpp | chacal/arduino | 6b77e59138a36d0627ab6f529e6f2ea7e65bcdfd | [
"Apache-2.0"
] | 1 | 2019-05-03T17:31:38.000Z | 2019-05-03T17:31:38.000Z |
namespace states {
template<typename M>
struct base_configure : M::Base {
protected:
struct config_timer_elapsed {
};
struct coap_timer_ticked {
};
public:
virtual void enter(typename M::Context &context) {
NRF_LOG_INFO("Configuring..");
config_timer.start(&context);
coap_tick_timer.start(&context);
get_configuration(context);
}
virtual void leave(typename M::Context &context) {
config_timer.stop();
coap_tick_timer.stop();
}
virtual void react(const coap_timer_ticked &event, typename M::Control &control, typename M::Context &context) {
coap_time_tick();
}
virtual void react(const config_timer_elapsed &event, typename M::Control &control, typename M::Context &context) {
get_configuration(context);
}
protected:
virtual void get_configuration(typename M::Context &context) = 0;
private:
milliseconds coap_tick_period = std::chrono::seconds(1);
milliseconds config_timer_period = std::chrono::seconds(60);
periodic_timer coap_tick_timer{coap_tick_period,
[](void *ctx) { static_cast<typename M::Context *>(ctx)->react(coap_timer_ticked{}); }};
periodic_timer config_timer{config_timer_period,
[](void *ctx) { static_cast<typename M::Context *>(ctx)->react(config_timer_elapsed{}); }};
};
} | 31.977273 | 123 | 0.656716 | chacal |
b82611c42d8f0b365ea2dddb233f071d28d1b593 | 11,969 | cpp | C++ | SHORT_READ_ANALYSIS/src/cluster_graph.cpp | CSB5/OPERA-MS | ae46e005322774efc896d7c21ec265ad35748bc0 | [
"MIT"
] | 81 | 2018-03-22T15:01:08.000Z | 2022-01-17T17:52:31.000Z | SHORT_READ_ANALYSIS/src/cluster_graph.cpp | CSB5/OPERA-MS | ae46e005322774efc896d7c21ec265ad35748bc0 | [
"MIT"
] | 68 | 2017-09-14T08:17:53.000Z | 2022-03-09T18:56:12.000Z | SHORT_READ_ANALYSIS/src/cluster_graph.cpp | CSB5/OPERA-MS | ae46e005322774efc896d7c21ec265ad35748bc0 | [
"MIT"
] | 21 | 2017-09-14T06:15:18.000Z | 2021-09-30T03:19:22.000Z | #include <cstdlib>
#include <cstdio>
#include <cmath>
#include <iostream>
#include "cluster_graph.h"
#include "sigma.h"
ClusterGraph::ClusterGraph(ContigMap* contigs, EdgeQueue* edges) {
num_contigs_ = (int) contigs->size();
num_windows_ = 0;
for (auto it = contigs->begin(); it != contigs->end(); ++it) {
sContig* contig = (*it).second;
//num_windows_ += contig->num_windows();
roots_.insert(new Cluster(contig));
}
num_windows_ = (double)Sigma::total_assembly_size / (double)Sigma::contig_window_len;
while (!edges->empty()) {
Edge edge = edges->top();
Cluster* cluster1 = edge.contig1()->cluster();
Cluster* cluster2 = edge.contig2()->cluster();
if (cluster1 != cluster2) {
roots_.insert(new Cluster(cluster1, cluster2));
roots_.erase(cluster1);
roots_.erase(cluster2);
}
edges->pop();
/*
//Average linkage !!!
for(int i = 0; i < (int) edges->size(); ++i){
if(edges->size() < num_edges_to_resort){
break;
}
Edge resort_edge = edges->top();
edges->pop();
resort_edge.computeDistanceCluster();
edges->push(resort_edge);
}
*/
}
updateClusters();
}
ClusterGraph::ClusterGraph(ContigMap* contigs, std::string tree_file) {
//Contruct the hash of each cluster ID to their pointer
std::unordered_map<std::string, Cluster*> cluster_map;
std::unordered_map<Cluster*, bool> father_map;
num_contigs_ = (int) contigs->size();
num_windows_ = 0;
FILE* t_f = fopen(tree_file.c_str(), "r");
char f_id[256];
char s_id_1[256];
char s_id_2[256];
char c_id[256];
double s_1, s_2;
Cluster* father;
fprintf(stderr, " **** Reading tree file %s\n", tree_file.c_str());
while (!feof(t_f)) {
//320468544 168318128 167063312 -24.914767 -31.573449 -
if (fscanf(t_f, "%s\t%s\t%s\t%lf\t%lf\t%s\n", f_id, s_id_1, s_id_2, &s_1, &s_2, c_id) == 6) {
if(s_1 == -1){
continue;
}
//fprintf(stderr, "Reading tree file cluster: %s\n", f_id);
//it is a contig
if(c_id[0] != '-'){
//fprintf(stderr, "Updating contig: %s -> %s\n", f_id, c_id);std::cin.get();
auto it = contigs->find(c_id);
father = new Cluster(it->second);
father->set_ID(new std::string(f_id));
cluster_map[f_id] = father;
}
//It is an internal node
else{
//Search for cluster1
Cluster* cluster1 = get_cluster_in_hash(s_id_1, &cluster_map);
//Search for cluster1
Cluster* cluster2 = get_cluster_in_hash(s_id_2, &cluster_map);
//Search for the father
father = get_cluster_in_hash(f_id, &cluster_map);
father->set_cluster(cluster1, cluster2);
//To keep track of the roots
father_map[cluster1] = false;
father_map[cluster2] = false;
}
//update the root value for the father node
auto it = father_map.find(father);
if(it == father_map.end()){
father_map[father] = true;
}
}
}
num_windows_ = (double)Sigma::total_assembly_size / (double)Sigma::contig_window_len;
//For each cluster roots initialize the clusters and the root contig set
std::vector<sContig*> *r_contig = new std::vector<sContig*>();
for (auto it = father_map.begin(); it != father_map.end(); ++it) {
//This is a root
if(it->second){
Cluster* root = it->first;
roots_.insert(root);
//fprintf(stderr, " **** init_cluster next root \n");
init_cluster(root, r_contig);
root->set_contigs(r_contig);
r_contig->clear();
}
}
delete r_contig;
updateClusters();
}
void ClusterGraph::init_cluster(Cluster* cluster, std::vector<sContig*> *v_contig){
//It is a leaf
//fprintf(stderr, "\t **** init_cluster %s\n", (cluster->get_ID())->c_str());
if(cluster->num_contigs() == 1){
v_contig->push_back(cluster->contigs()[0]);
}
else{
Cluster* c1 = cluster->child1();
if(c1 != NULL){
init_cluster(c1, v_contig);
}
else{
fprintf(stderr, "\t\t **** init_cluster null c1 %s\n", (cluster->get_ID())->c_str());
}
Cluster* c2 = cluster->child2();
if(c2 != NULL){
init_cluster(c2, v_contig);
}
else{
fprintf(stderr, "\t\t **** init_cluster null c2 %s\n", (cluster->get_ID())->c_str());
}
cluster->update_cluster_length_read_count(c1, c2);
}
}
Cluster* ClusterGraph::get_cluster_in_hash(std::string id, std::unordered_map<std::string, Cluster*>* c_map){
Cluster* cluster;
auto it = c_map->find(id);
if(it == c_map->end()){
cluster = new Cluster();
cluster->set_ID(new std::string(id));
(*c_map)[id] = cluster;
}
else{
cluster = it->second;
}
return cluster;
}
void ClusterGraph::updateClusters() {
ClusterStack clusters;
for (auto it = roots_.begin(); it != roots_.end(); ++it) {
clusters.push(*it);
}
while (!clusters.empty()) {
Cluster* cluster = clusters.top();
clusters.pop();
if (cluster->num_contigs() > 1) {
cluster->child1()->set_contigs(cluster->contigs());
cluster->child2()->set_contigs(cluster->contigs() + cluster->child1()->num_contigs());
clusters.push(cluster->child1());
clusters.push(cluster->child2());
}
}
}
ClusterGraph::~ClusterGraph() {
ClusterStack clusters;
for (auto it = roots_.begin(); it != roots_.end(); ++it) {
Cluster* cluster = *it;
for (int contig_index = 0; contig_index < cluster->num_contigs(); ++contig_index) {
delete cluster->contigs()[contig_index];
}
delete[] cluster->contigs();
clusters.push(cluster);
}
while (!clusters.empty()) {
Cluster* cluster = clusters.top();
clusters.pop();
if (cluster->num_contigs() > 1) {
clusters.push(cluster->child1());
clusters.push(cluster->child2());
}
delete cluster;
}
}
ClusterSet* ClusterGraph::roots() { return &roots_; }
void ClusterGraph::computeScores(const ProbabilityDistribution* prob_dist) {
ClusterStack clusters;
std::string output_clusters_file_path = Sigma::output_dir + "/scored_clusters.dat";
fprintf(stderr, "Outputing scored clusters in %s\n", output_clusters_file_path.c_str());
output_file_debug = fopen(output_clusters_file_path.c_str(), "w");
//fclose(output_file_debug);
for (auto it = roots_.begin(); it != roots_.end(); ++it) {
clusters.push(*it);
}
while (!clusters.empty()) {
Cluster* cluster = clusters.top();
clusters.pop();
if (cluster->num_contigs() > 1) {
clusters.push(cluster->child1());
clusters.push(cluster->child2());
}
computeClusterScore(cluster, prob_dist);
}
}
void ClusterGraph::output_clusters(Cluster* cluster, double cs, double un_cs) {
//std::string output_clusters_file_path = Sigma::output_dir + "/scored_clusters.dat";
//FILE *output_file = fopen(output_clusters_file_path.c_str(), "a");
//fprintf(output_file, "%d\t%d\t%d\t%f\t", cluster, cluster->child1(), cluster->child2(), cluster->score());
fprintf(output_file_debug, "%s\t%s\t%s\t%f\t%f\t", (*(cluster->get_ID())).c_str(), (*(cluster->child1()->get_ID())).c_str(), (*(cluster->child2()->get_ID())).c_str(), cs, un_cs);
//To write the contig idea in case of a leaf
if(cluster->num_contigs() == 1){
sContig* contig = cluster->contigs()[0];
fprintf(output_file_debug, "%s\n", contig->id().c_str());
}
else{
fprintf(output_file_debug, "-\n");
}
// for (int contig_index = 0; contig_index < cluster->num_contigs(); ++contig_index) {
// Contig* contig = cluster->contigs()[contig_index];
// fprintf(output_file, "%s\t", contig->id().c_str());
// }
// fprintf(output_file, "\n");
//fclose(output_file);
return;
}
void ClusterGraph::computeClusterScore(Cluster* cluster, const ProbabilityDistribution* prob_dist) {
double score = 0;
for (int sample_index = 0; sample_index < Sigma::num_samples; ++sample_index) {
double cluster_read_count = 0.0;
double cluster_dispersion = 0.0;
if (Sigma::USE_WINDOW == 1) {
cluster_read_count = cluster->arrival_rates()[sample_index] * Sigma::contig_window_len;
cluster_dispersion = Sigma::R_VALUE;
}
for (int contig_index = 0; contig_index < cluster->num_contigs(); ++contig_index) {
sContig* contig = cluster->contigs()[contig_index];
if (Sigma::USE_WINDOW == 0) {
cluster_read_count = cluster->arrival_rates()[sample_index] * contig->modified_length();
cluster_dispersion = Sigma::R_VALUE*contig->modified_length();
//fprintf(stdout, " *** global R: %f, cluster_dispersion: %f\n", Sigma::R, cluster_dispersion);
score += prob_dist->logpf(cluster_read_count, cluster_dispersion, contig->sum_read_counts()[sample_index]);
} else {
for (int window_index = 0; window_index < contig->num_windows(); ++window_index) {
score += prob_dist->logpf(cluster_read_count, cluster_dispersion, contig->read_counts()[sample_index][window_index]);
}
}
}
}
//Can add a penalty factor X: score * X
if(Sigma::USE_WINDOW == 0){
score -= 0.5 * Sigma::num_samples * log((double)Sigma::total_assembly_nb_contig);
}
else{
score -= 0.5 * Sigma::num_samples * log(num_windows_);
}
cluster->set_score(score);
}
void ClusterGraph::computeModels() {
ClusterStack clusters;
fprintf(stderr, " *** computeModels: Init Root ...\n");
for (auto it = roots_.begin(); it != roots_.end(); ++it) {
clusters.push(*it);
}
fprintf(stderr, " *** computeModels: computeClusterModel ...\n");
while (!clusters.empty()) {
Cluster* cluster = clusters.top();
if (cluster->num_contigs() == 1 || (cluster->child1()->modeled() && cluster->child2()->modeled())) {
clusters.pop();
computeClusterModel(cluster);
} else {
clusters.push(cluster->child1());
clusters.push(cluster->child2());
}
}
fprintf(stderr, " *** computeModels: Init Root (2) ...\n");
for (auto it = roots_.begin(); it != roots_.end(); ++it) {
clusters.push(*it);
}
fprintf(stderr, " *** computeModels: Associate contig to cluster ...\n");
while (!clusters.empty()) {
Cluster* cluster = clusters.top();
clusters.pop();
if (cluster->connected()) {
for (int contig_index = 0; contig_index < cluster->num_contigs(); ++contig_index) {
cluster->contigs()[contig_index]->set_cluster(cluster);
}
} else {
clusters.push(cluster->child1());
clusters.push(cluster->child2());
}
}
}
void ClusterGraph::computeClusterModel(Cluster* cluster) {
if (cluster->num_contigs() == 1) {
cluster->set_model_score(cluster->score());
cluster->set_connected(true);
//To correct to get the full true
//output_clusters(cluster, cluster->score(), cluster->score());
} else {
double connected_score = cluster->score();
double disconnected_score = cluster->child1()->model_score() + cluster->child2()->model_score();
//output_clusters(cluster, connected_score, disconnected_score);
if (connected_score >= disconnected_score){// - Sigma::SPLITTING_PENALTY) {
cluster->set_model_score(connected_score);
cluster->set_connected(true);
} else {
cluster->set_model_score(disconnected_score);
cluster->set_connected(false);
}
}
cluster->set_modeled(true);
}
void ClusterGraph::saveClusters(const char* clusters_file_path) {
FILE* clusters_fp = fopen(clusters_file_path, "w");
if (clusters_fp != NULL) {
int cluster_id = 1;
ClusterStack clusters;
for (auto it = roots_.begin(); it != roots_.end(); ++it) {
if(Sigma::COMPUTE_SCORE == 0){
(*it)->set_connected(true);
}
clusters.push(*it);
}
while (!clusters.empty()) {
Cluster* cluster = clusters.top();
clusters.pop();
if (cluster->connected()) {
//Output the cluster ID were the cut have been made
//output_clusters(cluster, -1, -1);
for (int contig_index = 0; contig_index < cluster->num_contigs(); ++contig_index) {
sContig* contig = cluster->contigs()[contig_index];
fprintf(clusters_fp, "%s\t%d\t%d\t%f\n",
contig->id().c_str(), cluster_id, contig->sum_read_counts()[0], cluster->arrival_rates()[0]);
}
cluster_id++;
} else {
clusters.push(cluster->child1());
clusters.push(cluster->child2());
}
}
fclose(clusters_fp);
fclose(output_file_debug);
} else {
fprintf(stderr, "Error opening file: %s\n", clusters_file_path);
exit(EXIT_FAILURE);
}
}
| 27.389016 | 179 | 0.658869 | CSB5 |
b8294de0404c1e326b046165de3f894ea80efe44 | 1,730 | hpp | C++ | ReactNativeFrontend/ios/Pods/boost/boost/phoenix/core/nothing.hpp | Harshitha91/Tmdb-react-native-node | e06e3f25a7ee6946ef07a1f524fdf62e48424293 | [
"Apache-2.0"
] | 12,278 | 2015-01-29T17:11:33.000Z | 2022-03-31T21:12:00.000Z | ios/Pods/boost-for-react-native/boost/phoenix/core/nothing.hpp | c7yrus/alyson-v3 | 5ad95a8f782f5f5d2fd543d44ca6a8b093395965 | [
"Apache-2.0"
] | 9,469 | 2015-01-30T05:33:07.000Z | 2022-03-31T16:17:21.000Z | ios/Pods/boost-for-react-native/boost/phoenix/core/nothing.hpp | c7yrus/alyson-v3 | 5ad95a8f782f5f5d2fd543d44ca6a8b093395965 | [
"Apache-2.0"
] | 892 | 2015-01-29T16:26:19.000Z | 2022-03-20T07:44:30.000Z | /*==============================================================================
Copyright (c) 2005-2010 Joel de Guzman
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 BOOST_PHOENIX_CORE_NOTHING_HPP
#define BOOST_PHOENIX_CORE_NOTHING_HPP
#include <boost/phoenix/core/limits.hpp>
#include <boost/mpl/void.hpp>
#include <boost/phoenix/core/actor.hpp>
#include <boost/phoenix/core/call.hpp>
#include <boost/phoenix/core/expression.hpp>
#include <boost/phoenix/core/value.hpp>
namespace boost { namespace phoenix
{
/////////////////////////////////////////////////////////////////////////////
//
// null_actor
//
// An actor that does nothing (a "bum", if you will :-).
//
/////////////////////////////////////////////////////////////////////////////
namespace detail
{
struct nothing {};
}
namespace expression
{
struct null
: expression::value<detail::nothing>
{};
}
template<typename Dummy>
struct is_custom_terminal<detail::nothing, Dummy>
: mpl::true_
{};
template<typename Dummy>
struct custom_terminal<detail::nothing, Dummy>
{
typedef void result_type;
template <typename Context>
void operator()(detail::nothing, Context &) const
{
}
};
typedef expression::null::type nothing_type BOOST_ATTRIBUTE_UNUSED;
#ifndef BOOST_PHOENIX_NO_PREDEFINED_TERMINALS
nothing_type const BOOST_ATTRIBUTE_UNUSED nothing = {{{}}};
#endif
}}
#endif
| 28.360656 | 81 | 0.539306 | Harshitha91 |
b82c16435c0f26eb9fb9ae139071aa811f89799b | 3,412 | cpp | C++ | BrainUnfuckCompiler/src/Structure.cpp | leonardo-ono/BrainUnfuck-to-Brainfuck-Compiler | b2428ee683bf6fadc2162f441a2964b176108b4b | [
"Xnet",
"X11"
] | 2 | 2022-01-23T15:39:35.000Z | 2022-01-24T01:57:58.000Z | BrainUnfuckCompiler/src/Structure.cpp | leonardo-ono/BrainUnfuck-to-Brainfuck-Compiler | b2428ee683bf6fadc2162f441a2964b176108b4b | [
"Xnet",
"X11"
] | null | null | null | BrainUnfuckCompiler/src/Structure.cpp | leonardo-ono/BrainUnfuck-to-Brainfuck-Compiler | b2428ee683bf6fadc2162f441a2964b176108b4b | [
"Xnet",
"X11"
] | null | null | null | #include "Structure.h"
Command::Name Command::commandNameFromStr(std::string str)
{
if (str == "DATA")
return Command::Name::DATA;
else if (str == "PROC")
return Command::Name::PROC;
else if (str == "ENDPROC")
return Command::Name::ENDPROC;
else if (str == "DO")
return Command::Name::DO;
else if (str == "DO_")
return Command::Name::DO_;
else if (str == "WHILE")
return Command::Name::WHILE;
else if (str == "ENDWHILE")
return Command::Name::ENDWHILE;
else if (str == "STORE")
return Command::Name::STORE;
else if (str == "IN")
return Command::Name::IN;
else if (str == "OUT")
return Command::Name::OUT;
else if (str == "ADDRESS")
return Command::Name::ADDRESS;
else if (str == "COPYVV")
return Command::Name::COPYVV;
else if (str == "COPYMV")
return Command::Name::COPYMV;
else if (str == "COPYVM")
return Command::Name::COPYVM;
else if (str == "ADD")
return Command::Name::ADD;
else if (str == "SUB")
return Command::Name::SUB;
else if (str == "MUL")
return Command::Name::MUL;
else if (str == "DIV")
return Command::Name::DIV;
else if (str == "LT")
return Command::Name::LT;
else if (str == "GT")
return Command::Name::GT;
else if (str == "EQ")
return Command::Name::EQ;
else if (str == "NEQ")
return Command::Name::NEQ;
else if (str == "LTE")
return Command::Name::LTE;
else if (str == "GTE")
return Command::Name::GTE;
else if (str == "NOT")
return Command::Name::NOT;
else if (str == "OR")
return Command::Name::OR;
else if (str == "AND")
return Command::Name::AND;
return Command::Name::INVALID;
}
std::string Command::commandStrFromName(Name name)
{
if (name == Name::DATA)
return "DATA";
else if (name == Name::PROC)
return "PROC";
else if (name == Name::ENDPROC)
return "ENDPROC";
else if (name == Name::DO)
return "DO";
else if (name == Name::DO_)
return "DO_";
else if (name == Name::WHILE)
return "WHILE";
else if (name == Name::ENDWHILE)
return "ENDWHILE";
else if (name == Name::STORE)
return "STORE";
else if (name == Name::IN)
return "IN";
else if (name == Name::OUT)
return "OUT";
else if (name == Name::ADDRESS)
return "ADDRESS";
else if (name == Name::COPYVV)
return "COPYVV";
else if (name == Name::COPYMV)
return "COPYMV";
else if (name == Name::COPYVM)
return "COPYVM";
else if (name == Name::ADD)
return "ADD";
else if (name == Name::SUB)
return "SUB";
else if (name == Name::MUL)
return "MUL";
else if (name == Name::DIV)
return "DIV";
else if (name == Name::LT)
return "LT";
else if (name == Name::GT)
return "GT";
else if (name == Name::EQ)
return "EQ";
else if (name == Name::NEQ)
return "NEQ";
else if (name == Name::LTE)
return "LTE";
else if (name == Name::GTE)
return "GTE";
else if (name == Name::NOT)
return "NOT";
else if (name == Name::OR)
return "OR";
else if (name == Name::AND)
return "AND";
return "INVALID";
}
| 27.967213 | 58 | 0.524619 | leonardo-ono |
b830c7c4211304406d7ac25ae9af2eb6d3dac48a | 1,179 | cpp | C++ | 10401.cpp | felikjunvianto/kfile-uvaoj-submissions | 5bd8b3b413ca8523abe412b0a0545f766f70ce63 | [
"MIT"
] | null | null | null | 10401.cpp | felikjunvianto/kfile-uvaoj-submissions | 5bd8b3b413ca8523abe412b0a0545f766f70ce63 | [
"MIT"
] | null | null | null | 10401.cpp | felikjunvianto/kfile-uvaoj-submissions | 5bd8b3b413ca8523abe412b0a0545f766f70ce63 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cmath>
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <vector>
#include <utility>
#include <stack>
#include <queue>
#include <map>
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define pi 2*acos(0.0)
#define eps 1e-9
#define PII pair<int,int>
#define PDD pair<double,double>
#define LL long long
#define INF 1000000000
using namespace std;
char col[20];
LL dp[20][20];
int panjang;
int dec(char T)
{
if(T<='9') return(T-'0');
return(T-'A'+10);
}
LL solve(int y,int x)
{
if(x+1==panjang) return(1);
if(dp[y][x]==-1)
{
dp[y][x]=0;
if(col[x+1]=='?')
{
for(int z=1;z<=panjang;z++)
if(abs(z-y)>1) dp[y][x]+=solve(z,x+1);
}
else
{
int next=dec(col[x+1]);
if(abs(next-y)>1) dp[y][x]+=solve(next,x+1);
}
}
return(dp[y][x]);
}
int main()
{
while(scanf("%s",col)!=EOF)
{
panjang=strlen(col);
memset(dp,-1,sizeof(dp));
LL ans=0;
if(col[0]=='?') for(int x=1;x<=panjang;x++) ans+=solve(x,0); else
ans=solve(dec(col[0]),0);
printf("%lld\n",ans);
}
return 0;
}
| 16.605634 | 68 | 0.566582 | felikjunvianto |
b836c787925ac977b39fd05e124a121d5b967c68 | 2,109 | cpp | C++ | Compiler Design Lab/code/LAB10/leaders-19_61.cpp | TanmayVig/sem6Labs | 68de98eae695806b0317012bb9c634d3124f5062 | [
"MIT"
] | null | null | null | Compiler Design Lab/code/LAB10/leaders-19_61.cpp | TanmayVig/sem6Labs | 68de98eae695806b0317012bb9c634d3124f5062 | [
"MIT"
] | null | null | null | Compiler Design Lab/code/LAB10/leaders-19_61.cpp | TanmayVig/sem6Labs | 68de98eae695806b0317012bb9c634d3124f5062 | [
"MIT"
] | null | null | null | // identify leaders and then blocks
#include <bits/stdc++.h>
using namespace std;
int create_num(string s, size_t found)
{
int num = 0, ind = found + 5;
while (isdigit(s[ind]))
{
num = num * 10 + (s[ind++] - '0');
}
return num;
}
class Block
{
public:
vector<string> code;
vector<int> gotu;
pair<int, int> boundry;
public:
Block(vector<string> tac, int i, int j)
{
for (int k = i - 1; k < j; k++)
code.push_back(tac[k]);
boundry = {i, j};
size_t found_if = tac[j - 1].find("if");
size_t found_goto = tac[j - 1].find("goto");
if (found_if != string::npos || found_goto == string::npos)
{
gotu.push_back(j + 1);
}
if (found_goto != string::npos)
{
gotu.push_back(create_num(tac[j - 1], found_goto));
}
}
};
int main()
{
cout << "TANMAY VIG\n19BCS061\n";
set<int> leaders_set;
vector<int> leaders;
vector<string> tac;
string line;
fstream file;
file.open("./TAC.txt", ios::in);
if (file.is_open())
{
while (getline(file, line))
{
tac.push_back(line);
}
}
file.close();
leaders_set.insert(1);
int ind = 1;
for (string s : tac)
{
size_t found = s.find("goto");
if (found != string::npos)
{
leaders_set.insert(ind + 1);
leaders_set.insert(create_num(s, found));
}
ind++;
}
leaders.assign(leaders_set.begin(), leaders_set.end());
// file.open("./leaders.txt", ios::out);
vector<Block> blocks;
for (int i = 0; i < leaders.size(); i++)
{
blocks.push_back(Block(tac, leaders[i], (i == leaders.size() - 1) ? tac.size() : leaders[i + 1] - 1));
}
int c = 0;
cout << "Block\tLeader\tGoto\n";
for (Block b : blocks)
{
cout << "B" << c++ << ":\t";
cout << b.boundry.first << "\t";
for (int i : b.gotu)
{
cout << i << ",";
}
cout << endl;
}
cout << endl;
return 0;
} | 22.2 | 110 | 0.488383 | TanmayVig |
b8387e639b1e2d38c75e2aaf3196407e8fe24922 | 3,732 | hpp | C++ | client/systems/ui_toolkit.hpp | Exonical/Vanguard_Wasteland.cup_chernarus_A3 | ee8f51807847f35c924bb8bf701e863387b603b8 | [
"MIT"
] | 1 | 2020-07-23T13:49:05.000Z | 2020-07-23T13:49:05.000Z | client/systems/ui_toolkit.hpp | Exonical/Vanguard_Wasteland.cup_chernarus_A3 | ee8f51807847f35c924bb8bf701e863387b603b8 | [
"MIT"
] | null | null | null | client/systems/ui_toolkit.hpp | Exonical/Vanguard_Wasteland.cup_chernarus_A3 | ee8f51807847f35c924bb8bf701e863387b603b8 | [
"MIT"
] | null | null | null | // ******************************************************************************************
// * This project is licensed under the GNU Affero GPL v3. Copyright © 2014 A3Wasteland.com *
// ******************************************************************************************
// @file Name: ui_toolkit.hpp
// @file Author: AgentRev
// Arma UI Mini Toolkit v1.0 by AgentRev
// Uncomment the define below if you want your UIs to scale according to the UI size selected by the user
//#define FOLLOW_UI_SIZE
// Uncomment the define below if you want your UIs to scale according to the resolution selected by the user
#define FOLLOW_RESOLUTION
// This is the percentage from the dev resolution that the UI must start compensating in order to stay at a reasonable size (ex: UI cannot get smaller than 75% from the dev resolution)
#define FOLLOW_RES_LOWER_CAP 0.75
// Effects:
// FOLLOW_UI_SIZE only = UI will be scaled according to the user's UI size, relative from UI_SIZE_DEV below, regardless of the resolution (not recommended)
// FOLLOW_RESOLUTION only = UI will be scaled according to the resolution, relative from RES_Y_DEV below, regardless of the user's UI size
// both commented = UI will be the same size in pixels across all UI sizes and resolutions
// both uncommented = UI will be scaled according to the resolution, then scaled according to the user's UI size
// ----- Interface size & resolution -----
#define UI_VSMALL 0.47
#define UI_SMALL 0.55
#define UI_NORMAL 0.7
#define UI_LARGE 0.85
#define UI_VLARGE 1.0
#define UI_SIZE_DEV UI_SMALL // If you want your text to stay the same size across all UI sizes, change this to your UI size
#define UI_SIZE (getResolution select 5) // Interface size selected in game options
#define RES_Y_DEV 1080 // If you want your UIs to stay the same size across all resolutions, change this to your game's resolution height
#define RES_Y (getResolution select 1) // Resolution height in pixels
// ----- Safezone & scales -----
#define SZ_LEFT safezoneX // X left
#define SZ_RIGHT (1 - SZ_LEFT) // X right
#define SZ_TOP safezoneY // Y top
#define SZ_BOTTOM (1 - SZ_TOP) // Y bottom
// Determine if UI & text scales are relative to UI size
#ifdef FOLLOW_UI_SIZE
#define UI_SCALE (UI_SIZE / UI_SIZE_DEV) // Constant UI scale across all UI sizes
#define TEXT_SCALE_UI 1 // Regular text scale
#else
#define UI_SCALE 1 // Regular UI scale
#define TEXT_SCALE_UI (UI_SIZE_DEV / UI_SIZE) // Compensate text scale against UI size
#endif
// Determine if UI scale is relative to resolution
#ifdef FOLLOW_RESOLUTION
#define RES_SCALE (((RES_Y_DEV * FOLLOW_RES_LOWER_CAP) / RES_Y) max 1) // Regular UI scale, with lower cap
#else
#define RES_SCALE (RES_Y_DEV / RES_Y) // Constant UI scale across all resolutions below dev resolution
#endif
#define TEXT_SCALE (TEXT_SCALE_UI * RES_SCALE) // Compensate text scale against resolution
// Set scales
#define SZ_SCALE_ABS (safezoneW min safezoneH)
#define SZ_SCALE (SZ_SCALE_ABS * RES_SCALE * UI_SCALE) // the smallest safezone is used for size ref (because W < H if ratio < 4/3)
#define X_SCALE (SZ_SCALE * 0.75) // cancels 4/3 ratio applied on X and W values by engine, so that X and Y have a uniform scale
#define Y_SCALE (SZ_SCALE * 1.0)
// Offsets
#define X_OFFSET 0
#define Y_OFFSET 0
// Positions relative to top left, plus above offsets
#define X_POS(VALUE) (SZ_LEFT + ((VALUE + X_OFFSET) * X_SCALE)) // stretches X value to full screen width
#define Y_POS(VALUE) (SZ_TOP + ((VALUE + Y_OFFSET) * Y_SCALE)) // stretches Y value to full screen height
// Function to find child offset relative to parent pos for centering inside
#define CENTER(PARENT_SIZE,CHILD_SIZE) (((PARENT_SIZE) / 2) - ((CHILD_SIZE) / 2))
| 48.467532 | 184 | 0.71463 | Exonical |
b8396941d68c6c4ea34d3ddc21475f5855b2ccee | 12,577 | cpp | C++ | QP/v5.4.2/qpcpp/examples/arm-cm/game_ek-lm3s811/mine1.cpp | hyller/GladiatorCots | 36a69df68675bb40b562081c531e6674037192a8 | [
"Unlicense"
] | null | null | null | QP/v5.4.2/qpcpp/examples/arm-cm/game_ek-lm3s811/mine1.cpp | hyller/GladiatorCots | 36a69df68675bb40b562081c531e6674037192a8 | [
"Unlicense"
] | null | null | null | QP/v5.4.2/qpcpp/examples/arm-cm/game_ek-lm3s811/mine1.cpp | hyller/GladiatorCots | 36a69df68675bb40b562081c531e6674037192a8 | [
"Unlicense"
] | null | null | null | //****************************************************************************
// Model: game.qm
// File: ./mine1.cpp
//
// This code has been generated by QM tool (see state-machine.com/qm).
// DO NOT EDIT THIS FILE MANUALLY. All your changes will be lost.
//
// This program is open source 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.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
//****************************************************************************
//${.::mine1.cpp} ............................................................
#include "qpcpp.h"
#include "bsp.h"
#include "game.h"
Q_DEFINE_THIS_FILE
// encapsulated delcaration of the Mine1 HSM ---------------------------------
namespace GAME {
//${AOs::Mine1} ..............................................................
class Mine1 : public QP::QMsm {
private:
uint8_t m_x;
uint8_t m_y;
uint8_t m_exp_ctr;
public:
Mine1()
: QMsm(Q_STATE_CAST(&Mine1::initial))
{}
protected:
static QP::QState initial(Mine1 * const me, QP::QEvt const * const e);
static QP::QState unused (Mine1 * const me, QP::QEvt const * const e);
static QP::QMState const unused_s;
static QP::QState used (Mine1 * const me, QP::QEvt const * const e);
static QP::QState used_x(Mine1 * const me);
static QP::QMState const used_s;
static QP::QState exploding (Mine1 * const me, QP::QEvt const * const e);
static QP::QState exploding_e(Mine1 * const me);
static QP::QMState const exploding_s;
static QP::QState planted (Mine1 * const me, QP::QEvt const * const e);
static QP::QMState const planted_s;
};
} // namespace GAME
namespace GAME {
// local objects -------------------------------------------------------------
static Mine1 l_mine1[GAME_MINES_MAX]; // a pool of type-1 mines
//............................................................................
QP::QMsm *Mine1_getInst(uint8_t id) {
Q_REQUIRE(id < GAME_MINES_MAX);
return &l_mine1[id];
}
// helper function to provide the ID of this mine ............................
static inline uint8_t MINE_ID(Mine1 const * const me) {
return static_cast<uint8_t>(me - l_mine1);
}
} // namespace GAME
// Mine1 class definition ----------------------------------------------------
namespace GAME {
//${AOs::Mine1} ..............................................................
//${AOs::Mine1::SM} ..........................................................
QP::QState Mine1::initial(Mine1 * const me, QP::QEvt const * const e) {
static QP::QMTranActTable const tatbl_ = { // transition-action table
&unused_s,
{
Q_ACTION_CAST(0) // zero terminator
}
};
// ${AOs::Mine1::SM::initial}
static bool dict_sent = false;
if (!dict_sent) {
dict_sent = true;
// object dictionaries for Mine1 pool...
QS_OBJ_DICTIONARY(&l_mine1[0]);
QS_OBJ_DICTIONARY(&l_mine1[1]);
QS_OBJ_DICTIONARY(&l_mine1[2]);
QS_OBJ_DICTIONARY(&l_mine1[3]);
QS_OBJ_DICTIONARY(&l_mine1[4]);
// function dictionaries for Mine1 SM
QS_FUN_DICTIONARY(&Mine1::initial);
QS_FUN_DICTIONARY(&Mine1::unused);
QS_FUN_DICTIONARY(&Mine1::used);
QS_FUN_DICTIONARY(&Mine1::planted);
QS_FUN_DICTIONARY(&Mine1::exploding);
}
// local signals
QS_SIG_DICTIONARY(MINE_PLANT_SIG, me);
QS_SIG_DICTIONARY(MINE_DISABLED_SIG, me);
QS_SIG_DICTIONARY(MINE_RECYCLE_SIG, me);
QS_SIG_DICTIONARY(SHIP_IMG_SIG, me);
QS_SIG_DICTIONARY(MISSILE_IMG_SIG, me);
(void)e; // unused parameter
return QM_TRAN_INIT(&tatbl_);
}
//${AOs::Mine1::SM::unused} ..................................................
QP::QMState const Mine1::unused_s = {
static_cast<QP::QMState const *>(0), // superstate (top)
Q_STATE_CAST(&unused),
Q_ACTION_CAST(0), // no entry action
Q_ACTION_CAST(0), // no exit action
Q_ACTION_CAST(0) // no intitial tran.
};
// ${AOs::Mine1::SM::unused}
QP::QState Mine1::unused(Mine1 * const me, QP::QEvt const * const e) {
QP::QState status_;
switch (e->sig) {
// ${AOs::Mine1::SM::unused::MINE_PLANT}
case MINE_PLANT_SIG: {
static QP::QMTranActTable const tatbl_ = { // transition-action table
&planted_s,
{
Q_ACTION_CAST(0) // zero terminator
}
};
me->m_x = Q_EVT_CAST(ObjectPosEvt)->x;
me->m_y = Q_EVT_CAST(ObjectPosEvt)->y;
status_ = QM_TRAN(&tatbl_);
break;
}
default: {
status_ = QM_SUPER();
break;
}
}
return status_;
}
//${AOs::Mine1::SM::used} ....................................................
QP::QMState const Mine1::used_s = {
static_cast<QP::QMState const *>(0), // superstate (top)
Q_STATE_CAST(&used),
Q_ACTION_CAST(0), // no entry action
Q_ACTION_CAST(&used_x),
Q_ACTION_CAST(0) // no intitial tran.
};
// ${AOs::Mine1::SM::used}
QP::QState Mine1::used_x(Mine1 * const me) {
// tell the Tunnel that this mine is becoming disabled
MineEvt *mev = Q_NEW(MineEvt, MINE_DISABLED_SIG);
mev->id = MINE_ID(me);
AO_Tunnel->POST(mev, me);
return QM_EXIT(&used_s);
}
// ${AOs::Mine1::SM::used}
QP::QState Mine1::used(Mine1 * const me, QP::QEvt const * const e) {
QP::QState status_;
switch (e->sig) {
// ${AOs::Mine1::SM::used::MINE_RECYCLE}
case MINE_RECYCLE_SIG: {
static struct {
QP::QMState const *target;
QP::QActionHandler act[2];
} const tatbl_ = { // transition-action table
&unused_s,
{
Q_ACTION_CAST(&used_x), // exit
Q_ACTION_CAST(0) // zero terminator
}
};
status_ = QM_TRAN(&tatbl_);
break;
}
default: {
status_ = QM_SUPER();
break;
}
}
return status_;
}
//${AOs::Mine1::SM::used::exploding} .........................................
QP::QMState const Mine1::exploding_s = {
&Mine1::used_s, // superstate
Q_STATE_CAST(&exploding),
Q_ACTION_CAST(&exploding_e),
Q_ACTION_CAST(0), // no exit action
Q_ACTION_CAST(0) // no intitial tran.
};
// ${AOs::Mine1::SM::used::exploding}
QP::QState Mine1::exploding_e(Mine1 * const me) {
me->m_exp_ctr = 0U;
return QM_ENTRY(&exploding_s);
}
// ${AOs::Mine1::SM::used::exploding}
QP::QState Mine1::exploding(Mine1 * const me, QP::QEvt const * const e) {
QP::QState status_;
switch (e->sig) {
// ${AOs::Mine1::SM::used::exploding::TIME_TICK}
case TIME_TICK_SIG: {
// ${AOs::Mine1::SM::used::exploding::TIME_TICK::[stillonscreen?]}
if ((me->m_x >= GAME_SPEED_X) && (me->m_exp_ctr < 15)) {
++me->m_exp_ctr; // advance the explosion counter
me->m_x -= GAME_SPEED_X; // move explosion by 1 step
// tell the Game to render the current stage of Explosion
ObjectImageEvt *oie = Q_NEW(ObjectImageEvt, EXPLOSION_SIG);
oie->x = me->m_x + 1U; // x of explosion
oie->y = (int8_t)((int)me->m_y - 4 + 2); // y of explosion
oie->bmp = EXPLOSION0_BMP + (me->m_exp_ctr >> 2);
AO_Tunnel->POST(oie, me);
status_ = QM_HANDLED();
}
// ${AOs::Mine1::SM::used::exploding::TIME_TICK::[else]}
else {
static struct {
QP::QMState const *target;
QP::QActionHandler act[2];
} const tatbl_ = { // transition-action table
&unused_s,
{
Q_ACTION_CAST(&used_x), // exit
Q_ACTION_CAST(0) // zero terminator
}
};
status_ = QM_TRAN(&tatbl_);
}
break;
}
default: {
status_ = QM_SUPER();
break;
}
}
return status_;
}
//${AOs::Mine1::SM::used::planted} ...........................................
QP::QMState const Mine1::planted_s = {
&Mine1::used_s, // superstate
Q_STATE_CAST(&planted),
Q_ACTION_CAST(0), // no entry action
Q_ACTION_CAST(0), // no exit action
Q_ACTION_CAST(0) // no intitial tran.
};
// ${AOs::Mine1::SM::used::planted}
QP::QState Mine1::planted(Mine1 * const me, QP::QEvt const * const e) {
QP::QState status_;
switch (e->sig) {
// ${AOs::Mine1::SM::used::planted::TIME_TICK}
case TIME_TICK_SIG: {
// ${AOs::Mine1::SM::used::planted::TIME_TICK::[me->m_x>=GAME_SPEED_X]}
if (me->m_x >= GAME_SPEED_X) {
me->m_x -= GAME_SPEED_X; // move the mine 1 step
// tell the Tunnel to draw the Mine
ObjectImageEvt *oie = Q_NEW(ObjectImageEvt, MINE_IMG_SIG);
oie->x = me->m_x;
oie->y = me->m_y;
oie->bmp = MINE1_BMP;
AO_Tunnel->POST(oie, me);
status_ = QM_HANDLED();
}
// ${AOs::Mine1::SM::used::planted::TIME_TICK::[else]}
else {
static struct {
QP::QMState const *target;
QP::QActionHandler act[2];
} const tatbl_ = { // transition-action table
&unused_s,
{
Q_ACTION_CAST(&used_x), // exit
Q_ACTION_CAST(0) // zero terminator
}
};
status_ = QM_TRAN(&tatbl_);
}
break;
}
// ${AOs::Mine1::SM::used::planted::SHIP_IMG}
case SHIP_IMG_SIG: {
uint8_t x = Q_EVT_CAST(ObjectImageEvt)->x;
uint8_t y = Q_EVT_CAST(ObjectImageEvt)->y;
uint8_t bmp = Q_EVT_CAST(ObjectImageEvt)->bmp;
// ${AOs::Mine1::SM::used::planted::SHIP_IMG::[collisionwithMINE1_BMP?]}
if (do_bitmaps_overlap(MINE1_BMP, me->m_x, me->m_y, bmp, x, y)) {
static struct {
QP::QMState const *target;
QP::QActionHandler act[2];
} const tatbl_ = { // transition-action table
&unused_s,
{
Q_ACTION_CAST(&used_x), // exit
Q_ACTION_CAST(0) // zero terminator
}
};
static MineEvt const mine1_hit(HIT_MINE_SIG, 1U);
AO_Ship->POST(&mine1_hit, me);
// go straight to 'disabled' and let the Ship do
// the exploding
status_ = QM_TRAN(&tatbl_);
}
else {
status_ = QM_UNHANDLED();
}
break;
}
// ${AOs::Mine1::SM::used::planted::MISSILE_IMG}
case MISSILE_IMG_SIG: {
uint8_t x = Q_EVT_CAST(ObjectImageEvt)->x;
uint8_t y = Q_EVT_CAST(ObjectImageEvt)->y;
uint8_t bmp = Q_EVT_CAST(ObjectImageEvt)->bmp;
// ${AOs::Mine1::SM::used::planted::MISSILE_IMG::[collisionwithMINE1_BMP?]}
if (do_bitmaps_overlap(MINE1_BMP, me->m_x, me->m_y, bmp, x, y)) {
static struct {
QP::QMState const *target;
QP::QActionHandler act[2];
} const tatbl_ = { // transition-action table
&exploding_s,
{
Q_ACTION_CAST(&exploding_e), // entry
Q_ACTION_CAST(0) // zero terminator
}
};
static ScoreEvt const mine1_destroyed(DESTROYED_MINE_SIG, 25U);
AO_Missile->POST(&mine1_destroyed, me);
status_ = QM_TRAN(&tatbl_);
}
else {
status_ = QM_UNHANDLED();
}
break;
}
default: {
status_ = QM_SUPER();
break;
}
}
return status_;
}
} // namespace GAME
| 36.140805 | 87 | 0.50481 | hyller |
b83b81095c06176978c02a6cb54c6c024248951c | 143 | cpp | C++ | src/10000/10569.cpp14.cpp | upple/BOJ | e6dbf9fd17fa2b458c6a781d803123b14c18e6f1 | [
"MIT"
] | 8 | 2018-04-12T15:54:09.000Z | 2020-06-05T07:41:15.000Z | src/10000/10569.cpp14.cpp | upple/BOJ | e6dbf9fd17fa2b458c6a781d803123b14c18e6f1 | [
"MIT"
] | null | null | null | src/10000/10569.cpp14.cpp | upple/BOJ | e6dbf9fd17fa2b458c6a781d803123b14c18e6f1 | [
"MIT"
] | null | null | null | #include <stdio.h>
int main()
{
int t, v, e;
scanf("%d", &t);
while(scanf("%d %d", &v, &e)!=EOF)
printf("%d\n", 2+e-v);
}
| 14.3 | 38 | 0.426573 | upple |
b83ffb464dcdf33a5a34274c2c0cba3f0f596985 | 1,216 | hpp | C++ | libhttpserver/HTTPHeaders.hpp | harsath/SSL-HTTP-Application-Server-CPP-RFC7231 | 140fb59997e9049bb4ca89806df527556ed890a0 | [
"MIT"
] | 5 | 2020-09-16T02:06:44.000Z | 2020-11-10T01:59:55.000Z | libhttpserver/HTTPHeaders.hpp | harsathAI/HTTP-Application-Server-CPP-RFC7231 | 140fb59997e9049bb4ca89806df527556ed890a0 | [
"MIT"
] | 9 | 2020-10-23T12:20:08.000Z | 2021-01-22T03:44:38.000Z | libhttpserver/HTTPHeaders.hpp | harsathAI/HTTP-Application-Server-CPP-RFC7231 | 140fb59997e9049bb4ca89806df527556ed890a0 | [
"MIT"
] | null | null | null | #pragma once
#include "HTTPHelpers.hpp"
#include <vector>
#include "HTTPConstants.hpp"
namespace HTTP{
class HTTPHeaders{
private:
std::unordered_map<std::string, std::string> _HTTPHeaders;
HTTP::HTTPConst::HTTP_RESPONSE_CODE _parser_response =
HTTP::HTTPConst::HTTP_RESPONSE_CODE::OK;
std::vector<std::pair<std::string, std::string>> _header_pair_vector;
std::string first_line; // first line
auto _find_element_iter(const std::string&) noexcept;
public:
explicit HTTPHeaders(std::string&& ClientHeader);
explicit HTTPHeaders(const std::string& ClientHeader);
explicit HTTPHeaders(){}
void AddHeader(const std::pair<std::string, std::string>& header_pair) noexcept;
int RemoveHeader(const std::string& name) noexcept;
std::string BuildRawMessage() const noexcept;
std::optional<std::string> GetHeaderValue(const std::string& name) const noexcept;
std::size_t GetHeaderCount() const noexcept;
bool HeaderContains(const std::string& name) const noexcept;
std::vector<std::pair<std::string, std::string>> GetHeaderPairVector() const noexcept;
HTTP::HTTPConst::HTTP_RESPONSE_CODE
GetParseResponseCode() const noexcept;
~HTTPHeaders() = default;
};
}
| 36.848485 | 89 | 0.741776 | harsath |
cdc2b080ca48331aca20b7101fe4a67b1b2a5519 | 976 | hxx | C++ | ImageSharpOpenJpegNative/src/openjpeg.hxx | cinderblocks/ImageSharp.OpenJpeg | bf5c976a6dbfa0d2666be566c845a7410440cea2 | [
"Apache-2.0"
] | null | null | null | ImageSharpOpenJpegNative/src/openjpeg.hxx | cinderblocks/ImageSharp.OpenJpeg | bf5c976a6dbfa0d2666be566c845a7410440cea2 | [
"Apache-2.0"
] | null | null | null | ImageSharpOpenJpegNative/src/openjpeg.hxx | cinderblocks/ImageSharp.OpenJpeg | bf5c976a6dbfa0d2666be566c845a7410440cea2 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2022 Sjofn LLC. 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.
*/
#ifndef _ISOJ_OPENJPEG_OPENJP2_OPENJPEG_H_
#define _ISOJ_OPENJPEG_OPENJP2_OPENJPEG_H_
#include "ImageSharpOpenJpeg_Exports.hxx"
#include "shared.hxx"
#include <string>
IMAGESHARPOPENJPEG_EXPORT std::string* openjpeg_openjp2_opj_version()
{
const auto str = ::opj_version();
return new std::string(str);
}
#endif // _ISOJ_OPENJPEG_OPENJP2_OPENJPEG_H_ | 32.533333 | 75 | 0.762295 | cinderblocks |
cdc2f99ba0fdf3a7abe0447b3323186aaa5ddbe2 | 40,702 | cpp | C++ | src/test/syscoin_offer_tests.cpp | gtacoin-dev/gtacoin | f66f063b47ba973856c200074db1b95abf5ab794 | [
"MIT"
] | null | null | null | src/test/syscoin_offer_tests.cpp | gtacoin-dev/gtacoin | f66f063b47ba973856c200074db1b95abf5ab794 | [
"MIT"
] | null | null | null | src/test/syscoin_offer_tests.cpp | gtacoin-dev/gtacoin | f66f063b47ba973856c200074db1b95abf5ab794 | [
"MIT"
] | null | null | null | #include "test/test_gtacoin_services.h"
#include "utiltime.h"
#include "rpc/server.h"
#include "alias.h"
#include "feedback.h"
#include <boost/test/unit_test.hpp>
BOOST_GLOBAL_FIXTURE( GtacoinTestingSetup );
BOOST_FIXTURE_TEST_SUITE (gtacoin_offer_tests, BasicGtacoinTestingSetup)
BOOST_AUTO_TEST_CASE (generate_offernew)
{
printf("Running generate_offernew...\n");
UniValue r;
GenerateBlocks(5);
GenerateBlocks(5, "node2");
GenerateBlocks(5, "node3");
AliasNew("node1", "selleralias1", "password", "changeddata1");
// generate a good offer
string offerguid = OfferNew("node1", "selleralias1", "category", "title", "100", "0.05", "description", "USD");
// by default offers are set to private and not searchable
BOOST_CHECK_EQUAL(OfferFilter("node1", "", "On"), false);
// direct search should work
BOOST_CHECK_EQUAL(OfferFilter("node1", offerguid, "On"), true);
// should fail: generate an offer with unknown alias
BOOST_CHECK_THROW(r = CallRPC("node1", "offernew fooalias category title 100 0.05 description USD"), runtime_error);
// should fail: generate an offer with negative quantity
BOOST_CHECK_THROW(r = CallRPC("node1", "offernew selleralias1 category title -2 0.05 description USD"), runtime_error);
// should fail: generate an offer too-large category
string s257bytes = "SdfsdfdfsdsfSfsdfdfsdsfDsdsdsdsfsfsdsfsdsfdsfsdsfdsfsdsfsdSfsdfdfsdsfSfsdfdfsdsfDsdsdsdsfsfsdsfsdsfdsfsdsfdsfsdsfsdSfsdfdfsdsfSfsdfdfsdsfDsdsdsdsfsfsdsfsdsfdsfsdsfdsfsdsfsdSfsdfdfsdsfSfsdfdfsdsfDsdsdsdsfsfsdsfsdsfdsfsdsfdsfsdsfsdSfsdfdfsdsfSfsdfdfsdsDfdfddz";
BOOST_CHECK_THROW(r = CallRPC("node1", "offernew selleralias1 " + s257bytes + " title 100 0.05 description USD"), runtime_error);
// should fail: generate an offer too-large title
BOOST_CHECK_THROW(r = CallRPC("node1", "offernew selleralias1 category " + s257bytes + " 100 0.05 description USD"), runtime_error);
// should fail: generate an offer too-large description
string s1025bytes = "sasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfssdsfsdfsdfsdfsdfsdsdfdfsdfsdfsdfsdz";
BOOST_CHECK_THROW(r = CallRPC("node1", "offernew selleralias1 category title 100 0.05 " + s1025bytes + " USD"), runtime_error);
// should fail: generate an offer with invalid currency
BOOST_CHECK_THROW(r = CallRPC("node1", "offernew selleralias1 category title 100 0.05 description ZZZ"), runtime_error);
// TODO test payment options
}
BOOST_AUTO_TEST_CASE (generate_certoffer)
{
printf("Running generate_certoffer...\n");
UniValue r;
GenerateBlocks(5);
GenerateBlocks(5, "node2");
GenerateBlocks(5, "node3");
AliasNew("node1", "node1alias", "password", "node1aliasdata");
AliasNew("node1", "node1aliasa", "password", "node1aliasdata");
AliasNew("node2", "node2alias", "password", "node2aliasdata");
string certguid1 = CertNew("node1", "node1alias", "title", "data", "pub");
string certguid1a = CertNew("node1", "node1aliasa", "title", "data", "pub");
string certguid2 = CertNew("node2", "node2alias", "title", "data", "pub");
// generate a good cert offer
string offerguidnoncert = OfferNew("node1", "node1alias", "category", "title", "10", "0.05", "description", "USD");
string offerguid = OfferNew("node1", "node1alias", "certificates", "title", "1", "0.05", "description", "USD", certguid1);
string offerguid1 = OfferNew("node1", "node1alias", "certificates-music", "title", "1", "0.05", "description", "USD", certguid1);
// must use certificates category for certoffer
BOOST_CHECK_THROW(r = CallRPC("node1", "offernew node1alias category title 1 0.05 description USD " + certguid1), runtime_error);
// should fail: generate a cert offer using a quantity greater than 1
BOOST_CHECK_THROW(r = CallRPC("node1", "offernew node1alias certificates title 2 0.05 description USD " + certguid1), runtime_error);
// should fail: generate a cert offer using a zero quantity
BOOST_CHECK_THROW(r = CallRPC("node1", "offernew node1alias certificates title 0 0.05 description USD " + certguid1), runtime_error);
// should fail: generate a cert offer using an unlimited quantity
BOOST_CHECK_THROW(r = CallRPC("node1", "offernew node1alias certificates title -1 0.05 description USD " + certguid1), runtime_error);
// should fail: generate a cert offer using a cert guid you don't own
BOOST_CHECK_THROW(r = CallRPC("node1", "offernew node1alias certificates title 1 0.05 description USD " + certguid2), runtime_error);
// should fail: update non cert offer to cert category
BOOST_CHECK_THROW(r = CallRPC("node1", "offerupdate node1alias " + offerguidnoncert + " certificates title 1 0.15 description USD"), runtime_error);
// should fail: update non cert offer to cert sub category
BOOST_CHECK_THROW(r = CallRPC("node1", "offerupdate node1alias " + offerguidnoncert + " certificates>music title 1 0.15 description USD"), runtime_error);
// update cert category to sub category of certificates
OfferUpdate("node1", "node1alias", offerguid, "certificates-music", "titlenew", "1", "0.15", "descriptionnew", "USD", false, certguid1);
// should fail: try to change non cert offer to cert offer without cert category
BOOST_CHECK_THROW(r = CallRPC("node1", "offerupdate node1alias " + offerguidnoncert + " category title 1 0.15 description USD 0 " + certguid1), runtime_error);
// change non cert offer to cert offer
OfferUpdate("node1", "node1alias", offerguidnoncert, "certificates", "titlenew", "1", "0.15", "descriptionnew", "USD", false, certguid1);
// generate a cert offer if accepting only BTC
OfferNew("node1", "node1alias", "certificates", "title", "1", "0.05", "description", "USD", certguid1, "BTC");
// generate a cert offer if accepting BTC OR GTA
OfferNew("node1", "node1alias", "certificates", "title", "1", "0.05", "description", "USD", certguid1, "GTA+BTC");
// should fail: generate a cert offer using different alias for cert and offer
BOOST_CHECK_THROW(r = CallRPC("node1", "offernew node1alias certificates title 1 0.05 description USD " + certguid1a), runtime_error);
// should fail: generate a cert offer with invalid payment option
BOOST_CHECK_THROW(r = CallRPC("node1", "offernew node1alias certificates title 1 0.05 description USD " + certguid1 + " BTC+SSS"), runtime_error);
}
BOOST_AUTO_TEST_CASE (generate_offerwhitelists)
{
printf("Running generate_offerwhitelists...\n");
UniValue r;
GenerateBlocks(5);
GenerateBlocks(5, "node2");
GenerateBlocks(5, "node3");
AliasNew("node1", "sellerwhitelistalias", "password", "changeddata1");
AliasNew("node2", "selleraddwhitelistalias", "password", "changeddata1");
AliasNew("node2", "selleraddwhitelistalias1", "password", "changeddata1");
// generate a good offer
string offerguid = OfferNew("node1", "sellerwhitelistalias", "category", "title", "100", "10.00", "description", "GTA", "nocert");
// add to whitelist
OfferAddWhitelist("node1", offerguid, "selleraddwhitelistalias", "5");
BOOST_CHECK_THROW(CallRPC("node1", "offeraddwhitelist " + offerguid + " selleraddwhitelistalias 5"), runtime_error);
// add to whitelist
OfferAddWhitelist("node1", offerguid, "selleraddwhitelistalias1", "6");
// remove from whitelist
OfferRemoveWhitelist("node1", offerguid, "selleraddwhitelistalias");
BOOST_CHECK_THROW(CallRPC("node1", "offerremovewhitelist " + offerguid + " selleraddwhitelistalias"), runtime_error);
AliasUpdate("node1", "sellerwhitelistalias", "changeddata2", "privdata2");
AliasUpdate("node2", "selleraddwhitelistalias", "changeddata2", "privdata2");
AliasUpdate("node2", "selleraddwhitelistalias1", "changeddata2", "privdata2");
// add to whitelist
OfferAddWhitelist("node1", offerguid, "selleraddwhitelistalias", "4");
OfferClearWhitelist("node1", offerguid);
BOOST_CHECK_THROW(CallRPC("node1", "offerclearwhitelist " + offerguid), runtime_error);
OfferAddWhitelist("node1", offerguid, "selleraddwhitelistalias", "6");
OfferAccept("node1", "node2", "selleraddwhitelistalias1", offerguid, "1", "message");
AliasUpdate("node1", "sellerwhitelistalias", "changeddata2", "privdata2");
AliasUpdate("node2", "selleraddwhitelistalias", "changeddata2", "privdata2");
AliasUpdate("node2", "selleraddwhitelistalias1", "changeddata2", "privdata2");
OfferRemoveWhitelist("node1", offerguid, "selleraddwhitelistalias");
OfferAddWhitelist("node1", offerguid, "selleraddwhitelistalias", "1");
OfferAccept("node1", "node2", "selleraddwhitelistalias1", offerguid, "1", "message");
OfferAddWhitelist("node1", offerguid, "selleraddwhitelistalias1", "2");
OfferAccept("node1", "node2", "selleraddwhitelistalias1", offerguid, "1", "message");
OfferClearWhitelist("node1", offerguid);
}
BOOST_AUTO_TEST_CASE (generate_offernew_linkedoffer)
{
printf("Running generate_offernew_linkedoffer...\n");
UniValue r;
GenerateBlocks(5);
GenerateBlocks(5, "node2");
GenerateBlocks(5, "node3");
AliasNew("node1", "selleralias5", "password", "changeddata1");
AliasNew("node2", "selleralias6", "password", "changeddata1");
// generate a good offer
string offerguid = OfferNew("node1", "selleralias5", "category", "title", "100", "10.00", "description", "USD", "nocert");
OfferAddWhitelist("node1", offerguid, "selleralias6", "5");
string lofferguid = OfferLink("node2", "selleralias6", offerguid, "5", "newdescription");
// it was already added to whitelist, remove it and add it as 5% discount
OfferRemoveWhitelist("node1", offerguid, "selleralias6");
OfferAddWhitelist("node1", offerguid, "selleralias6", "5");
BOOST_CHECK_NO_THROW(r = CallRPC("node2", "offerinfo " + lofferguid));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "price").get_str(), "10.50");
// generate a cert offer using a negative percentage bigger or equal to than discount which was set to 5% (uses -5 in calculcation)
BOOST_CHECK_THROW(r = CallRPC("node2", "offerlink selleralias6 " + offerguid + " -5 newdescription"), runtime_error);
// should fail: generate a cert offer using too-large pergentage
BOOST_CHECK_THROW(r = CallRPC("node2", "offerlink selleralias6 " + offerguid + " 101 newdescription"), runtime_error);
// should fail: generate an offerlink with too-large description
string s1025bytes = "sasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfssdsfsdfsdfsdfsdfsdsdfdfsdfsdfsdfsdz";
BOOST_CHECK_THROW(r = CallRPC("node2", "offerlink selleralias6 " + offerguid + " 5 " + s1025bytes), runtime_error);
// let the offer expire
ExpireAlias("selleralias6");
// should fail: try to link against an expired offer
BOOST_CHECK_THROW(r = CallRPC("node1", "offerlink selleralias6 " + offerguid + " 5 newdescription"), runtime_error);
}
BOOST_AUTO_TEST_CASE (generate_offernew_linkedofferexmode)
{
printf("Running generate_offernew_linkedofferexmode...\n");
UniValue r;
GenerateBlocks(5);
GenerateBlocks(5, "node2");
GenerateBlocks(5, "node3");
AliasNew("node1", "selleralias8", "password", "changeddata1");
AliasNew("node2", "selleralias9", "password", "changeddata1");
// generate a good offer
string offerguid = OfferNew("node1", "selleralias8", "category", "title", "100", "0.05", "description", "USD");
// should fail: attempt to create a linked offer for a product without being on the whitelist
BOOST_CHECK_THROW(r = CallRPC("node2", "offerlink selleralias9 " + offerguid + " 5 newdescription"), runtime_error);
OfferAddWhitelist("node1", offerguid, "selleralias9", "5");
// should succeed: attempt to create a linked offer for a product while being on the whitelist
OfferLink("node2", "selleralias9", offerguid, "5", "newdescription");
}
BOOST_AUTO_TEST_CASE (generate_offernew_linkedlinkedoffer)
{
printf("Running generate_offernew_linkedlinkedoffer...\n");
UniValue r;
GenerateBlocks(5);
GenerateBlocks(5, "node2");
GenerateBlocks(5, "node3");
AliasNew("node1", "selleralias12", "password", "changeddata1");
AliasNew("node2", "selleralias13", "password", "changeddata1");
AliasNew("node3", "selleralias14", "password", "changeddata1");
// generate a good offer
string offerguid = OfferNew("node1", "selleralias12", "category", "title", "100", "0.05", "description", "USD", "nocert");
OfferAddWhitelist("node1", offerguid, "selleralias13", "5");
string lofferguid = OfferLink("node2", "selleralias13", offerguid, "5", "newdescription");
// should fail: try to generate a linked offer with a linked offer
BOOST_CHECK_THROW(r = CallRPC("node3", "offerlink selleralias14 " + lofferguid + " 5 newdescription"), runtime_error);
}
BOOST_AUTO_TEST_CASE (generate_offerupdate)
{
printf("Running generate_offerupdate...\n");
UniValue r;
GenerateBlocks(5);
GenerateBlocks(5, "node2");
GenerateBlocks(5, "node3");
AliasNew("node1", "selleralias2", "password", "changeddata1");
// generate a good offer
string offerguid = OfferNew("node1", "selleralias2", "category", "title", "100", "0.05", "description", "USD");
// perform a valid update
OfferUpdate("node1", "selleralias2", offerguid, "category", "titlenew", "90", "0.15", "descriptionnew");
// should fail: offer cannot be updated by someone other than owner
BOOST_CHECK_THROW(r = CallRPC("node2", "offerupdate selleralias2 " + offerguid + " category title 90 0.15 description"), runtime_error);
// should fail: generate an offer with unknown alias
BOOST_CHECK_THROW(r = CallRPC("node1", "offerupdate fooalias " + offerguid + " category title 90 0.15 description"), runtime_error);
// should fail: generate an offer too-large category
string s257bytes = "dSfsdfdfsdsfSfsdfdfsdsfDsdsdsdsfsfsdsfsdsfdsfsdsfdsfsdsfsdSfsdfdfsdsfSfsdfdfsdsfDsdsdsdsfsfsdsfsdsfdsfsdsfdsfsdsfsdSfsdfdfsdsfSfsdfdfsdsfDsdsdsdsfsfsdsfsdsfdsfsdsfdsfsdsfsdSfsdfdfsdsfSfsdfdfsdsfDsdsdsdsfsfsdsfsdsfdsfsdsfdsfsdsfsdSfsdfdfsdsfSfsdfdfsdsDfdfddz";
BOOST_CHECK_THROW(r = CallRPC("node1", "offerupdate selleralias2 " + offerguid + " " + s257bytes + " title 90 0.15 description"), runtime_error);
// should fail: generate an offer too-large title
BOOST_CHECK_THROW(r = CallRPC("node1", "offerupdate selleralias2 " + offerguid + " category " + s257bytes + " 90 0.15 description"), runtime_error);
// should fail: generate an offer too-large description
string s1025ytes = "dasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfssdsfsdfsdfsdfsdfsdsdfdfsdfsdfsdfsdz";
BOOST_CHECK_THROW(r = CallRPC("node1", "offerupdate selleralias2 " + offerguid + " category title 90 0.15 " + s1025ytes), runtime_error);
}
BOOST_AUTO_TEST_CASE (generate_offerupdate_editcurrency)
{
printf("Running generate_offerupdate_editcurrency...\n");
UniValue r;
GenerateBlocks(5);
GenerateBlocks(5, "node2");
GenerateBlocks(5, "node3");
AliasNew("node1", "selleraliascurrency", "password", "changeddata1");
AliasNew("node2", "buyeraliascurrency", "password", "changeddata2");
// generate a good offer
string offerguid = OfferNew("node1", "selleraliascurrency", "category", "title", "100", "0.05", "description", "USD");
// accept and confirm payment is accurate with usd
string acceptguid = OfferAccept("node1", "node2", "buyeraliascurrency", offerguid, "2", "message");
UniValue acceptRet = FindOfferAcceptList("node1", "selleraliascurrency", offerguid, acceptguid);
CAmount nTotal = find_value(acceptRet, "systotal").get_int64();
// 2690.1 GTA/USD
BOOST_CHECK_EQUAL(nTotal, AmountFromValue(2*0.05*2690.1));
// perform a valid update
OfferUpdate("node1", "selleraliascurrency", offerguid, "category", "titlenew", "90", "0.15", "descriptionnew", "CAD");
// accept and confirm payment is accurate with cad
acceptguid = OfferAccept("node1", "node2", "buyeraliascurrency", offerguid, "3", "message");
acceptRet = FindOfferAcceptList("node1", "selleraliascurrency", offerguid, acceptguid);
nTotal = find_value(acceptRet, "systotal").get_int64();
// 2698.0 GTA/CAD
BOOST_CHECK_EQUAL(nTotal, AmountFromValue(3*0.15*2698.0));
AliasUpdate("node1", "selleraliascurrency", "changeddata2", "privdata2");
AliasUpdate("node2", "buyeraliascurrency", "changeddata2", "privdata2");
OfferUpdate("node1", "selleraliascurrency", offerguid, "category", "titlenew", "90", "1.00", "descriptionnew", "GTA");
// accept and confirm payment is accurate with sys
acceptguid = OfferAccept("node1", "node2", "buyeraliascurrency", offerguid, "3", "message");
acceptRet = FindOfferAcceptList("node1", "selleraliascurrency", offerguid, acceptguid);
nTotal = find_value(acceptRet, "systotal").get_int64();
// 1 GTA/GTA
BOOST_CHECK_EQUAL(nTotal, AmountFromValue(3));
OfferUpdate("node1", "selleraliascurrency", offerguid, "category", "titlenew", "90", "0.00001000", "descriptionnew", "BTC");
// accept and confirm payment is accurate with btc
acceptguid = OfferAccept("node1", "node2", "buyeraliascurrency", offerguid, "4", "message");
acceptRet = FindOfferAcceptList("node1", "selleraliascurrency", offerguid, acceptguid);
nTotal = find_value(acceptRet, "systotal").get_int64();
// 100000.0 GTA/BTC
BOOST_CHECK_EQUAL(nTotal, AmountFromValue(4*0.00001000*100000.0));
// try to update currency and accept in same block, ensure payment uses old currency not new
BOOST_CHECK_NO_THROW(CallRPC("node1", "offerupdate selleraliascurrency " + offerguid + " category title 90 0.2 desc EUR"));
BOOST_CHECK_NO_THROW(r = CallRPC("node2", "offeraccept buyeraliascurrency " + offerguid + " 10 message"));
const UniValue &arr = r.get_array();
acceptguid = arr[1].get_str();
GenerateBlocks(2);
GenerateBlocks(3);
GenerateBlocks(5, "node2");
acceptRet = FindOfferAcceptList("node1", "selleraliascurrency", offerguid, acceptguid);
nTotal = find_value(acceptRet, "systotal").get_int64();
// still used BTC conversion amount
BOOST_CHECK_EQUAL(nTotal, AmountFromValue(10*0.00001000*100000.0));
// 2695.2 GTA/EUR
acceptguid = OfferAccept("node1", "node2", "buyeraliascurrency", offerguid, "3", "message");
acceptRet = FindOfferAcceptList("node1", "selleraliascurrency", offerguid, acceptguid);
nTotal = find_value(acceptRet, "systotal").get_int64();
BOOST_CHECK_EQUAL(nTotal, AmountFromValue(3*0.2*2695.2));
// linked offer with root and linked offer changing currencies
// external payments
}
BOOST_AUTO_TEST_CASE (generate_offeraccept)
{
printf("Running generate_offeraccept...\n");
UniValue r;
GenerateBlocks(5);
GenerateBlocks(5, "node2");
GenerateBlocks(5, "node3");
AliasNew("node1", "selleralias3", "password", "somedata");
AliasNew("node2", "buyeralias3", "password", "somedata");
// generate a good offer
string offerguid = OfferNew("node1", "selleralias3", "category", "title", "100", "0.01", "description", "USD");
// perform a valid accept
string acceptguid = OfferAccept("node1", "node2", "buyeralias3", offerguid, "1", "message");
// should fail: generate an offer accept with too-large message
string s1024bytes = "asdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfasdfasdfsadfsadassdsfsdfsdfsdfsdfsdsdfssdsfsdfsdfsdfsdfsdsdfdfsdfsdfsdfsdz";
BOOST_CHECK_THROW(r = CallRPC("node2", "offeraccept buyeralias3 " + offerguid + " 1 " + s1024bytes), runtime_error);
// perform an accept on negative quantity
BOOST_CHECK_THROW(r = CallRPC("node2", "offeraccept buyeralias3 " + offerguid + " -1 message"), runtime_error);
// perform an accept on zero quantity
BOOST_CHECK_THROW(r = CallRPC("node2", "offeraccept buyeralias3 " + offerguid + " 0 message"), runtime_error);
// perform an accept on more items than available
BOOST_CHECK_THROW(r = CallRPC("node2", "offeraccept buyeralias3 " + offerguid + " 100 message"), runtime_error);
}
BOOST_AUTO_TEST_CASE (generate_linkedaccept)
{
printf("Running generate_linkedaccept...\n");
UniValue r;
GenerateBlocks(5);
GenerateBlocks(5, "node2");
GenerateBlocks(5, "node3");
AliasNew("node1", "node1aliaslinked", "password", "node1aliasdata");
AliasNew("node2", "node2aliaslinked", "password", "node2aliasdata");
AliasNew("node3", "node3aliaslinked", "password", "node2aliasdata");
string offerguid = OfferNew("node1", "node1aliaslinked", "category", "title", "10", "0.05", "description", "USD", "nocert");
OfferAddWhitelist("node1", offerguid, "node2aliaslinked", "0");
string lofferguid = OfferLink("node2", "node2aliaslinked", offerguid, "5", "newdescription");
LinkOfferAccept("node1", "node3", "node3aliaslinked", lofferguid, "6", "message", "node2");
}
BOOST_AUTO_TEST_CASE (generate_cert_linkedaccept)
{
printf("Running generate_cert_linkedaccept...\n");
UniValue r;
GenerateBlocks(5);
GenerateBlocks(5, "node2");
GenerateBlocks(5, "node3");
AliasNew("node1", "node1alias", "password1", "node1aliasdata");
AliasNew("node2", "node2alias", "password2", "node2aliasdata");
AliasNew("node3", "node3alias", "password3", "node2aliasdata");
string certguid = CertNew("node1", "node1alias", "title", "data", "pubdata");
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "certinfo " + certguid));
BOOST_CHECK(find_value(r.get_obj(), "ismine").get_str() == "true");
BOOST_CHECK(find_value(r.get_obj(), "alias").get_str() == "node1alias");
// generate a good cert offer
string offerguid = OfferNew("node1", "node1alias", "certificates", "title", "1", "0.05", "description", "USD", certguid);
OfferAddWhitelist("node1", offerguid, "node2alias", "0");
string lofferguid = OfferLink("node2", "node2alias", offerguid, "5", "newdescription");
AliasUpdate("node1", "node1alias", "changeddata2", "privdata2");
AliasUpdate("node2", "node2alias", "changeddata2", "privdata2");
AliasUpdate("node3", "node3alias", "changeddata3", "privdata3");
LinkOfferAccept("node1", "node3", "node3alias", lofferguid, "1", "message", "node2");
GenerateBlocks(5, "node1");
GenerateBlocks(5, "node3");
// cert does not get transferred, need to do it manually after the sale
BOOST_CHECK_NO_THROW(r = CallRPC("node3", "certinfo " + certguid));
BOOST_CHECK(find_value(r.get_obj(), "ismine").get_str() == "false");
BOOST_CHECK(find_value(r.get_obj(), "alias").get_str() == "node1alias");
}
BOOST_AUTO_TEST_CASE (generate_offeracceptfeedback)
{
printf("Running generate_offeracceptfeedback...\n");
UniValue r;
GenerateBlocks(5);
GenerateBlocks(5, "node2");
GenerateBlocks(5, "node3");
AliasNew("node1", "selleraliasfeedback", "password", "somedata");
AliasNew("node2", "buyeraliasfeedback", "password", "somedata");
// generate a good offer
string offerguid = OfferNew("node1", "selleraliasfeedback", "category", "title", "100", "0.01", "description", "USD");
// perform a valid accept
string acceptguid = OfferAccept("node1", "node2", "buyeraliasfeedback", offerguid, "1", "message");
// seller leaves feedback first
OfferAcceptFeedback("node1", "selleraliasfeedback", offerguid, acceptguid, "feedbackseller", "1", FEEDBACKSELLER, true);
// seller can leave feedback twice in a row
OfferAcceptFeedback("node1", "selleraliasfeedback", offerguid, acceptguid, "feedbackseller", "1", FEEDBACKSELLER, false);
// then buyer can leave feedback
OfferAcceptFeedback("node2","buyeraliasfeedback", offerguid, acceptguid, "feedbackbuyer", "5", FEEDBACKBUYER, true);
// can leave feedback twice in arow
OfferAcceptFeedback("node2","buyeraliasfeedback", offerguid, acceptguid, "feedbackbuyer2", "5", FEEDBACKBUYER, false);
// create up to 10 replies each
for(int i =0;i<8;i++)
{
// keep alive
OfferUpdate("node1", "selleraliasfeedback", offerguid, "category", "titlenew", "90", "0.01", "descriptionnew", "USD");
// seller can reply but not rate
OfferAcceptFeedback("node1", "selleraliasfeedback",offerguid, acceptguid, "feedbackseller1", "2", FEEDBACKSELLER, false);
// buyer can reply but not rate
OfferAcceptFeedback("node2", "buyeraliasfeedback", offerguid, acceptguid, "feedbackbuyer1", "3", FEEDBACKBUYER, false);
}
string offerfeedbackstr = "offeracceptfeedback " + offerguid + " " + acceptguid + " testfeedback 1";
// now you can't leave any more feedback as a seller
BOOST_CHECK_THROW(r = CallRPC("node1", offerfeedbackstr), runtime_error);
// perform a valid accept
acceptguid = OfferAccept("node1", "node2", "buyeraliasfeedback", offerguid, "1", "message");
GenerateBlocks(5, "node2");
// this time buyer leaves feedback first
OfferAcceptFeedback("node2","buyeraliasfeedback", offerguid, acceptguid, "feedbackbuyer", "1", FEEDBACKBUYER, true);
// buyer can leave feedback three times in a row
OfferAcceptFeedback("node2", "buyeraliasfeedback",offerguid, acceptguid, "feedbackbuyer", "1", FEEDBACKBUYER, false);
OfferAcceptFeedback("node2", "buyeraliasfeedback",offerguid, acceptguid, "feedbackbuyer", "1", FEEDBACKBUYER, false);
// then seller can leave feedback
OfferAcceptFeedback("node1", "selleraliasfeedback",offerguid, acceptguid, "feedbackseller", "5", FEEDBACKSELLER, true);
OfferAcceptFeedback("node1", "selleraliasfeedback",offerguid, acceptguid, "feedbackseller2", "4", FEEDBACKSELLER, false);
OfferAcceptFeedback("node1", "selleraliasfeedback",offerguid, acceptguid, "feedbackseller2", "4", FEEDBACKSELLER, false);
}
BOOST_AUTO_TEST_CASE (generate_offerexpired)
{
printf("Running generate_offerexpired...\n");
UniValue r;
GenerateBlocks(5);
GenerateBlocks(5, "node2");
GenerateBlocks(5, "node3");
AliasNew("node1", "selleralias4", "password", "somedata");
AliasNew("node2", "buyeralias4", "password", "somedata");
// generate a good offer
string offerguid = OfferNew("node1", "selleralias4", "category", "title", "100", "0.01", "description", "USD");
OfferAddWhitelist("node1", offerguid, "buyeralias4", "5");
// this will expire the offer
ExpireAlias("buyeralias4");
// should fail: perform an accept on expired offer
BOOST_CHECK_THROW(r = CallRPC("node2", "offeraccept buyeralias4 " + offerguid + " 1 message"), runtime_error);
// should fail: offer update on an expired offer
BOOST_CHECK_THROW(r = CallRPC("node1", "offerupdate selleralias4 " + offerguid + " category title 90 0.15 description"), runtime_error);
// should fail: link to an expired offer
BOOST_CHECK_THROW(r = CallRPC("node2", "offerlink buyeralias4 " + offerguid + " 5 newdescription"), runtime_error);
}
BOOST_AUTO_TEST_CASE (generate_offerexpiredexmode)
{
printf("Running generate_offerexpiredexmode...\n");
UniValue r;
GenerateBlocks(5);
GenerateBlocks(5, "node2");
GenerateBlocks(5, "node3");
AliasNew("node1", "selleralias10", "password", "changeddata1");
AliasNew("node2", "selleralias11", "password", "changeddata1");
// generate a good offer
string offerguid = OfferNew("node1", "selleralias10", "category", "title", "100", "0.05", "description", "USD", "nocert");
// should succeed: offer seller adds affiliate to whitelist
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "offeraddwhitelist " + offerguid + " selleralias11 10"));
ExpireAlias("selleralias10");
// should fail: remove whitelist item from expired offer
BOOST_CHECK_THROW(r = CallRPC("node1", "offerremovewhitelist " + offerguid + " selleralias11"), runtime_error);
// should fail: clear whitelist from expired offer
BOOST_CHECK_THROW(r = CallRPC("node1", "offerclearwhitelist " + offerguid), runtime_error);
}
BOOST_AUTO_TEST_CASE (generate_certofferexpired)
{
printf("Running generate_certofferexpired...\n");
UniValue r;
GenerateBlocks(5);
GenerateBlocks(5, "node2");
GenerateBlocks(5, "node3");
AliasNew("node1", "node1alias2a", "password", "node1aliasdata");
AliasNew("node1", "node1alias2", "password", "node1aliasdata");
AliasNew("node2", "node2alias2", "password", "node2aliasdata");
string certguid = CertNew("node1", "node1alias2", "title", "data", "pubdata");
string certguid1 = CertNew("node1", "node1alias2a", "title", "data", "pubdata");
GenerateBlocks(5);
// generate a good cert offer
string offerguid = OfferNew("node1", "node1alias2", "certificates", "title", "1", "0.05", "description", "USD", certguid);
// updates the alias which updates the offer and cert using this alias
BOOST_CHECK_NO_THROW(r = CallRPC("node2", "offeraccept node2alias2 " + offerguid + " 1 message"));
GenerateBlocks(5, "node2");
offerguid = OfferNew("node1", "node1alias2", "certificates", "title", "1", "0.05", "description", "USD", certguid);
ExpireAlias("node2alias2");
// should fail: accept an offer with expired alias
BOOST_CHECK_THROW(r = CallRPC("node2", "offeraccept node2alias2 " + offerguid + " 1 message"), runtime_error);
// should fail: generate a cert offer using an expired cert
BOOST_CHECK_THROW(r = CallRPC("node1", "offernew node1alias2 certificates title 1 0.05 description USD " + certguid1), runtime_error);
/// should fail: generate a cert offer using an expired cert
BOOST_CHECK_THROW(r = CallRPC("node1", "offernew node1alias2 certificates title 1 0.05 description USD " + certguid), runtime_error);
GenerateBlocks(5);
GenerateBlocks(5, "node2");
}
BOOST_AUTO_TEST_CASE (generate_offersafesearch)
{
printf("Running generate_offersafesearch...\n");
UniValue r;
GenerateBlocks(10);
GenerateBlocks(10, "node2");
AliasNew("node2", "selleralias15", "changeddata2", "privdata2");
// offer is safe to search
string offerguidsafe = OfferNew("node2", "selleralias15", "category", "title", "100", "10.00", "description", "USD", "nocert", "NONE", "location", "Yes");
// not safe to search
string offerguidnotsafe = OfferNew("node2", "selleralias15", "category", "title", "100", "10.00", "description", "USD", "nocert", "NONE", "location", "No");
// should include result in both safe search mode on and off
BOOST_CHECK_EQUAL(OfferFilter("node1", offerguidsafe, "On"), true);
BOOST_CHECK_EQUAL(OfferFilter("node1", offerguidsafe, "Off"), true);
// should only show up if safe search is off
BOOST_CHECK_EQUAL(OfferFilter("node1", offerguidnotsafe, "On"), false);
BOOST_CHECK_EQUAL(OfferFilter("node1", offerguidnotsafe, "Off"), true);
// shouldn't affect offerinfo
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "offerinfo " + offerguidsafe));
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "offerinfo " + offerguidnotsafe));
// reverse the rolls
OfferUpdate("node2", "selleralias15", offerguidsafe, "category", "titlenew", "90", "0.15", "descriptionnew", "USD", false, "nocert", "location", "No");
OfferUpdate("node2", "selleralias15", offerguidnotsafe, "category", "titlenew", "90", "0.15", "descriptionnew", "USD", false, "nocert", "location", "Yes");
// should include result in both safe search mode on and off
BOOST_CHECK_EQUAL(OfferFilter("node1", offerguidsafe, "Off"), true);
BOOST_CHECK_EQUAL(OfferFilter("node1", offerguidsafe, "On"), false);
// should only show up if safe search is off
BOOST_CHECK_EQUAL(OfferFilter("node1", offerguidnotsafe, "Off"), true);
BOOST_CHECK_EQUAL(OfferFilter("node1", offerguidnotsafe, "On"), true);
// shouldn't affect offerinfo
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "offerinfo " + offerguidsafe));
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "offerinfo " + offerguidnotsafe));
}
BOOST_AUTO_TEST_CASE (generate_offerban)
{
printf("Running generate_offerban...\n");
UniValue r;
GenerateBlocks(10);
GenerateBlocks(10, "node2");
AliasNew("node2", "selleralias15ban", "changeddata2", "privdata2");
// offer is safe to search
string offerguidsafe = OfferNew("node2", "selleralias15ban", "category", "title", "100", "10.00", "description", "USD", "nocert", "NONE", "location", "Yes");
// not safe to search
string offerguidnotsafe = OfferNew("node2", "selleralias15ban", "category", "title", "100", "10.00", "description", "USD", "nocert", "NONE", "location", "No");
// can't ban on any other node than one that created sysban
BOOST_CHECK_THROW(OfferBan("node2",offerguidnotsafe,SAFETY_LEVEL1), runtime_error);
BOOST_CHECK_THROW(OfferBan("node3",offerguidsafe,SAFETY_LEVEL1), runtime_error);
// ban both offers level 1 (only owner of syscategory can do this)
BOOST_CHECK_NO_THROW(OfferBan("node1",offerguidsafe,SAFETY_LEVEL1));
BOOST_CHECK_NO_THROW(OfferBan("node1",offerguidnotsafe,SAFETY_LEVEL1));
// should only show level 1 banned if safe search filter is not used
BOOST_CHECK_EQUAL(OfferFilter("node1", offerguidsafe, "On"), false);
BOOST_CHECK_EQUAL(OfferFilter("node1", offerguidsafe, "Off"), true);
BOOST_CHECK_EQUAL(OfferFilter("node1", offerguidnotsafe, "On"), false);
BOOST_CHECK_EQUAL(OfferFilter("node1", offerguidnotsafe, "Off"), true);
// should be able to offerinfo on level 1 banned offers
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "offerinfo " + offerguidsafe));
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "offerinfo " + offerguidnotsafe));
// ban both offers level 2 (only owner of syscategory can do this)
BOOST_CHECK_NO_THROW(OfferBan("node1",offerguidsafe,SAFETY_LEVEL2));
BOOST_CHECK_NO_THROW(OfferBan("node1",offerguidnotsafe,SAFETY_LEVEL2));
// no matter what filter won't show banned offers
BOOST_CHECK_EQUAL(OfferFilter("node1", offerguidsafe, "On"), false);
BOOST_CHECK_EQUAL(OfferFilter("node1", offerguidsafe, "Off"), false);
BOOST_CHECK_EQUAL(OfferFilter("node1", offerguidnotsafe, "On"), false);
BOOST_CHECK_EQUAL(OfferFilter("node1", offerguidnotsafe, "Off"), false);
// shouldn't be able to offerinfo on level 2 banned offers
BOOST_CHECK_THROW(r = CallRPC("node1", "offerinfo " + offerguidsafe), runtime_error);
BOOST_CHECK_THROW(r = CallRPC("node1", "offerinfo " + offerguidnotsafe), runtime_error);
// unban both offers (only owner of syscategory can do this)
BOOST_CHECK_NO_THROW(OfferBan("node1",offerguidsafe,0));
BOOST_CHECK_NO_THROW(OfferBan("node1",offerguidnotsafe,0));
// safe to search regardless of filter
BOOST_CHECK_EQUAL(OfferFilter("node1", offerguidsafe, "On"), true);
BOOST_CHECK_EQUAL(OfferFilter("node1", offerguidsafe, "Off"), true);
BOOST_CHECK_EQUAL(OfferFilter("node1", offerguidnotsafe, "On"), false);
BOOST_CHECK_EQUAL(OfferFilter("node1", offerguidnotsafe, "Off"), true);
// should be able to offerinfo on non banned offers
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "offerinfo " + offerguidsafe));
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "offerinfo " + offerguidnotsafe));
}
BOOST_AUTO_TEST_CASE (generate_offerpruning)
{
UniValue r;
// makes sure services expire in 100 blocks instead of 1 year of blocks for testing purposes
printf("Running generate_offerpruning...\n");
AliasNew("node1", "pruneoffer", "password", "changeddata1");
// stop node2 create a service, mine some blocks to expire the service, when we restart the node the service data won't be synced with node2
StopNode("node2");
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "offernew pruneoffer category title 1 0.05 description USD"));
const UniValue &arr = r.get_array();
string guid = arr[1].get_str();
GenerateBlocks(5, "node1");
// we can find it as normal first
BOOST_CHECK_EQUAL(OfferFilter("node1", guid, "Off"), true);
GenerateBlocks(5, "node1");
// then we let the service expire
ExpireAlias("pruneoffer");
StartNode("node2");
ExpireAlias("pruneoffer");
GenerateBlocks(5, "node2");
BOOST_CHECK_EQUAL(OfferFilter("node1", guid, "Off"), false);
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "offerinfo " + guid));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "expired").get_int(), 1);
// should be pruned
BOOST_CHECK_THROW(CallRPC("node2", "offerinfo " + guid), runtime_error);
// stop node3
StopNode("node3");
// should fail: already expired alias
BOOST_CHECK_THROW(CallRPC("node1", "aliasupdate sysrates.peg pruneoffer newdata privdata"), runtime_error);
GenerateBlocks(5, "node1");
// create a new service
BOOST_CHECK_NO_THROW(CallRPC("node1", "aliasnew sysrates.peg pruneoffer password1 temp data"));
GenerateBlocks(5, "node1");
BOOST_CHECK_NO_THROW(r = CallRPC("node1", "offernew pruneoffer category title 1 0.05 description USD"));
const UniValue &arr1 = r.get_array();
string guid1 = arr1[1].get_str();
GenerateBlocks(5, "node1");
// stop and start node1
StopNode("node1");
StartNode("node1");
GenerateBlocks(5, "node1");
// ensure you can still update before expiry
BOOST_CHECK_NO_THROW(CallRPC("node1", "offerupdate pruneoffer " + guid1 + " category title 1 0.05 description"));
// you can search it still on node1/node2
BOOST_CHECK_EQUAL(OfferFilter("node1", guid1, "Off"), true);
BOOST_CHECK_EQUAL(OfferFilter("node2", guid1, "Off"), true);
GenerateBlocks(5, "node1");
// make sure our offer alias doesn't expire
BOOST_CHECK_NO_THROW(CallRPC("node1", "aliasupdate sysrates.peg pruneoffer newdata privdata"));
GenerateBlocks(5, "node1");
ExpireAlias("pruneoffer");
// now it should be expired
BOOST_CHECK_THROW(CallRPC("node1", "offerupdate pruneoffer " + guid1 + " category title 1 0.05 description"), runtime_error);
BOOST_CHECK_EQUAL(OfferFilter("node1", guid1, "Off"), false);
BOOST_CHECK_EQUAL(OfferFilter("node2", guid1, "Off"), false);
// and it should say its expired
BOOST_CHECK_NO_THROW(r = CallRPC("node2", "offerinfo " + guid1));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "expired").get_int(), 1);
GenerateBlocks(5, "node1");
StartNode("node3");
ExpireAlias("pruneoffer");
GenerateBlocks(5, "node3");
// node3 shouldn't find the service at all (meaning node3 doesn't sync the data)
BOOST_CHECK_THROW(CallRPC("node3", "offerinfo " + guid1), runtime_error);
BOOST_CHECK_EQUAL(OfferFilter("node3", guid1, "Off"), false);
}
BOOST_AUTO_TEST_SUITE_END () | 52.79118 | 1,051 | 0.761486 | gtacoin-dev |
cdc4afd451eaa4186fa54f0c51080d39c591d5a7 | 1,156 | cpp | C++ | rct_optimizations/test/conversion_utest.cpp | m-limbird/robot_cal_tools | c3ee0c26895af50219afc450e7e6f866b7b86cbe | [
"Apache-2.0"
] | 110 | 2018-07-01T07:59:25.000Z | 2022-03-16T04:27:44.000Z | rct_optimizations/test/conversion_utest.cpp | m-limbird/robot_cal_tools | c3ee0c26895af50219afc450e7e6f866b7b86cbe | [
"Apache-2.0"
] | 65 | 2018-07-02T02:29:36.000Z | 2022-03-04T19:11:41.000Z | rct_optimizations/test/conversion_utest.cpp | m-limbird/robot_cal_tools | c3ee0c26895af50219afc450e7e6f866b7b86cbe | [
"Apache-2.0"
] | 35 | 2018-07-01T01:43:48.000Z | 2022-03-15T22:14:47.000Z | #include <gtest/gtest.h>
#include <rct_optimizations/eigen_conversions.h>
// Test the conversion of a pose from Eigen to internal calibration format and back
TEST(EigenConversions, there_and_back_identity)
{
const auto e_pose = Eigen::Isometry3d::Identity();
const auto cal_pose = rct_optimizations::poseEigenToCal(e_pose);
const auto recovered_e_pose = rct_optimizations::poseCalToEigen(cal_pose);
const Eigen::Matrix4d diff = e_pose.matrix() - recovered_e_pose.matrix();
EXPECT_TRUE(diff.isZero());
}
// Test the conversion of a pose from Eigen to internal calibration format and back
TEST(EigenConversions, there_and_back)
{
auto e_pose = Eigen::Isometry3d::Identity();
e_pose = e_pose * Eigen::Translation3d(0.5, 0.75, 1.0) * Eigen::AngleAxisd(M_PI_2, Eigen::Vector3d::UnitY());
const auto cal_pose = rct_optimizations::poseEigenToCal(e_pose);
const auto recovered_e_pose = rct_optimizations::poseCalToEigen(cal_pose);
const Eigen::Matrix4d diff = e_pose.matrix() - recovered_e_pose.matrix();
EXPECT_TRUE(diff.isZero());
}
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 36.125 | 111 | 0.759516 | m-limbird |
cdc84c6229ee327fd43a4b83217c5a5229b85eb0 | 1,780 | cpp | C++ | src/lib/utils/read_kv.cpp | ssd71/botan | d6b5b4a31af102bd6405e4f381e2ea21d2317a1c | [
"BSD-2-Clause"
] | 56 | 2019-04-25T19:06:11.000Z | 2022-03-25T20:26:25.000Z | src/lib/utils/read_kv.cpp | evpo/botan | 6f8a696962c3aa605e9e5a53710c96dcb8477c9f | [
"BSD-2-Clause"
] | 184 | 2019-04-24T18:20:08.000Z | 2022-03-22T18:56:45.000Z | src/lib/utils/read_kv.cpp | evpo/botan | 6f8a696962c3aa605e9e5a53710c96dcb8477c9f | [
"BSD-2-Clause"
] | 34 | 2019-04-03T15:21:16.000Z | 2022-03-20T04:26:53.000Z | /*
* (C) 2018 Ribose Inc
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/parsing.h>
#include <botan/exceptn.h>
namespace Botan {
std::map<std::string, std::string> read_kv(const std::string& kv)
{
std::map<std::string, std::string> m;
if(kv == "")
return m;
std::vector<std::string> parts;
try
{
parts = split_on(kv, ',');
}
catch(std::exception&)
{
throw Invalid_Argument("Bad KV spec");
}
bool escaped = false;
bool reading_key = true;
std::string cur_key;
std::string cur_val;
for(char c : kv)
{
if(c == '\\' && !escaped)
{
escaped = true;
}
else if(c == ',' && !escaped)
{
if(cur_key.empty())
throw Invalid_Argument("Bad KV spec empty key");
if(m.find(cur_key) != m.end())
throw Invalid_Argument("Bad KV spec duplicated key");
m[cur_key] = cur_val;
cur_key = "";
cur_val = "";
reading_key = true;
}
else if(c == '=' && !escaped)
{
if(reading_key == false)
throw Invalid_Argument("Bad KV spec unexpected equals sign");
reading_key = false;
}
else
{
if(reading_key)
cur_key += c;
else
cur_val += c;
if(escaped)
escaped = false;
}
}
if(!cur_key.empty())
{
if(reading_key == false)
{
if(m.find(cur_key) != m.end())
throw Invalid_Argument("Bad KV spec duplicated key");
m[cur_key] = cur_val;
}
else
throw Invalid_Argument("Bad KV spec incomplete string");
}
return m;
}
}
| 20.697674 | 73 | 0.497191 | ssd71 |
cdcb45daea15478082924df553febaad2a28f8b2 | 22,650 | cpp | C++ | gazebo_joint_control/src/GazeboJointControlLocalImpl.cpp | JenniferBuehler/joint-control-pkgs | 3fcbc64a87704a3ddaa9d7f4c78e45b48925ec6f | [
"BSD-3-Clause"
] | 22 | 2017-01-20T14:57:36.000Z | 2020-10-15T13:57:40.000Z | gazebo_joint_control/src/GazeboJointControlLocalImpl.cpp | jdom1824/joint-control-pkgs | 6db7d2447054622712690669036a256432fd7ba2 | [
"BSD-3-Clause"
] | 6 | 2016-07-16T13:09:02.000Z | 2020-12-07T14:42:58.000Z | gazebo_joint_control/src/GazeboJointControlLocalImpl.cpp | jdom1824/joint-control-pkgs | 6db7d2447054622712690669036a256432fd7ba2 | [
"BSD-3-Clause"
] | 18 | 2016-09-01T07:28:58.000Z | 2021-02-10T05:55:30.000Z | #ifdef DOXYGEN_SHOULD_SKIP_THIS
/**
Copyright (C) 2015 Jennifer Buehler
See also LICENSE file in this repository.
*/
#endif
#include <gazebo_joint_control/GazeboJointControlLocalImpl.h>
#include <gazebo_joint_control/GazeboVersionHelpers.h>
#include <convenience_math_functions/MathFunctions.h>
#include <map>
#include <string>
#define DISABLE_GRAVITY false
#define INIT_WITH_POS false
// Default PID gains if SetVelocity() returns true
#define KP_POS_SETVEL 15
#define KI_POS_SETVEL 2
#define KD_POS_SETVEL 0.1
#define KP_VEL_SETVEL 0.1
#define KI_VEL_SETVEL 0.01
#define KD_VEL_SETVEL 0
// Default PID gains if SetVelocity() returns false
#define KP_POS_SETF 100
#define KI_POS_SETF 0.01
#define KD_POS_SETF 5
#define KP_VEL_SETF 80
#define KI_VEL_SETF 0
#define KD_VEL_SETF 0.001
// do additional fallback for ensuring safe use:
// If velocity 0 is specified as target, but *no*
// alternative position value has been specified,
// calculate that position value. This will slow
// things down a little (even if position *was* specified)
// but it should make things
// work still if the user does not set the target
// commands consistenly. Warnings will be printed
// if this fix has been applied.
#define _FIX_POSITION_FALLBACK_
// the major version of Gazebo when call to Joint::SetForce()
// does *not* need to be repeated artificially in order for
// it to work...
#define GAZEBO_IMPROVED_SETFORCE 3
// for older Gazebo versions, it seems that successive calls to SetForce()
// are required (because it's accumulative), otherwise not enough force
// gets applied. SetForce() will always be called once, and the additional number
// specified here.
#if GAZEBO_MAJOR_VERSION < GAZEBO_IMPROVED_SETFORCE
#define GAZEBO_SETFORCE_REPEAT 1
#else
#define GAZEBO_SETFORCE_REPEAT 0
#endif
using convenience_math_functions::MathFunctions;
namespace gazebo
{
////////////////////////////////////////////////////////////////////////////////
GazeboJointControlLocalImpl::GazeboJointControlLocalImpl():
GazeboJointControl()
{
#if GAZEBO_MAJOR_VERSION > 2
gazebo::common::Console::SetQuiet(false);
#endif
ROS_INFO("Creating GazeboJointControlLocalImpl plugin");
ros::NodeHandle n("");
n.param<bool>("gazebo_use_set_velocity",useSetVelocity,true);
ROS_INFO_STREAM("Gazebo using SetVelocity(): "<<useSetVelocity);
}
////////////////////////////////////////////////////////////////////////////////
GazeboJointControlLocalImpl::~GazeboJointControlLocalImpl()
{
}
////////////////////////////////////////////////////////////////////////////////
bool GazeboJointControlLocalImpl::DisableGravity() const
{
return DISABLE_GRAVITY;
}
////////////////////////////////////////////////////////////////////////////////
bool GazeboJointControlLocalImpl::UseForce() const
{
return !SetVelocity();
}
////////////////////////////////////////////////////////////////////////////////
bool GazeboJointControlLocalImpl::SetVelocity() const
{
return useSetVelocity;
}
////////////////////////////////////////////////////////////////////////////////
void GazeboJointControlLocalImpl::GetDefaultPosGains(float& kp, float& ki, float& kd) const
{
if (SetVelocity())
{
kp = KP_POS_SETVEL;
ki = KI_POS_SETVEL;
kd = KD_POS_SETVEL;
} else {
kp = KP_POS_SETF;
ki = KI_POS_SETF;
kd = KD_POS_SETF;
}
}
////////////////////////////////////////////////////////////////////////////////
void GazeboJointControlLocalImpl::GetDefaultVelGains(float& kp, float& ki, float& kd) const
{
if (SetVelocity())
{
kp = KP_VEL_SETVEL;
ki = KI_VEL_SETVEL;
kd = KD_VEL_SETVEL;
} else {
kp = KP_VEL_SETF;
ki = KI_VEL_SETF;
kd = KD_VEL_SETF;
}
}
////////////////////////////////////////////////////////////////////////////////
double GazeboJointControlLocalImpl::DistToPosition(const physics::JointPtr& joint,
double targetPosition) const
{
const int axis = 0;
double currPosition = GetPosition(joint, axis);
double lowLimit=GetLowerLimit(joint, axis);
double highLimit=GetUpperLimit(joint, axis);
// ROS_INFO_STREAM("Limits: "<<lowLimit<<", "<<highLimit);
double _targetPosition=MathFunctions::limitsToTwoPI(targetPosition, lowLimit, highLimit);
// ... currPosition (read from Gazebo) is always in the right format already.
double dist=currPosition - _targetPosition;
if ((fabs(highLimit) > 2*M_PI) || (fabs(lowLimit) > 2*M_PI)) {
// the joint has no limits, so it can turn either direction.
// Use the shortest angle distance as goal.
// TODO: current limitation is the assumption that if there is
// either a high or a low limit, the arm has both limits.
dist=MathFunctions::angleDistance(_targetPosition,currPosition);
}
return dist;
}
/*
#define BREAK_LOOKAHEAD 0.03
double GazeboJointControlLocalImpl::AdjustForCloseTarget(const physics::JointPtr& joint,
const double distToTarget, const gazebo::common::Time& stepTime, const double lookaheadSecs, const double commandValue) const
{
const int axis=0;
double currVel = joint->GetVelocity(axis);
double nextStepSize = currVel * lookaheadSecs;
double retVal = commandValue;
if (((distToTarget < 0) && (nextStepSize < distToTarget)) ||
((distToTarget > 0) && (nextStepSize > distToTarget)))
{
// at this velocity, in <lookaheadSecs> would arrive at target exactly.
double targetVel = distToTarget / lookaheadSecs;
// how much smaller proportionally the target velocity is to the current velocity
double factor = targetVel / currVel;
if (factor < 0) {
ROS_ERROR_STREAM("Factor should always be positive! "<<factor);
throw std::string("Factor should always be positive!");
}
if (factor > 1.01) {
ROS_INFO_STREAM("Overshoot "<<joint->GetName()<<" for goal "<<distToTarget
<<", at currVel="<<currVel<<" and nextSTepSize "<<nextStepSize
<<": target "<<targetVel<<", adjust "<<commandValue<<" by "<<factor);
ROS_ERROR("DEBUG ME: Factor should never be higher");
throw std::string("DEBUG ME: Factor should never be higher");
}
retVal = commandValue * factor;
}
return retVal;
}
*/
////////////////////////////////////////////////////////////////////////////////
double GazeboJointControlLocalImpl::UpdateVelocityToPosition(const physics::JointPtr& joint,
double targetPosition, common::PID& pid, const gazebo::common::Time& stepTime) const
{
double dist = DistToPosition(joint,targetPosition);
double cmd = pid.Update(dist, stepTime);
// double targetVel = capTargetVel(joint, cmd, true, targetAngle,1e-04);
return capTargetVel(joint, cmd, false);
}
////////////////////////////////////////////////////////////////////////////////
double GazeboJointControlLocalImpl::UpdateForceToPosition(const physics::JointPtr& joint,
double targetPosition, common::PID& pid, const gazebo::common::Time& stepTime) const
{
double dist = DistToPosition(joint,targetPosition);
double cmd = pid.Update(dist, stepTime);
// ROS_INFO_STREAM("PID val "<<joint->GetName()<<": "<<cmd);
// return cmd;
// cmd = AdjustForCloseTarget(joint, dist, stepTime, BREAK_LOOKAHEAD, cmd);
return capTargetForce(joint, cmd, false);
}
////////////////////////////////////////////////////////////////////////////////
// removes from \e anyMap all joint names (map key) which are not maintained by \e joints
template<class Any>
void FilterMaintanedJointsMap(std::map<std::string, Any>& anyMap, const std::vector<std::string>& joint_names, const physics::ModelPtr& model)
{
// this implementation just builds a new map
std::map<std::string, Any> newMap;
for (std::vector<std::string>::const_iterator it=joint_names.begin(); it!=joint_names.end(); ++it)
{
// need to get the joint to retrieve the scoped name
physics::JointPtr joint = model->GetJoint(*it);
if (!joint)
{
ROS_ERROR_STREAM("GazeboJointControlLocalImpl: FilterMaintanedJointsMap can't find joint "<<*it);
continue;
}
typename std::map<std::string, Any>::iterator mEntry = anyMap.find(joint->GetScopedName());
if (mEntry!=anyMap.end())
{
newMap.insert(std::make_pair(mEntry->first, mEntry->second));
}
}
anyMap = newMap;
/*
// this implementation removes entries from the map which can't be found in joint_names
for (typename std::map<std::string, Any>::iterator it=anyMap.begin(); it!=anyMap.end(); ++it)
{
if (std::find(joint_names.begin(),joint_names.end(), it->first) == joint_names.end())
{
}
}*/
}
////////////////////////////////////////////////////////////////////////////////
bool GazeboJointControlLocalImpl::UpdateJoints()
{
// XXX TODO remove this test:
static boost::mutex updateMtx;
if (!updateMtx.try_lock()) {
ROS_WARN("Other thread is just updating the joints, your GazeboJointControlLocalImpl::UpdateJoints() may be too slow");
return false;
}
boost::adopt_lock_t adl;
boost::lock_guard<boost::mutex> updLck(updateMtx, adl);
// XXX end test
if (!model.get())
{
ROS_ERROR("Cannot update GazeboJointControlLocalImpl if no model is set");
return false;
}
if (!jointController.get())
{
ROS_ERROR("Cannot load GazeboJointControlLocalImpl if no default JointController is set for the model");
return false;
}
//ROS_INFO("Start");
common::Time currTime = GetSimTime(model->GetWorld());
common::Time stepTime = currTime - prevUpdateTime;
if (stepTime <= 0)
{
prevUpdateTime = currTime;
return true;
}
// ROS_INFO_STREAM("Step time: "<<stepTime.Double());
boost::unique_lock<boost::recursive_mutex> lck = jointController->GetLock();
std::map<std::string, double> forces = jointController->GetForces();
std::map<std::string, double> positions = jointController->GetPositions();
std::map<std::string, double> velocities = jointController->GetVelocities();
std::map<std::string, physics::JointPtr > jntMap = jointController->GetJoints();
std::vector<std::string> joint_names; // all joint names maintained by the joint manager. This should be a global field at some point.
joints->getJointNames(joint_names, true);
FilterMaintanedJointsMap(forces, joint_names, model);
FilterMaintanedJointsMap(positions, joint_names, model);
FilterMaintanedJointsMap(velocities, joint_names, model);
const int axis = 0;
// It is necessary to first collect the final target values, including the overwriting of
// lower-priority values, and then set the joint velocities in one batch with
// joint::SetVelocity().This is necessary because when calling joint::SetVelocity()
// first and then a little bit after again to do the overwriting, the arm wiggles.
// Therefore a map is pre-computed with all Joints to be updated, to run the
// actual updating at the end.
// The map contains hoints (with the key name Joint::GetName()) to be updated
// along with the velocity values.
// All joints which are not to be updated here will remain at their current pose.
std::map<std::string, double> finalJointUpdates;
if (!positions.empty())
{
std::map<std::string, common::PID> posPIDs = jointController->GetPositionPIDs();
std::map<std::string, double>::iterator it;
for (it = positions.begin(); it != positions.end(); ++it)
{
std::map<std::string, double>::iterator velIt = velocities.find(it->first);
static float eps = 1e-05;
std::map<std::string, physics::JointPtr >::iterator jntIt;
jntIt = jntMap.find(it->first);
if (jntIt == jntMap.end())
{
ROS_ERROR_STREAM("Could not find joint " << it->first << " in joint controllers map");
return false;
}
physics::JointPtr joint = jntIt->second;
std::map<std::string, common::PID>::iterator pidIt=posPIDs.find(it->first);
if (pidIt==posPIDs.end())
{
ROS_ERROR_STREAM_ONCE("No position PID controller found for "<<it->first<<
". Can't control joint. This message is only printed once.");
return false;
}
common::PID& pid = pidIt->second;
// ROS_INFO_STREAM("Updating position PID for "<<it->first);
double targetVal=it->second;
if (SetVelocity()) {
targetVal = UpdateVelocityToPosition(joint, it->second, pid, stepTime);
} else {
targetVal = UpdateForceToPosition(joint, it->second, pid, stepTime);
}
finalJointUpdates.insert(std::make_pair(joint->GetName(), targetVal));
// Because unfortunately JointController does not give us back a reference,
// we have to manually update the PID again
jointController->SetPositionPID(it->first, pid);
}
}
if (!velocities.empty())
{
if (!velocityControllersLoaded())
{
ROS_ERROR_STREAM_ONCE("No velocity controllers loaded. "<<
". Can't control joints. This message is only printed once.");
return false;
}
std::map<std::string, common::PID> velPIDs = jointController->GetVelocityPIDs();
std::map<std::string, double>::iterator it;
for (it = velocities.begin(); it != velocities.end(); ++it)
{
std::map<std::string, physics::JointPtr >::iterator jntIt;
jntIt = jntMap.find(it->first);
if (jntIt == jntMap.end())
{
ROS_ERROR_STREAM("Could not find joint " << it->first << " in joint controllers map");
return false;
}
physics::JointPtr joint = jntIt->second;
double targetVel = it->second;
targetVel = capTargetVel(joint, targetVel, false);
double currVel = joint->GetVelocity(axis);
std::map<std::string, common::PID>::iterator pidIt=velPIDs.find(it->first);
if (pidIt==velPIDs.end())
{
ROS_ERROR_STREAM_ONCE("No velocity PID controller found for "<<it->first<<
". Can't control joint. This message is only printed once.");
return false;
}
// ROS_INFO_STREAM("Updating velocity PID for "<<it->first<<" (curr vel "<<currVel<<")");
common::PID& pid = pidIt->second;
double cmd = pid.Update(currVel - targetVel, stepTime);
double finalTargetVal = targetVel;
// true when we want to insert the final value into the map
// so that the joint is updated. If false, already existing
// values (e.g. from positions) will be kept in the map instead,
// and not overwritten.
bool insertToMap = true;
if (DisableGravity())
{
if (!SetVelocity()) {
ROS_ERROR_STREAM_ONCE("GazeboJointControlLocalImpl does not support disabled "
<<"gravity and use of Joint::SetForce() yet. This message is printed only once.");
return false;
}
// Because there is no gravity anyway, set velocity directly.
finalTargetVal = targetVel;
if (fabs(targetVel) > 1e-04)
ROS_INFO_STREAM("DisableGrav: Velocity for "<<joint->GetName()<<": curr="<<currVel<<", target="<<targetVel<<" in orig map "<<it->second);
}
else
{
if (SetVelocity())
{
double pidTargetVel = targetVel + cmd;
pidTargetVel = capTargetVel(joint, pidTargetVel, false);
finalTargetVal = pidTargetVel;
} else {
finalTargetVal = cmd;
}
static const float eps = 1e-04;
if (fabs(targetVel) <= eps)
// if velocity is 0, rely on the position command instead
{
// Check whether a replacement position was actually specified as well, and print an error if not.
std::map<std::string, double>::iterator posIt = positions.find(it->first);
bool hasPositionUpdate = (posIt != positions.end());
#ifdef _FIX_POSITION_FALLBACK_
if (!hasPositionUpdate)
{
ROS_WARN_STREAM_ONCE("Velocity specified as 0 (" << targetVel << ") for joint " << it->first
<< ". If you specify a zero velocity, you should also specify a"
<< " position target at which to keep the arm. "
<< " Will now use the joint's current position to keep."
<< " This should work, but it is inefficient. "
<< " This message is printed only once.");
std::map<std::string, common::PID> posPIDs = jointController->GetPositionPIDs();
common::PID posPID = posPIDs[it->first];
double currPosition = GetPosition(joint, axis); // if capped to PI, it won't work for joint limits
if (SetVelocity()) finalTargetVal = UpdateVelocityToPosition(joint, currPosition, posPID, stepTime);
else finalTargetVal = UpdateForceToPosition(joint, currPosition, posPID, stepTime);
jointController->SetPositionPID(it->first, posPID);
}
#endif //_FIX_POSITION_FALLBACK_
if (hasPositionUpdate)
{
/*std::map<std::string, double>::iterator fju = finalJointUpdates.find(joint->GetName());
if (fju==finalJointUpdates.end()) {
ROS_FATAL("Target position velocity value should have been specified");
return false;
}
ROS_INFO_STREAM("Not overwriting "<<joint->GetName()<<" velocity "<<fju->second);*/
insertToMap = false;
}
}
else
{
// double p,i,d;
// pid.GetErrors(p,i,d);
// ROS_INFO_STREAM("Velocity for "<<joint->GetName()<<": curr="<<currVel<<", target="<<targetVel<<". Apply cmd="<<finalTargetVal); //<<", i="<<i);
}
}
if (insertToMap)
{
std::map<std::string, double>::iterator fju =
finalJointUpdates.insert(std::make_pair(joint->GetName(), finalTargetVal)).first;
if (fju == finalJointUpdates.end())
{
ROS_WARN_STREAM("Joint " << joint->GetName() << " was not in position map");
}
fju->second = finalTargetVal;
}
// Because unfortunately JointController does not give us back a reference,
// we have to manually update the PID again
jointController->SetVelocityPID(it->first, pid);
}
}
if (!forces.empty())
{
ROS_ERROR_ONCE("Setting forces is not implemented yet. Ignoring force settings. This message will only be printed once.");
}
std::map<std::string, double>::iterator fju;
for (fju = finalJointUpdates.begin(); fju != finalJointUpdates.end(); ++fju)
{
physics::JointPtr joint = model->GetJoint(fju->first);
if (!joint.get())
{
ROS_ERROR_STREAM("Could not find joint " << fju->first << " in model joints");
return false;
}
// possible HACK: If velocity is 0, we could here fix the current position with SetJointPosition(), and NOT
// do a velocity 0 update. This can prevent the arm from slightly wiggling around 0 velocity positions.
// ROS_INFO_STREAM("Setting velocity "<<joint->GetName()<<": "<<fju->second<<" (measured: "<<joint->GetVelocity(0)<<")");
if (SetVelocity())
{
// double currV=joint->GetVelocity(axis);
// ROS_INFO_STREAM("Setting velocity of "<<joint->GetName()<<": "<<fju->second<<" - curr "<<currV<<", stepTime: "<<stepTime.Double());
#if GAZEBO_MAJOR_VERSION > 2
// XXX TODO setting the velocity like this generates gazebo errors, but in the end it was required
// to make it work anyway? Switching off the error message here for now.
gazebo::common::Console::SetQuiet(true);
joint->SetParam("vel", axis, fju->second);
gazebo::common::Console::SetQuiet(false);
// ROS_INFO_STREAM("Setting velocity "<<joint->GetName()<<": "<<fju->second<<" (measured: "<<joint->GetVelocity(0)<<"), "<<joint->GetParam("vel", axis));
// for some reason, SetVelocity() still has to be called. But if called
// without the previous SetParam(), it doesn't work as effectively, set
// velocities are mostly not met if moving against direction of gravity.
joint->SetVelocity(axis, fju->second);
#else
joint->SetVelocity(axis, fju->second);
#endif
} else {
//double currF=joint->GetForce(axis);
//ROS_INFO_STREAM("Setting force of "<<joint->GetName()<<": "<<fju->second<<" - curr "<<currF<<", stepTime: "<<stepTime.Double());
joint->SetForce(axis, fju->second);
// sometimes, successive calls to SetForce
// are required (because it's accumulative),
// otherwise not enough force gets applied.
for (int i=0; i < GAZEBO_SETFORCE_REPEAT; ++i)
joint->SetForce(axis, fju->second);
}
}
prevUpdateTime = GetSimTime(model->GetWorld());
// ROS_INFO_STREAM("end: "<<stepTime.Double());
return true;
}
} // namespace gazebo
| 41.712707 | 166 | 0.580574 | JenniferBuehler |
cdcb60bd31e5d048d518a2981ad1211bad4acc3d | 5,050 | hpp | C++ | sprout/range/adaptor/adapted_window.hpp | EzoeRyou/Sprout | 12e12373d0f70543eac5f2ecfbec8f5112765f98 | [
"BSL-1.0"
] | 1 | 2016-09-29T21:55:58.000Z | 2016-09-29T21:55:58.000Z | sprout/range/adaptor/adapted_window.hpp | EzoeRyou/Sprout | 12e12373d0f70543eac5f2ecfbec8f5112765f98 | [
"BSL-1.0"
] | null | null | null | sprout/range/adaptor/adapted_window.hpp | EzoeRyou/Sprout | 12e12373d0f70543eac5f2ecfbec8f5112765f98 | [
"BSL-1.0"
] | null | null | null | /*=============================================================================
Copyright (c) 2011-2014 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
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 SPROUT_RANGE_ADAPTOR_ADAPTED_WINDOW_HPP
#define SPROUT_RANGE_ADAPTOR_ADAPTED_WINDOW_HPP
#include <sprout/config.hpp>
#include <sprout/type_traits/arithmetic_promote.hpp>
#include <sprout/utility/lvalue_forward.hpp>
#include <sprout/range/adaptor/taken.hpp>
#include <sprout/range/adaptor/dropped.hpp>
#include <sprout/range/adaptor/window.hpp>
#include <sprout/range/adaptor/jointed.hpp>
namespace sprout {
namespace adaptors {
//
// adapt_window_holder
//
template<typename Adaptor, typename Difference1, typename Difference2 = void>
class adapt_window_holder {
public:
typedef Adaptor adaptor_type;
typedef typename sprout::arithmetic_promote<Difference1, Difference2>::type difference_type;
private:
adaptor_type adaptor_;
difference_type to_first_;
difference_type to_last_;
public:
explicit SPROUT_CONSTEXPR adapt_window_holder(adaptor_type const& adaptor, difference_type to_first, difference_type to_last)
: adaptor_(adaptor), to_first_(to_first), to_last_(to_last)
{}
SPROUT_CONSTEXPR adaptor_type const& adaptor() const {
return adaptor_;
}
SPROUT_CONSTEXPR difference_type const& to_first() const {
return to_first_;
}
SPROUT_CONSTEXPR difference_type const& to_last() const {
return to_last_;
}
};
template<typename Adaptor, typename Difference>
class adapt_window_holder<Adaptor, Difference, void> {
public:
typedef Adaptor adaptor_type;
typedef Difference difference_type;
private:
adaptor_type adaptor_;
difference_type to_first_;
public:
explicit SPROUT_CONSTEXPR adapt_window_holder(adaptor_type const& adaptor, difference_type to_first)
: adaptor_(adaptor), to_first_(to_first)
{}
SPROUT_CONSTEXPR adaptor_type const& adaptor() const {
return adaptor_;
}
SPROUT_CONSTEXPR difference_type const& to_first() const {
return to_first_;
}
};
//
// adapted_window_forwarder
//
class adapted_window_forwarder {
public:
template<typename Adaptor, typename Difference1, typename Difference2>
SPROUT_CONSTEXPR sprout::adaptors::adapt_window_holder<Adaptor, Difference1, Difference2>
operator()(Adaptor const& adaptor, Difference1 to_first, Difference2 to_last) const {
return sprout::adaptors::adapt_window_holder<Adaptor, Difference1, Difference2>(adaptor, to_first, to_last);
}
template<typename Adaptor, typename Difference>
SPROUT_CONSTEXPR sprout::adaptors::adapt_window_holder<Adaptor, Difference>
operator()(Adaptor const& adaptor, Difference to_first) const {
return sprout::adaptors::adapt_window_holder<Adaptor, Difference>(adaptor, to_first);
}
};
//
// adapted_window
//
namespace {
SPROUT_STATIC_CONSTEXPR sprout::adaptors::adapted_window_forwarder adapted_window = {};
} // anonymous-namespace
//
// operator|
//
template<typename Range, typename Adaptor, typename Difference1, typename Difference2>
inline SPROUT_CONSTEXPR auto
operator|(Range&& lhs, sprout::adaptors::adapt_window_holder<Adaptor, Difference1, Difference2> const& rhs)
-> decltype(
sprout::lvalue_forward<Range>(lhs) | sprout::adaptors::taken(rhs.to_first())
| sprout::adaptors::jointed(sprout::lvalue_forward<Range>(lhs) | sprout::adaptors::window(rhs.to_first(), rhs.to_last()) | rhs.adaptor())
| sprout::adaptors::jointed(sprout::lvalue_forward<Range>(lhs) | sprout::adaptors::dropped(rhs.to_last()))
)
{
return sprout::lvalue_forward<Range>(lhs) | sprout::adaptors::taken(rhs.to_first())
| sprout::adaptors::jointed(sprout::lvalue_forward<Range>(lhs) | sprout::adaptors::window(rhs.to_first(), rhs.to_last()) | rhs.adaptor())
| sprout::adaptors::jointed(sprout::lvalue_forward<Range>(lhs) | sprout::adaptors::dropped(rhs.to_last()))
;
}
template<typename Range, typename Adaptor, typename Difference>
inline SPROUT_CONSTEXPR auto
operator|(Range&& lhs, sprout::adaptors::adapt_window_holder<Adaptor, Difference> const& rhs)
-> decltype(
sprout::lvalue_forward<Range>(lhs) | sprout::adaptors::taken(rhs.to_first())
| sprout::adaptors::jointed(sprout::lvalue_forward<Range>(lhs) | sprout::adaptors::window(rhs.to_first()) | rhs.adaptor())
)
{
return sprout::lvalue_forward<Range>(lhs) | sprout::adaptors::taken(rhs.to_first())
| sprout::adaptors::jointed(sprout::lvalue_forward<Range>(lhs) | sprout::adaptors::window(rhs.to_first()) | rhs.adaptor())
;
}
} // namespace adaptors
} // namespace sprout
#endif // #ifndef SPROUT_RANGE_ADAPTOR_ADAPTED_WINDOW_HPP
| 40.725806 | 142 | 0.707723 | EzoeRyou |
cdcd28bbb6c5a02f5a72ac2552d13db3a47befea | 4,071 | hpp | C++ | Source/engine/surface.hpp | mewpull/devilutionX | e82dc72d12817cdd0780cb2ea838d24c587333be | [
"Unlicense"
] | 5,649 | 2018-08-02T17:55:32.000Z | 2022-03-31T22:09:42.000Z | Source/engine/surface.hpp | mewpull/devilutionX | e82dc72d12817cdd0780cb2ea838d24c587333be | [
"Unlicense"
] | 2,748 | 2018-08-03T17:12:14.000Z | 2022-03-31T22:53:59.000Z | Source/engine/surface.hpp | mewpull/devilutionX | e82dc72d12817cdd0780cb2ea838d24c587333be | [
"Unlicense"
] | 835 | 2018-08-02T23:14:24.000Z | 2022-03-31T12:53:08.000Z | #pragma once
#include <cstdint>
#include <cstddef>
#include <SDL_version.h>
#if SDL_VERSION_ATLEAST(2, 0, 0)
#include <SDL_rect.h>
#include <SDL_surface.h>
#else
#include <SDL_video.h>
#include "utils/sdl2_to_1_2_backports.h"
#endif
#include "engine/point.hpp"
#include "utils/sdl_geometry.h"
#include "utils/sdl_wrap.h"
namespace devilution {
/**
* @brief 8-bit surface.
*/
struct Surface {
SDL_Surface *surface;
SDL_Rect region;
Surface()
: surface(nullptr)
, region(SDL_Rect { 0, 0, 0, 0 })
{
}
explicit Surface(SDL_Surface *surface)
: surface(surface)
, region(MakeSdlRect(0, 0, surface->w, surface->h))
{
}
Surface(SDL_Surface *surface, SDL_Rect region)
: surface(surface)
, region(region)
{
}
Surface(const Surface &other) = default;
Surface &operator=(const Surface &other) = default;
int w() const
{
return region.w;
}
int h() const
{
return region.h;
}
std::uint8_t &operator[](Point p) const
{
return *at(p.x, p.y);
}
std::uint8_t *at(int x, int y) const
{
return static_cast<uint8_t *>(surface->pixels) + region.x + x + surface->pitch * (region.y + y);
}
std::uint8_t *begin() const
{
return at(0, 0);
}
std::uint8_t *end() const
{
return at(0, region.h);
}
/**
* @brief Set the value of a single pixel if it is in bounds.
* @param point Target buffer coordinate
* @param col Color index from current palette
*/
void SetPixel(Point position, std::uint8_t col) const
{
if (InBounds(position))
(*this)[position] = col;
}
/**
* @brief Line width of the raw underlying byte buffer.
* May be wider than its logical width (for power-of-2 alignment).
*/
int pitch() const
{
return surface->pitch;
}
bool InBounds(Point position) const
{
return position.x >= 0 && position.y >= 0 && position.x < region.w && position.y < region.h;
}
/**
* @brief Returns a subregion of the given buffer.
*/
Surface subregion(int x, int y, int w, int h) const
{
return Surface(surface, MakeSdlRect(region.x + x, region.y + y, w, h));
}
/**
* @brief Returns a buffer that starts at `y` of height `h`.
*/
Surface subregionY(int y, int h) const
{
SDL_Rect subregion = region;
subregion.y += static_cast<decltype(SDL_Rect {}.y)>(y);
subregion.h = static_cast<decltype(SDL_Rect {}.h)>(h);
return Surface(surface, subregion);
}
/**
* @brief Clips srcRect and targetPosition to this output buffer.
*/
void Clip(SDL_Rect *srcRect, Point *targetPosition) const
{
if (targetPosition->x < 0) {
srcRect->x -= targetPosition->x;
srcRect->w += targetPosition->x;
targetPosition->x = 0;
}
if (targetPosition->y < 0) {
srcRect->y -= targetPosition->y;
srcRect->h += targetPosition->y;
targetPosition->y = 0;
}
if (targetPosition->x + srcRect->w > region.w) {
srcRect->w = region.w - targetPosition->x;
}
if (targetPosition->y + srcRect->h > region.h) {
srcRect->h = region.h - targetPosition->y;
}
}
/**
* @brief Copies the `srcRect` portion of the given buffer to this buffer at `targetPosition`.
*/
void BlitFrom(const Surface &src, SDL_Rect srcRect, Point targetPosition) const;
/**
* @brief Copies the `srcRect` portion of the given buffer to this buffer at `targetPosition`.
* Source pixels with index 0 are not copied.
*/
void BlitFromSkipColorIndexZero(const Surface &src, SDL_Rect srcRect, Point targetPosition) const;
};
class OwnedSurface : public Surface {
SDLSurfaceUniquePtr pinnedSurface;
public:
explicit OwnedSurface(SDLSurfaceUniquePtr surface)
: Surface(surface.get())
, pinnedSurface(std::move(surface))
{
}
OwnedSurface(int width, int height)
: OwnedSurface(SDLWrap::CreateRGBSurfaceWithFormat(0, width, height, 8, SDL_PIXELFORMAT_INDEX8))
{
}
explicit OwnedSurface(Size size)
: OwnedSurface(size.width, size.height)
{
}
};
} // namespace devilution
| 22.743017 | 102 | 0.637927 | mewpull |
cdce971983ea1a01c07ceaff159a24f2e3f40ce2 | 3,567 | cpp | C++ | graphics/graphics.cpp | Grayson112233/sdlgl | 68c0398fa1dc5ebed77f2528856f7cd6d6d9cdda | [
"MIT"
] | 1 | 2019-12-25T19:35:00.000Z | 2019-12-25T19:35:00.000Z | graphics/graphics.cpp | graysonpike/sdlgl | 68c0398fa1dc5ebed77f2528856f7cd6d6d9cdda | [
"MIT"
] | null | null | null | graphics/graphics.cpp | graysonpike/sdlgl | 68c0398fa1dc5ebed77f2528856f7cd6d6d9cdda | [
"MIT"
] | 1 | 2019-12-25T19:35:01.000Z | 2019-12-25T19:35:01.000Z | #include "graphics.h"
// PRIVATE HELPER FUNCTIONS
// Starts SDL2 and creates a window.
// Also starts additional libraries like sdl_ttf and sdl_mixer
// Some flags can be changed for different rendering settings
bool Graphics::init_sdl(std::string window_title) {
// Initialize SDL_video
if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0) {
printf("Error: Failed to init SDL2: %s\n", SDL_GetError());
return false;
}
// Create SDL Window
window = SDL_CreateWindow(
window_title.c_str(), // window title
SDL_WINDOWPOS_UNDEFINED, // initial x position
SDL_WINDOWPOS_UNDEFINED, // initial y position
width, // width, in pixels
height, // height, in pixels
SDL_WINDOW_OPENGL // flags - see below
);
if (window == NULL) {
printf("Could not create window: %s\n", SDL_GetError());
return false;
}
// Initialize renderer with flags
renderer = SDL_CreateRenderer(window, -1,
SDL_RENDERER_ACCELERATED |
SDL_RENDERER_PRESENTVSYNC);
if(renderer == NULL) {
printf("Could not init renderer: %s\n", SDL_GetError());
return false;
}
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
// Initialize TTF
if(TTF_Init() == -1) {
printf("SDL_ttf failed to initialize: %s\n", TTF_GetError());
return false;
}
return true;
}
void Graphics::init_capture_surface() {
capture_surface = SDL_CreateRGBSurface(0, this->width, this->height, 32, 0, 0, 0, 0);
}
// PUBLIC FUNCTIONS
// Initializes SDL and loads resources
Graphics::Graphics(int width, int height, std::string window_title) {
this->width = width;
this->height = height;
debug_visuals_enabled = false;
init_sdl(window_title);
resources = new Resources(renderer);
font_renderer = new FontRenderer(renderer, resources);
fps_counter = FPSCounter();
init_capture_surface();
}
// Clear the screen with a black background
void Graphics::clear_screen(SDL_Color color) {
SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a);
SDL_RenderClear(renderer);
};
// Present renderer and record delta time (in seconds)
void Graphics::present_renderer(float delta) {
SDL_RenderPresent(renderer);
fps_counter.count(delta);
}
void Graphics::toggle_debug_visuals() {
debug_visuals_enabled = !debug_visuals_enabled;
}
void Graphics::set_debug_visuals(bool enabled) {
debug_visuals_enabled = enabled;
}
int Graphics::get_width() {
return width;
}
int Graphics::get_height() {
return height;
}
bool Graphics::get_debug_visuals_enabled() {
return debug_visuals_enabled;
}
SDL_Renderer *Graphics::get_renderer() {
return renderer;
}
FontRenderer *Graphics::get_font_renderer() {
return font_renderer;
}
Resources *Graphics::get_resources() {
return resources;
}
float Graphics::get_fps() {
return fps_counter.get_fps();
}
void Graphics::capture_bmp(std::string filename) {
SDL_RenderReadPixels(renderer, NULL, SDL_GetWindowPixelFormat(window), capture_surface->pixels, capture_surface->pitch);
SDL_SaveBMP(capture_surface, filename.c_str());
}
Graphics::~Graphics() {
SDL_DestroyWindow(window);
SDL_DestroyRenderer(renderer);
SDL_FreeSurface(capture_surface);
delete resources;
delete font_renderer;
Mix_Quit();
IMG_Quit();
SDL_Quit();
} | 24.944056 | 124 | 0.663022 | Grayson112233 |
cdcf4d86da475ef50258ddf52b6cdccff49bd317 | 8,446 | cc | C++ | riegeli/lines/line_reading.cc | mingzhao-db/riegeli | 7314c9767426fa6d25a3a3b5db2bebbf81db27f2 | [
"Apache-2.0"
] | 302 | 2018-01-03T17:41:05.000Z | 2022-03-30T12:06:31.000Z | riegeli/lines/line_reading.cc | mingzhao-db/riegeli | 7314c9767426fa6d25a3a3b5db2bebbf81db27f2 | [
"Apache-2.0"
] | 23 | 2018-11-14T20:30:43.000Z | 2022-02-16T07:52:59.000Z | riegeli/lines/line_reading.cc | mingzhao-db/riegeli | 7314c9767426fa6d25a3a3b5db2bebbf81db27f2 | [
"Apache-2.0"
] | 49 | 2018-02-12T06:20:01.000Z | 2022-03-27T02:38:35.000Z | // Copyright 2019 Google LLC
//
// 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 "riegeli/lines/line_reading.h"
#include <stddef.h>
#include <cstring>
#include <string>
#include "absl/base/attributes.h"
#include "absl/base/optimization.h"
#include "absl/status/status.h"
#include "absl/strings/cord.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "riegeli/base/base.h"
#include "riegeli/base/chain.h"
#include "riegeli/bytes/reader.h"
namespace riegeli {
namespace {
// Reads `length_to_read` bytes from `src`, writes their prefix of
// `length_to_write` bytes to `dest`, appending to existing contents
// (unless `Dest` is `absl::string_view`).
//
// The data to read must be already available in the buffer.
template <typename Dest>
inline void ReadFlatAndSkip(Reader& src, size_t length_to_read,
size_t length_to_write, Dest& dest) {
RIEGELI_ASSERT_LE(length_to_read, src.available())
<< "Failed precondition of ReadFlatAndSkip(): "
"reading more than buffered";
RIEGELI_ASSERT_LE(length_to_write, length_to_read)
<< "Failed precondition of ReadFlatAndSkip(): "
"writing more than reading";
src.ReadAndAppend(length_to_write, dest);
src.Skip(length_to_read - length_to_write);
}
inline void ReadFlatAndSkip(Reader& src, size_t length_to_read,
size_t length_to_write, absl::string_view& dest) {
RIEGELI_ASSERT_LE(length_to_read, src.available())
<< "Failed precondition of ReadFlatAndSkip(): "
"reading more than buffered";
RIEGELI_ASSERT_LE(length_to_write, length_to_read)
<< "Failed precondition of ReadFlatAndSkip(): "
"writing more than reading";
dest = absl::string_view(src.cursor(), length_to_write);
src.move_cursor(length_to_read);
}
inline void ReadFlatAndSkip(Reader& src, size_t length_to_read,
size_t length_to_write, std::string& dest) {
RIEGELI_ASSERT_LE(length_to_read, src.available())
<< "Failed precondition of ReadFlatAndSkip(): "
"reading more than buffered";
RIEGELI_ASSERT_LE(length_to_write, length_to_read)
<< "Failed precondition of ReadFlatAndSkip(): "
"writing more than reading";
dest.append(src.cursor(), length_to_write);
src.move_cursor(length_to_read);
}
template <typename Dest>
inline void ReadFlat(Reader& src, size_t length, Dest& dest) {
return ReadFlatAndSkip(src, length, length, dest);
}
template <typename Dest>
ABSL_ATTRIBUTE_COLD bool MaxLineLengthExceeded(Reader& src, Dest& dest,
size_t max_length) {
ReadFlat(src, max_length, dest);
return src.Fail(absl::ResourceExhaustedError(
absl::StrCat("Maximum line length exceeded: ", max_length)));
}
template <typename Dest>
inline bool FoundNewline(Reader& src, Dest& dest, ReadLineOptions options,
size_t length, size_t newline_length) {
const size_t length_with_newline = length + newline_length;
if (options.keep_newline()) length = length_with_newline;
if (ABSL_PREDICT_FALSE(length > options.max_length())) {
return MaxLineLengthExceeded(src, dest, options.max_length());
}
ReadFlatAndSkip(src, length_with_newline, length, dest);
return true;
}
template <typename Dest>
inline bool ReadLineInternal(Reader& src, Dest& dest, ReadLineOptions options) {
if (ABSL_PREDICT_FALSE(!src.Pull())) return false;
do {
switch (options.newline()) {
case ReadLineOptions::Newline::kLf: {
const char* const newline = static_cast<const char*>(
std::memchr(src.cursor(), '\n', src.available()));
if (ABSL_PREDICT_TRUE(newline != nullptr)) {
return FoundNewline(src, dest, options,
PtrDistance(src.cursor(), newline), 1);
}
goto continue_reading;
}
case ReadLineOptions::Newline::kAny:
for (const char* newline = src.cursor(); newline < src.limit();
++newline) {
if (ABSL_PREDICT_FALSE(*newline == '\n')) {
return FoundNewline(src, dest, options,
PtrDistance(src.cursor(), newline), 1);
}
if (ABSL_PREDICT_FALSE(*newline == '\r')) {
const size_t length = PtrDistance(src.cursor(), newline);
return FoundNewline(src, dest, options, length,
ABSL_PREDICT_TRUE(src.Pull(length + 2)) &&
src.cursor()[length + 1] == '\n'
? size_t{2}
: size_t{1});
}
}
goto continue_reading;
}
RIEGELI_ASSERT_UNREACHABLE()
<< "Unknown newline: " << static_cast<int>(options.newline());
continue_reading:
if (ABSL_PREDICT_FALSE(src.available() > options.max_length())) {
return MaxLineLengthExceeded(src, dest, options.max_length());
}
options.set_max_length(options.max_length() - src.available());
ReadFlat(src, src.available(), dest);
} while (src.Pull());
return src.healthy();
}
} // namespace
bool ReadLine(Reader& src, absl::string_view& dest, ReadLineOptions options) {
options.set_max_length(UnsignedMin(options.max_length(), dest.max_size()));
size_t length = 0;
if (ABSL_PREDICT_FALSE(!src.Pull())) {
dest = absl::string_view();
return false;
}
do {
switch (options.newline()) {
case ReadLineOptions::Newline::kLf: {
const char* const newline = static_cast<const char*>(
std::memchr(src.cursor() + length, '\n', src.available() - length));
if (ABSL_PREDICT_TRUE(newline != nullptr)) {
return FoundNewline(src, dest, options,
PtrDistance(src.cursor(), newline), 1);
}
goto continue_reading;
}
case ReadLineOptions::Newline::kAny:
for (const char* newline = src.cursor() + length; newline < src.limit();
++newline) {
if (ABSL_PREDICT_FALSE(*newline == '\n')) {
return FoundNewline(src, dest, options,
PtrDistance(src.cursor(), newline), 1);
}
if (ABSL_PREDICT_FALSE(*newline == '\r')) {
length = PtrDistance(src.cursor(), newline);
return FoundNewline(src, dest, options, length,
ABSL_PREDICT_TRUE(src.Pull(length + 2)) &&
src.cursor()[length + 1] == '\n'
? size_t{2}
: size_t{1});
}
}
goto continue_reading;
}
RIEGELI_ASSERT_UNREACHABLE()
<< "Unknown newline: " << static_cast<int>(options.newline());
continue_reading:
length = src.available();
if (ABSL_PREDICT_FALSE(length > options.max_length())) {
return MaxLineLengthExceeded(src, dest, options.max_length());
}
} while (src.Pull(length + 1));
dest = absl::string_view(src.cursor(), src.available());
src.move_cursor(src.available());
return src.healthy();
}
bool ReadLine(Reader& src, std::string& dest, ReadLineOptions options) {
dest.clear();
options.set_max_length(UnsignedMin(options.max_length(), dest.max_size()));
return ReadLineInternal(src, dest, options);
}
bool ReadLine(Reader& src, Chain& dest, ReadLineOptions options) {
dest.Clear();
return ReadLineInternal(src, dest, options);
}
bool ReadLine(Reader& src, absl::Cord& dest, ReadLineOptions options) {
dest.Clear();
return ReadLineInternal(src, dest, options);
}
void SkipBOM(Reader& src) {
if (src.pos() != 0) return;
src.Pull(3);
if (src.available() >= 3 && src.cursor()[0] == static_cast<char>(0xef) &&
src.cursor()[1] == static_cast<char>(0xbb) &&
src.cursor()[2] == static_cast<char>(0xbf)) {
src.move_cursor(3);
}
}
} // namespace riegeli
| 37.371681 | 80 | 0.634738 | mingzhao-db |
cdd0fd6f8834ce7406a32374661b5d6b27108131 | 1,375 | cpp | C++ | Lab3/tests2.cpp | NLaDuke/CSIII-Labs | 8f2658d6fcf6cc838bbef17bc5110a10c742bf0e | [
"MIT"
] | null | null | null | Lab3/tests2.cpp | NLaDuke/CSIII-Labs | 8f2658d6fcf6cc838bbef17bc5110a10c742bf0e | [
"MIT"
] | null | null | null | Lab3/tests2.cpp | NLaDuke/CSIII-Labs | 8f2658d6fcf6cc838bbef17bc5110a10c742bf0e | [
"MIT"
] | null | null | null | // testing the implementation of templated list collection
// Mikhail Nesterenko
// 9/10/2015
#include <iostream>
#include <string>
#include "Collection.hpp" // template definition
using std::cout; using std::endl;
using std::string;
int main(){
// manipulating integers
Collection<int> cone;
cout << "Integer collection: ";
cone.add(1); cone.add(2); cone.add(3);
cone.print();
cone.remove(2);
cone.print();
if(equal(cone, cone))
cout << "cone is equal to itself" << endl;
// uncomment when you debug the code above
// manipulating strings
string sa[] = {"yellow", "orange", "green", "blue"};
Collection<string> ctwo;
for(auto s : sa)
ctwo.add(s);
cout << "String collection: ";
ctwo.print();
// manipulating character collections
// individal collections
Collection<char> a2g, h2n, o2u;
for(char c='a'; c <='g'; ++c) a2g.add(c);
for(char c='h'; c <='n'; ++c) h2n.add(c);
for(char c='o'; c <='u'; ++c) o2u.add(c);
if(!equal(a2g, h2n))
cout << "a2g is not equal to o2u" << endl;
// collection of collections
Collection<Collection<char>> cpile;
// adding individual collections
cpile.add(a2g);
cpile.add(h2n);
cpile.add(o2u);
// printing characters from last collection added
cout << "Last added character collection: ";
cpile.last().print();
}
| 21.153846 | 58 | 0.621818 | NLaDuke |
cdd3d2381e837938457bda2d73992f8d87155acc | 744 | cpp | C++ | _includes/code/2020-04/eyeDetection/KeypointDetector.cpp | bewagner/bewagner.github.io | 128b6cf543030ff7ddd0824e3e4d60abd6aadec1 | [
"MIT"
] | null | null | null | _includes/code/2020-04/eyeDetection/KeypointDetector.cpp | bewagner/bewagner.github.io | 128b6cf543030ff7ddd0824e3e4d60abd6aadec1 | [
"MIT"
] | 5 | 2020-08-15T11:04:55.000Z | 2022-02-26T07:43:45.000Z | _includes/code/2020-04/eyeDetection/KeypointDetector.cpp | bewagner/bewagner.github.io | 128b6cf543030ff7ddd0824e3e4d60abd6aadec1 | [
"MIT"
] | null | null | null | #include "KeypointDetector.h"
#include <opencv4/opencv2/opencv.hpp>
KeypointDetector::KeypointDetector() {
facemark_ = cv::face::FacemarkLBF::create();
facemark_->loadModel(KEYPOINT_DETECTION_MODEL);
}
std::vector<FaceKeypoints>
KeypointDetector::detect_keypoints(const std::vector<cv::Rect> &face_rectangles, const cv::Mat &image) const {
cv::InputArray faces_as_input_array(face_rectangles);
std::vector<std::vector<cv::Point2f> > keypoints;
facemark_->fit(image, faces_as_input_array, keypoints);
std::vector<FaceKeypoints> faces;
std::transform(keypoints.begin(), keypoints.end(), std::back_inserter(faces), [](const auto &keypoints) {
return FaceKeypoints(keypoints);
});
return faces;
}
| 29.76 | 110 | 0.727151 | bewagner |
cdd49c3db54b6cd5d21801fd8b786b03f0eb05d5 | 2,793 | cpp | C++ | Tests/unit-tests/Source/wali/domains/class-TraceSplitSemElem/TraceSplitSemElem.cpp | jusito/WALi-OpenNWA | 2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99 | [
"MIT"
] | 15 | 2015-03-07T17:25:57.000Z | 2022-02-04T20:17:00.000Z | Tests/unit-tests/Source/wali/domains/class-TraceSplitSemElem/TraceSplitSemElem.cpp | jusito/WALi-OpenNWA | 2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99 | [
"MIT"
] | 1 | 2018-03-03T05:58:55.000Z | 2018-03-03T12:26:10.000Z | Tests/unit-tests/Source/wali/domains/class-TraceSplitSemElem/TraceSplitSemElem.cpp | jusito/WALi-OpenNWA | 2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99 | [
"MIT"
] | 15 | 2015-09-25T17:44:35.000Z | 2021-07-18T18:25:38.000Z | #include <gtest/gtest.h>
#include "wali/domains/TraceSplitSemElem.hpp"
#include "fixtures.hpp"
namespace wali {
namespace domains {
TEST(testing$TraceSplitMaps, MapsHaveTheCorrectSize) {
TraceSplitMaps maps;
EXPECT_EQ(0u, maps.empty.size());
EXPECT_EQ(3u, maps.guards012.size());
EXPECT_EQ(3u, maps.guardsF12.size());
}
////////////////////////////////////////////////
TraceSplitSemElem *
down(sem_elem_t ptr_se) {
TraceSplitSemElem * ptr_tsse = dynamic_cast<TraceSplitSemElem*>(ptr_se.get_ptr());
assert(ptr_tsse);
return ptr_tsse;
}
TEST(wali$domains$TraceSplitSemElem$$getWeight, ReturnsDefaultValueForAbsentValues)
{
using namespace ::testing::ShortestPathWeights;
TraceSplitSemElems weights;
LiteralGuards guards;
EXPECT_TRUE(down(weights.empty_default_dist0)->getWeight(guards.zero) -> equal(dist0));
EXPECT_TRUE(down(weights.empty_default_infty)->getWeight(guards.zero) -> equal(semiring_zero));
EXPECT_TRUE(down(weights.guards012_default_dist0)->getWeight(guards.three) -> equal(dist0));
EXPECT_TRUE(down(weights.guards012_default_infty)->getWeight(guards.three) -> equal(semiring_zero));
EXPECT_TRUE(down(weights.guardsF12_default_dist0)->getWeight(guards.three) -> equal(dist0));
}
TEST(wali$domains$TraceSplitSemElem$$getWeight, FalseGuardNotAddedAndReturnsDefault)
{
using namespace ::testing::ShortestPathWeights;
TraceSplitSemElems weights;
LiteralGuards guards;
EXPECT_TRUE(down(weights.guardsF12_default_dist0)->getWeight(guards.false_) -> equal(dist0));
}
TEST(wali$domains$TraceSplitSemElem$$getWeight, ReturnsCorrectValueForPresentValues)
{
using namespace ::testing::ShortestPathWeights;
TraceSplitSemElems weights;
LiteralGuards guards;
EXPECT_TRUE(down(weights.guards012_default_dist0)->getWeight(guards.zero) -> equal(dist0));
EXPECT_TRUE(down(weights.guards012_default_infty)->getWeight(guards.zero) -> equal(dist0));
EXPECT_TRUE(down(weights.guards012_default_dist0)->getWeight(guards.one) -> equal(dist1));
EXPECT_TRUE(down(weights.guards012_default_infty)->getWeight(guards.one) -> equal(dist1));
EXPECT_TRUE(down(weights.guards012_default_dist0)->getWeight(guards.two) -> equal(dist2));
EXPECT_TRUE(down(weights.guards012_default_infty)->getWeight(guards.two) -> equal(dist2));
EXPECT_TRUE(down(weights.guardsF12_default_dist0)->getWeight(guards.one) -> equal(dist1));
EXPECT_TRUE(down(weights.guardsF12_default_dist0)->getWeight(guards.two) -> equal(dist2));
}
}
}
// Yo emacs!
// Local Variables:
// c-file-style: "ellemtel"
// c-basic-offset: 2
// indent-tabs-mode: nil
// End:
| 34.481481 | 106 | 0.706767 | jusito |
cdd50452790904e7c393193de03199bc7c3b7ffc | 9,975 | cpp | C++ | codes/View/MainWindow.cpp | wuzhuobin/IADE_Analyzer | fa78f5999c820a7cf6bf740080933d84ef8952ca | [
"Apache-2.0"
] | 2 | 2021-01-09T08:13:23.000Z | 2021-04-28T14:16:50.000Z | codes/View/MainWindow.cpp | wuzhuobin/IADE_Analyzer | fa78f5999c820a7cf6bf740080933d84ef8952ca | [
"Apache-2.0"
] | 8 | 2017-02-09T11:04:13.000Z | 2017-03-22T03:25:12.000Z | codes/View/MainWindow.cpp | wuzhuobin/IADE_Analyzer | fa78f5999c820a7cf6bf740080933d84ef8952ca | [
"Apache-2.0"
] | null | null | null | #include "MainWindow.h"
#include "ui_MainWindow.h"
#include "ui_ViewerWidget.h"
#include "ModuleWidget.h"
#include "ViewerWidget.h"
#include "MeasurementWidget.h"
#include <qdebug.h>
#include <qsettings.h>
#include <qfiledialog.h>
#include <QVTKInteractor.h>
#include <vtkRenderWindow.h>
#include "RegistrationWizard.h"
MainWindow::MainWindow(QWidget *parent)
:QMainWindow(parent)
{
ui = new Ui::MainWindow;
ui->setupUi(this);
this->moduleWiget = new ModuleWidget(this);
ui->moduleWidgetDockWidget->setWidget(this->moduleWiget);
this->measurementWidget = new MeasurementWidget(this);
ui->measurementDockWidget->setWidget(measurementWidget);
this->tabifyDockWidget(ui->measurementDockWidget, ui->moduleWidgetDockWidget);
QMainWindow* centralWidget = new QMainWindow(this);
centralWidget->setDockNestingEnabled(true);
ui->verticalLayoutCentralWidget->insertWidget(0, centralWidget);
for (int i = NUM_OF_VIEWERS - 1; i > -1; --i) {
this->viewerWidgets[i] = new ViewerWidget(this);
if (i % 2) {
centralWidget->addDockWidget(Qt::BottomDockWidgetArea, this->viewerWidgets[i]);
}
else {
centralWidget->addDockWidget(Qt::TopDockWidgetArea, this->viewerWidgets[i]);
}
this->selectImgMenus[i] = new QMenu(this);
this->viewerWidgets[i]->getUi()->pushButtonSelectImage->setMenu(this->selectImgMenus[i]);
}
settings = new QSettings("Setting.ini", QSettings::IniFormat, this);
connect(viewerWidgets[0]->getUi()->pushButtonRestore, SIGNAL(toggled(bool)),
ui->actionImage1, SLOT(setChecked(bool)));
connect(viewerWidgets[1]->getUi()->pushButtonRestore, SIGNAL(toggled(bool)),
ui->actionImage2, SLOT(setChecked(bool)));
connect(viewerWidgets[2]->getUi()->pushButtonRestore, SIGNAL(toggled(bool)),
ui->actionImage3, SLOT(setChecked(bool)));
connect(viewerWidgets[3]->getUi()->pushButtonRestore, SIGNAL(toggled(bool)),
ui->actionImage4, SLOT(setChecked(bool)));
QActionGroup* actionGroupActionImage = new QActionGroup(this);
actionGroupActionImage->addAction(ui->actionImage1);
actionGroupActionImage->addAction(ui->actionImage2);
actionGroupActionImage->addAction(ui->actionImage3);
actionGroupActionImage->addAction(ui->actionImage4);
actionGroupActionImage->addAction(ui->actionFourViews);
actionGroupActionImage->setExclusive(true);
connect(ui->actionImage1, SIGNAL(toggled(bool)), this, SLOT(slotImage(bool)));
connect(ui->actionImage2, SIGNAL(toggled(bool)), this, SLOT(slotImage(bool)));
connect(ui->actionImage3, SIGNAL(toggled(bool)), this, SLOT(slotImage(bool)));
connect(ui->actionImage4, SIGNAL(toggled(bool)), this, SLOT(slotImage(bool)));
connect(ui->actionFourViews, SIGNAL(toggled(bool)), this, SLOT(slotImage(bool)));
QActionGroup* actionGroupView = new QActionGroup(this);
actionGroupView->addAction(ui->actionAll_axial_view);
actionGroupView->addAction(ui->actionMulti_planar_view);
//actionGroupView->addAction(ui->actionCurved_view);
actionGroupView->setExclusive(true);
QActionGroup* actionGroupImage = new QActionGroup(this);
actionGroupImage->addAction(ui->actionNavigation);
actionGroupImage->addAction(ui->actionWindow_level);
actionGroupImage->addAction(ui->acitonVOI_selection);
actionGroupImage->addAction(ui->actionPaint_brush);
actionGroupImage->addAction(ui->actionSeeds_placer);
actionGroupImage->addAction(ui->actionVBD_Smoker);
actionGroupImage->addAction(ui->actionTubular_VOI);
actionGroupImage->addAction(ui->actionDistance_measure);
actionGroupImage->addAction(ui->actionTesting);
actionGroupImage->setExclusive(true);
QActionGroup* actionGroupSurface = new QActionGroup(this);
actionGroupSurface->addAction(ui->actionTraceball_camera);
actionGroupSurface->addAction(ui->actionCenter_line);
actionGroupSurface->addAction(ui->actionFind_maximum_radius);
actionGroupSurface->addAction(ui->actionCurved_navigation);
actionGroupSurface->setExclusive(true);
// Connection
connect(ui->actionExit, SIGNAL(triggered()), this, SLOT(close()));
connect(ui->actionImport_images, SIGNAL(triggered()), this, SLOT(slotOpenNewImage()));
connect(ui->actionImport_segmentation, SIGNAL(triggered()),
this, SLOT(slotOpenOverlay()));
connect(ui->actionExport_segmentation, SIGNAL(triggered()),
this, SLOT(slotSaveOverlay()));
createRecentImageActions();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::slotOpenRecentImage()
{
QCoreApplication::processEvents();
QAction *action = qobject_cast<QAction *>(sender());
if (action)
{
imageImport(action->data().toString());
}
}
void MainWindow::slotOpenNewImage()
{
imageImport("");
}
void MainWindow::slotOpenOverlay()
{
QString path = QFileDialog::getOpenFileName((this),
QString(tr("Import Segmentation")), ".", tr("NIFTI Images (*.nii)"));
if (path.isEmpty()) return;
emit signalOverlayImportLoad(path);
}
void MainWindow::slotSaveOverlay()
{
QString path = QFileDialog::getSaveFileName((this),
QString(tr("Export Segmentation")), ".", tr("NIFTI Images (*.nii)"));
if (path.isEmpty()) return;
emit signalOverlayExportSave(path);
}
void MainWindow::slotImage(bool flag)
{
QAction *action = qobject_cast<QAction *>(sender());
//qDebug() << actionGroupActionImage->checkedAction();
if (!flag) {
if (ui->actionImage1->isChecked() ||
ui->actionImage2->isChecked() ||
ui->actionImage3->isChecked() ||
ui->actionImage4->isChecked()) {
return;
}
else {
ui->actionFourViews->setChecked(true);
return;
}
}
for (int i = 0; i < NUM_OF_VIEWERS; ++i) {
if (!this->viewerWidgets[i]->isFloating()) {
this->viewerWidgets[i]->setHidden(true);
}
}
if (action == ui->actionFourViews) {
for (int i = 0; i < NUM_OF_VIEWERS; ++i) {
this->viewerWidgets[i]->setHidden(false);
this->viewerWidgets[i]->getUi()->pushButtonRestore->setChecked(false);
}
}
else if (action == ui->actionImage1) {
this->viewerWidgets[0]->setHidden(false);
this->viewerWidgets[0]->getUi()->pushButtonRestore->setChecked(true);
}
else if (action == ui->actionImage2) {
this->viewerWidgets[1]->setHidden(false);
this->viewerWidgets[1]->getUi()->pushButtonRestore->setChecked(true);
}
else if (action == ui->actionImage3) {
this->viewerWidgets[2]->setHidden(false);
this->viewerWidgets[2]->getUi()->pushButtonRestore->setChecked(true);
}
else if (action == ui->actionImage4)
{
this->viewerWidgets[3]->setHidden(false);
this->viewerWidgets[3]->getUi()->pushButtonRestore->setChecked(true);
}
//m_core->RenderAllViewer();
}
void MainWindow::imageImport(QString path)
{
RegistrationWizard rw(path, modalityNames.size(), this);
for (int i = 0; i < modalityNames.size(); ++i) {
rw.setImageModalityNames(i, modalityNames[i]);
}
QList<QStringList> _listOfFileNames;
if (QWizard::Accepted == rw.exec()) {
for (int i = 0; i < modalityNames.size(); ++i) {
if (rw.getFileNames(i)) {
qDebug() << *rw.getFileNames(i);
_listOfFileNames << *rw.getFileNames(i);
}
}
emit signalImageImportLoad(&_listOfFileNames);
qDebug() << rw.getDirectory();
adjustForCurrentFile(rw.getDirectory());
}
}
void MainWindow::initialization()
{
this->setEnabled(true);
ui->centralwidget->setEnabled(true);
ui->ActionToolBar->setEnabled(true);
ui->actionMulti_planar_view->trigger();
ui->actionNavigation->trigger();
}
void MainWindow::enableInteractor(bool flag)
{
}
//void MainWindow::setModuleWidget(QWidget * moduleWidget)
//{
// ui->moduleWidgetDockWidget->setWidget(moduleWidget);
//}
void MainWindow::addModalityNames(QString name)
{
modalityNames << name;
for (int i = 0; i < NUM_OF_2D_VIEWERS; ++i) {
selectImgMenus[i]->addAction(new QAction(name, selectImgMenus[i]));
}
}
void MainWindow::setSelectImgMenuVisible(unsigned int num, bool flag)
{
for (int i = 0; i < NUM_OF_2D_VIEWERS; ++i) {
QList<QAction*> actions = selectImgMenus[i]->actions();
actions[num]->setVisible(flag);
}
}
void MainWindow::clearModalityNames()
{
modalityNames.clear();
for (int i = 0; i < NUM_OF_2D_VIEWERS; ++i) {
selectImgMenus[i]->clear();
}
}
Ui::MainWindow * MainWindow::getUi()
{
return this->ui;
}
//QMainWindow * MainWindow::getCentralWidget()
//{
// return &this->centralWidget;
//}
ModuleWidget * MainWindow::getModuleWidget()
{
return this->moduleWiget;
}
ViewerWidget * MainWindow::getViewerWidget(unsigned int num)
{
return this->viewerWidgets[num];
}
MeasurementWidget * MainWindow::getMeasurementWidget()
{
return this->measurementWidget;
}
QMenu * MainWindow::getSelectImgMenu(unsigned int i)
{
return selectImgMenus[i];
}
void MainWindow::setEnabled(bool flag)
{
ui->actionAbout->setEnabled(true);
}
void MainWindow::createRecentImageActions()
{
QAction* recentFileAction = 0;
for (int i = 0; i < MAX_RECENT_IMAGE; i++) {
recentFileAction = new QAction(this);
recentFileAction->setVisible(false);
connect(recentFileAction, SIGNAL(triggered()), this, SLOT(slotOpenRecentImage()));
recentFileActionList.append(recentFileAction);
ui->menuRecentImage->addAction(recentFileAction);
}
updateRecentActionList();
}
void MainWindow::adjustForCurrentFile(const QString &filePath)
{
QStringList recentFilePaths = settings->value("recentFiles").toStringList();
recentFilePaths.removeAll(filePath);
recentFilePaths.prepend(filePath);
while (recentFilePaths.size() > MAX_RECENT_IMAGE)
recentFilePaths.removeLast();
settings->setValue("recentFiles", recentFilePaths);
// see note
updateRecentActionList();
}
void MainWindow::updateRecentActionList()
{
QStringList recentFilePaths =
settings->value("recentFiles").toStringList();
int itEnd = 0;
if (recentFilePaths.size() <= MAX_RECENT_IMAGE)
itEnd = recentFilePaths.size();
else
itEnd = MAX_RECENT_IMAGE;
for (int i = 0; i < itEnd; i++)
{
recentFileActionList.at(i)->setText(recentFilePaths.at(i));
recentFileActionList.at(i)->setData(recentFilePaths.at(i));
recentFileActionList.at(i)->setVisible(true);
}
for (int i = itEnd; i < MAX_RECENT_IMAGE; i++)
recentFileActionList.at(i)->setVisible(false);
} | 27.941176 | 91 | 0.735539 | wuzhuobin |
cdd644b75465c0698d69909d1ba66d14ac288cd5 | 531 | cpp | C++ | Disruptor.Tests/IgnoreExceptionHandlerTests.cpp | GregGodin/Disruptor-cpp | aa06c37b94dfae3b9859bfbeaf1cd66ea27fac6b | [
"Apache-2.0"
] | 4 | 2019-07-22T04:04:00.000Z | 2022-01-18T11:25:48.000Z | Disruptor.Tests/IgnoreExceptionHandlerTests.cpp | GregGodin/Disruptor-cpp | aa06c37b94dfae3b9859bfbeaf1cd66ea27fac6b | [
"Apache-2.0"
] | null | null | null | Disruptor.Tests/IgnoreExceptionHandlerTests.cpp | GregGodin/Disruptor-cpp | aa06c37b94dfae3b9859bfbeaf1cd66ea27fac6b | [
"Apache-2.0"
] | 2 | 2019-07-25T13:03:16.000Z | 2019-10-25T06:23:15.000Z | #include "stdafx.h"
#include "Disruptor/ArgumentException.h"
#include "Disruptor/IgnoreExceptionHandler.h"
#include "StubEvent.h"
using namespace Disruptor;
TEST(IgnoreExceptionHandlerTests, ShouldIgnoreException)
{
auto causeException = ArgumentException("IgnoreExceptionHandler.ShouldIgnoreException");
auto evt = Tests::StubEvent(0);
auto exceptionHandler = std::make_shared< IgnoreExceptionHandler< Tests::StubEvent> >();
EXPECT_NO_THROW(exceptionHandler->handleEventException(causeException, 0L, evt));
}
| 29.5 | 92 | 0.789077 | GregGodin |
cdd71c1edcc827f37720968a67eee211dfc2f3ae | 1,214 | cpp | C++ | 10229.cpp | felikjunvianto/kfile-uvaoj-submissions | 5bd8b3b413ca8523abe412b0a0545f766f70ce63 | [
"MIT"
] | null | null | null | 10229.cpp | felikjunvianto/kfile-uvaoj-submissions | 5bd8b3b413ca8523abe412b0a0545f766f70ce63 | [
"MIT"
] | null | null | null | 10229.cpp | felikjunvianto/kfile-uvaoj-submissions | 5bd8b3b413ca8523abe412b0a0545f766f70ce63 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cmath>
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <vector>
#include <utility>
#include <stack>
#include <queue>
#include <map>
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define pi 2*acos(0.0)
#define eps 1e-9
#define PII pair<int,int>
#define PDD pair<double,double>
#define LL long long
#define INF 1000000000
using namespace std;
typedef struct
{
LL a,b,c,d;
} cell;
int N,M;
LL mod;
int ans;
cell bigmod(int now)
{
if(now==1) return((cell){0,1,1,1});
cell ans,bagi=bigmod(now/2);
ans.a=((bagi.a*bagi.a)%mod+(bagi.b*bagi.c)%mod)%mod;
ans.b=((bagi.a*bagi.b)%mod+(bagi.b*bagi.d)%mod)%mod;
ans.c=((bagi.c*bagi.a)%mod+(bagi.d*bagi.c)%mod)%mod;
ans.d=((bagi.c*bagi.b)%mod+(bagi.d*bagi.d)%mod)%mod;
if(now&1)
{
cell temp=ans;
ans.a=temp.b;
ans.b=(temp.a+temp.b)%mod;
ans.c=temp.d;
ans.d=(temp.c+temp.d)%mod;
}
return(ans);
}
int main()
{
while(scanf("%d %d",&N,&M)!=EOF)
{
mod=1LL<<M;
if(N<2) printf("%lld\n",(LL)N%mod); else
{
cell mat=bigmod(N-1);
printf("%lld\n",mat.d%mod);
}
}
return 0;
}
| 17.594203 | 54 | 0.599671 | felikjunvianto |
cdd763b7a24905ccb38cf93e309fb5a7a6d4790a | 2,017 | hpp | C++ | src/sched/entry/ze/ze_barrier_entry.hpp | oneapi-src/oneCCL | b5d62cac0e7be776e2430a7d44d53a6e5e551daf | [
"Apache-2.0"
] | 70 | 2020-03-05T21:16:08.000Z | 2022-03-24T21:58:56.000Z | src/sched/entry/ze/ze_barrier_entry.hpp | oneapi-src/oneCCL | b5d62cac0e7be776e2430a7d44d53a6e5e551daf | [
"Apache-2.0"
] | 17 | 2020-03-14T08:28:07.000Z | 2022-03-03T06:35:34.000Z | src/sched/entry/ze/ze_barrier_entry.hpp | oneapi-src/oneCCL | b5d62cac0e7be776e2430a7d44d53a6e5e551daf | [
"Apache-2.0"
] | 22 | 2020-03-13T01:17:22.000Z | 2022-03-16T12:42:43.000Z | /*
Copyright 2016-2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#include "sched/entry/factory/entry_factory.hpp"
#include <ze_api.h>
class ze_barrier_entry : public sched_entry {
public:
static constexpr const char* class_name() noexcept {
return "ZE_BARRIER";
}
const char* name() const noexcept override {
return class_name();
}
ze_barrier_entry() = delete;
explicit ze_barrier_entry(ccl_sched* sched,
ccl_comm* comm,
ze_event_pool_handle_t& local_pool,
size_t event_idx);
~ze_barrier_entry();
void start() override;
void update() override;
void finalize() override;
protected:
void dump_detail(std::stringstream& str) const override {
ccl_logger::format(str,
"rank ",
rank,
", comm_size ",
comm_size,
", comm_id ",
sched->get_comm_id(),
"wait_events: ",
wait_events.size(),
"\n");
}
private:
ccl_comm* comm;
const int rank;
const int comm_size;
size_t last_completed_event_idx{};
size_t event_idx{};
ze_event_pool_handle_t local_pool{};
ze_event_handle_t signal_event{};
std::vector<std::pair<int, ze_event_handle_t>> wait_events{};
};
| 29.231884 | 73 | 0.597918 | oneapi-src |
cdd80d62e2be8d1d26a56e686edb98f577692c1d | 47,398 | cpp | C++ | Source/AliveLibAE/Map.cpp | Leonard2/alive_reversing | c6d85f435e275db1d41e2ec8b4e52454aa932e05 | [
"MIT"
] | null | null | null | Source/AliveLibAE/Map.cpp | Leonard2/alive_reversing | c6d85f435e275db1d41e2ec8b4e52454aa932e05 | [
"MIT"
] | null | null | null | Source/AliveLibAE/Map.cpp | Leonard2/alive_reversing | c6d85f435e275db1d41e2ec8b4e52454aa932e05 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "Map.hpp"
#include "PathData.hpp"
#include "Function.hpp"
#include "ScreenManager.hpp"
#include "ResourceManager.hpp"
#include "LvlArchive.hpp"
#include "Sound/Midi.hpp"
#include "SwitchStates.hpp"
#include "Game.hpp"
#include "Abe.hpp"
#include "MusicController.hpp"
#include "BackgroundMusic.hpp"
#include "stdlib.hpp"
#include "Path.hpp"
#include "QuikSave.hpp"
#include "Text.hpp"
#include "Sfx.hpp"
#include "FG1.hpp"
#include "CameraSwapper.hpp"
#include "MainMenu.hpp"
#include "Events.hpp"
#include "Movie.hpp"
#include "Particle.hpp"
#include "Door.hpp"
#include "Sound/PsxSpuApi.hpp"
#include "Sys.hpp"
#include <assert.h>
void Map_ForceLink()
{ }
ALIVE_VAR(1, 0x5c311c, s16, sMap_bDoPurpleLightEffect_5C311C, 0);
ALIVE_VAR(1, 0x5c3118, Camera*, sCameraBeingLoaded_5C3118, nullptr);
ALIVE_VAR(1, 0x5c3120, u32, sSoundChannelsMask_5C3120, 0);
// Map Path_ChangeTLV::field_18_wipe to CameraSwapEffects
const CameraSwapEffects kPathChangeEffectToInternalScreenChangeEffect_55D55C[10] = {
CameraSwapEffects::eEffect5_1_FMV,
CameraSwapEffects::eEffect2_RightToLeft,
CameraSwapEffects::eEffect1_LeftToRight,
CameraSwapEffects::eEffect4_BottomToTop,
CameraSwapEffects::eEffect3_TopToBottom,
CameraSwapEffects::eEffect8_BoxOut,
CameraSwapEffects::eEffect6_VerticalSplit,
CameraSwapEffects::eEffect7_HorizontalSplit,
CameraSwapEffects::eEffect11_Unknown,
CameraSwapEffects::eEffect0_InstantChange};
EXPORT void CC static_map_construct_4802F0()
{
gMap_5C3030.Reset_4805D0();
}
EXPORT void CC static_map_destruct_480330()
{
gMap_5C3030.Shutdown_4804E0();
}
EXPORT void CC static_map_init_4802D0()
{
static_map_construct_4802F0();
atexit(static_map_destruct_480330);
}
void Map::ScreenChange_Common()
{
if (field_6_state == 1)
{
ResourceManager::Reclaim_Memory_49C470(0);
Handle_PathTransition_481610();
}
else if (field_6_state == 2)
{
ResourceManager::Reclaim_Memory_49C470(0);
GoTo_Camera_481890();
}
field_6_state = 0;
SND_Stop_Channels_Mask_4CA810(sSoundChannelsMask_5C3120);
sSoundChannelsMask_5C3120 = 0;
}
void Map::ScreenChange_480B80()
{
if (field_6_state == 0)
{
return;
}
if (sMap_bDoPurpleLightEffect_5C311C)
{
RemoveObjectsWithPurpleLight_480740(1);
}
PSX_DrawSync_4F6280(0);
for (s32 i = 0; i < 2; i++) // Not sure why this is done twice?
{
DynamicArrayIter iter = {};
iter.field_4_idx = 0;
iter.field_0_pDynamicArray = gBaseGameObject_list_BB47C4;
while (iter.field_4_idx < iter.field_0_pDynamicArray->field_4_used_size)
{
BaseGameObject* pItem = gBaseGameObject_list_BB47C4->ItemAt(iter.field_4_idx);
++iter.field_4_idx;
if (!pItem)
{
break;
}
pItem->VScreenChanged();
// Did the screen change kill the object?
if (pItem->field_6_flags.Get(BaseGameObject::eDead_Bit3))
{
iter.Remove_At_Iter_40CCA0();
pItem->VDestructor(1);
}
}
}
ResourceManager::NoEffect_49C700();
//dword_5CA4A8 = 0; // TODO: Never used?
// TODO: Refactor this logic
if (!sMap_bDoPurpleLightEffect_5C311C && field_A_level == field_0_current_level)
{
ScreenChange_Common();
return;
}
if (field_A_level != field_0_current_level)
{
SsUtAllKeyOff_4FDFE0(0);
}
if (field_A_level != LevelIds::eNone)
{
if (field_A_level == LevelIds::eCredits_16)
{
sSoundChannelsMask_5C3120 = 0;
ScreenChange_Common();
return;
}
}
else if (field_0_current_level == LevelIds::eMenu_0)
{
sSoundChannelsMask_5C3120 = 0;
ScreenChange_Common();
return;
}
sSoundChannelsMask_5C3120 = SND_4CA5D0(0, 0, 36, 70, 0, 0);
ScreenChange_Common();
}
void Map::RemoveObjectsWithPurpleLight_480740(s16 bMakeInvisible)
{
auto pObjectsWithLightsArray = ae_new<DynamicArrayT<BaseAnimatedWithPhysicsGameObject>>();
pObjectsWithLightsArray->ctor_40CA60(16);
auto pPurpleLightArray = ae_new<DynamicArrayT<Particle>>();
pPurpleLightArray->ctor_40CA60(16);
bool bAddedALight = false;
for (s32 i = 0; i < gBaseGameObject_list_BB47C4->Size(); i++)
{
BaseGameObject* pObj = gBaseGameObject_list_BB47C4->ItemAt(i);
if (!pObj)
{
break;
}
if (pObj->field_6_flags.Get(BaseGameObject::eIsBaseAnimatedWithPhysicsObj_Bit5))
{
if (pObj->field_6_flags.Get(BaseGameObject::eDrawable_Bit4))
{
auto pBaseObj = static_cast<BaseAnimatedWithPhysicsGameObject*>(pObj);
PSX_RECT objRect = {};
pBaseObj->vGetBoundingRect_424FD0(&objRect, 1);
if (pBaseObj->field_DC_bApplyShadows & 2)
{
if (pBaseObj->field_20_animation.field_4_flags.Get(AnimFlags::eBit3_Render))
{
if (!pBaseObj->field_6_flags.Get(BaseGameObject::eDead_Bit3) && pBaseObj != sControlledCharacter_5C1B8C && gMap_5C3030.Rect_Location_Relative_To_Active_Camera_480FE0(&objRect) == CameraPos::eCamCurrent_0)
{
pObjectsWithLightsArray->Push_Back(pBaseObj);
const FP k60Scaled = (pBaseObj->field_CC_sprite_scale * FP_FromInteger(60));
Particle* pPurpleLight = New_DestroyOrCreateObject_Particle_426F40(
FP_FromInteger((objRect.x + objRect.w) / 2),
FP_FromInteger(((objRect.y + objRect.h) / 2)) + k60Scaled,
pBaseObj->field_CC_sprite_scale);
if (pPurpleLight)
{
pPurpleLightArray->Push_Back(pPurpleLight);
bAddedALight = true;
}
}
}
}
}
}
}
if (bAddedALight)
{
SFX_Play_46FBA0(SoundEffect::PossessEffect_17, 40, 2400);
for (s32 counter = 0; counter < 12; counter++)
{
if (bMakeInvisible && counter == 4)
{
// Make all the objects that have lights invisible now that the lights have been rendered for a few frames
for (s32 i = 0; i < pObjectsWithLightsArray->Size(); i++)
{
BaseAnimatedWithPhysicsGameObject* pObj = pObjectsWithLightsArray->ItemAt(i);
if (!pObj)
{
break;
}
pObj->field_20_animation.field_4_flags.Clear(AnimFlags::eBit3_Render);
}
}
for (s32 i = 0; i < pPurpleLightArray->Size(); i++)
{
Particle* pLight = pPurpleLightArray->ItemAt(i);
if (!pLight)
{
break;
}
if (!pLight->field_6_flags.Get(BaseGameObject::eDead_Bit3))
{
pLight->VUpdate();
}
}
// TODO/HACK what is the point of the f64 loop? Why not do both in 1 iteration ??
for (s32 i = 0; i < pPurpleLightArray->Size(); i++)
{
Particle* pLight = pPurpleLightArray->ItemAt(i);
if (!pLight)
{
break;
}
if (!pLight->field_6_flags.Get(BaseGameObject::eDead_Bit3))
{
pLight->field_20_animation.vDecode_40AC90();
}
}
for (s32 i = 0; i < gObjList_drawables_5C1124->Size(); i++)
{
BaseGameObject* pDrawable = gObjList_drawables_5C1124->ItemAt(i);
if (!pDrawable)
{
break;
}
if (!pDrawable->field_6_flags.Get(BaseGameObject::eDead_Bit3))
{
// TODO: Seems strange to check this flag, how did it get in the drawable list if its not a drawable ??
if (pDrawable->field_6_flags.Get(BaseGameObject::eDrawable_Bit4))
{
pDrawable->VRender(gPsxDisplay_5C1130.field_10_drawEnv[gPsxDisplay_5C1130.field_C_buffer_index].field_70_ot_buffer);
}
}
}
PSX_DrawSync_4F6280(0);
pScreenManager_5BB5F4->VRender(gPsxDisplay_5C1130.field_10_drawEnv[gPsxDisplay_5C1130.field_C_buffer_index].field_70_ot_buffer);
SYS_EventsPump_494580();
gPsxDisplay_5C1130.PSX_Display_Render_OT_41DDF0();
}
if (bMakeInvisible)
{
// Make all the objects that had lights visible again
for (s32 i = 0; i < pObjectsWithLightsArray->Size(); i++)
{
BaseAnimatedWithPhysicsGameObject* pObj = pObjectsWithLightsArray->ItemAt(i);
if (!pObj)
{
break;
}
pObj->field_20_animation.field_4_flags.Set(AnimFlags::eBit3_Render);
}
}
}
pObjectsWithLightsArray->field_4_used_size = 0;
pPurpleLightArray->field_4_used_size = 0;
if (pObjectsWithLightsArray)
{
pObjectsWithLightsArray->dtor_40CAD0();
ae_delete_free_495540(pObjectsWithLightsArray);
}
if (pPurpleLightArray)
{
pPurpleLightArray->dtor_40CAD0();
ae_delete_free_495540(pPurpleLightArray);
}
}
void Map::Handle_PathTransition_481610()
{
Path_Change* pPathChangeTLV = nullptr;
if (field_18_pAliveObj)
{
pPathChangeTLV = static_cast<Path_Change*>(sPath_dword_BB47C0->TLV_Get_At_4DB4B0(
FP_GetExponent(field_18_pAliveObj->field_B8_xpos),
FP_GetExponent(field_18_pAliveObj->field_BC_ypos),
FP_GetExponent(field_18_pAliveObj->field_B8_xpos),
FP_GetExponent(field_18_pAliveObj->field_BC_ypos),
TlvTypes::PathTransition_1));
}
if (field_18_pAliveObj && pPathChangeTLV)
{
field_A_level = pPathChangeTLV->field_10_level;
field_C_path = pPathChangeTLV->field_12_path;
field_E_camera = pPathChangeTLV->field_14_camera;
field_12_fmv_base_id = pPathChangeTLV->field_16_movie;
field_10_screen_change_effect = kPathChangeEffectToInternalScreenChangeEffect_55D55C[pPathChangeTLV->field_18_wipe];
field_18_pAliveObj->field_C2_lvl_number = field_A_level;
field_18_pAliveObj->field_C0_path_number = field_C_path;
GoTo_Camera_481890();
switch (pPathChangeTLV->field_1A_scale)
{
case Scale_short::eFull_0:
sActiveHero_5C1B68->field_CC_sprite_scale = FP_FromDouble(1.0);
sActiveHero_5C1B68->field_20_animation.field_C_render_layer = Layer::eLayer_AbeMenu_32;
break;
case Scale_short::eHalf_1:
sActiveHero_5C1B68->field_CC_sprite_scale = FP_FromDouble(0.5);
sActiveHero_5C1B68->field_20_animation.field_C_render_layer = Layer::eLayer_AbeMenu_Half_13;
break;
default:
LOG_ERROR("Invalid scale " << (s32) pPathChangeTLV->field_1A_scale);
break;
}
CameraPos remapped = CameraPos::eCamInvalid_m1;
switch (field_14_direction)
{
case MapDirections::eMapLeft_0:
remapped = CameraPos::eCamLeft_3;
break;
case MapDirections::eMapRight_1:
remapped = CameraPos::eCamRight_4;
break;
case MapDirections::eMapTop_2:
remapped = CameraPos::eCamTop_1;
break;
case MapDirections::eMapBottom_3:
remapped = CameraPos::eCamBottom_2;
break;
}
field_18_pAliveObj->VOnPathTransition_408320(
field_D0_cam_x_idx * field_D4_ptr->field_A_grid_width,
field_D2_cam_y_idx * field_D4_ptr->field_C_grid_height,
remapped);
}
else
{
switch (field_14_direction)
{
case MapDirections::eMapLeft_0:
field_D0_cam_x_idx--;
field_10_screen_change_effect = CameraSwapEffects::eEffect2_RightToLeft;
break;
case MapDirections::eMapRight_1:
field_D0_cam_x_idx++;
field_10_screen_change_effect = CameraSwapEffects::eEffect1_LeftToRight;
break;
case MapDirections::eMapTop_2:
field_D2_cam_y_idx--;
field_10_screen_change_effect = CameraSwapEffects::eEffect4_BottomToTop;
break;
case MapDirections::eMapBottom_3:
field_D2_cam_y_idx++;
field_10_screen_change_effect = CameraSwapEffects::eEffect3_TopToBottom;
break;
default:
break;
}
const u32 pCamNameOffset = sizeof(CameraName) * (field_D0_cam_x_idx + (field_D2_cam_y_idx * sPath_dword_BB47C0->field_6_cams_on_x));
const u8* pPathRes = *field_54_path_res_array.field_0_pPathRecs[field_2_current_path];
auto pCameraName = reinterpret_cast<const CameraName*>(pPathRes + pCamNameOffset);
// Convert the 2 digit camera number string to an integer
field_E_camera = 1 * (pCameraName->name[7] - '0') + 10 * (pCameraName->name[6] - '0');
GoTo_Camera_481890();
}
}
CameraPos Map::GetDirection_4811A0(s32 level, s32 path, FP xpos, FP ypos)
{
if (level != static_cast<s32>(field_0_current_level))
{
return CameraPos::eCamInvalid_m1;
}
if (path != field_2_current_path)
{
return CameraPos::eCamInvalid_m1;
}
PSX_RECT rect = {};
rect.x = FP_GetExponent(xpos);
rect.w = FP_GetExponent(xpos);
rect.y = FP_GetExponent(ypos);
rect.h = FP_GetExponent(ypos);
CameraPos ret = Rect_Location_Relative_To_Active_Camera_480FE0(&rect);
PSX_RECT camWorldRect = {};
if (!Get_Camera_World_Rect_481410(ret, &camWorldRect))
{
return CameraPos::eCamInvalid_m1;
}
const FP x = FP_FromInteger(camWorldRect.x);
const FP y = FP_FromInteger(camWorldRect.y);
const FP w = FP_FromInteger(camWorldRect.w);
const FP h = FP_FromInteger(camWorldRect.h);
switch (ret)
{
case CameraPos::eCamCurrent_0:
return ret;
case CameraPos::eCamTop_1:
if (ypos < y || xpos < x || xpos > w)
{
return CameraPos::eCamInvalid_m1;
}
return ypos > h ? CameraPos::eCamCurrent_0 : ret;
case CameraPos::eCamBottom_2:
if (ypos > h || xpos < x || xpos > w)
{
return CameraPos::eCamInvalid_m1;
}
return ypos < y ? CameraPos::eCamCurrent_0 : ret;
case CameraPos::eCamLeft_3:
if (xpos < x || ypos < y || ypos > h)
{
return CameraPos::eCamInvalid_m1;
}
return xpos > w ? CameraPos::eCamCurrent_0 : ret;
case CameraPos::eCamRight_4:
if (xpos > w || ypos < y || ypos > h)
{
return CameraPos::eCamInvalid_m1;
}
return xpos < x ? CameraPos::eCamCurrent_0 : ret;
default:
return CameraPos::eCamInvalid_m1;
}
}
void Map::Init_4803F0(LevelIds level, s16 path, s16 camera, CameraSwapEffects screenChangeEffect, s16 fmvBaseId, s16 forceChange)
{
sPath_dword_BB47C0 = ae_new<Path>();
sPath_dword_BB47C0->ctor_4DB170();
field_2C_camera_array[0] = nullptr;
field_2C_camera_array[1] = nullptr;
field_2C_camera_array[2] = nullptr;
field_2C_camera_array[3] = nullptr;
field_2C_camera_array[4] = nullptr;
field_22_overlayID = -1;
field_4_current_camera = static_cast<s16>(-1);
field_2_current_path = static_cast<s16>(-1);
field_0_current_level = LevelIds::eNone;
field_8_force_load = 0;
SetActiveCam_480D30(level, path, camera, screenChangeEffect, fmvBaseId, forceChange);
GoTo_Camera_481890();
field_6_state = 0;
}
void Map::Shutdown_4804E0()
{
sLvlArchive_5BC520.Free_433130();
stru_5C3110.Free_433130();
// Free Path resources
for (s32 i = 0; i < ALIVE_COUNTOF(field_54_path_res_array.field_0_pPathRecs); i++)
{
if (field_54_path_res_array.field_0_pPathRecs[i])
{
ResourceManager::FreeResource_49C330(field_54_path_res_array.field_0_pPathRecs[i]);
field_54_path_res_array.field_0_pPathRecs[i] = nullptr;
}
}
// Free cameras
for (s32 i = 0; i < ALIVE_COUNTOF(field_2C_camera_array); i++)
{
if (field_2C_camera_array[i])
{
field_2C_camera_array[i]->dtor_480E00();
ae_delete_free_495540(field_2C_camera_array[i]);
field_2C_camera_array[i] = nullptr;
}
}
pScreenManager_5BB5F4 = nullptr;
// Free path
if (sPath_dword_BB47C0)
{
sPath_dword_BB47C0->dtor_4DB1A0();
ae_delete_free_495540(sPath_dword_BB47C0);
}
sPath_dword_BB47C0 = nullptr;
ResourceManager::Reclaim_Memory_49C470(0);
Reset_4805D0();
}
void Map::Reset_4805D0()
{
for (s32 i = 0; i < ALIVE_COUNTOF(field_2C_camera_array); i++)
{
field_2C_camera_array[i] = nullptr;
}
field_2C_camera_array[0] = nullptr;
for (s32 i = 0; i < ALIVE_COUNTOF(field_54_path_res_array.field_0_pPathRecs); i++)
{
field_54_path_res_array.field_0_pPathRecs[i] = nullptr;
}
field_CC_unused = 1;
field_CE_free_all_anim_and_palts = 0;
field_D8_restore_quick_save = 0;
}
void Map::GoTo_Camera_481890()
{
s16 bShowLoadingIcon = FALSE;
if (field_0_current_level != LevelIds::eMenu_0 && field_0_current_level != LevelIds::eCredits_16 && field_0_current_level != LevelIds::eNone)
{
bShowLoadingIcon = TRUE;
}
if (field_10_screen_change_effect == CameraSwapEffects::eEffect11_Unknown)
{
BaseGameObject* pFmvRet = FMV_Camera_Change_482650(nullptr, this, field_0_current_level);
do
{
SYS_EventsPump_494580();
for (s32 i = 0; i < gBaseGameObject_list_BB47C4->Size(); i++)
{
BaseGameObject* pBaseGameObj = gBaseGameObject_list_BB47C4->ItemAt(i);
if (!pBaseGameObj)
{
break;
}
if (pBaseGameObj->field_6_flags.Get(BaseGameObject::eUpdatable_Bit2))
{
if (!(pBaseGameObj->field_6_flags.Get(BaseGameObject::eDead_Bit3)) && (!sNum_CamSwappers_5C1B66 || pBaseGameObj->field_6_flags.Get(BaseGameObject::eUpdateDuringCamSwap_Bit10)))
{
if (pBaseGameObj->field_1C_update_delay > 0)
{
pBaseGameObj->field_1C_update_delay--;
}
else
{
pBaseGameObj->VUpdate();
}
}
}
}
}
while (!pFmvRet->field_6_flags.Get(BaseGameObject::eDead_Bit3));
if (sSoundChannelsMask_5C3120)
{
SND_Stop_Channels_Mask_4CA810(sSoundChannelsMask_5C3120);
}
sSoundChannelsMask_5C3120 = SND_4CA5D0(0, 0, 36, 70, 0, 0);
}
if (field_0_current_level != LevelIds::eMenu_0 && field_0_current_level != LevelIds::eNone)
{
if (field_A_level != field_0_current_level
|| field_8_force_load
|| (field_C_path != field_2_current_path && field_10_screen_change_effect == CameraSwapEffects::eEffect5_1_FMV))
{
Game_ShowLoadingIcon_482D80();
}
}
if (field_A_level != field_0_current_level
|| field_C_path != field_2_current_path
|| field_8_force_load)
{
field_22_overlayID = GetOverlayId_480710();
}
if (field_A_level != field_0_current_level || field_8_force_load)
{
pResourceManager_5C1BB0->LoadingLoop_465590(bShowLoadingIcon);
// Free all cameras
for (s32 i = 0; i < ALIVE_COUNTOF(field_2C_camera_array); i++)
{
if (field_2C_camera_array[i])
{
field_2C_camera_array[i]->dtor_480E00();
ae_delete_free_495540(field_2C_camera_array[i]);
field_2C_camera_array[i] = nullptr;
}
}
if (field_0_current_level != LevelIds::eNone)
{
// Close LVL archives
sLvlArchive_5BC520.Free_433130();
stru_5C3110.Free_433130();
// Free all but the first ?
for (s32 i = 1; i <= sPathData_559660.paths[static_cast<s32>(field_0_current_level)].field_18_num_paths; ++i)
{
ResourceManager::FreeResource_49C330(field_54_path_res_array.field_0_pPathRecs[i]);
field_54_path_res_array.field_0_pPathRecs[i] = nullptr;
}
sPath_dword_BB47C0->Free_4DB1C0();
if (field_A_level != field_0_current_level)
{
SND_Reset_4C9FB0();
}
ResourceManager::Reclaim_Memory_49C470(0);
}
pResourceManager_5C1BB0->LoadingLoop_465590(bShowLoadingIcon);
const PathRoot& pathData = sPathData_559660.paths[static_cast<s32>(field_A_level)];
// Open LVL
while (!sLvlArchive_5BC520.Open_Archive_432E80(pathData.field_20_lvl_name_cd))
{
if (gAttract_5C1BA0)
{
// NOTE: Dead branch? Given no attract directory exists
char_type fileName[256] = {};
strcpy(fileName, "ATTRACT");
strcat(fileName, pathData.field_20_lvl_name_cd);
if (sLvlArchive_5BC520.Open_Archive_432E80(fileName))
{
break;
}
}
Display_Full_Screen_Message_Blocking_465820(pathData.field_1A_unused, MessageType::eLongTitle_0);
}
// Open Path BND
ResourceManager::LoadResourceFile_49C170(pathData.field_38_bnd_name, 0);
// Get pointer to each PATH
for (s32 i = 1; i <= pathData.field_18_num_paths; ++i)
{
field_54_path_res_array.field_0_pPathRecs[i] = ResourceManager::GetLoadedResource_49C2A0(ResourceManager::Resource_Path, i, TRUE, FALSE);
}
if (field_A_level == field_0_current_level)
{
MusicController::PlayMusic_47FD60(MusicController::MusicTypes::eNone_0, sActiveHero_5C1B68, 0, 0);
}
else
{
SND_Load_VABS_4CA350(pathData.field_8_pMusicInfo, pathData.field_10_reverb);
SND_Load_Seqs_4CAED0(sSeqData_558D50.mSeqs, pathData.field_C_bsq_file_name);
auto pBackgroundMusic = ae_new<BackgroundMusic>();
if (pBackgroundMusic)
{
pBackgroundMusic->ctor_4CB110(pathData.field_12_bg_music_id);
}
}
if (!field_8_force_load)
{
SwitchStates_SetRange_465FA0(2, 255);
}
if (field_CE_free_all_anim_and_palts)
{
ResourceManager::Free_Resource_Of_Type_49C6B0(ResourceManager::Resource_Animation);
ResourceManager::Free_Resource_Of_Type_49C6B0(ResourceManager::Resource_Palt);
field_CE_free_all_anim_and_palts = FALSE;
}
}
if (!field_C_path)
{
field_C_path = 1;
}
const s16 prevPathId = field_2_current_path;
const LevelIds prevLevelId = field_0_current_level;
field_2_current_path = field_C_path;
field_0_current_level = field_A_level;
field_4_current_camera = field_E_camera;
const PathBlyRec* pPathRec_1 = Path_Get_Bly_Record_460F30(field_A_level, field_C_path);
field_D4_ptr = pPathRec_1->field_4_pPathData;
sPath_dword_BB47C0->Init_4DB200(
field_D4_ptr,
field_A_level,
field_C_path,
field_E_camera,
field_54_path_res_array.field_0_pPathRecs[field_C_path]);
if (sQuickSave_saved_switchResetters_count_BB234C > 0)
{
Quicksave_RestoreSwitchResetterStates_4C9A30();
}
char_type pStrBuffer[13] = {};
Path_Format_CameraName_460FB0(pStrBuffer, field_A_level, field_C_path, field_E_camera);
u32 pCamNameOffset = 0;
if (sizeof(CameraName) * sPath_dword_BB47C0->field_6_cams_on_x * sPath_dword_BB47C0->field_8_cams_on_y > 0)
{
for (;;)
{
u8* pPathRes = *field_54_path_res_array.field_0_pPathRecs[field_C_path];
CameraName* pCameraNameIter = reinterpret_cast<CameraName*>(pPathRes + pCamNameOffset);
if (strncmp(pCameraNameIter->name, pStrBuffer, sizeof(CameraName)) == 0)
{
// Matched
break;
}
pCamNameOffset += sizeof(CameraName);
if (pCamNameOffset >= sizeof(CameraName) * sPath_dword_BB47C0->field_6_cams_on_x * sPath_dword_BB47C0->field_8_cams_on_y)
{
// Out of bounds
break;
}
}
}
field_D0_cam_x_idx = static_cast<s16>((pCamNameOffset / sizeof(CameraName)) % sPath_dword_BB47C0->field_6_cams_on_x);
field_D2_cam_y_idx = static_cast<s16>((pCamNameOffset / sizeof(CameraName)) / sPath_dword_BB47C0->field_6_cams_on_x);
field_24_camera_offset.field_0_x = FP_FromInteger(field_D0_cam_x_idx * field_D4_ptr->field_A_grid_width);
field_24_camera_offset.field_4_y = FP_FromInteger(field_D2_cam_y_idx * field_D4_ptr->field_C_grid_height);
// If map has changed then load new collision info
if (prevPathId != field_2_current_path || prevLevelId != field_0_current_level)
{
if (sCollisions_DArray_5C1128)
{
sCollisions_DArray_5C1128->dtor_4189F0();
ae_delete_free_495540(sCollisions_DArray_5C1128);
}
sCollisions_DArray_5C1128 = ae_new<Collisions>();
if (sCollisions_DArray_5C1128)
{
sCollisions_DArray_5C1128->ctor_418930(pPathRec_1->field_8_pCollisionData, *field_54_path_res_array.field_0_pPathRecs[field_2_current_path]);
}
}
if (field_D8_restore_quick_save)
{
QuikSave_RestoreBlyData_D481890_4C9BE0(field_D8_restore_quick_save);
field_D8_restore_quick_save = nullptr;
}
// Copy camera array and blank out the source
for (s32 i = 0; i < ALIVE_COUNTOF(field_40_stru_5); i++)
{
field_40_stru_5[i] = field_2C_camera_array[i];
field_2C_camera_array[i] = nullptr;
}
field_2C_camera_array[0] = Create_Camera_4829E0(field_D0_cam_x_idx, field_D2_cam_y_idx, 1);
field_2C_camera_array[3] = Create_Camera_4829E0(field_D0_cam_x_idx - 1, field_D2_cam_y_idx, 0);
field_2C_camera_array[4] = Create_Camera_4829E0(field_D0_cam_x_idx + 1, field_D2_cam_y_idx, 0);
field_2C_camera_array[1] = Create_Camera_4829E0(field_D0_cam_x_idx, field_D2_cam_y_idx - 1, 0);
field_2C_camera_array[2] = Create_Camera_4829E0(field_D0_cam_x_idx, field_D2_cam_y_idx + 1, 0);
// Free resources for each camera
for (s32 i = 0; i < ALIVE_COUNTOF(field_40_stru_5); i++)
{
if (field_40_stru_5[i])
{
pResourceManager_5C1BB0->Free_Resources_For_Camera_4656F0(field_40_stru_5[i]);
}
}
pResourceManager_5C1BB0->LoadingLoop_465590(bShowLoadingIcon);
// Free each camera itself
for (s32 i = 0; i < ALIVE_COUNTOF(field_40_stru_5); i++)
{
if (field_40_stru_5[i])
{
field_40_stru_5[i]->dtor_480E00();
ae_delete_free_495540(field_40_stru_5[i]);
field_40_stru_5[i] = nullptr;
}
}
Map::Load_Path_Items_482C10(field_2C_camera_array[0], 0);
pResourceManager_5C1BB0->LoadingLoop_465590(bShowLoadingIcon);
Map::Load_Path_Items_482C10(field_2C_camera_array[3], 0);
Map::Load_Path_Items_482C10(field_2C_camera_array[4], 0);
Map::Load_Path_Items_482C10(field_2C_camera_array[1], 0);
Map::Load_Path_Items_482C10(field_2C_camera_array[2], 0);
// Create the screen manager if it hasn't already been done (probably should have always been done by this point though?)
if (!pScreenManager_5BB5F4)
{
pScreenManager_5BB5F4 = ae_new<ScreenManager>();
if (pScreenManager_5BB5F4)
{
pScreenManager_5BB5F4->ctor_40E3E0(field_2C_camera_array[0]->field_C_pCamRes, &field_24_camera_offset);
}
}
sPath_dword_BB47C0->Loader_4DB800(field_D0_cam_x_idx, field_D2_cam_y_idx, LoadMode::Mode_0, TlvTypes::None_m1); // none = load all
if (prevPathId != field_2_current_path || prevLevelId != field_0_current_level)
{
if (sActiveHero_5C1B68)
{
if (field_2_current_path == sActiveHero_5C1B68->field_C0_path_number)
{
sActiveHero_5C1B68->VCheckCollisionLineStillValid_408A40(10);
}
}
}
Create_FG1s_480F10();
if (field_10_screen_change_effect == CameraSwapEffects::eEffect5_1_FMV)
{
Map::FMV_Camera_Change_482650(field_2C_camera_array[0]->field_C_pCamRes, this, field_A_level);
}
if (field_10_screen_change_effect == CameraSwapEffects::eEffect11_Unknown)
{
pScreenManager_5BB5F4->DecompressCameraToVRam_40EF60(reinterpret_cast<u16**>(field_2C_camera_array[0]->field_C_pCamRes));
pScreenManager_5BB5F4->InvalidateRect_40EC10(0, 0, 640, 240);
pScreenManager_5BB5F4->MoveImage_40EB70();
pScreenManager_5BB5F4->field_40_flags |= 0x10000;
}
if (prevLevelId != field_0_current_level)
{
pResourceManager_5C1BB0->LoadingLoop_465590(FALSE);
}
if (field_10_screen_change_effect != CameraSwapEffects::eEffect5_1_FMV && field_10_screen_change_effect != CameraSwapEffects::eEffect11_Unknown)
{
if (field_1E_door)
{
// TODO: Add template helpers
// Door transition
Path_Door* pDoorTlv = static_cast<Path_Door*>(sPath_dword_BB47C0->TLV_First_Of_Type_In_Camera_4DB6D0(TlvTypes::Door_5, 0));
while (pDoorTlv->field_18_door_number != sActiveHero_5C1B68->field_1A0_door_id)
{
pDoorTlv = static_cast<Path_Door*>(Path::TLV_Next_Of_Type_4DB720(pDoorTlv, TlvTypes::Door_5));
}
CreateScreenTransistionForTLV(pDoorTlv);
}
else
{
if (!field_20)
{
auto obj = ae_new<CameraSwapper>();
if (obj)
{
obj->ctor_4E5000(field_2C_camera_array[0]->field_C_pCamRes, field_10_screen_change_effect, 368 / 2, 240 / 2);
}
}
else
{
// TODO: Add template helpers
// Teleporter transition
Path_Teleporter* pTeleporterTlv = static_cast<Path_Teleporter*>(sPath_dword_BB47C0->TLV_First_Of_Type_In_Camera_4DB6D0(TlvTypes::Teleporter_88, 0));
Path_Teleporter_Data teleporterData = pTeleporterTlv->field_10_data;
while (teleporterData.field_10_id != sActiveHero_5C1B68->field_1A0_door_id)
{
pTeleporterTlv = static_cast<Path_Teleporter*>(Path::TLV_Next_Of_Type_4DB720(pTeleporterTlv, TlvTypes::Teleporter_88));
teleporterData = pTeleporterTlv->field_10_data;
}
CreateScreenTransistionForTLV(pTeleporterTlv);
}
}
}
bHideLoadingIcon_5C1BAA = 0;
loading_ticks_5C1BAC = 0;
field_8_force_load = 0;
if (sSoundChannelsMask_5C3120)
{
SND_Stop_Channels_Mask_4CA810(sSoundChannelsMask_5C3120);
sSoundChannelsMask_5C3120 = 0;
}
}
Camera* Map::GetCamera(CameraPos pos)
{
return field_2C_camera_array[static_cast<s32>(pos)];
}
void Map::CreateScreenTransistionForTLV(Path_TLV* pTlv)
{
auto obj = ae_new<CameraSwapper>();
if (obj)
{
// TODO: Refactor
const FP_Point* pCamPos2 = pScreenManager_5BB5F4->field_20_pCamPos;
const s16 doorYDiff = static_cast<s16>(pTlv->field_8_top_left.field_2_y - FP_GetExponent(pCamPos2->field_4_y));
FP camX = pCamPos2->field_0_x;
const s16 midX = (pTlv->field_8_top_left.field_0_x + pTlv->field_C_bottom_right.field_0_x) / 2;
const s16 rightPos = static_cast<s16>(midX - FP_GetExponent(camX));
const s16 xpos2 = rightPos;
obj->ctor_4E5000(field_2C_camera_array[0]->field_C_pCamRes, field_10_screen_change_effect, xpos2, doorYDiff);
}
}
void Map::Get_map_size_480640(PSX_Point* pPoint)
{
pPoint->field_0_x = field_D4_ptr->field_4_bTop;
pPoint->field_2_y = field_D4_ptr->field_6_bBottom;
}
void Map::GetCurrentCamCoords_480680(PSX_Point* pPoint)
{
pPoint->field_0_x = field_D0_cam_x_idx * field_D4_ptr->field_A_grid_width;
pPoint->field_2_y = field_D2_cam_y_idx * field_D4_ptr->field_C_grid_height;
}
void Map::Get_Abe_Spawn_Pos_4806D0(PSX_Point* pPoint)
{
pPoint->field_0_x = field_D4_ptr->field_1A_abe_start_xpos;
pPoint->field_2_y = field_D4_ptr->field_1C_abe_start_ypos;
}
s16 Map::GetOverlayId_480710()
{
// TODO: Probably need to redo field_C data as 1 bytes instead of a word
return Path_Get_Bly_Record_460F30(field_A_level, field_C_path)->field_C_overlay_id & 0xFF;
}
void Map::Create_FG1s_480F10()
{
pScreenManager_5BB5F4->UnsetDirtyBits_FG1_40ED70();
Camera* pCamera = field_2C_camera_array[0];
for (s32 i = 0; i < pCamera->field_0.Size(); i++)
{
u8** ppRes = pCamera->field_0.ItemAt(i);
if (!ppRes)
{
break;
}
if (*ppRes)
{
ResourceManager::Header* pHeader = ResourceManager::Get_Header_49C410(ppRes);
if (pHeader->field_8_type == ResourceManager::Resource_FG1)
{
FG1* pFG1 = ae_new<FG1>();
pFG1->ctor_499FC0(ppRes);
}
}
}
}
s16 Map::Get_Camera_World_Rect_481410(CameraPos camIdx, PSX_RECT* pRect)
{
if (camIdx < CameraPos::eCamCurrent_0 || camIdx > CameraPos::eCamRight_4)
{
return 0;
}
Camera* pCamera = field_2C_camera_array[static_cast<s32>(camIdx)];
if (!pCamera)
{
return 0;
}
if (!pRect)
{
return 1;
}
const s16 xpos = pCamera->field_14_xpos * field_D4_ptr->field_A_grid_width;
const s16 ypos = pCamera->field_16_ypos * field_D4_ptr->field_C_grid_height;
pRect->x = xpos;
pRect->y = ypos;
pRect->w = xpos + 368;
pRect->h = ypos + 240;
return 1;
}
s16 Map::Is_Point_In_Current_Camera_4810D0(s32 level, s32 path, FP xpos, FP ypos, s16 width)
{
const FP calculated_width = (width != 0) ? FP_FromInteger(6) : FP_FromInteger(0);
if (static_cast<LevelIds>(level) != field_0_current_level || path != field_2_current_path) // TODO: Remove when 100%
{
return FALSE;
}
PSX_RECT rect = {};
rect.x = FP_GetExponent(xpos - calculated_width);
rect.w = FP_GetExponent(calculated_width + xpos);
rect.y = FP_GetExponent(ypos);
rect.h = FP_GetExponent(ypos);
return Rect_Location_Relative_To_Active_Camera_480FE0(&rect) == CameraPos::eCamCurrent_0;
}
EXPORT CameraPos Map::Rect_Location_Relative_To_Active_Camera_480FE0(PSX_RECT* pRect)
{
if (Event_Get_422C00(kEventDeathReset))
{
return CameraPos::eCamNone_5;
}
const s32 camX = FP_GetExponent(field_24_camera_offset.field_0_x);
const s32 camY = FP_GetExponent(field_24_camera_offset.field_4_y);
if (pRect->x > (camX + 368))
{
return CameraPos::eCamRight_4;
}
if (pRect->y > (camY + 240))
{
return CameraPos::eCamBottom_2;
}
if (pRect->w >= camX)
{
if (pRect->h < camY)
{
return CameraPos::eCamTop_1;
}
else
{
return CameraPos::eCamCurrent_0;
}
}
return CameraPos::eCamLeft_3;
}
s16 Map::SetActiveCam_480D30(LevelIds level, s16 path, s16 cam, CameraSwapEffects screenChangeEffect, s16 fmvBaseId, s16 forceChange)
{
if (!forceChange && cam == field_4_current_camera && level == field_0_current_level && path == field_2_current_path)
{
return 0;
}
field_E_camera = cam;
field_12_fmv_base_id = fmvBaseId;
field_C_path = path;
field_A_level = level;
field_10_screen_change_effect = screenChangeEffect;
field_6_state = 2;
if (screenChangeEffect == CameraSwapEffects::eEffect5_1_FMV || screenChangeEffect == CameraSwapEffects::eEffect11_Unknown)
{
sMap_bDoPurpleLightEffect_5C311C = 1;
}
else
{
sMap_bDoPurpleLightEffect_5C311C = 0;
}
return 1;
}
BaseGameObject* CC Map::FMV_Camera_Change_482650(u8** ppBits, Map* pMap, LevelIds lvlId)
{
if (pMap->field_12_fmv_base_id > 10000u)
{
// Trippe FMV
FmvInfo* pFmvRec1 = Path_Get_FMV_Record_460F70(lvlId, pMap->field_12_fmv_base_id / 10000);
FmvInfo* pFmvRec2 = Path_Get_FMV_Record_460F70(lvlId, pMap->field_12_fmv_base_id / 100 % 100);
FmvInfo* pFmvRec3 = Path_Get_FMV_Record_460F70(lvlId, pMap->field_12_fmv_base_id % 100);
sLevelId_dword_5CA408 = static_cast<s32>(lvlId); // TODO: Strongly type this, but it hasn't got the same underlaying type as the enum grr..
u32 pos1 = 0;
u32 pos2 = 0;
u32 pos3 = 0;
Get_fmvs_sectors_494460(
pFmvRec1->field_0_pName,
pFmvRec2->field_0_pName,
pFmvRec3->field_0_pName,
&pos1,
&pos2,
&pos3);
auto pSwapper = ae_new<CameraSwapper>();
return pSwapper->ctor_4E4ED0(
ppBits,
pos1,
pFmvRec1->field_4_id,
pos2,
pFmvRec2->field_4_id,
pos3,
pFmvRec3->field_4_id,
pFmvRec1->field_6_flags & 1,
pFmvRec1->field_8_flags,
pFmvRec1->field_A_volume,
pFmvRec2->field_6_flags & 1,
pFmvRec2->field_8_flags,
pFmvRec2->field_A_volume,
pFmvRec3->field_6_flags & 1,
pFmvRec3->field_8_flags,
pFmvRec3->field_A_volume);
}
else if (pMap->field_12_fmv_base_id >= 100u)
{
// Double FMV
FmvInfo* pFmvRec1 = Path_Get_FMV_Record_460F70(lvlId, pMap->field_12_fmv_base_id / 100);
FmvInfo* pFmvRec2 = Path_Get_FMV_Record_460F70(lvlId, pMap->field_12_fmv_base_id % 100);
u32 cdPos1 = 0;
u32 cdPos2 = 0;
Get_fmvs_sectors_494460(pFmvRec1->field_0_pName, pFmvRec2->field_0_pName, 0, &cdPos1, &cdPos2, 0);
sLevelId_dword_5CA408 = static_cast<s32>(lvlId); // HACK
auto pSwapper = ae_new<CameraSwapper>();
return pSwapper->ctor_4E4DC0(
ppBits,
cdPos1,
pFmvRec1->field_4_id,
cdPos2,
pFmvRec2->field_4_id,
pFmvRec1->field_6_flags & 1,
pFmvRec1->field_8_flags,
pFmvRec1->field_A_volume,
pFmvRec2->field_6_flags & 1,
pFmvRec2->field_8_flags,
pFmvRec2->field_A_volume);
}
else // < 100
{
// Single FMV
FmvInfo* pFmvRec1 = Path_Get_FMV_Record_460F70(lvlId, pMap->field_12_fmv_base_id);
u32 cdPos = 0;
Get_fmvs_sectors_494460(pFmvRec1->field_0_pName, 0, 0, &cdPos, 0, 0);
sLevelId_dword_5CA408 = static_cast<s32>(lvlId); // HACK
auto pSwapper = ae_new<CameraSwapper>();
return pSwapper->ctor_4E4CA0(
ppBits,
cdPos,
pFmvRec1->field_4_id,
pFmvRec1->field_6_flags & 1,
pFmvRec1->field_8_flags,
pFmvRec1->field_A_volume);
}
}
Camera* Map::Create_Camera_4829E0(s16 xpos, s16 ypos, s32 /*a4*/)
{
// Check min bound
if (xpos < 0 || ypos < 0)
{
return nullptr;
}
// Check max bounds
if (xpos >= sPath_dword_BB47C0->field_6_cams_on_x || ypos >= sPath_dword_BB47C0->field_8_cams_on_y)
{
return nullptr;
}
// Return existing camera if we already have one
for (s32 i = 0; i < ALIVE_COUNTOF(field_40_stru_5); i++)
{
if (field_40_stru_5[i]
&& field_40_stru_5[i]->field_1A_level == field_0_current_level
&& field_40_stru_5[i]->field_18_path == field_2_current_path
&& field_40_stru_5[i]->field_14_xpos == xpos
&& field_40_stru_5[i]->field_16_ypos == ypos)
{
Camera* pTemp = field_40_stru_5[i];
field_40_stru_5[i] = nullptr;
return pTemp;
}
}
// Get a pointer to the camera name from the Path resource
const u8* pPathData = *field_54_path_res_array.field_0_pPathRecs[field_2_current_path];
auto pCamName = reinterpret_cast<const CameraName*>(&pPathData[(xpos + (ypos * sPath_dword_BB47C0->field_6_cams_on_x)) * sizeof(CameraName)]);
// Empty/blank camera in the map array
if (!pCamName->name[0])
{
return nullptr;
}
Camera* newCamera = ae_new<Camera>();
newCamera->ctor_480DD0();
// Copy in the camera name from the Path resource and append .CAM
memset(newCamera->field_1E_cam_name, 0, sizeof(newCamera->field_1E_cam_name));
strncpy(newCamera->field_1E_cam_name, pCamName->name, ALIVE_COUNTOF(CameraName::name));
strcat(newCamera->field_1E_cam_name, ".CAM");
newCamera->field_14_xpos = xpos;
newCamera->field_16_ypos = ypos;
newCamera->field_30_flags &= -1;
newCamera->field_1A_level = field_0_current_level;
newCamera->field_18_path = field_2_current_path;
// Calculate hash/resource ID of the camera
newCamera->field_10_camera_resource_id = 1 * (pCamName->name[7] - '0') + 10 * (pCamName->name[6] - '0') + 100 * (pCamName->name[4] - '0') + 1000 * (pCamName->name[3] - '0');
// Convert the 2 digit camera number string to an integer
newCamera->field_1C_camera_number = 1 * (pCamName->name[7] - '0') + 10 * (pCamName->name[6] - '0');
return newCamera;
}
void CCSTD Map::Load_Path_Items_482C10(Camera* pCamera, s16 loadMode)
{
if (!pCamera)
{
return;
}
// Is camera resource loaded check
if (!(pCamera->field_30_flags & 1))
{
if (loadMode == 0)
{
// Async camera load
ResourceManager::LoadResourceFile_49C130(pCamera->field_1E_cam_name, Camera::On_Loaded_480ED0, pCamera, pCamera);
sCameraBeingLoaded_5C3118 = pCamera;
sPath_dword_BB47C0->Loader_4DB800(pCamera->field_14_xpos, pCamera->field_16_ypos, LoadMode::Mode_1, TlvTypes::None_m1); // none = load all
}
else
{
// Blocking camera load
ResourceManager::LoadResourceFile_49C170(pCamera->field_1E_cam_name, pCamera);
pCamera->field_30_flags |= 1;
pCamera->field_C_pCamRes = ResourceManager::GetLoadedResource_49C2A0(ResourceManager::Resource_Bits, pCamera->field_10_camera_resource_id, 1, 0);
sCameraBeingLoaded_5C3118 = pCamera;
sPath_dword_BB47C0->Loader_4DB800(pCamera->field_14_xpos, pCamera->field_16_ypos, LoadMode::Mode_2, TlvTypes::None_m1); // none = load all
}
sCameraBeingLoaded_5C3118 = nullptr;
}
}
void CC Map::LoadResource_4DBE00(const char_type* pFileName, s32 type, s32 resourceId, LoadMode loadMode, s16 bDontLoad)
{
if (!bDontLoad)
{
pResourceManager_5C1BB0->LoadResource_464EE0(pFileName, type, resourceId, sCameraBeingLoaded_5C3118, sCameraBeingLoaded_5C3118, 0, 1);
if (loadMode == LoadMode::Mode_2)
{
pResourceManager_5C1BB0->LoadingLoop_465590(0);
}
}
}
void CC Map::LoadResourcesFromList_4DBE70(const char_type* pFileName, ResourceManager::ResourcesToLoadList* pList, LoadMode loadMode, s16 bDontLoad)
{
if (!bDontLoad)
{
pResourceManager_5C1BB0->LoadResourcesFromList_465150(pFileName, pList, sCameraBeingLoaded_5C3118, sCameraBeingLoaded_5C3118, 0, 1);
if (loadMode == LoadMode::Mode_2)
{
pResourceManager_5C1BB0->LoadingLoop_465590(0);
}
}
}
s16 Map::SetActiveCameraDelayed_4814A0(MapDirections direction, BaseAliveGameObject* pObj, s16 swapEffect)
{
Path_Change* pPathChangeTLV = nullptr;
CameraSwapEffects convertedSwapEffect = CameraSwapEffects::eEffect0_InstantChange;
if (pObj)
{
pPathChangeTLV = reinterpret_cast<Path_Change*>(sPath_dword_BB47C0->TLV_Get_At_4DB4B0(
FP_GetExponent(pObj->field_B8_xpos),
FP_GetExponent(pObj->field_BC_ypos),
FP_GetExponent(pObj->field_B8_xpos),
FP_GetExponent(pObj->field_BC_ypos),
TlvTypes::PathTransition_1));
}
if (pObj && pPathChangeTLV)
{
field_A_level = pPathChangeTLV->field_10_level;
field_C_path = pPathChangeTLV->field_12_path;
field_E_camera = pPathChangeTLV->field_14_camera;
if (swapEffect < 0)
{
// Map the TLV/editor value of screen change to the internal screen change
convertedSwapEffect = kPathChangeEffectToInternalScreenChangeEffect_55D55C[pPathChangeTLV->field_18_wipe];
}
else
{
// If not negative then its an actual swap effect
convertedSwapEffect = static_cast<CameraSwapEffects>(swapEffect);
}
}
else
{
switch (direction)
{
case MapDirections::eMapLeft_0:
if (!GetCamera(CameraPos::eCamLeft_3))
{
return 0;
}
break;
case MapDirections::eMapRight_1:
if (!GetCamera(CameraPos::eCamRight_4))
{
return 0;
}
break;
case MapDirections::eMapBottom_3:
if (!GetCamera(CameraPos::eCamBottom_2))
{
return 0;
}
break;
case MapDirections::eMapTop_2:
if (!GetCamera(CameraPos::eCamTop_1))
{
return 0;
}
break;
}
field_A_level = field_0_current_level;
field_C_path = field_2_current_path;
convertedSwapEffect = static_cast<CameraSwapEffects>(swapEffect); // TODO: Correct ??
}
field_14_direction = direction;
field_18_pAliveObj = pObj;
field_1C = convertedSwapEffect;
field_6_state = 1;
sMap_bDoPurpleLightEffect_5C311C = 0;
if (convertedSwapEffect == CameraSwapEffects::eEffect5_1_FMV || convertedSwapEffect == CameraSwapEffects::eEffect11_Unknown)
{
sMap_bDoPurpleLightEffect_5C311C = 1;
}
return 1;
}
ALIVE_VAR(1, 0x5C3030, Map, gMap_5C3030, {});
| 33.591779 | 228 | 0.624182 | Leonard2 |
cde3ba9501e1e3c7eb728ae15729956502bb1014 | 2,873 | hpp | C++ | src/Renderer.hpp | ser94mor/lidar-obstacle-detection | e0271e6cd7c925fbd1804ecbe24eb0b7706c1f64 | [
"MIT"
] | 23 | 2019-08-05T08:53:42.000Z | 2022-03-25T07:14:29.000Z | src/Renderer.hpp | ser94mor/lidar-obstacle-detection | e0271e6cd7c925fbd1804ecbe24eb0b7706c1f64 | [
"MIT"
] | 8 | 2019-06-20T09:23:31.000Z | 2020-11-25T09:14:06.000Z | src/Renderer.hpp | ser94mor/lidar-obstacle-detection | e0271e6cd7c925fbd1804ecbe24eb0b7706c1f64 | [
"MIT"
] | 7 | 2019-08-07T18:38:00.000Z | 2021-06-23T21:43:04.000Z | /**
* Copyright (C) 2019 Sergey Morozov <sergey@morozov.ch>
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
* THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//
// The original author of the rendering code is Aaron Brown (https://github.com/awbrown90).
// His code has been slightly modified to make it more structured.
//
#ifndef LIDAR_OBSTACLE_DETECTION_RENDERER_HPP
#define LIDAR_OBSTACLE_DETECTION_RENDERER_HPP
#include "Box.hpp"
#include <pcl/visualization/pcl_visualizer.h>
#include <iostream>
#include <vector>
#include <string>
namespace ser94mor::lidar_obstacle_detection
{
struct Color
{
float r, g, b;
Color(float setR, float setG, float setB)
: r(setR), g(setG), b(setB)
{}
};
enum class CameraAngle
{
XY, TopDown, Side, FPS
};
class Renderer
{
private:
pcl::visualization::PCLVisualizer::Ptr viewer_;
unsigned long long rays_counter_;
public:
Renderer();
void RenderHighway();
void RenderRays(const Eigen::Vector3f& origin, const pcl::PointCloud<pcl::PointXYZ>::Ptr& cloud);
void ClearRays();
void ClearViewer();
void RenderPointCloud(const pcl::PointCloud<pcl::PointXYZ>::Ptr& cloud,
const std::string& name,
const Color& color = Color(1,1,1));
void RenderPointCloud(const pcl::PointCloud<pcl::PointXYZI>::Ptr& cloud,
const std::string& name,
const Color& color = Color(-1,-1,-1));
void RenderBox(const Box& box, int id, const Color& color = Color(1,0,0), float opacity = 1.0);
void RenderBox(const BoxQ& box, int id, const Color& color = Color(1,0,0), float opacity = 1.0);
void InitCamera(CameraAngle view_angle);
bool WasViewerStopped() const;
void SpinViewerOnce() const;
};
}
#endif //LIDAR_OBSTACLE_DETECTION_RENDERER_HPP
| 29.316327 | 101 | 0.69196 | ser94mor |
cde562da0a39fd9620c9bc2b6048b46d2398b1a1 | 3,176 | cpp | C++ | pixmap_test.cpp | ndaniyarov/pixmap-ops | d893a7ef6621ddfacab68c58ec542502ee522e3a | [
"MIT"
] | null | null | null | pixmap_test.cpp | ndaniyarov/pixmap-ops | d893a7ef6621ddfacab68c58ec542502ee522e3a | [
"MIT"
] | null | null | null | pixmap_test.cpp | ndaniyarov/pixmap-ops | d893a7ef6621ddfacab68c58ec542502ee522e3a | [
"MIT"
] | null | null | null | #include <iostream>
#include "ppm_image.h"
using namespace std;
using namespace agl;
int main(int argc, char** argv)
{
ppm_image image;
image.load("../images/feep.ppm");
image.save("feep-test-save.ppm"); // should match original
// should print 4 4
cout << "loaded feep: " << image.width() << " " << image.height() << endl;
// test: copy constructor
ppm_image copy = image;
copy.save("feep-test-copy.ppm"); // should match original and load into gimp
// test: assignment operator
copy = image;
image.save("feep-test-assignment.ppm"); // should match original and load into gimp
// should print r,g,b
ppm_pixel pixel = image.get(1, 1);
cout << (int) pixel.r << " " << (int) pixel.g << " " << (int) pixel.b << endl;
// test: setting a color
pixel.r = 255;
image.set(1, 1, pixel);
image.save("feep-test-newcolor.ppm");
// test a non-trivial image
image.load("../images/earth-ascii.ppm"); // a real image
// should print 400 400
cout << "loaded earth: " << image.width() << " " << image.height() << endl;
// resize
ppm_image resize = image.resize(200,300);
resize.save("earth-200-300.ppm");
// grayscale
ppm_image grayscale = image.grayscale();
grayscale.save("earth-grayscale.ppm");
// flip horizontal
ppm_image flip = image.flip_horizontal();
flip.save("earth-flip.ppm");
// sub image
ppm_image sub = image.subimage(200, 200, 100, 100);
sub.save("earth-subimage.ppm");
// gamma correction
ppm_image gamma = image.gammaCorrect(0.6f);
gamma.save("earth-gamma-0.6.ppm");
gamma = image.gammaCorrect(2.2f);
gamma.save("earth-gamma-2.2.ppm");
// alpha blend
ppm_image soup;
soup.load("../images/soup-ascii.ppm");
//soup.save("soup.ppm");
int x = (int) (0.5f * (image.width() - soup.width()));
int y = (int) (0.5f * (image.height() - soup.height()));
//cout << image.width() << " " << image.height();
//cout << soup.width() << " " << soup.height();
image.save("new.ppm");
//139 108 121 183
ppm_image background = image.subimage(y,x,soup.width(), soup.height());
background.save("background-test.ppm");
ppm_image blend = background.alpha_blend(soup, 0.5f);
//blend.save("blenddd.ppm");
image.replace(blend, x, y);
image.save("earth-blend-0.5.ppm");
ppm_image rey;
rey.load("../images/earth-ascii.ppm");
ppm_image kylo;
kylo.load("../images/soup-ascii.ppm");
ppm_image invertedRey = rey.invert();
invertedRey.save("invert.ppm");
ppm_image swirledRey = rey.swirl();
swirledRey.save("swirl.ppm");
rey.load("../images/earth-ascii.ppm");
kylo.load("../images/soup-ascii.ppm");
ppm_image differenceReyKylo = rey.difference(kylo);
differenceReyKylo.save("difference.ppm");
ppm_image sumReyKylo = rey.sum(kylo);
sumReyKylo.save("sum.ppm");
ppm_pixel border;
border.r = 0;
border.g = 255;
border.b = 0;
kylo.border(border);
kylo.save("border.ppm");
rey.load("../images/earth-ascii.ppm");
kylo.load("../images/soup-ascii.ppm");
ppm_image lightestKyloRey = kylo.lightest(rey);
lightestKyloRey.save("lightest.ppm");
}
| 28.612613 | 86 | 0.627834 | ndaniyarov |
cde7e4b7fa6f62d6b3bff228cf0c3bc8964ca1fd | 6,534 | cpp | C++ | lesson03/src/helper_functions.cpp | MikluhaMaklay/CPPExercises2021 | 5bd9f103eeaa09bd2ffda2130ae143f269d9ef7f | [
"MIT"
] | null | null | null | lesson03/src/helper_functions.cpp | MikluhaMaklay/CPPExercises2021 | 5bd9f103eeaa09bd2ffda2130ae143f269d9ef7f | [
"MIT"
] | 2 | 2021-10-20T08:40:11.000Z | 2022-02-16T08:47:37.000Z | lesson03/src/helper_functions.cpp | MikluhaMaklay/CPPExercises2021 | 5bd9f103eeaa09bd2ffda2130ae143f269d9ef7f | [
"MIT"
] | null | null | null | #include "helper_functions.h"
#include <libutils/rasserts.h>
#include <iostream>
cv::Mat makeAllBlackPixelsBlue(cv::Mat image) {
// ниже приведен пример как узнать цвет отдельного пикселя - состоящий из тройки чисел BGR (Blue Green Red)
// чем больше значение одного из трех чисел - тем насыщеннее его оттенок
// всего их диапазон значений - от 0 до 255 включительно
// т.е. один байт, поэтому мы используем ниже тип unsigned char - целое однобайтовое неотрицательное число
for (int rows = 0; rows < image.rows; rows++){
for (int cols = 0; cols < image.cols; cols++){
cv::Vec3b color = image.at<cv::Vec3b>(rows, cols); // взяли и узнали что за цвет в пикселе в 14-ом ряду (т.к. индексация с нуля) и 6-ой колонке
// unsigned char blue = color[0]; // если это число равно 255 - в пикселе много синего, если равно 0 - в пикселе нет синего
// unsigned char green = color[1];
// unsigned char red = color[2];
if (color == cv::Vec3b(0, 0, 0)){
image.at<cv::Vec3b>(rows, cols) = cv::Vec3b(255, 0, 0);
}
}
}
// как получить белый цвет? как получить черный цвет? как получить желтый цвет?
// поэкспериментируйте! например можете всю картинку заполнить каким-то одним цветом
// пример как заменить цвет по тем же координатам
// red = 255;
// запустите эту версию функции и посмотрите на получившуюся картинку - lesson03/resultsData/01_blue_unicorn.jpg
// какой пиксель изменился? почему он не чисто красный?
return image;
}
cv::Mat invertImageColors(cv::Mat image) {
// т.е. пусть ночь станет днем, а сумрак рассеется
// иначе говоря замените каждое значение яркости x на (255-x) (т.к находится в диапазоне от 0 до 255)
for (int rows = 0; rows < image.rows; rows++){
for (int cols = 0; cols < image.cols; cols++){
cv::Vec3b color = image.at<cv::Vec3b>(rows, cols); // взяли и узнали что за цвет в пикселе в 14-ом ряду (т.к. индексация с нуля) и 6-ой колонке
unsigned char blue = color[0]; // если это число равно 255 - в пикселе много синего, если равно 0 - в пикселе нет синего
unsigned char green = color[1];
unsigned char red = color[2];
image.at<cv::Vec3b>(rows, cols) = cv::Vec3b(255 - blue, 255 - green, 255 - red);
}
}
return image;
}
cv::Mat addBackgroundInsteadOfBlackPixels(cv::Mat object, cv::Mat background) {
// т.е. что-то вроде накладного фона получится
// гарантируется что размеры картинок совпадают - проверьте это через rassert, вот например сверка ширины:
rassert(object.cols == background.cols, 341241251251351)
rassert(object.rows == background.rows, 274825321762864)
for (int rows = 0; rows < object.rows; rows++){
for (int cols = 0; cols < object.cols; cols++){
cv::Vec3b color = object.at<cv::Vec3b>(rows, cols); // взяли и узнали что за цвет в пикселе в 14-ом ряду (т.к. индексация с нуля) и 6-ой колонке
if (color == cv::Vec3b(0, 0, 0)){
object.at<cv::Vec3b>(rows, cols) = background.at<cv::Vec3b>(rows, cols);
}
}
}
return object;
}
cv::Mat addBackgroundInsteadOfBlackPixelsLargeBackground(cv::Mat object, cv::Mat largeBackground) {
// теперь вам гарантируется что largeBackground гораздо больше - добавьте проверок этого инварианта (rassert-ов)
rassert(object.cols < largeBackground.cols, 397928346)
rassert(object.rows < largeBackground.rows, 32473984619)
for (int rows = 0; rows < object.rows; rows++){
for (int cols = 0; cols < object.cols; cols++){
cv::Vec3b color = object.at<cv::Vec3b>(rows, cols); // взяли и узнали что за цвет в пикселе в 14-ом ряду (т.к. индексация с нуля) и 6-ой колонке
if (color != cv::Vec3b(0, 0, 0)){
largeBackground.at<cv::Vec3b>(largeBackground.rows / 2 - object.rows / 2 + rows, largeBackground.cols / 2 - object.cols / 2 + cols) = object.at<cv::Vec3b>(rows, cols);
}
}
}
return largeBackground;
}
cv::Mat drawManyTimes(cv::Mat object, cv::Mat background, int n) {
n = rand() % 100;
for (int i = 0; i < n; i++){
int x = rand() % (background.rows - object.rows);
int y = rand() % (background.cols - object.cols);
for (int rows = 0; rows < object.rows; rows++){
for (int cols = 0; cols < object.cols; cols++){
cv::Vec3b color = object.at<cv::Vec3b>(rows, cols); // взяли и узнали что за цвет в пикселе в 14-ом ряду (т.к. индексация с нуля) и 6-ой колонке
if (color != cv::Vec3b(0, 0, 0)){
background.at<cv::Vec3b>(x + rows, y + cols) = object.at<cv::Vec3b>(rows, cols);
}
}
}
}
return background;
}
cv::Mat unicornUpscale(cv::Mat object, cv::Mat background){
cv::Mat newImage(591, 591, CV_8UC3, cv::Scalar(256,56,0));
for (int rows = 0; rows < newImage.rows; rows++){
for (int cols = 0; cols < newImage.cols; cols++){
int y = rows*1.0 / newImage.rows * object.rows;
int x = cols*1.0 / newImage.cols * object.cols;
newImage.at<cv::Vec3b>(rows, cols) = object.at<cv::Vec3b>(y, x);
cv::Vec3b color = newImage.at<cv::Vec3b>(rows, cols); // взяли и узнали что за цвет в пикселе в 14-ом ряду (т.к. индексация с нуля) и 6-ой колонке
if (color != cv::Vec3b(0, 0, 0)){
background.at<cv::Vec3b>(rows, background.cols / 2 - newImage.cols / 2 + cols) = newImage.at<cv::Vec3b>(rows, cols);
}
}
}
return background;
}
cv::Mat epilepsy(cv::Mat lastImage){
cv::Mat image(591, 591, CV_8UC3, cv::Scalar(256,56,0));
for (int rows = 0; rows < image.rows; rows++){
for (int cols = 0; cols < image.cols; cols++){
int y = rows*1.0 / image.rows * lastImage.rows;
int x = cols*1.0 / image.cols * lastImage.cols;
image.at<cv::Vec3b>(rows, cols) = lastImage.at<cv::Vec3b>(y, x);
cv::Vec3b color = image.at<cv::Vec3b>(rows, cols); // взяли и узнали что за цвет в пикселе в 14-ом ряду (т.к. индексация с нуля) и 6-ой колонке
int R = rand() % 256;
int G = rand() % 256;
int B = rand() % 256;
if (color == cv::Vec3b(0, 0, 0)){
image.at<cv::Vec3b>(rows, cols) = cv::Vec3b(B, G, R);
}
}
}
return image;
}
| 39.125749 | 183 | 0.595654 | MikluhaMaklay |
cde8cf07bd6e5ae7f28619cef7251969b4f2c02f | 1,251 | cpp | C++ | Features/Integral_images.cpp | QuMIke/PracticePCL | efe947607516d28c176721c9930be049b50ad18a | [
"MIT"
] | null | null | null | Features/Integral_images.cpp | QuMIke/PracticePCL | efe947607516d28c176721c9930be049b50ad18a | [
"MIT"
] | null | null | null | Features/Integral_images.cpp | QuMIke/PracticePCL | efe947607516d28c176721c9930be049b50ad18a | [
"MIT"
] | null | null | null | /*
In this tutorial we will learn how to compute normals for an organized point cloud using integral images.
*/
#include "stdafx.h"
#include <iostream>
#include <vtkAutoInit.h>
#include <pcl/point_types.h>
#include <pcl/features/integral_image_normal.h>
#include <pcl/visualization/cloud_viewer.h>
#include "KinnectGrabber.h"
int main()
{
pcl::io::OpenNI2Grabber grabber;
KinnectGrabber<pcl::PointXYZRGBA> v(grabber);
v.run();
pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr cloud = nullptr;
cloud = v.getLatestCloud();
if (cloud == nullptr)
{
std::cout << "Get cloud failed!" << std::endl;
}
else
{
// estimate normals
pcl::PointCloud<pcl::Normal>::Ptr normals(new pcl::PointCloud<pcl::Normal>);
pcl::IntegralImageNormalEstimation<pcl::PointXYZRGBA, pcl::Normal> ne;
ne.setNormalEstimationMethod(ne.AVERAGE_3D_GRADIENT);
ne.setMaxDepthChangeFactor(0.02f);
ne.setNormalSmoothingSize(10.0f);
ne.setInputCloud(cloud);
ne.compute(*normals);
// visualize normals
pcl::visualization::PCLVisualizer viewer("PCL Viewer");
viewer.setBackgroundColor(0.0, 0.0, 0.5);
viewer.addPointCloudNormals<pcl::PointXYZRGBA, pcl::Normal>(cloud, normals);
while (!viewer.wasStopped())
{
viewer.spinOnce();
}
}
return 0;
}
| 25.02 | 105 | 0.725819 | QuMIke |
cde9bfc27e35818bd07632782b49ec82d5e94d67 | 3,727 | cpp | C++ | PAT_A/A1016|Phone Bills|e.g.cpp | FunamiYui/PAT_Code_Akari | 52e06689b6bf8177c43ab9256719258c47e80b25 | [
"MIT"
] | null | null | null | PAT_A/A1016|Phone Bills|e.g.cpp | FunamiYui/PAT_Code_Akari | 52e06689b6bf8177c43ab9256719258c47e80b25 | [
"MIT"
] | null | null | null | PAT_A/A1016|Phone Bills|e.g.cpp | FunamiYui/PAT_Code_Akari | 52e06689b6bf8177c43ab9256719258c47e80b25 | [
"MIT"
] | null | null | null | //example
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 1010;
int toll[25]; //资费
struct Record {
char name[25]; //姓名
int month, dd, hh, mm; //月份、日、时、分
bool status; //status == true表示该记录为on-line, 否则为off-line
} rec[maxn], temp;
bool cmp(Record a, Record b) {
int s = strcmp(a.name, b.name); //需要采取这种写法
if(s != 0) return s < 0; //优先按姓名字典序从小到大排序
//if(a.name != b.name) //这样写是错误的。估计是因为直接拿字符数组名作比较,是在比较字符数组首地址,而不是比较字符串内容
//return strcmp(a.name, b.name) < 0;
else if(a.month != b.month)
return a.month < b.month; //按月份从小到大排序
else if(a.dd != b.dd)
return a.dd < b.dd; //按日期从小到大排序
else if(a.hh != b.hh)
return a.hh < b.hh; //按小时从小到大排序
else
return a.mm < b.mm; //按分钟从小到大排序
}
void get_ans(int on, int off, int &time, int &money) { //on(on-line)和off(off-line)为配对的两条记录
temp = rec[on]; //用temp作临时变量是因为对数组作改动会直接改变数组内容,而当前我希望的是记录保持所输入的数据不改变,所以引入临时变量
while(temp.dd < rec[off].dd || temp.hh < rec[off].hh || temp.mm < rec[off].mm) {
time++; //该次记录总时间加1min
money += toll[temp.hh]; //话费增加tool[temp.hh]
temp.mm++; //当前时间加1min
if(temp.mm >= 60) { //当前分钟数到达60
temp.mm = 0; //进入下一个小时
temp.hh++;
}
if(temp.hh >= 24) { //当前小时数到达24
temp.hh = 0; //进入下一天
temp.dd++;
}
}
}
int main() {
for(int i = 0; i < 24; i++) {
scanf("%d", &toll[i]); //资费
}
int n;
scanf("%d", &n); //记录数
char line[10]; //临时存放on-line或off-line的输入
for(int i = 0; i < n; i++) {
scanf("%s", rec[i].name);
scanf("%d:%d:%d:%d ", &rec[i].month, &rec[i].dd, &rec[i].hh, &rec[i].mm);
scanf("%s", line);
if(strcmp(line, "on-line") == 0) {
rec[i].status = true; //如果是on-line,则令status为true
}
else {
rec[i].status = false; //如果是off-line,则令status为false
}
}
sort(rec, rec + n, cmp);
int on = 0, off, next; //on(on-line)和off(off-line)为配对的两条记录,next为下一位用户
while(on < n) { //每次循环处理 单个用户 的 所有 记录
int needprint = 0; //needprint表示该用户是否需要输出
next = on; //从当前位置开始寻找下一个用户,next可以理解为数组指针? 这个next变量很重要!
while(next < n && strcmp(rec[next].name, rec[on].name) == 0) { //先判断是否有有效记录,再进一步去看具体有效记录是怎么样的
if(needprint == 0 && rec[next].status == true) {
needprint = 1; //找到on,置needprint为1
}
else if(needprint == 1 && rec[next].status == false) {
needprint = 2; //在on之后如果找到off,置needprint为2
}
next++; //next自增,直到找到不同名字,即下一个用户
}
if(needprint < 2) { //没有找到配对的on-off
on = next;
continue;
}
int AllMoney = 0; //总共花费的钱
printf("%s %02d\n", rec[on].name, rec[on].month);
while(on < next) { //寻找该用户的 所有 配对
while(on < next - 1 && !(rec[on].status == true && rec[on + 1].status == false)) {
on++; //直到找到连续的on-line和off-line
}
off = on + 1; //off必须是on的下一个
if(off == next) { //已经输出完毕所有配对的on-line和off-line
on = next;
break;
}
printf("%02d:%02d:%02d ", rec[on].dd, rec[on].hh, rec[on].mm);
printf("%02d:%02d:%02d ", rec[off].dd, rec[off].hh, rec[off].mm);
int time = 0, money = 0; //时间、单次记录花费的钱
get_ans(on, off, time, money); //计算on到off内的时间和金钱
AllMoney += money; //总金额加上该次记录的钱
printf("%d $%.2f\n", time, money / 100.0); //金钱的单位要从cent转化为dollar
on = off + 1; //完成一个配对,从off + 1开始找下一对
}
printf("Total amount: $%.2f\n", AllMoney / 100.0);
}
return 0;
}
| 35.160377 | 104 | 0.513818 | FunamiYui |
cdea90f6d4d3824324c0b38f0a84cc8cfd0e0e3a | 4,526 | cpp | C++ | common/metrics.cpp | plsmaop/SLOG | bcf5775fdb756d73e56265835020517f6f7b79a7 | [
"MIT"
] | 26 | 2020-01-31T18:12:44.000Z | 2022-02-07T01:46:07.000Z | common/metrics.cpp | plsmaop/SLOG | bcf5775fdb756d73e56265835020517f6f7b79a7 | [
"MIT"
] | 17 | 2020-01-30T20:40:35.000Z | 2021-12-22T18:43:21.000Z | common/metrics.cpp | plsmaop/SLOG | bcf5775fdb756d73e56265835020517f6f7b79a7 | [
"MIT"
] | 6 | 2019-12-24T15:30:45.000Z | 2021-07-06T19:47:30.000Z | #include "metrics.h"
#include <algorithm>
#include <list>
#include <random>
#include "common/csv_writer.h"
#include "common/proto_utils.h"
#include "glog/logging.h"
#include "proto/internal.pb.h"
#include "version.h"
namespace slog {
using time_point_t = std::chrono::system_clock::time_point;
class TransactionEventMetrics {
public:
TransactionEventMetrics(const sample_mask_t& sample_mask, uint32_t local_replica, uint32_t local_partition)
: sample_mask_(sample_mask),
local_replica_(local_replica),
local_partition_(local_partition),
sample_count_(TransactionEvent_descriptor()->value_count(), 0) {}
time_point_t RecordEvent(TransactionEvent event) {
auto now = std::chrono::system_clock::now();
auto sample_index = static_cast<size_t>(event);
DCHECK_LT(sample_count_[sample_index], sample_mask_.size());
if (sample_mask_[sample_count_[sample_index]++]) {
txn_events_.push_back({.event = event,
.time = now.time_since_epoch().count(),
.partition = local_partition_,
.replica = local_replica_});
}
return now;
}
struct Data {
TransactionEvent event;
int64_t time;
uint32_t partition;
uint32_t replica;
};
std::list<Data>& data() { return txn_events_; }
private:
sample_mask_t sample_mask_;
uint32_t local_replica_;
uint32_t local_partition_;
std::vector<uint8_t> sample_count_;
std::list<Data> txn_events_;
};
/**
* MetricsRepository
*/
MetricsRepository::MetricsRepository(const ConfigurationPtr& config, const sample_mask_t& sample_mask)
: config_(config),
sample_mask_(sample_mask),
txn_event_metrics_(new TransactionEventMetrics(sample_mask, config->local_replica(), config->local_partition())) {
}
time_point_t MetricsRepository::RecordTxnEvent(TransactionEvent event) {
std::lock_guard<SpinLatch> guard(latch_);
return txn_event_metrics_->RecordEvent(event);
}
std::unique_ptr<TransactionEventMetrics> MetricsRepository::Reset() {
auto new_txn_event_metrics =
std::make_unique<TransactionEventMetrics>(sample_mask_, config_->local_replica(), config_->local_partition());
std::lock_guard<SpinLatch> guard(latch_);
txn_event_metrics_.swap(new_txn_event_metrics);
return new_txn_event_metrics;
}
thread_local std::shared_ptr<MetricsRepository> per_thread_metrics_repo;
/**
* MetricsRepositoryManager
*/
MetricsRepositoryManager::MetricsRepositoryManager(const std::string& config_name, const ConfigurationPtr& config)
: config_name_(config_name), config_(config) {
sample_mask_.fill(false);
for (uint32_t i = 0; i < config_->sample_rate() * kSampleMaskSize / 100; i++) {
sample_mask_[i] = true;
}
auto rd = std::random_device{};
auto rng = std::default_random_engine{rd()};
std::shuffle(sample_mask_.begin(), sample_mask_.end(), rng);
}
void MetricsRepositoryManager::RegisterCurrentThread() {
std::lock_guard<std::mutex> guard(mut_);
const auto thread_id = std::this_thread::get_id();
auto ins = metrics_repos_.try_emplace(thread_id, config_, new MetricsRepository(config_, sample_mask_));
per_thread_metrics_repo = ins.first->second;
}
void MetricsRepositoryManager::AggregateAndFlushToDisk(const std::string& dir) {
try {
CSVWriter metadata_csv(dir + "/metadata.csv", {"version", "config_name"});
metadata_csv << SLOG_VERSION << config_name_;
CSVWriter txn_events_csv(dir + "/events.csv", {"event", "time", "partition", "replica"});
std::list<TransactionEventMetrics::Data> txn_events_data;
std::lock_guard<std::mutex> guard(mut_);
for (auto& kv : metrics_repos_) {
auto metrics = kv.second->Reset();
txn_events_data.splice(txn_events_data.end(), metrics->data());
}
for (const auto& data : txn_events_data) {
txn_events_csv << ENUM_NAME(data.event, TransactionEvent) << data.time << data.partition << data.replica
<< csvendl;
}
LOG(INFO) << "Metrics written to: \"" << dir << "/\"";
} catch (std::runtime_error& e) {
LOG(ERROR) << e.what();
}
}
/**
* Initialization
*/
uint32_t gLocalMachineId = 0;
uint64_t gEnabledEvents = 0;
void InitializeRecording(const ConfigurationPtr& config) {
gLocalMachineId = config->local_machine_id();
auto events = config->enabled_events();
for (auto e : events) {
if (e == TransactionEvent::ALL) {
gEnabledEvents = ~0;
return;
}
gEnabledEvents |= (1 << e);
}
}
} // namespace slog | 31.213793 | 120 | 0.702828 | plsmaop |
cdeb94ad29e7d5ba1a3cb5525a706718280ca0dc | 12,406 | hpp | C++ | include/preform/fresnel.hpp | mgradysaunders/preform | ab5713d95653bd647d2985cdcd2c9e0e9a05f488 | [
"BSD-2-Clause"
] | null | null | null | include/preform/fresnel.hpp | mgradysaunders/preform | ab5713d95653bd647d2985cdcd2c9e0e9a05f488 | [
"BSD-2-Clause"
] | null | null | null | include/preform/fresnel.hpp | mgradysaunders/preform | ab5713d95653bd647d2985cdcd2c9e0e9a05f488 | [
"BSD-2-Clause"
] | null | null | null | /* Copyright (c) 2018-20 M. Grady Saunders
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*+-+*/
#if !DOXYGEN
#if !(__cplusplus >= 201402L)
#error "preform/fresnel.hpp requires >=C++14"
#endif // #if !(__cplusplus >= 201402L)
#endif // #if !DOXYGEN
#pragma once
#ifndef PREFORM_FRESNEL_HPP
#define PREFORM_FRESNEL_HPP
// for pre::signbit, pre::copysign, pre::sqrt, ...
#include <preform/math.hpp>
namespace pre {
/**
* @defgroup fresnel Fresnel equations
*
* `<preform/fresnel.hpp>`
*
* __C++ version__: >=C++14
*/
/**@{*/
/**
* @name Fresnel (dielectric)
*/
/**@{*/
/**
* @brief Fresnel equations for dielectric interface.
*
* @param[in] eta
* Refractive index @f$ \eta = \eta_i / \eta_t @f$.
*
* @param[in] cos_thetai
* Cosine of incidence angle.
*
* @param[out] cos_thetat
* Cosine of transmittance angle.
*
* @param[out] rs
* Reflection s-polarization.
*
* @param[out] rp
* Reflection p-polarization.
*
* @param[out] ts
* Transmission s-polarization.
*
* @param[out] tp
* Transmission p-polarization.
*
* @par Expression
* @parblock
* - @f$ \cos^2{\theta_t} = 1 - \eta^2 (1 - \cos^2{\theta_i}) @f$
* - @f$ r_s =
* (\eta \cos{\theta_i} - \cos{\theta_t}) /
* (\eta \cos{\theta_i} + \cos{\theta_t}) @f$
* - @f$ r_p =
* (\cos{\theta_i} - \eta \cos{\theta_t}) /
* (\cos{\theta_i} + \eta \cos{\theta_t}) @f$
* - @f$ t_s = 1 + r_s @f$
* - @f$ t_p = \eta (1 + r_p) @f$
* @endparblock
*
* @note
* In the case of total internal reflection,
* - `cos_thetat = 0`,
* - `rs = rp = 1`, and
* - `ts = tp = 0`.
*
* @returns
* If total internal reflection (TIR), returns `false`
* to indicate that there is no refracted ray. Otherwise, returns `true`.
*/
template <typename T>
inline std::enable_if_t<
std::is_floating_point<T>::value, bool> fresnel_diel(
T eta,
T cos_thetai,
T& cos_thetat,
T& rs, T& rp,
T& ts, T& tp)
{
T cos2_thetat = 1 - eta * eta * (1 - cos_thetai * cos_thetai);
if (!(cos2_thetat > 0)) {
cos_thetat = 0;
rs = rp = 1;
ts = tp = 0; // Total internal reflection.
return false;
}
else {
cos_thetat = pre::copysign(pre::sqrt(cos2_thetat), cos_thetai);
rs = (eta * cos_thetai - cos_thetat) / (eta * cos_thetai + cos_thetat);
rp = (cos_thetai - eta * cos_thetat) / (cos_thetai + eta * cos_thetat);
ts = 1 + rs;
tp = 1 + rp;
tp *= eta;
cos_thetat = -cos_thetat;
return true;
}
}
/**
* @brief Fresnel equations for dielectric interface, unpolarized form.
*
* @param[in] eta
* Refractive index @f$ \eta = \eta_i / \eta_t @f$.
*
* @param[in] cos_thetai
* Cosine of incidence angle.
*
* @param[out] cos_thetat
* Cosine of transmittance angle.
*
* @param[out] fr
* Reflection.
*
* @param[out] ft
* Transmission.
*
* @par Expression
* @parblock
* - @f$ F_r = (r_s^2 + r_p^2)/2 @f$
* - @f$ F_t = 1 - F_r @f$
* @endparblock
*
* @returns
* If total internal reflection (TIR), returns `false`
* to indicate that there is no refracted ray. Otherwise, returns `true`.
*/
template <typename T>
inline std::enable_if_t<
std::is_floating_point<T>::value, bool> fresnel_diel(
T eta,
T cos_thetai,
T& cos_thetat,
T& fr, T& ft)
{
T rs = 0, rp = 0;
T ts = 0, tp = 0;
bool res =
fresnel_diel(
eta,
cos_thetai,
cos_thetat,
rs, rp,
ts, tp);
fr = T(0.5) * (rs * rs + rp * rp);
ft = 1 - fr;
return res;
}
/**
* @brief Fresnel equations for dielectric interface, Schlick's approximation
* of unpolarized form.
*
* @param[in] eta
* Refractive index @f$ \eta = \eta_i / \eta_t @f$.
*
* @param[in] cos_thetai
* Cosine of incidence angle.
*
* @param[out] cos_thetat
* Cosine of transmittance angle.
*
* @param[out] fr
* Reflection.
*
* @param[out] ft
* Transmission.
*
* @par Expression
* @parblock
* - @f$ R_0 = (\eta - 1)^2 / (\eta + 1)^2 @f$
* - @f$ F_r = R_0 + (1 - R_0) (1 - \cos{\theta_i})^5 @f$
* - @f$ F_t = 1 - F_r @f$
* @endparblock
*
* @returns
* If total internal reflection (TIR), returns `false`
* to indicate that there is no refracted ray. Otherwise, returns `true`.
*/
template <typename T>
inline std::enable_if_t<
std::is_floating_point<T>::value, bool> fresnel_diel_schlick(
T eta,
T cos_thetai,
T& cos_thetat,
T& fr, T& ft)
{
T cos2_thetat = 1 - eta * eta * (1 - cos_thetai * cos_thetai);
if (!(cos2_thetat > 0)) {
cos_thetat = 0;
fr = 1;
ft = 0; // Total internal reflection.
return false;
}
else {
cos_thetat = pre::copysign(pre::sqrt(cos2_thetat), cos_thetai);
cos_thetat = -cos_thetat;
T sqrt_r0 = (eta - 1) / (eta + 1);
T r0 = sqrt_r0 * sqrt_r0;
T cos_thetai_term1 = 1 - cos_thetai;
T cos_thetai_term2 = cos_thetai_term1 * cos_thetai_term1;
T cos_thetai_term4 = cos_thetai_term2 * cos_thetai_term2;
T cos_thetai_term5 = cos_thetai_term4 * cos_thetai_term1;
fr = r0 + (1 - r0) * cos_thetai_term5;
ft = 1 - fr;
return true;
}
}
// TODO doc
/**
* @brief Fresnel's equations for dielectric thinfilm interface.
*
* @param[in] lambda
* Vacuum wavelength.
*
* @param[in] etai
* Absolute refractive index in incident hemisphere.
*
* @param[in] etaf
* Absolute refractive index in film.
*
* @param[in] ellf
* Film thickness.
*
* @param[in] muf
* Film volume absorption coefficient.
*
* @param[in] etat
* Absolute refractive index in transmitted hemisphere.
*
* @param[in] cos_thetai
* Cosine of incidence angle.
*
* @param[out] cos_thetat
* Cosine of transmittance angle.
*/
template <typename T>
inline std::enable_if_t<
std::is_floating_point<T>::value, bool> fresnel_diel_thinfilm(
T lambda,
T etai,
T etaf,
T ellf,
T muf,
T etat,
T cos_thetai,
T& cos_thetat,
std::complex<T>& rs, std::complex<T>& rp,
std::complex<T>& ts, std::complex<T>& tp)
{
// Refractive index ratios.
T eta1 = etai / etaf;
T eta2 = etaf / etat;
// Angle sines.
T sin2_thetai = 1 - cos_thetai * cos_thetai;
T sin2_theta1 = eta1 * eta1 * sin2_thetai;
T sin2_theta2 = eta2 * eta2 * sin2_theta1;
T cos2_theta1 = 1 - sin2_theta1;
T cos2_theta2 = 1 - sin2_theta2;
if (!(cos2_theta1 > 0 &&
cos2_theta2 > 0)) {
cos_thetat = 0;
rs = rp = 1;
ts = tp = 0;
return false;
}
// Angle cosines.
T cos_theta1 = pre::sqrt(cos2_theta1);
T cos_theta2 = pre::sqrt(cos2_theta2);
cos_theta1 = pre::copysign(cos_theta1, cos_thetai);
cos_theta2 = pre::copysign(cos_theta2, cos_thetai);
cos_thetat = -cos_theta2;
// Fresnel coefficients for interface 1.
T rs1, rp1;
T ts1, tp1;
rs1 = (eta1 * cos_thetai - cos_theta1) / (eta1 * cos_thetai + cos_theta1);
rp1 = (cos_thetai - eta1 * cos_theta1) / (cos_thetai + eta1 * cos_theta1);
ts1 = 1 + rs1;
tp1 = 1 + rp1;
tp1 *= eta1;
// Fresnel coefficients for interface 2.
T rs2, rp2;
T ts2, tp2;
rs2 = (eta2 * cos_theta1 - cos_theta2) / (eta2 * cos_theta1 + cos_theta2);
rp2 = (cos_theta1 - eta2 * cos_theta2) / (cos_theta1 + eta2 * cos_theta2);
ts2 = 1 + rs2;
tp2 = 1 + rp2;
tp2 *= eta2;
// Interference.
T phi = T(2) * etaf * ellf / (lambda * cos_theta1);
phi += (etai > etaf) ? T(1) : T(0);
phi += (etaf < etat) ? T(1) : T(0);
phi *= pre::numeric_constants<T>::M_pi();
T alpha = muf * ellf / cos_theta1;
std::complex<T> exp_phi = pre::exp(std::complex<T>{-alpha, phi});
std::complex<T> exp_phi2 = exp_phi * exp_phi;
std::complex<T> rs2_exp_phi2 = rs2 * exp_phi2;
std::complex<T> rp2_exp_phi2 = rp2 * exp_phi2;
T fac = (etaf * cos_theta1) / (etai * cos_thetai);
rs = rs1 + fac * ts1 * ts1 * rs2_exp_phi2 / (T(1) + rs1 * rs2_exp_phi2);
rp = rp1 + fac * tp1 * tp1 * rp2_exp_phi2 / (T(1) + rp1 * rp2_exp_phi2);
ts = ts1 * ts2 * exp_phi / (T(1) + rs1 * rs2_exp_phi2);
tp = tp1 * tp2 * exp_phi / (T(1) + rp1 * rp2_exp_phi2);
return true;
}
/**@}*/
/**
* @name Fresnel (dielectric-to-conducting)
*/
/**@{*/
/**
* @brief Fresnel equations for dielectric-to-conducting interface.
*
* @param[in] eta
* Refractive index @f$ \eta = \eta_i / \eta_t @f$.
*
* @param[in] cos_thetai
* Cosine of incidence angle.
*
* @param[out] cos_thetat
* Cosine of transmittance angle.
*
* @param[out] rs
* Reflection s-polarization.
*
* @param[out] rp
* Reflection p-polarization.
*
* @param[out] ts
* Transmission s-polarization.
*
* @param[out] tp
* Transmission p-polarization.
*
* @par Expression
* @parblock
* - @f$ \cos^2{\theta_t} = 1 - \eta^2 (1 - \cos^2{\theta_i}) @f$
* - @f$ r_s =
* (\eta \cos{\theta_i} - \cos{\theta_t}) /
* (\eta \cos{\theta_i} + \cos{\theta_t}) @f$
* - @f$ r_p =
* (\cos{\theta_i} - \eta \cos{\theta_t}) /
* (\cos{\theta_i} + \eta \cos{\theta_t}) @f$
* - @f$ t_s = 1 + r_s @f$
* - @f$ t_p = \eta (1 + r_p) @f$
* @endparblock
*
* @note
* In practice,
* - @f$ \eta_i @f$ should be real/dielectric, while
* - @f$ \eta_t @f$ may be complex/conducting.
*/
template <typename T>
inline std::enable_if_t<
std::is_floating_point<T>::value, void> fresnel_diel_cond(
std::complex<T> eta,
T cos_thetai,
std::complex<T>& cos_thetat,
std::complex<T>& rs, std::complex<T>& rp,
std::complex<T>& ts, std::complex<T>& tp)
{
cos_thetat =
pre::sign(cos_thetai) *
pre::sqrt(T(1) - eta * eta *
(T(1) - cos_thetai * cos_thetai));
rs = (eta * cos_thetai - cos_thetat) / (eta * cos_thetai + cos_thetat);
rp = (cos_thetai - eta * cos_thetat) / (cos_thetai + eta * cos_thetat);
ts = T(1) + rs;
tp = T(1) + rp;
tp *= eta;
cos_thetat = -cos_thetat;
}
/**
* @brief Fresnel equations for dielectric-to-conducting interface,
* unpolarized form.
*
* @param[in] eta
* Refractive index @f$ \eta = \eta_i / \eta_t @f$.
*
* @param[in] cos_thetai
* Cosine of incidence angle.
*
* @note
* In practice,
* - @f$ \eta_i @f$ should be real/dielectric, while
* - @f$ \eta_t @f$ may be complex/conducting.
*/
template <typename T>
inline std::enable_if_t<
std::is_floating_point<T>::value, T> fresnel_diel_cond(
std::complex<T> eta,
T cos_thetai)
{
std::complex<T> cos_thetat;
std::complex<T> rs, rp;
std::complex<T> ts, tp;
fresnel_diel_cond(
eta,
cos_thetai,
cos_thetat,
rs, rp,
ts, tp);
return T(0.5) * (pre::norm(rs) + pre::norm(rp));
}
/**@}*/
/**@}*/
} // namespace pre
#endif // #ifndef PREFORM_FRESNEL_HPP
| 27.265934 | 79 | 0.586007 | mgradysaunders |
cdebb629a94a7919cae317444dbb1b28755d0403 | 1,231 | cc | C++ | server/core/Source/SuccessiveOverRelaxationSpace.cc | paxbun/laplace-eq-therm | 26d50e5a559213f7248783329e7c4145cfd92589 | [
"MIT"
] | 1 | 2021-10-14T00:44:19.000Z | 2021-10-14T00:44:19.000Z | server/core/Source/SuccessiveOverRelaxationSpace.cc | paxbun/laplace-eq-therm | 26d50e5a559213f7248783329e7c4145cfd92589 | [
"MIT"
] | null | null | null | server/core/Source/SuccessiveOverRelaxationSpace.cc | paxbun/laplace-eq-therm | 26d50e5a559213f7248783329e7c4145cfd92589 | [
"MIT"
] | null | null | null | // Copyright (c) 2021 Chanjung Kim. All rights reserved.
// Licensed under the MIT License.
#include <leth/SuccessiveOverRelaxationSpace.hh>
#include <cmath>
#include <cstdio>
char const* SuccessiveOverRelaxationSpace::GetName() noexcept
{
return "SOR";
}
void SuccessiveOverRelaxationSpace::SolveEquation(std::vector<float> const& A,
std::vector<float>& x,
std::vector<float> const& b) noexcept
{
constexpr float omega { 1.12f };
size_t const numVars { x.size() };
for (size_t iter { 0 }; iter < 10000; ++iter)
{
bool converge { true };
for (size_t i { 0 }; i < numVars; ++i)
{
float const before { x[i] };
x[i] = b[i];
for (size_t j { 0 }; j < i; ++j) x[i] -= (A[i * numVars + j] * x[j]);
for (size_t j { i + 1 }; j < numVars; ++j) x[i] -= (A[i * numVars + j] * x[j]);
x[i] *= omega;
x[i] /= A[i * numVars + i];
x[i] += (1 - omega) * before;
if (std::abs(x[i] - before) >= 0.001)
converge = false;
}
if (converge)
break;
}
} | 27.355556 | 91 | 0.471974 | paxbun |
cdef8fffd037bc26f943dc5ac0cab4958310a58f | 4,288 | cpp | C++ | Engine/EngineCore/QtJSONStartupSettingsDataAccessObject.cpp | OGRECave/scape | 9c95ec7b6d8372a7a2a4eb6b96dcb5f2219e2bf2 | [
"BSD-2-Clause"
] | 48 | 2018-06-18T01:38:41.000Z | 2022-03-25T10:29:27.000Z | Engine/EngineCore/QtJSONStartupSettingsDataAccessObject.cpp | OGRECave/scape | 9c95ec7b6d8372a7a2a4eb6b96dcb5f2219e2bf2 | [
"BSD-2-Clause"
] | 32 | 2018-07-23T14:17:23.000Z | 2020-11-02T23:28:48.000Z | Engine/EngineCore/QtJSONStartupSettingsDataAccessObject.cpp | OGRECave/scape | 9c95ec7b6d8372a7a2a4eb6b96dcb5f2219e2bf2 | [
"BSD-2-Clause"
] | 7 | 2018-07-23T09:34:06.000Z | 2022-02-15T09:54:16.000Z | #include "ScapeEngineStableHeaders.h"
#include "QtJSONStartupSettingsDataAccessObject.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
namespace ScapeEngine
{
QtJSONStartupSettingsDataAccessObject::QtJSONStartupSettingsDataAccessObject(std::string fileName)
: mFileHelper(fileName)
{
}
QtJSONStartupSettingsDataAccessObject::~QtJSONStartupSettingsDataAccessObject() {}
const StartupSettings QtJSONStartupSettingsDataAccessObject::getStartupSettings() const
{
StartupSettings ret;
QJsonParseError errorStruct;
errorStruct.error = QJsonParseError::NoError;
QJsonDocument jsonDoc = mFileHelper.readJSONFile(errorStruct);
if (errorStruct.error == QJsonParseError::NoError)
{
if (jsonDoc.isObject())
{
QJsonObject rootObject = jsonDoc.object();
if (rootObject.contains(QString("Startup")))
{
QJsonValue startupValue = rootObject[QString("Startup")];
if (startupValue.isObject())
{
QJsonObject startupObject = startupValue.toObject();
if (startupObject.contains(QString("Heightfield")))
{
QJsonValue heightfieldValue = startupObject[QString("Heightfield")];
if (heightfieldValue.isObject())
{
QJsonObject heightfieldObject = heightfieldValue.toObject();
if (heightfieldObject.contains(QString("rows")))
{
QJsonValue heightfieldRowsValue = heightfieldObject[QString("rows")];
if (heightfieldRowsValue.isDouble())
{
ret.setHeightfieldRows(heightfieldRowsValue.toInt(0));
}
}
if (heightfieldObject.contains(QString("columns")))
{
QJsonValue heightfieldColumnsValue = heightfieldObject[QString("columns")];
if (heightfieldColumnsValue.isDouble())
{
ret.setHeightfieldColumns(heightfieldColumnsValue.toInt(0));
}
}
if (heightfieldObject.contains(QString("height")))
{
QJsonValue heightfieldHeightValue = heightfieldObject[QString("height")];
if (heightfieldHeightValue.isDouble())
{
ret.setHeightfieldHeight(heightfieldHeightValue.toDouble(0));
}
}
}
}
}
}
}
}
return ret;
}
void QtJSONStartupSettingsDataAccessObject::updateStartupSettings(const StartupSettings& startupSettings)
{
QJsonParseError errorStruct;
errorStruct.error = QJsonParseError::NoError;
QJsonDocument jsonDoc = mFileHelper.readJSONFile(errorStruct);
if (errorStruct.error == QJsonParseError::NoError)
{
if (jsonDoc.isObject())
{
QJsonObject rootObject = jsonDoc.object();
QJsonObject::iterator it = rootObject.find(QString("Startup"));
if (it != rootObject.end())
{
rootObject.erase(it);
}
QJsonObject startupObject = QJsonObject();
QJsonObject heightfieldObject = QJsonObject();
heightfieldObject.insert(QString("rows"), startupSettings.getHeightfieldRows());
heightfieldObject.insert(QString("columns"), startupSettings.getHeightfieldColumns());
heightfieldObject.insert(QString("height"), startupSettings.getHeightfieldHeight());
startupObject.insert(QString("Heightfield"), heightfieldObject);
rootObject.insert(QString("Startup"), startupObject);
jsonDoc = QJsonDocument(rootObject);
}
mFileHelper.writeJSONFile(jsonDoc);
}
}
}
| 36.033613 | 107 | 0.549907 | OGRECave |
cdf4d392d1d6d036ee22e88d1eacfcada103320b | 35,731 | cpp | C++ | innative-cmd/main.cpp | innative-sdk/innative | 7c4733a390ace01900e914b1b03cc6bc96e879c8 | [
"Apache-2.0"
] | 381 | 2018-12-13T19:53:48.000Z | 2022-03-21T07:33:39.000Z | innative-cmd/main.cpp | Black-Sphere-Studios/innative | 7c4733a390ace01900e914b1b03cc6bc96e879c8 | [
"Apache-2.0"
] | 62 | 2018-10-16T15:42:25.000Z | 2021-03-29T23:55:56.000Z | innative-cmd/main.cpp | Black-Sphere-Studios/innative | 7c4733a390ace01900e914b1b03cc6bc96e879c8 | [
"Apache-2.0"
] | 13 | 2018-12-13T17:43:49.000Z | 2020-06-13T15:10:38.000Z | // Copyright (c)2021 Fundament Software
// For conditions of distribution and use, see copyright notice in innative.h
#include "innative/export.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <unordered_map>
#include <functional>
#include <algorithm>
#include "../innative/filesys.h"
#ifdef IN_PLATFORM_WIN32
#include "../innative/win32.h"
inline std::unique_ptr<uint8_t[]> LoadFile(const path& file, long& sz)
{
FILE* f = nullptr;
FOPEN(f, file.c_str(), "rb");
if(!f)
return nullptr;
fseek(f, 0, SEEK_END);
sz = ftell(f);
fseek(f, 0, SEEK_SET);
std::unique_ptr<uint8_t[]> data(new uint8_t[sz]);
sz = (long)fread(data.get(), 1, sz, f);
fclose(f);
return data;
}
inline path GetProgramPath()
{
std::wstring programpath;
programpath.resize(MAX_PATH);
programpath.resize(GetModuleFileNameW(NULL, const_cast<wchar_t*>(programpath.data()), (DWORD)programpath.capacity()));
programpath.resize(wcsrchr(programpath.data(), '\\') - programpath.data());
return path(programpath);
}
#endif
KHASH_INIT(flags, const char*, unsigned int, 1, kh_str_hash_funcins, kh_str_hash_insequal);
static kh_flags_t* env_flags = kh_init_flags();
static kh_flags_t* env_optimize = kh_init_flags();
static kh_flags_t* env_abi = kh_init_flags();
static kh_flags_t* env_arch = kh_init_flags();
const static std::initializer_list<std::pair<const char*, unsigned int>> FLAG_MAP = {
{ "strict", ENV_STRICT },
{ "sandbox", ENV_SANDBOX },
{ "whitelist", ENV_WHITELIST },
{ "multithreaded", ENV_MULTITHREADED },
{ "debug", ENV_DEBUG },
{ "debug_pdb", ENV_DEBUG_PDB },
{ "debug_dwarf", ENV_DEBUG_DWARF },
{ "library", ENV_LIBRARY },
{ "llvm", ENV_EMIT_LLVM },
{ "noinit", ENV_NO_INIT },
{ "check_stack_overflow", ENV_CHECK_STACK_OVERFLOW },
{ "check_float_trunc", ENV_CHECK_FLOAT_TRUNC },
{ "check_memory_access", ENV_CHECK_MEMORY_ACCESS },
{ "check_indirect_call", ENV_CHECK_INDIRECT_CALL },
{ "check_int_division", ENV_CHECK_INT_DIVISION },
{ "disable_tail_call", ENV_DISABLE_TAIL_CALL },
};
const static std::initializer_list<std::pair<const char*, IN_ABI>> ABI_MAP = {
{ "windows", IN_ABI_Windows }, { "sys-v", IN_ABI_POSIX }, { "linux", IN_ABI_Linux },
{ "freebsd", IN_ABI_FreeBSD }, { "solaris", IN_ABI_Solaris }, { "arm", IN_ABI_ARM },
};
const static std::initializer_list<std::pair<const char*, IN_ARCH>> ARCH_MAP = {
{ "i386", IN_ARCH_x86 }, { "i486", IN_ARCH_x86 }, { "i586", IN_ARCH_x86 }, { "i686", IN_ARCH_x86 },
{ "x86", IN_ARCH_x86 }, { "amd64", IN_ARCH_amd64 }, { "x86-64", IN_ARCH_amd64 }, { "x86_64", IN_ARCH_amd64 },
{ "x64", IN_ARCH_amd64 }, { "ia64", IN_ARCH_IA64 }, { "arm", IN_ARCH_ARM }, { "xscale", IN_ARCH_ARM },
{ "arm64", IN_ARCH_ARM64 }, { "aarch64", IN_ARCH_ARM64 }, { "mips", IN_ARCH_MIPS }, { "ppc64", IN_ARCH_PPC64 },
{ "powerpc64", IN_ARCH_PPC64 }, { "ppu", IN_ARCH_PPC64 }, { "ppc", IN_ARCH_PPC }, { "powerpc", IN_ARCH_PPC },
{ "powerpcspe", IN_ARCH_PPC }, { "risc-v", IN_ARCH_RISCV }, { "riscv32", IN_ARCH_RISCV }
};
const static std::initializer_list<std::pair<const char*, unsigned int>> OPTIMIZE_MAP = {
{ "o0", ENV_OPTIMIZE_O0 }, { "o1", ENV_OPTIMIZE_O1 }, { "o2", ENV_OPTIMIZE_O2 },
{ "o3", ENV_OPTIMIZE_O3 }, { "os", ENV_OPTIMIZE_Os }, { "fastmath", ENV_OPTIMIZE_FAST_MATH },
};
struct OptBase
{
OptBase(const char* desc, const char* param) : description(desc), parameter(param) {}
virtual IN_ERROR Parse(int argc, char* argv[], int& pos) = 0;
virtual std::string Param() { return !parameter ? "" : parameter; }
const char* description;
const char* parameter;
};
template<class T> struct Opt;
template<> struct Opt<bool> : OptBase
{
Opt(const char* desc, const char* param = 0) : OptBase(desc, param), value(false) {}
virtual IN_ERROR Parse(int argc, char* argv[], int& pos) override
{
value = true;
return ERR_SUCCESS;
}
bool value;
};
template<class T, void (*ASSIGN)(T&, const char*)> struct OptValue : OptBase
{
OptValue(const char* desc, const char* param = 0) : OptBase(desc, param) {}
virtual IN_ERROR Parse(int argc, char* argv[], int& pos) override
{
if(pos < argc && argv[pos][0] != '-')
ASSIGN(value, argv[pos++]);
else
{
std::cout << "Missing command line argument parameter for " << argv[pos - 1] << std::endl;
return ERR_MISSING_COMMAND_LINE_PARAMETER;
}
return ERR_SUCCESS;
}
T value;
};
inline void STRING_ASSIGN(std::string& v, const char* s) { v = s; }
template<> struct Opt<std::string> : OptValue<std::string, &STRING_ASSIGN>
{
Opt(const char* desc, const char* param = 0) : OptValue(desc, param) {}
};
inline void PATH_ASSIGN(path& v, const char* s) { v = u8path(s); }
template<> struct Opt<path> : OptValue<path, &PATH_ASSIGN>
{
Opt(const char* desc, const char* param = 0) : OptValue(desc, param) {}
};
template<class T> struct optional // fake optional class so we don't need to rely on C++17 std::optional
{};
template<class T> struct Opt<optional<T>> : Opt<T>
{
Opt(const char* desc, const char* param = 0) : Opt<T>(desc, param), set(false), has_value(false) {}
virtual std::string Param() override { return "[" + Opt<T>::Param() + "]"; }
virtual IN_ERROR Parse(int argc, char* argv[], int& pos) override
{
set = true;
if(pos < argc && argv[pos][0] != '-')
{
IN_ERROR err = Opt<T>::Parse(argc, argv, pos);
if(err < 0)
return err;
has_value = true;
}
return ERR_SUCCESS;
}
bool set;
bool has_value;
};
template<class T> struct Opt<std::vector<T>> : Opt<T>
{
Opt(const char* desc, const char* param = 0) : Opt<T>(desc, param) {}
virtual std::string Param() override { return Opt<T>::Param() + " ... "; }
virtual IN_ERROR Parse(int argc, char* argv[], int& pos) override
{
IN_ERROR err = ERR_SUCCESS;
if(pos >= argc || argv[pos][0] == '-')
{
std::cout << "Missing command line argument parameter for " << argv[pos - 1] << std::endl;
return ERR_MISSING_COMMAND_LINE_PARAMETER;
}
while(pos < argc && argv[pos][0] != '-')
{
err = std::min(Opt<T>::Parse(argc, argv, pos), err);
if(err < ERR_SUCCESS)
break;
values.push_back(Opt<T>::value);
}
return err;
}
std::vector<T> values;
};
template<> struct Opt<WASM_ENVIRONMENT_FLAGS> : OptBase
{
Opt(const char* desc, const char* param = 0) : OptBase(desc, param)
{
help = description;
help += "\n Flags:\n ";
for(auto& f : FLAG_MAP)
{
help += f.first;
help += "\n ";
}
for(auto& f : OPTIMIZE_MAP)
{
help += f.first;
help += "\n ";
}
description = help.c_str();
}
virtual IN_ERROR Parse(int argc, char* argv[], int& pos) override
{
if(pos >= argc || argv[pos][0] == '-')
{
std::cout << "Missing command line argument parameter for " << argv[pos - 1] << std::endl;
return ERR_MISSING_COMMAND_LINE_PARAMETER;
}
IN_ERROR err = ERR_SUCCESS;
while(pos < argc && argv[pos][0] != '-')
{
khint_t iter = kh_get_flags(env_flags, argv[pos]);
if(kh_exist2(env_flags, iter))
value |= kh_value(env_flags, iter);
else
{
iter = kh_get_flags(env_optimize, argv[pos]);
if(kh_exist2(env_optimize, iter))
{
auto v = kh_value(env_optimize, iter);
if(v == ENV_OPTIMIZE_O0 || (v & ENV_OPTIMIZE_OMASK))
optimize = (optimize & ~ENV_OPTIMIZE_OMASK) | v;
else
optimize |= v;
}
else
{
std::cout << "Unknown flag: " << argv[pos] << std::endl;
err = ERR_UNKNOWN_FLAG;
}
}
++pos;
}
return err;
}
unsigned int value;
unsigned int optimize;
std::string help;
};
template<> struct Opt<IN_ABI> : OptBase
{
Opt(const char* desc, const char* param = 0) : OptBase(desc, param)
{
help = description;
help += "\n ABIs:\n ";
for(auto& f : ABI_MAP)
{
help += f.first;
help += "\n ";
}
description = help.c_str();
}
virtual IN_ERROR Parse(int argc, char* argv[], int& pos) override
{
if(pos >= argc || argv[pos][0] == '-')
{
std::cout << "Missing command line argument parameter for " << argv[pos - 1] << std::endl;
return ERR_MISSING_COMMAND_LINE_PARAMETER;
}
IN_ERROR err = ERR_SUCCESS;
if(pos < argc && argv[pos][0] != '-')
{
khint_t iter = kh_get_flags(env_abi, argv[pos]);
if(kh_exist2(env_abi, iter))
value = (IN_ABI)kh_value(env_abi, iter);
else
{
std::cout << "Unknown ABI: " << argv[pos] << std::endl;
err = ERR_INVALID_COMMAND_LINE;
}
++pos;
}
return err;
}
uint8_t value;
std::string help;
};
template<> struct Opt<IN_ARCH> : OptBase
{
Opt(const char* desc, const char* param = 0) : OptBase(desc, param)
{
// We only list architectures we actually support, and we don't list all the aliases.
help = description;
help += "\n ARCHs:"
"\n x86"
"\n amd64";
/*for(auto& f : ARCH_MAP)
{
help += f.first;
help += "\n ";
}*/
description = help.c_str();
}
virtual IN_ERROR Parse(int argc, char* argv[], int& pos) override
{
if(pos >= argc || argv[pos][0] == '-')
{
std::cout << "Missing command line argument parameter for " << argv[pos - 1] << std::endl;
return ERR_MISSING_COMMAND_LINE_PARAMETER;
}
IN_ERROR err = ERR_SUCCESS;
if(pos < argc && argv[pos][0] != '-')
{
khint_t iter = kh_get_flags(env_arch, argv[pos]);
if(kh_exist2(env_arch, iter))
value = kh_value(env_arch, iter);
else
{
std::cout << "Unknown architecture: " << argv[pos] << std::endl;
err = ERR_INVALID_COMMAND_LINE;
}
++pos;
}
return err;
}
uint8_t value;
std::string help;
};
KHASH_INIT(commands, const char*, OptBase*, 1, kh_str_hash_funcins, kh_str_hash_insequal);
struct CommandLine
{
CommandLine() :
commands(kh_init_commands()),
shortusage("Usage: innative-cmd"),
last_cmd(nullptr),
run("Run the compiled result immediately and display output. Requires a start function."),
flags("Set a supported flag to true.", "<FLAG>"),
libs("Links the input files against <FILE>, which must be a static library.", "<FILE>"),
shared_libs("Links the input files against <FILE>, which must be an ELF shared library.", "<FILE>"),
output_file("Sets the output path for the resulting executable or library.", "<FILE>"),
serialize(
"Serializes all modules to .wat files in addition to compiling them. <FILE> can specify the output if only one module is present, or 'emitdebug' will emit debug information",
"<FILE>|emitdebug"),
generate_loader(
"Instead of compiling immediately, creates a loader embedded with all the modules, environments, and settings, which compiles the modules on-demand when run."),
verbose("Turns on verbose logging."),
build_sourcemap(
"Assumes input files are ELF object files or binaries that contain DWARF debugging information, and creates a source map from them."),
whitelist("whitelists a given C import, does name-mangling if the module is specified.", "<[MODULE:]FUNCTION>"),
system(
"Sets the environment/system module name. Any functions with the module name will have the module name stripped when linking with C functions",
"<MODULE>"),
start(
"Sets or overrides the start function of a given module, in case it hasn't been properly specified. The function can't take any parameters and must return void.",
"<[MODULE:]FUNCTION>"),
linker("Specifies an alternative linker executable to use instead of LLD."),
install(
"Installs this SDK to the host operating system. On Windows, also updates file associations unless 'lite' is specified.",
"lite"),
uninstall("Uninstalls and deregisters this SDK from the host operating system."),
library_dir("Sets the directory that contains the SDK library and data files.", "<DIR>"),
object_dir("Sets the directory for temporary object files and intermediate compilation results.", "<DIR>"),
compile_llvm("Assumes the input files are LLVM IR files and compiles them into a single webassembly module."),
abi("Set the target ABI platform to compile for.", "<ABI>"),
arch("Set the target CPU architecture to compile for.", "<ARCH>"),
cpu_name(
"Set the target CPU name for code optimization. Set to \"generic\" for maximum portability (subject to CPU features requested). If this option isn't specified, the host CPU will be targeted."),
cpu_features(
"List CPU subfeatures, like SSSE3 or AVX, that the compiler should assume exist. Must be a valid subfeature string that LLVM recognizes.",
"<SUBFEATURE>")
{
flags.value = ENV_ENABLE_WAT;
flags.optimize = ENV_OPTIMIZE_O3;
abi.value = CURRENT_ABI;
arch.value = CURRENT_ARCH;
Register("r", &run);
Register("run", &run);
Register("f", &flags);
Register("flag", &flags);
Register("flags", &flags);
Register("l", &libs);
Register("lib", &libs);
Register("libs", &libs);
Register("library", &libs);
Register("shared-lib", &shared_libs);
Register("shared-libs", &shared_libs);
Register("shared-library", &shared_libs);
Register("o", &output_file);
Register("out", &output_file);
Register("output", &output_file);
Register("serialize", &serialize);
#ifdef IN_PLATFORM_WIN32
Register("generate-loader", &generate_loader);
#endif
Register("v", &verbose);
Register("verbose", &verbose);
Register("build-sourcemap", &build_sourcemap);
Register("w", &whitelist);
Register("whitelist", &whitelist);
Register("sys", &system);
Register("system", &system);
Register("start", &start);
Register("linker", &linker);
Register("i", &install);
Register("install", &install);
Register("u", &uninstall);
Register("uninstall", &uninstall);
Register("sdk", &library_dir);
Register("library-dir", &library_dir);
Register("obj", &object_dir);
Register("obj-dir", &object_dir);
Register("object-dir", &object_dir);
Register("intermediate-dir", &object_dir);
Register("compile-llvm", &compile_llvm);
Register("abi", &abi);
Register("platform", &abi);
Register("cpu", &cpu_name);
Register("cpu-name", &cpu_name);
Register("cpu-feature", &cpu_features);
Register("cpu-features", &cpu_features);
Register("arch", &arch);
Register("architecture", &arch);
DumpLastDescription();
usage += "\n\n Example usage: innative-cmd -r your-module.wasm";
}
void DumpLastDescription()
{
if(last_cmd)
{
if(last_cmd->parameter)
usage += " " + last_cmd->Param();
usage += ": ";
usage += last_cmd->description;
}
}
void Register(const char* shortcut, OptBase* command)
{
int err;
khiter_t iter = kh_put_commands(commands, shortcut, &err);
kh_value(commands, iter) = command;
if(last_cmd != command)
{
DumpLastDescription();
last_cmd = command;
shortusage += " [-";
shortusage += shortcut;
if(command->parameter)
shortusage += " " + command->Param();
shortusage += ']';
usage += "\n ";
}
usage += " -";
usage += shortcut;
}
IN_ERROR Parse(int argc, char* argv[])
{
IN_ERROR err = ERR_SUCCESS;
int pos = 0;
while(pos < argc)
{
if(argv[pos][0] == '-')
{
khiter_t iter = kh_get_commands(commands, argv[pos] + 1);
if(kh_exist2(commands, iter))
err = std::min(kh_value(commands, iter)->Parse(argc, argv, ++pos), err);
else
{
std::cout << "Unknown command line option: " << argv[pos++] << std::endl;
err = ERR_UNKNOWN_COMMAND_LINE;
}
}
else if(!STRICMP(u8path(argv[pos]).extension().u8string().c_str(), "wast")) // Check if this is a .wast script
wast.push_back(argv[pos++]);
else // Everything else is an input file
inputs.push_back(argv[pos++]);
}
return err;
}
void ResolveOutput()
{
if(output_file.value.empty()) // If no out is specified, default to name of first input file
{
output_file.value = u8path(!inputs.size() ? wast[0] : inputs[0]);
if(compile_llvm.value)
output_file.value.replace_extension(".wasm");
else if(build_sourcemap.value)
output_file.value += ".map";
else if(flags.value & ENV_LIBRARY)
output_file.value.replace_extension(abi.value == IN_ABI_Windows ? ".dll" : ".so");
else
output_file.value.replace_extension(abi.value == IN_ABI_Windows ? ".exe" : "");
}
}
Opt<bool> run;
Opt<WASM_ENVIRONMENT_FLAGS> flags;
Opt<std::vector<std::string>> libs;
Opt<std::vector<std::string>> shared_libs;
Opt<path> output_file;
Opt<optional<std::string>> serialize;
Opt<bool> generate_loader;
Opt<bool> verbose;
Opt<bool> build_sourcemap;
Opt<std::vector<std::string>> whitelist;
Opt<std::string> system;
Opt<std::string> start;
Opt<std::string> linker;
Opt<optional<std::string>> install;
Opt<bool> uninstall;
Opt<std::string> library_dir;
Opt<std::string> object_dir;
Opt<bool> compile_llvm;
Opt<IN_ABI> abi;
Opt<IN_ARCH> arch;
Opt<std::string> cpu_name;
Opt<std::vector<std::string>> cpu_features;
std::vector<const char*> inputs;
std::vector<const char*> wast; // WAST files will be executed in the order they are specified, after all other modules are
// injected into the environment
kh_commands_s* commands;
std::string shortusage;
std::string usage;
OptBase* last_cmd;
};
void printerr(INExports& exports, const Environment* env, const char* prefix, const char* postfix, int err)
{
const char* errstring = (*exports.GetErrorString)(err);
if(env)
{
if(errstring)
(*env->loghook)(env, "%s%s: %s\n", prefix, postfix, errstring);
else
(*env->loghook)(env, "%s%s: %i\n", prefix, postfix, err);
}
else if(errstring)
fprintf(stderr, "%s%s: %s\n", prefix, postfix, errstring);
else
fprintf(stderr, "%s%s: %i\n", prefix, postfix, err);
}
void dump_validation_errors(INExports& exports, Environment* env)
{
for(ValidationError* error = env->errors; error != nullptr; error = error->next)
{
const char* errstring = (*exports.GetErrorString)(error->code);
if(errstring)
(*env->loghook)(env, "Error %s: %s\n", errstring, error->error);
else
(*env->loghook)(env, "Error %i: %s\n", error->code, error->error);
}
}
int main(int argc, char* argv[])
{
int err;
for(auto& f : FLAG_MAP)
{
khiter_t iter = kh_put_flags(::env_flags, f.first, &err);
kh_value(::env_flags, iter) = f.second;
}
for(auto& f : OPTIMIZE_MAP)
{
khiter_t iter = kh_put_flags(::env_optimize, f.first, &err);
kh_value(::env_optimize, iter) = f.second;
}
for(auto& f : ABI_MAP)
{
khiter_t iter = kh_put_flags(::env_abi, f.first, &err);
kh_value(::env_abi, iter) = f.second;
}
for(auto& f : ARCH_MAP)
{
khiter_t iter = kh_put_flags(::env_arch, f.first, &err);
kh_value(::env_arch, iter) = f.second;
}
CommandLine commandline;
err = commandline.Parse(argc - 1, argv + 1); // skip 0th parameter
if(err != 0)
{
std::cout << commandline.shortusage << commandline.usage << std::endl;
return err;
}
if(commandline.run.value)
commandline.flags.value |= ENV_LIBRARY | ENV_NO_INIT;
if(commandline.uninstall.value)
{
std::cout << "Uninstalling inNative Runtime..." << std::endl;
err = innative_uninstall();
if(err != 0)
{
std::cout << "Failed to uninstall runtime! [" << err << "]" << std::endl;
return err;
}
std::cout << "Successfully uninstalled runtime!" << std::endl;
}
if(commandline.install.set)
{
std::cout << "Installing inNative Runtime..." << std::endl;
bool lite = commandline.install.has_value ? !STRICMP(commandline.install.value.c_str(), "lite") : false;
err = innative_install(argv[0], !lite);
if(err < 0)
std::cout << "Installation failed! [" << err << "]" << std::endl;
else
std::cout << "Installation succeeded!" << std::endl;
}
if(commandline.install.set || commandline.uninstall.value)
return err;
if(!commandline.inputs.size() && !commandline.wast.size())
{
std::cout << "No input files specified!" << std::endl;
std::cout << commandline.shortusage << commandline.usage << std::endl;
return ERR_NO_INPUT_FILES;
}
// If we are cross-compiling, set cpu_name to "generic" if it was not already specified
if(commandline.arch.value != CURRENT_ARCH || commandline.abi.value != CURRENT_ABI)
{
if(commandline.cpu_name.value.empty())
commandline.cpu_name.value = "generic";
}
commandline.ResolveOutput();
// If we're compiling LLVM IR instead of webassembly, we divert to another code path
if(commandline.compile_llvm.value)
return innative_compile_llvm(commandline.inputs.data(), commandline.inputs.size(), commandline.flags.value,
commandline.output_file.value.u8string().c_str(), stdout);
INExports exports = { 0 };
// If we are generating a loader, we replace all of the normal functions to reroute the resources into the EXE file
if(commandline.generate_loader.value)
{
if(commandline.run.value)
{
std::cout << "You can't run a file dynamically and also generate a loader, make up your mind!" << std::endl;
return ERR_COMMAND_LINE_CONFLICT;
}
#ifdef IN_PLATFORM_WIN32
exports.CreateEnvironment = [](unsigned int modules, unsigned int maxthreads, const char* arg0) -> Environment* {
Environment* env = reinterpret_cast<Environment*>(calloc(1, sizeof(Environment)));
if(env)
env->loghook = [](const Environment* env, const char* f, ...) -> int {
va_list args;
va_start(args, f);
int len = VPRINTF(f, args);
va_end(args);
return len;
};
return env;
};
exports.AddModule = [](Environment* env, const void* data, size_t size, const char* name, int* err) {
if(!size)
{
long sz = 0;
auto file = LoadFile(reinterpret_cast<const char*>(data), sz);
if(!sz)
*err = ERR_FATAL_FILE_ERROR;
else if(!UpdateResourceA(reinterpret_cast<HANDLE>(env->alloc), WIN32_RESOURCE_MODULE, name, 0, file.get(),
static_cast<DWORD>(sz)))
*err = ERR_FATAL_RESOURCE_ERROR;
}
else if(!UpdateResourceA(reinterpret_cast<HANDLE>(env->alloc), WIN32_RESOURCE_MODULE, name, 0,
const_cast<void*>(data), static_cast<DWORD>(size)))
*err = ERR_FATAL_RESOURCE_ERROR;
};
exports.AddWhitelist = [](Environment* env, const char* module_name, const char* export_name) -> IN_ERROR {
if(!UpdateResourceA(reinterpret_cast<HANDLE>(env->alloc), WIN32_RESOURCE_WHITELIST, module_name, 0,
const_cast<char*>(export_name), static_cast<DWORD>(strlen(export_name) + 1)))
{
std::cout << "Failed to add whitelist entry: " << (!module_name ? "" : module_name) << "|" << export_name
<< std::endl;
return ERR_FATAL_FILE_ERROR;
}
return ERR_SUCCESS;
};
exports.AddEmbedding = [](Environment* env, int tag, const void* data, size_t size,
const char* name_override) -> IN_ERROR {
char buf[20];
_itoa_s(tag, buf, 10);
if(!size)
{
long sz = 0;
path src = u8path(reinterpret_cast<const char*>(data));
FILE* f;
FOPEN(f, src.c_str(), "rb");
if(!f)
{
src = (!env->libpath ? GetProgramPath() : u8path(env->libpath)) / src;
}
else
fclose(f);
auto file = LoadFile(src.c_str(), sz);
if(!sz)
return ERR_FATAL_FILE_ERROR;
if(!UpdateResourceA(reinterpret_cast<HANDLE>(env->alloc), WIN32_RESOURCE_EMBEDDING, buf, 0, file.get(), sz))
return ERR_FATAL_RESOURCE_ERROR;
}
else if(!UpdateResourceA(reinterpret_cast<HANDLE>(env->alloc), WIN32_RESOURCE_EMBEDDING, buf, 0,
const_cast<void*>(data), static_cast<DWORD>(size)))
return ERR_FATAL_RESOURCE_ERROR;
return ERR_SUCCESS;
};
exports.FinalizeEnvironment = [](Environment* env) -> IN_ERROR {
if(!UpdateResourceA(reinterpret_cast<HANDLE>(env->alloc), WIN32_RESOURCE_FLAGS, "flags", 0, &env->flags,
sizeof(env->flags)))
return ERR_FATAL_RESOURCE_ERROR;
if(!UpdateResourceA(reinterpret_cast<HANDLE>(env->alloc), WIN32_RESOURCE_FLAGS, "optimize", 0, &env->optimize,
sizeof(env->optimize)))
return ERR_FATAL_RESOURCE_ERROR;
if(!UpdateResourceA(reinterpret_cast<HANDLE>(env->alloc), WIN32_RESOURCE_FLAGS, "features", 0, &env->features,
sizeof(env->features)))
return ERR_FATAL_RESOURCE_ERROR;
return ERR_SUCCESS;
};
exports.Compile = [](Environment* env, const char* file) -> IN_ERROR { return ERR_SUCCESS; };
exports.DestroyEnvironment = [](Environment* env) {
if(!EndUpdateResourceA(reinterpret_cast<HANDLE>(env->alloc), FALSE))
std::cout << "Failed to end resource update!" << std::endl;
};
#ifdef IN_DEBUG
std::string exe = "innative-loader-d";
#else
std::string exe = "innative-loader";
#endif
if(commandline.abi.value == IN_ABI_Windows)
exe += ".exe";
if(!copy_file(GetProgramPath() / exe, commandline.output_file.value, copy_options::overwrite_existing))
{
std::cout << "Could not find or copy loader EXE!" << std::endl;
return ERR_MISSING_LOADER;
}
#endif
}
else
innative_runtime(&exports);
// Make sure the functions we're going to use actually exist
if(!exports.CreateEnvironment || !exports.DestroyEnvironment || !exports.AddModule || !exports.AddWhitelist ||
!exports.AddEmbedding || !exports.FinalizeEnvironment || !exports.Compile || !exports.LoadAssembly ||
!exports.FreeAssembly || !exports.GetErrorString || !exports.CompileScript || !exports.SerializeModule)
return ERR_UNKNOWN_ENVIRONMENT_ERROR;
// Then create the runtime environment with the module count.
Environment* env =
(*exports.CreateEnvironment)(static_cast<unsigned int>(commandline.inputs.size()), 0, (!argc ? 0 : argv[0]));
env->flags = commandline.flags.value;
env->features = ENV_FEATURE_ALL;
env->optimize = commandline.flags.optimize;
if(!env)
{
fprintf(stderr, "Unknown error creating environment.\n");
return ERR_UNKNOWN_ENVIRONMENT_ERROR;
}
// If we're dumping DWARF to source map information, divert to another code path
if(commandline.build_sourcemap.value)
{
SourceMap map = { 0 };
for(auto& input : commandline.inputs)
{
err = ParseDWARF(env, &map, commandline.inputs[0], 0);
if(err < 0)
printerr(exports, nullptr, "Error parsing file ", commandline.inputs[0], err);
}
err = (*exports.SerializeSourceMap)(&map, commandline.output_file.value.u8string().c_str());
if(err < 0)
printerr(exports, nullptr, "Error saving file ", commandline.output_file.value.u8string().c_str(), err);
return err;
}
#ifdef IN_PLATFORM_WIN32
if(commandline.generate_loader.value)
env->alloc =
reinterpret_cast<IN_WASM_ALLOCATOR*>(BeginUpdateResourceA(commandline.output_file.value.u8string().c_str(), TRUE));
if(!env->alloc)
{
std::cout << "Failed to begin resource update!" << std::endl;
(*exports.DestroyEnvironment)(env);
return ERR_MISSING_LOADER;
}
#endif
if(commandline.verbose.value)
env->loglevel = LOG_NOTICE;
if(!commandline.library_dir.value.empty())
env->libpath = commandline.library_dir.value.c_str();
if(!commandline.object_dir.value.empty())
env->objpath = commandline.object_dir.value.c_str();
if(!commandline.linker.value.empty())
env->linker = commandline.linker.value.c_str();
if(!commandline.system.value.empty())
env->system = commandline.system.value.c_str();
env->abi = commandline.abi.value;
env->arch = commandline.arch.value;
if(!commandline.cpu_name.value.empty())
{
env->cpu_name = commandline.cpu_name.value.c_str();
if(commandline.cpu_name.value == "generic")
(exports.AddCPUFeature(env, nullptr));
}
for(auto item : commandline.cpu_features.values)
{
(exports.AddCPUFeature(env, item.c_str()));
}
for(auto item : commandline.whitelist.values)
{
char* ctx;
char* first = STRTOK(const_cast<char*>(item.data()), ":", &ctx);
char* second = STRTOK(NULL, ":", &ctx);
if(!second)
err = (*exports.AddWhitelist)(env, nullptr, first);
else
err = (*exports.AddWhitelist)(env, first, second);
if(err < 0)
{
STRTOK(NULL, ":", &ctx);
printerr(exports, env, "Error adding whitelist ", item.c_str(), err);
}
}
// Add all embedding environments, plus the default environment
#ifdef IN_DEBUG
const bool is_debug = true;
#else
const bool is_debug = false;
#endif
std::string default_embed;
default_embed.resize((*exports.GetEmbeddingPath)(env->abi, env->arch, is_debug, nullptr, nullptr, 0));
default_embed.resize(
(*exports.GetEmbeddingPath)(env->abi, env->arch, is_debug, nullptr, default_embed.data(), default_embed.capacity()));
commandline.libs.values.push_back(default_embed.c_str());
auto add_embeds = [](int tag, std::vector<std::string>& values, Environment* environment, INExports& exp) -> int {
IN_ERROR result = ERR_SUCCESS;
for(auto& embedding : values)
{
IN_ERROR e = (*exp.AddEmbedding)(environment, tag, embedding.c_str(), 0, 0);
if(e < 0)
{
printerr(exp, environment, tag ? "Error loading shared library " : "Error loading embedding ", embedding.c_str(),
e);
result = e;
}
}
return result;
};
err = add_embeds(IN_TAG_ANY, commandline.libs.values, env, exports);
err = std::min(err, add_embeds(IN_TAG_DYNAMIC, commandline.shared_libs.values, env, exports));
if(err < 0)
{
(*exports.DestroyEnvironment)(env);
return ERR_FATAL_FILE_ERROR;
}
// Load all modules
std::unique_ptr<int[]> errs(new int[commandline.inputs.size()]);
for(size_t i = 0; i < commandline.inputs.size(); ++i)
(*exports.AddModule)(env, commandline.inputs[i], 0, u8path(commandline.inputs[i]).stem().u8string().c_str(), &errs[i]);
// Override start if necessary
if(!commandline.start.value.empty() && env->n_modules > 0)
{
char* ctx;
char* first = STRTOK(const_cast<char*>(commandline.start.value.data()), ":", &ctx);
char* second = STRTOK(NULL, ":", &ctx);
Module* m = &env->modules[0];
if(second && first)
{
for(int i = 0; i < env->n_modules; ++i)
{
if(!strncmp(env->modules[i].name.str(), first, env->modules[i].name.size()))
m = &env->modules[i];
}
}
else
second = first;
if(!second)
{
(*env->loghook)(env, "No start function provided!\n");
err = ERR_INVALID_COMMAND_LINE;
}
else
{
varuint32 i = 0;
for(; i < m->exportsection.n_exports; ++i)
{
if(m->exportsection.exports[i].kind == WASM_KIND_FUNCTION &&
!strncmp(m->exportsection.exports[i].name.str(), second, m->exportsection.exports[i].name.size()))
{
m->start = m->exportsection.exports[i].index;
m->knownsections |= (1 << WASM_SECTION_START);
break;
}
}
if(i == m->exportsection.n_exports)
{
(*env->loghook)(env, "Couldn't find start function %s!\n", second);
err = ERR_INVALID_COMMAND_LINE;
}
}
}
// Ensure all modules are loaded, in case we have multithreading enabled
if(err >= 0)
err = (*exports.FinalizeEnvironment)(env);
for(size_t i = 0; i < commandline.inputs.size(); ++i)
{
if(errs[i] < 0)
{
printerr(exports, env, "Error loading module ", commandline.inputs[i], errs[i]);
if(err >= 0)
err = ERR_RUNTIME_INVALID_ASSEMBLY;
}
}
if(err < 0)
{
if(env->loglevel >= LOG_FATAL)
{
printerr(exports, env, "Error loading environment", "", err);
dump_validation_errors(exports, env);
}
(*exports.DestroyEnvironment)(env);
return err;
}
if(commandline.serialize.set) // If you want to serialize the results, we do so now that the modules have been loaded
{
bool emitdebug = false;
if(commandline.serialize.has_value) // If a name was specified, verify only one module exists
{
if(!STRICMP(commandline.serialize.value.c_str(), "emitdebug"))
emitdebug = true;
else if(env->n_modules != 1)
fprintf(
stderr,
"If you have more than one module, you cannot specify an output file for serialization. Use [-s] by itself, instead.\n");
}
for(size_t i = 0; i < env->n_modules; ++i)
{
std::string target = env->modules[i].name.str();
target += ".wat";
if(!emitdebug && commandline.serialize.has_value)
target = commandline.serialize.value;
(*exports.SerializeModule)(env, i, target.c_str(), 0, emitdebug);
}
}
// Check if this is a .wast file, which must be handled differently because it's an entire environment
if(commandline.wast.size() > 0)
{
for(size_t i = 0; i < commandline.wast.size() && !err; ++i)
err = (*exports.CompileScript)(reinterpret_cast<const uint8_t*>(commandline.wast[i]), 0, env, true,
commandline.output_file.value.parent_path().u8string().c_str());
}
else // Attempt to compile. If an error happens, output it and any validation errors to stderr
err = (*exports.Compile)(env, commandline.output_file.value.u8string().c_str());
if(err < 0)
{
if(env->loglevel >= LOG_ERROR)
{
printerr(exports, env, "Compile error", "", err);
dump_validation_errors(exports, env);
}
(*exports.DestroyEnvironment)(env);
return err;
}
// Destroy environment now that compilation is complete
(*exports.DestroyEnvironment)(env);
// Automatically run the assembly, but only if there were no wast scripts (which are always executed)
if(!commandline.wast.size())
{
if(commandline.run.value)
{
void* assembly = (*exports.LoadAssembly)(commandline.output_file.value.u8string().c_str());
if(!assembly)
{
(*env->loghook)(env, "Generated file cannot be found! Does innative-cmd have permissions for this directory?\n");
return ERR_FATAL_FILE_ERROR;
}
IN_Entrypoint start = (*exports.LoadFunction)(assembly, 0, IN_INIT_FUNCTION);
IN_Entrypoint exit = (*exports.LoadFunction)(assembly, 0, IN_EXIT_FUNCTION);
if(!start)
{
(*env->loghook)(env, "Start function is invalid or cannot be found!\n");
(*exports.FreeAssembly)(assembly);
return ERR_INVALID_START_FUNCTION;
}
(*start)();
if(exit)
(*exit)();
(*exports.FreeAssembly)(assembly);
return ERR_SUCCESS;
}
else
std::cout << "Successfully built " << commandline.output_file.value.u8string().c_str() << std::endl;
}
return err;
}
| 33.645009 | 199 | 0.62867 | innative-sdk |
cdf684d46caa1458057b6f7634711f50718f4658 | 24,102 | hpp | C++ | DoubleInt_t.hpp | jlinton/DoubleInt_t | 83659199e5136c376d1731ce39ce45193577db6c | [
"MIT"
] | 3 | 2015-05-12T02:33:28.000Z | 2017-12-06T08:47:27.000Z | DoubleInt_t.hpp | jlinton/DoubleInt_t | 83659199e5136c376d1731ce39ce45193577db6c | [
"MIT"
] | null | null | null | DoubleInt_t.hpp | jlinton/DoubleInt_t | 83659199e5136c376d1731ce39ce45193577db6c | [
"MIT"
] | null | null | null | // C++ BigNum template class
// AKA the integer doubler template.
// Copyright(C) 2007,2015 Jeremy Linton
//
// Source identity: DoubleInt_t.hpp
//
// This started as an amusing exercise in template meta-programming..
// Or in this case nestable classes. AKA std::list<std::list<>>
// But the optimizer can see into the nesting, so the generated assembly
// actually looks really sort of native. Especially since the base class
// is just gcc inline assembly...
//
// So, what we have is actually a pretty good class for "small" bignums
// AKA ones less than say 1k bits. Larger than that and the more intelligent
// algorithms used in GNU MP result in faster code.
//
// This is also an _AWESOME_ test of your compiler. Have you ever seen a
// single module take hours to compile? Well, that is possible with this one
// if the integer types are large enough!!!!! It can also create some crazy big
// functions...
//
// One of the nicer things about this code is the fact that I've created
// an x86 int128 class that can provide information about overflow/carry
// Its this class which is used as the basis for the integer doubler class.
//
// The amusing code is where we have:
// typedef class DoubleInt_t<int128> int256;
// typedef class DoubleInt_t<int256> int512;
// typedef class DoubleInt_t<int512> int1024;
// typedef class DoubleInt_t<int1024> int2048;
//
// While these are called int256/etc they are actually unsigned
// (because at the time, I thought that the default int class in C++ should be
// unsigned with a "signed" keyword to provide for signed math...)
//
// There is a signed template too called SignedInt_t<> which adds a sign
// bit to the given unsigned class, and transforms all the basic operations
// so that they work correctly depending on the state of the sign bit.
//
// combined with some inline assembly to create a integer class
// that could export information about whether an operation had overflow/carry
//
// these classes create an arbitrary size integer similar to GMP
//
// This module is both the template classes as well as some small "unit tests"
// which demonstrate how it can be used. Of particular note is the AsString()
// and FromString() routines which provide human readable input/output from
// the DoubleInt_t
//
//
// 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.
#ifndef DOUBLEINT_T_HPP
#define DOUBLEINT_T_HPP
#include "int128_t.hpp"
// This is the core doubler template. It takes either itself or the int128_t
// Class and creates a class which has exactly 2x the number of bits. This allows us
// To create somewhat arbitrary sized integers, although its not really useful beyond
// maybe 2k bits. If you need more, consider something like GNU MP.
template<class BaseIntT> class DoubleInt_t
{
public:
// construction/casting
DoubleInt_t() :Hi(0),Lo(0),size(Hi.size*2) {}
DoubleInt_t(const DoubleInt_t &orig):Hi(orig.Hi),Lo(orig.Lo),size(Hi.size*2) {}
DoubleInt_t(const BaseIntT &orig):Hi(0),Lo(orig),size(Hi.size*2) {}
DoubleInt_t(const int64 &orig):Hi(0),Lo(orig),size(Hi.size*2) {}
// assignment
DoubleInt_t &operator= (const DoubleInt_t &rhs) {Hi=rhs.Hi;Lo=rhs.Lo;return *this;}
// compariston
bool operator==(const DoubleInt_t &rhs) { if ((Hi==rhs.Hi) && (Lo==rhs.Lo)) return true; return false;}
bool operator!=(const DoubleInt_t &rhs) { if ((Hi==rhs.Hi) && (Lo==rhs.Lo)) return false; return true;}
bool operator>=(const DoubleInt_t &rhs) { if ((Hi>rhs.Hi) || ( (Hi==rhs.Hi) && (Lo>=rhs.Lo))) return true; return false;}
bool operator<=(const DoubleInt_t &rhs) { if ((Hi<rhs.Hi) || ( (Hi==rhs.Hi) && (Lo<=rhs.Lo))) return true; return false;}
bool operator> (const DoubleInt_t &rhs) { if ((Hi>rhs.Hi) || ( (Hi==rhs.Hi) && (Lo>rhs.Lo ))) return true; return false;}
bool operator< (const DoubleInt_t &rhs) { if ((Hi<rhs.Hi) || ( (Hi==rhs.Hi) && (Lo<rhs.Lo ))) return true; return false;}
// operations (these are exported for user use)
DoubleInt_t &operator>>=(const int rhs) { for (int x=0;x<rhs;x++) shiftright(this,0); return *this;}
DoubleInt_t &operator<<=(const int rhs) { for (int x=0;x<rhs;x++) shiftleft(this,0); return *this;}
DoubleInt_t &operator-=( const DoubleInt_t &rhs) { SubDouble(this,rhs,0); return *this;}
DoubleInt_t &operator+=( const DoubleInt_t &rhs) { AddDouble(this,rhs,0); return *this;}
DoubleInt_t &operator*=( const DoubleInt_t &rhs) { MultiplyDouble(this,rhs); return *this;}
DoubleInt_t &operator/=( const DoubleInt_t &rhs) { DivideDouble(this,rhs); return *this;}
DoubleInt_t &operator%=( const DoubleInt_t &rhs) { *this=DivideDouble(this,rhs); return *this;}
DoubleInt_t &operator&=( const int64 &rhs) { this->Lo&=rhs; return *this;}
DoubleInt_t &operator|=( const int64 &rhs) { this->Lo|=rhs; return *this;}
DoubleInt_t &operator^=( const int64 &rhs) { this->Lo^=rhs; return *this;}
DoubleInt_t &operator&=( const DoubleInt_t &rhs) { this->Lo&=rhs.Lo; this->Hi&=rhs.Hi; return *this;}
DoubleInt_t &operator|=( const DoubleInt_t &rhs) { this->Lo|=rhs.Lo; this->Hi|=rhs.Hi; return *this;}
DoubleInt_t &operator^=( const DoubleInt_t &rhs) { this->Lo^=rhs.Lo; this->Hi^=rhs.Hi; return *this;}
DoubleInt_t operator+( const DoubleInt_t &rhs) { DoubleInt_t tmp=*this; AddDouble(&tmp,rhs,0); return tmp;}
DoubleInt_t operator-( const DoubleInt_t &rhs) { DoubleInt_t tmp=*this; SubDouble(&tmp,rhs,0); return tmp;}
DoubleInt_t operator/( const DoubleInt_t &rhs) { DoubleInt_t tmp=*this; DivideDouble(&tmp,rhs); return tmp;}
DoubleInt_t operator%( const DoubleInt_t &rhs) { DoubleInt_t tmp=*this; tmp=DivideDouble(&tmp,rhs); return tmp;}
DoubleInt_t operator*( const DoubleInt_t &rhs) { DoubleInt_t tmp=*this; MultiplyDouble(&tmp,rhs); return tmp;}
DoubleInt_t operator&( const int64 &rhs) { DoubleInt_t tmp=*this; tmp.Lo&=rhs; return tmp;}
DoubleInt_t operator|( const int64 &rhs) { DoubleInt_t tmp=*this; tmp.Lo|=rhs; return tmp;}
DoubleInt_t operator^( const int64 &rhs) { DoubleInt_t tmp=*this; tmp.Lo^=rhs; return tmp;}
DoubleInt_t operator>>( const int &rhs) { DoubleInt_t tmp=*this; tmp>>=rhs; return tmp;}
DoubleInt_t operator<<( const int &rhs) { DoubleInt_t tmp=*this; tmp<<=rhs; return tmp;}
// consider overridding printf until then use AsString
string AsString(const char *format);
void FromString(const char *Source_prm);
char GetLowByte() {return Lo.GetLowByte();}
// protected:
// these operations are exported for higher level use
// they don't use the this variable...
static int SubDouble(DoubleInt_t *A,const DoubleInt_t &B,const int borrow);
static int AddDouble(DoubleInt_t *A,const DoubleInt_t &B,const int carry);
static DoubleInt_t DivideDouble(DoubleInt_t *A,const DoubleInt_t &B);
static DoubleInt_t MultiplyDouble(DoubleInt_t *A,const DoubleInt_t &B);
static int shiftleft(DoubleInt_t *Value,const int Carry_prm);
static int shiftright(DoubleInt_t *Value,const int Carry_prm);
// private:
BaseIntT Hi;
BaseIntT Lo;
const int size;
};
// throw exceptions on overflow/underflow etc..
template<class BaseInnT> class OverflowException_t
{
};
template<class BaseIntT, class ExponentT> class Floating_t
{
};
// normal number systems don't support -0 so we don't either...
// this class just takes an unsigned base and adds a sign to it,
// it does this without changing the bit encoding of the value, so its
// not exactly efficient for certain operations, on the other hand we don't then have
// to worry about sign extension or anything like that...
template<class BaseIntT> class SignedInt_t
{
public:
// construction/casting
SignedInt_t() :Value(0),Negative(0) {}
SignedInt_t(const SignedInt_t &orig):Value(orig.Value),Negative(orig.Negative) {}
SignedInt_t(const BaseIntT &orig):Value(orig),Negative(0) {}
SignedInt_t(const int64 &orig):Value(orig),Negative(0) { if (orig<0) { Negative=1; Value^=BaseIntT(-1); Value+=BaseIntT(1);}} //ugly!
// assignment
SignedInt_t &operator= (const SignedInt_t &rhs) {Value=rhs.Value; Negative=rhs.Negative; return *this;}
// compariston (some of thse operators could use a little teaking for efficiency)
bool operator==(const SignedInt_t &rhs) { if ((Value==rhs.Value) && (Negative==rhs.Negative)) return true; return false;}
bool operator!=(const SignedInt_t &rhs) { if ((Value==rhs.Value) && (Negative==rhs.Negative)) return false; return true;}
bool operator>=(const SignedInt_t &rhs) { if ((Negative==1) && (rhs.Negative==1)) { if (Value<=rhs.Value) { return true; } return false; }
else if ((Negative==0) && (rhs.Negative==0)) { if (Value>=rhs.Value) { return true; } return false; }
else if (Negative==1) { return false; } else { return true; } return false; }
bool operator<=(const SignedInt_t &rhs) { if (*this==rhs) return true; else if (*this>=rhs) return false; else return true;}
bool operator> (const SignedInt_t &rhs) { if (*this==rhs) return false; else return (*this>=rhs);}
bool operator< (const SignedInt_t &rhs) { if (*this==rhs) return false; else return !(*this>=rhs);}
// operations (these are exported for user use), many of these operations are "wierd" because they don't affect the sign aka shift and bit instructions maintain signage
SignedInt_t &operator>>=(const int rhs) { Value>>=rhs; return *this;}
SignedInt_t &operator<<=(const int rhs) { Value<<=rhs; return *this;}
SignedInt_t &operator-=( const SignedInt_t &rhs) { SubDouble(this,rhs,0); return *this;}
SignedInt_t &operator+=( const SignedInt_t &rhs) { AddDouble(this,rhs,0); return *this;}
SignedInt_t &operator*=( const SignedInt_t &rhs) { MultiplyDouble(this,rhs); return *this;}
SignedInt_t &operator/=( const SignedInt_t &rhs) { DivideDouble(this,rhs); return *this;}
SignedInt_t &operator&=( const int64 &rhs) { Value&=rhs; return *this;}
SignedInt_t &operator|=( const int64 &rhs) { Value|=rhs; return *this;}
SignedInt_t &operator^=( const int64 &rhs) { Value^=rhs; return *this;}
SignedInt_t &operator&=( const SignedInt_t &rhs) { Value&=rhs.Value; return *this;}
SignedInt_t &operator|=( const SignedInt_t &rhs) { Value|=rhs.Value; return *this;}
SignedInt_t &operator^=( const SignedInt_t &rhs) { Value^=rhs.Value; return *this;}
SignedInt_t operator+( const SignedInt_t &rhs) { SignedInt_t tmp=*this; AddDouble(&tmp,rhs,0); return tmp;}
SignedInt_t operator-( const SignedInt_t &rhs) { SignedInt_t tmp=*this; SubDouble(&tmp,rhs,0); return tmp;}
SignedInt_t operator/( const SignedInt_t &rhs) { SignedInt_t tmp=*this; DivideDouble(&tmp,rhs); return tmp;}
SignedInt_t operator*( const SignedInt_t &rhs) { SignedInt_t tmp=*this; MultiplyDouble(&tmp,rhs); return tmp;}
SignedInt_t operator&( const int64 &rhs) { SignedInt_t tmp=*this; tmp.Value&=rhs; return tmp;}
SignedInt_t operator|( const int64 &rhs) { SignedInt_t tmp=*this; tmp.Value|=rhs; return tmp;}
SignedInt_t operator^( const int64 &rhs) { SignedInt_t tmp=*this; tmp.Value^=rhs; return tmp;}
SignedInt_t operator>>( const int &rhs) { SignedInt_t tmp=*this; tmp>>=rhs; return tmp;}
SignedInt_t operator<<( const int &rhs) { SignedInt_t tmp=*this; tmp<<=rhs; return tmp;}
// the following pretty much the same as above, in both cases we are in temp hell
// consider overridding printf until then use AsString
//string AsString(const SignedInt_t &Value,char *format);
string AsString(const char *format) { string ret=Value.AsString(format); if (Negative) ret.insert(0,"-"); return ret;}
void FromString(const char *Source_prm);
char GetLowByte() {return Value.GetLowByte();}
// protected:
// these operations are exported for higher level use
// they don't use the this variable...
static int SubDouble(SignedInt_t *A,const SignedInt_t &B,const int borrow);
static int AddDouble(SignedInt_t *A,const SignedInt_t &B,const int carry);
static SignedInt_t DivideDouble(SignedInt_t *A,const SignedInt_t &B);
static SignedInt_t MultiplyDouble(SignedInt_t *A,const SignedInt_t &B);
static int shiftleft(SignedInt_t *Value_prm,const int Carry_prm) { return shiftleft(Value_prm->Value,Carry_prm);}
static int shiftright(SignedInt_t *Value_prm,const int Carry_prm) { return shiftright(Value_prm->Value,Carry_prm);}
// private:
BaseIntT Value;
int Negative;
};
template<class BaseIntT> int DoubleInt_t<BaseIntT>::SubDouble(DoubleInt_t *A,const DoubleInt_t &B,const int borrow)
{
int ret_borrow;
ret_borrow=BaseIntT::SubDouble(&A->Lo,B.Lo,borrow);
ret_borrow=BaseIntT::SubDouble(&A->Hi,B.Hi,ret_borrow);
return ret_borrow;
}
//
//
// The DoubleInt_t methods
//
//
//
template<class BaseIntT> int DoubleInt_t<BaseIntT>::AddDouble(DoubleInt_t *A,const DoubleInt_t &B,const int carry)
{
int carry_ret=0;
carry_ret=BaseIntT::AddDouble(&A->Lo,B.Lo,carry);
carry_ret=BaseIntT::AddDouble(&A->Hi,B.Hi,carry_ret);
return carry_ret;
}
template<class BaseIntT> DoubleInt_t<BaseIntT> DoubleInt_t<BaseIntT>::MultiplyDouble(DoubleInt_t *A,const DoubleInt_t &B)
{
DoubleInt_t ret;
BaseIntT tmp=0;
BaseIntT col3=0;
// a 128 bit multiply works like when you were in grade school except that instead of the max value per column being
// a 9 the max value is 2^64.
// ab
//* cd
//------
// bd
// ad
// bc
//+ac
//-------
// wxyz
BaseIntT a=A->Hi;
BaseIntT b=A->Lo;
BaseIntT c=B.Hi;
BaseIntT d=B.Lo;
BaseIntT w=0;
BaseIntT x=0;
BaseIntT y=0;
BaseIntT z=0;
int carry=0;
int carry2=0;
BaseIntT xp=0;
y=BaseIntT::MultiplyDouble(&b,d);
z=b; b=A->Lo;
x=BaseIntT::MultiplyDouble(&a,d);
carry=BaseIntT::AddDouble(&y,a,0);// y+=a;
a=A->Hi;
xp=BaseIntT::MultiplyDouble(&b,c);
carry=BaseIntT::AddDouble(&x,xp,carry); //x+=xp+carry;
carry2=BaseIntT::AddDouble(&y,b,0); //y+=b;
w=BaseIntT::MultiplyDouble(&a,c);
carry2=BaseIntT::AddDouble(&x,a,carry2);//x+=a;
// final w fixup
BaseIntT longcarry=carry2;
BaseIntT::AddDouble(&w,longcarry,carry2);
A->Lo=z;
A->Hi=y;
ret.Lo=x;
ret.Hi=w;
return ret;
}
template<class BaseIntT> int DoubleInt_t<BaseIntT>::shiftright(DoubleInt_t *Value,const int Carry_prm)
{
int carry_ret;
carry_ret=BaseIntT::shiftright(&Value->Hi,Carry_prm);
carry_ret=BaseIntT::shiftright(&Value->Lo,carry_ret);
return carry_ret;
}
template<class BaseIntT> int DoubleInt_t<BaseIntT>::shiftleft(DoubleInt_t *Value,const int Carry_prm)
{
int carry_ret;
carry_ret=BaseIntT::shiftleft(&Value->Lo,Carry_prm);
carry_ret=BaseIntT::shiftleft(&Value->Hi,carry_ret);
return carry_ret;
}
template<class BaseIntT> DoubleInt_t<BaseIntT> DoubleInt_t<BaseIntT>::DivideDouble(DoubleInt_t *A,const DoubleInt_t &B)
{
DoubleInt_t quotient=*A;
DoubleInt_t remainder;//==0
if ((DoubleInt_t)(B)==0) //TODO: fix this const mess
{
throw "division by zero";
}
for (int x=0;x<A->size;x++)
{
int hibit=shiftleft("ient,0);
shiftleft(&remainder,hibit);
if (remainder>=B)
{
SubDouble(&remainder,B,0); //remainder-=*B;
quotient.Lo|=1; //quotient|=1;
}
}
*A=quotient;
return remainder;
}
template<class BaseIntT> string DoubleInt_t<BaseIntT>::AsString(const char *format)
{
string ret;
switch (format[1])
{
case 'd':
{
char temp[2];
DoubleInt_t tmp;
int x=0;
tmp=*this;
if (tmp==0)
{
ret="0";
}
else
{
ret="";
temp[1]='\0';
while (tmp!=0)
{
DoubleInt_t remainder=DivideDouble(&tmp,DoubleInt_t(10)); //TODO: convert to something a little faster...
temp[0]=remainder.GetLowByte()+'0';
ret.insert(0,string(temp));
}
}
}
break;
case 'b':
{
DoubleInt_t tmp;
int x=0;
tmp=*this;
char temp[tmp.size+2];
for (int x=0;x<tmp.size;x++)
{
temp[x]=tmp.GetLowByte()&0x01+'0';
shiftright(&tmp,0);
}
temp[tmp.size]='\0';
ret=temp;
}
break;
case 'X':
case 'x':
{
DoubleInt_t tmp;
tmp=*this;
char *temp=new char[(tmp.size>>2)+2];
temp[(tmp.size>>2)]=0;
for (int x=(tmp.size>>2)-1;x>=0;x--)
{
temp[x]=(tmp.Lo).GetLowByte()&0xF;
if (temp[x]>0x9)
{
temp[x]+='A'-10;
}
else
{
temp[x]+='0';
}
shiftright(&tmp,0);
shiftright(&tmp,0);
shiftright(&tmp,0);
shiftright(&tmp,0);
}
ret=temp;
delete temp;
}
break;
}
return ret;
}
// takes the value as a base 10 or base 16 string and converts it to the big integer type
template<class BaseIntT> void DoubleInt_t<BaseIntT>::FromString(const char *Source_prm)
{
int start=0;
int base=10;
Hi=Lo=0;
while (Source_prm[start]!='\0')
{
if (Source_prm[start]=='0')
{
if (Source_prm[start+1]=='x')
{
base=16;
start+=2;
}
break;
}
if ((Source_prm[start]>='0') && (Source_prm[start]<='9'))
{
break;
}
start++;
}
// ok we found the beginning of the string..
if (base==10)
{
DoubleInt_t multconst(10);
while ((Source_prm[start]<='9') && (Source_prm[start]>='0'))
{
char tmp=Source_prm[start]-'0';
MultiplyDouble(this,multconst);
AddDouble(this,DoubleInt_t(tmp),0);
start++;
}
}
else
{
char upper=toupper(Source_prm[start]);
while (((upper<='9') && (upper>='0')) || ((upper>='A') && (upper<='F')))
{
char tmp;
if (upper<='9')
{
tmp=upper-'0';
}
else
{
tmp=upper-'A';
}
shiftleft(this,0);
shiftleft(this,0);
shiftleft(this,0);
shiftleft(this,0);
Lo|=int64(tmp);
start++;
upper=toupper(Source_prm[start]);
}
}
}
template<class BaseIntT> int SignedInt_t<BaseIntT>::AddDouble(SignedInt_t *A,const SignedInt_t &B,const int carry)
{
if (carry!=0)
{
throw "non zero carry passed to SignedInt add";
}
if (A->Negative==B.Negative) //same sign.. just add them, don't modify the sign
{
return BaseIntT::AddDouble(&A->Value,B.Value,carry);
}
else
{
// ok now here is the fun with non two complement numbers
// first detect which one has the larger magnitude
if (A->Value>B.Value)
{
//A will maintain its sign, but subtract B from A
if (BaseIntT::SubDouble(&A->Value,B.Value,0)!=0)
{
throw "borrow nessisary during add!"; //probably a bug...
}
return 0; //there shouldn't be a carry in this case
}
else
{
if (A->Value==B.Value)
{
//rare shortcut....
A->Value=0;
A->Negative=0;
return 0;
}
else // (B.Value>A.Value)
{
//A will have B's Sign..
// this is a lot sucky...
BaseIntT tmp=A->Value;
A->Value=B.Value;
if (BaseIntT::SubDouble(&A->Value,tmp,0)!=0)
{
throw "borrow nessisary during add!"; //probably a bug...
}
A->Negative=B.Negative;
return 0; //there shouldn't be a carry in this case
}
}
}
}
// flip the sign of A and add them...
template<class BaseIntT> int SignedInt_t<BaseIntT>::SubDouble(SignedInt_t *A,const SignedInt_t &B,const int borrow)
{
A->Negative^=1; //negate the sign with xor <chuckle>
return AddDouble(A,B,0);
}
//TODO make a finalizer class which sits between this class and the double template and throws overflow exceptions...
template<class BaseIntT> SignedInt_t<BaseIntT> SignedInt_t<BaseIntT>::MultiplyDouble(SignedInt_t *A,const SignedInt_t &B)
{
BaseIntT::MultiplyDouble(&A->Value,B.Value);
if (A->Value==0)
{
A->Negative=0;
}
else
{
A->Negative^=B.Negative; //flip sign as nessiary
}
}
template<class BaseIntT> SignedInt_t<BaseIntT> SignedInt_t<BaseIntT>::DivideDouble(SignedInt_t *A,const SignedInt_t &B)
{
SignedInt_t tmp;
tmp.Value=BaseIntT::DivideDouble(&A->Value,B.Value);
if (A->Value==0)
{
A->Negative=0;
}
else
{
A->Negative^=B.Negative; //flip sign as nessiary
}
return tmp.Value;
}
template<class BaseIntT> void SignedInt_t<BaseIntT>::FromString(const char *Source_prm)
{
int start=0;
Negative=0;
while (Source_prm[start]!='\0')
{
if (Source_prm[start]=='0')
{
if (Source_prm[start+1]=='x')
{
// hex start
Value.FromString(&Source_prm[start]);
break;
}
}
if ((Source_prm[start]>='0') && (Source_prm[start]<='9'))
{
// normal decimal start
Value.FromString(&Source_prm[start]);
break;
}
if (Source_prm[start]=='-')
{
Negative=1;
}
start++;
}
if (Source_prm[start]=='\0')
{
Value=0;
}
}
#endif // DOUBLEINT_T_HPP
| 37.896226 | 176 | 0.604141 | jlinton |
cdf81102fac6668ce226adff31a8cfefe0ff79fa | 3,676 | cpp | C++ | src/Broadcaster2006/OnAir/ComercialWnd.cpp | pedroroque/DigitalBroadcaster | 279e65b348421dcd8db53ebb588154b85dc169e9 | [
"MIT"
] | null | null | null | src/Broadcaster2006/OnAir/ComercialWnd.cpp | pedroroque/DigitalBroadcaster | 279e65b348421dcd8db53ebb588154b85dc169e9 | [
"MIT"
] | null | null | null | src/Broadcaster2006/OnAir/ComercialWnd.cpp | pedroroque/DigitalBroadcaster | 279e65b348421dcd8db53ebb588154b85dc169e9 | [
"MIT"
] | null | null | null | // ComercialWnd.cpp : implementation file
//
#include "stdafx.h"
#include "OnAir.h"
#include "ComercialWnd.h"
#include "ExternalObjects.h"
#include "OnAirUtils.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CComercialWnd
#define ID_SELECTION 1001
CComercialWnd::CComercialWnd()
{
}
CComercialWnd::~CComercialWnd()
{
}
BEGIN_MESSAGE_MAP(CComercialWnd, CFrameWnd)
//{{AFX_MSG_MAP(CComercialWnd)
ON_WM_PAINT()
ON_WM_CREATE()
ON_WM_KEYUP()
ON_WM_SYSKEYUP()
ON_WM_SYSCOMMAND()
ON_CBN_SELCHANGE( ID_SELECTION,OnSelChange )
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CComercialWnd message handlers
void CComercialWnd::OnPaint()
{
CPaintDC dc(this); // device context for painting
CRect rect;
GetClientRect(&rect);
dc.FillRect(&rect,&CBrush(GetSysColor(COLOR_3DFACE)));
}
int CComercialWnd::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
CRect rect;
GetClientRect(&rect);
m_ctrlSelection = new CComboBoxEx();
m_ctrlSelection->Create(CBS_DROPDOWNLIST|WS_VISIBLE,CRect(rect.left+20,rect.top+2,rect.right-1,rect.top+402),this,ID_SELECTION);
m_ctrlSelection->SetFont(g_cfont24);
m_ctrlSelection->SetImageList(g_ilContainer);
CString str;
str.LoadString(IDS_TRAFFIC_SPONSORS);
COMBOBOXEXITEM cbItem;
cbItem.mask=CBEIF_IMAGE|CBEIF_SELECTEDIMAGE|CBEIF_INDENT|CBEIF_LPARAM|CBEIF_TEXT;
cbItem.iItem=0;
cbItem.pszText=str.GetBuffer(0);
cbItem.cchTextMax=20;
cbItem.iImage=4;
cbItem.iSelectedImage=4;
cbItem.iIndent=0;
cbItem.lParam=CONTAINER_TRAFFIC_SPONSORS;
m_ctrlSelection->InsertItem(&cbItem);
str.LoadString(IDS_TRAFFIC_BLOCKS);
cbItem.pszText=str.GetBuffer(0);
cbItem.iItem=1;
cbItem.iImage=9;
cbItem.iSelectedImage=9;
cbItem.lParam=CONTAINER_TRAFFIC_SCREENS;
m_ctrlSelection->InsertItem(&cbItem);
str.LoadString(IDS_TRAFFIC_BUMPED);
cbItem.pszText=str.GetBuffer(0);
cbItem.iItem=2;
cbItem.iImage=14;
cbItem.iSelectedImage=14;
cbItem.lParam=CONTAINER_TRAFFIC_DELAYED;
m_ctrlSelection->InsertItem(&cbItem);
m_ctrlSelection->SetCurSel(0);
//////////////////////////////////////////////////////////////////////////////
// Child window Creation
// Get the window rect
GetWindowRect(&rect);
rect.DeflateRect(0,40,0,0);
// Sponsors window
m_wndSponsors = new CSponsorsWnd();
m_wndSponsors->Create(NULL,NULL,WS_VISIBLE|WS_POPUP,rect,this,0);
// Blocks window
m_wndBlocks = new CBlocksWnd();
m_wndBlocks->Create(NULL,NULL,WS_VISIBLE|WS_POPUP,rect,this,0);
// Bumped Windows
m_wndBumped = new CTrafficBumpedWnd();
m_wndBumped->Create(NULL,NULL,WS_VISIBLE|WS_POPUP,rect,this,0);
// Make sure the sponsor window is on top
m_wndSponsors->BringWindowToTop();
return 0;
}
void CComercialWnd::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags)
{
if( !CheckKey(nChar) )
CFrameWnd::OnKeyUp(nChar, nRepCnt, nFlags);
}
void CComercialWnd::OnSysKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags)
{
if( !CheckKey(nChar) )
CFrameWnd::OnSysKeyUp(nChar, nRepCnt, nFlags);
}
void CComercialWnd::OnSysCommand(UINT nID, LPARAM lParam)
{
}
void CComercialWnd::OnSelChange()
{
long int nSel=m_ctrlSelection->GetCurSel();
if( nSel==CB_ERR )
return;
LPARAM lID= m_ctrlSelection->GetItemData(nSel);
switch( lID )
{
case CONTAINER_TRAFFIC_SPONSORS:
m_wndSponsors->BringWindowToTop();
break;
case CONTAINER_TRAFFIC_SCREENS:
m_wndBlocks->BringWindowToTop();
break;
case CONTAINER_TRAFFIC_DELAYED:
m_wndBumped->BringWindowToTop();
break;
}
}
| 22.832298 | 129 | 0.715996 | pedroroque |
cdf937b7f8c26ab46651077cd53e332d416bfd0d | 12,392 | cpp | C++ | src/map2gtf.cpp | infphilo/tophat | 37540ce3f0c10e0f0bfafa2f29450055fc5da384 | [
"BSL-1.0"
] | 113 | 2015-04-07T13:21:43.000Z | 2021-08-20T01:52:43.000Z | src/map2gtf.cpp | infphilo/tophat | 37540ce3f0c10e0f0bfafa2f29450055fc5da384 | [
"BSL-1.0"
] | 47 | 2015-04-09T09:37:59.000Z | 2018-12-12T11:49:30.000Z | src/map2gtf.cpp | infphilo/tophat | 37540ce3f0c10e0f0bfafa2f29450055fc5da384 | [
"BSL-1.0"
] | 59 | 2015-04-01T13:48:59.000Z | 2021-11-15T09:27:30.000Z | /*
* Author: Harold Pimentel
* Contact: http://cs.berkeley.edu/~pimentel
* Date: June 10, 2011
*/
#include "map2gtf.h"
#include "tokenize.h"
void m2g_print_usage()
{
std::cerr << "Usage: map2gtf annotation.tlst "
<< "alignments.bam out_file.bam" << std::endl;
}
void tline_parserr(const std::string& tline, std::string add="") {
std::cerr << "Error at parsing .tlst line " << add << ":"
<< std::endl << '\t' << tline << std::endl;
exit(1);
}
GffTranscript::GffTranscript(const std::string& tline): exons(1),
numID(-1), gffID(), refID(), strand(0) {
std::istringstream f(tline);
std::string token;
std::vector<std::string> tokens;
while (std::getline(f, token, ' ')) {
tokens.push_back(token);
}
if (tokens.size()!=4) {
tline_parserr(tline);
}
numID=atoi(tokens[0].c_str());
gffID=tokens[1];
refID=tokens[2];
if (refID.length()<1) {
tline_parserr(tline, "(refID empty)");
}
strand=refID[refID.length()-1];
if (strand!='-' && strand!='+') {
tline_parserr(tline, "(invalid strand)");
}
refID.erase(refID.length()-1);
f.clear(); //to reset the std::getline() iterator
f.str(tokens[3]);
while (std::getline(f, token, ',')) {
size_t sp_pos=token.find('-');
if (sp_pos == std::string::npos) {
std::string s("(invalid exon str: ");
s+=token;s+=")";
tline_parserr(tline, s);
}
std::string s_start=token.substr(0,sp_pos);
std::string s_end=token.substr(sp_pos+1);
GSeg exon(atoi(s_start.c_str()), atoi(s_end.c_str()));
if (exon.start==0 || exon.end==0 || exon.end<exon.start) {
std::string s("(invalid exon: ");
s+=token;s+=")";
tline_parserr(tline, s);
}
if (start==0 || start>exon.start) start=exon.start;
if (end==0 || end<exon.end) end=exon.end;
exons.Add(exon);
} //while exons
}
Map2GTF::Map2GTF(const std::string& gtf_fname, const std::string& in_fname) :
gtf_fname_(gtf_fname), in_fname_(in_fname), out_sam_header_(NULL), refSeqTable_(true)
{
tlststream.open(gtf_fname_.c_str(), std::ios::in);
if (!tlststream.good())
{
std::cerr << "FATAL: Couldn't open transcript data: " << gtf_fname_ << std::endl;
exit(1);
}
std::ios::sync_with_stdio(false);
if (in_fname_=="-") {
in_fhandle_=samopen(in_fname_.c_str(), "rbu", 0);
}
else {
in_fhandle_=samopen(in_fname_.c_str(), "rb", 0);
}
if (in_fhandle_ == NULL)
{
std::cerr << "FATAL: Couldn't open input bam file: " << in_fname_ << std::endl;
exit(1);
}
in_sam_header_ = in_fhandle_->header;
std::cout << "Reading the transcript data: " << gtf_fname_ << std::endl;
std::string tline;
while (std::getline(tlststream, tline)) {
if (tline.length()>4) {
GffTranscript* t=new GffTranscript(tline);
transcripts.Add(t);
tidx_to_t[t->numID]=t;
}
}
tlststream.close();
std::cout << "Transcript data loaded." << std::endl;
}
Map2GTF::~Map2GTF()
{
std::cout << "map2gtf has completed. Cleaning up." << std::endl;
if (in_fhandle_ != NULL)
{
samclose(in_fhandle_);
}
std::cout << "Done. Thanks!" << std::endl;
}
//
bool Map2GTF::next_read_hits(vector<bam1_t*>& hits, size_t& num_hits, long& read_id)
{
if (hits.size() > num_hits)
{
bam1_t* temp = hits[num_hits];
hits[num_hits] = hits.front();
hits.front() = temp;
num_hits = 1;
char* name = bam1_qname(hits.front());
read_id = atol(name);
}
else
num_hits = 0;
while (true)
{
bam1_t* hit = NULL;
if (num_hits >= hits.size())
hits.push_back(bam_init1());
hit = hits[num_hits];
if (samread(in_fhandle_, hit) <= 0)
{
for (size_t i = num_hits; i < hits.size(); ++i)
bam_destroy1(hits[i]);
hits.erase(hits.begin() + num_hits, hits.end());
break;
}
char* name = bam1_qname(hit);
long temp_read_id = atol(name);
if (num_hits == 0)
{
read_id = temp_read_id;
}
else if (read_id != temp_read_id)
{
break;
}
++num_hits;
}
return num_hits > 0;
}
void Map2GTF::convert_coords(const std::string& out_fname, const std::string& sam_header)
{
samfile_t* out_sam_header_file = samopen(sam_header.c_str(), "r", 0);
if (out_sam_header_file == NULL)
std::cerr << "Error opening sam header: " << sam_header << std::endl;
out_sam_header_ = out_sam_header_file->header;
string index_out_fname = out_fname + ".index";
GBamWriter bam_writer(out_fname.c_str(), out_sam_header_, index_out_fname);
ref_to_id_.clear();
for (int i = 0; i < out_sam_header_->n_targets; ++i)
{
ref_to_id_[out_sam_header_->target_name[i]] = i;
}
std::vector<TranscriptomeHit> read_list;
//GffObj* p_trans = NULL;
GffTranscript* p_trans = NULL;
HitsForRead hit_group;
std::vector<TranscriptomeHit>::iterator bh_it;
std::vector<TranscriptomeHit>::iterator bh_unique_it;
BowtieHit bwt_hit;
vector<bam1_t*> hits;
size_t num_hits = 0;
long read_id = 0;
// a hit group is a set of reads with the same name
while (next_read_hits(hits, num_hits, read_id))
{
for (size_t i = 0; i < num_hits; ++i)
{
bam1_t* hit = hits[i];
const char* target_name = in_sam_header_->target_name[hit->core.tid];
int trans_idx = atoi(target_name);
//p_trans = gtfReader_.gflst.Get(trans_idx);
p_trans = tidx_to_t[trans_idx];
TranscriptomeHit converted_out(hit, p_trans);
bool success = trans_to_genomic_coords(converted_out);
if (success)
read_list.push_back(converted_out);
}
// XXX: Fine for now... should come up with a more efficient way though
// FIXME: Take frag length into consideration when filtering
std::sort(read_list.begin(), read_list.end());
bh_unique_it = std::unique(read_list.begin(), read_list.end());
for (bh_it = read_list.begin(); bh_it != bh_unique_it; ++bh_it)
{
bam_writer.write(bh_it->hit, read_id);
}
read_list.clear();
}
for (size_t i = 0; i < hits.size(); ++i)
{
bam_destroy1(hits[i]);
}
hits.clear();
}
bool Map2GTF::trans_to_genomic_coords(TranscriptomeHit& hit)
//out.trans must already have the corresponding GffObj*
{
// read start in genomic coords
size_t read_start = 0;
//GList<GffExon>& exon_list = hit.trans->exons;
GVec<GSeg>& exon_list = hit.trans->exons;
//GffExon* cur_exon;
//GffExon* next_exon;
GSeg* next_exon=NULL;
int cur_pos;
int match_length;
int miss_length;
int cur_intron_len = 0;
int i = 0;
static const int MAX_CIGARS = 1024;
int cigars[MAX_CIGARS];
int num_cigars = 0;
// TODO: Check this return value
bool ret_val = get_read_start(exon_list, hit.hit->core.pos, read_start, i);
if (!ret_val)
{
}
cur_pos = read_start;
for (int c = 0; c < hit.hit->core.n_cigar; ++c)
{
int opcode = bam1_cigar(hit.hit)[c] & BAM_CIGAR_MASK;
int length = bam1_cigar(hit.hit)[c] >> BAM_CIGAR_SHIFT;
if (opcode == BAM_CINS)
{
cigars[num_cigars] = opcode | (length << BAM_CIGAR_SHIFT);
++num_cigars;
}
if (opcode != BAM_CMATCH && opcode != BAM_CDEL)
continue;
int remaining_length = length;
for (; i < exon_list.Count(); ++i)
{
GSeg& cur_exon = exon_list[i];
if (cur_pos >= (int)cur_exon.start &&
cur_pos + remaining_length - 1 <= (int)cur_exon.end) // read ends in this exon
{
cigars[num_cigars] = opcode | (remaining_length << BAM_CIGAR_SHIFT);
++num_cigars;
cur_pos += remaining_length;
break;
}
// shouldn't need the check... can switch to a regular "else"
else if (cur_pos >= (int)cur_exon.start &&
cur_pos + remaining_length - 1 > (int)cur_exon.end)// read is spliced and overlaps this exon
{
// XXX: This should _never_ go out of range.
// get the max length that fits in this exon, go to next exon
// cur_pos should be the next exon start
// set assertion to check this
// TODO: check this
match_length = (int)cur_exon.end - cur_pos + 1;
if (match_length > 0)
{
cigars[num_cigars] = opcode | (match_length << BAM_CIGAR_SHIFT);
++num_cigars;
}
// XXX: DEBUG
if (i + 1 >= exon_list.Count())
{
std::cerr << "trying to access: " << i + 2 << " when size is: "
<< exon_list.Count() << std::endl;
print_trans(hit.trans, hit.hit, remaining_length, match_length, cur_pos,
read_start);
return false;
}
else
next_exon = & (exon_list[i + 1]);
// and this
miss_length = next_exon->start - cur_exon.end - 1;
cur_intron_len += miss_length;
cigars[num_cigars] = BAM_CREF_SKIP | (miss_length << BAM_CIGAR_SHIFT);
++num_cigars;
cur_pos += match_length + miss_length;
remaining_length -= match_length;
assert(cur_pos == (int)next_exon->start);
}
}
}
hit.hit->core.tid = ref_to_id_[hit.trans->getRefName()];
hit.hit->core.pos = read_start - 1;
hit.hit->core.flag &= ~BAM_FSECONDARY;
int old_n_cigar = hit.hit->core.n_cigar;
if (num_cigars != old_n_cigar)
{
int data_len = hit.hit->data_len + 4 * (num_cigars - old_n_cigar);
int m_data = max(data_len, hit.hit->m_data);
kroundup32(m_data);
uint8_t* data = (uint8_t*)calloc(m_data, 1);
int copy1_len = (uint8_t*)bam1_cigar(hit.hit) - hit.hit->data;
memcpy(data, hit.hit->data, copy1_len);
int copy2_len = num_cigars * 4;
memcpy(data + copy1_len, cigars, copy2_len);
int copy3_len = hit.hit->data_len - copy1_len - (old_n_cigar * 4);
memcpy(data + copy1_len + copy2_len, bam1_seq(hit.hit), copy3_len);
hit.hit->core.n_cigar = num_cigars;
free(hit.hit->data);
hit.hit->data = data;
hit.hit->data_len = data_len;
hit.hit->m_data = m_data;
}
char strand = hit.trans->strand;
uint8_t* ptr = bam_aux_get(hit.hit, "XS");
if (ptr)
bam_aux_del(hit.hit, ptr);
if (strand == '+' || strand == '-')
bam_aux_append(hit.hit, "XS", 'A', 1, (uint8_t*)&strand);
return true;
}
void print_trans(GffTranscript* trans, const bam1_t* in, size_t rem_len,
size_t match_len, size_t cur_pos, size_t start_pos)
{
GSeg* p_exon;
std::cerr << "\tCur_pos: " << cur_pos << " remaining: " << rem_len
<< " match_len: " << match_len << std::endl;
std::cerr << "\tTranscript:\t" << trans->start << "\t" << trans->end
<< std::endl;
for (int i = 0; i < trans->exons.Count(); ++i)
{
p_exon = & (trans->exons[i]);
std::cerr << "\t\t" << p_exon->start << "\t" << p_exon->end
<< std::endl;
}
std::cerr << std::endl;
std::cerr << "Read_id: " << bam1_qname(in) << std::endl;
std::cerr << "\tgff_start: " << in->core.pos << "\tgenome_start: "
<< start_pos << std::endl;
}
// Returns false if not in this exon list
//bool get_read_start(GList<GffExon>* exon_list, size_t gtf_start,
bool get_read_start(GVec<GSeg>& exon_list, size_t gtf_start,
size_t& genome_start, int& exon_idx)
{
//GffExon* cur_exon;
const GSeg* cur_exon;
size_t cur_intron_dist = 0;
//size_t trans_start = exon_list->First()->start;
size_t trans_start = exon_list[0].start;
int trans_offset = 0;
for (int i = 0; i < exon_list.Count(); ++i)
{
//cur_exon = exon_list->Get(i);
cur_exon = & (exon_list[i]);
trans_offset = trans_start + cur_intron_dist;
if (gtf_start >= cur_exon->start - trans_offset && gtf_start
<= cur_exon->end - trans_offset)
{
genome_start = gtf_start + trans_start + cur_intron_dist;
exon_idx = i;
return true;
}
else
{
if (i + 1 < exon_list.Count())
//cur_intron_dist += exon_list->Get(i + 1)->start - cur_exon->end - 1;
cur_intron_dist += exon_list[i + 1].start - cur_exon->end - 1;
else
return false;
}
}
return false;
}
int main(int argc, char *argv[])
{
int parse_ret = parse_options(argc, argv, m2g_print_usage);
if (parse_ret)
return parse_ret;
if (optind >= argc)
{
m2g_print_usage();
return 1;
}
std::string gtf_file(argv[optind++]);
std::string in_fname(argv[optind++]);
std::string out_fname(argv[optind++]);
if (gtf_file == "" || in_fname == "" || out_fname == "")
{
m2g_print_usage();
exit(1);
}
Map2GTF gtfMapper(gtf_file, in_fname);
gtfMapper.convert_coords(out_fname, sam_header);
return 0;
}
| 26.997821 | 96 | 0.617172 | infphilo |
a8007606839f98a50fb9df66f5e184f1252da6c0 | 10,063 | cpp | C++ | arduino/opencr_arduino/opencr/libraries/SPI/SPI.cpp | yemiaobing/opencr | 8700d276f60cb72db4f1ed85deff26a5f96ce7b6 | [
"Apache-2.0"
] | 2 | 2021-04-27T17:09:19.000Z | 2021-04-27T17:09:24.000Z | arduino/opencr_arduino/opencr/libraries/SPI/SPI.cpp | yemiaobing/opencr | 8700d276f60cb72db4f1ed85deff26a5f96ce7b6 | [
"Apache-2.0"
] | null | null | null | arduino/opencr_arduino/opencr/libraries/SPI/SPI.cpp | yemiaobing/opencr | 8700d276f60cb72db4f1ed85deff26a5f96ce7b6 | [
"Apache-2.0"
] | 1 | 2019-02-03T04:49:15.000Z | 2019-02-03T04:49:15.000Z | /****************************************************************************
*
* SPI Master library for Arduino STM32 + HAL + CubeMX (HALMX).
*
* Copyright (c) 2016 by Vassilis Serasidis <info@serasidis.gr>
* Home: http://www.serasidis.gr
* email: avrsite@yahoo.gr
*
* Arduino_STM32 forum: http://www.stm32duino.com
*
* This file is free software; you can redistribute it and/or modify
* it under the terms of either the GNU General Public License version 2
* or the GNU Lesser General Public License version 2.1, both as
* published by the Free Software Foundation.
*
****************************************************************************/
#include <SPI.h>
#include <chip.h>
/* Create an SPIClass instance */
SPIClass SPI (SPI2, 50000000);
SPIClass SPI_IMU(SPI1, 100000000);
SPIClass SPI_EXT(SPI4, 100000000);
SPIClass::SPIClass(SPI_TypeDef *spiPort, uint32_t spi_clock) {
_spiPort = spiPort;
if(spiPort == SPI1)
_hspi = &hspi1;
else if(spiPort == SPI2)
_hspi = &hspi2;
else if(spiPort == SPI4)
_hspi = &hspi4;
_spi_clock = spi_clock;
}
/**
* This constructor is written for backward compatibility with Arduino_STM32
* @Usage example: SPIClass my_spi(2) for using the SPI2 interface
*/
SPIClass::SPIClass(uint8_t spiPort){
switch(spiPort){
case 1:
_spiPort = SPI1;
_hspi = &hspi1;
break;
case 2:
_spiPort = SPI2;
_hspi = &hspi2;
break;
case 4:
_spiPort = SPI4;
_hspi = &hspi4;
break;
}
}
void SPIClass::begin(void) {
init();
}
void SPIClass::beginFast(void) {
drv_spi_enable_dma(_hspi);
init();
}
void SPIClass::init(void){
// Keep track of transaction logical values.
//_clockDiv = SPI_CLOCK_DIV16;
_bitOrder = MSBFIRST;
_dataMode = SPI_MODE0;
_dma_state = DMA_NOTINITIALIZED;
_dma_event_responder = NULL;
_hspi->Instance = _spiPort;
_hspi->Init.Mode = SPI_MODE_MASTER;
_hspi->Init.Direction = SPI_DIRECTION_2LINES;
_hspi->Init.DataSize = SPI_DATASIZE_8BIT;
_hspi->Init.CLKPolarity = SPI_POLARITY_LOW;
_hspi->Init.CLKPhase = SPI_PHASE_1EDGE;
_hspi->Init.NSS = SPI_NSS_SOFT;
_hspi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16; // 4.5 Mbit
_hspi->Init.FirstBit = SPI_FIRSTBIT_MSB;
_hspi->Init.TIMode = SPI_TIMODE_DISABLE;
_hspi->Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
_hspi->Init.CRCPolynomial = 10;
HAL_SPI_Init(_hspi);
}
uint8_t SPIClass::transfer(uint8_t data) const{
uint8_t ret;
HAL_SPI_TransmitReceive(_hspi, &data, &ret, 1, 0xffff);
return ret;
}
uint16_t SPIClass::transfer16(uint16_t data) {
uint8_t tBuf[2];
uint8_t rBuf[2];
uint16_t ret;
tBuf[1] = (uint8_t)data;
tBuf[0] = (uint8_t)(data>>8);
HAL_SPI_TransmitReceive(_hspi, (uint8_t *)&tBuf, (uint8_t *)&rBuf, 2, 0xffff);
ret = rBuf[0];
ret <<= 8;
ret += rBuf[1];
return ret;
}
void SPIClass::transfer(const void * buf, void * retbuf, size_t count) {
if ((count == 0) || ((buf == NULL) && (retbuf == NULL))) return; // nothing to do
// bool dma_enabled = drv_spi_dma_enabled(_hspi);
HAL_StatusTypeDef status;
if (retbuf == NULL) {
// write only transfer
status = HAL_SPI_Transmit(_hspi, (uint8_t *)buf, count, 0xffff);
} else if (buf == NULL) {
// Read only buffer
status = HAL_SPI_Receive(_hspi, (uint8_t*)retbuf, count, 0xffff);
} else {
// standard Read/write buffer transfer
// start off without DMA support
status = HAL_SPI_TransmitReceive(_hspi, (uint8_t *)buf, (uint8_t*)retbuf, count, 0xffff);
}
if (status != HAL_OK)
{
Serial.print("transfer status: ");
Serial.println((int)status, DEC);
}
}
// Write only functions many used by Adafruit libraries.
void SPIClass::write(uint8_t data) {
HAL_SPI_Transmit(_hspi, &data, 1, 0xffff);
}
void SPIClass::write16(uint16_t data) {
uint8_t tBuf[2];
tBuf[0] = (uint8_t)(data>>8);
tBuf[1] = (uint8_t)data;
HAL_SPI_Transmit(_hspi, tBuf, 2, 0xffff);
}
void SPIClass::write32(uint32_t data) {
uint8_t tBuf[4];
tBuf[0] = (uint8_t)(data>>24);
tBuf[1] = (uint8_t)(data>>16);
tBuf[2] = (uint8_t)(data>>8);
tBuf[3] = (uint8_t)data;
HAL_SPI_Transmit(_hspi, tBuf, 4, 0xffff);
}
void SPIClass::writeBytes(uint8_t * data, uint32_t size) {
HAL_SPI_Transmit(_hspi, data, size, 0xffff);
}
void SPIClass::writePixels(const void * data, uint32_t size) { //ili9341 compatible
// First pass a hack! need to reverse bytes... Use internal buffer..
uint8_t tBuf[64];
uint16_t *pixels = (uint16_t *)data;
// size is the number of bytes.
while (size) {
uint8_t *pb = tBuf;
uint32_t cb = (size > 64)? 64 : size;
for (uint32_t i = 0; i < cb; i += 2) {
*pb++ = *pixels >> 8;
*pb++ = (uint8_t)*pixels;
pixels++;
}
HAL_SPI_Transmit(_hspi, tBuf, cb, 0xffff);
size -= cb;
}
}
void SPIClass::setBitOrder(uint8_t bitOrder) {
_bitOrder = bitOrder;
if (bitOrder == 1)
_hspi->Init.FirstBit = SPI_FIRSTBIT_MSB;
else
_hspi->Init.FirstBit = SPI_FIRSTBIT_LSB;
HAL_SPI_Init(_hspi);
}
void SPIClass::setClockDivider(uint8_t clockDiv) {
_clock = 0; // clear out so we will set in setClock
switch(clockDiv){
case SPI_CLOCK_DIV2:
_hspi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2;
break;
case SPI_CLOCK_DIV4:
_hspi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_4;
break;
case SPI_CLOCK_DIV8:
_hspi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8;
break;
case SPI_CLOCK_DIV16:
_hspi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16;
break;
case SPI_CLOCK_DIV32:
_hspi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32;
break;
case SPI_CLOCK_DIV64:
_hspi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_64;
break;
case SPI_CLOCK_DIV128:
_hspi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_128;
break;
case SPI_CLOCK_DIV256:
_hspi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_256;
break;
}
HAL_SPI_Init(_hspi);
}
void SPIClass::setClock(uint32_t clock) {
_clock = clock; // remember our new clock
if (clock >= _spi_clock / 2) {
_hspi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2;
} else if (clock >= _spi_clock / 4) {
_hspi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_4;
} else if (clock >= _spi_clock / 8) {
_hspi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8;
} else if (clock >= _spi_clock / 16) {
_hspi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16;
} else if (clock >= _spi_clock / 32) {
_hspi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32;
} else if (clock >= _spi_clock / 64) {
_hspi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_64;
} else if (clock >= _spi_clock / 128) {
_hspi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_128;
} else {
_hspi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_128; // Our slowest mode
}
HAL_SPI_Init(_hspi);
}
void SPIClass::setDataMode(uint8_t dataMode){
switch( dataMode )
{
_dataMode = dataMode;
// CPOL=0, CPHA=0
case SPI_MODE0:
_hspi->Init.CLKPolarity = SPI_POLARITY_LOW;
_hspi->Init.CLKPhase = SPI_PHASE_1EDGE;
HAL_SPI_Init(_hspi);
break;
// CPOL=0, CPHA=1
case SPI_MODE1:
_hspi->Init.CLKPolarity = SPI_POLARITY_LOW;
_hspi->Init.CLKPhase = SPI_PHASE_2EDGE;
HAL_SPI_Init(_hspi);
break;
// CPOL=1, CPHA=0
case SPI_MODE2:
_hspi->Init.CLKPolarity = SPI_POLARITY_HIGH;
_hspi->Init.CLKPhase = SPI_PHASE_1EDGE;
HAL_SPI_Init(_hspi);
break;
// CPOL=1, CPHA=1
case SPI_MODE3:
_hspi->Init.CLKPolarity = SPI_POLARITY_HIGH;
_hspi->Init.CLKPhase = SPI_PHASE_2EDGE;
HAL_SPI_Init(_hspi);
break;
}
}
//=========================================================================
// Main Async Transfer function
//=========================================================================
bool SPIClass::transfer(const void *buf, void *retbuf, size_t count, EventResponderRef event_responder) {
// Serial.println("Transfer with Event Call"); Serial.flush();
if (_dma_state == DMA_ACTIVE)
return false; // already active
else if (_dma_state == DMA_NOTINITIALIZED)
{
// Serial.println("Before SPI enable DMA"); Serial.flush();
drv_spi_enable_dma(_hspi);
_dma_state = DMA_IDLE;
}
// Serial.println("Before Clear event"); Serial.flush();
event_responder.clearEvent(); // Make sure it is not set yet
if (count < 2) {
// Use non-async version to simplify cases...
transfer(buf, retbuf, count);
event_responder.triggerEvent();
return true;
}
if ((count == 0) || ((buf == NULL) && (retbuf == NULL))) return false; // nothing to do
_dma_event_responder = &event_responder; // remember the event object
//bool dma_enabled = drv_spi_dma_enabled(_hspi);
// new version handles where buf or retbuf are null
drv_spi_start_dma_txrx(_hspi, (uint8_t *)buf, (uint8_t *)retbuf, count, &dmaCallback);
_dma_state = DMA_ACTIVE;
return true;
}
void SPIClass::dmaCallback(SPI_HandleTypeDef* hspi)
{
// Static function call from our DMA DRV code
if (hspi == &hspi1) SPI_IMU.processDMACallback();
else if (hspi == &hspi2) SPI.processDMACallback();
else if (hspi == &hspi4) SPI_EXT.processDMACallback();
}
void SPIClass::processDMACallback()
{
// We have been called back, that the DMA completed
if (_dma_event_responder)
{
_dma_state = DMA_COMPETED; // set back to 1 in case our call wants to start up dma again
_dma_event_responder->triggerEvent();
}
}
| 29.510264 | 106 | 0.626751 | yemiaobing |
a8059cd5a89f7c1576103e6a2c7902038e12530d | 8,545 | cpp | C++ | src/lift.cpp | IrvingtonRobotics/tower-takeover-A | a17524116d6d896d00420b1229f0a46727a72f1e | [
"MIT"
] | null | null | null | src/lift.cpp | IrvingtonRobotics/tower-takeover-A | a17524116d6d896d00420b1229f0a46727a72f1e | [
"MIT"
] | null | null | null | src/lift.cpp | IrvingtonRobotics/tower-takeover-A | a17524116d6d896d00420b1229f0a46727a72f1e | [
"MIT"
] | 1 | 2019-07-02T06:37:25.000Z | 2019-07-02T06:37:25.000Z | #include "main.h"
#include "ports.hpp"
extern bool doClearArm;
extern bool doUnclearArm;
extern bool doClearDropArm;
/**
* Main class for the Lift subsystem.
* Wraps around both AsyncPosIntegratedController and AsyncVelIntegratedController
* to provide movement to precise locations and smooth movement when lowering
* to the button/limit switch
*
* TODO: Use raw pros::MOTOR to utilize separate velocity and position controls
* Maybe try Gyro (do we have one?)
* https://www.robotc.net/wikiarchive/VEX2_Sensors_Overview
* This'll denecessitate thorough calibration
*/
class Lift {
/* ---- CONFIG ---- */
const QLength ARM_LENGTH = 18.75_in;
// height of arm pivot above ground
const QLength ARM_ELEVATION = 15.5_in;
// 720 ticks/rev with 36:1 gears -- high torque
// 360 ticks/rev with 18:1 gears
// 180 ticks/rev with 6:1 gears -- high speed
const double GEAR_RATIO = 7;
const int TICKS_PER_REV = 720 * GEAR_RATIO;
// height the arm caps out at
const QLength MAX_ARM_HEIGHT = 31_in;
// height need to start clearing
const QLength CLEAR_ARM_HEIGHT = 9_in;
const QLength MIN_ARM_HEIGHT = 2_in;
// tolerance of position when calculating new targets
const QLength POS_TOLERANCE = 0.5_in;
// size of opcontrol small movements
const QLength SMALL_MOVE_SIZE = 0.5_in;
// just leave this very small
const QLength MIN_THRESHOLD = -1000_in;
// tolerance when doing small movements: just reach within this of the threshold
const QLength SMALL_MOVE_TOLERANCE = 0.2_in;
static const int NUM_HEIGHTS = 3;
const QLength TARE_HEIGHT = 2_in;
// WARNING: targetHeights MUST be sorted
// {min, small tower, med tower}
const QLength targetHeights[NUM_HEIGHTS] = {6_in, 20_in, 27_in};
const QLength MID_HEIGHT = (targetHeights[NUM_HEIGHTS-1] + targetHeights[0])/2;
// ticks per second
const int UP_DEFAULT_MAX_VELOCITY = 600;
const int DOWN_DEFAULT_MAX_VELOCITY = 900;
const QTime CLEAR_DELAY = 70_ms;
/* ---- No need to edit ---- */
double tareTicks = 0;
// threshold until the target is reached for opcontrol small movements
QLength smallMoveThreshold;
// direction currently (or last) moved in for small movements
int smallMoveDir = 1;
const int PORT = -LIFT_PORT;
// is this currently doing a hard stop?
bool isLowering = false;
AsyncPosIntegratedController controller =
AsyncControllerFactory::posIntegrated(PORT);
AsyncVelIntegratedController velController =
AsyncControllerFactory::velIntegrated(PORT);
/**
* @param QLength height from ground
* @returns ticks from center
*/
double getTicks(QLength height) {
QLength dy = height - ARM_ELEVATION;
double ratio = (dy / ARM_LENGTH).getValue();
// radians
double angle = asin(ratio);
return getTicks(angle);
}
/**
* @param radians angle delta
* @return ticks delta
*/
double getTicks(double angle) {
double revolutions = angle / PI / 2;
return revolutions * TICKS_PER_REV;
}
/**
* @param ticks from center
* @returns radian angle from center
*/
double getAngle(double taredTicks) {
double ticks = taredTicks;
double revolutions = ticks / TICKS_PER_REV;
// radians
double angle = revolutions * PI * 2;
return angle;
}
/**
* @param ticks from center
* @returns QLength height from ground
*/
QLength getHeight(double taredTicks) {
double angle = getAngle(taredTicks);
double ratio = sin(angle);
QLength dy = ratio * ARM_LENGTH;
QLength height = dy + ARM_ELEVATION;
return height;
}
/**
* To help opcontrol
* If isIncreaseSmall, adds a small bit in the direction isIncrease
* Else returns next preset in the direction isIncrease at least
* POS_TOLERANCE away
*/
QLength getChangedHeight(QLength lastHeight, bool isIncrease, bool isIncreaseSmall) {
int m = boolToSign(isIncrease);
if (isIncreaseSmall) {
// just move a bit in one direction
smallMoveDir = m;
QLength smallMoveTarget = lastHeight + m * SMALL_MOVE_SIZE;
smallMoveThreshold = smallMoveTarget * m - SMALL_MOVE_TOLERANCE;
return smallMoveTarget;
} else {
/*
increasing: find first one greater than current position
decreasing: find last one less than current position
switching isIncrease just switches direction and comparison type
*/
int i = isIncrease ? 0 : NUM_HEIGHTS - 1;
while (lastHeight * m > targetHeights[i] * m - POS_TOLERANCE) {
i += m;
}
i = std::clamp(i, 0, NUM_HEIGHTS - 1);
return targetHeights[i];
}
}
/**
* Switch control between position controller and velocity controller
*/
void flipDisable() {
controller.flipDisable();
velController.flipDisable();
}
public:
Lift() {
// turn off velController so it doesn't conflict with posController
velController.flipDisable();
resetMaxVelocity();
}
void tare() {
tareHeight(TARE_HEIGHT);
}
void moveToggle() {
if (getCurrentHeight() > MID_HEIGHT) {
move(0);
} else {
move(-1);
}
}
/**
* Retare by assuming the current position is at height height
*/
void tareHeight(QLength height) {
// calculates tareTicks as ticks from center
// tare to 0
controller.tarePosition();
// assume lift is height off ground
tareTicks = getTicks(height);
}
void move(int heightIndex) {
if (heightIndex < 0) {
heightIndex = NUM_HEIGHTS + heightIndex;
}
QLength targetHeight = targetHeights[heightIndex];
move(targetHeight);
}
void glide(bool isUp) {
move(isUp ? -1 : 0);
}
/**
* @param ticks from center
*/
void move(double ticks) {
double taredTicks = ticks - tareTicks;
printf("Moving lift to height %f_in\n", (getHeight(ticks)/1_in).getValue());
if (getHeight(ticks) > CLEAR_ARM_HEIGHT) {
doClearArm = true;
pros::delay((CLEAR_DELAY / 1_ms).getValue());
} else {
doUnclearArm = true;
}
controller.setTarget(taredTicks);
}
/**
* Moves, but height is limited between MIN_ARM_HEIGHT and MAX_ARM_HEIGHT
*/
void move(QLength height) {
QLength clampedHeight = std::clamp(height, MIN_ARM_HEIGHT, MAX_ARM_HEIGHT);
double targetTicks = getTicks(clampedHeight);
move(targetTicks);
}
/**
* Opcontrol calls this based on button inputs
*
* @param isIncrease whether or not the height increases
* @param isSmall whether to move in small increment or to next preset
*/
void move(bool isIncrease, bool isSmall) {
if (!isSmall) {
smallMoveThreshold = MIN_THRESHOLD;
}
QLength height = getCurrentHeight();
if (height * smallMoveDir >= smallMoveThreshold) {
QLength newHeight = getChangedHeight(getCurrentHeight (), isIncrease, isSmall);
move(newHeight);
}
}
/**
* @returns ticks from center
*/
float getCurrentTicks() {
// return controller.getTarget() + tareTicks;
return getTargetTicks() - controller.getError();
}
/**
* @returns height from ground
*/
QLength getCurrentHeight() {
// height off ground
return getHeight(getCurrentTicks());
}
/**
* @returns ticks from center
*/
float getTargetTicks() {
return controller.getTarget() + tareTicks;
}
/**
* @returns height from ground
*/
QLength getTargetHeight() {
return getHeight(getTargetTicks());
}
void resetMaxVelocity() {
setMaxVelocity(UP_DEFAULT_MAX_VELOCITY);
}
void setMaxVelocityDown() {
setMaxVelocity(DOWN_DEFAULT_MAX_VELOCITY);
}
void setMaxVelocity(double tps) {
controller.setMaxVelocity(tps);
}
void step() {
// double confirm that arm is holding in place
controller.setTarget(controller.getTarget());
if (doClearDropArm) {
doClearDropArm = false;
move(0);
}
}
/**
* Get a quick data readout of where the lift thinks it is
* Useful for calibration and debugging
*/
void query() {
printf("---------\n");
printf(" query \n");
printf("---------\n");
double ticks = getCurrentTicks();
printf("ticks %f\n", ticks);
QLength height = getHeight(ticks);
printf("Height: %f inches\n", height.getValue() * 1 / 0.0254);
double angle = getAngle(ticks);
printf("Height angle: %f degrees\n", angle * 180 / 3.14);
printf("---------\n");
}
void waitUntilSettled() {
while (isLowering) {
pros::delay(10);
}
controller.waitUntilSettled();
}
void stop() {
move(getCurrentTicks());
}
};
| 27.300319 | 87 | 0.667993 | IrvingtonRobotics |
a8060728fffbfba048d7571e27be8fbeb3f6447e | 11,548 | cpp | C++ | src/postgres/backend/nodes/read.cpp | jessesleeping/my_peloton | a19426cfe34a04692a11008eaffc9c3c9b49abc4 | [
"Apache-2.0"
] | 6 | 2017-04-28T00:38:52.000Z | 2018-11-06T07:06:49.000Z | src/postgres/backend/nodes/read.cpp | jessesleeping/my_peloton | a19426cfe34a04692a11008eaffc9c3c9b49abc4 | [
"Apache-2.0"
] | 57 | 2016-03-19T22:27:55.000Z | 2017-07-08T00:41:51.000Z | src/postgres/backend/nodes/read.cpp | eric-haibin-lin/pelotondb | 904d6bbd041a0498ee0e034d4f9f9f27086c3cab | [
"Apache-2.0"
] | 4 | 2016-07-17T20:44:56.000Z | 2018-06-27T01:01:36.000Z | /*-------------------------------------------------------------------------
*
* read.c
* routines to convert a string (legal ascii representation of node) back
* to nodes
*
* Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/backend/nodes/read.c
*
* HISTORY
* AUTHOR DATE MAJOR EVENT
* Andrew Yu Nov 2, 1994 file creation
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <ctype.h>
#include "nodes/pg_list.h"
#include "nodes/readfuncs.h"
#include "nodes/value.h"
/* Static state for pg_strtok */
static char *pg_strtok_ptr = NULL;
/*
* stringToNode -
* returns a Node with a given legal ASCII representation
*/
void *
stringToNode(char *str)
{
char *save_strtok;
void *retval;
/*
* We save and restore the pre-existing state of pg_strtok. This makes the
* world safe for re-entrant invocation of stringToNode, without incurring
* a lot of notational overhead by having to pass the next-character
* pointer around through all the readfuncs.c code.
*/
save_strtok = pg_strtok_ptr;
pg_strtok_ptr = str; /* point pg_strtok at the string to read */
retval = nodeRead(NULL, 0); /* do the reading */
pg_strtok_ptr = save_strtok;
return retval;
}
/*****************************************************************************
*
* the lisp token parser
*
*****************************************************************************/
/*
* pg_strtok --- retrieve next "token" from a string.
*
* Works kinda like strtok, except it never modifies the source string.
* (Instead of storing nulls into the string, the length of the token
* is returned to the caller.)
* Also, the rules about what is a token are hard-wired rather than being
* configured by passing a set of terminating characters.
*
* The string is assumed to have been initialized already by stringToNode.
*
* The rules for tokens are:
* * Whitespace (space, tab, newline) always separates tokens.
* * The characters '(', ')', '{', '}' form individual tokens even
* without any whitespace around them.
* * Otherwise, a token is all the characters up to the next whitespace
* or occurrence of one of the four special characters.
* * A backslash '\' can be used to quote whitespace or one of the four
* special characters, so that it is treated as a plain token character.
* Backslashes themselves must also be backslashed for consistency.
* Any other character can be, but need not be, backslashed as well.
* * If the resulting token is '<>' (with no backslash), it is returned
* as a non-NULL pointer to the token but with length == 0. Note that
* there is no other way to get a zero-length token.
*
* Returns a pointer to the start of the next token, and the length of the
* token (including any embedded backslashes!) in *length. If there are
* no more tokens, NULL and 0 are returned.
*
* NOTE: this routine doesn't remove backslashes; the caller must do so
* if necessary (see "debackslash").
*
* NOTE: prior to release 7.0, this routine also had a special case to treat
* a token starting with '"' as extending to the next '"'. This code was
* broken, however, since it would fail to cope with a string containing an
* embedded '"'. I have therefore removed this special case, and instead
* introduced rules for using backslashes to quote characters. Higher-level
* code should add backslashes to a string constant to ensure it is treated
* as a single token.
*/
char *
pg_strtok(int *length)
{
char *local_str; /* working pointer to string */
char *ret_str; /* start of token to return */
local_str = pg_strtok_ptr;
while (*local_str == ' ' || *local_str == '\n' || *local_str == '\t')
local_str++;
if (*local_str == '\0')
{
*length = 0;
pg_strtok_ptr = local_str;
return NULL; /* no more tokens */
}
/*
* Now pointing at start of next token.
*/
ret_str = local_str;
if (*local_str == '(' || *local_str == ')' ||
*local_str == '{' || *local_str == '}')
{
/* special 1-character token */
local_str++;
}
else
{
/* Normal token, possibly containing backslashes */
while (*local_str != '\0' &&
*local_str != ' ' && *local_str != '\n' &&
*local_str != '\t' &&
*local_str != '(' && *local_str != ')' &&
*local_str != '{' && *local_str != '}')
{
if (*local_str == '\\' && local_str[1] != '\0')
local_str += 2;
else
local_str++;
}
}
*length = local_str - ret_str;
/* Recognize special case for "empty" token */
if (*length == 2 && ret_str[0] == '<' && ret_str[1] == '>')
*length = 0;
pg_strtok_ptr = local_str;
return ret_str;
}
/*
* debackslash -
* create a palloc'd string holding the given token.
* any protective backslashes in the token are removed.
*/
char *
debackslash(char *token, int length)
{
char *result = static_cast<char *>(palloc(length + 1));
char *ptr = result;
while (length > 0)
{
if (*token == '\\' && length > 1)
token++, length--;
*ptr++ = *token++;
length--;
}
*ptr = '\0';
return result;
}
#define RIGHT_PAREN (1000000 + 1)
#define LEFT_PAREN (1000000 + 2)
#define LEFT_BRACE (1000000 + 3)
#define OTHER_TOKEN (1000000 + 4)
/*
* nodeTokenType -
* returns the type of the node token contained in token.
* It returns one of the following valid NodeTags:
* T_Integer, T_Float, T_String, T_BitString
* and some of its own:
* RIGHT_PAREN, LEFT_PAREN, LEFT_BRACE, OTHER_TOKEN
*
* Assumption: the ascii representation is legal
*/
static NodeTag
nodeTokenType(char *token, int length)
{
NodeTag retval;
char *numptr;
int numlen;
/*
* Check if the token is a number
*/
numptr = token;
numlen = length;
if (*numptr == '+' || *numptr == '-')
numptr++, numlen--;
if ((numlen > 0 && isdigit((unsigned char) *numptr)) ||
(numlen > 1 && *numptr == '.' && isdigit((unsigned char) numptr[1])))
{
/*
* Yes. Figure out whether it is integral or float; this requires
* both a syntax check and a range check. strtol() can do both for us.
* We know the token will end at a character that strtol will stop at,
* so we do not need to modify the string.
*/
long val;
char *endptr;
errno = 0;
val = strtol(token, &endptr, 10);
(void) val; /* avoid compiler warning if unused */
if (endptr != token + length || errno == ERANGE
#ifdef HAVE_LONG_INT_64
/* if long > 32 bits, check for overflow of int4 */
|| val != (long) ((int32) val)
#endif
)
return T_Float;
return T_Integer;
}
/*
* these three cases do not need length checks, since pg_strtok() will
* always treat them as single-byte tokens
*/
else if (*token == '(')
retval = static_cast<NodeTag>(LEFT_PAREN);
else if (*token == ')')
retval = static_cast<NodeTag>(RIGHT_PAREN);
else if (*token == '{')
retval = static_cast<NodeTag>(LEFT_BRACE);
else if (*token == '\"' && length > 1 && token[length - 1] == '\"')
retval = T_String;
else if (*token == 'b')
retval = T_BitString;
else
retval = static_cast<NodeTag>(OTHER_TOKEN);
return retval;
}
/*
* nodeRead -
* Slightly higher-level reader.
*
* This routine applies some semantic knowledge on top of the purely
* lexical tokenizer pg_strtok(). It can read
* * Value token nodes (integers, floats, or strings);
* * General nodes (via parseNodeString() from readfuncs.c);
* * Lists of the above;
* * Lists of integers or OIDs.
* The return value is declared void *, not Node *, to avoid having to
* cast it explicitly in callers that assign to fields of different types.
*
* External callers should always pass NULL/0 for the arguments. Internally
* a non-NULL token may be passed when the upper recursion level has already
* scanned the first token of a node's representation.
*
* We assume pg_strtok is already initialized with a string to read (hence
* this should only be invoked from within a stringToNode operation).
*/
void *
nodeRead(char *token, int tok_len)
{
Node *result;
NodeTag type;
if (token == NULL) /* need to read a token? */
{
token = pg_strtok(&tok_len);
if (token == NULL) /* end of input */
return NULL;
}
type = nodeTokenType(token, tok_len);
switch ((int) type)
{
case LEFT_BRACE:
result = parseNodeString();
token = pg_strtok(&tok_len);
if (token == NULL || token[0] != '}')
elog(ERROR, "did not find '}' at end of input node");
break;
case LEFT_PAREN:
{
List *l = NIL;
/*----------
* Could be an integer list: (i int int ...)
* or an OID list: (o int int ...)
* or a list of nodes/values: (node node ...)
*----------
*/
token = pg_strtok(&tok_len);
if (token == NULL)
elog(ERROR, "unterminated List structure");
if (tok_len == 1 && token[0] == 'i')
{
/* List of integers */
for (;;)
{
int val;
char *endptr;
token = pg_strtok(&tok_len);
if (token == NULL)
elog(ERROR, "unterminated List structure");
if (token[0] == ')')
break;
val = (int) strtol(token, &endptr, 10);
if (endptr != token + tok_len)
elog(ERROR, "unrecognized integer: \"%.*s\"",
tok_len, token);
l = lappend_int(l, val);
}
}
else if (tok_len == 1 && token[0] == 'o')
{
/* List of OIDs */
for (;;)
{
Oid val;
char *endptr;
token = pg_strtok(&tok_len);
if (token == NULL)
elog(ERROR, "unterminated List structure");
if (token[0] == ')')
break;
val = (Oid) strtoul(token, &endptr, 10);
if (endptr != token + tok_len)
elog(ERROR, "unrecognized OID: \"%.*s\"",
tok_len, token);
l = lappend_oid(l, val);
}
}
else
{
/* List of other node types */
for (;;)
{
/* We have already scanned next token... */
if (token[0] == ')')
break;
l = lappend(l, nodeRead(token, tok_len));
token = pg_strtok(&tok_len);
if (token == NULL)
elog(ERROR, "unterminated List structure");
}
}
result = (Node *) l;
break;
}
case RIGHT_PAREN:
elog(ERROR, "unexpected right parenthesis");
result = NULL; /* keep compiler happy */
break;
case OTHER_TOKEN:
if (tok_len == 0)
{
/* must be "<>" --- represents a null pointer */
result = NULL;
}
else
{
elog(ERROR, "unrecognized token: \"%.*s\"", tok_len, token);
result = NULL; /* keep compiler happy */
}
break;
case T_Integer:
/*
* we know that the token terminates on a char atol will stop at
*/
result = (Node *) makeInteger(atol(token));
break;
case T_Float:
{
char *fval = (char *) palloc(tok_len + 1);
memcpy(fval, token, tok_len);
fval[tok_len] = '\0';
result = (Node *) makeFloat(fval);
}
break;
case T_String:
/* need to remove leading and trailing quotes, and backslashes */
result = (Node *) makeString(debackslash(token + 1, tok_len - 2));
break;
case T_BitString:
{
char *val = static_cast<char *>(palloc(tok_len));
/* skip leading 'b' */
memcpy(val, token + 1, tok_len - 1);
val[tok_len - 1] = '\0';
result = (Node *) makeBitString(val);
break;
}
default:
elog(ERROR, "unrecognized node type: %d", (int) type);
result = NULL; /* keep compiler happy */
break;
}
return (void *) result;
}
| 27.171765 | 79 | 0.604953 | jessesleeping |
a80a752187acdc56525ef7ade8ebbba1d04b5191 | 128 | hxx | C++ | src/Providers/UNIXProviders/MonitorResolution/UNIX_MonitorResolution_AIX.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | 1 | 2020-10-12T09:00:09.000Z | 2020-10-12T09:00:09.000Z | src/Providers/UNIXProviders/MonitorResolution/UNIX_MonitorResolution_AIX.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | src/Providers/UNIXProviders/MonitorResolution/UNIX_MonitorResolution_AIX.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | #ifdef PEGASUS_OS_AIX
#ifndef __UNIX_MONITORRESOLUTION_PRIVATE_H
#define __UNIX_MONITORRESOLUTION_PRIVATE_H
#endif
#endif
| 10.666667 | 42 | 0.851563 | brunolauze |
a815aa6282df56f126dff9ccc284caf04f64ffdb | 4,239 | cpp | C++ | swri_opencv_util/src/show.cpp | fatadama/marti_common | 892c76ef02f91f45a72161b92989c47d931471f2 | [
"BSD-3-Clause"
] | 1 | 2020-03-19T09:19:10.000Z | 2020-03-19T09:19:10.000Z | swri_opencv_util/src/show.cpp | wangwenqiangGitHub/marti_common | cd601b8701e1f88a6de5c8c8ff4b992f24490e36 | [
"BSD-3-Clause"
] | null | null | null | swri_opencv_util/src/show.cpp | wangwenqiangGitHub/marti_common | cd601b8701e1f88a6de5c8c8ff4b992f24490e36 | [
"BSD-3-Clause"
] | null | null | null | // *****************************************************************************
//
// Copyright (c) 2014, Southwest Research Institute® (SwRI®)
// 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 Southwest Research Institute® (SwRI®) 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (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 <swri_opencv_util/show.h>
#include <map>
#include <string>
#include <boost/serialization/singleton.hpp>
#include <boost/thread/mutex.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <ros/ros.h>
namespace swri_opencv_util
{
class CvWindows
{
public:
~CvWindows() {}
void RegisterWindow(const std::string& name)
{
boost::unique_lock<boost::mutex> lock(mutex_);
if (windows_.empty())
{
cvStartWindowThread();
}
if (windows_.count(name) == 0)
{
windows_[name] = name;
cvNamedWindow(name.c_str(), CV_WINDOW_NORMAL);
}
}
#if (BOOST_VERSION / 100 % 1000) >= 65
friend class boost::serialization::singleton<CvWindows>;
#else
friend class boost::serialization::detail::singleton_wrapper<CvWindows>;
#endif
private:
CvWindows() {}
boost::mutex mutex_;
std::map<std::string, std::string> windows_;
};
typedef boost::serialization::singleton<CvWindows> CvWindowsSingleton;
void ShowScaled(
const std::string& name,
const cv::Mat& mat,
const cv::Mat& mask,
double a,
double b)
{
if (mat.empty())
{
return;
}
CvWindowsSingleton::get_mutable_instance().RegisterWindow(name);
cv::Mat scaled;
// Autoscale if a is negative
if(a < 0.0)
{
double min, max;
cv::minMaxLoc(mat, &min, &max, 0, 0, mask);
if(mat.type() == CV_8UC1)
{
a = 255.0 / std::max(max - min, DBL_EPSILON);
b = -min * a;
mat.convertTo(scaled, CV_8U, a, b);
}
else if(mat.type() == CV_32FC1)
{
a = 255.0 / std::max(max - min, DBL_EPSILON);
b = -min * a;
mat.convertTo(scaled, CV_8U, a, b);
if (!mask.empty())
{
cv::Mat color;
cv::cvtColor(scaled, color, CV_GRAY2BGR);
color.setTo(cv::Scalar(0.0,0.0,255.0), mask == 0);
scaled = color;
}
}
else if(mat.type() == CV_32FC3)
{
a = 255.0 / std::max(max - min, DBL_EPSILON);
b = -min * a;
mat.convertTo(scaled, CV_8UC3, a, b);
}
else if(mat.type() == CV_8UC3)
{
a = 255.0 / std::max(max - min, DBL_EPSILON);
b = -min * a;
mat.convertTo(scaled, CV_8UC3, a, b);
}
}
else
{
mat.convertTo(scaled, CV_8U, a, b);
}
cv::imshow(name, scaled);
}
}
| 29.852113 | 80 | 0.610993 | fatadama |
a81c4c440900594c010d09cb35606d3f5e2062aa | 1,835 | hh | C++ | host/plugin-param.hh | prokopyl/clap-host | ee8eb43895d5cc5d741788661f752c4a9cab9d2e | [
"MIT"
] | 24 | 2021-12-01T13:36:25.000Z | 2022-03-17T10:12:29.000Z | host/plugin-param.hh | prokopyl/clap-host | ee8eb43895d5cc5d741788661f752c4a9cab9d2e | [
"MIT"
] | 9 | 2021-11-02T14:39:54.000Z | 2022-03-19T11:04:54.000Z | host/plugin-param.hh | prokopyl/clap-host | ee8eb43895d5cc5d741788661f752c4a9cab9d2e | [
"MIT"
] | 4 | 2021-11-02T09:01:50.000Z | 2022-02-04T20:00:35.000Z | #pragma once
#include <ostream>
#include <unordered_map>
#include <QObject>
#include <clap/clap.h>
class PluginHost;
class PluginParam : public QObject {
Q_OBJECT;
public:
PluginParam(PluginHost &pluginHost, const clap_param_info &info, double value);
double value() const { return _value; }
void setValue(double v);
double modulation() const { return _modulation; }
void setModulation(double v);
double modulatedValue() const {
return std::min(_info.max_value, std::max(_info.min_value, _value + _modulation));
}
bool isValueValid(const double v) const;
void printShortInfo(std::ostream &os) const;
void printInfo(std::ostream &os) const;
void setInfo(const clap_param_info &info) noexcept { _info = info; }
bool isInfoEqualTo(const clap_param_info &info) const;
bool isInfoCriticallyDifferentTo(const clap_param_info &info) const;
clap_param_info &info() noexcept { return _info; }
const clap_param_info &info() const noexcept { return _info; }
bool isBeingAdjusted() const noexcept { return _isBeingAdjusted; }
void setIsAdjusting(bool isAdjusting) {
if (isAdjusting && !_isBeingAdjusted)
beginAdjust();
else if (!isAdjusting && _isBeingAdjusted)
endAdjust();
}
void beginAdjust() {
Q_ASSERT(!_isBeingAdjusted);
_isBeingAdjusted = true;
emit isBeingAdjustedChanged();
}
void endAdjust() {
Q_ASSERT(_isBeingAdjusted);
_isBeingAdjusted = false;
emit isBeingAdjustedChanged();
}
signals:
void isBeingAdjustedChanged();
void infoChanged();
void valueChanged();
void modulatedValueChanged();
private:
bool _isBeingAdjusted = false;
clap_param_info _info;
double _value = 0;
double _modulation = 0;
std::unordered_map<int64_t, std::string> _enumEntries;
}; | 26.985294 | 88 | 0.703542 | prokopyl |
a81dc4026cfb4c007f2ccf37e0eb129b680192a3 | 2,802 | cpp | C++ | src/Views/C64/VicDisplay/C64CharMulti.cpp | slajerek/RetroDebugger | e761e4f9efd103a05e65ef283423b142fa4324c7 | [
"Apache-2.0",
"MIT"
] | 34 | 2021-05-29T07:04:17.000Z | 2022-03-10T20:16:03.000Z | src/Views/C64/VicDisplay/C64CharMulti.cpp | slajerek/RetroDebugger | e761e4f9efd103a05e65ef283423b142fa4324c7 | [
"Apache-2.0",
"MIT"
] | 6 | 2021-12-25T13:05:21.000Z | 2022-01-19T17:35:17.000Z | src/Views/C64/VicDisplay/C64CharMulti.cpp | slajerek/RetroDebugger | e761e4f9efd103a05e65ef283423b142fa4324c7 | [
"Apache-2.0",
"MIT"
] | 6 | 2021-12-24T18:37:41.000Z | 2022-02-06T23:06:02.000Z | #include "C64CharMulti.h"
#include "CViewC64VicDisplay.h"
#include "CViewC64.h"
// copy from multi bitmap
C64CharMulti::C64CharMulti(CViewC64VicDisplay *vicDisplay, int x, int y)
: C64Bitmap(4, 8, true)
{
pixels = new u8[4*8];
colors = new u8[4];
histogram = new u8[4];
memset(colors, 0x00, 4);
memset(histogram, 0x00, 4);
int charColumn = floor((float)((float)x / 8.0f));
int charRow = floor((float)((float)y / 8.0f));
int offset = charColumn + charRow * 40;
u8 *screen_ptr;
u8 *color_ram_ptr;
u8 *chargen_ptr;
u8 *bitmap_low_ptr;
u8 *bitmap_high_ptr;
u8 d020colors[0x0F];
vicDisplay->GetViciiPointers(&(viewC64->viciiStateToShow), &screen_ptr, &color_ram_ptr, &chargen_ptr, &bitmap_low_ptr, &bitmap_high_ptr, d020colors);
///
this->frameColor = d020colors[0];
this->colors[0] = d020colors[1];
this->colors[1] = (screen_ptr[(charRow * 40) + charColumn] & 0xf0) >> 4;
this->colors[2] = screen_ptr[(charRow * 40) + charColumn] & 0xf;
this->colors[3] = color_ram_ptr[(charRow * 40) + charColumn] & 0xf;
// this->colors[1] = viewC64->debugInterface->GetByteC64(vicDisplay->screenAddress + offset) >> 4;
// this->colors[2] = viewC64->debugInterface->GetByteC64(vicDisplay->screenAddress + offset) & 0xf;
// copy pixels: MULTI
for (int pixelCharY = 0; pixelCharY < 8; pixelCharY++)
{
int vicAddr = charColumn*8 + charRow * 40*8 + pixelCharY;
u8 val;
if (vicAddr < 4096)
{
val = bitmap_low_ptr[vicAddr];
}
else
{
val = bitmap_high_ptr[vicAddr - 4096];
}
//u8 val = viewC64->debugInterface->GetByteC64(bitmapBase + offset);
for (int pixelNum = 0; pixelNum < 4; pixelNum++)
{
//LOGD("addr=%04x pixelNum=%d val=%02x", bitmapBase + offset, pixelNum, val);
u8 a = 0x03 << ((3-pixelNum)*2);
//LOGD(" a=%02x", a);
u8 va = val & a;
//LOGD("va=%02x", va);
u8 vb = va >> ((3-pixelNum)*2);
//LOGD(" =%02x", vb);
pixels[pixelNum + 4 * pixelCharY] = vb;
histogram[vb]++;
}
}
// this->DebugPrint();
}
u8 C64CharMulti::GetPixel(int x, int y)
{
return pixels[x + 4 * y];
}
void C64CharMulti::DebugPrint()
{
// debug print char
for (int pixelCharY = 0; pixelCharY < 8; pixelCharY++)
{
char buf[256];
sprintf(buf, " %d: ", pixelCharY);
for (int pixelNum = 0; pixelNum < 4; pixelNum++)
{
char buf2[256];
sprintf(buf2, " %d", GetPixel(pixelNum, pixelCharY));
strcat(buf, buf2);
}
LOGD(buf);
}
LOGD(" colors: d020=%02X | d021=%02X (%3d) screen1=%02X (%3d) screen2=%02X (%3d) colorRam=%02X (%3d)",
this->frameColor,
this->colors[0], this->histogram[0],
this->colors[1], this->histogram[1],
this->colors[2], this->histogram[2],
this->colors[3], this->histogram[3]);
}
| 23.157025 | 150 | 0.613847 | slajerek |
a81f3ca70129d56bffeb8935792a124c684ec6ac | 1,843 | cpp | C++ | aws-cpp-sdk-panorama/source/model/DeviceJob.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-panorama/source/model/DeviceJob.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-panorama/source/model/DeviceJob.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-12-30T04:25:33.000Z | 2021-12-30T04:25:33.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/panorama/model/DeviceJob.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Panorama
{
namespace Model
{
DeviceJob::DeviceJob() :
m_deviceNameHasBeenSet(false),
m_deviceIdHasBeenSet(false),
m_jobIdHasBeenSet(false),
m_createdTimeHasBeenSet(false)
{
}
DeviceJob::DeviceJob(JsonView jsonValue) :
m_deviceNameHasBeenSet(false),
m_deviceIdHasBeenSet(false),
m_jobIdHasBeenSet(false),
m_createdTimeHasBeenSet(false)
{
*this = jsonValue;
}
DeviceJob& DeviceJob::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("DeviceName"))
{
m_deviceName = jsonValue.GetString("DeviceName");
m_deviceNameHasBeenSet = true;
}
if(jsonValue.ValueExists("DeviceId"))
{
m_deviceId = jsonValue.GetString("DeviceId");
m_deviceIdHasBeenSet = true;
}
if(jsonValue.ValueExists("JobId"))
{
m_jobId = jsonValue.GetString("JobId");
m_jobIdHasBeenSet = true;
}
if(jsonValue.ValueExists("CreatedTime"))
{
m_createdTime = jsonValue.GetDouble("CreatedTime");
m_createdTimeHasBeenSet = true;
}
return *this;
}
JsonValue DeviceJob::Jsonize() const
{
JsonValue payload;
if(m_deviceNameHasBeenSet)
{
payload.WithString("DeviceName", m_deviceName);
}
if(m_deviceIdHasBeenSet)
{
payload.WithString("DeviceId", m_deviceId);
}
if(m_jobIdHasBeenSet)
{
payload.WithString("JobId", m_jobId);
}
if(m_createdTimeHasBeenSet)
{
payload.WithDouble("CreatedTime", m_createdTime.SecondsWithMSPrecision());
}
return payload;
}
} // namespace Model
} // namespace Panorama
} // namespace Aws
| 17.721154 | 77 | 0.70917 | perfectrecall |
a8200cccdc58efc76027c54efedc19330aa29a5f | 4,849 | hpp | C++ | dsp/GMS_32f_64f_add_64f_avx.hpp | erglabs/Guided-Missile-Modeling-Simulation | b4e53fc8b66897d7c5e054542c42496f3aff6a73 | [
"MIT"
] | 12 | 2019-12-01T01:47:49.000Z | 2022-03-29T09:24:07.000Z | dsp/GMS_32f_64f_add_64f_avx.hpp | erglabs/Guided-Missile-Modeling-Simulation | b4e53fc8b66897d7c5e054542c42496f3aff6a73 | [
"MIT"
] | 2 | 2020-07-27T13:38:55.000Z | 2020-12-17T16:28:27.000Z | dsp/GMS_32f_64f_add_64f_avx.hpp | erglabs/Guided-Missile-Modeling-Simulation | b4e53fc8b66897d7c5e054542c42496f3aff6a73 | [
"MIT"
] | 7 | 2020-12-14T03:26:13.000Z | 2022-03-20T19:32:38.000Z |
#ifndef __GMS_32F_64F_ADD_64F_AVX_HPP__
#define __GMS_32F_64F_ADD_64F_AVX_HPP__
/*
Based on VOLK project.
Modified by Bernard Gingold on:
Date: 12-12-2020 5:17PM +00200
contact: beniekg@gmail.com
Few modification were added to original
implementation (ICC pragmas, alignment directives and code layout rescheduled)
*/
/*
* Copyright 2018 Free Software Foundation, Inc.
*
* This file is part of GNU Radio
*
* GNU Radio is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* GNU Radio 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 GNU Radio; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#include <immintrin.h>
#include <cstdint>
#include "GMS_config.h"
#if !defined(DSP_32F_64F_ADD_64F_AVX_BLOCK)
#define DSP_32F_64F_ADD_64F_AVX_BLOCK \
int32_t idx = 0; \
const int32_t len = npoints/8; \
register __m256 aVal; \
register __m128 aVal1, aVal2; \
register __m256d aDbl1, aDbl2, bVal1, bVal2, cVal1, cVal2;
#endif
__ATTR_ALWAYS_INLINE__
__ATTR_HOT__
__ATTR_ALIGN__(32)
static inline
void dsp_32f_64f_add_64f_u_avx_looped(double * __restrict c,
float * __restrict b,
float * __restrict a,
const int32_t npoints) {
DSP_32F_64F_ADD_64F_AVX_BLOCK
#if defined __ICC || defined __INTEL_COMPILER
#pragma code_align(32)
#endif
for(; idx != len; ++idx) {
_mm_prefetch((const char*)&a+32,_MM_HINT_T0);
aVal = _mm256_loadu_ps(a);
aVal1 = _mm256_extractf128_ps(aVal, 0);
aDbl1 = _mm256_cvtps_pd(aVal1);
aVal2 = _mm256_extractf128_ps(aVal, 1);
aDbl2 = _mm256_cvtps_pd(aVal2);
_mm_prefetch((const char*)&b+32,_MM_HINT_T0);
bVal1 = _mm256_loadu_pd(b);
cVal1 = _mm256_add_pd(aDbl1, bVal1);
bVal2 = _mm256_loadu_pd(b+4);
cVal2 = _mm256_add_pd(aDbl2, bVal2);
_mm256_storeu_pd(c,cVal1);
_mm256_storeu_pd(c+4, cVal2);
a += 8;
b += 8;
c += 8;
}
idx = len*8;
#if defined __ICC || defined __INTEL_COMPILER
#pragma loop_count min(1),avg(4),max(7)
#endif
for(; idx != npoints; ++idx) {
c[i] = ((double)a[i])+b[i];
}
}
__ATTR_ALWAYS_INLINE__
__ATTR_HOT__
__ATTR_ALIGN__(32)
static inline
void dsp_32f_64f_add_64f_a_avx_looped(double * __restrict __ATTR_ALIGN__(32) c,
float * __restrict __ATTR_ALIGN__(32) b,
float * __restrict __ATTR_ALIGN__(32) a,
const int32_t npoints) {
DSP_32F_64F_ADD_64F_AVX_BLOCK
#if defined __ICC || defined __INTEL_COMPILER
__assume_aligned(c,32);
__assume_aligned(b,32);
__assume_aligned(a,32);
#elif defined __GNUC__ || !defined __INTEL_COMPILER
c = (double*)__builtin_assume_aligned(c,32);
b = (float*) __builtin_assume_aligned(b,32);
a = (float*) __builtin_assume_aligned(a,32);
#endif
#if defined __ICC || defined __INTEL_COMPILER
#pragma code_align(32)
#endif
for(; idx != len; ++idx) {
_mm_prefetch((const char*)&a+32,_MM_HINT_T0);
aVal = _mm256_load_ps(a);
aVal1 = _mm256_extractf128_ps(aVal,0);
aDbl1 = _mm256_cvtps_pd(aVal1);
aVal2 = _mm256_extractf128_ps(aVal,1);
aDbl2 = _mm256_cvtps_pd(aVal2);
_mm_prefetch((const char*)&b+32,_MM_HINT_T0);
bVal1 = _mm256_load_pd(b);
cVal1 = _mm256_add_pd(aDbl1, bVal1);
bVal2 = _mm256_load_pd(b+4);
cVal2 = _mm256_add_pd(aDbl2, bVal2);
_mm256_store_pd(c,cVal1);
_mm256_store_pd(c+4,cVal2);
a += 8;
b += 8;
c += 8;
}
idx = len*8;
#if defined __ICC || defined __INTEL_COMPILER
#pragma loop_count min(1),avg(4),max(7)
#endif
for(; idx != npoints; ++idx) {
c[i] = ((double)a[i])+b[i];
}
}
#endif /* __GMS_32F_64F_ADD_64F_AVX_HPP__*/
| 34.635714 | 82 | 0.591875 | erglabs |
a82071acc70b8f5a49155150019bdfadef7d850c | 10,724 | cpp | C++ | main/renderer/Renderer2D.cpp | James51332/Papaya | 05c8216e5525f1ec7ca3e12c18d338c5929a4e16 | [
"Apache-2.0"
] | 2 | 2021-02-03T22:13:24.000Z | 2021-07-15T14:43:27.000Z | main/renderer/Renderer2D.cpp | James51332/Papaya | 05c8216e5525f1ec7ca3e12c18d338c5929a4e16 | [
"Apache-2.0"
] | null | null | null | main/renderer/Renderer2D.cpp | James51332/Papaya | 05c8216e5525f1ec7ca3e12c18d338c5929a4e16 | [
"Apache-2.0"
] | null | null | null | #include "papayapch.h"
#include "Renderer2D.h"
#include "Buffer.h"
#include "BufferLayout.h"
#include "PipelineState.h"
#include "RenderCommand.h"
#include <glm/matrix.hpp>
#include <glm/vec4.hpp>
#include <glm/vec3.hpp>
#include <glm/vec2.hpp>
// Based of TheCherno/Hazel's Renderer2D
namespace Papaya
{
struct QuadVertex
{ // defines the layout of one vertex. An array of these is uploaded to the gpu
glm::vec3 Position;
glm::vec4 Color;
glm::vec2 TexCoord;
float TexIndex;
float TilingFactor;
};
struct Renderer2DData // Stores the state of the renderer
{
static const uint32_t MaxQuads = 20000;
static const uint32_t MaxVertices = MaxQuads * 4;
static const uint32_t MaxIndices = MaxQuads * 6;
static const uint32_t MaxTextureSlots = 16;
Ref<Buffer> QuadVertexBuffer;
Ref<Buffer> QuadIndexBuffer;
Ref<PipelineState> QuadPipelineState;
uint32_t QuadIndexCount = 0;
// This is the head of an array of vertices.
QuadVertex* QuadVertexBufferBase = nullptr;
// This pointer moves as we add quads to the batch so
// we can determine the size of the data to send to the gpu
QuadVertex* QuadVertexBufferPtr = nullptr;
Ref<Texture2D> WhiteTexture;
std::array<Ref<Texture2D>, MaxTextureSlots> TextureSlots;
uint32_t TextureIndex = 1; // 0 = WhiteTexture
glm::vec4 QuadVertexPositions[4];
};
static Renderer2DData s_Data;
void Renderer2D::OnInit()
{
// Create Vertex Buffer
s_Data.QuadVertexBuffer = Buffer::Create(nullptr,
sizeof(QuadVertex) * s_Data.MaxVertices,
BufferType::Vertex,
BufferUsage::Dynamic);
// Create Index Buffer Data
uint32_t* quadIndices = new uint32_t[s_Data.MaxIndices];
uint32_t offset = 0; // transforms are baked into data so we need to offset indices to vertices later in data
for (int i = 0; i < s_Data.MaxIndices; i += 6)
{
quadIndices[i + 0] = offset + 0;
quadIndices[i + 1] = offset + 1;
quadIndices[i + 2] = offset + 2;
quadIndices[i + 3] = offset + 0;
quadIndices[i + 4] = offset + 2;
quadIndices[i + 5] = offset + 3;
offset += 4; // increase four vertices for every six indices
}
// Create Index Buffer
s_Data.QuadIndexBuffer = Buffer::Create(quadIndices,
sizeof(uint32_t) * s_Data.MaxIndices,
BufferType::Index,
BufferUsage::Immutable);
// Free Index Buffer Data
delete[] quadIndices;
// Create Vertex Data Array
s_Data.QuadVertexBufferBase = new QuadVertex[s_Data.MaxVertices];
// Create Shader (TODO: Figure out how we want to store shaders [e.g. files, in executable, strings, etc.])
String vs = R"(
#version 410 core
layout (location = 0) in vec3 a_Pos;
layout (location = 1) in vec4 a_Color;
layout (location = 2) in vec2 a_TexCoord;
layout (location = 3) in float a_TexIndex;
layout (location = 4) in float a_TilingFactor;
uniform mat4 u_ViewProjection;
out vec4 v_Color;
out vec2 v_TexCoord;
flat out float v_TexIndex;
out float v_TilingFactor;
void main() {
v_Color = a_Color;
v_TexCoord = a_TexCoord;
v_TexIndex = a_TexIndex;
v_TilingFactor = a_TilingFactor;
gl_Position = u_ViewProjection * vec4(a_Pos, 1.0);
})";
String fs = R"(
#version 410 core
layout (location = 0) out vec4 FragColor;
in vec4 v_Color;
in vec2 v_TexCoord;
flat in float v_TexIndex;
in float v_TilingFactor;
uniform sampler2D u_Textures[16];
void main() {
vec4 texColor = v_Color;
switch (int(v_TexIndex))
{
case 0: texColor *= texture(u_Textures[0], v_TexCoord * v_TilingFactor); break;
case 1: texColor *= texture(u_Textures[1], v_TexCoord * v_TilingFactor); break;
case 2: texColor *= texture(u_Textures[2], v_TexCoord * v_TilingFactor); break;
case 3: texColor *= texture(u_Textures[3], v_TexCoord * v_TilingFactor); break;
case 4: texColor *= texture(u_Textures[4], v_TexCoord * v_TilingFactor); break;
case 5: texColor *= texture(u_Textures[5], v_TexCoord * v_TilingFactor); break;
case 6: texColor *= texture(u_Textures[6], v_TexCoord * v_TilingFactor); break;
case 7: texColor *= texture(u_Textures[7], v_TexCoord * v_TilingFactor); break;
case 8: texColor *= texture(u_Textures[8], v_TexCoord * v_TilingFactor); break;
case 9: texColor *= texture(u_Textures[9], v_TexCoord * v_TilingFactor); break;
case 10: texColor *= texture(u_Textures[10], v_TexCoord * v_TilingFactor); break;
case 11: texColor *= texture(u_Textures[11], v_TexCoord * v_TilingFactor); break;
case 12: texColor *= texture(u_Textures[12], v_TexCoord * v_TilingFactor); break;
case 13: texColor *= texture(u_Textures[13], v_TexCoord * v_TilingFactor); break;
case 14: texColor *= texture(u_Textures[14], v_TexCoord * v_TilingFactor); break;
case 15: texColor *= texture(u_Textures[15], v_TexCoord * v_TilingFactor); break;
}
FragColor = texColor;
})";
Ref<Shader> shader = Shader::Create(vs, fs);
// Set the layout of a vertex
VertexDescriptor layout = { {{ShaderDataType::Float3, "a_Pos"},
{ShaderDataType::Float4, "a_Color"},
{ShaderDataType::Float2, "a_TexCoord"},
{ShaderDataType::Float, "a_TexIndex"},
{ShaderDataType::Float, "a_TilingFactor"}} };
// Create the pipeline state using the shader and layout
s_Data.QuadPipelineState = PipelineState::Create({ shader, layout });
int samplers[s_Data.MaxTextureSlots];
for (int i = 0; i < s_Data.MaxTextureSlots; ++i)
samplers[i] = i;
s_Data.QuadPipelineState->GetShader()->Bind();
s_Data.QuadPipelineState->GetShader()->SetIntArray("u_Textures", samplers, s_Data.MaxTextureSlots);
uint32_t whiteTextureData = 0xffffffff;
s_Data.WhiteTexture = Texture2D::Create(&whiteTextureData, 1, 1, ChannelType::RGBA);
s_Data.TextureSlots[0] = s_Data.WhiteTexture;
// Create basic quad vertices that we can later sample from
s_Data.QuadVertexPositions[0] = { -0.5f, -0.5f, 0.0f, 1.0f };
s_Data.QuadVertexPositions[1] = { 0.5f, -0.5f, 0.0f, 1.0f };
s_Data.QuadVertexPositions[2] = { 0.5f, 0.5f, 0.0f, 1.0f };
s_Data.QuadVertexPositions[3] = { -0.5f, 0.5f, 0.0f, 1.0f };
}
void Renderer2D::OnTerminate()
{
// Delete Vertex Data Array
delete[] s_Data.QuadVertexBufferBase;
}
void Renderer2D::BeginScene(const Camera& camera)
{
s_Data.QuadPipelineState->GetShader()->Bind();
s_Data.QuadPipelineState->GetShader()->SetMat4("u_ViewProjection", camera.GetViewProjectionMatrix());
StartBatch();
}
void Renderer2D::BeginScene(const Camera& camera, const glm::mat4& transform)
{
s_Data.QuadPipelineState->GetShader()->Bind();
s_Data.QuadPipelineState->GetShader()->SetMat4("u_ViewProjection", camera.GetProjectionMatrix() * glm::inverse(transform));
StartBatch();
}
void Renderer2D::EndScene()
{
Flush();
}
void Renderer2D::StartBatch()
{
// Reset the vertex buffer pointer for the new batch
s_Data.QuadVertexBufferPtr = s_Data.QuadVertexBufferBase;
s_Data.QuadIndexCount = 0;
// Reset the texture index
s_Data.TextureIndex = 1; // 0 = White Texture
}
void Renderer2D::Flush()
{
if (s_Data.QuadIndexCount == 0)
return; // Nothing to draw
// Determine how many much of the vertex array we need to set.
uint32_t dataSize = static_cast<uint32_t>(s_Data.QuadVertexBufferPtr - s_Data.QuadVertexBufferBase) * sizeof(QuadVertex);
s_Data.QuadVertexBuffer->SetData(s_Data.QuadVertexBufferBase, dataSize); // Send the determined amount of data to the gpu
// Bind Pipeline State
s_Data.QuadPipelineState->Bind();
// Bind Textures
for (uint32_t i = 0; i < s_Data.TextureIndex; ++i)
s_Data.TextureSlots[i]->Bind(i);
RenderCommand::SetIndexSize(sizeof(uint32_t));
RenderCommand::SetIndexOffset(0);
RenderCommand::SetElementCount(0);
RenderCommand::DrawIndexed({ s_Data.QuadVertexBuffer }, s_Data.QuadPipelineState, s_Data.QuadIndexBuffer);
}
void Renderer2D::DrawQuad(const glm::mat4& transform, const glm::vec4& color)
{
constexpr size_t quadVertexCount = 4;
const float textureIndex = 0.0f; // White Texture
constexpr glm::vec2 textureCoords[] = { {0.0f, 0.0f}, {1.0f, 0.0f}, {1.0f, 1.0f}, {0.0f, 1.0f} };
const float tilingFactor = 1.0f;
if (s_Data.QuadIndexCount >= s_Data.MaxIndices)
{
Flush();
StartBatch();
}
for (size_t i = 0; i < quadVertexCount; i++)
{
s_Data.QuadVertexBufferPtr->Position = transform * s_Data.QuadVertexPositions[i];
s_Data.QuadVertexBufferPtr->Color = color;
s_Data.QuadVertexBufferPtr->TexCoord = textureCoords[i];
s_Data.QuadVertexBufferPtr->TexIndex = textureIndex;
s_Data.QuadVertexBufferPtr->TilingFactor = tilingFactor;
s_Data.QuadVertexBufferPtr++; // On the next iteration/draw we will use the next vertex
}
s_Data.QuadIndexCount += 6;
}
void Renderer2D::DrawQuad(const glm::mat4& transform, const Ref<Texture2D>& texture, float tilingFactor, const glm::vec4& tintColor)
{
constexpr size_t quadVertexCount = 4;
constexpr glm::vec2 textureCoords[] = { { 0.0f, 0.0f }, { 1.0f, 0.0f }, { 1.0f, 1.0f }, { 0.0f, 1.0f } };
if (s_Data.QuadIndexCount >= s_Data.MaxIndices)
{
Flush();
StartBatch();
}
float textureIndex = 0.0f;
for (uint32_t i = 0; i < s_Data.TextureIndex; i++)
{ // check if texture is already used in batch
if (*s_Data.TextureSlots[i] == *texture)
{
textureIndex = static_cast<float>(i);
break;
}
}
if (textureIndex == 0.0f)
{
if (s_Data.TextureIndex >= s_Data.MaxTextureSlots)
{
Flush();
StartBatch();
}
textureIndex = static_cast<float>(s_Data.TextureIndex);
s_Data.TextureSlots[s_Data.TextureIndex] = texture;
s_Data.TextureIndex++;
}
for (int i = 0; i < quadVertexCount; i++)
{
s_Data.QuadVertexBufferPtr->Position = transform * s_Data.QuadVertexPositions[i];
s_Data.QuadVertexBufferPtr->Color = tintColor;
s_Data.QuadVertexBufferPtr->TexCoord = textureCoords[i];
s_Data.QuadVertexBufferPtr->TexIndex = textureIndex;
s_Data.QuadVertexBufferPtr->TilingFactor = tilingFactor;
s_Data.QuadVertexBufferPtr++; // On the next iteration/draw we will use the next vertex
}
s_Data.QuadIndexCount += 6;
}
} // namespace Papaya
| 33.4081 | 134 | 0.663372 | James51332 |
a82130a1a114047c563d6904e3e35fead40189d4 | 1,329 | cpp | C++ | model/manufacturedhome.cpp | rdffg/bcaa_importer | f92e0b39673b5c557540154d4567c53a15adadcd | [
"Apache-2.0"
] | null | null | null | model/manufacturedhome.cpp | rdffg/bcaa_importer | f92e0b39673b5c557540154d4567c53a15adadcd | [
"Apache-2.0"
] | 2 | 2019-05-07T22:49:31.000Z | 2021-08-20T20:03:53.000Z | model/manufacturedhome.cpp | rdffg/bcaa_importer | f92e0b39673b5c557540154d4567c53a15adadcd | [
"Apache-2.0"
] | null | null | null | #include "manufacturedhome.h"
using namespace model;
ManufacturedHome::ManufacturedHome(QObject *parent) : QDjangoModel(parent)
{
}
QString ManufacturedHome::mhRegistryNumber() const
{
return m_mhRegistryNumber;
}
void ManufacturedHome::setMhRegistryNumber(const QString &mhRegistryNumber)
{
m_mhRegistryNumber = mhRegistryNumber;
}
QString ManufacturedHome::mhBayNumber() const
{
return m_mhBayNumber;
}
void ManufacturedHome::setMhBayNumber(const QString &mhBayNumber)
{
m_mhBayNumber = mhBayNumber;
}
QString ManufacturedHome::mhPark() const
{
return m_mhPark;
}
void ManufacturedHome::setMhPark(const QString &mhPark)
{
m_mhPark = mhPark;
}
QString ManufacturedHome::mhParkRollNumber() const
{
return m_mhParkRollNumber;
}
void ManufacturedHome::setMhParkRollNumber(const QString &mhParkRollNumber)
{
m_mhParkRollNumber = mhParkRollNumber;
}
Folio *ManufacturedHome::folio() const
{
return qobject_cast<model::Folio *>(foreignKey("folio"));
}
void ManufacturedHome::setFolio(model::Folio *folio)
{
setForeignKey("folio", folio);
}
void ManufacturedHome::setFolio(std::unique_ptr<model::Folio> folio)
{
setForeignKey("folio", folio.get());
}
QString ManufacturedHome::id() const
{
return m_id;
}
void ManufacturedHome::setId(const QString &id)
{
m_id = id;
}
| 18.205479 | 75 | 0.751693 | rdffg |
a82169ee2cd31926a9068d740b592d11f6bfcb69 | 10,662 | cpp | C++ | src/DemoLayout.cpp | StoneDemo1995/GraduationProject | 89cc28487cb79e449f37d21d430c10c07a9f06a9 | [
"MIT"
] | null | null | null | src/DemoLayout.cpp | StoneDemo1995/GraduationProject | 89cc28487cb79e449f37d21d430c10c07a9f06a9 | [
"MIT"
] | null | null | null | src/DemoLayout.cpp | StoneDemo1995/GraduationProject | 89cc28487cb79e449f37d21d430c10c07a9f06a9 | [
"MIT"
] | null | null | null | #include "DemoLayout.h"
DemoLayout::DemoLayout()
{
demoTemp = new DemoTemplate();
}
DemoLayout::~DemoLayout()
{
}
void DemoLayout::BeginLayout(float width, float height, BaseMaterial *m, Results *r)
{
material = m;
results = r;
results->SetResult("layoutMethod : DemoLayout");
ofxCvGrayscaleImage tempSMap(material->GetSaliencyMap());
tempSMap.resize(width, height);
Typography(width, height, tempSMap.getCvImage());
results->SetTemplate(demoTemp);
}
void DemoLayout::Typography(float width, float height, IplImage* sMap)
{
InitTemplate(width, height);
MinimizeEnergy(sMap);
}
void DemoLayout::InitTemplate(float w, float h)
{
demoTemp->InitTemplate(w, h);
vector<string> textList = material->GetTextList();
for (int i = 0; i < textList.size(); i++)
{
// Note that we use to_string(i) here to get the text weight
float weight = material->GetTextWeight(to_string(i) + "." + textList.at(i));
if (weight >= 3.0f)
{
demoTemp->PutMasthead(textList.at(i));
}
else if (weight >= 2.5f)
{
demoTemp->PutLeftCoverlines(textList.at(i));
}
else if (weight >= 2.0f)
{
demoTemp->PutRightCoverlines(textList.at(i));
}
else
{
demoTemp->PutByline(textList.at(i));
}
}
}
float DemoLayout::MinimizeEnergy(IplImage* sMap)
{
float energy = 1024.0f;
float freeSpace = 0.0f;
uchar* saliency = (uchar*)(sMap->imageData);
for (int i = 0; i < sMap->imageSize; i++)
{
if (saliency[i] == 0)
{
freeSpace += 1.0f;
}
}
energy += MinimizeEnergy_Masthead(demoTemp->GetMastheadRegion(), sMap, freeSpace);
energy += MinimizeEnergy_Coverlines(demoTemp->GetLeftCoverlinesRegion(), sMap, freeSpace);
energy += MinimizeEnergy_Coverlines(demoTemp->GetRightCoverlinesRegion(), sMap, freeSpace);
energy += MinimizeEnergy_Byline(demoTemp->GetBylineRegion(), sMap, freeSpace);
return energy;
}
float DemoLayout::MinimizeEnergy_Masthead(TemplateRegion * region, IplImage * sMap, float freeSpace)
{
float energy = 1024.0f;
int tempSize = region->GetMinSize();
float tX, tY, tWidth, tHeight;
tX = region->GetPosition().x;
tY = region->GetPosition().y;
tWidth = region->GetWidth();
tHeight = region->GetHeight();
TextContour tContour;
tContour.PutText(region->GetOriSentence(0));
tContour.SetAlign(region->GetAlign());
tContour.SetBound(tX, tY, tX + tWidth, tY + tHeight);
tContour.SetFont(region->GetFontStash());
while (true)
{
ofRectangle rect = (region->GetFontStash())->getBBox(region->GetOriSentence(0), tempSize, tX, tY + tHeight, region->GetAlign());
tContour.SetCoord(tX, tY + (tHeight + rect.getHeight()) * 0.5);
// std::cout << (rect.getMaxY() - tHeight - tY) << std::endl;
tContour.SetFontSize(tempSize);
if (!tContour.ComputeContour())
{
std::cout << tempSize << std::endl;
break;
}
region->ClearText();
region->ClearContourMap();
region->PutText(tContour.GetText());
region->PutContour(region->GetText(0), tContour);
// std::cout << region->GetText(0) << std::endl;
float tEnergy = ((0.10f * ComputeInstrutionEnergy(region, sMap)) - (ComputeUtilizationEnergy(region, sMap) / freeSpace));
if (tEnergy < energy)
{
energy = tEnergy;
region->UpdateBest(tempSize);
}
tempSize++;
}
return energy;
}
float DemoLayout::MinimizeEnergy_Coverlines(TemplateRegion * region, IplImage * sMap, float freeSpace)
{
int randomNum1 = 3000;
int randomNum2 = 1000;
float energy = 1024.0f;
float tX, tY, tWidth, tHeight;
tX = region->GetPosition().x;
tY = region->GetPosition().y;
tWidth = region->GetWidth();
tHeight = region->GetHeight();
map<string, vector<string>> wordMap;
int oriTextSize = region->GetOriSentenceList().size();
for (int i = 0; i < oriTextSize; i++)
{
Split(region->GetOriSentence(i), wordMap[region->GetOriSentence(i)], " ");
}
map<string, vector<vector<string>>> paragraphMap;
for (int i = 0; i < oriTextSize; i++)
{
string oriStr = region->GetOriSentence(i);
vector<string> word = wordMap[oriStr];
int count = 0;
vector<string> tempPara;
tempPara.push_back(oriStr);
paragraphMap[oriStr].push_back(tempPara);
for (int pos1 = 0; pos1 < word.size() - 1; pos1++)
{
for (int pos2 = pos1; pos2 < word.size() - 1; pos2++)
{
if (!tempPara.empty())
{
tempPara.clear();
}
string tempStr;
if (pos2 == pos1)
{
tempStr = WordMerge(word, 0, pos1);
tempPara.push_back(tempStr);
tempStr = WordMerge(word, pos1 + 1, word.size() - 1);
tempPara.push_back(tempStr);
paragraphMap[oriStr].push_back(tempPara);
}
else
{
tempStr = WordMerge(word, 0, pos1);
tempPara.push_back(tempStr);
tempStr = WordMerge(word, pos1 + 1, pos2);
tempPara.push_back(tempStr);
tempStr = WordMerge(word, pos2 + 1, word.size() - 1);
tempPara.push_back(tempStr);
paragraphMap[oriStr].push_back(tempPara);
}
}
}
}
map<string, int> hash;
for (int i = 0; i < randomNum1; i++)
{
srand((unsigned)time(0));
region->ClearText();
region->ClearContourMap();
vector<int> randList;
string tempKey;
for (int j = 0; j < oriTextSize; j++)
{
int size = paragraphMap[region->GetOriSentence(j)].size();
int random = rand() % size;
randList.push_back(random);
tempKey = tempKey + to_string(random) + " ";
}
if (1 == hash[tempKey])
{
continue;
}
hash[tempKey] = 1;
vector<TextContour> contourList;
for (int j = 0; j < oriTextSize; j++)
{
TextContour tContour;
tContour.SetAlign(region->GetAlign());
tContour.SetBound(tX, tY, tX + tWidth, tY + tHeight);
tContour.SetFont(region->GetFontStash());
vector<string> tempStrList = paragraphMap[region->GetOriSentence(j)].at(randList.at(j));
for (int z = 0; z < tempStrList.size(); z++)
{
tContour.PutText(tempStrList.at(z));
}
region->PutText(tContour.GetText());
contourList.push_back(tContour);
}
for (int j = 0; j < randomNum2; j++)
{
bool forFlag = false;
float xx = tX + 2;
if (OF_ALIGN_HORZ_LEFT == region->GetAlign())
{
xx = tX + 2;
}
else if (OF_ALIGN_HORZ_RIGHT == region->GetAlign())
{
xx = tX + tWidth;
}
//float yy = (rand() % (int)tHeight) + tY + (rand() / double(RAND_MAX));
float yy = tY + j;
for (int size = region->GetMinSize(); size <= region->GetMaxSize(); size++)
{
ofRectangle rect(xx, yy, 0, 0);
for (int z = 0; z < oriTextSize; z++)
{
float yyy = 0.0f;
if (0 == z)
{
yyy = rect.getMaxY() + (region->GetFontStash())->getFontHeight(size) + 2;
}
else
{
yyy = rect.getMaxY() + 1.5 * (region->GetFontStash())->getFontHeight(size);
}
rect = (region->GetFontStash())->getBBox(region->GetText(z), size, xx, yyy, region->GetAlign());
contourList.at(z).SetCoord(xx, yyy);
contourList.at(z).SetFontSize(size);
if (!contourList.at(z).ComputeContour())
{
forFlag = true;
break;
}
region->PutContour(region->GetText(z), contourList.at(z));
}
if (forFlag)
{
break;
}
float tEnergy = (0.75f * ComputeInstrutionEnergy(region, sMap)) - (ComputeUtilizationEnergy(region, sMap) / freeSpace);
if (tEnergy < energy)
{
energy = tEnergy;
region->UpdateBest(size);
}
}
if (forFlag)
{
continue;
}
}
}
return energy;
}
float DemoLayout::MinimizeEnergy_Byline(TemplateRegion * region, IplImage * sMap, float freeSpace)
{
float energy = 1024.0f;
float tX, tY, tWidth, tHeight;
tX = region->GetPosition().x;
tY = region->GetPosition().y;
tWidth = region->GetWidth();
tHeight = region->GetHeight();
int oriTextSize = region->GetOriSentenceList().size();
vector<TextContour> contourList;
for (int j = 0; j < oriTextSize; j++)
{
TextContour tContour;
tContour.SetAlign(region->GetAlign());
tContour.SetBound(tX, tY, tX + tWidth, tY + tHeight);
tContour.SetFont(region->GetFontStash());
tContour.PutText(region->GetOriSentence(j));
region->PutText(tContour.GetText());
contourList.push_back(tContour);
}
float xx = tX + 2;
float yy = tY + 2;
bool flag = false;
for (int size = region->GetMinSize(); size < region->GetMaxSize(); size++)
{
for (int j = 0; j < oriTextSize; j++)
{
contourList.at(j).SetCoord(xx, yy + (j + 1) * (region->GetFontStash())->getFontHeight(size));
contourList.at(j).SetFontSize(size);
if (!contourList.at(j).ComputeContour())
{
flag = true;
break;
}
region->PutContour(region->GetText(j), contourList.at(j));
}
if (flag)
{
break;
}
float tEnergy = (0.15f * ComputeInstrutionEnergy(region, sMap)) - (ComputeUtilizationEnergy(region, sMap) / freeSpace);
if (tEnergy < energy)
{
energy = tEnergy;
region->UpdateBest(size);
}
}
return energy;
}
float DemoLayout::ComputeInstrutionEnergy(TemplateRegion * region, IplImage* sMap)
{
float energy = 0.0f;
float mol = 0.0f;
float den = 0.0f;
uchar* saliency = (uchar*) (sMap->imageData);
int widthStep = sMap->widthStep;
vector<string> textList = region->GetTextList();
for (int i = 0; i < textList.size(); i++)
{
TextContour tempContour = region->GetContour(textList.at(i));
vector<ofRectangle> contourList = tempContour.GetContour();
for (int j = 0; j < contourList.size(); j++)
{
ofRectangle rect = contourList.at(j);
for (int row = rect.getTopLeft().y; row < rect.getBottomLeft().y; row++)
{
for (int col = rect.getTopLeft().x; col < rect.getTopRight().x; col++)
{
mol = mol + saliency[col + row * widthStep];
den += 255;
}
}
}
}
energy = mol / den;
return energy;
}
float DemoLayout::ComputeUtilizationEnergy(TemplateRegion * region, IplImage * sMap)
{
float energy = 0.0f;
vector<string> textList = region->GetTextList();
for (int i = 0; i < textList.size(); i++)
{
TextContour tempContour = region->GetContour(textList.at(i));
vector<ofRectangle> contourList = tempContour.GetContour();
for (int j = 0; j < contourList.size(); j++)
{
energy = energy + contourList.at(j).getArea();
}
}
return energy;
}
void DemoLayout::Split(const string & input, vector<string>& output, const string & c)
{
string::size_type pos1, pos2;
pos2 = input.find(c);
pos1 = 0;
while (string::npos != pos2)
{
output.push_back(input.substr(pos1, pos2 - pos1));
pos1 = pos2 + c.size();
pos2 = input.find(c, pos1);
}
if (pos1 != input.length())
{
output.push_back(input.substr(pos1));
}
}
string DemoLayout::WordMerge(const vector<string> word, int start, int end)
{
string tempStr;
for (int i = start; i <= end; i++)
{
tempStr = tempStr + word[i];
if (i < end)
{
tempStr = tempStr + " ";
}
}
return tempStr;
}
| 23.228758 | 130 | 0.643875 | StoneDemo1995 |
a821981998d22926a2316b981cd661668c5fbc7a | 951 | cpp | C++ | math/hafnian_of_matrix/sol/naive.cpp | tko919/library-checker-problems | 007a3ef79d1a1824e68545ab326d1523d9c05262 | [
"Apache-2.0"
] | 290 | 2019-06-06T22:20:36.000Z | 2022-03-27T12:45:04.000Z | math/hafnian_of_matrix/sol/naive.cpp | tko919/library-checker-problems | 007a3ef79d1a1824e68545ab326d1523d9c05262 | [
"Apache-2.0"
] | 536 | 2019-06-06T18:25:36.000Z | 2022-03-29T11:46:36.000Z | math/hafnian_of_matrix/sol/naive.cpp | tko919/library-checker-problems | 007a3ef79d1a1824e68545ab326d1523d9c05262 | [
"Apache-2.0"
] | 82 | 2019-06-06T18:17:55.000Z | 2022-03-21T07:40:31.000Z | #include <algorithm>
#include <cassert>
#include <cstdio>
#include <numeric>
#include <vector>
using i64 = long long;
constexpr i64 MOD = 998244353;
int main() {
int n;
std::scanf("%d", &n);
assert(n <= 11);
std::vector<std::vector<i64>> a(n, std::vector<i64>(n));
for (auto &v : a) {
for (i64 &e : v) {
std::scanf("%lld", &e);
}
}
i64 ans = 0;
std::vector<int> idx(n);
std::iota(idx.begin(), idx.end(), 0);
do {
bool f = true;
for (int i = 0; i != n; i += 2) {
if (idx[i] > idx[i + 1]) {
f = false;
}
}
for (int i = 2; i != n; i += 2) {
if (idx[i - 2] > idx[i]) {
f = false;
}
}
if (!f) {
continue;
}
i64 prod = 1;
for (int i = 0; i != n; i += 2) {
prod = (prod * a[idx[i]][idx[i + 1]]) % MOD;
}
ans = (ans + prod) % MOD;
} while (std::next_permutation(idx.begin(), idx.end()));
std::printf("%lld\n", ans);
}
| 18.647059 | 58 | 0.460568 | tko919 |
a8219e5210633bc568327e322fb861d5d0129563 | 1,091 | cc | C++ | template-prime.cc | mpolacek/goo | 74efae79e4ada9bff6c0b00d28b729ac4db2a066 | [
"MIT"
] | 1 | 2020-12-05T00:41:11.000Z | 2020-12-05T00:41:11.000Z | template-prime.cc | mpolacek/goo | 74efae79e4ada9bff6c0b00d28b729ac4db2a066 | [
"MIT"
] | null | null | null | template-prime.cc | mpolacek/goo | 74efae79e4ada9bff6c0b00d28b729ac4db2a066 | [
"MIT"
] | null | null | null | // Compute prime_p at compile time using templates.
template<unsigned int P, unsigned int D>
struct do_prime {
static constexpr bool value = (P % D) && do_prime<P, D - 1>::value;
};
template<unsigned int P>
struct do_prime<P, 2> {
static constexpr bool value = (P % 2 != 0);
};
template<unsigned int P>
struct prime_p {
static constexpr bool value = do_prime<P, P / 2>::value;
};
template<>
struct prime_p<0> { static constexpr bool value = false; };
template<>
struct prime_p<1> { static constexpr bool value = false; };
template<>
struct prime_p<2> { static constexpr bool value = true; };
template<>
struct prime_p<3> { static constexpr bool value = true; };
static_assert(!prime_p<1>::value);
static_assert(prime_p<2>::value);
static_assert(prime_p<3>::value);
static_assert(!prime_p<4>::value);
static_assert(prime_p<5>::value);
static_assert(!prime_p<6>::value);
static_assert(prime_p<7>::value);
static_assert(!prime_p<8>::value);
static_assert(!prime_p<9>::value);
static_assert(!prime_p<10>::value);
static_assert(prime_p<11>::value);
static_assert(!prime_p<12>::value);
| 27.974359 | 69 | 0.716774 | mpolacek |
a82586ba42eb4c62f9cff417c87cfb556203a9c4 | 2,959 | cpp | C++ | benchmarks/Automatic_unroll/conv/conv2/conv_tiramisu0.cpp | AsmaBALAMANE/tiramisu | 73f9995f1e77e6adbbadda8f7dca1cb349c73eb1 | [
"MIT"
] | null | null | null | benchmarks/Automatic_unroll/conv/conv2/conv_tiramisu0.cpp | AsmaBALAMANE/tiramisu | 73f9995f1e77e6adbbadda8f7dca1cb349c73eb1 | [
"MIT"
] | null | null | null | benchmarks/Automatic_unroll/conv/conv2/conv_tiramisu0.cpp | AsmaBALAMANE/tiramisu | 73f9995f1e77e6adbbadda8f7dca1cb349c73eb1 | [
"MIT"
] | null | null | null | #include <tiramisu/tiramisu.h>
#include "config.h"
#include "unrol_explor.h"
using namespace tiramisu;
int main(int argc, char **argv){
tiramisu::init("conv_tiramisu");
// parameters
// N: parameters[0]
// K: parameters[1]
// FIn: parameters[2]
// FOut: parameters[3]
// BATCH_SIZE: parameters[4]
var i("i", 0, 5);
input parameters("parameters",{i}, p_int32);
constant C_N0("C_N0",N+K);
constant C_N("C_N", N);
constant C_N1("C_N1", N-K);
constant C_N2("C_N2", N-K-K);
constant C_K("C_K",K+1 );
constant C_FIn("C_FIn", FIn);
constant C_FOut("C_FOut", FOut);
constant C_BATCH_SIZE("C_BATCH_SIZE", BATCH_SIZE);
var z1("z1", 0, C_FOut), k_x("k_x",0,C_K), k_y("k_y",0,C_K), k_z("k_z",0,C_FIn); // filter variables
var x("x", 0, C_N0 ), y("y", 0, C_N0), z("z", 0, C_FOut), n("n", 0, C_BATCH_SIZE ); // input
var x1("x1", 0, C_N), y1("y1", 0, C_N); // conv
// Input computations
input c_input("c_input",{n, z, y, x} , p_int32);
input bias("bias", {z1}, p_int32);
input filter("filter", {z1, k_z , k_y, k_x}, p_int32);
// conv computations
computation conv_init("conv_init",{n, z, y1, x1}, expr(0));
computation comp0("comp0",{n, z, y1, x1, k_z, k_y, k_x }, conv_init(n, z, y1, x1) + filter(z, k_z, k_y, k_x) * c_input(n, k_z, y1 + k_y, x1 + k_x));
//comp0.dump_computation_features_structure();
// Schedule
conv_init.tag_parallel_level(0);
comp0.after(conv_init, 2);
comp0.parallelize(n);
/*comp0.interchange(i0, i1);
comp0.tile(i0, i1,i2, 64, 64,64, i01, i02, i03, i04,i05,i06);
comp0.unroll(i02, 32);
comp0.parallelize(i01);
comp0.after(comp_init, 2);*/
// Layer III
buffer parameters_buf("parameters_buf", {expr(5)}, p_int32, a_input);
buffer input_buf("input_buf", {expr(C_BATCH_SIZE), expr(C_FIn), expr(C_N0), expr(C_N0)}, p_int32, a_input);
buffer conv_buf("conv_buf", {expr(C_BATCH_SIZE), expr(C_FOut), expr(C_N), expr(C_N)}, p_int32, a_output);
buffer filter_buf("filter_buf", {expr(C_FOut), expr(C_FIn), expr(C_K), expr(C_K)}, p_int32, a_input);
buffer bias_buf("bias_buf", {expr(C_FOut)}, p_int32, a_input);
buffer conv2_buf("conv2_buf", {expr(C_BATCH_SIZE), expr(C_FOut), expr(C_N1), expr(C_N1)}, p_int32, a_output);
buffer bias2_buf("bias2_buf", {expr(C_FOut)}, p_int32, a_input);
buffer filter2_buf("filter2_buf", {expr(C_FOut), expr(C_FIn), expr(C_K), expr(C_K)}, p_int32, a_input);
buffer maxpool_buf("maxpool_buf", {expr(C_BATCH_SIZE), expr(C_FOut), expr(C_N2), expr(C_N2)}, p_int32, a_output);
parameters.store_in(¶meters_buf);
c_input.store_in(&input_buf);
bias.store_in(&bias_buf);
filter.store_in(&filter_buf);
conv_init.store_in(&conv_buf);
comp0.store_in(&conv_buf,{n, z, y1, x1});
tiramisu::codegen({¶meters_buf, &input_buf, &filter_buf, &bias_buf, &conv_buf}, "conv.o");
return 0;
} | 38.934211 | 152 | 0.636026 | AsmaBALAMANE |
a829bf1a0ef83d836a3b8ca92c309027c6f7bf5c | 87 | hpp | C++ | addons/main/script_macros.hpp | diwako/fparma-mods | 18ab07b633307e0c614f449d2ca0f45c07a3687a | [
"MIT"
] | null | null | null | addons/main/script_macros.hpp | diwako/fparma-mods | 18ab07b633307e0c614f449d2ca0f45c07a3687a | [
"MIT"
] | null | null | null | addons/main/script_macros.hpp | diwako/fparma-mods | 18ab07b633307e0c614f449d2ca0f45c07a3687a | [
"MIT"
] | null | null | null | #include "\z\ace\addons\main\script_macros.hpp"
#define FP_SETTINGS "FPARMA Settings"
| 21.75 | 47 | 0.781609 | diwako |
a82cf7c14cb0d7adf79b1ff762b5d2408d0efe24 | 2,492 | hpp | C++ | Source/LuVector_Op.hpp | RedBlight/LoopUnrolledVector | bc73dfc24a3d5b438c596b14b2b43deee295d9ea | [
"Unlicense"
] | 1 | 2019-05-01T07:05:26.000Z | 2019-05-01T07:05:26.000Z | Source/LuVector_Op.hpp | RedBlight/LoopUnrolledVector | bc73dfc24a3d5b438c596b14b2b43deee295d9ea | [
"Unlicense"
] | null | null | null | Source/LuVector_Op.hpp | RedBlight/LoopUnrolledVector | bc73dfc24a3d5b438c596b14b2b43deee295d9ea | [
"Unlicense"
] | null | null | null | #ifndef LU_VECTOR_OP_INCLUDED
#define LU_VECTOR_OP_INCLUDED
#include "LuVector.hpp"
namespace LUV
{
//////////////////////////////////////////////////////////////
// TEMPLATE LOOP INDEX VARIABLE
//////////////////////////////////////////////////////////////
template< size_t N >
struct LOOP_INDEX
{
};
//////////////////////////////////////////////////////////////
// TEMPLATE LOOP UNROLLING OPERATION FUNCTORS
//////////////////////////////////////////////////////////////
template< class T, class S >
struct OP_COPY
{
inline void operator ()( T& lhs, const S& rhs )
{
lhs = rhs;
}
};
//////////////////////////////////////////////////////////////
template< class T, class S >
struct OP_ADD
{
inline void operator ()( T& lhs, const S& rhs )
{
lhs += rhs;
}
};
template< class T, class S >
struct OP_SUB
{
inline void operator ()( T& lhs, const S& rhs )
{
lhs -= rhs;
}
};
template< class T, class S >
struct OP_MUL
{
inline void operator ()( T& lhs, const S& rhs )
{
lhs *= rhs;
}
};
template< class T, class S >
struct OP_DIV
{
inline void operator ()( T& lhs, const S& rhs )
{
lhs /= rhs;
}
};
//////////////////////////////////////////////////////////////
template< class T, class S >
struct OP_ABS
{
inline void operator ()( T& lhs, const S& rhs )
{
lhs = abs( rhs );
}
};
template< class T, class S >
struct OP_ARG
{
inline void operator ()( T& lhs, const S& rhs )
{
lhs = arg( rhs );
}
};
template< size_t N, class T, class S >
struct OP_MIN
{
inline void operator ()( LuVector< N, T >& result, const LuVector< N, T >& lhs, const LuVector< N, S >& rhs, const size_t& I )
{
result[ I ] = lhs[ I ] < rhs[ I ] ? lhs[ I ] : rhs[ I ];
}
};
template< size_t N, class T, class S >
struct OP_MAX
{
inline void operator ()( LuVector< N, T >& result, const LuVector< N, T >& lhs, const LuVector< N, S >& rhs, const size_t& I )
{
result[ I ] = lhs[ I ] > rhs[ I ] ? lhs[ I ] : rhs[ I ];
}
};
template< size_t N, class T, class S >
struct OP_DOT
{
inline void operator ()( T& result, const LuVector< N, T >& lhs, const LuVector< N, S >& rhs, const size_t& I )
{
result += lhs[ I ] * rhs[ I ];
}
};
//////////////////////////////////////////////////////////////
template< class T >
struct OP_OSTREAM
{
inline void operator ()( ostream& lhs, const T& rhs, const string& delimeter )
{
lhs << rhs << delimeter;
}
};
};
#endif | 19.46875 | 128 | 0.477127 | RedBlight |
a8353a4892ea58fc90c48473b7e4cf2a52fc3032 | 10,777 | cpp | C++ | test/EnergyEfficientAgentTest.cpp | alawibaba/geopm | dc5dd54cf260b0b51d517bb50d1ba5db9e013c71 | [
"BSD-3-Clause"
] | null | null | null | test/EnergyEfficientAgentTest.cpp | alawibaba/geopm | dc5dd54cf260b0b51d517bb50d1ba5db9e013c71 | [
"BSD-3-Clause"
] | null | null | null | test/EnergyEfficientAgentTest.cpp | alawibaba/geopm | dc5dd54cf260b0b51d517bb50d1ba5db9e013c71 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2015, 2016, 2017, 2018, Intel Corporation
*
* 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 Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* 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 LOG OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <map>
#include <memory>
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "geopm_message.h"
#include "geopm_hash.h"
#include "Agent.hpp"
#include "EnergyEfficientAgent.hpp"
#include "Exception.hpp"
#include "Helper.hpp"
#include "Agg.hpp"
#include "MockPlatformIO.hpp"
#include "MockPlatformTopo.hpp"
#include "PlatformTopo.hpp"
#include "geopm.h"
using ::testing::_;
using ::testing::Invoke;
using ::testing::Sequence;
using ::testing::Return;
using ::testing::AtLeast;
using geopm::EnergyEfficientAgent;
using geopm::PlatformTopo;
using geopm::IPlatformIO;
class EnergyEfficientAgentTest : public :: testing :: Test
{
protected:
enum mock_signal_idx_e {
REGION_ID_IDX,
RUNTIME_IDX,
FREQ_IDX,
ENERGY_PKG_IDX,
};
void SetUp();
void TearDown();
static const size_t M_NUM_REGIONS = 5;
std::vector<size_t> m_hints;
std::vector<double> m_expected_freqs;
std::unique_ptr<EnergyEfficientAgent> m_agent;
std::vector<std::string> m_region_names;
std::vector<uint64_t> m_region_hash;
std::vector<double> m_mapped_freqs;
std::vector<double> m_sample;
std::vector<double> m_default_policy;
double m_freq_min;
double m_freq_max;
std::unique_ptr<MockPlatformIO> m_platform_io;
std::unique_ptr<MockPlatformTopo> m_platform_topo;
const int M_NUM_CPU = 4;
};
void EnergyEfficientAgentTest::SetUp()
{
m_platform_io = geopm::make_unique<MockPlatformIO>();
m_platform_topo = geopm::make_unique<MockPlatformTopo>();
ON_CALL(*m_platform_topo, num_domain(PlatformTopo::M_DOMAIN_CPU))
.WillByDefault(Return(M_NUM_CPU));
ON_CALL(*m_platform_io, signal_domain_type(_))
.WillByDefault(Return(PlatformTopo::M_DOMAIN_BOARD));
ON_CALL(*m_platform_io, control_domain_type(_))
.WillByDefault(Return(PlatformTopo::M_DOMAIN_CPU));
ON_CALL(*m_platform_io, read_signal(std::string("CPUINFO::FREQ_MIN"), _, _))
.WillByDefault(Return(1.0e9));
ON_CALL(*m_platform_io, read_signal(std::string("CPUINFO::FREQ_STICKER"), _, _))
.WillByDefault(Return(1.3e9));
ON_CALL(*m_platform_io, read_signal(std::string("CPUINFO::FREQ_MAX"), _, _))
.WillByDefault(Return(2.2e9));
ON_CALL(*m_platform_io, read_signal(std::string("CPUINFO::FREQ_STEP"), _, _))
.WillByDefault(Return(100e6));
ON_CALL(*m_platform_io, push_signal("REGION_ID#", _, _))
.WillByDefault(Return(REGION_ID_IDX));
ON_CALL(*m_platform_io, push_signal("REGION_RUNTIME", _, _))
.WillByDefault(Return(RUNTIME_IDX));
ON_CALL(*m_platform_io, push_signal("ENERGY_PACKAGE", _, _))
.WillByDefault(Return(ENERGY_PKG_IDX));
ON_CALL(*m_platform_io, push_control("FREQUENCY", _, _))
.WillByDefault(Return(FREQ_IDX));
ON_CALL(*m_platform_io, agg_function(_))
.WillByDefault(Return(geopm::Agg::max));
EXPECT_CALL(*m_platform_io, agg_function(_))
.WillRepeatedly(Return(geopm::Agg::max));
// calls in constructor
EXPECT_CALL(*m_platform_topo, num_domain(_)).Times(AtLeast(1));
EXPECT_CALL(*m_platform_io, signal_domain_type(_)).Times(AtLeast(1));
EXPECT_CALL(*m_platform_io, control_domain_type(_)).Times(AtLeast(1));
EXPECT_CALL(*m_platform_io, read_signal(_, _, _)).Times(AtLeast(1));
EXPECT_CALL(*m_platform_io, push_signal(_, _, _)).Times(AtLeast(1));
EXPECT_CALL(*m_platform_io, push_control(_, _, _)).Times(M_NUM_CPU);
m_freq_min = 1800000000.0;
m_freq_max = 2200000000.0;
m_region_names = {"mapped_region0", "mapped_region1", "mapped_region2", "mapped_region3", "mapped_region4"};
m_region_hash = {0xeffa9a8d, 0x4abb08f3, 0xa095c880, 0x5d45afe, 0x71243e97};
m_mapped_freqs = {m_freq_max, 2100000000.0, 2000000000.0, 1900000000.0, m_freq_min};
m_default_policy = {m_freq_min, m_freq_max};
m_hints = {GEOPM_REGION_HINT_COMPUTE, GEOPM_REGION_HINT_MEMORY,
GEOPM_REGION_HINT_SERIAL, GEOPM_REGION_HINT_NETWORK,
GEOPM_REGION_HINT_PARALLEL, GEOPM_REGION_HINT_IO,
GEOPM_REGION_HINT_COMPUTE, GEOPM_REGION_HINT_IGNORE,
GEOPM_REGION_HINT_COMPUTE, GEOPM_REGION_HINT_UNKNOWN};
m_expected_freqs = {m_freq_min, m_freq_max, m_freq_min, m_freq_max, m_freq_min};
m_sample.resize(1);
ASSERT_EQ(m_mapped_freqs.size(), m_region_names.size());
ASSERT_EQ(m_mapped_freqs.size(), m_region_hash.size());
ASSERT_EQ(m_mapped_freqs.size(), m_expected_freqs.size());
std::stringstream ss;
ss << "{";
for (size_t x = 0; x < M_NUM_REGIONS; x++) {
ss << "\"" << m_region_names[x] << "\": " << m_mapped_freqs[x];
if (x != M_NUM_REGIONS-1) {
ss << ", ";
}
}
ss << "}";
setenv("GEOPM_EFFICIENT_FREQ_MIN", std::to_string(m_freq_min).c_str(), 1);
setenv("GEOPM_EFFICIENT_FREQ_MAX", std::to_string(m_freq_max).c_str(), 1);
setenv("GEOPM_EFFICIENT_FREQ_RID_MAP", ss.str().c_str(), 1);
m_agent = geopm::make_unique<EnergyEfficientAgent>(*m_platform_io, *m_platform_topo);
}
void EnergyEfficientAgentTest::TearDown()
{
unsetenv("GEOPM_EFFICIENT_FREQ_RID_MAP");
unsetenv("GEOPM_EFFICIENT_FREQ_MIN");
unsetenv("GEOPM_EFFICIENT_FREQ_MAX");
}
TEST_F(EnergyEfficientAgentTest, map)
{
EXPECT_CALL(*m_platform_io, sample(ENERGY_PKG_IDX))
.Times(M_NUM_REGIONS)
.WillRepeatedly(Return(8888));
for (size_t x = 0; x < M_NUM_REGIONS; x++) {
EXPECT_CALL(*m_platform_io, sample(REGION_ID_IDX))
.WillOnce(Return(geopm_field_to_signal(m_region_hash[x])));
m_agent->sample_platform(m_sample);
EXPECT_CALL(*m_platform_io, adjust(FREQ_IDX, m_mapped_freqs[x])).Times(M_NUM_CPU);
m_agent->adjust_platform(m_default_policy);
}
}
TEST_F(EnergyEfficientAgentTest, name)
{
EXPECT_EQ("energy_efficient", m_agent->plugin_name());
EXPECT_NE("bad_string", m_agent->plugin_name());
}
TEST_F(EnergyEfficientAgentTest, hint)
{
EXPECT_CALL(*m_platform_io, sample(ENERGY_PKG_IDX))
.Times(m_hints.size())
.WillRepeatedly(Return(8888));
for (size_t x = 0; x < m_hints.size(); x++) {
EXPECT_CALL(*m_platform_io, sample(REGION_ID_IDX))
.WillOnce(Return(geopm_field_to_signal(
geopm_region_id_set_hint(m_hints[x], 0x1234))));
double expected_freq = NAN;
switch(m_hints[x]) {
// Hints for low CPU frequency
case GEOPM_REGION_HINT_MEMORY:
case GEOPM_REGION_HINT_NETWORK:
case GEOPM_REGION_HINT_IO:
expected_freq = 1.8e9;
break;
// Hints for maximum CPU frequency
case GEOPM_REGION_HINT_COMPUTE:
case GEOPM_REGION_HINT_SERIAL:
case GEOPM_REGION_HINT_PARALLEL:
expected_freq = 2.2e9;
break;
// Hint Inconclusive
//case GEOPM_REGION_HINT_UNKNOWN:
//case GEOPM_REGION_HINT_IGNORE:
default:
expected_freq = 1.8e9;
break;
}
EXPECT_CALL(*m_platform_io, adjust(FREQ_IDX, expected_freq)).Times(M_NUM_CPU);
m_agent->sample_platform(m_sample);
m_agent->adjust_platform(m_default_policy);
}
}
TEST_F(EnergyEfficientAgentTest, online_mode)
{
int err = unsetenv("GEOPM_EFFICIENT_FREQ_RID_MAP");
EXPECT_EQ(0, err);
EXPECT_EQ(NULL, getenv("GEOPM_EFFICIENT_FREQ_RID_MAP"));
setenv("GEOPM_EFFICIENT_FREQ_ONLINE", "yes", 1);
double freq_min = 1e9;
setenv("GEOPM_EFFICIENT_FREQ_MIN", std::to_string(freq_min).c_str(), 1);
double freq_max = 2e9;
setenv("GEOPM_EFFICIENT_FREQ_MAX", std::to_string(freq_max).c_str(), 1);
for (int x = 0; x < 4; ++x) {
// calls in constructor form SetUp and this test
EXPECT_CALL(*m_platform_io, signal_domain_type(_)).Times(1);
EXPECT_CALL(*m_platform_io, control_domain_type(_)).Times(1);
EXPECT_CALL(*m_platform_io, read_signal(_, _, _)).Times(2);
EXPECT_CALL(*m_platform_io, push_signal("REGION_ID#", _, _)).Times(1);
EXPECT_CALL(*m_platform_io, push_control("FREQUENCY", _, _)).Times(M_NUM_CPU);
EXPECT_CALL(*m_platform_io, push_signal("REGION_RUNTIME", _, _)).Times(1);
EXPECT_CALL(*m_platform_io, push_signal("ENERGY_PACKAGE", _, _)).Times(2);
// reset agent with new settings
m_agent = geopm::make_unique<EnergyEfficientAgent>(*m_platform_io, *m_platform_topo);
{
// within EfficientFreqRegion
EXPECT_CALL(*m_platform_io, sample(REGION_ID_IDX))
.WillOnce(Return(geopm_region_id_set_hint(m_hints[x], m_region_hash[x])));
EXPECT_CALL(*m_platform_io, sample(ENERGY_PKG_IDX)).Times(2);
EXPECT_CALL(*m_platform_io, adjust(FREQ_IDX, _)).Times(M_NUM_CPU);
m_agent->sample_platform(m_sample);
m_agent->adjust_platform(m_default_policy);
}
}
unsetenv("GEOPM_EFFICIENT_FREQ_RID_MAP");
}
| 39.914815 | 112 | 0.684513 | alawibaba |
a840b7ca99b4b2b135e52f6e27b1b6b8f0c10a01 | 927 | cpp | C++ | old-unit-tests/string/SA-generator.cpp | deadpool2794/Cp | 26eab96ef8ea336615fa8d6fadaa8e4d7d6f3a3c | [
"MIT"
] | 152 | 2019-04-09T18:26:41.000Z | 2022-03-20T23:19:41.000Z | old-unit-tests/string/SA-generator.cpp | deadpool2794/Cp | 26eab96ef8ea336615fa8d6fadaa8e4d7d6f3a3c | [
"MIT"
] | 1 | 2020-12-29T03:02:22.000Z | 2020-12-29T03:02:22.000Z | old-unit-tests/string/SA-generator.cpp | deadpool2794/Cp | 26eab96ef8ea336615fa8d6fadaa8e4d7d6f3a3c | [
"MIT"
] | 36 | 2019-11-28T09:27:01.000Z | 2022-03-10T18:22:13.000Z | //Solution by lukasP (Lukáš Poláček)
#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <algorithm>
#include <sstream>
#include <queue>
#include <bitset>
#include <utility>
#include <list>
#include <numeric>
#include <fstream>
#include <cstdio>
#include <cmath>
#include <cctype>
using namespace std;
#define rep(i,a,b) for(int i=a; i<int(b); ++i)
typedef long long ll;
typedef pair<string, int> pii;
typedef vector<int> vi;
int main()
{
int n = 4;
cout << n << endl;
ofstream out("SA.out");
rep(j,0,n)
{
int m = rand() % 80000 + 20;
string s;
rep(i,0,m)
s += 'a' + rand() % 2;
cout << s << endl;
vector<pii> a;
rep(i,0,m+1)
a.push_back(pii(s.substr(i), i));
sort(a.begin(), a.end());
rep(i,0,a.size())
out << a[i].second << " ";
out << endl;
}
}
| 19.3125 | 46 | 0.543689 | deadpool2794 |
61b542d0f3e6dcf0ba41713b13a47cafca5905d5 | 4,752 | cpp | C++ | ChemistryLib/CreatePhreeqcIO.cpp | MManicaM/ogs | 6d5ee002f7ac1d046b34655851b98907d5b8cc4f | [
"BSD-4-Clause"
] | null | null | null | ChemistryLib/CreatePhreeqcIO.cpp | MManicaM/ogs | 6d5ee002f7ac1d046b34655851b98907d5b8cc4f | [
"BSD-4-Clause"
] | null | null | null | ChemistryLib/CreatePhreeqcIO.cpp | MManicaM/ogs | 6d5ee002f7ac1d046b34655851b98907d5b8cc4f | [
"BSD-4-Clause"
] | null | null | null | /**
* \copyright
* Copyright (c) 2012-2019, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*
*/
#include "BaseLib/ConfigTreeUtil.h"
#include "BaseLib/Error.h"
#include "CreateOutput.h"
#include "CreatePhreeqcIO.h"
#include "PhreeqcIO.h"
#include "PhreeqcIOData/AqueousSolution.h"
#include "PhreeqcIOData/CreateAqueousSolution.h"
#include "PhreeqcIOData/CreateEquilibriumPhase.h"
#include "PhreeqcIOData/CreateKineticReactant.h"
#include "PhreeqcIOData/CreateReactionRate.h"
#include "PhreeqcIOData/EquilibriumPhase.h"
#include "PhreeqcIOData/KineticReactant.h"
#include "PhreeqcIOData/ReactionRate.h"
namespace ChemistryLib
{
std::unique_ptr<PhreeqcIO> createPhreeqcIO(
std::size_t const num_nodes,
std::vector<std::pair<int, std::string>> const&
process_id_to_component_name_map,
BaseLib::ConfigTree const& config,
std::string const& output_directory)
{
auto const& num_chemical_systems = num_nodes;
// database
//! \ogs_file_param{prj__chemical_system__database}
auto const database = config.getConfigParameter<std::string>("database");
auto path_to_database =
BaseLib::joinPaths(BaseLib::getProjectDirectory(), database);
if (BaseLib::IsFileExisting(path_to_database))
{
INFO("Found the specified thermodynamic database: %s",
path_to_database.c_str());
}
else
{
OGS_FATAL("Not found the specified thermodynamicdatabase: %s",
path_to_database.c_str());
}
// solution
auto const aqueous_solution_per_chem_sys = createAqueousSolution(
//! \ogs_file_param{prj__chemical_system__solution}
config.getConfigSubtree("solution"));
auto const& components_per_chem_sys =
aqueous_solution_per_chem_sys.components;
for (auto const& component : components_per_chem_sys)
{
auto process_id_to_component_name_map_element = std::find_if(
process_id_to_component_name_map.begin(),
process_id_to_component_name_map.end(),
[&component](std::pair<int, std::string> const& map_element) {
return map_element.second == component.name;
});
if (process_id_to_component_name_map_element ==
process_id_to_component_name_map.end())
{
OGS_FATAL(
"Component %s given in <solution>/<components> is not found in "
"specified coupled processes (see "
"<process>/<process_variables>/<concentration>).",
component.name.c_str());
}
}
if (components_per_chem_sys.size() + 1 !=
process_id_to_component_name_map.size())
{
OGS_FATAL(
"The number of components given in <solution>/<components> is not "
"in line with the number of transport processes - 1 which stands "
"for the transport process of hydrogen.");
}
std::vector<AqueousSolution> aqueous_solutions(
num_chemical_systems, aqueous_solution_per_chem_sys);
// equilibrium phases
auto const equilibrium_phases_per_chem_sys = createEquilibriumPhases(
//! \ogs_file_param{prj__chemical_system__equilibrium_phases}
config.getConfigSubtreeOptional("equilibrium_phases"));
std::vector<std::vector<EquilibriumPhase>> equilibrium_phases(
num_chemical_systems, equilibrium_phases_per_chem_sys);
// kinetic reactants
auto const kinetic_reactants_per_chem_sys = createKineticReactants(
//! \ogs_file_param{prj__chemical_system__kinetic_reactants}
config.getConfigSubtreeOptional("kinetic_reactants"));
std::vector<std::vector<KineticReactant>> kinetic_reactants(
num_chemical_systems, kinetic_reactants_per_chem_sys);
// rates
auto reaction_rates = createReactionRates(
//! \ogs_file_param{prj__chemical_system__rates}
config.getConfigSubtreeOptional("rates"));
// output
auto const project_file_name = BaseLib::joinPaths(
output_directory,
BaseLib::extractBaseNameWithoutExtension(config.getProjectFileName()));
auto output =
createOutput(components_per_chem_sys, equilibrium_phases_per_chem_sys,
kinetic_reactants_per_chem_sys, project_file_name);
return std::make_unique<PhreeqcIO>(
project_file_name, std::move(path_to_database),
std::move(aqueous_solutions), std::move(equilibrium_phases),
std::move(kinetic_reactants), std::move(reaction_rates),
std::move(output), process_id_to_component_name_map);
}
} // namespace ChemistryLib
| 38.322581 | 80 | 0.698443 | MManicaM |
61b5b30831302b611fa382e195e9f538a695c2e3 | 1,821 | hpp | C++ | sprout/tpp/algorithm/min_element.hpp | EzoeRyou/Sprout | 12e12373d0f70543eac5f2ecfbec8f5112765f98 | [
"BSL-1.0"
] | 1 | 2016-09-29T21:55:58.000Z | 2016-09-29T21:55:58.000Z | sprout/tpp/algorithm/min_element.hpp | EzoeRyou/Sprout | 12e12373d0f70543eac5f2ecfbec8f5112765f98 | [
"BSL-1.0"
] | null | null | null | sprout/tpp/algorithm/min_element.hpp | EzoeRyou/Sprout | 12e12373d0f70543eac5f2ecfbec8f5112765f98 | [
"BSL-1.0"
] | null | null | null | /*=============================================================================
Copyright (c) 2011-2014 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
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 SPROUT_TPP_ALGORITHM_MIN_ELEMENT_HPP
#define SPROUT_TPP_ALGORITHM_MIN_ELEMENT_HPP
#include <sprout/config.hpp>
#include <sprout/type_traits/common_decay.hpp>
#include <sprout/type_traits/integral_constant.hpp>
namespace sprout {
namespace tpp {
namespace detail {
template<typename T, T... Values>
struct min_element_impl;
template<typename T, T Value>
struct min_element_impl<T, Value>
: public sprout::integral_constant<T, Value>
{};
template<typename T, T Value1, T Value2>
struct min_element_impl<T, Value1, Value2>
: public sprout::integral_constant<T, (Value2 < Value1 ? Value2 : Value1)>
{};
template<typename T, T Value1, T Value2, T... Tail>
struct min_element_impl<T, Value1, Value2, Tail...>
: public sprout::tpp::detail::min_element_impl<T, sprout::tpp::detail::min_element_impl<T, Value1, Value2>::value, Tail...>
{};
} // namespace detail
//
// min_element_c
//
template<typename T, T... Values>
struct min_element_c
: public sprout::tpp::detail::min_element_impl<T, Values...>
{};
//
// min_element
//
template<typename... Types>
struct min_element
: public sprout::tpp::min_element_c<typename sprout::common_decay<decltype(Types::value)...>::type, Types::value...>
{};
} // namespace tpp
} // namespace sprout
#endif // #ifndef SPROUT_TPP_ALGORITHM_MIN_ELEMENT_HPP
| 35.705882 | 128 | 0.635365 | EzoeRyou |
61b7006f5d199787084317f30a505f1ab48aebb4 | 479 | hpp | C++ | PluginTray/Source/Images.hpp | FFFF0h/audiogridder | 672288f910ce06505910a742126643e816d5963b | [
"MIT"
] | 551 | 2020-04-22T22:29:46.000Z | 2022-03-30T00:09:40.000Z | PluginTray/Source/Images.hpp | FFFF0h/audiogridder | 672288f910ce06505910a742126643e816d5963b | [
"MIT"
] | 343 | 2020-04-24T00:27:25.000Z | 2022-03-28T13:58:08.000Z | PluginTray/Source/Images.hpp | FFFF0h/audiogridder | 672288f910ce06505910a742126643e816d5963b | [
"MIT"
] | 71 | 2020-04-23T15:22:17.000Z | 2022-03-23T08:31:23.000Z | /*
* Copyright (c) 2021 Andreas Pohl
* Licensed under MIT (https://github.com/apohl79/audiogridder/blob/master/COPYING)
*
* Author: Andreas Pohl
*/
#ifndef Images_hpp
#define Images_hpp
#include <JuceHeader.h>
class Images {
public:
static const char* tray_png;
static const int tray_pngSize;
static const char* wintray_png;
static const int wintray_pngSize;
static const char* logo_png;
static const int logo_pngSize;
};
#endif // Images_hpp
| 19.958333 | 83 | 0.716075 | FFFF0h |
61bd41551f9a1c7bc6038925d8f9b6f1f49607da | 149,607 | cpp | C++ | SU2-Quantum/SU2_CFD/src/output/CFlowOutput.cpp | Agony5757/SU2-Quantum | 16e7708371a597511e1242f3a7581e8c4187f5b2 | [
"Apache-2.0"
] | null | null | null | SU2-Quantum/SU2_CFD/src/output/CFlowOutput.cpp | Agony5757/SU2-Quantum | 16e7708371a597511e1242f3a7581e8c4187f5b2 | [
"Apache-2.0"
] | null | null | null | SU2-Quantum/SU2_CFD/src/output/CFlowOutput.cpp | Agony5757/SU2-Quantum | 16e7708371a597511e1242f3a7581e8c4187f5b2 | [
"Apache-2.0"
] | 1 | 2021-12-03T06:40:08.000Z | 2021-12-03T06:40:08.000Z | /*!
* \file output_flow.cpp
* \brief Main subroutines for compressible flow output
* \author R. Sanchez
* \version 7.0.6 "Blackbird"
*
* SU2 Project Website: https://su2code.github.io
*
* The SU2 Project is maintained by the SU2 Foundation
* (http://su2foundation.org)
*
* Copyright 2012-2020, SU2 Contributors (cf. AUTHORS.md)
*
* SU2 is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* SU2 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with SU2. If not, see <http://www.gnu.org/licenses/>.
*/
#include "../../include/output/CFlowOutput.hpp"
#include "../../../Common/include/geometry/CGeometry.hpp"
#include "../../include/solvers/CSolver.hpp"
CFlowOutput::CFlowOutput(CConfig *config, unsigned short nDim, bool fem_output) : COutput (config, nDim, fem_output){
}
CFlowOutput::~CFlowOutput(void){}
void CFlowOutput::AddAnalyzeSurfaceOutput(CConfig *config){
/// DESCRIPTION: Average mass flow
AddHistoryOutput("AVG_MASSFLOW", "Avg_Massflow", ScreenOutputFormat::SCIENTIFIC, "FLOW_COEFF", "Total average mass flow on all markers set in MARKER_ANALYZE", HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Average Mach number
AddHistoryOutput("AVG_MACH", "Avg_Mach", ScreenOutputFormat::SCIENTIFIC, "FLOW_COEFF", "Total average mach number on all markers set in MARKER_ANALYZE", HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Average Temperature
AddHistoryOutput("AVG_TEMP", "Avg_Temp", ScreenOutputFormat::SCIENTIFIC, "FLOW_COEFF", "Total average temperature on all markers set in MARKER_ANALYZE", HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Average Pressure
AddHistoryOutput("AVG_PRESS", "Avg_Press", ScreenOutputFormat::SCIENTIFIC, "FLOW_COEFF", "Total average pressure on all markers set in MARKER_ANALYZE", HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Average Density
AddHistoryOutput("AVG_DENSITY", "Avg_Density", ScreenOutputFormat::SCIENTIFIC, "FLOW_COEFF", "Total average density on all markers set in MARKER_ANALYZE", HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Average Enthalpy
AddHistoryOutput("AVG_ENTHALPY", "Avg_Enthalpy", ScreenOutputFormat::SCIENTIFIC, "FLOW_COEFF", "Total average enthalpy on all markers set in MARKER_ANALYZE", HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Average velocity in normal direction of the surface
AddHistoryOutput("AVG_NORMALVEL", "Avg_NormalVel", ScreenOutputFormat::SCIENTIFIC, "FLOW_COEFF", "Total average normal velocity on all markers set in MARKER_ANALYZE", HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Flow uniformity
AddHistoryOutput("UNIFORMITY", "Uniformity", ScreenOutputFormat::SCIENTIFIC, "FLOW_COEFF", "Total flow uniformity on all markers set in MARKER_ANALYZE", HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Secondary strength
AddHistoryOutput("SECONDARY_STRENGTH", "Secondary_Strength", ScreenOutputFormat::SCIENTIFIC, "FLOW_COEFF", "Total secondary strength on all markers set in MARKER_ANALYZE", HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Momentum distortion
AddHistoryOutput("MOMENTUM_DISTORTION", "Momentum_Distortion", ScreenOutputFormat::SCIENTIFIC, "FLOW_COEFF", "Total momentum distortion on all markers set in MARKER_ANALYZE", HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Secondary over uniformity
AddHistoryOutput("SECONDARY_OVER_UNIFORMITY", "Secondary_Over_Uniformity", ScreenOutputFormat::SCIENTIFIC, "FLOW_COEFF", "Total secondary over uniformity on all markers set in MARKER_ANALYZE", HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Average total temperature
AddHistoryOutput("AVG_TOTALTEMP", "Avg_TotalTemp", ScreenOutputFormat::SCIENTIFIC, "FLOW_COEFF", "Total average total temperature all markers set in MARKER_ANALYZE", HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Average total pressure
AddHistoryOutput("AVG_TOTALPRESS", "Avg_TotalPress", ScreenOutputFormat::SCIENTIFIC, "FLOW_COEFF", "Total average total pressure on all markers set in MARKER_ANALYZE", HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Pressure drop
AddHistoryOutput("PRESSURE_DROP", "Pressure_Drop", ScreenOutputFormat::SCIENTIFIC, "FLOW_COEFF", "Total pressure drop on all markers set in MARKER_ANALYZE", HistoryFieldType::COEFFICIENT);
/// END_GROUP
/// BEGIN_GROUP: AERO_COEFF_SURF, DESCRIPTION: Surface values on non-solid markers.
vector<string> Marker_Analyze;
for (unsigned short iMarker_Analyze = 0; iMarker_Analyze < config->GetnMarker_Analyze(); iMarker_Analyze++){
Marker_Analyze.push_back(config->GetMarker_Analyze_TagBound(iMarker_Analyze));
}
/// DESCRIPTION: Average mass flow
AddHistoryOutputPerSurface("AVG_MASSFLOW", "Avg_Massflow", ScreenOutputFormat::SCIENTIFIC, "FLOW_COEFF_SURF", Marker_Analyze, HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Average Mach number
AddHistoryOutputPerSurface("AVG_MACH", "Avg_Mach", ScreenOutputFormat::SCIENTIFIC, "FLOW_COEFF_SURF", Marker_Analyze, HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Average Temperature
AddHistoryOutputPerSurface("AVG_TEMP", "Avg_Temp", ScreenOutputFormat::SCIENTIFIC, "FLOW_COEFF_SURF", Marker_Analyze, HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Average Pressure
AddHistoryOutputPerSurface("AVG_PRESS", "Avg_Press", ScreenOutputFormat::SCIENTIFIC, "FLOW_COEFF_SURF", Marker_Analyze, HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Average Density
AddHistoryOutputPerSurface("AVG_DENSITY", "Avg_Density", ScreenOutputFormat::SCIENTIFIC, "FLOW_COEFF_SURF", Marker_Analyze, HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Average Enthalpy
AddHistoryOutputPerSurface("AVG_ENTHALPY", "Avg_Enthalpy", ScreenOutputFormat::SCIENTIFIC, "FLOW_COEFF_SURF", Marker_Analyze, HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Average velocity in normal direction of the surface
AddHistoryOutputPerSurface("AVG_NORMALVEL", "Avg_NormalVel", ScreenOutputFormat::SCIENTIFIC, "FLOW_COEFF_SURF", Marker_Analyze, HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Flow uniformity
AddHistoryOutputPerSurface("UNIFORMITY", "Uniformity", ScreenOutputFormat::SCIENTIFIC, "FLOW_COEFF_SURF", Marker_Analyze, HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Secondary strength
AddHistoryOutputPerSurface("SECONDARY_STRENGTH", "Secondary_Strength", ScreenOutputFormat::SCIENTIFIC, "FLOW_COEFF_SURF", Marker_Analyze, HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Momentum distortion
AddHistoryOutputPerSurface("MOMENTUM_DISTORTION", "Momentum_Distortion", ScreenOutputFormat::SCIENTIFIC, "FLOW_COEFF_SURF", Marker_Analyze, HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Secondary over uniformity
AddHistoryOutputPerSurface("SECONDARY_OVER_UNIFORMITY", "Secondary_Over_Uniformity", ScreenOutputFormat::SCIENTIFIC, "FLOW_COEFF_SURF", Marker_Analyze, HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Average total temperature
AddHistoryOutputPerSurface("AVG_TOTALTEMP", "Avg_TotalTemp", ScreenOutputFormat::SCIENTIFIC, "FLOW_COEFF_SURF", Marker_Analyze, HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Average total pressure
AddHistoryOutputPerSurface("AVG_TOTALPRESS", "Avg_TotalPress", ScreenOutputFormat::SCIENTIFIC, "FLOW_COEFF_SURF", Marker_Analyze, HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Pressure drop
AddHistoryOutputPerSurface("PRESSURE_DROP", "Pressure_Drop", ScreenOutputFormat::SCIENTIFIC, "FLOW_COEFF_SURF", Marker_Analyze, HistoryFieldType::COEFFICIENT);
/// END_GROUP
}
void CFlowOutput::SetAnalyzeSurface(CSolver *solver, CGeometry *geometry, CConfig *config, bool output){
unsigned short iDim, iMarker, iMarker_Analyze;
unsigned long iVertex, iPoint;
su2double Mach = 0.0, Pressure, Temperature = 0.0, TotalPressure = 0.0, TotalTemperature = 0.0,
Enthalpy, Velocity[3] = {}, TangVel[3], Velocity2, MassFlow, Density, Area,
AxiFactor = 1.0, SoundSpeed, Vn, Vn2, Vtang2, Weight = 1.0;
su2double Gas_Constant = config->GetGas_ConstantND();
su2double Gamma = config->GetGamma();
unsigned short nMarker = config->GetnMarker_All();
unsigned short nDim = geometry->GetnDim();
unsigned short Kind_Average = config->GetKind_Average();
bool compressible = config->GetKind_Regime() == COMPRESSIBLE;
bool incompressible = config->GetKind_Regime() == INCOMPRESSIBLE;
bool energy = config->GetEnergy_Equation();
bool axisymmetric = config->GetAxisymmetric();
unsigned short nMarker_Analyze = config->GetnMarker_Analyze();
su2double *Vector = new su2double[nDim];
su2double *Surface_MassFlow = new su2double[nMarker];
su2double *Surface_Mach = new su2double[nMarker];
su2double *Surface_Temperature = new su2double[nMarker];
su2double *Surface_Density = new su2double[nMarker];
su2double *Surface_Enthalpy = new su2double[nMarker];
su2double *Surface_NormalVelocity = new su2double[nMarker];
su2double *Surface_StreamVelocity2 = new su2double[nMarker];
su2double *Surface_TransvVelocity2 = new su2double[nMarker];
su2double *Surface_Pressure = new su2double[nMarker];
su2double *Surface_TotalTemperature = new su2double[nMarker];
su2double *Surface_TotalPressure = new su2double[nMarker];
su2double *Surface_VelocityIdeal = new su2double[nMarker];
su2double *Surface_Area = new su2double[nMarker];
su2double *Surface_MassFlow_Abs = new su2double[nMarker];
su2double Tot_Surface_MassFlow = 0.0;
su2double Tot_Surface_Mach = 0.0;
su2double Tot_Surface_Temperature = 0.0;
su2double Tot_Surface_Density = 0.0;
su2double Tot_Surface_Enthalpy = 0.0;
su2double Tot_Surface_NormalVelocity = 0.0;
su2double Tot_Surface_StreamVelocity2 = 0.0;
su2double Tot_Surface_TransvVelocity2 = 0.0;
su2double Tot_Surface_Pressure = 0.0;
su2double Tot_Surface_TotalTemperature = 0.0;
su2double Tot_Surface_TotalPressure = 0.0;
su2double Tot_Momentum_Distortion = 0.0;
su2double Tot_SecondOverUniformity = 0.0;
su2double Tot_Surface_PressureDrop = 0.0;
/*--- Compute the numerical fan face Mach number, and the total area of the inflow ---*/
for (iMarker = 0; iMarker < nMarker; iMarker++) {
Surface_MassFlow[iMarker] = 0.0;
Surface_Mach[iMarker] = 0.0;
Surface_Temperature[iMarker] = 0.0;
Surface_Density[iMarker] = 0.0;
Surface_Enthalpy[iMarker] = 0.0;
Surface_NormalVelocity[iMarker] = 0.0;
Surface_StreamVelocity2[iMarker] = 0.0;
Surface_TransvVelocity2[iMarker] = 0.0;
Surface_Pressure[iMarker] = 0.0;
Surface_TotalTemperature[iMarker] = 0.0;
Surface_TotalPressure[iMarker] = 0.0;
Surface_VelocityIdeal[iMarker] = 0.0;
Surface_Area[iMarker] = 0.0;
Surface_MassFlow_Abs[iMarker] = 0.0;
if (config->GetMarker_All_Analyze(iMarker) == YES) {
for (iVertex = 0; iVertex < geometry->nVertex[iMarker]; iVertex++) {
iPoint = geometry->vertex[iMarker][iVertex]->GetNode();
if (geometry->nodes->GetDomain(iPoint)) {
geometry->vertex[iMarker][iVertex]->GetNormal(Vector);
if (axisymmetric) {
if (geometry->nodes->GetCoord(iPoint, 1) != 0.0)
AxiFactor = 2.0*PI_NUMBER*geometry->nodes->GetCoord(iPoint, 1);
else {
/*--- Find the point "above" by finding the neighbor of iPoint that is also a vertex of iMarker. ---*/
AxiFactor = 0.0;
for (unsigned short iNeigh = 0; iNeigh < geometry->nodes->GetnPoint(iPoint); ++iNeigh) {
auto jPoint = geometry->nodes->GetPoint(iPoint, iNeigh);
if (geometry->nodes->GetVertex(jPoint, iMarker) >= 0) {
/*--- Not multiplied by two since we need to half the y coordinate. ---*/
AxiFactor = PI_NUMBER * geometry->nodes->GetCoord(jPoint, 1);
break;
}
}
}
} else {
AxiFactor = 1.0;
}
Density = solver->GetNodes()->GetDensity(iPoint);
Velocity2 = 0.0; Area = 0.0; MassFlow = 0.0; Vn = 0.0; Vtang2 = 0.0;
for (iDim = 0; iDim < nDim; iDim++) {
Area += (Vector[iDim] * AxiFactor) * (Vector[iDim] * AxiFactor);
Velocity[iDim] = solver->GetNodes()->GetVelocity(iPoint,iDim);
Velocity2 += Velocity[iDim] * Velocity[iDim];
Vn += Velocity[iDim] * Vector[iDim] * AxiFactor;
MassFlow += Vector[iDim] * AxiFactor * Density * Velocity[iDim];
}
Area = sqrt (Area);
if (AxiFactor == 0.0) Vn = 0.0; else Vn /= Area;
Vn2 = Vn * Vn;
Pressure = solver->GetNodes()->GetPressure(iPoint);
SoundSpeed = solver->GetNodes()->GetSoundSpeed(iPoint);
for (iDim = 0; iDim < nDim; iDim++) {
TangVel[iDim] = Velocity[iDim] - Vn*Vector[iDim]*AxiFactor/Area;
Vtang2 += TangVel[iDim]*TangVel[iDim];
}
if (incompressible){
if (config->GetKind_DensityModel() == VARIABLE) {
Mach = sqrt(solver->GetNodes()->GetVelocity2(iPoint))/
sqrt(solver->GetNodes()->GetSpecificHeatCp(iPoint)*config->GetPressure_ThermodynamicND()/(solver->GetNodes()->GetSpecificHeatCv(iPoint)*solver->GetNodes()->GetDensity(iPoint)));
} else {
Mach = sqrt(solver->GetNodes()->GetVelocity2(iPoint))/
sqrt(config->GetBulk_Modulus()/(solver->GetNodes()->GetDensity(iPoint)));
}
Temperature = solver->GetNodes()->GetTemperature(iPoint);
Enthalpy = solver->GetNodes()->GetSpecificHeatCp(iPoint)*Temperature;
TotalTemperature = Temperature + 0.5*Velocity2/solver->GetNodes()->GetSpecificHeatCp(iPoint);
TotalPressure = Pressure + 0.5*Density*Velocity2;
}
else{
Mach = sqrt(Velocity2)/SoundSpeed;
Temperature = Pressure / (Gas_Constant * Density);
Enthalpy = solver->GetNodes()->GetEnthalpy(iPoint);
TotalTemperature = Temperature * (1.0 + Mach * Mach * 0.5 * (Gamma - 1.0));
TotalPressure = Pressure * pow( 1.0 + Mach * Mach * 0.5 * (Gamma - 1.0), Gamma / (Gamma - 1.0));
}
/*--- Compute the mass Surface_MassFlow ---*/
Surface_Area[iMarker] += Area;
Surface_MassFlow[iMarker] += MassFlow;
Surface_MassFlow_Abs[iMarker] += abs(MassFlow);
if (Kind_Average == AVERAGE_MASSFLUX) Weight = abs(MassFlow);
else if (Kind_Average == AVERAGE_AREA) Weight = abs(Area);
else Weight = 1.0;
Surface_Mach[iMarker] += Mach*Weight;
Surface_Temperature[iMarker] += Temperature*Weight;
Surface_Density[iMarker] += Density*Weight;
Surface_Enthalpy[iMarker] += Enthalpy*Weight;
Surface_NormalVelocity[iMarker] += Vn*Weight;
Surface_Pressure[iMarker] += Pressure*Weight;
Surface_TotalTemperature[iMarker] += TotalTemperature*Weight;
Surface_TotalPressure[iMarker] += TotalPressure*Weight;
/*--- For now, always used the area to weight the uniformities. ---*/
Weight = abs(Area);
Surface_StreamVelocity2[iMarker] += Vn2*Weight;
Surface_TransvVelocity2[iMarker] += Vtang2*Weight;
}
}
}
}
/*--- Copy to the appropriate structure ---*/
su2double *Surface_MassFlow_Local = new su2double [nMarker_Analyze];
su2double *Surface_Mach_Local = new su2double [nMarker_Analyze];
su2double *Surface_Temperature_Local = new su2double [nMarker_Analyze];
su2double *Surface_Density_Local = new su2double [nMarker_Analyze];
su2double *Surface_Enthalpy_Local = new su2double [nMarker_Analyze];
su2double *Surface_NormalVelocity_Local = new su2double [nMarker_Analyze];
su2double *Surface_StreamVelocity2_Local = new su2double [nMarker_Analyze];
su2double *Surface_TransvVelocity2_Local = new su2double [nMarker_Analyze];
su2double *Surface_Pressure_Local = new su2double [nMarker_Analyze];
su2double *Surface_TotalTemperature_Local = new su2double [nMarker_Analyze];
su2double *Surface_TotalPressure_Local = new su2double [nMarker_Analyze];
su2double *Surface_Area_Local = new su2double [nMarker_Analyze];
su2double *Surface_MassFlow_Abs_Local = new su2double [nMarker_Analyze];
su2double *Surface_MassFlow_Total = new su2double [nMarker_Analyze];
su2double *Surface_Mach_Total = new su2double [nMarker_Analyze];
su2double *Surface_Temperature_Total = new su2double [nMarker_Analyze];
su2double *Surface_Density_Total = new su2double [nMarker_Analyze];
su2double *Surface_Enthalpy_Total = new su2double [nMarker_Analyze];
su2double *Surface_NormalVelocity_Total = new su2double [nMarker_Analyze];
su2double *Surface_StreamVelocity2_Total = new su2double [nMarker_Analyze];
su2double *Surface_TransvVelocity2_Total = new su2double [nMarker_Analyze];
su2double *Surface_Pressure_Total = new su2double [nMarker_Analyze];
su2double *Surface_TotalTemperature_Total = new su2double [nMarker_Analyze];
su2double *Surface_TotalPressure_Total = new su2double [nMarker_Analyze];
su2double *Surface_Area_Total = new su2double [nMarker_Analyze];
su2double *Surface_MassFlow_Abs_Total = new su2double [nMarker_Analyze];
su2double *Surface_MomentumDistortion_Total = new su2double [nMarker_Analyze];
for (iMarker_Analyze = 0; iMarker_Analyze < nMarker_Analyze; iMarker_Analyze++) {
Surface_MassFlow_Local[iMarker_Analyze] = 0.0;
Surface_Mach_Local[iMarker_Analyze] = 0.0;
Surface_Temperature_Local[iMarker_Analyze] = 0.0;
Surface_Density_Local[iMarker_Analyze] = 0.0;
Surface_Enthalpy_Local[iMarker_Analyze] = 0.0;
Surface_NormalVelocity_Local[iMarker_Analyze] = 0.0;
Surface_StreamVelocity2_Local[iMarker_Analyze] = 0.0;
Surface_TransvVelocity2_Local[iMarker_Analyze] = 0.0;
Surface_Pressure_Local[iMarker_Analyze] = 0.0;
Surface_TotalTemperature_Local[iMarker_Analyze] = 0.0;
Surface_TotalPressure_Local[iMarker_Analyze] = 0.0;
Surface_Area_Local[iMarker_Analyze] = 0.0;
Surface_MassFlow_Abs_Local[iMarker_Analyze] = 0.0;
Surface_MassFlow_Total[iMarker_Analyze] = 0.0;
Surface_Mach_Total[iMarker_Analyze] = 0.0;
Surface_Temperature_Total[iMarker_Analyze] = 0.0;
Surface_Density_Total[iMarker_Analyze] = 0.0;
Surface_Enthalpy_Total[iMarker_Analyze] = 0.0;
Surface_NormalVelocity_Total[iMarker_Analyze] = 0.0;
Surface_StreamVelocity2_Total[iMarker_Analyze] = 0.0;
Surface_TransvVelocity2_Total[iMarker_Analyze] = 0.0;
Surface_Pressure_Total[iMarker_Analyze] = 0.0;
Surface_TotalTemperature_Total[iMarker_Analyze] = 0.0;
Surface_TotalPressure_Total[iMarker_Analyze] = 0.0;
Surface_Area_Total[iMarker_Analyze] = 0.0;
Surface_MassFlow_Abs_Total[iMarker_Analyze] = 0.0;
Surface_MomentumDistortion_Total[iMarker_Analyze] = 0.0;
}
/*--- Compute the numerical fan face Mach number, mach number, temperature and the total area ---*/
for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) {
if (config->GetMarker_All_Analyze(iMarker) == YES) {
for (iMarker_Analyze= 0; iMarker_Analyze < nMarker_Analyze; iMarker_Analyze++) {
/*--- Add the Surface_MassFlow, and Surface_Area to the particular boundary ---*/
if (config->GetMarker_All_TagBound(iMarker) == config->GetMarker_Analyze_TagBound(iMarker_Analyze)) {
Surface_MassFlow_Local[iMarker_Analyze] += Surface_MassFlow[iMarker];
Surface_Mach_Local[iMarker_Analyze] += Surface_Mach[iMarker];
Surface_Temperature_Local[iMarker_Analyze] += Surface_Temperature[iMarker];
Surface_Density_Local[iMarker_Analyze] += Surface_Density[iMarker];
Surface_Enthalpy_Local[iMarker_Analyze] += Surface_Enthalpy[iMarker];
Surface_NormalVelocity_Local[iMarker_Analyze] += Surface_NormalVelocity[iMarker];
Surface_StreamVelocity2_Local[iMarker_Analyze] += Surface_StreamVelocity2[iMarker];
Surface_TransvVelocity2_Local[iMarker_Analyze] += Surface_TransvVelocity2[iMarker];
Surface_Pressure_Local[iMarker_Analyze] += Surface_Pressure[iMarker];
Surface_TotalTemperature_Local[iMarker_Analyze] += Surface_TotalTemperature[iMarker];
Surface_TotalPressure_Local[iMarker_Analyze] += Surface_TotalPressure[iMarker];
Surface_Area_Local[iMarker_Analyze] += Surface_Area[iMarker];
Surface_MassFlow_Abs_Local[iMarker_Analyze] += Surface_MassFlow_Abs[iMarker];
}
}
}
}
#ifdef HAVE_MPI
SU2_MPI::Allreduce(Surface_MassFlow_Local, Surface_MassFlow_Total, nMarker_Analyze, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
SU2_MPI::Allreduce(Surface_Mach_Local, Surface_Mach_Total, nMarker_Analyze, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
SU2_MPI::Allreduce(Surface_Temperature_Local, Surface_Temperature_Total, nMarker_Analyze, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
SU2_MPI::Allreduce(Surface_Density_Local, Surface_Density_Total, nMarker_Analyze, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
SU2_MPI::Allreduce(Surface_Enthalpy_Local, Surface_Enthalpy_Total, nMarker_Analyze, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
SU2_MPI::Allreduce(Surface_NormalVelocity_Local, Surface_NormalVelocity_Total, nMarker_Analyze, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
SU2_MPI::Allreduce(Surface_StreamVelocity2_Local, Surface_StreamVelocity2_Total, nMarker_Analyze, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
SU2_MPI::Allreduce(Surface_TransvVelocity2_Local, Surface_TransvVelocity2_Total, nMarker_Analyze, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
SU2_MPI::Allreduce(Surface_Pressure_Local, Surface_Pressure_Total, nMarker_Analyze, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
SU2_MPI::Allreduce(Surface_TotalTemperature_Local, Surface_TotalTemperature_Total, nMarker_Analyze, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
SU2_MPI::Allreduce(Surface_TotalPressure_Local, Surface_TotalPressure_Total, nMarker_Analyze, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
SU2_MPI::Allreduce(Surface_Area_Local, Surface_Area_Total, nMarker_Analyze, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
SU2_MPI::Allreduce(Surface_MassFlow_Abs_Local, Surface_MassFlow_Abs_Total, nMarker_Analyze, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#else
for (iMarker_Analyze = 0; iMarker_Analyze < nMarker_Analyze; iMarker_Analyze++) {
Surface_MassFlow_Total[iMarker_Analyze] = Surface_MassFlow_Local[iMarker_Analyze];
Surface_Mach_Total[iMarker_Analyze] = Surface_Mach_Local[iMarker_Analyze];
Surface_Temperature_Total[iMarker_Analyze] = Surface_Temperature_Local[iMarker_Analyze];
Surface_Density_Total[iMarker_Analyze] = Surface_Density_Local[iMarker_Analyze];
Surface_Enthalpy_Total[iMarker_Analyze] = Surface_Enthalpy_Local[iMarker_Analyze];
Surface_NormalVelocity_Total[iMarker_Analyze] = Surface_NormalVelocity_Local[iMarker_Analyze];
Surface_StreamVelocity2_Total[iMarker_Analyze] = Surface_StreamVelocity2_Local[iMarker_Analyze];
Surface_TransvVelocity2_Total[iMarker_Analyze] = Surface_TransvVelocity2_Local[iMarker_Analyze];
Surface_Pressure_Total[iMarker_Analyze] = Surface_Pressure_Local[iMarker_Analyze];
Surface_TotalTemperature_Total[iMarker_Analyze] = Surface_TotalTemperature_Local[iMarker_Analyze];
Surface_TotalPressure_Total[iMarker_Analyze] = Surface_TotalPressure_Local[iMarker_Analyze];
Surface_Area_Total[iMarker_Analyze] = Surface_Area_Local[iMarker_Analyze];
Surface_MassFlow_Abs_Total[iMarker_Analyze] = Surface_MassFlow_Abs_Local[iMarker_Analyze];
}
#endif
/*--- Compute the value of Surface_Area_Total, and Surface_Pressure_Total, and
set the value in the config structure for future use ---*/
for (iMarker_Analyze = 0; iMarker_Analyze < nMarker_Analyze; iMarker_Analyze++) {
if (Kind_Average == AVERAGE_MASSFLUX) Weight = Surface_MassFlow_Abs_Total[iMarker_Analyze];
else if (Kind_Average == AVERAGE_AREA) Weight = abs(Surface_Area_Total[iMarker_Analyze]);
else Weight = 1.0;
if (Weight != 0.0) {
Surface_Mach_Total[iMarker_Analyze] /= Weight;
Surface_Temperature_Total[iMarker_Analyze] /= Weight;
Surface_Density_Total[iMarker_Analyze] /= Weight;
Surface_Enthalpy_Total[iMarker_Analyze] /= Weight;
Surface_NormalVelocity_Total[iMarker_Analyze] /= Weight;
Surface_Pressure_Total[iMarker_Analyze] /= Weight;
Surface_TotalTemperature_Total[iMarker_Analyze] /= Weight;
Surface_TotalPressure_Total[iMarker_Analyze] /= Weight;
}
else {
Surface_Mach_Total[iMarker_Analyze] = 0.0;
Surface_Temperature_Total[iMarker_Analyze] = 0.0;
Surface_Density_Total[iMarker_Analyze] = 0.0;
Surface_Enthalpy_Total[iMarker_Analyze] = 0.0;
Surface_NormalVelocity_Total[iMarker_Analyze] = 0.0;
Surface_Pressure_Total[iMarker_Analyze] = 0.0;
Surface_TotalTemperature_Total[iMarker_Analyze] = 0.0;
Surface_TotalPressure_Total[iMarker_Analyze] = 0.0;
}
/*--- Compute flow uniformity parameters separately (always area for now). ---*/
Area = fabs(Surface_Area_Total[iMarker_Analyze]);
/*--- The definitions for Distortion and Uniformity Parameters are taken as defined by Banko, Andrew J., et al. in section 3.2 of
https://www.sciencedirect.com/science/article/pii/S0142727X16301412 ------*/
if (Area != 0.0) {
Surface_MomentumDistortion_Total[iMarker_Analyze] = Surface_StreamVelocity2_Total[iMarker_Analyze]/(Surface_NormalVelocity_Total[iMarker_Analyze]*Surface_NormalVelocity_Total[iMarker_Analyze]*Area) - 1.0;
Surface_StreamVelocity2_Total[iMarker_Analyze] /= Area;
Surface_TransvVelocity2_Total[iMarker_Analyze] /= Area;
}
else {
Surface_MomentumDistortion_Total[iMarker_Analyze] = 0.0;
Surface_StreamVelocity2_Total[iMarker_Analyze] = 0.0;
Surface_TransvVelocity2_Total[iMarker_Analyze] = 0.0;
}
}
for (iMarker_Analyze = 0; iMarker_Analyze < nMarker_Analyze; iMarker_Analyze++) {
su2double MassFlow = Surface_MassFlow_Total[iMarker_Analyze] * config->GetDensity_Ref() * config->GetVelocity_Ref();
if (config->GetSystemMeasurements() == US) MassFlow *= 32.174;
SetHistoryOutputPerSurfaceValue("AVG_MASSFLOW", MassFlow, iMarker_Analyze);
Tot_Surface_MassFlow += MassFlow;
config->SetSurface_MassFlow(iMarker_Analyze, MassFlow);
su2double Mach = Surface_Mach_Total[iMarker_Analyze];
SetHistoryOutputPerSurfaceValue("AVG_MACH", Mach, iMarker_Analyze);
Tot_Surface_Mach += Mach;
config->SetSurface_Mach(iMarker_Analyze, Mach);
su2double Temperature = Surface_Temperature_Total[iMarker_Analyze] * config->GetTemperature_Ref();
SetHistoryOutputPerSurfaceValue("AVG_TEMP", Temperature, iMarker_Analyze);
Tot_Surface_Temperature += Temperature;
config->SetSurface_Temperature(iMarker_Analyze, Temperature);
su2double Pressure = Surface_Pressure_Total[iMarker_Analyze] * config->GetPressure_Ref();
SetHistoryOutputPerSurfaceValue("AVG_PRESS", Pressure, iMarker_Analyze);
Tot_Surface_Pressure += Pressure;
config->SetSurface_Pressure(iMarker_Analyze, Pressure);
su2double Density = Surface_Density_Total[iMarker_Analyze] * config->GetDensity_Ref();
SetHistoryOutputPerSurfaceValue("AVG_DENSITY", Density, iMarker_Analyze);
Tot_Surface_Density += Density;
config->SetSurface_Density(iMarker_Analyze, Density);
su2double Enthalpy = Surface_Enthalpy_Total[iMarker_Analyze];
SetHistoryOutputPerSurfaceValue("AVG_ENTHALPY", Enthalpy, iMarker_Analyze);
Tot_Surface_Enthalpy += Enthalpy;
config->SetSurface_Enthalpy(iMarker_Analyze, Enthalpy);
su2double NormalVelocity = Surface_NormalVelocity_Total[iMarker_Analyze] * config->GetVelocity_Ref();
SetHistoryOutputPerSurfaceValue("AVG_NORMALVEL", NormalVelocity, iMarker_Analyze);
Tot_Surface_NormalVelocity += NormalVelocity;
config->SetSurface_NormalVelocity(iMarker_Analyze, NormalVelocity);
su2double Uniformity = sqrt(Surface_StreamVelocity2_Total[iMarker_Analyze]) * config->GetVelocity_Ref();
SetHistoryOutputPerSurfaceValue("UNIFORMITY", Uniformity, iMarker_Analyze);
Tot_Surface_StreamVelocity2 += Uniformity;
config->SetSurface_Uniformity(iMarker_Analyze, Uniformity);
su2double SecondaryStrength = sqrt(Surface_TransvVelocity2_Total[iMarker_Analyze]) * config->GetVelocity_Ref();
SetHistoryOutputPerSurfaceValue("SECONDARY_STRENGTH", SecondaryStrength, iMarker_Analyze);
Tot_Surface_TransvVelocity2 += SecondaryStrength;
config->SetSurface_SecondaryStrength(iMarker_Analyze, SecondaryStrength);
su2double MomentumDistortion = Surface_MomentumDistortion_Total[iMarker_Analyze];
SetHistoryOutputPerSurfaceValue("MOMENTUM_DISTORTION", MomentumDistortion, iMarker_Analyze);
Tot_Momentum_Distortion += MomentumDistortion;
config->SetSurface_MomentumDistortion(iMarker_Analyze, MomentumDistortion);
su2double SecondOverUniform = SecondaryStrength/Uniformity;
SetHistoryOutputPerSurfaceValue("SECONDARY_OVER_UNIFORMITY", SecondOverUniform, iMarker_Analyze);
Tot_SecondOverUniformity += SecondOverUniform;
config->SetSurface_SecondOverUniform(iMarker_Analyze, SecondOverUniform);
su2double TotalTemperature = Surface_TotalTemperature_Total[iMarker_Analyze] * config->GetTemperature_Ref();
SetHistoryOutputPerSurfaceValue("AVG_TOTALTEMP", TotalTemperature, iMarker_Analyze);
Tot_Surface_TotalTemperature += TotalTemperature;
config->SetSurface_TotalTemperature(iMarker_Analyze, TotalTemperature);
su2double TotalPressure = Surface_TotalPressure_Total[iMarker_Analyze] * config->GetPressure_Ref();
SetHistoryOutputPerSurfaceValue("AVG_TOTALPRESS", TotalPressure, iMarker_Analyze);
Tot_Surface_TotalPressure += TotalPressure;
config->SetSurface_TotalPressure(iMarker_Analyze, TotalPressure);
}
/*--- Compute the average static pressure drop between two surfaces. Note
that this assumes we have two surfaces being analyzed and that the outlet
is first followed by the inlet. This is because we may also want to choose
outlet values (temperature, uniformity, etc.) for our design problems,
which require the outlet to be listed first. This is a simple first version
that could be generalized to a different orders/lists/etc. ---*/
for (iMarker_Analyze = 0; iMarker_Analyze < nMarker_Analyze; iMarker_Analyze++) {
su2double Pressure_Drop = 0.0;
if (nMarker_Analyze == 2) {
Pressure_Drop = (Surface_Pressure_Total[1]-Surface_Pressure_Total[0]) * config->GetPressure_Ref();
config->SetSurface_PressureDrop(iMarker_Analyze, Pressure_Drop);
}
SetHistoryOutputPerSurfaceValue("PRESSURE_DROP", Pressure_Drop, iMarker_Analyze);
Tot_Surface_PressureDrop += Pressure_Drop;
}
SetHistoryOutputValue("AVG_MASSFLOW", Tot_Surface_MassFlow);
SetHistoryOutputValue("AVG_MACH", Tot_Surface_Mach);
SetHistoryOutputValue("AVG_TEMP", Tot_Surface_Temperature);
SetHistoryOutputValue("AVG_PRESS", Tot_Surface_Pressure);
SetHistoryOutputValue("AVG_DENSITY", Tot_Surface_Density);
SetHistoryOutputValue("AVG_ENTHALPY", Tot_Surface_Enthalpy);
SetHistoryOutputValue("AVG_NORMALVEL", Tot_Surface_Enthalpy);
SetHistoryOutputValue("UNIFORMITY", Tot_Surface_StreamVelocity2);
SetHistoryOutputValue("SECONDARY_STRENGTH", Tot_Surface_TransvVelocity2);
SetHistoryOutputValue("MOMENTUM_DISTORTION", Tot_Momentum_Distortion);
SetHistoryOutputValue("SECONDARY_OVER_UNIFORMITY", Tot_SecondOverUniformity);
SetHistoryOutputValue("AVG_TOTALTEMP", Tot_Surface_TotalTemperature);
SetHistoryOutputValue("AVG_TOTALPRESS", Tot_Surface_TotalPressure);
SetHistoryOutputValue("PRESSURE_DROP", Tot_Surface_PressureDrop);
if ((rank == MASTER_NODE) && !config->GetDiscrete_Adjoint() && output) {
cout.precision(6);
cout.setf(ios::scientific, ios::floatfield);
cout << endl << "Computing surface mean values." << endl << endl;
for (iMarker_Analyze = 0; iMarker_Analyze < nMarker_Analyze; iMarker_Analyze++) {
cout << "Surface "<< config->GetMarker_Analyze_TagBound(iMarker_Analyze) << ":" << endl;
if (nDim == 3) { if (config->GetSystemMeasurements() == SI) cout << setw(20) << "Area (m^2): "; else cout << setw(20) << "Area (ft^2): "; }
else { if (config->GetSystemMeasurements() == SI) cout << setw(20) << "Area (m): "; else cout << setw(20) << "Area (ft): "; }
if (config->GetSystemMeasurements() == SI) cout << setw(15) << fabs(Surface_Area_Total[iMarker_Analyze]);
else if (config->GetSystemMeasurements() == US) cout << setw(15) << fabs(Surface_Area_Total[iMarker_Analyze])*12.0*12.0;
cout << endl;
su2double MassFlow = config->GetSurface_MassFlow(iMarker_Analyze);
if (config->GetSystemMeasurements() == SI) cout << setw(20) << "Mf (kg/s): " << setw(15) << MassFlow;
else if (config->GetSystemMeasurements() == US) cout << setw(20) << "Mf (lbs/s): " << setw(15) << MassFlow;
su2double NormalVelocity = config->GetSurface_NormalVelocity(iMarker_Analyze);
if (config->GetSystemMeasurements() == SI) cout << setw(20) << "Vn (m/s): " << setw(15) << NormalVelocity;
else if (config->GetSystemMeasurements() == US) cout << setw(20) << "Vn (ft/s): " << setw(15) << NormalVelocity;
cout << endl;
su2double Uniformity = config->GetSurface_Uniformity(iMarker_Analyze);
if (config->GetSystemMeasurements() == SI) cout << setw(20) << "Uniformity (m/s): " << setw(15) << Uniformity;
else if (config->GetSystemMeasurements() == US) cout << setw(20) << "Uniformity (ft/s): " << setw(15) << Uniformity;
su2double SecondaryStrength = config->GetSurface_SecondaryStrength(iMarker_Analyze);
if (config->GetSystemMeasurements() == SI) cout << setw(20) << "Secondary (m/s): " << setw(15) << SecondaryStrength;
else if (config->GetSystemMeasurements() == US) cout << setw(20) << "Secondary (ft/s): " << setw(15) << SecondaryStrength;
cout << endl;
su2double MomentumDistortion = config->GetSurface_MomentumDistortion(iMarker_Analyze);
cout << setw(20) << "Mom. Distortion: " << setw(15) << MomentumDistortion;
su2double SecondOverUniform = config->GetSurface_SecondOverUniform(iMarker_Analyze);
cout << setw(20) << "Second/Uniform: " << setw(15) << SecondOverUniform;
cout << endl;
su2double Pressure = config->GetSurface_Pressure(iMarker_Analyze);
if (config->GetSystemMeasurements() == SI) cout << setw(20) << "P (Pa): " << setw(15) << Pressure;
else if (config->GetSystemMeasurements() == US) cout << setw(20) << "P (psf): " << setw(15) << Pressure;
su2double TotalPressure = config->GetSurface_TotalPressure(iMarker_Analyze);
if (config->GetSystemMeasurements() == SI) cout << setw(20) << "PT (Pa): " << setw(15) <<TotalPressure;
else if (config->GetSystemMeasurements() == US) cout << setw(20) << "PT (psf): " << setw(15) <<TotalPressure;
cout << endl;
su2double Mach = config->GetSurface_Mach(iMarker_Analyze);
cout << setw(20) << "Mach: " << setw(15) << Mach;
su2double Density = config->GetSurface_Density(iMarker_Analyze);
if (config->GetSystemMeasurements() == SI) cout << setw(20) << "Rho (kg/m^3): " << setw(15) << Density;
else if (config->GetSystemMeasurements() == US) cout << setw(20) << "Rho (lb/ft^3): " << setw(15) << Density*32.174;
cout << endl;
if (compressible || energy) {
su2double Temperature = config->GetSurface_Temperature(iMarker_Analyze);
if (config->GetSystemMeasurements() == SI) cout << setw(20) << "T (K): " << setw(15) << Temperature;
else if (config->GetSystemMeasurements() == US) cout << setw(20) << "T (R): " << setw(15) << Temperature;
su2double TotalTemperature = config->GetSurface_TotalTemperature(iMarker_Analyze);
if (config->GetSystemMeasurements() == SI) cout << setw(20) << "TT (K): " << setw(15) << TotalTemperature;
else if (config->GetSystemMeasurements() == US) cout << setw(20) << "TT (R): " << setw(15) << TotalTemperature;
cout << endl;
}
}
cout.unsetf(ios_base::floatfield);
}
delete [] Surface_MassFlow_Local;
delete [] Surface_Mach_Local;
delete [] Surface_Temperature_Local;
delete [] Surface_Density_Local;
delete [] Surface_Enthalpy_Local;
delete [] Surface_NormalVelocity_Local;
delete [] Surface_StreamVelocity2_Local;
delete [] Surface_TransvVelocity2_Local;
delete [] Surface_Pressure_Local;
delete [] Surface_TotalTemperature_Local;
delete [] Surface_TotalPressure_Local;
delete [] Surface_Area_Local;
delete [] Surface_MassFlow_Abs_Local;
delete [] Surface_MassFlow_Total;
delete [] Surface_Mach_Total;
delete [] Surface_Temperature_Total;
delete [] Surface_Density_Total;
delete [] Surface_Enthalpy_Total;
delete [] Surface_NormalVelocity_Total;
delete [] Surface_StreamVelocity2_Total;
delete [] Surface_TransvVelocity2_Total;
delete [] Surface_Pressure_Total;
delete [] Surface_TotalTemperature_Total;
delete [] Surface_TotalPressure_Total;
delete [] Surface_Area_Total;
delete [] Surface_MassFlow_Abs_Total;
delete [] Surface_MomentumDistortion_Total;
delete [] Surface_MassFlow;
delete [] Surface_Mach;
delete [] Surface_Temperature;
delete [] Surface_Density;
delete [] Surface_Enthalpy;
delete [] Surface_NormalVelocity;
delete [] Surface_StreamVelocity2;
delete [] Surface_TransvVelocity2;
delete [] Surface_Pressure;
delete [] Surface_TotalTemperature;
delete [] Surface_TotalPressure;
delete [] Surface_Area;
delete [] Vector;
delete [] Surface_VelocityIdeal;
delete [] Surface_MassFlow_Abs;
std::cout << std::resetiosflags(std::cout.flags());
}
void CFlowOutput::AddAerodynamicCoefficients(CConfig *config){
/// BEGIN_GROUP: AERO_COEFF, DESCRIPTION: Sum of the aerodynamic coefficients and forces on all surfaces (markers) set with MARKER_MONITORING.
/// DESCRIPTION: Drag coefficient
AddHistoryOutput("DRAG", "CD", ScreenOutputFormat::FIXED, "AERO_COEFF", "Total drag coefficient on all surfaces set with MARKER_MONITORING", HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Lift coefficient
AddHistoryOutput("LIFT", "CL", ScreenOutputFormat::FIXED, "AERO_COEFF", "Total lift coefficient on all surfaces set with MARKER_MONITORING", HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Sideforce coefficient
AddHistoryOutput("SIDEFORCE", "CSF", ScreenOutputFormat::FIXED, "AERO_COEFF", "Total sideforce coefficient on all surfaces set with MARKER_MONITORING", HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Moment around the x-axis
AddHistoryOutput("MOMENT_X", "CMx", ScreenOutputFormat::FIXED, "AERO_COEFF", "Total momentum x-component on all surfaces set with MARKER_MONITORING", HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Moment around the y-axis
AddHistoryOutput("MOMENT_Y", "CMy", ScreenOutputFormat::FIXED, "AERO_COEFF", "Total momentum y-component on all surfaces set with MARKER_MONITORING", HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Moment around the z-axis
AddHistoryOutput("MOMENT_Z", "CMz", ScreenOutputFormat::FIXED, "AERO_COEFF", "Total momentum z-component on all surfaces set with MARKER_MONITORING", HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Force in x direction
AddHistoryOutput("FORCE_X", "CFx", ScreenOutputFormat::FIXED, "AERO_COEFF", "Total force x-component on all surfaces set with MARKER_MONITORING", HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Force in y direction
AddHistoryOutput("FORCE_Y", "CFy", ScreenOutputFormat::FIXED, "AERO_COEFF", "Total force y-component on all surfaces set with MARKER_MONITORING", HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Force in z direction
AddHistoryOutput("FORCE_Z", "CFz", ScreenOutputFormat::FIXED, "AERO_COEFF", "Total force z-component on all surfaces set with MARKER_MONITORING", HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Lift-to-drag ratio
AddHistoryOutput("EFFICIENCY", "CEff", ScreenOutputFormat::FIXED, "AERO_COEFF", "Total lift-to-drag ratio on all surfaces set with MARKER_MONITORING", HistoryFieldType::COEFFICIENT);
/// END_GROUP
/// BEGIN_GROUP: AERO_COEFF_SURF, DESCRIPTION: Aerodynamic coefficients and forces per surface.
vector<string> Marker_Monitoring;
for (unsigned short iMarker_Monitoring = 0; iMarker_Monitoring < config->GetnMarker_Monitoring(); iMarker_Monitoring++){
Marker_Monitoring.push_back(config->GetMarker_Monitoring_TagBound(iMarker_Monitoring));
}
/// DESCRIPTION: Drag coefficient
AddHistoryOutputPerSurface("DRAG_ON_SURFACE", "CD", ScreenOutputFormat::FIXED, "AERO_COEFF_SURF", Marker_Monitoring, HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Lift coefficient
AddHistoryOutputPerSurface("LIFT_ON_SURFACE", "CL", ScreenOutputFormat::FIXED, "AERO_COEFF_SURF", Marker_Monitoring, HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Sideforce coefficient
AddHistoryOutputPerSurface("SIDEFORCE_ON_SURFACE", "CSF", ScreenOutputFormat::FIXED, "AERO_COEFF_SURF", Marker_Monitoring, HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Moment around the x-axis
AddHistoryOutputPerSurface("MOMENT-X_ON_SURFACE", "CMx", ScreenOutputFormat::FIXED, "AERO_COEFF_SURF", Marker_Monitoring, HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Moment around the y-axis
AddHistoryOutputPerSurface("MOMENT-Y_ON_SURFACE", "CMy", ScreenOutputFormat::FIXED, "AERO_COEFF_SURF", Marker_Monitoring, HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Moment around the z-axis
AddHistoryOutputPerSurface("MOMENT-Z_ON_SURFACE", "CMz", ScreenOutputFormat::FIXED, "AERO_COEFF_SURF", Marker_Monitoring, HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Force in x direction
AddHistoryOutputPerSurface("FORCE-X_ON_SURFACE", "CFx", ScreenOutputFormat::FIXED, "AERO_COEFF_SURF", Marker_Monitoring, HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Force in y direction
AddHistoryOutputPerSurface("FORCE-Y_ON_SURFACE", "CFy", ScreenOutputFormat::FIXED, "AERO_COEFF_SURF", Marker_Monitoring, HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Force in z direction
AddHistoryOutputPerSurface("FORCE-Z_ON_SURFACE", "CFz", ScreenOutputFormat::FIXED, "AERO_COEFF_SURF", Marker_Monitoring, HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Lift-to-drag ratio
AddHistoryOutputPerSurface("EFFICIENCY_ON_SURFACE", "CEff", ScreenOutputFormat::FIXED, "AERO_COEFF_SURF", Marker_Monitoring, HistoryFieldType::COEFFICIENT);
/// END_GROUP
/// DESCRIPTION: Angle of attack
AddHistoryOutput("AOA", "AoA", ScreenOutputFormat::FIXED, "AOA", "Angle of attack");
}
void CFlowOutput::SetAerodynamicCoefficients(CConfig *config, CSolver *flow_solver){
SetHistoryOutputValue("DRAG", flow_solver->GetTotal_CD());
SetHistoryOutputValue("LIFT", flow_solver->GetTotal_CL());
if (nDim == 3)
SetHistoryOutputValue("SIDEFORCE", flow_solver->GetTotal_CSF());
if (nDim == 3){
SetHistoryOutputValue("MOMENT_X", flow_solver->GetTotal_CMx());
SetHistoryOutputValue("MOMENT_Y", flow_solver->GetTotal_CMy());
}
SetHistoryOutputValue("MOMENT_Z", flow_solver->GetTotal_CMz());
SetHistoryOutputValue("FORCE_X", flow_solver->GetTotal_CFx());
SetHistoryOutputValue("FORCE_Y", flow_solver->GetTotal_CFy());
if (nDim == 3)
SetHistoryOutputValue("FORCE_Z", flow_solver->GetTotal_CFz());
SetHistoryOutputValue("EFFICIENCY", flow_solver->GetTotal_CEff());
for (unsigned short iMarker_Monitoring = 0; iMarker_Monitoring < config->GetnMarker_Monitoring(); iMarker_Monitoring++) {
SetHistoryOutputPerSurfaceValue("DRAG_ON_SURFACE", flow_solver->GetSurface_CD(iMarker_Monitoring), iMarker_Monitoring);
SetHistoryOutputPerSurfaceValue("LIFT_ON_SURFACE", flow_solver->GetSurface_CL(iMarker_Monitoring), iMarker_Monitoring);
if (nDim == 3)
SetHistoryOutputPerSurfaceValue("SIDEFORCE_ON_SURFACE", flow_solver->GetSurface_CSF(iMarker_Monitoring), iMarker_Monitoring);
if (nDim == 3){
SetHistoryOutputPerSurfaceValue("MOMENT-X_ON_SURFACE", flow_solver->GetSurface_CMx(iMarker_Monitoring), iMarker_Monitoring);
SetHistoryOutputPerSurfaceValue("MOMENT-Y_ON_SURFACE", flow_solver->GetSurface_CMy(iMarker_Monitoring), iMarker_Monitoring);
}
SetHistoryOutputPerSurfaceValue("MOMENT-Z_ON_SURFACE", flow_solver->GetSurface_CMz(iMarker_Monitoring), iMarker_Monitoring);
SetHistoryOutputPerSurfaceValue("FORCE-X_ON_SURFACE", flow_solver->GetSurface_CFx(iMarker_Monitoring), iMarker_Monitoring);
SetHistoryOutputPerSurfaceValue("FORCE-Y_ON_SURFACE", flow_solver->GetSurface_CFy(iMarker_Monitoring), iMarker_Monitoring);
if (nDim == 3)
SetHistoryOutputPerSurfaceValue("FORCE-Z_ON_SURFACE", flow_solver->GetSurface_CFz(iMarker_Monitoring), iMarker_Monitoring);
SetHistoryOutputPerSurfaceValue("EFFICIENCY_ON_SURFACE", flow_solver->GetSurface_CEff(iMarker_Monitoring), iMarker_Monitoring);
if (config->GetAeroelastic_Simulation()){
SetHistoryOutputPerSurfaceValue("PITCH", config->GetAeroelastic_pitch(iMarker_Monitoring), iMarker_Monitoring);
SetHistoryOutputPerSurfaceValue("PLUNGE", config->GetAeroelastic_plunge(iMarker_Monitoring), iMarker_Monitoring);
}
}
SetHistoryOutputValue("AOA", config->GetAoA());
}
void CFlowOutput::SetRotatingFrameCoefficients(CConfig *config, CSolver *flow_solver) {
SetHistoryOutputValue("CT", flow_solver->GetTotal_CT());
SetHistoryOutputValue("CQ", flow_solver->GetTotal_CQ());
SetHistoryOutputValue("MERIT", flow_solver->GetTotal_CMerit());
}
void CFlowOutput::Add_CpInverseDesignOutput(CConfig *config){
AddHistoryOutput("CP_DIFF", "Cp_Diff", ScreenOutputFormat::FIXED, "CP_DIFF", "Cp difference for inverse design");
}
void CFlowOutput::Set_CpInverseDesign(CSolver *solver, CGeometry *geometry, CConfig *config){
unsigned short iMarker, icommas, Boundary, iDim;
unsigned long iVertex, iPoint, (*Point2Vertex)[2], nPointLocal = 0, nPointGlobal = 0;
su2double XCoord, YCoord, ZCoord, Pressure, PressureCoeff = 0, Cp, CpTarget, *Normal = nullptr, Area, PressDiff = 0.0;
bool *PointInDomain;
string text_line, surfCp_filename;
ifstream Surface_file;
char cstr[200];
/*--- Prepare to read the surface pressure files (CSV) ---*/
surfCp_filename = "TargetCp";
surfCp_filename = config->GetUnsteady_FileName(surfCp_filename, (int)curTimeIter, ".dat");
strcpy (cstr, surfCp_filename.c_str());
/*--- Read the surface pressure file ---*/
string::size_type position;
Surface_file.open(cstr, ios::in);
if (!(Surface_file.fail())) {
nPointLocal = geometry->GetnPoint();
#ifdef HAVE_MPI
SU2_MPI::Allreduce(&nPointLocal, &nPointGlobal, 1, MPI_UNSIGNED_LONG, MPI_SUM, MPI_COMM_WORLD);
#else
nPointGlobal = nPointLocal;
#endif
Point2Vertex = new unsigned long[nPointGlobal][2];
PointInDomain = new bool[nPointGlobal];
for (iPoint = 0; iPoint < nPointGlobal; iPoint ++)
PointInDomain[iPoint] = false;
for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) {
Boundary = config->GetMarker_All_KindBC(iMarker);
if ((Boundary == EULER_WALL ) ||
(Boundary == HEAT_FLUX ) ||
(Boundary == ISOTHERMAL ) ||
(Boundary == NEARFIELD_BOUNDARY)) {
for (iVertex = 0; iVertex < geometry->GetnVertex(iMarker); iVertex++) {
/*--- The Pressure file uses the global numbering ---*/
iPoint = geometry->nodes->GetGlobalIndex(geometry->vertex[iMarker][iVertex]->GetNode());
if (geometry->vertex[iMarker][iVertex]->GetNode() < geometry->GetnPointDomain()) {
Point2Vertex[iPoint][0] = iMarker;
Point2Vertex[iPoint][1] = iVertex;
PointInDomain[iPoint] = true;
solver->SetCPressureTarget(iMarker, iVertex, 0.0);
}
}
}
}
getline(Surface_file, text_line);
while (getline(Surface_file, text_line)) {
for (icommas = 0; icommas < 50; icommas++) {
position = text_line.find( ",", 0 );
if (position!=string::npos) text_line.erase (position,1);
}
stringstream point_line(text_line);
if (geometry->GetnDim() == 2) point_line >> iPoint >> XCoord >> YCoord >> Pressure >> PressureCoeff;
if (geometry->GetnDim() == 3) point_line >> iPoint >> XCoord >> YCoord >> ZCoord >> Pressure >> PressureCoeff;
if (PointInDomain[iPoint]) {
/*--- Find the vertex for the Point and Marker ---*/
iMarker = Point2Vertex[iPoint][0];
iVertex = Point2Vertex[iPoint][1];
solver->SetCPressureTarget(iMarker, iVertex, PressureCoeff);
}
}
Surface_file.close();
delete [] Point2Vertex;
delete [] PointInDomain;
/*--- Compute the pressure difference ---*/
PressDiff = 0.0;
for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) {
Boundary = config->GetMarker_All_KindBC(iMarker);
if ((Boundary == EULER_WALL ) ||
(Boundary == HEAT_FLUX ) ||
(Boundary == ISOTHERMAL ) ||
(Boundary == NEARFIELD_BOUNDARY)) {
for (iVertex = 0; iVertex < geometry->GetnVertex(iMarker); iVertex++) {
Normal = geometry->vertex[iMarker][iVertex]->GetNormal();
Cp = solver->GetCPressure(iMarker, iVertex);
CpTarget = solver->GetCPressureTarget(iMarker, iVertex);
Area = 0.0;
for (iDim = 0; iDim < geometry->GetnDim(); iDim++)
Area += Normal[iDim]*Normal[iDim];
Area = sqrt(Area);
PressDiff += Area * (CpTarget - Cp) * (CpTarget - Cp);
}
}
}
#ifdef HAVE_MPI
su2double MyPressDiff = PressDiff;
SU2_MPI::Allreduce(&MyPressDiff, &PressDiff, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#endif
}
/*--- Update the total Cp difference coeffient ---*/
solver->SetTotal_CpDiff(PressDiff);
SetHistoryOutputValue("CP_DIFF", PressDiff);
}
su2double CFlowOutput::GetQ_Criterion(su2double** VelocityGradient) const {
/*--- Make a 3D copy of the gradient so we do not have worry about nDim ---*/
su2double Grad_Vel[3][3] = {{0.0, 0.0, 0.0},{0.0, 0.0, 0.0},{0.0, 0.0, 0.0}};
for (unsigned short iDim = 0; iDim < nDim; iDim++)
for (unsigned short jDim = 0 ; jDim < nDim; jDim++)
Grad_Vel[iDim][jDim] = VelocityGradient[iDim][jDim];
/*--- Q Criterion Eq 1.2 of HALLER, G. (2005). An objective definition of a vortex.
Journal of Fluid Mechanics, 525, 1-26. doi:10.1017/S0022112004002526 ---*/
/*--- Components of the strain rate tensor (symmetric) ---*/
su2double s11 = Grad_Vel[0][0];
su2double s12 = 0.5 * (Grad_Vel[0][1] + Grad_Vel[1][0]);
su2double s13 = 0.5 * (Grad_Vel[0][2] + Grad_Vel[2][0]);
su2double s22 = Grad_Vel[1][1];
su2double s23 = 0.5 * (Grad_Vel[1][2] + Grad_Vel[2][1]);
su2double s33 = Grad_Vel[2][2];
/*--- Components of the spin tensor (skew-symmetric) ---*/
su2double omega12 = 0.5 * (Grad_Vel[0][1] - Grad_Vel[1][0]);
su2double omega13 = 0.5 * (Grad_Vel[0][2] - Grad_Vel[2][0]);
su2double omega23 = 0.5 * (Grad_Vel[1][2] - Grad_Vel[2][1]);
/*--- Q = ||Omega|| - ||Strain|| ---*/
su2double Q = 2*(pow(omega12,2) + pow(omega13,2) + pow(omega23,2)) -
(pow(s11,2) + pow(s22,2) + pow(s33,2) + 2*(pow(s12,2) + pow(s13,2) + pow(s23,2)));
return Q;
}
void CFlowOutput::WriteAdditionalFiles(CConfig *config, CGeometry *geometry, CSolver **solver_container){
if (config->GetFixed_CL_Mode() || config->GetFixed_CM_Mode()){
WriteMetaData(config);
}
if (config->GetWrt_ForcesBreakdown()){
WriteForcesBreakdown(config, geometry, solver_container);
}
}
void CFlowOutput::WriteMetaData(CConfig *config){
ofstream meta_file;
string filename = "flow";
filename = config->GetFilename(filename, ".meta", curTimeIter);
/*--- All processors open the file. ---*/
if (rank == MASTER_NODE) {
meta_file.open(filename.c_str(), ios::out);
meta_file.precision(15);
if (config->GetTime_Marching() == DT_STEPPING_1ST || config->GetTime_Marching() == DT_STEPPING_2ND)
meta_file <<"ITER= " << curTimeIter + 1 << endl;
else
meta_file <<"ITER= " << curInnerIter + config->GetExtIter_OffSet() + 1 << endl;
if (config->GetFixed_CL_Mode()){
meta_file <<"AOA= " << config->GetAoA() - config->GetAoA_Offset() << endl;
meta_file <<"SIDESLIP_ANGLE= " << config->GetAoS() - config->GetAoS_Offset() << endl;
meta_file <<"DCD_DCL_VALUE= " << config->GetdCD_dCL() << endl;
if (nDim==3){
meta_file <<"DCMX_DCL_VALUE= " << config->GetdCMx_dCL() << endl;
meta_file <<"DCMY_DCL_VALUE= " << config->GetdCMy_dCL() << endl;
}
meta_file <<"DCMZ_DCL_VALUE= " << config->GetdCMz_dCL() << endl;
}
meta_file <<"INITIAL_BCTHRUST= " << config->GetInitial_BCThrust() << endl;
if (( config->GetKind_Solver() == DISC_ADJ_EULER ||
config->GetKind_Solver() == DISC_ADJ_NAVIER_STOKES ||
config->GetKind_Solver() == DISC_ADJ_RANS )) {
meta_file << "SENS_AOA=" << GetHistoryFieldValue("SENS_AOA") * PI_NUMBER / 180.0 << endl;
}
}
meta_file.close();
}
void CFlowOutput::WriteForcesBreakdown(CConfig *config, CGeometry *geometry, CSolver **solver_container){
char cstr[200];
unsigned short iDim, iMarker_Monitoring;
ofstream Breakdown_file;
bool compressible = (config->GetKind_Regime() == COMPRESSIBLE);
bool incompressible = (config->GetKind_Regime() == INCOMPRESSIBLE);
bool unsteady = (config->GetTime_Marching() != NO);
bool viscous = config->GetViscous();
bool dynamic_grid = config->GetDynamic_Grid();
bool gravity = config->GetGravityForce();
bool turbulent = config->GetKind_Solver() == RANS;
bool fixed_cl = config->GetFixed_CL_Mode();
unsigned short Kind_Solver = config->GetKind_Solver();
unsigned short Kind_Turb_Model = config->GetKind_Turb_Model();
unsigned short Ref_NonDim = config->GetRef_NonDim();
unsigned short nDim = geometry->GetnDim();
/*--- Output the mean flow solution using only the master node ---*/
if ( rank == MASTER_NODE) {
cout << endl << "Writing the forces breakdown file ("<< config->GetBreakdown_FileName() << ")." << endl;
/*--- Initialize variables to store information from all domains (direct solution) ---*/
su2double Total_CL = 0.0, Total_CD = 0.0, Total_CSF = 0.0,
Total_CMx = 0.0, Total_CMy = 0.0, Total_CMz = 0.0, Total_CEff = 0.0,
Total_CoPx = 0.0, Total_CoPy = 0.0, Total_CoPz = 0.0,
Total_CFx = 0.0, Total_CFy = 0.0, Total_CFz = 0.0, Inv_CL = 0.0,
Inv_CD = 0.0, Inv_CSF = 0.0, Inv_CMx = 0.0, Inv_CMy = 0.0,
Inv_CMz = 0.0, Inv_CEff = 0.0, Inv_CFx = 0.0, Inv_CFy = 0.0, Inv_CFz =
0.0, Mnt_CL = 0.0,
Mnt_CD = 0.0, Mnt_CSF = 0.0, Mnt_CMx = 0.0, Mnt_CMy = 0.0,
Mnt_CMz = 0.0, Mnt_CEff = 0.0, Mnt_CFx = 0.0, Mnt_CFy = 0.0, Mnt_CFz =
0.0, Visc_CL = 0.0,
Visc_CD = 0.0, Visc_CSF = 0.0, Visc_CMx = 0.0, Visc_CMy = 0.0,
Visc_CMz = 0.0, Visc_CEff = 0.0, Visc_CFx = 0.0, Visc_CFy = 0.0, Visc_CFz =
0.0, *Surface_CL = nullptr, *Surface_CD = nullptr,
*Surface_CSF = nullptr, *Surface_CEff = nullptr, *Surface_CFx = nullptr,
*Surface_CFy = nullptr, *Surface_CFz = nullptr,
*Surface_CMx = nullptr, *Surface_CMy = nullptr, *Surface_CMz = nullptr,
*Surface_CL_Inv = nullptr,
*Surface_CD_Inv = nullptr, *Surface_CSF_Inv = nullptr,
*Surface_CEff_Inv = nullptr, *Surface_CFx_Inv = nullptr, *Surface_CFy_Inv =
nullptr, *Surface_CFz_Inv = nullptr, *Surface_CMx_Inv = nullptr,
*Surface_CMy_Inv = nullptr, *Surface_CMz_Inv = nullptr,
*Surface_CL_Visc = nullptr,
*Surface_CD_Visc = nullptr, *Surface_CSF_Visc = nullptr,
*Surface_CEff_Visc = nullptr, *Surface_CFx_Visc = nullptr, *Surface_CFy_Visc =
nullptr, *Surface_CFz_Visc = nullptr, *Surface_CMx_Visc = nullptr,
*Surface_CMy_Visc = nullptr, *Surface_CMz_Visc = nullptr,
*Surface_CL_Mnt = nullptr,
*Surface_CD_Mnt = nullptr, *Surface_CSF_Mnt = nullptr,
*Surface_CEff_Mnt = nullptr, *Surface_CFx_Mnt = nullptr, *Surface_CFy_Mnt =
nullptr, *Surface_CFz_Mnt = nullptr, *Surface_CMx_Mnt = nullptr,
*Surface_CMy_Mnt = nullptr, *Surface_CMz_Mnt = nullptr;
/*--- WARNING: when compiling on Windows, ctime() is not available. Comment out
the two lines below that use the dt variable. ---*/
//time_t now = time(0);
//string dt = ctime(&now); dt[24] = '.';
/*--- Allocate memory for the coefficients being monitored ---*/
Surface_CL = new su2double[config->GetnMarker_Monitoring()];
Surface_CD = new su2double[config->GetnMarker_Monitoring()];
Surface_CSF = new su2double[config->GetnMarker_Monitoring()];
Surface_CEff = new su2double[config->GetnMarker_Monitoring()];
Surface_CFx = new su2double[config->GetnMarker_Monitoring()];
Surface_CFy = new su2double[config->GetnMarker_Monitoring()];
Surface_CFz = new su2double[config->GetnMarker_Monitoring()];
Surface_CMx = new su2double[config->GetnMarker_Monitoring()];
Surface_CMy = new su2double[config->GetnMarker_Monitoring()];
Surface_CMz = new su2double[config->GetnMarker_Monitoring()];
Surface_CL_Inv = new su2double[config->GetnMarker_Monitoring()];
Surface_CD_Inv = new su2double[config->GetnMarker_Monitoring()];
Surface_CSF_Inv = new su2double[config->GetnMarker_Monitoring()];
Surface_CEff_Inv = new su2double[config->GetnMarker_Monitoring()];
Surface_CFx_Inv = new su2double[config->GetnMarker_Monitoring()];
Surface_CFy_Inv = new su2double[config->GetnMarker_Monitoring()];
Surface_CFz_Inv = new su2double[config->GetnMarker_Monitoring()];
Surface_CMx_Inv = new su2double[config->GetnMarker_Monitoring()];
Surface_CMy_Inv = new su2double[config->GetnMarker_Monitoring()];
Surface_CMz_Inv = new su2double[config->GetnMarker_Monitoring()];
Surface_CL_Visc = new su2double[config->GetnMarker_Monitoring()];
Surface_CD_Visc = new su2double[config->GetnMarker_Monitoring()];
Surface_CSF_Visc =
new su2double[config->GetnMarker_Monitoring()];
Surface_CEff_Visc = new su2double[config->GetnMarker_Monitoring()];
Surface_CFx_Visc = new su2double[config->GetnMarker_Monitoring()];
Surface_CFy_Visc = new su2double[config->GetnMarker_Monitoring()];
Surface_CFz_Visc = new su2double[config->GetnMarker_Monitoring()];
Surface_CMx_Visc = new su2double[config->GetnMarker_Monitoring()];
Surface_CMy_Visc = new su2double[config->GetnMarker_Monitoring()];
Surface_CMz_Visc = new su2double[config->GetnMarker_Monitoring()];
Surface_CL_Mnt = new su2double[config->GetnMarker_Monitoring()];
Surface_CD_Mnt = new su2double[config->GetnMarker_Monitoring()];
Surface_CSF_Mnt =
new su2double[config->GetnMarker_Monitoring()];
Surface_CEff_Mnt = new su2double[config->GetnMarker_Monitoring()];
Surface_CFx_Mnt = new su2double[config->GetnMarker_Monitoring()];
Surface_CFy_Mnt = new su2double[config->GetnMarker_Monitoring()];
Surface_CFz_Mnt = new su2double[config->GetnMarker_Monitoring()];
Surface_CMx_Mnt = new su2double[config->GetnMarker_Monitoring()];
Surface_CMy_Mnt = new su2double[config->GetnMarker_Monitoring()];
Surface_CMz_Mnt = new su2double[config->GetnMarker_Monitoring()];
/*--- Flow solution coefficients ---*/
Total_CL = solver_container[FLOW_SOL]->GetTotal_CL();
Total_CD = solver_container[FLOW_SOL]->GetTotal_CD();
Total_CSF = solver_container[FLOW_SOL]->GetTotal_CSF();
Total_CEff = solver_container[FLOW_SOL]->GetTotal_CEff();
Total_CMx = solver_container[FLOW_SOL]->GetTotal_CMx();
Total_CMy = solver_container[FLOW_SOL]->GetTotal_CMy();
Total_CMz = solver_container[FLOW_SOL]->GetTotal_CMz();
Total_CFx = solver_container[FLOW_SOL]->GetTotal_CFx();
Total_CFy = solver_container[FLOW_SOL]->GetTotal_CFy();
Total_CFz = solver_container[FLOW_SOL]->GetTotal_CFz();
if (nDim == 2) {
Total_CoPx = solver_container[FLOW_SOL]->GetTotal_CoPx() / solver_container[FLOW_SOL]->GetTotal_CFy();
Total_CoPy = solver_container[FLOW_SOL]->GetTotal_CoPy() / solver_container[FLOW_SOL]->GetTotal_CFx();
Total_CoPz = 0.0;
}
if (nDim == 3) {
Total_CoPx = solver_container[FLOW_SOL]->GetTotal_CoPx() / solver_container[FLOW_SOL]->GetTotal_CFz();
Total_CoPy = 0.0;
Total_CoPz = solver_container[FLOW_SOL]->GetTotal_CoPz() / solver_container[FLOW_SOL]->GetTotal_CFx();
}
if (config->GetSystemMeasurements() == US) { Total_CoPx *= 12.0; Total_CoPy *= 12.0; Total_CoPz *= 12.0; }
/*--- Flow inviscid solution coefficients ---*/
Inv_CL =
solver_container[FLOW_SOL]->GetAllBound_CL_Inv();
Inv_CD =
solver_container[FLOW_SOL]->GetAllBound_CD_Inv();
Inv_CSF =
solver_container[FLOW_SOL]->GetAllBound_CSF_Inv();
Inv_CEff =
solver_container[FLOW_SOL]->GetAllBound_CEff_Inv();
Inv_CMx =
solver_container[FLOW_SOL]->GetAllBound_CMx_Inv();
Inv_CMy =
solver_container[FLOW_SOL]->GetAllBound_CMy_Inv();
Inv_CMz =
solver_container[FLOW_SOL]->GetAllBound_CMz_Inv();
Inv_CFx =
solver_container[FLOW_SOL]->GetAllBound_CFx_Inv();
Inv_CFy =
solver_container[FLOW_SOL]->GetAllBound_CFy_Inv();
Inv_CFz =
solver_container[FLOW_SOL]->GetAllBound_CFz_Inv();
/*--- Flow viscous solution coefficients ---*/
Visc_CL =
solver_container[FLOW_SOL]->GetAllBound_CL_Visc();
Visc_CD =
solver_container[FLOW_SOL]->GetAllBound_CD_Visc();
Visc_CSF =
solver_container[FLOW_SOL]->GetAllBound_CSF_Visc();
Visc_CEff =
solver_container[FLOW_SOL]->GetAllBound_CEff_Visc();
Visc_CMx =
solver_container[FLOW_SOL]->GetAllBound_CMx_Visc();
Visc_CMy =
solver_container[FLOW_SOL]->GetAllBound_CMy_Visc();
Visc_CMz =
solver_container[FLOW_SOL]->GetAllBound_CMz_Visc();
Visc_CFx =
solver_container[FLOW_SOL]->GetAllBound_CFx_Visc();
Visc_CFy =
solver_container[FLOW_SOL]->GetAllBound_CFy_Visc();
Visc_CFz =
solver_container[FLOW_SOL]->GetAllBound_CFz_Visc();
/*--- Flow momentum solution coefficients ---*/
Mnt_CL =
solver_container[FLOW_SOL]->GetAllBound_CL_Mnt();
Mnt_CD =
solver_container[FLOW_SOL]->GetAllBound_CD_Mnt();
Mnt_CSF =
solver_container[FLOW_SOL]->GetAllBound_CSF_Mnt();
Mnt_CEff =
solver_container[FLOW_SOL]->GetAllBound_CEff_Mnt();
Mnt_CMx =
solver_container[FLOW_SOL]->GetAllBound_CMx_Mnt();
Mnt_CMy =
solver_container[FLOW_SOL]->GetAllBound_CMy_Mnt();
Mnt_CMz =
solver_container[FLOW_SOL]->GetAllBound_CMz_Mnt();
Mnt_CFx =
solver_container[FLOW_SOL]->GetAllBound_CFx_Mnt();
Mnt_CFy =
solver_container[FLOW_SOL]->GetAllBound_CFy_Mnt();
Mnt_CFz =
solver_container[FLOW_SOL]->GetAllBound_CFz_Mnt();
/*--- Look over the markers being monitored and get the desired values ---*/
for (iMarker_Monitoring = 0;
iMarker_Monitoring < config->GetnMarker_Monitoring();
iMarker_Monitoring++) {
Surface_CL[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CL(
iMarker_Monitoring);
Surface_CD[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CD(
iMarker_Monitoring);
Surface_CSF[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CSF(
iMarker_Monitoring);
Surface_CEff[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CEff(
iMarker_Monitoring);
Surface_CMx[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CMx(
iMarker_Monitoring);
Surface_CMy[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CMy(
iMarker_Monitoring);
Surface_CMz[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CMz(
iMarker_Monitoring);
Surface_CFx[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CFx(
iMarker_Monitoring);
Surface_CFy[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CFy(
iMarker_Monitoring);
Surface_CFz[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CFz(
iMarker_Monitoring);
Surface_CL_Inv[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CL_Inv(
iMarker_Monitoring);
Surface_CD_Inv[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CD_Inv(
iMarker_Monitoring);
Surface_CSF_Inv[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CSF_Inv(
iMarker_Monitoring);
Surface_CEff_Inv[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CEff_Inv(
iMarker_Monitoring);
Surface_CMx_Inv[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CMx_Inv(
iMarker_Monitoring);
Surface_CMy_Inv[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CMy_Inv(
iMarker_Monitoring);
Surface_CMz_Inv[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CMz_Inv(
iMarker_Monitoring);
Surface_CFx_Inv[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CFx_Inv(
iMarker_Monitoring);
Surface_CFy_Inv[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CFy_Inv(
iMarker_Monitoring);
Surface_CFz_Inv[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CFz_Inv(
iMarker_Monitoring);
Surface_CL_Visc[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CL_Visc(
iMarker_Monitoring);
Surface_CD_Visc[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CD_Visc(
iMarker_Monitoring);
Surface_CSF_Visc[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CSF_Visc(
iMarker_Monitoring);
Surface_CEff_Visc[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CEff_Visc(
iMarker_Monitoring);
Surface_CMx_Visc[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CMx_Visc(
iMarker_Monitoring);
Surface_CMy_Visc[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CMy_Visc(
iMarker_Monitoring);
Surface_CMz_Visc[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CMz_Visc(
iMarker_Monitoring);
Surface_CFx_Visc[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CFx_Visc(
iMarker_Monitoring);
Surface_CFy_Visc[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CFy_Visc(
iMarker_Monitoring);
Surface_CFz_Visc[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CFz_Visc(
iMarker_Monitoring);
Surface_CL_Mnt[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CL_Mnt(
iMarker_Monitoring);
Surface_CD_Mnt[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CD_Mnt(
iMarker_Monitoring);
Surface_CSF_Mnt[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CSF_Mnt(
iMarker_Monitoring);
Surface_CEff_Mnt[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CEff_Mnt(
iMarker_Monitoring);
Surface_CMx_Mnt[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CMx_Mnt(
iMarker_Monitoring);
Surface_CMy_Mnt[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CMy_Mnt(
iMarker_Monitoring);
Surface_CMz_Mnt[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CMz_Mnt(
iMarker_Monitoring);
Surface_CFx_Mnt[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CFx_Mnt(
iMarker_Monitoring);
Surface_CFy_Mnt[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CFy_Mnt(
iMarker_Monitoring);
Surface_CFz_Mnt[iMarker_Monitoring] =
solver_container[FLOW_SOL]->GetSurface_CFz_Mnt(
iMarker_Monitoring);
}
/*--- Write file name with extension ---*/
string filename = config->GetBreakdown_FileName();
strcpy (cstr, filename.data());
Breakdown_file.open(cstr, ios::out);
Breakdown_file << "\n" <<"-------------------------------------------------------------------------" << "\n";
Breakdown_file << "| ___ _ _ ___ |" << "\n";
Breakdown_file << "| / __| | | |_ ) Release 7.0.6 \"Blackbird\" |" << "\n";
Breakdown_file << "| \\__ \\ |_| |/ / |" << "\n";
Breakdown_file << "| |___/\\___//___| Suite (Computational Fluid Dynamics Code) |" << "\n";
Breakdown_file << "| |" << "\n";
//Breakdown_file << "| Local date and time: " << dt << " |" << "\n";
Breakdown_file << "-------------------------------------------------------------------------" << "\n";
Breakdown_file << "| SU2 Project Website: https://su2code.github.io |" << "\n";
Breakdown_file << "| |" << "\n";
Breakdown_file << "| The SU2 Project is maintained by the SU2 Foundation |" << "\n";
Breakdown_file << "| (http://su2foundation.org) |" << "\n";
Breakdown_file << "-------------------------------------------------------------------------" << "\n";
Breakdown_file << "| Copyright 2012-2020, SU2 Contributors |" << "\n";
Breakdown_file << "| |" << "\n";
Breakdown_file << "| SU2 is free software; you can redistribute it and/or |" << "\n";
Breakdown_file << "| modify it under the terms of the GNU Lesser General Public |" << "\n";
Breakdown_file << "| License as published by the Free Software Foundation; either |" << "\n";
Breakdown_file << "| version 2.1 of the License, or (at your option) any later version. |" << "\n";
Breakdown_file << "| |" << "\n";
Breakdown_file << "| SU2 is distributed in the hope that it will be useful, |" << "\n";
Breakdown_file << "| but WITHOUT ANY WARRANTY; without even the implied warranty of |" << "\n";
Breakdown_file << "| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |" << "\n";
Breakdown_file << "| Lesser General Public License for more details. |" << "\n";
Breakdown_file << "| |" << "\n";
Breakdown_file << "| You should have received a copy of the GNU Lesser General Public |" << "\n";
Breakdown_file << "| License along with SU2. If not, see <http://www.gnu.org/licenses/>. |" << "\n";
Breakdown_file << "-------------------------------------------------------------------------" << "\n";
Breakdown_file.precision(6);
Breakdown_file << "\n" << "\n" << "Problem definition:" << "\n" << "\n";
switch (Kind_Solver) {
case EULER: case INC_EULER:
if (compressible) Breakdown_file << "Compressible Euler equations." << "\n";
if (incompressible) Breakdown_file << "Incompressible Euler equations." << "\n";
break;
case NAVIER_STOKES: case INC_NAVIER_STOKES:
if (compressible) Breakdown_file << "Compressible Laminar Navier-Stokes' equations." << "\n";
if (incompressible) Breakdown_file << "Incompressible Laminar Navier-Stokes' equations." << "\n";
break;
case RANS: case INC_RANS:
if (compressible) Breakdown_file << "Compressible RANS equations." << "\n";
if (incompressible) Breakdown_file << "Incompressible RANS equations." << "\n";
Breakdown_file << "Turbulence model: ";
switch (Kind_Turb_Model) {
case SA: Breakdown_file << "Spalart Allmaras" << "\n"; break;
case SA_NEG: Breakdown_file << "Negative Spalart Allmaras" << "\n"; break;
case SA_E: Breakdown_file << "Edwards Spalart Allmaras" << "\n"; break;
case SA_COMP: Breakdown_file << "Compressibility Correction Spalart Allmaras" << "\n"; break;
case SA_E_COMP: Breakdown_file << "Compressibility Correction Edwards Spalart Allmaras" << "\n"; break;
case SST: Breakdown_file << "Menter's SST" << "\n"; break;
case SST_SUST: Breakdown_file << "Menter's SST with sustaining terms" << "\n"; break;
}
break;
}
/*--- Compressible version of console output ---*/
if (compressible) {
if (compressible) {
Breakdown_file << "Mach number: " << config->GetMach() <<"."<< "\n";
Breakdown_file << "Angle of attack (AoA): " << config->GetAoA() <<" deg, and angle of sideslip (AoS): " << config->GetAoS() <<" deg."<< "\n";
if ((Kind_Solver == NAVIER_STOKES) || (Kind_Solver == INC_NAVIER_STOKES) ||
(Kind_Solver == RANS) || (Kind_Solver == INC_RANS))
Breakdown_file << "Reynolds number: " << config->GetReynolds() <<"."<< "\n";
}
if (fixed_cl) {
Breakdown_file << "Simulation at a cte. CL: " << config->GetTarget_CL() << ".\n";
Breakdown_file << "Approx. Delta CL / Delta AoA: " << config->GetdCL_dAlpha() << " (1/deg).\n";
Breakdown_file << "Approx. Delta CD / Delta CL: " << config->GetdCD_dCL() << ".\n";
if (nDim == 3 ) {
Breakdown_file << "Approx. Delta CMx / Delta CL: " << config->GetdCMx_dCL() << ".\n";
Breakdown_file << "Approx. Delta CMy / Delta CL: " << config->GetdCMy_dCL() << ".\n";
}
Breakdown_file << "Approx. Delta CMz / Delta CL: " << config->GetdCMz_dCL() << ".\n";
}
if (Ref_NonDim == DIMENSIONAL) { Breakdown_file << "Dimensional simulation." << "\n"; }
else if (Ref_NonDim == FREESTREAM_PRESS_EQ_ONE) { Breakdown_file << "Non-Dimensional simulation (P=1.0, Rho=1.0, T=1.0 at the farfield)." << "\n"; }
else if (Ref_NonDim == FREESTREAM_VEL_EQ_MACH) { Breakdown_file << "Non-Dimensional simulation (V=Mach, Rho=1.0, T=1.0 at the farfield)." << "\n"; }
else if (Ref_NonDim == FREESTREAM_VEL_EQ_ONE) { Breakdown_file << "Non-Dimensional simulation (V=1.0, Rho=1.0, T=1.0 at the farfield)." << "\n"; }
if (config->GetSystemMeasurements() == SI) {
Breakdown_file << "The reference area is " << config->GetRefArea() << " m^2." << "\n";
Breakdown_file << "The reference length is " << config->GetRefLength() << " m." << "\n";
}
if (config->GetSystemMeasurements() == US) {
Breakdown_file << "The reference area is " << config->GetRefArea()*12.0*12.0 << " in^2." << "\n";
Breakdown_file << "The reference length is " << config->GetRefLength()*12.0 << " in." << "\n";
}
Breakdown_file << "\n" << "\n" <<"Problem definition:" << "\n" << "\n";
if (compressible) {
if (viscous) {
Breakdown_file << "Viscous flow: Computing pressure using the ideal gas law" << "\n";
Breakdown_file << "based on the free-stream temperature and a density computed" << "\n";
Breakdown_file << "from the Reynolds number." << "\n";
} else {
Breakdown_file << "Inviscid flow: Computing density based on free-stream" << "\n";
Breakdown_file << "temperature and pressure using the ideal gas law." << "\n";
}
}
if (dynamic_grid) Breakdown_file << "Force coefficients computed using MACH_MOTION." << "\n";
else Breakdown_file << "Force coefficients computed using free-stream values." << "\n";
if (incompressible) {
Breakdown_file << "Viscous and Inviscid flow: rho_ref, and vel_ref" << "\n";
Breakdown_file << "are based on the free-stream values, p_ref = rho_ref*vel_ref^2." << "\n";
Breakdown_file << "The free-stream value of the pressure is 0." << "\n";
Breakdown_file << "Mach number: "<< config->GetMach() << ", computed using the Bulk modulus." << "\n";
Breakdown_file << "Angle of attack (deg): "<< config->GetAoA() << ", computed using the the free-stream velocity." << "\n";
Breakdown_file << "Side slip angle (deg): "<< config->GetAoS() << ", computed using the the free-stream velocity." << "\n";
if (viscous) Breakdown_file << "Reynolds number: " << config->GetReynolds() << ", computed using free-stream values."<< "\n";
Breakdown_file << "Only dimensional computation, the grid should be dimensional." << "\n";
}
Breakdown_file <<"-- Input conditions:"<< "\n";
if (compressible) {
switch (config->GetKind_FluidModel()) {
case STANDARD_AIR:
Breakdown_file << "Fluid Model: STANDARD_AIR "<< "\n";
Breakdown_file << "Specific gas constant: " << config->GetGas_Constant();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " N.m/kg.K." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " lbf.ft/slug.R." << "\n";
Breakdown_file << "Specific gas constant (non-dim): " << config->GetGas_ConstantND()<< "\n";
Breakdown_file << "Specific Heat Ratio: 1.4000 "<< "\n";
break;
case IDEAL_GAS:
Breakdown_file << "Fluid Model: IDEAL_GAS "<< "\n";
Breakdown_file << "Specific gas constant: " << config->GetGas_Constant() << " N.m/kg.K." << "\n";
Breakdown_file << "Specific gas constant (non-dim): " << config->GetGas_ConstantND()<< "\n";
Breakdown_file << "Specific Heat Ratio: "<< config->GetGamma() << "\n";
break;
case VW_GAS:
Breakdown_file << "Fluid Model: Van der Waals "<< "\n";
Breakdown_file << "Specific gas constant: " << config->GetGas_Constant() << " N.m/kg.K." << "\n";
Breakdown_file << "Specific gas constant (non-dim): " << config->GetGas_ConstantND()<< "\n";
Breakdown_file << "Specific Heat Ratio: "<< config->GetGamma() << "\n";
Breakdown_file << "Critical Pressure: " << config->GetPressure_Critical() << " Pa." << "\n";
Breakdown_file << "Critical Temperature: " << config->GetTemperature_Critical() << " K." << "\n";
Breakdown_file << "Critical Pressure (non-dim): " << config->GetPressure_Critical() /config->GetPressure_Ref() << "\n";
Breakdown_file << "Critical Temperature (non-dim) : " << config->GetTemperature_Critical() /config->GetTemperature_Ref() << "\n";
break;
case PR_GAS:
Breakdown_file << "Fluid Model: Peng-Robinson "<< "\n";
Breakdown_file << "Specific gas constant: " << config->GetGas_Constant() << " N.m/kg.K." << "\n";
Breakdown_file << "Specific gas constant(non-dim): " << config->GetGas_ConstantND()<< "\n";
Breakdown_file << "Specific Heat Ratio: "<< config->GetGamma() << "\n";
Breakdown_file << "Critical Pressure: " << config->GetPressure_Critical() << " Pa." << "\n";
Breakdown_file << "Critical Temperature: " << config->GetTemperature_Critical() << " K." << "\n";
Breakdown_file << "Critical Pressure (non-dim): " << config->GetPressure_Critical() /config->GetPressure_Ref() << "\n";
Breakdown_file << "Critical Temperature (non-dim) : " << config->GetTemperature_Critical() /config->GetTemperature_Ref() << "\n";
break;
}
if (viscous) {
switch (config->GetKind_ViscosityModel()) {
case CONSTANT_VISCOSITY:
Breakdown_file << "Viscosity Model: CONSTANT_VISCOSITY "<< "\n";
Breakdown_file << "Laminar Viscosity: " << config->GetMu_Constant();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " N.s/m^2." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " lbf.s/ft^2." << "\n";
Breakdown_file << "Laminar Viscosity (non-dim): " << config->GetMu_ConstantND()<< "\n";
break;
case SUTHERLAND:
Breakdown_file << "Viscosity Model: SUTHERLAND "<< "\n";
Breakdown_file << "Ref. Laminar Viscosity: " << config->GetMu_Ref();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " N.s/m^2." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " lbf.s/ft^2." << "\n";
Breakdown_file << "Ref. Temperature: " << config->GetMu_Temperature_Ref();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " K." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " R." << "\n";
Breakdown_file << "Sutherland Constant: "<< config->GetMu_S();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " K." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " R." << "\n";
Breakdown_file << "Laminar Viscosity (non-dim): " << config->GetMu_ConstantND()<< "\n";
Breakdown_file << "Ref. Temperature (non-dim): " << config->GetMu_Temperature_RefND()<< "\n";
Breakdown_file << "Sutherland constant (non-dim): "<< config->GetMu_SND()<< "\n";
break;
}
switch (config->GetKind_ConductivityModel()) {
case CONSTANT_PRANDTL:
Breakdown_file << "Conductivity Model: CONSTANT_PRANDTL "<< "\n";
Breakdown_file << "Prandtl: " << config->GetPrandtl_Lam()<< "\n";
break;
case CONSTANT_CONDUCTIVITY:
Breakdown_file << "Conductivity Model: CONSTANT_CONDUCTIVITY "<< "\n";
Breakdown_file << "Molecular Conductivity: " << config->GetKt_Constant()<< " W/m^2.K." << "\n";
Breakdown_file << "Molecular Conductivity (non-dim): " << config->GetKt_ConstantND()<< "\n";
break;
}
if ((Kind_Solver == RANS) || (Kind_Solver == INC_RANS)) {
switch (config->GetKind_ConductivityModel_Turb()) {
case CONSTANT_PRANDTL_TURB:
Breakdown_file << "Turbulent Conductivity Model: CONSTANT_PRANDTL_TURB "<< "\n";
Breakdown_file << "Turbulent Prandtl: " << config->GetPrandtl_Turb()<< "\n";
break;
case NO_CONDUCTIVITY_TURB:
Breakdown_file << "Turbulent Conductivity Model: NO_CONDUCTIVITY_TURB "<< "\n";
Breakdown_file << "No turbulent component in effective thermal conductivity." << "\n";
break;
}
}
}
}
if (incompressible) {
Breakdown_file << "Bulk modulus: " << config->GetBulk_Modulus();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " Pa." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " psf." << "\n";
Breakdown_file << "Epsilon^2 multiplier of Beta for incompressible preconditioner: " << config->GetBeta_Factor();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " Pa." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " psf." << "\n";
}
Breakdown_file << "Free-stream static pressure: " << config->GetPressure_FreeStream();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " Pa." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " psf." << "\n";
Breakdown_file << "Free-stream total pressure: " << config->GetPressure_FreeStream() * pow( 1.0+config->GetMach()*config->GetMach()*0.5*(config->GetGamma()-1.0), config->GetGamma()/(config->GetGamma()-1.0) );
if (config->GetSystemMeasurements() == SI) Breakdown_file << " Pa." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " psf." << "\n";
if (compressible) {
Breakdown_file << "Free-stream temperature: " << config->GetTemperature_FreeStream();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " K." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " R." << "\n";
Breakdown_file << "Free-stream total temperature: " << config->GetTemperature_FreeStream() * (1.0 + config->GetMach() * config->GetMach() * 0.5 * (config->GetGamma() - 1.0));
if (config->GetSystemMeasurements() == SI) Breakdown_file << " K." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " R." << "\n";
}
Breakdown_file << "Free-stream density: " << config->GetDensity_FreeStream();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " kg/m^3." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " slug/ft^3." << "\n";
if (nDim == 2) {
Breakdown_file << "Free-stream velocity: (" << config->GetVelocity_FreeStream()[0] << ", ";
Breakdown_file << config->GetVelocity_FreeStream()[1] << ")";
}
if (nDim == 3) {
Breakdown_file << "Free-stream velocity: (" << config->GetVelocity_FreeStream()[0] << ", ";
Breakdown_file << config->GetVelocity_FreeStream()[1] << ", " << config->GetVelocity_FreeStream()[2] << ")";
}
if (config->GetSystemMeasurements() == SI) Breakdown_file << " m/s. ";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " ft/s. ";
Breakdown_file << "Magnitude: " << config->GetModVel_FreeStream();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " m/s." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " ft/s." << "\n";
if (compressible) {
Breakdown_file << "Free-stream total energy per unit mass: " << config->GetEnergy_FreeStream();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " m^2/s^2." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " ft^2/s^2." << "\n";
}
if (viscous) {
Breakdown_file << "Free-stream viscosity: " << config->GetViscosity_FreeStream();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " N.s/m^2." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " lbf.s/ft^2." << "\n";
if (turbulent) {
Breakdown_file << "Free-stream turb. kinetic energy per unit mass: " << config->GetTke_FreeStream();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " m^2/s^2." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " ft^2/s^2." << "\n";
Breakdown_file << "Free-stream specific dissipation: " << config->GetOmega_FreeStream();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " 1/s." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " 1/s." << "\n";
}
}
if (unsteady) { Breakdown_file << "Total time: " << config->GetTotal_UnstTime() << " s. Time step: " << config->GetDelta_UnstTime() << " s." << "\n"; }
/*--- Print out reference values. ---*/
Breakdown_file <<"-- Reference values:"<< "\n";
if (compressible) {
Breakdown_file << "Reference specific gas constant: " << config->GetGas_Constant_Ref();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " N.m/kg.K." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " lbf.ft/slug.R." << "\n";
}
Breakdown_file << "Reference pressure: " << config->GetPressure_Ref();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " Pa." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " psf." << "\n";
if (compressible) {
Breakdown_file << "Reference temperature: " << config->GetTemperature_Ref();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " K." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " R." << "\n";
}
Breakdown_file << "Reference density: " << config->GetDensity_Ref();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " kg/m^3." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " slug/ft^3." << "\n";
Breakdown_file << "Reference velocity: " << config->GetVelocity_Ref();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " m/s." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " ft/s." << "\n";
if (compressible) {
Breakdown_file << "Reference energy per unit mass: " << config->GetEnergy_Ref();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " m^2/s^2." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " ft^2/s^2." << "\n";
}
if (incompressible) {
Breakdown_file << "Reference length: " << config->GetLength_Ref();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " m." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " in." << "\n";
}
if (viscous) {
Breakdown_file << "Reference viscosity: " << config->GetViscosity_Ref();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " N.s/m^2." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " lbf.s/ft^2." << "\n";
if (compressible){
Breakdown_file << "Reference conductivity: " << config->GetConductivity_Ref();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " W/m^2.K." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " lbf/ft.s.R." << "\n";
}
}
if (unsteady) Breakdown_file << "Reference time: " << config->GetTime_Ref() <<" s." << "\n";
/*--- Print out resulting non-dim values here. ---*/
Breakdown_file << "-- Resulting non-dimensional state:" << "\n";
Breakdown_file << "Mach number (non-dim): " << config->GetMach() << "\n";
if (viscous) {
Breakdown_file << "Reynolds number (non-dim): " << config->GetReynolds() <<". Re length: " << config->GetLength_Reynolds();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " m." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " ft." << "\n";
}
if (gravity) {
Breakdown_file << "Froude number (non-dim): " << config->GetFroude() << "\n";
Breakdown_file << "Lenght of the baseline wave (non-dim): " << 2.0*PI_NUMBER*config->GetFroude()*config->GetFroude() << "\n";
}
if (compressible) {
Breakdown_file << "Specific gas constant (non-dim): " << config->GetGas_ConstantND() << "\n";
Breakdown_file << "Free-stream temperature (non-dim): " << config->GetTemperature_FreeStreamND() << "\n";
}
Breakdown_file << "Free-stream pressure (non-dim): " << config->GetPressure_FreeStreamND() << "\n";
Breakdown_file << "Free-stream density (non-dim): " << config->GetDensity_FreeStreamND() << "\n";
if (nDim == 2) {
Breakdown_file << "Free-stream velocity (non-dim): (" << config->GetVelocity_FreeStreamND()[0] << ", ";
Breakdown_file << config->GetVelocity_FreeStreamND()[1] << "). ";
} else {
Breakdown_file << "Free-stream velocity (non-dim): (" << config->GetVelocity_FreeStreamND()[0] << ", ";
Breakdown_file << config->GetVelocity_FreeStreamND()[1] << ", " << config->GetVelocity_FreeStreamND()[2] << "). ";
}
Breakdown_file << "Magnitude: " << config->GetModVel_FreeStreamND() << "\n";
if (compressible)
Breakdown_file << "Free-stream total energy per unit mass (non-dim): " << config->GetEnergy_FreeStreamND() << "\n";
if (viscous) {
Breakdown_file << "Free-stream viscosity (non-dim): " << config->GetViscosity_FreeStreamND() << "\n";
if (turbulent) {
Breakdown_file << "Free-stream turb. kinetic energy (non-dim): " << config->GetTke_FreeStreamND() << "\n";
Breakdown_file << "Free-stream specific dissipation (non-dim): " << config->GetOmega_FreeStreamND() << "\n";
}
}
if (unsteady) {
Breakdown_file << "Total time (non-dim): " << config->GetTotal_UnstTimeND() << "\n";
Breakdown_file << "Time step (non-dim): " << config->GetDelta_UnstTimeND() << "\n";
}
} else {
/*--- Incompressible version of the console output ---*/
bool energy = config->GetEnergy_Equation();
bool boussinesq = (config->GetKind_DensityModel() == BOUSSINESQ);
if (config->GetRef_Inc_NonDim() == DIMENSIONAL) {
Breakdown_file << "Viscous and Inviscid flow: rho_ref, vel_ref, temp_ref, p_ref" << "\n";
Breakdown_file << "are set to 1.0 in order to perform a dimensional calculation." << "\n";
if (dynamic_grid) Breakdown_file << "Force coefficients computed using MACH_MOTION." << "\n";
else Breakdown_file << "Force coefficients computed using initial values." << "\n";
}
else if (config->GetRef_Inc_NonDim() == INITIAL_VALUES) {
Breakdown_file << "Viscous and Inviscid flow: rho_ref, vel_ref, and temp_ref" << "\n";
Breakdown_file << "are based on the initial values, p_ref = rho_ref*vel_ref^2." << "\n";
if (dynamic_grid) Breakdown_file << "Force coefficients computed using MACH_MOTION." << "\n";
else Breakdown_file << "Force coefficients computed using initial values." << "\n";
}
else if (config->GetRef_Inc_NonDim() == REFERENCE_VALUES) {
Breakdown_file << "Viscous and Inviscid flow: rho_ref, vel_ref, and temp_ref" << "\n";
Breakdown_file << "are user-provided reference values, p_ref = rho_ref*vel_ref^2." << "\n";
if (dynamic_grid) Breakdown_file << "Force coefficients computed using MACH_MOTION." << "\n";
else Breakdown_file << "Force coefficients computed using reference values." << "\n";
}
Breakdown_file << "The reference area for force coeffs. is " << config->GetRefArea() << " m^2." << "\n";
Breakdown_file << "The reference length for force coeffs. is " << config->GetRefLength() << " m." << "\n";
Breakdown_file << "The pressure is decomposed into thermodynamic and dynamic components." << "\n";
Breakdown_file << "The initial value of the dynamic pressure is 0." << "\n";
Breakdown_file << "Mach number: "<< config->GetMach();
if (config->GetKind_FluidModel() == CONSTANT_DENSITY) {
Breakdown_file << ", computed using the Bulk modulus." << "\n";
} else {
Breakdown_file << ", computed using fluid speed of sound." << "\n";
}
Breakdown_file << "For external flows, the initial state is imposed at the far-field." << "\n";
Breakdown_file << "Angle of attack (deg): "<< config->GetAoA() << ", computed using the initial velocity." << "\n";
Breakdown_file << "Side slip angle (deg): "<< config->GetAoS() << ", computed using the initial velocity." << "\n";
if (viscous) {
Breakdown_file << "Reynolds number per meter: " << config->GetReynolds() << ", computed using initial values."<< "\n";
Breakdown_file << "Reynolds number is a byproduct of inputs only (not used internally)." << "\n";
}
Breakdown_file << "SI units only. The grid should be dimensional (meters)." << "\n";
switch (config->GetKind_DensityModel()) {
case CONSTANT:
if (energy) Breakdown_file << "Energy equation is active and decoupled." << "\n";
else Breakdown_file << "No energy equation." << "\n";
break;
case BOUSSINESQ:
if (energy) Breakdown_file << "Energy equation is active and coupled through Boussinesq approx." << "\n";
break;
case VARIABLE:
if (energy) Breakdown_file << "Energy equation is active and coupled for variable density." << "\n";
break;
}
Breakdown_file <<"-- Input conditions:"<< "\n";
switch (config->GetKind_FluidModel()) {
case CONSTANT_DENSITY:
Breakdown_file << "Fluid Model: CONSTANT_DENSITY "<< "\n";
if (energy) {
Breakdown_file << "Specific heat at constant pressure (Cp): " << config->GetSpecific_Heat_Cp() << " N.m/kg.K." << "\n";
}
if (boussinesq) Breakdown_file << "Thermal expansion coefficient: " << config->GetThermal_Expansion_Coeff() << " K^-1." << "\n";
Breakdown_file << "Thermodynamic pressure not required." << "\n";
break;
case INC_IDEAL_GAS:
Breakdown_file << "Fluid Model: INC_IDEAL_GAS "<< endl;
Breakdown_file << "Variable density incompressible flow using ideal gas law." << endl;
Breakdown_file << "Density is a function of temperature (constant thermodynamic pressure)." << endl;
Breakdown_file << "Specific heat at constant pressure (Cp): " << config->GetSpecific_Heat_Cp() << " N.m/kg.K." << endl;
Breakdown_file << "Molecular weight : "<< config->GetMolecular_Weight() << " g/mol" << endl;
Breakdown_file << "Specific gas constant: " << config->GetGas_Constant() << " N.m/kg.K." << endl;
Breakdown_file << "Thermodynamic pressure: " << config->GetPressure_Thermodynamic();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " Pa." << endl;
else if (config->GetSystemMeasurements() == US) Breakdown_file << " psf." << endl;
break;
case INC_IDEAL_GAS_POLY:
Breakdown_file << "Fluid Model: INC_IDEAL_GAS_POLY "<< endl;
Breakdown_file << "Variable density incompressible flow using ideal gas law." << endl;
Breakdown_file << "Density is a function of temperature (constant thermodynamic pressure)." << endl;
Breakdown_file << "Molecular weight: " << config->GetMolecular_Weight() << " g/mol." << endl;
Breakdown_file << "Specific gas constant: " << config->GetGas_Constant() << " N.m/kg.K." << endl;
Breakdown_file << "Specific gas constant (non-dim): " << config->GetGas_ConstantND() << endl;
Breakdown_file << "Thermodynamic pressure: " << config->GetPressure_Thermodynamic();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " Pa." << endl;
else if (config->GetSystemMeasurements() == US) Breakdown_file << " psf." << endl;
Breakdown_file << "Cp(T) polynomial coefficients: \n (";
for (unsigned short iVar = 0; iVar < config->GetnPolyCoeffs(); iVar++) {
Breakdown_file << config->GetCp_PolyCoeff(iVar);
if (iVar < config->GetnPolyCoeffs()-1) Breakdown_file << ", ";
}
Breakdown_file << ")." << endl;
Breakdown_file << "Cp(T) polynomial coefficients (non-dim.): \n (";
for (unsigned short iVar = 0; iVar < config->GetnPolyCoeffs(); iVar++) {
Breakdown_file << config->GetCp_PolyCoeffND(iVar);
if (iVar < config->GetnPolyCoeffs()-1) Breakdown_file << ", ";
}
Breakdown_file << ")." << endl;
break;
}
if (viscous) {
switch (config->GetKind_ViscosityModel()) {
case CONSTANT_VISCOSITY:
Breakdown_file << "Viscosity Model: CONSTANT_VISCOSITY "<< "\n";
Breakdown_file << "Constant Laminar Viscosity: " << config->GetMu_Constant();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " N.s/m^2." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " lbf.s/ft^2." << "\n";
Breakdown_file << "Laminar Viscosity (non-dim): " << config->GetMu_ConstantND()<< "\n";
break;
case SUTHERLAND:
Breakdown_file << "Viscosity Model: SUTHERLAND "<< "\n";
Breakdown_file << "Ref. Laminar Viscosity: " << config->GetMu_Ref();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " N.s/m^2." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " lbf.s/ft^2." << "\n";
Breakdown_file << "Ref. Temperature: " << config->GetMu_Temperature_Ref();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " K." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " R." << "\n";
Breakdown_file << "Sutherland Constant: "<< config->GetMu_S();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " K." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " R." << "\n";
Breakdown_file << "Laminar Viscosity (non-dim): " << config->GetMu_ConstantND()<< "\n";
Breakdown_file << "Ref. Temperature (non-dim): " << config->GetMu_Temperature_RefND()<< "\n";
Breakdown_file << "Sutherland constant (non-dim): "<< config->GetMu_SND()<< "\n";
break;
case POLYNOMIAL_VISCOSITY:
Breakdown_file << "Viscosity Model: POLYNOMIAL_VISCOSITY "<< endl;
Breakdown_file << "Mu(T) polynomial coefficients: \n (";
for (unsigned short iVar = 0; iVar < config->GetnPolyCoeffs(); iVar++) {
Breakdown_file << config->GetMu_PolyCoeff(iVar);
if (iVar < config->GetnPolyCoeffs()-1) Breakdown_file << ", ";
}
Breakdown_file << ")." << endl;
Breakdown_file << "Mu(T) polynomial coefficients (non-dim.): \n (";
for (unsigned short iVar = 0; iVar < config->GetnPolyCoeffs(); iVar++) {
Breakdown_file << config->GetMu_PolyCoeffND(iVar);
if (iVar < config->GetnPolyCoeffs()-1) Breakdown_file << ", ";
}
Breakdown_file << ")." << endl;
break;
}
if (energy) {
switch (config->GetKind_ConductivityModel()) {
case CONSTANT_PRANDTL:
Breakdown_file << "Conductivity Model: CONSTANT_PRANDTL "<< "\n";
Breakdown_file << "Prandtl (Laminar): " << config->GetPrandtl_Lam()<< "\n";
break;
case CONSTANT_CONDUCTIVITY:
Breakdown_file << "Conductivity Model: CONSTANT_CONDUCTIVITY "<< "\n";
Breakdown_file << "Molecular Conductivity: " << config->GetKt_Constant()<< " W/m^2.K." << "\n";
Breakdown_file << "Molecular Conductivity (non-dim): " << config->GetKt_ConstantND()<< "\n";
break;
case POLYNOMIAL_CONDUCTIVITY:
Breakdown_file << "Viscosity Model: POLYNOMIAL_CONDUCTIVITY "<< endl;
Breakdown_file << "Kt(T) polynomial coefficients: \n (";
for (unsigned short iVar = 0; iVar < config->GetnPolyCoeffs(); iVar++) {
Breakdown_file << config->GetKt_PolyCoeff(iVar);
if (iVar < config->GetnPolyCoeffs()-1) Breakdown_file << ", ";
}
Breakdown_file << ")." << endl;
Breakdown_file << "Kt(T) polynomial coefficients (non-dim.): \n (";
for (unsigned short iVar = 0; iVar < config->GetnPolyCoeffs(); iVar++) {
Breakdown_file << config->GetKt_PolyCoeffND(iVar);
if (iVar < config->GetnPolyCoeffs()-1) Breakdown_file << ", ";
}
Breakdown_file << ")." << endl;
break;
}
if ((Kind_Solver == RANS) || (Kind_Solver == ADJ_RANS) || (Kind_Solver == DISC_ADJ_RANS)) {
switch (config->GetKind_ConductivityModel_Turb()) {
case CONSTANT_PRANDTL_TURB:
Breakdown_file << "Turbulent Conductivity Model: CONSTANT_PRANDTL_TURB "<< "\n";
Breakdown_file << "Turbulent Prandtl: " << config->GetPrandtl_Turb()<< "\n";
break;
case NO_CONDUCTIVITY_TURB:
Breakdown_file << "Turbulent Conductivity Model: NO_CONDUCTIVITY_TURB "<< "\n";
Breakdown_file << "No turbulent component in effective thermal conductivity." << "\n";
break;
}
}
}
}
if (config->GetKind_FluidModel() == CONSTANT_DENSITY) {
Breakdown_file << "Bulk modulus: " << config->GetBulk_Modulus();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " Pa." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " psf." << "\n";
}
Breakdown_file << "Initial dynamic pressure: " << config->GetPressure_FreeStream();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " Pa." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " psf." << "\n";
Breakdown_file << "Initial total pressure: " << config->GetPressure_FreeStream() + 0.5*config->GetDensity_FreeStream()*config->GetModVel_FreeStream()*config->GetModVel_FreeStream();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " Pa." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " psf." << "\n";
if (energy) {
Breakdown_file << "Initial temperature: " << config->GetTemperature_FreeStream();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " K." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " R." << "\n";
}
Breakdown_file << "Initial density: " << config->GetDensity_FreeStream();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " kg/m^3." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " slug/ft^3." << "\n";
if (nDim == 2) {
Breakdown_file << "Initial velocity: (" << config->GetVelocity_FreeStream()[0] << ", ";
Breakdown_file << config->GetVelocity_FreeStream()[1] << ")";
}
if (nDim == 3) {
Breakdown_file << "Initial velocity: (" << config->GetVelocity_FreeStream()[0] << ", ";
Breakdown_file << config->GetVelocity_FreeStream()[1] << ", " << config->GetVelocity_FreeStream()[2] << ")";
}
if (config->GetSystemMeasurements() == SI) Breakdown_file << " m/s. ";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " ft/s. ";
Breakdown_file << "Magnitude: " << config->GetModVel_FreeStream();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " m/s." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " ft/s." << "\n";
if (viscous) {
Breakdown_file << "Initial laminar viscosity: " << config->GetViscosity_FreeStream();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " N.s/m^2." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " lbf.s/ft^2." << "\n";
if (turbulent) {
Breakdown_file << "Initial turb. kinetic energy per unit mass: " << config->GetTke_FreeStream();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " m^2/s^2." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " ft^2/s^2." << "\n";
Breakdown_file << "Initial specific dissipation: " << config->GetOmega_FreeStream();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " 1/s." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " 1/s." << "\n";
}
}
if (unsteady) { Breakdown_file << "Total time: " << config->GetTotal_UnstTime() << " s. Time step: " << config->GetDelta_UnstTime() << " s." << "\n"; }
/*--- Print out reference values. ---*/
Breakdown_file <<"-- Reference values:"<< "\n";
if (config->GetKind_FluidModel() != CONSTANT_DENSITY) {
Breakdown_file << "Reference specific gas constant: " << config->GetGas_Constant_Ref();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " N.m/kg.K." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " lbf.ft/slug.R." << "\n";
} else {
if (energy) {
Breakdown_file << "Reference specific heat: " << config->GetGas_Constant_Ref();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " N.m/kg.K." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " lbf.ft/slug.R." << "\n";
}
}
Breakdown_file << "Reference pressure: " << config->GetPressure_Ref();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " Pa." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " psf." << "\n";
if (energy) {
Breakdown_file << "Reference temperature: " << config->GetTemperature_Ref();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " K." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " R." << "\n";
}
Breakdown_file << "Reference density: " << config->GetDensity_Ref();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " kg/m^3." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " slug/ft^3." << "\n";
Breakdown_file << "Reference velocity: " << config->GetVelocity_Ref();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " m/s." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " ft/s." << "\n";
Breakdown_file << "Reference length: " << config->GetLength_Ref();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " m." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " in." << "\n";
if (viscous) {
Breakdown_file << "Reference viscosity: " << config->GetViscosity_Ref();
if (config->GetSystemMeasurements() == SI) Breakdown_file << " N.s/m^2." << "\n";
else if (config->GetSystemMeasurements() == US) Breakdown_file << " lbf.s/ft^2." << "\n";
}
if (unsteady) Breakdown_file << "Reference time: " << config->GetTime_Ref() <<" s." << "\n";
/*--- Print out resulting non-dim values here. ---*/
Breakdown_file << "-- Resulting non-dimensional state:" << "\n";
Breakdown_file << "Mach number (non-dim): " << config->GetMach() << "\n";
if (viscous) {
Breakdown_file << "Reynolds number (per m): " << config->GetReynolds() << "\n";
}
if (config->GetKind_FluidModel() != CONSTANT_DENSITY) {
Breakdown_file << "Specific gas constant (non-dim): " << config->GetGas_ConstantND() << "\n";
Breakdown_file << "Initial thermodynamic pressure (non-dim): " << config->GetPressure_ThermodynamicND() << "\n";
} else {
if (energy) {
Breakdown_file << "Specific heat at constant pressure (non-dim): " << config->GetSpecific_Heat_CpND() << "\n";
if (boussinesq) Breakdown_file << "Thermal expansion coefficient (non-dim.): " << config->GetThermal_Expansion_CoeffND() << " K^-1." << "\n";
}
}
if (energy) Breakdown_file << "Initial temperature (non-dim): " << config->GetTemperature_FreeStreamND() << "\n";
Breakdown_file << "Initial pressure (non-dim): " << config->GetPressure_FreeStreamND() << "\n";
Breakdown_file << "Initial density (non-dim): " << config->GetDensity_FreeStreamND() << "\n";
if (nDim == 2) {
Breakdown_file << "Initial velocity (non-dim): (" << config->GetVelocity_FreeStreamND()[0] << ", ";
Breakdown_file << config->GetVelocity_FreeStreamND()[1] << "). ";
} else {
Breakdown_file << "Initial velocity (non-dim): (" << config->GetVelocity_FreeStreamND()[0] << ", ";
Breakdown_file << config->GetVelocity_FreeStreamND()[1] << ", " << config->GetVelocity_FreeStreamND()[2] << "). ";
}
Breakdown_file << "Magnitude: " << config->GetModVel_FreeStreamND() << "\n";
if (viscous) {
Breakdown_file << "Initial viscosity (non-dim): " << config->GetViscosity_FreeStreamND() << "\n";
if (turbulent) {
Breakdown_file << "Initial turb. kinetic energy (non-dim): " << config->GetTke_FreeStreamND() << "\n";
Breakdown_file << "Initial specific dissipation (non-dim): " << config->GetOmega_FreeStreamND() << "\n";
}
}
if (unsteady) {
Breakdown_file << "Total time (non-dim): " << config->GetTotal_UnstTimeND() << "\n";
Breakdown_file << "Time step (non-dim): " << config->GetDelta_UnstTimeND() << "\n";
}
}
/*--- Begin forces breakdown info. ---*/
Breakdown_file << fixed;
Breakdown_file << "\n" << "\n" <<"Forces breakdown:" << "\n" << "\n";
if (nDim == 3) {
su2double m = solver_container[FLOW_SOL]->GetTotal_CFz()/solver_container[FLOW_SOL]->GetTotal_CFx();
su2double term = (Total_CoPz/m)-Total_CoPx;
if (term > 0) Breakdown_file << "Center of Pressure: X=" << 1/m <<"Z-"<< term << "." << "\n\n";
else Breakdown_file << "Center of Pressure: X=" << 1/m <<"Z+"<< fabs(term);
if (config->GetSystemMeasurements() == SI) Breakdown_file << " m." << "\n\n";
else Breakdown_file << " in." << "\n\n";
}
else {
su2double m = solver_container[FLOW_SOL]->GetTotal_CFy()/solver_container[FLOW_SOL]->GetTotal_CFx();
su2double term = (Total_CoPy/m)-Total_CoPx;
if (term > 0) Breakdown_file << "Center of Pressure: X=" << 1/m <<"Y-"<< term << "." << "\n\n";
else Breakdown_file << "Center of Pressure: X=" << 1/m <<"Y+"<< fabs(term);
if (config->GetSystemMeasurements() == SI) Breakdown_file << " m." << "\n\n";
else Breakdown_file << " in." << "\n\n";
}
/*--- Reference area and force factors. ---*/
su2double RefDensity, RefArea, RefVel, Factor, Ref;
RefArea = config->GetRefArea();
if (compressible) {
RefDensity = solver_container[FLOW_SOL]->GetDensity_Inf();
RefVel = solver_container[FLOW_SOL]->GetModVelocity_Inf();
} else {
if ((config->GetRef_Inc_NonDim() == DIMENSIONAL) ||
(config->GetRef_Inc_NonDim() == INITIAL_VALUES)) {
RefDensity = solver_container[FLOW_SOL]->GetDensity_Inf();
RefVel = 0.0;
for (iDim = 0; iDim < nDim; iDim++)
RefVel += solver_container[FLOW_SOL]->GetVelocity_Inf(iDim)*solver_container[FLOW_SOL]->GetVelocity_Inf(iDim);
RefVel = sqrt(RefVel);
} else {
RefDensity = config->GetInc_Density_Ref();
RefVel = config->GetInc_Velocity_Ref();
}
}
Factor = (0.5*RefDensity*RefArea*RefVel*RefVel);
Ref = config->GetDensity_Ref() * config->GetVelocity_Ref() * config->GetVelocity_Ref() * 1.0 * 1.0;
Breakdown_file << "NOTE: Multiply forces by the non-dimensional factor: " << Factor << ", and the reference factor: " << Ref << "\n";
Breakdown_file << "to obtain the dimensional force." << "\n" << "\n";
Breakdown_file << "Total CL: ";
Breakdown_file.width(11);
Breakdown_file << Total_CL;
Breakdown_file << " | Pressure (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Inv_CL * 100.0) / (Total_CL + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Inv_CL;
Breakdown_file << " | Friction (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Visc_CL * 100.0) / (Total_CL + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Visc_CL;
Breakdown_file << " | Momentum (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Mnt_CL * 100.0) / (Total_CL + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Mnt_CL << "\n";
Breakdown_file << "Total CD: ";
Breakdown_file.width(11);
Breakdown_file << Total_CD;
Breakdown_file << " | Pressure (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Inv_CD * 100.0) / (Total_CD + EPS)) << "%): ";
Breakdown_file.width(11);
Breakdown_file << Inv_CD;
Breakdown_file << " | Friction (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Visc_CD * 100.0) / (Total_CD + EPS)) << "%): ";
Breakdown_file.width(11);
Breakdown_file << Visc_CD;
Breakdown_file << " | Momentum (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Mnt_CD * 100.0) / (Total_CD + EPS)) << "%): ";
Breakdown_file.width(11);
Breakdown_file << Mnt_CD << "\n";
if (nDim == 3) {
Breakdown_file << "Total CSF: ";
Breakdown_file.width(11);
Breakdown_file << Total_CSF;
Breakdown_file << " | Pressure (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Inv_CSF * 100.0) / (Total_CSF + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Inv_CSF;
Breakdown_file << " | Friction (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Visc_CSF * 100.0) / (Total_CSF + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Visc_CSF;
Breakdown_file << " | Momentum (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Mnt_CSF * 100.0) / (Total_CSF + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Mnt_CSF << "\n";
}
Breakdown_file << "Total CL/CD: ";
Breakdown_file.width(11);
Breakdown_file << Total_CEff;
Breakdown_file << " | Pressure (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Inv_CEff * 100.0) / (Total_CEff + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Inv_CEff;
Breakdown_file << " | Friction (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Visc_CEff * 100.0) / (Total_CEff + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Visc_CEff;
Breakdown_file << " | Momentum (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Mnt_CEff * 100.0) / (Total_CEff + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Mnt_CEff << "\n";
if (nDim == 3) {
Breakdown_file << "Total CMx: ";
Breakdown_file.width(11);
Breakdown_file << Total_CMx;
Breakdown_file << " | Pressure (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Inv_CMx * 100.0) / (Total_CMx + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Inv_CMx;
Breakdown_file << " | Friction (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Visc_CMx * 100.0) / (Total_CMx + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Visc_CMx;
Breakdown_file << " | Momentum (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Mnt_CMx * 100.0) / (Total_CMx + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Mnt_CMx << "\n";
Breakdown_file << "Total CMy: ";
Breakdown_file.width(11);
Breakdown_file << Total_CMy;
Breakdown_file << " | Pressure (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Inv_CMy * 100.0) / (Total_CMy + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Inv_CMy;
Breakdown_file << " | Friction (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Visc_CMy * 100.0) / (Total_CMy + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Visc_CMy;
Breakdown_file << " | Momentum (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Mnt_CMz * 100.0) / (Total_CMz + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Mnt_CMy << "\n";
}
Breakdown_file << "Total CMz: ";
Breakdown_file.width(11);
Breakdown_file << Total_CMz;
Breakdown_file << " | Pressure (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Inv_CMz * 100.0) / (Total_CMz + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Inv_CMz;
Breakdown_file << " | Friction (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Visc_CMz * 100.0) / (Total_CMz + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Visc_CMz;
Breakdown_file << " | Momentum (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Mnt_CMz * 100.0) / (Total_CMz + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Mnt_CMz << "\n";
Breakdown_file << "Total CFx: ";
Breakdown_file.width(11);
Breakdown_file << Total_CFx;
Breakdown_file << " | Pressure (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Inv_CFx * 100.0) / (Total_CFx + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Inv_CFx;
Breakdown_file << " | Friction (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Visc_CFx * 100.0) / (Total_CFx + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Visc_CFx;
Breakdown_file << " | Momentum (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Mnt_CFx * 100.0) / (Total_CFx + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Mnt_CFx << "\n";
Breakdown_file << "Total CFy: ";
Breakdown_file.width(11);
Breakdown_file << Total_CFy;
Breakdown_file << " | Pressure (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Inv_CFy * 100.0) / (Total_CFy + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Inv_CFy;
Breakdown_file << " | Friction (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Visc_CFy * 100.0) / (Total_CFy + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Visc_CFy;
Breakdown_file << " | Momentum (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Mnt_CFy * 100.0) / (Total_CFy + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Mnt_CFy << "\n";
if (nDim == 3) {
Breakdown_file << "Total CFz: ";
Breakdown_file.width(11);
Breakdown_file << Total_CFz;
Breakdown_file << " | Pressure (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Inv_CFz * 100.0) / (Total_CFz + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Inv_CFz;
Breakdown_file << " | Friction (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Visc_CFz * 100.0) / (Total_CFz + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Visc_CFz;
Breakdown_file << " | Momentum (";
Breakdown_file.width(5);
Breakdown_file << SU2_TYPE::Int((Mnt_CFz * 100.0) / (Total_CFz + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Mnt_CFz << "\n";
}
Breakdown_file << "\n" << "\n";
for (iMarker_Monitoring = 0;
iMarker_Monitoring < config->GetnMarker_Monitoring();
iMarker_Monitoring++) {
Breakdown_file << "Surface name: "
<< config->GetMarker_Monitoring_TagBound(
iMarker_Monitoring) << "\n" << "\n";
Breakdown_file << "Total CL (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CL[iMarker_Monitoring] * 100.0)
/ (Total_CL + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Surface_CL[iMarker_Monitoring];
Breakdown_file << " | Pressure (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CL_Inv[iMarker_Monitoring] * 100.0)
/ (Surface_CL[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Surface_CL_Inv[iMarker_Monitoring];
Breakdown_file << " | Friction (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CL_Visc[iMarker_Monitoring] * 100.0)
/ (Surface_CL[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Surface_CL_Visc[iMarker_Monitoring];
Breakdown_file << " | Momentum (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CL_Mnt[iMarker_Monitoring] * 100.0)
/ (Surface_CL[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Surface_CL_Mnt[iMarker_Monitoring] << "\n";
Breakdown_file << "Total CD (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CD[iMarker_Monitoring] * 100.0)
/ (Total_CD + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Surface_CD[iMarker_Monitoring];
Breakdown_file << " | Pressure (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CD_Inv[iMarker_Monitoring] * 100.0)
/ (Surface_CD[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Surface_CD_Inv[iMarker_Monitoring];
Breakdown_file << " | Friction (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CD_Visc[iMarker_Monitoring] * 100.0)
/ (Surface_CD[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Surface_CD_Visc[iMarker_Monitoring];
Breakdown_file << " | Momentum (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CD_Mnt[iMarker_Monitoring] * 100.0)
/ (Surface_CD[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Surface_CD_Mnt[iMarker_Monitoring] << "\n";
if (nDim == 3) {
Breakdown_file << "Total CSF (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CSF[iMarker_Monitoring] * 100.0)
/ (Total_CSF + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Surface_CSF[iMarker_Monitoring];
Breakdown_file << " | Pressure (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CSF_Inv[iMarker_Monitoring] * 100.0)
/ (Surface_CSF[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Surface_CSF_Inv[iMarker_Monitoring];
Breakdown_file << " | Friction (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CSF_Visc[iMarker_Monitoring] * 100.0)
/ (Surface_CSF[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file
<< Surface_CSF_Visc[iMarker_Monitoring];
Breakdown_file << " | Momentum (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CSF_Mnt[iMarker_Monitoring] * 100.0)
/ (Surface_CSF[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file
<< Surface_CSF_Mnt[iMarker_Monitoring] << "\n";
}
Breakdown_file << "Total CL/CD (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CEff[iMarker_Monitoring] * 100.0) / (Total_CEff + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Surface_CEff[iMarker_Monitoring];
Breakdown_file << " | Pressure (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CEff_Inv[iMarker_Monitoring] * 100.0)
/ (Surface_CEff[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Surface_CEff_Inv[iMarker_Monitoring];
Breakdown_file << " | Friction (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CEff_Visc[iMarker_Monitoring] * 100.0)
/ (Surface_CEff[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file
<< Surface_CEff_Visc[iMarker_Monitoring];
Breakdown_file << " | Momentum (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CEff_Mnt[iMarker_Monitoring] * 100.0)
/ (Surface_CEff[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file
<< Surface_CEff_Mnt[iMarker_Monitoring] << "\n";
if (nDim == 3) {
Breakdown_file << "Total CMx (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CMx[iMarker_Monitoring] * 100.0) / (Total_CMx + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Surface_CMx[iMarker_Monitoring];
Breakdown_file << " | Pressure (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CMx_Inv[iMarker_Monitoring] * 100.0)
/ (Surface_CMx[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Surface_CMx_Inv[iMarker_Monitoring];
Breakdown_file << " | Friction (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CMx_Visc[iMarker_Monitoring] * 100.0)
/ (Surface_CMx[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file
<< Surface_CMx_Visc[iMarker_Monitoring];
Breakdown_file << " | Momentum (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CMx_Mnt[iMarker_Monitoring] * 100.0)
/ (Surface_CMx[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file
<< Surface_CMx_Mnt[iMarker_Monitoring] << "\n";
Breakdown_file << "Total CMy (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CMy[iMarker_Monitoring] * 100.0) / (Total_CMy + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Surface_CMy[iMarker_Monitoring];
Breakdown_file << " | Pressure (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CMy_Inv[iMarker_Monitoring] * 100.0)
/ (Surface_CMy[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Surface_CMy_Inv[iMarker_Monitoring];
Breakdown_file << " | Friction (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CMy_Visc[iMarker_Monitoring] * 100.0)
/ (Surface_CMy[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file
<< Surface_CMy_Visc[iMarker_Monitoring];
Breakdown_file << " | Momentum (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CMy_Mnt[iMarker_Monitoring] * 100.0)
/ (Surface_CMy[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file
<< Surface_CMy_Mnt[iMarker_Monitoring] << "\n";
}
Breakdown_file << "Total CMz (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int((Surface_CMz[iMarker_Monitoring] * 100.0) / (Total_CMz + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Surface_CMz[iMarker_Monitoring];
Breakdown_file << " | Pressure (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CMz_Inv[iMarker_Monitoring] * 100.0)
/ (Surface_CMz[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Surface_CMz_Inv[iMarker_Monitoring];
Breakdown_file << " | Friction (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CMz_Visc[iMarker_Monitoring] * 100.0)
/ (Surface_CMz[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file
<< Surface_CMz_Visc[iMarker_Monitoring];
Breakdown_file << " | Momentum (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CMz_Mnt[iMarker_Monitoring] * 100.0)
/ (Surface_CMz[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file
<< Surface_CMz_Mnt[iMarker_Monitoring] << "\n";
Breakdown_file << "Total CFx (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int((Surface_CFx[iMarker_Monitoring] * 100.0) / (Total_CFx + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Surface_CFx[iMarker_Monitoring];
Breakdown_file << " | Pressure (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CFx_Inv[iMarker_Monitoring] * 100.0)
/ (Surface_CFx[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Surface_CFx_Inv[iMarker_Monitoring];
Breakdown_file << " | Friction (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CFx_Visc[iMarker_Monitoring] * 100.0)
/ (Surface_CFx[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file
<< Surface_CFx_Visc[iMarker_Monitoring];
Breakdown_file << " | Momentum (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CFx_Mnt[iMarker_Monitoring] * 100.0)
/ (Surface_CFx[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file
<< Surface_CFx_Mnt[iMarker_Monitoring] << "\n";
Breakdown_file << "Total CFy (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int((Surface_CFy[iMarker_Monitoring] * 100.0) / (Total_CFy + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Surface_CFy[iMarker_Monitoring];
Breakdown_file << " | Pressure (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CFy_Inv[iMarker_Monitoring] * 100.0)
/ (Surface_CFy[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Surface_CFy_Inv[iMarker_Monitoring];
Breakdown_file << " | Friction (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CFy_Visc[iMarker_Monitoring] * 100.0)
/ (Surface_CFy[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file
<< Surface_CFy_Visc[iMarker_Monitoring];
Breakdown_file << " | Momentum (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CFy_Mnt[iMarker_Monitoring] * 100.0)
/ (Surface_CFy[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file
<< Surface_CFy_Mnt[iMarker_Monitoring] << "\n";
if (nDim == 3) {
Breakdown_file << "Total CFz (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CFz[iMarker_Monitoring] * 100.0) / (Total_CFz + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Surface_CFz[iMarker_Monitoring];
Breakdown_file << " | Pressure (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CFz_Inv[iMarker_Monitoring] * 100.0)
/ (Surface_CFz[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file << Surface_CFz_Inv[iMarker_Monitoring];
Breakdown_file << " | Friction (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CFz_Visc[iMarker_Monitoring] * 100.0)
/ (Surface_CFz[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file
<< Surface_CFz_Visc[iMarker_Monitoring];
Breakdown_file << " | Momentum (";
Breakdown_file.width(5);
Breakdown_file
<< SU2_TYPE::Int(
(Surface_CFz_Mnt[iMarker_Monitoring] * 100.0)
/ (Surface_CFz[iMarker_Monitoring] + EPS));
Breakdown_file << "%): ";
Breakdown_file.width(11);
Breakdown_file
<< Surface_CFz_Mnt[iMarker_Monitoring] << "\n";
}
Breakdown_file << "\n";
}
delete [] Surface_CL;
delete [] Surface_CD;
delete [] Surface_CSF;
delete [] Surface_CEff;
delete [] Surface_CFx;
delete [] Surface_CFy;
delete [] Surface_CFz;
delete [] Surface_CMx;
delete [] Surface_CMy;
delete [] Surface_CMz;
delete [] Surface_CL_Inv;
delete [] Surface_CD_Inv;
delete [] Surface_CSF_Inv;
delete [] Surface_CEff_Inv;
delete [] Surface_CFx_Inv;
delete [] Surface_CFy_Inv;
delete [] Surface_CFz_Inv;
delete [] Surface_CMx_Inv;
delete [] Surface_CMy_Inv;
delete [] Surface_CMz_Inv;
delete [] Surface_CL_Visc;
delete [] Surface_CD_Visc;
delete [] Surface_CSF_Visc;
delete [] Surface_CEff_Visc;
delete [] Surface_CFx_Visc;
delete [] Surface_CFy_Visc;
delete [] Surface_CFz_Visc;
delete [] Surface_CMx_Visc;
delete [] Surface_CMy_Visc;
delete [] Surface_CMz_Visc;
delete [] Surface_CL_Mnt;
delete [] Surface_CD_Mnt;
delete [] Surface_CSF_Mnt;
delete [] Surface_CEff_Mnt;
delete [] Surface_CFx_Mnt;
delete [] Surface_CFy_Mnt;
delete [] Surface_CFz_Mnt;
delete [] Surface_CMx_Mnt;
delete [] Surface_CMy_Mnt;
delete [] Surface_CMz_Mnt;
Breakdown_file.close();
}
}
bool CFlowOutput::WriteVolume_Output(CConfig *config, unsigned long Iter, bool force_writing){
if (config->GetTime_Domain()){
if (((config->GetTime_Marching() == DT_STEPPING_1ST) ||
(config->GetTime_Marching() == TIME_STEPPING)) &&
((Iter == 0) || (Iter % config->GetVolume_Wrt_Freq() == 0))){
return true;
}
if ((config->GetTime_Marching() == DT_STEPPING_2ND) &&
((Iter == 0) || (Iter % config->GetVolume_Wrt_Freq() == 0) ||
((Iter+1) % config->GetVolume_Wrt_Freq() == 0) ||
((Iter+2 == config->GetnTime_Iter())))){
return true;
}
} else {
if (config->GetFixed_CL_Mode() && config->GetFinite_Difference_Mode()) return false;
return ((Iter > 0) && Iter % config->GetVolume_Wrt_Freq() == 0) || force_writing;
}
return false || force_writing;
}
void CFlowOutput::SetTimeAveragedFields(){
AddVolumeOutput("MEAN_DENSITY", "MeanDensity", "TIME_AVERAGE", "Mean density");
AddVolumeOutput("MEAN_VELOCITY-X", "MeanVelocity_x", "TIME_AVERAGE", "Mean velocity x-component");
AddVolumeOutput("MEAN_VELOCITY-Y", "MeanVelocity_y", "TIME_AVERAGE", "Mean velocity y-component");
if (nDim == 3)
AddVolumeOutput("MEAN_VELOCITY-Z", "MeanVelocity_z", "TIME_AVERAGE", "Mean velocity z-component");
AddVolumeOutput("MEAN_PRESSURE", "MeanPressure", "TIME_AVERAGE", "Mean pressure");
AddVolumeOutput("RMS_U", "RMS[u]", "TIME_AVERAGE", "RMS u");
AddVolumeOutput("RMS_V", "RMS[v]", "TIME_AVERAGE", "RMS v");
AddVolumeOutput("RMS_UV", "RMS[uv]", "TIME_AVERAGE", "RMS uv");
AddVolumeOutput("RMS_P", "RMS[Pressure]", "TIME_AVERAGE", "RMS Pressure");
AddVolumeOutput("UUPRIME", "u'u'", "TIME_AVERAGE", "Mean Reynolds-stress component u'u'");
AddVolumeOutput("VVPRIME", "v'v'", "TIME_AVERAGE", "Mean Reynolds-stress component v'v'");
AddVolumeOutput("UVPRIME", "u'v'", "TIME_AVERAGE", "Mean Reynolds-stress component u'v'");
AddVolumeOutput("PPRIME", "p'p'", "TIME_AVERAGE", "Mean pressure fluctuation p'p'");
if (nDim == 3){
AddVolumeOutput("RMS_W", "RMS[w]", "TIME_AVERAGE", "RMS u");
AddVolumeOutput("RMS_UW", "RMS[uw]", "TIME_AVERAGE", "RMS uw");
AddVolumeOutput("RMS_VW", "RMS[vw]", "TIME_AVERAGE", "RMS vw");
AddVolumeOutput("WWPRIME", "w'w'", "TIME_AVERAGE", "Mean Reynolds-stress component w'w'");
AddVolumeOutput("UWPRIME", "w'u'", "TIME_AVERAGE", "Mean Reynolds-stress component w'u'");
AddVolumeOutput("VWPRIME", "w'v'", "TIME_AVERAGE", "Mean Reynolds-stress component w'v'");
}
}
void CFlowOutput::LoadTimeAveragedData(unsigned long iPoint, CVariable *Node_Flow){
SetAvgVolumeOutputValue("MEAN_DENSITY", iPoint, Node_Flow->GetDensity(iPoint));
SetAvgVolumeOutputValue("MEAN_VELOCITY-X", iPoint, Node_Flow->GetVelocity(iPoint,0));
SetAvgVolumeOutputValue("MEAN_VELOCITY-Y", iPoint, Node_Flow->GetVelocity(iPoint,1));
if (nDim == 3)
SetAvgVolumeOutputValue("MEAN_VELOCITY-Z", iPoint, Node_Flow->GetVelocity(iPoint,2));
SetAvgVolumeOutputValue("MEAN_PRESSURE", iPoint, Node_Flow->GetPressure(iPoint));
SetAvgVolumeOutputValue("RMS_U", iPoint, pow(Node_Flow->GetVelocity(iPoint,0),2));
SetAvgVolumeOutputValue("RMS_V", iPoint, pow(Node_Flow->GetVelocity(iPoint,1),2));
SetAvgVolumeOutputValue("RMS_UV", iPoint, Node_Flow->GetVelocity(iPoint,0) * Node_Flow->GetVelocity(iPoint,1));
SetAvgVolumeOutputValue("RMS_P", iPoint, pow(Node_Flow->GetPressure(iPoint),2));
if (nDim == 3){
SetAvgVolumeOutputValue("RMS_W", iPoint, pow(Node_Flow->GetVelocity(iPoint,2),2));
SetAvgVolumeOutputValue("RMS_VW", iPoint, Node_Flow->GetVelocity(iPoint,2) * Node_Flow->GetVelocity(iPoint,1));
SetAvgVolumeOutputValue("RMS_UW", iPoint, Node_Flow->GetVelocity(iPoint,2) * Node_Flow->GetVelocity(iPoint,0));
}
const su2double umean = GetVolumeOutputValue("MEAN_VELOCITY-X", iPoint);
const su2double uumean = GetVolumeOutputValue("RMS_U", iPoint);
const su2double vmean = GetVolumeOutputValue("MEAN_VELOCITY-Y", iPoint);
const su2double vvmean = GetVolumeOutputValue("RMS_V", iPoint);
const su2double uvmean = GetVolumeOutputValue("RMS_UV", iPoint);
const su2double pmean = GetVolumeOutputValue("MEAN_PRESSURE", iPoint);
const su2double ppmean = GetVolumeOutputValue("RMS_P", iPoint);
SetVolumeOutputValue("UUPRIME", iPoint, -(umean*umean - uumean));
SetVolumeOutputValue("VVPRIME", iPoint, -(vmean*vmean - vvmean));
SetVolumeOutputValue("UVPRIME", iPoint, -(umean*vmean - uvmean));
SetVolumeOutputValue("PPRIME", iPoint, -(pmean*pmean - ppmean));
if (nDim == 3){
const su2double wmean = GetVolumeOutputValue("MEAN_VELOCITY-Z", iPoint);
const su2double wwmean = GetVolumeOutputValue("RMS_W", iPoint);
const su2double uwmean = GetVolumeOutputValue("RMS_UW", iPoint);
const su2double vwmean = GetVolumeOutputValue("RMS_VW", iPoint);
SetVolumeOutputValue("WWPRIME", iPoint, -(wmean*wmean - wwmean));
SetVolumeOutputValue("UWPRIME", iPoint, -(umean*wmean - uwmean));
SetVolumeOutputValue("VWPRIME", iPoint, -(vmean*wmean - vwmean));
}
}
| 50.765864 | 226 | 0.634489 | Agony5757 |
61be0dc34bd8eb491cc05bc3a7a7a968e659a320 | 688 | cpp | C++ | test/src/graph/min_cost_flow/min_cost_flow.test.cpp | suisen-cp/cp-library-cpp | 8fbbdcdbceb60f5adc56ff4740549ce3c1a1ea43 | [
"CC0-1.0"
] | 2 | 2021-10-04T15:46:56.000Z | 2022-01-14T19:28:43.000Z | test/src/graph/min_cost_flow/min_cost_flow.test.cpp | suisen-cp/cp-library-cpp | 8fbbdcdbceb60f5adc56ff4740549ce3c1a1ea43 | [
"CC0-1.0"
] | null | null | null | test/src/graph/min_cost_flow/min_cost_flow.test.cpp | suisen-cp/cp-library-cpp | 8fbbdcdbceb60f5adc56ff4740549ce3c1a1ea43 | [
"CC0-1.0"
] | null | null | null | #define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_6_B"
#include <iostream>
#include "library/graph/min_cost_flow.hpp"
using namespace suisen;
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int n, m, f;
std::cin >> n >> m >> f;
MinCostFlow<int, int, DIJKSTRA> mcf(n);
for (int i = 0; i < m; ++i) {
int u, v, cap, cost;
std::cin >> u >> v >> cap >> cost;
mcf.add_edge(u, v, cap, cost);
}
auto [flow, cost] = mcf.min_cost_max_flow(0, n - 1, f);
if (flow == f) {
std::cout << cost << std::endl;
} else {
std::cout << -1 << std::endl;
}
return 0;
} | 24.571429 | 83 | 0.543605 | suisen-cp |
61c108a5ca04b37a528ae9d453b1b97b5ac02ae3 | 7,680 | cc | C++ | mars/comm/socket/udpclient.cc | 20150723/mars | 916f895d5d6c31a1f4720b189bb0a83e92e0161c | [
"Apache-2.0",
"BSD-2-Clause"
] | 325 | 2016-12-28T14:19:10.000Z | 2021-11-24T07:01:51.000Z | mars/comm/socket/udpclient.cc | wblzu/mars | 4396e753aee627a92b55ae7a1bc12b4d6f4f6445 | [
"Apache-2.0"
] | 2 | 2019-10-22T02:57:02.000Z | 2019-10-31T23:30:17.000Z | mars/comm/socket/udpclient.cc | pengjinning/mars | 227aff64a5b819555091a7d6eae6727701e9fff0 | [
"Apache-2.0",
"BSD-2-Clause"
] | 114 | 2016-12-28T14:36:15.000Z | 2021-12-08T09:05:50.000Z | // Tencent is pleased to support the open source community by making Mars available.
// Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
// Licensed under the MIT License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
// http://opensource.org/licenses/MIT
// 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.
/*
* UdpClient.cpp
*
* Created on: 2014-9-5
* Author: zhouzhijie
*/
#include "udpclient.h"
#include "comm/xlogger/xlogger.h"
#include "mars/boost/bind.hpp"
#include "comm/socket/socket_address.h"
#define DELETE_AND_NULL(a) {if (a) delete a; a = NULL;}
#define MAX_DATAGRAM 65536
struct UdpSendData
{
UdpSendData() {}
UdpSendData(const UdpSendData& rhs)
{
}
AutoBuffer data;
};
UdpClient::UdpClient(const std::string& _ip, int _port)
:fd_socket_(INVALID_SOCKET)
, event_(NULL)
, selector_(breaker_, true)
, thread_(NULL)
{
__InitSocket(_ip, _port);
}
UdpClient::UdpClient(const std::string& _ip, int _port, IAsyncUdpClientEvent* _event)
:fd_socket_(INVALID_SOCKET)
, event_(_event)
, selector_(breaker_, true)
{
thread_ = new Thread(boost::bind(&UdpClient::__RunLoop, this));
__InitSocket(_ip, _port);
}
UdpClient::~UdpClient()
{
if (thread_ && thread_->isruning())
{
event_ = NULL;
breaker_.Break();
thread_->join();
}
breaker_.Break();
DELETE_AND_NULL(thread_);
list_buffer_.clear();
if (fd_socket_ != INVALID_SOCKET)
socket_close(fd_socket_);
}
int UdpClient::SendBlock(void* _buf, size_t _len)
{
xassert2((fd_socket_ != INVALID_SOCKET && event_ == NULL), "socket invalid");
if (fd_socket_ == INVALID_SOCKET || event_ != NULL)
return -1;
int err = 0;
return __DoSelect(false, true, _buf, _len, err, -1);
}
int UdpClient::ReadBlock(void* _buf, size_t _len, int _timeOutMs)
{
xassert2((fd_socket_ != INVALID_SOCKET && event_ == NULL), "socket invalid");
if (fd_socket_ == INVALID_SOCKET || event_ != NULL)
return -1;
int err = 0;
return __DoSelect(true, false, _buf, _len, err, -1);
}
bool UdpClient::HasBuuferToSend()
{
ScopedLock lock(mutex_);
return !list_buffer_.empty();
}
void UdpClient::SendAsync(void* _buf, size_t _len)
{
xassert2((fd_socket_ != INVALID_SOCKET && event_ != NULL), "socket invalid");
if (fd_socket_ == INVALID_SOCKET || event_ == NULL)
return;
ScopedLock lock(mutex_);
list_buffer_.push_back(UdpSendData());
list_buffer_.back().data.Write(_buf, _len);
if (!thread_->isruning())
thread_->start();
breaker_.Break();
}
void UdpClient::SetIpPort(const std::string& _ip, int _port)
{
bzero(&addr_, sizeof(addr_));
addr_ = *(struct sockaddr_in*)(&socket_address(_ip.c_str(), _port).address());
}
void UdpClient::__InitSocket(const std::string& _ip, int _port)
{
int errCode = 0;
bzero(&addr_, sizeof(addr_));
addr_ = *(struct sockaddr_in*)(&socket_address(_ip.c_str(), _port).address());
fd_socket_ = socket(AF_INET, SOCK_DGRAM, 0);
if (fd_socket_ == INVALID_SOCKET)
{
errCode = socket_errno;
xerror2(TSF"udp socket create error, error: %0", socket_strerror(errCode));
return;
}
if (IPV4_BROADCAST_IP == _ip)
{
int on = 1;
if (setsockopt(fd_socket_, SOL_SOCKET, SO_BROADCAST, (const char *)&on, sizeof(on)) != 0)
{
errCode = socket_errno;
xerror2(TSF"udp set broadcast error: %0", socket_strerror(errCode));
return;
}
}
}
void UdpClient::__RunLoop()
{
xassert2(fd_socket_ != INVALID_SOCKET, "socket invalid");
if (fd_socket_ == INVALID_SOCKET)
return;
char* readBuffer = new char[MAX_DATAGRAM];
void* buf = NULL;
size_t len = 0;
int ret = 0;
while (true)
{
mutex_.lock();
bool bWriteSet = list_buffer_.size() > 0;
if (bWriteSet)
{
buf = list_buffer_.front().data.Ptr();
len = list_buffer_.front().data.Length();
} else {
bzero(readBuffer, MAX_DATAGRAM);
buf = readBuffer;
len = MAX_DATAGRAM - 1;
}
mutex_.unlock();
int err = 0;
ret = __DoSelect(bWriteSet ? false : true, bWriteSet, buf, len, err, -1); // only read or write can be true
if (ret == -1)
{
xerror2(TSF"select error");
if (event_)
event_->OnError(this, err);
break;
}
if (ret == -2 && event_ == NULL)
{
xinfo2(TSF"normal break");
break;
}
if (ret == -2)
continue;
if (bWriteSet)
{
ScopedLock lock(mutex_);
list_buffer_.pop_front();
continue;
}
}
delete[] readBuffer;
}
/*
* return -2 break, -1 error, 0 timeout, else handle size
*/
int UdpClient::__DoSelect(bool _bReadSet, bool _bWriteSet, void* _buf, size_t _len, int& _errno, int _timeoutMs)
{
xassert2((!(_bReadSet && _bWriteSet) && (_bReadSet || _bWriteSet)), "only read or write can be true, not both");
selector_.PreSelect();
if (_bWriteSet)
selector_.Write_FD_SET(fd_socket_);
else if (_bReadSet)
selector_.Read_FD_SET(fd_socket_);
selector_.Exception_FD_SET(fd_socket_);
int ret = ((_timeoutMs == -1) ? selector_.Select() : selector_.Select(_timeoutMs));
if (ret < 0)
{
xerror2(TSF"udp select error: %0", socket_strerror(selector_.Errno()));
_errno = selector_.Errno();
return -1;
}
if (ret == 0)
{
xinfo2(TSF"udp select timeout:%0 ms", _timeoutMs);
return 0;
}
// user break
if (selector_.IsException())
{
_errno = selector_.Errno();
xerror2(TSF"sel exception");
return -1;
}
if (selector_.IsBreak())
{
xinfo2(TSF"sel breaker");
return -2;
}
if (selector_.Exception_FD_ISSET(fd_socket_))
{
_errno = socket_errno;
xerror2(TSF"socket exception error");
return -1;
}
if (selector_.Write_FD_ISSET(fd_socket_))
{
int ret = (int)sendto(fd_socket_, (const char *)_buf, _len, 0, (sockaddr*)&addr_, sizeof(sockaddr_in));
if (ret == -1)
{
_errno = socket_errno;
xerror2(TSF"sendto error: %0", socket_strerror(_errno));
return -1;
}
if (event_)
event_->OnDataSent(this);
return ret;
}
if (selector_.Read_FD_ISSET(fd_socket_))
{
int ret = (int)recvfrom(fd_socket_, (char *)_buf, _len, 0, NULL, NULL);
if (ret == -1)
{
_errno = socket_errno;
xerror2(TSF"recvfrom error: %0", socket_strerror(_errno));
return -1;
}
if (event_)
event_->OnDataGramRead(this, _buf, ret);
return ret;
}
return -1;
}
| 27.137809 | 119 | 0.572266 | 20150723 |
61c5872aab5d12e1793a1b27a8cd3b7235ed1b2e | 1,704 | hpp | C++ | hpx/lcos/barrier.hpp | Titzi90/hpx | 150fb0de1cfe40c26a722918097199147957b45c | [
"BSL-1.0"
] | null | null | null | hpx/lcos/barrier.hpp | Titzi90/hpx | 150fb0de1cfe40c26a722918097199147957b45c | [
"BSL-1.0"
] | null | null | null | hpx/lcos/barrier.hpp | Titzi90/hpx | 150fb0de1cfe40c26a722918097199147957b45c | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2007-2012 Hartmut Kaiser
//
// 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)
#if !defined(HPX_LCOS_BARRIER_MAR_10_2010_0307PM)
#define HPX_LCOS_BARRIER_MAR_10_2010_0307PM
#include <hpx/exception.hpp>
#include <hpx/include/client.hpp>
#include <hpx/lcos/stubs/barrier.hpp>
///////////////////////////////////////////////////////////////////////////////
namespace hpx { namespace lcos
{
class barrier
: public components::client_base<barrier, lcos::stubs::barrier>
{
typedef components::client_base<barrier, lcos::stubs::barrier> base_type;
public:
barrier()
{}
/// Create a client side representation for the existing
/// \a server#barrier instance with the given global id \a gid.
barrier(naming::id_type gid)
: base_type(gid)
{}
barrier(lcos::shared_future<naming::id_type> gid)
: base_type(gid)
{}
///////////////////////////////////////////////////////////////////////
// exposed functionality of this component
lcos::future<void> wait_async()
{
return this->base_type::wait_async(get_gid());
}
void wait()
{
this->base_type::wait(get_gid());
}
lcos::future<void> set_exception_async(boost::exception_ptr const& e)
{
return this->base_type::set_exception_async(get_gid(), e);
}
void set_exception(boost::exception_ptr const& e)
{
this->base_type::set_exception(get_gid(), e);
}
};
}}
#endif
| 27.934426 | 81 | 0.562793 | Titzi90 |
61c5e7d3809f13c99eef5ff602b871c6b31848eb | 323,260 | hxx | C++ | _skbuild/linux-x86_64-3.8/cmake-build/projects/biogears/biogears/schema/biogears/BioGearsPhysiology.hxx | vybhavramachandran/mophy | 7271c12b85a324a4f1494e0ce15942dc25bc4931 | [
"Apache-2.0"
] | null | null | null | _skbuild/linux-x86_64-3.8/cmake-build/projects/biogears/biogears/schema/biogears/BioGearsPhysiology.hxx | vybhavramachandran/mophy | 7271c12b85a324a4f1494e0ce15942dc25bc4931 | [
"Apache-2.0"
] | 5 | 2020-12-23T00:19:32.000Z | 2020-12-29T20:53:58.000Z | _skbuild/linux-x86_64-3.8/cmake-build/projects/biogears/biogears/schema/biogears/BioGearsPhysiology.hxx | vybhavramachandran/biogears-vybhav | 7271c12b85a324a4f1494e0ce15942dc25bc4931 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2005-2014 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema to
// C++ data binding compiler.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
// In addition, as a special exception, Code Synthesis Tools CC gives
// permission to link this program with the Xerces-C++ library (or with
// modified versions of Xerces-C++ that use the same license as Xerces-C++),
// and distribute linked combinations including the two. You must obey
// the GNU General Public License version 2 in all respects for all of
// the code used other than Xerces-C++. If you modify this copy of the
// program, you may extend this exception to your version of the program,
// but you are not obligated to do so. If you do not wish to do so, delete
// this exception statement from your version.
//
// Furthermore, Code Synthesis Tools CC makes a special exception for
// the Free/Libre and Open Source Software (FLOSS) which is described
// in the accompanying FLOSSE file.
//
/**
* @file
* @brief Generated from BioGearsPhysiology.xsd.
*/
#ifndef CXX_OPT_BIOGEARS_CORE_SHARE_XSD__BIOGEARS_BIO_GEARS_PHYSIOLOGY_HXX
#define CXX_OPT_BIOGEARS_CORE_SHARE_XSD__BIOGEARS_BIO_GEARS_PHYSIOLOGY_HXX
#ifndef XSD_CXX11
#define XSD_CXX11
#endif
#ifndef XSD_USE_CHAR
#define XSD_USE_CHAR
#endif
#ifndef XSD_CXX_TREE_USE_CHAR
#define XSD_CXX_TREE_USE_CHAR
#endif
// Begin prologue.
//
#include <biogears/cdm-exports.h>
//
// End prologue.
#include <xsd/cxx/config.hxx>
#if (XSD_INT_VERSION != 4000000L)
#error XSD runtime version mismatch
#endif
#include <xsd/cxx/pre.hxx>
#include <xsd/cxx/xml/char-utf8.hxx>
#include <xsd/cxx/tree/exceptions.hxx>
#include <xsd/cxx/tree/elements.hxx>
#include <xsd/cxx/tree/types.hxx>
#include <xsd/cxx/xml/error-handler.hxx>
#include <xsd/cxx/xml/dom/auto-ptr.hxx>
#include <xsd/cxx/tree/parsing.hxx>
#include <xsd/cxx/tree/parsing/byte.hxx>
#include <xsd/cxx/tree/parsing/unsigned-byte.hxx>
#include <xsd/cxx/tree/parsing/short.hxx>
#include <xsd/cxx/tree/parsing/unsigned-short.hxx>
#include <xsd/cxx/tree/parsing/int.hxx>
#include <xsd/cxx/tree/parsing/unsigned-int.hxx>
#include <xsd/cxx/tree/parsing/long.hxx>
#include <xsd/cxx/tree/parsing/unsigned-long.hxx>
#include <xsd/cxx/tree/parsing/boolean.hxx>
#include <xsd/cxx/tree/parsing/float.hxx>
#include <xsd/cxx/tree/parsing/double.hxx>
#include <xsd/cxx/tree/parsing/decimal.hxx>
#include <xsd/cxx/xml/dom/serialization-header.hxx>
#include <xsd/cxx/tree/serialization.hxx>
#include <xsd/cxx/tree/serialization/byte.hxx>
#include <xsd/cxx/tree/serialization/unsigned-byte.hxx>
#include <xsd/cxx/tree/serialization/short.hxx>
#include <xsd/cxx/tree/serialization/unsigned-short.hxx>
#include <xsd/cxx/tree/serialization/int.hxx>
#include <xsd/cxx/tree/serialization/unsigned-int.hxx>
#include <xsd/cxx/tree/serialization/long.hxx>
#include <xsd/cxx/tree/serialization/unsigned-long.hxx>
#include <xsd/cxx/tree/serialization/boolean.hxx>
#include <xsd/cxx/tree/serialization/float.hxx>
#include <xsd/cxx/tree/serialization/double.hxx>
#include <xsd/cxx/tree/serialization/decimal.hxx>
#include <xsd/cxx/tree/std-ostream-operators.hxx>
/**
* @brief C++ namespace for the %http://www.w3.org/2001/XMLSchema
* schema namespace.
*/
namespace xml_schema
{
// anyType and anySimpleType.
//
/**
* @brief C++ type corresponding to the anyType XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::type type;
/**
* @brief C++ type corresponding to the anySimpleType XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::simple_type< char, type > simple_type;
/**
* @brief Alias for the anyType type.
*/
typedef ::xsd::cxx::tree::type container;
// 8-bit
//
/**
* @brief C++ type corresponding to the byte XML Schema
* built-in type.
*/
typedef signed char byte;
/**
* @brief C++ type corresponding to the unsignedByte XML Schema
* built-in type.
*/
typedef unsigned char unsigned_byte;
// 16-bit
//
/**
* @brief C++ type corresponding to the short XML Schema
* built-in type.
*/
typedef short short_;
/**
* @brief C++ type corresponding to the unsignedShort XML Schema
* built-in type.
*/
typedef unsigned short unsigned_short;
// 32-bit
//
/**
* @brief C++ type corresponding to the int XML Schema
* built-in type.
*/
typedef int int_;
/**
* @brief C++ type corresponding to the unsignedInt XML Schema
* built-in type.
*/
typedef unsigned int unsigned_int;
// 64-bit
//
/**
* @brief C++ type corresponding to the long XML Schema
* built-in type.
*/
typedef long long long_;
/**
* @brief C++ type corresponding to the unsignedLong XML Schema
* built-in type.
*/
typedef unsigned long long unsigned_long;
// Supposed to be arbitrary-length integral types.
//
/**
* @brief C++ type corresponding to the integer XML Schema
* built-in type.
*/
typedef long long integer;
/**
* @brief C++ type corresponding to the nonPositiveInteger XML Schema
* built-in type.
*/
typedef long long non_positive_integer;
/**
* @brief C++ type corresponding to the nonNegativeInteger XML Schema
* built-in type.
*/
typedef unsigned long long non_negative_integer;
/**
* @brief C++ type corresponding to the positiveInteger XML Schema
* built-in type.
*/
typedef unsigned long long positive_integer;
/**
* @brief C++ type corresponding to the negativeInteger XML Schema
* built-in type.
*/
typedef long long negative_integer;
// Boolean.
//
/**
* @brief C++ type corresponding to the boolean XML Schema
* built-in type.
*/
typedef bool boolean;
// Floating-point types.
//
/**
* @brief C++ type corresponding to the float XML Schema
* built-in type.
*/
typedef float float_;
/**
* @brief C++ type corresponding to the double XML Schema
* built-in type.
*/
typedef double double_;
/**
* @brief C++ type corresponding to the decimal XML Schema
* built-in type.
*/
typedef double decimal;
// String types.
//
/**
* @brief C++ type corresponding to the string XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::string< char, simple_type > string;
/**
* @brief C++ type corresponding to the normalizedString XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::normalized_string< char, string > normalized_string;
/**
* @brief C++ type corresponding to the token XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::token< char, normalized_string > token;
/**
* @brief C++ type corresponding to the Name XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::name< char, token > name;
/**
* @brief C++ type corresponding to the NMTOKEN XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::nmtoken< char, token > nmtoken;
/**
* @brief C++ type corresponding to the NMTOKENS XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::nmtokens< char, simple_type, nmtoken > nmtokens;
/**
* @brief C++ type corresponding to the NCName XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::ncname< char, name > ncname;
/**
* @brief C++ type corresponding to the language XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::language< char, token > language;
// ID/IDREF.
//
/**
* @brief C++ type corresponding to the ID XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::id< char, ncname > id;
/**
* @brief C++ type corresponding to the IDREF XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::idref< char, ncname, type > idref;
/**
* @brief C++ type corresponding to the IDREFS XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::idrefs< char, simple_type, idref > idrefs;
// URI.
//
/**
* @brief C++ type corresponding to the anyURI XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::uri< char, simple_type > uri;
// Qualified name.
//
/**
* @brief C++ type corresponding to the QName XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::qname< char, simple_type, uri, ncname > qname;
// Binary.
//
/**
* @brief Binary buffer type.
*/
typedef ::xsd::cxx::tree::buffer< char > buffer;
/**
* @brief C++ type corresponding to the base64Binary XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::base64_binary< char, simple_type > base64_binary;
/**
* @brief C++ type corresponding to the hexBinary XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::hex_binary< char, simple_type > hex_binary;
// Date/time.
//
/**
* @brief Time zone type.
*/
typedef ::xsd::cxx::tree::time_zone time_zone;
/**
* @brief C++ type corresponding to the date XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::date< char, simple_type > date;
/**
* @brief C++ type corresponding to the dateTime XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::date_time< char, simple_type > date_time;
/**
* @brief C++ type corresponding to the duration XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::duration< char, simple_type > duration;
/**
* @brief C++ type corresponding to the gDay XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::gday< char, simple_type > gday;
/**
* @brief C++ type corresponding to the gMonth XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::gmonth< char, simple_type > gmonth;
/**
* @brief C++ type corresponding to the gMonthDay XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::gmonth_day< char, simple_type > gmonth_day;
/**
* @brief C++ type corresponding to the gYear XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::gyear< char, simple_type > gyear;
/**
* @brief C++ type corresponding to the gYearMonth XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::gyear_month< char, simple_type > gyear_month;
/**
* @brief C++ type corresponding to the time XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::time< char, simple_type > time;
// Entity.
//
/**
* @brief C++ type corresponding to the ENTITY XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::entity< char, ncname > entity;
/**
* @brief C++ type corresponding to the ENTITIES XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::entities< char, simple_type, entity > entities;
/**
* @brief Content order sequence entry.
*/
typedef ::xsd::cxx::tree::content_order content_order;
// Namespace information and list stream. Used in
// serialization functions.
//
/**
* @brief Namespace serialization information.
*/
typedef ::xsd::cxx::xml::dom::namespace_info< char > namespace_info;
/**
* @brief Namespace serialization information map.
*/
typedef ::xsd::cxx::xml::dom::namespace_infomap< char > namespace_infomap;
/**
* @brief List serialization stream.
*/
typedef ::xsd::cxx::tree::list_stream< char > list_stream;
/**
* @brief Serialization wrapper for the %double type.
*/
typedef ::xsd::cxx::tree::as_double< double_ > as_double;
/**
* @brief Serialization wrapper for the %decimal type.
*/
typedef ::xsd::cxx::tree::as_decimal< decimal > as_decimal;
/**
* @brief Simple type facet.
*/
typedef ::xsd::cxx::tree::facet facet;
// Flags and properties.
//
/**
* @brief Parsing and serialization flags.
*/
typedef ::xsd::cxx::tree::flags flags;
/**
* @brief Parsing properties.
*/
typedef ::xsd::cxx::tree::properties< char > properties;
// Parsing/serialization diagnostics.
//
/**
* @brief Error severity.
*/
typedef ::xsd::cxx::tree::severity severity;
/**
* @brief Error condition.
*/
typedef ::xsd::cxx::tree::error< char > error;
/**
* @brief List of %error conditions.
*/
typedef ::xsd::cxx::tree::diagnostics< char > diagnostics;
// Exceptions.
//
/**
* @brief Root of the C++/Tree %exception hierarchy.
*/
typedef ::xsd::cxx::tree::exception< char > exception;
/**
* @brief Exception indicating that the size argument exceeds
* the capacity argument.
*/
typedef ::xsd::cxx::tree::bounds< char > bounds;
/**
* @brief Exception indicating that a duplicate ID value
* was encountered in the object model.
*/
typedef ::xsd::cxx::tree::duplicate_id< char > duplicate_id;
/**
* @brief Exception indicating a parsing failure.
*/
typedef ::xsd::cxx::tree::parsing< char > parsing;
/**
* @brief Exception indicating that an expected element
* was not encountered.
*/
typedef ::xsd::cxx::tree::expected_element< char > expected_element;
/**
* @brief Exception indicating that an unexpected element
* was encountered.
*/
typedef ::xsd::cxx::tree::unexpected_element< char > unexpected_element;
/**
* @brief Exception indicating that an expected attribute
* was not encountered.
*/
typedef ::xsd::cxx::tree::expected_attribute< char > expected_attribute;
/**
* @brief Exception indicating that an unexpected enumerator
* was encountered.
*/
typedef ::xsd::cxx::tree::unexpected_enumerator< char > unexpected_enumerator;
/**
* @brief Exception indicating that the text content was
* expected for an element.
*/
typedef ::xsd::cxx::tree::expected_text_content< char > expected_text_content;
/**
* @brief Exception indicating that a prefix-namespace
* mapping was not provided.
*/
typedef ::xsd::cxx::tree::no_prefix_mapping< char > no_prefix_mapping;
/**
* @brief Exception indicating that the type information
* is not available for a type.
*/
typedef ::xsd::cxx::tree::no_type_info< char > no_type_info;
/**
* @brief Exception indicating that the types are not
* related by inheritance.
*/
typedef ::xsd::cxx::tree::not_derived< char > not_derived;
/**
* @brief Exception indicating a serialization failure.
*/
typedef ::xsd::cxx::tree::serialization< char > serialization;
/**
* @brief Error handler callback interface.
*/
typedef ::xsd::cxx::xml::error_handler< char > error_handler;
/**
* @brief DOM interaction.
*/
namespace dom
{
/**
* @brief Automatic pointer for DOMDocument.
*/
using ::xsd::cxx::xml::dom::unique_ptr;
#ifndef XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA
#define XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA
/**
* @brief DOM user data key for back pointers to tree nodes.
*/
const XMLCh* const tree_node_key = ::xsd::cxx::tree::user_data_keys::node;
#endif
}
}
// Forward declarations.
//
namespace mil
{
namespace tatrc
{
namespace physiology
{
namespace datamodel
{
class BioGearsBloodChemistrySystemData;
class BioGearsCardiovascularSystemData;
class BioGearsDrugSystemData;
class BioGearsEndocrineSystemData;
class BioGearsEnergySystemData;
class BioGearsGastrointestinalSystemData;
class BioGearsHepaticSystemData;
class BioGearsNervousSystemData;
class BioGearsRenalSystemData;
class BioGearsRespiratorySystemData;
class BioGearsTissueSystemData;
}
}
}
}
#include <memory> // ::std::unique_ptr
#include <limits> // std::numeric_limits
#include <algorithm> // std::binary_search
#include <utility> // std::move
#include <xsd/cxx/xml/char-utf8.hxx>
#include <xsd/cxx/tree/exceptions.hxx>
#include <xsd/cxx/tree/elements.hxx>
#include <xsd/cxx/tree/containers.hxx>
#include <xsd/cxx/tree/list.hxx>
#include <xsd/cxx/xml/dom/parsing-header.hxx>
#include "../cdm/Physiology.hxx"
#include "../cdm/PatientActions.hxx"
namespace mil
{
namespace tatrc
{
namespace physiology
{
/**
* @brief C++ namespace for the %uri:/mil/tatrc/physiology/datamodel
* schema namespace.
*/
namespace datamodel
{
/**
* @brief Class corresponding to the %BioGearsBloodChemistrySystemData schema type.
*
* @nosubgrouping
*/
class BIOGEARS_CDM_API BioGearsBloodChemistrySystemData: public ::mil::tatrc::physiology::datamodel::BloodChemistrySystemData
{
public:
/**
* @name ArterialOxygenAverage_mmHg
*
* @brief Accessor and modifier functions for the %ArterialOxygenAverage_mmHg
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::RunningAverageData ArterialOxygenAverage_mmHg_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< ArterialOxygenAverage_mmHg_type, char > ArterialOxygenAverage_mmHg_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const ArterialOxygenAverage_mmHg_type&
ArterialOxygenAverage_mmHg () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
ArterialOxygenAverage_mmHg_type&
ArterialOxygenAverage_mmHg ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
ArterialOxygenAverage_mmHg (const ArterialOxygenAverage_mmHg_type& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
ArterialOxygenAverage_mmHg (::std::unique_ptr< ArterialOxygenAverage_mmHg_type > p);
//@}
/**
* @name ArterialCarbonDioxideAverage_mmHg
*
* @brief Accessor and modifier functions for the %ArterialCarbonDioxideAverage_mmHg
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::RunningAverageData ArterialCarbonDioxideAverage_mmHg_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< ArterialCarbonDioxideAverage_mmHg_type, char > ArterialCarbonDioxideAverage_mmHg_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const ArterialCarbonDioxideAverage_mmHg_type&
ArterialCarbonDioxideAverage_mmHg () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
ArterialCarbonDioxideAverage_mmHg_type&
ArterialCarbonDioxideAverage_mmHg ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
ArterialCarbonDioxideAverage_mmHg (const ArterialCarbonDioxideAverage_mmHg_type& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
ArterialCarbonDioxideAverage_mmHg (::std::unique_ptr< ArterialCarbonDioxideAverage_mmHg_type > p);
//@}
/**
* @name RhFactorMismatch_ct
*
* @brief Accessor and modifier functions for the %RhFactorMismatch_ct
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ RhFactorMismatch_ct_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< RhFactorMismatch_ct_type, char, ::xsd::cxx::tree::schema_type::double_ > RhFactorMismatch_ct_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const RhFactorMismatch_ct_type&
RhFactorMismatch_ct () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
RhFactorMismatch_ct_type&
RhFactorMismatch_ct ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
RhFactorMismatch_ct (const RhFactorMismatch_ct_type& x);
//@}
/**
* @name RhTransfusionReactionVolume_mL
*
* @brief Accessor and modifier functions for the %RhTransfusionReactionVolume_mL
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ RhTransfusionReactionVolume_mL_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< RhTransfusionReactionVolume_mL_type, char, ::xsd::cxx::tree::schema_type::double_ > RhTransfusionReactionVolume_mL_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const RhTransfusionReactionVolume_mL_type&
RhTransfusionReactionVolume_mL () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
RhTransfusionReactionVolume_mL_type&
RhTransfusionReactionVolume_mL ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
RhTransfusionReactionVolume_mL (const RhTransfusionReactionVolume_mL_type& x);
//@}
/**
* @name DonorRBC_ct
*
* @brief Accessor and modifier functions for the %DonorRBC_ct
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ DonorRBC_ct_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< DonorRBC_ct_type, char, ::xsd::cxx::tree::schema_type::double_ > DonorRBC_ct_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const DonorRBC_ct_type&
DonorRBC_ct () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
DonorRBC_ct_type&
DonorRBC_ct ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
DonorRBC_ct (const DonorRBC_ct_type& x);
//@}
/**
* @name PatientRBC_ct
*
* @brief Accessor and modifier functions for the %PatientRBC_ct
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ PatientRBC_ct_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< PatientRBC_ct_type, char, ::xsd::cxx::tree::schema_type::double_ > PatientRBC_ct_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const PatientRBC_ct_type&
PatientRBC_ct () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
PatientRBC_ct_type&
PatientRBC_ct ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
PatientRBC_ct (const PatientRBC_ct_type& x);
//@}
/**
* @name TwoCellAgglutinates_ct
*
* @brief Accessor and modifier functions for the %TwoCellAgglutinates_ct
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ TwoCellAgglutinates_ct_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< TwoCellAgglutinates_ct_type, char, ::xsd::cxx::tree::schema_type::double_ > TwoCellAgglutinates_ct_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const TwoCellAgglutinates_ct_type&
TwoCellAgglutinates_ct () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
TwoCellAgglutinates_ct_type&
TwoCellAgglutinates_ct ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
TwoCellAgglutinates_ct (const TwoCellAgglutinates_ct_type& x);
//@}
/**
* @name ThreeCellPatAgglutinates_ct
*
* @brief Accessor and modifier functions for the %ThreeCellPatAgglutinates_ct
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ ThreeCellPatAgglutinates_ct_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< ThreeCellPatAgglutinates_ct_type, char, ::xsd::cxx::tree::schema_type::double_ > ThreeCellPatAgglutinates_ct_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const ThreeCellPatAgglutinates_ct_type&
ThreeCellPatAgglutinates_ct () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
ThreeCellPatAgglutinates_ct_type&
ThreeCellPatAgglutinates_ct ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
ThreeCellPatAgglutinates_ct (const ThreeCellPatAgglutinates_ct_type& x);
//@}
/**
* @name ThreeCellDonAgglutinates_ct
*
* @brief Accessor and modifier functions for the %ThreeCellDonAgglutinates_ct
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ ThreeCellDonAgglutinates_ct_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< ThreeCellDonAgglutinates_ct_type, char, ::xsd::cxx::tree::schema_type::double_ > ThreeCellDonAgglutinates_ct_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const ThreeCellDonAgglutinates_ct_type&
ThreeCellDonAgglutinates_ct () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
ThreeCellDonAgglutinates_ct_type&
ThreeCellDonAgglutinates_ct ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
ThreeCellDonAgglutinates_ct (const ThreeCellDonAgglutinates_ct_type& x);
//@}
/**
* @name FourCellAgglutinates_ct
*
* @brief Accessor and modifier functions for the %FourCellAgglutinates_ct
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ FourCellAgglutinates_ct_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< FourCellAgglutinates_ct_type, char, ::xsd::cxx::tree::schema_type::double_ > FourCellAgglutinates_ct_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const FourCellAgglutinates_ct_type&
FourCellAgglutinates_ct () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
FourCellAgglutinates_ct_type&
FourCellAgglutinates_ct ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
FourCellAgglutinates_ct (const FourCellAgglutinates_ct_type& x);
//@}
/**
* @name RemovedRBC_ct
*
* @brief Accessor and modifier functions for the %RemovedRBC_ct
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ RemovedRBC_ct_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< RemovedRBC_ct_type, char, ::xsd::cxx::tree::schema_type::double_ > RemovedRBC_ct_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const RemovedRBC_ct_type&
RemovedRBC_ct () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
RemovedRBC_ct_type&
RemovedRBC_ct ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
RemovedRBC_ct (const RemovedRBC_ct_type& x);
//@}
/**
* @name Constructors
*/
//@{
/**
* @brief Default constructor.
*
* Note that this constructor leaves required elements and
* attributes uninitialized.
*/
BioGearsBloodChemistrySystemData ();
/**
* @brief Create an instance from the ultimate base and
* initializers for required elements and attributes.
*/
BioGearsBloodChemistrySystemData (const ArterialOxygenAverage_mmHg_type&,
const ArterialCarbonDioxideAverage_mmHg_type&,
const RhFactorMismatch_ct_type&,
const RhTransfusionReactionVolume_mL_type&,
const DonorRBC_ct_type&,
const PatientRBC_ct_type&,
const TwoCellAgglutinates_ct_type&,
const ThreeCellPatAgglutinates_ct_type&,
const ThreeCellDonAgglutinates_ct_type&,
const FourCellAgglutinates_ct_type&,
const RemovedRBC_ct_type&);
/**
* @brief Create an instance from the ultimate base and
* initializers for required elements and attributes
* (::std::unique_ptr version).
*
* This constructor will try to use the passed values directly
* instead of making copies.
*/
BioGearsBloodChemistrySystemData (::std::unique_ptr< ArterialOxygenAverage_mmHg_type >,
::std::unique_ptr< ArterialCarbonDioxideAverage_mmHg_type >,
const RhFactorMismatch_ct_type&,
const RhTransfusionReactionVolume_mL_type&,
const DonorRBC_ct_type&,
const PatientRBC_ct_type&,
const TwoCellAgglutinates_ct_type&,
const ThreeCellPatAgglutinates_ct_type&,
const ThreeCellDonAgglutinates_ct_type&,
const FourCellAgglutinates_ct_type&,
const RemovedRBC_ct_type&);
/**
* @brief Create an instance from a DOM element.
*
* @param e A DOM element to extract the data from.
* @param f Flags to create the new instance with.
* @param c A pointer to the object that will contain the new
* instance.
*/
BioGearsBloodChemistrySystemData (const ::xercesc::DOMElement& e,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
/**
* @brief Copy constructor.
*
* @param x An instance to make a copy of.
* @param f Flags to create the copy with.
* @param c A pointer to the object that will contain the copy.
*
* For polymorphic object models use the @c _clone function instead.
*/
BioGearsBloodChemistrySystemData (const BioGearsBloodChemistrySystemData& x,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
/**
* @brief Copy the instance polymorphically.
*
* @param f Flags to create the copy with.
* @param c A pointer to the object that will contain the copy.
* @return A pointer to the dynamically allocated copy.
*
* This function ensures that the dynamic type of the instance is
* used for copying and should be used for polymorphic object
* models instead of the copy constructor.
*/
virtual BioGearsBloodChemistrySystemData*
_clone (::xml_schema::flags f = 0,
::xml_schema::container* c = 0) const;
/**
* @brief Copy assignment operator.
*
* @param x An instance to make a copy of.
* @return A reference to itself.
*
* For polymorphic object models use the @c _clone function instead.
*/
BioGearsBloodChemistrySystemData&
operator= (const BioGearsBloodChemistrySystemData& x);
//@}
/**
* @brief Destructor.
*/
virtual
~BioGearsBloodChemistrySystemData ();
// Implementation.
//
//@cond
protected:
void
parse (::xsd::cxx::xml::dom::parser< char >&,
::xml_schema::flags);
protected:
::xsd::cxx::tree::one< ArterialOxygenAverage_mmHg_type > ArterialOxygenAverage_mmHg_;
::xsd::cxx::tree::one< ArterialCarbonDioxideAverage_mmHg_type > ArterialCarbonDioxideAverage_mmHg_;
::xsd::cxx::tree::one< RhFactorMismatch_ct_type > RhFactorMismatch_ct_;
::xsd::cxx::tree::one< RhTransfusionReactionVolume_mL_type > RhTransfusionReactionVolume_mL_;
::xsd::cxx::tree::one< DonorRBC_ct_type > DonorRBC_ct_;
::xsd::cxx::tree::one< PatientRBC_ct_type > PatientRBC_ct_;
::xsd::cxx::tree::one< TwoCellAgglutinates_ct_type > TwoCellAgglutinates_ct_;
::xsd::cxx::tree::one< ThreeCellPatAgglutinates_ct_type > ThreeCellPatAgglutinates_ct_;
::xsd::cxx::tree::one< ThreeCellDonAgglutinates_ct_type > ThreeCellDonAgglutinates_ct_;
::xsd::cxx::tree::one< FourCellAgglutinates_ct_type > FourCellAgglutinates_ct_;
::xsd::cxx::tree::one< RemovedRBC_ct_type > RemovedRBC_ct_;
//@endcond
};
/**
* @brief Class corresponding to the %BioGearsCardiovascularSystemData schema type.
*
* @nosubgrouping
*/
class BIOGEARS_CDM_API BioGearsCardiovascularSystemData: public ::mil::tatrc::physiology::datamodel::CardiovascularSystemData
{
public:
/**
* @name StartSystole
*
* @brief Accessor and modifier functions for the %StartSystole
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::boolean StartSystole_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< StartSystole_type, char > StartSystole_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const StartSystole_type&
StartSystole () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
StartSystole_type&
StartSystole ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
StartSystole (const StartSystole_type& x);
//@}
/**
* @name HeartFlowDetected
*
* @brief Accessor and modifier functions for the %HeartFlowDetected
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::boolean HeartFlowDetected_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< HeartFlowDetected_type, char > HeartFlowDetected_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const HeartFlowDetected_type&
HeartFlowDetected () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
HeartFlowDetected_type&
HeartFlowDetected ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
HeartFlowDetected (const HeartFlowDetected_type& x);
//@}
/**
* @name EnterCardiacArrest
*
* @brief Accessor and modifier functions for the %EnterCardiacArrest
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::boolean EnterCardiacArrest_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< EnterCardiacArrest_type, char > EnterCardiacArrest_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const EnterCardiacArrest_type&
EnterCardiacArrest () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
EnterCardiacArrest_type&
EnterCardiacArrest ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
EnterCardiacArrest (const EnterCardiacArrest_type& x);
//@}
/**
* @name CardiacCyclePeriod_s
*
* @brief Accessor and modifier functions for the %CardiacCyclePeriod_s
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ CardiacCyclePeriod_s_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CardiacCyclePeriod_s_type, char, ::xsd::cxx::tree::schema_type::double_ > CardiacCyclePeriod_s_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CardiacCyclePeriod_s_type&
CardiacCyclePeriod_s () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CardiacCyclePeriod_s_type&
CardiacCyclePeriod_s ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CardiacCyclePeriod_s (const CardiacCyclePeriod_s_type& x);
//@}
/**
* @name CurrentCardiacCycleDuration_s
*
* @brief Accessor and modifier functions for the %CurrentCardiacCycleDuration_s
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ CurrentCardiacCycleDuration_s_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CurrentCardiacCycleDuration_s_type, char, ::xsd::cxx::tree::schema_type::double_ > CurrentCardiacCycleDuration_s_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CurrentCardiacCycleDuration_s_type&
CurrentCardiacCycleDuration_s () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CurrentCardiacCycleDuration_s_type&
CurrentCardiacCycleDuration_s ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CurrentCardiacCycleDuration_s (const CurrentCardiacCycleDuration_s_type& x);
//@}
/**
* @name LeftHeartElastanceModifier
*
* @brief Accessor and modifier functions for the %LeftHeartElastanceModifier
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ LeftHeartElastanceModifier_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< LeftHeartElastanceModifier_type, char, ::xsd::cxx::tree::schema_type::double_ > LeftHeartElastanceModifier_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const LeftHeartElastanceModifier_type&
LeftHeartElastanceModifier () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
LeftHeartElastanceModifier_type&
LeftHeartElastanceModifier ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
LeftHeartElastanceModifier (const LeftHeartElastanceModifier_type& x);
//@}
/**
* @name LeftHeartElastance_mmHg_Per_mL
*
* @brief Accessor and modifier functions for the %LeftHeartElastance_mmHg_Per_mL
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ LeftHeartElastance_mmHg_Per_mL_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< LeftHeartElastance_mmHg_Per_mL_type, char, ::xsd::cxx::tree::schema_type::double_ > LeftHeartElastance_mmHg_Per_mL_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const LeftHeartElastance_mmHg_Per_mL_type&
LeftHeartElastance_mmHg_Per_mL () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
LeftHeartElastance_mmHg_Per_mL_type&
LeftHeartElastance_mmHg_Per_mL ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
LeftHeartElastance_mmHg_Per_mL (const LeftHeartElastance_mmHg_Per_mL_type& x);
//@}
/**
* @name LeftHeartElastanceMax_mmHg_Per_mL
*
* @brief Accessor and modifier functions for the %LeftHeartElastanceMax_mmHg_Per_mL
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ LeftHeartElastanceMax_mmHg_Per_mL_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< LeftHeartElastanceMax_mmHg_Per_mL_type, char, ::xsd::cxx::tree::schema_type::double_ > LeftHeartElastanceMax_mmHg_Per_mL_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const LeftHeartElastanceMax_mmHg_Per_mL_type&
LeftHeartElastanceMax_mmHg_Per_mL () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
LeftHeartElastanceMax_mmHg_Per_mL_type&
LeftHeartElastanceMax_mmHg_Per_mL ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
LeftHeartElastanceMax_mmHg_Per_mL (const LeftHeartElastanceMax_mmHg_Per_mL_type& x);
//@}
/**
* @name LeftHeartElastanceMin_mmHg_Per_mL
*
* @brief Accessor and modifier functions for the %LeftHeartElastanceMin_mmHg_Per_mL
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ LeftHeartElastanceMin_mmHg_Per_mL_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< LeftHeartElastanceMin_mmHg_Per_mL_type, char, ::xsd::cxx::tree::schema_type::double_ > LeftHeartElastanceMin_mmHg_Per_mL_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const LeftHeartElastanceMin_mmHg_Per_mL_type&
LeftHeartElastanceMin_mmHg_Per_mL () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
LeftHeartElastanceMin_mmHg_Per_mL_type&
LeftHeartElastanceMin_mmHg_Per_mL ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
LeftHeartElastanceMin_mmHg_Per_mL (const LeftHeartElastanceMin_mmHg_Per_mL_type& x);
//@}
/**
* @name RightHeartElastance_mmHg_Per_mL
*
* @brief Accessor and modifier functions for the %RightHeartElastance_mmHg_Per_mL
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ RightHeartElastance_mmHg_Per_mL_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< RightHeartElastance_mmHg_Per_mL_type, char, ::xsd::cxx::tree::schema_type::double_ > RightHeartElastance_mmHg_Per_mL_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const RightHeartElastance_mmHg_Per_mL_type&
RightHeartElastance_mmHg_Per_mL () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
RightHeartElastance_mmHg_Per_mL_type&
RightHeartElastance_mmHg_Per_mL ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
RightHeartElastance_mmHg_Per_mL (const RightHeartElastance_mmHg_Per_mL_type& x);
//@}
/**
* @name RightHeartElastanceMax_mmHg_Per_mL
*
* @brief Accessor and modifier functions for the %RightHeartElastanceMax_mmHg_Per_mL
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ RightHeartElastanceMax_mmHg_Per_mL_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< RightHeartElastanceMax_mmHg_Per_mL_type, char, ::xsd::cxx::tree::schema_type::double_ > RightHeartElastanceMax_mmHg_Per_mL_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const RightHeartElastanceMax_mmHg_Per_mL_type&
RightHeartElastanceMax_mmHg_Per_mL () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
RightHeartElastanceMax_mmHg_Per_mL_type&
RightHeartElastanceMax_mmHg_Per_mL ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
RightHeartElastanceMax_mmHg_Per_mL (const RightHeartElastanceMax_mmHg_Per_mL_type& x);
//@}
/**
* @name RightHeartElastanceMin_mmHg_Per_mL
*
* @brief Accessor and modifier functions for the %RightHeartElastanceMin_mmHg_Per_mL
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ RightHeartElastanceMin_mmHg_Per_mL_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< RightHeartElastanceMin_mmHg_Per_mL_type, char, ::xsd::cxx::tree::schema_type::double_ > RightHeartElastanceMin_mmHg_Per_mL_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const RightHeartElastanceMin_mmHg_Per_mL_type&
RightHeartElastanceMin_mmHg_Per_mL () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
RightHeartElastanceMin_mmHg_Per_mL_type&
RightHeartElastanceMin_mmHg_Per_mL ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
RightHeartElastanceMin_mmHg_Per_mL (const RightHeartElastanceMin_mmHg_Per_mL_type& x);
//@}
/**
* @name CompressionTime_s
*
* @brief Accessor and modifier functions for the %CompressionTime_s
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ CompressionTime_s_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CompressionTime_s_type, char, ::xsd::cxx::tree::schema_type::double_ > CompressionTime_s_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CompressionTime_s_type&
CompressionTime_s () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CompressionTime_s_type&
CompressionTime_s ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CompressionTime_s (const CompressionTime_s_type& x);
//@}
/**
* @name CompressionRatio
*
* @brief Accessor and modifier functions for the %CompressionRatio
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ CompressionRatio_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CompressionRatio_type, char, ::xsd::cxx::tree::schema_type::double_ > CompressionRatio_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CompressionRatio_type&
CompressionRatio () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CompressionRatio_type&
CompressionRatio ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CompressionRatio (const CompressionRatio_type& x);
//@}
/**
* @name CompressionPeriod_s
*
* @brief Accessor and modifier functions for the %CompressionPeriod_s
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ CompressionPeriod_s_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CompressionPeriod_s_type, char, ::xsd::cxx::tree::schema_type::double_ > CompressionPeriod_s_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CompressionPeriod_s_type&
CompressionPeriod_s () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CompressionPeriod_s_type&
CompressionPeriod_s ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CompressionPeriod_s (const CompressionPeriod_s_type& x);
//@}
/**
* @name CurrentCardiacCycleTime_s
*
* @brief Accessor and modifier functions for the %CurrentCardiacCycleTime_s
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ CurrentCardiacCycleTime_s_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CurrentCardiacCycleTime_s_type, char, ::xsd::cxx::tree::schema_type::double_ > CurrentCardiacCycleTime_s_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CurrentCardiacCycleTime_s_type&
CurrentCardiacCycleTime_s () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CurrentCardiacCycleTime_s_type&
CurrentCardiacCycleTime_s ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CurrentCardiacCycleTime_s (const CurrentCardiacCycleTime_s_type& x);
//@}
/**
* @name CardiacCycleDiastolicVolume_mL
*
* @brief Accessor and modifier functions for the %CardiacCycleDiastolicVolume_mL
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ CardiacCycleDiastolicVolume_mL_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CardiacCycleDiastolicVolume_mL_type, char, ::xsd::cxx::tree::schema_type::double_ > CardiacCycleDiastolicVolume_mL_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CardiacCycleDiastolicVolume_mL_type&
CardiacCycleDiastolicVolume_mL () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CardiacCycleDiastolicVolume_mL_type&
CardiacCycleDiastolicVolume_mL ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CardiacCycleDiastolicVolume_mL (const CardiacCycleDiastolicVolume_mL_type& x);
//@}
/**
* @name CardiacCycleAortaPressureLow_mmHg
*
* @brief Accessor and modifier functions for the %CardiacCycleAortaPressureLow_mmHg
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ CardiacCycleAortaPressureLow_mmHg_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CardiacCycleAortaPressureLow_mmHg_type, char, ::xsd::cxx::tree::schema_type::double_ > CardiacCycleAortaPressureLow_mmHg_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CardiacCycleAortaPressureLow_mmHg_type&
CardiacCycleAortaPressureLow_mmHg () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CardiacCycleAortaPressureLow_mmHg_type&
CardiacCycleAortaPressureLow_mmHg ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CardiacCycleAortaPressureLow_mmHg (const CardiacCycleAortaPressureLow_mmHg_type& x);
//@}
/**
* @name CardiacCycleAortaPressureHigh_mmHg
*
* @brief Accessor and modifier functions for the %CardiacCycleAortaPressureHigh_mmHg
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ CardiacCycleAortaPressureHigh_mmHg_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CardiacCycleAortaPressureHigh_mmHg_type, char, ::xsd::cxx::tree::schema_type::double_ > CardiacCycleAortaPressureHigh_mmHg_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CardiacCycleAortaPressureHigh_mmHg_type&
CardiacCycleAortaPressureHigh_mmHg () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CardiacCycleAortaPressureHigh_mmHg_type&
CardiacCycleAortaPressureHigh_mmHg ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CardiacCycleAortaPressureHigh_mmHg (const CardiacCycleAortaPressureHigh_mmHg_type& x);
//@}
/**
* @name CardiacCyclePulmonaryArteryPressureLow_mmHg
*
* @brief Accessor and modifier functions for the %CardiacCyclePulmonaryArteryPressureLow_mmHg
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ CardiacCyclePulmonaryArteryPressureLow_mmHg_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CardiacCyclePulmonaryArteryPressureLow_mmHg_type, char, ::xsd::cxx::tree::schema_type::double_ > CardiacCyclePulmonaryArteryPressureLow_mmHg_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CardiacCyclePulmonaryArteryPressureLow_mmHg_type&
CardiacCyclePulmonaryArteryPressureLow_mmHg () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CardiacCyclePulmonaryArteryPressureLow_mmHg_type&
CardiacCyclePulmonaryArteryPressureLow_mmHg ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CardiacCyclePulmonaryArteryPressureLow_mmHg (const CardiacCyclePulmonaryArteryPressureLow_mmHg_type& x);
//@}
/**
* @name CardiacCyclePulmonaryArteryPressureHigh_mmHg
*
* @brief Accessor and modifier functions for the %CardiacCyclePulmonaryArteryPressureHigh_mmHg
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ CardiacCyclePulmonaryArteryPressureHigh_mmHg_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CardiacCyclePulmonaryArteryPressureHigh_mmHg_type, char, ::xsd::cxx::tree::schema_type::double_ > CardiacCyclePulmonaryArteryPressureHigh_mmHg_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CardiacCyclePulmonaryArteryPressureHigh_mmHg_type&
CardiacCyclePulmonaryArteryPressureHigh_mmHg () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CardiacCyclePulmonaryArteryPressureHigh_mmHg_type&
CardiacCyclePulmonaryArteryPressureHigh_mmHg ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CardiacCyclePulmonaryArteryPressureHigh_mmHg (const CardiacCyclePulmonaryArteryPressureHigh_mmHg_type& x);
//@}
/**
* @name LastCardiacCycleMeanArterialCO2PartialPressure_mmHg
*
* @brief Accessor and modifier functions for the %LastCardiacCycleMeanArterialCO2PartialPressure_mmHg
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ LastCardiacCycleMeanArterialCO2PartialPressure_mmHg_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< LastCardiacCycleMeanArterialCO2PartialPressure_mmHg_type, char, ::xsd::cxx::tree::schema_type::double_ > LastCardiacCycleMeanArterialCO2PartialPressure_mmHg_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const LastCardiacCycleMeanArterialCO2PartialPressure_mmHg_type&
LastCardiacCycleMeanArterialCO2PartialPressure_mmHg () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
LastCardiacCycleMeanArterialCO2PartialPressure_mmHg_type&
LastCardiacCycleMeanArterialCO2PartialPressure_mmHg ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
LastCardiacCycleMeanArterialCO2PartialPressure_mmHg (const LastCardiacCycleMeanArterialCO2PartialPressure_mmHg_type& x);
//@}
/**
* @name CardiacCycleStrokeVolume_mL
*
* @brief Accessor and modifier functions for the %CardiacCycleStrokeVolume_mL
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ CardiacCycleStrokeVolume_mL_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CardiacCycleStrokeVolume_mL_type, char, ::xsd::cxx::tree::schema_type::double_ > CardiacCycleStrokeVolume_mL_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CardiacCycleStrokeVolume_mL_type&
CardiacCycleStrokeVolume_mL () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CardiacCycleStrokeVolume_mL_type&
CardiacCycleStrokeVolume_mL ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CardiacCycleStrokeVolume_mL (const CardiacCycleStrokeVolume_mL_type& x);
//@}
/**
* @name CardiacCycleArterialPressure_mmHg
*
* @brief Accessor and modifier functions for the %CardiacCycleArterialPressure_mmHg
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::RunningAverageData CardiacCycleArterialPressure_mmHg_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CardiacCycleArterialPressure_mmHg_type, char > CardiacCycleArterialPressure_mmHg_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CardiacCycleArterialPressure_mmHg_type&
CardiacCycleArterialPressure_mmHg () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CardiacCycleArterialPressure_mmHg_type&
CardiacCycleArterialPressure_mmHg ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CardiacCycleArterialPressure_mmHg (const CardiacCycleArterialPressure_mmHg_type& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
CardiacCycleArterialPressure_mmHg (::std::unique_ptr< CardiacCycleArterialPressure_mmHg_type > p);
//@}
/**
* @name CardiacCycleArterialCO2PartialPressure_mmHg
*
* @brief Accessor and modifier functions for the %CardiacCycleArterialCO2PartialPressure_mmHg
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::RunningAverageData CardiacCycleArterialCO2PartialPressure_mmHg_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CardiacCycleArterialCO2PartialPressure_mmHg_type, char > CardiacCycleArterialCO2PartialPressure_mmHg_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CardiacCycleArterialCO2PartialPressure_mmHg_type&
CardiacCycleArterialCO2PartialPressure_mmHg () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CardiacCycleArterialCO2PartialPressure_mmHg_type&
CardiacCycleArterialCO2PartialPressure_mmHg ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CardiacCycleArterialCO2PartialPressure_mmHg (const CardiacCycleArterialCO2PartialPressure_mmHg_type& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
CardiacCycleArterialCO2PartialPressure_mmHg (::std::unique_ptr< CardiacCycleArterialCO2PartialPressure_mmHg_type > p);
//@}
/**
* @name CardiacCyclePulmonaryCapillariesWedgePressure_mmHg
*
* @brief Accessor and modifier functions for the %CardiacCyclePulmonaryCapillariesWedgePressure_mmHg
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::RunningAverageData CardiacCyclePulmonaryCapillariesWedgePressure_mmHg_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CardiacCyclePulmonaryCapillariesWedgePressure_mmHg_type, char > CardiacCyclePulmonaryCapillariesWedgePressure_mmHg_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CardiacCyclePulmonaryCapillariesWedgePressure_mmHg_type&
CardiacCyclePulmonaryCapillariesWedgePressure_mmHg () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CardiacCyclePulmonaryCapillariesWedgePressure_mmHg_type&
CardiacCyclePulmonaryCapillariesWedgePressure_mmHg ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CardiacCyclePulmonaryCapillariesWedgePressure_mmHg (const CardiacCyclePulmonaryCapillariesWedgePressure_mmHg_type& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
CardiacCyclePulmonaryCapillariesWedgePressure_mmHg (::std::unique_ptr< CardiacCyclePulmonaryCapillariesWedgePressure_mmHg_type > p);
//@}
/**
* @name CardiacCyclePulmonaryCapillariesFlow_mL_Per_s
*
* @brief Accessor and modifier functions for the %CardiacCyclePulmonaryCapillariesFlow_mL_Per_s
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::RunningAverageData CardiacCyclePulmonaryCapillariesFlow_mL_Per_s_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CardiacCyclePulmonaryCapillariesFlow_mL_Per_s_type, char > CardiacCyclePulmonaryCapillariesFlow_mL_Per_s_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CardiacCyclePulmonaryCapillariesFlow_mL_Per_s_type&
CardiacCyclePulmonaryCapillariesFlow_mL_Per_s () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CardiacCyclePulmonaryCapillariesFlow_mL_Per_s_type&
CardiacCyclePulmonaryCapillariesFlow_mL_Per_s ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CardiacCyclePulmonaryCapillariesFlow_mL_Per_s (const CardiacCyclePulmonaryCapillariesFlow_mL_Per_s_type& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
CardiacCyclePulmonaryCapillariesFlow_mL_Per_s (::std::unique_ptr< CardiacCyclePulmonaryCapillariesFlow_mL_Per_s_type > p);
//@}
/**
* @name CardiacCyclePulmonaryShuntFlow_mL_Per_s
*
* @brief Accessor and modifier functions for the %CardiacCyclePulmonaryShuntFlow_mL_Per_s
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::RunningAverageData CardiacCyclePulmonaryShuntFlow_mL_Per_s_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CardiacCyclePulmonaryShuntFlow_mL_Per_s_type, char > CardiacCyclePulmonaryShuntFlow_mL_Per_s_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CardiacCyclePulmonaryShuntFlow_mL_Per_s_type&
CardiacCyclePulmonaryShuntFlow_mL_Per_s () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CardiacCyclePulmonaryShuntFlow_mL_Per_s_type&
CardiacCyclePulmonaryShuntFlow_mL_Per_s ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CardiacCyclePulmonaryShuntFlow_mL_Per_s (const CardiacCyclePulmonaryShuntFlow_mL_Per_s_type& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
CardiacCyclePulmonaryShuntFlow_mL_Per_s (::std::unique_ptr< CardiacCyclePulmonaryShuntFlow_mL_Per_s_type > p);
//@}
/**
* @name CardiacCyclePulmonaryArteryPressure_mmHg
*
* @brief Accessor and modifier functions for the %CardiacCyclePulmonaryArteryPressure_mmHg
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::RunningAverageData CardiacCyclePulmonaryArteryPressure_mmHg_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CardiacCyclePulmonaryArteryPressure_mmHg_type, char > CardiacCyclePulmonaryArteryPressure_mmHg_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CardiacCyclePulmonaryArteryPressure_mmHg_type&
CardiacCyclePulmonaryArteryPressure_mmHg () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CardiacCyclePulmonaryArteryPressure_mmHg_type&
CardiacCyclePulmonaryArteryPressure_mmHg ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CardiacCyclePulmonaryArteryPressure_mmHg (const CardiacCyclePulmonaryArteryPressure_mmHg_type& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
CardiacCyclePulmonaryArteryPressure_mmHg (::std::unique_ptr< CardiacCyclePulmonaryArteryPressure_mmHg_type > p);
//@}
/**
* @name CardiacCycleCentralVenousPressure_mmHg
*
* @brief Accessor and modifier functions for the %CardiacCycleCentralVenousPressure_mmHg
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::RunningAverageData CardiacCycleCentralVenousPressure_mmHg_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CardiacCycleCentralVenousPressure_mmHg_type, char > CardiacCycleCentralVenousPressure_mmHg_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CardiacCycleCentralVenousPressure_mmHg_type&
CardiacCycleCentralVenousPressure_mmHg () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CardiacCycleCentralVenousPressure_mmHg_type&
CardiacCycleCentralVenousPressure_mmHg ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CardiacCycleCentralVenousPressure_mmHg (const CardiacCycleCentralVenousPressure_mmHg_type& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
CardiacCycleCentralVenousPressure_mmHg (::std::unique_ptr< CardiacCycleCentralVenousPressure_mmHg_type > p);
//@}
/**
* @name CardiacCycleSkinFlow_mL_Per_s
*
* @brief Accessor and modifier functions for the %CardiacCycleSkinFlow_mL_Per_s
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::RunningAverageData CardiacCycleSkinFlow_mL_Per_s_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CardiacCycleSkinFlow_mL_Per_s_type, char > CardiacCycleSkinFlow_mL_Per_s_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CardiacCycleSkinFlow_mL_Per_s_type&
CardiacCycleSkinFlow_mL_Per_s () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CardiacCycleSkinFlow_mL_Per_s_type&
CardiacCycleSkinFlow_mL_Per_s ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CardiacCycleSkinFlow_mL_Per_s (const CardiacCycleSkinFlow_mL_Per_s_type& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
CardiacCycleSkinFlow_mL_Per_s (::std::unique_ptr< CardiacCycleSkinFlow_mL_Per_s_type > p);
//@}
/**
* @name Constructors
*/
//@{
/**
* @brief Default constructor.
*
* Note that this constructor leaves required elements and
* attributes uninitialized.
*/
BioGearsCardiovascularSystemData ();
/**
* @brief Create an instance from the ultimate base and
* initializers for required elements and attributes.
*/
BioGearsCardiovascularSystemData (const StartSystole_type&,
const HeartFlowDetected_type&,
const EnterCardiacArrest_type&,
const CardiacCyclePeriod_s_type&,
const CurrentCardiacCycleDuration_s_type&,
const LeftHeartElastanceModifier_type&,
const LeftHeartElastance_mmHg_Per_mL_type&,
const LeftHeartElastanceMax_mmHg_Per_mL_type&,
const LeftHeartElastanceMin_mmHg_Per_mL_type&,
const RightHeartElastance_mmHg_Per_mL_type&,
const RightHeartElastanceMax_mmHg_Per_mL_type&,
const RightHeartElastanceMin_mmHg_Per_mL_type&,
const CompressionTime_s_type&,
const CompressionRatio_type&,
const CompressionPeriod_s_type&,
const CurrentCardiacCycleTime_s_type&,
const CardiacCycleDiastolicVolume_mL_type&,
const CardiacCycleAortaPressureLow_mmHg_type&,
const CardiacCycleAortaPressureHigh_mmHg_type&,
const CardiacCyclePulmonaryArteryPressureLow_mmHg_type&,
const CardiacCyclePulmonaryArteryPressureHigh_mmHg_type&,
const LastCardiacCycleMeanArterialCO2PartialPressure_mmHg_type&,
const CardiacCycleStrokeVolume_mL_type&,
const CardiacCycleArterialPressure_mmHg_type&,
const CardiacCycleArterialCO2PartialPressure_mmHg_type&,
const CardiacCyclePulmonaryCapillariesWedgePressure_mmHg_type&,
const CardiacCyclePulmonaryCapillariesFlow_mL_Per_s_type&,
const CardiacCyclePulmonaryShuntFlow_mL_Per_s_type&,
const CardiacCyclePulmonaryArteryPressure_mmHg_type&,
const CardiacCycleCentralVenousPressure_mmHg_type&,
const CardiacCycleSkinFlow_mL_Per_s_type&);
/**
* @brief Create an instance from the ultimate base and
* initializers for required elements and attributes
* (::std::unique_ptr version).
*
* This constructor will try to use the passed values directly
* instead of making copies.
*/
BioGearsCardiovascularSystemData (const StartSystole_type&,
const HeartFlowDetected_type&,
const EnterCardiacArrest_type&,
const CardiacCyclePeriod_s_type&,
const CurrentCardiacCycleDuration_s_type&,
const LeftHeartElastanceModifier_type&,
const LeftHeartElastance_mmHg_Per_mL_type&,
const LeftHeartElastanceMax_mmHg_Per_mL_type&,
const LeftHeartElastanceMin_mmHg_Per_mL_type&,
const RightHeartElastance_mmHg_Per_mL_type&,
const RightHeartElastanceMax_mmHg_Per_mL_type&,
const RightHeartElastanceMin_mmHg_Per_mL_type&,
const CompressionTime_s_type&,
const CompressionRatio_type&,
const CompressionPeriod_s_type&,
const CurrentCardiacCycleTime_s_type&,
const CardiacCycleDiastolicVolume_mL_type&,
const CardiacCycleAortaPressureLow_mmHg_type&,
const CardiacCycleAortaPressureHigh_mmHg_type&,
const CardiacCyclePulmonaryArteryPressureLow_mmHg_type&,
const CardiacCyclePulmonaryArteryPressureHigh_mmHg_type&,
const LastCardiacCycleMeanArterialCO2PartialPressure_mmHg_type&,
const CardiacCycleStrokeVolume_mL_type&,
::std::unique_ptr< CardiacCycleArterialPressure_mmHg_type >,
::std::unique_ptr< CardiacCycleArterialCO2PartialPressure_mmHg_type >,
::std::unique_ptr< CardiacCyclePulmonaryCapillariesWedgePressure_mmHg_type >,
::std::unique_ptr< CardiacCyclePulmonaryCapillariesFlow_mL_Per_s_type >,
::std::unique_ptr< CardiacCyclePulmonaryShuntFlow_mL_Per_s_type >,
::std::unique_ptr< CardiacCyclePulmonaryArteryPressure_mmHg_type >,
::std::unique_ptr< CardiacCycleCentralVenousPressure_mmHg_type >,
::std::unique_ptr< CardiacCycleSkinFlow_mL_Per_s_type >);
/**
* @brief Create an instance from a DOM element.
*
* @param e A DOM element to extract the data from.
* @param f Flags to create the new instance with.
* @param c A pointer to the object that will contain the new
* instance.
*/
BioGearsCardiovascularSystemData (const ::xercesc::DOMElement& e,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
/**
* @brief Copy constructor.
*
* @param x An instance to make a copy of.
* @param f Flags to create the copy with.
* @param c A pointer to the object that will contain the copy.
*
* For polymorphic object models use the @c _clone function instead.
*/
BioGearsCardiovascularSystemData (const BioGearsCardiovascularSystemData& x,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
/**
* @brief Copy the instance polymorphically.
*
* @param f Flags to create the copy with.
* @param c A pointer to the object that will contain the copy.
* @return A pointer to the dynamically allocated copy.
*
* This function ensures that the dynamic type of the instance is
* used for copying and should be used for polymorphic object
* models instead of the copy constructor.
*/
virtual BioGearsCardiovascularSystemData*
_clone (::xml_schema::flags f = 0,
::xml_schema::container* c = 0) const;
/**
* @brief Copy assignment operator.
*
* @param x An instance to make a copy of.
* @return A reference to itself.
*
* For polymorphic object models use the @c _clone function instead.
*/
BioGearsCardiovascularSystemData&
operator= (const BioGearsCardiovascularSystemData& x);
//@}
/**
* @brief Destructor.
*/
virtual
~BioGearsCardiovascularSystemData ();
// Implementation.
//
//@cond
protected:
void
parse (::xsd::cxx::xml::dom::parser< char >&,
::xml_schema::flags);
protected:
::xsd::cxx::tree::one< StartSystole_type > StartSystole_;
::xsd::cxx::tree::one< HeartFlowDetected_type > HeartFlowDetected_;
::xsd::cxx::tree::one< EnterCardiacArrest_type > EnterCardiacArrest_;
::xsd::cxx::tree::one< CardiacCyclePeriod_s_type > CardiacCyclePeriod_s_;
::xsd::cxx::tree::one< CurrentCardiacCycleDuration_s_type > CurrentCardiacCycleDuration_s_;
::xsd::cxx::tree::one< LeftHeartElastanceModifier_type > LeftHeartElastanceModifier_;
::xsd::cxx::tree::one< LeftHeartElastance_mmHg_Per_mL_type > LeftHeartElastance_mmHg_Per_mL_;
::xsd::cxx::tree::one< LeftHeartElastanceMax_mmHg_Per_mL_type > LeftHeartElastanceMax_mmHg_Per_mL_;
::xsd::cxx::tree::one< LeftHeartElastanceMin_mmHg_Per_mL_type > LeftHeartElastanceMin_mmHg_Per_mL_;
::xsd::cxx::tree::one< RightHeartElastance_mmHg_Per_mL_type > RightHeartElastance_mmHg_Per_mL_;
::xsd::cxx::tree::one< RightHeartElastanceMax_mmHg_Per_mL_type > RightHeartElastanceMax_mmHg_Per_mL_;
::xsd::cxx::tree::one< RightHeartElastanceMin_mmHg_Per_mL_type > RightHeartElastanceMin_mmHg_Per_mL_;
::xsd::cxx::tree::one< CompressionTime_s_type > CompressionTime_s_;
::xsd::cxx::tree::one< CompressionRatio_type > CompressionRatio_;
::xsd::cxx::tree::one< CompressionPeriod_s_type > CompressionPeriod_s_;
::xsd::cxx::tree::one< CurrentCardiacCycleTime_s_type > CurrentCardiacCycleTime_s_;
::xsd::cxx::tree::one< CardiacCycleDiastolicVolume_mL_type > CardiacCycleDiastolicVolume_mL_;
::xsd::cxx::tree::one< CardiacCycleAortaPressureLow_mmHg_type > CardiacCycleAortaPressureLow_mmHg_;
::xsd::cxx::tree::one< CardiacCycleAortaPressureHigh_mmHg_type > CardiacCycleAortaPressureHigh_mmHg_;
::xsd::cxx::tree::one< CardiacCyclePulmonaryArteryPressureLow_mmHg_type > CardiacCyclePulmonaryArteryPressureLow_mmHg_;
::xsd::cxx::tree::one< CardiacCyclePulmonaryArteryPressureHigh_mmHg_type > CardiacCyclePulmonaryArteryPressureHigh_mmHg_;
::xsd::cxx::tree::one< LastCardiacCycleMeanArterialCO2PartialPressure_mmHg_type > LastCardiacCycleMeanArterialCO2PartialPressure_mmHg_;
::xsd::cxx::tree::one< CardiacCycleStrokeVolume_mL_type > CardiacCycleStrokeVolume_mL_;
::xsd::cxx::tree::one< CardiacCycleArterialPressure_mmHg_type > CardiacCycleArterialPressure_mmHg_;
::xsd::cxx::tree::one< CardiacCycleArterialCO2PartialPressure_mmHg_type > CardiacCycleArterialCO2PartialPressure_mmHg_;
::xsd::cxx::tree::one< CardiacCyclePulmonaryCapillariesWedgePressure_mmHg_type > CardiacCyclePulmonaryCapillariesWedgePressure_mmHg_;
::xsd::cxx::tree::one< CardiacCyclePulmonaryCapillariesFlow_mL_Per_s_type > CardiacCyclePulmonaryCapillariesFlow_mL_Per_s_;
::xsd::cxx::tree::one< CardiacCyclePulmonaryShuntFlow_mL_Per_s_type > CardiacCyclePulmonaryShuntFlow_mL_Per_s_;
::xsd::cxx::tree::one< CardiacCyclePulmonaryArteryPressure_mmHg_type > CardiacCyclePulmonaryArteryPressure_mmHg_;
::xsd::cxx::tree::one< CardiacCycleCentralVenousPressure_mmHg_type > CardiacCycleCentralVenousPressure_mmHg_;
::xsd::cxx::tree::one< CardiacCycleSkinFlow_mL_Per_s_type > CardiacCycleSkinFlow_mL_Per_s_;
//@endcond
};
/**
* @brief Class corresponding to the %BioGearsDrugSystemData schema type.
*
* @nosubgrouping
*/
class BIOGEARS_CDM_API BioGearsDrugSystemData: public ::mil::tatrc::physiology::datamodel::DrugSystemData
{
public:
/**
* @name BolusAdministration
*
* @brief Accessor and modifier functions for the %BolusAdministration
* sequence element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::SubstanceBolusStateData BolusAdministration_type;
/**
* @brief Element sequence container type.
*/
typedef ::xsd::cxx::tree::sequence< BolusAdministration_type > BolusAdministration_sequence;
/**
* @brief Element iterator type.
*/
typedef BolusAdministration_sequence::iterator BolusAdministration_iterator;
/**
* @brief Element constant iterator type.
*/
typedef BolusAdministration_sequence::const_iterator BolusAdministration_const_iterator;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< BolusAdministration_type, char > BolusAdministration_traits;
/**
* @brief Return a read-only (constant) reference to the element
* sequence.
*
* @return A constant reference to the sequence container.
*/
const BolusAdministration_sequence&
BolusAdministration () const;
/**
* @brief Return a read-write reference to the element sequence.
*
* @return A reference to the sequence container.
*/
BolusAdministration_sequence&
BolusAdministration ();
/**
* @brief Copy elements from a given sequence.
*
* @param s A sequence to copy elements from.
*
* For each element in @a s this function makes a copy and adds it
* to the sequence. Note that this operation completely changes the
* sequence and all old elements will be lost.
*/
void
BolusAdministration (const BolusAdministration_sequence& s);
//@}
/**
* @name NasalStates
*
* @brief Accessor and modifier functions for the %NasalStates
* sequence element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::NasalStateData NasalStates_type;
/**
* @brief Element sequence container type.
*/
typedef ::xsd::cxx::tree::sequence< NasalStates_type > NasalStates_sequence;
/**
* @brief Element iterator type.
*/
typedef NasalStates_sequence::iterator NasalStates_iterator;
/**
* @brief Element constant iterator type.
*/
typedef NasalStates_sequence::const_iterator NasalStates_const_iterator;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< NasalStates_type, char > NasalStates_traits;
/**
* @brief Return a read-only (constant) reference to the element
* sequence.
*
* @return A constant reference to the sequence container.
*/
const NasalStates_sequence&
NasalStates () const;
/**
* @brief Return a read-write reference to the element sequence.
*
* @return A reference to the sequence container.
*/
NasalStates_sequence&
NasalStates ();
/**
* @brief Copy elements from a given sequence.
*
* @param s A sequence to copy elements from.
*
* For each element in @a s this function makes a copy and adds it
* to the sequence. Note that this operation completely changes the
* sequence and all old elements will be lost.
*/
void
NasalStates (const NasalStates_sequence& s);
//@}
/**
* @name TransmucosalStates
*
* @brief Accessor and modifier functions for the %TransmucosalStates
* sequence element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::TransmucosalStateData TransmucosalStates_type;
/**
* @brief Element sequence container type.
*/
typedef ::xsd::cxx::tree::sequence< TransmucosalStates_type > TransmucosalStates_sequence;
/**
* @brief Element iterator type.
*/
typedef TransmucosalStates_sequence::iterator TransmucosalStates_iterator;
/**
* @brief Element constant iterator type.
*/
typedef TransmucosalStates_sequence::const_iterator TransmucosalStates_const_iterator;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< TransmucosalStates_type, char > TransmucosalStates_traits;
/**
* @brief Return a read-only (constant) reference to the element
* sequence.
*
* @return A constant reference to the sequence container.
*/
const TransmucosalStates_sequence&
TransmucosalStates () const;
/**
* @brief Return a read-write reference to the element sequence.
*
* @return A reference to the sequence container.
*/
TransmucosalStates_sequence&
TransmucosalStates ();
/**
* @brief Copy elements from a given sequence.
*
* @param s A sequence to copy elements from.
*
* For each element in @a s this function makes a copy and adds it
* to the sequence. Note that this operation completely changes the
* sequence and all old elements will be lost.
*/
void
TransmucosalStates (const TransmucosalStates_sequence& s);
//@}
/**
* @name SarinRbcAcetylcholinesteraseComplex_nM
*
* @brief Accessor and modifier functions for the %SarinRbcAcetylcholinesteraseComplex_nM
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ SarinRbcAcetylcholinesteraseComplex_nM_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< SarinRbcAcetylcholinesteraseComplex_nM_type, char, ::xsd::cxx::tree::schema_type::double_ > SarinRbcAcetylcholinesteraseComplex_nM_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const SarinRbcAcetylcholinesteraseComplex_nM_type&
SarinRbcAcetylcholinesteraseComplex_nM () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
SarinRbcAcetylcholinesteraseComplex_nM_type&
SarinRbcAcetylcholinesteraseComplex_nM ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
SarinRbcAcetylcholinesteraseComplex_nM (const SarinRbcAcetylcholinesteraseComplex_nM_type& x);
//@}
/**
* @name AgedRbcAcetylcholinesterase_nM
*
* @brief Accessor and modifier functions for the %AgedRbcAcetylcholinesterase_nM
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ AgedRbcAcetylcholinesterase_nM_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< AgedRbcAcetylcholinesterase_nM_type, char, ::xsd::cxx::tree::schema_type::double_ > AgedRbcAcetylcholinesterase_nM_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const AgedRbcAcetylcholinesterase_nM_type&
AgedRbcAcetylcholinesterase_nM () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
AgedRbcAcetylcholinesterase_nM_type&
AgedRbcAcetylcholinesterase_nM ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
AgedRbcAcetylcholinesterase_nM (const AgedRbcAcetylcholinesterase_nM_type& x);
//@}
/**
* @name Constructors
*/
//@{
/**
* @brief Default constructor.
*
* Note that this constructor leaves required elements and
* attributes uninitialized.
*/
BioGearsDrugSystemData ();
/**
* @brief Create an instance from the ultimate base and
* initializers for required elements and attributes.
*/
BioGearsDrugSystemData (const SarinRbcAcetylcholinesteraseComplex_nM_type&,
const AgedRbcAcetylcholinesterase_nM_type&);
/**
* @brief Create an instance from a DOM element.
*
* @param e A DOM element to extract the data from.
* @param f Flags to create the new instance with.
* @param c A pointer to the object that will contain the new
* instance.
*/
BioGearsDrugSystemData (const ::xercesc::DOMElement& e,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
/**
* @brief Copy constructor.
*
* @param x An instance to make a copy of.
* @param f Flags to create the copy with.
* @param c A pointer to the object that will contain the copy.
*
* For polymorphic object models use the @c _clone function instead.
*/
BioGearsDrugSystemData (const BioGearsDrugSystemData& x,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
/**
* @brief Copy the instance polymorphically.
*
* @param f Flags to create the copy with.
* @param c A pointer to the object that will contain the copy.
* @return A pointer to the dynamically allocated copy.
*
* This function ensures that the dynamic type of the instance is
* used for copying and should be used for polymorphic object
* models instead of the copy constructor.
*/
virtual BioGearsDrugSystemData*
_clone (::xml_schema::flags f = 0,
::xml_schema::container* c = 0) const;
/**
* @brief Copy assignment operator.
*
* @param x An instance to make a copy of.
* @return A reference to itself.
*
* For polymorphic object models use the @c _clone function instead.
*/
BioGearsDrugSystemData&
operator= (const BioGearsDrugSystemData& x);
//@}
/**
* @brief Destructor.
*/
virtual
~BioGearsDrugSystemData ();
// Implementation.
//
//@cond
protected:
void
parse (::xsd::cxx::xml::dom::parser< char >&,
::xml_schema::flags);
protected:
BolusAdministration_sequence BolusAdministration_;
NasalStates_sequence NasalStates_;
TransmucosalStates_sequence TransmucosalStates_;
::xsd::cxx::tree::one< SarinRbcAcetylcholinesteraseComplex_nM_type > SarinRbcAcetylcholinesteraseComplex_nM_;
::xsd::cxx::tree::one< AgedRbcAcetylcholinesterase_nM_type > AgedRbcAcetylcholinesterase_nM_;
//@endcond
};
/**
* @brief Class corresponding to the %BioGearsEndocrineSystemData schema type.
*
* @nosubgrouping
*/
class BIOGEARS_CDM_API BioGearsEndocrineSystemData: public ::mil::tatrc::physiology::datamodel::EndocrineSystemData
{
public:
/**
* @name Constructors
*/
//@{
/**
* @brief Create an instance from the ultimate base and
* initializers for required elements and attributes.
*/
BioGearsEndocrineSystemData ();
/**
* @brief Create an instance from a DOM element.
*
* @param e A DOM element to extract the data from.
* @param f Flags to create the new instance with.
* @param c A pointer to the object that will contain the new
* instance.
*/
BioGearsEndocrineSystemData (const ::xercesc::DOMElement& e,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
/**
* @brief Copy constructor.
*
* @param x An instance to make a copy of.
* @param f Flags to create the copy with.
* @param c A pointer to the object that will contain the copy.
*
* For polymorphic object models use the @c _clone function instead.
*/
BioGearsEndocrineSystemData (const BioGearsEndocrineSystemData& x,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
/**
* @brief Copy the instance polymorphically.
*
* @param f Flags to create the copy with.
* @param c A pointer to the object that will contain the copy.
* @return A pointer to the dynamically allocated copy.
*
* This function ensures that the dynamic type of the instance is
* used for copying and should be used for polymorphic object
* models instead of the copy constructor.
*/
virtual BioGearsEndocrineSystemData*
_clone (::xml_schema::flags f = 0,
::xml_schema::container* c = 0) const;
//@}
/**
* @brief Destructor.
*/
virtual
~BioGearsEndocrineSystemData ();
};
/**
* @brief Class corresponding to the %BioGearsEnergySystemData schema type.
*
* @nosubgrouping
*/
class BIOGEARS_CDM_API BioGearsEnergySystemData: public ::mil::tatrc::physiology::datamodel::EnergySystemData
{
public:
/**
* @name BloodpH
*
* @brief Accessor and modifier functions for the %BloodpH
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::RunningAverageData BloodpH_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< BloodpH_type, char > BloodpH_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const BloodpH_type&
BloodpH () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
BloodpH_type&
BloodpH ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
BloodpH (const BloodpH_type& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
BloodpH (::std::unique_ptr< BloodpH_type > p);
//@}
/**
* @name BicarbonateMolarity_mmol_Per_L
*
* @brief Accessor and modifier functions for the %BicarbonateMolarity_mmol_Per_L
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::RunningAverageData BicarbonateMolarity_mmol_Per_L_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< BicarbonateMolarity_mmol_Per_L_type, char > BicarbonateMolarity_mmol_Per_L_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const BicarbonateMolarity_mmol_Per_L_type&
BicarbonateMolarity_mmol_Per_L () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
BicarbonateMolarity_mmol_Per_L_type&
BicarbonateMolarity_mmol_Per_L ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
BicarbonateMolarity_mmol_Per_L (const BicarbonateMolarity_mmol_Per_L_type& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
BicarbonateMolarity_mmol_Per_L (::std::unique_ptr< BicarbonateMolarity_mmol_Per_L_type > p);
//@}
/**
* @name PackOn
*
* @brief Accessor and modifier functions for the %PackOn
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::boolean PackOn_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< PackOn_type, char > PackOn_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const PackOn_type&
PackOn () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
PackOn_type&
PackOn ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
PackOn (const PackOn_type& x);
//@}
/**
* @name PreviousWeightPack_kg
*
* @brief Accessor and modifier functions for the %PreviousWeightPack_kg
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ PreviousWeightPack_kg_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< PreviousWeightPack_kg_type, char, ::xsd::cxx::tree::schema_type::double_ > PreviousWeightPack_kg_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const PreviousWeightPack_kg_type&
PreviousWeightPack_kg () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
PreviousWeightPack_kg_type&
PreviousWeightPack_kg ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
PreviousWeightPack_kg (const PreviousWeightPack_kg_type& x);
//@}
/**
* @name Constructors
*/
//@{
/**
* @brief Default constructor.
*
* Note that this constructor leaves required elements and
* attributes uninitialized.
*/
BioGearsEnergySystemData ();
/**
* @brief Create an instance from the ultimate base and
* initializers for required elements and attributes.
*/
BioGearsEnergySystemData (const BloodpH_type&,
const BicarbonateMolarity_mmol_Per_L_type&,
const PackOn_type&,
const PreviousWeightPack_kg_type&);
/**
* @brief Create an instance from the ultimate base and
* initializers for required elements and attributes
* (::std::unique_ptr version).
*
* This constructor will try to use the passed values directly
* instead of making copies.
*/
BioGearsEnergySystemData (::std::unique_ptr< BloodpH_type >,
::std::unique_ptr< BicarbonateMolarity_mmol_Per_L_type >,
const PackOn_type&,
const PreviousWeightPack_kg_type&);
/**
* @brief Create an instance from a DOM element.
*
* @param e A DOM element to extract the data from.
* @param f Flags to create the new instance with.
* @param c A pointer to the object that will contain the new
* instance.
*/
BioGearsEnergySystemData (const ::xercesc::DOMElement& e,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
/**
* @brief Copy constructor.
*
* @param x An instance to make a copy of.
* @param f Flags to create the copy with.
* @param c A pointer to the object that will contain the copy.
*
* For polymorphic object models use the @c _clone function instead.
*/
BioGearsEnergySystemData (const BioGearsEnergySystemData& x,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
/**
* @brief Copy the instance polymorphically.
*
* @param f Flags to create the copy with.
* @param c A pointer to the object that will contain the copy.
* @return A pointer to the dynamically allocated copy.
*
* This function ensures that the dynamic type of the instance is
* used for copying and should be used for polymorphic object
* models instead of the copy constructor.
*/
virtual BioGearsEnergySystemData*
_clone (::xml_schema::flags f = 0,
::xml_schema::container* c = 0) const;
/**
* @brief Copy assignment operator.
*
* @param x An instance to make a copy of.
* @return A reference to itself.
*
* For polymorphic object models use the @c _clone function instead.
*/
BioGearsEnergySystemData&
operator= (const BioGearsEnergySystemData& x);
//@}
/**
* @brief Destructor.
*/
virtual
~BioGearsEnergySystemData ();
// Implementation.
//
//@cond
protected:
void
parse (::xsd::cxx::xml::dom::parser< char >&,
::xml_schema::flags);
protected:
::xsd::cxx::tree::one< BloodpH_type > BloodpH_;
::xsd::cxx::tree::one< BicarbonateMolarity_mmol_Per_L_type > BicarbonateMolarity_mmol_Per_L_;
::xsd::cxx::tree::one< PackOn_type > PackOn_;
::xsd::cxx::tree::one< PreviousWeightPack_kg_type > PreviousWeightPack_kg_;
//@endcond
};
/**
* @brief Class corresponding to the %BioGearsGastrointestinalSystemData schema type.
*
* @nosubgrouping
*/
class BIOGEARS_CDM_API BioGearsGastrointestinalSystemData: public ::mil::tatrc::physiology::datamodel::GastrointestinalSystemData
{
public:
/**
* @name Constructors
*/
//@{
/**
* @brief Create an instance from the ultimate base and
* initializers for required elements and attributes.
*/
BioGearsGastrointestinalSystemData ();
/**
* @brief Create an instance from a DOM element.
*
* @param e A DOM element to extract the data from.
* @param f Flags to create the new instance with.
* @param c A pointer to the object that will contain the new
* instance.
*/
BioGearsGastrointestinalSystemData (const ::xercesc::DOMElement& e,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
/**
* @brief Copy constructor.
*
* @param x An instance to make a copy of.
* @param f Flags to create the copy with.
* @param c A pointer to the object that will contain the copy.
*
* For polymorphic object models use the @c _clone function instead.
*/
BioGearsGastrointestinalSystemData (const BioGearsGastrointestinalSystemData& x,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
/**
* @brief Copy the instance polymorphically.
*
* @param f Flags to create the copy with.
* @param c A pointer to the object that will contain the copy.
* @return A pointer to the dynamically allocated copy.
*
* This function ensures that the dynamic type of the instance is
* used for copying and should be used for polymorphic object
* models instead of the copy constructor.
*/
virtual BioGearsGastrointestinalSystemData*
_clone (::xml_schema::flags f = 0,
::xml_schema::container* c = 0) const;
//@}
/**
* @brief Destructor.
*/
virtual
~BioGearsGastrointestinalSystemData ();
};
/**
* @brief Class corresponding to the %BioGearsHepaticSystemData schema type.
*
* @nosubgrouping
*/
class BIOGEARS_CDM_API BioGearsHepaticSystemData: public ::mil::tatrc::physiology::datamodel::HepaticSystemData
{
public:
/**
* @name Constructors
*/
//@{
/**
* @brief Create an instance from the ultimate base and
* initializers for required elements and attributes.
*/
BioGearsHepaticSystemData ();
/**
* @brief Create an instance from a DOM element.
*
* @param e A DOM element to extract the data from.
* @param f Flags to create the new instance with.
* @param c A pointer to the object that will contain the new
* instance.
*/
BioGearsHepaticSystemData (const ::xercesc::DOMElement& e,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
/**
* @brief Copy constructor.
*
* @param x An instance to make a copy of.
* @param f Flags to create the copy with.
* @param c A pointer to the object that will contain the copy.
*
* For polymorphic object models use the @c _clone function instead.
*/
BioGearsHepaticSystemData (const BioGearsHepaticSystemData& x,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
/**
* @brief Copy the instance polymorphically.
*
* @param f Flags to create the copy with.
* @param c A pointer to the object that will contain the copy.
* @return A pointer to the dynamically allocated copy.
*
* This function ensures that the dynamic type of the instance is
* used for copying and should be used for polymorphic object
* models instead of the copy constructor.
*/
virtual BioGearsHepaticSystemData*
_clone (::xml_schema::flags f = 0,
::xml_schema::container* c = 0) const;
//@}
/**
* @brief Destructor.
*/
virtual
~BioGearsHepaticSystemData ();
};
/**
* @brief Class corresponding to the %BioGearsNervousSystemData schema type.
*
* @nosubgrouping
*/
class BIOGEARS_CDM_API BioGearsNervousSystemData: public ::mil::tatrc::physiology::datamodel::NervousSystemData
{
public:
/**
* @name AfferentChemoreceptor_Hz
*
* @brief Accessor and modifier functions for the %AfferentChemoreceptor_Hz
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ AfferentChemoreceptor_Hz_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< AfferentChemoreceptor_Hz_type, char, ::xsd::cxx::tree::schema_type::double_ > AfferentChemoreceptor_Hz_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const AfferentChemoreceptor_Hz_type&
AfferentChemoreceptor_Hz () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
AfferentChemoreceptor_Hz_type&
AfferentChemoreceptor_Hz ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
AfferentChemoreceptor_Hz (const AfferentChemoreceptor_Hz_type& x);
//@}
/**
* @name AfferentPulmonaryStrechReceptor_Hz
*
* @brief Accessor and modifier functions for the %AfferentPulmonaryStrechReceptor_Hz
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ AfferentPulmonaryStrechReceptor_Hz_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< AfferentPulmonaryStrechReceptor_Hz_type, char, ::xsd::cxx::tree::schema_type::double_ > AfferentPulmonaryStrechReceptor_Hz_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const AfferentPulmonaryStrechReceptor_Hz_type&
AfferentPulmonaryStrechReceptor_Hz () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
AfferentPulmonaryStrechReceptor_Hz_type&
AfferentPulmonaryStrechReceptor_Hz ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
AfferentPulmonaryStrechReceptor_Hz (const AfferentPulmonaryStrechReceptor_Hz_type& x);
//@}
/**
* @name AorticBaroreceptorStrain
*
* @brief Accessor and modifier functions for the %AorticBaroreceptorStrain
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ AorticBaroreceptorStrain_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< AorticBaroreceptorStrain_type, char, ::xsd::cxx::tree::schema_type::double_ > AorticBaroreceptorStrain_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const AorticBaroreceptorStrain_type&
AorticBaroreceptorStrain () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
AorticBaroreceptorStrain_type&
AorticBaroreceptorStrain ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
AorticBaroreceptorStrain (const AorticBaroreceptorStrain_type& x);
//@}
/**
* @name ArterialOxygenBaseline_mmHg
*
* @brief Accessor and modifier functions for the %ArterialOxygenBaseline_mmHg
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ ArterialOxygenBaseline_mmHg_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< ArterialOxygenBaseline_mmHg_type, char, ::xsd::cxx::tree::schema_type::double_ > ArterialOxygenBaseline_mmHg_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const ArterialOxygenBaseline_mmHg_type&
ArterialOxygenBaseline_mmHg () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
ArterialOxygenBaseline_mmHg_type&
ArterialOxygenBaseline_mmHg ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
ArterialOxygenBaseline_mmHg (const ArterialOxygenBaseline_mmHg_type& x);
//@}
/**
* @name ArterialCarbonDioxideBaseline_mmHg
*
* @brief Accessor and modifier functions for the %ArterialCarbonDioxideBaseline_mmHg
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ ArterialCarbonDioxideBaseline_mmHg_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< ArterialCarbonDioxideBaseline_mmHg_type, char, ::xsd::cxx::tree::schema_type::double_ > ArterialCarbonDioxideBaseline_mmHg_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const ArterialCarbonDioxideBaseline_mmHg_type&
ArterialCarbonDioxideBaseline_mmHg () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
ArterialCarbonDioxideBaseline_mmHg_type&
ArterialCarbonDioxideBaseline_mmHg ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
ArterialCarbonDioxideBaseline_mmHg (const ArterialCarbonDioxideBaseline_mmHg_type& x);
//@}
/**
* @name BaroreceptorOperatingPoint_mmHg
*
* @brief Accessor and modifier functions for the %BaroreceptorOperatingPoint_mmHg
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ BaroreceptorOperatingPoint_mmHg_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< BaroreceptorOperatingPoint_mmHg_type, char, ::xsd::cxx::tree::schema_type::double_ > BaroreceptorOperatingPoint_mmHg_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const BaroreceptorOperatingPoint_mmHg_type&
BaroreceptorOperatingPoint_mmHg () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
BaroreceptorOperatingPoint_mmHg_type&
BaroreceptorOperatingPoint_mmHg ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
BaroreceptorOperatingPoint_mmHg (const BaroreceptorOperatingPoint_mmHg_type& x);
//@}
/**
* @name CardiopulmonaryInputBaseline_mmHg
*
* @brief Accessor and modifier functions for the %CardiopulmonaryInputBaseline_mmHg
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ CardiopulmonaryInputBaseline_mmHg_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CardiopulmonaryInputBaseline_mmHg_type, char, ::xsd::cxx::tree::schema_type::double_ > CardiopulmonaryInputBaseline_mmHg_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CardiopulmonaryInputBaseline_mmHg_type&
CardiopulmonaryInputBaseline_mmHg () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CardiopulmonaryInputBaseline_mmHg_type&
CardiopulmonaryInputBaseline_mmHg ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CardiopulmonaryInputBaseline_mmHg (const CardiopulmonaryInputBaseline_mmHg_type& x);
//@}
/**
* @name CardiopulmonaryInput_mmHg
*
* @brief Accessor and modifier functions for the %CardiopulmonaryInput_mmHg
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ CardiopulmonaryInput_mmHg_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CardiopulmonaryInput_mmHg_type, char, ::xsd::cxx::tree::schema_type::double_ > CardiopulmonaryInput_mmHg_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CardiopulmonaryInput_mmHg_type&
CardiopulmonaryInput_mmHg () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CardiopulmonaryInput_mmHg_type&
CardiopulmonaryInput_mmHg ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CardiopulmonaryInput_mmHg (const CardiopulmonaryInput_mmHg_type& x);
//@}
/**
* @name CarotidBaroreceptorStrain
*
* @brief Accessor and modifier functions for the %CarotidBaroreceptorStrain
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ CarotidBaroreceptorStrain_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CarotidBaroreceptorStrain_type, char, ::xsd::cxx::tree::schema_type::double_ > CarotidBaroreceptorStrain_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CarotidBaroreceptorStrain_type&
CarotidBaroreceptorStrain () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CarotidBaroreceptorStrain_type&
CarotidBaroreceptorStrain ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CarotidBaroreceptorStrain (const CarotidBaroreceptorStrain_type& x);
//@}
/**
* @name CerebralArteriesEffectors_Large
*
* @brief Accessor and modifier functions for the %CerebralArteriesEffectors_Large
* sequence element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ CerebralArteriesEffectors_Large_type;
/**
* @brief Element sequence container type.
*/
typedef ::xsd::cxx::tree::sequence< CerebralArteriesEffectors_Large_type > CerebralArteriesEffectors_Large_sequence;
/**
* @brief Element iterator type.
*/
typedef CerebralArteriesEffectors_Large_sequence::iterator CerebralArteriesEffectors_Large_iterator;
/**
* @brief Element constant iterator type.
*/
typedef CerebralArteriesEffectors_Large_sequence::const_iterator CerebralArteriesEffectors_Large_const_iterator;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CerebralArteriesEffectors_Large_type, char, ::xsd::cxx::tree::schema_type::double_ > CerebralArteriesEffectors_Large_traits;
/**
* @brief Return a read-only (constant) reference to the element
* sequence.
*
* @return A constant reference to the sequence container.
*/
const CerebralArteriesEffectors_Large_sequence&
CerebralArteriesEffectors_Large () const;
/**
* @brief Return a read-write reference to the element sequence.
*
* @return A reference to the sequence container.
*/
CerebralArteriesEffectors_Large_sequence&
CerebralArteriesEffectors_Large ();
/**
* @brief Copy elements from a given sequence.
*
* @param s A sequence to copy elements from.
*
* For each element in @a s this function makes a copy and adds it
* to the sequence. Note that this operation completely changes the
* sequence and all old elements will be lost.
*/
void
CerebralArteriesEffectors_Large (const CerebralArteriesEffectors_Large_sequence& s);
//@}
/**
* @name CerebralArteriesEffectors_Small
*
* @brief Accessor and modifier functions for the %CerebralArteriesEffectors_Small
* sequence element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ CerebralArteriesEffectors_Small_type;
/**
* @brief Element sequence container type.
*/
typedef ::xsd::cxx::tree::sequence< CerebralArteriesEffectors_Small_type > CerebralArteriesEffectors_Small_sequence;
/**
* @brief Element iterator type.
*/
typedef CerebralArteriesEffectors_Small_sequence::iterator CerebralArteriesEffectors_Small_iterator;
/**
* @brief Element constant iterator type.
*/
typedef CerebralArteriesEffectors_Small_sequence::const_iterator CerebralArteriesEffectors_Small_const_iterator;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CerebralArteriesEffectors_Small_type, char, ::xsd::cxx::tree::schema_type::double_ > CerebralArteriesEffectors_Small_traits;
/**
* @brief Return a read-only (constant) reference to the element
* sequence.
*
* @return A constant reference to the sequence container.
*/
const CerebralArteriesEffectors_Small_sequence&
CerebralArteriesEffectors_Small () const;
/**
* @brief Return a read-write reference to the element sequence.
*
* @return A reference to the sequence container.
*/
CerebralArteriesEffectors_Small_sequence&
CerebralArteriesEffectors_Small ();
/**
* @brief Copy elements from a given sequence.
*
* @param s A sequence to copy elements from.
*
* For each element in @a s this function makes a copy and adds it
* to the sequence. Note that this operation completely changes the
* sequence and all old elements will be lost.
*/
void
CerebralArteriesEffectors_Small (const CerebralArteriesEffectors_Small_sequence& s);
//@}
/**
* @name CerebralBloodFlowBaseline_mL_Per_s
*
* @brief Accessor and modifier functions for the %CerebralBloodFlowBaseline_mL_Per_s
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ CerebralBloodFlowBaseline_mL_Per_s_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CerebralBloodFlowBaseline_mL_Per_s_type, char, ::xsd::cxx::tree::schema_type::double_ > CerebralBloodFlowBaseline_mL_Per_s_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CerebralBloodFlowBaseline_mL_Per_s_type&
CerebralBloodFlowBaseline_mL_Per_s () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CerebralBloodFlowBaseline_mL_Per_s_type&
CerebralBloodFlowBaseline_mL_Per_s ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CerebralBloodFlowBaseline_mL_Per_s (const CerebralBloodFlowBaseline_mL_Per_s_type& x);
//@}
/**
* @name CerebralBloodFlowInput_mL_Per_s
*
* @brief Accessor and modifier functions for the %CerebralBloodFlowInput_mL_Per_s
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ CerebralBloodFlowInput_mL_Per_s_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CerebralBloodFlowInput_mL_Per_s_type, char, ::xsd::cxx::tree::schema_type::double_ > CerebralBloodFlowInput_mL_Per_s_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CerebralBloodFlowInput_mL_Per_s_type&
CerebralBloodFlowInput_mL_Per_s () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CerebralBloodFlowInput_mL_Per_s_type&
CerebralBloodFlowInput_mL_Per_s ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CerebralBloodFlowInput_mL_Per_s (const CerebralBloodFlowInput_mL_Per_s_type& x);
//@}
/**
* @name CentralFrequencyDelta_Per_min
*
* @brief Accessor and modifier functions for the %CentralFrequencyDelta_Per_min
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ CentralFrequencyDelta_Per_min_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CentralFrequencyDelta_Per_min_type, char, ::xsd::cxx::tree::schema_type::double_ > CentralFrequencyDelta_Per_min_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CentralFrequencyDelta_Per_min_type&
CentralFrequencyDelta_Per_min () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CentralFrequencyDelta_Per_min_type&
CentralFrequencyDelta_Per_min ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CentralFrequencyDelta_Per_min (const CentralFrequencyDelta_Per_min_type& x);
//@}
/**
* @name CentralPressureDelta_cmH2O
*
* @brief Accessor and modifier functions for the %CentralPressureDelta_cmH2O
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ CentralPressureDelta_cmH2O_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CentralPressureDelta_cmH2O_type, char, ::xsd::cxx::tree::schema_type::double_ > CentralPressureDelta_cmH2O_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CentralPressureDelta_cmH2O_type&
CentralPressureDelta_cmH2O () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CentralPressureDelta_cmH2O_type&
CentralPressureDelta_cmH2O ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CentralPressureDelta_cmH2O (const CentralPressureDelta_cmH2O_type& x);
//@}
/**
* @name CerebralOxygenSaturationBaseline
*
* @brief Accessor and modifier functions for the %CerebralOxygenSaturationBaseline
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ CerebralOxygenSaturationBaseline_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CerebralOxygenSaturationBaseline_type, char, ::xsd::cxx::tree::schema_type::double_ > CerebralOxygenSaturationBaseline_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CerebralOxygenSaturationBaseline_type&
CerebralOxygenSaturationBaseline () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CerebralOxygenSaturationBaseline_type&
CerebralOxygenSaturationBaseline ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CerebralOxygenSaturationBaseline (const CerebralOxygenSaturationBaseline_type& x);
//@}
/**
* @name CerebralPerfusionPressureBaseline_mmHg
*
* @brief Accessor and modifier functions for the %CerebralPerfusionPressureBaseline_mmHg
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ CerebralPerfusionPressureBaseline_mmHg_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CerebralPerfusionPressureBaseline_mmHg_type, char, ::xsd::cxx::tree::schema_type::double_ > CerebralPerfusionPressureBaseline_mmHg_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CerebralPerfusionPressureBaseline_mmHg_type&
CerebralPerfusionPressureBaseline_mmHg () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CerebralPerfusionPressureBaseline_mmHg_type&
CerebralPerfusionPressureBaseline_mmHg ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CerebralPerfusionPressureBaseline_mmHg (const CerebralPerfusionPressureBaseline_mmHg_type& x);
//@}
/**
* @name ChemoreceptorPeripheralBloodGasInteractionBaseline_Hz
*
* @brief Accessor and modifier functions for the %ChemoreceptorPeripheralBloodGasInteractionBaseline_Hz
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ ChemoreceptorPeripheralBloodGasInteractionBaseline_Hz_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< ChemoreceptorPeripheralBloodGasInteractionBaseline_Hz_type, char, ::xsd::cxx::tree::schema_type::double_ > ChemoreceptorPeripheralBloodGasInteractionBaseline_Hz_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const ChemoreceptorPeripheralBloodGasInteractionBaseline_Hz_type&
ChemoreceptorPeripheralBloodGasInteractionBaseline_Hz () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
ChemoreceptorPeripheralBloodGasInteractionBaseline_Hz_type&
ChemoreceptorPeripheralBloodGasInteractionBaseline_Hz ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
ChemoreceptorPeripheralBloodGasInteractionBaseline_Hz (const ChemoreceptorPeripheralBloodGasInteractionBaseline_Hz_type& x);
//@}
/**
* @name ChemoreceptorFiringRateSetPoint_Hz
*
* @brief Accessor and modifier functions for the %ChemoreceptorFiringRateSetPoint_Hz
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ ChemoreceptorFiringRateSetPoint_Hz_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< ChemoreceptorFiringRateSetPoint_Hz_type, char, ::xsd::cxx::tree::schema_type::double_ > ChemoreceptorFiringRateSetPoint_Hz_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const ChemoreceptorFiringRateSetPoint_Hz_type&
ChemoreceptorFiringRateSetPoint_Hz () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
ChemoreceptorFiringRateSetPoint_Hz_type&
ChemoreceptorFiringRateSetPoint_Hz ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
ChemoreceptorFiringRateSetPoint_Hz (const ChemoreceptorFiringRateSetPoint_Hz_type& x);
//@}
/**
* @name ComplianceModifier
*
* @brief Accessor and modifier functions for the %ComplianceModifier
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ ComplianceModifier_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< ComplianceModifier_type, char, ::xsd::cxx::tree::schema_type::double_ > ComplianceModifier_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const ComplianceModifier_type&
ComplianceModifier () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
ComplianceModifier_type&
ComplianceModifier ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
ComplianceModifier (const ComplianceModifier_type& x);
//@}
/**
* @name HeartElastanceModifier
*
* @brief Accessor and modifier functions for the %HeartElastanceModifier
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ HeartElastanceModifier_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< HeartElastanceModifier_type, char, ::xsd::cxx::tree::schema_type::double_ > HeartElastanceModifier_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const HeartElastanceModifier_type&
HeartElastanceModifier () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
HeartElastanceModifier_type&
HeartElastanceModifier ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
HeartElastanceModifier (const HeartElastanceModifier_type& x);
//@}
/**
* @name HeartOxygenBaseline
*
* @brief Accessor and modifier functions for the %HeartOxygenBaseline
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ HeartOxygenBaseline_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< HeartOxygenBaseline_type, char, ::xsd::cxx::tree::schema_type::double_ > HeartOxygenBaseline_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const HeartOxygenBaseline_type&
HeartOxygenBaseline () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
HeartOxygenBaseline_type&
HeartOxygenBaseline ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
HeartOxygenBaseline (const HeartOxygenBaseline_type& x);
//@}
/**
* @name HeartRateModifierSympathetic
*
* @brief Accessor and modifier functions for the %HeartRateModifierSympathetic
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ HeartRateModifierSympathetic_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< HeartRateModifierSympathetic_type, char, ::xsd::cxx::tree::schema_type::double_ > HeartRateModifierSympathetic_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const HeartRateModifierSympathetic_type&
HeartRateModifierSympathetic () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
HeartRateModifierSympathetic_type&
HeartRateModifierSympathetic ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
HeartRateModifierSympathetic (const HeartRateModifierSympathetic_type& x);
//@}
/**
* @name HeartRateModifierVagal
*
* @brief Accessor and modifier functions for the %HeartRateModifierVagal
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ HeartRateModifierVagal_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< HeartRateModifierVagal_type, char, ::xsd::cxx::tree::schema_type::double_ > HeartRateModifierVagal_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const HeartRateModifierVagal_type&
HeartRateModifierVagal () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
HeartRateModifierVagal_type&
HeartRateModifierVagal ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
HeartRateModifierVagal (const HeartRateModifierVagal_type& x);
//@}
/**
* @name HypercapniaThresholdHeart
*
* @brief Accessor and modifier functions for the %HypercapniaThresholdHeart
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ HypercapniaThresholdHeart_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< HypercapniaThresholdHeart_type, char, ::xsd::cxx::tree::schema_type::double_ > HypercapniaThresholdHeart_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const HypercapniaThresholdHeart_type&
HypercapniaThresholdHeart () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
HypercapniaThresholdHeart_type&
HypercapniaThresholdHeart ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
HypercapniaThresholdHeart (const HypercapniaThresholdHeart_type& x);
//@}
/**
* @name HypercapniaThresholdPeripheral
*
* @brief Accessor and modifier functions for the %HypercapniaThresholdPeripheral
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ HypercapniaThresholdPeripheral_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< HypercapniaThresholdPeripheral_type, char, ::xsd::cxx::tree::schema_type::double_ > HypercapniaThresholdPeripheral_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const HypercapniaThresholdPeripheral_type&
HypercapniaThresholdPeripheral () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
HypercapniaThresholdPeripheral_type&
HypercapniaThresholdPeripheral ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
HypercapniaThresholdPeripheral (const HypercapniaThresholdPeripheral_type& x);
//@}
/**
* @name HypoxiaThresholdHeart
*
* @brief Accessor and modifier functions for the %HypoxiaThresholdHeart
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ HypoxiaThresholdHeart_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< HypoxiaThresholdHeart_type, char, ::xsd::cxx::tree::schema_type::double_ > HypoxiaThresholdHeart_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const HypoxiaThresholdHeart_type&
HypoxiaThresholdHeart () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
HypoxiaThresholdHeart_type&
HypoxiaThresholdHeart ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
HypoxiaThresholdHeart (const HypoxiaThresholdHeart_type& x);
//@}
/**
* @name HypoxiaThresholdPeripheral
*
* @brief Accessor and modifier functions for the %HypoxiaThresholdPeripheral
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ HypoxiaThresholdPeripheral_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< HypoxiaThresholdPeripheral_type, char, ::xsd::cxx::tree::schema_type::double_ > HypoxiaThresholdPeripheral_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const HypoxiaThresholdPeripheral_type&
HypoxiaThresholdPeripheral () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
HypoxiaThresholdPeripheral_type&
HypoxiaThresholdPeripheral ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
HypoxiaThresholdPeripheral (const HypoxiaThresholdPeripheral_type& x);
//@}
/**
* @name MeanLungVolume_L
*
* @brief Accessor and modifier functions for the %MeanLungVolume_L
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ MeanLungVolume_L_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< MeanLungVolume_L_type, char, ::xsd::cxx::tree::schema_type::double_ > MeanLungVolume_L_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const MeanLungVolume_L_type&
MeanLungVolume_L () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
MeanLungVolume_L_type&
MeanLungVolume_L ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
MeanLungVolume_L (const MeanLungVolume_L_type& x);
//@}
/**
* @name MuscleOxygenBaseline
*
* @brief Accessor and modifier functions for the %MuscleOxygenBaseline
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ MuscleOxygenBaseline_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< MuscleOxygenBaseline_type, char, ::xsd::cxx::tree::schema_type::double_ > MuscleOxygenBaseline_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const MuscleOxygenBaseline_type&
MuscleOxygenBaseline () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
MuscleOxygenBaseline_type&
MuscleOxygenBaseline ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
MuscleOxygenBaseline (const MuscleOxygenBaseline_type& x);
//@}
/**
* @name OxygenAutoregulatorHeart
*
* @brief Accessor and modifier functions for the %OxygenAutoregulatorHeart
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ OxygenAutoregulatorHeart_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< OxygenAutoregulatorHeart_type, char, ::xsd::cxx::tree::schema_type::double_ > OxygenAutoregulatorHeart_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const OxygenAutoregulatorHeart_type&
OxygenAutoregulatorHeart () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
OxygenAutoregulatorHeart_type&
OxygenAutoregulatorHeart ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
OxygenAutoregulatorHeart (const OxygenAutoregulatorHeart_type& x);
//@}
/**
* @name OxygenAutoregulatorMuscle
*
* @brief Accessor and modifier functions for the %OxygenAutoregulatorMuscle
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ OxygenAutoregulatorMuscle_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< OxygenAutoregulatorMuscle_type, char, ::xsd::cxx::tree::schema_type::double_ > OxygenAutoregulatorMuscle_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const OxygenAutoregulatorMuscle_type&
OxygenAutoregulatorMuscle () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
OxygenAutoregulatorMuscle_type&
OxygenAutoregulatorMuscle ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
OxygenAutoregulatorMuscle (const OxygenAutoregulatorMuscle_type& x);
//@}
/**
* @name PeripheralFrequencyDelta_Per_min
*
* @brief Accessor and modifier functions for the %PeripheralFrequencyDelta_Per_min
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ PeripheralFrequencyDelta_Per_min_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< PeripheralFrequencyDelta_Per_min_type, char, ::xsd::cxx::tree::schema_type::double_ > PeripheralFrequencyDelta_Per_min_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const PeripheralFrequencyDelta_Per_min_type&
PeripheralFrequencyDelta_Per_min () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
PeripheralFrequencyDelta_Per_min_type&
PeripheralFrequencyDelta_Per_min ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
PeripheralFrequencyDelta_Per_min (const PeripheralFrequencyDelta_Per_min_type& x);
//@}
/**
* @name PeripheralPressureDelta_cmH2O
*
* @brief Accessor and modifier functions for the %PeripheralPressureDelta_cmH2O
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ PeripheralPressureDelta_cmH2O_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< PeripheralPressureDelta_cmH2O_type, char, ::xsd::cxx::tree::schema_type::double_ > PeripheralPressureDelta_cmH2O_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const PeripheralPressureDelta_cmH2O_type&
PeripheralPressureDelta_cmH2O () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
PeripheralPressureDelta_cmH2O_type&
PeripheralPressureDelta_cmH2O ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
PeripheralPressureDelta_cmH2O (const PeripheralPressureDelta_cmH2O_type& x);
//@}
/**
* @name ResistanceModifierExtrasplanchnic
*
* @brief Accessor and modifier functions for the %ResistanceModifierExtrasplanchnic
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ ResistanceModifierExtrasplanchnic_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< ResistanceModifierExtrasplanchnic_type, char, ::xsd::cxx::tree::schema_type::double_ > ResistanceModifierExtrasplanchnic_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const ResistanceModifierExtrasplanchnic_type&
ResistanceModifierExtrasplanchnic () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
ResistanceModifierExtrasplanchnic_type&
ResistanceModifierExtrasplanchnic ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
ResistanceModifierExtrasplanchnic (const ResistanceModifierExtrasplanchnic_type& x);
//@}
/**
* @name ResistanceModifierMuscle
*
* @brief Accessor and modifier functions for the %ResistanceModifierMuscle
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ ResistanceModifierMuscle_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< ResistanceModifierMuscle_type, char, ::xsd::cxx::tree::schema_type::double_ > ResistanceModifierMuscle_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const ResistanceModifierMuscle_type&
ResistanceModifierMuscle () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
ResistanceModifierMuscle_type&
ResistanceModifierMuscle ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
ResistanceModifierMuscle (const ResistanceModifierMuscle_type& x);
//@}
/**
* @name ResistanceModifierSplanchnic
*
* @brief Accessor and modifier functions for the %ResistanceModifierSplanchnic
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ ResistanceModifierSplanchnic_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< ResistanceModifierSplanchnic_type, char, ::xsd::cxx::tree::schema_type::double_ > ResistanceModifierSplanchnic_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const ResistanceModifierSplanchnic_type&
ResistanceModifierSplanchnic () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
ResistanceModifierSplanchnic_type&
ResistanceModifierSplanchnic ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
ResistanceModifierSplanchnic (const ResistanceModifierSplanchnic_type& x);
//@}
/**
* @name SympatheticPeripheralSignalBaseline
*
* @brief Accessor and modifier functions for the %SympatheticPeripheralSignalBaseline
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ SympatheticPeripheralSignalBaseline_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< SympatheticPeripheralSignalBaseline_type, char, ::xsd::cxx::tree::schema_type::double_ > SympatheticPeripheralSignalBaseline_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const SympatheticPeripheralSignalBaseline_type&
SympatheticPeripheralSignalBaseline () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
SympatheticPeripheralSignalBaseline_type&
SympatheticPeripheralSignalBaseline ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
SympatheticPeripheralSignalBaseline (const SympatheticPeripheralSignalBaseline_type& x);
//@}
/**
* @name SympatheticSinoatrialSignalBaseline
*
* @brief Accessor and modifier functions for the %SympatheticSinoatrialSignalBaseline
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ SympatheticSinoatrialSignalBaseline_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< SympatheticSinoatrialSignalBaseline_type, char, ::xsd::cxx::tree::schema_type::double_ > SympatheticSinoatrialSignalBaseline_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const SympatheticSinoatrialSignalBaseline_type&
SympatheticSinoatrialSignalBaseline () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
SympatheticSinoatrialSignalBaseline_type&
SympatheticSinoatrialSignalBaseline ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
SympatheticSinoatrialSignalBaseline (const SympatheticSinoatrialSignalBaseline_type& x);
//@}
/**
* @name SympatheticPeripheralSignalFatigue
*
* @brief Accessor and modifier functions for the %SympatheticPeripheralSignalFatigue
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ SympatheticPeripheralSignalFatigue_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< SympatheticPeripheralSignalFatigue_type, char, ::xsd::cxx::tree::schema_type::double_ > SympatheticPeripheralSignalFatigue_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const SympatheticPeripheralSignalFatigue_type&
SympatheticPeripheralSignalFatigue () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
SympatheticPeripheralSignalFatigue_type&
SympatheticPeripheralSignalFatigue ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
SympatheticPeripheralSignalFatigue (const SympatheticPeripheralSignalFatigue_type& x);
//@}
/**
* @name VagalSignalBaseline
*
* @brief Accessor and modifier functions for the %VagalSignalBaseline
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ VagalSignalBaseline_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< VagalSignalBaseline_type, char, ::xsd::cxx::tree::schema_type::double_ > VagalSignalBaseline_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const VagalSignalBaseline_type&
VagalSignalBaseline () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
VagalSignalBaseline_type&
VagalSignalBaseline ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
VagalSignalBaseline (const VagalSignalBaseline_type& x);
//@}
/**
* @name Constructors
*/
//@{
/**
* @brief Default constructor.
*
* Note that this constructor leaves required elements and
* attributes uninitialized.
*/
BioGearsNervousSystemData ();
/**
* @brief Create an instance from the ultimate base and
* initializers for required elements and attributes.
*/
BioGearsNervousSystemData (const AfferentChemoreceptor_Hz_type&,
const AfferentPulmonaryStrechReceptor_Hz_type&,
const AorticBaroreceptorStrain_type&,
const ArterialOxygenBaseline_mmHg_type&,
const ArterialCarbonDioxideBaseline_mmHg_type&,
const BaroreceptorOperatingPoint_mmHg_type&,
const CardiopulmonaryInputBaseline_mmHg_type&,
const CardiopulmonaryInput_mmHg_type&,
const CarotidBaroreceptorStrain_type&,
const CerebralBloodFlowBaseline_mL_Per_s_type&,
const CerebralBloodFlowInput_mL_Per_s_type&,
const CentralFrequencyDelta_Per_min_type&,
const CentralPressureDelta_cmH2O_type&,
const CerebralOxygenSaturationBaseline_type&,
const CerebralPerfusionPressureBaseline_mmHg_type&,
const ChemoreceptorPeripheralBloodGasInteractionBaseline_Hz_type&,
const ChemoreceptorFiringRateSetPoint_Hz_type&,
const ComplianceModifier_type&,
const HeartElastanceModifier_type&,
const HeartOxygenBaseline_type&,
const HeartRateModifierSympathetic_type&,
const HeartRateModifierVagal_type&,
const HypercapniaThresholdHeart_type&,
const HypercapniaThresholdPeripheral_type&,
const HypoxiaThresholdHeart_type&,
const HypoxiaThresholdPeripheral_type&,
const MeanLungVolume_L_type&,
const MuscleOxygenBaseline_type&,
const OxygenAutoregulatorHeart_type&,
const OxygenAutoregulatorMuscle_type&,
const PeripheralFrequencyDelta_Per_min_type&,
const PeripheralPressureDelta_cmH2O_type&,
const ResistanceModifierExtrasplanchnic_type&,
const ResistanceModifierMuscle_type&,
const ResistanceModifierSplanchnic_type&,
const SympatheticPeripheralSignalBaseline_type&,
const SympatheticSinoatrialSignalBaseline_type&,
const SympatheticPeripheralSignalFatigue_type&,
const VagalSignalBaseline_type&);
/**
* @brief Create an instance from a DOM element.
*
* @param e A DOM element to extract the data from.
* @param f Flags to create the new instance with.
* @param c A pointer to the object that will contain the new
* instance.
*/
BioGearsNervousSystemData (const ::xercesc::DOMElement& e,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
/**
* @brief Copy constructor.
*
* @param x An instance to make a copy of.
* @param f Flags to create the copy with.
* @param c A pointer to the object that will contain the copy.
*
* For polymorphic object models use the @c _clone function instead.
*/
BioGearsNervousSystemData (const BioGearsNervousSystemData& x,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
/**
* @brief Copy the instance polymorphically.
*
* @param f Flags to create the copy with.
* @param c A pointer to the object that will contain the copy.
* @return A pointer to the dynamically allocated copy.
*
* This function ensures that the dynamic type of the instance is
* used for copying and should be used for polymorphic object
* models instead of the copy constructor.
*/
virtual BioGearsNervousSystemData*
_clone (::xml_schema::flags f = 0,
::xml_schema::container* c = 0) const;
/**
* @brief Copy assignment operator.
*
* @param x An instance to make a copy of.
* @return A reference to itself.
*
* For polymorphic object models use the @c _clone function instead.
*/
BioGearsNervousSystemData&
operator= (const BioGearsNervousSystemData& x);
//@}
/**
* @brief Destructor.
*/
virtual
~BioGearsNervousSystemData ();
// Implementation.
//
//@cond
protected:
void
parse (::xsd::cxx::xml::dom::parser< char >&,
::xml_schema::flags);
protected:
::xsd::cxx::tree::one< AfferentChemoreceptor_Hz_type > AfferentChemoreceptor_Hz_;
::xsd::cxx::tree::one< AfferentPulmonaryStrechReceptor_Hz_type > AfferentPulmonaryStrechReceptor_Hz_;
::xsd::cxx::tree::one< AorticBaroreceptorStrain_type > AorticBaroreceptorStrain_;
::xsd::cxx::tree::one< ArterialOxygenBaseline_mmHg_type > ArterialOxygenBaseline_mmHg_;
::xsd::cxx::tree::one< ArterialCarbonDioxideBaseline_mmHg_type > ArterialCarbonDioxideBaseline_mmHg_;
::xsd::cxx::tree::one< BaroreceptorOperatingPoint_mmHg_type > BaroreceptorOperatingPoint_mmHg_;
::xsd::cxx::tree::one< CardiopulmonaryInputBaseline_mmHg_type > CardiopulmonaryInputBaseline_mmHg_;
::xsd::cxx::tree::one< CardiopulmonaryInput_mmHg_type > CardiopulmonaryInput_mmHg_;
::xsd::cxx::tree::one< CarotidBaroreceptorStrain_type > CarotidBaroreceptorStrain_;
CerebralArteriesEffectors_Large_sequence CerebralArteriesEffectors_Large_;
CerebralArteriesEffectors_Small_sequence CerebralArteriesEffectors_Small_;
::xsd::cxx::tree::one< CerebralBloodFlowBaseline_mL_Per_s_type > CerebralBloodFlowBaseline_mL_Per_s_;
::xsd::cxx::tree::one< CerebralBloodFlowInput_mL_Per_s_type > CerebralBloodFlowInput_mL_Per_s_;
::xsd::cxx::tree::one< CentralFrequencyDelta_Per_min_type > CentralFrequencyDelta_Per_min_;
::xsd::cxx::tree::one< CentralPressureDelta_cmH2O_type > CentralPressureDelta_cmH2O_;
::xsd::cxx::tree::one< CerebralOxygenSaturationBaseline_type > CerebralOxygenSaturationBaseline_;
::xsd::cxx::tree::one< CerebralPerfusionPressureBaseline_mmHg_type > CerebralPerfusionPressureBaseline_mmHg_;
::xsd::cxx::tree::one< ChemoreceptorPeripheralBloodGasInteractionBaseline_Hz_type > ChemoreceptorPeripheralBloodGasInteractionBaseline_Hz_;
::xsd::cxx::tree::one< ChemoreceptorFiringRateSetPoint_Hz_type > ChemoreceptorFiringRateSetPoint_Hz_;
::xsd::cxx::tree::one< ComplianceModifier_type > ComplianceModifier_;
::xsd::cxx::tree::one< HeartElastanceModifier_type > HeartElastanceModifier_;
::xsd::cxx::tree::one< HeartOxygenBaseline_type > HeartOxygenBaseline_;
::xsd::cxx::tree::one< HeartRateModifierSympathetic_type > HeartRateModifierSympathetic_;
::xsd::cxx::tree::one< HeartRateModifierVagal_type > HeartRateModifierVagal_;
::xsd::cxx::tree::one< HypercapniaThresholdHeart_type > HypercapniaThresholdHeart_;
::xsd::cxx::tree::one< HypercapniaThresholdPeripheral_type > HypercapniaThresholdPeripheral_;
::xsd::cxx::tree::one< HypoxiaThresholdHeart_type > HypoxiaThresholdHeart_;
::xsd::cxx::tree::one< HypoxiaThresholdPeripheral_type > HypoxiaThresholdPeripheral_;
::xsd::cxx::tree::one< MeanLungVolume_L_type > MeanLungVolume_L_;
::xsd::cxx::tree::one< MuscleOxygenBaseline_type > MuscleOxygenBaseline_;
::xsd::cxx::tree::one< OxygenAutoregulatorHeart_type > OxygenAutoregulatorHeart_;
::xsd::cxx::tree::one< OxygenAutoregulatorMuscle_type > OxygenAutoregulatorMuscle_;
::xsd::cxx::tree::one< PeripheralFrequencyDelta_Per_min_type > PeripheralFrequencyDelta_Per_min_;
::xsd::cxx::tree::one< PeripheralPressureDelta_cmH2O_type > PeripheralPressureDelta_cmH2O_;
::xsd::cxx::tree::one< ResistanceModifierExtrasplanchnic_type > ResistanceModifierExtrasplanchnic_;
::xsd::cxx::tree::one< ResistanceModifierMuscle_type > ResistanceModifierMuscle_;
::xsd::cxx::tree::one< ResistanceModifierSplanchnic_type > ResistanceModifierSplanchnic_;
::xsd::cxx::tree::one< SympatheticPeripheralSignalBaseline_type > SympatheticPeripheralSignalBaseline_;
::xsd::cxx::tree::one< SympatheticSinoatrialSignalBaseline_type > SympatheticSinoatrialSignalBaseline_;
::xsd::cxx::tree::one< SympatheticPeripheralSignalFatigue_type > SympatheticPeripheralSignalFatigue_;
::xsd::cxx::tree::one< VagalSignalBaseline_type > VagalSignalBaseline_;
//@endcond
};
/**
* @brief Class corresponding to the %BioGearsRenalSystemData schema type.
*
* @nosubgrouping
*/
class BIOGEARS_CDM_API BioGearsRenalSystemData: public ::mil::tatrc::physiology::datamodel::RenalSystemData
{
public:
/**
* @name Urinating
*
* @brief Accessor and modifier functions for the %Urinating
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::boolean Urinating_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< Urinating_type, char > Urinating_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const Urinating_type&
Urinating () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
Urinating_type&
Urinating ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
Urinating (const Urinating_type& x);
//@}
/**
* @name LeftAfferentResistance_mmHg_s_Per_mL
*
* @brief Accessor and modifier functions for the %LeftAfferentResistance_mmHg_s_Per_mL
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ LeftAfferentResistance_mmHg_s_Per_mL_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< LeftAfferentResistance_mmHg_s_Per_mL_type, char, ::xsd::cxx::tree::schema_type::double_ > LeftAfferentResistance_mmHg_s_Per_mL_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const LeftAfferentResistance_mmHg_s_Per_mL_type&
LeftAfferentResistance_mmHg_s_Per_mL () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
LeftAfferentResistance_mmHg_s_Per_mL_type&
LeftAfferentResistance_mmHg_s_Per_mL ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
LeftAfferentResistance_mmHg_s_Per_mL (const LeftAfferentResistance_mmHg_s_Per_mL_type& x);
//@}
/**
* @name RightAfferentResistance_mmHg_s_Per_mL
*
* @brief Accessor and modifier functions for the %RightAfferentResistance_mmHg_s_Per_mL
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ RightAfferentResistance_mmHg_s_Per_mL_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< RightAfferentResistance_mmHg_s_Per_mL_type, char, ::xsd::cxx::tree::schema_type::double_ > RightAfferentResistance_mmHg_s_Per_mL_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const RightAfferentResistance_mmHg_s_Per_mL_type&
RightAfferentResistance_mmHg_s_Per_mL () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
RightAfferentResistance_mmHg_s_Per_mL_type&
RightAfferentResistance_mmHg_s_Per_mL ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
RightAfferentResistance_mmHg_s_Per_mL (const RightAfferentResistance_mmHg_s_Per_mL_type& x);
//@}
/**
* @name LeftSodiumFlowSetPoint_mg_Per_s
*
* @brief Accessor and modifier functions for the %LeftSodiumFlowSetPoint_mg_Per_s
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ LeftSodiumFlowSetPoint_mg_Per_s_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< LeftSodiumFlowSetPoint_mg_Per_s_type, char, ::xsd::cxx::tree::schema_type::double_ > LeftSodiumFlowSetPoint_mg_Per_s_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const LeftSodiumFlowSetPoint_mg_Per_s_type&
LeftSodiumFlowSetPoint_mg_Per_s () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
LeftSodiumFlowSetPoint_mg_Per_s_type&
LeftSodiumFlowSetPoint_mg_Per_s ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
LeftSodiumFlowSetPoint_mg_Per_s (const LeftSodiumFlowSetPoint_mg_Per_s_type& x);
//@}
/**
* @name RightSodiumFlowSetPoint_mg_Per_s
*
* @brief Accessor and modifier functions for the %RightSodiumFlowSetPoint_mg_Per_s
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ RightSodiumFlowSetPoint_mg_Per_s_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< RightSodiumFlowSetPoint_mg_Per_s_type, char, ::xsd::cxx::tree::schema_type::double_ > RightSodiumFlowSetPoint_mg_Per_s_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const RightSodiumFlowSetPoint_mg_Per_s_type&
RightSodiumFlowSetPoint_mg_Per_s () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
RightSodiumFlowSetPoint_mg_Per_s_type&
RightSodiumFlowSetPoint_mg_Per_s ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
RightSodiumFlowSetPoint_mg_Per_s (const RightSodiumFlowSetPoint_mg_Per_s_type& x);
//@}
/**
* @name UrineProductionRate_mL_Per_min
*
* @brief Accessor and modifier functions for the %UrineProductionRate_mL_Per_min
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::RunningAverageData UrineProductionRate_mL_Per_min_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< UrineProductionRate_mL_Per_min_type, char > UrineProductionRate_mL_Per_min_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const UrineProductionRate_mL_Per_min_type&
UrineProductionRate_mL_Per_min () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
UrineProductionRate_mL_Per_min_type&
UrineProductionRate_mL_Per_min ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
UrineProductionRate_mL_Per_min (const UrineProductionRate_mL_Per_min_type& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
UrineProductionRate_mL_Per_min (::std::unique_ptr< UrineProductionRate_mL_Per_min_type > p);
//@}
/**
* @name UrineOsmolarity_mOsm_Per_L
*
* @brief Accessor and modifier functions for the %UrineOsmolarity_mOsm_Per_L
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::RunningAverageData UrineOsmolarity_mOsm_Per_L_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< UrineOsmolarity_mOsm_Per_L_type, char > UrineOsmolarity_mOsm_Per_L_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const UrineOsmolarity_mOsm_Per_L_type&
UrineOsmolarity_mOsm_Per_L () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
UrineOsmolarity_mOsm_Per_L_type&
UrineOsmolarity_mOsm_Per_L ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
UrineOsmolarity_mOsm_Per_L (const UrineOsmolarity_mOsm_Per_L_type& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
UrineOsmolarity_mOsm_Per_L (::std::unique_ptr< UrineOsmolarity_mOsm_Per_L_type > p);
//@}
/**
* @name SodiumConcentration_mg_Per_mL
*
* @brief Accessor and modifier functions for the %SodiumConcentration_mg_Per_mL
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::RunningAverageData SodiumConcentration_mg_Per_mL_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< SodiumConcentration_mg_Per_mL_type, char > SodiumConcentration_mg_Per_mL_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const SodiumConcentration_mg_Per_mL_type&
SodiumConcentration_mg_Per_mL () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
SodiumConcentration_mg_Per_mL_type&
SodiumConcentration_mg_Per_mL ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
SodiumConcentration_mg_Per_mL (const SodiumConcentration_mg_Per_mL_type& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
SodiumConcentration_mg_Per_mL (::std::unique_ptr< SodiumConcentration_mg_Per_mL_type > p);
//@}
/**
* @name SodiumExcretionRate_mg_Per_min
*
* @brief Accessor and modifier functions for the %SodiumExcretionRate_mg_Per_min
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::RunningAverageData SodiumExcretionRate_mg_Per_min_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< SodiumExcretionRate_mg_Per_min_type, char > SodiumExcretionRate_mg_Per_min_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const SodiumExcretionRate_mg_Per_min_type&
SodiumExcretionRate_mg_Per_min () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
SodiumExcretionRate_mg_Per_min_type&
SodiumExcretionRate_mg_Per_min ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
SodiumExcretionRate_mg_Per_min (const SodiumExcretionRate_mg_Per_min_type& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
SodiumExcretionRate_mg_Per_min (::std::unique_ptr< SodiumExcretionRate_mg_Per_min_type > p);
//@}
/**
* @name LeftSodiumFlow_mg_Per_s
*
* @brief Accessor and modifier functions for the %LeftSodiumFlow_mg_Per_s
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::RunningAverageData LeftSodiumFlow_mg_Per_s_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< LeftSodiumFlow_mg_Per_s_type, char > LeftSodiumFlow_mg_Per_s_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const LeftSodiumFlow_mg_Per_s_type&
LeftSodiumFlow_mg_Per_s () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
LeftSodiumFlow_mg_Per_s_type&
LeftSodiumFlow_mg_Per_s ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
LeftSodiumFlow_mg_Per_s (const LeftSodiumFlow_mg_Per_s_type& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
LeftSodiumFlow_mg_Per_s (::std::unique_ptr< LeftSodiumFlow_mg_Per_s_type > p);
//@}
/**
* @name RightSodiumFlow_mg_Per_s
*
* @brief Accessor and modifier functions for the %RightSodiumFlow_mg_Per_s
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::RunningAverageData RightSodiumFlow_mg_Per_s_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< RightSodiumFlow_mg_Per_s_type, char > RightSodiumFlow_mg_Per_s_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const RightSodiumFlow_mg_Per_s_type&
RightSodiumFlow_mg_Per_s () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
RightSodiumFlow_mg_Per_s_type&
RightSodiumFlow_mg_Per_s ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
RightSodiumFlow_mg_Per_s (const RightSodiumFlow_mg_Per_s_type& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
RightSodiumFlow_mg_Per_s (::std::unique_ptr< RightSodiumFlow_mg_Per_s_type > p);
//@}
/**
* @name LeftRenalArterialPressure_mmHg
*
* @brief Accessor and modifier functions for the %LeftRenalArterialPressure_mmHg
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::RunningAverageData LeftRenalArterialPressure_mmHg_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< LeftRenalArterialPressure_mmHg_type, char > LeftRenalArterialPressure_mmHg_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const LeftRenalArterialPressure_mmHg_type&
LeftRenalArterialPressure_mmHg () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
LeftRenalArterialPressure_mmHg_type&
LeftRenalArterialPressure_mmHg ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
LeftRenalArterialPressure_mmHg (const LeftRenalArterialPressure_mmHg_type& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
LeftRenalArterialPressure_mmHg (::std::unique_ptr< LeftRenalArterialPressure_mmHg_type > p);
//@}
/**
* @name RightRenalArterialPressure_mmHg
*
* @brief Accessor and modifier functions for the %RightRenalArterialPressure_mmHg
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::RunningAverageData RightRenalArterialPressure_mmHg_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< RightRenalArterialPressure_mmHg_type, char > RightRenalArterialPressure_mmHg_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const RightRenalArterialPressure_mmHg_type&
RightRenalArterialPressure_mmHg () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
RightRenalArterialPressure_mmHg_type&
RightRenalArterialPressure_mmHg ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
RightRenalArterialPressure_mmHg (const RightRenalArterialPressure_mmHg_type& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
RightRenalArterialPressure_mmHg (::std::unique_ptr< RightRenalArterialPressure_mmHg_type > p);
//@}
/**
* @name Constructors
*/
//@{
/**
* @brief Default constructor.
*
* Note that this constructor leaves required elements and
* attributes uninitialized.
*/
BioGearsRenalSystemData ();
/**
* @brief Create an instance from the ultimate base and
* initializers for required elements and attributes.
*/
BioGearsRenalSystemData (const Urinating_type&,
const LeftAfferentResistance_mmHg_s_Per_mL_type&,
const RightAfferentResistance_mmHg_s_Per_mL_type&,
const LeftSodiumFlowSetPoint_mg_Per_s_type&,
const RightSodiumFlowSetPoint_mg_Per_s_type&,
const UrineProductionRate_mL_Per_min_type&,
const UrineOsmolarity_mOsm_Per_L_type&,
const SodiumConcentration_mg_Per_mL_type&,
const SodiumExcretionRate_mg_Per_min_type&,
const LeftSodiumFlow_mg_Per_s_type&,
const RightSodiumFlow_mg_Per_s_type&,
const LeftRenalArterialPressure_mmHg_type&,
const RightRenalArterialPressure_mmHg_type&);
/**
* @brief Create an instance from the ultimate base and
* initializers for required elements and attributes
* (::std::unique_ptr version).
*
* This constructor will try to use the passed values directly
* instead of making copies.
*/
BioGearsRenalSystemData (const Urinating_type&,
const LeftAfferentResistance_mmHg_s_Per_mL_type&,
const RightAfferentResistance_mmHg_s_Per_mL_type&,
const LeftSodiumFlowSetPoint_mg_Per_s_type&,
const RightSodiumFlowSetPoint_mg_Per_s_type&,
::std::unique_ptr< UrineProductionRate_mL_Per_min_type >,
::std::unique_ptr< UrineOsmolarity_mOsm_Per_L_type >,
::std::unique_ptr< SodiumConcentration_mg_Per_mL_type >,
::std::unique_ptr< SodiumExcretionRate_mg_Per_min_type >,
::std::unique_ptr< LeftSodiumFlow_mg_Per_s_type >,
::std::unique_ptr< RightSodiumFlow_mg_Per_s_type >,
::std::unique_ptr< LeftRenalArterialPressure_mmHg_type >,
::std::unique_ptr< RightRenalArterialPressure_mmHg_type >);
/**
* @brief Create an instance from a DOM element.
*
* @param e A DOM element to extract the data from.
* @param f Flags to create the new instance with.
* @param c A pointer to the object that will contain the new
* instance.
*/
BioGearsRenalSystemData (const ::xercesc::DOMElement& e,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
/**
* @brief Copy constructor.
*
* @param x An instance to make a copy of.
* @param f Flags to create the copy with.
* @param c A pointer to the object that will contain the copy.
*
* For polymorphic object models use the @c _clone function instead.
*/
BioGearsRenalSystemData (const BioGearsRenalSystemData& x,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
/**
* @brief Copy the instance polymorphically.
*
* @param f Flags to create the copy with.
* @param c A pointer to the object that will contain the copy.
* @return A pointer to the dynamically allocated copy.
*
* This function ensures that the dynamic type of the instance is
* used for copying and should be used for polymorphic object
* models instead of the copy constructor.
*/
virtual BioGearsRenalSystemData*
_clone (::xml_schema::flags f = 0,
::xml_schema::container* c = 0) const;
/**
* @brief Copy assignment operator.
*
* @param x An instance to make a copy of.
* @return A reference to itself.
*
* For polymorphic object models use the @c _clone function instead.
*/
BioGearsRenalSystemData&
operator= (const BioGearsRenalSystemData& x);
//@}
/**
* @brief Destructor.
*/
virtual
~BioGearsRenalSystemData ();
// Implementation.
//
//@cond
protected:
void
parse (::xsd::cxx::xml::dom::parser< char >&,
::xml_schema::flags);
protected:
::xsd::cxx::tree::one< Urinating_type > Urinating_;
::xsd::cxx::tree::one< LeftAfferentResistance_mmHg_s_Per_mL_type > LeftAfferentResistance_mmHg_s_Per_mL_;
::xsd::cxx::tree::one< RightAfferentResistance_mmHg_s_Per_mL_type > RightAfferentResistance_mmHg_s_Per_mL_;
::xsd::cxx::tree::one< LeftSodiumFlowSetPoint_mg_Per_s_type > LeftSodiumFlowSetPoint_mg_Per_s_;
::xsd::cxx::tree::one< RightSodiumFlowSetPoint_mg_Per_s_type > RightSodiumFlowSetPoint_mg_Per_s_;
::xsd::cxx::tree::one< UrineProductionRate_mL_Per_min_type > UrineProductionRate_mL_Per_min_;
::xsd::cxx::tree::one< UrineOsmolarity_mOsm_Per_L_type > UrineOsmolarity_mOsm_Per_L_;
::xsd::cxx::tree::one< SodiumConcentration_mg_Per_mL_type > SodiumConcentration_mg_Per_mL_;
::xsd::cxx::tree::one< SodiumExcretionRate_mg_Per_min_type > SodiumExcretionRate_mg_Per_min_;
::xsd::cxx::tree::one< LeftSodiumFlow_mg_Per_s_type > LeftSodiumFlow_mg_Per_s_;
::xsd::cxx::tree::one< RightSodiumFlow_mg_Per_s_type > RightSodiumFlow_mg_Per_s_;
::xsd::cxx::tree::one< LeftRenalArterialPressure_mmHg_type > LeftRenalArterialPressure_mmHg_;
::xsd::cxx::tree::one< RightRenalArterialPressure_mmHg_type > RightRenalArterialPressure_mmHg_;
//@endcond
};
/**
* @brief Class corresponding to the %BioGearsRespiratorySystemData schema type.
*
* @nosubgrouping
*/
class BIOGEARS_CDM_API BioGearsRespiratorySystemData: public ::mil::tatrc::physiology::datamodel::RespiratorySystemData
{
public:
/**
* @name InitialExpiratoryReserveVolume_L
*
* @brief Accessor and modifier functions for the %InitialExpiratoryReserveVolume_L
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ InitialExpiratoryReserveVolume_L_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< InitialExpiratoryReserveVolume_L_type, char, ::xsd::cxx::tree::schema_type::double_ > InitialExpiratoryReserveVolume_L_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const InitialExpiratoryReserveVolume_L_type&
InitialExpiratoryReserveVolume_L () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
InitialExpiratoryReserveVolume_L_type&
InitialExpiratoryReserveVolume_L ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
InitialExpiratoryReserveVolume_L (const InitialExpiratoryReserveVolume_L_type& x);
//@}
/**
* @name InitialFunctionalResidualCapacity_L
*
* @brief Accessor and modifier functions for the %InitialFunctionalResidualCapacity_L
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ InitialFunctionalResidualCapacity_L_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< InitialFunctionalResidualCapacity_L_type, char, ::xsd::cxx::tree::schema_type::double_ > InitialFunctionalResidualCapacity_L_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const InitialFunctionalResidualCapacity_L_type&
InitialFunctionalResidualCapacity_L () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
InitialFunctionalResidualCapacity_L_type&
InitialFunctionalResidualCapacity_L ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
InitialFunctionalResidualCapacity_L (const InitialFunctionalResidualCapacity_L_type& x);
//@}
/**
* @name InitialInspiratoryCapacity_L
*
* @brief Accessor and modifier functions for the %InitialInspiratoryCapacity_L
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ InitialInspiratoryCapacity_L_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< InitialInspiratoryCapacity_L_type, char, ::xsd::cxx::tree::schema_type::double_ > InitialInspiratoryCapacity_L_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const InitialInspiratoryCapacity_L_type&
InitialInspiratoryCapacity_L () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
InitialInspiratoryCapacity_L_type&
InitialInspiratoryCapacity_L ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
InitialInspiratoryCapacity_L (const InitialInspiratoryCapacity_L_type& x);
//@}
/**
* @name InitialResidualVolume_L
*
* @brief Accessor and modifier functions for the %InitialResidualVolume_L
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ InitialResidualVolume_L_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< InitialResidualVolume_L_type, char, ::xsd::cxx::tree::schema_type::double_ > InitialResidualVolume_L_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const InitialResidualVolume_L_type&
InitialResidualVolume_L () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
InitialResidualVolume_L_type&
InitialResidualVolume_L ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
InitialResidualVolume_L (const InitialResidualVolume_L_type& x);
//@}
/**
* @name NotBreathing
*
* @brief Accessor and modifier functions for the %NotBreathing
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::boolean NotBreathing_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< NotBreathing_type, char > NotBreathing_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const NotBreathing_type&
NotBreathing () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
NotBreathing_type&
NotBreathing ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
NotBreathing (const NotBreathing_type& x);
//@}
/**
* @name TopBreathTotalVolume_L
*
* @brief Accessor and modifier functions for the %TopBreathTotalVolume_L
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ TopBreathTotalVolume_L_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< TopBreathTotalVolume_L_type, char, ::xsd::cxx::tree::schema_type::double_ > TopBreathTotalVolume_L_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const TopBreathTotalVolume_L_type&
TopBreathTotalVolume_L () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
TopBreathTotalVolume_L_type&
TopBreathTotalVolume_L ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
TopBreathTotalVolume_L (const TopBreathTotalVolume_L_type& x);
//@}
/**
* @name TopBreathAlveoliVolume_L
*
* @brief Accessor and modifier functions for the %TopBreathAlveoliVolume_L
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ TopBreathAlveoliVolume_L_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< TopBreathAlveoliVolume_L_type, char, ::xsd::cxx::tree::schema_type::double_ > TopBreathAlveoliVolume_L_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const TopBreathAlveoliVolume_L_type&
TopBreathAlveoliVolume_L () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
TopBreathAlveoliVolume_L_type&
TopBreathAlveoliVolume_L ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
TopBreathAlveoliVolume_L (const TopBreathAlveoliVolume_L_type& x);
//@}
/**
* @name TopBreathDeadSpaceVolume_L
*
* @brief Accessor and modifier functions for the %TopBreathDeadSpaceVolume_L
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ TopBreathDeadSpaceVolume_L_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< TopBreathDeadSpaceVolume_L_type, char, ::xsd::cxx::tree::schema_type::double_ > TopBreathDeadSpaceVolume_L_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const TopBreathDeadSpaceVolume_L_type&
TopBreathDeadSpaceVolume_L () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
TopBreathDeadSpaceVolume_L_type&
TopBreathDeadSpaceVolume_L ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
TopBreathDeadSpaceVolume_L (const TopBreathDeadSpaceVolume_L_type& x);
//@}
/**
* @name TopBreathPleuralPressure_cmH2O
*
* @brief Accessor and modifier functions for the %TopBreathPleuralPressure_cmH2O
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ TopBreathPleuralPressure_cmH2O_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< TopBreathPleuralPressure_cmH2O_type, char, ::xsd::cxx::tree::schema_type::double_ > TopBreathPleuralPressure_cmH2O_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const TopBreathPleuralPressure_cmH2O_type&
TopBreathPleuralPressure_cmH2O () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
TopBreathPleuralPressure_cmH2O_type&
TopBreathPleuralPressure_cmH2O ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
TopBreathPleuralPressure_cmH2O (const TopBreathPleuralPressure_cmH2O_type& x);
//@}
/**
* @name LastCardiacCycleBloodPH
*
* @brief Accessor and modifier functions for the %LastCardiacCycleBloodPH
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ LastCardiacCycleBloodPH_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< LastCardiacCycleBloodPH_type, char, ::xsd::cxx::tree::schema_type::double_ > LastCardiacCycleBloodPH_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const LastCardiacCycleBloodPH_type&
LastCardiacCycleBloodPH () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
LastCardiacCycleBloodPH_type&
LastCardiacCycleBloodPH ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
LastCardiacCycleBloodPH (const LastCardiacCycleBloodPH_type& x);
//@}
/**
* @name PreviousTotalLungVolume_L
*
* @brief Accessor and modifier functions for the %PreviousTotalLungVolume_L
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ PreviousTotalLungVolume_L_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< PreviousTotalLungVolume_L_type, char, ::xsd::cxx::tree::schema_type::double_ > PreviousTotalLungVolume_L_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const PreviousTotalLungVolume_L_type&
PreviousTotalLungVolume_L () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
PreviousTotalLungVolume_L_type&
PreviousTotalLungVolume_L ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
PreviousTotalLungVolume_L (const PreviousTotalLungVolume_L_type& x);
//@}
/**
* @name BloodPHRunningAverage
*
* @brief Accessor and modifier functions for the %BloodPHRunningAverage
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::RunningAverageData BloodPHRunningAverage_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< BloodPHRunningAverage_type, char > BloodPHRunningAverage_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const BloodPHRunningAverage_type&
BloodPHRunningAverage () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
BloodPHRunningAverage_type&
BloodPHRunningAverage ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
BloodPHRunningAverage (const BloodPHRunningAverage_type& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
BloodPHRunningAverage (::std::unique_ptr< BloodPHRunningAverage_type > p);
//@}
/**
* @name BreathingCycle
*
* @brief Accessor and modifier functions for the %BreathingCycle
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::boolean BreathingCycle_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< BreathingCycle_type, char > BreathingCycle_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const BreathingCycle_type&
BreathingCycle () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
BreathingCycle_type&
BreathingCycle ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
BreathingCycle (const BreathingCycle_type& x);
//@}
/**
* @name ArterialOxygenPressure_mmHg
*
* @brief Accessor and modifier functions for the %ArterialOxygenPressure_mmHg
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ ArterialOxygenPressure_mmHg_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< ArterialOxygenPressure_mmHg_type, char, ::xsd::cxx::tree::schema_type::double_ > ArterialOxygenPressure_mmHg_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const ArterialOxygenPressure_mmHg_type&
ArterialOxygenPressure_mmHg () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
ArterialOxygenPressure_mmHg_type&
ArterialOxygenPressure_mmHg ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
ArterialOxygenPressure_mmHg (const ArterialOxygenPressure_mmHg_type& x);
//@}
/**
* @name ArterialCarbonDioxidePressure_mmHg
*
* @brief Accessor and modifier functions for the %ArterialCarbonDioxidePressure_mmHg
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ ArterialCarbonDioxidePressure_mmHg_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< ArterialCarbonDioxidePressure_mmHg_type, char, ::xsd::cxx::tree::schema_type::double_ > ArterialCarbonDioxidePressure_mmHg_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const ArterialCarbonDioxidePressure_mmHg_type&
ArterialCarbonDioxidePressure_mmHg () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
ArterialCarbonDioxidePressure_mmHg_type&
ArterialCarbonDioxidePressure_mmHg ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
ArterialCarbonDioxidePressure_mmHg (const ArterialCarbonDioxidePressure_mmHg_type& x);
//@}
/**
* @name ArterialOxygenAverage_mmHg
*
* @brief Accessor and modifier functions for the %ArterialOxygenAverage_mmHg
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::RunningAverageData ArterialOxygenAverage_mmHg_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< ArterialOxygenAverage_mmHg_type, char > ArterialOxygenAverage_mmHg_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const ArterialOxygenAverage_mmHg_type&
ArterialOxygenAverage_mmHg () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
ArterialOxygenAverage_mmHg_type&
ArterialOxygenAverage_mmHg ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
ArterialOxygenAverage_mmHg (const ArterialOxygenAverage_mmHg_type& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
ArterialOxygenAverage_mmHg (::std::unique_ptr< ArterialOxygenAverage_mmHg_type > p);
//@}
/**
* @name ArterialCarbonDioxideAverage_mmHg
*
* @brief Accessor and modifier functions for the %ArterialCarbonDioxideAverage_mmHg
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::RunningAverageData ArterialCarbonDioxideAverage_mmHg_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< ArterialCarbonDioxideAverage_mmHg_type, char > ArterialCarbonDioxideAverage_mmHg_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const ArterialCarbonDioxideAverage_mmHg_type&
ArterialCarbonDioxideAverage_mmHg () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
ArterialCarbonDioxideAverage_mmHg_type&
ArterialCarbonDioxideAverage_mmHg ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
ArterialCarbonDioxideAverage_mmHg (const ArterialCarbonDioxideAverage_mmHg_type& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
ArterialCarbonDioxideAverage_mmHg (::std::unique_ptr< ArterialCarbonDioxideAverage_mmHg_type > p);
//@}
/**
* @name BreathingCycleTime_s
*
* @brief Accessor and modifier functions for the %BreathingCycleTime_s
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ BreathingCycleTime_s_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< BreathingCycleTime_s_type, char, ::xsd::cxx::tree::schema_type::double_ > BreathingCycleTime_s_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const BreathingCycleTime_s_type&
BreathingCycleTime_s () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
BreathingCycleTime_s_type&
BreathingCycleTime_s ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
BreathingCycleTime_s (const BreathingCycleTime_s_type& x);
//@}
/**
* @name BreathTimeExhale_min
*
* @brief Accessor and modifier functions for the %BreathTimeExhale_min
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ BreathTimeExhale_min_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< BreathTimeExhale_min_type, char, ::xsd::cxx::tree::schema_type::double_ > BreathTimeExhale_min_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const BreathTimeExhale_min_type&
BreathTimeExhale_min () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
BreathTimeExhale_min_type&
BreathTimeExhale_min ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
BreathTimeExhale_min (const BreathTimeExhale_min_type& x);
//@}
/**
* @name DefaultDrivePressure_cmH2O
*
* @brief Accessor and modifier functions for the %DefaultDrivePressure_cmH2O
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ DefaultDrivePressure_cmH2O_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< DefaultDrivePressure_cmH2O_type, char, ::xsd::cxx::tree::schema_type::double_ > DefaultDrivePressure_cmH2O_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const DefaultDrivePressure_cmH2O_type&
DefaultDrivePressure_cmH2O () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
DefaultDrivePressure_cmH2O_type&
DefaultDrivePressure_cmH2O ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
DefaultDrivePressure_cmH2O (const DefaultDrivePressure_cmH2O_type& x);
//@}
/**
* @name DriverPressure_cmH2O
*
* @brief Accessor and modifier functions for the %DriverPressure_cmH2O
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ DriverPressure_cmH2O_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< DriverPressure_cmH2O_type, char, ::xsd::cxx::tree::schema_type::double_ > DriverPressure_cmH2O_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const DriverPressure_cmH2O_type&
DriverPressure_cmH2O () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
DriverPressure_cmH2O_type&
DriverPressure_cmH2O ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
DriverPressure_cmH2O (const DriverPressure_cmH2O_type& x);
//@}
/**
* @name DriverPressureMin_cmH2O
*
* @brief Accessor and modifier functions for the %DriverPressureMin_cmH2O
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ DriverPressureMin_cmH2O_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< DriverPressureMin_cmH2O_type, char, ::xsd::cxx::tree::schema_type::double_ > DriverPressureMin_cmH2O_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const DriverPressureMin_cmH2O_type&
DriverPressureMin_cmH2O () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
DriverPressureMin_cmH2O_type&
DriverPressureMin_cmH2O ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
DriverPressureMin_cmH2O (const DriverPressureMin_cmH2O_type& x);
//@}
/**
* @name ElapsedBreathingCycleTime_min
*
* @brief Accessor and modifier functions for the %ElapsedBreathingCycleTime_min
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ ElapsedBreathingCycleTime_min_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< ElapsedBreathingCycleTime_min_type, char, ::xsd::cxx::tree::schema_type::double_ > ElapsedBreathingCycleTime_min_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const ElapsedBreathingCycleTime_min_type&
ElapsedBreathingCycleTime_min () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
ElapsedBreathingCycleTime_min_type&
ElapsedBreathingCycleTime_min ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
ElapsedBreathingCycleTime_min (const ElapsedBreathingCycleTime_min_type& x);
//@}
/**
* @name IEscaleFactor
*
* @brief Accessor and modifier functions for the %IEscaleFactor
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ IEscaleFactor_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< IEscaleFactor_type, char, ::xsd::cxx::tree::schema_type::double_ > IEscaleFactor_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const IEscaleFactor_type&
IEscaleFactor () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
IEscaleFactor_type&
IEscaleFactor ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
IEscaleFactor (const IEscaleFactor_type& x);
//@}
/**
* @name InstantaneousFunctionalResidualCapacity_L
*
* @brief Accessor and modifier functions for the %InstantaneousFunctionalResidualCapacity_L
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ InstantaneousFunctionalResidualCapacity_L_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< InstantaneousFunctionalResidualCapacity_L_type, char, ::xsd::cxx::tree::schema_type::double_ > InstantaneousFunctionalResidualCapacity_L_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const InstantaneousFunctionalResidualCapacity_L_type&
InstantaneousFunctionalResidualCapacity_L () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
InstantaneousFunctionalResidualCapacity_L_type&
InstantaneousFunctionalResidualCapacity_L ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
InstantaneousFunctionalResidualCapacity_L (const InstantaneousFunctionalResidualCapacity_L_type& x);
//@}
/**
* @name MaxDriverPressure_cmH2O
*
* @brief Accessor and modifier functions for the %MaxDriverPressure_cmH2O
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ MaxDriverPressure_cmH2O_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< MaxDriverPressure_cmH2O_type, char, ::xsd::cxx::tree::schema_type::double_ > MaxDriverPressure_cmH2O_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const MaxDriverPressure_cmH2O_type&
MaxDriverPressure_cmH2O () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
MaxDriverPressure_cmH2O_type&
MaxDriverPressure_cmH2O ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
MaxDriverPressure_cmH2O (const MaxDriverPressure_cmH2O_type& x);
//@}
/**
* @name PeakRespiratoryDrivePressure_cmH2O
*
* @brief Accessor and modifier functions for the %PeakRespiratoryDrivePressure_cmH2O
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ PeakRespiratoryDrivePressure_cmH2O_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< PeakRespiratoryDrivePressure_cmH2O_type, char, ::xsd::cxx::tree::schema_type::double_ > PeakRespiratoryDrivePressure_cmH2O_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const PeakRespiratoryDrivePressure_cmH2O_type&
PeakRespiratoryDrivePressure_cmH2O () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
PeakRespiratoryDrivePressure_cmH2O_type&
PeakRespiratoryDrivePressure_cmH2O ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
PeakRespiratoryDrivePressure_cmH2O (const PeakRespiratoryDrivePressure_cmH2O_type& x);
//@}
/**
* @name VentilationFrequency_Per_min
*
* @brief Accessor and modifier functions for the %VentilationFrequency_Per_min
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ VentilationFrequency_Per_min_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< VentilationFrequency_Per_min_type, char, ::xsd::cxx::tree::schema_type::double_ > VentilationFrequency_Per_min_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const VentilationFrequency_Per_min_type&
VentilationFrequency_Per_min () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
VentilationFrequency_Per_min_type&
VentilationFrequency_Per_min ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
VentilationFrequency_Per_min (const VentilationFrequency_Per_min_type& x);
//@}
/**
* @name ConsciousBreathing
*
* @brief Accessor and modifier functions for the %ConsciousBreathing
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::boolean ConsciousBreathing_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< ConsciousBreathing_type, char > ConsciousBreathing_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const ConsciousBreathing_type&
ConsciousBreathing () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
ConsciousBreathing_type&
ConsciousBreathing ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
ConsciousBreathing (const ConsciousBreathing_type& x);
//@}
/**
* @name ConsciousRespirationPeriod_s
*
* @brief Accessor and modifier functions for the %ConsciousRespirationPeriod_s
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ ConsciousRespirationPeriod_s_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< ConsciousRespirationPeriod_s_type, char, ::xsd::cxx::tree::schema_type::double_ > ConsciousRespirationPeriod_s_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const ConsciousRespirationPeriod_s_type&
ConsciousRespirationPeriod_s () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
ConsciousRespirationPeriod_s_type&
ConsciousRespirationPeriod_s ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
ConsciousRespirationPeriod_s (const ConsciousRespirationPeriod_s_type& x);
//@}
/**
* @name ConsciousRespirationRemainingPeriod_s
*
* @brief Accessor and modifier functions for the %ConsciousRespirationRemainingPeriod_s
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ ConsciousRespirationRemainingPeriod_s_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< ConsciousRespirationRemainingPeriod_s_type, char, ::xsd::cxx::tree::schema_type::double_ > ConsciousRespirationRemainingPeriod_s_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const ConsciousRespirationRemainingPeriod_s_type&
ConsciousRespirationRemainingPeriod_s () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
ConsciousRespirationRemainingPeriod_s_type&
ConsciousRespirationRemainingPeriod_s ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
ConsciousRespirationRemainingPeriod_s (const ConsciousRespirationRemainingPeriod_s_type& x);
//@}
/**
* @name ExpiratoryReserveVolumeFraction
*
* @brief Accessor and modifier functions for the %ExpiratoryReserveVolumeFraction
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ ExpiratoryReserveVolumeFraction_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< ExpiratoryReserveVolumeFraction_type, char, ::xsd::cxx::tree::schema_type::double_ > ExpiratoryReserveVolumeFraction_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const ExpiratoryReserveVolumeFraction_type&
ExpiratoryReserveVolumeFraction () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
ExpiratoryReserveVolumeFraction_type&
ExpiratoryReserveVolumeFraction ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
ExpiratoryReserveVolumeFraction (const ExpiratoryReserveVolumeFraction_type& x);
//@}
/**
* @name InspiratoryCapacityFraction
*
* @brief Accessor and modifier functions for the %InspiratoryCapacityFraction
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ InspiratoryCapacityFraction_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< InspiratoryCapacityFraction_type, char, ::xsd::cxx::tree::schema_type::double_ > InspiratoryCapacityFraction_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const InspiratoryCapacityFraction_type&
InspiratoryCapacityFraction () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
InspiratoryCapacityFraction_type&
InspiratoryCapacityFraction ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
InspiratoryCapacityFraction (const InspiratoryCapacityFraction_type& x);
//@}
/**
* @name ConsciousStartPressure_cmH2O
*
* @brief Accessor and modifier functions for the %ConsciousStartPressure_cmH2O
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ ConsciousStartPressure_cmH2O_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< ConsciousStartPressure_cmH2O_type, char, ::xsd::cxx::tree::schema_type::double_ > ConsciousStartPressure_cmH2O_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const ConsciousStartPressure_cmH2O_type&
ConsciousStartPressure_cmH2O () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
ConsciousStartPressure_cmH2O_type&
ConsciousStartPressure_cmH2O ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
ConsciousStartPressure_cmH2O (const ConsciousStartPressure_cmH2O_type& x);
//@}
/**
* @name ConsciousEndPressure_cmH2O
*
* @brief Accessor and modifier functions for the %ConsciousEndPressure_cmH2O
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ ConsciousEndPressure_cmH2O_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< ConsciousEndPressure_cmH2O_type, char, ::xsd::cxx::tree::schema_type::double_ > ConsciousEndPressure_cmH2O_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const ConsciousEndPressure_cmH2O_type&
ConsciousEndPressure_cmH2O () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
ConsciousEndPressure_cmH2O_type&
ConsciousEndPressure_cmH2O ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
ConsciousEndPressure_cmH2O (const ConsciousEndPressure_cmH2O_type& x);
//@}
/**
* @name HadAirwayObstruction
*
* @brief Accessor and modifier functions for the %HadAirwayObstruction
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::boolean HadAirwayObstruction_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< HadAirwayObstruction_type, char > HadAirwayObstruction_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const HadAirwayObstruction_type&
HadAirwayObstruction () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
HadAirwayObstruction_type&
HadAirwayObstruction ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
HadAirwayObstruction (const HadAirwayObstruction_type& x);
//@}
/**
* @name HadBronchoconstriction
*
* @brief Accessor and modifier functions for the %HadBronchoconstriction
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::boolean HadBronchoconstriction_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< HadBronchoconstriction_type, char > HadBronchoconstriction_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const HadBronchoconstriction_type&
HadBronchoconstriction () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
HadBronchoconstriction_type&
HadBronchoconstriction ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
HadBronchoconstriction (const HadBronchoconstriction_type& x);
//@}
/**
* @name Constructors
*/
//@{
/**
* @brief Default constructor.
*
* Note that this constructor leaves required elements and
* attributes uninitialized.
*/
BioGearsRespiratorySystemData ();
/**
* @brief Create an instance from the ultimate base and
* initializers for required elements and attributes.
*/
BioGearsRespiratorySystemData (const InitialExpiratoryReserveVolume_L_type&,
const InitialFunctionalResidualCapacity_L_type&,
const InitialInspiratoryCapacity_L_type&,
const InitialResidualVolume_L_type&,
const NotBreathing_type&,
const TopBreathTotalVolume_L_type&,
const TopBreathAlveoliVolume_L_type&,
const TopBreathDeadSpaceVolume_L_type&,
const TopBreathPleuralPressure_cmH2O_type&,
const LastCardiacCycleBloodPH_type&,
const PreviousTotalLungVolume_L_type&,
const BloodPHRunningAverage_type&,
const BreathingCycle_type&,
const ArterialOxygenPressure_mmHg_type&,
const ArterialCarbonDioxidePressure_mmHg_type&,
const ArterialOxygenAverage_mmHg_type&,
const ArterialCarbonDioxideAverage_mmHg_type&,
const BreathingCycleTime_s_type&,
const BreathTimeExhale_min_type&,
const DefaultDrivePressure_cmH2O_type&,
const DriverPressure_cmH2O_type&,
const DriverPressureMin_cmH2O_type&,
const ElapsedBreathingCycleTime_min_type&,
const IEscaleFactor_type&,
const InstantaneousFunctionalResidualCapacity_L_type&,
const MaxDriverPressure_cmH2O_type&,
const PeakRespiratoryDrivePressure_cmH2O_type&,
const VentilationFrequency_Per_min_type&,
const ConsciousBreathing_type&,
const ConsciousRespirationPeriod_s_type&,
const ConsciousRespirationRemainingPeriod_s_type&,
const ExpiratoryReserveVolumeFraction_type&,
const InspiratoryCapacityFraction_type&,
const ConsciousStartPressure_cmH2O_type&,
const ConsciousEndPressure_cmH2O_type&,
const HadAirwayObstruction_type&,
const HadBronchoconstriction_type&);
/**
* @brief Create an instance from the ultimate base and
* initializers for required elements and attributes
* (::std::unique_ptr version).
*
* This constructor will try to use the passed values directly
* instead of making copies.
*/
BioGearsRespiratorySystemData (const InitialExpiratoryReserveVolume_L_type&,
const InitialFunctionalResidualCapacity_L_type&,
const InitialInspiratoryCapacity_L_type&,
const InitialResidualVolume_L_type&,
const NotBreathing_type&,
const TopBreathTotalVolume_L_type&,
const TopBreathAlveoliVolume_L_type&,
const TopBreathDeadSpaceVolume_L_type&,
const TopBreathPleuralPressure_cmH2O_type&,
const LastCardiacCycleBloodPH_type&,
const PreviousTotalLungVolume_L_type&,
::std::unique_ptr< BloodPHRunningAverage_type >,
const BreathingCycle_type&,
const ArterialOxygenPressure_mmHg_type&,
const ArterialCarbonDioxidePressure_mmHg_type&,
::std::unique_ptr< ArterialOxygenAverage_mmHg_type >,
::std::unique_ptr< ArterialCarbonDioxideAverage_mmHg_type >,
const BreathingCycleTime_s_type&,
const BreathTimeExhale_min_type&,
const DefaultDrivePressure_cmH2O_type&,
const DriverPressure_cmH2O_type&,
const DriverPressureMin_cmH2O_type&,
const ElapsedBreathingCycleTime_min_type&,
const IEscaleFactor_type&,
const InstantaneousFunctionalResidualCapacity_L_type&,
const MaxDriverPressure_cmH2O_type&,
const PeakRespiratoryDrivePressure_cmH2O_type&,
const VentilationFrequency_Per_min_type&,
const ConsciousBreathing_type&,
const ConsciousRespirationPeriod_s_type&,
const ConsciousRespirationRemainingPeriod_s_type&,
const ExpiratoryReserveVolumeFraction_type&,
const InspiratoryCapacityFraction_type&,
const ConsciousStartPressure_cmH2O_type&,
const ConsciousEndPressure_cmH2O_type&,
const HadAirwayObstruction_type&,
const HadBronchoconstriction_type&);
/**
* @brief Create an instance from a DOM element.
*
* @param e A DOM element to extract the data from.
* @param f Flags to create the new instance with.
* @param c A pointer to the object that will contain the new
* instance.
*/
BioGearsRespiratorySystemData (const ::xercesc::DOMElement& e,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
/**
* @brief Copy constructor.
*
* @param x An instance to make a copy of.
* @param f Flags to create the copy with.
* @param c A pointer to the object that will contain the copy.
*
* For polymorphic object models use the @c _clone function instead.
*/
BioGearsRespiratorySystemData (const BioGearsRespiratorySystemData& x,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
/**
* @brief Copy the instance polymorphically.
*
* @param f Flags to create the copy with.
* @param c A pointer to the object that will contain the copy.
* @return A pointer to the dynamically allocated copy.
*
* This function ensures that the dynamic type of the instance is
* used for copying and should be used for polymorphic object
* models instead of the copy constructor.
*/
virtual BioGearsRespiratorySystemData*
_clone (::xml_schema::flags f = 0,
::xml_schema::container* c = 0) const;
/**
* @brief Copy assignment operator.
*
* @param x An instance to make a copy of.
* @return A reference to itself.
*
* For polymorphic object models use the @c _clone function instead.
*/
BioGearsRespiratorySystemData&
operator= (const BioGearsRespiratorySystemData& x);
//@}
/**
* @brief Destructor.
*/
virtual
~BioGearsRespiratorySystemData ();
// Implementation.
//
//@cond
protected:
void
parse (::xsd::cxx::xml::dom::parser< char >&,
::xml_schema::flags);
protected:
::xsd::cxx::tree::one< InitialExpiratoryReserveVolume_L_type > InitialExpiratoryReserveVolume_L_;
::xsd::cxx::tree::one< InitialFunctionalResidualCapacity_L_type > InitialFunctionalResidualCapacity_L_;
::xsd::cxx::tree::one< InitialInspiratoryCapacity_L_type > InitialInspiratoryCapacity_L_;
::xsd::cxx::tree::one< InitialResidualVolume_L_type > InitialResidualVolume_L_;
::xsd::cxx::tree::one< NotBreathing_type > NotBreathing_;
::xsd::cxx::tree::one< TopBreathTotalVolume_L_type > TopBreathTotalVolume_L_;
::xsd::cxx::tree::one< TopBreathAlveoliVolume_L_type > TopBreathAlveoliVolume_L_;
::xsd::cxx::tree::one< TopBreathDeadSpaceVolume_L_type > TopBreathDeadSpaceVolume_L_;
::xsd::cxx::tree::one< TopBreathPleuralPressure_cmH2O_type > TopBreathPleuralPressure_cmH2O_;
::xsd::cxx::tree::one< LastCardiacCycleBloodPH_type > LastCardiacCycleBloodPH_;
::xsd::cxx::tree::one< PreviousTotalLungVolume_L_type > PreviousTotalLungVolume_L_;
::xsd::cxx::tree::one< BloodPHRunningAverage_type > BloodPHRunningAverage_;
::xsd::cxx::tree::one< BreathingCycle_type > BreathingCycle_;
::xsd::cxx::tree::one< ArterialOxygenPressure_mmHg_type > ArterialOxygenPressure_mmHg_;
::xsd::cxx::tree::one< ArterialCarbonDioxidePressure_mmHg_type > ArterialCarbonDioxidePressure_mmHg_;
::xsd::cxx::tree::one< ArterialOxygenAverage_mmHg_type > ArterialOxygenAverage_mmHg_;
::xsd::cxx::tree::one< ArterialCarbonDioxideAverage_mmHg_type > ArterialCarbonDioxideAverage_mmHg_;
::xsd::cxx::tree::one< BreathingCycleTime_s_type > BreathingCycleTime_s_;
::xsd::cxx::tree::one< BreathTimeExhale_min_type > BreathTimeExhale_min_;
::xsd::cxx::tree::one< DefaultDrivePressure_cmH2O_type > DefaultDrivePressure_cmH2O_;
::xsd::cxx::tree::one< DriverPressure_cmH2O_type > DriverPressure_cmH2O_;
::xsd::cxx::tree::one< DriverPressureMin_cmH2O_type > DriverPressureMin_cmH2O_;
::xsd::cxx::tree::one< ElapsedBreathingCycleTime_min_type > ElapsedBreathingCycleTime_min_;
::xsd::cxx::tree::one< IEscaleFactor_type > IEscaleFactor_;
::xsd::cxx::tree::one< InstantaneousFunctionalResidualCapacity_L_type > InstantaneousFunctionalResidualCapacity_L_;
::xsd::cxx::tree::one< MaxDriverPressure_cmH2O_type > MaxDriverPressure_cmH2O_;
::xsd::cxx::tree::one< PeakRespiratoryDrivePressure_cmH2O_type > PeakRespiratoryDrivePressure_cmH2O_;
::xsd::cxx::tree::one< VentilationFrequency_Per_min_type > VentilationFrequency_Per_min_;
::xsd::cxx::tree::one< ConsciousBreathing_type > ConsciousBreathing_;
::xsd::cxx::tree::one< ConsciousRespirationPeriod_s_type > ConsciousRespirationPeriod_s_;
::xsd::cxx::tree::one< ConsciousRespirationRemainingPeriod_s_type > ConsciousRespirationRemainingPeriod_s_;
::xsd::cxx::tree::one< ExpiratoryReserveVolumeFraction_type > ExpiratoryReserveVolumeFraction_;
::xsd::cxx::tree::one< InspiratoryCapacityFraction_type > InspiratoryCapacityFraction_;
::xsd::cxx::tree::one< ConsciousStartPressure_cmH2O_type > ConsciousStartPressure_cmH2O_;
::xsd::cxx::tree::one< ConsciousEndPressure_cmH2O_type > ConsciousEndPressure_cmH2O_;
::xsd::cxx::tree::one< HadAirwayObstruction_type > HadAirwayObstruction_;
::xsd::cxx::tree::one< HadBronchoconstriction_type > HadBronchoconstriction_;
//@endcond
};
/**
* @brief Class corresponding to the %BioGearsTissueSystemData schema type.
*
* @nosubgrouping
*/
class BIOGEARS_CDM_API BioGearsTissueSystemData: public ::mil::tatrc::physiology::datamodel::TissueSystemData
{
public:
/**
* @name RestingPatientMass_kg
*
* @brief Accessor and modifier functions for the %RestingPatientMass_kg
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ RestingPatientMass_kg_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< RestingPatientMass_kg_type, char, ::xsd::cxx::tree::schema_type::double_ > RestingPatientMass_kg_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const RestingPatientMass_kg_type&
RestingPatientMass_kg () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
RestingPatientMass_kg_type&
RestingPatientMass_kg ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
RestingPatientMass_kg (const RestingPatientMass_kg_type& x);
//@}
/**
* @name RestingFluidMass_kg
*
* @brief Accessor and modifier functions for the %RestingFluidMass_kg
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::xml_schema::double_ RestingFluidMass_kg_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< RestingFluidMass_kg_type, char, ::xsd::cxx::tree::schema_type::double_ > RestingFluidMass_kg_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const RestingFluidMass_kg_type&
RestingFluidMass_kg () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
RestingFluidMass_kg_type&
RestingFluidMass_kg ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
RestingFluidMass_kg (const RestingFluidMass_kg_type& x);
//@}
/**
* @name O2ConsumedRunningAverage_mL_Per_s
*
* @brief Accessor and modifier functions for the %O2ConsumedRunningAverage_mL_Per_s
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::RunningAverageData O2ConsumedRunningAverage_mL_Per_s_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< O2ConsumedRunningAverage_mL_Per_s_type, char > O2ConsumedRunningAverage_mL_Per_s_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const O2ConsumedRunningAverage_mL_Per_s_type&
O2ConsumedRunningAverage_mL_Per_s () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
O2ConsumedRunningAverage_mL_Per_s_type&
O2ConsumedRunningAverage_mL_Per_s ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
O2ConsumedRunningAverage_mL_Per_s (const O2ConsumedRunningAverage_mL_Per_s_type& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
O2ConsumedRunningAverage_mL_Per_s (::std::unique_ptr< O2ConsumedRunningAverage_mL_Per_s_type > p);
//@}
/**
* @name CO2ProducedRunningAverage_mL_Per_s
*
* @brief Accessor and modifier functions for the %CO2ProducedRunningAverage_mL_Per_s
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::RunningAverageData CO2ProducedRunningAverage_mL_Per_s_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< CO2ProducedRunningAverage_mL_Per_s_type, char > CO2ProducedRunningAverage_mL_Per_s_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const CO2ProducedRunningAverage_mL_Per_s_type&
CO2ProducedRunningAverage_mL_Per_s () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
CO2ProducedRunningAverage_mL_Per_s_type&
CO2ProducedRunningAverage_mL_Per_s ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
CO2ProducedRunningAverage_mL_Per_s (const CO2ProducedRunningAverage_mL_Per_s_type& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
CO2ProducedRunningAverage_mL_Per_s (::std::unique_ptr< CO2ProducedRunningAverage_mL_Per_s_type > p);
//@}
/**
* @name RespiratoryQuotientRunningAverage
*
* @brief Accessor and modifier functions for the %RespiratoryQuotientRunningAverage
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::RunningAverageData RespiratoryQuotientRunningAverage_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< RespiratoryQuotientRunningAverage_type, char > RespiratoryQuotientRunningAverage_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const RespiratoryQuotientRunningAverage_type&
RespiratoryQuotientRunningAverage () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
RespiratoryQuotientRunningAverage_type&
RespiratoryQuotientRunningAverage ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
RespiratoryQuotientRunningAverage (const RespiratoryQuotientRunningAverage_type& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
RespiratoryQuotientRunningAverage (::std::unique_ptr< RespiratoryQuotientRunningAverage_type > p);
//@}
/**
* @name FatigueRunningAverage
*
* @brief Accessor and modifier functions for the %FatigueRunningAverage
* required element.
*/
//@{
/**
* @brief Element type.
*/
typedef ::mil::tatrc::physiology::datamodel::RunningAverageData FatigueRunningAverage_type;
/**
* @brief Element traits type.
*/
typedef ::xsd::cxx::tree::traits< FatigueRunningAverage_type, char > FatigueRunningAverage_traits;
/**
* @brief Return a read-only (constant) reference to the element.
*
* @return A constant reference to the element.
*/
const FatigueRunningAverage_type&
FatigueRunningAverage () const;
/**
* @brief Return a read-write reference to the element.
*
* @return A reference to the element.
*/
FatigueRunningAverage_type&
FatigueRunningAverage ();
/**
* @brief Set the element value.
*
* @param x A new value to set.
*
* This function makes a copy of its argument and sets it as
* the new value of the element.
*/
void
FatigueRunningAverage (const FatigueRunningAverage_type& x);
/**
* @brief Set the element value without copying.
*
* @param p A new value to use.
*
* This function will try to use the passed value directly
* instead of making a copy.
*/
void
FatigueRunningAverage (::std::unique_ptr< FatigueRunningAverage_type > p);
//@}
/**
* @name Constructors
*/
//@{
/**
* @brief Default constructor.
*
* Note that this constructor leaves required elements and
* attributes uninitialized.
*/
BioGearsTissueSystemData ();
/**
* @brief Create an instance from the ultimate base and
* initializers for required elements and attributes.
*/
BioGearsTissueSystemData (const RestingPatientMass_kg_type&,
const RestingFluidMass_kg_type&,
const O2ConsumedRunningAverage_mL_Per_s_type&,
const CO2ProducedRunningAverage_mL_Per_s_type&,
const RespiratoryQuotientRunningAverage_type&,
const FatigueRunningAverage_type&);
/**
* @brief Create an instance from the ultimate base and
* initializers for required elements and attributes
* (::std::unique_ptr version).
*
* This constructor will try to use the passed values directly
* instead of making copies.
*/
BioGearsTissueSystemData (const RestingPatientMass_kg_type&,
const RestingFluidMass_kg_type&,
::std::unique_ptr< O2ConsumedRunningAverage_mL_Per_s_type >,
::std::unique_ptr< CO2ProducedRunningAverage_mL_Per_s_type >,
::std::unique_ptr< RespiratoryQuotientRunningAverage_type >,
::std::unique_ptr< FatigueRunningAverage_type >);
/**
* @brief Create an instance from a DOM element.
*
* @param e A DOM element to extract the data from.
* @param f Flags to create the new instance with.
* @param c A pointer to the object that will contain the new
* instance.
*/
BioGearsTissueSystemData (const ::xercesc::DOMElement& e,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
/**
* @brief Copy constructor.
*
* @param x An instance to make a copy of.
* @param f Flags to create the copy with.
* @param c A pointer to the object that will contain the copy.
*
* For polymorphic object models use the @c _clone function instead.
*/
BioGearsTissueSystemData (const BioGearsTissueSystemData& x,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
/**
* @brief Copy the instance polymorphically.
*
* @param f Flags to create the copy with.
* @param c A pointer to the object that will contain the copy.
* @return A pointer to the dynamically allocated copy.
*
* This function ensures that the dynamic type of the instance is
* used for copying and should be used for polymorphic object
* models instead of the copy constructor.
*/
virtual BioGearsTissueSystemData*
_clone (::xml_schema::flags f = 0,
::xml_schema::container* c = 0) const;
/**
* @brief Copy assignment operator.
*
* @param x An instance to make a copy of.
* @return A reference to itself.
*
* For polymorphic object models use the @c _clone function instead.
*/
BioGearsTissueSystemData&
operator= (const BioGearsTissueSystemData& x);
//@}
/**
* @brief Destructor.
*/
virtual
~BioGearsTissueSystemData ();
// Implementation.
//
//@cond
protected:
void
parse (::xsd::cxx::xml::dom::parser< char >&,
::xml_schema::flags);
protected:
::xsd::cxx::tree::one< RestingPatientMass_kg_type > RestingPatientMass_kg_;
::xsd::cxx::tree::one< RestingFluidMass_kg_type > RestingFluidMass_kg_;
::xsd::cxx::tree::one< O2ConsumedRunningAverage_mL_Per_s_type > O2ConsumedRunningAverage_mL_Per_s_;
::xsd::cxx::tree::one< CO2ProducedRunningAverage_mL_Per_s_type > CO2ProducedRunningAverage_mL_Per_s_;
::xsd::cxx::tree::one< RespiratoryQuotientRunningAverage_type > RespiratoryQuotientRunningAverage_;
::xsd::cxx::tree::one< FatigueRunningAverage_type > FatigueRunningAverage_;
//@endcond
};
}
}
}
}
#include <iosfwd>
namespace mil
{
namespace tatrc
{
namespace physiology
{
namespace datamodel
{
BIOGEARS_CDM_API
::std::ostream&
operator<< (::std::ostream&, const BioGearsBloodChemistrySystemData&);
BIOGEARS_CDM_API
::std::ostream&
operator<< (::std::ostream&, const BioGearsCardiovascularSystemData&);
BIOGEARS_CDM_API
::std::ostream&
operator<< (::std::ostream&, const BioGearsDrugSystemData&);
BIOGEARS_CDM_API
::std::ostream&
operator<< (::std::ostream&, const BioGearsEndocrineSystemData&);
BIOGEARS_CDM_API
::std::ostream&
operator<< (::std::ostream&, const BioGearsEnergySystemData&);
BIOGEARS_CDM_API
::std::ostream&
operator<< (::std::ostream&, const BioGearsGastrointestinalSystemData&);
BIOGEARS_CDM_API
::std::ostream&
operator<< (::std::ostream&, const BioGearsHepaticSystemData&);
BIOGEARS_CDM_API
::std::ostream&
operator<< (::std::ostream&, const BioGearsNervousSystemData&);
BIOGEARS_CDM_API
::std::ostream&
operator<< (::std::ostream&, const BioGearsRenalSystemData&);
BIOGEARS_CDM_API
::std::ostream&
operator<< (::std::ostream&, const BioGearsRespiratorySystemData&);
BIOGEARS_CDM_API
::std::ostream&
operator<< (::std::ostream&, const BioGearsTissueSystemData&);
}
}
}
}
#include <iosfwd>
#include <xercesc/sax/InputSource.hpp>
#include <xercesc/dom/DOMDocument.hpp>
#include <xercesc/dom/DOMErrorHandler.hpp>
namespace mil
{
namespace tatrc
{
namespace physiology
{
namespace datamodel
{
}
}
}
}
#include <iosfwd>
#include <xercesc/dom/DOMDocument.hpp>
#include <xercesc/dom/DOMErrorHandler.hpp>
#include <xercesc/framework/XMLFormatter.hpp>
#include <xsd/cxx/xml/dom/auto-ptr.hxx>
namespace mil
{
namespace tatrc
{
namespace physiology
{
namespace datamodel
{
BIOGEARS_CDM_API
void
operator<< (::xercesc::DOMElement&, const BioGearsBloodChemistrySystemData&);
BIOGEARS_CDM_API
void
operator<< (::xercesc::DOMElement&, const BioGearsCardiovascularSystemData&);
BIOGEARS_CDM_API
void
operator<< (::xercesc::DOMElement&, const BioGearsDrugSystemData&);
BIOGEARS_CDM_API
void
operator<< (::xercesc::DOMElement&, const BioGearsEndocrineSystemData&);
BIOGEARS_CDM_API
void
operator<< (::xercesc::DOMElement&, const BioGearsEnergySystemData&);
BIOGEARS_CDM_API
void
operator<< (::xercesc::DOMElement&, const BioGearsGastrointestinalSystemData&);
BIOGEARS_CDM_API
void
operator<< (::xercesc::DOMElement&, const BioGearsHepaticSystemData&);
BIOGEARS_CDM_API
void
operator<< (::xercesc::DOMElement&, const BioGearsNervousSystemData&);
BIOGEARS_CDM_API
void
operator<< (::xercesc::DOMElement&, const BioGearsRenalSystemData&);
BIOGEARS_CDM_API
void
operator<< (::xercesc::DOMElement&, const BioGearsRespiratorySystemData&);
BIOGEARS_CDM_API
void
operator<< (::xercesc::DOMElement&, const BioGearsTissueSystemData&);
}
}
}
}
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
#endif // CXX_OPT_BIOGEARS_CORE_SHARE_XSD__BIOGEARS_BIO_GEARS_PHYSIOLOGY_HXX
| 33.564531 | 212 | 0.548416 | vybhavramachandran |
61c86c87d786df7f481b6de133202c0141998c0a | 939 | hpp | C++ | ZeroLibraries/SpatialPartition/DynamicAabbTreeBroadPhase.hpp | RachelWilSingh/ZeroCore | e9a2f82d395e5c89fb98eceac44ce60d016dbff3 | [
"MIT"
] | 52 | 2018-09-11T17:18:35.000Z | 2022-03-13T15:28:21.000Z | ZeroLibraries/SpatialPartition/DynamicAabbTreeBroadPhase.hpp | RachelWilSingh/ZeroCore | e9a2f82d395e5c89fb98eceac44ce60d016dbff3 | [
"MIT"
] | 1,409 | 2018-09-19T18:03:43.000Z | 2021-06-09T08:33:33.000Z | ZeroLibraries/SpatialPartition/DynamicAabbTreeBroadPhase.hpp | RachelWilSingh/ZeroCore | e9a2f82d395e5c89fb98eceac44ce60d016dbff3 | [
"MIT"
] | 26 | 2018-09-11T17:16:32.000Z | 2021-11-22T06:21:19.000Z | ///////////////////////////////////////////////////////////////////////////////
///
/// \file DynamicAabbTreeBroadPhase.hpp
/// Declaration of the DynamicAabbTreeBroadPhase class.
///
/// Authors: Joshua Davis
/// Copyright 2011, DigiPen Institute of Technology
///
///////////////////////////////////////////////////////////////////////////////
#pragma once
namespace Zero
{
///The BroadPhase interface for the DynamicAabbTree. Unlike the tree itself,
///this keeps track of internal pairs and figures out what actually
///needs to be queried for self intersections.
class DynamicAabbTreeBroadPhase
: public BaseDynamicAabbTreeBroadPhase<DynamicAabbTree<void*> >
{
public:
ZilchDeclareType(TypeCopyMode::ReferenceType);
typedef DynamicAabbTree<void*> TreeType;
typedef TreeType::SelfQueryRange TreeSelfRange;
DynamicAabbTreeBroadPhase();
~DynamicAabbTreeBroadPhase();
};
}//namespace Zero
| 29.34375 | 80 | 0.619808 | RachelWilSingh |
61cda07ef3d4b0208115dc9ea8081202bc325f4d | 2,150 | cpp | C++ | proj.android/Photon-AndroidNDK_SDK/Demos/demo_memory/src/BaseView.cpp | h-iwata/MultiplayPaint | b170ec60bdda93c041ef59625ac2d6eba54d0335 | [
"MIT"
] | 1 | 2016-05-31T22:56:26.000Z | 2016-05-31T22:56:26.000Z | proj.ios_mac/Photon-iOS_SDK/Demos/demo_memory/src/BaseView.cpp | h-iwata/MultiplayPaint | b170ec60bdda93c041ef59625ac2d6eba54d0335 | [
"MIT"
] | null | null | null | proj.ios_mac/Photon-iOS_SDK/Demos/demo_memory/src/BaseView.cpp | h-iwata/MultiplayPaint | b170ec60bdda93c041ef59625ac2d6eba54d0335 | [
"MIT"
] | null | null | null | #include <stdarg.h>
#include <stdio.h>
#include "BaseView.h"
#ifdef _EG_ANDROID_PLATFORM
# include <android/log.h>
#endif
void BaseView::info(const char* format, ...)
{
fprintf(stdout, "INFO: ");
va_list argptr;
va_start(argptr, format);
vfprintf(stdout, format, argptr);
va_end(argptr);
fprintf(stdout, "\n");
#ifdef _EG_ANDROID_PLATFORM
__android_log_vprint(ANDROID_LOG_INFO, "DemoMemory", format, argptr);
#endif
}
void BaseView::warn(const char* format, ...)
{
fprintf(stderr, "WARN: ");
va_list argptr;
va_start(argptr, format);
vfprintf(stderr, format, argptr);
va_end(argptr);
fprintf(stderr, "\n");
#ifdef _EG_ANDROID_PLATFORM
__android_log_vprint(ANDROID_LOG_INFO, "DemoMemory", format, argptr);
#endif
}
void BaseView::error(const char* format, ...)
{
fprintf(stderr, "ERROR: ");
va_list argptr;
va_start(argptr, format);
vfprintf(stderr, format, argptr);
va_end(argptr);
fprintf(stderr, "\n");
#ifdef _EG_ANDROID_PLATFORM
__android_log_vprint(ANDROID_LOG_INFO, "DemoMemory", format, argptr);
#endif
}
void BaseView::onStateChange(int state, const char* stateStr, bool inLobby, bool inRoom)
{
info("state: %d/%s", state, stateStr);
}
void BaseView::refreshStateInfo(const char* stateInfo)
{
info("state info: %s", stateInfo);
}
void BaseView::refreshMessage(const char* msg)
{
info("game message: %s", msg);
}
void BaseView::setup()
{
info("setup view");
}
void BaseView::setupBoard(int tileCols, int tileRows)
{
info("setup board %dx%d", tileCols, tileRows);
}
void BaseView::updateBoard(unsigned char* tiles, unsigned char flippedTiles[2])
{
info("update board, flips: [%d, %d]", flippedTiles[0], flippedTiles[1]);
}
void BaseView::updateRoomList(const char** roomNames, unsigned int size)
{
info("room list:");
for(unsigned int i=0; i<size; ++i)
info(" %s", roomNames[i]);
}
void BaseView::updateSavedRoomList(const char** savedRoomNames, unsigned int size)
{
info("saved room list:");
for(unsigned int i=0; i<size; ++i)
{
info(" %s", savedRoomNames[i]);
}
} | 23.11828 | 90 | 0.666512 | h-iwata |
61d0fff0c28e348382846f37ee6f2a7acfc7f1ab | 3,970 | inl | C++ | include/MEL/Daq/Detail/Output.inl | mahilab/MEL | b877b2ed9cd265b1ee3c1cc623a339ec1dc73185 | [
"Zlib"
] | 6 | 2018-09-14T05:07:03.000Z | 2021-09-30T17:15:11.000Z | include/MEL/Daq/Detail/Output.inl | mahilab/MEL | b877b2ed9cd265b1ee3c1cc623a339ec1dc73185 | [
"Zlib"
] | null | null | null | include/MEL/Daq/Detail/Output.inl | mahilab/MEL | b877b2ed9cd265b1ee3c1cc623a339ec1dc73185 | [
"Zlib"
] | 3 | 2018-09-20T00:58:31.000Z | 2022-02-09T06:02:56.000Z | namespace mel {
template <typename T>
Output<T>::Output() :
Module<T>(),
enable_values_(this),
disable_values_(this),
expire_values_(this)
{ }
template <typename T>
Output<T>::Output(const ChanNums& channel_numbers) :
Module<T>(channel_numbers),
enable_values_(this),
disable_values_(this),
expire_values_(this)
{ }
template <typename T>
Output<T>::~Output() {}
template <typename T>
bool Output<T>::set_expire_values(const std::vector<T>& expire_values) {
expire_values_.set(expire_values);
return true;
}
template <typename T>
bool Output<T>::set_expire_value(ChanNum channel_number, T expire_value) {
if (Module<T>::validate_channel_number(channel_number)) {
expire_values_[channel_number] = expire_value;
return true;
}
return false;
}
template <typename T>
void Output<T>::set_enable_values(const std::vector<T>& enable_values) {
if (this->validate_channel_count(enable_values.size()))
enable_values_.set(enable_values);
}
template <typename T>
void Output<T>::set_enable_value(ChanNum channel_number, T enable_value) {
if (Module<T>::validate_channel_number(channel_number))
enable_values_[channel_number] = enable_value;
}
template <typename T>
void Output<T>::set_disable_values(const std::vector<T>& disable_values) {
if (this->validate_channel_count(disable_values.size()))
disable_values_.set(disable_values);
}
template <typename T>
void Output<T>::set_disable_value(ChanNum channel_number, T disable_value) {
if (Module<T>::validate_channel_number(channel_number))
disable_values_[channel_number] = disable_value;
}
template <typename T>
typename Output<T>::Channel Output<T>::get_channel(ChanNum channel_number) {
if (Module<T>::validate_channel_number(channel_number))
return Channel(this, channel_number);
else
return Channel();
}
template <typename T>
std::vector<typename Output<T>::Channel> Output<T>::get_channels(
const ChanNums& channel_numbers) {
std::vector<Channel> channels;
for (std::size_t i = 0; i < channel_numbers.size(); ++i)
channels.push_back(get_channel(channel_numbers[i]));
return channels;
}
template <typename T>
typename Output<T>::Channel Output<T>::operator[](ChanNum channel_number) {
return get_channel(channel_number);
}
template <typename T>
std::vector<typename Output<T>::Channel> Output<T>::operator[](
const ChanNums& channel_numbers) {
return get_channels(channel_numbers);
}
template <typename T>
bool Output<T>::on_enable() {
this->set_values(enable_values_.get());
return this->update();
}
template <typename T>
bool Output<T>::on_disable() {
this->set_values(disable_values_.get());
return this->update();
}
template <typename T>
Output<T>::Channel::Channel() : ChannelBase<T>() {}
template <typename T>
Output<T>::Channel::Channel(Output* module, ChanNum channel_number)
: ChannelBase<T>(module, channel_number) {}
template <typename T>
void Output<T>::Channel::set_enable_value(T enable_value) {
dynamic_cast<Output<T>*>(this->module_)->set_enable_value(this->channel_number_, enable_value);
}
template <typename T>
void Output<T>::Channel::set_disable_value(T disable_value) {
dynamic_cast<Output<T>*>(this->module_)->set_disable_value(this->channel_number_, disable_value);
}
template <typename T>
bool Output<T>::Channel::set_expire_value(T expire_value) {
return dynamic_cast<Output<T>*>(this->module_)->set_expire_value(this->channel_number_, expire_value);
}
} // namespace mel
| 32.016129 | 110 | 0.650378 | mahilab |
61d243af56daa02c7680d7b52bc18e1c042c2150 | 1,325 | cpp | C++ | projects/2_alg_dan/asd_lab_5/realty.cpp | GodBastardNeil/somethings | 56a25ab2a3150658356924b00fed7d97ad76a9cb | [
"BSD-3-Clause"
] | null | null | null | projects/2_alg_dan/asd_lab_5/realty.cpp | GodBastardNeil/somethings | 56a25ab2a3150658356924b00fed7d97ad76a9cb | [
"BSD-3-Clause"
] | null | null | null | projects/2_alg_dan/asd_lab_5/realty.cpp | GodBastardNeil/somethings | 56a25ab2a3150658356924b00fed7d97ad76a9cb | [
"BSD-3-Clause"
] | null | null | null | #include "realty.h"
void realty::data_checker(const std::string &data)
{
if (data.size() > 8) { throw data_8(); }
}
realty::realty(std::string d, const std::string &N, const std::initializer_list<data_t> &v): tree(v)
{
data_checker(d);
data = d;
name = N;
}
realty::realty(std::string d, const std::string &N, const tree &other): tree(other)
{
data_checker(d);
data = d;
name = N;
}
realty::realty(std::string d, const std::string &N, tree &&other): tree(std::move(other))
{
data_checker(d);
data = d;
name = N;
}
realty::realty(const realty &other) noexcept: tree(other)
{
name = other.name;
data = other.data;
}
realty::realty(realty &&other) noexcept: tree(std::move(other))
{
name = other.name;
data = other.data;
other.name.clear();
other.data = nullptr;
}
void realty::_add_(const data_t &v) { insert(v); }
void realty::_change_(const key_t &s, const value_t &v) { replace(s, v); }
void realty::_delete_(const key_t &s) { erase(s); }
realty::value_t realty::find_id(const key_t &id) { return std::get<1>(find(id)); }
std::string realty::toString() noexcept
{
std::string s = "Контора: " + name + "\n Дата создания: " + data + '\n';
if (count() > 0)
{
s += to_string();
} else { s += "\n Нет Информации"; }
return s;
}
| 22.844828 | 100 | 0.607547 | GodBastardNeil |
61d4a441a8401ca2ed8d0a2f4d2ecdc8a334eca7 | 2,340 | cpp | C++ | src/fuselage/CCPACSFuselageSectionElement.cpp | MarAlder/tigl | 76e1f1442a045e1b8b7954119ca6f9c883ea41e2 | [
"Apache-2.0"
] | 10 | 2018-09-05T15:12:26.000Z | 2019-05-04T05:41:39.000Z | src/fuselage/CCPACSFuselageSectionElement.cpp | MarAlder/tigl | 76e1f1442a045e1b8b7954119ca6f9c883ea41e2 | [
"Apache-2.0"
] | null | null | null | src/fuselage/CCPACSFuselageSectionElement.cpp | MarAlder/tigl | 76e1f1442a045e1b8b7954119ca6f9c883ea41e2 | [
"Apache-2.0"
] | 1 | 2019-01-12T13:54:14.000Z | 2019-01-12T13:54:14.000Z | /*
* Copyright (C) 2007-2013 German Aerospace Center (DLR/SC)
*
* Created: 2010-08-13 Markus Litz <Markus.Litz@dlr.de>
* 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.
*/
/**
* @file
* @brief Implementation of CPACS fuselage section element handling routines.
*/
#include "CCPACSFuselageSectionElement.h"
#include "CCPACSFuselageSectionElements.h"
#include "CCPACSFuselageSections.h"
#include "CCPACSFuselageSection.h"
#include "CCPACSFuselage.h"
namespace tigl
{
// Constructor
CCPACSFuselageSectionElement::CCPACSFuselageSectionElement(CCPACSFuselageSectionElements* parent, CTiglUIDManager* uidMgr)
: generated::CPACSFuselageElement(parent, uidMgr) {}
void CCPACSFuselageSectionElement::SetProfileUID(const std::string& value) {
generated::CPACSFuselageElement::SetProfileUID(value);
// invalidate fuselage
m_parent->GetParent()->GetParent()->GetParent()->Invalidate();
}
// Gets the section element transformation
CTiglTransformation CCPACSFuselageSectionElement::GetSectionElementTransformation() const
{
return m_transformation.getTransformationMatrix();
}
CTiglPoint CCPACSFuselageSectionElement::GetTranslation() const
{
return m_transformation.getTranslationVector();
}
CTiglPoint CCPACSFuselageSectionElement::GetRotation() const
{
return m_transformation.getRotation();
}
CTiglPoint CCPACSFuselageSectionElement::GetScaling() const
{
return m_transformation.getScaling();
}
void CCPACSFuselageSectionElement::SetTranslation(const CTiglPoint &translation)
{
m_transformation.setTranslation(translation, ABS_LOCAL);
}
void CCPACSFuselageSectionElement::SetRotation(const CTiglPoint &rotation)
{
m_transformation.setRotation(rotation);
}
void CCPACSFuselageSectionElement::SetScaling(const CTiglPoint &scaling)
{
m_transformation.setScaling(scaling);
}
} // end namespace tigl
| 29.620253 | 122 | 0.787607 | MarAlder |
61d50fcf44ad490da12e2717c04790dda11e07f5 | 447 | cpp | C++ | FontX/FXLog.cpp | frinkr/FontViewer | 69b5706e557ecd33515c5c8d6ba8fc1d6f06e0c0 | [
"MIT"
] | 2 | 2019-05-08T06:31:34.000Z | 2020-08-30T00:35:09.000Z | FontX/FXLog.cpp | frinkr/FontViewer | 69b5706e557ecd33515c5c8d6ba8fc1d6f06e0c0 | [
"MIT"
] | 1 | 2018-05-07T09:29:02.000Z | 2018-05-07T09:29:02.000Z | FontX/FXLog.cpp | frinkr/FontViewer | 69b5706e557ecd33515c5c8d6ba8fc1d6f06e0c0 | [
"MIT"
] | 2 | 2018-09-10T07:16:28.000Z | 2022-01-07T06:41:01.000Z | #include "FXLog.h"
namespace {
FXLogFunc s_log_func;
}
void
FXDefaultLogFunc(FXLogLevel level, const FXLogLocation * location, const char * message) {
const char * s[4] = {"error", "warning", "info", "verbose"};
printf("FX (%s) : %s", s[(size_t)level], message);
}
FXLogFunc
FXGetLogFunc() {
if (!s_log_func) s_log_func = FXDefaultLogFunc;
return s_log_func;
}
void
FXSetLogFunc(FXLogFunc func) {
s_log_func = func;
}
| 18.625 | 90 | 0.668904 | frinkr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.