text
stringlengths 5
1.04M
|
|---|
//===-- ValueObjectConstResult.cpp ----------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "lldb/Core/ValueObjectConstResult.h"
#include "lldb/Core/ValueObjectDynamicValue.h"
#include "lldb/Symbol/CompilerType.h"
#include "lldb/Target/ExecutionContext.h"
#include "lldb/Target/ExecutionContextScope.h"
#include "lldb/Target/Process.h"
#include "lldb/Utility/DataBuffer.h"
#include "lldb/Utility/DataBufferHeap.h"
#include "lldb/Utility/DataExtractor.h"
#include "lldb/Utility/Scalar.h"
namespace lldb_private {
class Module;
}
using namespace lldb;
using namespace lldb_private;
ValueObjectSP ValueObjectConstResult::Create(ExecutionContextScope *exe_scope,
ByteOrder byte_order,
uint32_t addr_byte_size,
lldb::addr_t address) {
auto manager_sp = ValueObjectManager::Create();
return (new ValueObjectConstResult(exe_scope, *manager_sp, byte_order,
addr_byte_size, address))
->GetSP();
}
ValueObjectConstResult::ValueObjectConstResult(ExecutionContextScope *exe_scope,
ValueObjectManager &manager,
ByteOrder byte_order,
uint32_t addr_byte_size,
lldb::addr_t address)
: ValueObject(exe_scope, manager), m_type_name(), m_byte_size(0),
m_impl(this, address) {
SetIsConstant();
SetValueIsValid(true);
m_data.SetByteOrder(byte_order);
m_data.SetAddressByteSize(addr_byte_size);
SetAddressTypeOfChildren(eAddressTypeLoad);
}
ValueObjectSP ValueObjectConstResult::Create(ExecutionContextScope *exe_scope,
const CompilerType &compiler_type,
ConstString name,
const DataExtractor &data,
lldb::addr_t address) {
auto manager_sp = ValueObjectManager::Create();
return (new ValueObjectConstResult(exe_scope, *manager_sp, compiler_type,
name, data, address))
->GetSP();
}
ValueObjectConstResult::ValueObjectConstResult(
ExecutionContextScope *exe_scope, ValueObjectManager &manager,
const CompilerType &compiler_type, ConstString name,
const DataExtractor &data, lldb::addr_t address)
: ValueObject(exe_scope, manager), m_type_name(), m_byte_size(0),
m_impl(this, address) {
m_data = data;
if (!m_data.GetSharedDataBuffer()) {
DataBufferSP shared_data_buffer(
new DataBufferHeap(data.GetDataStart(), data.GetByteSize()));
m_data.SetData(shared_data_buffer);
}
m_value.GetScalar() = (uintptr_t)m_data.GetDataStart();
m_value.SetValueType(Value::eValueTypeHostAddress);
m_value.SetCompilerType(compiler_type);
m_name = name;
SetIsConstant();
SetValueIsValid(true);
SetAddressTypeOfChildren(eAddressTypeLoad);
}
ValueObjectSP ValueObjectConstResult::Create(ExecutionContextScope *exe_scope,
const CompilerType &compiler_type,
ConstString name,
const lldb::DataBufferSP &data_sp,
lldb::ByteOrder data_byte_order,
uint32_t data_addr_size,
lldb::addr_t address) {
auto manager_sp = ValueObjectManager::Create();
return (new ValueObjectConstResult(exe_scope, *manager_sp, compiler_type,
name, data_sp, data_byte_order,
data_addr_size, address))
->GetSP();
}
ValueObjectSP ValueObjectConstResult::Create(ExecutionContextScope *exe_scope,
Value &value,
ConstString name,
Module *module) {
auto manager_sp = ValueObjectManager::Create();
return (new ValueObjectConstResult(exe_scope, *manager_sp, value, name,
module))
->GetSP();
}
ValueObjectConstResult::ValueObjectConstResult(
ExecutionContextScope *exe_scope, ValueObjectManager &manager,
const CompilerType &compiler_type, ConstString name,
const lldb::DataBufferSP &data_sp, lldb::ByteOrder data_byte_order,
uint32_t data_addr_size, lldb::addr_t address)
: ValueObject(exe_scope, manager), m_type_name(), m_byte_size(0),
m_impl(this, address) {
m_data.SetByteOrder(data_byte_order);
m_data.SetAddressByteSize(data_addr_size);
m_data.SetData(data_sp);
m_value.GetScalar() = (uintptr_t)data_sp->GetBytes();
m_value.SetValueType(Value::eValueTypeHostAddress);
m_value.SetCompilerType(compiler_type);
m_name = name;
SetIsConstant();
SetValueIsValid(true);
SetAddressTypeOfChildren(eAddressTypeLoad);
}
ValueObjectSP ValueObjectConstResult::Create(ExecutionContextScope *exe_scope,
const CompilerType &compiler_type,
ConstString name,
lldb::addr_t address,
AddressType address_type,
uint32_t addr_byte_size) {
auto manager_sp = ValueObjectManager::Create();
return (new ValueObjectConstResult(exe_scope, *manager_sp, compiler_type,
name, address, address_type,
addr_byte_size))
->GetSP();
}
ValueObjectConstResult::ValueObjectConstResult(
ExecutionContextScope *exe_scope, ValueObjectManager &manager,
const CompilerType &compiler_type, ConstString name, lldb::addr_t address,
AddressType address_type, uint32_t addr_byte_size)
: ValueObject(exe_scope, manager), m_type_name(), m_byte_size(0),
m_impl(this, address) {
m_value.GetScalar() = address;
m_data.SetAddressByteSize(addr_byte_size);
m_value.GetScalar().GetData(m_data, addr_byte_size);
// m_value.SetValueType(Value::eValueTypeHostAddress);
switch (address_type) {
case eAddressTypeInvalid:
m_value.SetValueType(Value::eValueTypeScalar);
break;
case eAddressTypeFile:
m_value.SetValueType(Value::eValueTypeFileAddress);
break;
case eAddressTypeLoad:
m_value.SetValueType(Value::eValueTypeLoadAddress);
break;
case eAddressTypeHost:
m_value.SetValueType(Value::eValueTypeHostAddress);
break;
}
m_value.SetCompilerType(compiler_type);
m_name = name;
SetIsConstant();
SetValueIsValid(true);
SetAddressTypeOfChildren(eAddressTypeLoad);
}
ValueObjectSP ValueObjectConstResult::Create(ExecutionContextScope *exe_scope,
const Status &error) {
auto manager_sp = ValueObjectManager::Create();
return (new ValueObjectConstResult(exe_scope, *manager_sp, error))->GetSP();
}
ValueObjectConstResult::ValueObjectConstResult(ExecutionContextScope *exe_scope,
ValueObjectManager &manager,
const Status &error)
: ValueObject(exe_scope, manager), m_type_name(), m_byte_size(0),
m_impl(this) {
m_error = error;
SetIsConstant();
}
ValueObjectConstResult::ValueObjectConstResult(ExecutionContextScope *exe_scope,
ValueObjectManager &manager,
const Value &value,
ConstString name, Module *module)
: ValueObject(exe_scope, manager), m_type_name(), m_byte_size(0),
m_impl(this) {
m_value = value;
m_name = name;
ExecutionContext exe_ctx;
exe_scope->CalculateExecutionContext(exe_ctx);
m_error = m_value.GetValueAsData(&exe_ctx, m_data, module);
}
ValueObjectConstResult::~ValueObjectConstResult() {}
CompilerType ValueObjectConstResult::GetCompilerTypeImpl() {
return m_value.GetCompilerType();
}
lldb::ValueType ValueObjectConstResult::GetValueType() const {
return eValueTypeConstResult;
}
uint64_t ValueObjectConstResult::GetByteSize() {
ExecutionContext exe_ctx(GetExecutionContextRef());
if (m_byte_size == 0) {
if (auto size =
GetCompilerType().GetByteSize(exe_ctx.GetBestExecutionContextScope()))
SetByteSize(*size);
}
return m_byte_size;
}
void ValueObjectConstResult::SetByteSize(size_t size) { m_byte_size = size; }
size_t ValueObjectConstResult::CalculateNumChildren(uint32_t max) {
ExecutionContext exe_ctx(GetExecutionContextRef());
auto children_count = GetCompilerType().GetNumChildren(true, &exe_ctx);
return children_count <= max ? children_count : max;
}
ConstString ValueObjectConstResult::GetTypeName() {
if (m_type_name.IsEmpty())
m_type_name = GetCompilerType().GetTypeName();
return m_type_name;
}
ConstString ValueObjectConstResult::GetDisplayTypeName() {
const SymbolContext *sc = nullptr;
if (GetFrameSP())
sc = &GetFrameSP()->GetSymbolContext(eSymbolContextFunction);
return GetCompilerType().GetDisplayTypeName(sc);
}
bool ValueObjectConstResult::UpdateValue() {
// Const value is always valid
SetValueIsValid(true);
return true;
}
bool ValueObjectConstResult::IsInScope() {
// A const result value is always in scope since it serializes all
// information needed to contain the constant value.
return true;
}
lldb::ValueObjectSP ValueObjectConstResult::Dereference(Status &error) {
return m_impl.Dereference(error);
}
lldb::ValueObjectSP ValueObjectConstResult::GetSyntheticChildAtOffset(
uint32_t offset, const CompilerType &type, bool can_create,
ConstString name_const_str) {
return m_impl.GetSyntheticChildAtOffset(offset, type, can_create,
name_const_str);
}
lldb::ValueObjectSP ValueObjectConstResult::AddressOf(Status &error) {
return m_impl.AddressOf(error);
}
lldb::addr_t ValueObjectConstResult::GetAddressOf(bool scalar_is_load_address,
AddressType *address_type) {
return m_impl.GetAddressOf(scalar_is_load_address, address_type);
}
ValueObject *ValueObjectConstResult::CreateChildAtIndex(
size_t idx, bool synthetic_array_member, int32_t synthetic_index) {
return m_impl.CreateChildAtIndex(idx, synthetic_array_member,
synthetic_index);
}
size_t ValueObjectConstResult::GetPointeeData(DataExtractor &data,
uint32_t item_idx,
uint32_t item_count) {
return m_impl.GetPointeeData(data, item_idx, item_count);
}
lldb::ValueObjectSP
ValueObjectConstResult::GetDynamicValue(lldb::DynamicValueType use_dynamic) {
// Always recalculate dynamic values for const results as the memory that
// they might point to might have changed at any time.
if (use_dynamic != eNoDynamicValues) {
if (!IsDynamic()) {
ExecutionContext exe_ctx(GetExecutionContextRef());
Process *process = exe_ctx.GetProcessPtr();
if (process && process->IsPossibleDynamicValue(*this))
m_dynamic_value = new ValueObjectDynamicValue(*this, use_dynamic);
}
if (m_dynamic_value)
return m_dynamic_value->GetSP();
}
return ValueObjectSP();
}
lldb::ValueObjectSP
ValueObjectConstResult::Cast(const CompilerType &compiler_type) {
return m_impl.Cast(compiler_type);
}
lldb::LanguageType ValueObjectConstResult::GetPreferredDisplayLanguage() {
if (m_preferred_display_language != lldb::eLanguageTypeUnknown)
return m_preferred_display_language;
return GetCompilerTypeImpl().GetMinimumLanguage();
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparamsbase.h"
#include "clientversion.h"
#include "rpcclient.h"
#include "rpcprotocol.h"
#include "util.h"
#include "utilstrencodings.h"
#include <boost/filesystem/operations.hpp>
#include <stdio.h>
#include <event2/event.h>
#include <event2/http.h>
#include <event2/buffer.h>
#include <event2/keyvalq_struct.h>
#include <univalue.h>
using namespace std;
static const char DEFAULT_RPCCONNECT[] = "127.0.0.1";
static const int DEFAULT_HTTP_CLIENT_TIMEOUT=900;
std::string HelpMessageCli()
{
string strUsage;
strUsage += HelpMessageGroup(_("Options:"));
strUsage += HelpMessageOpt("-?", _("This help message"));
strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), BITCOIN_CONF_FILENAME));
strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
AppendParamsHelpMessages(strUsage);
strUsage += HelpMessageOpt("-rpcconnect=<ip>", strprintf(_("Send commands to node running on <ip> (default: %s)"), DEFAULT_RPCCONNECT));
strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Connect to JSON-RPC on <port> (default: %u or testnet: %u)"), BaseParams(CBaseChainParams::MAIN).RPCPort(), BaseParams(CBaseChainParams::TESTNET).RPCPort()));
strUsage += HelpMessageOpt("-rpcwait", _("Wait for RPC server to start"));
strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
strUsage += HelpMessageOpt("-rpcclienttimeout=<n>", strprintf(_("Timeout during HTTP requests (default: %d)"), DEFAULT_HTTP_CLIENT_TIMEOUT));
return strUsage;
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
//
// Exception thrown on connection error. This error is used to determine
// when to wait if -rpcwait is given.
//
class CConnectionFailed : public std::runtime_error
{
public:
explicit inline CConnectionFailed(const std::string& msg) :
std::runtime_error(msg)
{}
};
static bool AppInitRPC(int argc, char* argv[])
{
//
// Parameters
//
ParseParameters(argc, argv);
if (argc<2 || mapArgs.count("-?") || mapArgs.count("-h") || mapArgs.count("-help") || mapArgs.count("-version")) {
std::string strUsage = _("Bitcoin Classic RPC client version") + " " + FormatFullVersion() + "\n";
if (!mapArgs.count("-version")) {
strUsage += "\n" + _("Usage:") + "\n" +
" bitcoin-cli [options] <command> [params] " + _("Send command to Bitcoin Classic") + "\n" +
" bitcoin-cli [options] help " + _("List commands") + "\n" +
" bitcoin-cli [options] help <command> " + _("Get help for a command") + "\n";
strUsage += "\n" + HelpMessageCli();
}
fprintf(stdout, "%s", strUsage.c_str());
return false;
}
if (!boost::filesystem::is_directory(GetDataDir(false))) {
fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str());
return false;
}
try {
ReadConfigFile(mapArgs, mapMultiArgs);
} catch (const std::exception& e) {
fprintf(stderr,"Error reading configuration file: %s\n", e.what());
return false;
}
// Check for -testnet or -regtest parameter (BaseParams() calls are only valid after this clause)
try {
SelectBaseParams(ChainNameFromCommandLine());
} catch (const std::exception& e) {
fprintf(stderr, "Error: %s\n", e.what());
return false;
}
if (GetBoolArg("-rpcssl", false))
{
fprintf(stderr, "Error: SSL mode for RPC (-rpcssl) is no longer supported.\n");
return false;
}
return true;
}
/** Reply structure for request_done to fill in */
struct HTTPReply
{
int status;
std::string body;
};
static void http_request_done(struct evhttp_request *req, void *ctx)
{
HTTPReply *reply = static_cast<HTTPReply*>(ctx);
if (req == NULL) {
/* If req is NULL, it means an error occurred while connecting, but
* I'm not sure how to find out which one. We also don't really care.
*/
reply->status = 0;
return;
}
reply->status = evhttp_request_get_response_code(req);
struct evbuffer *buf = evhttp_request_get_input_buffer(req);
if (buf)
{
size_t size = evbuffer_get_length(buf);
const char *data = (const char*)evbuffer_pullup(buf, size);
if (data)
reply->body = std::string(data, size);
evbuffer_drain(buf, size);
}
}
UniValue CallRPC(const string& strMethod, const UniValue& params)
{
std::string host = GetArg("-rpcconnect", DEFAULT_RPCCONNECT);
int port = GetArg("-rpcport", BaseParams().RPCPort());
// Create event base
struct event_base *base = event_base_new(); // TODO RAII
if (!base)
throw runtime_error("cannot create event_base");
// Synchronously look up hostname
struct evhttp_connection *evcon = evhttp_connection_base_new(base, NULL, host.c_str(), port); // TODO RAII
if (evcon == NULL)
throw runtime_error("create connection failed");
evhttp_connection_set_timeout(evcon, GetArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT));
HTTPReply response;
struct evhttp_request *req = evhttp_request_new(http_request_done, (void*)&response); // TODO RAII
if (req == NULL)
throw runtime_error("create http request failed");
// Get credentials
std::string strRPCUserColonPass;
if (mapArgs["-rpcpassword"] == "") {
// Try fall back to cookie-based authentication if no password is provided
if (!GetAuthCookie(&strRPCUserColonPass)) {
throw runtime_error(strprintf(
_("Could not locate RPC credentials. No authentication cookie could be found, and no rpcpassword is set in the configuration file (%s)"),
GetConfigFile().string().c_str()));
}
} else {
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
}
struct evkeyvalq *output_headers = evhttp_request_get_output_headers(req);
assert(output_headers);
evhttp_add_header(output_headers, "Host", host.c_str());
evhttp_add_header(output_headers, "Connection", "close");
evhttp_add_header(output_headers, "Authorization", (std::string("Basic ") + EncodeBase64(strRPCUserColonPass)).c_str());
// Attach request data
std::string strRequest = JSONRPCRequest(strMethod, params, 1);
struct evbuffer * output_buffer = evhttp_request_get_output_buffer(req);
assert(output_buffer);
evbuffer_add(output_buffer, strRequest.data(), strRequest.size());
int r = evhttp_make_request(evcon, req, EVHTTP_REQ_POST, "/");
if (r != 0) {
evhttp_connection_free(evcon);
event_base_free(base);
throw CConnectionFailed("send http request failed");
}
event_base_dispatch(base);
evhttp_connection_free(evcon);
event_base_free(base);
if (response.status == 0)
throw CConnectionFailed("couldn't connect to server");
else if (response.status == HTTP_UNAUTHORIZED)
throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (response.status >= 400 && response.status != HTTP_BAD_REQUEST && response.status != HTTP_NOT_FOUND && response.status != HTTP_INTERNAL_SERVER_ERROR)
throw runtime_error(strprintf("server returned HTTP error %d", response.status));
else if (response.body.empty())
throw runtime_error("no response from server");
// Parse reply
UniValue valReply(UniValue::VSTR);
if (!valReply.read(response.body))
throw runtime_error("couldn't parse reply from server");
const UniValue& reply = valReply.get_obj();
if (reply.empty())
throw runtime_error("expected reply to have result, error and id properties");
return reply;
}
int CommandLineRPC(int argc, char *argv[])
{
string strPrint;
int nRet = 0;
try {
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0])) {
argc--;
argv++;
}
// Method
if (argc < 2)
throw runtime_error("too few parameters");
string strMethod = argv[1];
// Parameters default to strings
std::vector<std::string> strParams(&argv[2], &argv[argc]);
UniValue params = RPCConvertValues(strMethod, strParams);
// Execute and handle connection failures with -rpcwait
const bool fWait = GetBoolArg("-rpcwait", false);
do {
try {
const UniValue reply = CallRPC(strMethod, params);
// Parse reply
const UniValue& result = find_value(reply, "result");
const UniValue& error = find_value(reply, "error");
if (!error.isNull()) {
// Error
int code = error["code"].get_int();
if (fWait && code == RPC_IN_WARMUP)
throw CConnectionFailed("server in warmup");
strPrint = "error: " + error.write();
nRet = abs(code);
if (error.isObject())
{
UniValue errCode = find_value(error, "code");
UniValue errMsg = find_value(error, "message");
strPrint = errCode.isNull() ? "" : "error code: "+errCode.getValStr()+"\n";
if (errMsg.isStr())
strPrint += "error message:\n"+errMsg.get_str();
}
} else {
// Result
if (result.isNull())
strPrint = "";
else if (result.isStr())
strPrint = result.get_str();
else
strPrint = result.write(2);
}
// Connection succeeded, no need to retry.
break;
}
catch (const CConnectionFailed&) {
if (fWait)
MilliSleep(1000);
else
throw;
}
} while (fWait);
}
catch (const boost::thread_interrupted&) {
throw;
}
catch (const std::exception& e) {
strPrint = string("error: ") + e.what();
nRet = EXIT_FAILURE;
}
catch (...) {
PrintExceptionContinue(NULL, "CommandLineRPC()");
throw;
}
if (strPrint != "") {
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
int main(int argc, char* argv[])
{
SetupEnvironment();
if (!SetupNetworking()) {
fprintf(stderr, "Error: Initializing networking failed\n");
exit(1);
}
try {
if(!AppInitRPC(argc, argv))
return EXIT_FAILURE;
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "AppInitRPC()");
return EXIT_FAILURE;
} catch (...) {
PrintExceptionContinue(NULL, "AppInitRPC()");
return EXIT_FAILURE;
}
int ret = EXIT_FAILURE;
try {
ret = CommandLineRPC(argc, argv);
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "CommandLineRPC()");
} catch (...) {
PrintExceptionContinue(NULL, "CommandLineRPC()");
}
return ret;
}
|
#include "hevcStreamReader.h"
#include <fs/systemlog.h>
#include "hevc.h"
#include "nalUnits.h"
#include "tsMuxer.h"
#include "tsPacket.h"
#include "vodCoreException.h"
using namespace std;
static const int MAX_SLICE_HEADER = 64;
static const int HEVC_DESCRIPTOR_TAG = 0x38;
HEVCStreamReader::HEVCStreamReader()
: MPEGStreamReader(),
m_vps(0),
m_sps(0),
m_pps(0),
m_hdr(0),
m_firstFrame(true),
m_frameNum(0),
m_fullPicOrder(0),
m_frameDepth(1),
m_picOrderMsb(0),
m_prevPicOrder(0),
m_picOrderBase(0),
m_lastIFrame(false),
m_firstFileFrame(false),
m_vpsCounter(0),
m_vpsSizeDiff(0)
{
}
HEVCStreamReader::~HEVCStreamReader()
{
delete m_vps;
delete m_sps;
delete m_pps;
delete m_hdr;
}
CheckStreamRez HEVCStreamReader::checkStream(uint8_t* buffer, int len)
{
CheckStreamRez rez;
uint8_t* end = buffer + len;
for (uint8_t* nal = NALUnit::findNextNAL(buffer, end); nal < end - 4; nal = NALUnit::findNextNAL(nal, end))
{
if (*nal & 0x80)
return rez; // invalid nal
int nalType = (*nal >> 1) & 0x3f;
uint8_t* nextNal = NALUnit::findNALWithStartCode(nal, end, true);
switch (nalType)
{
case NAL_VPS:
{
if (!m_vps)
m_vps = new HevcVpsUnit();
m_vps->decodeBuffer(nal, nextNal);
if (m_vps->deserialize())
return rez;
m_spsPpsFound = true;
if (m_vps->num_units_in_tick)
updateFPS(m_vps, nal, nextNal, 0);
break;
}
case NAL_SPS:
{
if (!m_sps)
m_sps = new HevcSpsUnit();
m_sps->decodeBuffer(nal, nextNal);
if (m_sps->deserialize() != 0)
return rez;
m_spsPpsFound = true;
updateFPS(m_sps, nal, nextNal, 0);
break;
}
case NAL_PPS:
{
if (!m_pps)
m_pps = new HevcPpsUnit();
m_pps->decodeBuffer(nal, nextNal);
if (m_pps->deserialize() != 0)
return rez;
break;
}
case NAL_SEI_PREFIX:
{
if (!m_hdr)
m_hdr = new HevcHdrUnit();
m_hdr->decodeBuffer(nal, nextNal);
if (m_hdr->deserialize() != 0)
return rez;
break;
}
case NAL_DVRPU:
case NAL_DVEL:
{
if (!m_hdr)
m_hdr = new HevcHdrUnit();
if (nal[1] == 1)
{
if (nalType == NAL_DVEL)
m_hdr->isDVEL = true;
else
m_hdr->isDVRPU = true;
V3_flags |= DV;
}
break;
}
}
}
if (m_vps && m_sps && m_pps && m_sps->vps_id == m_vps->vps_id && m_pps->sps_id == m_sps->sps_id)
{
if (m_sps->colour_primaries == 9 && m_sps->transfer_characteristics == 16 &&
m_sps->matrix_coeffs == 9) // BT.2100
{
if (!m_hdr)
m_hdr = new HevcHdrUnit();
m_hdr->isHDR10 = true;
V3_flags |= HDR10;
}
rez.codecInfo = hevcCodecInfo;
rez.streamDescr = m_sps->getDescription();
size_t frSpsPos = rez.streamDescr.find("Frame rate: not found");
if (frSpsPos != string::npos)
rez.streamDescr = rez.streamDescr.substr(0, frSpsPos) + string(" ") + m_vps->getDescription();
}
return rez;
}
int HEVCStreamReader::getTSDescriptor(uint8_t* dstBuff, bool blurayMode)
{
if (m_firstFrame)
CheckStreamRez rez = checkStream(m_buffer, m_bufEnd - m_buffer);
/* non-HDMV descriptor, for future use
if (!blurayMode && (V3_flags & DV))
for (uint8_t* nal = NALUnit::findNextNAL(m_buffer, m_bufEnd); nal < m_bufEnd - 4;
nal = NALUnit::findNextNAL(nal, m_bufEnd))
{
uint8_t nalType = (*nal >> 1) & 0x3f;
uint8_t* nextNal = NALUnit::findNALWithStartCode(nal, m_bufEnd, true);
if (nalType == NAL_SPS)
{
uint8_t tmpBuffer[512];
int toDecode = FFMIN(sizeof(tmpBuffer) - 8, nextNal - nal);
int decodedLen = NALUnit::decodeNAL(nal, nal + toDecode, tmpBuffer, sizeof(tmpBuffer));
int lenDoviDesc = 0;
if (m_hdr->isDVEL || m_hdr->isDVRPU)
{
lenDoviDesc = setDoViDescriptor(dstBuff);
dstBuff += lenDoviDesc;
}
*dstBuff++ = HEVC_DESCRIPTOR_TAG;
*dstBuff++ = 13; // descriptor length
memcpy(dstBuff, tmpBuffer + 3, 12);
dstBuff += 12;
// temporal_layer_subset, HEVC_still_present, HEVC_24hr_picture_present, HDR_WCG unspecified
*dstBuff = 0x0f;
if (!m_sps->sub_pic_hrd_params_present_flag)
*dstBuff |= 0x10;
dstBuff++;
// HEVC_timing_and_HRD_descriptor
memcpy(dstBuff, "\x3f\x0f\x03\x7f\x7f", 5);
dstBuff += 5;
uint32_t N = 1001 * getFPS();
uint32_t K = 27000000;
uint32_t num_units_in_tick = 1001;
if (N % 1000)
{
N = 1000 * getFPS();
num_units_in_tick = 1000;
}
N = my_htonl(N);
K = my_htonl(K);
num_units_in_tick = my_htonl(num_units_in_tick);
memcpy(dstBuff, &N, 4);
dstBuff += 4;
memcpy(dstBuff, &K, 4);
dstBuff += 4;
memcpy(dstBuff, &num_units_in_tick, 4);
dstBuff += 4;
return 32 + lenDoviDesc;
}
} */
// 'HDMV' registration descriptor
*dstBuff++ = 0x05;
*dstBuff++ = 8;
memcpy(dstBuff, "HDMV\xff\x24", 6);
dstBuff += 6;
int video_format, frame_rate_index, aspect_ratio_index;
M2TSStreamInfo::blurayStreamParams(getFPS(), getInterlaced(), getStreamWidth(), getStreamHeight(), getStreamAR(),
&video_format, &frame_rate_index, &aspect_ratio_index);
*dstBuff++ = (video_format << 4) + frame_rate_index;
*dstBuff++ = (aspect_ratio_index << 4) + 0xf;
int lenDoviDesc = 0;
if (!blurayMode && (m_hdr->isDVEL || m_hdr->isDVRPU))
{
lenDoviDesc = setDoViDescriptor(dstBuff);
dstBuff += lenDoviDesc;
}
return 10 + lenDoviDesc;
}
int HEVCStreamReader::setDoViDescriptor(uint8_t* dstBuff)
{
int isDVBL = !(V3_flags & NON_DV_TRACK);
if (!isDVBL)
m_hdr->isDVEL = true;
int width = getStreamWidth();
int pixelRate = width * getStreamHeight() * getFPS();
if (!isDVBL && V3_flags & FOUR_K)
pixelRate *= 4;
// cf. "http://www.dolby.com/us/en/technologies/dolby-vision/dolby-vision-profiles-levels.pdf"
int profile;
int compatibility;
if (m_sps->bit_depth_luma_minus8 == 2)
{
if (!isDVBL) // dual HEVC track
{
profile = 7;
compatibility = 6;
}
else if (m_hdr->isDVEL && (V3_flags & HDR10))
{
profile = 6;
compatibility = 1;
}
else if (m_hdr->isDVEL)
{
profile = 4;
compatibility = 2;
}
else if (m_sps->colour_primaries == 2 && m_sps->transfer_characteristics == 2 &&
m_sps->matrix_coeffs == 2) // DV IPT color space
{
profile = 5;
compatibility = 0;
}
else if (m_sps->colour_primaries == 9 && m_sps->transfer_characteristics == 16 &&
m_sps->matrix_coeffs == 9) // DV BT.2100
{
profile = 8;
compatibility = 1;
}
else // DV SDR
{
profile = 8;
compatibility = 2;
}
}
else // 8-bit
{
if (m_sps->colour_primaries == 2 && m_sps->transfer_characteristics == 2 &&
m_sps->matrix_coeffs == 2) // DV IPT color space
{
profile = 3;
compatibility = 0;
}
else
{
profile = 2;
compatibility = 2;
}
}
int level = 0;
if (width <= 1280 && pixelRate <= 22118400)
level = 1;
else if (width <= 1280 && pixelRate <= 27648000)
level = 2;
else if (width <= 1920 && pixelRate <= 49766400)
level = 3;
else if (width <= 2560 && pixelRate <= 62208000)
level = 4;
else if (width <= 3840 && pixelRate <= 124416000)
level = 5;
else if (width <= 3840 && pixelRate <= 199065600)
level = 6;
else if (width <= 3840 && pixelRate <= 248832000)
level = 7;
else if (width <= 3840 && pixelRate <= 398131200)
level = 8;
else if (width <= 3840 && pixelRate <= 497664000)
level = 9;
else if (width <= 3840 && pixelRate <= 995328000)
level = 10;
else if (width <= 7680 && pixelRate <= 995328000)
level = 11;
else if (width <= 7680 && pixelRate <= 1990656000)
level = 12;
else if (width <= 7680 && pixelRate <= 3981312000)
level = 13;
BitStreamWriter bitWriter;
bitWriter.setBuffer(dstBuff, dstBuff + 128);
// 'DOVI' registration descriptor
bitWriter.putBits(8, 5);
bitWriter.putBits(8, 4);
bitWriter.putBits(32, 0x444f5649);
bitWriter.putBits(8, 0xb0); // DoVi descriptor tag
bitWriter.putBits(8, isDVBL ? 5 : 7); // descriptor length
bitWriter.putBits(8, 1); // dv version major
bitWriter.putBits(8, 0); // dv version minor
bitWriter.putBits(7, profile); // dv profile
bitWriter.putBits(6, level); // dv level
bitWriter.putBits(1, m_hdr->isDVRPU); // rpu_present_flag
bitWriter.putBits(1, m_hdr->isDVEL); // el_present_flag
bitWriter.putBits(1, isDVBL); // bl_present_flag
if (!isDVBL)
{
bitWriter.putBits(13, 0x1011); // dependency_pid
bitWriter.putBits(3, 7); // reserved
}
bitWriter.putBits(4, compatibility); // dv_bl_signal_compatibility_id
bitWriter.putBits(4, 15); // reserved
bitWriter.flushBits();
return 8 + (isDVBL ? 5 : 7);
}
void HEVCStreamReader::updateStreamFps(void* nalUnit, uint8_t* buff, uint8_t* nextNal, int)
{
int oldNalSize = nextNal - buff;
m_vpsSizeDiff = 0;
HevcVpsUnit* vps = (HevcVpsUnit*)nalUnit;
vps->setFPS(m_fps);
uint8_t* tmpBuffer = new uint8_t[vps->nalBufferLen() + 16];
long newSpsLen = vps->serializeBuffer(tmpBuffer, tmpBuffer + vps->nalBufferLen() + 16);
if (newSpsLen == -1)
THROW(ERR_COMMON, "Not enough buffer");
if (newSpsLen != oldNalSize)
{
m_vpsSizeDiff = newSpsLen - oldNalSize;
if (m_bufEnd + m_vpsSizeDiff > m_tmpBuffer + TMP_BUFFER_SIZE)
THROW(ERR_COMMON, "Not enough buffer");
memmove(nextNal + m_vpsSizeDiff, nextNal, m_bufEnd - nextNal);
m_bufEnd += m_vpsSizeDiff;
}
memcpy(buff, tmpBuffer, newSpsLen);
delete[] tmpBuffer;
}
int HEVCStreamReader::getStreamWidth() const { return m_sps ? m_sps->pic_width_in_luma_samples : 0; }
int HEVCStreamReader::getStreamHeight() const { return m_sps ? m_sps->pic_height_in_luma_samples : 0; }
int HEVCStreamReader::getStreamHDR() const
{
return (m_hdr->isDVRPU || m_hdr->isDVEL) ? 4 : (m_hdr->isHDR10plus ? 16 : (m_hdr->isHDR10 ? 2 : 1));
}
double HEVCStreamReader::getStreamFPS(void* curNalUnit)
{
double fps = 0;
if (m_vps)
fps = m_vps->getFPS();
if (fps == 0 && m_sps)
fps = m_sps->getFPS();
return fps;
}
bool HEVCStreamReader::isSlice(int nalType) const
{
if (!m_sps || !m_vps || !m_pps)
return false;
return (nalType >= NAL_TRAIL_N && nalType <= NAL_RASL_R) ||
(nalType >= NAL_BLA_W_LP && nalType <= NAL_RSV_IRAP_VCL23);
}
bool HEVCStreamReader::isSuffix(int nalType) const
{
if (!m_sps || !m_vps || !m_pps)
return false;
return (nalType == NAL_FD_NUT || nalType == NAL_SEI_SUFFIX || nalType == NAL_RSV_NVCL45 ||
(nalType >= NAL_RSV_NVCL45 && nalType <= NAL_RSV_NVCL47) ||
(nalType >= NAL_UNSPEC56 && nalType <= NAL_DVEL));
}
void HEVCStreamReader::incTimings()
{
if (m_totalFrameNum++ > 0)
m_curDts += m_pcrIncPerFrame;
int delta = m_frameNum - m_fullPicOrder;
m_curPts = m_curDts - delta * m_pcrIncPerFrame;
m_frameNum++;
m_firstFrame = false;
if (delta > m_frameDepth)
{
m_frameDepth = FFMIN(4, delta);
LTRACE(LT_INFO, 2,
"B-pyramid level " << m_frameDepth - 1 << " detected. Shift DTS to " << m_frameDepth << " frames");
}
}
int HEVCStreamReader::toFullPicOrder(HevcSliceHeader* slice, int pic_bits)
{
if (slice->isIDR())
{
m_picOrderBase = m_frameNum;
m_picOrderMsb = 0;
m_prevPicOrder = 0;
}
else
{
int range = 1 << pic_bits;
if (slice->pic_order_cnt_lsb < m_prevPicOrder && m_prevPicOrder - slice->pic_order_cnt_lsb >= range / 2)
m_picOrderMsb += range;
else if (slice->pic_order_cnt_lsb > m_prevPicOrder && slice->pic_order_cnt_lsb - m_prevPicOrder >= range / 2)
m_picOrderMsb -= range;
m_prevPicOrder = slice->pic_order_cnt_lsb;
}
return slice->pic_order_cnt_lsb + m_picOrderMsb + m_picOrderBase;
}
void HEVCStreamReader::storeBuffer(MemoryBlock& dst, const uint8_t* data, const uint8_t* dataEnd)
{
dataEnd--;
while (dataEnd > data && dataEnd[-1] == 0) dataEnd--;
if (dataEnd > data)
{
dst.resize(dataEnd - data);
memcpy(dst.data(), data, dataEnd - data);
}
}
int HEVCStreamReader::intDecodeNAL(uint8_t* buff)
{
int rez = 0;
bool sliceFound = false;
m_spsPpsFound = false;
m_lastIFrame = false;
uint8_t* prevPos = 0;
uint8_t* curPos = buff;
uint8_t* nextNal = NALUnit::findNextNAL(curPos, m_bufEnd);
uint8_t* nextNalWithStartCode;
long oldSpsLen = 0;
if (!m_eof && nextNal == m_bufEnd)
return NOT_ENOUGH_BUFFER;
while (curPos < m_bufEnd)
{
int nalType = (*curPos >> 1) & 0x3f;
if (isSlice(nalType))
{
if (curPos[2] & 0x80) // slice.first_slice
{
if (sliceFound)
{ // first slice of next frame: case where there is no non-VCL NAL between the two frames
m_lastDecodedPos = prevPos; // next frame started
incTimings();
return 0;
}
else
{ // first slice of current frame
HevcSliceHeader slice;
slice.decodeBuffer(curPos, FFMIN(curPos + MAX_SLICE_HEADER, nextNal));
rez = slice.deserialize(m_sps, m_pps);
if (rez)
return rez; // not enough buffer or error
// if (slice.slice_type == HEVC_IFRAME_SLICE)
if (nalType >= NAL_BLA_W_LP)
m_lastIFrame = true;
m_fullPicOrder = toFullPicOrder(&slice, m_sps->log2_max_pic_order_cnt_lsb);
}
}
sliceFound = true;
}
else if (!isSuffix(nalType))
{ // first non-VCL prefix NAL (AUD, SEI...) following current frame
if (sliceFound)
{
incTimings();
m_lastDecodedPos = prevPos; // next frame started
return 0;
}
nextNalWithStartCode = nextNal[-4] == 0 ? nextNal - 4 : nextNal - 3;
switch (nalType)
{
case NAL_VPS:
if (!m_vps)
m_vps = new HevcVpsUnit();
m_vps->decodeBuffer(curPos, nextNalWithStartCode);
rez = m_vps->deserialize();
if (rez)
return rez;
m_spsPpsFound = true;
m_vpsCounter++;
m_vpsSizeDiff = 0;
if (m_vps->num_units_in_tick)
updateFPS(m_vps, curPos, nextNalWithStartCode, 0);
nextNal += m_vpsSizeDiff;
storeBuffer(m_vpsBuffer, curPos, nextNalWithStartCode);
break;
case NAL_SPS:
if (!m_sps)
m_sps = new HevcSpsUnit();
m_sps->decodeBuffer(curPos, nextNalWithStartCode);
rez = m_sps->deserialize();
if (rez)
return rez;
m_spsPpsFound = true;
updateFPS(m_sps, curPos, nextNalWithStartCode, 0);
storeBuffer(m_spsBuffer, curPos, nextNalWithStartCode);
break;
case NAL_PPS:
if (!m_pps)
m_pps = new HevcPpsUnit();
m_pps->decodeBuffer(curPos, nextNalWithStartCode);
rez = m_pps->deserialize();
if (rez)
return rez;
m_spsPpsFound = true;
storeBuffer(m_ppsBuffer, curPos, nextNalWithStartCode);
break;
case NAL_SEI_PREFIX:
if (!m_hdr)
m_hdr = new HevcHdrUnit();
m_hdr->decodeBuffer(curPos, nextNal);
if (m_hdr->deserialize() != 0)
return rez;
break;
}
}
prevPos = curPos;
curPos = nextNal;
nextNal = NALUnit::findNextNAL(curPos, m_bufEnd);
if (!m_eof && nextNal == m_bufEnd)
return NOT_ENOUGH_BUFFER;
}
if (m_eof)
{
m_lastDecodedPos = m_bufEnd;
return 0;
}
else
return NEED_MORE_DATA;
}
uint8_t* HEVCStreamReader::writeNalPrefix(uint8_t* curPos)
{
if (!m_shortStartCodes)
*curPos++ = 0;
*curPos++ = 0;
*curPos++ = 0;
*curPos++ = 1;
return curPos;
}
uint8_t* HEVCStreamReader::writeBuffer(MemoryBlock& srcData, uint8_t* dstBuffer, uint8_t* dstEnd)
{
if (srcData.isEmpty())
return dstBuffer;
int bytesLeft = dstEnd - dstBuffer;
int requiredBytes = srcData.size() + 3 + (m_shortStartCodes ? 0 : 1);
if (bytesLeft < requiredBytes)
return dstBuffer;
dstBuffer = writeNalPrefix(dstBuffer);
memcpy(dstBuffer, srcData.data(), srcData.size());
dstBuffer += srcData.size();
return dstBuffer;
}
int HEVCStreamReader::writeAdditionData(uint8_t* dstBuffer, uint8_t* dstEnd, AVPacket& avPacket,
PriorityDataInfo* priorityData)
{
uint8_t* curPos = dstBuffer;
if (avPacket.size > 4 && avPacket.size < dstEnd - dstBuffer)
{
int offset = avPacket.data[2] == 1 ? 3 : 4;
uint8_t nalType = (avPacket.data[offset] >> 1) & 0x3f;
if (nalType == NAL_AUD)
{
// place delimiter at first place
memcpy(curPos, avPacket.data, avPacket.size);
curPos += avPacket.size;
avPacket.size = 0;
avPacket.data = 0;
}
}
bool needInsSpsPps = m_firstFileFrame && !(avPacket.flags & AVPacket::IS_SPS_PPS_IN_GOP);
if (needInsSpsPps)
{
avPacket.flags |= AVPacket::IS_SPS_PPS_IN_GOP;
curPos = writeBuffer(m_vpsBuffer, curPos, dstEnd);
curPos = writeBuffer(m_spsBuffer, curPos, dstEnd);
curPos = writeBuffer(m_ppsBuffer, curPos, dstEnd);
}
m_firstFileFrame = false;
return curPos - dstBuffer;
}
|
#include <jps3d/planner/planner_util.h>
template <int Dim>
JPSPlanner<Dim>::JPSPlanner(bool verbose): planner_verbose_(verbose) {
planner_verbose_ = verbose;
if(planner_verbose_)
printf(ANSI_COLOR_CYAN "JPS PLANNER VERBOSE ON\n" ANSI_COLOR_RESET);
}
template <int Dim>
void JPSPlanner<Dim>::setMapUtil(const std::shared_ptr<JPS::MapUtil<Dim>> &map_util) {
map_util_ = map_util;
}
template <int Dim>
int JPSPlanner<Dim>::status() { return status_; }
template <int Dim>
vec_Vecf<Dim> JPSPlanner<Dim>::getPath() { return path_; }
template <int Dim>
vec_Vecf<Dim> JPSPlanner<Dim>::getRawPath() { return raw_path_; }
template <int Dim>
vec_Vecf<Dim> JPSPlanner<Dim>::removeCornerPts(const vec_Vecf<Dim> &path) {
if (path.size() < 2)
return path;
// cut zigzag segment
vec_Vecf<Dim> optimized_path;
Vecf<Dim> pose1 = path[0];
Vecf<Dim> pose2 = path[1];
Vecf<Dim> prev_pose = pose1;
optimized_path.push_back(pose1);
decimal_t cost1, cost2, cost3;
if (!map_util_->isBlocked(pose1, pose2))
cost1 = (pose1 - pose2).norm();
else
cost1 = std::numeric_limits<decimal_t>::infinity();
for (unsigned int i = 1; i < path.size() - 1; i++) {
pose1 = path[i];
pose2 = path[i + 1];
if (!map_util_->isBlocked(pose1, pose2))
cost2 = (pose1 - pose2).norm();
else
cost2 = std::numeric_limits<decimal_t>::infinity();
if (!map_util_->isBlocked(prev_pose, pose2))
cost3 = (prev_pose - pose2).norm();
else
cost3 = std::numeric_limits<decimal_t>::infinity();
if (cost3 < cost1 + cost2)
cost1 = cost3;
else {
optimized_path.push_back(path[i]);
cost1 = (pose1 - pose2).norm();
prev_pose = pose1;
}
}
optimized_path.push_back(path.back());
return optimized_path;
}
template <int Dim>
vec_Vecf<Dim> JPSPlanner<Dim>::removeLinePts(const vec_Vecf<Dim> &path) {
if (path.size() < 3)
return path;
vec_Vecf<Dim> new_path;
new_path.push_back(path.front());
for (unsigned int i = 1; i < path.size() - 1; i++) {
Vecf<Dim> p = (path[i + 1] - path[i]) - (path[i] - path[i - 1]);
if(Dim == 3) {
if (fabs(p(0)) + fabs(p(1)) + fabs(p(2)) > 1e-2)
new_path.push_back(path[i]);
}
else {
if (fabs(p(0)) + fabs(p(1)) > 1e-2)
new_path.push_back(path[i]);
}
}
new_path.push_back(path.back());
return new_path;
}
template <int Dim>
vec_Vecf<Dim> JPSPlanner<Dim>::getOpenSet() const {
vec_Vecf<Dim> ps;
const auto ss = graph_search_->getOpenSet();
for(const auto& it: ss) {
if(Dim == 3) {
Veci<Dim> pn;
pn << it->x, it->y, it->z;
ps.push_back(map_util_->intToFloat(pn));
}
else
ps.push_back(map_util_->intToFloat(Veci<Dim>(it->x, it->y)));
}
return ps;
}
template <int Dim>
vec_Vecf<Dim> JPSPlanner<Dim>::getCloseSet() const {
vec_Vecf<Dim> ps;
const auto ss = graph_search_->getCloseSet();
for(const auto& it: ss) {
if(Dim == 3) {
Veci<Dim> pn;
pn << it->x, it->y, it->z;
ps.push_back(map_util_->intToFloat(pn));
}
else
ps.push_back(map_util_->intToFloat(Veci<Dim>(it->x, it->y)));
}
return ps;
}
template <int Dim>
vec_Vecf<Dim> JPSPlanner<Dim>::getAllSet() const {
vec_Vecf<Dim> ps;
const auto ss = graph_search_->getAllSet();
for(const auto& it: ss) {
if(Dim == 3) {
Veci<Dim> pn;
pn << it->x, it->y, it->z;
ps.push_back(map_util_->intToFloat(pn));
}
else
ps.push_back(map_util_->intToFloat(Veci<Dim>(it->x, it->y)));
}
return ps;
}
template <int Dim>
void JPSPlanner<Dim>::updateMap() {
Veci<Dim> dim = map_util_->getDim();
if(Dim == 3) {
cmap_.resize(dim(0)*dim(1)*dim(2));
for( int z = 0; z < dim(2); ++z) {
for( int y = 0; y < dim(1); ++y) {
for( int x = 0; x < dim(0); ++x) {
Veci<Dim> pn;
pn << x, y, z;
cmap_[x+y*dim(0)+z*dim(0)*dim(1)] = map_util_->isOccupied(pn) ? 1:0;
}
}
}
}
else {
cmap_.resize(dim(0)*dim(1));
for( int y = 0; y < dim(1); ++y)
for( int x = 0; x < dim(0); ++x)
cmap_[x+y*dim(0)] = map_util_->isOccupied(Veci<Dim>(x,y)) ? 1:0;
}
}
template <int Dim>
bool JPSPlanner<Dim>::plan(const Vecf<Dim> &start, const Vecf<Dim> &goal, decimal_t eps, bool use_jps) {
if(planner_verbose_){
std::cout <<"Start: " << start.transpose() << std::endl;
std::cout <<"Goal: " << goal.transpose() << std::endl;
std::cout <<"Epsilon: " << eps << std::endl;
}
path_.clear();
raw_path_.clear();
status_ = 0;
const Veci<Dim> start_int = map_util_->floatToInt(start);
if (!map_util_->isFree(start_int)) {
if(planner_verbose_) {
if (map_util_->isOccupied(start_int))
printf(ANSI_COLOR_RED "start is occupied!\n" ANSI_COLOR_RESET);
else if (map_util_->isUnknown(start_int))
printf(ANSI_COLOR_RED "start is unknown!\n" ANSI_COLOR_RESET);
else {
printf(ANSI_COLOR_RED "start is outside!\n" ANSI_COLOR_RESET);
std::cout << "startI: " << start_int.transpose() << std::endl;
std::cout <<"Map origin: " << map_util_->getOrigin().transpose() << std::endl;
std::cout <<"Map dim: " << map_util_->getDim().transpose() << std::endl;
}
}
status_ = 1;
return false;
}
const Veci<Dim> goal_int = map_util_->floatToInt(goal);
if (!map_util_->isFree(goal_int)) {
if(planner_verbose_)
printf(ANSI_COLOR_RED "goal is not free!\n" ANSI_COLOR_RESET);
status_ = 2;
return false;
}
if(cmap_.empty()) {
if(planner_verbose_)
printf(ANSI_COLOR_RED "need to set cmap, call updateMap()!\n" ANSI_COLOR_RESET);
return -1;
}
const Veci<Dim> dim = map_util_->getDim();
if(Dim == 3) {
graph_search_ = std::make_shared<JPS::GraphSearch>(cmap_.data(), dim(0), dim(1), dim(2), eps, planner_verbose_);
graph_search_->plan(start_int(0), start_int(1), start_int(2), goal_int(0), goal_int(1), goal_int(2), use_jps);
}
else {
graph_search_ = std::make_shared<JPS::GraphSearch>(cmap_.data(), dim(0), dim(1), eps, planner_verbose_);
graph_search_->plan(start_int(0), start_int(1), goal_int(0), goal_int(1), use_jps);
}
const auto path = graph_search_->getPath();
if (path.size() < 1) {
if(planner_verbose_)
std::cout << ANSI_COLOR_RED "Cannot find a path from " << start.transpose() <<" to " << goal.transpose() << " Abort!" ANSI_COLOR_RESET << std::endl;
status_ = -1;
return false;
}
//**** raw path, s --> g
vec_Vecf<Dim> ps;
for (const auto &it : path) {
if(Dim == 3) {
Veci<Dim> pn;
pn << it->x, it->y, it->z;
ps.push_back(map_util_->intToFloat(pn));
}
else
ps.push_back(map_util_->intToFloat(Veci<Dim>(it->x, it->y)));
}
raw_path_ = ps;
std::reverse(std::begin(raw_path_), std::end(raw_path_));
// Simplify the raw path
path_ = removeLinePts(raw_path_);
path_ = removeCornerPts(path_);
std::reverse(std::begin(path_), std::end(path_));
path_ = removeCornerPts(path_);
std::reverse(std::begin(path_), std::end(path_));
return true;
}
template class JPSPlanner<2>;
template class JPSPlanner<3>;
|
// Copyright Take Vos 2021.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
#include "ttauri/geometry/transform.hpp"
#include <gtest/gtest.h>
#include <iostream>
#include <string>
using namespace tt::geo;
TEST(geometry, identity_translate)
{
static_assert(std::is_same_v<decltype(identity() * translate<2>(1.0, 2.0)), translate<2>>);
static_assert(std::is_same_v<decltype(identity() * translate<3>(1.0, 2.0, 3.0)), translate<3>>);
static_assert(identity() * translate<2>(1.0, 2.0) == translate<2>(1.0, 2.0));
static_assert(identity() * translate<3>(1.0, 2.0, 3.0) == translate<3>(1.0, 2.0, 3.0));
ASSERT_TRUE(identity() * translate<2>(1.0, 2.0) == translate<2>(1.0, 2.0));
ASSERT_TRUE(identity() * translate<3>(1.0, 2.0, 3.0) == translate<3>(1.0, 2.0, 3.0));
}
TEST(geometry, identity_scale)
{
static_assert(std::is_same_v<decltype(identity() * scale<2>(1.0, 2.0)), scale<2>>);
static_assert(std::is_same_v<decltype(identity() * scale<3>(1.0, 2.0, 3.0)), scale<3>>);
static_assert(identity() * scale<2>(1.0, 2.0) == scale<2>(1.0, 2.0));
static_assert(identity() * scale<3>(1.0, 2.0, 3.0) == scale<3>(1.0, 2.0, 3.0));
ASSERT_TRUE(identity() * scale<2>(1.0, 2.0) == scale<2>(1.0, 2.0));
ASSERT_TRUE(identity() * scale<3>(1.0, 2.0, 3.0) == scale<3>(1.0, 2.0, 3.0));
}
TEST(geometry, translate_scale_point)
{
static_assert(std::is_same_v<decltype(translate<2>(-3, -4) * (scale<2>(4.0, 6.0) * point<2>(1.0, 2.0))), point<2>>);
static_assert(std::is_same_v<decltype(translate<2>(-3, -4) * (scale<2>(4.0, 6.0) * point<3>(1.0, 2.0, 3.0))), point<3>>);
static_assert(std::is_same_v<decltype(translate<2>(-3, -4) * (scale<3>(4.0, 6.0, 8.0) * point<2>(1.0, 2.0))), point<2>>);
static_assert(std::is_same_v<decltype(translate<2>(-3, -4) * (scale<3>(4.0, 6.0, 8.0) * point<3>(1.0, 2.0, 3.0))), point<3>>);
static_assert(std::is_same_v<decltype(translate<3>(-3, -4, -5) * (scale<2>(4.0, 6.0) * point<2>(1.0, 2.0))), point<3>>);
static_assert(std::is_same_v<decltype(translate<3>(-3, -4, -5) * (scale<2>(4.0, 6.0) * point<3>(1.0, 2.0, 3.0))), point<3>>);
static_assert(std::is_same_v<decltype(translate<3>(-3, -4, -5) * (scale<3>(4.0, 6.0, 8.0) * point<2>(1.0, 2.0))), point<3>>);
static_assert(
std::is_same_v<decltype(translate<3>(-3, -4, -5) * (scale<3>(4.0, 6.0, 8.0) * point<3>(1.0, 2.0, 3.0))), point<3>>);
static_assert(translate<2>(-3, -4) * (scale<2>(4.0, 6.0) * point<2>(1.0, 2.0)) == point<2>(1.0, 8.0));
static_assert(translate<2>(-3, -4) * (scale<2>(4.0, 6.0) * point<3>(1.0, 2.0, 3.0)) == point<3>(1.0, 8.0, 3.0));
static_assert(translate<2>(-3, -4) * (scale<3>(4.0, 6.0, 8.0) * point<2>(1.0, 2.0)) == point<2>(1.0, 8.0));
static_assert(translate<2>(-3, -4) * (scale<3>(4.0, 6.0, 8.0) * point<3>(1.0, 2.0, 3.0)) == point<3>(1, 8.0, 24.0));
static_assert(translate<3>(-3, -4, -5) * (scale<2>(4.0, 6.0) * point<2>(1.0, 2.0)) == point<3>(1.0, 8.0, -5));
static_assert(translate<3>(-3, -4, -5) * (scale<2>(4.0, 6.0) * point<3>(1.0, 2.0, 3.0)) == point<3>(1.0, 8.0, -2.0));
static_assert(translate<3>(-3, -4, -5) * (scale<3>(4.0, 6.0, 8.0) * point<2>(1.0, 2.0)) == point<3>(1.0, 8.0, -5));
static_assert(translate<3>(-3, -4, -5) * (scale<3>(4.0, 6.0, 8.0) * point<3>(1.0, 2.0, 3.0)) == point<3>(1, 8.0, 19.0));
ASSERT_TRUE(translate<2>(-3, -4) * (scale<2>(4.0, 6.0) * point<2>(1.0, 2.0)) == point<2>(1.0, 8.0));
ASSERT_TRUE(translate<2>(-3, -4) * (scale<2>(4.0, 6.0) * point<3>(1.0, 2.0, 3.0)) == point<3>(1.0, 8.0, 3.0));
ASSERT_TRUE(translate<2>(-3, -4) * (scale<3>(4.0, 6.0, 8.0) * point<2>(1.0, 2.0)) == point<2>(1.0, 8.0));
ASSERT_TRUE(translate<2>(-3, -4) * (scale<3>(4.0, 6.0, 8.0) * point<3>(1.0, 2.0, 3.0)) == point<3>(1, 8.0, 24.0));
ASSERT_TRUE(translate<3>(-3, -4, -5) * (scale<2>(4.0, 6.0) * point<2>(1.0, 2.0)) == point<3>(1.0, 8.0, -5));
ASSERT_TRUE(translate<3>(-3, -4, -5) * (scale<2>(4.0, 6.0) * point<3>(1.0, 2.0, 3.0)) == point<3>(1.0, 8.0, -2.0));
ASSERT_TRUE(translate<3>(-3, -4, -5) * (scale<3>(4.0, 6.0, 8.0) * point<2>(1.0, 2.0)) == point<3>(1.0, 8.0, -5));
ASSERT_TRUE(translate<3>(-3, -4, -5) * (scale<3>(4.0, 6.0, 8.0) * point<3>(1.0, 2.0, 3.0)) == point<3>(1, 8.0, 19.0));
static_assert(std::is_same_v<decltype((translate<2>(-3, -4) * scale<2>(4.0, 6.0)) * point<2>(1.0, 2.0)), point<2>>);
static_assert(std::is_same_v<decltype((translate<2>(-3, -4) * scale<2>(4.0, 6.0)) * point<3>(1.0, 2.0, 3.0)), point<3>>);
static_assert(std::is_same_v<decltype((translate<2>(-3, -4) * scale<3>(4.0, 6.0, 8.0)) * point<2>(1.0, 2.0)), point<3>>);
static_assert(std::is_same_v<decltype((translate<2>(-3, -4) * scale<3>(4.0, 6.0, 8.0)) * point<3>(1.0, 2.0, 3.0)), point<3>>);
static_assert(std::is_same_v<decltype((translate<3>(-3, -4, -5) * scale<2>(4.0, 6.0)) * point<2>(1.0, 2.0)), point<3>>);
static_assert(std::is_same_v<decltype((translate<3>(-3, -4, -5) * scale<2>(4.0, 6.0)) * point<3>(1.0, 2.0, 3.0)), point<3>>);
static_assert(std::is_same_v<decltype((translate<3>(-3, -4, -5) * scale<3>(4.0, 6.0, 8.0)) * point<2>(1.0, 2.0)), point<3>>);
static_assert(
std::is_same_v<decltype((translate<3>(-3, -4, -5) * scale<3>(4.0, 6.0, 8.0)) * point<3>(1.0, 2.0, 3.0)), point<3>>);
static_assert((translate<2>(-3, -4) * scale<2>(4.0, 6.0)) * point<3>(1.0, 2.0, 3.0) == point<3>(1.0, 8.0, 3.0));
static_assert((translate<2>(-3, -4) * scale<3>(4.0, 6.0, 8.0)) * point<2>(1.0, 2.0) == point<3>(1.0, 8.0, 0.0));
static_assert((translate<2>(-3, -4) * scale<3>(4.0, 6.0, 8.0)) * point<3>(1.0, 2.0, 3.0) == point<3>(1, 8.0, 24.0));
static_assert((translate<2>(-3, -4) * scale<2>(4.0, 6.0)) * point<2>(1.0, 2.0) == point<3>(1.0, 8.0, 0.0));
static_assert((translate<3>(-3, -4, -5) * scale<2>(4.0, 6.0)) * point<2>(1.0, 2.0) == point<3>(1.0, 8.0, -5));
static_assert((translate<3>(-3, -4, -5) * scale<2>(4.0, 6.0)) * point<3>(1.0, 2.0, 3.0) == point<3>(1.0, 8.0, -2.0));
static_assert((translate<3>(-3, -4, -5) * scale<3>(4.0, 6.0, 8.0)) * point<2>(1.0, 2.0) == point<3>(1.0, 8.0, -5));
static_assert((translate<3>(-3, -4, -5) * scale<3>(4.0, 6.0, 8.0)) * point<3>(1.0, 2.0, 3.0) == point<3>(1, 8.0, 19.0));
ASSERT_TRUE((translate<2>(-3, -4) * scale<2>(4.0, 6.0)) * point<3>(1.0, 2.0, 3.0) == point<3>(1.0, 8.0, 3.0));
ASSERT_TRUE((translate<2>(-3, -4) * scale<3>(4.0, 6.0, 8.0)) * point<2>(1.0, 2.0) == point<3>(1.0, 8.0, 0.0));
ASSERT_TRUE((translate<2>(-3, -4) * scale<3>(4.0, 6.0, 8.0)) * point<3>(1.0, 2.0, 3.0) == point<3>(1, 8.0, 24.0));
ASSERT_TRUE((translate<2>(-3, -4) * scale<2>(4.0, 6.0)) * point<2>(1.0, 2.0) == point<3>(1.0, 8.0, 0.0));
ASSERT_TRUE((translate<3>(-3, -4, -5) * scale<2>(4.0, 6.0)) * point<2>(1.0, 2.0) == point<3>(1.0, 8.0, -5));
ASSERT_TRUE((translate<3>(-3, -4, -5) * scale<2>(4.0, 6.0)) * point<3>(1.0, 2.0, 3.0) == point<3>(1.0, 8.0, -2.0));
ASSERT_TRUE((translate<3>(-3, -4, -5) * scale<3>(4.0, 6.0, 8.0)) * point<2>(1.0, 2.0) == point<3>(1.0, 8.0, -5));
ASSERT_TRUE((translate<3>(-3, -4, -5) * scale<3>(4.0, 6.0, 8.0)) * point<3>(1.0, 2.0, 3.0) == point<3>(1, 8.0, 19.0));
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:e18138deeb3f9fad38375032d6ef0b59faa370cc487c35506d7c1642d9ed0e15
size 3511
|
#include "Matrix.h"
#include "exceptions.h"
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
Matrix::Matrix(int _n, int _m) : n(_n), m(_m), data(nullptr)
{
data = (int*)calloc(n * m, sizeof(int));
}
Matrix::Matrix(int _n, int _m, std::istream& is) : n(_n), m(_m), data(nullptr)
{
data = (int*)calloc(n * m, sizeof(int));
is >> *this;
}
Matrix::~Matrix()
{
delete[] data;
}
bool Matrix::operator==(Matrix& other) {
if (n != other.getN() || m != other.getM())
return false;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (data[i * m + j] != other(i, j))
return false;
}
}
return true;
}
int& Matrix::operator()(int i, int j) {
return data[i * m + j];
}
const int& Matrix::operator()(int i, int j) const {
return data[i * m + j];
}
std::istream& operator>>(std::istream& is, Matrix& matrix)
{
if (!is)
throw InvalidStream("Trying to read from invalid stream");
int a, b;
is >> a >> b;
if (a != matrix.getN() || b != matrix.getM()) {
ostringstream ss;
ss << "Dimensions of stream and matrix are incompatible:" << endl
<< "Stream dimensions (" << a << "," << b << ")" << endl
<< "Matrix dimensions (" << matrix.getN() << "," << matrix.getM() << ")";
throw InvalidDimensions(ss.str());
}
int br = 0;
while (is >> matrix.data[br]) {
++br;
}
if (is.eof()) {
return is;
}
else {
throw BadFileFormat("Error happend while trying to read data from file to matrix");
}
}
std::ostream& operator<<(std::ostream& os, const Matrix& matrix)
{
os << matrix.n << " " << matrix.m << '\n';
for (int i = 0; i < matrix.n; ++i) {
for (int j = 0; j < matrix.m; ++j) {
os << matrix(i, j) << " ";
}
os << '\n';
}
return os;
}
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.ValueType
#include "System/ValueType.hpp"
// Including type: System.Globalization.HebrewNumber/System.Globalization.HS
#include "System/Globalization/HebrewNumber.hpp"
// Completed includes
// Type namespace: System.Globalization
namespace System::Globalization {
// Forward declaring type: HebrewNumberParsingContext
struct HebrewNumberParsingContext;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(::System::Globalization::HebrewNumberParsingContext, "System.Globalization", "HebrewNumberParsingContext");
// Type namespace: System.Globalization
namespace System::Globalization {
// Size: 0x8
#pragma pack(push, 1)
// WARNING Layout: Sequential may not be correctly taken into account!
// Autogenerated type: System.Globalization.HebrewNumberParsingContext
// [TokenAttribute] Offset: FFFFFFFF
struct HebrewNumberParsingContext/*, public ::System::ValueType*/ {
public:
public:
// System.Globalization.HebrewNumber/System.Globalization.HS state
// Size: 0x4
// Offset: 0x0
::System::Globalization::HebrewNumber::HS state;
// Field size check
static_assert(sizeof(::System::Globalization::HebrewNumber::HS) == 0x4);
// System.Int32 result
// Size: 0x4
// Offset: 0x4
int result;
// Field size check
static_assert(sizeof(int) == 0x4);
public:
// Creating value type constructor for type: HebrewNumberParsingContext
constexpr HebrewNumberParsingContext(::System::Globalization::HebrewNumber::HS state_ = {}, int result_ = {}) noexcept : state{state_}, result{result_} {}
// Creating interface conversion operator: operator ::System::ValueType
operator ::System::ValueType() noexcept {
return *reinterpret_cast<::System::ValueType*>(this);
}
// Get instance field reference: System.Globalization.HebrewNumber/System.Globalization.HS state
::System::Globalization::HebrewNumber::HS& dyn_state();
// Get instance field reference: System.Int32 result
int& dyn_result();
// public System.Void .ctor(System.Int32 result)
// Offset: 0x20F52E8
HebrewNumberParsingContext(int result);
}; // System.Globalization.HebrewNumberParsingContext
#pragma pack(pop)
static check_size<sizeof(HebrewNumberParsingContext), 4 + sizeof(int)> __System_Globalization_HebrewNumberParsingContextSizeCheck;
static_assert(sizeof(HebrewNumberParsingContext) == 0x8);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::Globalization::HebrewNumberParsingContext::HebrewNumberParsingContext
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
|
// This file is made available under Elastic License 2.0.
// This file is based on code available under the Apache license here:
// https://github.com/apache/incubator-doris/blob/master/be/src/exec/mysql_scanner.cpp
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include <mysql/mysql.h>
#define __StarRocksMysql MYSQL
#define __StarRocksMysqlRes MYSQL_RES
#include "common/logging.h"
#include "gutil/strings/substitute.h"
#include "mysql_scanner.h"
namespace starrocks {
// Our new vectorized query executor is more powerful and stable than old query executor,
// The executor query executor related codes could be deleted safely.
// TODO: Remove old query executor related codes before 2021-09-30
MysqlScanner::MysqlScanner(const MysqlScannerParam& param)
: _my_param(param), _my_conn(NULL), _my_result(NULL), _is_open(false), _field_num(0) {}
MysqlScanner::~MysqlScanner() {
if (_my_result) {
mysql_free_result(_my_result);
_my_result = NULL;
}
if (_my_conn) {
mysql_close(_my_conn);
_my_conn = NULL;
}
}
Status MysqlScanner::open() {
if (_is_open) {
LOG(INFO) << "this scanner already opened";
return Status::OK();
}
_my_conn = mysql_init(NULL);
if (NULL == _my_conn) {
return Status::InternalError("mysql init failed.");
}
VLOG(1) << "MysqlScanner::Connect";
if (NULL == mysql_real_connect(_my_conn, _my_param.host.c_str(), _my_param.user.c_str(), _my_param.passwd.c_str(),
_my_param.db.c_str(), atoi(_my_param.port.c_str()), NULL, _my_param.client_flag)) {
LOG(WARNING) << "connect Mysql: "
<< "Host: " << _my_param.host << " user: " << _my_param.user << " passwd: " << _my_param.passwd
<< " db: " << _my_param.db << " port: " << _my_param.port;
return _error_status("mysql real connect failed.");
}
if (mysql_set_character_set(_my_conn, "utf8")) {
return Status::InternalError("mysql set character set failed.");
}
_is_open = true;
return Status::OK();
}
Status MysqlScanner::query(const std::string& query) {
if (!_is_open) {
return Status::InternalError("Query before open.");
}
int sql_result = mysql_query(_my_conn, query.c_str());
if (0 != sql_result) {
LOG(WARNING) << "mysql query failed. query =" << query;
return _error_status("mysql query failed.");
} else {
LOG(INFO) << "mysql query success. query =" << query;
}
// clean the last query result
if (_my_result) {
mysql_free_result(_my_result);
}
// NOTE(zc): Result set may be very large, such as 100GB, which can not be stored in memory.
// So we use mysql_use_result here to read result set in streaming. But this may hurt the
// performance of small result sets. This need to be more investigation.
_my_result = mysql_use_result(_my_conn);
if (_my_result == nullptr) {
return _error_status("mysql store result failed.");
}
_field_num = mysql_num_fields(_my_result);
return Status::OK();
}
Status MysqlScanner::query(const std::string& table, const std::vector<std::string>& fields,
const std::vector<std::string>& filters) {
if (!_is_open) {
return Status::InternalError("Query before open.");
}
_sql_str = "SELECT";
for (int i = 0; i < fields.size(); ++i) {
if (0 != i) {
_sql_str += ",";
}
_sql_str += " " + fields[i];
}
_sql_str += " FROM " + table;
if (!filters.empty()) {
_sql_str += " WHERE ";
for (int i = 0; i < filters.size(); ++i) {
if (0 != i) {
_sql_str += " AND";
}
_sql_str += " (" + filters[i] + ") ";
}
}
return query(_sql_str);
}
Status MysqlScanner::get_next_row(char*** buf, unsigned long** lengths, bool* eos) {
if (!_is_open) {
return Status::InternalError("GetNextRow before open.");
}
if (NULL == buf || NULL == lengths || NULL == eos) {
return Status::InternalError("input parameter invalid.");
}
if (NULL == _my_result) {
return Status::InternalError("get next row before query.");
}
*buf = mysql_fetch_row(_my_result);
if (*buf == nullptr) {
// because we use mysql_use_result, we should check mysql error to see what error happend
// https://dev.mysql.com/doc/c-api/8.0/en/mysql-fetch-row.html
if (mysql_errno(_my_conn) != 0) {
return Status::InternalError(
strings::Substitute("fail to read MySQL result, msg=$0", mysql_error(_my_conn)));
} else {
// if mysql_errno is 0, it means query finish normally.
*eos = true;
return Status::OK();
}
}
*lengths = mysql_fetch_lengths(_my_result);
if (NULL == *lengths) {
return _error_status("mysql fetch row failed.");
}
*eos = false;
return Status::OK();
}
Status MysqlScanner::_error_status(const std::string& prefix) {
std::stringstream msg;
msg << prefix << " Err: " << mysql_error(_my_conn);
LOG(INFO) << msg.str();
return Status::InternalError(msg.str());
}
} // namespace starrocks
|
/**
* @file
* @copyright defined in Achainplus/LICENSE
*/
#pragma once
#include <eosio/chain/wasm_interface.hpp>
#include <fc/time.hpp>
#pragma GCC diagnostic ignored "-Wunused-variable"
namespace eosio { namespace chain { namespace config {
typedef __uint128_t uint128_t;
const static auto default_blocks_dir_name = "blocks";
const static auto reversible_blocks_dir_name = "reversible";
const static auto default_reversible_cache_size = 340*1024*1024ll;/// 1MB * 340 blocks based on 21 producer BFT delay
const static auto default_reversible_guard_size = 2*1024*1024ll;/// 1MB * 340 blocks based on 21 producer BFT delay
const static auto default_state_dir_name = "state";
const static auto forkdb_filename = "forkdb.dat";
const static auto default_state_size = 1*1024*1024*1024ll;
const static auto default_state_guard_size = 128*1024*1024ll;
const static uint64_t system_account_name = N(act);
const static uint64_t null_account_name = N(act.null);
const static uint64_t producers_account_name = N(act.prods);
// Active permission of producers account requires greater than 2/3 of the producers to authorize
const static uint64_t majority_producers_permission_name = N(prod.major); // greater than 1/2 of producers needed to authorize
const static uint64_t minority_producers_permission_name = N(prod.minor); // greater than 1/3 of producers needed to authorize0
const static uint64_t eosio_auth_scope = N(act.auth);
const static uint64_t eosio_all_scope = N(act.all);
const static uint64_t active_name = N(active);
const static uint64_t owner_name = N(owner);
const static uint64_t eosio_any_name = N(act.any);
const static uint64_t eosio_code_name = N(act.code);
const static int block_interval_ms = 3000;
const static int block_interval_us = block_interval_ms*1000;
const static uint64_t block_timestamp_epoch = 946684800000ll; // epoch is year 2000.
/** Percentages are fixed point with a denominator of 10,000 */
const static int percent_100 = 10000;
const static int percent_1 = 100;
static const uint32_t account_cpu_usage_average_window_ms = 24*60*60*1000l;
static const uint32_t account_net_usage_average_window_ms = 24*60*60*1000l;
static const uint32_t block_cpu_usage_average_window_ms = 60*1000l;
static const uint32_t block_size_average_window_ms = 60*1000l;
//const static uint64_t default_max_storage_size = 10 * 1024;
//const static uint32_t default_max_trx_runtime = 10*1000;
//const static uint32_t default_max_gen_trx_size = 64 * 1024;
const static uint32_t rate_limiting_precision = 1000*1000;
const static uint32_t default_max_block_net_usage = 1024 * 1024; /// at 500ms blocks and 200byte trx, this enables ~10,000 TPS burst
const static uint32_t default_target_block_net_usage_pct = 10 * percent_1; /// we target 1000 TPS
const static uint32_t default_max_transaction_net_usage = default_max_block_net_usage / 2;
const static uint32_t default_base_per_transaction_net_usage = 12; // 12 bytes (11 bytes for worst case of transaction_receipt_header + 1 byte for static_variant tag)
const static uint32_t default_net_usage_leeway = 500; // TODO: is this reasonable?
const static uint32_t default_context_free_discount_net_usage_num = 20; // TODO: is this reasonable?
const static uint32_t default_context_free_discount_net_usage_den = 100;
const static uint32_t transaction_id_net_usage = 32; // 32 bytes for the size of a transaction id
const static uint32_t default_max_block_cpu_usage = 200'000; /// max block cpu usage in microseconds
const static uint32_t default_target_block_cpu_usage_pct = 10 * percent_1;
const static uint32_t default_max_transaction_cpu_usage = 3*default_max_block_cpu_usage/4; /// max trx cpu usage in microseconds
const static uint32_t default_min_transaction_cpu_usage = 100; /// min trx cpu usage in microseconds (10000 TPS equiv)
const static uint32_t default_max_trx_lifetime = 60*60; // 1 hour
const static uint32_t default_deferred_trx_expiration_window = 10*60; // 10 minutes
const static uint32_t default_max_trx_delay = 45*24*3600; // 45 days
const static uint32_t default_max_inline_action_size = 4 * 1024; // 4 KB
const static uint16_t default_max_inline_action_depth = 4;
const static uint16_t default_max_auth_depth = 6;
const static uint32_t default_sig_cpu_bill_pct = 50 * percent_1; // billable percentage of signature recovery
const static uint16_t default_controller_thread_pool_size = 2;
const static uint32_t min_net_usage_delta_between_base_and_max_for_trx = 10*1024;
// Should be large enough to allow recovery from badly set blockchain parameters without a hard fork
// (unless net_usage_leeway is set to 0 and so are the net limits of all accounts that can help with resetting blockchain parameters).
const static uint32_t fixed_net_overhead_of_packed_trx = 16; // TODO: is this reasonable?
const static uint32_t fixed_overhead_shared_vector_ram_bytes = 16; ///< overhead accounts for fixed portion of size of shared_vector field
const static uint32_t overhead_per_row_per_index_ram_bytes = 32; ///< overhead accounts for basic tracking structures in a row per index
const static uint32_t overhead_per_account_ram_bytes = 2*1024; ///< overhead accounts for basic account storage and pre-pays features like account recovery
const static uint32_t setcode_ram_bytes_multiplier = 10; ///< multiplier on contract size to account for multiple copies and cached compilation
const static uint32_t hashing_checktime_block_size = 10*1024; /// call checktime from hashing intrinsic once per this number of bytes
const static eosio::chain::wasm_interface::vm_type default_wasm_runtime = eosio::chain::wasm_interface::vm_type::wabt;
const static uint32_t default_abi_serializer_max_time_ms = 15*1000; ///< default deadline for abi serialization methods
/**
* The number of sequential blocks produced by a single producer
*/
const static int producer_repetitions = 3;
const static int max_producers = 99;
const static size_t maximum_tracked_dpos_confirmations = 1024; ///<
static_assert(maximum_tracked_dpos_confirmations >= ((max_producers * 2 / 3) + 1) * producer_repetitions, "Settings never allow for DPOS irreversibility" );
/**
* The number of blocks produced per round is based upon all producers having a chance
* to produce all of their consecutive blocks.
*/
//const static int blocks_per_round = producer_count * producer_repetitions;
const static int irreversible_threshold_percent= 70 * percent_1;
const static uint64_t billable_alignment = 16;
//the initail schedule proposed producer is 17
//add for achainplus
const static uint32_t initial_schedule_size = 11;
template<typename T>
struct billable_size;
template<typename T>
constexpr uint64_t billable_size_v = ((billable_size<T>::value + billable_alignment - 1) / billable_alignment) * billable_alignment;
} } } // namespace eosio::chain::config
constexpr uint64_t EOS_PERCENT(uint64_t value, uint32_t percentage) {
return (value * percentage) / eosio::chain::config::percent_100;
}
template<typename Number>
Number EOS_PERCENT_CEIL(Number value, uint32_t percentage) {
return ((value * percentage) + eosio::chain::config::percent_100 - eosio::chain::config::percent_1) / eosio::chain::config::percent_100;
}
|
// Copyright (c) 2017 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//
// ---------------------------------------------------------------------------
//
// This file was generated by the CEF translator tool. If making changes by
// hand only do so within the body of existing method and function
// implementations. See the translator.README.txt file in the tools directory
// for more information.
//
#include <algorithm>
#include "libcef_dll/ctocpp/views/display_ctocpp.h"
// STATIC METHODS - Body may be edited by hand.
CefRefPtr<CefDisplay> CefDisplay::GetPrimaryDisplay() {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Execute
cef_display_t* _retval = cef_display_get_primary();
// Return type: refptr_same
return CefDisplayCToCpp::Wrap(_retval);
}
CefRefPtr<CefDisplay> CefDisplay::GetDisplayNearestPoint(const CefPoint& point,
bool input_pixel_coords) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Execute
cef_display_t* _retval = cef_display_get_nearest_point(
&point,
input_pixel_coords);
// Return type: refptr_same
return CefDisplayCToCpp::Wrap(_retval);
}
CefRefPtr<CefDisplay> CefDisplay::GetDisplayMatchingBounds(
const CefRect& bounds, bool input_pixel_coords) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Execute
cef_display_t* _retval = cef_display_get_matching_bounds(
&bounds,
input_pixel_coords);
// Return type: refptr_same
return CefDisplayCToCpp::Wrap(_retval);
}
size_t CefDisplay::GetDisplayCount() {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Execute
size_t _retval = cef_display_get_count();
// Return type: simple
return _retval;
}
void CefDisplay::GetAllDisplays(std::vector<CefRefPtr<CefDisplay>>& displays) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Translate param: displays; type: refptr_vec_same_byref
size_t displaysSize = displays.size();
size_t displaysCount = std::max(GetDisplayCount(), displaysSize);
cef_display_t** displaysList = NULL;
if (displaysCount > 0) {
displaysList = new cef_display_t*[displaysCount];
DCHECK(displaysList);
if (displaysList) {
memset(displaysList, 0, sizeof(cef_display_t*)*displaysCount);
}
if (displaysList && displaysSize > 0) {
for (size_t i = 0; i < displaysSize; ++i) {
displaysList[i] = CefDisplayCToCpp::Unwrap(displays[i]);
}
}
}
// Execute
cef_display_get_alls(
&displaysCount,
displaysList);
// Restore param:displays; type: refptr_vec_same_byref
displays.clear();
if (displaysCount > 0 && displaysList) {
for (size_t i = 0; i < displaysCount; ++i) {
displays.push_back(CefDisplayCToCpp::Wrap(displaysList[i]));
}
delete [] displaysList;
}
}
// VIRTUAL METHODS - Body may be edited by hand.
int64 CefDisplayCToCpp::GetID() {
cef_display_t* _struct = GetStruct();
if (CEF_MEMBER_MISSING(_struct, get_id))
return 0;
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Execute
int64 _retval = _struct->get_id(_struct);
// Return type: simple
return _retval;
}
float CefDisplayCToCpp::GetDeviceScaleFactor() {
cef_display_t* _struct = GetStruct();
if (CEF_MEMBER_MISSING(_struct, get_device_scale_factor))
return 0;
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Execute
float _retval = _struct->get_device_scale_factor(_struct);
// Return type: simple
return _retval;
}
void CefDisplayCToCpp::ConvertPointToPixels(CefPoint& point) {
cef_display_t* _struct = GetStruct();
if (CEF_MEMBER_MISSING(_struct, convert_point_to_pixels))
return;
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Execute
_struct->convert_point_to_pixels(_struct,
&point);
}
void CefDisplayCToCpp::ConvertPointFromPixels(CefPoint& point) {
cef_display_t* _struct = GetStruct();
if (CEF_MEMBER_MISSING(_struct, convert_point_from_pixels))
return;
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Execute
_struct->convert_point_from_pixels(_struct,
&point);
}
CefRect CefDisplayCToCpp::GetBounds() {
cef_display_t* _struct = GetStruct();
if (CEF_MEMBER_MISSING(_struct, get_bounds))
return CefRect();
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Execute
cef_rect_t _retval = _struct->get_bounds(_struct);
// Return type: simple
return _retval;
}
CefRect CefDisplayCToCpp::GetWorkArea() {
cef_display_t* _struct = GetStruct();
if (CEF_MEMBER_MISSING(_struct, get_work_area))
return CefRect();
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Execute
cef_rect_t _retval = _struct->get_work_area(_struct);
// Return type: simple
return _retval;
}
int CefDisplayCToCpp::GetRotation() {
cef_display_t* _struct = GetStruct();
if (CEF_MEMBER_MISSING(_struct, get_rotation))
return 0;
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Execute
int _retval = _struct->get_rotation(_struct);
// Return type: simple
return _retval;
}
// CONSTRUCTOR - Do not edit by hand.
CefDisplayCToCpp::CefDisplayCToCpp() {
}
template<> cef_display_t* CefCToCpp<CefDisplayCToCpp, CefDisplay,
cef_display_t>::UnwrapDerived(CefWrapperType type, CefDisplay* c) {
NOTREACHED() << "Unexpected class type: " << type;
return NULL;
}
#if DCHECK_IS_ON()
template<> base::AtomicRefCount CefCToCpp<CefDisplayCToCpp, CefDisplay,
cef_display_t>::DebugObjCt = 0;
#endif
template<> CefWrapperType CefCToCpp<CefDisplayCToCpp, CefDisplay,
cef_display_t>::kWrapperType = WT_DISPLAY;
|
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under both the GPLv2 (found in the
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a VSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "db/db_impl.h"
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include <inttypes.h>
#include "db/event_helpers.h"
#include "util/file_util.h"
#include "util/sst_file_manager_impl.h"
namespace rocksdb {
uint64_t DBImpl::FindMinPrepLogReferencedByMemTable() {
if (!allow_2pc()) {
return 0;
}
uint64_t min_log = 0;
// we must look through the memtables for two phase transactions
// that have been committed but not yet flushed
for (auto loop_cfd : *versions_->GetColumnFamilySet()) {
if (loop_cfd->IsDropped()) {
continue;
}
auto log = loop_cfd->imm()->GetMinLogContainingPrepSection();
if (log > 0 && (min_log == 0 || log < min_log)) {
min_log = log;
}
log = loop_cfd->mem()->GetMinLogContainingPrepSection();
if (log > 0 && (min_log == 0 || log < min_log)) {
min_log = log;
}
}
return min_log;
}
// TODO(myabandeh): Avoid using locks
void DBImpl::MarkLogAsHavingPrepSectionFlushed(uint64_t log) {
assert(log != 0);
std::lock_guard<std::mutex> lock(prep_heap_mutex_);
auto it = prepared_section_completed_.find(log);
assert(it != prepared_section_completed_.end());
it->second += 1;
}
// TODO(myabandeh): Avoid using locks
void DBImpl::MarkLogAsContainingPrepSection(uint64_t log) {
assert(log != 0);
std::lock_guard<std::mutex> lock(prep_heap_mutex_);
min_log_with_prep_.push(log);
auto it = prepared_section_completed_.find(log);
if (it == prepared_section_completed_.end()) {
prepared_section_completed_[log] = 0;
}
}
uint64_t DBImpl::FindMinLogContainingOutstandingPrep() {
if (!allow_2pc()) {
return 0;
}
std::lock_guard<std::mutex> lock(prep_heap_mutex_);
uint64_t min_log = 0;
// first we look in the prepared heap where we keep
// track of transactions that have been prepared (written to WAL)
// but not yet committed.
while (!min_log_with_prep_.empty()) {
min_log = min_log_with_prep_.top();
auto it = prepared_section_completed_.find(min_log);
// value was marked as 'deleted' from heap
if (it != prepared_section_completed_.end() && it->second > 0) {
it->second -= 1;
min_log_with_prep_.pop();
// back to squere one...
min_log = 0;
continue;
} else {
// found a valid value
break;
}
}
return min_log;
}
uint64_t DBImpl::MinLogNumberToKeep() {
uint64_t log_number = versions_->MinLogNumber();
if (allow_2pc()) {
// if are 2pc we must consider logs containing prepared
// sections of outstanding transactions.
//
// We must check min logs with outstanding prep before we check
// logs referneces by memtables because a log referenced by the
// first data structure could transition to the second under us.
//
// TODO(horuff): iterating over all column families under db mutex.
// should find more optimial solution
auto min_log_in_prep_heap = FindMinLogContainingOutstandingPrep();
if (min_log_in_prep_heap != 0 && min_log_in_prep_heap < log_number) {
log_number = min_log_in_prep_heap;
}
auto min_log_refed_by_mem = FindMinPrepLogReferencedByMemTable();
if (min_log_refed_by_mem != 0 && min_log_refed_by_mem < log_number) {
log_number = min_log_refed_by_mem;
}
}
return log_number;
}
// * Returns the list of live files in 'sst_live'
// If it's doing full scan:
// * Returns the list of all files in the filesystem in
// 'full_scan_candidate_files'.
// Otherwise, gets obsolete files from VersionSet.
// no_full_scan = true -- never do the full scan using GetChildren()
// force = false -- don't force the full scan, except every
// mutable_db_options_.delete_obsolete_files_period_micros
// force = true -- force the full scan
void DBImpl::FindObsoleteFiles(JobContext* job_context, bool force,
bool no_full_scan) {
mutex_.AssertHeld();
// if deletion is disabled, do nothing
if (disable_delete_obsolete_files_ > 0) {
return;
}
bool doing_the_full_scan = false;
// logic for figurint out if we're doing the full scan
if (no_full_scan) {
doing_the_full_scan = false;
} else if (force ||
mutable_db_options_.delete_obsolete_files_period_micros == 0) {
doing_the_full_scan = true;
} else {
const uint64_t now_micros = env_->NowMicros();
if ((delete_obsolete_files_last_run_ +
mutable_db_options_.delete_obsolete_files_period_micros) <
now_micros) {
doing_the_full_scan = true;
delete_obsolete_files_last_run_ = now_micros;
}
}
// don't delete files that might be currently written to from compaction
// threads
// Since job_context->min_pending_output is set, until file scan finishes,
// mutex_ cannot be released. Otherwise, we might see no min_pending_output
// here but later find newer generated unfinalized files while scannint.
if (!pending_outputs_.empty()) {
job_context->min_pending_output = *pending_outputs_.begin();
} else {
// delete all of them
job_context->min_pending_output = std::numeric_limits<uint64_t>::max();
}
// Get obsolete files. This function will also update the list of
// pending files in VersionSet().
versions_->GetObsoleteFiles(&job_context->sst_delete_files,
&job_context->manifest_delete_files,
job_context->min_pending_output);
// store the current filenum, lognum, etc
job_context->manifest_file_number = versions_->manifest_file_number();
job_context->pending_manifest_file_number =
versions_->pending_manifest_file_number();
job_context->log_number = MinLogNumberToKeep();
job_context->prev_log_number = versions_->prev_log_number();
versions_->AddLiveFiles(&job_context->sst_live);
if (doing_the_full_scan) {
for (size_t path_id = 0; path_id < immutable_db_options_.db_paths.size();
path_id++) {
// set of all files in the directory. We'll exclude files that are still
// alive in the subsequent processings.
std::vector<std::string> files;
env_->GetChildren(immutable_db_options_.db_paths[path_id].path,
&files); // Ignore errors
for (std::string file : files) {
// TODO(icanadi) clean up this mess to avoid having one-off "/" prefixes
job_context->full_scan_candidate_files.emplace_back(
"/" + file, static_cast<uint32_t>(path_id));
}
}
// Add log files in wal_dir
if (immutable_db_options_.wal_dir != dbname_) {
std::vector<std::string> log_files;
env_->GetChildren(immutable_db_options_.wal_dir,
&log_files); // Ignore errors
for (std::string log_file : log_files) {
job_context->full_scan_candidate_files.emplace_back(log_file, 0);
}
}
// Add info log files in db_log_dir
if (!immutable_db_options_.db_log_dir.empty() &&
immutable_db_options_.db_log_dir != dbname_) {
std::vector<std::string> info_log_files;
// Ignore errors
env_->GetChildren(immutable_db_options_.db_log_dir, &info_log_files);
for (std::string log_file : info_log_files) {
job_context->full_scan_candidate_files.emplace_back(log_file, 0);
}
}
}
// logs_ is empty when called during recovery, in which case there can't yet
// be any tracked obsolete logs
if (!alive_log_files_.empty() && !logs_.empty()) {
uint64_t min_log_number = job_context->log_number;
size_t num_alive_log_files = alive_log_files_.size();
// find newly obsoleted log files
while (alive_log_files_.begin()->number < min_log_number) {
auto& earliest = *alive_log_files_.begin();
if (immutable_db_options_.recycle_log_file_num >
log_recycle_files.size()) {
ROCKS_LOG_INFO(immutable_db_options_.info_log,
"adding log %" PRIu64 " to recycle list\n",
earliest.number);
log_recycle_files.push_back(earliest.number);
} else {
job_context->log_delete_files.push_back(earliest.number);
}
if (job_context->size_log_to_delete == 0) {
job_context->prev_total_log_size = total_log_size_;
job_context->num_alive_log_files = num_alive_log_files;
}
job_context->size_log_to_delete += earliest.size;
total_log_size_ -= earliest.size;
if (concurrent_prepare_) {
log_write_mutex_.Lock();
}
alive_log_files_.pop_front();
if (concurrent_prepare_) {
log_write_mutex_.Unlock();
}
// Current log should always stay alive since it can't have
// number < MinLogNumber().
assert(alive_log_files_.size());
}
while (!logs_.empty() && logs_.front().number < min_log_number) {
auto& log = logs_.front();
if (log.getting_synced) {
log_sync_cv_.Wait();
// logs_ could have changed while we were waiting.
continue;
}
logs_to_free_.push_back(log.ReleaseWriter());
{
InstrumentedMutexLock wl(&log_write_mutex_);
logs_.pop_front();
}
}
// Current log cannot be obsolete.
assert(!logs_.empty());
}
// We're just cleaning up for DB::Write().
assert(job_context->logs_to_free.empty());
job_context->logs_to_free = logs_to_free_;
job_context->log_recycle_files.assign(log_recycle_files.begin(),
log_recycle_files.end());
logs_to_free_.clear();
}
namespace {
bool CompareCandidateFile(const JobContext::CandidateFileInfo& first,
const JobContext::CandidateFileInfo& second) {
if (first.file_name > second.file_name) {
return true;
} else if (first.file_name < second.file_name) {
return false;
} else {
return (first.path_id > second.path_id);
}
}
}; // namespace
// Delete obsolete files and log status and information of file deletion
void DBImpl::DeleteObsoleteFileImpl(int job_id, const std::string& fname,
FileType type, uint64_t number,
uint32_t path_id) {
Status file_deletion_status;
if (type == kTableFile) {
file_deletion_status =
DeleteSSTFile(&immutable_db_options_, fname, path_id);
} else {
file_deletion_status = env_->DeleteFile(fname);
}
if (file_deletion_status.ok()) {
ROCKS_LOG_DEBUG(immutable_db_options_.info_log,
"[JOB %d] Delete %s type=%d #%" PRIu64 " -- %s\n", job_id,
fname.c_str(), type, number,
file_deletion_status.ToString().c_str());
} else if (env_->FileExists(fname).IsNotFound()) {
ROCKS_LOG_INFO(
immutable_db_options_.info_log,
"[JOB %d] Tried to delete a non-existing file %s type=%d #%" PRIu64
" -- %s\n",
job_id, fname.c_str(), type, number,
file_deletion_status.ToString().c_str());
} else {
ROCKS_LOG_ERROR(immutable_db_options_.info_log,
"[JOB %d] Failed to delete %s type=%d #%" PRIu64 " -- %s\n",
job_id, fname.c_str(), type, number,
file_deletion_status.ToString().c_str());
}
if (type == kTableFile) {
EventHelpers::LogAndNotifyTableFileDeletion(
&event_logger_, job_id, number, fname, file_deletion_status, GetName(),
immutable_db_options_.listeners);
}
}
// Diffs the files listed in filenames and those that do not
// belong to live files are posibly removed. Also, removes all the
// files in sst_delete_files and log_delete_files.
// It is not necessary to hold the mutex when invoking this method.
void DBImpl::PurgeObsoleteFiles(const JobContext& state, bool schedule_only) {
// we'd better have sth to delete
assert(state.HaveSomethingToDelete());
// this checks if FindObsoleteFiles() was run before. If not, don't do
// PurgeObsoleteFiles(). If FindObsoleteFiles() was run, we need to also
// run PurgeObsoleteFiles(), even if disable_delete_obsolete_files_ is true
if (state.manifest_file_number == 0) {
return;
}
// Now, convert live list to an unordered map, WITHOUT mutex held;
// set is slow.
std::unordered_map<uint64_t, const FileDescriptor*> sst_live_map;
for (const FileDescriptor& fd : state.sst_live) {
sst_live_map[fd.GetNumber()] = &fd;
}
std::unordered_set<uint64_t> log_recycle_files_set(
state.log_recycle_files.begin(), state.log_recycle_files.end());
auto candidate_files = state.full_scan_candidate_files;
candidate_files.reserve(
candidate_files.size() + state.sst_delete_files.size() +
state.log_delete_files.size() + state.manifest_delete_files.size());
// We may ignore the dbname when generating the file names.
const char* kDumbDbName = "";
for (auto file : state.sst_delete_files) {
candidate_files.emplace_back(
MakeTableFileName(kDumbDbName, file->fd.GetNumber()),
file->fd.GetPathId());
if (file->table_reader_handle) {
table_cache_->Release(file->table_reader_handle);
}
delete file;
}
for (auto file_num : state.log_delete_files) {
if (file_num > 0) {
candidate_files.emplace_back(LogFileName(kDumbDbName, file_num), 0);
}
}
for (const auto& filename : state.manifest_delete_files) {
candidate_files.emplace_back(filename, 0);
}
// dedup state.candidate_files so we don't try to delete the same
// file twice
std::sort(candidate_files.begin(), candidate_files.end(),
CompareCandidateFile);
candidate_files.erase(
std::unique(candidate_files.begin(), candidate_files.end()),
candidate_files.end());
if (state.prev_total_log_size > 0) {
ROCKS_LOG_INFO(immutable_db_options_.info_log,
"[JOB %d] Try to delete WAL files size %" PRIu64
", prev total WAL file size %" PRIu64
", number of live WAL files %" ROCKSDB_PRIszt ".\n",
state.job_id, state.size_log_to_delete,
state.prev_total_log_size, state.num_alive_log_files);
}
std::vector<std::string> old_info_log_files;
InfoLogPrefix info_log_prefix(!immutable_db_options_.db_log_dir.empty(),
dbname_);
for (const auto& candidate_file : candidate_files) {
std::string to_delete = candidate_file.file_name;
uint32_t path_id = candidate_file.path_id;
uint64_t number;
FileType type;
// Ignore file if we cannot recognize it.
if (!ParseFileName(to_delete, &number, info_log_prefix.prefix, &type)) {
continue;
}
bool keep = true;
switch (type) {
case kLogFile:
keep = ((number >= state.log_number) ||
(number == state.prev_log_number) ||
(log_recycle_files_set.find(number) !=
log_recycle_files_set.end()));
break;
case kDescriptorFile:
// Keep my manifest file, and any newer incarnations'
// (can happen during manifest roll)
keep = (number >= state.manifest_file_number);
break;
case kTableFile:
// If the second condition is not there, this makes
// DontDeletePendingOutputs fail
keep = (sst_live_map.find(number) != sst_live_map.end()) ||
number >= state.min_pending_output;
break;
case kTempFile:
// Any temp files that are currently being written to must
// be recorded in pending_outputs_, which is inserted into "live".
// Also, SetCurrentFile creates a temp file when writing out new
// manifest, which is equal to state.pending_manifest_file_number. We
// should not delete that file
//
// TODO(yhchiang): carefully modify the third condition to safely
// remove the temp options files.
keep = (sst_live_map.find(number) != sst_live_map.end()) ||
(number == state.pending_manifest_file_number) ||
(to_delete.find(kOptionsFileNamePrefix) != std::string::npos);
break;
case kInfoLogFile:
keep = true;
if (number != 0) {
old_info_log_files.push_back(to_delete);
}
break;
case kCurrentFile:
case kDBLockFile:
case kIdentityFile:
case kMetaDatabase:
case kOptionsFile:
case kBlobFile:
keep = true;
break;
}
if (keep) {
continue;
}
std::string fname;
if (type == kTableFile) {
// evict from cache
TableCache::Evict(table_cache_.get(), number);
fname = TableFileName(immutable_db_options_.db_paths, number, path_id);
} else {
fname = ((type == kLogFile) ? immutable_db_options_.wal_dir : dbname_) +
"/" + to_delete;
}
#ifndef ROCKSDB_LITE
if (type == kLogFile && (immutable_db_options_.wal_ttl_seconds > 0 ||
immutable_db_options_.wal_size_limit_mb > 0)) {
wal_manager_.ArchiveWALFile(fname, number);
continue;
}
#endif // !ROCKSDB_LITE
Status file_deletion_status;
if (schedule_only) {
InstrumentedMutexLock guard_lock(&mutex_);
SchedulePendingPurge(fname, type, number, path_id, state.job_id);
} else {
DeleteObsoleteFileImpl(state.job_id, fname, type, number, path_id);
}
}
// Delete old info log files.
size_t old_info_log_file_count = old_info_log_files.size();
if (old_info_log_file_count != 0 &&
old_info_log_file_count >= immutable_db_options_.keep_log_file_num) {
std::sort(old_info_log_files.begin(), old_info_log_files.end());
size_t end =
old_info_log_file_count - immutable_db_options_.keep_log_file_num;
for (unsigned int i = 0; i <= end; i++) {
std::string& to_delete = old_info_log_files.at(i);
std::string full_path_to_delete =
(immutable_db_options_.db_log_dir.empty()
? dbname_
: immutable_db_options_.db_log_dir) +
"/" + to_delete;
ROCKS_LOG_INFO(immutable_db_options_.info_log,
"[JOB %d] Delete info log file %s\n", state.job_id,
full_path_to_delete.c_str());
Status s = env_->DeleteFile(full_path_to_delete);
if (!s.ok()) {
if (env_->FileExists(full_path_to_delete).IsNotFound()) {
ROCKS_LOG_INFO(
immutable_db_options_.info_log,
"[JOB %d] Tried to delete non-existing info log file %s FAILED "
"-- %s\n",
state.job_id, to_delete.c_str(), s.ToString().c_str());
} else {
ROCKS_LOG_ERROR(immutable_db_options_.info_log,
"[JOB %d] Delete info log file %s FAILED -- %s\n",
state.job_id, to_delete.c_str(),
s.ToString().c_str());
}
}
}
}
#ifndef ROCKSDB_LITE
wal_manager_.PurgeObsoleteWALFiles();
#endif // ROCKSDB_LITE
LogFlush(immutable_db_options_.info_log);
}
void DBImpl::DeleteObsoleteFiles() {
mutex_.AssertHeld();
JobContext job_context(next_job_id_.fetch_add(1));
FindObsoleteFiles(&job_context, true);
mutex_.Unlock();
if (job_context.HaveSomethingToDelete()) {
PurgeObsoleteFiles(job_context);
}
job_context.Clean();
mutex_.Lock();
}
} // namespace rocksdb
|
#include "tensorflow/core/lib/strings/str_util.h"
#include <gtest/gtest.h>
namespace tensorflow {
TEST(CEscape, Basic) {
EXPECT_EQ(str_util::CEscape("hello"), "hello");
EXPECT_EQ(str_util::CEscape("hello\n"), "hello\\n");
EXPECT_EQ(str_util::CEscape("hello\r"), "hello\\r");
EXPECT_EQ(str_util::CEscape("\t\r\"'"), "\\t\\r\\\"\\'");
EXPECT_EQ(str_util::CEscape("\320hi\200"), "\\320hi\\200");
}
string ExpectCUnescapeSuccess(StringPiece source) {
string dest;
string error;
EXPECT_TRUE(str_util::CUnescape(source, &dest, &error)) << error;
return dest;
}
TEST(CUnescape, Basic) {
EXPECT_EQ("hello", ExpectCUnescapeSuccess("hello"));
EXPECT_EQ("hello\n", ExpectCUnescapeSuccess("hello\\n"));
EXPECT_EQ("hello\r", ExpectCUnescapeSuccess("hello\\r"));
EXPECT_EQ("\t\r\"'", ExpectCUnescapeSuccess("\\t\\r\\\"\\'"));
EXPECT_EQ("\320hi\200", ExpectCUnescapeSuccess("\\320hi\\200"));
}
TEST(NumericParse32, Basic) {
int32 val = -1234;
EXPECT_TRUE(str_util::NumericParse32("0", &val) && val == 0);
EXPECT_TRUE(str_util::NumericParse32("123", &val) && val == 123);
EXPECT_TRUE(str_util::NumericParse32("-375", &val) && val == -375);
EXPECT_FALSE(str_util::NumericParse32("123hello", &val));
EXPECT_FALSE(str_util::NumericParse32("hello123", &val));
}
TEST(StripTrailingWhitespace, Basic) {
string test;
test = "hello";
str_util::StripTrailingWhitespace(&test);
EXPECT_EQ(test, "hello");
test = "foo ";
str_util::StripTrailingWhitespace(&test);
EXPECT_EQ(test, "foo");
test = " ";
str_util::StripTrailingWhitespace(&test);
EXPECT_EQ(test, "");
test = "";
str_util::StripTrailingWhitespace(&test);
EXPECT_EQ(test, "");
test = " abc\t";
str_util::StripTrailingWhitespace(&test);
EXPECT_EQ(test, " abc");
}
TEST(RemoveLeadingWhitespace, Basic) {
string text = " \t \n \r Quick\t";
StringPiece data(text);
// check that all whitespace is removed
EXPECT_EQ(str_util::RemoveLeadingWhitespace(&data), 11);
EXPECT_EQ(data, StringPiece("Quick\t"));
// check that non-whitespace is not removed
EXPECT_EQ(str_util::RemoveLeadingWhitespace(&data), 0);
EXPECT_EQ(data, StringPiece("Quick\t"));
}
TEST(RemoveLeadingWhitespace, TerminationHandling) {
// check termination handling
string text = "\t";
StringPiece data(text);
EXPECT_EQ(str_util::RemoveLeadingWhitespace(&data), 1);
EXPECT_EQ(data, StringPiece(""));
// check termination handling again
EXPECT_EQ(str_util::RemoveLeadingWhitespace(&data), 0);
EXPECT_EQ(data, StringPiece(""));
}
TEST(RemoveTrailingWhitespace, Basic) {
string text = " \t \n \r Quick \t";
StringPiece data(text);
// check that all whitespace is removed
EXPECT_EQ(str_util::RemoveTrailingWhitespace(&data), 2);
EXPECT_EQ(data, StringPiece(" \t \n \r Quick"));
// check that non-whitespace is not removed
EXPECT_EQ(str_util::RemoveTrailingWhitespace(&data), 0);
EXPECT_EQ(data, StringPiece(" \t \n \r Quick"));
}
TEST(RemoveTrailingWhitespace, TerminationHandling) {
// check termination handling
string text = "\t";
StringPiece data(text);
EXPECT_EQ(str_util::RemoveTrailingWhitespace(&data), 1);
EXPECT_EQ(data, StringPiece(""));
// check termination handling again
EXPECT_EQ(str_util::RemoveTrailingWhitespace(&data), 0);
EXPECT_EQ(data, StringPiece(""));
}
TEST(RemoveWhitespaceContext, Basic) {
string text = " \t \n \r Quick \t";
StringPiece data(text);
// check that all whitespace is removed
EXPECT_EQ(str_util::RemoveWhitespaceContext(&data), 13);
EXPECT_EQ(data, StringPiece("Quick"));
// check that non-whitespace is not removed
EXPECT_EQ(str_util::RemoveWhitespaceContext(&data), 0);
EXPECT_EQ(data, StringPiece("Quick"));
// Test empty string
text = "";
data = text;
EXPECT_EQ(str_util::RemoveWhitespaceContext(&data), 0);
EXPECT_EQ(data, StringPiece(""));
}
void TestConsumeLeadingDigits(StringPiece s, int64 expected,
StringPiece remaining) {
uint64 v;
StringPiece input(s);
if (str_util::ConsumeLeadingDigits(&input, &v)) {
EXPECT_EQ(v, static_cast<uint64>(expected));
EXPECT_EQ(input, remaining);
} else {
EXPECT_LT(expected, 0);
EXPECT_EQ(input, remaining);
}
}
TEST(ConsumeLeadingDigits, Basic) {
TestConsumeLeadingDigits("123", 123, "");
TestConsumeLeadingDigits("a123", -1, "a123");
TestConsumeLeadingDigits("9_", 9, "_");
TestConsumeLeadingDigits("11111111111xyz", 11111111111ll, "xyz");
// Overflow case
TestConsumeLeadingDigits("1111111111111111111111111111111xyz", -1,
"1111111111111111111111111111111xyz");
// 2^64
TestConsumeLeadingDigits("18446744073709551616xyz", -1,
"18446744073709551616xyz");
// 2^64-1
TestConsumeLeadingDigits("18446744073709551615xyz", 18446744073709551615ull,
"xyz");
}
TEST(ConsumePrefix, Basic) {
string s("abcdef");
StringPiece input(s);
EXPECT_FALSE(str_util::ConsumePrefix(&input, "abcdefg"));
EXPECT_EQ(input, "abcdef");
EXPECT_FALSE(str_util::ConsumePrefix(&input, "abce"));
EXPECT_EQ(input, "abcdef");
EXPECT_TRUE(str_util::ConsumePrefix(&input, ""));
EXPECT_EQ(input, "abcdef");
EXPECT_FALSE(str_util::ConsumePrefix(&input, "abcdeg"));
EXPECT_EQ(input, "abcdef");
EXPECT_TRUE(str_util::ConsumePrefix(&input, "abcdef"));
EXPECT_EQ(input, "");
input = s;
EXPECT_TRUE(str_util::ConsumePrefix(&input, "abcde"));
EXPECT_EQ(input, "f");
}
TEST(JoinStrings, Basic) {
std::vector<string> s;
s = {"hi"};
EXPECT_EQ(str_util::Join(s, " "), "hi");
s = {"hi", "there", "strings"};
EXPECT_EQ(str_util::Join(s, " "), "hi there strings");
std::vector<StringPiece> sp;
sp = {"hi"};
EXPECT_EQ(str_util::Join(sp, ",,"), "hi");
sp = {"hi", "there", "strings"};
EXPECT_EQ(str_util::Join(sp, "--"), "hi--there--strings");
}
TEST(Split, Basic) {
EXPECT_TRUE(str_util::Split("", ',').empty());
EXPECT_EQ(str_util::Join(str_util::Split("a", ','), "|"), "a");
EXPECT_EQ(str_util::Join(str_util::Split(",", ','), "|"), "|");
EXPECT_EQ(str_util::Join(str_util::Split("a,b,c", ','), "|"), "a|b|c");
EXPECT_EQ(str_util::Join(str_util::Split("a,,,b,,c,", ','), "|"),
"a|||b||c|");
EXPECT_EQ(str_util::Join(
str_util::Split("a,,,b,,c,", ',', str_util::SkipEmpty()), "|"),
"a|b|c");
EXPECT_EQ(
str_util::Join(
str_util::Split("a, ,b,,c,", ',', str_util::SkipWhitespace()), "|"),
"a|b|c");
}
TEST(SplitAndParseAsInts, Basic) {
std::vector<int32> nums;
EXPECT_TRUE(str_util::SplitAndParseAsInts("", ',', &nums));
EXPECT_EQ(nums.size(), 0);
EXPECT_TRUE(str_util::SplitAndParseAsInts("134", ',', &nums));
EXPECT_EQ(nums.size(), 1);
EXPECT_EQ(nums[0], 134);
EXPECT_TRUE(str_util::SplitAndParseAsInts("134,2,13,-5", ',', &nums));
EXPECT_EQ(nums.size(), 4);
EXPECT_EQ(nums[0], 134);
EXPECT_EQ(nums[1], 2);
EXPECT_EQ(nums[2], 13);
EXPECT_EQ(nums[3], -5);
EXPECT_FALSE(str_util::SplitAndParseAsInts("abc", ',', &nums));
EXPECT_FALSE(str_util::SplitAndParseAsInts("-13,abc", ',', &nums));
EXPECT_FALSE(str_util::SplitAndParseAsInts("13,abc,5", ',', &nums));
}
TEST(Lowercase, Basic) {
EXPECT_EQ("", str_util::Lowercase(""));
EXPECT_EQ("hello", str_util::Lowercase("hello"));
EXPECT_EQ("hello world", str_util::Lowercase("Hello World"));
}
TEST(Uppercase, Basic) {
EXPECT_EQ("", str_util::Uppercase(""));
EXPECT_EQ("HELLO", str_util::Uppercase("hello"));
EXPECT_EQ("HELLO WORLD", str_util::Uppercase("Hello World"));
}
TEST(TitlecaseString, Basic) {
string s = "sparse_lookup";
str_util::TitlecaseString(&s, "_");
ASSERT_EQ(s, "Sparse_Lookup");
s = "sparse_lookup";
str_util::TitlecaseString(&s, " ");
ASSERT_EQ(s, "Sparse_lookup");
s = "dense";
str_util::TitlecaseString(&s, " ");
ASSERT_EQ(s, "Dense");
}
} // namespace tensorflow
|
/**
* cpp/virtual.cc
*
* Contains the (empty) definitions for some of the functions required by g++.
**/
// TODO: Trigger kernel panic if one of these occur?
// Function for invalid virtual calls
extern "C" void __cxa_pure_virtual() {
}
extern "C" void __cxa__virtual() {
}
// We don't want to call anything at kernel exit (yet)
extern "C" void __cxa_atexit() {
}
namespace __cxxabiv1
{
// TODO: these are only stubs!
// The ABI requires a 64-bit type.
__extension__ typedef int __guard __attribute__((mode(__DI__)));
extern "C" int __cxa_guard_acquire (__guard *g)
{
return !*(char *)(g);
}
extern "C" void __cxa_guard_release (__guard *g)
{
*(char *)g = 1;
}
extern "C" void __cxa_guard_abort (__guard *)
{
}
}
|
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
int len = 0;
ListNode* head_copy = head;
while (head_copy != nullptr) {
head_copy = head_copy->next;
len++;
}
if (n == len) {
ListNode* new_head = head->next;
delete head;
return new_head;
}
head_copy = head;
for (int i = 1; i < (len - n); i++) {
head_copy = head_copy->next;
}
ListNode* to_delete = head_copy->next;
head_copy->next = head_copy->next->next;
delete to_delete;
return head;
}
};
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/view_ax_platform_node_delegate_win.h"
#include <oleacc.h>
#include <wrl/client.h>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/win/scoped_bstr.h"
#include "base/win/scoped_variant.h"
#include "third_party/iaccessible2/ia2_api_all.h"
#include "ui/accessibility/ax_constants.mojom.h"
#include "ui/accessibility/platform/ax_platform_node_win.h"
#include "ui/views/accessibility/test_list_grid_view.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/scroll_view.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/test/views_test_base.h"
using base::win::ScopedBstr;
using base::win::ScopedVariant;
using Microsoft::WRL::ComPtr;
namespace views {
namespace test {
#define EXPECT_UIA_BOOL_EQ(node, property_id, expected) \
{ \
ScopedVariant expectedVariant(expected); \
ASSERT_EQ(VT_BOOL, expectedVariant.type()); \
ScopedVariant actual; \
ASSERT_HRESULT_SUCCEEDED( \
node->GetPropertyValue(property_id, actual.Receive())); \
EXPECT_EQ(expectedVariant.ptr()->boolVal, actual.ptr()->boolVal); \
}
namespace {
// Whether |left| represents the same COM object as |right|.
template <typename T, typename U>
bool IsSameObject(T* left, U* right) {
if (!left && !right)
return true;
if (!left || !right)
return false;
ComPtr<IUnknown> left_unknown;
left->QueryInterface(IID_PPV_ARGS(&left_unknown));
ComPtr<IUnknown> right_unknown;
right->QueryInterface(IID_PPV_ARGS(&right_unknown));
return left_unknown == right_unknown;
}
} // namespace
class ViewAXPlatformNodeDelegateWinTest : public ViewsTestBase {
public:
ViewAXPlatformNodeDelegateWinTest() = default;
~ViewAXPlatformNodeDelegateWinTest() override = default;
protected:
void GetIAccessible2InterfaceForView(View* view, IAccessible2_2** result) {
ComPtr<IAccessible> view_accessible(view->GetNativeViewAccessible());
ComPtr<IServiceProvider> service_provider;
ASSERT_EQ(S_OK, view_accessible.As(&service_provider));
ASSERT_EQ(S_OK, service_provider->QueryService(IID_IAccessible2_2, result));
}
ComPtr<IRawElementProviderSimple> GetIRawElementProviderSimple(View* view) {
ComPtr<IRawElementProviderSimple> result;
EXPECT_HRESULT_SUCCEEDED(view->GetNativeViewAccessible()->QueryInterface(
__uuidof(IRawElementProviderSimple), &result));
return result;
}
ComPtr<IAccessible2> ToIAccessible2(ComPtr<IAccessible> accessible) {
CHECK(accessible);
ComPtr<IServiceProvider> service_provider;
accessible.As(&service_provider);
ComPtr<IAccessible2> result;
CHECK(SUCCEEDED(service_provider->QueryService(IID_IAccessible2,
IID_PPV_ARGS(&result))));
return result;
}
};
TEST_F(ViewAXPlatformNodeDelegateWinTest, TextfieldAccessibility) {
Widget widget;
Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP);
init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget.Init(std::move(init_params));
View* content = widget.SetContentsView(std::make_unique<View>());
Textfield* textfield = new Textfield;
textfield->SetAccessibleName(u"Name");
textfield->SetText(u"Value");
content->AddChildView(textfield);
ComPtr<IAccessible> content_accessible(content->GetNativeViewAccessible());
LONG child_count = 0;
ASSERT_EQ(S_OK, content_accessible->get_accChildCount(&child_count));
EXPECT_EQ(1, child_count);
ComPtr<IDispatch> textfield_dispatch;
ComPtr<IAccessible> textfield_accessible;
ScopedVariant child_index(1);
ASSERT_EQ(S_OK,
content_accessible->get_accChild(child_index, &textfield_dispatch));
ASSERT_EQ(S_OK, textfield_dispatch.As(&textfield_accessible));
ASSERT_EQ(S_OK, textfield_accessible->get_accChildCount(&child_count));
EXPECT_EQ(0, child_count)
<< "Text fields should be leaf nodes on this platform, otherwise no "
"descendants will be recognized by assistive software.";
ScopedBstr name;
ScopedVariant childid_self(CHILDID_SELF);
ASSERT_EQ(S_OK,
textfield_accessible->get_accName(childid_self, name.Receive()));
EXPECT_STREQ(L"Name", name.Get());
ScopedBstr value;
ASSERT_EQ(S_OK,
textfield_accessible->get_accValue(childid_self, value.Receive()));
EXPECT_STREQ(L"Value", value.Get());
ScopedBstr new_value(L"New value");
ASSERT_EQ(S_OK,
textfield_accessible->put_accValue(childid_self, new_value.Get()));
EXPECT_EQ(u"New value", textfield->GetText());
}
TEST_F(ViewAXPlatformNodeDelegateWinTest, TextfieldAssociatedLabel) {
Widget widget;
Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP);
init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget.Init(std::move(init_params));
View* content = widget.SetContentsView(std::make_unique<View>());
Label* label = new Label(u"Label");
content->AddChildView(label);
Textfield* textfield = new Textfield;
textfield->SetAssociatedLabel(label);
content->AddChildView(textfield);
ComPtr<IAccessible> content_accessible(content->GetNativeViewAccessible());
LONG child_count = 0;
ASSERT_EQ(S_OK, content_accessible->get_accChildCount(&child_count));
ASSERT_EQ(2L, child_count);
ComPtr<IDispatch> textfield_dispatch;
ComPtr<IAccessible> textfield_accessible;
ScopedVariant child_index(2);
ASSERT_EQ(S_OK,
content_accessible->get_accChild(child_index, &textfield_dispatch));
ASSERT_EQ(S_OK, textfield_dispatch.As(&textfield_accessible));
ScopedBstr name;
ScopedVariant childid_self(CHILDID_SELF);
ASSERT_EQ(S_OK,
textfield_accessible->get_accName(childid_self, name.Receive()));
ASSERT_STREQ(L"Label", name.Get());
ComPtr<IAccessible2_2> textfield_ia2;
EXPECT_EQ(S_OK, textfield_accessible.As(&textfield_ia2));
ScopedBstr type(IA2_RELATION_LABELLED_BY);
IUnknown** targets;
LONG n_targets;
EXPECT_EQ(S_OK, textfield_ia2->get_relationTargetsOfType(
type.Get(), 0, &targets, &n_targets));
ASSERT_EQ(1, n_targets);
ComPtr<IUnknown> label_unknown(targets[0]);
ComPtr<IAccessible> label_accessible;
ASSERT_EQ(S_OK, label_unknown.As(&label_accessible));
ScopedVariant role;
EXPECT_EQ(S_OK, label_accessible->get_accRole(childid_self, role.Receive()));
EXPECT_EQ(ROLE_SYSTEM_STATICTEXT, V_I4(role.ptr()));
}
// A subclass of ViewAXPlatformNodeDelegateWinTest that we run twice,
// first where we create an transient child widget (child = false), the second
// time where we create a child widget (child = true).
class ViewAXPlatformNodeDelegateWinTestWithBoolChildFlag
: public ViewAXPlatformNodeDelegateWinTest,
public testing::WithParamInterface<bool> {
public:
ViewAXPlatformNodeDelegateWinTestWithBoolChildFlag() = default;
ViewAXPlatformNodeDelegateWinTestWithBoolChildFlag(
const ViewAXPlatformNodeDelegateWinTestWithBoolChildFlag&) = delete;
ViewAXPlatformNodeDelegateWinTestWithBoolChildFlag& operator=(
const ViewAXPlatformNodeDelegateWinTestWithBoolChildFlag&) = delete;
~ViewAXPlatformNodeDelegateWinTestWithBoolChildFlag() override = default;
};
INSTANTIATE_TEST_SUITE_P(All,
ViewAXPlatformNodeDelegateWinTestWithBoolChildFlag,
testing::Bool());
TEST_P(ViewAXPlatformNodeDelegateWinTestWithBoolChildFlag, AuraChildWidgets) {
// Create the parent widget.
Widget widget;
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_WINDOW);
init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
init_params.bounds = gfx::Rect(0, 0, 400, 200);
widget.Init(std::move(init_params));
widget.Show();
// Initially it has 1 child.
ComPtr<IAccessible> root_view_accessible(
widget.GetRootView()->GetNativeViewAccessible());
LONG child_count = 0;
ASSERT_EQ(S_OK, root_view_accessible->get_accChildCount(&child_count));
ASSERT_EQ(1L, child_count);
// Create the child widget, one of two ways (see below).
Widget child_widget;
Widget::InitParams child_init_params =
CreateParams(Widget::InitParams::TYPE_BUBBLE);
child_init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
child_init_params.parent = widget.GetNativeView();
child_init_params.bounds = gfx::Rect(30, 40, 100, 50);
// NOTE: this test is run two times, GetParam() returns a different
// value each time. The first time we test with child = false,
// making this an owned widget (a transient child). The second time
// we test with child = true, making it a child widget.
child_init_params.child = GetParam();
child_widget.Init(std::move(child_init_params));
child_widget.Show();
// Now the IAccessible for the parent widget should have 2 children.
ASSERT_EQ(S_OK, root_view_accessible->get_accChildCount(&child_count));
ASSERT_EQ(2L, child_count);
// Ensure the bounds of the parent widget are as expected.
ScopedVariant childid_self(CHILDID_SELF);
LONG x, y, width, height;
ASSERT_EQ(S_OK, root_view_accessible->accLocation(&x, &y, &width, &height,
childid_self));
EXPECT_EQ(0, x);
EXPECT_EQ(0, y);
EXPECT_EQ(400, width);
EXPECT_EQ(200, height);
// Get the IAccessible for the second child of the parent widget,
// which should be the one for our child widget.
ComPtr<IDispatch> child_widget_dispatch;
ComPtr<IAccessible> child_widget_accessible;
ScopedVariant child_index_2(2);
ASSERT_EQ(S_OK, root_view_accessible->get_accChild(child_index_2,
&child_widget_dispatch));
ASSERT_EQ(S_OK, child_widget_dispatch.As(&child_widget_accessible));
// Check the bounds of the IAccessible for the child widget.
// This is a sanity check to make sure we have the right object
// and not some other view.
ASSERT_EQ(S_OK, child_widget_accessible->accLocation(&x, &y, &width, &height,
childid_self));
EXPECT_EQ(30, x);
EXPECT_EQ(40, y);
EXPECT_EQ(100, width);
EXPECT_EQ(50, height);
// Now make sure that querying the parent of the child gets us back to
// the original parent.
ComPtr<IDispatch> child_widget_parent_dispatch;
ComPtr<IAccessible> child_widget_parent_accessible;
ASSERT_EQ(S_OK, child_widget_accessible->get_accParent(
&child_widget_parent_dispatch));
ASSERT_EQ(S_OK,
child_widget_parent_dispatch.As(&child_widget_parent_accessible));
EXPECT_EQ(root_view_accessible.Get(), child_widget_parent_accessible.Get());
}
// Flaky on Windows: https://crbug.com/461837.
TEST_F(ViewAXPlatformNodeDelegateWinTest, DISABLED_RetrieveAllAlerts) {
Widget widget;
Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP);
init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget.Init(std::move(init_params));
View* content = widget.SetContentsView(std::make_unique<View>());
View* infobar = new View;
content->AddChildView(infobar);
View* infobar2 = new View;
content->AddChildView(infobar2);
View* root_view = content->parent();
ASSERT_EQ(nullptr, root_view->parent());
ComPtr<IAccessible2_2> root_view_accessible;
GetIAccessible2InterfaceForView(root_view, &root_view_accessible);
ComPtr<IAccessible2_2> infobar_accessible;
GetIAccessible2InterfaceForView(infobar, &infobar_accessible);
ComPtr<IAccessible2_2> infobar2_accessible;
GetIAccessible2InterfaceForView(infobar2, &infobar2_accessible);
// Initially, there are no alerts
ScopedBstr alerts_bstr(L"alerts");
IUnknown** targets;
LONG n_targets;
ASSERT_EQ(S_FALSE, root_view_accessible->get_relationTargetsOfType(
alerts_bstr.Get(), 0, &targets, &n_targets));
ASSERT_EQ(0, n_targets);
// Fire alert events on the infobars.
infobar->NotifyAccessibilityEvent(ax::mojom::Event::kAlert, true);
infobar2->NotifyAccessibilityEvent(ax::mojom::Event::kAlert, true);
// Now calling get_relationTargetsOfType should retrieve the alerts.
ASSERT_EQ(S_OK, root_view_accessible->get_relationTargetsOfType(
alerts_bstr.Get(), 0, &targets, &n_targets));
ASSERT_EQ(2, n_targets);
ASSERT_TRUE(IsSameObject(infobar_accessible.Get(), targets[0]));
ASSERT_TRUE(IsSameObject(infobar2_accessible.Get(), targets[1]));
CoTaskMemFree(targets);
// If we set max_targets to 1, we should only get the first one.
ASSERT_EQ(S_OK, root_view_accessible->get_relationTargetsOfType(
alerts_bstr.Get(), 1, &targets, &n_targets));
ASSERT_EQ(1, n_targets);
ASSERT_TRUE(IsSameObject(infobar_accessible.Get(), targets[0]));
CoTaskMemFree(targets);
// If we delete the first view, we should only get the second one now.
delete infobar;
ASSERT_EQ(S_OK, root_view_accessible->get_relationTargetsOfType(
alerts_bstr.Get(), 0, &targets, &n_targets));
ASSERT_EQ(1, n_targets);
ASSERT_TRUE(IsSameObject(infobar2_accessible.Get(), targets[0]));
CoTaskMemFree(targets);
}
// Test trying to retrieve child widgets during window close does not crash.
TEST_F(ViewAXPlatformNodeDelegateWinTest, GetAllOwnedWidgetsCrash) {
Widget widget;
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_WINDOW);
init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget.Init(std::move(init_params));
widget.CloseNow();
LONG child_count = 0;
ComPtr<IAccessible> content_accessible(
widget.GetRootView()->GetNativeViewAccessible());
EXPECT_EQ(S_OK, content_accessible->get_accChildCount(&child_count));
EXPECT_EQ(1L, child_count);
}
TEST_F(ViewAXPlatformNodeDelegateWinTest, WindowHasRoleApplication) {
// We expect that our internal window object does not expose
// ROLE_SYSTEM_WINDOW, but ROLE_SYSTEM_PANE instead.
Widget widget;
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_WINDOW);
init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget.Init(std::move(init_params));
ComPtr<IAccessible> accessible(
widget.GetRootView()->GetNativeViewAccessible());
ScopedVariant childid_self(CHILDID_SELF);
ScopedVariant role;
EXPECT_EQ(S_OK, accessible->get_accRole(childid_self, role.Receive()));
EXPECT_EQ(VT_I4, role.type());
EXPECT_EQ(ROLE_SYSTEM_PANE, V_I4(role.ptr()));
}
TEST_F(ViewAXPlatformNodeDelegateWinTest, Overrides) {
// We expect that our internal window object does not expose
// ROLE_SYSTEM_WINDOW, but ROLE_SYSTEM_PANE instead.
Widget widget;
Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP);
init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget.Init(std::move(init_params));
View* contents_view = widget.SetContentsView(std::make_unique<View>());
View* alert_view = new ScrollView;
alert_view->GetViewAccessibility().OverrideRole(ax::mojom::Role::kAlert);
alert_view->GetViewAccessibility().OverrideName(u"Name");
alert_view->GetViewAccessibility().OverrideDescription("Description");
alert_view->GetViewAccessibility().OverrideIsLeaf(true);
contents_view->AddChildView(alert_view);
// Descendant should be ignored because the parent uses OverrideIsLeaf().
View* ignored_descendant = new View;
alert_view->AddChildView(ignored_descendant);
ComPtr<IAccessible> content_accessible(
contents_view->GetNativeViewAccessible());
ScopedVariant child_index(1);
// Role.
ScopedVariant role;
EXPECT_EQ(S_OK, content_accessible->get_accRole(child_index, role.Receive()));
EXPECT_EQ(VT_I4, role.type());
EXPECT_EQ(ROLE_SYSTEM_ALERT, V_I4(role.ptr()));
// Name.
ScopedBstr name;
ASSERT_EQ(S_OK, content_accessible->get_accName(child_index, name.Receive()));
ASSERT_STREQ(L"Name", name.Get());
// Description.
ScopedBstr description;
ASSERT_EQ(S_OK, content_accessible->get_accDescription(
child_index, description.Receive()));
ASSERT_STREQ(L"Description", description.Get());
// Get the child accessible.
ComPtr<IDispatch> alert_dispatch;
ComPtr<IAccessible> alert_accessible;
ASSERT_EQ(S_OK,
content_accessible->get_accChild(child_index, &alert_dispatch));
ASSERT_EQ(S_OK, alert_dispatch.As(&alert_accessible));
// Child accessible is a leaf.
LONG child_count = 0;
ASSERT_EQ(S_OK, alert_accessible->get_accChildCount(&child_count));
ASSERT_EQ(0, child_count);
ComPtr<IDispatch> child_dispatch;
ASSERT_EQ(E_INVALIDARG,
alert_accessible->get_accChild(child_index, &child_dispatch));
ASSERT_EQ(child_dispatch.Get(), nullptr);
}
TEST_F(ViewAXPlatformNodeDelegateWinTest, GridRowColumnCount) {
Widget widget;
Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP);
init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget.Init(std::move(init_params));
View* content = widget.SetContentsView(std::make_unique<View>());
TestListGridView* grid = new TestListGridView();
content->AddChildView(grid);
Microsoft::WRL::ComPtr<IGridProvider> grid_provider;
EXPECT_HRESULT_SUCCEEDED(
grid->GetViewAccessibility().GetNativeObject()->QueryInterface(
__uuidof(IGridProvider), &grid_provider));
// If set, aria row/column count takes precedence over table row/column count.
// Expect E_UNEXPECTED if the result is kUnknownAriaColumnOrRowCount (-1) or
// if neither is set.
int row_count;
int column_count;
// aria row/column count = not set
// table row/column count = not set
grid->UnsetAriaTableSize();
grid->UnsetTableSize();
EXPECT_HRESULT_SUCCEEDED(grid_provider->get_RowCount(&row_count));
EXPECT_HRESULT_SUCCEEDED(grid_provider->get_ColumnCount(&column_count));
EXPECT_EQ(0, row_count);
EXPECT_EQ(0, column_count);
// To do still: When nothing is set, currently
// AXPlatformNodeDelegateBase::GetTable{Row/Col}Count() returns 0 Should it
// return absl::nullopt if the attribute is not set? Like
// GetTableAria{Row/Col}Count()
// EXPECT_EQ(E_UNEXPECTED, grid_provider->get_RowCount(&row_count));
// aria row/column count = 2
// table row/column count = not set
grid->SetAriaTableSize(2, 2);
EXPECT_HRESULT_SUCCEEDED(grid_provider->get_RowCount(&row_count));
EXPECT_HRESULT_SUCCEEDED(grid_provider->get_ColumnCount(&column_count));
EXPECT_EQ(2, row_count);
EXPECT_EQ(2, column_count);
// aria row/column count = kUnknownAriaColumnOrRowCount
// table row/column count = not set
grid->SetAriaTableSize(ax::mojom::kUnknownAriaColumnOrRowCount,
ax::mojom::kUnknownAriaColumnOrRowCount);
EXPECT_EQ(E_UNEXPECTED, grid_provider->get_RowCount(&row_count));
EXPECT_EQ(E_UNEXPECTED, grid_provider->get_ColumnCount(&column_count));
// aria row/column count = 3
// table row/column count = 4
grid->SetAriaTableSize(3, 3);
grid->SetTableSize(4, 4);
EXPECT_HRESULT_SUCCEEDED(grid_provider->get_RowCount(&row_count));
EXPECT_HRESULT_SUCCEEDED(grid_provider->get_ColumnCount(&column_count));
EXPECT_EQ(3, row_count);
EXPECT_EQ(3, column_count);
// aria row/column count = not set
// table row/column count = 4
grid->UnsetAriaTableSize();
grid->SetTableSize(4, 4);
EXPECT_HRESULT_SUCCEEDED(grid_provider->get_RowCount(&row_count));
EXPECT_HRESULT_SUCCEEDED(grid_provider->get_ColumnCount(&column_count));
EXPECT_EQ(4, row_count);
EXPECT_EQ(4, column_count);
// aria row/column count = not set
// table row/column count = kUnknownAriaColumnOrRowCount
grid->SetTableSize(ax::mojom::kUnknownAriaColumnOrRowCount,
ax::mojom::kUnknownAriaColumnOrRowCount);
EXPECT_EQ(E_UNEXPECTED, grid_provider->get_RowCount(&row_count));
EXPECT_EQ(E_UNEXPECTED, grid_provider->get_ColumnCount(&column_count));
}
TEST_F(ViewAXPlatformNodeDelegateWinTest, IsUIAControlIsTrueEvenWhenReadonly) {
// This test ensures that the value returned by
// AXPlatformNodeWin::IsUIAControl returns true even if the element is
// read-only. The previous implementation was incorrect and used to return
// false for read-only views, causing all sorts of issues with ATs.
//
// Since we can't test IsUIAControl directly, we go through the
// UIA_IsControlElementPropertyId, which is computed using IsUIAControl.
Widget widget;
Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP);
init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget.Init(std::move(init_params));
View* content = widget.SetContentsView(std::make_unique<View>());
Textfield* text_field = new Textfield();
text_field->SetReadOnly(true);
content->AddChildView(text_field);
ComPtr<IRawElementProviderSimple> textfield_provider =
GetIRawElementProviderSimple(text_field);
EXPECT_UIA_BOOL_EQ(textfield_provider, UIA_IsControlElementPropertyId, true);
}
//
// TableView tests.
//
namespace {
class TestTableModel : public ui::TableModel {
public:
TestTableModel() = default;
TestTableModel(const TestTableModel&) = delete;
TestTableModel& operator=(const TestTableModel&) = delete;
// ui::TableModel:
int RowCount() override { return 3; }
std::u16string GetText(int row, int column_id) override {
if (row == -1)
return std::u16string();
const char* const cells[5][3] = {
{"Australia", "24,584,620", "1,323,421,072,479"},
{"Spain", "46,647,428", "1,314,314,164,402"},
{"Nigeria", "190.873,244", "375,745,486,521"},
};
return base::ASCIIToUTF16(cells[row % 5][column_id]);
}
void SetObserver(ui::TableModelObserver* observer) override {}
};
} // namespace
class ViewAXPlatformNodeDelegateWinTableTest
: public ViewAXPlatformNodeDelegateWinTest {
void SetUp() override {
ViewAXPlatformNodeDelegateWinTest::SetUp();
std::vector<ui::TableColumn> columns;
columns.push_back(TestTableColumn(0, "Country"));
columns.push_back(TestTableColumn(1, "Population"));
columns.push_back(TestTableColumn(2, "GDP"));
model_ = std::make_unique<TestTableModel>();
auto table =
std::make_unique<TableView>(model_.get(), columns, TEXT_ONLY, true);
table_ = table.get();
widget_ = new Widget;
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_POPUP);
init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
init_params.bounds = gfx::Rect(0, 0, 400, 400);
widget_->Init(std::move(init_params));
View* content = widget_->SetContentsView(std::make_unique<View>());
content->AddChildView(
TableView::CreateScrollViewWithTable(std::move(table)));
widget_->Show();
}
void TearDown() override {
if (!widget_->IsClosed())
widget_->Close();
ViewAXPlatformNodeDelegateWinTest::TearDown();
}
ui::TableColumn TestTableColumn(int id, const std::string& title) {
ui::TableColumn column;
column.id = id;
column.title = base::ASCIIToUTF16(title.c_str());
column.sortable = true;
return column;
}
protected:
std::unique_ptr<TestTableModel> model_;
Widget* widget_ = nullptr;
TableView* table_ = nullptr; // Owned by parent.
};
TEST_F(ViewAXPlatformNodeDelegateWinTableTest, TableCellAttributes) {
ComPtr<IAccessible2_2> table_accessible;
GetIAccessible2InterfaceForView(table_, &table_accessible);
auto get_attributes = [&](int row_child, int cell_child) -> std::wstring {
ComPtr<IDispatch> row_dispatch;
CHECK_EQ(S_OK, table_accessible->get_accChild(ScopedVariant(row_child),
&row_dispatch));
ComPtr<IAccessible> row;
CHECK_EQ(S_OK, row_dispatch.As(&row));
ComPtr<IAccessible2> ia2_row = ToIAccessible2(row);
ComPtr<IDispatch> cell_dispatch;
CHECK_EQ(S_OK,
row->get_accChild(ScopedVariant(cell_child), &cell_dispatch));
ComPtr<IAccessible> cell;
CHECK_EQ(S_OK, cell_dispatch.As(&cell));
ComPtr<IAccessible2> ia2_cell = ToIAccessible2(cell);
ScopedBstr attributes_bstr;
CHECK_EQ(S_OK, ia2_cell->get_attributes(attributes_bstr.Receive()));
std::wstring attributes(attributes_bstr.Get());
return attributes;
};
// These strings should NOT contain rowindex or colindex, since those
// imply an ARIA override.
EXPECT_EQ(get_attributes(1, 1),
L"explicit-name:true;sort:none;class:AXVirtualView;");
EXPECT_EQ(get_attributes(1, 2),
L"explicit-name:true;sort:none;class:AXVirtualView;");
EXPECT_EQ(get_attributes(2, 1),
L"hidden:true;explicit-name:true;class:AXVirtualView;");
EXPECT_EQ(get_attributes(2, 2),
L"hidden:true;explicit-name:true;class:AXVirtualView;");
}
} // namespace test
} // namespace views
|
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/wiki-config.h"
#endif
#include <cstring>
#if HAVE_DECL_STRNLEN == 0
size_t strnlen( const char *start, size_t max_len)
{
const char *end = (const char *)memchr(start, '\0', max_len);
return end ? (size_t)(end - start) : max_len;
}
#endif // HAVE_DECL_STRNLEN
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Enum
#include "System/Enum.hpp"
// Completed includes
// Type namespace: TMPro
namespace TMPro {
// Size: 0x4
#pragma pack(push, 1)
// Autogenerated type: TMPro.UnicodeCharacter
struct UnicodeCharacter/*, public System::Enum*/ {
public:
// public System.UInt32 value__
// Size: 0x4
// Offset: 0x0
uint value;
// Field size check
static_assert(sizeof(uint) == 0x4);
// Creating value type constructor for type: UnicodeCharacter
constexpr UnicodeCharacter(uint value_ = {}) noexcept : value{value_} {}
// Creating interface conversion operator: operator System::Enum
operator System::Enum() noexcept {
return *reinterpret_cast<System::Enum*>(this);
}
// Creating conversion operator: operator uint
constexpr operator uint() const noexcept {
return value;
}
// static field const value: static public TMPro.UnicodeCharacter HYPHEN_MINUS
static constexpr const uint HYPHEN_MINUS = 45u;
// Get static field: static public TMPro.UnicodeCharacter HYPHEN_MINUS
static TMPro::UnicodeCharacter _get_HYPHEN_MINUS();
// Set static field: static public TMPro.UnicodeCharacter HYPHEN_MINUS
static void _set_HYPHEN_MINUS(TMPro::UnicodeCharacter value);
// static field const value: static public TMPro.UnicodeCharacter SOFT_HYPHEN
static constexpr const uint SOFT_HYPHEN = 173u;
// Get static field: static public TMPro.UnicodeCharacter SOFT_HYPHEN
static TMPro::UnicodeCharacter _get_SOFT_HYPHEN();
// Set static field: static public TMPro.UnicodeCharacter SOFT_HYPHEN
static void _set_SOFT_HYPHEN(TMPro::UnicodeCharacter value);
// static field const value: static public TMPro.UnicodeCharacter HYPHEN
static constexpr const uint HYPHEN = 8208u;
// Get static field: static public TMPro.UnicodeCharacter HYPHEN
static TMPro::UnicodeCharacter _get_HYPHEN();
// Set static field: static public TMPro.UnicodeCharacter HYPHEN
static void _set_HYPHEN(TMPro::UnicodeCharacter value);
// static field const value: static public TMPro.UnicodeCharacter NON_BREAKING_HYPHEN
static constexpr const uint NON_BREAKING_HYPHEN = 8209u;
// Get static field: static public TMPro.UnicodeCharacter NON_BREAKING_HYPHEN
static TMPro::UnicodeCharacter _get_NON_BREAKING_HYPHEN();
// Set static field: static public TMPro.UnicodeCharacter NON_BREAKING_HYPHEN
static void _set_NON_BREAKING_HYPHEN(TMPro::UnicodeCharacter value);
// static field const value: static public TMPro.UnicodeCharacter ZERO_WIDTH_SPACE
static constexpr const uint ZERO_WIDTH_SPACE = 8203u;
// Get static field: static public TMPro.UnicodeCharacter ZERO_WIDTH_SPACE
static TMPro::UnicodeCharacter _get_ZERO_WIDTH_SPACE();
// Set static field: static public TMPro.UnicodeCharacter ZERO_WIDTH_SPACE
static void _set_ZERO_WIDTH_SPACE(TMPro::UnicodeCharacter value);
// static field const value: static public TMPro.UnicodeCharacter RIGHT_SINGLE_QUOTATION
static constexpr const uint RIGHT_SINGLE_QUOTATION = 8217u;
// Get static field: static public TMPro.UnicodeCharacter RIGHT_SINGLE_QUOTATION
static TMPro::UnicodeCharacter _get_RIGHT_SINGLE_QUOTATION();
// Set static field: static public TMPro.UnicodeCharacter RIGHT_SINGLE_QUOTATION
static void _set_RIGHT_SINGLE_QUOTATION(TMPro::UnicodeCharacter value);
// static field const value: static public TMPro.UnicodeCharacter APOSTROPHE
static constexpr const uint APOSTROPHE = 39u;
// Get static field: static public TMPro.UnicodeCharacter APOSTROPHE
static TMPro::UnicodeCharacter _get_APOSTROPHE();
// Set static field: static public TMPro.UnicodeCharacter APOSTROPHE
static void _set_APOSTROPHE(TMPro::UnicodeCharacter value);
// static field const value: static public TMPro.UnicodeCharacter WORD_JOINER
static constexpr const uint WORD_JOINER = 8288u;
// Get static field: static public TMPro.UnicodeCharacter WORD_JOINER
static TMPro::UnicodeCharacter _get_WORD_JOINER();
// Set static field: static public TMPro.UnicodeCharacter WORD_JOINER
static void _set_WORD_JOINER(TMPro::UnicodeCharacter value);
}; // TMPro.UnicodeCharacter
#pragma pack(pop)
static check_size<sizeof(UnicodeCharacter), 0 + sizeof(uint)> __TMPro_UnicodeCharacterSizeCheck;
static_assert(sizeof(UnicodeCharacter) == 0x4);
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(TMPro::UnicodeCharacter, "TMPro", "UnicodeCharacter");
|
#define CATCH_CONFIG_RUNNER
#include<bits/stdc++.h>
#include "catch.hpp"
#include "anagram.h"
using namespace std;
CheckValues check;
string tempreature="tempreature",humidity=humidity;
TEST_CASE("raise error and warning when tempreature is greater than alert level")
{
REQUIRE(check.checkforhighvalues(42,tempreature,40,37)==("ALERT!! tempreature is very high"));
REQUIRE(check.checkforhighvalues(42,tempreature,40,37)==("ALERT!! tempreature is high"));
}
TEST_CASE("raise error and warning when tempreature is lower than alert level")
{
REQUIRE(check.checkforlowvalues(-0.92,tempreature,0,4)==("ALERT!! tempreature is very low"));
REQUIRE(check.checkforlowvalues(2,tempreature,0,4)==("WARNING!! tempreature is low"));
}
TEST_CASE("raise error and warning when humidity is greater than alert level")
{
REQUIRE(check.checkforhighvalues(93,humidity,90,70)==("ALERT!! humidity is very high"));
REQUIRE(check.checkforhighvalues(73,humidity,90,70)==("ALERT!! humidity is high"));
}
TEST_CASE("Do nothing when tempreature is in normal conditions")
{
REQUIRE(check.CheckValuesForAlert(5,tempreature,40,37,0,4)=="");
REQUIRE(check.CheckValuesForAlert(34,tempreature,40,37,0,4)=="");
}
TEST_CASE("Do nothing when humidity is in normal conditions")
{
REQUIRE(check.CheckValuesForAlert(7,humidity,90,70,0,0)=="");
REQUIRE(check.CheckValuesForAlert(34,humidity,90,70,0,0)=="");
}
void extractValuesFromStringAndSendValuesForChecking(string line)
{
stringstream ss(line);
while(ss.good())
{
string tempreaturestring,humiditystring;
getline(ss,tempreaturestring,' ');
getline(ss,humiditystring,'\n');
CheckForWarningAndAlert obj(stof(tempreaturestring),stof(humiditystring));
}
}
int main()
{
string line="";
while(getline(cin,line))
{
extractValuesFromStringAndSendValuesForChecking(line);
}
return 0;
}
|
/**
* @copyright
*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright(C) 2018 - 2021 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.
*
* @file test_cryptology.cc
* @brief test cryptology
* @author fancyxu (fancyxu@tencent.com)
* @version 1.0
* @date 2021-07-07
*
* @par Change Log:
* <table>
* <tr><th>Date <th>Version <th>Author <th>Description
* <tr><td>2021-07-07 <td>1.0 <td>fancyxu <td>first commit
* <tr><td>2021-07-08 <td>1.1 <td>fancyxu <td>fix code standard of IotSha1Context
* </table>
*/
#include <iostream>
#include <string>
#include "gtest/gtest.h"
#include "utils_base64.h"
#include "utils_hmac.h"
#include "utils_md5.h"
#include "utils_sha1.h"
namespace cryptology_unittest {
/**
* @brief Test base64.
*
*/
TEST(CryptologyTest, base64) {
const uint8_t base64_test_dec[64] = {0x24, 0x48, 0x6E, 0x56, 0x87, 0x62, 0x5A, 0xBD, 0xBF, 0x17, 0xD9, 0xA2, 0xC4,
0x17, 0x1A, 0x01, 0x94, 0xED, 0x8F, 0x1E, 0x11, 0xB3, 0xD7, 0x09, 0x0C, 0xB6,
0xE9, 0x10, 0x6F, 0x22, 0xEE, 0x13, 0xCA, 0xB3, 0x07, 0x05, 0x76, 0xC9, 0xFA,
0x31, 0x6C, 0x08, 0x34, 0xFF, 0x8D, 0xC2, 0x6C, 0x38, 0x00, 0x43, 0xE9, 0x54,
0x97, 0xAF, 0x50, 0x4B, 0xD1, 0x41, 0xBA, 0x95, 0x31, 0x5A, 0x0B, 0x97};
const uint8_t base64_test_enc[] =
"JEhuVodiWr2/F9mixBcaAZTtjx4Rs9cJDLbpEG8i7hPK"
"swcFdsn6MWwINP+Nwmw4AEPpVJevUEvRQbqVMVoLlw==";
size_t len;
uint8_t buffer[128];
ASSERT_EQ(utils_base64encode(buffer, sizeof(buffer), &len, base64_test_dec, sizeof(base64_test_dec)), 0);
ASSERT_EQ(memcmp(base64_test_enc, buffer, len), 0);
ASSERT_EQ(utils_base64decode(buffer, sizeof(buffer), &len, base64_test_enc, sizeof(base64_test_enc) - 1), 0);
ASSERT_EQ(memcmp(base64_test_dec, buffer, len), 0);
}
/**
* @brief Test hmac.
*
*/
TEST(CryptologyTest, hmac) {
/**
* @brief HMAC-SHA1
*
*/
const char test_buf[] = "Here is a test for hmac-sha1!";
const uint8_t key[] = "0123456789123456";
const char result[] = "614b650ffefff7862c1bc7fdd9de4e472a8184c4";
char buf[128] = {0};
ASSERT_EQ(utils_hmac_sha1(test_buf, strlen(test_buf), key, sizeof(key), buf), 0);
ASSERT_EQ(memcmp(buf, result, sizeof(result)), 0);
}
/**
* @brief Test sha1.
*
*/
TEST(CryptologyTest, sha1) {
/*
* FIPS-180-1 test vectors
*/
const uint8_t sha1_test_buf[3][57] = {{"abc"}, {"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"}, {""}};
const int sha1_test_buflen[3] = {3, 56, 1000};
const uint8_t sha1_test_sum[3][20] = {
{
0xA9, 0x99, 0x3E, 0x36, 0x47, 0x06, 0x81, 0x6A, 0xBA, 0x3E,
0x25, 0x71, 0x78, 0x50, 0xC2, 0x6C, 0x9C, 0xD0, 0xD8, 0x9D,
},
{
0x84, 0x98, 0x3E, 0x44, 0x1C, 0x3B, 0xD2, 0x6E, 0xBA, 0xAE,
0x4A, 0xA1, 0xF9, 0x51, 0x29, 0xE5, 0xE5, 0x46, 0x70, 0xF1,
},
{
0x34, 0xAA, 0x97, 0x3C, 0xD4, 0xC4, 0xDA, 0xA4, 0xF6, 0x1E,
0xEB, 0x2B, 0xDB, 0xAD, 0x27, 0x31, 0x65, 0x34, 0x01, 0x6F,
},
};
int i, j, buflen, rc = 0;
uint8_t buf[1024];
uint8_t sha1sum[20];
IotSha1Context ctx;
utils_sha1_init(&ctx);
for (i = 0; i < 3; i++) {
utils_sha1_starts(&ctx);
if (i == 2) {
memset(buf, 'a', buflen = 1000);
for (j = 0; j < 1000; j++) {
utils_sha1_update(&ctx, buf, buflen);
}
} else {
utils_sha1_update(&ctx, sha1_test_buf[i], sha1_test_buflen[i]);
}
utils_sha1_finish(&ctx, sha1sum);
ASSERT_EQ(memcmp(sha1sum, sha1_test_sum[i], 20), 0);
}
utils_sha1_free(&ctx);
utils_sha1(sha1_test_buf[0], 3, sha1sum);
ASSERT_EQ(memcmp(sha1sum, sha1_test_sum[0], 20), 0);
}
/**
* @brief Test md5.
*
*/
TEST(CryptologyTest, md5) {
/*
* RFC 1321 test vectors
*/
const uint8_t md5_test_buf[7][81] = {
{""},
{"a"},
{"abc"},
{"message digest"},
{"abcdefghijklmnopqrstuvwxyz"},
{"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"},
{"12345678901234567890123456789012345678901234567890123456789012345678901234567890"},
};
const size_t md5_test_buflen[7] = {0, 1, 3, 14, 26, 62, 80};
const char md5_test_sum[7][33] = {
{"D41D8CD98F00B204E9800998ECF8427E"}, {"0CC175B9C0F1B6A831C399E269772661"}, {"900150983CD24FB0D6963F7D28E17F72"},
{"F96B697D7CB7938D525A2F31AAF161D0"}, {"C3FCD3D76192E4007DFB496CCA67E13B"}, {"D174AB98D277D9F5A5611C2C9F419D9F"},
{"57EDF4A22BE3C955AC49DA2E2107B67A"},
};
/*
* Checkup routine
*/
IotMd5Context md5_ctx;
for (int i = 0; i < 7; i++) {
utils_md5_reset(&md5_ctx);
utils_md5_update(&md5_ctx, md5_test_buf[i], md5_test_buflen[i]);
utils_md5_finish(&md5_ctx);
ASSERT_EQ(utils_md5_compare(&md5_ctx, md5_test_sum[i]), 0);
}
}
} // namespace cryptology_unittest
|
// classical dp
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int height = triangle.size();
for (int i = 1; i < height; i++){
triangle[i][0] += triangle[i-1][0];
for (int j = 1; j < triangle[i].size()-1; j++)
triangle[i][j] += min(triangle[i-1][j-1], triangle[i-1][j]);
triangle[i].back() += triangle[i-1].back();
}
return *min_element(triangle[height-1].begin(), triangle[height-1].end());
}
};
|
/*
* libjingle
* Copyright 2004--2011, Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "talk/base/common.h"
#include "talk/base/gunit.h"
#include "talk/base/thread.h"
#include "talk/base/urlencode.h"
TEST(Urlencode, SourceTooLong) {
char source[] = "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"
"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^";
char dest[1];
ASSERT_EQ(0, UrlEncode(source, dest, ARRAY_SIZE(dest)));
ASSERT_EQ('\0', dest[0]);
dest[0] = 'a';
ASSERT_EQ(0, UrlEncode(source, dest, 0));
ASSERT_EQ('a', dest[0]);
}
TEST(Urlencode, OneCharacterConversion) {
char source[] = "^";
char dest[4];
ASSERT_EQ(3, UrlEncode(source, dest, ARRAY_SIZE(dest)));
ASSERT_STREQ("%5E", dest);
}
TEST(Urlencode, ShortDestinationNoEncoding) {
// In this case we have a destination that would not be
// big enough to hold an encoding but is big enough to
// hold the text given.
char source[] = "aa";
char dest[3];
ASSERT_EQ(2, UrlEncode(source, dest, ARRAY_SIZE(dest)));
ASSERT_STREQ("aa", dest);
}
TEST(Urlencode, ShortDestinationEncoding) {
// In this case we have a destination that is not
// big enough to hold the encoding.
char source[] = "&";
char dest[3];
ASSERT_EQ(0, UrlEncode(source, dest, ARRAY_SIZE(dest)));
ASSERT_EQ('\0', dest[0]);
}
TEST(Urlencode, Encoding1) {
char source[] = "A^ ";
char dest[8];
ASSERT_EQ(5, UrlEncode(source, dest, ARRAY_SIZE(dest)));
ASSERT_STREQ("A%5E+", dest);
}
TEST(Urlencode, Encoding2) {
char source[] = "A^ ";
char dest[8];
ASSERT_EQ(7, UrlEncodeWithoutEncodingSpaceAsPlus(source, dest,
ARRAY_SIZE(dest)));
ASSERT_STREQ("A%5E%20", dest);
}
TEST(Urldecode, Decoding1) {
char source[] = "A%5E+";
char dest[8];
ASSERT_EQ(3, UrlDecode(source, dest));
ASSERT_STREQ("A^ ", dest);
}
TEST(Urldecode, Decoding2) {
char source[] = "A%5E+";
char dest[8];
ASSERT_EQ(3, UrlDecodeWithoutEncodingSpaceAsPlus(source, dest));
ASSERT_STREQ("A^+", dest);
}
|
/** @file
traffic_ctl
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "traffic_ctl.h"
#include "records/I_RecProcess.h"
#include "RecordsConfig.h"
#include "tscore/I_Layout.h"
#include "tscore/runroot.h"
const char *
CtrlMgmtRecord::name() const
{
return this->ele->rec_name;
}
TSRecordT
CtrlMgmtRecord::type() const
{
return this->ele->rec_type;
}
int
CtrlMgmtRecord::rclass() const
{
return this->ele->rec_class;
}
int64_t
CtrlMgmtRecord::as_int() const
{
switch (this->ele->rec_type) {
case TS_REC_INT:
return this->ele->valueT.int_val;
case TS_REC_COUNTER:
return this->ele->valueT.counter_val;
default:
return 0;
}
}
TSMgmtError
CtrlMgmtRecord::fetch(const char *name)
{
return TSRecordGet(name, this->ele);
}
TSMgmtError
CtrlMgmtRecordList::match(const char *name)
{
return TSRecordGetMatchMlt(name, this->list);
}
CtrlMgmtRecordValue::CtrlMgmtRecordValue(const CtrlMgmtRecord &rec)
{
this->init(rec.ele->rec_type, rec.ele->valueT);
}
CtrlMgmtRecordValue::CtrlMgmtRecordValue(const TSRecordEle *ele)
{
this->init(ele->rec_type, ele->valueT);
}
CtrlMgmtRecordValue::CtrlMgmtRecordValue(TSRecordT _t, TSRecordValueT _v)
{
this->init(_t, _v);
}
void
CtrlMgmtRecordValue::init(TSRecordT _t, TSRecordValueT _v)
{
this->rec_type = _t;
switch (this->rec_type) {
case TS_REC_INT:
snprintf(this->fmt.nbuf, sizeof(this->fmt.nbuf), "%" PRId64, _v.int_val);
break;
case TS_REC_COUNTER:
snprintf(this->fmt.nbuf, sizeof(this->fmt.nbuf), "%" PRId64, _v.counter_val);
break;
case TS_REC_FLOAT:
snprintf(this->fmt.nbuf, sizeof(this->fmt.nbuf), "%f", _v.float_val);
break;
case TS_REC_STRING:
if (strcmp(_v.string_val, "") == 0) {
this->fmt.str = "\"\"";
} else {
this->fmt.str = _v.string_val;
}
break;
default:
rec_type = TS_REC_STRING;
this->fmt.str = "(invalid)";
}
}
const char *
CtrlMgmtRecordValue::c_str() const
{
switch (this->rec_type) {
case TS_REC_STRING:
return this->fmt.str;
default:
return this->fmt.nbuf;
}
}
void
CtrlMgmtError(TSMgmtError err, const char *fmt, ...)
{
ats_scoped_str msg(TSGetErrorMessage(err));
if (fmt) {
va_list ap;
fprintf(stderr, "%s: ", program_name);
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
fprintf(stderr, ": %s\n", (const char *)msg);
} else {
fprintf(stderr, "%s: %s\n", program_name, (const char *)msg);
}
}
void
CtrlEngine::CtrlUnimplementedCommand(std::string_view command)
{
fprintf(stderr, "'%s' command is not implemented\n", command.data());
status_code = CTRL_EX_UNIMPLEMENTED;
}
int
main(int argc, const char **argv)
{
CtrlEngine engine;
engine.parser.add_global_usage("traffic_ctl [OPTIONS] CMD [ARGS ...]");
engine.parser.require_commands();
engine.parser.add_option("--debug", "", "Enable debugging output")
.add_option("--version", "-V", "Print version string")
.add_option("--help", "-h", "Print usage information")
.add_option("--run-root", "", "using TS_RUNROOT as sandbox", "TS_RUNROOT", 1);
auto &alarm_command = engine.parser.add_command("alarm", "Manipulate alarms").require_commands();
auto &config_command = engine.parser.add_command("config", "Manipulate configuration records").require_commands();
auto &metric_command = engine.parser.add_command("metric", "Manipulate performance metrics").require_commands();
auto &server_command = engine.parser.add_command("server", "Stop, restart and examine the server").require_commands();
auto &storage_command = engine.parser.add_command("storage", "Manipulate cache storage").require_commands();
auto &plugin_command = engine.parser.add_command("plugin", "Interact with plugins").require_commands();
auto &host_command = engine.parser.add_command("host", "Interact with host status").require_commands();
// alarm commands
alarm_command.add_command("clear", "Clear all current alarms", [&]() { engine.alarm_clear(); })
.add_example_usage("traffic_ctl alarm clear");
alarm_command.add_command("list", "List all current alarms", [&]() { engine.alarm_list(); })
.add_example_usage("traffic_ctl alarm list");
alarm_command.add_command("resolve", "Resolve the listed alarms", "", MORE_THAN_ONE_ARG_N, [&]() { engine.alarm_resolve(); })
.add_example_usage("traffic_ctl alarm resolve ALARM [ALARM ...]");
// config commands
config_command.add_command("defaults", "Show default information configuration values", [&]() { engine.config_defaults(); })
.add_example_usage("traffic_ctl config defaults [OPTIONS]")
.add_option("--records", "", "Emit output in records.config format");
config_command
.add_command("describe", "Show detailed information about configuration values", "", MORE_THAN_ONE_ARG_N,
[&]() { engine.config_describe(); })
.add_example_usage("traffic_ctl config describe RECORD [RECORD ...]");
config_command.add_command("diff", "Show non-default configuration values", [&]() { engine.config_diff(); })
.add_example_usage("traffic_ctl config diff [OPTIONS]")
.add_option("--records", "", "Emit output in records.config format");
config_command.add_command("get", "Get one or more configuration values", "", MORE_THAN_ONE_ARG_N, [&]() { engine.config_get(); })
.add_example_usage("traffic_ctl config get [OPTIONS] RECORD [RECORD ...]")
.add_option("--records", "", "Emit output in records.config format");
config_command
.add_command("match", "Get configuration matching a regular expression", "", MORE_THAN_ONE_ARG_N,
[&]() { engine.config_match(); })
.add_example_usage("traffic_ctl config match [OPTIONS] REGEX [REGEX ...]")
.add_option("--records", "", "Emit output in records.config format");
config_command.add_command("reload", "Request a configuration reload", [&]() { engine.config_reload(); })
.add_example_usage("traffic_ctl config reload");
config_command.add_command("status", "Check the configuration status", [&]() { engine.config_status(); })
.add_example_usage("traffic_ctl config status");
config_command.add_command("set", "Set a configuration value", "", 2, [&]() { engine.config_set(); })
.add_example_usage("traffic_ctl config set RECORD VALUE");
// host commands
host_command.add_command("status", "Get one or more host statuses", "", MORE_THAN_ONE_ARG_N, [&]() { engine.status_get(); })
.add_example_usage("traffic_ctl host status HOST [HOST ...]");
host_command.add_command("down", "Set down one or more host(s)", "", MORE_THAN_ONE_ARG_N, [&]() { engine.status_down(); })
.add_example_usage("traffic_ctl host down HOST [OPTIONS]")
.add_option("--time", "-I", "number of seconds that a host is marked down", "", 1)
.add_option("--reason", "", "reason for marking the host down, one of 'manual|active|local", "", 1);
host_command.add_command("up", "Set up one or more host(s)", "", MORE_THAN_ONE_ARG_N, [&]() { engine.status_up(); })
.add_example_usage("traffic_ctl host up METRIC value")
.add_option("--reason", "", "reason for marking the host up, one of 'manual|active|local", "", 1);
// metric commands
metric_command.add_command("get", "Get one or more metric values", "", MORE_THAN_ONE_ARG_N, [&]() { engine.metric_get(); })
.add_example_usage("traffic_ctl metric get METRIC [METRIC ...]");
metric_command.add_command("clear", "Clear all metric values", [&]() { engine.metric_clear(); });
metric_command.add_command("describe", "Show detailed information about one or more metric values", "", MORE_THAN_ONE_ARG_N,
[&]() { engine.CtrlUnimplementedCommand("describe"); }); // not implemented
metric_command.add_command("match", "Get metrics matching a regular expression", "", MORE_THAN_ZERO_ARG_N,
[&]() { engine.metric_match(); });
metric_command.add_command("monitor", "Display the value of a metric over time", "", MORE_THAN_ZERO_ARG_N,
[&]() { engine.CtrlUnimplementedCommand("monitor"); }); // not implemented
metric_command.add_command("zero", "Clear one or more metric values", "", MORE_THAN_ONE_ARG_N, [&]() { engine.metric_zero(); });
// plugin command
plugin_command
.add_command("msg", "Send message to plugins - a TAG and the message DATA(optional)", "", MORE_THAN_ONE_ARG_N,
[&]() { engine.plugin_msg(); })
.add_example_usage("traffic_ctl plugin msg TAG DATA");
// server commands
server_command.add_command("backtrace", "Show a full stack trace of the traffic_server process",
[&]() { engine.server_backtrace(); });
server_command.add_command("restart", "Restart Traffic Server", [&]() { engine.server_restart(); })
.add_example_usage("traffic_ctl server restart [OPTIONS]")
.add_option("--drain", "", "Wait for client connections to drain before restarting")
.add_option("--manager", "", "Restart traffic_manager as well as traffic_server");
server_command.add_command("start", "Start the proxy", [&]() { engine.server_start(); })
.add_example_usage("traffic_ctl server start [OPTIONS]")
.add_option("--clear-cache", "", "Clear the disk cache on startup")
.add_option("--clear-hostdb", "", "Clear the DNS cache on startup");
server_command.add_command("status", "Show the proxy status", [&]() { engine.server_status(); })
.add_example_usage("traffic_ctl server status");
server_command.add_command("stop", "Stop the proxy", [&]() { engine.server_stop(); })
.add_example_usage("traffic_ctl server stop [OPTIONS]")
.add_option("--drain", "", "Wait for client connections to drain before stopping");
server_command.add_command("drain", "Drain the requests", [&]() { engine.server_drain(); })
.add_example_usage("traffic_ctl server drain [OPTIONS]")
.add_option("--no-new-connection", "-N", "Wait for new connections down to threshold before starting draining")
.add_option("--undo", "-U", "Recover server from the drain mode");
// storage commands
storage_command
.add_command("offline", "Take one or more storage volumes offline", "", MORE_THAN_ONE_ARG_N,
[&]() { engine.storage_offline(); })
.add_example_usage("storage offline DEVICE [DEVICE ...]");
storage_command.add_command("status", "Show the storage configuration", "", MORE_THAN_ZERO_ARG_N,
[&]() { engine.CtrlUnimplementedCommand("status"); }); // not implemented
// parse the arguments
engine.arguments = engine.parser.parse(argv);
BaseLogFile *base_log_file = new BaseLogFile("stderr");
diags = new Diags("traffic_ctl", "" /* tags */, "" /* actions */, base_log_file);
if (engine.arguments.get("debug")) {
diags->activate_taglist("traffic_ctl", DiagsTagType_Debug);
diags->config.enabled[DiagsTagType_Debug] = true;
diags->show_location = SHOW_LOCATION_DEBUG;
}
argparser_runroot_handler(engine.arguments.get("--run-root").value(), argv[0]);
Layout::create();
// This is a little bit of a hack, for now it'll suffice.
max_records_entries = 262144;
RecProcessInit(RECM_STAND_ALONE, diags);
LibRecordsConfigInit();
ats_scoped_str rundir(RecConfigReadRuntimeDir());
// Make a best effort to connect the control socket. If it turns out we are
// just displaying help or something then it
// doesn't matter that we failed. If we end up performing some operation then
// that operation will fail and display the
// error.
TSInit(rundir, static_cast<TSInitOptionT>(TS_MGMT_OPT_NO_EVENTS | TS_MGMT_OPT_NO_SOCK_TESTS));
engine.arguments.invoke();
// Done with the mgmt API.
TSTerminate();
return engine.status_code;
}
|
/* Copyright © 2020 Apple Inc. All rights reserved.
*
* Use of this source code is governed by a BSD-3-clause license that can
* be found in the LICENSE.txt file or at
* https://opensource.org/licenses/BSD-3-Clause
*/
#include <ml/neural_net/PosixTaskQueue.hpp>
#include <core/parallel/lambda_omp.hpp>
namespace turi {
namespace neural_net {
// static
std::shared_ptr<PosixTaskQueue> PosixTaskQueue::GetGlobalConcurrentQueue() {
// We use a pointer to a shared_ptr to guarantee that the singleton is never
// deconstructed, even when main() ends, in case background threads are still
// trying to call this function.
static const auto* const singleton = new std::shared_ptr<PosixTaskQueue>(
std::make_shared<GlobalPosixTaskQueue>());
return *singleton;
}
// static
std::unique_ptr<PosixTaskQueue> PosixTaskQueue::CreateSerialQueue(const char* label)
{
return std::unique_ptr<SerialPosixTaskQueue>(new SerialPosixTaskQueue(/* num_threads */ 1));
}
void PosixTaskQueue::DispatchAsync(std::function<void()> task) {
GetThreadPool().launch(task);
}
void PosixTaskQueue::DispatchSync(std::function<void()> task) {
parallel_task_queue queue(GetThreadPool());
queue.launch(task);
queue.join();
}
SerialPosixTaskQueue::SerialPosixTaskQueue(size_t num_threads)
: threads_(num_threads) {}
SerialPosixTaskQueue::~SerialPosixTaskQueue() = default;
thread_pool& SerialPosixTaskQueue::GetThreadPool() { return threads_; }
void SerialPosixTaskQueue::DispatchApply(size_t n,
std::function<void(size_t i)> task) {
DispatchSync([n, task] {
for (size_t i = 0; i < n; ++i) {
task(i);
}
});
}
GlobalPosixTaskQueue::GlobalPosixTaskQueue() = default;
GlobalPosixTaskQueue::~GlobalPosixTaskQueue() = default;
GlobalPosixTaskQueue::GlobalPosixTaskQueue(const GlobalPosixTaskQueue&) =
default;
GlobalPosixTaskQueue::GlobalPosixTaskQueue(GlobalPosixTaskQueue&&) = default;
GlobalPosixTaskQueue& GlobalPosixTaskQueue::operator=(
const GlobalPosixTaskQueue&) = default;
GlobalPosixTaskQueue& GlobalPosixTaskQueue::operator=(GlobalPosixTaskQueue&&) =
default;
thread_pool& GlobalPosixTaskQueue::GetThreadPool() {
return thread_pool::get_instance();
}
void GlobalPosixTaskQueue::DispatchApply(size_t n,
std::function<void(size_t i)> task) {
// Just use turi::parallel_for, which always uses thread_pool::get_instance().
// This implementation slices the n logical iterations into k slices and
// dispatches to k threads, where k is the number of CPU cores.
parallel_for(0, n, task);
}
} // namespace neural_net
} // namespace turi
|
#ifndef CUAUV_SIM_FMTS_H
#define CUAUV_SIM_FMTS_H
#include <memory>
#include <iostream>
#include <string>
#include <stdio.h>
// Originally from http://stackoverflow.com/a/26221725 .
namespace cuauv {
namespace fishbowl {
template<typename... Args>
std::string fmts(const std::string& format, Args... args)
{
size_t size = 1 + snprintf(nullptr, 0, format.data(), args...);
std::unique_ptr<char[]> buf(new char[size]);
snprintf(buf.get(), size, format.data(), args...);
return std::string(buf.get(), buf.get() + size);
}
} // namespace fishbowl
} // namespace cuauv
#endif // CUAUV_SIM_FMTS_H
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 vmolsa <ville.molsa@gmail.com> (http://github.com/vmolsa)
*
* 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 "Core.h"
#include "GetSources.h"
using namespace v8;
using namespace WebRTC;
void GetSources::Init(Handle<Object> exports) {
LOG(LS_INFO) << __PRETTY_FUNCTION__;
exports->Set(Nan::New("getSources").ToLocalChecked(), Nan::New<FunctionTemplate>(GetSources::GetDevices)->GetFunction());
}
rtc::scoped_refptr<webrtc::AudioTrackInterface> GetSources::GetAudioSource(const rtc::scoped_refptr<MediaConstraints> &constraints) {
LOG(LS_INFO) << __PRETTY_FUNCTION__;
//webrtc::PeerConnectionFactoryInterface *factory = Core::GetFactory();
rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> factory = Core::CreateFactory();
rtc::scoped_refptr<webrtc::AudioTrackInterface> track;
if (factory.get()) {
rtc::scoped_refptr<webrtc::AudioSourceInterface> src = factory->CreateAudioSource(constraints->ToConstraints());
track = factory->CreateAudioTrack("audio", src);
}
return track;
}
rtc::scoped_refptr<webrtc::AudioTrackInterface> GetSources::GetAudioSource(const std::string id, const rtc::scoped_refptr<MediaConstraints> &constraints) {
LOG(LS_INFO) << __PRETTY_FUNCTION__;
// TODO(): CreateAudioSource(cricket::AudioCapturer*, MediaConstraintsInterface) Missing?
return GetSources::GetAudioSource(constraints);
}
rtc::scoped_refptr<webrtc::VideoTrackInterface> GetSources::GetVideoSource(const rtc::scoped_refptr<MediaConstraints> &constraints) {
LOG(LS_INFO) << __PRETTY_FUNCTION__;
cricket::DeviceManagerInterface *manager = Core::GetManager();
rtc::scoped_refptr<webrtc::VideoTrackInterface> track;
cricket::VideoCapturer *cap = 0;
#ifndef USE_SERCOMM
if (manager) {
std::vector<cricket::Device> video_devs;
if (manager->GetVideoCaptureDevices(&video_devs)) {
std::vector<cricket::Device>::iterator video_it = video_devs.begin();
for (video_it = video_devs.begin(); !cap && video_it != video_devs.end(); video_it++) {
cap = manager->CreateVideoCapturer(*video_it);
}
}
}
#else
const cricket::Device device_temp("YuvFramesGenerator", "YuvFramesGenerator_id");
cap = manager->CreateVideoCapturer(device_temp);
#endif
if (cap) {
//webrtc::PeerConnectionFactoryInterface *factory = Core::GetFactory();
rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> factory = Core::CreateFactory();
if (factory.get()) {
rtc::scoped_refptr<webrtc::VideoSourceInterface> src = factory->CreateVideoSource(cap, constraints->ToConstraints());
track = factory->CreateVideoTrack("video", src);
}
}
return track;
}
rtc::scoped_refptr<webrtc::VideoTrackInterface> GetSources::GetVideoSource(const std::string id, const rtc::scoped_refptr<MediaConstraints> &constraints) {
LOG(LS_INFO) << __PRETTY_FUNCTION__;
cricket::DeviceManagerInterface *manager = Core::GetManager();
rtc::scoped_refptr<webrtc::VideoTrackInterface> track;
cricket::VideoCapturer *cap = 0;
#ifndef USE_SERCOMM
if (manager) {
cricket::Device video_dev;
if (!manager->GetVideoCaptureDevice(id, &video_dev)) {
cap = manager->CreateVideoCapturer(video_dev);
}
}
#else
const cricket::Device device_temp("YuvFramesGenerator", "YuvFramesGenerator_id");
cap = manager->CreateVideoCapturer(device_temp);
#endif
if (cap) {
//webrtc::PeerConnectionFactoryInterface *factory = Core::GetFactory();
rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> factory = Core::CreateFactory();
if (factory.get()) {
rtc::scoped_refptr<webrtc::VideoSourceInterface> src = factory->CreateVideoSource(cap, constraints->ToConstraints());
track = factory->CreateVideoTrack("video", src);
}
}
return track;
}
Local<Value> GetSources::GetDevices() {
LOG(LS_INFO) << __PRETTY_FUNCTION__;
Nan::EscapableHandleScope scope;
Local<Array> list = Nan::New<Array>();
uint32_t index = 0;
cricket::DeviceManagerInterface *manager = Core::GetManager();
if (manager) {
std::vector<cricket::Device> audio_devs;
std::vector<cricket::Device> video_devs;
if (manager->GetAudioInputDevices(&audio_devs)) {
std::vector<cricket::Device>::iterator audio_it;
for (audio_it = audio_devs.begin(); audio_it != audio_devs.end(); audio_it++) {
const cricket::Device &dev = *audio_it;
Local<Object> dev_obj = Nan::New<Object>();
dev_obj->Set(Nan::New("kind").ToLocalChecked(), Nan::New("audio").ToLocalChecked());
dev_obj->Set(Nan::New("label").ToLocalChecked(), Nan::New(dev.name.c_str()).ToLocalChecked());
dev_obj->Set(Nan::New("id").ToLocalChecked(), Nan::New(dev.id.c_str()).ToLocalChecked());
list->Set(index, dev_obj);
index++;
}
}
if (manager->GetVideoCaptureDevices(&video_devs)) {
std::vector<cricket::Device>::iterator video_it = video_devs.begin();
for (video_it = video_devs.begin(); video_it != video_devs.end(); video_it++) {
const cricket::Device &dev = *video_it;
Local<Object> dev_obj = Nan::New<Object>();
dev_obj->Set(Nan::New("kind").ToLocalChecked(), Nan::New("video").ToLocalChecked());
dev_obj->Set(Nan::New("label").ToLocalChecked(), Nan::New(dev.name.c_str()).ToLocalChecked());
dev_obj->Set(Nan::New("id").ToLocalChecked(), Nan::New(dev.id.c_str()).ToLocalChecked());
list->Set(index, dev_obj);
index++;
}
}
}
return scope.Escape(list);
}
void GetSources::GetDevices(const Nan::FunctionCallbackInfo<Value> &info) {
LOG(LS_INFO) << __PRETTY_FUNCTION__;
if (info.Length() == 1 && info[0]->IsFunction()) {
Local<Function> callback = Local<Function>::Cast(info[0]);
Local<Value> argv[1] = {
GetSources::GetDevices()
};
if (!callback.IsEmpty()) {
callback->Call(info.This(), 1, argv);
}
}
info.GetReturnValue().SetUndefined();
}
|
// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2018 The SYNERGYWORK developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "overviewpage.h"
#include "ui_overviewpage.h"
#include "bitcoinunits.h"
#include "clientmodel.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "init.h"
#include "obfuscation.h"
#include "obfuscationconfig.h"
#include "optionsmodel.h"
#include "transactionfilterproxy.h"
#include "transactionrecord.h"
#include "transactiontablemodel.h"
#include "walletmodel.h"
#include <QAbstractItemDelegate>
#include <QPainter>
#include <QSettings>
#include <QTimer>
#define DECORATION_SIZE 48
#define ICON_OFFSET 16
#define NUM_ITEMS 9
extern CWallet* pwalletMain;
class TxViewDelegate : public QAbstractItemDelegate
{
Q_OBJECT
public:
TxViewDelegate() : QAbstractItemDelegate(), unit(BitcoinUnits::SWK)
{
}
inline void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
painter->save();
QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole));
QRect mainRect = option.rect;
mainRect.moveLeft(ICON_OFFSET);
QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));
int xspace = DECORATION_SIZE + 8;
int ypad = 6;
int halfheight = (mainRect.height() - 2 * ypad) / 2;
QRect amountRect(mainRect.left() + xspace, mainRect.top() + ypad, mainRect.width() - xspace - ICON_OFFSET, halfheight);
QRect addressRect(mainRect.left() + xspace, mainRect.top() + ypad + halfheight, mainRect.width() - xspace, halfheight);
icon.paint(painter, decorationRect);
QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime();
QString address = index.data(Qt::DisplayRole).toString();
qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong();
bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool();
QVariant value = index.data(Qt::ForegroundRole);
QColor foreground = COLOR_BLACK;
if (value.canConvert<QBrush>()) {
QBrush brush = qvariant_cast<QBrush>(value);
foreground = brush.color();
}
painter->setPen(foreground);
QRect boundingRect;
painter->drawText(addressRect, Qt::AlignLeft | Qt::AlignVCenter, address, &boundingRect);
if (index.data(TransactionTableModel::WatchonlyRole).toBool()) {
QIcon iconWatchonly = qvariant_cast<QIcon>(index.data(TransactionTableModel::WatchonlyDecorationRole));
QRect watchonlyRect(boundingRect.right() + 5, mainRect.top() + ypad + halfheight, 16, halfheight);
iconWatchonly.paint(painter, watchonlyRect);
}
if (amount < 0)
foreground = COLOR_NEGATIVE;
painter->setPen(foreground);
QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true, BitcoinUnits::separatorAlways);
if (!confirmed) {
amountText = QString("[") + amountText + QString("]");
}
painter->drawText(amountRect, Qt::AlignRight | Qt::AlignVCenter, amountText);
painter->setPen(COLOR_BLACK);
painter->drawText(amountRect, Qt::AlignLeft | Qt::AlignVCenter, GUIUtil::dateTimeStr(date));
painter->restore();
}
inline QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
{
return QSize(DECORATION_SIZE, DECORATION_SIZE);
}
int unit;
};
#include "overviewpage.moc"
OverviewPage::OverviewPage(QWidget* parent) : QWidget(parent),
ui(new Ui::OverviewPage),
clientModel(0),
walletModel(0),
currentBalance(-1),
currentUnconfirmedBalance(-1),
currentImmatureBalance(-1),
currentZerocoinBalance(-1),
currentUnconfirmedZerocoinBalance(-1),
currentimmatureZerocoinBalance(-1),
currentWatchOnlyBalance(-1),
currentWatchUnconfBalance(-1),
currentWatchImmatureBalance(-1),
txdelegate(new TxViewDelegate()),
filter(0)
{
nDisplayUnit = 0; // just make sure it's not unitialized
ui->setupUi(this);
// Recent transactions
ui->listTransactions->setItemDelegate(txdelegate);
ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));
ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2));
ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false);
connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex)));
// init "out of sync" warning labels
ui->labelWalletStatus->setText("(" + tr("out of sync") + ")");
ui->labelTransactionsStatus->setText("(" + tr("out of sync") + ")");
// start with displaying the "out of sync" warnings
showOutOfSyncWarning(true);
}
void OverviewPage::handleTransactionClicked(const QModelIndex& index)
{
if (filter)
emit transactionClicked(filter->mapToSource(index));
}
OverviewPage::~OverviewPage()
{
delete ui;
}
void OverviewPage::getPercentage(CAmount nUnlockedBalance, CAmount nZerocoinBalance, QString& sSWKPercentage, QString& szSWKPercentage)
{
int nPrecision = 2;
double dzPercentage = 0.0;
if (nZerocoinBalance <= 0){
dzPercentage = 0.0;
}
else{
if (nUnlockedBalance <= 0){
dzPercentage = 100.0;
}
else{
dzPercentage = 100.0 * (double)(nZerocoinBalance / (double)(nZerocoinBalance + nUnlockedBalance));
}
}
double dPercentage = 100.0 - dzPercentage;
szSWKPercentage = "(" + QLocale(QLocale::system()).toString(dzPercentage, 'f', nPrecision) + " %)";
sSWKPercentage = "(" + QLocale(QLocale::system()).toString(dPercentage, 'f', nPrecision) + " %)";
}
void OverviewPage::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance,
const CAmount& zerocoinBalance, const CAmount& unconfirmedZerocoinBalance, const CAmount& immatureZerocoinBalance,
const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance)
{
currentBalance = balance;
currentUnconfirmedBalance = unconfirmedBalance;
currentImmatureBalance = immatureBalance;
currentZerocoinBalance = zerocoinBalance;
currentUnconfirmedZerocoinBalance = unconfirmedZerocoinBalance;
currentimmatureZerocoinBalance = immatureZerocoinBalance;
currentWatchOnlyBalance = watchOnlyBalance;
currentWatchUnconfBalance = watchUnconfBalance;
currentWatchImmatureBalance = watchImmatureBalance;
CAmount nLockedBalance = 0;
CAmount nWatchOnlyLockedBalance = 0;
if (pwalletMain) {
nLockedBalance = pwalletMain->GetLockedCoins();
nWatchOnlyLockedBalance = pwalletMain->GetLockedWatchOnlyBalance();
}
// SWK Balance
CAmount nTotalBalance = balance + unconfirmedBalance;
CAmount swkAvailableBalance = balance - immatureBalance - nLockedBalance;
CAmount nUnlockedBalance = nTotalBalance - nLockedBalance;
// SWK Watch-Only Balance
CAmount nTotalWatchBalance = watchOnlyBalance + watchUnconfBalance;
CAmount nAvailableWatchBalance = watchOnlyBalance - watchImmatureBalance - nWatchOnlyLockedBalance;
// zSWK Balance
CAmount matureZerocoinBalance = zerocoinBalance - unconfirmedZerocoinBalance - immatureZerocoinBalance;
// Percentages
QString szPercentage = "";
QString sPercentage = "";
getPercentage(nUnlockedBalance, zerocoinBalance, sPercentage, szPercentage);
// Combined balances
CAmount availableTotalBalance = swkAvailableBalance + matureZerocoinBalance;
CAmount sumTotalBalance = nTotalBalance + zerocoinBalance;
// SWK labels
ui->labelBalance->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, swkAvailableBalance, false, BitcoinUnits::separatorAlways));
ui->labelUnconfirmed->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, unconfirmedBalance, false, BitcoinUnits::separatorAlways));
ui->labelImmature->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, immatureBalance, false, BitcoinUnits::separatorAlways));
ui->labelLockedBalance->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, nLockedBalance, false, BitcoinUnits::separatorAlways));
ui->labelTotal->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, nTotalBalance, false, BitcoinUnits::separatorAlways));
// Watchonly labels
ui->labelWatchAvailable->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, nAvailableWatchBalance, false, BitcoinUnits::separatorAlways));
ui->labelWatchPending->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, watchUnconfBalance, false, BitcoinUnits::separatorAlways));
ui->labelWatchImmature->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, watchImmatureBalance, false, BitcoinUnits::separatorAlways));
ui->labelWatchLocked->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, nWatchOnlyLockedBalance, false, BitcoinUnits::separatorAlways));
ui->labelWatchTotal->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, nTotalWatchBalance, false, BitcoinUnits::separatorAlways));
// zSWK labels
ui->labelzBalance->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, zerocoinBalance, false, BitcoinUnits::separatorAlways));
ui->labelzBalanceUnconfirmed->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, unconfirmedZerocoinBalance, false, BitcoinUnits::separatorAlways));
ui->labelzBalanceMature->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, matureZerocoinBalance, false, BitcoinUnits::separatorAlways));
ui->labelzBalanceImmature->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, immatureZerocoinBalance, false, BitcoinUnits::separatorAlways));
// Combined labels
ui->labelBalancez->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, availableTotalBalance, false, BitcoinUnits::separatorAlways));
ui->labelTotalz->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, sumTotalBalance, false, BitcoinUnits::separatorAlways));
// Percentage labels
ui->labelSWKPercent->setText(sPercentage);
ui->labelzSWKPercent->setText(szPercentage);
// Adjust bubble-help according to AutoMint settings
QString automintHelp = tr("Current percentage of zSWK.\nIf AutoMint is enabled this percentage will settle around the configured AutoMint percentage (default = 10%).\n");
bool fEnableZeromint = GetBoolArg("-enablezeromint", true);
int nZeromintPercentage = GetArg("-zeromintpercentage", 10);
if (fEnableZeromint) {
automintHelp += tr("AutoMint is currently enabled and set to ") + QString::number(nZeromintPercentage) + "%.\n";
automintHelp += tr("To disable AutoMint add 'enablezeromint=0' in synergywork.conf.");
}
else {
automintHelp += tr("AutoMint is currently disabled.\nTo enable AutoMint change 'enablezeromint=0' to 'enablezeromint=1' in synergywork.conf");
}
// Only show most balances if they are non-zero for the sake of simplicity
QSettings settings;
bool settingShowAllBalances = !settings.value("fHideZeroBalances").toBool();
bool showSumAvailable = settingShowAllBalances || sumTotalBalance != availableTotalBalance;
ui->labelBalanceTextz->setVisible(showSumAvailable);
ui->labelBalancez->setVisible(showSumAvailable);
bool showWatchOnly = nTotalWatchBalance != 0;
// SWK Available
bool showSWKAvailable = settingShowAllBalances || swkAvailableBalance != nTotalBalance;
bool showWatchOnlySWKAvailable = showSWKAvailable || nAvailableWatchBalance != nTotalWatchBalance;
ui->labelBalanceText->setVisible(showSWKAvailable || showWatchOnlySWKAvailable);
ui->labelBalance->setVisible(showSWKAvailable || showWatchOnlySWKAvailable);
ui->labelWatchAvailable->setVisible(showWatchOnlySWKAvailable && showWatchOnly);
// SWK Pending
bool showSWKPending = settingShowAllBalances || unconfirmedBalance != 0;
bool showWatchOnlySWKPending = showSWKPending || watchUnconfBalance != 0;
ui->labelPendingText->setVisible(showSWKPending || showWatchOnlySWKPending);
ui->labelUnconfirmed->setVisible(showSWKPending || showWatchOnlySWKPending);
ui->labelWatchPending->setVisible(showWatchOnlySWKPending && showWatchOnly);
// SWK Immature
bool showSWKImmature = settingShowAllBalances || immatureBalance != 0;
bool showWatchOnlyImmature = showSWKImmature || watchImmatureBalance != 0;
ui->labelImmatureText->setVisible(showSWKImmature || showWatchOnlyImmature);
ui->labelImmature->setVisible(showSWKImmature || showWatchOnlyImmature); // for symmetry reasons also show immature label when the watch-only one is shown
ui->labelWatchImmature->setVisible(showWatchOnlyImmature && showWatchOnly); // show watch-only immature balance
// SWK Locked
bool showSWKLocked = settingShowAllBalances || nLockedBalance != 0;
bool showWatchOnlySWKLocked = showSWKLocked || nWatchOnlyLockedBalance != 0;
ui->labelLockedBalanceText->setVisible(showSWKLocked || showWatchOnlySWKLocked);
ui->labelLockedBalance->setVisible(showSWKLocked || showWatchOnlySWKLocked);
ui->labelWatchLocked->setVisible(showWatchOnlySWKLocked && showWatchOnly);
// zSWK
bool showzSWKAvailable = settingShowAllBalances || zerocoinBalance != matureZerocoinBalance;
bool showzSWKUnconfirmed = settingShowAllBalances || unconfirmedZerocoinBalance != 0;
bool showzSWKImmature = settingShowAllBalances || immatureZerocoinBalance != 0;
ui->labelzBalanceMature->setVisible(showzSWKAvailable);
ui->labelzBalanceMatureText->setVisible(showzSWKAvailable);
ui->labelzBalanceUnconfirmed->setVisible(showzSWKUnconfirmed);
ui->labelzBalanceUnconfirmedText->setVisible(showzSWKUnconfirmed);
ui->labelzBalanceImmature->setVisible(showzSWKImmature);
ui->labelzBalanceImmatureText->setVisible(showzSWKImmature);
// Percent split
bool showPercentages = ! (zerocoinBalance == 0 && nTotalBalance == 0);
ui->labelSWKPercent->setVisible(showPercentages);
ui->labelzSWKPercent->setVisible(showPercentages);
static int cachedTxLocks = 0;
if (cachedTxLocks != nCompleteTXLocks) {
cachedTxLocks = nCompleteTXLocks;
ui->listTransactions->update();
}
}
// show/hide watch-only labels
void OverviewPage::updateWatchOnlyLabels(bool showWatchOnly)
{
ui->labelSpendable->setVisible(showWatchOnly); // show spendable label (only when watch-only is active)
ui->labelWatchonly->setVisible(showWatchOnly); // show watch-only label
ui->labelWatchAvailable->setVisible(showWatchOnly); // show watch-only available balance
ui->labelWatchPending->setVisible(showWatchOnly); // show watch-only pending balance
ui->labelWatchLocked->setVisible(showWatchOnly); // show watch-only total balance
ui->labelWatchTotal->setVisible(showWatchOnly); // show watch-only total balance
if (!showWatchOnly) {
ui->labelWatchImmature->hide();
} else {
ui->labelBalance->setIndent(20);
ui->labelUnconfirmed->setIndent(20);
ui->labelLockedBalance->setIndent(20);
ui->labelImmature->setIndent(20);
ui->labelTotal->setIndent(20);
}
}
void OverviewPage::setClientModel(ClientModel* model)
{
this->clientModel = model;
if (model) {
// Show warning if this is a prerelease version
connect(model, SIGNAL(alertsChanged(QString)), this, SLOT(updateAlerts(QString)));
updateAlerts(model->getStatusBarWarnings());
}
}
void OverviewPage::setWalletModel(WalletModel* model)
{
this->walletModel = model;
if (model && model->getOptionsModel()) {
// Set up transaction list
filter = new TransactionFilterProxy();
filter->setSourceModel(model->getTransactionTableModel());
filter->setLimit(NUM_ITEMS);
filter->setDynamicSortFilter(true);
filter->setSortRole(Qt::EditRole);
filter->setShowInactive(false);
filter->sort(TransactionTableModel::Date, Qt::DescendingOrder);
ui->listTransactions->setModel(filter);
ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);
// Keep up to date with wallet
setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(),
model->getZerocoinBalance(), model->getUnconfirmedZerocoinBalance(), model->getImmatureZerocoinBalance(),
model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance());
connect(model, SIGNAL(balanceChanged(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)), this,
SLOT(setBalance(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)));
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
connect(model->getOptionsModel(), SIGNAL(hideZeroBalancesChanged(bool)), this, SLOT(updateDisplayUnit()));
updateWatchOnlyLabels(model->haveWatchOnly());
connect(model, SIGNAL(notifyWatchonlyChanged(bool)), this, SLOT(updateWatchOnlyLabels(bool)));
}
// update the display unit, to not use the default ("SWK")
updateDisplayUnit();
}
void OverviewPage::updateDisplayUnit()
{
if (walletModel && walletModel->getOptionsModel()) {
nDisplayUnit = walletModel->getOptionsModel()->getDisplayUnit();
if (currentBalance != -1)
setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance, currentZerocoinBalance, currentUnconfirmedZerocoinBalance, currentimmatureZerocoinBalance,
currentWatchOnlyBalance, currentWatchUnconfBalance, currentWatchImmatureBalance);
// Update txdelegate->unit with the current unit
txdelegate->unit = nDisplayUnit;
ui->listTransactions->update();
}
}
void OverviewPage::updateAlerts(const QString& warnings)
{
this->ui->labelAlerts->setVisible(!warnings.isEmpty());
this->ui->labelAlerts->setText(warnings);
}
void OverviewPage::showOutOfSyncWarning(bool fShow)
{
ui->labelWalletStatus->setVisible(fShow);
ui->labelTransactionsStatus->setVisible(fShow);
}
|
/* ************************************************************************************************************* */
/* */
/* GLIP-COMPUTE */
/* Command-Line Utility for the OpenGL Image Processing LIBrary */
/* */
/* Author : R. Kerviche */
/* LICENSE : MIT License */
/* Website : glip-lib.net */
/* */
/* File : FreeImagePlusInterface.hpp */
/* Original Date : August 18th 2014 */
/* */
/* Description : FreeImage3 interface for image input/output. */
/* */
/* ************************************************************************************************************* */
#ifndef __GLIPCOMPUTE_FREEIMAGEPLUSINTERFACE__
#define __GLIPCOMPUTE_FREEIMAGEPLUSINTERFACE__
#include <FreeImagePlus.h>
#include "GLIPLib.hpp"
extern Glip::CoreGL::HdlTexture* loadImage(const std::string& filename);
extern void saveImage(Glip::CoreGL::HdlTexture& texture, const std::string& filename);
#endif
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ash/policy/external_data/user_cloud_external_data_manager.h"
#include <memory>
#include "base/location.h"
#include "base/task/sequenced_task_runner.h"
#include "components/policy/core/common/cloud/cloud_external_data_store.h"
#include "components/policy/core/common/cloud/cloud_policy_store.h"
#include "components/policy/core/common/cloud/resource_cache.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
namespace policy {
namespace {
const char kCacheKey[] = "data";
} // namespace
UserCloudExternalDataManager::UserCloudExternalDataManager(
const GetChromePolicyDetailsCallback& get_policy_details,
scoped_refptr<base::SequencedTaskRunner> backend_task_runner,
const base::FilePath& cache_path,
CloudPolicyStore* policy_store)
: CloudExternalDataManagerBase(get_policy_details, backend_task_runner),
resource_cache_(new ResourceCache(cache_path,
backend_task_runner,
/* max_cache_size */ absl::nullopt)) {
SetPolicyStore(policy_store);
SetExternalDataStore(std::make_unique<CloudExternalDataStore>(
kCacheKey, backend_task_runner, resource_cache_));
}
UserCloudExternalDataManager::~UserCloudExternalDataManager() {
SetExternalDataStore(nullptr);
backend_task_runner_->DeleteSoon(FROM_HERE, resource_cache_);
}
} // namespace policy
|
No-one has translated the ppqueue example into C++ yet. Be the first to create
ppqueue in C++ and get one free Internet! If you're the author of the C++
binding, this is a great way to get people to use 0MQ in C++.
To submit a new translation email it to zeromq-dev@lists.zeromq.org. Please:
* Stick to identical functionality and naming used in examples so that readers
can easily compare languages.
* You MUST place your name as author in the examples so readers can contact you.
* You MUST state in the email that you license your code under the MIT/X11
license.
Subscribe to the email list at http://lists.zeromq.org/mailman/listinfo/zeromq-dev.
|
// Copyright 2017-2018 by Martin Moene
//
// https://github.com/martinmoene/string-view-lite
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include "string-view-main.t.hpp"
#define nssv_PRESENT( x ) \
std::cout << #x << ": " << x << "\n"
#define nssv_ABSENT( x ) \
std::cout << #x << ": (undefined)\n"
lest::tests & specification()
{
static lest::tests tests;
return tests;
}
CASE( "string-view-lite version" "[.string-view][.version]" )
{
nssv_PRESENT( string_view_lite_MAJOR );
nssv_PRESENT( string_view_lite_MINOR );
nssv_PRESENT( string_view_lite_PATCH );
nssv_PRESENT( string_view_lite_VERSION );
}
CASE( "string-view-lite configuration" "[.string-view][.config]" )
{
nssv_PRESENT( nssv_HAVE_STD_STRING_VIEW );
nssv_PRESENT( nssv_USES_STD_STRING_VIEW );
nssv_PRESENT( nssv_CONFIG_SELECT_STRING_VIEW );
nssv_PRESENT( nssv_STRING_VIEW_DEFAULT );
nssv_PRESENT( nssv_STRING_VIEW_NONSTD );
nssv_PRESENT( nssv_STRING_VIEW_STD );
nssv_PRESENT( nssv_CONFIG_STD_SV_OPERATOR );
nssv_PRESENT( nssv_CONFIG_USR_SV_OPERATOR );
// nssv_PRESENT( nssv_CONFIG_CONVERSION_STD_STRING );
nssv_PRESENT( nssv_CONFIG_CONVERSION_STD_STRING_CLASS_METHODS );
nssv_PRESENT( nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS );
nssv_PRESENT( nssv_CPLUSPLUS );
}
CASE( "__cplusplus" "[.stdc++]" )
{
nssv_PRESENT( __cplusplus );
#if _MSVC_LANG
nssv_PRESENT( _MSVC_LANG );
#else
nssv_ABSENT( _MSVC_LANG );
#endif
}
CASE( "Compiler version" "[.compiler]" )
{
#if nssv_USES_STD_STRING_VIEW
std::cout << "(Compiler version not available: using std::string_view)\n";
#else
nssv_PRESENT( nssv_COMPILER_CLANG_VERSION );
nssv_PRESENT( nssv_COMPILER_GNUC_VERSION );
nssv_PRESENT( nssv_COMPILER_MSVC_VERSION );
#endif
}
CASE( "presence of C++ language features" "[.stdlanguage]" )
{
#if nssv_USES_STD_STRING_VIEW
std::cout << "(Compiler version not available: using std::string_view)\n";
#else
nssv_PRESENT( nssv_HAVE_CONSTEXPR_11 );
nssv_PRESENT( nssv_HAVE_CONSTEXPR_14 );
nssv_PRESENT( nssv_HAVE_EXPLICIT_CONVERSION );
nssv_PRESENT( nssv_HAVE_NODISCARD );
nssv_PRESENT( nssv_HAVE_NOEXCEPT );
nssv_PRESENT( nssv_HAVE_NULLPTR );
nssv_PRESENT( nssv_HAVE_REF_QUALIFIER );
nssv_PRESENT( nssv_HAVE_UNICODE_LITERALS );
nssv_PRESENT( nssv_HAVE_USER_DEFINED_LITERALS );
nssv_PRESENT( nssv_HAVE_WCHAR16_T );
nssv_PRESENT( nssv_HAVE_WCHAR32_T );
#endif
}
CASE( "presence of C++ library features" "[.stdlibrary]" )
{
#if nssv_USES_STD_STRING_VIEW
std::cout << "(Compiler version not available: using std::string_view)\n";
#else
nssv_PRESENT( nssv_HAVE_STD_HASH );
#endif
#if _HAS_CPP0X
nssv_PRESENT( _HAS_CPP0X );
#else
nssv_ABSENT( _HAS_CPP0X );
#endif
}
int main( int argc, char * argv[] )
{
return lest::run( specification(), argc, argv );
}
#if 0
g++ -I../include/nonstd -o string-view-lite.t.exe string-view-lite.t.cpp && string-view-lite.t.exe --pass
g++ -std=c++98 -I../include/nonstd -o string-view-lite.t.exe string-view-lite.t.cpp && string-view-lite.t.exe --pass
g++ -std=c++03 -I../include/nonstd -o string-view-lite.t.exe string-view-lite.t.cpp && string-view-lite.t.exe --pass
g++ -std=c++0x -I../include/nonstd -o string-view-lite.t.exe string-view-lite.t.cpp && string-view-lite.t.exe --pass
g++ -std=c++11 -I../include/nonstd -o string-view-lite.t.exe string-view-lite.t.cpp && string-view-lite.t.exe --pass
g++ -std=c++14 -I../include/nonstd -o string-view-lite.t.exe string-view-lite.t.cpp && string-view-lite.t.exe --pass
g++ -std=c++17 -I../include/nonstd -o string-view-lite.t.exe string-view-lite.t.cpp && string-view-lite.t.exe --pass
cl -EHsc -I../include/nonstd string-view-lite.t.cpp && string-view-lite.t.exe --pass
#endif
// end of file
|
//! \file
/*
** Copyright (C) - Triton
**
** This program is under the terms of the BSD License.
*/
#include <triton/pythonBindings.hpp>
#include <triton/pythonUtils.hpp>
#include <triton/callbacks.hpp>
/*! \page py_CALLBACK_page CALLBACK
\brief [**python api**] All information about the CALLBACK python namespace.
\tableofcontents
\section CALLBACK_py_description Description
<hr>
The CALLBACK namespace contains all kinds of callbacks.
\subsection CALLBACK_py_example Example
~~~~~~~~~~~~~{.py}
>>> addCallback(your_function, CALLBACK.GET_CONCRETE_MEMORY_VALUE)
~~~~~~~~~~~~~
\section CALLBACK_py_api Python API - Items of the CALLBACK namespace
<hr>
- **CALLBACK.GET_CONCRETE_MEMORY_VALUE**<br>
The callback takes as arguments a \ref py_TritonContext_page and a \ref py_MemoryAccess_page. Callbacks will be called each time that the
Triton library will need a concrete memory value. The callback must return nothing.
- **CALLBACK.GET_CONCRETE_REGISTER_VALUE**<br>
The callback takes as arguments a \ref py_TritonContext_page and a \ref py_Register_page. Callbacks will be called each time that the
Triton library will need a concrete register value. The callback must return nothing.
- **CALLBACK.SYMBOLIC_SIMPLIFICATION**<br>
Defines a callback which be called before all symbolic assignments. The callback takes as arguments
a \ref py_TritonContext_page and an \ref py_AstNode_page. This callback must return a valid \ref py_AstNode_page. The returned node is
used as assignment. See also the page about \ref SMT_simplification_page.
*/
namespace triton {
namespace bindings {
namespace python {
void initCallbackNamespace(PyObject* callbackDict) {
PyDict_SetItemString(callbackDict, "GET_CONCRETE_MEMORY_VALUE", PyLong_FromUint32(triton::callbacks::GET_CONCRETE_MEMORY_VALUE));
PyDict_SetItemString(callbackDict, "GET_CONCRETE_REGISTER_VALUE", PyLong_FromUint32(triton::callbacks::GET_CONCRETE_REGISTER_VALUE));
PyDict_SetItemString(callbackDict, "SYMBOLIC_SIMPLIFICATION", PyLong_FromUint32(triton::callbacks::SYMBOLIC_SIMPLIFICATION));
}
}; /* python namespace */
}; /* bindings namespace */
}; /* triton namespace */
|
//------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// 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 "math/meta/math_type_traits.hpp"
#include "math/standard_functions/exp.hpp"
#include "vm/fixed.hpp"
#include "vm/module.hpp"
#include "vm/vm.hpp"
#include "vm_modules/math/exp.hpp"
#include <cmath>
using namespace fetch::vm;
namespace fetch {
namespace vm_modules {
namespace math {
namespace {
template <typename T>
fetch::math::meta::IfIsMath<T, T> Exp(VM * /*vm*/, T const &a)
{
T x;
fetch::math::Exp(a, x);
return x;
}
template <typename T>
IfIsPtrFixed128<T, Ptr<T>> ExpPtr(VM *vm, Ptr<T> const &a)
{
fixed_point::fp128_t x = a->data_;
fetch::math::Exp(x, x);
return Ptr<Fixed128>(new Fixed128(vm, x));
}
} // namespace
void BindExp(Module &module)
{
module.CreateFreeFunction("exp", &Exp<float_t>);
module.CreateFreeFunction("exp", &Exp<double_t>);
module.CreateFreeFunction("exp", &Exp<fixed_point::fp32_t>);
module.CreateFreeFunction("exp", &Exp<fixed_point::fp64_t>);
module.CreateFreeFunction("exp", &ExpPtr<Fixed128>);
}
} // namespace math
} // namespace vm_modules
} // namespace fetch
|
#include <string>
using std::string;
#include "crypto_scalarmult.h"
string crypto_scalarmult_base(const string &n)
{
unsigned char q[crypto_scalarmult_BYTES];
if (n.size() != crypto_scalarmult_SCALARBYTES) throw "incorrect scalar length";
crypto_scalarmult_base(q,(const unsigned char *) n.c_str());
return string((char *) q,sizeof q);
}
|
//------------------------------------------------------------------------------
// ceuigeometrybuffer.cc
// (C) 2009 Radon Labs GmbH
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "sui/ceui/ceuigeometrybuffer.h"
#include "sui/ceui/ceuiserver.h"
#include "coregraphics/vertexcomponent.h"
#include "coregraphics/memoryvertexbufferloader.h"
#include "resources/resourceloader.h"
#include "coregraphics/renderdevice.h"
namespace CEUI
{
using namespace CoreGraphics;
using namespace Resources;
//------------------------------------------------------------------------------
/**
*/
CEUIGeometryBuffer::CEUIGeometryBuffer() :
translation(0, 0, 0),
rotation(0, 0, 0),
pivot(0, 0, 0),
renderEffect(0),
vertexCount(0)
{
// create vertex buffer
this->vertexBuffer = VertexBuffer::Create();
// MemoryVertexBufferLoader::Setup mit 0-Datapointern
Util::Array<VertexComponent> vertexComponents;
vertexComponents.Append(VertexComponent(VertexComponent::Position, 0, VertexComponent::Float3));
vertexComponents.Append(VertexComponent(VertexComponent::Color, 0, VertexComponent::Float4));
vertexComponents.Append(VertexComponent(VertexComponent::TexCoord, 0, VertexComponent::Float2));
Ptr<MemoryVertexBufferLoader> vbLoader = MemoryVertexBufferLoader::Create();
vbLoader->Setup(vertexComponents,
4096,
0,
4096 * 9 * sizeof(float),
Base::ResourceBase::UsageDynamic,
Base::ResourceBase::AccessWrite);
this->vertexBuffer->SetLoader(vbLoader.upcast<ResourceLoader>());
this->vertexBuffer->SetAsyncEnabled(false);
this->vertexBuffer->Load();
n_assert(this->vertexBuffer->IsLoaded());
this->vertexBuffer->SetLoader(0);
// set primitive group
this->primGroup.SetBaseVertex(0);
this->primGroup.SetNumVertices(4096);
this->primGroup.SetBaseIndex(0);
this->primGroup.SetNumIndices(0);
this->primGroup.SetPrimitiveTopology(PrimitiveTopology::TriangleList);
}
//------------------------------------------------------------------------------
/**
*/
CEUIGeometryBuffer::~CEUIGeometryBuffer()
{
if (this->vertexBuffer.isvalid())
{
this->vertexBuffer->Unload();
this->vertexBuffer = 0;
}
this->batches.Clear();
this->vertexCount = 0;
this->activeTexture = 0;
}
//------------------------------------------------------------------------------
/**
*/
void
CEUIGeometryBuffer::draw() const
{
// render batches
//in case of this assertion: increase the number of vertices (4096) in open-function
n_assert(this->vertexBuffer.isvalid());
n_assert((int)this->getVertexCount() < (int)this->vertexBuffer->GetNumVertices());
// just do if one element min
if (this->getBatchCount() <= 0)
{
return;
}
const_cast<CEUIGeometryBuffer*>(this)->UpdateVertexBuffer();
// get shader instance
const_cast<CEUIGeometryBuffer*>(this)->shdInst = CEUIRenderer::Instance()->GetShaderInstance();
const_cast<CEUIGeometryBuffer*>(this)->guiTextureSemantic = CEUIRenderer::Instance()->GetTextureSemantic();
// now simply draw the vertex buffer
IndexT currentIndex = 0;
IndexT index;
for (index = 0; index < this->batches.Size(); index++)
{
const BatchInfo& batch = this->batches[index];
//// apply shader variables
shdInst->GetVariableBySemantic(this->guiTextureSemantic)->SetTexture(batch.Key());
#ifdef __DX11__
shdInst->CommitAll();
#else
shdInst->Commit();
#endif
//// render the vertex buffer
RenderDevice* renderDevice = RenderDevice::Instance();
const_cast<CEUIGeometryBuffer*>(this)->primGroup.SetBaseVertex(currentIndex);
const_cast<CEUIGeometryBuffer*>(this)->primGroup.SetNumVertices(batch.Value());
renderDevice->SetStreamSource(0, this->vertexBuffer, 0);
renderDevice->SetVertexLayout(this->vertexBuffer->GetVertexLayout());
renderDevice->SetPrimitiveGroup(this->primGroup);
renderDevice->Draw();
currentIndex += batch.Value();
}
}
//------------------------------------------------------------------------------
/**
*/
void
CEUIGeometryBuffer::appendVertex(const CEGUI::Vertex& vertex)
{
this->appendGeometry(&vertex, 1);
}
//------------------------------------------------------------------------------
/**
*/
void
CEUIGeometryBuffer::appendGeometry(const CEGUI::Vertex* const vbuff, CEGUI::uint vertex_count)
{
// create new batch if this is the first one or
// active texture differs from last batch
if (this->batches.IsEmpty() || this->batches.Back().Key() != this->activeTexture->GetTexture())
{
this->batches.Append(BatchInfo(this->activeTexture->GetTexture(), vertex_count));
}
else
{
this->batches.Back().Value() += vertex_count;
}
// transform to screen coordinates
const CEGUI::Size& sz = CEUI::CEUIRenderer::Instance()->getDisplaySize();
float posToScreenX = 1.0f / sz.d_width;
float posToScreenY = 1.0f / sz.d_height;
// append vertex buffer entries to this batch
CEGUI::uint vertexId;
for (vertexId = 0; vertexId < vertex_count; vertexId++)
{
VertexBufferEntry entry;
entry.pos.set_x(((vbuff[vertexId].position.d_x * posToScreenX) * 2.0f)- 1.0f);
entry.pos.set_y(-(((vbuff[vertexId].position.d_y * posToScreenY) * 2.0f) -1.0f));
entry.pos.set_z(vbuff[vertexId].position.d_z);
entry.col.set_x(vbuff[vertexId].colour_val.getRed());
entry.col.set_y(vbuff[vertexId].colour_val.getGreen());
entry.col.set_z(vbuff[vertexId].colour_val.getBlue());
entry.col.set_w(vbuff[vertexId].colour_val.getAlpha());
// copy vertex uv
entry.uv.set(vbuff[vertexId].tex_coords.d_x, vbuff[vertexId].tex_coords.d_y);
this->vbEntries.Append(entry);
}
this->vertexCount += vertex_count;
}
//------------------------------------------------------------------------------
/**
*/
void
CEUIGeometryBuffer::UpdateVertexBuffer()
{
// map vertex buffer for appending vertices
float* vertexPtr = (float*)this->vertexBuffer->Map(VertexBuffer::MapWriteDiscard);
// append vertex buffer entries to this batch
CEGUI::uint vertexId;
for (vertexId = 0; vertexId < this->getVertexCount(); vertexId++)
{
// copy vertex position
vertexPtr[0] = this->vbEntries[vertexId].pos.x() + this->translation.d_x;
vertexPtr[1] = this->vbEntries[vertexId].pos.y() + this->translation.d_y;
vertexPtr[2] = this->vbEntries[vertexId].pos.z() + this->translation.d_z;
vertexPtr += 3;
// copy vertex colour
vertexPtr[0] = this->vbEntries[vertexId].col.x();
vertexPtr[1] = this->vbEntries[vertexId].col.y();
vertexPtr[2] = this->vbEntries[vertexId].col.z();
vertexPtr[3] = this->vbEntries[vertexId].col.w();
vertexPtr += 4;
// copy vertex uv
vertexPtr[0] = this->vbEntries[vertexId].uv.x();
vertexPtr[1] = this->vbEntries[vertexId].uv.y();
vertexPtr += 2;
}
// unmap vertex buffer
this->vertexBuffer->Unmap();
}
//------------------------------------------------------------------------------
/**
*/
void
CEUIGeometryBuffer::reset()
{
this->batches.Clear();
this->vbEntries.Clear();
this->vertexCount = 0;
this->activeTexture = 0;
}
//------------------------------------------------------------------------------
/**
*/
void
CEUIGeometryBuffer::setTranslation(const CEGUI::Vector3& v)
{
// transform to screen coordinates
const CEGUI::Size& sz = CEUI::CEUIRenderer::Instance()->getDisplaySize();
float posToScreenX = 1.0f / sz.d_width;
float posToScreenY = 1.0f / sz.d_height;
this->translation.d_x = v.d_x * posToScreenX * 2.0f;
this->translation.d_y = -v.d_y * posToScreenY * 2.0f;
this->translation.d_z = v.d_z;
}
//------------------------------------------------------------------------------
/**
*/
void
CEUIGeometryBuffer::setRotation(const CEGUI::Vector3& r)
{
this->rotation = r;
}
//------------------------------------------------------------------------------
/**
*/
void
CEUIGeometryBuffer::setPivot(const CEGUI::Vector3& p)
{
this->pivot = p;
}
} // namespace CEUI
|
/*
Motor.cpp - Library for motor control
Created by Klaus Röbenack, 2015, 2019
*/
#include "Arduino.h"
#include "Motor.h"
// Constructor
Motor::Motor (byte pinDIRA, byte pinDIRB,
byte pinPWMA, byte pinPWMB)
: DIRA(pinDIRA), DIRB(pinDIRB),
PWMA(pinPWMA), PWMB(pinPWMB)
{
digitalWrite (PWMA, 0);
digitalWrite (PWMB, 0);
}
// Initialization
void Motor::begin()
{
pinMode (DIRA, OUTPUT);
pinMode (DIRB, OUTPUT);
pinMode (PWMA, OUTPUT);
pinMode (PWMB, OUTPUT);
}
// Internal function
void Motor::setValues (byte pinDir, byte pinPwm, int speed)
{
// Direction
digitalWrite (pinDir, speed>=0 ? LOW : HIGH );
// Speed (PWM value)
speed=abs(speed);
speed=min(speed,VMAX);
if (speed<VMIN) speed=0;
analogWrite(pinPwm, speed);
}
// Speed for both motors
void Motor::write (int speedA, int speedB)
{
writeA(speedA);
writeB(speedB);
}
|
//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#pragma once
#include "LayerTestResult.hpp"
#include <backendsCommon/IBackendInternal.hpp>
#include <backendsCommon/WorkloadFactory.hpp>
LayerTestResult<float, 4> StridedSlice4dFloat32Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<float, 4> StridedSlice4dReverseFloat32Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<float, 4> StridedSliceSimpleStrideFloat32Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<float, 4> StridedSliceSimpleRangeMaskFloat32Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<float, 2> StridedSliceShrinkAxisMaskFloat32Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<float, 2> StridedSliceShrinkAxisMaskBitPosition0Dim3Float32Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<float, 4> StridedSliceShrinkAxisMaskCTSFloat32Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<float, 3> StridedSliceShrinkAxisMaskBitPosition0Float32Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<float, 3> StridedSliceShrinkAxisMaskBitPosition1Float32Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<float, 3> StridedSliceShrinkAxisMaskBitPosition2Float32Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<float, 3> StridedSliceShrinkAxisMaskBitPosition3Float32Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<float, 2> StridedSliceShrinkAxisMaskBitPosition0And1Float32Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<float, 2> StridedSliceShrinkAxisMaskBitPosition0And2Float32Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<float, 2> StridedSliceShrinkAxisMaskBitPosition0And3Float32Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<float, 1> StridedSliceShrinkAxisMaskBitPosition0And1And3Float32Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<float, 3> StridedSlice3dFloat32Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<float, 3> StridedSlice3dReverseFloat32Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<float, 2> StridedSlice2dFloat32Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<float, 2> StridedSlice2dReverseFloat32Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<uint8_t, 4> StridedSlice4dUint8Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<uint8_t, 4> StridedSlice4dReverseUint8Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<uint8_t, 4> StridedSliceSimpleStrideUint8Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<uint8_t, 4> StridedSliceSimpleRangeMaskUint8Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<uint8_t, 2> StridedSliceShrinkAxisMaskUint8Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<uint8_t, 2> StridedSliceShrinkAxisMaskBitPosition0Dim3Uint8Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<uint8_t, 3> StridedSliceShrinkAxisMaskBitPosition0Uint8Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<uint8_t, 3> StridedSliceShrinkAxisMaskBitPosition1Uint8Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<uint8_t, 3> StridedSliceShrinkAxisMaskBitPosition2Uint8Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<uint8_t, 3> StridedSliceShrinkAxisMaskBitPosition3Uint8Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<uint8_t, 2> StridedSliceShrinkAxisMaskBitPosition0And1Uint8Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<uint8_t, 2> StridedSliceShrinkAxisMaskBitPosition0And2Uint8Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<uint8_t, 2> StridedSliceShrinkAxisMaskBitPosition0And3Uint8Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<uint8_t, 1> StridedSliceShrinkAxisMaskBitPosition0And1And3Uint8Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<uint8_t, 3> StridedSlice3dUint8Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<uint8_t, 3> StridedSlice3dReverseUint8Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<uint8_t, 2> StridedSlice2dUint8Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<uint8_t, 2> StridedSlice2dReverseUint8Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<int16_t, 4> StridedSlice4dInt16Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<int16_t, 4> StridedSlice4dReverseInt16Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<int16_t, 4> StridedSliceSimpleStrideInt16Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<int16_t, 4> StridedSliceSimpleRangeMaskInt16Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<int16_t, 2> StridedSliceShrinkAxisMaskInt16Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<int16_t, 3> StridedSlice3dInt16Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<int16_t, 3> StridedSlice3dReverseInt16Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<int16_t, 2> StridedSlice2dInt16Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
LayerTestResult<int16_t, 2> StridedSlice2dReverseInt16Test(
armnn::IWorkloadFactory& workloadFactory,
const armnn::IBackendInternal::IMemoryManagerSharedPtr& memoryManager);
|
/**************************************************************************************
Copyright 2015 Applied Research Associates, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the License
at:
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
**************************************************************************************/
#include <biogears/cdm/stdafx.h>
#include <biogears/cdm/circuit/SECircuitNode.h>
#include <biogears/schema/CircuitNodeData.hxx>
template <CIRCUIT_NODE_TEMPLATE>
SECircuitNode<CIRCUIT_NODE_TYPES>::SECircuitNode(const std::string& name, Logger* logger)
: Loggable(logger)
, m_Name(name)
{
m_Potential = nullptr;
m_NextPotential = nullptr;
m_Quantity = nullptr;
m_NextQuantity = nullptr;
m_QuantityBaseline = nullptr;
}
template <CIRCUIT_NODE_TEMPLATE>
SECircuitNode<CIRCUIT_NODE_TYPES>::~SECircuitNode()
{
Clear();
}
template <CIRCUIT_NODE_TEMPLATE>
void SECircuitNode<CIRCUIT_NODE_TYPES>::Clear()
{
SAFE_DELETE(m_Potential);
SAFE_DELETE(m_NextPotential);
SAFE_DELETE(m_Quantity);
SAFE_DELETE(m_NextQuantity);
SAFE_DELETE(m_QuantityBaseline);
}
template <CIRCUIT_NODE_TEMPLATE>
bool SECircuitNode<CIRCUIT_NODE_TYPES>::Load(const CDM::CircuitNodeData& in)
{
Clear();
return true;
}
template <CIRCUIT_NODE_TEMPLATE>
void SECircuitNode<CIRCUIT_NODE_TYPES>::Unload(CDM::CircuitNodeData& data) const
{
data.Name(m_Name);
}
template <CIRCUIT_NODE_TEMPLATE>
std::string SECircuitNode<CIRCUIT_NODE_TYPES>::GetName() const
{
return m_Name;
}
template <CIRCUIT_NODE_TEMPLATE>
bool SECircuitNode<CIRCUIT_NODE_TYPES>::HasPotential() const
{
return m_Potential == nullptr ? false : m_Potential->IsValid();
}
template <CIRCUIT_NODE_TEMPLATE>
PotentialScalar& SECircuitNode<CIRCUIT_NODE_TYPES>::GetPotential()
{
if (m_Potential == nullptr)
m_Potential = new PotentialScalar();
return *m_Potential;
}
template <CIRCUIT_NODE_TEMPLATE>
bool SECircuitNode<CIRCUIT_NODE_TYPES>::HasNextPotential() const
{
return m_NextPotential == nullptr ? false : m_NextPotential->IsValid();
}
template <CIRCUIT_NODE_TEMPLATE>
PotentialScalar& SECircuitNode<CIRCUIT_NODE_TYPES>::GetNextPotential()
{
if (m_NextPotential == nullptr)
m_NextPotential = new PotentialScalar();
return *m_NextPotential;
}
template <CIRCUIT_NODE_TEMPLATE>
bool SECircuitNode<CIRCUIT_NODE_TYPES>::HasQuantity() const
{
return m_Quantity == nullptr ? false : m_Quantity->IsValid();
}
template <CIRCUIT_NODE_TEMPLATE>
QuantityScalar& SECircuitNode<CIRCUIT_NODE_TYPES>::GetQuantity()
{
if (m_Quantity == nullptr)
m_Quantity = new QuantityScalar();
return *m_Quantity;
}
template <CIRCUIT_NODE_TEMPLATE>
bool SECircuitNode<CIRCUIT_NODE_TYPES>::HasNextQuantity() const
{
return m_NextQuantity == nullptr ? false : m_NextQuantity->IsValid();
}
template <CIRCUIT_NODE_TEMPLATE>
QuantityScalar& SECircuitNode<CIRCUIT_NODE_TYPES>::GetNextQuantity()
{
if (m_NextQuantity == nullptr)
m_NextQuantity = new QuantityScalar();
return *m_NextQuantity;
}
template <CIRCUIT_NODE_TEMPLATE>
bool SECircuitNode<CIRCUIT_NODE_TYPES>::HasQuantityBaseline() const
{
return m_QuantityBaseline == nullptr ? false : m_QuantityBaseline->IsValid();
}
template <CIRCUIT_NODE_TEMPLATE>
QuantityScalar& SECircuitNode<CIRCUIT_NODE_TYPES>::GetQuantityBaseline()
{
if (m_QuantityBaseline == nullptr)
m_QuantityBaseline = new QuantityScalar();
return *m_QuantityBaseline;
}
|
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/pdf/browser/pdf_navigation_throttle.h"
#include <memory>
#include <utility>
#include "base/location.h"
#include "base/run_loop.h"
#include "base/test/scoped_feature_list.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "components/pdf/browser/fake_pdf_stream_delegate.h"
#include "components/pdf/browser/pdf_stream_delegate.h"
#include "content/public/browser/navigation_throttle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/test/mock_navigation_handle.h"
#include "content/public/test/mock_web_contents_observer.h"
#include "content/public/test/navigation_simulator.h"
#include "content/public/test/test_renderer_host.h"
#include "pdf/pdf_features.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/page_transition_types.h"
#include "url/gurl.h"
namespace pdf {
namespace {
using ::testing::_;
using ::testing::NiceMock;
using ::testing::Return;
class PdfNavigationThrottleTest : public content::RenderViewHostTestHarness {
protected:
content::RenderFrameHost* CreateChildFrame() {
content::RenderFrameHostTester::For(main_rfh())
->InitializeRenderFrameIfNeeded();
return content::RenderFrameHostTester::For(main_rfh())
->AppendChild("subframe");
}
void InitializeNavigationHandle(const GURL& url,
content::RenderFrameHost* render_frame_host) {
navigation_handle_ =
std::make_unique<NiceMock<content::MockNavigationHandle>>(
url, render_frame_host);
navigation_handle_->set_initiator_origin(
render_frame_host->GetLastCommittedOrigin());
}
std::unique_ptr<PdfNavigationThrottle> CreateNavigationThrottle(
const GURL& url) {
content::RenderFrameHost* child_frame = CreateChildFrame();
InitializeNavigationHandle(url, child_frame);
ON_CALL(*navigation_handle_, GetFrameTreeNodeId())
.WillByDefault(Return(child_frame->GetFrameTreeNodeId()));
return std::make_unique<PdfNavigationThrottle>(navigation_handle_.get(),
std::move(stream_delegate_));
}
GURL stream_url() const {
return GURL(FakePdfStreamDelegate::kDefaultStreamUrl);
}
GURL original_url() const {
return GURL(FakePdfStreamDelegate::kDefaultOriginalUrl);
}
base::test::ScopedFeatureList features_;
std::unique_ptr<FakePdfStreamDelegate> stream_delegate_ =
std::make_unique<FakePdfStreamDelegate>();
std::unique_ptr<NiceMock<content::MockNavigationHandle>> navigation_handle_;
};
class PdfNavigationThrottleUnseasonedDisabledTest
: public PdfNavigationThrottleTest {
protected:
PdfNavigationThrottleUnseasonedDisabledTest() {
features_.InitAndDisableFeature(chrome_pdf::features::kPdfUnseasoned);
}
};
class PdfNavigationThrottleUnseasonedEnabledTest
: public PdfNavigationThrottleTest {
protected:
PdfNavigationThrottleUnseasonedEnabledTest() {
features_.InitAndEnableFeature(chrome_pdf::features::kPdfUnseasoned);
}
};
} // namespace
TEST_F(PdfNavigationThrottleUnseasonedDisabledTest, MaybeCreateThrottleFor) {
InitializeNavigationHandle(stream_url(), CreateChildFrame());
EXPECT_FALSE(PdfNavigationThrottle::MaybeCreateThrottleFor(
navigation_handle_.get(), std::move(stream_delegate_)));
}
TEST_F(PdfNavigationThrottleUnseasonedEnabledTest, MaybeCreateThrottleFor) {
InitializeNavigationHandle(stream_url(), CreateChildFrame());
EXPECT_TRUE(PdfNavigationThrottle::MaybeCreateThrottleFor(
navigation_handle_.get(), std::move(stream_delegate_)));
}
TEST_F(PdfNavigationThrottleUnseasonedEnabledTest,
MaybeCreateThrottleForMainFrame) {
InitializeNavigationHandle(stream_url(), main_rfh());
EXPECT_FALSE(PdfNavigationThrottle::MaybeCreateThrottleFor(
navigation_handle_.get(), std::move(stream_delegate_)));
}
TEST_F(PdfNavigationThrottleTest, WillStartRequest) {
auto navigation_throttle = CreateNavigationThrottle(stream_url());
NiceMock<content::MockWebContentsObserver> web_contents_observer(
web_contents());
EXPECT_EQ(content::NavigationThrottle::CANCEL_AND_IGNORE,
navigation_throttle->WillStartRequest().action());
EXPECT_CALL(web_contents_observer, DidStartLoading());
base::RunLoop run_loop;
base::SequencedTaskRunnerHandle::Get()->PostTask(FROM_HERE,
run_loop.QuitClosure());
run_loop.Run();
auto navigation_simulator = content::NavigationSimulator::CreateFromPending(
web_contents()->GetController());
EXPECT_TRUE(ui::PageTransitionCoreTypeIs(
ui::PAGE_TRANSITION_AUTO_SUBFRAME,
navigation_simulator->GetNavigationHandle()->GetPageTransition()));
EXPECT_CALL(web_contents_observer, DidFinishLoad(_, original_url()));
navigation_simulator->Commit();
}
TEST_F(PdfNavigationThrottleTest, WillStartRequestDeleteContents) {
auto navigation_throttle = CreateNavigationThrottle(stream_url());
NiceMock<content::MockWebContentsObserver> web_contents_observer(
web_contents());
EXPECT_EQ(content::NavigationThrottle::CANCEL_AND_IGNORE,
navigation_throttle->WillStartRequest().action());
DeleteContents();
EXPECT_CALL(web_contents_observer, DidStartLoading()).Times(0);
base::RunLoop run_loop;
base::SequencedTaskRunnerHandle::Get()->PostTask(FROM_HERE,
run_loop.QuitClosure());
run_loop.Run();
}
TEST_F(PdfNavigationThrottleTest, WillStartRequestNoStreamInfo) {
stream_delegate_->clear_stream_info();
auto navigation_throttle = CreateNavigationThrottle(stream_url());
EXPECT_EQ(content::NavigationThrottle::PROCEED,
navigation_throttle->WillStartRequest().action());
}
TEST_F(PdfNavigationThrottleTest, WillStartRequestOtherUrl) {
auto navigation_throttle =
CreateNavigationThrottle(GURL("https://example.test"));
EXPECT_EQ(content::NavigationThrottle::PROCEED,
navigation_throttle->WillStartRequest().action());
}
} // namespace pdf
|
#include "CuaEstatica.h"
#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;
CuaEstatica::CuaEstatica(const int max_size) {
_data = new int[max_size];
_max_size = max_size;
_size = 0;
_front = 0;
_rear = 0;
cout << "Estructura creada.\n\n";
}
CuaEstatica::~CuaEstatica() {
delete [] _data;
}
void CuaEstatica::enqueue(const int key) {
if (isFull()) throw std::out_of_range("EXCEPTION: L'estructura esta plena.");
else {
_data[_rear] = key;
cout << "Element " << _data[_rear] << " agregat.\n\n";
_rear = ++_rear % _max_size;
_size++;
}
}
void CuaEstatica::dequeue() {
if (isEmpty()) throw std::out_of_range("EXCEPTION: L'estructura esta buida.");
else {
cout << "Element " << _data[_front] << " eliminat." << "\n\n";
_front = ++_front % _max_size;
_size--;
}
}
bool CuaEstatica::isFull() {
if (_size < _max_size) return false;
else return true;
}
bool CuaEstatica::isEmpty() {
if (_size != 0) return false;
else return true;
}
void CuaEstatica::print() {
//Comentat per que els couts dels casos de prova coincideixin amb les sortides esperades de l'enunciat.
//if (isEmpty()) throw std::out_of_range("EXCEPTION: L'estructura esta buida");
cout << '[';
for (int i = 0; i < _size; i++) {
cout << _data[(i + _front) % _max_size] << (i != _size - 1 ? ", " : "]\n\n");
}
}
int CuaEstatica::getFront() {
if (isEmpty()) throw std::out_of_range("EXCEPTION: L'estructura esta buida.");
return _data[_front];
}
void CuaEstatica::printFrontRear() {
//Comentat per que els couts dels casos de prova coincideixin amb les sortides esperades de l'enunciat.
//if (isEmpty()) throw std::out_of_range("EXCEPTION: L'estructura esta buida");
cout << "Front: " << _front << ", Rear: " << _rear << ".\n\n";
}
void CuaEstatica::duplica() {
int tamany_original = this->_size;
for (int i = 0; i < tamany_original; i++) {
this->enqueue(this->_data[(i + _front) % _max_size]);
}
}
|
/*
Copyright (c) 2010-2016, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Universite de Sherbrooke nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <rtabmap_ros/OdometryROS.h>
#include <pluginlib/class_list_macros.h>
#include <nodelet/nodelet.h>
#include <message_filters/subscriber.h>
#include <message_filters/time_synchronizer.h>
#include <message_filters/sync_policies/approximate_time.h>
#include <image_transport/image_transport.h>
#include <image_transport/subscriber_filter.h>
#include <image_geometry/stereo_camera_model.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/image_encodings.h>
#include <cv_bridge/cv_bridge.h>
#include "rtabmap_ros/MsgConversion.h"
#include <rtabmap/core/util3d.h>
#include <rtabmap/core/util2d.h>
#include <rtabmap/utilite/ULogger.h>
#include <rtabmap/utilite/UConversion.h>
#include <rtabmap/utilite/UStl.h>
using namespace rtabmap;
namespace rtabmap_ros
{
class RGBDOdometry : public rtabmap_ros::OdometryROS
{
public:
RGBDOdometry() :
OdometryROS(false, true, false),
approxSync_(0),
exactSync_(0),
approxSync2_(0),
exactSync2_(0),
approxSync3_(0),
exactSync3_(0),
approxSync4_(0),
exactSync4_(0),
queueSize_(5)
{
}
virtual ~RGBDOdometry()
{
rgbdSub_.shutdown();
if(approxSync_)
{
delete approxSync_;
}
if(exactSync_)
{
delete exactSync_;
}
if(approxSync2_)
{
delete approxSync2_;
}
if(exactSync2_)
{
delete exactSync2_;
}
if(approxSync3_)
{
delete approxSync3_;
}
if(exactSync3_)
{
delete exactSync3_;
}
if(approxSync4_)
{
delete approxSync4_;
}
if(exactSync4_)
{
delete exactSync4_;
}
}
private:
virtual void onOdomInit()
{
ros::NodeHandle & nh = getNodeHandle();
ros::NodeHandle & pnh = getPrivateNodeHandle();
int rgbdCameras = 1;
bool approxSync = true;
bool subscribeRGBD = false;
pnh.param("approx_sync", approxSync, approxSync);
pnh.param("queue_size", queueSize_, queueSize_);
pnh.param("subscribe_rgbd", subscribeRGBD, subscribeRGBD);
if(pnh.hasParam("depth_cameras"))
{
ROS_ERROR("\"depth_cameras\" parameter doesn't exist anymore. It is replaced by \"rgbd_cameras\" with the \"rgbd_image\" input topics. \"subscribe_rgbd\" should be also set to true.");
}
pnh.param("rgbd_cameras", rgbdCameras, rgbdCameras);
if(rgbdCameras <= 0)
{
rgbdCameras = 1;
}
if(rgbdCameras > 4)
{
NODELET_FATAL("Only 4 cameras maximum supported yet.");
}
NODELET_INFO("RGBDOdometry: approx_sync = %s", approxSync?"true":"false");
NODELET_INFO("RGBDOdometry: queue_size = %d", queueSize_);
NODELET_INFO("RGBDOdometry: subscribe_rgbd = %s", subscribeRGBD?"true":"false");
NODELET_INFO("RGBDOdometry: rgbd_cameras = %d", rgbdCameras);
std::string subscribedTopicsMsg;
if(subscribeRGBD)
{
if(rgbdCameras >= 2)
{
rgbd_image1_sub_.subscribe(nh, "rgbd_image0", 1);
rgbd_image2_sub_.subscribe(nh, "rgbd_image1", 1);
if(rgbdCameras >= 3)
{
rgbd_image3_sub_.subscribe(nh, "rgbd_image2", 1);
}
if(rgbdCameras >= 4)
{
rgbd_image4_sub_.subscribe(nh, "rgbd_image3", 1);
}
if(rgbdCameras == 2)
{
if(approxSync)
{
approxSync2_ = new message_filters::Synchronizer<MyApproxSync2Policy>(
MyApproxSync2Policy(queueSize_),
rgbd_image1_sub_,
rgbd_image2_sub_);
approxSync2_->registerCallback(boost::bind(&RGBDOdometry::callbackRGBD2, this, _1, _2));
}
else
{
exactSync2_ = new message_filters::Synchronizer<MyExactSync2Policy>(
MyExactSync2Policy(queueSize_),
rgbd_image1_sub_,
rgbd_image2_sub_);
exactSync2_->registerCallback(boost::bind(&RGBDOdometry::callbackRGBD2, this, _1, _2));
}
subscribedTopicsMsg = uFormat("\n%s subscribed to (%s sync):\n %s,\n %s",
getName().c_str(),
approxSync?"approx":"exact",
rgbd_image1_sub_.getTopic().c_str(),
rgbd_image2_sub_.getTopic().c_str());
}
else if(rgbdCameras == 3)
{
if(approxSync)
{
approxSync3_ = new message_filters::Synchronizer<MyApproxSync3Policy>(
MyApproxSync3Policy(queueSize_),
rgbd_image1_sub_,
rgbd_image2_sub_,
rgbd_image3_sub_);
approxSync3_->registerCallback(boost::bind(&RGBDOdometry::callbackRGBD3, this, _1, _2, _3));
}
else
{
exactSync3_ = new message_filters::Synchronizer<MyExactSync3Policy>(
MyExactSync3Policy(queueSize_),
rgbd_image1_sub_,
rgbd_image2_sub_,
rgbd_image3_sub_);
exactSync3_->registerCallback(boost::bind(&RGBDOdometry::callbackRGBD3, this, _1, _2, _3));
}
subscribedTopicsMsg = uFormat("\n%s subscribed to (%s sync):\n %s,\n %s,\n %s",
getName().c_str(),
approxSync?"approx":"exact",
rgbd_image1_sub_.getTopic().c_str(),
rgbd_image2_sub_.getTopic().c_str(),
rgbd_image3_sub_.getTopic().c_str());
}
else if(rgbdCameras == 4)
{
if(approxSync)
{
approxSync4_ = new message_filters::Synchronizer<MyApproxSync4Policy>(
MyApproxSync4Policy(queueSize_),
rgbd_image1_sub_,
rgbd_image2_sub_,
rgbd_image3_sub_,
rgbd_image4_sub_);
approxSync4_->registerCallback(boost::bind(&RGBDOdometry::callbackRGBD4, this, _1, _2, _3, _4));
}
else
{
exactSync4_ = new message_filters::Synchronizer<MyExactSync4Policy>(
MyExactSync4Policy(queueSize_),
rgbd_image1_sub_,
rgbd_image2_sub_,
rgbd_image3_sub_,
rgbd_image4_sub_);
exactSync4_->registerCallback(boost::bind(&RGBDOdometry::callbackRGBD4, this, _1, _2, _3, _4));
}
subscribedTopicsMsg = uFormat("\n%s subscribed to (%s sync):\n %s,\n %s,\n %s,\n %s",
getName().c_str(),
approxSync?"approx":"exact",
rgbd_image1_sub_.getTopic().c_str(),
rgbd_image2_sub_.getTopic().c_str(),
rgbd_image3_sub_.getTopic().c_str(),
rgbd_image4_sub_.getTopic().c_str());
}
}
else
{
rgbdSub_ = nh.subscribe("rgbd_image", 1, &RGBDOdometry::callbackRGBD, this);
subscribedTopicsMsg =
uFormat("\n%s subscribed to:\n %s",
getName().c_str(),
rgbdSub_.getTopic().c_str());
}
}
else
{
ros::NodeHandle rgb_nh(nh, "rgb");
ros::NodeHandle depth_nh(nh, "depth");
ros::NodeHandle rgb_pnh(pnh, "rgb");
ros::NodeHandle depth_pnh(pnh, "depth");
image_transport::ImageTransport rgb_it(rgb_nh);
image_transport::ImageTransport depth_it(depth_nh);
image_transport::TransportHints hintsRgb("raw", ros::TransportHints(), rgb_pnh);
image_transport::TransportHints hintsDepth("raw", ros::TransportHints(), depth_pnh);
image_mono_sub_.subscribe(rgb_it, rgb_nh.resolveName("image"), 1, hintsRgb);
image_depth_sub_.subscribe(depth_it, depth_nh.resolveName("image"), 1, hintsDepth);
info_sub_.subscribe(rgb_nh, "camera_info", 1);
if(approxSync)
{
approxSync_ = new message_filters::Synchronizer<MyApproxSyncPolicy>(MyApproxSyncPolicy(queueSize_), image_mono_sub_, image_depth_sub_, info_sub_);
approxSync_->registerCallback(boost::bind(&RGBDOdometry::callback, this, _1, _2, _3));
}
else
{
exactSync_ = new message_filters::Synchronizer<MyExactSyncPolicy>(MyExactSyncPolicy(queueSize_), image_mono_sub_, image_depth_sub_, info_sub_);
exactSync_->registerCallback(boost::bind(&RGBDOdometry::callback, this, _1, _2, _3));
}
subscribedTopicsMsg = uFormat("\n%s subscribed to (%s sync):\n %s,\n %s,\n %s",
getName().c_str(),
approxSync?"approx":"exact",
image_mono_sub_.getTopic().c_str(),
image_depth_sub_.getTopic().c_str(),
info_sub_.getTopic().c_str());
}
this->startWarningThread(subscribedTopicsMsg, approxSync);
}
virtual void updateParameters(ParametersMap & parameters)
{
//make sure we are using Reg/Strategy=0
ParametersMap::iterator iter = parameters.find(Parameters::kRegStrategy());
if(iter != parameters.end() && iter->second.compare("0") != 0)
{
ROS_WARN("RGBD odometry works only with \"Reg/Strategy\"=0. Ignoring value %s.", iter->second.c_str());
}
uInsert(parameters, ParametersPair(Parameters::kRegStrategy(), "0"));
int estimationType = Parameters::defaultVisEstimationType();
Parameters::parse(parameters, Parameters::kVisEstimationType(), estimationType);
ros::NodeHandle & pnh = getPrivateNodeHandle();
int rgbdCameras = 1;
bool subscribeRGBD = false;
pnh.param("subscribe_rgbd", subscribeRGBD, subscribeRGBD);
pnh.param("rgbd_cameras", rgbdCameras, rgbdCameras);
if(subscribeRGBD && rgbdCameras> 1 && estimationType>0)
{
NODELET_WARN("Setting \"%s\" parameter to 0 (%d is not supported "
"for multi-cameras) as \"subscribe_rgbd\" is "
"true and \"rgbd_cameras\">1. Set \"%s\" to 0 to suppress this warning.",
Parameters::kVisEstimationType().c_str(),
estimationType,
Parameters::kVisEstimationType().c_str());
uInsert(parameters, ParametersPair(Parameters::kVisEstimationType(), "0"));
}
}
void commonCallback(
const std::vector<cv_bridge::CvImageConstPtr> & rgbImages,
const std::vector<cv_bridge::CvImageConstPtr> & depthImages,
const std::vector<sensor_msgs::CameraInfo>& cameraInfos)
{
ROS_ASSERT(rgbImages.size() > 0 && rgbImages.size() == depthImages.size() && rgbImages.size() == cameraInfos.size());
ros::Time higherStamp;
int imageWidth = rgbImages[0]->image.cols;
int imageHeight = rgbImages[0]->image.rows;
int depthWidth = depthImages[0]->image.cols;
int depthHeight = depthImages[0]->image.rows;
UASSERT_MSG(
imageWidth % depthWidth == 0 && imageHeight % depthHeight == 0 &&
imageWidth/depthWidth == imageHeight/depthHeight,
uFormat("rgb=%dx%d depth=%dx%d", imageWidth, imageHeight, depthWidth, depthHeight).c_str());
int cameraCount = rgbImages.size();
cv::Mat rgb;
cv::Mat depth;
pcl::PointCloud<pcl::PointXYZ> scanCloud;
std::vector<CameraModel> cameraModels;
for(unsigned int i=0; i<rgbImages.size(); ++i)
{
if(!(rgbImages[i]->encoding.compare(sensor_msgs::image_encodings::TYPE_8UC1) ==0 ||
rgbImages[i]->encoding.compare(sensor_msgs::image_encodings::MONO8) ==0 ||
rgbImages[i]->encoding.compare(sensor_msgs::image_encodings::MONO16) ==0 ||
rgbImages[i]->encoding.compare(sensor_msgs::image_encodings::BGR8) == 0 ||
rgbImages[i]->encoding.compare(sensor_msgs::image_encodings::RGB8) == 0 ||
rgbImages[i]->encoding.compare(sensor_msgs::image_encodings::BGRA8) == 0 ||
rgbImages[i]->encoding.compare(sensor_msgs::image_encodings::RGBA8) == 0 ||
rgbImages[i]->encoding.compare(sensor_msgs::image_encodings::BAYER_GRBG8) == 0) ||
!(depthImages[i]->encoding.compare(sensor_msgs::image_encodings::TYPE_16UC1) == 0 ||
depthImages[i]->encoding.compare(sensor_msgs::image_encodings::TYPE_32FC1) == 0 ||
depthImages[i]->encoding.compare(sensor_msgs::image_encodings::MONO16) == 0))
{
NODELET_ERROR("Input type must be image=mono8,mono16,rgb8,bgr8,bgra8,rgba8 and "
"image_depth=32FC1,16UC1,mono16. Current rgb=%s and depth=%s",
rgbImages[i]->encoding.c_str(),
depthImages[i]->encoding.c_str());
return;
}
UASSERT_MSG(rgbImages[i]->image.cols == imageWidth && rgbImages[i]->image.rows == imageHeight,
uFormat("imageWidth=%d vs %d imageHeight=%d vs %d",
imageWidth,
rgbImages[i]->image.cols,
imageHeight,
rgbImages[i]->image.rows).c_str());
UASSERT_MSG(depthImages[i]->image.cols == depthWidth && depthImages[i]->image.rows == depthHeight,
uFormat("depthWidth=%d vs %d depthHeight=%d vs %d",
depthWidth,
depthImages[i]->image.cols,
depthHeight,
depthImages[i]->image.rows).c_str());
ros::Time stamp = rgbImages[i]->header.stamp>depthImages[i]->header.stamp?rgbImages[i]->header.stamp:depthImages[i]->header.stamp;
if(i == 0)
{
higherStamp = stamp;
}
else if(stamp > higherStamp)
{
higherStamp = stamp;
}
Transform localTransform = getTransform(this->frameId(), rgbImages[i]->header.frame_id, stamp);
if(localTransform.isNull())
{
return;
}
cv_bridge::CvImageConstPtr ptrImage = rgbImages[i];
if(rgbImages[i]->encoding.compare(sensor_msgs::image_encodings::TYPE_8UC1) !=0 &&
rgbImages[i]->encoding.compare(sensor_msgs::image_encodings::MONO8) != 0)
{
ptrImage = cv_bridge::cvtColor(rgbImages[i], "mono8");
}
cv_bridge::CvImageConstPtr ptrDepth = depthImages[i];
cv::Mat subDepth = ptrDepth->image;
// initialize
if(rgb.empty())
{
rgb = cv::Mat(imageHeight, imageWidth*cameraCount, ptrImage->image.type());
}
if(depth.empty())
{
depth = cv::Mat(depthHeight, depthWidth*cameraCount, subDepth.type());
}
if(ptrImage->image.type() == rgb.type())
{
ptrImage->image.copyTo(cv::Mat(rgb, cv::Rect(i*imageWidth, 0, imageWidth, imageHeight)));
}
else
{
NODELET_ERROR("Some RGB images are not the same type!");
return;
}
if(subDepth.type() == depth.type())
{
subDepth.copyTo(cv::Mat(depth, cv::Rect(i*depthWidth, 0, depthWidth, depthHeight)));
}
else
{
NODELET_ERROR("Some Depth images are not the same type!");
return;
}
cameraModels.push_back(rtabmap_ros::cameraModelFromROS(cameraInfos[i], localTransform));
}
rtabmap::SensorData data(
rgb,
depth,
cameraModels,
0,
rtabmap_ros::timestampFromROS(higherStamp));
this->processData(data, higherStamp);
}
void callback(
const sensor_msgs::ImageConstPtr& image,
const sensor_msgs::ImageConstPtr& depth,
const sensor_msgs::CameraInfoConstPtr& cameraInfo)
{
callbackCalled();
if(!this->isPaused())
{
std::vector<cv_bridge::CvImageConstPtr> imageMsgs(1);
std::vector<cv_bridge::CvImageConstPtr> depthMsgs(1);
std::vector<sensor_msgs::CameraInfo> infoMsgs;
imageMsgs[0] = cv_bridge::toCvShare(image);
depthMsgs[0] = cv_bridge::toCvShare(depth);
infoMsgs.push_back(*cameraInfo);
this->commonCallback(imageMsgs, depthMsgs, infoMsgs);
}
}
void callbackRGBD(
const rtabmap_ros::RGBDImageConstPtr& image)
{
callbackCalled();
if(!this->isPaused())
{
std::vector<cv_bridge::CvImageConstPtr> imageMsgs(1);
std::vector<cv_bridge::CvImageConstPtr> depthMsgs(1);
std::vector<sensor_msgs::CameraInfo> infoMsgs;
rtabmap_ros::toCvShare(image, imageMsgs[0], depthMsgs[0]);
infoMsgs.push_back(image->rgbCameraInfo);
this->commonCallback(imageMsgs, depthMsgs, infoMsgs);
}
}
void callbackRGBD2(
const rtabmap_ros::RGBDImageConstPtr& image,
const rtabmap_ros::RGBDImageConstPtr& image2)
{
callbackCalled();
if(!this->isPaused())
{
std::vector<cv_bridge::CvImageConstPtr> imageMsgs(2);
std::vector<cv_bridge::CvImageConstPtr> depthMsgs(2);
std::vector<sensor_msgs::CameraInfo> infoMsgs;
rtabmap_ros::toCvShare(image, imageMsgs[0], depthMsgs[0]);
rtabmap_ros::toCvShare(image2, imageMsgs[1], depthMsgs[1]);
infoMsgs.push_back(image->rgbCameraInfo);
infoMsgs.push_back(image2->rgbCameraInfo);
this->commonCallback(imageMsgs, depthMsgs, infoMsgs);
}
}
void callbackRGBD3(
const rtabmap_ros::RGBDImageConstPtr& image,
const rtabmap_ros::RGBDImageConstPtr& image2,
const rtabmap_ros::RGBDImageConstPtr& image3)
{
callbackCalled();
if(!this->isPaused())
{
std::vector<cv_bridge::CvImageConstPtr> imageMsgs(3);
std::vector<cv_bridge::CvImageConstPtr> depthMsgs(3);
std::vector<sensor_msgs::CameraInfo> infoMsgs;
rtabmap_ros::toCvShare(image, imageMsgs[0], depthMsgs[0]);
rtabmap_ros::toCvShare(image2, imageMsgs[1], depthMsgs[1]);
rtabmap_ros::toCvShare(image3, imageMsgs[2], depthMsgs[2]);
infoMsgs.push_back(image->rgbCameraInfo);
infoMsgs.push_back(image2->rgbCameraInfo);
infoMsgs.push_back(image3->rgbCameraInfo);
this->commonCallback(imageMsgs, depthMsgs, infoMsgs);
}
}
void callbackRGBD4(
const rtabmap_ros::RGBDImageConstPtr& image,
const rtabmap_ros::RGBDImageConstPtr& image2,
const rtabmap_ros::RGBDImageConstPtr& image3,
const rtabmap_ros::RGBDImageConstPtr& image4)
{
callbackCalled();
if(!this->isPaused())
{
std::vector<cv_bridge::CvImageConstPtr> imageMsgs(4);
std::vector<cv_bridge::CvImageConstPtr> depthMsgs(4);
std::vector<sensor_msgs::CameraInfo> infoMsgs;
rtabmap_ros::toCvShare(image, imageMsgs[0], depthMsgs[0]);
rtabmap_ros::toCvShare(image2, imageMsgs[1], depthMsgs[1]);
rtabmap_ros::toCvShare(image3, imageMsgs[2], depthMsgs[2]);
rtabmap_ros::toCvShare(image4, imageMsgs[3], depthMsgs[3]);
infoMsgs.push_back(image->rgbCameraInfo);
infoMsgs.push_back(image2->rgbCameraInfo);
infoMsgs.push_back(image3->rgbCameraInfo);
infoMsgs.push_back(image4->rgbCameraInfo);
this->commonCallback(imageMsgs, depthMsgs, infoMsgs);
}
}
protected:
virtual void flushCallbacks()
{
// flush callbacks
if(approxSync_)
{
delete approxSync_;
approxSync_ = new message_filters::Synchronizer<MyApproxSyncPolicy>(MyApproxSyncPolicy(queueSize_), image_mono_sub_, image_depth_sub_, info_sub_);
approxSync_->registerCallback(boost::bind(&RGBDOdometry::callback, this, _1, _2, _3));
}
if(exactSync_)
{
delete exactSync_;
exactSync_ = new message_filters::Synchronizer<MyExactSyncPolicy>(MyExactSyncPolicy(queueSize_), image_mono_sub_, image_depth_sub_, info_sub_);
exactSync_->registerCallback(boost::bind(&RGBDOdometry::callback, this, _1, _2, _3));
}
if(approxSync2_)
{
delete approxSync2_;
approxSync2_ = new message_filters::Synchronizer<MyApproxSync2Policy>(
MyApproxSync2Policy(queueSize_),
rgbd_image1_sub_,
rgbd_image2_sub_);
approxSync2_->registerCallback(boost::bind(&RGBDOdometry::callbackRGBD2, this, _1, _2));
}
if(exactSync2_)
{
delete exactSync2_;
exactSync2_ = new message_filters::Synchronizer<MyExactSync2Policy>(
MyExactSync2Policy(queueSize_),
rgbd_image1_sub_,
rgbd_image2_sub_);
exactSync2_->registerCallback(boost::bind(&RGBDOdometry::callbackRGBD2, this, _1, _2));
}
if(approxSync3_)
{
delete approxSync3_;
approxSync3_ = new message_filters::Synchronizer<MyApproxSync3Policy>(
MyApproxSync3Policy(queueSize_),
rgbd_image1_sub_,
rgbd_image2_sub_,
rgbd_image3_sub_);
approxSync3_->registerCallback(boost::bind(&RGBDOdometry::callbackRGBD3, this, _1, _2, _3));
}
if(exactSync3_)
{
delete exactSync3_;
exactSync3_ = new message_filters::Synchronizer<MyExactSync3Policy>(
MyExactSync3Policy(queueSize_),
rgbd_image1_sub_,
rgbd_image2_sub_,
rgbd_image3_sub_);
exactSync3_->registerCallback(boost::bind(&RGBDOdometry::callbackRGBD3, this, _1, _2, _3));
}
if(approxSync4_)
{
delete approxSync4_;
approxSync4_ = new message_filters::Synchronizer<MyApproxSync4Policy>(
MyApproxSync4Policy(queueSize_),
rgbd_image1_sub_,
rgbd_image2_sub_,
rgbd_image3_sub_,
rgbd_image4_sub_);
approxSync4_->registerCallback(boost::bind(&RGBDOdometry::callbackRGBD4, this, _1, _2, _3, _4));
}
if(exactSync4_)
{
delete exactSync4_;
exactSync4_ = new message_filters::Synchronizer<MyExactSync4Policy>(
MyExactSync4Policy(queueSize_),
rgbd_image1_sub_,
rgbd_image2_sub_,
rgbd_image3_sub_,
rgbd_image4_sub_);
exactSync4_->registerCallback(boost::bind(&RGBDOdometry::callbackRGBD4, this, _1, _2, _3, _4));
}
}
private:
image_transport::SubscriberFilter image_mono_sub_;
image_transport::SubscriberFilter image_depth_sub_;
message_filters::Subscriber<sensor_msgs::CameraInfo> info_sub_;
ros::Subscriber rgbdSub_;
message_filters::Subscriber<rtabmap_ros::RGBDImage> rgbd_image1_sub_;
message_filters::Subscriber<rtabmap_ros::RGBDImage> rgbd_image2_sub_;
message_filters::Subscriber<rtabmap_ros::RGBDImage> rgbd_image3_sub_;
message_filters::Subscriber<rtabmap_ros::RGBDImage> rgbd_image4_sub_;
typedef message_filters::sync_policies::ApproximateTime<sensor_msgs::Image, sensor_msgs::Image, sensor_msgs::CameraInfo> MyApproxSyncPolicy;
message_filters::Synchronizer<MyApproxSyncPolicy> * approxSync_;
typedef message_filters::sync_policies::ExactTime<sensor_msgs::Image, sensor_msgs::Image, sensor_msgs::CameraInfo> MyExactSyncPolicy;
message_filters::Synchronizer<MyExactSyncPolicy> * exactSync_;
typedef message_filters::sync_policies::ApproximateTime<rtabmap_ros::RGBDImage, rtabmap_ros::RGBDImage> MyApproxSync2Policy;
message_filters::Synchronizer<MyApproxSync2Policy> * approxSync2_;
typedef message_filters::sync_policies::ExactTime<rtabmap_ros::RGBDImage, rtabmap_ros::RGBDImage> MyExactSync2Policy;
message_filters::Synchronizer<MyExactSync2Policy> * exactSync2_;
typedef message_filters::sync_policies::ApproximateTime<rtabmap_ros::RGBDImage, rtabmap_ros::RGBDImage, rtabmap_ros::RGBDImage> MyApproxSync3Policy;
message_filters::Synchronizer<MyApproxSync3Policy> * approxSync3_;
typedef message_filters::sync_policies::ExactTime<rtabmap_ros::RGBDImage, rtabmap_ros::RGBDImage, rtabmap_ros::RGBDImage> MyExactSync3Policy;
message_filters::Synchronizer<MyExactSync3Policy> * exactSync3_;
typedef message_filters::sync_policies::ApproximateTime<rtabmap_ros::RGBDImage, rtabmap_ros::RGBDImage, rtabmap_ros::RGBDImage, rtabmap_ros::RGBDImage> MyApproxSync4Policy;
message_filters::Synchronizer<MyApproxSync4Policy> * approxSync4_;
typedef message_filters::sync_policies::ExactTime<rtabmap_ros::RGBDImage, rtabmap_ros::RGBDImage, rtabmap_ros::RGBDImage, rtabmap_ros::RGBDImage> MyExactSync4Policy;
message_filters::Synchronizer<MyExactSync4Policy> * exactSync4_;
int queueSize_;
};
PLUGINLIB_EXPORT_CLASS(rtabmap_ros::RGBDOdometry, nodelet::Nodelet);
}
|
// Copyright (c) 2020 Jason Waataja
// 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 LIBJLINKDB_QUERY_OR_COLLECTION_HH_
#define LIBJLINKDB_QUERY_OR_COLLECTION_HH_
#include <memory>
#include <vector>
#include "link_entry.hh"
#include "query/query.hh"
namespace libjlinkdb {
namespace query {
// A query with a collection of subqueries that matches if and only if at
// least one query in the collection matches.
class OrCollection : public Query {
public:
// Constructs an empty collection.
OrCollection() = default;
// Constructs a collection containing all queries in the range [first,
// last). The iterator should point to type shared_ptr<Query>.
template <typename InputIterator>
OrCollection(InputIterator first, InputIterator last);
// Constructs a collection containing all queries listed in queries.
explicit OrCollection(const std::vector<std::shared_ptr<Query>>& queries);
// Returns true if and only if every query in the collection matches
// entry.
bool matches(const LinkEntry& entry) const override;
private:
std::vector<std::shared_ptr<Query>> queries_;
};
template <typename InputIterator>
OrCollection::OrCollection(InputIterator first, InputIterator last)
: queries_{first, last}
{
}
} // namespace query
} // namespace libjlinkdb
#endif // LIBJLINKDB_QUERY_OR_COLLECTION_HH_
|
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2005, 2006
// University of Rochester
// Department of Computer Science
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the University of Rochester nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <iostream>
using std::cout;
using std::endl;
#include "RandomGraphList.h"
using namespace stm;
using namespace bench;
// try to find an entry in /this/ whose value is nval
sh_ptr<GNode>
GNodeList::lookup(int nval) const
{
// open the head of the list (which may already be open)
// NB: first entry is a sentinel, so we can skip it
rd_ptr<LNode> list_node(getList());
list_node = list_node->get_next(list_node.v());
// This is outside the loop so that we don't keep initializing
// the pointer inside the loop.
rd_ptr<GNode> node_contents;
// linear search through the list
while (list_node != NULL)
{
// open the current node and look at its value
node_contents = list_node->get_node(list_node.v());
if (node_contents->get_val(node_contents.v()) > nval)
{
return sh_ptr<GNode>(); // nobody in list with val==nval
}
if (node_contents->get_val(node_contents.v()) == nval)
{
return node_contents;
}
list_node = list_node->get_next(list_node.v());
}
return sh_ptr<GNode>();
}
// this inserts "n" into the list, but does not do any linking
bool
GNodeList::insert(const sh_ptr<GNode>& add_node) const
{
// first get the value of the node being added
rd_ptr<GNode> node(add_node);
int nval = node->get_val(node.v());
// now traverse the list to find where to place the add_node
rd_ptr<LNode> curr_node(getList());
rd_ptr<LNode> next_node(curr_node->get_next(curr_node.v()));
rd_ptr<GNode> next_content;
while (next_node != NULL)
{
next_content = next_node->get_node(next_node.v());
if (next_content->get_val(next_content.v()) > nval)
{
break;
}
else if (next_content->get_val(next_content.v()) == nval)
{
return false;
}
curr_node = next_node;
next_node = next_node->get_next(next_node.v());
}
// now insert a new LNode between curr_node and next_node
wr_ptr<LNode> insert_point(curr_node);
insert_point->set_next(sh_ptr<LNode>(new LNode(add_node, next_node)));
return true;
}
// this code is responsible for finding the entry in the list whose value is
// nval, and removing that entry from the list. we return the entry we
// removed, in case it is needed for more work (most notably, for disconnecting
// the removed node from its peers)
sh_ptr<GNode>
GNodeList::remove(int nval) const
{
// first go through the list and try to find a GNode with val==nval
rd_ptr<LNode> curr_node(getList());
rd_ptr<LNode> next_node(curr_node->get_next(curr_node.v()));
rd_ptr<GNode> next_content;
while (next_node != NULL)
{
next_content = next_node->get_node(next_node.v());
if (next_content->get_val(next_content.v()) > nval)
{
return sh_ptr<GNode>();
}
else if (next_content->get_val(next_content.v()) == nval)
{
break;
}
curr_node = next_node;
next_node = next_node->get_next(next_node.v());
}
// if we get here and we have a next node, then we need to remove next_node
// from the linked list.
if (next_node != NULL) {
wr_ptr<LNode> curr_w(curr_node);
curr_w->set_next(next_node->get_next(next_node.v()));
tx_delete(next_node);
return next_content;
}
return sh_ptr<GNode>();
}
// this is supposed to make /this/ have a neighbor entry of n, and n have a
// neighbor entry of /this/
void
GNode::insert(const sh_ptr<GNode>& this_sh, const sh_ptr<GNode>& new_peer)
{
m_neighbors.insert(new_peer);
rd_ptr<GNode> rnp(new_peer);
rnp->m_neighbors.insert(this_sh);
}
// this method is responsible for going through /this/.neighbors and for each
// entry E, calling E.neighbors.remove(this.nval)
void
GNode::disconnect(wr_ptr<GNode>& this_w)
{
// skip the first node of the neighbor list since it is a sentinel
rd_ptr<LNode> curr_node(m_neighbors.getList());
curr_node = curr_node->get_next(curr_node.v());
// Used to avoid temporary generation in the loop
rd_ptr<GNode> neighbors;
// traverse the list
while (curr_node != NULL)
{
// open the payload, get its neighbor list, and call remove on that
neighbors = curr_node->get_node(curr_node.v());
neighbors->m_neighbors.remove(get_val(this_w.v()));
curr_node = curr_node->get_next(curr_node.v());
}
}
// This is the entry point for an insert tx from the benchmark harness
void
RandomGraph::insert(unsigned int* seed)
{
// get the rand vals outside of the tx, so that the tx doesn't succeed by
// retrying until it gets a lucky set of values
int val = rand_r(seed) % maxNodes;
int linkups[CONNECTIONS_PER_NODE];
for (int i = 0; i < CONNECTIONS_PER_NODE; i++)
// select a random node to connect to
linkups[i] = rand_r(seed) % maxNodes;
BEGIN_TRANSACTION;
// create the node we'll try to insert
sh_ptr<GNode> new_node = sh_ptr<GNode>(new GNode(val));
// now try to insert the new node into the RandomGraphList
if (nodes.insert(new_node))
{
// Used in the loop
sh_ptr<GNode> peer;
wr_ptr<GNode> new_content(new_node);
// if the insert succeeded, then try to link this guy to some peers
for (int i = 0; i < CONNECTIONS_PER_NODE; i++)
{
if (linkups[i] == val)
{
continue; // don't link to self
}
// for each neighbor, if it exists, connect to it
if ((peer = nodes.lookup(linkups[i])) != NULL)
{
new_content->insert(new_node, peer);
}
}
}
else
{
// the value is already in the graph, so quit this tx
tx_delete(new_node);
}
END_TRANSACTION;
}
// This is the entry point for a remove tx from the benchmark harness
void RandomGraph::remove(unsigned int* seed)
{
int val = rand_r(seed) % maxNodes;
BEGIN_TRANSACTION;
// first remove the node from the main list of nodes
sh_ptr<GNode> remove_node = nodes.remove(val);
// now disconnect the node from its peers
if (remove_node != NULL)
{
wr_ptr<GNode> w(remove_node);
w->disconnect(w);
}
END_TRANSACTION;
}
// sanity check of the RandomGraph structure
bool
RandomGraph::isSane() const
{
bool sane = false;
BEGIN_TRANSACTION;
sane = true; // assume we'll succeed
// outer loop: make sure that the main list of nodes is sorted
int last_val = -1;
rd_ptr<LNode> curr_node(nodes.getList());
rd_ptr<GNode> curr_content;
rd_ptr<LNode> nbor_node;
rd_ptr<GNode> nbor_content;
while (curr_node != NULL)
{
if (curr_node->get_node(curr_node.v()) == NULL)
{
// move to the next node in the outer loop
curr_node = curr_node->get_next(curr_node.v());
continue;
}
// check that the main list is sorted
curr_content = curr_node->get_node(curr_node.v());
if (curr_content->get_val(curr_content.v()) < last_val)
{
sane = false;
break;
}
last_val = curr_content->get_val(curr_content.v());
// drill down on curr_content to make sure its neighbors are sorted,
// and to make sure that each neighbor is a bidirectional link
int last_nbor = -1;
nbor_node = curr_content->m_neighbors.getList();
while (nbor_node != NULL)
{
if (nbor_node->get_node(nbor_node.v()) == NULL)
{
nbor_node = nbor_node->get_next(nbor_node.v());
continue;
}
// make sure the neighbors are sorted:
nbor_content = nbor_node->get_node(nbor_node.v());
if (nbor_content->get_val(nbor_content.v()) < last_nbor)
{
sane = false;
break;
}
last_nbor = nbor_content->get_val(nbor_content.v());
// Make sure the neighbor is in the main list
// Implicit conversion here
if (nodes.lookup(last_nbor) != nbor_content)
{
sane = false;
break;
}
// Make sure the neighbor links back to this node
// Implicit conversion here
if (nbor_content->m_neighbors.lookup(curr_content->get_val(curr_content.v()))
!= curr_content)
{
sane = false;
break;
}
// This neighbor passed. Move to the next one
nbor_node = nbor_node->get_next(nbor_node.v());
}
// the break statements in the inner while () only get us to here; we
// need to break a second time if the data structure isn't sane
if (!sane)
break;
// move to the next node in the outer loop
curr_node = curr_node->get_next(curr_node.v());
}
END_TRANSACTION;
return sane;
}
// print the RandomGraph structure
void
RandomGraph::print() const
{
BEGIN_TRANSACTION;
cout << "graph:" << endl;
rd_ptr<LNode> curr_node(nodes.getList());
rd_ptr<GNode> curr_content;
rd_ptr<LNode> nbor_node;
rd_ptr<GNode> nbor_content;
// outer loop: go through all nodes in the graph
while (curr_node != NULL)
{
if (curr_node->get_node(curr_node.v()) == NULL)
{
// move to the next node in the outer loop
curr_node = curr_node->get_next(curr_node.v());
continue;
}
// print this node's value
curr_content = curr_node->get_node(curr_node.v());
cout << " node " << curr_content->get_val(curr_content.v());
// print the neighbor list
nbor_node = curr_content->m_neighbors.getList();
while (nbor_node != NULL)
{
if (nbor_node->get_node(nbor_node.v()) == NULL)
{
nbor_node = nbor_node->get_next(nbor_node.v());
continue;
}
// print the neighbor
nbor_content = nbor_node->get_node(nbor_node.v());
cout << "::" << nbor_content->get_val(nbor_content.v());
nbor_node = nbor_node->get_next(nbor_node.v());
}
// move to the next node in the outer loop
curr_node = curr_node->get_next(curr_node.v());
cout << endl;
}
END_TRANSACTION;
}
|
#include "services/network/HttpClientImpl.hpp"
#include "infra/stream/CountingOutputStream.hpp"
#include "infra/stream/StringInputStream.hpp"
namespace services
{
HttpClientImpl::HttpClientImpl(infra::BoundedConstString hostname)
: hostname(hostname)
, bodyReaderAccess(infra::emptyFunction)
, sendingState(infra::InPlaceType<SendingStateRequest>(), *this)
, nextState(infra::InPlaceType<SendingStateRequest>(), *this)
{}
void HttpClientImpl::Get(infra::BoundedConstString requestTarget, HttpHeaders headers)
{
ExecuteRequest(HttpVerb::get, requestTarget, headers);
}
void HttpClientImpl::Head(infra::BoundedConstString requestTarget, HttpHeaders headers)
{
ExecuteRequest(HttpVerb::head, requestTarget, headers);
}
void HttpClientImpl::Connect(infra::BoundedConstString requestTarget, HttpHeaders headers)
{
ExecuteRequest(HttpVerb::connect, requestTarget, headers);
}
void HttpClientImpl::Options(infra::BoundedConstString requestTarget, HttpHeaders headers)
{
ExecuteRequest(HttpVerb::options, requestTarget, headers);
}
void HttpClientImpl::Post(infra::BoundedConstString requestTarget, infra::BoundedConstString content, HttpHeaders headers)
{
ExecuteRequestWithContent(HttpVerb::post, requestTarget, content, headers);
}
void HttpClientImpl::Post(infra::BoundedConstString requestTarget, std::size_t contentSize, HttpHeaders headers)
{
ExecuteRequestWithContent(HttpVerb::post, requestTarget, contentSize, headers);
}
void HttpClientImpl::Post(infra::BoundedConstString requestTarget, HttpHeaders headers)
{
ExecuteRequestWithContent(HttpVerb::post, requestTarget, headers);
}
void HttpClientImpl::Put(infra::BoundedConstString requestTarget, infra::BoundedConstString content, HttpHeaders headers)
{
ExecuteRequestWithContent(HttpVerb::put, requestTarget, content, headers);
}
void HttpClientImpl::Put(infra::BoundedConstString requestTarget, std::size_t contentSize, HttpHeaders headers)
{
ExecuteRequestWithContent(HttpVerb::put, requestTarget, contentSize, headers);
}
void HttpClientImpl::Put(infra::BoundedConstString requestTarget, HttpHeaders headers)
{
ExecuteRequestWithContent(HttpVerb::put, requestTarget, headers);
}
void HttpClientImpl::Patch(infra::BoundedConstString requestTarget, infra::BoundedConstString content, HttpHeaders headers)
{
ExecuteRequestWithContent(HttpVerb::patch, requestTarget, content, headers);
}
void HttpClientImpl::Patch(infra::BoundedConstString requestTarget, HttpHeaders headers)
{
ExecuteRequestWithContent(HttpVerb::patch, requestTarget, headers);
}
void HttpClientImpl::Delete(infra::BoundedConstString requestTarget, infra::BoundedConstString content, HttpHeaders headers)
{
ExecuteRequestWithContent(HttpVerb::delete_, requestTarget, content, headers);
}
void HttpClientImpl::AckReceived()
{
ConnectionObserver::Subject().AckReceived();
}
void HttpClientImpl::Close()
{
ConnectionObserver::Subject().CloseAndDestroy();
}
Connection& HttpClientImpl::GetConnection()
{
return ConnectionObserver::Subject();
}
void HttpClientImpl::Attached()
{
infra::WeakPtr<HttpClientImpl> self = infra::StaticPointerCast<HttpClientImpl>(services::ConnectionObserver::Subject().ObserverPtr());
bodyReaderAccess.SetAction([self]()
{
if (auto sharedSelf = self.lock())
sharedSelf->BodyReaderDestroyed();
});
}
void HttpClientImpl::SendStreamAvailable(infra::SharedPtr<infra::StreamWriter>&& writer)
{
sendingState->SendStreamAvailable(std::move(writer));
}
void HttpClientImpl::DataReceived()
{
if (bodyReader != infra::none)
Observer().BodyAvailable(infra::MakeContainedSharedObject(bodyReader->countingReader, bodyReaderAccess.MakeShared(bodyReader)));
else
{
if (response)
HandleData();
else
AbortAndDestroy();
}
}
void HttpClientImpl::Detaching()
{
bodyReaderAccess.SetAction(infra::emptyFunction);
if (HttpClient::IsAttached())
HttpClient::Detach();
}
void HttpClientImpl::StatusAvailable(HttpStatusCode code, infra::BoundedConstString statusLine)
{
statusCode = code;
Observer().StatusAvailable(code);
}
void HttpClientImpl::HeaderAvailable(HttpHeader header)
{
if (infra::CaseInsensitiveCompare(header.Field(), "Content-Length"))
{
contentLength = 0;
infra::StringInputStream contentLengthStream(header.Value());
contentLengthStream >> *contentLength;
}
else
Observer().HeaderAvailable(header);
}
void HttpClientImpl::ExpectResponse()
{
response.Emplace(static_cast<HttpHeaderParserObserver&>(*this));
}
void HttpClientImpl::HandleData()
{
if (!response->Done())
{
auto reader = ConnectionObserver::Subject().ReceiveStream();
infra::WeakPtr<services::ConnectionObserver> self = services::ConnectionObserver::Subject().ObserverPtr();
response->DataReceived(*reader);
if (!self.lock()) // DataReceived may close the connection
return;
ConnectionObserver::Subject().AckReceived();
if (response->Done())
{
if (contentLength == infra::none && (statusCode == HttpStatusCode::Continue
|| statusCode == HttpStatusCode::SwitchingProtocols
|| statusCode == HttpStatusCode::NoContent
|| statusCode == HttpStatusCode::NotModified))
contentLength = 0;
}
}
if (response->Done())
{
if (!response->Error() && contentLength != infra::none)
BodyReceived();
else
AbortAndDestroy();
}
}
void HttpClientImpl::BodyReceived()
{
if (contentLength == 0)
BodyComplete();
else
{
bodyReader.Emplace(ConnectionObserver::Subject().ReceiveStream(), *contentLength);
Observer().BodyAvailable(infra::MakeContainedSharedObject(bodyReader->countingReader, bodyReaderAccess.MakeShared(bodyReader)));
}
}
void HttpClientImpl::BodyReaderDestroyed()
{
ConnectionObserver::Subject().AckReceived();
*contentLength -= bodyReader->countingReader.TotalRead();
bodyReader = infra::none;
if (*contentLength == 0)
BodyComplete();
}
void HttpClientImpl::BodyComplete()
{
contentLength = infra::none;
response = infra::none;
Observer().BodyComplete();
}
void HttpClientImpl::ExecuteRequest(HttpVerb verb, infra::BoundedConstString requestTarget, const HttpHeaders headers)
{
request.Emplace(verb, hostname, requestTarget, headers);
ConnectionObserver::Subject().RequestSendStream(request->Size());
}
void HttpClientImpl::ExecuteRequestWithContent(HttpVerb verb, infra::BoundedConstString requestTarget, infra::BoundedConstString content, const HttpHeaders headers)
{
request.Emplace(verb, hostname, requestTarget, content, headers);
ConnectionObserver::Subject().RequestSendStream(request->Size());
}
void HttpClientImpl::ExecuteRequestWithContent(HttpVerb verb, infra::BoundedConstString requestTarget, std::size_t contentSize, const HttpHeaders headers)
{
request.Emplace(verb, hostname, requestTarget, contentSize, headers);
nextState.Emplace<SendingStateForwardSendStream>(*this, contentSize);
ConnectionObserver::Subject().RequestSendStream(request->Size());
}
void HttpClientImpl::ExecuteRequestWithContent(HttpVerb verb, infra::BoundedConstString requestTarget, const HttpHeaders headers)
{
auto contentSize = ReadContentSizeFromObserver();
request.Emplace(verb, hostname, requestTarget, contentSize, headers);
nextState.Emplace<SendingStateForwardFillContent>(*this, contentSize);
ConnectionObserver::Subject().RequestSendStream(request->Size());
}
uint32_t HttpClientImpl::ReadContentSizeFromObserver() const
{
infra::DataOutputStream::WithWriter<infra::CountingStreamWriter> stream;
Observer().FillContent(stream.Writer());
return stream.Writer().Processed();
}
void HttpClientImpl::AbortAndDestroy()
{
ConnectionObserver::Subject().AbortAndDestroy();
}
HttpClientImpl::BodyReader::BodyReader(const infra::SharedPtr<infra::StreamReaderWithRewinding>& reader, uint32_t contentLength)
: reader(reader)
, limitedReader(*reader, contentLength)
{}
HttpClientImpl::SendingState::SendingState(HttpClientImpl& client)
: client(client)
{}
void HttpClientImpl::SendingState::NextState()
{
auto& client = this->client;
client.sendingState = client.nextState;
client.nextState.Emplace<SendingStateRequest>(client);
client.sendingState->Activate();
}
HttpClientImpl::SendingStateRequest::SendingStateRequest(HttpClientImpl& client)
: SendingState(client)
{}
void HttpClientImpl::SendingStateRequest::SendStreamAvailable(infra::SharedPtr<infra::StreamWriter>&& writer)
{
infra::TextOutputStream::WithErrorPolicy stream(*writer);
client.request->Write(stream);
client.request = infra::none;
writer = nullptr;
NextState();
}
void HttpClientImpl::SendingStateRequest::Activate()
{
client.ExpectResponse();
}
HttpClientImpl::SendingStateForwardSendStream::SendingStateForwardSendStream(const SendingStateForwardSendStream& other)
: SendingState(other)
, contentSize(other.contentSize)
{}
HttpClientImpl::SendingStateForwardSendStream::SendingStateForwardSendStream(HttpClientImpl& client, std::size_t contentSize)
: SendingState(client)
, contentSize(contentSize)
{}
void HttpClientImpl::SendingStateForwardSendStream::Activate()
{
if (contentSize != 0)
client.ConnectionObserver::Subject().RequestSendStream(std::min(contentSize, client.ConnectionObserver::Subject().MaxSendStreamSize()));
else
NextState();
}
void HttpClientImpl::SendingStateForwardSendStream::SendStreamAvailable(infra::SharedPtr<infra::StreamWriter>&& writer)
{
forwardStreamPtr = std::move(writer);
auto available = forwardStreamPtr->Available();
forwardStreamAccess.SetAction([this, available]()
{
contentSize -= available - forwardStreamPtr->Available();
forwardStreamPtr = nullptr;
Activate();
});
client.Observer().SendStreamAvailable(forwardStreamAccess.MakeShared(*forwardStreamPtr));
}
HttpClientImpl::SendingStateForwardFillContent::SendingStateForwardFillContent(HttpClientImpl& client, std::size_t contentSize)
: SendingState(client)
, contentSize(contentSize)
{}
void HttpClientImpl::SendingStateForwardFillContent::Activate()
{
if (contentSize != 0)
client.ConnectionObserver::Subject().RequestSendStream(std::min(contentSize, client.ConnectionObserver::Subject().MaxSendStreamSize()));
else
NextState();
}
void HttpClientImpl::SendingStateForwardFillContent::SendStreamAvailable(infra::SharedPtr<infra::StreamWriter>&& writer)
{
WindowWriter windowWriter(*writer, processed, writer->Available());
client.Observer().FillContent(windowWriter);
contentSize -= windowWriter.Processed();
processed += windowWriter.Processed();
writer = nullptr;
Activate();
}
HttpClientImpl::SendingStateForwardFillContent::WindowWriter::WindowWriter(infra::StreamWriter& writer, std::size_t start, std::size_t limit)
: writer(writer)
, start(start)
, limit(limit)
{}
std::size_t HttpClientImpl::SendingStateForwardFillContent::WindowWriter::Processed() const
{
return processed;
}
void HttpClientImpl::SendingStateForwardFillContent::WindowWriter::Insert(infra::ConstByteRange range, infra::StreamErrorPolicy& errorPolicy)
{
auto discard = std::min(range.size(), start);
range = infra::Head(infra::DiscardHead(range, discard), limit);
start -= discard;
if (!range.empty())
{
writer.Insert(range, errorPolicy);
processed += range.size();
}
}
std::size_t HttpClientImpl::SendingStateForwardFillContent::WindowWriter::Available() const
{
return std::numeric_limits<std::size_t>::max();
}
}
|
/*
FLAGS:
TINGE_PRINT_OFF disables print function
TINGE_ERR_OFF disables err function
TINGE_LOG_OFF disables log function
TINGE_PLAIN disables all styles and colours
*/
#pragma once
#ifndef TINGE_HPP
#define TINGE_HPP
#include <iostream>
#include <iomanip>
#include <sstream>
#include <utility>
#include <string>
// Styles and colours.
namespace tinge {
// Styles.
#ifndef TINGE_PLAIN
constexpr auto bold = "\033[1m";
constexpr auto reverse = "\033[7m";
#else
constexpr auto bold = "";
constexpr auto reverse = "";
#endif
// Reset colours and style.
constexpr auto reset = "\033[0;49;39m";
constexpr auto reset_colour = "\033[49;39m";
constexpr auto reset_style = "\033[0m";
// Colours.
#ifndef TINGE_PLAIN
// Add ANSI escape sequences for colours to a string.
#define NEW_COLOUR_MAKER(name, colour) \
template <typename... Ts> auto make_##name(Ts&&... args) { \
std::stringstream ss; \
((ss << colour << args << tinge::reset), ...); \
return ss.str(); \
}
namespace fg {
constexpr auto grey = "\033[38m";
constexpr auto white = "\033[37m";
constexpr auto cyan = "\033[36m";
constexpr auto magenta = "\033[35m";
constexpr auto blue = "\033[34m";
constexpr auto yellow = "\033[33m";
constexpr auto green = "\033[32m";
constexpr auto red = "\033[31m";
constexpr auto black = "\033[30m";
NEW_COLOUR_MAKER(grey, tinge::fg::grey)
NEW_COLOUR_MAKER(white, tinge::fg::white)
NEW_COLOUR_MAKER(cyan, tinge::fg::cyan)
NEW_COLOUR_MAKER(magenta, tinge::fg::magenta)
NEW_COLOUR_MAKER(blue, tinge::fg::blue)
NEW_COLOUR_MAKER(yellow, tinge::fg::yellow)
NEW_COLOUR_MAKER(green, tinge::fg::green)
NEW_COLOUR_MAKER(red, tinge::fg::red)
NEW_COLOUR_MAKER(black, tinge::fg::black)
namespace bright {
constexpr auto grey = "\033[98m";
constexpr auto white = "\033[97m";
constexpr auto cyan = "\033[96m";
constexpr auto magenta = "\033[95m";
constexpr auto blue = "\033[94m";
constexpr auto yellow = "\033[93m";
constexpr auto green = "\033[92m";
constexpr auto red = "\033[91m";
constexpr auto black = "\033[90m";
NEW_COLOUR_MAKER(grey, tinge::fg::bright::grey)
NEW_COLOUR_MAKER(white, tinge::fg::bright::white)
NEW_COLOUR_MAKER(cyan, tinge::fg::bright::cyan)
NEW_COLOUR_MAKER(magenta, tinge::fg::bright::magenta)
NEW_COLOUR_MAKER(blue, tinge::fg::bright::blue)
NEW_COLOUR_MAKER(yellow, tinge::fg::bright::yellow)
NEW_COLOUR_MAKER(green, tinge::fg::bright::green)
NEW_COLOUR_MAKER(red, tinge::fg::bright::red)
NEW_COLOUR_MAKER(black, tinge::fg::bright::black)
}
namespace dim {
constexpr auto grey = "\033[2;98m";
constexpr auto white = "\033[2;97m";
constexpr auto cyan = "\033[2;96m";
constexpr auto magenta = "\033[2;95m";
constexpr auto blue = "\033[2;94m";
constexpr auto yellow = "\033[2;93m";
constexpr auto green = "\033[2;92m";
constexpr auto red = "\033[2;91m";
constexpr auto black = "\033[2;90m";
NEW_COLOUR_MAKER(grey, tinge::fg::dim::grey)
NEW_COLOUR_MAKER(white, tinge::fg::dim::white)
NEW_COLOUR_MAKER(cyan, tinge::fg::dim::cyan)
NEW_COLOUR_MAKER(magenta, tinge::fg::dim::magenta)
NEW_COLOUR_MAKER(blue, tinge::fg::dim::blue)
NEW_COLOUR_MAKER(yellow, tinge::fg::dim::yellow)
NEW_COLOUR_MAKER(green, tinge::fg::dim::green)
NEW_COLOUR_MAKER(red, tinge::fg::dim::red)
NEW_COLOUR_MAKER(black, tinge::fg::dim::black)
}
}
namespace bg {
constexpr auto reset = "\033[49m";
constexpr auto grey = "\033[48m";
constexpr auto white = "\033[47m";
constexpr auto cyan = "\033[46m";
constexpr auto magenta = "\033[45m";
constexpr auto blue = "\033[44m";
constexpr auto yellow = "\033[43m";
constexpr auto green = "\033[42m";
constexpr auto red = "\033[41m";
constexpr auto black = "\033[40m";
NEW_COLOUR_MAKER(grey, tinge::bg::grey)
NEW_COLOUR_MAKER(white, tinge::bg::white)
NEW_COLOUR_MAKER(cyan, tinge::bg::cyan)
NEW_COLOUR_MAKER(magenta, tinge::bg::magenta)
NEW_COLOUR_MAKER(blue, tinge::bg::blue)
NEW_COLOUR_MAKER(yellow, tinge::bg::yellow)
NEW_COLOUR_MAKER(green, tinge::bg::green)
NEW_COLOUR_MAKER(red, tinge::bg::red)
NEW_COLOUR_MAKER(black, tinge::bg::black)
namespace bright {
constexpr auto grey = "\033[108m";
constexpr auto white = "\033[107m";
constexpr auto cyan = "\033[106m";
constexpr auto magenta = "\033[105m";
constexpr auto blue = "\033[104m";
constexpr auto yellow = "\033[103m";
constexpr auto green = "\033[102m";
constexpr auto red = "\033[101m";
constexpr auto black = "\033[100m";
NEW_COLOUR_MAKER(grey, tinge::bg::bright::grey)
NEW_COLOUR_MAKER(white, tinge::bg::bright::white)
NEW_COLOUR_MAKER(cyan, tinge::bg::bright::cyan)
NEW_COLOUR_MAKER(magenta, tinge::bg::bright::magenta)
NEW_COLOUR_MAKER(blue, tinge::bg::bright::blue)
NEW_COLOUR_MAKER(yellow, tinge::bg::bright::yellow)
NEW_COLOUR_MAKER(green, tinge::bg::bright::green)
NEW_COLOUR_MAKER(red, tinge::bg::bright::red)
NEW_COLOUR_MAKER(black, tinge::bg::bright::black)
}
}
#else
// Add ANSI escape sequences for colours to a string.
#define NEW_COLOUR_MAKER(name, colour) \
template <typename T> auto make_##name(const T& arg) { \
std::stringstream ss; \
(ss << ... << args); \
return ss.str(); \
}
namespace fg {
constexpr auto reset = "";
constexpr auto grey = "";
constexpr auto white = "";
constexpr auto cyan = "";
constexpr auto magenta = "";
constexpr auto blue = "";
constexpr auto yellow = "";
constexpr auto green = "";
constexpr auto red = "";
constexpr auto black = "";
NEW_COLOUR_MAKER(grey, tinge::fg::grey)
NEW_COLOUR_MAKER(white, tinge::fg::white)
NEW_COLOUR_MAKER(cyan, tinge::fg::cyan)
NEW_COLOUR_MAKER(magenta, tinge::fg::magenta)
NEW_COLOUR_MAKER(blue, tinge::fg::blue)
NEW_COLOUR_MAKER(yellow, tinge::fg::yellow)
NEW_COLOUR_MAKER(green, tinge::fg::green)
NEW_COLOUR_MAKER(red, tinge::fg::red)
NEW_COLOUR_MAKER(black, tinge::fg::black)
namespace bright {
constexpr auto grey = "";
constexpr auto white = "";
constexpr auto cyan = "";
constexpr auto magenta = "";
constexpr auto blue = "";
constexpr auto yellow = "";
constexpr auto green = "";
constexpr auto red = "";
constexpr auto black = "";
NEW_COLOUR_MAKER(grey, tinge::fg::bright::grey)
NEW_COLOUR_MAKER(white, tinge::fg::bright::white)
NEW_COLOUR_MAKER(cyan, tinge::fg::bright::cyan)
NEW_COLOUR_MAKER(magenta, tinge::fg::bright::magenta)
NEW_COLOUR_MAKER(blue, tinge::fg::bright::blue)
NEW_COLOUR_MAKER(yellow, tinge::fg::bright::yellow)
NEW_COLOUR_MAKER(green, tinge::fg::bright::green)
NEW_COLOUR_MAKER(red, tinge::fg::bright::red)
NEW_COLOUR_MAKER(black, tinge::fg::bright::black)
}
namespace dim {
constexpr auto grey = "";
constexpr auto white = "";
constexpr auto cyan = "";
constexpr auto magenta = "";
constexpr auto blue = "";
constexpr auto yellow = "";
constexpr auto green = "";
constexpr auto red = "";
constexpr auto black = "";
NEW_COLOUR_MAKER(grey, tinge::fg::dim::grey)
NEW_COLOUR_MAKER(white, tinge::fg::dim::white)
NEW_COLOUR_MAKER(cyan, tinge::fg::dim::cyan)
NEW_COLOUR_MAKER(magenta, tinge::fg::dim::magenta)
NEW_COLOUR_MAKER(blue, tinge::fg::dim::blue)
NEW_COLOUR_MAKER(yellow, tinge::fg::dim::yellow)
NEW_COLOUR_MAKER(green, tinge::fg::dim::green)
NEW_COLOUR_MAKER(red, tinge::fg::dim::red)
NEW_COLOUR_MAKER(black, tinge::fg::dim::black)
}
}
namespace bg {
constexpr auto grey = "";
constexpr auto white = "";
constexpr auto cyan = "";
constexpr auto magenta = "";
constexpr auto blue = "";
constexpr auto yellow = "";
constexpr auto green = "";
constexpr auto red = "";
constexpr auto black = "";
NEW_COLOUR_MAKER(grey, tinge::bg::grey)
NEW_COLOUR_MAKER(white, tinge::bg::white)
NEW_COLOUR_MAKER(cyan, tinge::bg::cyan)
NEW_COLOUR_MAKER(magenta, tinge::bg::magenta)
NEW_COLOUR_MAKER(blue, tinge::bg::blue)
NEW_COLOUR_MAKER(yellow, tinge::bg::yellow)
NEW_COLOUR_MAKER(green, tinge::bg::green)
NEW_COLOUR_MAKER(red, tinge::bg::red)
NEW_COLOUR_MAKER(black, tinge::bg::black)
namespace bright {
constexpr auto grey = "";
constexpr auto white = "";
constexpr auto cyan = "";
constexpr auto magenta = "";
constexpr auto blue = "";
constexpr auto yellow = "";
constexpr auto green = "";
constexpr auto red = "";
constexpr auto black = "";
NEW_COLOUR_MAKER(grey, tinge::bg::bright::grey)
NEW_COLOUR_MAKER(white, tinge::bg::bright::white)
NEW_COLOUR_MAKER(cyan, tinge::bg::bright::cyan)
NEW_COLOUR_MAKER(magenta, tinge::bg::bright::magenta)
NEW_COLOUR_MAKER(blue, tinge::bg::bright::blue)
NEW_COLOUR_MAKER(yellow, tinge::bg::bright::yellow)
NEW_COLOUR_MAKER(green, tinge::bg::bright::green)
NEW_COLOUR_MAKER(red, tinge::bg::bright::red)
NEW_COLOUR_MAKER(black, tinge::bg::bright::black)
}
}
#endif
#undef NEW_COLOUR_MAKER
// Presets.
namespace detail {
// Just used as tags.
struct Notice {};
struct Warn {};
struct Error {};
struct Success {};
// Overload operator<<
inline std::ostream& operator<<(std::ostream& os, const Notice&) {
return (os << tinge::bold << tinge::fg::white);
}
inline std::ostream& operator<<(std::ostream& os, const Warn&) {
return (os << tinge::bold << tinge::fg::blue);
}
inline std::ostream& operator<<(std::ostream& os, const Error&) {
return (os << tinge::bold << tinge::fg::red);
}
inline std::ostream& operator<<(std::ostream& os, const Success&) {
return (os << tinge::bold << tinge::fg::green);
}
// Instantiate.
constexpr detail::Notice notice;
constexpr detail::Warn warn;
constexpr detail::Error error;
constexpr detail::Success success;
}
}
// Core print functions.
namespace tinge {
// Print to stdout.
template <typename... Ts> inline std::ostream& print(Ts&&... args) {
#ifndef TINGE_PRINT_OFF
return ((std::cout << tinge::reset) << ... << std::forward<Ts>(args)) << tinge::reset;
#else
return std::cout;
#endif
}
// Print to buffered stderr.
template <typename... Ts> inline std::ostream& log(Ts&&... args) {
#ifndef TINGE_LOG_OFF
return ((std::clog << tinge::reset) << ... << std::forward<Ts>(args)) << tinge::reset;
#else
return std::clog;
#endif
}
// Print to stderr.
template <typename... Ts> inline std::ostream& err(Ts&&... args) {
#ifndef TINGE_ERR_OFF
return ((std::cerr << tinge::reset) << ... << std::forward<Ts>(args)) << tinge::reset;
#else
return std::cerr;
#endif
}
}
// Helper print functions.
namespace tinge {
// Symbols for special print functions.
namespace detail::symbol {
constexpr auto notice = "[-]";
constexpr auto warn = "[*]";
constexpr auto error = "[!]";
constexpr auto success = "[^]";
}
// Strong type to signal to the below functions that something should be printed before special symbol.
template <typename T>
struct before {
using value_type = T;
const T& s;
constexpr before(const T& s_): s(s_) {}
};
template <typename T>
inline std::ostream& operator<<(std::ostream& os, const before<T>& s) {
return (os << s.s);
}
// fancy printing functions
template <typename T, typename... Ts> inline std::ostream& notice(T&& arg, Ts&&... args) {
return tinge::log(detail::notice, detail::symbol::notice, tinge::reset, " ", std::forward<T>(arg), std::forward<Ts>(args)...);
}
template <typename T, typename... Ts> inline std::ostream& warn(T&& arg, Ts&&... args) {
return tinge::log(detail::warn, detail::symbol::warn, tinge::reset, " ", std::forward<T>(arg), std::forward<Ts>(args)...);
}
template <typename T, typename... Ts> inline std::ostream& error(T&& arg, Ts&&... args) {
return tinge::err(detail::error, detail::symbol::error, tinge::reset, " ", std::forward<T>(arg), std::forward<Ts>(args)...);
}
template <typename T, typename... Ts> inline std::ostream& success(T&& arg, Ts&&... args) {
return tinge::log(detail::success, detail::symbol::success, tinge::reset, " ", std::forward<T>(arg), std::forward<Ts>(args)...);
}
// const r-value ref
template <typename T, typename... Ts> inline std::ostream& notice(before<T>& arg, Ts&&... args) {
return tinge::log(arg, detail::notice, detail::symbol::notice, tinge::reset, std::forward<Ts>(args)...);
}
template <typename T, typename... Ts> inline std::ostream& warn(before<T>& arg, Ts&&... args) {
return tinge::log(arg, detail::warn, detail::symbol::warn, tinge::reset, std::forward<Ts>(args)...);
}
template <typename T, typename... Ts> inline std::ostream& error(before<T>& arg, Ts&&... args) {
return tinge::err(arg, detail::error, detail::symbol::error, tinge::reset, std::forward<Ts>(args)...);
}
template <typename T, typename... Ts> inline std::ostream& success(before<T>& arg, Ts&&... args) {
return tinge::log(arg, detail::success, detail::symbol::success, tinge::reset, std::forward<Ts>(args)...);
}
// r-value overloads of above.
template <typename T, typename... Ts> inline std::ostream& notice(before<T>&& arg, Ts&&... args) {
return tinge::log(arg, detail::notice, detail::symbol::notice, tinge::reset, std::forward<Ts>(args)...);
}
template <typename T, typename... Ts> inline std::ostream& warn(before<T>&& arg, Ts&&... args) {
return tinge::log(arg, detail::warn, detail::symbol::warn, tinge::reset, std::forward<Ts>(args)...);
}
template <typename T, typename... Ts> inline std::ostream& error(before<T>&& arg, Ts&&... args) {
return tinge::err(arg, detail::error, detail::symbol::error, tinge::reset, std::forward<Ts>(args)...);
}
template <typename T, typename... Ts> inline std::ostream& success(before<T>&& arg, Ts&&... args) {
return tinge::log(arg, detail::success, detail::symbol::success, tinge::reset, std::forward<Ts>(args)...);
}
// Newline variants.
namespace detail {
template <typename... Ts> inline auto ln() {
if constexpr(sizeof...(Ts) > 0)
return '\n';
else
return "";
}
}
template <typename... Ts> inline std::ostream& println(Ts&&... args) {
return tinge::print(std::forward<Ts>(args)..., tinge::reset, detail::ln<Ts...>());
}
template <typename... Ts> inline std::ostream& logln(Ts&&... args) {
return tinge::log(std::forward<Ts>(args)..., tinge::reset, detail::ln<Ts...>());
}
template <typename... Ts> inline std::ostream& errln(Ts&&... args) {
return tinge::err(std::forward<Ts>(args)..., tinge::reset, detail::ln<Ts...>());
}
template <typename... Ts> inline std::ostream& noticeln(Ts&&... args) {
return tinge::notice(std::forward<Ts>(args)..., tinge::reset, detail::ln<Ts...>());
}
template <typename... Ts> inline std::ostream& warnln(Ts&&... args) {
return tinge::warn(std::forward<Ts>(args)..., tinge::reset, detail::ln<Ts...>());
}
template <typename... Ts> inline std::ostream& errorln(Ts&&... args) {
return tinge::error(std::forward<Ts>(args)..., tinge::reset, detail::ln<Ts...>());
}
template <typename... Ts> inline std::ostream& successln(Ts&&... args) {
return tinge::success(std::forward<Ts>(args)..., tinge::reset, detail::ln<Ts...>());
}
}
// Utility functions.
namespace tinge {
template <typename... Ts>
inline std::string strcat(Ts&&... args) {
std::string buf{sizeof...(Ts), '\0'};
std::stringstream ss{buf};
((ss << std::forward<Ts>(args)), ...);
return ss.str();
}
namespace detail {
// unsafe, can be called like: repeat(5, 'n') or repeat('n', 5)
inline std::string repeat(char c, std::string::size_type n) {
return std::string(n, c);
}
}
// std::string constructor does not allow repeating a string so
// this function implements it.
inline std::string repeat(const std::string& c, std::string::size_type n) {
if (!n)
return ""; // Check for 0.
std::string out = c;
out.reserve(c.size() * n);
for (n--; n > 0; n--)
out += c;
return out;
}
inline std::string space(std::string::size_type n = 1) {
return detail::repeat(' ', n);
}
inline std::string tab(std::string::size_type n = 1) {
return detail::repeat('\t', n);
}
inline std::string line(std::string::size_type n = 1) {
return detail::repeat('\n', n);
}
}
#endif
|
#pragma once
#include "util/logger.hpp"
#include "config.hpp"
#include "QounterRegistry.hpp"
#include "custom-types/shared/macros.hpp"
#include "questui/shared/BeatSaberUI.hpp"
#include "GlobalNamespace/SimpleLevelStarter.hpp"
#include "GlobalNamespace/BeatmapLevelSO.hpp"
#include "GlobalNamespace/GameplayModifiers.hpp"
#include "HMUI/ViewController.hpp"
#include "UnityEngine/RectOffset.hpp"
#include "System/Reflection/Pointer.hpp"
struct NavigationButtonContext : Il2CppObject {
UnityEngine::Transform* parent;
std::string title;
std::string _namespace;
std::string _class;
std::vector<std::shared_ptr<QountersMinus::QounterRegistry::ConfigMetadata>> configMetadata;
};
DECLARE_CLASS_CODEGEN(QountersMinus, QounterSettingsViewController, HMUI::ViewController,
DECLARE_OVERRIDE_METHOD(void, DidActivate, il2cpp_utils::FindMethodUnsafe("HMUI", "ViewController", "DidActivate", 3), bool firstActivation, bool addedToHierarchy, bool screenSystemEnabling);
public:
static void CreateQounterConfigView(
UnityEngine::Transform* parent,
std::string title,
std::string namespaze,
std::string klass,
std::vector<std::shared_ptr<QountersMinus::QounterRegistry::ConfigMetadata>> configMetadata
);
)
|
/**
* Copyright (C) 2021-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* 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
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include <memory>
#include <vector>
#include "mongo/bson/bsonmisc.h"
#include "mongo/db/persistent_task_store.h"
#include "mongo/db/query/collation/collator_factory_mock.h"
#include "mongo/db/query/collation/collator_interface_mock.h"
#include "mongo/db/repl/replication_coordinator_mock.h"
#include "mongo/db/s/resharding/resharding_data_copy_util.h"
#include "mongo/db/s/resharding/resharding_data_replication.h"
#include "mongo/db/s/resharding/resharding_oplog_applier_progress_gen.h"
#include "mongo/db/s/resharding/resharding_util.h"
#include "mongo/db/service_context_d_test_fixture.h"
#include "mongo/logv2/log.h"
#include "mongo/s/catalog/type_chunk.h"
#include "mongo/s/chunk_manager.h"
#include "mongo/unittest/unittest.h"
#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kTest
namespace mongo {
namespace {
class ReshardingDataReplicationTest : public ServiceContextMongoDTest {
public:
void setUp() override {
ServiceContextMongoDTest::setUp();
auto serviceContext = getServiceContext();
{
auto opCtx = makeOperationContext();
auto replCoord = std::make_unique<repl::ReplicationCoordinatorMock>(serviceContext);
ASSERT_OK(replCoord->setFollowerMode(repl::MemberState::RS_PRIMARY));
repl::ReplicationCoordinator::set(serviceContext, std::move(replCoord));
repl::createOplog(opCtx.get());
CollatorFactoryInterface::set(serviceContext, std::make_unique<CollatorFactoryMock>());
}
}
ChunkManager makeChunkManagerForSourceCollection(
std::unique_ptr<CollatorInterface> defaultCollator) {
const OID epoch = OID::gen();
std::vector<ChunkType> chunks = {ChunkType{
_sourceUUID,
ChunkRange{BSON(_currentShardKey << MINKEY), BSON(_currentShardKey << MAXKEY)},
ChunkVersion(100, 0, epoch, Timestamp(1, 1)),
_myDonorId}};
auto rt = RoutingTableHistory::makeNew(_sourceNss,
_sourceUUID,
BSON(_currentShardKey << 1),
std::move(defaultCollator),
false /* unique */,
std::move(epoch),
Timestamp(1, 1),
boost::none /* timeseriesFields */,
boost::none /* reshardingFields */,
boost::none /* chunkSizeBytes */,
true /* allowMigrations */,
chunks);
return ChunkManager(_myDonorId,
DatabaseVersion(UUID::gen(), Timestamp(1, 1)),
makeStandaloneRoutingTableHistory(std::move(rt)),
boost::none /* clusterTime */);
}
const NamespaceString& sourceNss() {
return _sourceNss;
}
const UUID& sourceUUID() {
return _sourceUUID;
}
private:
RoutingTableHistoryValueHandle makeStandaloneRoutingTableHistory(RoutingTableHistory rt) {
const auto version = rt.getVersion();
return RoutingTableHistoryValueHandle(
std::make_shared<RoutingTableHistory>(std::move(rt)),
ComparableChunkVersion::makeComparableChunkVersion(version));
}
const StringData _currentShardKey = "sk";
const NamespaceString _sourceNss{"test_crud", "collection_being_resharded"};
const UUID _sourceUUID = UUID::gen();
const ShardId _myDonorId{"myDonorId"};
};
TEST_F(ReshardingDataReplicationTest, StashCollectionsHaveSameCollationAsReshardingCollection) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
auto sourceChunkMgr = makeChunkManagerForSourceCollection(collator.clone());
auto stashCollections = [&] {
auto opCtx = makeOperationContext();
return ReshardingDataReplication::ensureStashCollectionsExist(
opCtx.get(),
sourceChunkMgr,
{DonorShardFetchTimestamp{{"shard0"}}, DonorShardFetchTimestamp{{"shard1"}}});
}();
for (const auto& nss : stashCollections) {
auto opCtx = makeOperationContext();
AutoGetCollection stashColl(opCtx.get(), nss, MODE_IS);
ASSERT_TRUE(bool(stashColl->getDefaultCollator()))
<< "Stash collection was created with 'simple' collation";
ASSERT_BSONOBJ_BINARY_EQ(stashColl->getDefaultCollator()->getSpec().toBSON(),
collator.getSpec().toBSON());
}
}
// TODO(SERVER-59325): Remove stress test when no longer needed.
TEST_F(ReshardingDataReplicationTest,
StashCollectionsHaveSameCollationAsReshardingCollectionStressTest) {
static constexpr int kThreads = 10;
std::vector<stdx::thread> threads;
Counter64 iterations;
for (int t = 0; t < kThreads; ++t) {
stdx::thread thread([&]() {
ThreadClient threadClient(getGlobalServiceContext());
Timer timer;
while (timer.elapsed() < Seconds(2)) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
auto sourceChunkMgr = makeChunkManagerForSourceCollection(collator.clone());
auto stashCollections = [&] {
auto opCtx = Client::getCurrent()->makeOperationContext();
return ReshardingDataReplication::ensureStashCollectionsExist(
opCtx.get(),
sourceChunkMgr,
{DonorShardFetchTimestamp{{"shard0"}},
DonorShardFetchTimestamp{{"shard1"}}});
}();
for (const auto& nss : stashCollections) {
auto opCtx = Client::getCurrent()->makeOperationContext();
AutoGetCollection stashColl(opCtx.get(), nss, MODE_IS);
ASSERT_TRUE(bool(stashColl->getDefaultCollator()))
<< "Stash collection was created with 'simple' collation";
ASSERT_BSONOBJ_BINARY_EQ(stashColl->getDefaultCollator()->getSpec().toBSON(),
collator.getSpec().toBSON());
}
}
});
threads.push_back(std::move(thread));
}
for (auto& t : threads) {
t.join();
}
LOGV2(5930702, "Stress test completed", "iterations"_attr = iterations);
}
TEST_F(ReshardingDataReplicationTest, GetOplogFetcherResumeId) {
auto opCtx = makeOperationContext();
const auto reshardingUUID = UUID::gen();
auto oplogBufferNss = getLocalOplogBufferNamespace(reshardingUUID, {"shard0"});
const auto minFetchTimestamp = Timestamp{10, 0};
const auto oplogId1 = ReshardingDonorOplogId{{20, 0}, {18, 0}};
const auto oplogId2 = ReshardingDonorOplogId{{20, 0}, {19, 0}};
const auto oplogId3 = ReshardingDonorOplogId{{20, 0}, {20, 0}};
// The minFetchTimestamp value is used when the oplog buffer collection doesn't exist.
ASSERT_BSONOBJ_BINARY_EQ(
ReshardingDataReplication::getOplogFetcherResumeId(
opCtx.get(), reshardingUUID, oplogBufferNss, minFetchTimestamp)
.toBSON(),
(ReshardingDonorOplogId{minFetchTimestamp, minFetchTimestamp}.toBSON()));
// The minFetchTimestamp value is used when the oplog buffer collection is empty.
resharding::data_copy::ensureCollectionExists(opCtx.get(), oplogBufferNss, CollectionOptions{});
ASSERT_BSONOBJ_BINARY_EQ(
ReshardingDataReplication::getOplogFetcherResumeId(
opCtx.get(), reshardingUUID, oplogBufferNss, minFetchTimestamp)
.toBSON(),
(ReshardingDonorOplogId{minFetchTimestamp, minFetchTimestamp}.toBSON()));
auto insertFn = [&](const ReshardingDonorOplogId& oplogId) {
repl::MutableOplogEntry oplogEntry;
oplogEntry.setNss({});
oplogEntry.setOpType(repl::OpTypeEnum::kNoop);
oplogEntry.setObject({});
oplogEntry.setOpTime({{}, {}});
oplogEntry.setWallClockTime({});
oplogEntry.set_id(Value(oplogId.toBSON()));
AutoGetCollection oplogBufferColl(opCtx.get(), oplogBufferNss, MODE_IX);
WriteUnitOfWork wuow(opCtx.get());
ASSERT_OK(oplogBufferColl->insertDocument(
opCtx.get(), InsertStatement{oplogEntry.toBSON()}, nullptr));
wuow.commit();
};
insertFn(oplogId2);
ASSERT_BSONOBJ_BINARY_EQ(ReshardingDataReplication::getOplogFetcherResumeId(
opCtx.get(), reshardingUUID, oplogBufferNss, minFetchTimestamp)
.toBSON(),
oplogId2.toBSON());
// The highest oplog ID is used regardless of the original insertion order.
insertFn(oplogId3);
insertFn(oplogId1);
ASSERT_BSONOBJ_BINARY_EQ(ReshardingDataReplication::getOplogFetcherResumeId(
opCtx.get(), reshardingUUID, oplogBufferNss, minFetchTimestamp)
.toBSON(),
oplogId3.toBSON());
}
TEST_F(ReshardingDataReplicationTest, GetOplogApplierResumeId) {
auto opCtx = makeOperationContext();
const auto reshardingUUID = UUID::gen();
const auto minFetchTimestamp = Timestamp{10, 0};
const ReshardingSourceId sourceId{reshardingUUID, {"shard0"}};
// The minFetchTimestamp value is used when the applier progress collection doesn't exist.
ASSERT_BSONOBJ_BINARY_EQ(
ReshardingDataReplication::getOplogApplierResumeId(opCtx.get(), sourceId, minFetchTimestamp)
.toBSON(),
(ReshardingDonorOplogId{minFetchTimestamp, minFetchTimestamp}.toBSON()));
// The minFetchTimestamp value is used when the applier progress collection is empty.
resharding::data_copy::ensureCollectionExists(
opCtx.get(), NamespaceString::kReshardingApplierProgressNamespace, CollectionOptions{});
ASSERT_BSONOBJ_BINARY_EQ(
ReshardingDataReplication::getOplogApplierResumeId(opCtx.get(), sourceId, minFetchTimestamp)
.toBSON(),
(ReshardingDonorOplogId{minFetchTimestamp, minFetchTimestamp}.toBSON()));
PersistentTaskStore<ReshardingOplogApplierProgress> store(
NamespaceString::kReshardingApplierProgressNamespace);
const auto expectedOplogId = ReshardingDonorOplogId{{20, 0}, {18, 0}};
store.add(opCtx.get(), ReshardingOplogApplierProgress{sourceId, expectedOplogId, 5});
ASSERT_BSONOBJ_BINARY_EQ(
ReshardingDataReplication::getOplogApplierResumeId(opCtx.get(), sourceId, minFetchTimestamp)
.toBSON(),
expectedOplogId.toBSON());
// The progress for the specific ReshardingSourceId is returned.
store.add(opCtx.get(),
ReshardingOplogApplierProgress{ReshardingSourceId{reshardingUUID, {"shard1"}},
ReshardingDonorOplogId{{20, 0}, {19, 0}},
6});
store.add(opCtx.get(),
ReshardingOplogApplierProgress{ReshardingSourceId{UUID::gen(), {"shard0"}},
ReshardingDonorOplogId{{20, 0}, {20, 0}},
7});
ASSERT_BSONOBJ_BINARY_EQ(
ReshardingDataReplication::getOplogApplierResumeId(opCtx.get(), sourceId, minFetchTimestamp)
.toBSON(),
expectedOplogId.toBSON());
}
} // namespace
} // namespace mongo
|
/*
* X.509 Name Constraint
* (C) 2015 Kai Michaelis
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/pkix_types.h>
#include <botan/ber_dec.h>
#include <botan/internal/loadstor.h>
#include <botan/x509cert.h>
#include <botan/internal/parsing.h>
#include <sstream>
#include <functional>
namespace Botan {
class DER_Encoder;
GeneralName::GeneralName(const std::string& str) : GeneralName()
{
size_t p = str.find(':');
if(p != std::string::npos)
{
m_type = str.substr(0, p);
m_name = str.substr(p + 1, std::string::npos);
}
else
{
throw Invalid_Argument("Failed to decode Name Constraint");
}
}
void GeneralName::encode_into(DER_Encoder& /*to*/) const
{
throw Not_Implemented("GeneralName encoding");
}
void GeneralName::decode_from(class BER_Decoder& ber)
{
BER_Object obj = ber.get_next_object();
if(obj.is_a(1, ASN1_Class::ContextSpecific))
{
m_type = "RFC822";
m_name = ASN1::to_string(obj);
}
else if(obj.is_a(2, ASN1_Class::ContextSpecific))
{
m_type = "DNS";
m_name = ASN1::to_string(obj);
}
else if(obj.is_a(6, ASN1_Class::ContextSpecific))
{
m_type = "URI";
m_name = ASN1::to_string(obj);
}
else if(obj.is_a(4, ASN1_Class::ContextSpecific | ASN1_Class::Constructed))
{
m_type = "DN";
X509_DN dn;
BER_Decoder dec(obj);
std::stringstream ss;
dn.decode_from(dec);
ss << dn;
m_name = ss.str();
}
else if(obj.is_a(7, ASN1_Class::ContextSpecific))
{
if(obj.length() == 8)
{
m_type = "IP";
m_name = ipv4_to_string(load_be<uint32_t>(obj.bits(), 0)) + "/" +
ipv4_to_string(load_be<uint32_t>(obj.bits(), 1));
}
else if(obj.length() == 32)
{
throw Decoding_Error("Unsupported IPv6 name constraint");
}
else
{
throw Decoding_Error("Invalid IP name constraint size " + std::to_string(obj.length()));
}
}
else
{
throw Decoding_Error("Found unknown GeneralName type");
}
}
GeneralName::MatchResult GeneralName::matches(const X509_Certificate& cert) const
{
std::vector<std::string> nam;
std::function<bool(const GeneralName*, const std::string&)> match_fn;
const X509_DN& dn = cert.subject_dn();
const AlternativeName& alt_name = cert.subject_alt_name();
if(type() == "DNS")
{
match_fn = std::mem_fn(&GeneralName::matches_dns);
nam = alt_name.get_attribute("DNS");
if(nam.empty())
{
nam = dn.get_attribute("CN");
}
}
else if(type() == "DN")
{
match_fn = std::mem_fn(&GeneralName::matches_dn);
nam.push_back(dn.to_string());
const auto alt_dn = alt_name.dn();
if(alt_dn.empty() == false)
{
nam.push_back(alt_dn.to_string());
}
}
else if(type() == "IP")
{
match_fn = std::mem_fn(&GeneralName::matches_ip);
nam = alt_name.get_attribute("IP");
}
else
{
return MatchResult::UnknownType;
}
if(nam.empty())
{
return MatchResult::NotFound;
}
bool some = false;
bool all = true;
for(const std::string& n: nam)
{
bool m = match_fn(this, n);
some |= m;
all &= m;
}
if(all)
{
return MatchResult::All;
}
else if(some)
{
return MatchResult::Some;
}
else
{
return MatchResult::None;
}
}
bool GeneralName::matches_dns(const std::string& nam) const
{
if(nam.size() == name().size())
{
return tolower_string(nam) == tolower_string(name());
}
else if(name().size() > nam.size())
{
// The constraint is longer than the issued name: not possibly a match
return false;
}
else // name.size() < nam.size()
{
// constr is suffix of nam
const std::string constr = name().front() == '.' ? name() : "." + name();
const std::string substr = nam.substr(nam.size() - constr.size(), constr.size());
return tolower_string(constr) == tolower_string(substr);
}
}
bool GeneralName::matches_dn(const std::string& nam) const
{
std::stringstream ss(nam);
std::stringstream tt(name());
X509_DN nam_dn, my_dn;
ss >> nam_dn;
tt >> my_dn;
auto attr = nam_dn.get_attributes();
bool ret = true;
size_t trys = 0;
for(const auto& c: my_dn.dn_info())
{
auto i = attr.equal_range(c.first);
if(i.first != i.second)
{
trys += 1;
ret = ret && (i.first->second == c.second.value());
}
}
return trys > 0 && ret;
}
bool GeneralName::matches_ip(const std::string& nam) const
{
uint32_t ip = string_to_ipv4(nam);
std::vector<std::string> p = split_on(name(), '/');
if(p.size() != 2)
throw Decoding_Error("failed to parse IPv4 address");
uint32_t net = string_to_ipv4(p.at(0));
uint32_t mask = string_to_ipv4(p.at(1));
return (ip & mask) == net;
}
std::ostream& operator<<(std::ostream& os, const GeneralName& gn)
{
os << gn.type() << ":" << gn.name();
return os;
}
GeneralSubtree::GeneralSubtree(const std::string& str) : GeneralSubtree()
{
size_t p0, p1;
const auto min = std::stoull(str, &p0, 10);
const auto max = std::stoull(str.substr(p0 + 1), &p1, 10);
GeneralName gn(str.substr(p0 + p1 + 2));
if(p0 > 0 && p1 > 0)
{
m_minimum = static_cast<size_t>(min);
m_maximum = static_cast<size_t>(max);
m_base = gn;
}
else
{
throw Invalid_Argument("Failed to decode Name Constraint");
}
}
void GeneralSubtree::encode_into(DER_Encoder& /*to*/) const
{
throw Not_Implemented("General Subtree encoding");
}
void GeneralSubtree::decode_from(class BER_Decoder& ber)
{
ber.start_sequence()
.decode(m_base)
.decode_optional(m_minimum, ASN1_Type(0), ASN1_Class::ContextSpecific, size_t(0))
.end_cons();
if(m_minimum != 0)
throw Decoding_Error("GeneralSubtree minimum must be 0");
m_maximum = std::numeric_limits<std::size_t>::max();
}
std::ostream& operator<<(std::ostream& os, const GeneralSubtree& gs)
{
os << gs.minimum() << "," << gs.maximum() << "," << gs.base();
return os;
}
}
|
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/crostini/crostini_uninstaller_view.h"
#include "base/bind.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/chromeos/crostini/crostini_features.h"
#include "chrome/browser/chromeos/crostini/crostini_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "chrome/browser/ui/views/chrome_layout_provider.h"
#include "chrome/grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/chromeos/devicetype_utils.h"
#include "ui/strings/grit/ui_strings.h"
#include "ui/views/border.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/progress_bar.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/layout/layout_provider.h"
namespace {
CrostiniUninstallerView* g_crostini_uninstaller_view = nullptr;
constexpr char kCrostiniUninstallResultHistogram[] = "Crostini.UninstallResult";
constexpr char kCrostiniUninstallSourceHistogram[] = "Crostini.UninstallSource";
} // namespace
void crostini::ShowCrostiniUninstallerView(
Profile* profile,
crostini::CrostiniUISurface ui_surface) {
base::UmaHistogramEnumeration(kCrostiniUninstallSourceHistogram, ui_surface,
crostini::CrostiniUISurface::kCount);
return CrostiniUninstallerView::Show(profile);
}
void CrostiniUninstallerView::Show(Profile* profile) {
DCHECK(crostini::CrostiniFeatures::Get()->IsUIAllowed(profile));
if (!g_crostini_uninstaller_view) {
g_crostini_uninstaller_view = new CrostiniUninstallerView(profile);
views::DialogDelegate::CreateDialogWidget(g_crostini_uninstaller_view,
nullptr, nullptr);
}
g_crostini_uninstaller_view->GetWidget()->Show();
}
bool CrostiniUninstallerView::Accept() {
state_ = State::UNINSTALLING;
SetButtons(ui::DIALOG_BUTTON_NONE);
message_label_->SetText(
l10n_util::GetStringUTF16(IDS_CROSTINI_UNINSTALLER_UNINSTALLING_MESSAGE));
// Kick off the Crostini Remove sequence.
crostini::CrostiniManager::GetForProfile(profile_)->RemoveCrostini(
crostini::kCrostiniDefaultVmName,
base::BindOnce(&CrostiniUninstallerView::UninstallCrostiniFinished,
weak_ptr_factory_.GetWeakPtr()));
progress_bar_ = new views::ProgressBar();
AddChildView(progress_bar_);
// Setting value to -1 makes the progress bar play the
// "indeterminate animation".
progress_bar_->SetValue(-1);
DialogModelChanged();
GetWidget()->UpdateWindowTitle();
GetWidget()->SetSize(GetWidget()->non_client_view()->GetPreferredSize());
return false; // Should not close the dialog
}
bool CrostiniUninstallerView::Cancel() {
RecordUninstallResultHistogram(UninstallResult::kCancelled);
return true; // Should close the dialog
}
gfx::Size CrostiniUninstallerView::CalculatePreferredSize() const {
const int dialog_width = ChromeLayoutProvider::Get()->GetDistanceMetric(
DISTANCE_STANDALONE_BUBBLE_PREFERRED_WIDTH) -
margins().width();
return gfx::Size(dialog_width, GetHeightForWidth(dialog_width));
}
// static
CrostiniUninstallerView* CrostiniUninstallerView::GetActiveViewForTesting() {
return g_crostini_uninstaller_view;
}
CrostiniUninstallerView::CrostiniUninstallerView(Profile* profile)
: profile_(profile) {
SetShowCloseButton(false);
SetTitle(IDS_CROSTINI_UNINSTALLER_TITLE);
SetButtonLabel(
ui::DIALOG_BUTTON_OK,
l10n_util::GetStringUTF16(IDS_CROSTINI_UNINSTALLER_UNINSTALL_BUTTON));
views::LayoutProvider* provider = views::LayoutProvider::Get();
SetLayoutManager(std::make_unique<views::BoxLayout>(
views::BoxLayout::Orientation::kVertical,
provider->GetInsetsMetric(views::InsetsMetric::INSETS_DIALOG),
provider->GetDistanceMetric(views::DISTANCE_RELATED_CONTROL_VERTICAL)));
const base::string16 device_type = ui::GetChromeOSDeviceName();
const base::string16 message =
l10n_util::GetStringFUTF16(IDS_CROSTINI_UNINSTALLER_BODY, device_type);
message_label_ = new views::Label(message);
message_label_->SetMultiLine(true);
message_label_->SetHorizontalAlignment(gfx::ALIGN_LEFT);
AddChildView(message_label_);
chrome::RecordDialogCreation(chrome::DialogIdentifier::CROSTINI_UNINSTALLER);
}
CrostiniUninstallerView::~CrostiniUninstallerView() {
g_crostini_uninstaller_view = nullptr;
}
void CrostiniUninstallerView::HandleError(const base::string16& error_message) {
state_ = State::ERROR;
SetButtons(ui::DIALOG_BUTTON_CANCEL);
message_label_->SetVisible(true);
message_label_->SetText(error_message);
progress_bar_->SetVisible(false);
DialogModelChanged();
GetWidget()->UpdateWindowTitle();
GetWidget()->SetSize(GetWidget()->non_client_view()->GetPreferredSize());
RecordUninstallResultHistogram(UninstallResult::kError);
}
void CrostiniUninstallerView::UninstallCrostiniFinished(
crostini::CrostiniResult result) {
if (result != crostini::CrostiniResult::SUCCESS) {
HandleError(l10n_util::GetStringUTF16(IDS_CROSTINI_UNINSTALLER_ERROR));
return;
} else {
RecordUninstallResultHistogram(UninstallResult::kSuccess);
}
GetWidget()->Close();
}
void CrostiniUninstallerView::RecordUninstallResultHistogram(
UninstallResult result) {
// Prevent multiple results being logged for a given uninstall flow. This
// happens because Cancel is always called, either due to the user cancelling
// or the dialog being closed. The simplest way to prevent metrics being
// erroneously logged for user cancellation is to only record the first
// metric.
if (has_logged_result_)
return;
base::UmaHistogramEnumeration(kCrostiniUninstallResultHistogram, result,
UninstallResult::kCount);
has_logged_result_ = true;
}
|
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/hlo_graph_dumper.h"
#include <unistd.h>
#include <algorithm>
#include <atomic>
#include <deque>
#include <map>
#include <memory>
#include <queue>
#include <string>
#include <tuple>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_replace.h"
#include "absl/types/optional.h"
#include "tensorflow/compiler/xla/layout_util.h"
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/compiler/xla/service/hlo_casting_utils.h"
#include "tensorflow/compiler/xla/service/hlo_instructions.h"
#include "tensorflow/compiler/xla/service/hlo_module.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
#include "tensorflow/compiler/xla/service/pattern_matcher.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/compiler/xla/window_util.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/lib/strings/numbers.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/regexp.h"
namespace xla {
namespace {
using absl::nullopt;
using absl::optional;
using absl::StrAppend;
using absl::StrCat;
using absl::StrFormat;
using absl::StrJoin;
// Used to indicate how we should treat a given HLOInstruction in the graph.
// should we treat it like normal, hide it, and so on?
enum NodeFilterResult {
kNormalNode,
kHideNode,
// Make the node easy to find in the final graph.
kHighlightNode,
// "Gray out" the node to indicate that some of its operands have been
// omitted.
kSomeOperandsOmitted,
// Style the node the same as kSomeOperandsOmitted, but also don't connect it
// to its operands, even if they're present in the graph.
kOmitNodeOperands,
// Same style as kSomeOperandsOmitted, but used to indicate that some of the
// node's *users* have been omitted.
kSomeUsersOmitted,
};
// NodeFilter is essentially a map from HloInstruction*s to NodeFilterResult.
// It lets callers tell the graph-drawing routines which nodes they want to be
// shown, hidden, or highlighted.
class NodeFilter {
public:
NodeFilter() : filter_([](const HloInstruction*) { return kNormalNode; }) {}
explicit NodeFilter(
std::function<NodeFilterResult(const HloInstruction* instr)> filter)
: filter_(std::move(filter)) {}
bool Show(const HloInstruction* instr) const {
return filter_(instr) != kHideNode;
}
bool Highlight(const HloInstruction* instr) const {
return filter_(instr) == kHighlightNode;
}
bool OmitOperands(const HloInstruction* instr) const {
return filter_(instr) == kOmitNodeOperands;
}
bool SomeOrAllOperandsOmitted(const HloInstruction* instr) const {
auto result = filter_(instr);
return result == kOmitNodeOperands || result == kSomeOperandsOmitted;
}
bool Deemphasized(const HloInstruction* instr) const {
auto result = filter_(instr);
return result == kOmitNodeOperands || result == kSomeOperandsOmitted ||
result == kSomeUsersOmitted;
}
private:
std::function<NodeFilterResult(const HloInstruction* instr)> filter_;
};
// We arbitrarily set this as the boundary between "large" and "small"
// instructions.
bool IsSmall(const HloInstruction* instr) {
if (ShapeUtil::HasPrimitiveType(instr->shape(), OPAQUE_TYPE) ||
ShapeUtil::HasPrimitiveType(instr->shape(), TOKEN)) {
return true;
}
return ShapeUtil::ElementsInRecursive(instr->shape()) < 4096;
}
// Node color schemes, used by NodeColorAttributes.
enum ColorScheme {
kBlue,
kBrown,
kDarkBlue,
kDarkGreen,
kDarkOrange,
kDarkRed,
kGray,
kGreen,
kOrange,
kPurple,
kRed,
kWhite,
kYellow,
// Causes the node's border to be a dashed line, and its content to be gray
// text on a white background, suggesting that this is an "unimportant" node.
kDashedBorder,
};
// Graphviz attributes/colors that make up a color scheme.
struct NodeColors {
const char* style;
const char* fill_color;
const char* stroke_color;
const char* font_color;
};
NodeColors NodeColorsForScheme(ColorScheme color) {
switch (color) {
case kBlue:
return NodeColors{"filled", "#bbdefb", "#8aacc8", "black"};
case kBrown:
return NodeColors{"filled", "#bcaaa4", "#8c7b75", "black"};
case kDarkBlue:
return NodeColors{"filled", "#1565c0", "#003c8f", "white"};
case kDarkGreen:
return NodeColors{"filled", "#2e7d32", "#005005", "white"};
case kDarkOrange:
// This is more of a "medium" orange, made to look close to kOrange;
// there's probably room for a darker weight if desired.
return NodeColors{"filled", "#ffb74d", "#c88719", "black"};
case kDarkRed:
return NodeColors{"filled", "#b71c1c", "#7f0000", "white"};
case kGray:
return NodeColors{"filled", "#cfd8dc", "#9ea7aa", "black"};
case kGreen:
return NodeColors{"filled", "#c8e6c9", "#97b498", "black"};
case kOrange:
return NodeColors{"filled", "#ffe0b2", "#cbae82", "black"};
case kPurple:
return NodeColors{"filled", "#e1bee7", "#af8eb5", "black"};
case kRed:
return NodeColors{"filled", "#ffcdd2", "#cb9ca1", "black"};
case kWhite:
return NodeColors{"filled", "white", "black", "black"};
case kYellow:
return NodeColors{"filled", "#fff9c4", "#cbc693", "black"};
case kDashedBorder:
// "filled,dashed" looks the same as "dashed", since we have a white
// background. But we use "filled,dashed" so that when you hover over
// any part of the node (not just the text inside the node), our css
// :hover rule is triggered.
return NodeColors{"filled,dashed", "white", "#757575", "#757575"};
}
}
// Given a ColorScheme, returns an attribute string for a node of that color.
// Sets the node's style and fill/stroke/text colors.
//
// Colors are from https://material.io/color.
string NodeColorAttributes(ColorScheme color) {
NodeColors node_colors = NodeColorsForScheme(color);
return StrFormat(R"(style="%s", fontcolor="%s", color="%s", fillcolor="%s")",
node_colors.style, node_colors.font_color,
node_colors.stroke_color, node_colors.fill_color);
}
// Replaces <> with <>, so that this string is safe(er) for use in a
// graphviz HTML-like string.
string HtmlLikeStringSanitize(absl::string_view s) {
return absl::StrReplaceAll(s, {{"<", "<"}, {">", ">"}});
}
bool IsFusedBroadcastOfConstantEffectiveScalar(const HloInstruction* instr) {
namespace m = match;
return instr->parent()->IsFusionComputation() &&
Match(instr, m::Broadcast(m::ConstantEffectiveScalar()));
}
// Tries to generates a human-readable one-word description of the given
// computation.
//
// Currently we support:
//
// "return param0 + param1;" --> "add"
// "return param0 * param1;" --> "multiply"
// "return min(param0, param1);" --> "min"
// "return max(param0, param1);" --> "max"
// "return param0 <= param1;" --> "less-or-equal"
// "return param0 >= param1;" --> "greater-or-equal"
// "return param0 > param1;" --> "greater-than"
// "return param0 < param1;" --> "less-than"
// "return param0 == param1;" --> "equal-to"
// "return param0 != param1;" --> "not-equal-to"
//
// where param0 and param1 are effective scalars. For the ops that are
// commutative, we also support them with param0 and param1 swapped.
//
// This is useful primarily for reduce and map nodes. These take a
// subcomputation which is almost always one of the above, and pattern matching
// it to a short string lets us tell the user what the subcomputation is without
// drawing it as a graph.
optional<string> MatchTrivialComputation(const HloComputation* computation) {
namespace m = match;
if (computation->instruction_count() != 3) {
return nullopt;
}
HloInstruction* root = computation->root_instruction();
const HloInstruction *param0, *param1;
if (!Match(root, m::Op()
.WithNumOperands(2)
.WithShape(m::Shape().IsEffectiveScalar())
.WithBinaryOperandsAnyOrder(
m::Parameter(¶m0, 0)
.WithShape(m::Shape().IsEffectiveScalar()),
m::Parameter(¶m1, 1)
.WithShape(m::Shape().IsEffectiveScalar())))) {
return nullopt;
}
// If the params are reversed (i.e. operand0 is param1 and operand1 is
// param0), check that the operation being performed is commutative.
if (root->operand(0) == param1) {
CHECK_EQ(root->operand(1), param0);
if (root->opcode() == HloOpcode()) {
switch (root->comparison_direction()) {
case ComparisonDirection::kLe:
case ComparisonDirection::kGe:
case ComparisonDirection::kGt:
case ComparisonDirection::kLt:
return nullopt;
default:
break;
}
}
}
// If we recognize the root's opcode, we've successfully pattern-matched!
switch (root->opcode()) {
case HloOpcode::kAdd:
return "add";
case HloOpcode::kMultiply:
return "multiply";
case HloOpcode::kMinimum:
return "min";
case HloOpcode::kMaximum:
return "max";
case HloOpcode::kCompare: {
switch (root->comparison_direction()) {
case ComparisonDirection::kLe:
return "less-or-equal";
case ComparisonDirection::kGe:
return "greater-or-equal";
case ComparisonDirection::kGt:
return "greater-than";
case ComparisonDirection::kLt:
return "less-than";
case ComparisonDirection::kEq:
return "equal-to";
case ComparisonDirection::kNe:
return "not-equal-to";
}
}
default:
return nullopt;
}
}
// Encapsulates logic for dumping an HLO module to DOT (i.e. graphviz syntax).
class HloDotDumper {
public:
HloDotDumper(const HloComputation* computation, absl::string_view label,
const DebugOptions& debug_options,
HloRenderOptions hlo_render_options,
const HloExecutionProfile* profile, NodeFilter filter)
: computation_(computation),
label_(label),
debug_options_(debug_options),
hlo_render_options_(hlo_render_options),
profile_(profile),
filter_(std::move(filter)) {}
string Dump();
private:
// Returns the dot graph identifier for the given instruction.
string InstructionId(const HloInstruction* instruction) {
return StrCat(reinterpret_cast<uint64>(instruction));
}
// Returns the dot graph identifier for the given computation.
string SubcomputationId(const HloComputation* computation) {
return StrCat("cluster_", reinterpret_cast<uint64>(computation));
}
// Generates graph header/footer. These should be called *after* dumping all
// of the instructions and subcomputations for the graph, as they both use
// data generated while dumping the graph.
string Header();
string Footer();
bool ShouldShowSubcomputation(const HloComputation* subcomp);
bool ShouldShowFusionSubcomputation(const HloInstruction* instr);
// We omit some nodes from the graph, instead drawing them inlined into the
// nodes that use them.
bool ShouldMergeIntoUsers(const HloInstruction* instr) const;
string DumpSubcomputation(const HloComputation* subcomp,
const HloInstruction* parent_instr);
string DumpComputation(const HloComputation* comp);
string DumpRootTag();
string DumpInstruction(const HloInstruction* instr);
ColorScheme GetInstructionColor(const HloInstruction* instr);
string GetInstructionNodeShape(const HloInstruction* instr);
string GetInstructionNodeLabel(const HloInstruction* instr);
string GetInstructionNodeMetadata(const HloInstruction* instr);
string GetInstructionNodeBackendConfig(const HloInstruction* instr);
string GetInstructionNodeExtraInfo(const HloInstruction* instr);
string GetInstructionNodeInlinedOperands(const HloInstruction* instr);
void AddInstructionIncomingEdges(const HloInstruction* instr);
// For most instructions, GetNodeForEdge(instr) returns instr.
//
// The exception is fusion nodes. For these, we walk up the chain of nested
// fusion nodes starting at instr until we reach a node that either (a) isn't
// a fusion node, or (b) is a fusion node for which
// ShouldShowFusionSubcomputation is false.
//
// We do this because fusion nodes are expanded inline -- if
// ShouldShowFusionSubcomputation is true, the fusion node won't be present in
// the graph.
//
// In general when you want to draw an edge from A to B, you should actually
// draw an edge from GetNodeForEdge(A) to GetNodeForEdge(B).
const HloInstruction* GetNodeForEdge(const HloInstruction* instr);
// If instr has just one computation and it's trivial (e.g. "return param0 +
// param1"), returns a string you can put into the node's body that names the
// subcomputation, e.g. "Subcomputation: <b>add</b>".
string GetInstructionTrivialComputationStr(const HloInstruction* instr);
const HloComputation* computation_; // never null
const string label_; // overall name for the graph
const DebugOptions& debug_options_;
const HloRenderOptions hlo_render_options_;
const HloExecutionProfile* profile_; // may be null
const NodeFilter filter_;
// Each HloInstruction dumped gets a monotonically-increasing node ID. This
// must start at 1, because that's where graphviz's accounting starts.
int64 next_node_id_ = 1;
absl::flat_hash_map<const HloInstruction*, int64> node_ids_;
// The "root" tag doesn't have an associated HloInstruction pointer, so we
// need to store it outside the map.
int64 root_node_id_;
// Each (from, to) edge gets a monotonically-increasing ID. This is a
// multimap because it's possible for the same edge to appear multiple times
// in the graph (e.g. x^2 may be represented as mul(x, x)).
int64 next_edge_id_ = 1;
std::unordered_multimap<
std::pair<const HloInstruction*, const HloInstruction*>, int64,
tensorflow::hash<std::pair<const HloInstruction*, const HloInstruction*>>>
edge_ids_;
// Each HloComputation that's emitted gets a monotonically-increasing ID.
int64 next_cluster_id_ = 1;
absl::flat_hash_map<const HloComputation*, int64> cluster_ids_;
// Edges to print from Footer(). Edges come at the end because graphviz is
// unhappy if an edge from a subcomputation to a node in the outer computation
// appears before both the inner computation and the destination node are
// defined.
std::vector<string> edges_;
// When coloring by sharding information, we track the sharding string
// representation to color association, by round-robin the color schemes.
absl::flat_hash_map<HloSharding, ColorScheme, HloSharding::Hasher>
sharding_colors_;
int64 next_shard_color_ = 0;
};
string HloDotDumper::Dump() {
string body;
StrAppend(&body, DumpComputation(computation_));
StrAppend(&body, DumpRootTag());
// By contract, Header() and Footer() have to be called after we've dumped all
// our instructions, because they use state generated during that process.
string g = Header();
StrAppend(&g, body);
StrAppend(&g, Footer());
return g;
}
string HloDotDumper::Header() {
constexpr char fmt[] = R"(digraph G {
rankdir = TB;
compound = true;
label = <<b>%s</b>>;
labelloc = t;
// Disable the tooltip. Interestingly, "" doesn't work!
tooltip = " ";
// DOT graphs accept a stylesheet as a URI. So naturally, an inline
// stylesheet is a data URI!
stylesheet=<
data:text/css,
@import url(https://fonts.googleapis.com/css?family=Roboto:400,700);
svg text {
font-family: 'Roboto';
font-size: 12px;
}
%s
>
)";
VLOG(3) << "Generating Header";
string graph_label =
StrCat(label_, "<br/>Computation ", computation_->name());
if (computation_->IsFusionComputation()) {
StrAppend(&graph_label, " (in fusion instruction ",
computation_->FusionInstruction()->name(), ")");
}
if (profile_ != nullptr) {
auto cycles = profile_->total_cycles_executed(*computation_);
absl::StrAppendFormat(&graph_label, "<br/>total cycles = %d (%s)", cycles,
tensorflow::strings::HumanReadableNum(cycles));
}
// Create CSS rules that say, when you hover over the given node or cluster,
// turn the given edge the given color.
//
// We rely on a few properties of how graphviz generates SVGs:
//
// - Nodes are named "nodeN", where N corresponds to the 1-based index of
// the node in our DOT (i.e. the first node in the DOT is "node1", etc.).
// Edges are similarly named "edgeN", and clusters are named "clustN".
// - Nodes come before their in- and out-edges in the SVG. We need this
// because the "X ~ Y" CSS selector finds a sibling of X that *comes
// after X in the DOM* and matches Y.
std::vector<string> edge_css_rules;
const char* kBlue = "#1976d2";
const char* kRed = "#d32f2f";
for (const auto& kv : edge_ids_) {
const HloInstruction* from_node = kv.first.first;
const HloInstruction* to_node = kv.first.second;
int64 edge_id = kv.second;
auto add_hover_css_rule = [&](string elem_type, int64 elem_id,
const char* color) {
// One could imagine other ways of writing this CSS rule that involve
// less duplication, but this way seems to be relatively performant.
edge_css_rules.push_back(
StrFormat(" #%s%d:hover ~ #edge%d text { fill: %s; }\n"
" #%s%d:hover ~ #edge%d path { "
"stroke: %s; stroke-width: .2em; }\n"
" #%s%d:hover ~ #edge%d polygon { "
"fill: %s; stroke: %s; stroke-width: .2em; }\n",
elem_type, elem_id, edge_id, color, //
elem_type, elem_id, edge_id, color, //
elem_type, elem_id, edge_id, color, color));
};
// The "to_node" value may be a NULL, indicating that this points to the
// "root" tag rather than a normal node.
int64 from_node_id =
tensorflow::gtl::FindWithDefault(node_ids_, from_node, -1);
if (from_node_id == -1) {
LOG(FATAL) << from_node->name() << " was added to edges but not to nodes";
}
int64 to_node_id =
to_node ? tensorflow::gtl::FindWithDefault(node_ids_, to_node, -1)
: root_node_id_;
if (to_node != nullptr && to_node_id == -1) {
LOG(FATAL) << to_node->name() << " was added to edges but not to nodes";
}
add_hover_css_rule("node", from_node_id, kBlue);
add_hover_css_rule("node", to_node_id, kRed);
if (to_node) {
VLOG(3) << "Adding css for edge " << edge_id << " from node "
<< from_node->name() << " to node " << to_node->name();
} else {
VLOG(3) << "Adding css for edge " << edge_id << " from node "
<< from_node->name() << " to root tag";
}
// If this edge crosses a fusion cluster boundary, highlight it when the
// cluster is hovered over.
if (to_node) {
if (from_node->IsFused() &&
from_node->parent()->root_instruction() == from_node) {
int64 cluster_id = cluster_ids_.at(from_node->parent());
add_hover_css_rule("clust", cluster_id, kBlue);
}
if (to_node->IsFused() && to_node->opcode() == HloOpcode::kParameter) {
int64 cluster_id = cluster_ids_.at(to_node->parent());
add_hover_css_rule("clust", cluster_id, kRed);
}
}
}
// Browsers require that we URI-encode the contents of our data URI. (It
// seems this was a relatively recent change?) In practice, this means that we
// need to escape '#'.
return StrFormat(
fmt, graph_label,
absl::StrReplaceAll(StrJoin(edge_css_rules, "\n"), {{"#", "%23"}}));
}
string HloDotDumper::Footer() { return StrCat(StrJoin(edges_, "\n"), "\n}"); }
bool HloDotDumper::ShouldShowFusionSubcomputation(const HloInstruction* instr) {
CHECK_EQ(instr->opcode(), HloOpcode::kFusion);
return ShouldShowSubcomputation(instr->fused_instructions_computation());
}
bool HloDotDumper::ShouldShowSubcomputation(const HloComputation* subcomp) {
if (subcomp->IsFusionComputation()) {
const HloInstruction* fusion = subcomp->FusionInstruction();
if (!filter_.Show(fusion) || filter_.SomeOrAllOperandsOmitted(fusion) ||
!hlo_render_options_.show_fusion_subcomputations) {
return false;
}
}
// Don't show trivial subcomputations on non-fusion nodes -- these are inlined
// into the graph.
if (!subcomp->IsFusionComputation() && MatchTrivialComputation(subcomp)) {
return false;
}
// Show the subcomputation if we're showing any of its members.
return absl::c_any_of(
subcomp->instructions(),
[&](const HloInstruction* instr) { return filter_.Show(instr); });
}
string HloDotDumper::DumpSubcomputation(const HloComputation* subcomp,
const HloInstruction* parent_instr) {
VLOG(2) << "Dumping subcomputation " << subcomp->name();
// Add an edge from the subcomputation to its parent node. If subcomp
// belongs to a fusion node, it's drawn in place of the fusion instruction,
// so there's no need to link those.
if (parent_instr->opcode() != HloOpcode::kFusion) {
const HloInstruction* from = GetNodeForEdge(subcomp->root_instruction());
VLOG(2) << "Edge: from " << from->name() << " to " << parent_instr->name()
<< " as " << next_edge_id_;
edge_ids_.insert({{from, parent_instr}, next_edge_id_++});
constexpr char edge_fmt[] =
R"(%s -> %s [ltail="%s", style="dashed" tooltip="%s -> %s"];)";
edges_.push_back(StrFormat(
edge_fmt, InstructionId(from), InstructionId(parent_instr),
SubcomputationId(subcomp), subcomp->name(), parent_instr->name()));
}
// Have we already dumped this subcomputation? If so, generating the edge
// linking it and parent_instr is all we want to do in this function.
if (cluster_ids_.find(subcomp) != cluster_ids_.end()) {
return "";
}
cluster_ids_[subcomp] = next_cluster_id_++;
string id = SubcomputationId(subcomp);
string subcomp_label, style;
if (parent_instr->opcode() == HloOpcode::kFusion) {
subcomp_label =
StrFormat("Fused expression for <b>%s</b><br/>%s",
HtmlLikeStringSanitize(parent_instr->name()),
HtmlLikeStringSanitize(parent_instr->ToCategory()));
string extra_info = GetInstructionNodeExtraInfo(parent_instr);
if (!extra_info.empty()) {
StrAppend(&subcomp_label, "<br/>", extra_info);
}
string node_backend_config = GetInstructionNodeBackendConfig(parent_instr);
if (!node_backend_config.empty()) {
StrAppend(&subcomp_label, "<br/>", node_backend_config);
}
bool highlight = filter_.Highlight(parent_instr);
const char* fillcolor;
const char* strokecolor;
if (debug_options_.xla_hlo_graph_sharding_color() && !highlight) {
// Use the sharding color, if the node isn't highlighted.
NodeColors node_colors =
NodeColorsForScheme(GetInstructionColor(parent_instr));
fillcolor = node_colors.fill_color;
strokecolor = node_colors.stroke_color;
} else {
// Subcomputation's fill/stroke color is light/dark red/gray, depending on
// whether or not the subcomputation's fusion node is highlighted.
fillcolor = highlight ? "#ffcdd2" : "#f5f5f5";
strokecolor = highlight ? "#b71c1c" : "#c2c2c2";
}
style =
StrFormat(R"(style="rounded,filled,bold"; fillcolor="%s"; color="%s;")",
fillcolor, strokecolor);
} else {
subcomp_label = StrFormat("Subcomputation for <b>%s</b><br/>%s",
HtmlLikeStringSanitize(parent_instr->name()),
HtmlLikeStringSanitize(subcomp->name()));
style = "style=rounded; color=black;";
}
string comp_body = DumpComputation(subcomp);
constexpr char computation_fmt[] = R"(subgraph %s {
%s
label = <%s>;
labelloc = t;
tooltip = " ";
%s
} // %s
)";
return StrFormat(computation_fmt, id, style, subcomp_label, comp_body, id);
}
string HloDotDumper::DumpComputation(const HloComputation* comp) {
string g;
for (const auto* instr : comp->instructions()) {
if (!filter_.Show(instr)) {
continue;
}
// Dump subcomputations within instr.
for (const HloComputation* subcomp : instr->called_computations()) {
if (ShouldShowSubcomputation(subcomp)) {
StrAppend(&g, DumpSubcomputation(subcomp, instr));
}
}
StrAppend(&g, DumpInstruction(instr));
}
return g;
}
string HloDotDumper::DumpRootTag() {
const HloInstruction* from = GetNodeForEdge(computation_->root_instruction());
// We didn't display constants or broadcasts of effective scalars within
// fusions as separate nodes; so if the root is a constant/broadcast of
// scalar, we don't add root tag or edge for it.
if (!filter_.Show(from) || from->opcode() == HloOpcode::kConstant ||
IsFusedBroadcastOfConstantEffectiveScalar(from)) {
return "";
}
auto from_id = InstructionId(from);
// The ID of the root computation is otherwise unused, so it makes a good ID
// to use for the root-tag node. However, the edge_ids_ map requires a
// HloInstruction* pointer for the 'to' value, so we use a NULL value there
// (rather than a pointer type-cast) to make it obvious if it is erroneously
// dereferenced.
HloInstruction* to = nullptr;
auto to_id = SubcomputationId(computation_);
string node_body = "ROOT";
string node_shape = "circle";
ColorScheme color = kBrown;
VLOG(2) << "Adding root tag as node " << next_node_id_;
root_node_id_ = next_node_id_++;
VLOG(2) << "Adding edge from " << from->name() << " to root tag as "
<< next_edge_id_;
edge_ids_.insert({{from, to}, next_edge_id_++});
edges_.push_back(StrFormat(R"(%s -> %s [tooltip=" "];)", from_id, to_id));
return StrFormat(R"(%s [label=<%s>, shape=%s, tooltip=" ", %s];)"
"\n",
to_id, node_body, node_shape, NodeColorAttributes(color));
}
static const HloConstantInstruction* TryGetFusionParameterConstant(
const HloInstruction* instr) {
if (instr->opcode() != HloOpcode::kParameter || !instr->IsFused()) {
return nullptr;
}
const HloInstruction* fusion = instr->parent()->FusionInstruction();
const HloInstruction* operand = fusion->operand(instr->parameter_number());
return DynCast<HloConstantInstruction>(operand);
}
bool HloDotDumper::ShouldMergeIntoUsers(const HloInstruction* instr) const {
// If a node:
//
// - is a parameter of a fusion node which is bound to a constant,
//
// or
//
// - is a tuple-shaped parameter, and
// - is not a parameter to a fusion node, and
// - has at least kMinUsersToOmit users shown, and
// - all of the shown users are get-tuple-elements,
//
// then we omit it from the graph, merging it with its users.
//
// This helps us handle the common case where a while loop body has one big
// tuple-shaped parameter.
if (TryGetFusionParameterConstant(instr) != nullptr) {
return true;
}
const int kMinUsersToOmit = 3;
return instr->opcode() == HloOpcode::kParameter && instr->shape().IsTuple() &&
!instr->IsFused() &&
absl::c_count_if(instr->users(),
[&](const HloInstruction* user) {
return filter_.Show(user);
}) > kMinUsersToOmit &&
absl::c_all_of(instr->users(), [&](const HloInstruction* user) {
return !filter_.Show(user) ||
user->opcode() == HloOpcode::kGetTupleElement;
});
}
string HloDotDumper::DumpInstruction(const HloInstruction* instr) {
// We don't display constants or broadcasts of effective scalar constants
// within fusions as separate nodes; they're merged into their users.
if (instr->opcode() == HloOpcode::kConstant ||
IsFusedBroadcastOfConstantEffectiveScalar(instr)) {
return "";
}
// Skip this node if it's merged into its users.
if (ShouldMergeIntoUsers(instr)) {
return "";
}
// Omit the fusion node if its subcomputation is drawn, since the
// subcomputation will be drawn inline.
if (instr->opcode() == HloOpcode::kFusion &&
ShouldShowFusionSubcomputation(instr)) {
return "";
}
VLOG(2) << "Adding node " << instr->name() << " as " << next_node_id_;
node_ids_[instr] = next_node_id_++;
ColorScheme color = GetInstructionColor(instr);
string node_shape = GetInstructionNodeShape(instr);
string node_label = GetInstructionNodeLabel(instr);
string node_metadata = GetInstructionNodeMetadata(instr);
string node_backend_config = GetInstructionNodeBackendConfig(instr);
string extra_info = GetInstructionNodeExtraInfo(instr);
string inlined_constants = GetInstructionNodeInlinedOperands(instr);
string trivial_subcomputation = GetInstructionTrivialComputationStr(instr);
AddInstructionIncomingEdges(instr);
if (!debug_options_.xla_hlo_graph_sharding_color()) {
// Override the node's styling if it should be (de-)emphasized.
if (filter_.Deemphasized(instr)) {
color = kDashedBorder;
}
if (filter_.Highlight(instr)) {
node_shape = "diamond";
color = kDarkRed;
}
}
// Build the text that will be displayed inside the node.
string node_body = node_label;
for (const string& s : {trivial_subcomputation, node_backend_config,
extra_info, inlined_constants}) {
if (!s.empty()) {
StrAppend(&node_body, "<br/>", s);
}
}
return StrFormat(R"(%s [label=<%s>, shape=%s, tooltip="%s", %s];)"
"\n",
InstructionId(instr), node_body, node_shape, node_metadata,
NodeColorAttributes(color));
}
string HloDotDumper::GetInstructionNodeInlinedOperands(
const HloInstruction* instr) {
// The constant's shape is a parameter because, in the case of a broadcasted
// scalar constant, we want to show the broadcasted shape, not the constant's
// scalar shape.
auto stringify_constant = [](const HloConstantInstruction* constant,
const Shape& shape) {
// If the shape has a dimension of size zero, print it as e.g.
// "{} (f32[42, 0, 10])". The alternative, calling Literal::ToString(),
// enumerates all of its empty dimensions (e.g. "{ { {}, {} }, ..."), which
// is just noise.
if (ShapeUtil::IsZeroElementArray(shape)) {
return StrFormat("{} (%s)", ShapeUtil::HumanString(constant->shape()));
}
// Print the literal value of constants with <= K elements. Note that we
// use `constant->shape()` rather than `shape`, because if `constant` is a
// scalar that's broadcasted into `shape`, we want to print the constant.
optional<int64> elem_count;
if (shape.IsArray()) {
elem_count = ShapeUtil::ElementsIn(constant->shape());
}
// Allow HloDotDumper to print HloInstruction reconstructed from HloProto
// collected from profiling tools. Those constants may not have a valid
// literal.
if (elem_count.has_value() && *elem_count <= 8 && constant->HasLiteral()) {
return StrFormat("%s %s", shape.ToString(),
constant->literal().ToStringWithoutShape());
}
// Otherwise, print e.g. "%constant.42 (s32[100])".
string constant_name;
if (absl::StartsWith(constant->name(), "constant")) {
constant_name = constant->name();
} else {
constant_name = StrCat("constant ", constant->name());
}
return StrFormat("%s %s", constant_name, ShapeUtil::HumanString(shape));
};
std::vector<string> lines;
for (int64 i = 0; i < instr->operand_count(); ++i) {
const HloInstruction* operand = instr->operand(i);
optional<string> operand_str;
if (const auto* constant_operand =
DynCast<HloConstantInstruction>(operand)) {
operand_str =
stringify_constant(constant_operand, constant_operand->shape());
} else if (IsFusedBroadcastOfConstantEffectiveScalar(operand)) {
operand_str = stringify_constant(
Cast<HloConstantInstruction>(operand->operand(0)), operand->shape());
} else if (ShouldMergeIntoUsers(operand)) {
// Special case: If the operand is a parameter to a fusion node and it
// always has a constant value, display it like a regular constant.
//
// For other parameters, use the parameter number rather than the proper
// name, because that's generally how people think of the node.
if (operand->opcode() == HloOpcode::kParameter) {
if (const HloConstantInstruction* constant =
TryGetFusionParameterConstant(operand)) {
operand_str = stringify_constant(constant, constant->shape());
} else {
operand_str = StrFormat("Parameter %d", operand->parameter_number());
}
} else {
operand_str = operand->name();
}
}
if (operand_str) {
if (instr->operand_count() > 1) {
lines.push_back(StrFormat("<b>operand %d</b> = %s", i, *operand_str));
} else {
lines.push_back(StrFormat("<b>operand</b> = %s", *operand_str));
}
}
}
return StrJoin(lines, "<br/>");
}
ColorScheme HloDotDumper::GetInstructionColor(const HloInstruction* instr) {
if (debug_options_.xla_hlo_graph_sharding_color()) {
if (!instr->has_sharding()) {
return kDashedBorder;
}
auto it = sharding_colors_.find(instr->sharding());
if (it != sharding_colors_.end()) {
return it->second;
}
ColorScheme color = static_cast<ColorScheme>(
kBlue + (next_shard_color_++ % (kDashedBorder - kBlue)));
sharding_colors_.emplace(instr->sharding(), color);
return color;
}
// Choose different weights of orange for small vs large parameters. This
// distinction is often important, especially in fusion nodes.
auto parameter_color = IsSmall(instr) ? kOrange : kDarkOrange;
// Special case: If this instruction has a parameter merged into it, paint it
// the same color as a parameter. Unless the merged-in parameter is a
// parameter to a fusion node that is bound to a constant -- these aren't
// "real" parameters from the user's perspective.
if (absl::c_any_of(instr->operands(), [&](const HloInstruction* operand) {
return operand->opcode() == HloOpcode::kParameter &&
ShouldMergeIntoUsers(operand) &&
TryGetFusionParameterConstant(operand) == nullptr;
})) {
return parameter_color;
}
// Pick different colors or shapes for instructions which are particularly
// expensive (eg, dot) and those which are unusual in some way or unique
// (eg, parameter).
switch (instr->opcode()) {
case HloOpcode::kAbs:
case HloOpcode::kAdd:
case HloOpcode::kAnd:
case HloOpcode::kAtan2:
case HloOpcode::kBitcastConvert:
case HloOpcode::kCeil:
case HloOpcode::kClamp:
case HloOpcode::kClz:
case HloOpcode::kCompare:
case HloOpcode::kComplex:
case HloOpcode::kConvert:
case HloOpcode::kCos:
case HloOpcode::kDivide:
case HloOpcode::kExp:
case HloOpcode::kExpm1:
case HloOpcode::kFloor:
case HloOpcode::kImag:
case HloOpcode::kIota:
case HloOpcode::kIsFinite:
case HloOpcode::kLog:
case HloOpcode::kLog1p:
case HloOpcode::kMaximum:
case HloOpcode::kMinimum:
case HloOpcode::kMultiply:
case HloOpcode::kNegate:
case HloOpcode::kNot:
case HloOpcode::kPopulationCount:
case HloOpcode::kOr:
case HloOpcode::kXor:
case HloOpcode::kPower:
case HloOpcode::kReal:
case HloOpcode::kRemainder:
case HloOpcode::kRng:
case HloOpcode::kRngGetAndUpdateState:
case HloOpcode::kRngBitGenerator:
case HloOpcode::kRoundNearestAfz:
case HloOpcode::kRsqrt:
case HloOpcode::kSelect:
case HloOpcode::kShiftLeft:
case HloOpcode::kShiftRightArithmetic:
case HloOpcode::kShiftRightLogical:
case HloOpcode::kLogistic:
case HloOpcode::kSign:
case HloOpcode::kSin:
case HloOpcode::kSlice:
case HloOpcode::kSort:
case HloOpcode::kSqrt:
case HloOpcode::kCbrt:
case HloOpcode::kSubtract:
case HloOpcode::kTanh:
// De-emphasize scalar-shaped elementwise ops -- they're generally
// uninteresting.
if (ShapeUtil::IsEffectiveScalar(instr->shape())) {
return kWhite;
}
return kYellow;
case HloOpcode::kBitcast:
case HloOpcode::kGetTupleElement:
case HloOpcode::kTrace:
case HloOpcode::kAfterAll:
case HloOpcode::kAddDependency:
case HloOpcode::kTuple:
return kWhite;
case HloOpcode::kBroadcast:
// De-emphasize nodes which broadcast a scalar within a fusion node --
// these are essentially free.
if (instr->IsFused() &&
ShapeUtil::IsEffectiveScalar(instr->operand(0)->shape())) {
return kWhite;
}
return kGreen;
case HloOpcode::kConcatenate:
case HloOpcode::kDynamicSlice:
case HloOpcode::kGather:
case HloOpcode::kPad:
case HloOpcode::kReshape:
case HloOpcode::kDynamicReshape:
case HloOpcode::kReverse:
case HloOpcode::kTupleSelect:
case HloOpcode::kTranspose:
// De-emphasize scalar-shaped data movement ops and all data movement ops
// inside fusion nodes, both of which are essentially free.
if (ShapeUtil::IsEffectiveScalar(instr->shape()) || instr->IsFused()) {
return kWhite;
}
return kGreen;
case HloOpcode::kDynamicUpdateSlice:
// Unlike the data-movement ops above, dynamic-update-slice is not ~free
// inside of fusion nodes, so we de-emphasize it only if it's
// scalar-shaped.
if (ShapeUtil::IsEffectiveScalar(instr->shape())) {
return kWhite;
}
return kGreen;
case HloOpcode::kScatter:
// Do not de-emphasize Scatter, since it involves significant work.
case HloOpcode::kCopy:
case HloOpcode::kCopyStart:
case HloOpcode::kCopyDone:
// Emphasize copy nodes, which are either physical transposes (and thus
// significant), or copies of read-only buffers (and thus dead weight).
return kGreen;
case HloOpcode::kConvolution:
case HloOpcode::kDot:
case HloOpcode::kFft:
case HloOpcode::kTriangularSolve:
case HloOpcode::kCholesky:
return kDarkBlue;
case HloOpcode::kReducePrecision:
return kRed;
case HloOpcode::kParameter:
return parameter_color;
case HloOpcode::kBatchNormGrad:
case HloOpcode::kBatchNormInference:
case HloOpcode::kBatchNormTraining:
case HloOpcode::kReduce:
case HloOpcode::kReduceWindow:
case HloOpcode::kSelectAndScatter:
return kPurple;
case HloOpcode::kDomain:
case HloOpcode::kFusion:
case HloOpcode::kMap:
case HloOpcode::kGetDimensionSize:
case HloOpcode::kSetDimensionSize:
return kGray;
case HloOpcode::kAllGather:
case HloOpcode::kAllReduce:
case HloOpcode::kAllToAll:
case HloOpcode::kCollectivePermute:
case HloOpcode::kCollectivePermuteStart:
case HloOpcode::kCollectivePermuteDone:
case HloOpcode::kInfeed:
case HloOpcode::kOutfeed:
case HloOpcode::kPartitionId:
case HloOpcode::kRecv:
case HloOpcode::kRecvDone:
case HloOpcode::kSend:
case HloOpcode::kSendDone:
case HloOpcode::kReplicaId:
return kBrown;
case HloOpcode::kCall:
case HloOpcode::kConditional:
case HloOpcode::kCustomCall:
case HloOpcode::kWhile:
return kDarkGreen;
case HloOpcode::kConstant:
LOG(FATAL) << "Constants don't get their own nodes in the graph.";
}
}
string HloDotDumper::GetInstructionNodeShape(const HloInstruction* instr) {
// Give while loops a different shape so they're easier to pick out.
switch (instr->opcode()) {
case HloOpcode::kWhile:
return "ellipse";
default:
return "rect";
}
}
string HloDotDumper::GetInstructionNodeLabel(const HloInstruction* instr) {
// If we have a parameter, put the param number in the name.
if (instr->opcode() == HloOpcode::kParameter) {
return StrFormat("<b>Parameter %d</b>", instr->parameter_number());
}
// The HLO instruction name contains usually the opcode, e.g. "%add.42" is
// an add instruction. In this case we render just the name.
if (absl::StartsWith(instr->name(), HloOpcodeString(instr->opcode()))) {
return StrFormat("<b>%s</b>", HtmlLikeStringSanitize(instr->name()));
}
string extended_opcode =
StrCat(HloOpcodeString(instr->opcode()),
instr->opcode() != HloOpcode::kFusion
? ""
: StrCat(":", xla::ToString(instr->fusion_kind())));
// If the name does not contain the opcode, render both.
return StrFormat("<b>%s</b><br/>%s", HtmlLikeStringSanitize(extended_opcode),
HtmlLikeStringSanitize(instr->name()));
}
string HloDotDumper::GetInstructionNodeMetadata(const HloInstruction* instr) {
std::vector<string> lines;
if (!instr->metadata().op_name().empty()) {
lines.push_back(HtmlLikeStringSanitize(instr->metadata().op_name()));
}
if (!instr->metadata().op_type().empty()) {
lines.push_back(StrFormat(
"op_type: %s", HtmlLikeStringSanitize(instr->metadata().op_type())));
}
if (!instr->metadata().source_file().empty() &&
instr->metadata().source_line() != 0) {
lines.push_back(StrFormat("op_type: %s:%d", instr->metadata().source_file(),
instr->metadata().source_line()));
}
return StrJoin(lines, "\n");
}
string HloDotDumper::GetInstructionNodeBackendConfig(
const HloInstruction* instr) {
if (!hlo_render_options_.show_backend_config ||
instr->raw_backend_config_string().empty()) {
return "";
}
return StrCat("backend_config=\"", instr->raw_backend_config_string(), "\"");
}
string HloDotDumper::GetInstructionNodeExtraInfo(const HloInstruction* instr) {
std::vector<string> lines;
// Get the instruction's extra attributes excluding the names of its
// subcomputations, since those are drawn explicitly in the graph.
for (const auto& line : instr->ExtraAttributesToString(
HloPrintOptions().set_print_subcomputation_mode(
HloPrintOptions::PrintSubcomputationMode::kOff))) {
// Some instructions have giant replica group fields, so truncate the
// replica group line length to 128.
constexpr int kMaxReplicaGroupLen = 128;
if (absl::StartsWith(line, "replica_groups=") &&
line.length() > kMaxReplicaGroupLen) {
lines.push_back(HtmlLikeStringSanitize(
StrCat(line.substr(0, kMaxReplicaGroupLen - 3), "...")));
} else {
lines.push_back(HtmlLikeStringSanitize(line));
}
}
// Show the shape and layout of the instruction, unless it's an inlined fusion
// node -- there the shape and layout is present in the output node.
if (instr->opcode() != HloOpcode::kFusion ||
!ShouldShowFusionSubcomputation(instr)) {
// Show layout of instructions with more than one dimension. Don't show
// layout on tuples or tensors with just one dimension (which only have one
// possible layout) to avoid visual noise.
bool shape_is_multidim = false;
ShapeUtil::ForEachSubshape(instr->shape(),
[&](const Shape& s, const ShapeIndex&) {
shape_is_multidim |= s.dimensions_size() > 1;
});
string instr_shape;
if (instr->opcode() != HloOpcode::kTuple && shape_is_multidim) {
instr_shape = ShapeUtil::HumanStringWithLayout(instr->shape());
} else {
instr_shape = ShapeUtil::HumanString(instr->shape());
}
// Some instructions have giant tuples as their shapes, so truncate the
// HLO's shape to kMaxShapeLen characters.
constexpr int kMaxShapeLen = 64;
if (instr_shape.length() > kMaxShapeLen) {
instr_shape = StrCat(
absl::string_view(instr_shape).substr(0, kMaxShapeLen - 3), "...");
}
lines.push_back(HtmlLikeStringSanitize(instr_shape));
}
if (debug_options_.xla_hlo_graph_addresses()) {
lines.push_back(StrFormat("[%p]", instr));
}
if (profile_ != nullptr) {
double hlo_cycles_executed = profile_->GetCyclesTakenBy(*instr);
double total_cycles_executed =
profile_->total_cycles_executed(*instr->parent());
if (hlo_cycles_executed > 0 && total_cycles_executed > 0) {
lines.push_back(
StrFormat("%% of cycles executed=%.2f",
100 * hlo_cycles_executed / total_cycles_executed));
}
}
return StrJoin(lines, "<br/>");
}
void HloDotDumper::AddInstructionIncomingEdges(const HloInstruction* instr) {
auto add_edge = [&](const HloInstruction* from, const HloInstruction* to,
int64 operand_num, bool control_edge = false) {
from = GetNodeForEdge(from);
if (!filter_.Show(from) || from->opcode() == HloOpcode::kConstant ||
IsFusedBroadcastOfConstantEffectiveScalar(from) ||
ShouldMergeIntoUsers(from)) {
return;
}
VLOG(2) << "Adding edge from " << from->name() << " to " << to->name()
<< " as " << next_edge_id_;
edge_ids_.insert({{from, to}, next_edge_id_++});
string edge_label;
if (instr->operand_count() > 1 && !control_edge) {
edge_label =
StrFormat(R"( headlabel="%d", labeldistance=2)", operand_num);
} else if (control_edge) {
edge_label = "style=\"dotted\" color=\"gray\" label=\"ctrl\"";
}
// We print "small" arrays using a hollow arrowhead and "large" arrays using
// a filled arrowhead.
constexpr char kEdgeFmt[] =
R"(%s -> %s [arrowhead=%s tooltip="%s -> %s" %s];)";
edges_.push_back(StrFormat(kEdgeFmt, InstructionId(from), InstructionId(to),
(IsSmall(from) ? "empty" : "normal"),
from->name(), to->name(), edge_label));
};
// Add edges from instr's operands to instr. Parameters within fusion
// expressions are handled specially -- we draw an edge from the corresponding
// operand on the fusion node itself to the parameter.
if (instr->opcode() == HloOpcode::kParameter && instr->IsFused()) {
// Only add the edge if this is not the outermost computation; otherwise it
// will lead from a node we're not drawing.
if (instr->parent() != computation_) {
const HloInstruction* fusion = instr->parent()->FusionInstruction();
add_edge(fusion->operand(instr->parameter_number()), instr,
/*operand_num=*/0);
}
} else {
for (int64 i = 0; i < instr->operand_count(); ++i) {
add_edge(instr->operand(i), instr, i);
}
for (const HloInstruction* pred : instr->control_predecessors()) {
add_edge(pred, instr, /*operand_num=*/0, /*control_edge=*/true);
}
}
}
string HloDotDumper::GetInstructionTrivialComputationStr(
const HloInstruction* instr) {
// called_computations() on a fusion node "inherits" any called computations
// of the fused root, which isn't what we want. Just ignore fusion nodes
// here; they're handled separately.
if (instr->opcode() == HloOpcode::kFusion) {
return "";
}
std::vector<string> lines;
for (int64 i = 0; i < instr->called_computations().size(); ++i) {
optional<string> computation_type =
MatchTrivialComputation(instr->called_computations()[i]);
if (!computation_type) {
continue;
}
if (instr->called_computations().size() == 1) {
lines.push_back(StrFormat("Subcomputation: <b>%s</b>",
HtmlLikeStringSanitize(*computation_type)));
} else {
lines.push_back(StrFormat("Subcomputation %d: <b>%s</b>", i,
HtmlLikeStringSanitize(*computation_type)));
}
}
return StrJoin(lines, "<br/>");
}
const HloInstruction* HloDotDumper::GetNodeForEdge(
const HloInstruction* instr) {
while (instr->opcode() == HloOpcode::kFusion &&
ShouldShowFusionSubcomputation(instr)) {
instr = instr->fused_expression_root();
}
return instr;
}
// Gets a NodeFilter that includes roughly all instructions whose distance from
// root is <= radius.
NodeFilter MakeNodeRadiusAroundFilter(
const HloInstruction* root, int64 radius,
const absl::flat_hash_set<const HloInstruction*>& boundary) {
// First, find the neighborhood of nodes with distance from root <= radius.
// These nodes are our initial set of "normal" nodes.
absl::flat_hash_map<const HloInstruction*, NodeFilterResult> nodes;
std::deque<std::pair<const HloInstruction*, /*depth*/ int64>> worklist;
worklist.push_back({root, 0});
while (!worklist.empty()) {
const HloInstruction* instr;
int64 depth;
std::tie(instr, depth) = worklist.front();
worklist.pop_front();
nodes[instr] = kNormalNode;
if (depth == radius) {
continue;
}
if (boundary.contains(instr)) {
continue;
}
// Traverse into instr's operands.
//
// Don't traverse into tuples' operands unless the tuple is the root.
// Usually a tuple is the bottommost node in the graph, and so its operands
// are not interesting to the graph at hand.
if (instr == root || instr->opcode() != HloOpcode::kTuple) {
for (const HloInstruction* operand : instr->operands()) {
if (!nodes.contains(operand)) {
worklist.push_back({operand, depth + 1});
}
}
}
// Traverse into instr's nested computations.
for (const HloComputation* computation : instr->called_computations()) {
worklist.push_back({computation->root_instruction(), depth + 1});
}
// Traverse into instr's users, unless:
//
// - there are a ton of them, in which case they're probably not
// interesting (and anyway, rendering them all would make the graph
// unreadable), or
// - instr is a constant, in which case its users are probably not
// interesting.
if (instr->opcode() == HloOpcode::kConstant) {
continue;
}
constexpr int kMaxUsersToRender = 16;
if (instr->user_count() > kMaxUsersToRender) {
// If we're going to skip this node's users, style it as such.
nodes[instr] = kSomeUsersOmitted;
continue;
}
for (const HloInstruction* user : instr->users()) {
if (!nodes.contains(user)) {
worklist.push_back({user, depth + 1});
}
}
}
auto is_displayed = [&](const HloInstruction* instr) {
// Constants are displayed inline with their users; they're never omitted.
// Nodes in subcomputations are always shown.
return nodes.contains(instr) || instr->opcode() == HloOpcode::kConstant ||
instr->parent() != root->parent();
};
// Make a second pass over 'nodes' to fix up the NodeFilterResults now that we
// know which nodes will be included in the graph.
for (auto& kv : nodes) {
const HloInstruction* instr = kv.first;
NodeFilterResult& filter_result = kv.second;
const auto& operands = instr->operands();
if (absl::c_any_of(operands, is_displayed) &&
!absl::c_all_of(operands, is_displayed)) {
// Mark nodes with some operands omitted appropriately.
filter_result = kSomeOperandsOmitted;
} else if (!operands.empty() && absl::c_none_of(operands, is_displayed)) {
// Mark nodes with *all* operands omitted appropriately.
filter_result = kOmitNodeOperands;
}
// Promote nodes with type kSomeUsersOmitted to kNormalNode if all of their
// users made it into the graph.
if (filter_result == kSomeUsersOmitted &&
absl::c_all_of(instr->users(), is_displayed)) {
filter_result = kNormalNode;
}
}
// Highlight the root node.
nodes[root] = kHighlightNode;
return NodeFilter([=](const HloInstruction* instr) {
auto it = nodes.find(instr);
if (it != nodes.end()) {
return it->second;
}
// Show all nodes in subcomputations.
if (instr->parent() != root->parent()) {
return kNormalNode;
}
return kHideNode;
});
}
// Gets a node filter that includes nodes on all paths from `from` to `to`. If
// the all-paths set contains more than max_nodes elements, includes the nodes
// on the shortest paths and sets hit_limit to true.
NodeFilter MakeNodeFromToFilter(const HloInstruction* from,
const HloInstruction* to, int64 max_nodes,
bool* hit_limit) {
*hit_limit = false;
// Elements in the queue are paths through the graph.
std::deque<std::vector<const HloInstruction*>> queue;
queue.push_front({from});
// Compute the set of nodes we want to show using a slightly-modified
// Djikstra's algorithm. The only real difference is, rather than stopping
// when we find a (shortest) path, we continue until we've found max_nodes
// nodes on some path.
std::unordered_set<const HloInstruction*> visited;
std::unordered_set<const HloInstruction*> to_display = {from, to};
while (!queue.empty() && to_display.size() < max_nodes) {
std::vector<const HloInstruction*> path = std::move(queue.front());
queue.pop_front();
if (!visited.insert(path.back()).second) {
continue;
}
for (const auto* user : path.back()->users()) {
if (user == to) {
auto it = path.begin();
for (; it != path.end() && to_display.size() < max_nodes; ++it) {
to_display.insert(*it);
}
if (it != path.end()) {
*hit_limit = true;
}
} else if (!visited.count(user)) {
auto new_path = path;
new_path.push_back(user);
queue.push_back(std::move(new_path));
}
}
}
return NodeFilter([=](const HloInstruction* instr) {
if (instr == from || instr == to) {
return kHighlightNode;
}
return to_display.count(instr) ? kNormalNode : kHideNode;
});
}
string WrapDotInHtml(absl::string_view dot) {
static const char html_prefix[] = R"html(
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
body {
height: 100vh;
margin: 0;
}
</style>
</head>
<body>
<!-- Integrity hash is generated by https://www.srihash.org/ -->
<script src="https://cdn.jsdelivr.net/npm/viz.js@2.1.1/viz.js"
integrity="sha384-aD1MJYb0WKIUT+CtwJp5LTuV3U4pLAS6B/nUxL7ECimC2pN9N8vjlMr/yQCAkzxE"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/viz.js@2.1.1/full.render.js"
integrity="sha384-bAixY275aIpCj6Te19y0MILZ4V+VEC8CVFujFEH+Lf7W+4XYYeYLwW5IBI6yQmMT"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/svg-pan-zoom@3.6.0/dist/svg-pan-zoom.min.js"
integrity="sha384-3008WpYB2pOBvE7lwkrKf+qTmbTPGGPYxA9C1YVhvbPukns4ZFj7E98QPLkNW9dS"
crossorigin="anonymous"></script>
<div id="container" style="height:95vh; border:1px solid black; "></div>
<script>
var data = `
)html";
static const char html_suffix[] = R"html(
`;
var cssregex = new RegExp('stylesheet=<([^]*)\n>\n', 'gm');
var results = cssregex.exec(data)
// graphviz has problem dealing with large stylesheets.
// https://github.com/tensorflow/tensorflow/issues/17220#issuecomment-369228492
// In order to avoid the problem, remove the stylesheet from the dot and
// insert it directly info the rendered SVG.
var dot_data = data;
var css_data = ''
if (results !== null) {
css_data = results[1].replace(/\s*data:.*\s*,/,''); // Strip content-type field.
// CSS inside DOT is URL-escaped, so we must unescape it
// before we can insert it into SVG.
css_data = unescape(css_data);
dot_data = data.replace(cssregex, ''); // Remove the stylesheet
}
var render_start = performance.now()
function add_controls(svg) {
var htmlblob = new Blob([document.documentElement.innerHTML],
{type: 'text/html'});
var savehtml = document.createElement('a');
savehtml.setAttribute('href', URL.createObjectURL(htmlblob));
savehtml.setAttribute('download', 'graph.html');
savehtml.innerHTML = " [Save HTML+SVG] ";
document.body.append(savehtml);
var svgblob = new Blob([svg.outerHTML], {type: 'image/svg'});
var savesvg = document.createElement('a');
savesvg.setAttribute('href', URL.createObjectURL(svgblob));
savesvg.setAttribute('download', 'graph.svg');
savesvg.innerHTML = " [Save SVG] ";
document.body.append(savesvg);
var dotblob = new Blob([data], {type: 'text/dot'});
var savedot = document.createElement('a');
savedot.setAttribute('href', URL.createObjectURL(dotblob));
savedot.setAttribute('download', 'graph.dot');
savedot.innerHTML = " [Save DOT] ";
document.body.append(savedot);
// Will get called after embed element was loaded
var panzoom = svgPanZoom(svg, {
zoomEnabled: true,
controlIconsEnabled: true,
});
document.getElementsByTagName("BODY")[0].onresize = function() {
panzoom.resize();
panzoom.fit();
panzoom.center();
};
var render_end = performance.now();
var render_note = document.createElement('div')
render_note.innerHTML = 'Rendering took '
+ (render_end - render_start).toFixed(2) + "ms."
document.body.append(render_note);
}
var svg = document.getElementById('graph')
if (svg == null) {
// Need to render SVG first.
var viz = new Viz();
viz.renderSVGElement(dot_data)
.then(function(svg){
var container = document.getElementById('container')
var style = document.createElementNS('http://www.w3.org/2000/svg', 'style');
var node = document.createTextNode(css_data);
style.appendChild(node);
svg.setAttribute('width', '100%');
svg.setAttribute('height', '100%');
svg.setAttribute('id', 'graph');
svg.appendChild(style);
container.appendChild(svg);
add_controls(svg);
})
} else {
// HTML already has rendered SVG embedded, so we just need to add
// controls.
add_controls(svg);
}
</script>
</body>
</html>
)html";
return absl::StrCat(html_prefix, dot, html_suffix);
}
tensorflow::mutex url_renderer_mu(tensorflow::LINKER_INITIALIZED);
std::function<StatusOr<string>(absl::string_view)>* url_renderer
TF_GUARDED_BY(url_renderer_mu) = nullptr;
// Storage for fusion visualization: (module_id, computation_id) -> sequence of
// dot dumps.
tensorflow::mutex fusion_visualizer_state_mu(tensorflow::LINKER_INITIALIZED);
static auto& fusion_visualizer_state TF_GUARDED_BY(fusion_visualizer_state_mu) =
*new absl::flat_hash_map<std::pair<int64, int64>,
std::vector<std::string>>();
// Generates a key to the fusion visualizer state mapping.
std::pair<int, int> FusionVisualizerStateKey(
const HloComputation& computation) {
return std::make_pair(computation.parent()->unique_id(),
computation.unique_id());
}
// Generates a fusion explorer for the given computation using the data in
// fusion_visualizer_state and the URL renderer. Precondition: url_renderer !=
// nullptr.
StatusOr<std::string> WrapFusionExplorer(const HloComputation& computation)
TF_EXCLUSIVE_LOCKS_REQUIRED(url_renderer_mu) {
CHECK(url_renderer != nullptr);
tensorflow::mutex_lock lock(fusion_visualizer_state_mu);
const std::vector<std::string>& dot_graphs =
fusion_visualizer_state[FusionVisualizerStateKey(computation)];
std::vector<std::string> dot_urls;
dot_urls.reserve(dot_graphs.size());
for (const std::string& dot : dot_graphs) {
TF_ASSIGN_OR_RETURN(std::string url, (*url_renderer)(dot));
dot_urls.push_back(url);
}
return absl::StrReplaceAll(
R"(
<!doctype html>
<style>
html, body {height: 100%; text-align: center;}
#display {height: 80%; width: 80%;}
</style>
<title>Fusion Explorer: $TITLE</title>
<iframe id='display' width=80% height=80%></iframe>
<p id='description'></p>
<p>
<a id='prev' href='#'>Prev Step</a>
<a id='next' href='#'>Next Step</a>
</p>
<p>
Use j/k for keyboard navigation.
</p>
<script>
var currId = -1;
var urls = [$URLS];
var setIframe = function() {
document.getElementById('display').src = urls[currId];
};
var update = function(delta) {
currId = (currId + delta + urls.length) % urls.length;
document.getElementById('description').innerHTML = "Frame #"
+ (currId + 1) + " / " + urls.length;
setIframe();
};
document.getElementById('prev').onclick = function() {
update(-1);
return false;
};
document.getElementById('next').onclick = function() {
update(1);
return false;
};
window.addEventListener("keydown", function (event) {
if (event.defaultPrevented) {
return;
}
if (event.key == "j") {
update(1);
} else if (event.key == "k") {
update(-1);
} else {
return;
}
event.preventDefault();
}, true);
document.addEventListener("DOMContentLoaded", function() {
update(1);
});
</script>
)",
{{"$URLS", absl::StrJoin(dot_urls, ", ",
[&](std::string* out, const std::string& url) {
absl::StrAppend(out, "\"", url, "\"");
})},
{"$TITLE",
absl::StrCat(computation.parent()->name(), "_", computation.name())}});
}
// Precondition: (url_renderer != nullptr || (format != kUrl
// && format != kFusionVisualization)).
//
// (We specify this as a precondition rather than checking it in here and
// returning an error because we want to fail quickly when there's no URL
// renderer available, and this function runs only after we've done all the work
// of producing dot for the graph.)
StatusOr<string> WrapDotInFormat(const HloComputation& computation,
absl::string_view dot,
RenderedGraphFormat format)
TF_EXCLUSIVE_LOCKS_REQUIRED(url_renderer_mu) {
switch (format) {
case RenderedGraphFormat::kUrl:
CHECK(url_renderer != nullptr)
<< "Should have checked url_renderer != null before calling.";
return (*url_renderer)(dot);
case RenderedGraphFormat::kHtml:
return WrapDotInHtml(dot);
case RenderedGraphFormat::kDot:
return string(dot);
case RenderedGraphFormat::kFusionVisualization:
return WrapFusionExplorer(computation);
}
}
} // namespace
void RegisterGraphToURLRenderer(
std::function<StatusOr<string>(absl::string_view)> renderer) {
tensorflow::mutex_lock lock(url_renderer_mu);
if (url_renderer != nullptr) {
LOG(WARNING) << "Multiple calls to RegisterGraphToURLRenderer. Last call "
"wins, but because order of initialization in C++ is "
"nondeterministic, this may not be what you want.";
}
delete url_renderer;
url_renderer = new std::function<StatusOr<string>(absl::string_view)>(
std::move(renderer));
}
Status RegisterFusionState(const HloComputation& computation,
absl::string_view label) {
tensorflow::mutex_lock lock(fusion_visualizer_state_mu);
TF_ASSIGN_OR_RETURN(
string dot_graph,
RenderGraph(computation,
absl::StrCat(computation.parent()->name(), ", ",
computation.name(), ", ", label),
/*debug_options=*/{}, xla::RenderedGraphFormat::kDot,
/*hlo_execution_profile=*/nullptr,
/*hlo_render_options=*/{}));
std::vector<std::string>& fusion_states =
fusion_visualizer_state[FusionVisualizerStateKey(computation)];
if (fusion_states.empty() || fusion_states.back() != dot_graph) {
fusion_states.push_back(dot_graph);
}
return Status::OK();
}
StatusOr<string> RenderGraph(const HloComputation& computation,
absl::string_view label,
const DebugOptions& debug_options,
RenderedGraphFormat format,
const HloExecutionProfile* hlo_execution_profile,
HloRenderOptions hlo_render_options) {
tensorflow::mutex_lock lock(url_renderer_mu);
if (format == RenderedGraphFormat::kUrl && url_renderer == nullptr) {
return Unavailable("Can't render as URL; no URL renderer was registered.");
}
string rendered_dot =
HloDotDumper(&computation, label, debug_options, hlo_render_options,
hlo_execution_profile, NodeFilter())
.Dump();
return WrapDotInFormat(computation, rendered_dot, format);
}
StatusOr<string> RenderNeighborhoodAround(
const HloInstruction& node, int radius, RenderedGraphFormat format,
HloRenderOptions hlo_render_options,
const absl::flat_hash_set<const HloInstruction*>& boundary) {
tensorflow::mutex_lock lock(url_renderer_mu);
if (format == RenderedGraphFormat::kUrl && url_renderer == nullptr) {
return FailedPrecondition(
"Can't render as URL; no URL renderer was registered.");
}
string label =
StrCat("Neighborhood of ", radius, " nodes around ", node.name());
string rendered_dot =
HloDotDumper(node.parent(), label,
node.GetModule()->config().debug_options(),
hlo_render_options, /*profile=*/nullptr,
MakeNodeRadiusAroundFilter(&node, radius, boundary))
.Dump();
return WrapDotInFormat(*node.parent(), rendered_dot, format);
}
StatusOr<string> RenderAllPathsFromTo(const HloInstruction& from,
const HloInstruction& to, int64 max_nodes,
RenderedGraphFormat format,
HloRenderOptions hlo_render_options) {
tensorflow::mutex_lock lock(url_renderer_mu);
if (format == RenderedGraphFormat::kUrl && url_renderer == nullptr) {
return FailedPrecondition(
"Can't render as URL; no URL renderer was registered.");
}
CHECK_EQ(from.parent(), to.parent()) << "Nodes must be in same computation!";
auto debug_options = from.GetModule()->config().debug_options();
bool hit_limit = false;
NodeFilter filter = MakeNodeFromToFilter(&from, &to, max_nodes, &hit_limit);
string label;
if (!hit_limit) {
label = StrCat("All paths from ", from.name(), " to ", to.name());
} else {
label = StrCat(max_nodes, " nodes on the shortest paths from ", from.name(),
" to ", to.name(),
"<br/><br/>***SHOWING ONLY A SUBSET OF ALL PATHS BETWEEN "
"NODES***<br/><br/>");
}
string rendered_dot =
HloDotDumper(from.parent(), label, debug_options, hlo_render_options,
/*profile=*/nullptr, filter)
.Dump();
return WrapDotInFormat(*from.parent(), rendered_dot, format);
}
} // namespace xla
|
/*
Copyright (c) 2010-2014, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Universite de Sherbrooke nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef UTIL3D_HPP_
#define UTIL3D_HPP_
#include <rtabmap/utilite/ULogger.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/filters/random_sample.h>
#include <pcl/filters/passthrough.h>
#include <pcl/filters/filter.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/common/transforms.h>
#include <pcl/common/common.h>
#include <pcl/search/kdtree.h>
#include <pcl/features/normal_3d.h>
#include <pcl/segmentation/extract_clusters.h>
namespace rtabmap{
namespace util3d{
template<typename PointT>
typename pcl::PointCloud<PointT>::Ptr voxelize(
const typename pcl::PointCloud<PointT>::Ptr & cloud,
float voxelSize)
{
typedef typename pcl::PointCloud<PointT> PointCloud;
typedef typename PointCloud::Ptr PointCloudPtr;
UASSERT(voxelSize > 0.0f);
PointCloudPtr output(new PointCloud);
pcl::VoxelGrid<PointT> filter;
filter.setLeafSize(voxelSize, voxelSize, voxelSize);
filter.setInputCloud(cloud);
filter.filter(*output);
return output;
}
template<typename PointT>
typename pcl::PointCloud<PointT>::Ptr sampling(
const typename pcl::PointCloud<PointT>::Ptr & cloud, int samples)
{
typedef typename pcl::PointCloud<PointT> PointCloud;
typedef typename PointCloud::Ptr PointCloudPtr;
UASSERT(samples > 0);
PointCloudPtr output(new PointCloud);
pcl::RandomSample<PointT> filter;
filter.setSample(samples);
filter.setInputCloud(cloud);
filter.filter(*output);
return output;
}
template<typename PointT>
typename pcl::PointCloud<PointT>::Ptr passThrough(
const typename pcl::PointCloud<PointT>::Ptr & cloud,
const std::string & axis,
float min,
float max)
{
typedef typename pcl::PointCloud<PointT> PointCloud;
typedef typename PointCloud::Ptr PointCloudPtr;
UASSERT(max > min);
UASSERT(axis.compare("x") == 0 || axis.compare("y") == 0 || axis.compare("z") == 0);
PointCloudPtr output(new PointCloud);
pcl::PassThrough<PointT> filter;
filter.setFilterFieldName(axis);
filter.setFilterLimits(min, max);
filter.setInputCloud(cloud);
filter.filter(*output);
return output;
}
template<typename PointT>
typename pcl::PointCloud<PointT>::Ptr removeNaNFromPointCloud(
const typename pcl::PointCloud<PointT>::Ptr & cloud)
{
typedef typename pcl::PointCloud<PointT> PointCloud;
typedef typename PointCloud::Ptr PointCloudPtr;
PointCloudPtr output(new PointCloud);
std::vector<int> indices;
pcl::removeNaNFromPointCloud<PointT>(*cloud, *output, indices);
return output;
}
template<typename PointT>
typename pcl::PointCloud<PointT>::Ptr removeNaNNormalsFromPointCloud(
const typename pcl::PointCloud<PointT>::Ptr & cloud)
{
typedef typename pcl::PointCloud<PointT> PointCloud;
typedef typename PointCloud::Ptr PointCloudPtr;
PointCloudPtr output(new PointCloud);
std::vector<int> indices;
pcl::removeNaNNormalsFromPointCloud<PointT>(*cloud, *output, indices);
return output;
}
template<typename PointT>
typename pcl::PointCloud<PointT>::Ptr transformPointCloud(
const typename pcl::PointCloud<PointT>::Ptr & cloud,
const Transform & transform)
{
typedef typename pcl::PointCloud<PointT> PointCloud;
typedef typename PointCloud::Ptr PointCloudPtr;
PointCloudPtr output(new PointCloud);
pcl::transformPointCloud<PointT>(*cloud, *output, transform.toEigen4f());
return output;
}
template<typename PointT>
PointT transformPoint(
const PointT & pt,
const Transform & transform)
{
return pcl::transformPoint(pt, transform.toEigen3f());
}
template<typename PointT>
void segmentObstaclesFromGround(
const typename pcl::PointCloud<PointT>::Ptr & cloud,
pcl::IndicesPtr & ground,
pcl::IndicesPtr & obstacles,
float normalRadiusSearch,
float groundNormalAngle,
int minClusterSize,
bool segmentFlatObstacles)
{
ground.reset(new std::vector<int>);
obstacles.reset(new std::vector<int>);
// Find the ground
pcl::IndicesPtr flatSurfaces = util3d::normalFiltering<PointT>(
cloud,
groundNormalAngle,
Eigen::Vector4f(0,0,1,0),
normalRadiusSearch*2.0f,
Eigen::Vector4f(0,0,100,0));
if(segmentFlatObstacles)
{
int biggestFlatSurfaceIndex;
std::vector<pcl::IndicesPtr> clusteredFlatSurfaces = util3d::extractClusters<PointT>(
cloud,
flatSurfaces,
normalRadiusSearch*2.0f,
minClusterSize,
std::numeric_limits<int>::max(),
&biggestFlatSurfaceIndex);
// cluster all surfaces for which the centroid is in the Z-range of the bigger surface
ground = clusteredFlatSurfaces.at(biggestFlatSurfaceIndex);
Eigen::Vector4f min,max;
pcl::getMinMax3D<PointT>(*cloud, *clusteredFlatSurfaces.at(biggestFlatSurfaceIndex), min, max);
for(unsigned int i=0; i<clusteredFlatSurfaces.size(); ++i)
{
if((int)i!=biggestFlatSurfaceIndex)
{
Eigen::Vector4f centroid;
pcl::compute3DCentroid<PointT>(*cloud, *clusteredFlatSurfaces.at(i), centroid);
if(centroid[2] >= min[2] && centroid[2] <= max[2])
{
ground = util3d::concatenate(ground, clusteredFlatSurfaces.at(i));
}
}
}
}
else
{
ground = flatSurfaces;
}
if(ground->size() != cloud->size())
{
// Remove ground
pcl::IndicesPtr otherStuffIndices = util3d::extractNegativeIndices<PointT>(cloud, ground);
//Cluster remaining stuff (obstacles)
std::vector<pcl::IndicesPtr> clusteredObstaclesSurfaces = util3d::extractClusters<PointT>(
cloud,
otherStuffIndices,
normalRadiusSearch*2.0f,
minClusterSize);
// merge indices
obstacles = util3d::concatenate(clusteredObstaclesSurfaces);
}
}
template<typename PointT>
void projectCloudOnXYPlane(
typename pcl::PointCloud<PointT>::Ptr & cloud)
{
for(unsigned int i=0; i<cloud->size(); ++i)
{
cloud->at(i).z = 0;
}
}
template<typename PointT>
pcl::IndicesPtr radiusFiltering(
const typename pcl::PointCloud<PointT>::Ptr & cloud,
float radiusSearch,
int minNeighborsInRadius)
{
pcl::IndicesPtr indices(new std::vector<int>);
return radiusFiltering<PointT>(cloud, indices, radiusSearch, minNeighborsInRadius);
}
template<typename PointT>
pcl::IndicesPtr radiusFiltering(
const typename pcl::PointCloud<PointT>::Ptr & cloud,
const pcl::IndicesPtr & indices,
float radiusSearch,
int minNeighborsInRadius)
{
typedef typename pcl::search::KdTree<PointT> KdTree;
typedef typename KdTree::Ptr KdTreePtr;
KdTreePtr tree (new KdTree(false));
if(indices->size())
{
pcl::IndicesPtr output(new std::vector<int>(indices->size()));
int oi = 0; // output iterator
tree->setInputCloud(cloud, indices);
for(unsigned int i=0; i<indices->size(); ++i)
{
std::vector<int> kIndices;
std::vector<float> kDistances;
int k = tree->radiusSearch(cloud->at(indices->at(i)), radiusSearch, kIndices, kDistances);
if(k > minNeighborsInRadius)
{
output->at(oi++) = indices->at(i);
}
}
output->resize(oi);
return output;
}
else
{
pcl::IndicesPtr output(new std::vector<int>(cloud->size()));
int oi = 0; // output iterator
tree->setInputCloud(cloud);
for(unsigned int i=0; i<cloud->size(); ++i)
{
std::vector<int> kIndices;
std::vector<float> kDistances;
int k = tree->radiusSearch(cloud->at(i), radiusSearch, kIndices, kDistances);
if(k > minNeighborsInRadius)
{
output->at(oi++) = i;
}
}
output->resize(oi);
return output;
}
}
template<typename PointT>
pcl::IndicesPtr normalFiltering(
const typename pcl::PointCloud<PointT>::Ptr & cloud,
float angleMax,
const Eigen::Vector4f & normal,
float radiusSearch,
const Eigen::Vector4f & viewpoint)
{
pcl::IndicesPtr indices(new std::vector<int>);
return normalFiltering<PointT>(cloud, indices, angleMax, normal, radiusSearch, viewpoint);
}
template<typename PointT>
pcl::IndicesPtr normalFiltering(
const typename pcl::PointCloud<PointT>::Ptr & cloud,
const pcl::IndicesPtr & indices,
float angleMax,
const Eigen::Vector4f & normal,
float radiusSearch,
const Eigen::Vector4f & viewpoint)
{
typedef typename pcl::search::KdTree<PointT> KdTree;
typedef typename KdTree::Ptr KdTreePtr;
pcl::NormalEstimation<PointT, pcl::Normal> ne;
ne.setInputCloud (cloud);
if(indices->size())
{
ne.setIndices(indices);
}
KdTreePtr tree (new KdTree(false));
if(indices->size())
{
tree->setInputCloud(cloud, indices);
}
else
{
tree->setInputCloud(cloud);
}
ne.setSearchMethod (tree);
pcl::PointCloud<pcl::Normal>::Ptr cloud_normals (new pcl::PointCloud<pcl::Normal>);
ne.setRadiusSearch (radiusSearch);
if(viewpoint[0] != 0 || viewpoint[1] != 0 || viewpoint[2] != 0)
{
ne.setViewPoint(viewpoint[0], viewpoint[1], viewpoint[2]);
}
ne.compute (*cloud_normals);
pcl::IndicesPtr output(new std::vector<int>(cloud_normals->size()));
int oi = 0; // output iterator
Eigen::Vector3f n(normal[0], normal[1], normal[2]);
for(unsigned int i=0; i<cloud_normals->size(); ++i)
{
Eigen::Vector4f v(cloud_normals->at(i).normal_x, cloud_normals->at(i).normal_y, cloud_normals->at(i).normal_z, 0.0f);
float angle = pcl::getAngle3D(normal, v);
if(angle < angleMax)
{
output->at(oi++) = indices->size()!=0?indices->at(i):i;
}
}
output->resize(oi);
return output;
}
template<typename PointT>
std::vector<pcl::IndicesPtr> extractClusters(
const typename pcl::PointCloud<PointT>::Ptr & cloud,
float clusterTolerance,
int minClusterSize,
int maxClusterSize,
int * biggestClusterIndex)
{
pcl::IndicesPtr indices(new std::vector<int>);
return extractClusters<PointT>(cloud, indices, clusterTolerance, minClusterSize, maxClusterSize, biggestClusterIndex);
}
template<typename PointT>
std::vector<pcl::IndicesPtr> extractClusters(
const typename pcl::PointCloud<PointT>::Ptr & cloud,
const pcl::IndicesPtr & indices,
float clusterTolerance,
int minClusterSize,
int maxClusterSize,
int * biggestClusterIndex)
{
typedef typename pcl::search::KdTree<PointT> KdTree;
typedef typename KdTree::Ptr KdTreePtr;
KdTreePtr tree(new KdTree);
pcl::EuclideanClusterExtraction<PointT> ec;
ec.setClusterTolerance (clusterTolerance);
ec.setMinClusterSize (minClusterSize);
ec.setMaxClusterSize (maxClusterSize);
ec.setInputCloud (cloud);
if(indices->size())
{
ec.setIndices(indices);
tree->setInputCloud(cloud, indices);
}
else
{
tree->setInputCloud(cloud);
}
ec.setSearchMethod (tree);
std::vector<pcl::PointIndices> cluster_indices;
ec.extract (cluster_indices);
int maxIndex=-1;
unsigned int maxSize = 0;
std::vector<pcl::IndicesPtr> output(cluster_indices.size());
for(unsigned int i=0; i<cluster_indices.size(); ++i)
{
output[i] = pcl::IndicesPtr(new std::vector<int>(cluster_indices[i].indices));
if(maxSize < cluster_indices[i].indices.size())
{
maxSize = cluster_indices[i].indices.size();
maxIndex = i;
}
}
if(biggestClusterIndex)
{
*biggestClusterIndex = maxIndex;
}
return output;
}
template<typename PointT>
pcl::IndicesPtr extractNegativeIndices(
const typename pcl::PointCloud<PointT>::Ptr & cloud,
const pcl::IndicesPtr & indices)
{
pcl::IndicesPtr output(new std::vector<int>);
pcl::ExtractIndices<PointT> extract;
extract.setInputCloud (cloud);
extract.setIndices(indices);
extract.setNegative(true);
extract.filter(*output);
return output;
}
} // util3d
} // rtabmap
#endif //UTIL3D_HPP_
|
// OpenArchive.cpp
// #define SHOW_DEBUG_INFO
#ifdef SHOW_DEBUG_INFO
#include <stdio.h>
#endif
#include "../../../../C/CpuArch.h"
#include "../../../Common/ComTry.h"
#include "../../../Common/IntToString.h"
#include "../../../Common/StringConvert.h"
#include "../../../Common/StringToInt.h"
#include "../../../Common/Wildcard.h"
#include "../../../Windows/FileDir.h"
#include "../../Common/FileStreams.h"
#include "../../Common/LimitedStreams.h"
#include "../../Common/ProgressUtils.h"
#include "../../Common/StreamUtils.h"
#include "../../Compress/CopyCoder.h"
#include "DefaultName.h"
#include "OpenArchive.h"
#ifndef _SFX
#include "SetProperties.h"
#endif
#ifdef SHOW_DEBUG_INFO
#define PRF(x) x
#else
#define PRF(x)
#endif
// increase it, if you need to support larger SFX stubs
static const UInt64 kMaxCheckStartPosition = 1 << 23;
/*
Open:
- formatIndex >= 0 (exact Format)
1) Open with main type. Archive handler is allowed to use archive start finder.
Warning, if there is tail.
- formatIndex = -1 (Parser:0) (default)
- same as #1 but doesn't return Parser
- formatIndex = -2 (#1)
- file has supported extension (like a.7z)
Open with that main type (only starting from start of file).
- open OK:
- if there is no tail - return OK
- if there is tail:
- archive is not "Self Exe" - return OK with Warning, that there is tail
- archive is "Self Exe"
ignore "Self Exe" stub, and tries to open tail
- tail can be open as archive - shows that archive and stub size property.
- tail can't be open as archive - shows Parser ???
- open FAIL:
Try to open with all other types from offset 0 only.
If some open type is OK and physical archive size is uequal or larger
than file size, then return that archive with warning that can not be open as [extension type].
If extension was EXE, it will try to open as unknown_extension case
- file has unknown extension (like a.hhh)
It tries to open via parser code.
- if there is full archive or tail archive and unknown block or "Self Exe"
at front, it shows tail archive and stub size property.
- in another cases, if there is some archive inside file, it returns parser/
- in another cases, it retuens S_FALSE
- formatIndex = -3 (#2)
- same as #1, but
- stub (EXE) + archive is open in Parser
- formatIndex = -4 (#3)
- returns only Parser. skip full file archive. And show other sub-archives
- formatIndex = -5 (#4)
- returns only Parser. skip full file archive. And show other sub-archives for each byte pos
*/
using namespace NWindows;
/*
#ifdef _SFX
#define OPEN_PROPS_PARAM
#else
#define OPEN_PROPS_PARAM , props
#endif
*/
/*
CArc::~CArc()
{
GetRawProps.Release();
Archive.Release();
printf("\nCArc::~CArc()\n");
}
*/
#ifndef _SFX
namespace NArchive {
namespace NParser {
struct CParseItem
{
UInt64 Offset;
UInt64 Size;
// UInt64 OkSize;
UString Name;
UString Extension;
FILETIME FileTime;
UString Comment;
UString ArcType;
bool FileTime_Defined;
bool UnpackSize_Defined;
bool NumSubDirs_Defined;
bool NumSubFiles_Defined;
bool IsSelfExe;
bool IsNotArcType;
UInt64 UnpackSize;
UInt64 NumSubDirs;
UInt64 NumSubFiles;
int FormatIndex;
bool LenIsUnknown;
CParseItem():
LenIsUnknown(false),
FileTime_Defined(false),
UnpackSize_Defined(false),
NumSubFiles_Defined(false),
NumSubDirs_Defined(false),
IsSelfExe(false),
IsNotArcType(false)
// OkSize(0)
{}
/*
bool IsEqualTo(const CParseItem &item) const
{
return Offset == item.Offset && Size == item.Size;
}
*/
void NormalizeOffset()
{
if ((Int64)Offset < 0)
{
Size += Offset;
// OkSize += Offset;
Offset = 0;
}
}
};
class CHandler:
public IInArchive,
public IInArchiveGetStream,
public CMyUnknownImp
{
public:
CObjectVector<CParseItem> _items;
UInt64 _maxEndOffset;
CMyComPtr<IInStream> _stream;
MY_UNKNOWN_IMP2(
IInArchive,
IInArchiveGetStream)
INTERFACE_IInArchive(;)
STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
UInt64 GetLastEnd() const
{
if (_items.IsEmpty())
return 0;
const CParseItem &back = _items.Back();
return back.Offset + back.Size;
}
void AddUnknownItem(UInt64 next);
int FindInsertPos(const CParseItem &item) const;
void AddItem(const CParseItem &item);
CHandler(): _maxEndOffset(0) {}
};
int CHandler::FindInsertPos(const CParseItem &item) const
{
unsigned left = 0, right = _items.Size();
while (left != right)
{
unsigned mid = (left + right) / 2;
const CParseItem & midItem = _items[mid];
if (item.Offset < midItem.Offset)
right = mid;
else if (item.Offset > midItem.Offset)
left = mid + 1;
else if (item.Size < midItem.Size)
right = mid;
else if (item.Size > midItem.Size)
left = mid + 1;
else
{
left = mid + 1;
// return -1;
}
}
return left;
}
void CHandler::AddUnknownItem(UInt64 next)
{
/*
UInt64 prevEnd = 0;
if (!_items.IsEmpty())
{
const CParseItem &back = _items.Back();
prevEnd = back.Offset + back.Size;
}
*/
if (_maxEndOffset < next)
{
CParseItem item2;
item2.Offset = _maxEndOffset;
item2.Size = next - _maxEndOffset;
_maxEndOffset = next;
_items.Add(item2);
}
else if (_maxEndOffset > next && !_items.IsEmpty())
{
CParseItem &back = _items.Back();
if (back.LenIsUnknown)
{
back.Size = next - back.Offset;
_maxEndOffset = next;
}
}
}
void CHandler::AddItem(const CParseItem &item)
{
AddUnknownItem(item.Offset);
int pos = FindInsertPos(item);
if (pos >= 0)
{
_items.Insert(pos, item);
UInt64 next = item.Offset + item.Size;
if (_maxEndOffset < next)
_maxEndOffset = next;
}
}
/*
static const CStatProp kProps[] =
{
{ NULL, kpidPath, VT_BSTR},
{ NULL, kpidSize, VT_UI8},
{ NULL, kpidMTime, VT_FILETIME},
{ NULL, kpidType, VT_BSTR},
{ NULL, kpidComment, VT_BSTR},
{ NULL, kpidOffset, VT_UI8},
{ NULL, kpidUnpackSize, VT_UI8},
// { NULL, kpidNumSubDirs, VT_UI8},
};
*/
static const Byte kProps[] =
{
kpidPath,
kpidSize,
kpidMTime,
kpidType,
kpidComment,
kpidOffset,
kpidUnpackSize
};
IMP_IInArchive_Props
IMP_IInArchive_ArcProps_NO
STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback * /* openArchiveCallback */)
{
COM_TRY_BEGIN
{
Close();
_stream = stream;
}
return S_OK;
COM_TRY_END
}
STDMETHODIMP CHandler::Close()
{
_items.Clear();
_stream.Release();
return S_OK;
}
STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems)
{
*numItems = _items.Size();
return S_OK;
}
STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)
{
COM_TRY_BEGIN
NCOM::CPropVariant prop;
const CParseItem &item = _items[index];
switch (propID)
{
case kpidPath:
{
wchar_t sz[32];
ConvertUInt32ToString(index + 1, sz);
UString s = sz;
if (!item.Name.IsEmpty())
{
s += L'.';
s += item.Name;
}
if (!item.Extension.IsEmpty())
{
s += L'.';
s += item.Extension;
}
prop = s; break;
}
case kpidSize:
case kpidPackSize: prop = item.Size; break;
case kpidOffset: prop = item.Offset; break;
case kpidUnpackSize: if (item.UnpackSize_Defined) prop = item.UnpackSize; break;
case kpidNumSubFiles: if (item.NumSubFiles_Defined) prop = item.NumSubFiles; break;
case kpidNumSubDirs: if (item.NumSubDirs_Defined) prop = item.NumSubDirs; break;
case kpidMTime: if (item.FileTime_Defined) prop = item.FileTime; break;
case kpidComment: if (!item.Comment.IsEmpty()) prop = item.Comment; break;
case kpidType: if (!item.ArcType.IsEmpty()) prop = item.ArcType; break;
}
prop.Detach(value);
return S_OK;
COM_TRY_END
}
HRESULT CHandler::Extract(const UInt32 *indices, UInt32 numItems,
Int32 testMode, IArchiveExtractCallback *extractCallback)
{
COM_TRY_BEGIN
bool allFilesMode = (numItems == (UInt32)(Int32)-1);
if (allFilesMode)
numItems = _items.Size();
if (_stream && numItems == 0)
return S_OK;
UInt64 totalSize = 0;
UInt32 i;
for (i = 0; i < numItems; i++)
totalSize += _items[allFilesMode ? i : indices[i]].Size;
extractCallback->SetTotal(totalSize);
totalSize = 0;
CLocalProgress *lps = new CLocalProgress;
CMyComPtr<ICompressProgressInfo> progress = lps;
lps->Init(extractCallback, false);
CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream;
CMyComPtr<ISequentialInStream> inStream(streamSpec);
streamSpec->SetStream(_stream);
CLimitedSequentialOutStream *outStreamSpec = new CLimitedSequentialOutStream;
CMyComPtr<ISequentialOutStream> outStream(outStreamSpec);
NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder();
CMyComPtr<ICompressCoder> copyCoder = copyCoderSpec;
for (i = 0; i < numItems; i++)
{
lps->InSize = totalSize;
lps->OutSize = totalSize;
RINOK(lps->SetCur());
CMyComPtr<ISequentialOutStream> realOutStream;
Int32 askMode = testMode ?
NExtract::NAskMode::kTest :
NExtract::NAskMode::kExtract;
Int32 index = allFilesMode ? i : indices[i];
const CParseItem &item = _items[index];
RINOK(extractCallback->GetStream(index, &realOutStream, askMode));
UInt64 unpackSize = item.Size;
totalSize += unpackSize;
bool skipMode = false;
if (!testMode && !realOutStream)
continue;
RINOK(extractCallback->PrepareOperation(askMode));
outStreamSpec->SetStream(realOutStream);
realOutStream.Release();
outStreamSpec->Init(skipMode ? 0 : unpackSize, true);
Int32 opRes = NExtract::NOperationResult::kOK;
RINOK(_stream->Seek(item.Offset, STREAM_SEEK_SET, NULL));
streamSpec->Init(unpackSize);
RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress));
if (outStreamSpec->GetRem() != 0)
opRes = NExtract::NOperationResult::kDataError;
outStreamSpec->ReleaseStream();
RINOK(extractCallback->SetOperationResult(opRes));
}
return S_OK;
COM_TRY_END
}
STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream)
{
COM_TRY_BEGIN
const CParseItem &item = _items[index];
return CreateLimitedInStream(_stream, item.Offset, item.Size, stream);
COM_TRY_END
}
}}
#endif
HRESULT Archive_GetItemBoolProp(IInArchive *arc, UInt32 index, PROPID propID, bool &result) throw()
{
NCOM::CPropVariant prop;
result = false;
RINOK(arc->GetProperty(index, propID, &prop));
if (prop.vt == VT_BOOL)
result = VARIANT_BOOLToBool(prop.boolVal);
else if (prop.vt != VT_EMPTY)
return E_FAIL;
return S_OK;
}
HRESULT Archive_IsItem_Dir(IInArchive *arc, UInt32 index, bool &result) throw()
{
return Archive_GetItemBoolProp(arc, index, kpidIsDir, result);
}
HRESULT Archive_IsItem_Aux(IInArchive *arc, UInt32 index, bool &result) throw()
{
return Archive_GetItemBoolProp(arc, index, kpidIsAux, result);
}
HRESULT Archive_IsItem_AltStream(IInArchive *arc, UInt32 index, bool &result) throw()
{
return Archive_GetItemBoolProp(arc, index, kpidIsAltStream, result);
}
HRESULT Archive_IsItem_Deleted(IInArchive *arc, UInt32 index, bool &result) throw()
{
return Archive_GetItemBoolProp(arc, index, kpidIsDeleted, result);
}
static HRESULT Archive_GetArcBoolProp(IInArchive *arc, PROPID propid, bool &result) throw()
{
NCOM::CPropVariant prop;
result = false;
RINOK(arc->GetArchiveProperty(propid, &prop));
if (prop.vt == VT_BOOL)
result = VARIANT_BOOLToBool(prop.boolVal);
else if (prop.vt != VT_EMPTY)
return E_FAIL;
return S_OK;
}
static HRESULT Archive_GetArcProp_UInt(IInArchive *arc, PROPID propid, UInt64 &result, bool &defined)
{
defined = false;
NCOM::CPropVariant prop;
RINOK(arc->GetArchiveProperty(propid, &prop));
switch (prop.vt)
{
case VT_UI4: result = prop.ulVal; defined = true; break;
case VT_I4: result = (Int64)prop.lVal; defined = true; break;
case VT_UI8: result = (UInt64)prop.uhVal.QuadPart; defined = true; break;
case VT_I8: result = (UInt64)prop.hVal.QuadPart; defined = true; break;
case VT_EMPTY: break;
default: return E_FAIL;
}
return S_OK;
}
static HRESULT Archive_GetArcProp_Int(IInArchive *arc, PROPID propid, Int64 &result, bool &defined)
{
defined = false;
NCOM::CPropVariant prop;
RINOK(arc->GetArchiveProperty(propid, &prop));
switch (prop.vt)
{
case VT_UI4: result = prop.ulVal; defined = true; break;
case VT_I4: result = prop.lVal; defined = true; break;
case VT_UI8: result = (Int64)prop.uhVal.QuadPart; defined = true; break;
case VT_I8: result = (Int64)prop.hVal.QuadPart; defined = true; break;
case VT_EMPTY: break;
default: return E_FAIL;
}
return S_OK;
}
#ifndef _SFX
HRESULT CArc::GetItemPathToParent(UInt32 index, UInt32 parent, UStringVector &parts) const
{
if (!GetRawProps)
return E_FAIL;
if (index == parent)
return S_OK;
UInt32 curIndex = index;
UString s;
bool prevWasAltStream = false;
for (;;)
{
#ifdef MY_CPU_LE
const void *p;
UInt32 size;
UInt32 propType;
RINOK(GetRawProps->GetRawProp(curIndex, kpidName, &p, &size, &propType));
if (p && propType == PROP_DATA_TYPE_wchar_t_PTR_Z_LE)
s = (const wchar_t *)p;
else
#endif
{
NCOM::CPropVariant prop;
RINOK(Archive->GetProperty(curIndex, kpidName, &prop));
if (prop.vt == VT_BSTR && prop.bstrVal)
s.SetFromBstr(prop.bstrVal);
else if (prop.vt == VT_EMPTY)
s.Empty();
else
return E_FAIL;
}
UInt32 curParent = (UInt32)(Int32)-1;
UInt32 parentType = 0;
RINOK(GetRawProps->GetParent(curIndex, &curParent, &parentType));
if (parentType != NParentType::kAltStream)
{
for (;;)
{
int pos = s.ReverseFind_PathSepar();
if (pos < 0)
{
break;
}
parts.Insert(0, s.Ptr(pos + 1));
s.DeleteFrom(pos);
}
}
parts.Insert(0, s);
if (prevWasAltStream)
{
{
UString &s2 = parts[parts.Size() - 2];
s2 += L':';
s2 += parts.Back();
}
parts.DeleteBack();
}
if (parent == curParent)
return S_OK;
prevWasAltStream = false;
if (parentType == NParentType::kAltStream)
prevWasAltStream = true;
if (curParent == (UInt32)(Int32)-1)
return E_FAIL;
curIndex = curParent;
}
}
#endif
HRESULT CArc::GetItemPath(UInt32 index, UString &result) const
{
#ifdef MY_CPU_LE
if (GetRawProps)
{
const void *p;
UInt32 size;
UInt32 propType;
if (!IsTree)
{
if (GetRawProps->GetRawProp(index, kpidPath, &p, &size, &propType) == S_OK &&
propType == NPropDataType::kUtf16z)
{
unsigned len = size / 2 - 1;
wchar_t *s = result.GetBuf(len);
for (unsigned i = 0; i < len; i++)
{
wchar_t c = GetUi16(p);
p = (const void *)((const Byte *)p + 2);
#if WCHAR_PATH_SEPARATOR != L'/'
if (c == L'/')
c = WCHAR_PATH_SEPARATOR;
#endif
*s++ = c;
}
*s = 0;
result.ReleaseBuf_SetLen(len);
if (len != 0)
return S_OK;
}
}
/*
else if (GetRawProps->GetRawProp(index, kpidName, &p, &size, &propType) == S_OK &&
p && propType == NPropDataType::kUtf16z)
{
size -= 2;
UInt32 totalSize = size;
bool isOK = false;
{
UInt32 index2 = index;
for (;;)
{
UInt32 parent = (UInt32)(Int32)-1;
UInt32 parentType = 0;
if (GetRawProps->GetParent(index2, &parent, &parentType) != S_OK)
break;
if (parent == (UInt32)(Int32)-1)
{
if (parentType != 0)
totalSize += 2;
isOK = true;
break;
}
index2 = parent;
UInt32 size2;
const void *p2;
if (GetRawProps->GetRawProp(index2, kpidName, &p2, &size2, &propType) != S_OK &&
p2 && propType == NPropDataType::kUtf16z)
break;
totalSize += size2;
}
}
if (isOK)
{
wchar_t *sz = result.GetBuf_SetEnd(totalSize / 2);
UInt32 pos = totalSize - size;
memcpy((Byte *)sz + pos, p, size);
UInt32 index2 = index;
for (;;)
{
UInt32 parent = (UInt32)(Int32)-1;
UInt32 parentType = 0;
if (GetRawProps->GetParent(index2, &parent, &parentType) != S_OK)
break;
if (parent == (UInt32)(Int32)-1)
{
if (parentType != 0)
sz[pos / 2 - 1] = L':';
break;
}
index2 = parent;
UInt32 size2;
const void *p2;
if (GetRawProps->GetRawProp(index2, kpidName, &p2, &size2, &propType) != S_OK)
break;
pos -= size2;
memcpy((Byte *)sz + pos, p2, size2);
sz[(pos + size2 - 2) / 2] = (parentType == 0) ? WCHAR_PATH_SEPARATOR : L':';
}
#ifdef _WIN32
// result.Replace(L'/', WCHAR_PATH_SEPARATOR);
#endif
return S_OK;
}
}
*/
}
#endif
{
NCOM::CPropVariant prop;
RINOK(Archive->GetProperty(index, kpidPath, &prop));
if (prop.vt == VT_BSTR && prop.bstrVal)
result.SetFromBstr(prop.bstrVal);
else if (prop.vt == VT_EMPTY)
result.Empty();
else
return E_FAIL;
}
if (result.IsEmpty())
return GetDefaultItemPath(index, result);
return S_OK;
}
HRESULT CArc::GetDefaultItemPath(UInt32 index, UString &result) const
{
result.Empty();
bool isDir;
RINOK(Archive_IsItem_Dir(Archive, index, isDir));
if (!isDir)
{
result = DefaultName;
NCOM::CPropVariant prop;
RINOK(Archive->GetProperty(index, kpidExtension, &prop));
if (prop.vt == VT_BSTR)
{
result += L'.';
result += prop.bstrVal;
}
else if (prop.vt != VT_EMPTY)
return E_FAIL;
}
return S_OK;
}
HRESULT CArc::GetItemPath2(UInt32 index, UString &result) const
{
RINOK(GetItemPath(index, result));
if (Ask_Deleted)
{
bool isDeleted = false;
RINOK(Archive_IsItem_Deleted(Archive, index, isDeleted));
if (isDeleted)
result.Insert(0, L"[DELETED]" WSTRING_PATH_SEPARATOR);
}
return S_OK;
}
#ifdef SUPPORT_ALT_STREAMS
int FindAltStreamColon_in_Path(const wchar_t *path)
{
unsigned i = 0;
int colonPos = -1;
for (;; i++)
{
wchar_t c = path[i];
if (c == 0)
return colonPos;
if (c == ':')
{
if (colonPos < 0)
colonPos = i;
continue;
}
if (c == WCHAR_PATH_SEPARATOR)
colonPos = -1;
}
}
#endif
HRESULT CArc::GetItem(UInt32 index, CReadArcItem &item) const
{
#ifdef SUPPORT_ALT_STREAMS
item.IsAltStream = false;
item.AltStreamName.Empty();
item.MainPath.Empty();
#endif
item.IsDir = false;
item.Path.Empty();
item.ParentIndex = (UInt32)(Int32)-1;
item.PathParts.Clear();
RINOK(Archive_IsItem_Dir(Archive, index, item.IsDir));
item.MainIsDir = item.IsDir;
RINOK(GetItemPath2(index, item.Path));
#ifndef _SFX
UInt32 mainIndex = index;
#endif
#ifdef SUPPORT_ALT_STREAMS
item.MainPath = item.Path;
if (Ask_AltStream)
{
RINOK(Archive_IsItem_AltStream(Archive, index, item.IsAltStream));
}
bool needFindAltStream = false;
if (item.IsAltStream)
{
needFindAltStream = true;
if (GetRawProps)
{
UInt32 parentType = 0;
UInt32 parentIndex;
RINOK(GetRawProps->GetParent(index, &parentIndex, &parentType));
if (parentType == NParentType::kAltStream)
{
NCOM::CPropVariant prop;
RINOK(Archive->GetProperty(index, kpidName, &prop));
if (prop.vt == VT_BSTR && prop.bstrVal)
item.AltStreamName.SetFromBstr(prop.bstrVal);
else if (prop.vt != VT_EMPTY)
return E_FAIL;
else
{
// item.IsAltStream = false;
}
/*
if (item.AltStreamName.IsEmpty())
item.IsAltStream = false;
*/
needFindAltStream = false;
item.ParentIndex = parentIndex;
mainIndex = parentIndex;
if (parentIndex == (UInt32)(Int32)-1)
{
item.MainPath.Empty();
item.MainIsDir = true;
}
else
{
RINOK(GetItemPath2(parentIndex, item.MainPath));
RINOK(Archive_IsItem_Dir(Archive, parentIndex, item.MainIsDir));
}
}
}
}
if (item.WriteToAltStreamIfColon || needFindAltStream)
{
/* Good handler must support GetRawProps::GetParent for alt streams./
So the following code currently is not used */
int colon = FindAltStreamColon_in_Path(item.Path);
if (colon >= 0)
{
item.MainPath.DeleteFrom(colon);
item.AltStreamName = item.Path.Ptr(colon + 1);
item.MainIsDir = (colon == 0 || IsPathSepar(item.Path[(unsigned)colon - 1]));
item.IsAltStream = true;
}
}
#endif
#ifndef _SFX
if (item._use_baseParentFolder_mode)
{
RINOK(GetItemPathToParent(mainIndex, item._baseParentFolder, item.PathParts));
#ifdef SUPPORT_ALT_STREAMS
if ((item.WriteToAltStreamIfColon || needFindAltStream) && !item.PathParts.IsEmpty())
{
int colon;
{
UString &s = item.PathParts.Back();
colon = FindAltStreamColon_in_Path(s);
if (colon >= 0)
{
item.AltStreamName = s.Ptr(colon + 1);
item.MainIsDir = (colon == 0 || IsPathSepar(s[(unsigned)colon - 1]));
item.IsAltStream = true;
s.DeleteFrom(colon);
}
}
if (colon == 0)
item.PathParts.DeleteBack();
}
#endif
}
else
#endif
SplitPathToParts(
#ifdef SUPPORT_ALT_STREAMS
item.MainPath
#else
item.Path
#endif
, item.PathParts);
return S_OK;
}
#ifndef _SFX
static HRESULT Archive_GetItem_Size(IInArchive *archive, UInt32 index, UInt64 &size, bool &defined)
{
NCOM::CPropVariant prop;
defined = false;
size = 0;
RINOK(archive->GetProperty(index, kpidSize, &prop));
switch (prop.vt)
{
case VT_UI1: size = prop.bVal; break;
case VT_UI2: size = prop.uiVal; break;
case VT_UI4: size = prop.ulVal; break;
case VT_UI8: size = (UInt64)prop.uhVal.QuadPart; break;
case VT_EMPTY: return S_OK;
default: return E_FAIL;
}
defined = true;
return S_OK;
}
#endif
HRESULT CArc::GetItemSize(UInt32 index, UInt64 &size, bool &defined) const
{
NCOM::CPropVariant prop;
defined = false;
size = 0;
RINOK(Archive->GetProperty(index, kpidSize, &prop));
switch (prop.vt)
{
case VT_UI1: size = prop.bVal; break;
case VT_UI2: size = prop.uiVal; break;
case VT_UI4: size = prop.ulVal; break;
case VT_UI8: size = (UInt64)prop.uhVal.QuadPart; break;
case VT_EMPTY: return S_OK;
default: return E_FAIL;
}
defined = true;
return S_OK;
}
HRESULT CArc::GetItemMTime(UInt32 index, FILETIME &ft, bool &defined) const
{
NCOM::CPropVariant prop;
defined = false;
ft.dwHighDateTime = ft.dwLowDateTime = 0;
RINOK(Archive->GetProperty(index, kpidMTime, &prop));
if (prop.vt == VT_FILETIME)
{
ft = prop.filetime;
defined = true;
}
else if (prop.vt != VT_EMPTY)
return E_FAIL;
else if (MTimeDefined)
{
ft = MTime;
defined = true;
}
return S_OK;
}
#ifndef _SFX
static inline bool TestSignature(const Byte *p1, const Byte *p2, size_t size)
{
for (size_t i = 0; i < size; i++)
if (p1[i] != p2[i])
return false;
return true;
}
static void MakeCheckOrder(CCodecs *codecs,
CIntVector &orderIndices, unsigned numTypes, CIntVector &orderIndices2,
const Byte *data, size_t dataSize)
{
for (unsigned i = 0; i < numTypes; i++)
{
int index = orderIndices[i];
if (index < 0)
continue;
const CArcInfoEx &ai = codecs->Formats[index];
if (ai.SignatureOffset != 0)
{
orderIndices2.Add(index);
orderIndices[i] = -1;
continue;
}
const CObjectVector<CByteBuffer> &sigs = ai.Signatures;
FOR_VECTOR (k, sigs)
{
const CByteBuffer &sig = sigs[k];
if (sig.Size() == 0 && dataSize == 0 ||
sig.Size() != 0 && sig.Size() <= dataSize &&
TestSignature(data, sig, sig.Size()))
{
orderIndices2.Add(index);
orderIndices[i] = -1;
break;
}
}
}
}
#endif
#ifdef UNDER_CE
static const unsigned kNumHashBytes = 1;
#define HASH_VAL(buf, pos) ((buf)[pos])
#else
static const unsigned kNumHashBytes = 2;
#define HASH_VAL(buf, pos) ((buf)[pos] | ((UInt32)(buf)[pos + 1] << 8))
#endif
#ifndef _SFX
static bool IsExeExt(const UString &ext)
{
return ext.IsEqualTo_Ascii_NoCase("exe");
}
static const char * const k_PreArcFormats[] =
{
"pe"
, "elf"
, "macho"
, "mub"
, "te"
};
static bool IsNameFromList(const UString &s, const char * const names[], size_t num)
{
for (unsigned i = 0; i < num; i++)
if (StringsAreEqualNoCase_Ascii(s, names[i]))
return true;
return false;
}
static bool IsPreArcFormat(const CArcInfoEx &ai)
{
if (ai.Flags_PreArc())
return true;
return IsNameFromList(ai.Name, k_PreArcFormats, ARRAY_SIZE(k_PreArcFormats));
}
static const char * const k_Formats_with_simple_signuature[] =
{
"7z"
, "xz"
, "rar"
, "bzip2"
, "gzip"
, "cab"
, "wim"
, "rpm"
, "vhd"
, "xar"
};
static bool IsNewStyleSignature(const CArcInfoEx &ai)
{
// if (ai.Version >= 0x91F)
if (ai.NewInterface)
return true;
return IsNameFromList(ai.Name, k_Formats_with_simple_signuature, ARRAY_SIZE(k_Formats_with_simple_signuature));
}
class CArchiveOpenCallback_Offset:
public IArchiveOpenCallback,
public IArchiveOpenVolumeCallback,
#ifndef _NO_CRYPTO
public ICryptoGetTextPassword,
#endif
public CMyUnknownImp
{
public:
CMyComPtr<IArchiveOpenCallback> Callback;
CMyComPtr<IArchiveOpenVolumeCallback> OpenVolumeCallback;
UInt64 Files;
UInt64 Offset;
#ifndef _NO_CRYPTO
CMyComPtr<ICryptoGetTextPassword> GetTextPassword;
#endif
MY_QUERYINTERFACE_BEGIN2(IArchiveOpenCallback)
MY_QUERYINTERFACE_ENTRY(IArchiveOpenVolumeCallback)
#ifndef _NO_CRYPTO
MY_QUERYINTERFACE_ENTRY(ICryptoGetTextPassword)
#endif
MY_QUERYINTERFACE_END
MY_ADDREF_RELEASE
INTERFACE_IArchiveOpenCallback(;)
INTERFACE_IArchiveOpenVolumeCallback(;)
#ifndef _NO_CRYPTO
STDMETHOD(CryptoGetTextPassword)(BSTR *password);
#endif
};
#ifndef _NO_CRYPTO
STDMETHODIMP CArchiveOpenCallback_Offset::CryptoGetTextPassword(BSTR *password)
{
COM_TRY_BEGIN
if (GetTextPassword)
return GetTextPassword->CryptoGetTextPassword(password);
return E_NOTIMPL;
COM_TRY_END
}
#endif
STDMETHODIMP CArchiveOpenCallback_Offset::SetTotal(const UInt64 *, const UInt64 *)
{
return S_OK;
}
STDMETHODIMP CArchiveOpenCallback_Offset::SetCompleted(const UInt64 *, const UInt64 *bytes)
{
if (!Callback)
return S_OK;
UInt64 value = Offset;
if (bytes)
value += *bytes;
return Callback->SetCompleted(&Files, &value);
}
STDMETHODIMP CArchiveOpenCallback_Offset::GetProperty(PROPID propID, PROPVARIANT *value)
{
if (OpenVolumeCallback)
return OpenVolumeCallback->GetProperty(propID, value);
NCOM::PropVariant_Clear(value);
return S_OK;
// return E_NOTIMPL;
}
STDMETHODIMP CArchiveOpenCallback_Offset::GetStream(const wchar_t *name, IInStream **inStream)
{
if (OpenVolumeCallback)
return OpenVolumeCallback->GetStream(name, inStream);
return S_FALSE;
}
#endif
UInt32 GetOpenArcErrorFlags(const NCOM::CPropVariant &prop, bool *isDefinedProp)
{
if (isDefinedProp != NULL)
*isDefinedProp = false;
switch (prop.vt)
{
case VT_UI8: if (isDefinedProp) *isDefinedProp = true; return (UInt32)prop.uhVal.QuadPart;
case VT_UI4: if (isDefinedProp) *isDefinedProp = true; return prop.ulVal;
case VT_EMPTY: return 0;
default: throw 151199;
}
}
void CArcErrorInfo::ClearErrors()
{
// ErrorFormatIndex = -1; // we don't need to clear ErrorFormatIndex here !!!
ThereIsTail = false;
UnexpecedEnd = false;
IgnoreTail = false;
// NonZerosTail = false;
ErrorFlags_Defined = false;
ErrorFlags = 0;
WarningFlags = 0;
TailSize = 0;
ErrorMessage.Empty();
WarningMessage.Empty();
}
HRESULT CArc::ReadBasicProps(IInArchive *archive, UInt64 startPos, HRESULT openRes)
{
// OkPhySize_Defined = false;
PhySizeDefined = false;
PhySize = 0;
Offset = 0;
AvailPhySize = FileSize - startPos;
ErrorInfo.ClearErrors();
{
NCOM::CPropVariant prop;
RINOK(archive->GetArchiveProperty(kpidErrorFlags, &prop));
ErrorInfo.ErrorFlags = GetOpenArcErrorFlags(prop, &ErrorInfo.ErrorFlags_Defined);
}
{
NCOM::CPropVariant prop;
RINOK(archive->GetArchiveProperty(kpidWarningFlags, &prop));
ErrorInfo.WarningFlags = GetOpenArcErrorFlags(prop);
}
{
NCOM::CPropVariant prop;
RINOK(archive->GetArchiveProperty(kpidError, &prop));
if (prop.vt != VT_EMPTY)
ErrorInfo.ErrorMessage = (prop.vt == VT_BSTR ? prop.bstrVal : L"Unknown error");
}
{
NCOM::CPropVariant prop;
RINOK(archive->GetArchiveProperty(kpidWarning, &prop));
if (prop.vt != VT_EMPTY)
ErrorInfo.WarningMessage = (prop.vt == VT_BSTR ? prop.bstrVal : L"Unknown warning");
}
if (openRes == S_OK || ErrorInfo.IsArc_After_NonOpen())
{
RINOK(Archive_GetArcProp_UInt(archive, kpidPhySize, PhySize, PhySizeDefined));
/*
RINOK(Archive_GetArcProp_UInt(archive, kpidOkPhySize, OkPhySize, OkPhySize_Defined));
if (!OkPhySize_Defined)
{
OkPhySize_Defined = PhySizeDefined;
OkPhySize = PhySize;
}
*/
bool offsetDefined;
RINOK(Archive_GetArcProp_Int(archive, kpidOffset, Offset, offsetDefined));
Int64 globalOffset = startPos + Offset;
AvailPhySize = FileSize - globalOffset;
if (PhySizeDefined)
{
UInt64 endPos = globalOffset + PhySize;
if (endPos < FileSize)
{
AvailPhySize = PhySize;
ErrorInfo.ThereIsTail = true;
ErrorInfo.TailSize = FileSize - endPos;
}
else if (endPos > FileSize)
ErrorInfo.UnexpecedEnd = true;
}
}
return S_OK;
}
/*
static PrintNumber(const char *s, int n)
{
char temp[100];
sprintf(temp, "%s %d", s, n);
OutputDebugStringA(temp);
}
*/
HRESULT CArc::PrepareToOpen(const COpenOptions &op, unsigned formatIndex, CMyComPtr<IInArchive> &archive)
{
// OutputDebugStringA("a1");
// PrintNumber("formatIndex", formatIndex);
RINOK(op.codecs->CreateInArchive(formatIndex, archive));
// OutputDebugStringA("a2");
if (!archive)
return S_OK;
#ifdef EXTERNAL_CODECS
if (op.codecs->NeedSetLibCodecs)
{
const CArcInfoEx &ai = op.codecs->Formats[formatIndex];
if (ai.LibIndex >= 0 ?
!op.codecs->Libs[ai.LibIndex].SetCodecs :
!op.codecs->Libs.IsEmpty())
{
CMyComPtr<ISetCompressCodecsInfo> setCompressCodecsInfo;
archive.QueryInterface(IID_ISetCompressCodecsInfo, (void **)&setCompressCodecsInfo);
if (setCompressCodecsInfo)
{
RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(op.codecs));
}
}
}
#endif
#ifndef _SFX
const CArcInfoEx &ai = op.codecs->Formats[formatIndex];
// OutputDebugStringW(ai.Name);
// OutputDebugStringA("a3");
if (ai.Flags_PreArc())
{
/* we notify parsers that extract executables, that they don't need
to open archive, if there is tail after executable (for SFX cases) */
CMyComPtr<IArchiveAllowTail> allowTail;
archive.QueryInterface(IID_IArchiveAllowTail, (void **)&allowTail);
if (allowTail)
allowTail->AllowTail(BoolToInt(true));
}
if (op.props)
{
/*
FOR_VECTOR (y, op.props)
{
const COptionalOpenProperties &optProps = (*op.props)[y];
if (optProps.FormatName.IsEmpty() || optProps.FormatName.CompareNoCase(ai.Name) == 0)
{
RINOK(SetProperties(archive, optProps.Props));
break;
}
}
*/
RINOK(SetProperties(archive, *op.props));
}
#endif
return S_OK;
}
#ifndef _SFX
static HRESULT ReadParseItemProps(IInArchive *archive, const CArcInfoEx &ai, NArchive::NParser::CParseItem &pi)
{
pi.Extension = ai.GetMainExt();
pi.FileTime_Defined = false;
pi.ArcType = ai.Name;
RINOK(Archive_GetArcBoolProp(archive, kpidIsNotArcType, pi.IsNotArcType));
// RINOK(Archive_GetArcBoolProp(archive, kpidIsSelfExe, pi.IsSelfExe));
pi.IsSelfExe = ai.Flags_PreArc();
{
NCOM::CPropVariant prop;
RINOK(archive->GetArchiveProperty(kpidMTime, &prop));
if (prop.vt == VT_FILETIME)
{
pi.FileTime_Defined = true;
pi.FileTime = prop.filetime;
}
}
if (!pi.FileTime_Defined)
{
NCOM::CPropVariant prop;
RINOK(archive->GetArchiveProperty(kpidCTime, &prop));
if (prop.vt == VT_FILETIME)
{
pi.FileTime_Defined = true;
pi.FileTime = prop.filetime;
}
}
{
NCOM::CPropVariant prop;
RINOK(archive->GetArchiveProperty(kpidName, &prop));
if (prop.vt == VT_BSTR)
{
pi.Name.SetFromBstr(prop.bstrVal);
pi.Extension.Empty();
}
else
{
RINOK(archive->GetArchiveProperty(kpidExtension, &prop));
if (prop.vt == VT_BSTR)
pi.Extension.SetFromBstr(prop.bstrVal);
}
}
{
NCOM::CPropVariant prop;
RINOK(archive->GetArchiveProperty(kpidShortComment, &prop));
if (prop.vt == VT_BSTR)
pi.Comment.SetFromBstr(prop.bstrVal);
}
UInt32 numItems;
RINOK(archive->GetNumberOfItems(&numItems));
// pi.NumSubFiles = numItems;
// RINOK(Archive_GetArcProp_UInt(archive, kpidUnpackSize, pi.UnpackSize, pi.UnpackSize_Defined));
// if (!pi.UnpackSize_Defined)
{
pi.NumSubFiles = 0;
pi.NumSubDirs = 0;
pi.UnpackSize = 0;
for (UInt32 i = 0; i < numItems; i++)
{
UInt64 size = 0;
bool defined = false;
Archive_GetItem_Size(archive, i, size, defined);
if (defined)
{
pi.UnpackSize_Defined = true;
pi.UnpackSize += size;
}
bool isDir = false;
Archive_IsItem_Dir(archive, i, isDir);
if (isDir)
pi.NumSubDirs++;
else
pi.NumSubFiles++;
}
if (pi.NumSubDirs != 0)
pi.NumSubDirs_Defined = true;
pi.NumSubFiles_Defined = true;
}
return S_OK;
}
#endif
HRESULT CArc::CheckZerosTail(const COpenOptions &op, UInt64 offset)
{
if (!op.stream)
return S_OK;
RINOK(op.stream->Seek(offset, STREAM_SEEK_SET, NULL));
const UInt32 kBufSize = 1 << 11;
Byte buf[kBufSize];
for (;;)
{
UInt32 processed = 0;
RINOK(op.stream->Read(buf, kBufSize, &processed));
if (processed == 0)
{
// ErrorInfo.NonZerosTail = false;
ErrorInfo.IgnoreTail = true;
return S_OK;
}
for (size_t i = 0; i < processed; i++)
{
if (buf[i] != 0)
{
// ErrorInfo.IgnoreTail = false;
// ErrorInfo.NonZerosTail = true;
return S_OK;
}
}
}
}
#ifndef _SFX
class CExtractCallback_To_OpenCallback:
public IArchiveExtractCallback,
public ICompressProgressInfo,
public CMyUnknownImp
{
public:
CMyComPtr<IArchiveOpenCallback> Callback;
UInt64 Files;
UInt64 Offset;
MY_UNKNOWN_IMP2(IArchiveExtractCallback, ICompressProgressInfo)
INTERFACE_IArchiveExtractCallback(;)
STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize);
void Init(IArchiveOpenCallback *callback)
{
Callback = callback;
Files = 0;
Offset = 0;
}
};
STDMETHODIMP CExtractCallback_To_OpenCallback::SetTotal(UInt64 /* size */)
{
return S_OK;
}
STDMETHODIMP CExtractCallback_To_OpenCallback::SetCompleted(const UInt64 * /* completeValue */)
{
return S_OK;
}
STDMETHODIMP CExtractCallback_To_OpenCallback::SetRatioInfo(const UInt64 *inSize, const UInt64 * /* outSize */)
{
if (Callback)
{
UInt64 value = Offset;
if (inSize)
value += *inSize;
return Callback->SetCompleted(&Files, &value);
}
return S_OK;
}
STDMETHODIMP CExtractCallback_To_OpenCallback::GetStream(UInt32 /* index */, ISequentialOutStream **outStream, Int32 /* askExtractMode */)
{
*outStream = 0;
return S_OK;
}
STDMETHODIMP CExtractCallback_To_OpenCallback::PrepareOperation(Int32 /* askExtractMode */)
{
return S_OK;
}
STDMETHODIMP CExtractCallback_To_OpenCallback::SetOperationResult(Int32 /* operationResult */)
{
return S_OK;
}
static HRESULT OpenArchiveSpec(IInArchive *archive, bool needPhySize,
IInStream *stream, const UInt64 *maxCheckStartPosition,
IArchiveOpenCallback *openCallback,
IArchiveExtractCallback *extractCallback)
{
/*
if (needPhySize)
{
CMyComPtr<IArchiveOpen2> open2;
archive->QueryInterface(IID_IArchiveOpen2, (void **)&open2);
if (open2)
return open2->ArcOpen2(stream, kOpenFlags_RealPhySize, openCallback);
}
*/
RINOK(archive->Open(stream, maxCheckStartPosition, openCallback));
if (needPhySize)
{
bool phySize_Defined = false;
UInt64 phySize = 0;
RINOK(Archive_GetArcProp_UInt(archive, kpidPhySize, phySize, phySize_Defined));
if (phySize_Defined)
return S_OK;
bool phySizeCantBeDetected = false;;
RINOK(Archive_GetArcBoolProp(archive, kpidPhySizeCantBeDetected, phySizeCantBeDetected));
if (!phySizeCantBeDetected)
{
RINOK(archive->Extract(0, (UInt32)(Int32)-1, BoolToInt(true), extractCallback));
}
}
return S_OK;
}
static int FindFormatForArchiveType(CCodecs *codecs, CIntVector orderIndices, const char *name)
{
FOR_VECTOR (i, orderIndices)
if (StringsAreEqualNoCase_Ascii(codecs->Formats[orderIndices[i]].Name, name))
return i;
return -1;
}
#endif
HRESULT CArc::OpenStream2(const COpenOptions &op)
{
// fprintf(stdout, "\nOpen: %S", Path); fflush(stdout);
Archive.Release();
GetRawProps.Release();
GetRootProps.Release();
ErrorInfo.ClearErrors();
ErrorInfo.ErrorFormatIndex = -1;
IsParseArc = false;
ArcStreamOffset = 0;
// OutputDebugStringA("1");
// OutputDebugStringW(Path);
const UString fileName = ExtractFileNameFromPath(Path);
UString extension;
{
int dotPos = fileName.ReverseFind_Dot();
if (dotPos >= 0)
extension = fileName.Ptr(dotPos + 1);
}
CIntVector orderIndices;
bool searchMarkerInHandler = false;
#ifdef _SFX
searchMarkerInHandler = true;
#endif
CBoolArr isMainFormatArr(op.codecs->Formats.Size());
{
FOR_VECTOR(i, op.codecs->Formats)
isMainFormatArr[i] = false;
}
UInt64 maxStartOffset =
op.openType.MaxStartOffset_Defined ?
op.openType.MaxStartOffset :
kMaxCheckStartPosition;
#ifndef _SFX
bool isUnknownExt = false;
#endif
bool isForced = false;
unsigned numMainTypes = 0;
int formatIndex = op.openType.FormatIndex;
if (formatIndex >= 0)
{
isForced = true;
orderIndices.Add(formatIndex);
numMainTypes = 1;
isMainFormatArr[(unsigned)formatIndex] = true;
searchMarkerInHandler = true;
}
else
{
unsigned numFinded = 0;
#ifndef _SFX
bool isPrearcExt = false;
#endif
{
#ifndef _SFX
bool isZip = false;
bool isRar = false;
const wchar_t c = extension[0];
if (c == 'z' || c == 'Z' || c == 'r' || c == 'R')
{
bool isNumber = false;
for (unsigned k = 1;; k++)
{
const wchar_t d = extension[k];
if (d == 0)
break;
if (d < '0' || d > '9')
{
isNumber = false;
break;
}
isNumber = true;
}
if (isNumber)
if (c == 'z' || c == 'Z')
isZip = true;
else
isRar = true;
}
#endif
FOR_VECTOR (i, op.codecs->Formats)
{
const CArcInfoEx &ai = op.codecs->Formats[i];
if (IgnoreSplit || !op.openType.CanReturnArc)
if (ai.IsSplit())
continue;
if (op.excludedFormats->FindInSorted(i) >= 0)
continue;
#ifndef _SFX
if (IsPreArcFormat(ai))
isPrearcExt = true;
#endif
if (ai.FindExtension(extension) >= 0
#ifndef _SFX
|| isZip && StringsAreEqualNoCase_Ascii(ai.Name, "zip")
|| isRar && StringsAreEqualNoCase_Ascii(ai.Name, "rar")
#endif
)
{
// PrintNumber("orderIndices.Insert", i);
orderIndices.Insert(numFinded++, i);
isMainFormatArr[i] = true;
}
else
orderIndices.Add(i);
}
}
if (!op.stream)
{
if (numFinded != 1)
return E_NOTIMPL;
orderIndices.DeleteFrom(1);
}
// PrintNumber("numFinded", numFinded );
/*
if (op.openOnlySpecifiedByExtension)
{
if (numFinded != 0 && !IsExeExt(extension))
orderIndices.DeleteFrom(numFinded);
}
*/
#ifndef _SFX
if (op.stream && orderIndices.Size() >= 2)
{
RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL));
CByteBuffer byteBuffer;
CIntVector orderIndices2;
if (numFinded == 0 || IsExeExt(extension))
{
// signature search was here
}
else if (extension.IsEqualTo("000") || extension.IsEqualTo("001"))
{
int i = FindFormatForArchiveType(op.codecs, orderIndices, "rar");
if (i >= 0)
{
const size_t kBufSize = (1 << 10);
byteBuffer.Alloc(kBufSize);
size_t processedSize = kBufSize;
RINOK(ReadStream(op.stream, byteBuffer, &processedSize));
if (processedSize >= 16)
{
const Byte *buf = byteBuffer;
const Byte kRarHeader[] = { 0x52 , 0x61, 0x72, 0x21, 0x1a, 0x07, 0x00 };
if (TestSignature(buf, kRarHeader, 7) && buf[9] == 0x73 && (buf[10] & 1) != 0)
{
orderIndices2.Add(orderIndices[i]);
orderIndices[i] = -1;
if (i >= (int)numFinded)
numFinded++;
}
}
}
}
else
{
const size_t kBufSize = (1 << 10);
byteBuffer.Alloc(kBufSize);
size_t processedSize = kBufSize;
RINOK(ReadStream(op.stream, byteBuffer, &processedSize));
if (processedSize == 0)
return S_FALSE;
/*
check type order:
1) matched extension, no signuature
2) matched extension, matched signuature
// 3) no signuature
// 4) matched signuature
*/
MakeCheckOrder(op.codecs, orderIndices, numFinded, orderIndices2, NULL, 0);
MakeCheckOrder(op.codecs, orderIndices, numFinded, orderIndices2, byteBuffer, processedSize);
// MakeCheckOrder(op.codecs, orderIndices, orderIndices.Size(), orderIndices2, NULL, 0);
// MakeCheckOrder(op.codecs, orderIndices, orderIndices.Size(), orderIndices2, byteBuffer, processedSize);
}
FOR_VECTOR (i, orderIndices)
{
int val = orderIndices[i];
if (val != -1)
orderIndices2.Add(val);
}
orderIndices = orderIndices2;
}
if (orderIndices.Size() >= 2)
{
int iIso = FindFormatForArchiveType(op.codecs, orderIndices, "iso");
int iUdf = FindFormatForArchiveType(op.codecs, orderIndices, "udf");
if (iUdf > iIso && iIso >= 0)
{
int isoIndex = orderIndices[iIso];
int udfIndex = orderIndices[iUdf];
orderIndices[iUdf] = isoIndex;
orderIndices[iIso] = udfIndex;
}
}
numMainTypes = numFinded;
isUnknownExt = (numMainTypes == 0) || isPrearcExt;
#else // _SFX
numMainTypes = orderIndices.Size();
// we need correct numMainTypes for mutlivolume SFX (if some volume is missing)
if (numFinded != 0)
numMainTypes = numFinded;
#endif
}
UInt64 fileSize = 0;
if (op.stream)
{
RINOK(op.stream->Seek(0, STREAM_SEEK_END, &fileSize));
RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL));
}
FileSize = fileSize;
#ifndef _SFX
CBoolArr skipFrontalFormat(op.codecs->Formats.Size());
{
FOR_VECTOR(i, op.codecs->Formats)
skipFrontalFormat[i] = false;
}
#endif
const COpenType &mode = op.openType;
if (mode.CanReturnArc)
{
// ---------- OPEN main type by extenssion ----------
unsigned numCheckTypes = orderIndices.Size();
if (formatIndex >= 0)
numCheckTypes = numMainTypes;
for (unsigned i = 0; i < numCheckTypes; i++)
{
FormatIndex = orderIndices[i];
bool exactOnly = false;
#ifndef _SFX
const CArcInfoEx &ai = op.codecs->Formats[FormatIndex];
// OutputDebugStringW(ai.Name);
if (i >= numMainTypes)
{
if (!ai.Flags_BackwardOpen()
// && !ai.Flags_PureStartOpen()
)
continue;
exactOnly = true;
}
#endif
// Some handlers do not set total bytes. So we set it here
if (op.callback)
RINOK(op.callback->SetTotal(NULL, &fileSize));
if (op.stream)
{
RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL));
}
CMyComPtr<IInArchive> archive;
RINOK(PrepareToOpen(op, FormatIndex, archive));
if (!archive)
continue;
HRESULT result;
if (op.stream)
{
UInt64 searchLimit = (!exactOnly && searchMarkerInHandler) ? maxStartOffset: 0;
result = archive->Open(op.stream, &searchLimit, op.callback);
}
else
{
CMyComPtr<IArchiveOpenSeq> openSeq;
archive.QueryInterface(IID_IArchiveOpenSeq, (void **)&openSeq);
if (!openSeq)
return E_NOTIMPL;
result = openSeq->OpenSeq(op.seqStream);
}
RINOK(ReadBasicProps(archive, 0, result));
if (result == S_FALSE)
{
bool isArc = ErrorInfo.IsArc_After_NonOpen();
#ifndef _SFX
// if it's archive, we allow another open attempt for parser
if (!mode.CanReturnParser || !isArc)
skipFrontalFormat[(unsigned)FormatIndex] = true;
#endif
if (exactOnly)
continue;
if (i == 0 && numMainTypes == 1)
{
// we set NonOpenErrorInfo, only if there is only one main format (defined by extension).
ErrorInfo.ErrorFormatIndex = FormatIndex;
NonOpen_ErrorInfo = ErrorInfo;
if (!mode.CanReturnParser && isArc)
{
// if (formatIndex < 0 && !searchMarkerInHandler)
{
// if bad archive was detected, we don't need additional open attempts
#ifndef _SFX
if (!IsPreArcFormat(ai) /* || !mode.SkipSfxStub */)
#endif
return S_FALSE;
}
}
}
/*
#ifndef _SFX
if (IsExeExt(extension) || ai.Flags_PreArc())
{
// openOnlyFullArc = false;
// canReturnTailArc = true;
// limitSignatureSearch = true;
}
#endif
*/
continue;
}
RINOK(result);
#ifndef _SFX
bool isMainFormat = isMainFormatArr[(unsigned)FormatIndex];
const COpenSpecFlags &specFlags = mode.GetSpec(isForced, isMainFormat, isUnknownExt);
bool thereIsTail = ErrorInfo.ThereIsTail;
if (thereIsTail && mode.ZerosTailIsAllowed)
{
RINOK(CheckZerosTail(op, Offset + PhySize));
if (ErrorInfo.IgnoreTail)
thereIsTail = false;
}
if (Offset > 0)
{
if (exactOnly
|| !searchMarkerInHandler
|| !specFlags.CanReturn_NonStart()
|| (mode.MaxStartOffset_Defined && (UInt64)Offset > mode.MaxStartOffset))
continue;
}
if (thereIsTail)
{
if (Offset > 0)
{
if (!specFlags.CanReturnMid)
continue;
}
else if (!specFlags.CanReturnFrontal)
continue;
}
if (Offset > 0 || thereIsTail)
{
if (formatIndex < 0)
{
if (IsPreArcFormat(ai))
{
// openOnlyFullArc = false;
// canReturnTailArc = true;
/*
if (mode.SkipSfxStub)
limitSignatureSearch = true;
*/
// if (mode.SkipSfxStub)
{
// skipFrontalFormat[FormatIndex] = true;
continue;
}
}
}
}
#endif
Archive = archive;
return S_OK;
}
}
#ifndef _SFX
if (!op.stream)
return S_FALSE;
if (formatIndex >= 0 && !mode.CanReturnParser)
{
if (mode.MaxStartOffset_Defined)
{
if (mode.MaxStartOffset == 0)
return S_FALSE;
}
else
{
const CArcInfoEx &ai = op.codecs->Formats[formatIndex];
if (ai.FindExtension(extension) >= 0)
{
if (ai.Flags_FindSignature() && searchMarkerInHandler)
return S_FALSE;
}
}
}
NArchive::NParser::CHandler *handlerSpec = new NArchive::NParser::CHandler;
CMyComPtr<IInArchive> handler = handlerSpec;
CExtractCallback_To_OpenCallback *extractCallback_To_OpenCallback_Spec = new CExtractCallback_To_OpenCallback;
CMyComPtr<IArchiveExtractCallback> extractCallback_To_OpenCallback = extractCallback_To_OpenCallback_Spec;
extractCallback_To_OpenCallback_Spec->Init(op.callback);
{
// ---------- Check all possible START archives ----------
// this code is better for full file archives than Parser's code.
CByteBuffer byteBuffer;
bool endOfFile = false;
size_t processedSize;
{
size_t bufSize = 1 << 20; // it must be larger than max signature offset or IsArcFunc offset ((1 << 19) + x for UDF)
if (bufSize > fileSize)
{
bufSize = (size_t)fileSize;
endOfFile = true;
}
byteBuffer.Alloc(bufSize);
RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL));
processedSize = bufSize;
RINOK(ReadStream(op.stream, byteBuffer, &processedSize));
if (processedSize == 0)
return S_FALSE;
if (processedSize < bufSize)
endOfFile = true;
}
CUIntVector sortedFormats;
unsigned i;
int splitIndex = -1;
for (i = 0; i < orderIndices.Size(); i++)
{
unsigned form = orderIndices[i];
if (skipFrontalFormat[form])
continue;
const CArcInfoEx &ai = op.codecs->Formats[form];
if (ai.IsSplit())
{
splitIndex = form;
continue;
}
if (ai.IsArcFunc)
{
UInt32 isArcRes = ai.IsArcFunc(byteBuffer, processedSize);
if (isArcRes == k_IsArc_Res_NO)
continue;
if (isArcRes == k_IsArc_Res_NEED_MORE && endOfFile)
continue;
// if (isArcRes == k_IsArc_Res_YES_LOW_PROB) continue;
sortedFormats.Insert(0, form);
continue;
}
bool isNewStyleSignature = IsNewStyleSignature(ai);
bool needCheck = !isNewStyleSignature
|| ai.Signatures.IsEmpty()
|| ai.Flags_PureStartOpen()
|| ai.Flags_StartOpen()
|| ai.Flags_BackwardOpen();
if (isNewStyleSignature && !ai.Signatures.IsEmpty())
{
unsigned k;
for (k = 0; k < ai.Signatures.Size(); k++)
{
const CByteBuffer &sig = ai.Signatures[k];
UInt32 signatureEnd = ai.SignatureOffset + (UInt32)sig.Size();
if (processedSize < signatureEnd)
{
if (!endOfFile)
needCheck = true;
}
else if (memcmp(sig, byteBuffer + ai.SignatureOffset, sig.Size()) == 0)
break;
}
if (k != ai.Signatures.Size())
{
sortedFormats.Insert(0, form);
continue;
}
}
if (needCheck)
sortedFormats.Add(form);
}
if (splitIndex >= 0)
sortedFormats.Insert(0, splitIndex);
for (i = 0; i < sortedFormats.Size(); i++)
{
FormatIndex = sortedFormats[i];
const CArcInfoEx &ai = op.codecs->Formats[FormatIndex];
if (op.callback)
RINOK(op.callback->SetTotal(NULL, &fileSize));
RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL));
CMyComPtr<IInArchive> archive;
RINOK(PrepareToOpen(op, FormatIndex, archive));
if (!archive)
continue;
PRF(printf("\nSorted Open %S", (const wchar_t *)ai.Name));
HRESULT result;
{
UInt64 searchLimit = 0;
/*
if (mode.CanReturnArc)
result = archive->Open(op.stream, &searchLimit, op.callback);
else
*/
result = OpenArchiveSpec(archive, !mode.CanReturnArc, op.stream, &searchLimit, op.callback, extractCallback_To_OpenCallback);
}
if (result == S_FALSE)
{
skipFrontalFormat[(unsigned)FormatIndex] = true;
// FIXME: maybe we must use LenIsUnknown.
// printf(" OpenForSize Error");
continue;
}
RINOK(result);
RINOK(ReadBasicProps(archive, 0, result));
if (Offset > 0)
{
continue; // good handler doesn't return such Offset > 0
// but there are some cases like false prefixed PK00 archive, when
// we can support it?
}
NArchive::NParser::CParseItem pi;
pi.Offset = Offset;
pi.Size = AvailPhySize;
// bool needScan = false;
if (!PhySizeDefined)
{
// it's for Z format
pi.LenIsUnknown = true;
// needScan = true;
// phySize = arcRem;
// nextNeedCheckStartOpen = false;
}
/*
if (OkPhySize_Defined)
pi.OkSize = pi.OkPhySize;
else
pi.OkSize = pi.Size;
*/
pi.NormalizeOffset();
// printf(" phySize = %8d", (unsigned)phySize);
if (mode.CanReturnArc)
{
bool isMainFormat = isMainFormatArr[(unsigned)FormatIndex];
const COpenSpecFlags &specFlags = mode.GetSpec(isForced, isMainFormat, isUnknownExt);
bool openCur = false;
if (!ErrorInfo.ThereIsTail)
openCur = true;
else
{
if (mode.ZerosTailIsAllowed)
{
RINOK(CheckZerosTail(op, Offset + PhySize));
if (ErrorInfo.IgnoreTail)
openCur = true;
}
if (!openCur)
{
openCur = specFlags.CanReturnFrontal;
if (formatIndex < 0) // format is not forced
{
if (IsPreArcFormat(ai))
{
// if (mode.SkipSfxStub)
{
openCur = false;
}
}
}
}
}
if (openCur)
{
InStream = op.stream;
Archive = archive;
return S_OK;
}
}
skipFrontalFormat[(unsigned)FormatIndex] = true;
// if (!mode.CanReturnArc)
/*
if (!ErrorInfo.ThereIsTail)
continue;
*/
if (pi.Offset == 0 && !pi.LenIsUnknown && pi.Size >= FileSize)
continue;
// printf("\nAdd offset = %d", (int)pi.Offset);
RINOK(ReadParseItemProps(archive, ai, pi));
handlerSpec->AddItem(pi);
}
}
// ---------- PARSER ----------
CUIntVector arc2sig; // formatIndex to signatureIndex
CUIntVector sig2arc; // signatureIndex to formatIndex;
{
unsigned sum = 0;
FOR_VECTOR (i, op.codecs->Formats)
{
arc2sig.Add(sum);
const CObjectVector<CByteBuffer> &sigs = op.codecs->Formats[i].Signatures;
sum += sigs.Size();
FOR_VECTOR (k, sigs)
sig2arc.Add(i);
}
}
{
const size_t kBeforeSize = 1 << 16;
const size_t kAfterSize = 1 << 20;
const size_t kBufSize = 1 << 22; // it must be more than kBeforeSize + kAfterSize
const UInt32 kNumVals = (UInt32)1 << (kNumHashBytes * 8);
CByteArr hashBuffer(kNumVals);
Byte *hash = hashBuffer;
memset(hash, 0xFF, kNumVals);
Byte prevs[256];
memset(prevs, 0xFF, sizeof(prevs));
if (sig2arc.Size() >= 0xFF)
return S_FALSE;
CUIntVector difficultFormats;
CBoolArr difficultBools(256);
{
for (unsigned i = 0; i < 256; i++)
difficultBools[i] = false;
}
bool thereAreHandlersForSearch = false;
// UInt32 maxSignatureEnd = 0;
FOR_VECTOR (i, orderIndices)
{
int index = orderIndices[i];
if (index < 0)
continue;
const CArcInfoEx &ai = op.codecs->Formats[index];
bool isDifficult = false;
// if (ai.Version < 0x91F) // we don't use parser with old DLL (before 9.31)
if (!ai.NewInterface)
isDifficult = true;
else
{
if (ai.Flags_StartOpen())
isDifficult = true;
FOR_VECTOR (k, ai.Signatures)
{
const CByteBuffer &sig = ai.Signatures[k];
/*
UInt32 signatureEnd = ai.SignatureOffset + (UInt32)sig.Size();
if (maxSignatureEnd < signatureEnd)
maxSignatureEnd = signatureEnd;
*/
if (sig.Size() < kNumHashBytes)
{
isDifficult = true;
continue;
}
thereAreHandlersForSearch = true;
UInt32 v = HASH_VAL(sig, 0);
unsigned sigIndex = arc2sig[(unsigned)index] + k;
prevs[sigIndex] = hash[v];
hash[v] = (Byte)sigIndex;
}
}
if (isDifficult)
{
difficultFormats.Add(index);
difficultBools[index] = true;
}
}
if (!thereAreHandlersForSearch)
{
// openOnlyFullArc = true;
// canReturnTailArc = true;
}
RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL));
CLimitedCachedInStream *limitedStreamSpec = new CLimitedCachedInStream;
CMyComPtr<IInStream> limitedStream = limitedStreamSpec;
limitedStreamSpec->SetStream(op.stream);
CArchiveOpenCallback_Offset *openCallback_Offset_Spec = NULL;
CMyComPtr<IArchiveOpenCallback> openCallback_Offset;
if (op.callback)
{
openCallback_Offset_Spec = new CArchiveOpenCallback_Offset;
openCallback_Offset = openCallback_Offset_Spec;
openCallback_Offset_Spec->Callback = op.callback;
openCallback_Offset_Spec->Callback.QueryInterface(IID_IArchiveOpenVolumeCallback, &openCallback_Offset_Spec->OpenVolumeCallback);
#ifndef _NO_CRYPTO
openCallback_Offset_Spec->Callback.QueryInterface(IID_ICryptoGetTextPassword, &openCallback_Offset_Spec->GetTextPassword);
#endif
}
if (op.callback)
RINOK(op.callback->SetTotal(NULL, &fileSize));
CByteBuffer &byteBuffer = limitedStreamSpec->Buffer;
byteBuffer.Alloc(kBufSize);
UInt64 callbackPrev = 0;
bool needCheckStartOpen = true; // = true, if we need to test all archives types for current pos.
bool endOfFile = false;
UInt64 bufPhyPos = 0;
size_t bytesInBuf = 0;
// UInt64 prevPos = 0;
// ---------- Main Scan Loop ----------
UInt64 pos = 0;
if (!mode.EachPos && handlerSpec->_items.Size() == 1)
{
NArchive::NParser::CParseItem &pi = handlerSpec->_items[0];
if (!pi.LenIsUnknown && pi.Offset == 0)
pos = pi.Size;
}
for (;;)
{
// printf("\nPos = %d", (int)pos);
UInt64 posInBuf = pos - bufPhyPos;
// if (pos > ((UInt64)1 << 35)) break;
if (!endOfFile)
{
if (bytesInBuf < kBufSize)
{
size_t processedSize = kBufSize - bytesInBuf;
// printf("\nRead ask = %d", (unsigned)processedSize);
UInt64 seekPos = bufPhyPos + bytesInBuf;
RINOK(op.stream->Seek(bufPhyPos + bytesInBuf, STREAM_SEEK_SET, NULL));
RINOK(ReadStream(op.stream, byteBuffer + bytesInBuf, &processedSize));
// printf(" processed = %d", (unsigned)processedSize);
if (processedSize == 0)
{
fileSize = seekPos;
endOfFile = true;
}
else
{
bytesInBuf += processedSize;
limitedStreamSpec->SetCache(processedSize, (size_t)bufPhyPos);
}
continue;
}
if (bytesInBuf < posInBuf)
{
UInt64 skipSize = posInBuf - bytesInBuf;
if (skipSize <= kBeforeSize)
{
size_t keepSize = (size_t)(kBeforeSize - skipSize);
// printf("\nmemmove skip = %d", (int)keepSize);
memmove(byteBuffer, byteBuffer + bytesInBuf - keepSize, keepSize);
bytesInBuf = keepSize;
bufPhyPos = pos - keepSize;
continue;
}
// printf("\nSkip %d", (int)(skipSize - kBeforeSize));
// RINOK(op.stream->Seek(skipSize - kBeforeSize, STREAM_SEEK_CUR, NULL));
bytesInBuf = 0;
bufPhyPos = pos - kBeforeSize;
continue;
}
if (bytesInBuf - posInBuf < kAfterSize)
{
size_t beg = (size_t)posInBuf - kBeforeSize;
// printf("\nmemmove for after beg = %d", (int)beg);
memmove(byteBuffer, byteBuffer + beg, bytesInBuf - beg);
bufPhyPos += beg;
bytesInBuf -= beg;
continue;
}
}
bool useOffsetCallback = false;
if (openCallback_Offset)
{
openCallback_Offset_Spec->Files = handlerSpec->_items.Size();
openCallback_Offset_Spec->Offset = pos;
useOffsetCallback = (!op.openType.CanReturnArc || handlerSpec->_items.Size() > 1);
if (pos >= callbackPrev + (1 << 23))
{
RINOK(openCallback_Offset_Spec->SetCompleted(NULL, NULL));
callbackPrev = pos;
}
}
{
UInt64 endPos = bufPhyPos + bytesInBuf;
if (fileSize < endPos)
{
FileSize = fileSize; // why ????
fileSize = endPos;
}
}
size_t availSize = bytesInBuf - (size_t)posInBuf;
if (availSize < kNumHashBytes)
break;
size_t scanSize = availSize -
((availSize >= kAfterSize) ? kAfterSize : kNumHashBytes);
{
/*
UInt64 scanLimit = openOnlyFullArc ?
maxSignatureEnd :
op.openType.ScanSize + maxSignatureEnd;
*/
if (!mode.CanReturnParser)
{
if (pos > maxStartOffset)
break;
UInt64 remScan = maxStartOffset - pos;
if (scanSize > remScan)
scanSize = (size_t)remScan;
}
}
scanSize++;
const Byte *buf = byteBuffer + (size_t)posInBuf;
size_t ppp = 0;
if (!needCheckStartOpen)
{
for (; ppp < scanSize && hash[HASH_VAL(buf, ppp)] == 0xFF; ppp++);
pos += ppp;
if (ppp == scanSize)
continue;
}
UInt32 v = HASH_VAL(buf, ppp);
bool nextNeedCheckStartOpen = true;
unsigned i = hash[v];
unsigned indexOfDifficult = 0;
// ---------- Open Loop for Current Pos ----------
bool wasOpen = false;
for (;;)
{
unsigned index;
bool isDifficult;
if (needCheckStartOpen && indexOfDifficult < difficultFormats.Size())
{
index = difficultFormats[indexOfDifficult++];
isDifficult = true;
}
else
{
if (i == 0xFF)
break;
index = sig2arc[i];
unsigned sigIndex = i - arc2sig[index];
i = prevs[i];
if (needCheckStartOpen && difficultBools[index])
continue;
const CArcInfoEx &ai = op.codecs->Formats[index];
if (pos < ai.SignatureOffset)
continue;
/*
if (openOnlyFullArc)
if (pos != ai.SignatureOffset)
continue;
*/
const CByteBuffer &sig = ai.Signatures[sigIndex];
if (ppp + sig.Size() > availSize
|| !TestSignature(buf + ppp, sig, sig.Size()))
continue;
// printf("\nSignature OK: %10S %8x %5d", (const wchar_t *)ai.Name, (int)pos, (int)(pos - prevPos));
// prevPos = pos;
isDifficult = false;
}
const CArcInfoEx &ai = op.codecs->Formats[index];
if ((isDifficult && pos == 0) || ai.SignatureOffset == pos)
{
// we don't check same archive second time */
if (skipFrontalFormat[index])
continue;
}
UInt64 startArcPos = pos;
if (!isDifficult)
{
if (pos < ai.SignatureOffset)
continue;
startArcPos = pos - ai.SignatureOffset;
/*
// we don't need the check for Z files
if (startArcPos < handlerSpec->GetLastEnd())
continue;
*/
}
if (ai.IsArcFunc && startArcPos >= bufPhyPos)
{
size_t offsetInBuf = (size_t)(startArcPos - bufPhyPos);
if (offsetInBuf < bytesInBuf)
{
UInt32 isArcRes = ai.IsArcFunc(byteBuffer + offsetInBuf, bytesInBuf - offsetInBuf);
if (isArcRes == k_IsArc_Res_NO)
continue;
if (isArcRes == k_IsArc_Res_NEED_MORE && endOfFile)
continue;
/*
if (isArcRes == k_IsArc_Res_YES_LOW_PROB)
{
// if (pos != ai.SignatureOffset)
continue;
}
*/
}
// printf("\nIsArc OK: %S", (const wchar_t *)ai.Name);
}
/*
if (pos == 67109888)
pos = pos;
*/
PRF(printf("\npos = %9I64d : %S", pos, (const wchar_t *)ai.Name));
bool isMainFormat = isMainFormatArr[index];
const COpenSpecFlags &specFlags = mode.GetSpec(isForced, isMainFormat, isUnknownExt);
CMyComPtr<IInArchive> archive;
RINOK(PrepareToOpen(op, index, archive));
if (!archive)
return E_FAIL;
// OutputDebugStringW(ai.Name);
UInt64 rem = fileSize - startArcPos;
UInt64 arcStreamOffset = 0;
if (ai.Flags_UseGlobalOffset())
{
limitedStreamSpec->InitAndSeek(0, fileSize);
limitedStream->Seek(startArcPos, STREAM_SEEK_SET, NULL);
}
else
{
limitedStreamSpec->InitAndSeek(startArcPos, rem);
arcStreamOffset = startArcPos;
}
UInt64 maxCheckStartPosition = 0;
if (openCallback_Offset)
{
openCallback_Offset_Spec->Files = handlerSpec->_items.Size();
openCallback_Offset_Spec->Offset = startArcPos;
}
// HRESULT result = archive->Open(limitedStream, &maxCheckStartPosition, openCallback_Offset);
extractCallback_To_OpenCallback_Spec->Files = 0;
extractCallback_To_OpenCallback_Spec->Offset = startArcPos;
HRESULT result = OpenArchiveSpec(archive, true, limitedStream, &maxCheckStartPosition,
useOffsetCallback ? (IArchiveOpenCallback *)openCallback_Offset : (IArchiveOpenCallback *)op.callback,
extractCallback_To_OpenCallback);
RINOK(ReadBasicProps(archive, ai.Flags_UseGlobalOffset() ? 0 : startArcPos, result));
bool isOpen = false;
if (result == S_FALSE)
{
if (!mode.CanReturnParser)
{
if (formatIndex < 0 && ErrorInfo.IsArc_After_NonOpen())
{
ErrorInfo.ErrorFormatIndex = index;
NonOpen_ErrorInfo = ErrorInfo;
// if archive was detected, we don't need additional open attempts
return S_FALSE;
}
continue;
}
if (!ErrorInfo.IsArc_After_NonOpen() || !PhySizeDefined || PhySize == 0)
continue;
}
else
{
isOpen = true;
RINOK(result);
PRF(printf(" OK "));
}
// fprintf(stderr, "\n %8X %S", startArcPos, Path);
// printf("\nOpen OK: %S", ai.Name);
NArchive::NParser::CParseItem pi;
pi.Offset = startArcPos;
if (ai.Flags_UseGlobalOffset())
pi.Offset = Offset;
else if (Offset != 0)
return E_FAIL;
UInt64 arcRem = FileSize - pi.Offset;
UInt64 phySize = arcRem;
bool phySizeDefined = PhySizeDefined;
if (phySizeDefined)
{
if (pi.Offset + PhySize > FileSize)
{
// ErrorInfo.ThereIsTail = true;
PhySize = FileSize - pi.Offset;
}
phySize = PhySize;
}
if (phySize == 0 || (UInt64)phySize > ((UInt64)1 << 63))
return E_FAIL;
/*
if (!ai.UseGlobalOffset)
{
if (phySize > arcRem)
{
ThereIsTail = true;
phySize = arcRem;
}
}
*/
bool needScan = false;
if (isOpen && !phySizeDefined)
{
// it's for Z format
pi.LenIsUnknown = true;
needScan = true;
phySize = arcRem;
nextNeedCheckStartOpen = false;
}
pi.Size = phySize;
/*
if (OkPhySize_Defined)
pi.OkSize = OkPhySize;
*/
pi.NormalizeOffset();
// printf(" phySize = %8d", (unsigned)phySize);
/*
if (needSkipFullArc)
if (pi.Offset == 0 && phySizeDefined && pi.Size >= fileSize)
continue;
*/
if (pi.Offset == 0 && !pi.LenIsUnknown && pi.Size >= FileSize)
{
// it's possible for dmg archives
if (!mode.CanReturnArc)
continue;
}
if (mode.EachPos)
pos++;
else if (needScan)
{
pos++;
/*
if (!OkPhySize_Defined)
pos++;
else
pos = pi.Offset + pi.OkSize;
*/
}
else
pos = pi.Offset + pi.Size;
RINOK(ReadParseItemProps(archive, ai, pi));
if (pi.Offset < startArcPos && !mode.EachPos /* && phySizeDefined */)
{
/* It's for DMG format.
This code deletes all previous items that are included to current item */
while (!handlerSpec->_items.IsEmpty())
{
{
const NArchive::NParser::CParseItem &back = handlerSpec->_items.Back();
if (back.Offset < pi.Offset)
break;
if (back.Offset + back.Size > pi.Offset + pi.Size)
break;
}
handlerSpec->_items.DeleteBack();
}
}
if (isOpen && mode.CanReturnArc && phySizeDefined)
{
// if (pi.Offset + pi.Size >= fileSize)
bool openCur = false;
bool thereIsTail = ErrorInfo.ThereIsTail;
if (thereIsTail && mode.ZerosTailIsAllowed)
{
RINOK(CheckZerosTail(op, arcStreamOffset + Offset + PhySize));
if (ErrorInfo.IgnoreTail)
thereIsTail = false;
}
if (pi.Offset != 0)
{
if (!pi.IsNotArcType)
if (thereIsTail)
openCur = specFlags.CanReturnMid;
else
openCur = specFlags.CanReturnTail;
}
else
{
if (!thereIsTail)
openCur = true;
else
openCur = specFlags.CanReturnFrontal;
if (formatIndex >= -2)
openCur = true;
}
if (formatIndex < 0 && pi.IsSelfExe /* && mode.SkipSfxStub */)
openCur = false;
// We open file as SFX, if there is front archive or first archive is "Self Executable"
if (!openCur && !pi.IsSelfExe && !thereIsTail &&
(!pi.IsNotArcType || pi.Offset == 0))
{
if (handlerSpec->_items.IsEmpty())
{
if (specFlags.CanReturnTail)
openCur = true;
}
else if (handlerSpec->_items.Size() == 1)
{
if (handlerSpec->_items[0].IsSelfExe)
{
if (mode.SpecUnknownExt.CanReturnTail)
openCur = true;
}
}
}
if (openCur)
{
InStream = op.stream;
Archive = archive;
FormatIndex = index;
ArcStreamOffset = arcStreamOffset;
return S_OK;
}
}
/*
if (openOnlyFullArc)
{
ErrorInfo.ClearErrors();
return S_FALSE;
}
*/
pi.FormatIndex = index;
// printf("\nAdd offset = %d", (int)pi.Offset);
handlerSpec->AddItem(pi);
wasOpen = true;
break;
}
// ---------- End of Open Loop for Current Pos ----------
if (!wasOpen)
pos++;
needCheckStartOpen = (nextNeedCheckStartOpen && wasOpen);
}
// ---------- End of Main Scan Loop ----------
/*
if (handlerSpec->_items.Size() == 1)
{
const NArchive::NParser::CParseItem &pi = handlerSpec->_items[0];
if (pi.Size == fileSize && pi.Offset == 0)
{
Archive = archive;
FormatIndex2 = pi.FormatIndex;
return S_OK;
}
}
*/
if (mode.CanReturnParser)
{
bool returnParser = (handlerSpec->_items.Size() == 1); // it's possible if fileSize was not correct at start of parsing
handlerSpec->AddUnknownItem(fileSize);
if (handlerSpec->_items.Size() == 0)
return S_FALSE;
if (returnParser || handlerSpec->_items.Size() != 1)
{
// return S_FALSE;
handlerSpec->_stream = op.stream;
Archive = handler;
ErrorInfo.ClearErrors();
IsParseArc = true;
FormatIndex = -1; // It's parser
Offset = 0;
return S_OK;
}
}
}
#endif
if (!Archive)
return S_FALSE;
return S_OK;
}
HRESULT CArc::OpenStream(const COpenOptions &op)
{
RINOK(OpenStream2(op));
// PrintNumber("op.formatIndex 3", op.formatIndex);
if (Archive)
{
GetRawProps.Release();
GetRootProps.Release();
Archive->QueryInterface(IID_IArchiveGetRawProps, (void **)&GetRawProps);
Archive->QueryInterface(IID_IArchiveGetRootProps, (void **)&GetRootProps);
RINOK(Archive_GetArcBoolProp(Archive, kpidIsTree, IsTree));
RINOK(Archive_GetArcBoolProp(Archive, kpidIsDeleted, Ask_Deleted));
RINOK(Archive_GetArcBoolProp(Archive, kpidIsAltStream, Ask_AltStream));
RINOK(Archive_GetArcBoolProp(Archive, kpidIsAux, Ask_Aux));
RINOK(Archive_GetArcBoolProp(Archive, kpidINode, Ask_INode));
RINOK(Archive_GetArcBoolProp(Archive, kpidReadOnly, IsReadOnly));
const UString fileName = ExtractFileNameFromPath(Path);
UString extension;
{
int dotPos = fileName.ReverseFind_Dot();
if (dotPos >= 0)
extension = fileName.Ptr(dotPos + 1);
}
DefaultName.Empty();
if (FormatIndex >= 0)
{
const CArcInfoEx &ai = op.codecs->Formats[FormatIndex];
if (ai.Exts.Size() == 0)
DefaultName = GetDefaultName2(fileName, UString(), UString());
else
{
int subExtIndex = ai.FindExtension(extension);
if (subExtIndex < 0)
subExtIndex = 0;
const CArcExtInfo &extInfo = ai.Exts[subExtIndex];
DefaultName = GetDefaultName2(fileName, extInfo.Ext, extInfo.AddExt);
}
}
}
return S_OK;
}
#ifdef _SFX
#ifdef _WIN32
static const char *k_ExeExt = ".exe";
static const unsigned k_ExeExt_Len = 4;
#else
static const char *k_ExeExt = "";
static const unsigned k_ExeExt_Len = 0;
#endif
#endif
HRESULT CArc::OpenStreamOrFile(COpenOptions &op)
{
CMyComPtr<IInStream> fileStream;
CMyComPtr<ISequentialInStream> seqStream;
CInFileStream *fileStreamSpec = NULL;
if (op.stdInMode)
{
seqStream = new CStdInFileStream;
op.seqStream = seqStream;
}
else if (!op.stream)
{
fileStreamSpec = new CInFileStream;
fileStream = fileStreamSpec;
Path = filePath;
if (!fileStreamSpec->Open(us2fs(Path)))
{
return GetLastError();
}
op.stream = fileStream;
#ifdef _SFX
IgnoreSplit = true;
#endif
}
/*
if (callback)
{
UInt64 fileSize;
RINOK(op.stream->Seek(0, STREAM_SEEK_END, &fileSize));
RINOK(op.callback->SetTotal(NULL, &fileSize))
}
*/
HRESULT res = OpenStream(op);
IgnoreSplit = false;
#ifdef _SFX
if (res != S_FALSE
|| !fileStreamSpec
|| !op.callbackSpec
|| NonOpen_ErrorInfo.IsArc_After_NonOpen())
return res;
{
if (filePath.Len() > k_ExeExt_Len
&& StringsAreEqualNoCase_Ascii(filePath.RightPtr(k_ExeExt_Len), k_ExeExt))
{
const UString path2 = filePath.Left(filePath.Len() - k_ExeExt_Len);
FOR_VECTOR (i, op.codecs->Formats)
{
const CArcInfoEx &ai = op.codecs->Formats[i];
if (ai.IsSplit())
continue;
UString path3 = path2;
path3 += L'.';
path3 += ai.GetMainExt(); // "7z" for SFX.
Path = path3;
Path.AddAscii(".001");
bool isOk = op.callbackSpec->SetSecondFileInfo(us2fs(Path));
if (!isOk)
{
Path = path3;
isOk = op.callbackSpec->SetSecondFileInfo(us2fs(Path));
}
if (isOk)
{
if (fileStreamSpec->Open(us2fs(Path)))
{
op.stream = fileStream;
NonOpen_ErrorInfo.ClearErrors_Full();
if (OpenStream(op) == S_OK)
return S_OK;
}
}
}
}
}
#endif
return res;
}
void CArchiveLink::KeepModeForNextOpen()
{
for (unsigned i = Arcs.Size(); i != 0;)
{
i--;
CMyComPtr<IArchiveKeepModeForNextOpen> keep;
Arcs[i].Archive->QueryInterface(IID_IArchiveKeepModeForNextOpen, (void **)&keep);
if (keep)
keep->KeepModeForNextOpen();
}
}
HRESULT CArchiveLink::Close()
{
for (unsigned i = Arcs.Size(); i != 0;)
{
i--;
RINOK(Arcs[i].Close());
}
IsOpen = false;
// ErrorsText.Empty();
return S_OK;
}
void CArchiveLink::Release()
{
// NonOpenErrorFormatIndex = -1;
NonOpen_ErrorInfo.ClearErrors();
NonOpen_ArcPath.Empty();
while (!Arcs.IsEmpty())
Arcs.DeleteBack();
}
/*
void CArchiveLink::Set_ErrorsText()
{
FOR_VECTOR(i, Arcs)
{
const CArc &arc = Arcs[i];
if (!arc.ErrorFlagsText.IsEmpty())
{
if (!ErrorsText.IsEmpty())
ErrorsText.Add_LF();
ErrorsText += GetUnicodeString(arc.ErrorFlagsText);
}
if (!arc.ErrorMessage.IsEmpty())
{
if (!ErrorsText.IsEmpty())
ErrorsText.Add_LF();
ErrorsText += arc.ErrorMessage;
}
if (!arc.WarningMessage.IsEmpty())
{
if (!ErrorsText.IsEmpty())
ErrorsText.Add_LF();
ErrorsText += arc.WarningMessage;
}
}
}
*/
HRESULT CArchiveLink::Open(COpenOptions &op)
{
Release();
if (op.types->Size() >= 32)
return E_NOTIMPL;
HRESULT resSpec;
for (;;)
{
resSpec = S_OK;
op.openType = COpenType();
if (op.types->Size() >= 1)
{
COpenType latest;
if (Arcs.Size() < op.types->Size())
latest = (*op.types)[op.types->Size() - Arcs.Size() - 1];
else
{
latest = (*op.types)[0];
if (!latest.Recursive)
break;
}
op.openType = latest;
}
else if (Arcs.Size() >= 32)
break;
/*
op.formatIndex = -1;
if (op.types->Size() >= 1)
{
int latest;
if (Arcs.Size() < op.types->Size())
latest = (*op.types)[op.types->Size() - Arcs.Size() - 1];
else
{
latest = (*op.types)[0];
if (latest != -2 && latest != -3)
break;
}
if (latest >= 0)
op.formatIndex = latest;
else if (latest == -1 || latest == -2)
{
// default
}
else if (latest == -3)
op.formatIndex = -2;
else
op.formatIndex = latest + 2;
}
else if (Arcs.Size() >= 32)
break;
*/
if (Arcs.IsEmpty())
{
CArc arc;
arc.filePath = op.filePath;
arc.Path = op.filePath;
arc.SubfileIndex = (UInt32)(Int32)-1;
HRESULT result = arc.OpenStreamOrFile(op);
if (result != S_OK)
{
if (result == S_FALSE)
{
NonOpen_ErrorInfo = arc.NonOpen_ErrorInfo;
// NonOpenErrorFormatIndex = arc.ErrorFormatIndex;
NonOpen_ArcPath = arc.Path;
}
return result;
}
Arcs.Add(arc);
continue;
}
// PrintNumber("op.formatIndex 11", op.formatIndex);
const CArc &arc = Arcs.Back();
if (op.types->Size() > Arcs.Size())
resSpec = E_NOTIMPL;
UInt32 mainSubfile;
{
NCOM::CPropVariant prop;
RINOK(arc.Archive->GetArchiveProperty(kpidMainSubfile, &prop));
if (prop.vt == VT_UI4)
mainSubfile = prop.ulVal;
else
break;
UInt32 numItems;
RINOK(arc.Archive->GetNumberOfItems(&numItems));
if (mainSubfile >= numItems)
break;
}
CMyComPtr<IInArchiveGetStream> getStream;
if (arc.Archive->QueryInterface(IID_IInArchiveGetStream, (void **)&getStream) != S_OK || !getStream)
break;
CMyComPtr<ISequentialInStream> subSeqStream;
if (getStream->GetStream(mainSubfile, &subSeqStream) != S_OK || !subSeqStream)
break;
CMyComPtr<IInStream> subStream;
if (subSeqStream.QueryInterface(IID_IInStream, &subStream) != S_OK || !subStream)
break;
CArc arc2;
RINOK(arc.GetItemPath(mainSubfile, arc2.Path));
bool zerosTailIsAllowed;
RINOK(Archive_GetItemBoolProp(arc.Archive, mainSubfile, kpidZerosTailIsAllowed, zerosTailIsAllowed));
if (op.callback)
{
CMyComPtr<IArchiveOpenSetSubArchiveName> setSubArchiveName;
op.callback->QueryInterface(IID_IArchiveOpenSetSubArchiveName, (void **)&setSubArchiveName);
if (setSubArchiveName)
setSubArchiveName->SetSubArchiveName(arc2.Path);
}
arc2.SubfileIndex = mainSubfile;
// CIntVector incl;
CIntVector excl;
COpenOptions op2;
#ifndef _SFX
op2.props = op.props;
#endif
op2.codecs = op.codecs;
// op2.types = &incl;
op2.openType = op.openType;
op2.openType.ZerosTailIsAllowed = zerosTailIsAllowed;
op2.excludedFormats = !
op2.stdInMode = false;
op2.stream = subStream;
op2.filePath = arc2.Path;
op2.callback = op.callback;
op2.callbackSpec = op.callbackSpec;
HRESULT result = arc2.OpenStream(op2);
resSpec = (op.types->Size() == 0 ? S_OK : S_FALSE);
if (result == S_FALSE)
{
NonOpen_ErrorInfo = arc2.ErrorInfo;
NonOpen_ArcPath = arc2.Path;
break;
}
RINOK(result);
RINOK(arc.GetItemMTime(mainSubfile, arc2.MTime, arc2.MTimeDefined));
Arcs.Add(arc2);
}
IsOpen = !Arcs.IsEmpty();
return resSpec;
}
HRESULT CArchiveLink::Open2(COpenOptions &op, IOpenCallbackUI *callbackUI)
{
VolumesSize = 0;
COpenCallbackImp *openCallbackSpec = new COpenCallbackImp;
CMyComPtr<IArchiveOpenCallback> callback = openCallbackSpec;
openCallbackSpec->Callback = callbackUI;
FString prefix, name;
if (!op.stream && !op.stdInMode)
{
NFile::NDir::GetFullPathAndSplit(us2fs(op.filePath), prefix, name);
openCallbackSpec->Init(prefix, name);
}
else
{
openCallbackSpec->SetSubArchiveName(op.filePath);
}
op.callback = callback;
op.callbackSpec = openCallbackSpec;
HRESULT res = Open(op);
PasswordWasAsked = openCallbackSpec->PasswordWasAsked;
// Password = openCallbackSpec->Password;
RINOK(res);
// VolumePaths.Add(fs2us(prefix + name));
FOR_VECTOR (i, openCallbackSpec->FileNames_WasUsed)
{
if (openCallbackSpec->FileNames_WasUsed[i])
{
VolumePaths.Add(fs2us(prefix) + openCallbackSpec->FileNames[i]);
VolumesSize += openCallbackSpec->FileSizes[i];
}
}
// VolumesSize = openCallbackSpec->TotalSize;
return S_OK;
}
HRESULT CArc::ReOpen(const COpenOptions &op)
{
ErrorInfo.ClearErrors();
ErrorInfo.ErrorFormatIndex = -1;
UInt64 fileSize = 0;
if (op.stream)
{
RINOK(op.stream->Seek(0, STREAM_SEEK_END, &fileSize));
RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL));
}
FileSize = fileSize;
CMyComPtr<IInStream> stream2;
Int64 globalOffset = GetGlobalOffset();
if (globalOffset <= 0)
stream2 = op.stream;
else
{
CTailInStream *tailStreamSpec = new CTailInStream;
stream2 = tailStreamSpec;
tailStreamSpec->Stream = op.stream;
tailStreamSpec->Offset = globalOffset;
tailStreamSpec->Init();
RINOK(tailStreamSpec->SeekToStart());
}
// There are archives with embedded STUBs (like ZIP), so we must support signature scanning
// But for another archives we can use 0 here. So the code can be fixed !!!
UInt64 maxStartPosition = kMaxCheckStartPosition;
HRESULT res = Archive->Open(stream2, &maxStartPosition, op.callback);
if (res == S_OK)
{
RINOK(ReadBasicProps(Archive, globalOffset, res));
ArcStreamOffset = globalOffset;
if (ArcStreamOffset != 0)
InStream = op.stream;
}
return res;
}
HRESULT CArchiveLink::Open3(COpenOptions &op, IOpenCallbackUI *callbackUI)
{
HRESULT res = Open2(op, callbackUI);
if (callbackUI)
{
RINOK(callbackUI->Open_Finished());
}
return res;
}
HRESULT CArchiveLink::ReOpen(COpenOptions &op)
{
if (Arcs.Size() > 1)
return E_NOTIMPL;
CObjectVector<COpenType> inc;
CIntVector excl;
op.types = &inc;
op.excludedFormats = !
op.stdInMode = false;
op.stream = NULL;
if (Arcs.Size() == 0) // ???
return Open2(op, NULL);
COpenCallbackImp *openCallbackSpec = new COpenCallbackImp;
CMyComPtr<IArchiveOpenCallback> openCallbackNew = openCallbackSpec;
openCallbackSpec->Callback = NULL;
openCallbackSpec->ReOpenCallback = op.callback;
{
FString dirPrefix, fileName;
NFile::NDir::GetFullPathAndSplit(us2fs(op.filePath), dirPrefix, fileName);
openCallbackSpec->Init(dirPrefix, fileName);
}
CInFileStream *fileStreamSpec = new CInFileStream;
CMyComPtr<IInStream> stream(fileStreamSpec);
if (!fileStreamSpec->Open(us2fs(op.filePath)))
return GetLastError();
op.stream = stream;
CArc &arc = Arcs[0];
HRESULT res = arc.ReOpen(op);
PasswordWasAsked = openCallbackSpec->PasswordWasAsked;
// Password = openCallbackSpec->Password;
IsOpen = (res == S_OK);
return res;
}
#ifndef _SFX
bool ParseComplexSize(const wchar_t *s, UInt64 &result)
{
result = 0;
const wchar_t *end;
UInt64 number = ConvertStringToUInt64(s, &end);
if (end == s)
return false;
if (*end == 0)
{
result = number;
return true;
}
if (end[1] != 0)
return false;
unsigned numBits;
switch (MyCharLower_Ascii(*end))
{
case 'b': result = number; return true;
case 'k': numBits = 10; break;
case 'm': numBits = 20; break;
case 'g': numBits = 30; break;
case 't': numBits = 40; break;
default: return false;
}
if (number >= ((UInt64)1 << (64 - numBits)))
return false;
result = number << numBits;
return true;
}
static bool ParseTypeParams(const UString &s, COpenType &type)
{
if (s[0] == 0)
return true;
if (s[1] == 0)
{
switch ((unsigned)(Byte)s[0])
{
case 'e': type.EachPos = true; return true;
case 'a': type.CanReturnArc = true; return true;
case 'r': type.Recursive = true; return true;
}
return false;
}
if (s[0] == 's')
{
UInt64 result;
if (!ParseComplexSize(s.Ptr(1), result))
return false;
type.MaxStartOffset = result;
type.MaxStartOffset_Defined = true;
return true;
}
return false;
}
bool ParseType(CCodecs &codecs, const UString &s, COpenType &type)
{
int pos2 = s.Find(L':');
{
UString name;
if (pos2 < 0)
{
name = s;
pos2 = s.Len();
}
else
{
name = s.Left(pos2);
pos2++;
}
int index = codecs.FindFormatForArchiveType(name);
type.Recursive = false;
if (index < 0)
{
if (name[0] == '*')
{
if (name[1] != 0)
return false;
}
else if (name[0] == '#')
{
if (name[1] != 0)
return false;
type.CanReturnArc = false;
type.CanReturnParser = true;
}
else
return false;
}
type.FormatIndex = index;
}
for (unsigned i = pos2; i < s.Len();)
{
int next = s.Find(L':', i);
if (next < 0)
next = s.Len();
const UString name = s.Mid(i, next - i);
if (name.IsEmpty())
return false;
if (!ParseTypeParams(name, type))
return false;
i = next + 1;
}
return true;
}
bool ParseOpenTypes(CCodecs &codecs, const UString &s, CObjectVector<COpenType> &types)
{
types.Clear();
for (unsigned pos = 0; pos < s.Len();)
{
int pos2 = s.Find(L'.', pos);
if (pos2 < 0)
pos2 = s.Len();
UString name = s.Mid(pos, pos2 - pos);
if (name.IsEmpty())
return false;
COpenType type;
if (!ParseType(codecs, name, type))
return false;
types.Add(type);
pos = pos2 + 1;
}
return true;
}
#endif
|
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// test sized operator delete[] replacement.
// Note that sized delete operator definitions below are simply ignored
// when sized deallocation is not supported, e.g., prior to C++14.
// UNSUPPORTED: sanitizer-new-delete
// XFAIL: availability_markup=macosx10.11
// XFAIL: availability_markup=macosx10.10
// XFAIL: availability_markup=macosx10.9
// XFAIL: availability_markup=macosx10.8
// XFAIL: availability_markup=macosx10.7
// NOTE: Only clang-3.7 and GCC 5.1 and greater support -fsized-deallocation.
// REQUIRES: fsized-deallocation
// RUN: %build -fsized-deallocation
// RUN: %run
#if !defined(__cpp_sized_deallocation)
# error __cpp_sized_deallocation should be defined
#endif
#if !(__cpp_sized_deallocation >= 201309L)
# error expected __cpp_sized_deallocation >= 201309L
#endif
#include <new>
#include <cstddef>
#include <cstdlib>
#include <cassert>
#include "test_macros.h"
int unsized_delete_called = 0;
int unsized_delete_nothrow_called = 0;
int sized_delete_called = 0;
void operator delete[](void* p) TEST_NOEXCEPT
{
++unsized_delete_called;
std::free(p);
}
void operator delete[](void* p, const std::nothrow_t&) TEST_NOEXCEPT
{
++unsized_delete_nothrow_called;
std::free(p);
}
void operator delete[](void* p, std::size_t) TEST_NOEXCEPT
{
++sized_delete_called;
std::free(p);
}
// NOTE: Use a class with a non-trivial destructor as the test type in order
// to ensure the correct overload is called.
// C++14 5.3.5 [expr.delete]p10
// - If the type is complete and if, for the second alternative (delete array)
// only, the operand is a pointer to a class type with a non-trivial
// destructor or a (possibly multi-dimensional) array thereof, the function
// with two parameters is selected.
// - Otherwise, it is unspecified which of the two deallocation functions is
// selected.
struct A { ~A() {} };
int main()
{
A* x = new A[3];
assert(0 == unsized_delete_called);
assert(0 == unsized_delete_nothrow_called);
assert(0 == sized_delete_called);
delete [] x;
assert(0 == unsized_delete_called);
assert(0 == unsized_delete_nothrow_called);
assert(1 == sized_delete_called);
}
|
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "paddle/fluid/operators/fused/fusion_seqconv_eltadd_relu_op.h"
#include <algorithm> // for min, max
#include <string>
#include "paddle/fluid/operators/math/fc.h"
#include "paddle/phi/kernels/funcs/blas/blas.h"
namespace paddle {
namespace operators {
void FusionSeqConvEltAddReluOp::InferShape(
framework::InferShapeContext* ctx) const {
OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X",
"fusion_seqconv_eltadd_relu");
OP_INOUT_CHECK(ctx->HasInput("Filter"), "Input", "Filter",
"fusion_seqconv_eltadd_relu");
OP_INOUT_CHECK(ctx->HasInput("Bias"), "Input", "Bias",
"fusion_seqconv_eltadd_relu");
OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out",
"fusion_seqconv_eltadd_relu");
OP_INOUT_CHECK(ctx->HasOutput("ColMat"), "Output", "ColMat",
"fusion_seqconv_eltadd_relu");
auto x_dims = ctx->GetInputDim("X");
auto w_dims = ctx->GetInputDim("Filter");
int context_length = ctx->Attrs().Get<int>("contextLength");
PADDLE_ENFORCE_EQ(ctx->Attrs().Get<int>("contextStride"), 1,
platform::errors::InvalidArgument(
"Currently, FusionSeqConvEltAddReluOp only supports "
"contextStride=1, but received value is: %d.",
ctx->Attrs().Get<int>("contextStride")));
PADDLE_ENFORCE_EQ(
x_dims.size(), 2,
platform::errors::InvalidArgument(
"Input(X) should be 2-D tensor, but reveiced value is: %d.",
x_dims.size()));
PADDLE_ENFORCE_EQ(
w_dims.size(), 2,
platform::errors::InvalidArgument(
"Filter should be 2-D tensor, but reveiced value is: %d.",
w_dims.size()));
PADDLE_ENFORCE_EQ(w_dims[0], context_length * x_dims[1],
platform::errors::InvalidArgument(
"Filter's height should be equal to context_length * "
"input_hidden_size, but received Filter height is: %d,"
"context_length is: %d, input_hidden_size is: %d.",
w_dims[0], context_length, x_dims[1]));
PADDLE_ENFORCE_GT(
context_length + ctx->Attrs().Get<int>("contextStart"), 0,
platform::errors::InvalidArgument(
"contextStart size should be smaller than contextLength, "
"but received context_length is: %d, contextStart is: "
"%d.",
context_length, ctx->Attrs().Get<int>("contextStart")));
ctx->SetOutputDim("Out", {x_dims[0], w_dims[1]});
ctx->SetOutputDim("ColMat", {x_dims[0], w_dims[0]});
ctx->ShareLoD("X", "Out");
}
framework::OpKernelType FusionSeqConvEltAddReluOp::GetExpectedKernelType(
const framework::ExecutionContext& ctx) const {
return framework::OpKernelType(
OperatorWithKernel::IndicateVarDataType(ctx, "X"), ctx.device_context());
}
void FusionSeqConvEltAddReluOpMaker::Make() {
AddInput("X",
"(LoDTensor) the input is a LodTensor, which support "
"variable-time length input sequence. The underlying tensor in "
"this LoDTensor is a matrix with shape (T X M), where T is the "
"total time steps in this mini-batch, M is the dim size of x.");
// PaddingData only support false yet, should be ensured at pass.
AddInput("Filter",
"(Tensor) same as the input(Filter) of sequence conv op is an "
"learnable parameter."
"This is a tensor with shape (K, N), where K is the "
"context_length * dim size of x, N is the output feature size.");
AddInput("Bias",
"(Tensor) the learnable weights. shape (1, N), where N is the "
"output feature size");
AddOutput(
"Out",
"(LoDTensor) the output(Out) is a LodTensor, which support "
"variable-time length output sequence. The underlying tensor in "
"this LoDTensor is a matrix with shape (T, N), where, T is the "
"total time steps in this mini-batch, N is the output feature size.");
AddOutput("ColMat",
"(Tensor) (T, K), where T is where T is the "
"total time steps in this mini-batch, K is height of Filter")
.AsIntermediate();
AddAttr<int>("contextLength",
"(int) the contextLength of FusionSeqConvEltAddReluOp is the "
"height of the convolution kernel.")
.GreaterThan(0);
AddAttr<int>("contextStart",
"(int, default:0) the contextStart of FusionSeqConvEltAddReluOp "
"represents the beginning of the convolution of the number of "
"rows of sequence, which can be negative. The negative number "
"means to pad contextStart time-steps of zeros or learnable "
"parameters at the beginning of each instance. The positive "
"number means to skip contextStart time-steps of each "
"instance.")
.SetDefault(0);
AddAttr<int>(
"contextStride",
"(int, default:1) the contextStride of FusionSeqConvEltAddReluOp "
"represents the stride length of convolution kernel. "
"Currently, FusionSeqConvEltAddReluOp only supports"
"contextStride=1.")
.SetDefault(1)
.GreaterThan(0);
AddComment(R"DOC(
Fusion Sequence Conv and ElementwiseAdd Operator.
)DOC");
}
template <typename T>
class FusionSeqConvEltAddReluKernel : public framework::OpKernel<T> {
public:
void Compute(const framework::ExecutionContext& ctx) const override {
using DeviceContext = paddle::platform::CPUDeviceContext;
auto* x = ctx.Input<LoDTensor>("X");
auto* w = ctx.Input<Tensor>("Filter");
auto* b = ctx.Input<Tensor>("Bias");
auto* y = ctx.Output<LoDTensor>("Out");
auto* col = ctx.Output<Tensor>("ColMat");
auto x_lod = x->lod();
auto x_dims = x->dims();
auto w_dims = w->dims();
PADDLE_ENFORCE_EQ(
b->numel(), w_dims[1],
platform::errors::InvalidArgument(
"bias size should be equal to weights feature size, but received "
"bias size is: %d, weights feature size is: %d.",
b->numel(), w_dims[1]));
PADDLE_ENFORCE_EQ(
x_lod.size(), 1UL,
platform::errors::InvalidArgument(
"Only support one level sequence now, but received value is: %d.",
x_lod.size()));
const T* x_data = x->data<T>();
const T* w_data = w->data<T>();
const T* b_data = b->data<T>();
T* y_data = y->mutable_data<T>(ctx.GetPlace());
T* col_data = col->mutable_data<T>(ctx.GetPlace());
int context_start = ctx.Attr<int>("contextStart");
int context_length = ctx.Attr<int>("contextLength");
int up_pad = std::max(0, -context_start);
int down_pad = std::max(0, context_start + context_length - 1);
// im2col
int src_mat_w = static_cast<int>(x_dims[1]);
int src_mat_w_sz = src_mat_w * sizeof(T);
int col_mat_w = static_cast<int>(w_dims[0]);
int col_mat_w_sz = col_mat_w * sizeof(T);
for (int i = 0; i < static_cast<int>(x_lod[0].size()) - 1; ++i) {
int st = x_lod[0][i];
int ed = x_lod[0][i + 1];
const T* src_data = x_data + st * src_mat_w;
T* dst_data = col_data + st * col_mat_w;
int seq_len = ed - st;
if (seq_len > up_pad + down_pad) {
// zero all up_pad and fill data
std::memset(dst_data, 0, up_pad * col_mat_w_sz);
dst_data = dst_data + up_pad * src_mat_w;
int copy_size = col_mat_w_sz - up_pad * src_mat_w_sz;
for (int j = 0; j < up_pad; ++j) {
// blas.VCOPY?
std::memcpy(dst_data, src_data, copy_size);
dst_data += (col_mat_w - src_mat_w);
copy_size += src_mat_w_sz;
}
// fill data
if (context_start > 0) {
src_data += context_start * src_mat_w;
}
for (int j = 0; j < seq_len - up_pad - down_pad; ++j) {
std::memcpy(dst_data, src_data, copy_size);
dst_data += col_mat_w;
src_data += src_mat_w;
}
// zero all down_pad and fill data
std::memset(dst_data, 0, down_pad * col_mat_w_sz);
copy_size -= src_mat_w_sz;
for (int j = 0; j < down_pad; ++j) {
if (copy_size < 0) {
copy_size = 0;
}
std::memcpy(dst_data, src_data, copy_size);
dst_data += col_mat_w;
src_data += src_mat_w;
copy_size -= src_mat_w_sz;
}
} else {
std::memset(dst_data, 0, seq_len * col_mat_w_sz);
dst_data = dst_data + up_pad * src_mat_w;
int zero_sz = up_pad * src_mat_w_sz;
int cur_src_sz = seq_len * src_mat_w_sz;
for (int j = 0; j < std::min(up_pad, seq_len); ++j) {
int copy_size = std::min(cur_src_sz, col_mat_w_sz - zero_sz);
std::memcpy(dst_data, src_data, copy_size);
dst_data += (col_mat_w - src_mat_w);
zero_sz -= src_mat_w_sz;
}
// from bottom
dst_data = col_data + ed * col_mat_w;
src_data = x_data + st * src_mat_w;
if (context_start > 0) {
src_data += context_start * src_mat_w;
}
zero_sz = down_pad * src_mat_w_sz;
for (int j = 1; j <= std::min(down_pad, seq_len); ++j) {
int copy_size = std::min(cur_src_sz, col_mat_w_sz - zero_sz);
if (copy_size < 0) {
copy_size = 0;
}
std::memcpy(dst_data - (zero_sz + copy_size) / sizeof(T),
src_data + std::max(seq_len - j - up_pad, 0) * src_mat_w,
copy_size);
dst_data -= col_mat_w;
zero_sz -= src_mat_w_sz;
}
}
}
auto& dev_ctx = ctx.template device_context<DeviceContext>();
math::FCFunctor<DeviceContext, T> fc;
fc(dev_ctx, x_dims[0], w_dims[1], w_dims[0], col_data, w_data, y_data,
b_data, true);
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OPERATOR(fusion_seqconv_eltadd_relu, ops::FusionSeqConvEltAddReluOp,
ops::FusionSeqConvEltAddReluOpMaker);
REGISTER_OP_CPU_KERNEL(fusion_seqconv_eltadd_relu,
ops::FusionSeqConvEltAddReluKernel<float>,
ops::FusionSeqConvEltAddReluKernel<double>);
|
/******************************************************************
*
* Copyright 2018 GRANITE RIVER LABS All Rights Reserved.
* 2021 CASCODA LTD All Rights Reserved.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************/
#include <cstdlib>
#include <gtest/gtest.h>
#include <stdio.h>
#include <string>
#include "oc_api.h"
#include "oc_helpers.h"
#include "oc_ri.h"
#include "port/linux/oc_config.h"
#define RESOURCE_URI "/LightResourceURI"
#define RESOURCE_NAME "roomlights"
#define OBSERVERPERIODSECONDS_P 1
class TestOcRi : public testing::Test {
protected:
virtual void SetUp() { oc_ri_init(); }
virtual void TearDown() { oc_ri_shutdown(); }
};
static void
onGet(oc_request_t *request, oc_interface_mask_t iface_mask, void *user_data)
{
(void)request;
(void)iface_mask;
(void)user_data;
}
TEST_F(TestOcRi, GetAppResourceByUri_P)
{
oc_resource_t *res;
res = oc_new_resource(RESOURCE_NAME, RESOURCE_URI, 1, 0);
oc_resource_set_discoverable(res, true);
oc_resource_set_periodic_observable(res, OBSERVERPERIODSECONDS_P);
oc_resource_set_request_handler(res, OC_GET, onGet, NULL);
oc_ri_add_resource(res);
res = oc_ri_get_app_resource_by_uri(RESOURCE_URI, strlen(RESOURCE_URI), 0);
EXPECT_NE(res, NULL);
oc_ri_delete_resource(res);
}
TEST_F(TestOcRi, GetAppResourceByUri_N)
{
oc_resource_t *res;
res = oc_ri_get_app_resource_by_uri(RESOURCE_URI, strlen(RESOURCE_URI), 0);
EXPECT_EQ(res, NULL);
}
TEST_F(TestOcRi, RiGetAppResource_P)
{
oc_resource_t *res;
res = oc_new_resource(RESOURCE_NAME, RESOURCE_URI, 1, 0);
oc_resource_set_discoverable(res, true);
oc_resource_set_periodic_observable(res, OBSERVERPERIODSECONDS_P);
oc_resource_set_request_handler(res, OC_GET, onGet, NULL);
oc_ri_add_resource(res);
res = oc_ri_get_app_resources();
EXPECT_NE(0, res);
oc_ri_delete_resource(res);
}
TEST_F(TestOcRi, RiGetAppResource_N)
{
oc_resource_t *res;
res = oc_ri_get_app_resources();
EXPECT_EQ(0, res);
}
TEST_F(TestOcRi, RiAllocResource_P)
{
oc_resource_t *res;
res = oc_ri_alloc_resource();
EXPECT_NE(0, res);
oc_ri_delete_resource(res);
}
TEST_F(TestOcRi, RiDeleteResource_P)
{
oc_resource_t *res;
bool del_check;
res = oc_ri_alloc_resource();
del_check = oc_ri_delete_resource(res);
EXPECT_EQ(del_check, 1);
}
TEST_F(TestOcRi, RiFreeResourceProperties_P)
{
oc_resource_t *res;
res = oc_new_resource(RESOURCE_NAME, RESOURCE_URI, 1, 0);
oc_ri_free_resource_properties(res);
EXPECT_EQ(0, oc_string_len(res->name));
oc_ri_delete_resource(res);
}
TEST_F(TestOcRi, RiAddResource_P)
{
oc_resource_t *res;
bool res_check;
res = oc_new_resource(RESOURCE_NAME, RESOURCE_URI, 1, 0);
oc_resource_set_discoverable(res, true);
oc_resource_set_periodic_observable(res, OBSERVERPERIODSECONDS_P);
oc_resource_set_request_handler(res, OC_GET, onGet, NULL);
res_check = oc_ri_add_resource(res);
EXPECT_EQ(res_check, 1);
oc_ri_delete_resource(res);
}
TEST_F(TestOcRi, RIGetQueryValue_P)
{
const char *input[] = { "key=1", "data=1&key=2", "key=2&data=3",
"x&key=2&data=3", "y&x&key=2&data=3", "y&x&key=2",
"y&x&key=2&y" };
int ret;
char *value;
for (int i = 0; i < 7; i++) {
ret = oc_ri_get_query_value(input[i], strlen(input[i]), "key", &value);
EXPECT_EQ(1, ret) << "P input[" << i << "] " << input[i] << " "
<< "key";
}
for (int i = 0; i < 7; i++) {
ret = oc_ri_get_query_value(input[i], strlen(input[i]), "key2", &value);
EXPECT_EQ(-1, ret) << "N input[" << i << "] " << input[i] << " "
<< "key2";
}
}
TEST_F(TestOcRi, RIQueryExists_P)
{
const char *input[] = { "key=1",
"key",
"data=1&key=2",
"data=2&key",
"key&data=3",
"key=2&data=3",
"x=1&key=2&data=3",
"y=&key=2&data=3",
"y=1&x&key=2&data=3",
"y=1&x&key" };
int ret;
for (int i = 0; i < 10; i++) {
ret = oc_ri_query_exists(input[i], strlen(input[i]), "key");
EXPECT_EQ(1, ret) << "P input[" << i << "] " << input[i] << " "
<< "key";
}
for (int i = 0; i < 10; i++) {
ret = oc_ri_query_exists(input[i], strlen(input[i]), "key2");
EXPECT_EQ(-1, ret) << "N input[" << i << "] " << input[i] << " "
<< "key2";
}
}
|
/*************************************************************************/
/* multimesh.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "multimesh.h"
#include "servers/rendering_server.h"
#ifndef DISABLE_DEPRECATED
// Kept for compatibility from 3.x to 4.0.
void MultiMesh::_set_transform_array(const Vector<Vector3> &p_array) {
if (transform_format != TRANSFORM_3D) {
return;
}
const Vector<Vector3> &xforms = p_array;
int len = xforms.size();
ERR_FAIL_COND((len / 4) != instance_count);
if (len == 0) {
return;
}
const Vector3 *r = xforms.ptr();
for (int i = 0; i < len / 4; i++) {
Transform t;
t.basis[0] = r[i * 4 + 0];
t.basis[1] = r[i * 4 + 1];
t.basis[2] = r[i * 4 + 2];
t.origin = r[i * 4 + 3];
set_instance_transform(i, t);
}
}
Vector<Vector3> MultiMesh::_get_transform_array() const {
if (transform_format != TRANSFORM_3D) {
return Vector<Vector3>();
}
if (instance_count == 0) {
return Vector<Vector3>();
}
Vector<Vector3> xforms;
xforms.resize(instance_count * 4);
Vector3 *w = xforms.ptrw();
for (int i = 0; i < instance_count; i++) {
Transform t = get_instance_transform(i);
w[i * 4 + 0] = t.basis[0];
w[i * 4 + 1] = t.basis[1];
w[i * 4 + 2] = t.basis[2];
w[i * 4 + 3] = t.origin;
}
return xforms;
}
void MultiMesh::_set_transform_2d_array(const Vector<Vector2> &p_array) {
if (transform_format != TRANSFORM_2D) {
return;
}
const Vector<Vector2> &xforms = p_array;
int len = xforms.size();
ERR_FAIL_COND((len / 3) != instance_count);
if (len == 0) {
return;
}
const Vector2 *r = xforms.ptr();
for (int i = 0; i < len / 3; i++) {
Transform2D t;
t.elements[0] = r[i * 3 + 0];
t.elements[1] = r[i * 3 + 1];
t.elements[2] = r[i * 3 + 2];
set_instance_transform_2d(i, t);
}
}
Vector<Vector2> MultiMesh::_get_transform_2d_array() const {
if (transform_format != TRANSFORM_2D) {
return Vector<Vector2>();
}
if (instance_count == 0) {
return Vector<Vector2>();
}
Vector<Vector2> xforms;
xforms.resize(instance_count * 3);
Vector2 *w = xforms.ptrw();
for (int i = 0; i < instance_count; i++) {
Transform2D t = get_instance_transform_2d(i);
w[i * 3 + 0] = t.elements[0];
w[i * 3 + 1] = t.elements[1];
w[i * 3 + 2] = t.elements[2];
}
return xforms;
}
void MultiMesh::_set_color_array(const Vector<Color> &p_array) {
const Vector<Color> &colors = p_array;
int len = colors.size();
if (len == 0) {
return;
}
ERR_FAIL_COND(len != instance_count);
const Color *r = colors.ptr();
for (int i = 0; i < len; i++) {
set_instance_color(i, r[i]);
}
}
Vector<Color> MultiMesh::_get_color_array() const {
if (instance_count == 0 || !use_colors) {
return Vector<Color>();
}
Vector<Color> colors;
colors.resize(instance_count);
for (int i = 0; i < instance_count; i++) {
colors.set(i, get_instance_color(i));
}
return colors;
}
void MultiMesh::_set_custom_data_array(const Vector<Color> &p_array) {
const Vector<Color> &custom_datas = p_array;
int len = custom_datas.size();
if (len == 0) {
return;
}
ERR_FAIL_COND(len != instance_count);
const Color *r = custom_datas.ptr();
for (int i = 0; i < len; i++) {
set_instance_custom_data(i, r[i]);
}
}
Vector<Color> MultiMesh::_get_custom_data_array() const {
if (instance_count == 0 || !use_custom_data) {
return Vector<Color>();
}
Vector<Color> custom_datas;
custom_datas.resize(instance_count);
for (int i = 0; i < instance_count; i++) {
custom_datas.set(i, get_instance_custom_data(i));
}
return custom_datas;
}
#endif // DISABLE_DEPRECATED
void MultiMesh::set_buffer(const Vector<float> &p_buffer) {
RS::get_singleton()->multimesh_set_buffer(multimesh, p_buffer);
}
Vector<float> MultiMesh::get_buffer() const {
return RS::get_singleton()->multimesh_get_buffer(multimesh);
}
void MultiMesh::set_mesh(const Ref<Mesh> &p_mesh) {
mesh = p_mesh;
if (!mesh.is_null()) {
RenderingServer::get_singleton()->multimesh_set_mesh(multimesh, mesh->get_rid());
} else {
RenderingServer::get_singleton()->multimesh_set_mesh(multimesh, RID());
}
}
Ref<Mesh> MultiMesh::get_mesh() const {
return mesh;
}
void MultiMesh::set_instance_count(int p_count) {
ERR_FAIL_COND(p_count < 0);
RenderingServer::get_singleton()->multimesh_allocate(multimesh, p_count, RS::MultimeshTransformFormat(transform_format), use_colors, use_custom_data);
instance_count = p_count;
}
int MultiMesh::get_instance_count() const {
return instance_count;
}
void MultiMesh::set_visible_instance_count(int p_count) {
ERR_FAIL_COND(p_count < -1);
ERR_FAIL_COND(p_count > instance_count);
RenderingServer::get_singleton()->multimesh_set_visible_instances(multimesh, p_count);
visible_instance_count = p_count;
}
int MultiMesh::get_visible_instance_count() const {
return visible_instance_count;
}
void MultiMesh::set_instance_transform(int p_instance, const Transform &p_transform) {
RenderingServer::get_singleton()->multimesh_instance_set_transform(multimesh, p_instance, p_transform);
}
void MultiMesh::set_instance_transform_2d(int p_instance, const Transform2D &p_transform) {
RenderingServer::get_singleton()->multimesh_instance_set_transform_2d(multimesh, p_instance, p_transform);
}
Transform MultiMesh::get_instance_transform(int p_instance) const {
return RenderingServer::get_singleton()->multimesh_instance_get_transform(multimesh, p_instance);
}
Transform2D MultiMesh::get_instance_transform_2d(int p_instance) const {
return RenderingServer::get_singleton()->multimesh_instance_get_transform_2d(multimesh, p_instance);
}
void MultiMesh::set_instance_color(int p_instance, const Color &p_color) {
RenderingServer::get_singleton()->multimesh_instance_set_color(multimesh, p_instance, p_color);
}
Color MultiMesh::get_instance_color(int p_instance) const {
return RenderingServer::get_singleton()->multimesh_instance_get_color(multimesh, p_instance);
}
void MultiMesh::set_instance_custom_data(int p_instance, const Color &p_custom_data) {
RenderingServer::get_singleton()->multimesh_instance_set_custom_data(multimesh, p_instance, p_custom_data);
}
Color MultiMesh::get_instance_custom_data(int p_instance) const {
return RenderingServer::get_singleton()->multimesh_instance_get_custom_data(multimesh, p_instance);
}
AABB MultiMesh::get_aabb() const {
return RenderingServer::get_singleton()->multimesh_get_aabb(multimesh);
}
RID MultiMesh::get_rid() const {
return multimesh;
}
void MultiMesh::set_use_colors(bool p_enable) {
ERR_FAIL_COND(instance_count > 0);
use_colors = p_enable;
}
bool MultiMesh::is_using_colors() const {
return use_colors;
}
void MultiMesh::set_use_custom_data(bool p_enable) {
ERR_FAIL_COND(instance_count > 0);
use_custom_data = p_enable;
}
bool MultiMesh::is_using_custom_data() const {
return use_custom_data;
}
void MultiMesh::set_transform_format(TransformFormat p_transform_format) {
ERR_FAIL_COND(instance_count > 0);
transform_format = p_transform_format;
}
MultiMesh::TransformFormat MultiMesh::get_transform_format() const {
return transform_format;
}
void MultiMesh::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_mesh", "mesh"), &MultiMesh::set_mesh);
ClassDB::bind_method(D_METHOD("get_mesh"), &MultiMesh::get_mesh);
ClassDB::bind_method(D_METHOD("set_use_colors", "enable"), &MultiMesh::set_use_colors);
ClassDB::bind_method(D_METHOD("is_using_colors"), &MultiMesh::is_using_colors);
ClassDB::bind_method(D_METHOD("set_use_custom_data", "enable"), &MultiMesh::set_use_custom_data);
ClassDB::bind_method(D_METHOD("is_using_custom_data"), &MultiMesh::is_using_custom_data);
ClassDB::bind_method(D_METHOD("set_transform_format", "format"), &MultiMesh::set_transform_format);
ClassDB::bind_method(D_METHOD("get_transform_format"), &MultiMesh::get_transform_format);
ClassDB::bind_method(D_METHOD("set_instance_count", "count"), &MultiMesh::set_instance_count);
ClassDB::bind_method(D_METHOD("get_instance_count"), &MultiMesh::get_instance_count);
ClassDB::bind_method(D_METHOD("set_visible_instance_count", "count"), &MultiMesh::set_visible_instance_count);
ClassDB::bind_method(D_METHOD("get_visible_instance_count"), &MultiMesh::get_visible_instance_count);
ClassDB::bind_method(D_METHOD("set_instance_transform", "instance", "transform"), &MultiMesh::set_instance_transform);
ClassDB::bind_method(D_METHOD("set_instance_transform_2d", "instance", "transform"), &MultiMesh::set_instance_transform_2d);
ClassDB::bind_method(D_METHOD("get_instance_transform", "instance"), &MultiMesh::get_instance_transform);
ClassDB::bind_method(D_METHOD("get_instance_transform_2d", "instance"), &MultiMesh::get_instance_transform_2d);
ClassDB::bind_method(D_METHOD("set_instance_color", "instance", "color"), &MultiMesh::set_instance_color);
ClassDB::bind_method(D_METHOD("get_instance_color", "instance"), &MultiMesh::get_instance_color);
ClassDB::bind_method(D_METHOD("set_instance_custom_data", "instance", "custom_data"), &MultiMesh::set_instance_custom_data);
ClassDB::bind_method(D_METHOD("get_instance_custom_data", "instance"), &MultiMesh::get_instance_custom_data);
ClassDB::bind_method(D_METHOD("get_aabb"), &MultiMesh::get_aabb);
ClassDB::bind_method(D_METHOD("get_buffer"), &MultiMesh::get_buffer);
ClassDB::bind_method(D_METHOD("set_buffer", "buffer"), &MultiMesh::set_buffer);
ADD_PROPERTY(PropertyInfo(Variant::INT, "transform_format", PROPERTY_HINT_ENUM, "2D,3D"), "set_transform_format", "get_transform_format");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_colors"), "set_use_colors", "is_using_colors");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_custom_data"), "set_use_custom_data", "is_using_custom_data");
ADD_PROPERTY(PropertyInfo(Variant::INT, "instance_count", PROPERTY_HINT_RANGE, "0,16384,1,or_greater"), "set_instance_count", "get_instance_count");
ADD_PROPERTY(PropertyInfo(Variant::INT, "visible_instance_count", PROPERTY_HINT_RANGE, "-1,16384,1,or_greater"), "set_visible_instance_count", "get_visible_instance_count");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "mesh", PROPERTY_HINT_RESOURCE_TYPE, "Mesh"), "set_mesh", "get_mesh");
ADD_PROPERTY(PropertyInfo(Variant::PACKED_FLOAT32_ARRAY, "buffer", PROPERTY_HINT_NONE), "set_buffer", "get_buffer");
#ifndef DISABLE_DEPRECATED
// Kept for compatibility from 3.x to 4.0.
ClassDB::bind_method(D_METHOD("_set_transform_array"), &MultiMesh::_set_transform_array);
ClassDB::bind_method(D_METHOD("_get_transform_array"), &MultiMesh::_get_transform_array);
ClassDB::bind_method(D_METHOD("_set_transform_2d_array"), &MultiMesh::_set_transform_2d_array);
ClassDB::bind_method(D_METHOD("_get_transform_2d_array"), &MultiMesh::_get_transform_2d_array);
ClassDB::bind_method(D_METHOD("_set_color_array"), &MultiMesh::_set_color_array);
ClassDB::bind_method(D_METHOD("_get_color_array"), &MultiMesh::_get_color_array);
ClassDB::bind_method(D_METHOD("_set_custom_data_array"), &MultiMesh::_set_custom_data_array);
ClassDB::bind_method(D_METHOD("_get_custom_data_array"), &MultiMesh::_get_custom_data_array);
ADD_PROPERTY(PropertyInfo(Variant::PACKED_VECTOR3_ARRAY, "transform_array", PROPERTY_HINT_NONE, "", 0), "_set_transform_array", "_get_transform_array");
ADD_PROPERTY(PropertyInfo(Variant::PACKED_VECTOR2_ARRAY, "transform_2d_array", PROPERTY_HINT_NONE, "", 0), "_set_transform_2d_array", "_get_transform_2d_array");
ADD_PROPERTY(PropertyInfo(Variant::PACKED_COLOR_ARRAY, "color_array", PROPERTY_HINT_NONE, "", 0), "_set_color_array", "_get_color_array");
ADD_PROPERTY(PropertyInfo(Variant::PACKED_COLOR_ARRAY, "custom_data_array", PROPERTY_HINT_NONE, "", 0), "_set_custom_data_array", "_get_custom_data_array");
#endif
BIND_ENUM_CONSTANT(TRANSFORM_2D);
BIND_ENUM_CONSTANT(TRANSFORM_3D);
}
MultiMesh::MultiMesh() {
multimesh = RenderingServer::get_singleton()->multimesh_create();
use_colors = false;
use_custom_data = false;
transform_format = TRANSFORM_2D;
visible_instance_count = -1;
instance_count = 0;
}
MultiMesh::~MultiMesh() {
RenderingServer::get_singleton()->free(multimesh);
}
|
/** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Internal Includes
#include <osvr/ClientKit/Context.h>
#include <osvr/ClientKit/Interface.h>
#include <osvr/Util/ClientReportTypesC.h>
// Library/third-party includes
// Standard includes
#include <iostream>
#include <string>
void printLocation2DReport(const OSVR_Location2DReport *report) {
std::cout << report->location.data[0] << "; " << report->location.data[1]
<< "\t" << std::endl;
}
void location2DCallback(void * /*userdata*/,
const OSVR_TimeValue * /*timestamp*/,
const OSVR_Location2DReport *report) {
std::cout << "Got 2D Location Report, for sensor #" << report->sensor
<< std::endl;
printLocation2DReport(report);
}
int main() {
osvr::clientkit::ClientContext context(
"com.osvr.exampleclients.Location2DCallback");
osvr::clientkit::Interface location =
context.getInterface("/com_osvr_Multi/Location2D/location2D");
location.registerCallback(&location2DCallback, NULL);
// Pretend that this is your application's mainloop.
while (1) {
context.update();
}
std::cout << "Library shut down, exiting." << std::endl;
return 0;
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2014-2020 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/dash-config.h"
#endif
#include "net.h"
#include "netmessagemaker.h"
#include "addrman.h"
#include "chainparams.h"
#include "clientversion.h"
#include "consensus/consensus.h"
#include "crypto/common.h"
#include "crypto/sha256.h"
#include "hash.h"
#include "primitives/transaction.h"
#include "netbase.h"
#include "scheduler.h"
#include "ui_interface.h"
#include "utilstrencodings.h"
#include "validation.h"
#include "masternode/masternode-sync.h"
#include "privatesend/privatesend.h"
#include "evo/deterministicmns.h"
#ifdef WIN32
#include <string.h>
#else
#include <fcntl.h>
#endif
#ifdef USE_UPNP
#include <miniupnpc/miniupnpc.h>
#include <miniupnpc/miniwget.h>
#include <miniupnpc/upnpcommands.h>
#include <miniupnpc/upnperrors.h>
#endif
#include <math.h>
// Dump addresses to peers.dat and banlist.dat every 15 minutes (900s)
#define DUMP_ADDRESSES_INTERVAL 900
// We add a random period time (0 to 1 seconds) to feeler connections to prevent synchronization.
#define FEELER_SLEEP_WINDOW 1
#if !defined(HAVE_MSG_NOSIGNAL)
#define MSG_NOSIGNAL 0
#endif
// MSG_DONTWAIT is not available on some platforms, if it doesn't exist define it as 0
#if !defined(HAVE_MSG_DONTWAIT)
#define MSG_DONTWAIT 0
#endif
// Fix for ancient MinGW versions, that don't have defined these in ws2tcpip.h.
// Todo: Can be removed when our pull-tester is upgraded to a modern MinGW version.
#ifdef WIN32
#ifndef PROTECTION_LEVEL_UNRESTRICTED
#define PROTECTION_LEVEL_UNRESTRICTED 10
#endif
#ifndef IPV6_PROTECTION_LEVEL
#define IPV6_PROTECTION_LEVEL 23
#endif
#endif
/** Used to pass flags to the Bind() function */
enum BindFlags {
BF_NONE = 0,
BF_EXPLICIT = (1U << 0),
BF_REPORT_ERROR = (1U << 1),
BF_WHITELIST = (1U << 2),
};
const static std::string NET_MESSAGE_COMMAND_OTHER = "*other*";
constexpr const CConnman::CFullyConnectedOnly CConnman::FullyConnectedOnly;
constexpr const CConnman::CAllNodes CConnman::AllNodes;
static const uint64_t RANDOMIZER_ID_NETGROUP = 0x6c0edd8036ef4036ULL; // SHA256("netgroup")[0:8]
static const uint64_t RANDOMIZER_ID_LOCALHOSTNONCE = 0xd93e69e2bbfa5735ULL; // SHA256("localhostnonce")[0:8]
//
// Global state variables
//
bool fDiscover = true;
bool fListen = true;
bool fRelayTxes = true;
bool fNoSmsg = false;
CCriticalSection cs_mapLocalHost;
std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
static bool vfLimited[NET_MAX] = {};
std::string strSubVersion;
unordered_limitedmap<uint256, int64_t, StaticSaltedHasher> mapAlreadyAskedFor(MAX_INV_SZ, MAX_INV_SZ * 2);
void CConnman::AddOneShot(const std::string& strDest)
{
LOCK(cs_vOneShots);
vOneShots.push_back(strDest);
}
unsigned short GetListenPort()
{
return (unsigned short)(gArgs.GetArg("-port", Params().GetDefaultPort()));
}
// find 'best' local address for a particular peer
bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
{
if (!fListen)
return false;
int nBestScore = -1;
int nBestReachability = -1;
{
LOCK(cs_mapLocalHost);
for (std::map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
{
int nScore = (*it).second.nScore;
int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore))
{
addr = CService((*it).first, (*it).second.nPort);
nBestReachability = nReachability;
nBestScore = nScore;
}
}
}
return nBestScore >= 0;
}
//! Convert the pnSeeds6 array into usable address objects.
static std::vector<CAddress> convertSeed6(const std::vector<SeedSpec6> &vSeedsIn)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7*24*60*60;
std::vector<CAddress> vSeedsOut;
vSeedsOut.reserve(vSeedsIn.size());
for (std::vector<SeedSpec6>::const_iterator i(vSeedsIn.begin()); i != vSeedsIn.end(); ++i)
{
struct in6_addr ip;
memcpy(&ip, i->addr, sizeof(ip));
CAddress addr(CService(ip, i->port), NODE_NETWORK);
addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
vSeedsOut.push_back(addr);
}
return vSeedsOut;
}
// get best local address for a particular peer as a CAddress
// Otherwise, return the unroutable 0.0.0.0 but filled in with
// the normal parameters, since the IP may be changed to a useful
// one by discovery.
CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
{
CAddress ret(CService(CNetAddr(),GetListenPort()), nLocalServices);
CService addr;
if (GetLocal(addr, paddrPeer))
{
ret = CAddress(addr, nLocalServices);
}
ret.nTime = GetAdjustedTime();
return ret;
}
int GetnScore(const CService& addr)
{
LOCK(cs_mapLocalHost);
if (mapLocalHost.count(addr) == LOCAL_NONE)
return 0;
return mapLocalHost[addr].nScore;
}
// Is our peer's addrLocal potentially useful as an external IP source?
bool IsPeerAddrLocalGood(CNode *pnode)
{
CService addrLocal = pnode->GetAddrLocal();
return fDiscover && pnode->addr.IsRoutable() && addrLocal.IsRoutable() &&
!IsLimited(addrLocal.GetNetwork());
}
// pushes our own address to a peer
void AdvertiseLocal(CNode *pnode)
{
if (fListen && pnode->fSuccessfullyConnected)
{
CAddress addrLocal = GetLocalAddress(&pnode->addr, pnode->GetLocalServices());
// If discovery is enabled, sometimes give our peer the address it
// tells us that it sees us as in case it has a better idea of our
// address than we do.
if (IsPeerAddrLocalGood(pnode) && (!addrLocal.IsRoutable() ||
GetRand((GetnScore(addrLocal) > LOCAL_MANUAL) ? 8:2) == 0))
{
addrLocal.SetIP(pnode->GetAddrLocal());
}
if (addrLocal.IsRoutable())
{
LogPrint(BCLog::NET, "AdvertiseLocal: advertising address %s\n", addrLocal.ToString());
FastRandomContext insecure_rand;
pnode->PushAddress(addrLocal, insecure_rand);
}
}
}
// learn a new local address
bool AddLocal(const CService& addr, int nScore)
{
if (!addr.IsRoutable() && Params().RequireRoutableExternalIP())
return false;
if (!fDiscover && nScore < LOCAL_MANUAL)
return false;
if (IsLimited(addr))
return false;
LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore);
{
LOCK(cs_mapLocalHost);
bool fAlready = mapLocalHost.count(addr) > 0;
LocalServiceInfo &info = mapLocalHost[addr];
if (!fAlready || nScore >= info.nScore) {
info.nScore = nScore + (fAlready ? 1 : 0);
info.nPort = addr.GetPort();
}
}
return true;
}
bool AddLocal(const CNetAddr &addr, int nScore)
{
return AddLocal(CService(addr, GetListenPort()), nScore);
}
bool RemoveLocal(const CService& addr)
{
LOCK(cs_mapLocalHost);
LogPrintf("RemoveLocal(%s)\n", addr.ToString());
mapLocalHost.erase(addr);
return true;
}
/** Make a particular network entirely off-limits (no automatic connects to it) */
void SetLimited(enum Network net, bool fLimited)
{
if (net == NET_UNROUTABLE || net == NET_INTERNAL)
return;
LOCK(cs_mapLocalHost);
vfLimited[net] = fLimited;
}
bool IsLimited(enum Network net)
{
LOCK(cs_mapLocalHost);
return vfLimited[net];
}
bool IsLimited(const CNetAddr &addr)
{
return IsLimited(addr.GetNetwork());
}
/** vote for a local address */
bool SeenLocal(const CService& addr)
{
{
LOCK(cs_mapLocalHost);
if (mapLocalHost.count(addr) == 0)
return false;
mapLocalHost[addr].nScore++;
}
return true;
}
/** check whether a given address is potentially local */
bool IsLocal(const CService& addr)
{
LOCK(cs_mapLocalHost);
return mapLocalHost.count(addr) > 0;
}
/** check whether a given network is one we can probably connect to */
bool IsReachable(enum Network net)
{
LOCK(cs_mapLocalHost);
return !vfLimited[net];
}
/** check whether a given address is in a network we can probably connect to */
bool IsReachable(const CNetAddr& addr)
{
enum Network net = addr.GetNetwork();
return IsReachable(net);
}
CNode* CConnman::FindNode(const CNetAddr& ip)
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes)
if ((CNetAddr)pnode->addr == ip)
return (pnode);
return nullptr;
}
CNode* CConnman::FindNode(const CSubNet& subNet)
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes)
if (subNet.Match((CNetAddr)pnode->addr))
return (pnode);
return nullptr;
}
CNode* CConnman::FindNode(const std::string& addrName)
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes) {
if (pnode->GetAddrName() == addrName) {
return (pnode);
}
}
return nullptr;
}
CNode* CConnman::FindNode(const CService& addr)
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes)
if((CService)pnode->addr == addr)
return (pnode);
return nullptr;
}
bool CConnman::CheckIncomingNonce(uint64_t nonce)
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes) {
if (!pnode->fSuccessfullyConnected && !pnode->fInbound && pnode->GetLocalNonce() == nonce)
return false;
}
return true;
}
/** Get the bind address for a socket as CAddress */
static CAddress GetBindAddress(SOCKET sock)
{
CAddress addr_bind;
struct sockaddr_storage sockaddr_bind;
socklen_t sockaddr_bind_len = sizeof(sockaddr_bind);
if (sock != INVALID_SOCKET) {
if (!getsockname(sock, (struct sockaddr*)&sockaddr_bind, &sockaddr_bind_len)) {
addr_bind.SetSockAddr((const struct sockaddr*)&sockaddr_bind);
} else {
LogPrint(BCLog::NET, "Warning: getsockname failed\n");
}
}
return addr_bind;
}
CNode* CConnman::ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure)
{
if (pszDest == nullptr) {
bool fAllowLocal = Params().AllowMultiplePorts() && addrConnect.GetPort() != GetListenPort();
if (!fAllowLocal && IsLocal(addrConnect)) {
return nullptr;
}
// Look for an existing connection
CNode* pnode = FindNode((CService)addrConnect);
if (pnode)
{
LogPrintf("Failed to open new connection, already connected\n");
return nullptr;
}
}
/// debug print
if (fLogIPs) {
LogPrint(BCLog::NET, "trying connection %s lastseen=%.1fhrs\n",
pszDest ? pszDest : addrConnect.ToString(),
pszDest ? 0.0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
} else {
LogPrint(BCLog::NET, "trying connection lastseen=%.1fhrs\n",
pszDest ? 0.0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
}
// Connect
SOCKET hSocket;
bool proxyConnectionFailed = false;
if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, Params().GetDefaultPort(), nConnectTimeout, &proxyConnectionFailed) :
ConnectSocket(addrConnect, hSocket, nConnectTimeout, &proxyConnectionFailed))
{
if (!IsSelectableSocket(hSocket)) {
LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
CloseSocket(hSocket);
return nullptr;
}
if (pszDest && addrConnect.IsValid()) {
// It is possible that we already have a connection to the IP/port pszDest resolved to.
// In that case, drop the connection that was just created, and return the existing CNode instead.
// Also store the name we used to connect in that CNode, so that future FindNode() calls to that
// name catch this early.
LOCK(cs_vNodes);
CNode* pnode = FindNode((CService)addrConnect);
if (pnode)
{
pnode->MaybeSetAddrName(std::string(pszDest));
CloseSocket(hSocket);
LogPrintf("Failed to open new connection, already connected\n");
return nullptr;
}
}
addrman.Attempt(addrConnect, fCountFailure);
// Add node
NodeId id = GetNewNodeId();
uint64_t nonce = GetDeterministicRandomizer(RANDOMIZER_ID_LOCALHOSTNONCE).Write(id).Finalize();
CAddress addr_bind = GetBindAddress(hSocket);
CNode* pnode = new CNode(id, nLocalServices, GetBestHeight(), hSocket, addrConnect, CalculateKeyedNetGroup(addrConnect), nonce, addr_bind, pszDest ? pszDest : "", false);
pnode->AddRef();
return pnode;
} else if (!proxyConnectionFailed) {
// If connecting to the node failed, and failure is not caused by a problem connecting to
// the proxy, mark this as an attempt.
addrman.Attempt(addrConnect, fCountFailure);
}
return nullptr;
}
void CConnman::DumpBanlist()
{
SweepBanned(); // clean unused entries (if bantime has expired)
if (!BannedSetIsDirty())
return;
int64_t nStart = GetTimeMillis();
CBanDB bandb;
banmap_t banmap;
GetBanned(banmap);
if (bandb.Write(banmap)) {
SetBannedSetDirty(false);
}
LogPrint(BCLog::NET, "Flushed %d banned node ips/subnets to banlist.dat %dms\n",
banmap.size(), GetTimeMillis() - nStart);
}
void CNode::CloseSocketDisconnect()
{
fDisconnect = true;
LOCK(cs_hSocket);
if (hSocket != INVALID_SOCKET)
{
LogPrint(BCLog::NET, "disconnecting peer=%d\n", id);
CloseSocket(hSocket);
}
}
void CConnman::ClearBanned()
{
{
LOCK(cs_setBanned);
setBanned.clear();
setBannedIsDirty = true;
}
DumpBanlist(); //store banlist to disk
if(clientInterface)
clientInterface->BannedListChanged();
}
bool CConnman::IsBanned(CNetAddr ip)
{
LOCK(cs_setBanned);
for (banmap_t::iterator it = setBanned.begin(); it != setBanned.end(); it++)
{
CSubNet subNet = (*it).first;
CBanEntry banEntry = (*it).second;
if (subNet.Match(ip) && GetTime() < banEntry.nBanUntil) {
return true;
}
}
return false;
}
bool CConnman::IsBanned(CSubNet subnet)
{
LOCK(cs_setBanned);
banmap_t::iterator i = setBanned.find(subnet);
if (i != setBanned.end())
{
CBanEntry banEntry = (*i).second;
if (GetTime() < banEntry.nBanUntil) {
return true;
}
}
return false;
}
void CConnman::Ban(const CNetAddr& addr, const BanReason &banReason, int64_t bantimeoffset, bool sinceUnixEpoch) {
CSubNet subNet(addr);
Ban(subNet, banReason, bantimeoffset, sinceUnixEpoch);
}
void CConnman::Ban(const CSubNet& subNet, const BanReason &banReason, int64_t bantimeoffset, bool sinceUnixEpoch) {
CBanEntry banEntry(GetTime());
banEntry.banReason = banReason;
if (bantimeoffset <= 0)
{
bantimeoffset = gArgs.GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME);
sinceUnixEpoch = false;
}
banEntry.nBanUntil = (sinceUnixEpoch ? 0 : GetTime() )+bantimeoffset;
{
LOCK(cs_setBanned);
if (setBanned[subNet].nBanUntil < banEntry.nBanUntil) {
setBanned[subNet] = banEntry;
setBannedIsDirty = true;
}
else
return;
}
if(clientInterface)
clientInterface->BannedListChanged();
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes) {
if (subNet.Match((CNetAddr)pnode->addr))
pnode->fDisconnect = true;
}
}
if(banReason == BanReasonManuallyAdded)
DumpBanlist(); //store banlist to disk immediately if user requested ban
}
bool CConnman::Unban(const CNetAddr &addr) {
CSubNet subNet(addr);
return Unban(subNet);
}
bool CConnman::Unban(const CSubNet &subNet) {
{
LOCK(cs_setBanned);
if (!setBanned.erase(subNet))
return false;
setBannedIsDirty = true;
}
if(clientInterface)
clientInterface->BannedListChanged();
DumpBanlist(); //store banlist to disk immediately
return true;
}
void CConnman::GetBanned(banmap_t &banMap)
{
LOCK(cs_setBanned);
// Sweep the banlist so expired bans are not returned
SweepBanned();
banMap = setBanned; //create a thread safe copy
}
void CConnman::SetBanned(const banmap_t &banMap)
{
LOCK(cs_setBanned);
setBanned = banMap;
setBannedIsDirty = true;
}
void CConnman::SweepBanned()
{
int64_t now = GetTime();
LOCK(cs_setBanned);
banmap_t::iterator it = setBanned.begin();
while(it != setBanned.end())
{
CSubNet subNet = (*it).first;
CBanEntry banEntry = (*it).second;
if(now > banEntry.nBanUntil)
{
setBanned.erase(it++);
setBannedIsDirty = true;
LogPrint(BCLog::NET, "%s: Removed banned node ip/subnet from banlist.dat: %s\n", __func__, subNet.ToString());
}
else
++it;
}
}
bool CConnman::BannedSetIsDirty()
{
LOCK(cs_setBanned);
return setBannedIsDirty;
}
void CConnman::SetBannedSetDirty(bool dirty)
{
LOCK(cs_setBanned); //reuse setBanned lock for the isDirty flag
setBannedIsDirty = dirty;
}
bool CConnman::IsWhitelistedRange(const CNetAddr &addr) {
for (const CSubNet& subnet : vWhitelistedRange) {
if (subnet.Match(addr))
return true;
}
return false;
}
std::string CNode::GetAddrName() const {
LOCK(cs_addrName);
return addrName;
}
void CNode::MaybeSetAddrName(const std::string& addrNameIn) {
LOCK(cs_addrName);
if (addrName.empty()) {
addrName = addrNameIn;
}
}
CService CNode::GetAddrLocal() const {
LOCK(cs_addrLocal);
return addrLocal;
}
void CNode::SetAddrLocal(const CService& addrLocalIn) {
LOCK(cs_addrLocal);
if (addrLocal.IsValid()) {
error("Addr local already set for node: %i. Refusing to change from %s to %s", id, addrLocal.ToString(), addrLocalIn.ToString());
} else {
addrLocal = addrLocalIn;
}
}
std::string CNode::GetLogString() const
{
return fLogIPs ? addr.ToString() : strprintf("%d", id);
}
#undef X
#define X(name) stats.name = name
void CNode::copyStats(CNodeStats &stats)
{
stats.nodeid = this->GetId();
X(nServices);
X(addr);
X(addrBind);
{
LOCK(cs_filter);
X(fRelayTxes);
}
X(nLastSend);
X(nLastRecv);
X(nTimeConnected);
X(nTimeOffset);
stats.addrName = GetAddrName();
X(nVersion);
{
LOCK(cs_SubVer);
X(cleanSubVer);
}
X(fInbound);
X(m_manual_connection);
X(nStartingHeight);
{
LOCK(cs_vSend);
X(mapSendBytesPerMsgCmd);
X(nSendBytes);
}
{
LOCK(cs_vRecv);
X(mapRecvBytesPerMsgCmd);
X(nRecvBytes);
}
X(fWhitelisted);
// It is common for nodes with good ping times to suddenly become lagged,
// due to a new block arriving or other large transfer.
// Merely reporting pingtime might fool the caller into thinking the node was still responsive,
// since pingtime does not update until the ping is complete, which might take a while.
// So, if a ping is taking an unusually long time in flight,
// the caller can immediately detect that this is happening.
int64_t nPingUsecWait = 0;
if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) {
nPingUsecWait = GetTimeMicros() - nPingUsecStart;
}
// Raw ping time is in microseconds, but show it to user as whole seconds (Dash users should be well used to small numbers with many decimal places by now :)
stats.dPingTime = (((double)nPingUsecTime) / 1e6);
stats.dMinPing = (((double)nMinPingUsecTime) / 1e6);
stats.dPingWait = (((double)nPingUsecWait) / 1e6);
// Leave string empty if addrLocal invalid (not filled in yet)
CService addrLocalUnlocked = GetAddrLocal();
stats.addrLocal = addrLocalUnlocked.IsValid() ? addrLocalUnlocked.ToString() : "";
{
LOCK(cs_mnauth);
X(verifiedProRegTxHash);
}
}
#undef X
bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool& complete)
{
complete = false;
int64_t nTimeMicros = GetTimeMicros();
LOCK(cs_vRecv);
nLastRecv = nTimeMicros / 1000000;
nRecvBytes += nBytes;
while (nBytes > 0) {
// get current incomplete message, or create a new one
if (vRecvMsg.empty() ||
vRecvMsg.back().complete())
vRecvMsg.push_back(CNetMessage(Params().MessageStart(), SER_NETWORK, INIT_PROTO_VERSION));
CNetMessage& msg = vRecvMsg.back();
// absorb network data
int handled;
if (!msg.in_data) {
handled = msg.readHeader(pch, nBytes);
} else {
handled = msg.readData(pch, nBytes);
}
if (handled < 0)
return false;
if (msg.in_data && msg.hdr.nMessageSize > MAX_PROTOCOL_MESSAGE_LENGTH) {
LogPrint(BCLog::NET, "Oversized message from peer=%i, disconnecting\n", GetId());
return false;
}
pch += handled;
nBytes -= handled;
if (msg.complete()) {
//store received bytes per message command
//to prevent a memory DOS, only allow valid commands
mapMsgCmdSize::iterator i = mapRecvBytesPerMsgCmd.find(msg.hdr.pchCommand);
if (i == mapRecvBytesPerMsgCmd.end())
i = mapRecvBytesPerMsgCmd.find(NET_MESSAGE_COMMAND_OTHER);
assert(i != mapRecvBytesPerMsgCmd.end());
i->second += msg.hdr.nMessageSize + CMessageHeader::HEADER_SIZE;
msg.nTime = nTimeMicros;
complete = true;
}
}
return true;
}
void CNode::SetSendVersion(int nVersionIn)
{
// Send version may only be changed in the version message, and
// only one version message is allowed per session. We can therefore
// treat this value as const and even atomic as long as it's only used
// once a version message has been successfully processed. Any attempt to
// set this twice is an error.
if (nSendVersion != 0) {
error("Send version already set for node: %i. Refusing to change from %i to %i", id, nSendVersion, nVersionIn);
} else {
nSendVersion = nVersionIn;
}
}
int CNode::GetSendVersion() const
{
// The send version should always be explicitly set to
// INIT_PROTO_VERSION rather than using this value until SetSendVersion
// has been called.
if (nSendVersion == 0) {
error("Requesting unset send version for node: %i. Using %i", id, INIT_PROTO_VERSION);
return INIT_PROTO_VERSION;
}
return nSendVersion;
}
int CNetMessage::readHeader(const char *pch, unsigned int nBytes)
{
// copy data to temporary parsing buffer
unsigned int nRemaining = 24 - nHdrPos;
unsigned int nCopy = std::min(nRemaining, nBytes);
memcpy(&hdrbuf[nHdrPos], pch, nCopy);
nHdrPos += nCopy;
// if header incomplete, exit
if (nHdrPos < 24)
return nCopy;
// deserialize to CMessageHeader
try {
hdrbuf >> hdr;
}
catch (const std::exception&) {
return -1;
}
// reject messages larger than MAX_SIZE
if (hdr.nMessageSize > MAX_SIZE)
return -1;
// switch state to reading message data
in_data = true;
return nCopy;
}
int CNetMessage::readData(const char *pch, unsigned int nBytes)
{
unsigned int nRemaining = hdr.nMessageSize - nDataPos;
unsigned int nCopy = std::min(nRemaining, nBytes);
if (vRecv.size() < nDataPos + nCopy) {
// Allocate up to 256 KiB ahead, but never more than the total message size.
vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024));
}
hasher.Write((const unsigned char*)pch, nCopy);
memcpy(&vRecv[nDataPos], pch, nCopy);
nDataPos += nCopy;
return nCopy;
}
const uint256& CNetMessage::GetMessageHash() const
{
assert(complete());
if (data_hash.IsNull())
hasher.Finalize(data_hash.begin());
return data_hash;
}
// requires LOCK(cs_vSend)
size_t CConnman::SocketSendData(CNode *pnode) const
{
auto it = pnode->vSendMsg.begin();
size_t nSentSize = 0;
while (it != pnode->vSendMsg.end()) {
const auto &data = *it;
assert(data.size() > pnode->nSendOffset);
int nBytes = 0;
{
LOCK(pnode->cs_hSocket);
if (pnode->hSocket == INVALID_SOCKET)
break;
nBytes = send(pnode->hSocket, reinterpret_cast<const char*>(data.data()) + pnode->nSendOffset, data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT);
}
if (nBytes > 0) {
pnode->nLastSend = GetSystemTimeInSeconds();
pnode->nSendBytes += nBytes;
pnode->nSendOffset += nBytes;
nSentSize += nBytes;
if (pnode->nSendOffset == data.size()) {
pnode->nSendOffset = 0;
pnode->nSendSize -= data.size();
pnode->fPauseSend = pnode->nSendSize > nSendBufferMaxSize;
it++;
} else {
// could not send full message; stop sending more
break;
}
} else {
if (nBytes < 0) {
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
{
LogPrintf("socket send error %s\n", NetworkErrorString(nErr));
pnode->fDisconnect = true;
}
}
// couldn't send anything at all
break;
}
}
if (it == pnode->vSendMsg.end()) {
assert(pnode->nSendOffset == 0);
assert(pnode->nSendSize == 0);
}
pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it);
return nSentSize;
}
struct NodeEvictionCandidate
{
NodeId id;
int64_t nTimeConnected;
int64_t nMinPingUsecTime;
int64_t nLastBlockTime;
int64_t nLastTXTime;
bool fRelevantServices;
bool fRelayTxes;
bool fBloomFilter;
uint64_t nKeyedNetGroup;
};
static bool ReverseCompareNodeMinPingTime(const NodeEvictionCandidate& a, const NodeEvictionCandidate& b)
{
return a.nMinPingUsecTime > b.nMinPingUsecTime;
}
static bool ReverseCompareNodeTimeConnected(const NodeEvictionCandidate& a, const NodeEvictionCandidate& b)
{
return a.nTimeConnected > b.nTimeConnected;
}
static bool CompareNetGroupKeyed(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b) {
return a.nKeyedNetGroup < b.nKeyedNetGroup;
}
static bool CompareNodeBlockTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
{
// There is a fall-through here because it is common for a node to have many peers which have not yet relayed a block.
if (a.nLastBlockTime != b.nLastBlockTime) return a.nLastBlockTime < b.nLastBlockTime;
if (a.fRelevantServices != b.fRelevantServices) return b.fRelevantServices;
return a.nTimeConnected > b.nTimeConnected;
}
static bool CompareNodeTXTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
{
// There is a fall-through here because it is common for a node to have more than a few peers that have not yet relayed txn.
if (a.nLastTXTime != b.nLastTXTime) return a.nLastTXTime < b.nLastTXTime;
if (a.fRelayTxes != b.fRelayTxes) return b.fRelayTxes;
if (a.fBloomFilter != b.fBloomFilter) return a.fBloomFilter;
return a.nTimeConnected > b.nTimeConnected;
}
/** Try to find a connection to evict when the node is full.
* Extreme care must be taken to avoid opening the node to attacker
* triggered network partitioning.
* The strategy used here is to protect a small number of peers
* for each of several distinct characteristics which are difficult
* to forge. In order to partition a node the attacker must be
* simultaneously better at all of them than honest peers.
*/
bool CConnman::AttemptToEvictConnection()
{
std::vector<NodeEvictionCandidate> vEvictionCandidates;
{
LOCK(cs_vNodes);
for (CNode *node : vNodes) {
if (node->fWhitelisted)
continue;
if (!node->fInbound)
continue;
if (node->fDisconnect)
continue;
if (fMasternodeMode) {
// This handles eviction protected nodes. Nodes are always protected for a short time after the connection
// was accepted. This short time is meant for the VERSION/VERACK exchange and the possible MNAUTH that might
// follow when the incoming connection is from another masternode. When a message other than MNAUTH
// is received after VERSION/VERACK, the protection is lifted immediately.
bool isProtected = GetSystemTimeInSeconds() - node->nTimeConnected < INBOUND_EVICTION_PROTECTION_TIME;
if (node->nTimeFirstMessageReceived != 0 && !node->fFirstMessageIsMNAUTH) {
isProtected = false;
}
// if MNAUTH was valid, the node is always protected (and at the same time not accounted when
// checking incoming connection limits)
if (!node->verifiedProRegTxHash.IsNull()) {
isProtected = true;
}
if (isProtected) {
continue;
}
}
NodeEvictionCandidate candidate = {node->GetId(), node->nTimeConnected, node->nMinPingUsecTime,
node->nLastBlockTime, node->nLastTXTime,
HasAllDesirableServiceFlags(node->nServices),
node->fRelayTxes, node->pfilter != nullptr, node->nKeyedNetGroup};
vEvictionCandidates.push_back(candidate);
}
}
if (vEvictionCandidates.empty()) return false;
// Protect connections with certain characteristics
// Deterministically select 4 peers to protect by netgroup.
// An attacker cannot predict which netgroups will be protected
std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), CompareNetGroupKeyed);
vEvictionCandidates.erase(vEvictionCandidates.end() - std::min(4, static_cast<int>(vEvictionCandidates.size())), vEvictionCandidates.end());
if (vEvictionCandidates.empty()) return false;
// Protect the 8 nodes with the lowest minimum ping time.
// An attacker cannot manipulate this metric without physically moving nodes closer to the target.
std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), ReverseCompareNodeMinPingTime);
vEvictionCandidates.erase(vEvictionCandidates.end() - std::min(8, static_cast<int>(vEvictionCandidates.size())), vEvictionCandidates.end());
if (vEvictionCandidates.empty()) return false;
// Protect 4 nodes that most recently sent us transactions.
// An attacker cannot manipulate this metric without performing useful work.
std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), CompareNodeTXTime);
vEvictionCandidates.erase(vEvictionCandidates.end() - std::min(4, static_cast<int>(vEvictionCandidates.size())), vEvictionCandidates.end());
if (vEvictionCandidates.empty()) return false;
// Protect 4 nodes that most recently sent us blocks.
// An attacker cannot manipulate this metric without performing useful work.
std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), CompareNodeBlockTime);
vEvictionCandidates.erase(vEvictionCandidates.end() - std::min(4, static_cast<int>(vEvictionCandidates.size())), vEvictionCandidates.end());
if (vEvictionCandidates.empty()) return false;
// Protect the half of the remaining nodes which have been connected the longest.
// This replicates the non-eviction implicit behavior, and precludes attacks that start later.
std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), ReverseCompareNodeTimeConnected);
vEvictionCandidates.erase(vEvictionCandidates.end() - static_cast<int>(vEvictionCandidates.size() / 2), vEvictionCandidates.end());
if (vEvictionCandidates.empty()) return false;
// Identify the network group with the most connections and youngest member.
// (vEvictionCandidates is already sorted by reverse connect time)
uint64_t naMostConnections;
unsigned int nMostConnections = 0;
int64_t nMostConnectionsTime = 0;
std::map<uint64_t, std::vector<NodeEvictionCandidate> > mapNetGroupNodes;
for (const NodeEvictionCandidate &node : vEvictionCandidates) {
mapNetGroupNodes[node.nKeyedNetGroup].push_back(node);
int64_t grouptime = mapNetGroupNodes[node.nKeyedNetGroup][0].nTimeConnected;
size_t groupsize = mapNetGroupNodes[node.nKeyedNetGroup].size();
if (groupsize > nMostConnections || (groupsize == nMostConnections && grouptime > nMostConnectionsTime)) {
nMostConnections = groupsize;
nMostConnectionsTime = grouptime;
naMostConnections = node.nKeyedNetGroup;
}
}
// Reduce to the network group with the most connections
vEvictionCandidates = std::move(mapNetGroupNodes[naMostConnections]);
// Disconnect from the network group with the most connections
NodeId evicted = vEvictionCandidates.front().id;
LOCK(cs_vNodes);
for(std::vector<CNode*>::const_iterator it(vNodes.begin()); it != vNodes.end(); ++it) {
if ((*it)->GetId() == evicted) {
(*it)->fDisconnect = true;
return true;
}
}
return false;
}
void CConnman::AcceptConnection(const ListenSocket& hListenSocket) {
struct sockaddr_storage sockaddr;
socklen_t len = sizeof(sockaddr);
SOCKET hSocket = accept(hListenSocket.socket, (struct sockaddr*)&sockaddr, &len);
CAddress addr;
int nInbound = 0;
int nVerifiedInboundMasternodes = 0;
int nMaxInbound = nMaxConnections - (nMaxOutbound + nMaxFeeler);
if (hSocket != INVALID_SOCKET) {
if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr)) {
LogPrintf("Warning: Unknown socket family\n");
}
}
bool whitelisted = hListenSocket.whitelisted || IsWhitelistedRange(addr);
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes) {
if (pnode->fInbound) {
nInbound++;
if (!pnode->verifiedProRegTxHash.IsNull()) {
nVerifiedInboundMasternodes++;
}
}
}
}
if (hSocket == INVALID_SOCKET)
{
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK)
LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr));
return;
}
std::string strDropped;
if (fLogIPs) {
strDropped = strprintf("connection from %s dropped", addr.ToString());
} else {
strDropped = "connection dropped";
}
if (!fNetworkActive) {
LogPrintf("%s: not accepting new connections\n", strDropped);
CloseSocket(hSocket);
return;
}
if (!IsSelectableSocket(hSocket))
{
LogPrintf("%s: non-selectable socket\n", strDropped);
CloseSocket(hSocket);
return;
}
// According to the internet TCP_NODELAY is not carried into accepted sockets
// on all platforms. Set it again here just to be sure.
SetSocketNoDelay(hSocket);
if (IsBanned(addr) && !whitelisted)
{
LogPrintf("%s (banned)\n", strDropped);
CloseSocket(hSocket);
return;
}
// Evict connections until we are below nMaxInbound. In case eviction protection resulted in nodes to not be evicted
// before, they might get evicted in batches now (after the protection timeout).
// We don't evict verified MN connections and also don't take them into account when checking limits. We can do this
// because we know that such connections are naturally limited by the total number of MNs, so this is not usable
// for attacks.
while (nInbound - nVerifiedInboundMasternodes >= nMaxInbound)
{
if (!AttemptToEvictConnection()) {
// No connection to evict, disconnect the new connection
LogPrint(BCLog::NET, "failed to find an eviction candidate - connection dropped (full)\n");
CloseSocket(hSocket);
return;
}
nInbound--;
}
// don't accept incoming connections until fully synced
if(fMasternodeMode && !masternodeSync.IsSynced()) {
LogPrint(BCLog::NET, "AcceptConnection -- masternode is not synced yet, skipping inbound connection attempt\n");
CloseSocket(hSocket);
return;
}
NodeId id = GetNewNodeId();
uint64_t nonce = GetDeterministicRandomizer(RANDOMIZER_ID_LOCALHOSTNONCE).Write(id).Finalize();
CAddress addr_bind = GetBindAddress(hSocket);
CNode* pnode = new CNode(id, nLocalServices, GetBestHeight(), hSocket, addr, CalculateKeyedNetGroup(addr), nonce, addr_bind, "", true);
pnode->AddRef();
pnode->fWhitelisted = whitelisted;
m_msgproc->InitializeNode(pnode);
if (fLogIPs) {
LogPrint(BCLog::NET, "connection from %s accepted\n", addr.ToString());
} else {
LogPrint(BCLog::NET, "connection accepted\n");
}
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
}
void CConnman::ThreadSocketHandler()
{
unsigned int nPrevNodeCount = 0;
while (!interruptNet)
{
//
// Disconnect nodes
//
{
LOCK(cs_vNodes);
// Disconnect unused nodes
std::vector<CNode*> vNodesCopy = vNodes;
for (CNode* pnode : vNodesCopy)
{
if (pnode->fDisconnect)
{
if (fLogIPs) {
LogPrintf("ThreadSocketHandler -- removing node: peer=%d addr=%s nRefCount=%d fInbound=%d fMasternode=%d\n",
pnode->GetId(), pnode->addr.ToString(), pnode->GetRefCount(), pnode->fInbound, pnode->fMasternode);
} else {
LogPrintf("ThreadSocketHandler -- removing node: peer=%d nRefCount=%d fInbound=%d fMasternode=%d\n",
pnode->GetId(), pnode->GetRefCount(), pnode->fInbound, pnode->fMasternode);
}
// remove from vNodes
vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
// release outbound grant (if any)
pnode->grantOutbound.Release();
pnode->grantMasternodeOutbound.Release();
// close socket and cleanup
pnode->CloseSocketDisconnect();
// hold in disconnected pool until all refs are released
pnode->Release();
vNodesDisconnected.push_back(pnode);
}
}
}
{
// Delete disconnected nodes
std::list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
for (CNode* pnode : vNodesDisconnectedCopy)
{
// wait until threads are done using it
if (pnode->GetRefCount() <= 0) {
bool fDelete = false;
{
TRY_LOCK(pnode->cs_inventory, lockInv);
if (lockInv) {
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend) {
fDelete = true;
}
}
}
if (fDelete) {
vNodesDisconnected.remove(pnode);
DeleteNode(pnode);
}
}
}
}
size_t vNodesSize;
{
LOCK(cs_vNodes);
vNodesSize = vNodes.size();
}
if(vNodesSize != nPrevNodeCount) {
nPrevNodeCount = vNodesSize;
if(clientInterface)
clientInterface->NotifyNumConnectionsChanged(nPrevNodeCount);
}
//
// Find which sockets have data to receive
//
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 50000; // frequency to poll pnode->vSend
fd_set fdsetRecv;
fd_set fdsetSend;
fd_set fdsetError;
FD_ZERO(&fdsetRecv);
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
SOCKET hSocketMax = 0;
bool have_fds = false;
#ifndef WIN32
// We add a pipe to the read set so that the select() call can be woken up from the outside
// This is done when data is available for sending and at the same time optimistic sending was disabled
// when pushing the data.
// This is currently only implemented for POSIX compliant systems. This means that Windows will fall back to
// timing out after 50ms and then trying to send. This is ok as we assume that heavy-load daemons are usually
// run on Linux and friends.
FD_SET(wakeupPipe[0], &fdsetRecv);
hSocketMax = std::max(hSocketMax, (SOCKET)wakeupPipe[0]);
have_fds = true;
#endif
for (const ListenSocket& hListenSocket : vhListenSocket) {
FD_SET(hListenSocket.socket, &fdsetRecv);
hSocketMax = std::max(hSocketMax, hListenSocket.socket);
have_fds = true;
}
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes)
{
// Implement the following logic:
// * If there is data to send, select() for sending data. As this only
// happens when optimistic write failed, we choose to first drain the
// write buffer in this case before receiving more. This avoids
// needlessly queueing received data, if the remote peer is not themselves
// receiving data. This means properly utilizing TCP flow control signalling.
// * Otherwise, if there is space left in the receive buffer, select() for
// receiving data.
// * Hand off all complete messages to the processor, to be handled without
// blocking here.
bool select_recv = !pnode->fPauseRecv;
bool select_send;
{
LOCK(pnode->cs_vSend);
select_send = !pnode->vSendMsg.empty();
}
LOCK(pnode->cs_hSocket);
if (pnode->hSocket == INVALID_SOCKET)
continue;
FD_SET(pnode->hSocket, &fdsetError);
hSocketMax = std::max(hSocketMax, pnode->hSocket);
have_fds = true;
if (select_send) {
FD_SET(pnode->hSocket, &fdsetSend);
continue;
}
if (select_recv) {
FD_SET(pnode->hSocket, &fdsetRecv);
}
}
}
wakeupSelectNeeded = true;
int nSelect = select(have_fds ? hSocketMax + 1 : 0,
&fdsetRecv, &fdsetSend, &fdsetError, &timeout);
wakeupSelectNeeded = false;
if (interruptNet)
return;
if (nSelect == SOCKET_ERROR)
{
if (have_fds)
{
int nErr = WSAGetLastError();
LogPrintf("socket select error %s\n", NetworkErrorString(nErr));
for (unsigned int i = 0; i <= hSocketMax; i++)
FD_SET(i, &fdsetRecv);
}
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
if (!interruptNet.sleep_for(std::chrono::milliseconds(timeout.tv_usec/1000)))
return;
}
#ifndef WIN32
// drain the wakeup pipe
if (FD_ISSET(wakeupPipe[0], &fdsetRecv)) {
LogPrint(BCLog::NET, "woke up select()\n");
char buf[128];
while (true) {
int r = read(wakeupPipe[0], buf, sizeof(buf));
if (r <= 0) {
break;
}
}
}
#endif
//
// Accept new connections
//
for (const ListenSocket& hListenSocket : vhListenSocket)
{
if (hListenSocket.socket != INVALID_SOCKET && FD_ISSET(hListenSocket.socket, &fdsetRecv))
{
AcceptConnection(hListenSocket);
}
}
//
// Service each socket
//
std::vector<CNode*> vNodesCopy = CopyNodeVector();
for (CNode* pnode : vNodesCopy)
{
if (interruptNet)
return;
//
// Receive
//
bool recvSet = false;
bool sendSet = false;
bool errorSet = false;
{
LOCK(pnode->cs_hSocket);
if (pnode->hSocket == INVALID_SOCKET)
continue;
recvSet = FD_ISSET(pnode->hSocket, &fdsetRecv);
sendSet = FD_ISSET(pnode->hSocket, &fdsetSend);
errorSet = FD_ISSET(pnode->hSocket, &fdsetError);
}
if (recvSet || errorSet)
{
// typical socket buffer is 8K-64K
char pchBuf[0x10000];
int nBytes = 0;
{
LOCK(pnode->cs_hSocket);
if (pnode->hSocket == INVALID_SOCKET)
continue;
nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
}
if (nBytes > 0)
{
bool notify = false;
if (!pnode->ReceiveMsgBytes(pchBuf, nBytes, notify))
pnode->CloseSocketDisconnect();
RecordBytesRecv(nBytes);
if (notify) {
size_t nSizeAdded = 0;
auto it(pnode->vRecvMsg.begin());
for (; it != pnode->vRecvMsg.end(); ++it) {
if (!it->complete())
break;
nSizeAdded += it->vRecv.size() + CMessageHeader::HEADER_SIZE;
}
{
LOCK(pnode->cs_vProcessMsg);
pnode->vProcessMsg.splice(pnode->vProcessMsg.end(), pnode->vRecvMsg, pnode->vRecvMsg.begin(), it);
pnode->nProcessQueueSize += nSizeAdded;
pnode->fPauseRecv = pnode->nProcessQueueSize > nReceiveFloodSize;
}
WakeMessageHandler();
}
}
else if (nBytes == 0)
{
// socket closed gracefully
if (!pnode->fDisconnect) {
LogPrint(BCLog::NET, "socket closed\n");
}
pnode->CloseSocketDisconnect();
}
else if (nBytes < 0)
{
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
{
if (!pnode->fDisconnect)
LogPrintf("socket recv error %s\n", NetworkErrorString(nErr));
pnode->CloseSocketDisconnect();
}
}
}
//
// Send
//
if (sendSet)
{
LOCK(pnode->cs_vSend);
size_t nBytes = SocketSendData(pnode);
if (nBytes) {
RecordBytesSent(nBytes);
}
}
//
// Inactivity checking
//
int64_t nTime = GetSystemTimeInSeconds();
if (nTime - pnode->nTimeConnected > 60)
{
if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
{
LogPrint(BCLog::NET, "socket no message in first 60 seconds, %d %d from %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0, pnode->GetId());
pnode->fDisconnect = true;
}
else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL)
{
LogPrintf("socket sending timeout: %is\n", nTime - pnode->nLastSend);
pnode->fDisconnect = true;
}
else if (nTime - pnode->nLastRecv > (pnode->nVersion > BIP0031_VERSION ? TIMEOUT_INTERVAL : 90*60))
{
LogPrintf("socket receive timeout: %is\n", nTime - pnode->nLastRecv);
pnode->fDisconnect = true;
}
else if (pnode->nPingNonceSent && pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 < GetTimeMicros())
{
LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode->nPingUsecStart));
pnode->fDisconnect = true;
}
else if (!pnode->fSuccessfullyConnected)
{
LogPrintf("version handshake timeout from %d\n", pnode->GetId());
pnode->fDisconnect = true;
}
}
}
ReleaseNodeVector(vNodesCopy);
}
}
void CConnman::WakeMessageHandler()
{
{
std::lock_guard<std::mutex> lock(mutexMsgProc);
fMsgProcWake = true;
}
condMsgProc.notify_one();
}
void CConnman::WakeSelect()
{
#ifndef WIN32
if (wakeupPipe[1] == -1) {
return;
}
LogPrint(BCLog::NET, "waking up select()\n");
char buf[1];
if (write(wakeupPipe[1], buf, 1) != 1) {
LogPrint(BCLog::NET, "write to wakeupPipe failed\n");
}
#endif
wakeupSelectNeeded = false;
}
#ifdef USE_UPNP
void ThreadMapPort()
{
std::string port = strprintf("%u", GetListenPort());
const char * multicastif = 0;
const char * minissdpdpath = 0;
struct UPNPDev * devlist = 0;
char lanaddr[64];
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
#elif MINIUPNPC_API_VERSION < 14
/* miniupnpc 1.6 */
int error = 0;
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
#else
/* miniupnpc 1.9.20150730 */
int error = 0;
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, 2, &error);
#endif
struct UPNPUrls urls;
struct IGDdatas data;
int r;
r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
if (r == 1)
{
if (fDiscover) {
char externalIPAddress[40];
r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
if(r != UPNPCOMMAND_SUCCESS)
LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r);
else
{
if(externalIPAddress[0])
{
CNetAddr resolved;
if(LookupHost(externalIPAddress, resolved, false)) {
LogPrintf("UPnP: ExternalIPAddress = %s\n", resolved.ToString().c_str());
AddLocal(resolved, LOCAL_UPNP);
}
}
else
LogPrintf("UPnP: GetExternalIPAddress failed.\n");
}
}
std::string strDesc = "Pyrk " + FormatFullVersion();
try {
while (true) {
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
#else
/* miniupnpc 1.6 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
#endif
if(r!=UPNPCOMMAND_SUCCESS)
LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
port, port, lanaddr, r, strupnperror(r));
else
LogPrintf("UPnP Port Mapping successful.\n");
MilliSleep(20*60*1000); // Refresh every 20 minutes
}
}
catch (const boost::thread_interrupted&)
{
r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
LogPrintf("UPNP_DeletePortMapping() returned: %d\n", r);
freeUPNPDevlist(devlist); devlist = 0;
FreeUPNPUrls(&urls);
throw;
}
} else {
LogPrintf("No valid UPnP IGDs found\n");
freeUPNPDevlist(devlist); devlist = 0;
if (r != 0)
FreeUPNPUrls(&urls);
}
}
void MapPort(bool fUseUPnP)
{
static boost::thread* upnp_thread = nullptr;
if (fUseUPnP)
{
if (upnp_thread) {
upnp_thread->interrupt();
upnp_thread->join();
delete upnp_thread;
}
upnp_thread = new boost::thread(boost::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort));
}
else if (upnp_thread) {
upnp_thread->interrupt();
upnp_thread->join();
delete upnp_thread;
upnp_thread = nullptr;
}
}
#else
void MapPort(bool)
{
// Intentionally left blank.
}
#endif
static std::string GetDNSHost(const CDNSSeedData& data, ServiceFlags* requiredServiceBits)
{
//use default host for non-filter-capable seeds or if we use the default service bits (NODE_NETWORK)
if (!data.supportsServiceBitsFiltering || *requiredServiceBits == NODE_NETWORK) {
*requiredServiceBits = NODE_NETWORK;
return data.host;
}
return strprintf("x%x.%s", *requiredServiceBits, data.host);
}
void CConnman::ThreadDNSAddressSeed()
{
// goal: only query DNS seeds if address need is acute
// Avoiding DNS seeds when we don't need them improves user privacy by
// creating fewer identifying DNS requests, reduces trust by giving seeds
// less influence on the network topology, and reduces traffic to the seeds.
if ((addrman.size() > 0) &&
(!gArgs.GetBoolArg("-forcednsseed", DEFAULT_FORCEDNSSEED))) {
if (!interruptNet.sleep_for(std::chrono::seconds(11)))
return;
LOCK(cs_vNodes);
int nRelevant = 0;
for (auto pnode : vNodes) {
nRelevant += pnode->fSuccessfullyConnected && !pnode->fFeeler && !pnode->fOneShot && !pnode->m_manual_connection && !pnode->fInbound;
}
if (nRelevant >= 2) {
LogPrintf("P2P peers available. Skipped DNS seeding.\n");
return;
}
}
const std::vector<CDNSSeedData> &vSeeds = Params().DNSSeeds();
int found = 0;
LogPrintf("Loading addresses from DNS seeds (could take a while)\n");
for (const CDNSSeedData &seed : vSeeds) {
if (interruptNet) {
return;
}
if (HaveNameProxy()) {
AddOneShot(seed.host);
} else {
std::vector<CNetAddr> vIPs;
std::vector<CAddress> vAdd;
ServiceFlags requiredServiceBits = GetDesirableServiceFlags(NODE_NONE);
std::string host = GetDNSHost(seed, &requiredServiceBits);
CNetAddr resolveSource;
if (!resolveSource.SetInternal(host)) {
continue;
}
if (LookupHost(host.c_str(), vIPs, 0, true))
{
for (const CNetAddr& ip : vIPs)
{
int nOneDay = 24*3600;
CAddress addr = CAddress(CService(ip, Params().GetDefaultPort()), requiredServiceBits);
addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
vAdd.push_back(addr);
found++;
}
addrman.Add(vAdd, resolveSource);
}
}
}
LogPrintf("%d addresses found from DNS seeds\n", found);
}
void CConnman::DumpAddresses()
{
int64_t nStart = GetTimeMillis();
CAddrDB adb;
adb.Write(addrman);
LogPrint(BCLog::NET, "Flushed %d addresses to peers.dat %dms\n",
addrman.size(), GetTimeMillis() - nStart);
}
void CConnman::DumpData()
{
DumpAddresses();
DumpBanlist();
}
void CConnman::ProcessOneShot()
{
std::string strDest;
{
LOCK(cs_vOneShots);
if (vOneShots.empty())
return;
strDest = vOneShots.front();
vOneShots.pop_front();
}
CAddress addr;
CSemaphoreGrant grant(*semOutbound, true);
if (grant) {
if (!OpenNetworkConnection(addr, false, &grant, strDest.c_str(), true))
AddOneShot(strDest);
}
}
bool CConnman::GetTryNewOutboundPeer()
{
return m_try_another_outbound_peer;
}
void CConnman::SetTryNewOutboundPeer(bool flag)
{
m_try_another_outbound_peer = flag;
LogPrint(BCLog::NET, "net: setting try another outbound peer=%s\n", flag ? "true" : "false");
}
// Return the number of peers we have over our outbound connection limit
// Exclude peers that are marked for disconnect, or are going to be
// disconnected soon (eg one-shots and feelers)
// Also exclude peers that haven't finished initial connection handshake yet
// (so that we don't decide we're over our desired connection limit, and then
// evict some peer that has finished the handshake)
int CConnman::GetExtraOutboundCount()
{
int nOutbound = 0;
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes) {
// don't count outbound masternodes
if (pnode->fMasternode) {
continue;
}
if (!pnode->fInbound && !pnode->m_manual_connection && !pnode->fFeeler && !pnode->fDisconnect && !pnode->fOneShot && pnode->fSuccessfullyConnected) {
++nOutbound;
}
}
}
return std::max(nOutbound - nMaxOutbound, 0);
}
void CConnman::ThreadOpenConnections()
{
// Connect to specific addresses
if (gArgs.IsArgSet("-connect"))
{
for (int64_t nLoop = 0;; nLoop++)
{
ProcessOneShot();
for (const std::string& strAddr : gArgs.GetArgs("-connect"))
{
CAddress addr(CService(), NODE_NONE);
OpenNetworkConnection(addr, false, nullptr, strAddr.c_str(), false, false, true);
for (int i = 0; i < 10 && i < nLoop; i++)
{
if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
return;
}
}
if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
return;
}
}
// Initiate network connections
int64_t nStart = GetTime();
// Minimum time before next feeler connection (in microseconds).
int64_t nNextFeeler = PoissonNextSend(nStart*1000*1000, FEELER_INTERVAL);
while (!interruptNet)
{
ProcessOneShot();
if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
return;
CSemaphoreGrant grant(*semOutbound);
if (interruptNet)
return;
// Add seed nodes if DNS seeds are all down (an infrastructure attack?).
if (addrman.size() == 0 && (GetTime() - nStart > 1)) {
static bool done = false;
if (!done) {
LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n");
CNetAddr local;
local.SetInternal("fixedseeds");
addrman.Add(convertSeed6(Params().FixedSeeds()), local);
done = true;
}
}
//
// Choose an address to connect to based on most recently seen
//
CAddress addrConnect;
// Only connect out to one peer per network group (/16 for IPv4).
// Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
// This is only done for mainnet and testnet
int nOutbound = 0;
std::set<std::vector<unsigned char> > setConnected;
if (!Params().AllowMultipleAddressesFromGroup()) {
LOCK(cs_vNodes);
for (CNode* pnode : vNodes) {
if (!pnode->fInbound && !pnode->fMasternode && !pnode->m_manual_connection) {
// Netgroups for inbound and addnode peers are not excluded because our goal here
// is to not use multiple of our limited outbound slots on a single netgroup
// but inbound and addnode peers do not use our outbound slots. Inbound peers
// also have the added issue that they're attacker controlled and could be used
// to prevent us from connecting to particular hosts if we used them here.
setConnected.insert(pnode->addr.GetGroup());
nOutbound++;
}
}
}
// Feeler Connections
//
// Design goals:
// * Increase the number of connectable addresses in the tried table.
//
// Method:
// * Choose a random address from new and attempt to connect to it if we can connect
// successfully it is added to tried.
// * Start attempting feeler connections only after node finishes making outbound
// connections.
// * Only make a feeler connection once every few minutes.
//
bool fFeeler = false;
if (nOutbound >= nMaxOutbound && !GetTryNewOutboundPeer()) {
int64_t nTime = GetTimeMicros(); // The current time right now (in microseconds).
if (nTime > nNextFeeler) {
nNextFeeler = PoissonNextSend(nTime, FEELER_INTERVAL);
fFeeler = true;
} else {
continue;
}
}
auto mnList = deterministicMNManager->GetListAtChainTip();
int64_t nANow = GetAdjustedTime();
int nTries = 0;
while (!interruptNet)
{
CAddrInfo addr = addrman.Select(fFeeler);
bool isMasternode = mnList.GetMNByService(addr) != nullptr;
// if we selected an invalid address, restart
if (!addr.IsValid() || setConnected.count(addr.GetGroup()))
break;
// if we selected a local address, restart (local addresses are allowed in regtest and devnet)
bool fAllowLocal = Params().AllowMultiplePorts() && addrConnect.GetPort() != GetListenPort();
if (!fAllowLocal && IsLocal(addrConnect))
break;
// If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
// stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
// already-connected network ranges, ...) before trying new addrman addresses.
nTries++;
if (nTries > 100)
break;
if (IsLimited(addr))
continue;
// only consider very recently tried nodes after 30 failed attempts
if (nANow - addr.nLastTry < 600 && nTries < 30)
continue;
// for non-feelers, require all the services we'll want,
// for feelers, only require they be a full node (only because most
// SPV clients don't have a good address DB available)
if (!isMasternode && !fFeeler && !HasAllDesirableServiceFlags(addr.nServices)) {
continue;
} else if (!isMasternode && fFeeler && !MayHaveUsefulAddressDB(addr.nServices)) {
continue;
}
// do not allow non-default ports, unless after 50 invalid addresses selected already
if ((!isMasternode || !Params().AllowMultiplePorts()) && addr.GetPort() != Params().GetDefaultPort() && addr.GetPort() != GetListenPort() && nTries < 50)
continue;
addrConnect = addr;
break;
}
if (addrConnect.IsValid()) {
if (fFeeler) {
// Add small amount of random noise before connection to avoid synchronization.
int randsleep = GetRandInt(FEELER_SLEEP_WINDOW * 1000);
if (!interruptNet.sleep_for(std::chrono::milliseconds(randsleep)))
return;
if (fLogIPs) {
LogPrint(BCLog::NET, "Making feeler connection to %s\n", addrConnect.ToString());
} else {
LogPrint(BCLog::NET, "Making feeler connection\n");
}
}
OpenNetworkConnection(addrConnect, (int)setConnected.size() >= std::min(nMaxConnections - 1, 2), &grant, nullptr, false, fFeeler);
}
}
}
std::vector<AddedNodeInfo> CConnman::GetAddedNodeInfo()
{
std::vector<AddedNodeInfo> ret;
std::list<std::string> lAddresses(0);
{
LOCK(cs_vAddedNodes);
ret.reserve(vAddedNodes.size());
for (const std::string& strAddNode : vAddedNodes)
lAddresses.push_back(strAddNode);
}
// Build a map of all already connected addresses (by IP:port and by name) to inbound/outbound and resolved CService
std::map<CService, bool> mapConnected;
std::map<std::string, std::pair<bool, CService>> mapConnectedByName;
{
LOCK(cs_vNodes);
for (const CNode* pnode : vNodes) {
if (pnode->addr.IsValid()) {
mapConnected[pnode->addr] = pnode->fInbound;
}
std::string addrName = pnode->GetAddrName();
if (!addrName.empty()) {
mapConnectedByName[std::move(addrName)] = std::make_pair(pnode->fInbound, static_cast<const CService&>(pnode->addr));
}
}
}
for (const std::string& strAddNode : lAddresses) {
CService service(LookupNumeric(strAddNode.c_str(), Params().GetDefaultPort()));
if (service.IsValid()) {
// strAddNode is an IP:port
auto it = mapConnected.find(service);
if (it != mapConnected.end()) {
ret.push_back(AddedNodeInfo{strAddNode, service, true, it->second});
} else {
ret.push_back(AddedNodeInfo{strAddNode, CService(), false, false});
}
} else {
// strAddNode is a name
auto it = mapConnectedByName.find(strAddNode);
if (it != mapConnectedByName.end()) {
ret.push_back(AddedNodeInfo{strAddNode, it->second.second, true, it->second.first});
} else {
ret.push_back(AddedNodeInfo{strAddNode, CService(), false, false});
}
}
}
return ret;
}
void CConnman::ThreadOpenAddedConnections()
{
{
LOCK(cs_vAddedNodes);
vAddedNodes = gArgs.GetArgs("-addnode");
}
while (true)
{
CSemaphoreGrant grant(*semAddnode);
std::vector<AddedNodeInfo> vInfo = GetAddedNodeInfo();
bool tried = false;
for (const AddedNodeInfo& info : vInfo) {
if (!info.fConnected) {
if (!grant.TryAcquire()) {
// If we've used up our semaphore and need a new one, lets not wait here since while we are waiting
// the addednodeinfo state might change.
break;
}
// If strAddedNode is an IP/port, decode it immediately, so
// OpenNetworkConnection can detect existing connections to that IP/port.
tried = true;
CService service(LookupNumeric(info.strAddedNode.c_str(), Params().GetDefaultPort()));
OpenNetworkConnection(CAddress(service, NODE_NONE), false, &grant, info.strAddedNode.c_str(), false, false, true);
if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
return;
}
}
// Retry every 60 seconds if a connection was attempted, otherwise two seconds
if (!interruptNet.sleep_for(std::chrono::seconds(tried ? 60 : 2)))
return;
}
}
void CConnman::ThreadOpenMasternodeConnections()
{
// Connecting to specific addresses, no masternode connections available
if (gArgs.IsArgSet("-connect") && gArgs.GetArgs("-connect").size() > 0)
return;
while (!interruptNet)
{
if (!interruptNet.sleep_for(std::chrono::milliseconds(1000)))
return;
std::set<CService> connectedNodes;
std::set<uint256> connectedProRegTxHashes;
ForEachNode([&](const CNode* pnode) {
connectedNodes.emplace(pnode->addr);
if (!pnode->verifiedProRegTxHash.IsNull()) {
connectedProRegTxHashes.emplace(pnode->verifiedProRegTxHash);
}
});
auto mnList = deterministicMNManager->GetListAtChainTip();
CSemaphoreGrant grant(*semMasternodeOutbound);
if (interruptNet)
return;
int64_t nANow = GetAdjustedTime();
// NOTE: Process only one pending masternode at a time
CService addr;
{ // don't hold lock while calling OpenMasternodeConnection as cs_main is locked deep inside
LOCK2(cs_vNodes, cs_vPendingMasternodes);
std::vector<CService> pending;
for (const auto& group : masternodeQuorumNodes) {
for (const auto& proRegTxHash : group.second) {
auto dmn = mnList.GetMN(proRegTxHash);
if (!dmn) {
continue;
}
const auto& addr2 = dmn->pdmnState->addr;
if (!connectedNodes.count(addr2) && !IsMasternodeOrDisconnectRequested(addr2) && !connectedProRegTxHashes.count(proRegTxHash)) {
auto addrInfo = addrman.GetAddressInfo(addr2);
// back off trying connecting to an address if we already tried recently
if (addrInfo.IsValid() && nANow - addrInfo.nLastTry < 60) {
continue;
}
pending.emplace_back(addr2);
}
}
}
if (!vPendingMasternodes.empty()) {
auto addr2 = vPendingMasternodes.front();
vPendingMasternodes.erase(vPendingMasternodes.begin());
if (!connectedNodes.count(addr2) && !IsMasternodeOrDisconnectRequested(addr2)) {
pending.emplace_back(addr2);
}
}
if (pending.empty()) {
// nothing to do, keep waiting
continue;
}
std::random_shuffle(pending.begin(), pending.end());
addr = pending.front();
}
OpenMasternodeConnection(CAddress(addr, NODE_NETWORK));
// should be in the list now if connection was opened
ForNode(addr, CConnman::AllNodes, [&](CNode* pnode) {
if (pnode->fDisconnect) {
return false;
}
grant.MoveTo(pnode->grantMasternodeOutbound);
return true;
});
}
}
// if successful, this moves the passed grant to the constructed node
bool CConnman::OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *pszDest, bool fOneShot, bool fFeeler, bool manual_connection, bool fConnectToMasternode)
{
//
// Initiate outbound network connection
//
if (interruptNet) {
return false;
}
if (!fNetworkActive) {
return false;
}
if (!pszDest) {
// banned or exact match?
if (IsBanned(addrConnect) || FindNode(addrConnect.ToStringIPPort()))
return false;
// local and not a connection to itself?
bool fAllowLocal = Params().AllowMultiplePorts() && addrConnect.GetPort() != GetListenPort();
if (!fAllowLocal && IsLocal(addrConnect))
return false;
// if multiple ports for same IP are allowed, search for IP:PORT match, otherwise search for IP-only match
if ((!Params().AllowMultiplePorts() && FindNode((CNetAddr)addrConnect)) ||
(Params().AllowMultiplePorts() && FindNode((CService)addrConnect)))
return false;
} else if (FindNode(std::string(pszDest)))
return false;
CNode* pnode = ConnectNode(addrConnect, pszDest, fCountFailure);
if (!pnode)
return false;
if (grantOutbound)
grantOutbound->MoveTo(pnode->grantOutbound);
if (fOneShot)
pnode->fOneShot = true;
if (fFeeler)
pnode->fFeeler = true;
if (manual_connection)
pnode->m_manual_connection = true;
if (fConnectToMasternode)
pnode->fMasternode = true;
m_msgproc->InitializeNode(pnode);
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
return true;
}
bool CConnman::OpenMasternodeConnection(const CAddress &addrConnect) {
return OpenNetworkConnection(addrConnect, false, nullptr, nullptr, false, false, false, true);
}
void CConnman::ThreadMessageHandler()
{
while (!flagInterruptMsgProc)
{
std::vector<CNode*> vNodesCopy = CopyNodeVector();
bool fMoreWork = false;
for (CNode* pnode : vNodesCopy)
{
if (pnode->fDisconnect)
continue;
// Receive messages
bool fMoreNodeWork = m_msgproc->ProcessMessages(pnode, flagInterruptMsgProc);
fMoreWork |= (fMoreNodeWork && !pnode->fPauseSend);
if (flagInterruptMsgProc)
return;
// Send messages
{
LOCK(pnode->cs_sendProcessing);
m_msgproc->SendMessages(pnode, flagInterruptMsgProc);
}
if (flagInterruptMsgProc)
return;
}
ReleaseNodeVector(vNodesCopy);
std::unique_lock<std::mutex> lock(mutexMsgProc);
if (!fMoreWork) {
condMsgProc.wait_until(lock, std::chrono::steady_clock::now() + std::chrono::milliseconds(100), [this] { return fMsgProcWake; });
}
fMsgProcWake = false;
}
}
bool CConnman::BindListenPort(const CService &addrBind, std::string& strError, bool fWhitelisted)
{
strError = "";
int nOne = 1;
// Create socket for listening for incoming connections
struct sockaddr_storage sockaddr;
socklen_t len = sizeof(sockaddr);
if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
{
strError = strprintf("Error: Bind address family for %s not supported", addrBind.ToString());
LogPrintf("%s\n", strError);
return false;
}
SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (hListenSocket == INVALID_SOCKET)
{
strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError()));
LogPrintf("%s\n", strError);
return false;
}
if (!IsSelectableSocket(hListenSocket))
{
strError = "Error: Couldn't create a listenable socket for incoming connections";
LogPrintf("%s\n", strError);
return false;
}
#ifndef WIN32
#ifdef SO_NOSIGPIPE
// Different way of disabling SIGPIPE on BSD
setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
#endif
// Allow binding if the port is still in TIME_WAIT state after
// the program was closed and restarted.
setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
// Disable Nagle's algorithm
setsockopt(hListenSocket, IPPROTO_TCP, TCP_NODELAY, (void*)&nOne, sizeof(int));
#else
setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&nOne, sizeof(int));
setsockopt(hListenSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&nOne, sizeof(int));
#endif
// Set to non-blocking, incoming connections will also inherit this
if (!SetSocketNonBlocking(hListenSocket, true)) {
CloseSocket(hListenSocket);
strError = strprintf("BindListenPort: Setting listening socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
LogPrintf("%s\n", strError);
return false;
}
// some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
// and enable it by default or not. Try to enable it, if possible.
if (addrBind.IsIPv6()) {
#ifdef IPV6_V6ONLY
#ifdef WIN32
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
#else
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
#endif
#endif
#ifdef WIN32
int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED;
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, (const char*)&nProtLevel, sizeof(int));
#endif
}
if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
{
int nErr = WSAGetLastError();
if (nErr == WSAEADDRINUSE)
strError = strprintf(_("Unable to bind to %s on this computer. %s is probably already running."), addrBind.ToString(), _(PACKAGE_NAME));
else
strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToString(), NetworkErrorString(nErr));
LogPrintf("%s\n", strError);
CloseSocket(hListenSocket);
return false;
}
LogPrintf("Bound to %s\n", addrBind.ToString());
// Listen for incoming connections
if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
{
strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError()));
LogPrintf("%s\n", strError);
CloseSocket(hListenSocket);
return false;
}
vhListenSocket.push_back(ListenSocket(hListenSocket, fWhitelisted));
if (addrBind.IsRoutable() && fDiscover && !fWhitelisted)
AddLocal(addrBind, LOCAL_BIND);
return true;
}
void Discover(boost::thread_group& threadGroup)
{
if (!fDiscover)
return;
#ifdef WIN32
// Get local host IP
char pszHostName[256] = "";
if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
{
std::vector<CNetAddr> vaddr;
if (LookupHost(pszHostName, vaddr, 0, true))
{
for (const CNetAddr &addr : vaddr)
{
if (AddLocal(addr, LOCAL_IF))
LogPrintf("%s: %s - %s\n", __func__, pszHostName, addr.ToString());
}
}
}
#else
// Get local host ip
struct ifaddrs* myaddrs;
if (getifaddrs(&myaddrs) == 0)
{
for (struct ifaddrs* ifa = myaddrs; ifa != nullptr; ifa = ifa->ifa_next)
{
if (ifa->ifa_addr == nullptr) continue;
if ((ifa->ifa_flags & IFF_UP) == 0) continue;
if (strcmp(ifa->ifa_name, "lo") == 0) continue;
if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
if (ifa->ifa_addr->sa_family == AF_INET)
{
struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
CNetAddr addr(s4->sin_addr);
if (AddLocal(addr, LOCAL_IF))
LogPrintf("%s: IPv4 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
}
else if (ifa->ifa_addr->sa_family == AF_INET6)
{
struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
CNetAddr addr(s6->sin6_addr);
if (AddLocal(addr, LOCAL_IF))
LogPrintf("%s: IPv6 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
}
}
freeifaddrs(myaddrs);
}
#endif
}
void CConnman::SetNetworkActive(bool active)
{
LogPrint(BCLog::NET, "SetNetworkActive: %s\n", active);
if (fNetworkActive == active) {
return;
}
fNetworkActive = active;
if (!fNetworkActive) {
LOCK(cs_vNodes);
// Close sockets to all nodes
for (CNode* pnode : vNodes) {
pnode->CloseSocketDisconnect();
}
}
uiInterface.NotifyNetworkActiveChanged(fNetworkActive);
}
CConnman::CConnman(uint64_t nSeed0In, uint64_t nSeed1In) :
addrman(Params().AllowMultiplePorts()),
nSeed0(nSeed0In), nSeed1(nSeed1In)
{
fNetworkActive = true;
setBannedIsDirty = false;
fAddressesInitialized = false;
nLastNodeId = 0;
nSendBufferMaxSize = 0;
nReceiveFloodSize = 0;
semOutbound = nullptr;
semAddnode = nullptr;
semMasternodeOutbound = nullptr;
flagInterruptMsgProc = false;
SetTryNewOutboundPeer(false);
Options connOptions;
Init(connOptions);
}
NodeId CConnman::GetNewNodeId()
{
return nLastNodeId.fetch_add(1, std::memory_order_relaxed);
}
bool CConnman::Bind(const CService &addr, unsigned int flags) {
if (!(flags & BF_EXPLICIT) && IsLimited(addr))
return false;
std::string strError;
if (!BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) {
if ((flags & BF_REPORT_ERROR) && clientInterface) {
clientInterface->ThreadSafeMessageBox(strError, "", CClientUIInterface::MSG_ERROR);
}
return false;
}
return true;
}
bool CConnman::InitBinds(const std::vector<CService>& binds, const std::vector<CService>& whiteBinds) {
bool fBound = false;
for (const auto& addrBind : binds) {
fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
}
for (const auto& addrBind : whiteBinds) {
fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
}
if (binds.empty() && whiteBinds.empty()) {
struct in_addr inaddr_any;
inaddr_any.s_addr = INADDR_ANY;
fBound |= Bind(CService((in6_addr)IN6ADDR_ANY_INIT, GetListenPort()), BF_NONE);
fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
}
return fBound;
}
bool CConnman::Start(CScheduler& scheduler, const Options& connOptions)
{
Init(connOptions);
nTotalBytesRecv = 0;
nTotalBytesSent = 0;
nMaxOutboundTotalBytesSentInCycle = 0;
nMaxOutboundCycleStartTime = 0;
if (fListen && !InitBinds(connOptions.vBinds, connOptions.vWhiteBinds)) {
if (clientInterface) {
clientInterface->ThreadSafeMessageBox(
_("Failed to listen on any port. Use -listen=0 if you want this."),
"", CClientUIInterface::MSG_ERROR);
}
return false;
}
for (const auto& strDest : connOptions.vSeedNodes) {
AddOneShot(strDest);
}
if (clientInterface) {
clientInterface->InitMessage(_("Loading P2P addresses..."));
}
// Load addresses from peers.dat
int64_t nStart = GetTimeMillis();
{
CAddrDB adb;
if (adb.Read(addrman))
LogPrintf("Loaded %i addresses from peers.dat %dms\n", addrman.size(), GetTimeMillis() - nStart);
else {
addrman.Clear(); // Addrman can be in an inconsistent state after failure, reset it
LogPrintf("Invalid or missing peers.dat; recreating\n");
DumpAddresses();
}
}
if (clientInterface)
clientInterface->InitMessage(_("Loading banlist..."));
// Load addresses from banlist.dat
nStart = GetTimeMillis();
CBanDB bandb;
banmap_t banmap;
if (bandb.Read(banmap)) {
SetBanned(banmap); // thread save setter
SetBannedSetDirty(false); // no need to write down, just read data
SweepBanned(); // sweep out unused entries
LogPrint(BCLog::NET, "Loaded %d banned node ips/subnets from banlist.dat %dms\n",
banmap.size(), GetTimeMillis() - nStart);
} else {
LogPrintf("Invalid or missing banlist.dat; recreating\n");
SetBannedSetDirty(true); // force write
DumpBanlist();
}
uiInterface.InitMessage(_("Starting network threads..."));
fAddressesInitialized = true;
if (semOutbound == nullptr) {
// initialize semaphore
semOutbound = new CSemaphore(std::min((nMaxOutbound + nMaxFeeler), nMaxConnections));
}
if (semAddnode == nullptr) {
// initialize semaphore
semAddnode = new CSemaphore(nMaxAddnode);
}
if (semMasternodeOutbound == nullptr) {
// initialize semaphore
semMasternodeOutbound = new CSemaphore(fMasternodeMode ? MAX_OUTBOUND_MASTERNODE_CONNECTIONS_ON_MN : MAX_OUTBOUND_MASTERNODE_CONNECTIONS);
}
//
// Start threads
//
assert(m_msgproc);
InterruptSocks5(false);
interruptNet.reset();
flagInterruptMsgProc = false;
{
std::unique_lock<std::mutex> lock(mutexMsgProc);
fMsgProcWake = false;
}
#ifndef WIN32
if (pipe(wakeupPipe) != 0) {
wakeupPipe[0] = wakeupPipe[1] = -1;
LogPrint(BCLog::NET, "pipe() for wakeupPipe failed\n");
} else {
int fFlags = fcntl(wakeupPipe[0], F_GETFL, 0);
if (fcntl(wakeupPipe[0], F_SETFL, fFlags | O_NONBLOCK) == -1) {
LogPrint(BCLog::NET, "fcntl for O_NONBLOCK on wakeupPipe failed\n");
}
fFlags = fcntl(wakeupPipe[1], F_GETFL, 0);
if (fcntl(wakeupPipe[1], F_SETFL, fFlags | O_NONBLOCK) == -1) {
LogPrint(BCLog::NET, "fcntl for O_NONBLOCK on wakeupPipe failed\n");
}
}
#endif
// Send and receive from sockets, accept connections
threadSocketHandler = std::thread(&TraceThread<std::function<void()> >, "net", std::function<void()>(std::bind(&CConnman::ThreadSocketHandler, this)));
if (!gArgs.GetBoolArg("-dnsseed", true))
LogPrintf("DNS seeding disabled\n");
else
threadDNSAddressSeed = std::thread(&TraceThread<std::function<void()> >, "dnsseed", std::function<void()>(std::bind(&CConnman::ThreadDNSAddressSeed, this)));
// Initiate outbound connections from -addnode
threadOpenAddedConnections = std::thread(&TraceThread<std::function<void()> >, "addcon", std::function<void()>(std::bind(&CConnman::ThreadOpenAddedConnections, this)));
// Initiate outbound connections unless connect=0
if (!gArgs.IsArgSet("-connect") || gArgs.GetArgs("-connect").size() != 1 || gArgs.GetArgs("-connect")[0] != "0")
threadOpenConnections = std::thread(&TraceThread<std::function<void()> >, "opencon", std::function<void()>(std::bind(&CConnman::ThreadOpenConnections, this)));
// Initiate masternode connections
threadOpenMasternodeConnections = std::thread(&TraceThread<std::function<void()> >, "mncon", std::function<void()>(std::bind(&CConnman::ThreadOpenMasternodeConnections, this)));
// Process messages
threadMessageHandler = std::thread(&TraceThread<std::function<void()> >, "msghand", std::function<void()>(std::bind(&CConnman::ThreadMessageHandler, this)));
// Dump network addresses
scheduler.scheduleEvery(std::bind(&CConnman::DumpData, this), DUMP_ADDRESSES_INTERVAL * 1000);
return true;
}
class CNetCleanup
{
public:
CNetCleanup() {}
~CNetCleanup()
{
#ifdef WIN32
// Shutdown Windows Sockets
WSACleanup();
#endif
}
}
instance_of_cnetcleanup;
void CExplicitNetCleanup::callCleanup()
{
// Explicit call to destructor of CNetCleanup because it's not implicitly called
// when the wallet is restarted from within the wallet itself.
CNetCleanup *tmp = new CNetCleanup();
delete tmp; // Stroustrup's gonna kill me for that
}
void CConnman::Interrupt()
{
{
std::lock_guard<std::mutex> lock(mutexMsgProc);
flagInterruptMsgProc = true;
}
condMsgProc.notify_all();
interruptNet();
InterruptSocks5(true);
if (semOutbound) {
for (int i=0; i<(nMaxOutbound + nMaxFeeler); i++) {
semOutbound->post();
}
}
if (semAddnode) {
for (int i=0; i<nMaxAddnode; i++) {
semAddnode->post();
}
}
if (semMasternodeOutbound) {
int nMaxMasternodeOutbound = fMasternodeMode ? MAX_OUTBOUND_MASTERNODE_CONNECTIONS_ON_MN : MAX_OUTBOUND_MASTERNODE_CONNECTIONS;
for (int i = 0; i < nMaxMasternodeOutbound; i++) {
semMasternodeOutbound->post();
}
}
}
void CConnman::Stop()
{
if (threadMessageHandler.joinable())
threadMessageHandler.join();
if (threadOpenMasternodeConnections.joinable())
threadOpenMasternodeConnections.join();
if (threadOpenConnections.joinable())
threadOpenConnections.join();
if (threadOpenAddedConnections.joinable())
threadOpenAddedConnections.join();
if (threadDNSAddressSeed.joinable())
threadDNSAddressSeed.join();
if (threadSocketHandler.joinable())
threadSocketHandler.join();
if (fAddressesInitialized)
{
DumpData();
fAddressesInitialized = false;
}
// Close sockets
for (CNode* pnode : vNodes)
pnode->CloseSocketDisconnect();
for (ListenSocket& hListenSocket : vhListenSocket)
if (hListenSocket.socket != INVALID_SOCKET)
if (!CloseSocket(hListenSocket.socket))
LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError()));
// clean up some globals (to help leak detection)
for (CNode *pnode : vNodes) {
DeleteNode(pnode);
}
for (CNode *pnode : vNodesDisconnected) {
DeleteNode(pnode);
}
vNodes.clear();
vNodesDisconnected.clear();
vhListenSocket.clear();
delete semOutbound;
semOutbound = nullptr;
delete semAddnode;
semAddnode = nullptr;
delete semMasternodeOutbound;
semMasternodeOutbound = nullptr;
#ifndef WIN32
if (wakeupPipe[0] != -1) close(wakeupPipe[0]);
if (wakeupPipe[1] != -1) close(wakeupPipe[1]);
wakeupPipe[0] = wakeupPipe[1] = -1;
#endif
}
void CConnman::DeleteNode(CNode* pnode)
{
assert(pnode);
bool fUpdateConnectionTime = false;
m_msgproc->FinalizeNode(pnode->GetId(), fUpdateConnectionTime);
if(fUpdateConnectionTime) {
addrman.Connected(pnode->addr);
}
delete pnode;
}
CConnman::~CConnman()
{
Interrupt();
Stop();
}
size_t CConnman::GetAddressCount() const
{
return addrman.size();
}
void CConnman::SetServices(const CService &addr, ServiceFlags nServices)
{
addrman.SetServices(addr, nServices);
}
void CConnman::MarkAddressGood(const CAddress& addr)
{
addrman.Good(addr);
}
void CConnman::AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty)
{
addrman.Add(vAddr, addrFrom, nTimePenalty);
}
std::vector<CAddress> CConnman::GetAddresses()
{
return addrman.GetAddr();
}
bool CConnman::AddNode(const std::string& strNode)
{
LOCK(cs_vAddedNodes);
for(std::vector<std::string>::const_iterator it = vAddedNodes.begin(); it != vAddedNodes.end(); ++it) {
if (strNode == *it)
return false;
}
vAddedNodes.push_back(strNode);
return true;
}
bool CConnman::RemoveAddedNode(const std::string& strNode)
{
LOCK(cs_vAddedNodes);
for(std::vector<std::string>::iterator it = vAddedNodes.begin(); it != vAddedNodes.end(); ++it) {
if (strNode == *it) {
vAddedNodes.erase(it);
return true;
}
}
return false;
}
bool CConnman::AddPendingMasternode(const CService& service)
{
LOCK(cs_vPendingMasternodes);
for(std::vector<CService>::const_iterator it = vPendingMasternodes.begin(); it != vPendingMasternodes.end(); ++it) {
if (service == *it)
return false;
}
vPendingMasternodes.push_back(service);
return true;
}
bool CConnman::AddMasternodeQuorumNodes(Consensus::LLMQType llmqType, const uint256& quorumHash, const std::set<uint256>& proTxHashes)
{
LOCK(cs_vPendingMasternodes);
auto it = masternodeQuorumNodes.find(std::make_pair(llmqType, quorumHash));
if (it != masternodeQuorumNodes.end()) {
return false;
}
masternodeQuorumNodes.emplace(std::make_pair(llmqType, quorumHash), proTxHashes);
return true;
}
bool CConnman::HasMasternodeQuorumNodes(Consensus::LLMQType llmqType, const uint256& quorumHash)
{
LOCK(cs_vPendingMasternodes);
return masternodeQuorumNodes.count(std::make_pair(llmqType, quorumHash));
}
std::set<uint256> CConnman::GetMasternodeQuorums(Consensus::LLMQType llmqType)
{
LOCK(cs_vPendingMasternodes);
std::set<uint256> result;
for (const auto& p : masternodeQuorumNodes) {
if (p.first.first != llmqType) {
continue;
}
result.emplace(p.first.second);
}
return result;
}
std::set<NodeId> CConnman::GetMasternodeQuorumNodes(Consensus::LLMQType llmqType, const uint256& quorumHash) const
{
LOCK2(cs_vNodes, cs_vPendingMasternodes);
auto it = masternodeQuorumNodes.find(std::make_pair(llmqType, quorumHash));
if (it == masternodeQuorumNodes.end()) {
return {};
}
const auto& proRegTxHashes = it->second;
std::set<NodeId> nodes;
for (const auto pnode : vNodes) {
if (pnode->fDisconnect) {
continue;
}
if (!pnode->qwatch && (pnode->verifiedProRegTxHash.IsNull() || !proRegTxHashes.count(pnode->verifiedProRegTxHash))) {
continue;
}
nodes.emplace(pnode->GetId());
}
return nodes;
}
void CConnman::RemoveMasternodeQuorumNodes(Consensus::LLMQType llmqType, const uint256& quorumHash)
{
LOCK(cs_vPendingMasternodes);
masternodeQuorumNodes.erase(std::make_pair(llmqType, quorumHash));
}
bool CConnman::IsMasternodeQuorumNode(const CNode* pnode)
{
// Let's see if this is an outgoing connection to an address that is known to be a masternode
// We however only need to know this if the node did not authenticate itself as a MN yet
uint256 assumedProTxHash;
if (pnode->verifiedProRegTxHash.IsNull() && !pnode->fInbound) {
auto mnList = deterministicMNManager->GetListAtChainTip();
auto dmn = mnList.GetMNByService(pnode->addr);
if (dmn == nullptr) {
// This is definitely not a masternode
return false;
}
assumedProTxHash = dmn->proTxHash;
}
LOCK(cs_vPendingMasternodes);
for (const auto& p : masternodeQuorumNodes) {
if (!pnode->verifiedProRegTxHash.IsNull()) {
if (p.second.count(pnode->verifiedProRegTxHash)) {
return true;
}
} else if (!assumedProTxHash.IsNull()) {
if (p.second.count(assumedProTxHash)) {
return true;
}
}
}
return false;
}
size_t CConnman::GetNodeCount(NumConnections flags)
{
LOCK(cs_vNodes);
if (flags == CConnman::CONNECTIONS_ALL) // Shortcut if we want total
return vNodes.size();
int nNum = 0;
for(std::vector<CNode*>::const_iterator it = vNodes.begin(); it != vNodes.end(); ++it)
if (flags & ((*it)->fInbound ? CONNECTIONS_IN : CONNECTIONS_OUT))
nNum++;
return nNum;
}
size_t CConnman::GetMaxOutboundNodeCount()
{
return nMaxOutbound;
}
void CConnman::GetNodeStats(std::vector<CNodeStats>& vstats)
{
vstats.clear();
LOCK(cs_vNodes);
vstats.reserve(vNodes.size());
for(std::vector<CNode*>::iterator it = vNodes.begin(); it != vNodes.end(); ++it) {
CNode* pnode = *it;
vstats.emplace_back();
pnode->copyStats(vstats.back());
}
}
bool CConnman::DisconnectNode(const std::string& strNode)
{
LOCK(cs_vNodes);
if (CNode* pnode = FindNode(strNode)) {
pnode->fDisconnect = true;
return true;
}
return false;
}
bool CConnman::DisconnectNode(NodeId id)
{
LOCK(cs_vNodes);
for(CNode* pnode : vNodes) {
if (id == pnode->GetId()) {
pnode->fDisconnect = true;
return true;
}
}
return false;
}
void CConnman::RelayTransaction(const CTransaction& tx)
{
uint256 hash = tx.GetHash();
int nInv = MSG_TX;
if (CPrivateSend::GetDSTX(hash)) {
nInv = MSG_DSTX;
}
CInv inv(nInv, hash);
LOCK(cs_vNodes);
for (CNode* pnode : vNodes)
{
pnode->PushInventory(inv);
}
}
void CConnman::RelayInv(CInv &inv, const int minProtoVersion) {
LOCK(cs_vNodes);
for (const auto& pnode : vNodes)
if(pnode->nVersion >= minProtoVersion)
pnode->PushInventory(inv);
}
void CConnman::RelayInvFiltered(CInv &inv, const CTransaction& relatedTx, const int minProtoVersion)
{
LOCK(cs_vNodes);
for (const auto& pnode : vNodes) {
if(pnode->nVersion < minProtoVersion)
continue;
{
LOCK(pnode->cs_filter);
if(pnode->pfilter && !pnode->pfilter->IsRelevantAndUpdate(relatedTx))
continue;
}
pnode->PushInventory(inv);
}
}
void CConnman::RelayInvFiltered(CInv &inv, const uint256& relatedTxHash, const int minProtoVersion)
{
LOCK(cs_vNodes);
for (const auto& pnode : vNodes) {
if(pnode->nVersion < minProtoVersion) continue;
{
LOCK(pnode->cs_filter);
if(pnode->pfilter && !pnode->pfilter->contains(relatedTxHash)) continue;
}
pnode->PushInventory(inv);
}
}
void CConnman::RemoveAskFor(const uint256& hash)
{
mapAlreadyAskedFor.erase(hash);
LOCK(cs_vNodes);
for (const auto& pnode : vNodes) {
pnode->RemoveAskFor(hash);
}
}
void CConnman::RecordBytesRecv(uint64_t bytes)
{
LOCK(cs_totalBytesRecv);
nTotalBytesRecv += bytes;
}
void CConnman::RecordBytesSent(uint64_t bytes)
{
LOCK(cs_totalBytesSent);
nTotalBytesSent += bytes;
uint64_t now = GetTime();
if (nMaxOutboundCycleStartTime + nMaxOutboundTimeframe < now)
{
// timeframe expired, reset cycle
nMaxOutboundCycleStartTime = now;
nMaxOutboundTotalBytesSentInCycle = 0;
}
// TODO, exclude whitebind peers
nMaxOutboundTotalBytesSentInCycle += bytes;
}
void CConnman::SetMaxOutboundTarget(uint64_t limit)
{
LOCK(cs_totalBytesSent);
nMaxOutboundLimit = limit;
}
uint64_t CConnman::GetMaxOutboundTarget()
{
LOCK(cs_totalBytesSent);
return nMaxOutboundLimit;
}
uint64_t CConnman::GetMaxOutboundTimeframe()
{
LOCK(cs_totalBytesSent);
return nMaxOutboundTimeframe;
}
uint64_t CConnman::GetMaxOutboundTimeLeftInCycle()
{
LOCK(cs_totalBytesSent);
if (nMaxOutboundLimit == 0)
return 0;
if (nMaxOutboundCycleStartTime == 0)
return nMaxOutboundTimeframe;
uint64_t cycleEndTime = nMaxOutboundCycleStartTime + nMaxOutboundTimeframe;
uint64_t now = GetTime();
return (cycleEndTime < now) ? 0 : cycleEndTime - GetTime();
}
void CConnman::SetMaxOutboundTimeframe(uint64_t timeframe)
{
LOCK(cs_totalBytesSent);
if (nMaxOutboundTimeframe != timeframe)
{
// reset measure-cycle in case of changing
// the timeframe
nMaxOutboundCycleStartTime = GetTime();
}
nMaxOutboundTimeframe = timeframe;
}
bool CConnman::OutboundTargetReached(bool historicalBlockServingLimit)
{
LOCK(cs_totalBytesSent);
if (nMaxOutboundLimit == 0)
return false;
if (historicalBlockServingLimit)
{
// keep a large enough buffer to at least relay each block once
uint64_t timeLeftInCycle = GetMaxOutboundTimeLeftInCycle();
uint64_t buffer = timeLeftInCycle / 600 * MaxBlockSize(fDIP0001ActiveAtTip);
if (buffer >= nMaxOutboundLimit || nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit - buffer)
return true;
}
else if (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit)
return true;
return false;
}
uint64_t CConnman::GetOutboundTargetBytesLeft()
{
LOCK(cs_totalBytesSent);
if (nMaxOutboundLimit == 0)
return 0;
return (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit) ? 0 : nMaxOutboundLimit - nMaxOutboundTotalBytesSentInCycle;
}
uint64_t CConnman::GetTotalBytesRecv()
{
LOCK(cs_totalBytesRecv);
return nTotalBytesRecv;
}
uint64_t CConnman::GetTotalBytesSent()
{
LOCK(cs_totalBytesSent);
return nTotalBytesSent;
}
ServiceFlags CConnman::GetLocalServices() const
{
return nLocalServices;
}
void CConnman::SetBestHeight(int height)
{
nBestHeight.store(height, std::memory_order_release);
}
int CConnman::GetBestHeight() const
{
return nBestHeight.load(std::memory_order_acquire);
}
unsigned int CConnman::GetReceiveFloodSize() const { return nReceiveFloodSize; }
CNode::CNode(NodeId idIn, ServiceFlags nLocalServicesIn, int nMyStartingHeightIn, SOCKET hSocketIn, const CAddress& addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const CAddress &addrBindIn, const std::string& addrNameIn, bool fInboundIn) :
nTimeConnected(GetSystemTimeInSeconds()),
nTimeFirstMessageReceived(0),
fFirstMessageIsMNAUTH(false),
addr(addrIn),
addrBind(addrBindIn),
fInbound(fInboundIn),
nKeyedNetGroup(nKeyedNetGroupIn),
addrKnown(5000, 0.001),
filterInventoryKnown(50000, 0.000001),
id(idIn),
nLocalHostNonce(nLocalHostNonceIn),
nLocalServices(nLocalServicesIn),
nMyStartingHeight(nMyStartingHeightIn),
nSendVersion(0)
{
nServices = NODE_NONE;
hSocket = hSocketIn;
nRecvVersion = INIT_PROTO_VERSION;
nLastSend = 0;
nLastRecv = 0;
nSendBytes = 0;
nRecvBytes = 0;
nTimeOffset = 0;
addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
nVersion = 0;
nNumWarningsSkipped = 0;
nLastWarningTime = 0;
strSubVer = "";
fWhitelisted = false;
fOneShot = false;
m_manual_connection = false;
fClient = false; // set by version message
fFeeler = false;
fSuccessfullyConnected = false;
fDisconnect = false;
nRefCount = 0;
nSendSize = 0;
nSendOffset = 0;
hashContinue = uint256();
nStartingHeight = -1;
filterInventoryKnown.reset();
fSendMempool = false;
fGetAddr = false;
nNextLocalAddrSend = 0;
nNextAddrSend = 0;
nNextInvSend = 0;
fRelayTxes = false;
fSentAddr = false;
pfilter = new CBloomFilter();
timeLastMempoolReq = 0;
nLastBlockTime = 0;
nLastTXTime = 0;
nPingNonceSent = 0;
nPingUsecStart = 0;
nPingUsecTime = 0;
fPingQueued = false;
fMasternode = false;
nMinPingUsecTime = std::numeric_limits<int64_t>::max();
fPauseRecv = false;
fPauseSend = false;
nProcessQueueSize = 0;
for (const std::string &msg : getAllNetMessageTypes())
mapRecvBytesPerMsgCmd[msg] = 0;
mapRecvBytesPerMsgCmd[NET_MESSAGE_COMMAND_OTHER] = 0;
if (fLogIPs) {
LogPrint(BCLog::NET, "Added connection to %s peer=%d\n", addrName, id);
} else {
LogPrint(BCLog::NET, "Added connection peer=%d\n", id);
}
}
CNode::~CNode()
{
CloseSocket(hSocket);
if (pfilter)
delete pfilter;
}
void CNode::AskFor(const CInv& inv, int64_t doubleRequestDelay)
{
if (queueAskFor.size() > MAPASKFOR_MAX_SZ || setAskFor.size() > SETASKFOR_MAX_SZ) {
int64_t nNow = GetTime();
if(nNow - nLastWarningTime > WARNING_INTERVAL) {
LogPrintf("CNode::AskFor -- WARNING: inventory message dropped: vecAskFor.size = %d, setAskFor.size = %d, MAPASKFOR_MAX_SZ = %d, SETASKFOR_MAX_SZ = %d, nSkipped = %d, peer=%d\n",
queueAskFor.size(), setAskFor.size(), MAPASKFOR_MAX_SZ, SETASKFOR_MAX_SZ, nNumWarningsSkipped, id);
nLastWarningTime = nNow;
nNumWarningsSkipped = 0;
}
else {
++nNumWarningsSkipped;
}
return;
}
// a peer may not have multiple non-responded queue positions for a single inv item
if (!setAskFor.emplace(inv.hash).second)
return;
// We're using queueAskFor as a priority queue,
// the key is the earliest time the request can be sent
int64_t nRequestTime;
auto it = mapAlreadyAskedFor.find(inv.hash);
if (it != mapAlreadyAskedFor.end())
nRequestTime = it->second;
else
nRequestTime = 0;
LogPrint(BCLog::NET, "askfor %s %d (%s) peer=%d\n", inv.ToString(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000), id);
// Make sure not to reuse time indexes to keep things in the same order
int64_t nNow = GetTimeMicros() - 1000000;
static int64_t nLastTime;
++nLastTime;
nNow = std::max(nNow, nLastTime);
nLastTime = nNow;
// Each retry is 2 minutes after the last
nRequestTime = std::max(nRequestTime + doubleRequestDelay, nNow);
if (it != mapAlreadyAskedFor.end())
mapAlreadyAskedFor.update(it, nRequestTime);
else
mapAlreadyAskedFor.insert(std::make_pair(inv.hash, nRequestTime));
queueAskFor.emplace(nRequestTime, inv);
setAskForInQueue.emplace(inv.hash);
}
void CNode::RemoveAskFor(const uint256& hash)
{
setAskFor.erase(hash);
// we don't really remove it from queueAskFor as it would be too expensive to rebuild the heap
// instead, we're ignoring the entry later as it won't be found in setAskForInQueue anymore
setAskForInQueue.erase(hash);
}
bool CConnman::NodeFullyConnected(const CNode* pnode)
{
return pnode && pnode->fSuccessfullyConnected && !pnode->fDisconnect;
}
void CConnman::PushMessage(CNode* pnode, CSerializedNetMsg&& msg, bool allowOptimisticSend)
{
size_t nMessageSize = msg.data.size();
size_t nTotalSize = nMessageSize + CMessageHeader::HEADER_SIZE;
LogPrint(BCLog::NET, "sending %s (%d bytes) peer=%d\n", SanitizeString(msg.command.c_str()), nMessageSize, pnode->GetId());
std::vector<unsigned char> serializedHeader;
serializedHeader.reserve(CMessageHeader::HEADER_SIZE);
uint256 hash = Hash(msg.data.data(), msg.data.data() + nMessageSize);
CMessageHeader hdr(Params().MessageStart(), msg.command.c_str(), nMessageSize);
memcpy(hdr.pchChecksum, hash.begin(), CMessageHeader::CHECKSUM_SIZE);
CVectorWriter{SER_NETWORK, INIT_PROTO_VERSION, serializedHeader, 0, hdr};
size_t nBytesSent = 0;
{
LOCK(pnode->cs_vSend);
bool hasPendingData = !pnode->vSendMsg.empty();
bool optimisticSend(allowOptimisticSend && pnode->vSendMsg.empty());
//log total amount of bytes per command
pnode->mapSendBytesPerMsgCmd[msg.command] += nTotalSize;
pnode->nSendSize += nTotalSize;
if (pnode->nSendSize > nSendBufferMaxSize)
pnode->fPauseSend = true;
pnode->vSendMsg.push_back(std::move(serializedHeader));
if (nMessageSize)
pnode->vSendMsg.push_back(std::move(msg.data));
// If write queue empty, attempt "optimistic write"
if (optimisticSend == true)
nBytesSent = SocketSendData(pnode);
// wake up select() call in case there was no pending data before (so it was not selecting this socket for sending)
else if (!hasPendingData && wakeupSelectNeeded)
WakeSelect();
}
if (nBytesSent)
RecordBytesSent(nBytesSent);
}
bool CConnman::ForNode(const CService& addr, std::function<bool(const CNode* pnode)> cond, std::function<bool(CNode* pnode)> func)
{
CNode* found = nullptr;
LOCK(cs_vNodes);
for (auto&& pnode : vNodes) {
if((CService)pnode->addr == addr) {
found = pnode;
break;
}
}
return found != nullptr && cond(found) && func(found);
}
bool CConnman::ForNode(NodeId id, std::function<bool(const CNode* pnode)> cond, std::function<bool(CNode* pnode)> func)
{
CNode* found = nullptr;
LOCK(cs_vNodes);
for (auto&& pnode : vNodes) {
if(pnode->GetId() == id) {
found = pnode;
break;
}
}
return found != nullptr && cond(found) && func(found);
}
bool CConnman::IsMasternodeOrDisconnectRequested(const CService& addr) {
return ForNode(addr, AllNodes, [](CNode* pnode){
return pnode->fMasternode || pnode->fDisconnect;
});
}
int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds) {
return nNow + (int64_t)(log1p(GetRand(1ULL << 48) * -0.0000000000000035527136788 /* -1/2^48 */) * average_interval_seconds * -1000000.0 + 0.5);
}
std::vector<CNode*> CConnman::CopyNodeVector(std::function<bool(const CNode* pnode)> cond)
{
std::vector<CNode*> vecNodesCopy;
LOCK(cs_vNodes);
for(size_t i = 0; i < vNodes.size(); ++i) {
CNode* pnode = vNodes[i];
if (!cond(pnode))
continue;
pnode->AddRef();
vecNodesCopy.push_back(pnode);
}
return vecNodesCopy;
}
std::vector<CNode*> CConnman::CopyNodeVector()
{
return CopyNodeVector(AllNodes);
}
void CConnman::ReleaseNodeVector(const std::vector<CNode*>& vecNodes)
{
LOCK(cs_vNodes);
for(size_t i = 0; i < vecNodes.size(); ++i) {
CNode* pnode = vecNodes[i];
pnode->Release();
}
}
CSipHasher CConnman::GetDeterministicRandomizer(uint64_t id) const
{
return CSipHasher(nSeed0, nSeed1).Write(id);
}
uint64_t CConnman::CalculateKeyedNetGroup(const CAddress& ad) const
{
std::vector<unsigned char> vchNetGroup(ad.GetGroup());
return GetDeterministicRandomizer(RANDOMIZER_ID_NETGROUP).Write(vchNetGroup.data(), vchNetGroup.size()).Finalize();
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/first_run/first_run.h"
#include "base/path_service.h"
#include "base/prefs/pref_service.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/first_run/first_run_internal.h"
#include "chrome/browser/importer/importer_host.h"
#include "chrome/browser/importer/importer_list.h"
#include "chrome/browser/importer/importer_progress_dialog.h"
#include "chrome/browser/importer/importer_progress_observer.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/pref_names.h"
#include "chrome/installer/util/google_update_settings.h"
#include "chrome/installer/util/master_preferences.h"
#include "chrome/installer/util/master_preferences_constants.h"
namespace {
// This class acts as an observer for the ImporterProgressObserver::ImportEnded
// callback. When the import process is started, certain errors may cause
// ImportEnded() to be called synchronously, but the typical case is that
// ImportEnded() is called asynchronously. Thus we have to handle both cases.
class ImportEndedObserver : public importer::ImporterProgressObserver {
public:
ImportEndedObserver() : ended_(false),
should_quit_message_loop_(false) {}
virtual ~ImportEndedObserver() {}
// importer::ImporterProgressObserver:
virtual void ImportStarted() OVERRIDE {}
virtual void ImportItemStarted(importer::ImportItem item) OVERRIDE {}
virtual void ImportItemEnded(importer::ImportItem item) OVERRIDE {}
virtual void ImportEnded() OVERRIDE {
ended_ = true;
if (should_quit_message_loop_)
MessageLoop::current()->Quit();
}
void set_should_quit_message_loop() {
should_quit_message_loop_ = true;
}
bool ended() {
return ended_;
}
private:
// Set if the import has ended.
bool ended_;
// Set by the client (via set_should_quit_message_loop) if, when the import
// ends, this class should quit the message loop.
bool should_quit_message_loop_;
};
} // namespace
namespace first_run {
namespace internal {
void DoPostImportPlatformSpecificTasks() {
#if !defined(OS_CHROMEOS)
// If stats reporting was turned on by the first run dialog then toggle
// the pref (on Windows, the download is tagged with enable/disable stats so
// this is POSIX-specific).
if (GoogleUpdateSettings::GetCollectStatsConsent()) {
g_browser_process->local_state()->SetBoolean(
prefs::kMetricsReportingEnabled, true);
}
#endif
}
bool GetFirstRunSentinelFilePath(base::FilePath* path) {
base::FilePath first_run_sentinel;
if (!PathService::Get(chrome::DIR_USER_DATA, &first_run_sentinel))
return false;
*path = first_run_sentinel.Append(chrome::kFirstRunSentinel);
return true;
}
bool ImportSettings(Profile* profile,
scoped_refptr<ImporterHost> importer_host,
scoped_refptr<ImporterList> importer_list,
int items_to_import) {
const importer::SourceProfile& source_profile =
importer_list->GetSourceProfileAt(0);
// Ensure that importers aren't requested to import items that they do not
// support. If there is no overlap, skip.
items_to_import &= source_profile.services_supported;
if (items_to_import == 0)
return true;
scoped_ptr<ImportEndedObserver> observer(new ImportEndedObserver);
importer_host->SetObserver(observer.get());
importer_host->StartImportSettings(source_profile,
profile,
items_to_import,
new ProfileWriter(profile),
true);
// If the import process has not errored out, block on it.
if (!observer->ended()) {
observer->set_should_quit_message_loop();
MessageLoop::current()->Run();
}
// Unfortunately there's no success/fail signal in ImporterHost.
return true;
}
void SetImportPreferencesAndLaunchImport(
MasterPrefs* out_prefs,
installer::MasterPreferences* install_prefs) {
std::string import_bookmarks_path;
install_prefs->GetString(
installer::master_preferences::kDistroImportBookmarksFromFilePref,
&import_bookmarks_path);
if (!import_bookmarks_path.empty()) {
// There are bookmarks to import from a file.
base::FilePath path = base::FilePath::FromWStringHack(UTF8ToWide(
import_bookmarks_path));
if (!ImportBookmarks(path)) {
LOG(WARNING) << "silent bookmark import failed";
}
}
}
bool ShowPostInstallEULAIfNeeded(installer::MasterPreferences* install_prefs) {
// The EULA is only handled on Windows.
return true;
}
} // namespace internal
} // namespace first_run
namespace first_run {
// TODO(port): Import switches need to be ported to both Mac and Linux. Not all
// import switches here are implemented for Linux. None are implemented for Mac
// (as this function will not be called on Mac).
int ImportNow(Profile* profile, const CommandLine& cmdline) {
return internal::ImportBookmarkFromFileIfNeeded(profile, cmdline);
}
} // namespace first_run
|
// This is an independent project of an individual developer. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
#include "stdafx.h"
#include "DynamicTileset.h"
#include "Log.h"
#include "Bitmap.h"
#include "Utility.h"
#include "Geometry.h"
#include "Encoding.h"
//-----------------------------------------------------------------------------
DynamicTileset::DynamicTileset(char32_t offset, OptionGroup& options) :
Tileset(offset)
{
if (!options.attributes.count(L"size"))
{
throw std::runtime_error("DynamicTileset: 'size' attribute is missing");
}
if (!try_parse(options.attributes[L"size"], m_tile_size))
{
throw std::runtime_error("DynamicTileset: failed to parse 'size' attribute");
}
}
DynamicTileset::DynamicTileset(char32_t offset, Size cell_size) :
Tileset(offset),
m_tile_size(cell_size)
{ }
Bitmap MakeBoxLines(Size size, std::vector<int> pattern)
{
Bitmap result(size, Color(0, 0, 0, 0));
if (pattern.size() < 25) return result;
int thickness = (int)std::floor(size.width / 7.0f);
if (thickness == 0) thickness = 1;
thickness = 1;
int cx = (int)std::floor(size.width / 2.0f - thickness / 2.0f); // 8/2.0f = 4 (fifth pixel), 3/2.0 = 1[.5] (second pixel)
int cy = (int)std::floor(size.height / 2.0f - thickness / 2.0f);
int cl = cx - thickness;
int ct = cy - thickness;
int cw = thickness * 3;
int ch = thickness * 3;
int cr = cl + cw;
int cb = ct + ch;
auto put_rect = [&](int left, int top, int width, int height)
{
for (int x = left; x<left + width; x++)
{
for (int y = top; y<top + height; y++)
{
result(x, y) = Color(255, 255, 255, 255);
}
}
};
for (int dy = -1; dy <= 1; dy++)
{
for (int dx = -1; dx <= 1; dx++)
{
int i = (dy + 2) * 5 + (dx + 2);
if (pattern[i]) put_rect(cx + dx*thickness, cy + dy*thickness, thickness, thickness);
}
}
// Left and right
for (int dy = -1; dy <= 1; dy++)
{
int i1 = (dy + 2) * 5;
if (pattern[i1])
{
for (int x = 0; x<cl; x++) put_rect(x, cy + dy*thickness, 1, thickness);
}
int i2 = (dy + 2) * 5 + 4;
if (pattern[i2])
{
for (int x = cr; x<size.width; x++) put_rect(x, cy + dy*thickness, 1, thickness);
}
}
// Top and bottom
for (int dx = -1; dx <= 1; dx++)
{
int i1 = dx + 2;
if (pattern[i1])
{
for (int y = 0; y<ct; y++) put_rect(cx + dx*thickness, y, thickness, 1);
}
int i2 = 4 * 5 + dx + 2;
if (pattern[i2])
{
for (int y = cb; y<size.height; y++) put_rect(cx + dx*thickness, y, thickness, 1);
}
}
return result;
}
Bitmap MakeDashLines(Size size, bool vertical, bool thick, int parts)
{
Bitmap result(size, Color(0, 0, 0, 0));
int thickness = (int)std::floor(size.width / 7.0f);
if (thickness == 0) thickness = 1;
thickness = 1;
int cx = (int)std::floor(size.width / 2.0f - thickness / 2.0f); // 8/2.0f = 4 (fifth pixel), 3/2.0 = 1[.5] (second pixel)
int cy = (int)std::floor(size.height / 2.0f - thickness / 2.0f);
int cl = cx - thickness;
int ct = cy - thickness;
int cw = thickness * 3;
int ch = thickness * 3;
int cr = cl + cw;
int cb = ct + ch;
auto put_rect = [&](int left, int top, int width, int height, int alpha)
{
for (int x = left; x<left + width; x++)
{
for (int y = top; y<top + height; y++)
{
result(x, y) = Color(alpha, 255, 255, 255);
}
}
};
int length = vertical ? size.height : size.width;
int n = (int)std::floor((length + 1) / 2.0f);
if (n > parts) n = parts;
float p0 = length / (float)n;
float p1 = p0 / 2.0f;
int gap = (int)std::floor(p1);
if (gap < 1) gap = 1;
int dash = (int)std::floor((length - gap*(n - 1)) / (float)n);
int total = dash*n + gap*(n - 1);
int as = 0, ae = 0;
if (total < length)
{
float extra = (length - total) / 2.0f;
as = (int)std::floor(extra);
ae = (int)std::ceil(extra);
}
if (vertical)
{
int t = thick ? 3 : 1;
int l = cx - (t - 1) / 2 * thickness;
int w = t*thickness;
put_rect(l, 0, w, as, 255);
for (int i = 0; i<n; i++)
{
put_rect(l, as + i*(dash + gap), w, dash, 255);
}
put_rect(l, length - ae, w, ae, 255);
}
else
{
int t = thick ? 3 : 1;
int p = cy - (t - 1) / 2 * thickness;
int h = t*thickness;
put_rect(0, p, as, h, 255);
for (int i = 0; i<n; i++)
{
put_rect(as + i*(dash + gap), p, dash, h, 255);
}
put_rect(length - ae, p, ae, h, 255);
}
return result;
}
Bitmap MakeVerticalSplit(Size size, float from, float to)
{
Bitmap result(size, Color(0, 0, 0, 0));
auto put_rect = [&](int left, int top, int width, int height, int alpha)
{
for (int x = left; x<left + width; x++)
{
for (int y = top; y<top + height; y++)
{
result(x, y) = Color(alpha, 255, 255, 255);
}
}
};
int tt = (int)std::floor(from*size.height);
int tb = (int)std::ceil(from*size.height);
int bt = (int)std::floor(to*size.height);
int bb = (int)std::ceil(to*size.height);
if (bt > tb) put_rect(0, tb, size.width, bt - tb, 255);
if (tt < tb) put_rect(0, tt, size.width, 1, (tb - from) * 255);
if (bt < bb) put_rect(0, bt, size.width, 1, (to - bt) * 255);
return result;
}
Bitmap MakeHorisontalSplit(Size size, float from, float to)
{
Bitmap result(size, Color(0, 0, 0, 0));
auto put_rect = [&](int left, int top, int width, int height, int alpha)
{
for (int x = left; x<left + width; x++)
{
for (int y = top; y<top + height; y++)
{
result(x, y) = Color(alpha, 255, 255, 255);
}
}
};
int ll = (int)std::floor(from*size.width);
int lr = (int)std::ceil(from*size.width);
int rl = (int)std::floor(to*size.width);
int rr = (int)std::ceil(to*size.width);
if (rl > lr) put_rect(lr, 0, rl - lr, size.height, 255);
if (ll < lr) put_rect(ll, 0, 1, size.height, (lr - from) * 255);
if (rl < rr) put_rect(rr - 1, 0, 1, size.height, (to - rl) * 255);
return result;
}
Bitmap MakeQuadrandTile(Size size, bool top_left, bool top_right, bool bottom_left, bool bottom_right)
{
Bitmap result(size, Color(0, 0, 0, 0));//255,255,255));
auto put_rect = [&](int left, int top, int width, int height, int alpha)
{
for (int x = left; x<left + width; x++)
{
for (int y = top; y<top + height; y++)
{
result(x, y) = Color(alpha, 255, 255, 255);
//result(x, y).a += alpha;
}
}
};
float cx = size.width / 2.0f;
float cy = size.height / 2.0f;
int l = (int)std::floor(cx);
int r = (int)std::ceil(cx);
int t = (int)std::floor(cy);
int b = (int)std::ceil(cy);
// Round up to top-left corner
r = l;
b = t;
if (top_left) put_rect(0, 0, l, t, 255);
if (top_right) put_rect(r, 0, size.width - r, t, 255);
if (bottom_left) put_rect(0, b, l, size.height - b, 255);
if (bottom_right) put_rect(r, b, size.width - r, size.height - b, 255);
return result;
}
Bitmap MakeNotACharacterTile(Size size)
{
Bitmap result(size, Color());
for (int x = 1; x<size.width - 1; x++)
{
result(x, 1) = Color(255, 255, 255, 255);
result(x, size.height - 2) = Color(255, 255, 255, 255);
}
for (int y = 1; y<size.height - 1; y++)
{
result(1, y) = Color(255, 255, 255, 255);
result(size.width - 2, y) = Color(255, 255, 255, 255);
}
return result;
}
Size DynamicTileset::GetBoundingBoxSize()
{
return m_tile_size;
}
bool DynamicTileset::Provides(char32_t code)
{
return IsDynamicTile(code);
}
const char box_lines[][25] =
{
{ 0,0,0,0,0, 0,0,0,0,0, 1,1,1,1,1, 0,0,0,0,0, 0,0,0,0,0 }, // 2500
{ 0,0,0,0,0, 1,1,1,1,1, 1,1,1,1,1, 1,1,1,1,1, 0,0,0,0,0 }, // 2501
{ 0,0,1,0,0, 0,0,1,0,0, 0,0,1,0,0, 0,0,1,0,0, 0,0,1,0,0 }, // 2502
{ 0,1,1,1,0, 0,1,1,1,0, 0,1,1,1,0, 0,1,1,1,0, 0,1,1,1,0 }, // 2503
{ 0 }, // 2504
{ 0 }, // 2505
{ 0 }, // 2506
{ 0 }, // 2507
{ 0 }, // 2508
{ 0 }, // 2509
{ 0 }, // 250A
{ 0 }, // 250B
{ 0,0,0,0,0, 0,0,0,0,0, 0,0,1,1,1, 0,0,1,0,0, 0,0,1,0,0 }, // 250C: Single right and bottom
{ 0,0,0,0,0, 0,0,1,1,1, 0,0,1,1,1, 0,0,1,1,1, 0,0,1,0,0 }, // 250D: Wide right and single bottom
{ 0,0,0,0,0, 0,0,0,0,0, 0,0,1,1,1, 0,1,1,1,0, 0,1,1,1,0 }, // 250E: Single right and wide bottom
{ 0,0,0,0,0, 0,1,1,1,1, 0,1,1,1,1, 0,1,1,1,1, 0,1,1,1,0 }, // 250F: Wide right and bottom
{ 0,0,0,0,0, 0,0,0,0,0, 1,1,1,0,0, 0,0,1,0,0, 0,0,1,0,0 }, // 2510: Single left and bottom
{ 0,0,0,0,0, 1,1,1,0,0, 1,1,1,0,0, 1,1,1,0,0, 0,0,1,0,0 }, // 2511: Wide left and single bottom
{ 0,0,0,0,0, 0,0,0,0,0, 1,1,1,1,0, 0,1,1,1,0, 0,1,1,1,0 }, // 2512: Single left and wide bottom
{ 0,0,0,0,0, 1,1,1,1,0, 1,1,1,1,0, 1,1,1,1,0, 0,1,1,1,0 }, // 2513: Wide left and bottom
{ 0,0,1,0,0, 0,0,1,0,0, 0,0,1,1,1, 0,0,0,0,0, 0,0,0,0,0 }, // 2514: Single top and right
{ 0,0,1,0,0, 0,0,1,1,1, 0,0,1,1,1, 0,0,1,1,1, 0,0,0,0,0 }, // 2515: Single top and wide right
{ 0,1,1,1,0, 0,1,1,1,0, 0,1,1,1,1, 0,0,0,0,0, 0,0,0,0,0 }, // 2516: Wide top and single right
{ 0,1,1,1,0, 0,1,1,1,1, 0,1,1,1,1, 0,1,1,1,1, 0,0,0,0,0 }, // 2517: Wide top and right
{ 0,0,1,0,0, 0,0,1,0,0, 1,1,1,0,0, 0,0,0,0,0, 0,0,0,0,0 }, // 2518: Single left and top
{ 0,0,1,0,0, 1,1,1,0,0, 1,1,1,0,0, 1,1,1,0,0, 0,0,0,0,0 }, // 2519: Wide left and single top
{ 0,1,1,1,0, 0,1,1,1,0, 1,1,1,1,0, 0,0,0,0,0, 0,0,0,0,0 }, // 251A: Single left and wide top
{ 0,1,1,1,0, 1,1,1,1,0, 1,1,1,1,0, 1,1,1,1,0, 0,0,0,0,0 }, // 251B: Wide left and top
{ 0,0,1,0,0, 0,0,1,0,0, 0,0,1,1,1, 0,0,1,0,0, 0,0,1,0,0 }, // 251C: Single top, right and bottom
{ 0,0,1,0,0, 0,0,1,1,1, 0,0,1,1,1, 0,0,1,1,1, 0,0,1,0,0 }, // 251D: Single top and bottom, wide right
{ 0,1,1,1,0, 0,1,1,1,0, 0,1,1,1,1, 0,0,1,0,0, 0,0,1,0,0 }, // 251E: Wide top, single right and bottom
{ 0,0,1,0,0, 0,0,1,0,0, 0,1,1,1,1, 0,1,1,1,0, 0,1,1,1,0 }, // 251F: Single top and right, wide bottom
{ 0,1,1,1,0, 0,1,1,1,0, 0,1,1,1,1, 0,1,1,1,0, 0,1,1,1,0 }, // 2520: Wide top and bottom, single right
{ 0,1,1,1,0, 0,1,1,1,1, 0,1,1,1,1, 0,1,1,1,1, 0,0,1,0,0 }, // 2521: Wide top and right, single bottom
{ 0,0,1,0,0, 0,1,1,1,1, 0,1,1,1,1, 0,1,1,1,1, 0,1,1,1,0 }, // 2522: Single top, wide right and bottom
{ 0,1,1,1,0, 0,1,1,1,1, 0,1,1,1,1, 0,1,1,1,1, 0,1,1,1,0 }, // 2523: Wide top, right and bottom
{ 0,0,1,0,0, 0,0,1,0,0, 1,1,1,0,0, 0,0,1,0,0, 0,0,1,0,0 }, // 2524: Single left, top and bottom
{ 0,0,1,0,0, 1,1,1,0,0, 1,1,1,0,0, 1,1,1,0,0, 0,0,1,0,0 }, // 2525: Wide left, single top and bottom
{ 0,1,1,1,0, 0,1,1,1,0, 1,1,1,1,0, 0,0,1,0,0, 0,0,1,0,0 }, // 2526: Single left and bottom, wide top
{ 0,0,1,0,0, 0,0,1,0,0, 1,1,1,1,0, 0,1,1,1,0, 0,1,1,1,0 }, // 2527: Single left and top, wide bottom
{ 0,1,1,1,0, 0,1,1,1,0, 1,1,1,1,0, 0,1,1,1,0, 0,1,1,1,0 }, // 2528: Single left, wide top and bottom
{ 0,1,1,1,0, 1,1,1,1,0, 1,1,1,1,0, 1,1,1,1,0, 0,0,1,0,0 }, // 2529: Wide left and top, single bottom
{ 0,0,1,0,0, 1,1,1,1,0, 1,1,1,1,0, 1,1,1,1,0, 0,1,1,1,0 }, // 252A: Wide left and bottom, single top
{ 0,1,1,1,0, 1,1,1,1,0, 1,1,1,1,0, 1,1,1,1,0, 0,1,1,1,0 }, // 252B: Wide left, top and bottom
{ 0,0,0,0,0, 0,0,0,0,0, 1,1,1,1,1, 0,0,1,0,0, 0,0,1,0,0 }, // 252C: Single left, right and bottom
{ 0,0,0,0,0, 1,1,1,0,0, 1,1,1,1,1, 1,1,1,0,0, 0,0,1,0,0 }, // 252D: Wide left, single right and bottom
{ 0,0,0,0,0, 0,0,1,1,1, 1,1,1,1,1, 0,0,1,1,1, 0,0,1,0,0 }, // 252E: Single left and bottom, wide right
{ 0,0,0,0,0, 1,1,1,1,1, 1,1,1,1,1, 1,1,1,1,1, 0,1,1,1,0 }, // 252F: Wide left and right, signle bottom
{ 0,0,0,0,0, 0,0,0,0,0, 1,1,1,1,1, 0,1,1,1,0, 0,1,1,1,0 }, // 2530: Single left and right, wide bottom
{ 0,0,0,0,0, 1,1,1,1,0, 1,1,1,1,1, 1,1,1,1,0, 0,1,1,1,0 }, // 2531: Wide left and bottom, single right
{ 0,0,0,0,0, 0,1,1,1,1, 1,1,1,1,1, 0,1,1,1,1, 0,1,1,1,0 }, // 2532: Single left, wide right and bottom
{ 0,0,0,0,0, 1,1,1,1,1, 1,1,1,1,1, 1,1,1,1,1, 0,1,1,1,0 }, // 2533: Wide left, right and bottom
{ 0,0,1,0,0, 0,0,1,0,0, 1,1,1,1,1, 0,0,0,0,0, 0,0,0,0,0 }, // 2534: Single left, top and right
{ 0,0,1,0,0, 1,1,1,0,0, 1,1,1,1,1, 1,1,1,0,0, 0,0,0,0,0 }, // 2535: Wide left, single top and right
{ 0,0,1,0,0, 0,0,1,1,1, 1,1,1,1,1, 0,0,1,1,1, 0,0,0,0,0 }, // 2536: Single left and top, wide right
{ 0,0,1,0,0, 1,1,1,1,1, 1,1,1,1,1, 1,1,1,1,1, 0,0,0,0,0 }, // 2537: Wide left and right, single top
{ 0,1,1,1,0, 0,1,1,1,0, 1,1,1,1,1, 0,0,0,0,0, 0,0,0,0,0 }, // 2538: Single left and right, wide top
{ 0,1,1,1,0, 1,1,1,1,0, 1,1,1,1,1, 1,1,1,1,0, 0,0,0,0,0 }, // 2539: Wide left and top, single right
{ 0,1,1,1,0, 0,1,1,1,0, 0,1,1,1,1, 0,1,1,1,0, 0,1,1,1,0 }, // 253A: Wide top and bottom, single right
{ 0,1,1,1,0, 1,1,1,1,0, 1,1,1,1,0, 1,1,1,1,0, 0,1,1,1,0 }, // 253B: Wide left, top and bottom
{ 0,0,1,0,0, 0,0,1,0,0, 1,1,1,1,1, 0,0,1,0,0, 0,0,1,0,0 }, // 253C: Single left, top, right and bottom
{ 0,0,1,0,0, 1,1,1,0,0, 1,1,1,1,1, 1,1,1,0,0, 0,0,1,0,0 }, // 253D: Wide left, single top, right and bottom
{ 0,0,1,0,0, 0,0,1,1,1, 1,1,1,1,1, 0,0,1,1,1, 0,0,1,0,0 }, // 253E: Single left, top and bottom, wide right
{ 0,0,1,0,0, 1,1,1,1,1, 1,1,1,1,1, 1,1,1,1,1, 0,0,1,0,0 }, // 253F: Wide left and right, single top and bottom
{ 0,1,1,1,0, 0,1,1,1,0, 1,1,1,1,1, 0,0,1,0,0, 0,0,1,0,0 }, // 2540: Single left, right and bottom, wide top
{ 0,0,1,0,0, 0,0,1,0,0, 1,1,1,1,1, 0,1,1,1,0, 0,1,1,1,0 }, // 2541: Single left, top and right, wide bottom
{ 0,1,1,1,0, 0,1,1,1,0, 1,1,1,1,1, 0,1,1,1,0, 0,1,1,1,0 }, // 2542: Single left and right, wide top and bottom
{ 0,1,1,1,0, 1,1,1,1,0, 1,1,1,1,1, 1,1,1,1,0, 0,0,1,0,0 }, // 2543: Wide left and top, single right and bottom
{ 0,1,1,1,0, 0,1,1,1,1, 1,1,1,1,1, 0,1,1,1,1, 0,0,1,0,0 }, // 2544: Single left and bottom, wide top and right
{ 0,0,1,0,0, 1,1,1,1,0, 1,1,1,1,1, 1,1,1,1,0, 0,1,1,1,0 }, // 2545: Wide left and bottom, single top and right
{ 0,0,1,0,0, 0,0,1,1,1, 1,1,1,1,1, 0,1,1,1,1, 0,1,1,1,0 }, // 2546: Single left and top, wide right and bottom
{ 0,1,1,1,0, 1,1,1,1,1, 1,1,1,1,1, 1,1,1,1,1, 0,0,1,0,0 }, // 2547: Wide left, top and right, single bottom
{ 0,0,1,0,0, 1,1,1,1,1, 1,1,1,1,1, 1,1,1,1,1, 0,1,1,1,0 }, // 2548: Wide left, right and bottom, single top
{ 0,1,1,1,0, 1,1,1,1,0, 1,1,1,1,1, 1,1,1,1,0, 0,1,1,1,0 }, // 2549: Wide left, top and bottom, single right
{ 0,1,1,1,0, 0,1,1,1,1, 1,1,1,1,1, 0,1,1,1,1, 0,1,1,1,0 }, // 254A: Single left, wide top, right and bottom
{ 0,1,1,1,0, 1,1,1,1,1, 1,1,1,1,1, 1,1,1,1,1, 0,1,1,1,0 }, // 254B: Wide left, top, right and bottom
{ 0 }, // 254C
{ 0 }, // 254D
{ 0 }, // 254E
{ 0 }, // 254F
{ 0,0,0,0,0, 1,1,1,1,1, 0,0,0,0,0, 1,1,1,1,1, 0,0,0,0,0 }, // 2550: Horisontal double
{ 0,1,0,1,0, 0,1,0,1,0, 0,1,0,1,0, 0,1,0,1,0, 0,1,0,1,0 }, // 2551: Vertical double
{ 0,0,0,0,0, 0,0,1,1,1, 0,0,1,0,0, 0,0,1,1,1, 0,0,1,0,0 }, // 2552: Double right, single bottom
{ 0,0,0,0,0, 0,0,0,0,0, 0,1,1,1,1, 0,1,0,1,0, 0,1,0,1,0 }, // 2553: Single right, double bottom
{ 0,0,0,0,0, 0,1,1,1,1, 0,1,0,0,0, 0,1,0,1,1, 0,1,0,1,0 }, // 2554: Double right and bottom
{ 0,0,0,0,0, 1,1,1,0,0, 0,0,1,0,0, 1,1,1,0,0, 0,0,1,0,0 }, // 2555: Double left and single bottom
{ 0,0,0,0,0, 0,0,0,0,0, 1,1,1,1,0, 0,1,0,1,0, 0,1,0,1,0 }, // 2556: Single left and double bottom
{ 0,0,0,0,0, 1,1,1,1,0, 0,0,0,1,0, 1,1,0,1,0, 0,1,0,1,0 }, // 2557: Double left and bottom
{ 0,0,1,0,0, 0,0,1,1,1, 0,0,1,0,0, 0,0,1,1,1, 0,0,0,0,0 }, // 2558: Single top and double right
{ 0,1,0,1,0, 0,1,0,1,0, 0,1,1,1,1, 0,0,0,0,0, 0,0,0,0,0 }, // 2559: Double top and single right
{ 0,1,0,1,0, 0,1,0,1,1, 0,1,0,0,0, 0,1,1,1,1, 0,0,0,0,0 }, // 255A: Double top and right
{ 0,0,1,0,0, 1,1,1,0,0, 0,0,1,0,0, 1,1,1,0,0, 0,0,0,0,0 }, // 255B: Double left, single up
{ 0,1,0,1,0, 0,1,0,1,0, 1,1,1,1,0, 0,0,0,0,0, 0,0,0,0,0 }, // 255C: Single left and double top
{ 0,1,0,1,0, 1,1,0,1,0, 0,0,0,1,0, 1,1,1,1,0, 0,0,0,0,0 }, // 255D: Double left and top
{ 0,0,1,0,0, 0,0,1,1,1, 0,0,1,0,0, 0,0,1,1,1, 0,0,1,0,0 }, // 255E: Single top and bottom, double right
{ 0,1,0,1,0, 0,1,0,1,0, 0,1,0,1,1, 0,1,0,1,0, 0,1,0,1,0 }, // 255F: Double top and bottom, single right
{ 0,1,0,1,0, 0,1,0,1,1, 0,1,0,0,0, 0,1,0,1,1, 0,1,0,1,0 }, // 2560: Double top, right and bottom
{ 0,0,1,0,0, 1,1,1,0,0, 0,0,1,0,0, 1,1,1,0,0, 0,0,1,0,0 }, // 2561: Double left, single top and bottom
{ 0,1,0,1,0, 0,1,0,1,0, 1,1,0,1,0, 0,1,0,1,0, 0,1,0,1,0 }, // 2562: Single left, double top and bottom
{ 0,1,0,1,0, 1,1,0,1,0, 0,0,0,1,0, 1,1,0,1,0, 0,1,0,1,0 }, // 2563: Double left, top bottom
{ 0,0,0,0,0, 1,1,1,1,1, 0,0,0,0,0, 1,1,1,1,1, 0,0,1,0,0 }, // 2564: Double left and right, single bottom
{ 0,0,0,0,0, 0,0,0,0,0, 1,1,1,1,1, 0,1,0,1,0, 0,1,0,1,0 }, // 2565: Single left and right, double bottom
{ 0,0,0,0,0, 1,1,1,1,1, 0,0,0,0,0, 1,1,0,1,1, 0,1,0,1,0 }, // 2566: Double left, right and bottom
{ 0,0,1,0,0, 1,1,1,1,1, 0,0,0,0,0, 1,1,1,1,1, 0,0,0,0,0 }, // 2567: Double left and right, single top
{ 0,1,0,1,0, 0,1,0,1,0, 1,1,1,1,1, 0,0,0,0,0, 0,0,0,0,0 }, // 2568: Single left and right, double top
{ 0,1,0,1,0, 1,1,0,1,1, 0,0,0,0,0, 1,1,1,1,1, 0,0,0,0,0 }, // 2569: Double left, top and right
{ 0,0,1,0,0, 1,1,1,1,1, 0,0,0,0,0, 1,1,1,1,1, 0,0,1,0,0 }, // 256A: Double left and right, single top and bottom
{ 0,1,0,1,0, 0,1,0,1,0, 1,1,0,1,1, 0,1,0,1,0, 0,1,0,1,0 }, // 256B: Single left and right, double top and bottom
{ 0,1,0,1,0, 1,1,0,1,1, 0,0,0,0,0, 1,1,0,1,1, 0,1,0,1,0 }, // 256C: Double horisontal and vertical
{ 0 }, // 256D
{ 0 }, // 256E
{ 0 }, // 256F
{ 0 }, // 2570
{ 0 }, // 2571
{ 0 }, // 2572
{ 0 }, // 2573
{ 0,0,0,0,0, 0,0,0,0,0, 1,1,1,0,0, 0,0,0,0,0, 0,0,0,0,0 }, // 2574: Single left
{ 0,0,1,0,0, 0,0,1,0,0, 0,0,1,0,0, 0,0,0,0,0, 0,0,0,0,0 }, // 2575: Single up
{ 0,0,0,0,0, 0,0,0,0,0, 0,0,1,1,1, 0,0,0,0,0, 0,0,0,0,0 }, // 2576: Single right
{ 0,0,0,0,0, 0,0,0,0,0, 0,0,1,0,0, 0,0,1,0,0, 0,0,1,0,0 }, // 2577: Single down
{ 0,0,0,0,0, 1,1,1,0,0, 1,1,1,0,0, 1,1,1,0,0, 0,0,0,0,0 }, // 2578: Wide left
{ 0,1,1,1,0, 0,1,1,1,0, 0,1,1,1,0, 0,0,0,0,0, 0,0,0,0,0 }, // 2579: Wide up
{ 0,0,0,0,0, 0,0,1,1,1, 0,0,1,1,1, 0,0,1,1,1, 0,0,0,0,0 }, // 257A: Wide right
{ 0,0,0,0,0, 0,0,0,0,0, 0,1,1,1,0, 0,1,1,1,0, 0,1,1,1,0 }, // 257B: Wide down
{ 0,0,0,0,0, 0,0,1,1,1, 1,1,1,1,1, 0,0,1,1,1, 0,0,0,0,0 }, // 257C: Single left and wide right
{ 0,0,1,0,0, 0,0,1,0,0, 0,1,1,1,0, 0,1,1,1,0, 0,1,1,1,0 }, // 257D: Single up and wide down
{ 0,0,0,0,0, 1,1,1,0,0, 1,1,1,1,1, 1,1,1,0,0, 0,0,0,0,0 }, // 257E: Wide left and single right
{ 0,1,1,1,0, 0,1,1,1,0, 0,1,1,1,0, 0,0,1,0,0, 0,0,1,0,0 }, // 257F: Wide up and single down
};
const float splits[][3] =
{
{ 0, 0.0f, 0.5f }, // 2580: ▀ UPPER HALF BLOCK
{ 0, 1.0f - 0.125f, 1.0f }, // 2581: ▁ LOWER ONE EIGHTH BLOCK
{ 0, 0.75f, 1.0f }, // 2582: ▂ LOWER ONE QUARTER BLOCK
{ 0, 1.0f - 3 * 0.125f, 1.0f }, // 2583: ▃ LOWER THREE EIGHTHS BLOCK
{ 0, 0.5f, 1.0f }, // 2584: ▄ LOWER HALF BLOCK
{ 0, 1.0f - 5 * 0.125f, 1.0f }, // 2585: ▅ LOWER FIVE EIGHTHS BLOCK
{ 0, 0.25f, 1.0f }, // 2586: ▆ LOWER THREE QUARTERS BLOCK
{ 0, 0.125f, 1.0f }, // 2587: ▇ LOWER SEVEN EIGHTHS BLOCK
{ 0, 0.0f, 1.0f }, // 2588: █ FULL BLOCK
{ 1, 0.0f, 7 * 0.125f }, // 2589: ▉ LEFT SEVEN EIGHTHS BLOCK
{ 1, 0.0f, 0.75f }, // 258A: ▊ LEFT THREE QUARTERS BLOCK
{ 1, 0.0f, 5 * 0.125f }, // 258B: ▋ LEFT FIVE EIGHTHS BLOCK
{ 1, 0.0f, 0.5f }, // 258C: ▌ LEFT HALF BLOCK
{ 1, 0.0f, 3 * 0.125f }, // 258D: ▍ LEFT THREE EIGHTHS BLOCK
{ 1, 0.0f, 0.25f }, // 258E: ▎ LEFT ONE QUARTER BLOCK
{ 1, 0.0f, 0.125f }, // 258F: ▏ LEFT ONE EIGHTH BLOCK
{ 1, 0.5f, 1.0f }, // 2590: ▐ RIGHT HALF BLOCK
{ 0 }, // 2591
{ 0 }, // 2592,
{ 0 }, // 2593
{ 0, 0.0f, 0.125f }, // 2594: ▔ UPPER ONE EIGHTH BLOCK
{ 1, 1.0f - 0.125f, 1.0f } // 2595:▕ RIGHT ONE EIGHTH BLOCK
};
const bool quadrants[][4] =
{
{ false, false, true, false }, // 2596: ▖ QUADRANT LOWER LEFT
{ false, false, false, true }, // 2597: ▗ QUADRANT LOWER RIGHT
{ true, false, false, false }, // 2598: ▘ QUADRANT UPPER LEFT
{ true, false, true, true }, // 2599: ▙ QUADRANT UPPER LEFT AND LOWER LEFT AND LOWER RIGHT
{ true, false, false, true }, // 259A: ▚ QUADRANT UPPER LEFT AND LOWER RIGHT
{ true, true, true, false }, // 259B: ▛ QUADRANT UPPER LEFT AND UPPER RIGHT AND LOWER LEFT
{ true, true, false, true }, // 259C: ▜ QUADRANT UPPER LEFT AND UPPER RIGHT AND LOWER RIGHT
{ false, true, false, false }, // 259D: ▝ QUADRANT UPPER RIGHT
{ false, true, true, false }, // 259E: ▞ QUADRANT UPPER RIGHT AND LOWER LEFT
{ false, true, true, true } // 259F: ▟ QUADRANT UPPER RIGHT AND LOWER LEFT AND LOWER RIGHT
};
bool IsDynamicTile(char32_t code)
{
code = (code & Tileset::kCharOffsetMask);
return (code >= 0x2500 && code <= 0x259F) || code == kUnicodeReplacementCharacter;
}
Bitmap GenerateDynamicTile(char32_t code, Size size)
{
code = (code & Tileset::kCharOffsetMask);
if ((code >= 0x2500 && code <= 0x2503) ||
(code >= 0x250C && code <= 0x254B) ||
(code >= 0x2550 && code <= 0x256C) ||
(code >= 0x2574 && code <= 0x257F))
{
int i = code - 0x2500;
std::vector<int> tmp;
for (int j = 0; j<25; j++)
tmp.push_back(box_lines[i][j]);
return MakeBoxLines(size, tmp);
}
else if ((code >= 0x2580 && code <= 0x2590) || (code >= 0x2594 && code <= 0x2595))
{
int i = code - 0x2580;
if (splits[i][0] > 0)
return MakeHorisontalSplit(size, splits[i][1], splits[i][2]);
else
return MakeVerticalSplit(size, splits[i][1], splits[i][2]);
}
else if (code >= 0x2596 && code <= 0x259F)
{
int i = code - 0x2596;
return MakeQuadrandTile(size, quadrants[i][0], quadrants[i][1], quadrants[i][2], quadrants[i][3]);
}
else
{
switch (code)
{
// U+2500..U+2503: Light and heavy solid lines
// U+2504..U+250B: Light and heavy dashed lines
case 0x2504:
return MakeDashLines(size, false, false, 3); // Single triple horisontal dash
break;
case 0x2505:
return MakeDashLines(size, false, true, 3); // Wide triple horisontal dash
break;
case 0x2506:
return MakeDashLines(size, true, false, 3); // Single triple vertical dash
break;
case 0x2507:
return MakeDashLines(size, true, true, 3); // Wide triple horisontal dash
break;
case 0x2508:
return MakeDashLines(size, false, false, 4); // Singlee quadruple horisontal dash
break;
case 0x2509:
return MakeDashLines(size, false, true, 4); // Wide quadruple horisontal dash
break;
case 0x250A:
return MakeDashLines(size, true, false, 4); // Single quadruple vertical dash
break;
case 0x250B:
return MakeDashLines(size, true, true, 4); // Wide quadruple vertical dash
break;
// U+250C..U+254B: Light and heavy line box components
// U+254C..U+254F: Light and heavy dashed lines
case 0x254C:
return MakeDashLines(size, false, false, 2); // BOX DRAWINGS LIGHT DOUBLE DASH HORIZONTAL
break;
case 0x254D:
return MakeDashLines(size, false, true, 2); // BOX DRAWINGS HEAVY DOUBLE DASH HORIZONTAL
break;
case 0x254E:
return MakeDashLines(size, true, false, 2); // BOX DRAWINGS LIGHT DOUBLE DASH VERTICAL
break;
case 0x254F:
return MakeDashLines(size, true, true, 2); // BOX DRAWINGS HEAVY DOUBLE DASH VERTICAL
break;
// U+2550..U+2551: Double lines
// U+2552..U+256C: Light and double line box components
// U+2574..U+257B: Light and heavy half lines
// U+257C..U+257F: Mixed light and heavy lines
// U+2580..U+2590: Block elements 1
// U+2591..U+2593: Shade characters
case 0x2591:
return Bitmap(size, Color(64, 255, 255, 255)); // ░ LIGHT SHADE
break;
case 0x2592:
return Bitmap(size, Color(128, 255, 255, 255)); // ▒ MEDIUM SHADE
break;
case 0x2593:
return Bitmap(size, Color(192, 255, 255, 255)); // ▓ DARK SHADE
break;
// U+2594..U+2595: Block elements 2
// U+2596..U+259F: Block elements 3 (quadrants)
default:
return MakeNotACharacterTile(size);
break;
}
}
return MakeNotACharacterTile(size);
}
std::shared_ptr<TileInfo> DynamicTileset::Get(char32_t code)
{
if (!Provides(code))
{
throw std::runtime_error("DynamicTileset::Prepare: request for a tile which is not provided by this tileset");
}
auto i = m_cache.find(code);
if (i != m_cache.end())
{
return i->second;
}
Size spacing{ 1, 1 };
char32_t font_offset = (code & Tileset::kFontOffsetMask);
auto j = g_tilesets.find(font_offset); \
if (j != g_tilesets.end())
{
spacing = j->second->GetSpacing();
}
Bitmap tile = GenerateDynamicTile(code, m_tile_size * spacing);
auto tile_ref = std::make_shared<TileInfo>();
tile_ref->tileset = this;
tile_ref->alignment = TileAlignment::TopLeft;
tile_ref->spacing = spacing;
tile_ref->bitmap = tile;
m_cache[code] = tile_ref;
return tile_ref;
}
|
// See the file "COPYING" in the main distribution directory for copyright.
//
// See ConnSize.h for more extensive comments.
#include "ConnSize.h"
#include "analyzer/protocol/tcp/TCP.h"
#include "IP.h"
#include "Reporter.h"
#include "events.bif.h"
using namespace analyzer::conn_size;
ConnSize_Analyzer::ConnSize_Analyzer(Connection* c)
: Analyzer("CONNSIZE", c),
orig_bytes(), resp_bytes(), orig_pkts(), resp_pkts(),
orig_bytes_thresh(), resp_bytes_thresh(), orig_pkts_thresh(), resp_pkts_thresh(), duration_thresh()
{
start_time = c->StartTime();
}
ConnSize_Analyzer::~ConnSize_Analyzer()
{
}
void ConnSize_Analyzer::Init()
{
Analyzer::Init();
orig_bytes = 0;
orig_pkts = 0;
resp_bytes = 0;
resp_pkts = 0;
orig_bytes_thresh = 0;
orig_pkts_thresh = 0;
resp_bytes_thresh = 0;
resp_pkts_thresh = 0;
}
void ConnSize_Analyzer::Done()
{
Analyzer::Done();
}
void ConnSize_Analyzer::ThresholdEvent(EventHandlerPtr f, uint64_t threshold, bool is_orig)
{
if ( ! f )
return;
EnqueueConnEvent(f,
ConnVal(),
zeek::val_mgr->Count(threshold),
zeek::val_mgr->Bool(is_orig)
);
}
void ConnSize_Analyzer::CheckThresholds(bool is_orig)
{
if ( is_orig )
{
if ( orig_bytes_thresh && orig_bytes >= orig_bytes_thresh )
{
ThresholdEvent(conn_bytes_threshold_crossed, orig_bytes_thresh, is_orig);
orig_bytes_thresh = 0;
}
if ( orig_pkts_thresh && orig_pkts >= orig_pkts_thresh )
{
ThresholdEvent(conn_packets_threshold_crossed, orig_pkts_thresh, is_orig);
orig_pkts_thresh = 0;
}
}
else
{
if ( resp_bytes_thresh && resp_bytes >= resp_bytes_thresh )
{
ThresholdEvent(conn_bytes_threshold_crossed, resp_bytes_thresh, is_orig);
resp_bytes_thresh = 0;
}
if ( resp_pkts_thresh && resp_pkts >= resp_pkts_thresh )
{
ThresholdEvent(conn_packets_threshold_crossed, resp_pkts_thresh, is_orig);
resp_pkts_thresh = 0;
}
}
if ( duration_thresh != 0 )
{
if ( ( network_time - start_time ) > duration_thresh && conn_duration_threshold_crossed )
{
EnqueueConnEvent(conn_duration_threshold_crossed,
ConnVal(),
zeek::make_intrusive<zeek::IntervalVal>(duration_thresh),
zeek::val_mgr->Bool(is_orig)
);
duration_thresh = 0;
}
}
}
void ConnSize_Analyzer::DeliverPacket(int len, const u_char* data, bool is_orig, uint64_t seq, const IP_Hdr* ip, int caplen)
{
Analyzer::DeliverPacket(len, data, is_orig, seq, ip, caplen);
if ( is_orig )
{
orig_bytes += ip->TotalLen();
orig_pkts ++;
}
else
{
resp_bytes += ip->TotalLen();
resp_pkts ++;
}
CheckThresholds(is_orig);
}
void ConnSize_Analyzer::SetByteAndPacketThreshold(uint64_t threshold, bool bytes, bool orig)
{
if ( bytes )
{
if ( orig )
orig_bytes_thresh = threshold;
else
resp_bytes_thresh = threshold;
}
else
{
if ( orig )
orig_pkts_thresh = threshold;
else
resp_pkts_thresh = threshold;
}
// Check if threshold is already crossed.
CheckThresholds(orig);
}
uint64_t ConnSize_Analyzer::GetByteAndPacketThreshold(bool bytes, bool orig)
{
if ( bytes )
{
if ( orig )
return orig_bytes_thresh;
else
return resp_bytes_thresh;
}
else
{
if ( orig )
return orig_pkts_thresh;
else
return resp_pkts_thresh;
}
}
void ConnSize_Analyzer::SetDurationThreshold(double duration)
{
duration_thresh = duration;
// for duration thresholds, it does not matter which direction we check.
CheckThresholds(true);
}
void ConnSize_Analyzer::UpdateConnVal(zeek::RecordVal *conn_val)
{
// RecordType *connection_type is decleared in NetVar.h
zeek::RecordVal* orig_endp = conn_val->GetField("orig")->AsRecordVal();
zeek::RecordVal* resp_endp = conn_val->GetField("resp")->AsRecordVal();
// endpoint is the RecordType from NetVar.h
int pktidx = zeek::id::endpoint->FieldOffset("num_pkts");
int bytesidx = zeek::id::endpoint->FieldOffset("num_bytes_ip");
if ( pktidx < 0 )
reporter->InternalError("'endpoint' record missing 'num_pkts' field");
if ( bytesidx < 0 )
reporter->InternalError("'endpoint' record missing 'num_bytes_ip' field");
orig_endp->Assign(pktidx, zeek::val_mgr->Count(orig_pkts));
orig_endp->Assign(bytesidx, zeek::val_mgr->Count(orig_bytes));
resp_endp->Assign(pktidx, zeek::val_mgr->Count(resp_pkts));
resp_endp->Assign(bytesidx, zeek::val_mgr->Count(resp_bytes));
Analyzer::UpdateConnVal(conn_val);
}
void ConnSize_Analyzer::FlipRoles()
{
Analyzer::FlipRoles();
uint64_t tmp;
tmp = orig_bytes;
orig_bytes = resp_bytes;
resp_bytes = tmp;
tmp = orig_pkts;
orig_pkts = resp_pkts;
resp_pkts = tmp;
}
|
#include "mtf/SSM/ProjectiveBase.h"
#include <boost/random/random_device.hpp>
#include <boost/random/seed_seq.hpp>
#include "mtf/Utilities/warpUtils.h"
#include "mtf/Utilities/miscUtils.h"
_MTF_BEGIN_NAMESPACE
ProjectiveBase::ProjectiveBase(const SSMParams *params) :
StateSpaceModel(params){
init_pts_hm.resize(Eigen::NoChange, n_pts);
curr_pts_hm.resize(Eigen::NoChange, n_pts);
norm_pts.resize(Eigen::NoChange, n_pts);
norm_pts_hm.resize(Eigen::NoChange, n_pts);
utils::getNormUnitSquarePts(norm_pts, norm_corners, resx, resy);
utils::homogenize(norm_pts, norm_pts_hm);
utils::homogenize(norm_corners, norm_corners_hm);
}
void ProjectiveBase::getPtsFromCorners(ProjWarpT &warp, PtsT &pts, HomPtsT &pts_hm,
const CornersT &corners){
warp = utils::computeHomographyDLT(norm_corners, corners);
pts_hm = warp * norm_pts_hm;
utils::dehomogenize(pts_hm, pts);
}
void ProjectiveBase::setCorners(const CornersT& corners){
curr_corners = corners;
getPtsFromCorners(curr_warp, curr_pts, curr_pts_hm, curr_corners);
utils::homogenize(curr_corners, curr_corners_hm);
init_corners = curr_corners;
init_pts = curr_pts;
init_corners_hm = curr_corners_hm;
utils::homogenize(init_pts, init_pts_hm);
curr_warp = Matrix3d::Identity();
curr_state.fill(0);
}
void ProjectiveBase::setState(const VectorXd &ssm_state){
validate_ssm_state(ssm_state);
curr_state = ssm_state;
getWarpFromState(curr_warp, curr_state);
curr_pts_hm.noalias() = curr_warp * init_pts_hm;
curr_corners_hm.noalias() = curr_warp * init_corners_hm;
utils::dehomogenize(curr_pts_hm, curr_pts);
utils::dehomogenize(curr_corners_hm, curr_corners);
}
void ProjectiveBase::additiveUpdate(const VectorXd& state_update){
validate_ssm_state(state_update);
curr_state += state_update;
setState(curr_state);
}
void ProjectiveBase::invertState(VectorXd& inv_state, const VectorXd& state){
getWarpFromState(warp_mat, state);
inv_warp_mat = warp_mat.inverse();
inv_warp_mat /= inv_warp_mat(2, 2);
getStateFromWarp(inv_state, inv_warp_mat);
}
void ProjectiveBase::updateGradPts(double grad_eps){
Vector3d diff_vec_x_warped = curr_warp.col(0) * grad_eps;
Vector3d diff_vec_y_warped = curr_warp.col(1) * grad_eps;
Vector3d pt_inc_warped, pt_dec_warped;
for(unsigned int pt_id = 0; pt_id < n_pts; pt_id++){
pt_inc_warped = curr_pts_hm.col(pt_id) + diff_vec_x_warped;
grad_pts(0, pt_id) = pt_inc_warped(0) / pt_inc_warped(2);
grad_pts(1, pt_id) = pt_inc_warped(1) / pt_inc_warped(2);
pt_dec_warped = curr_pts_hm.col(pt_id) - diff_vec_x_warped;
grad_pts(2, pt_id) = pt_dec_warped(0) / pt_dec_warped(2);
grad_pts(3, pt_id) = pt_dec_warped(1) / pt_dec_warped(2);
pt_inc_warped = curr_pts_hm.col(pt_id) + diff_vec_y_warped;
grad_pts(4, pt_id) = pt_inc_warped(0) / pt_inc_warped(2);
grad_pts(5, pt_id) = pt_inc_warped(1) / pt_inc_warped(2);
pt_dec_warped = curr_pts_hm.col(pt_id) - diff_vec_y_warped;
grad_pts(6, pt_id) = pt_dec_warped(0) / pt_dec_warped(2);
grad_pts(7, pt_id) = pt_dec_warped(1) / pt_dec_warped(2);
}
}
void ProjectiveBase::updateHessPts(double hess_eps){
double hess_eps2 = 2 * hess_eps;
Vector3d diff_vec_xx_warped = curr_warp.col(0) * hess_eps2;
Vector3d diff_vec_yy_warped = curr_warp.col(1) * hess_eps2;
Vector3d diff_vec_xy_warped = (curr_warp.col(0) + curr_warp.col(1)) * hess_eps;
Vector3d diff_vec_yx_warped = (curr_warp.col(0) - curr_warp.col(1)) * hess_eps;
Vector3d pt_inc_warped, pt_dec_warped;
for(unsigned int pt_id = 0; pt_id < n_pts; pt_id++){
pt_inc_warped = curr_pts_hm.col(pt_id) + diff_vec_xx_warped;
hess_pts(0, pt_id) = pt_inc_warped(0) / pt_inc_warped(2);
hess_pts(1, pt_id) = pt_inc_warped(1) / pt_inc_warped(2);
pt_dec_warped = curr_pts_hm.col(pt_id) - diff_vec_xx_warped;
hess_pts(2, pt_id) = pt_dec_warped(0) / pt_dec_warped(2);
hess_pts(3, pt_id) = pt_dec_warped(1) / pt_dec_warped(2);
pt_inc_warped = curr_pts_hm.col(pt_id) + diff_vec_yy_warped;
hess_pts(4, pt_id) = pt_inc_warped(0) / pt_inc_warped(2);
hess_pts(5, pt_id) = pt_inc_warped(1) / pt_inc_warped(2);
pt_dec_warped = curr_pts_hm.col(pt_id) - diff_vec_yy_warped;
hess_pts(6, pt_id) = pt_dec_warped(0) / pt_dec_warped(2);
hess_pts(7, pt_id) = pt_dec_warped(1) / pt_dec_warped(2);
pt_inc_warped = curr_pts_hm.col(pt_id) + diff_vec_xy_warped;
hess_pts(8, pt_id) = pt_inc_warped(0) / pt_inc_warped(2);
hess_pts(9, pt_id) = pt_inc_warped(1) / pt_inc_warped(2);
pt_dec_warped = curr_pts_hm.col(pt_id) - diff_vec_xy_warped;
hess_pts(10, pt_id) = pt_dec_warped(0) / pt_dec_warped(2);
hess_pts(11, pt_id) = pt_dec_warped(1) / pt_dec_warped(2);
pt_inc_warped = curr_pts_hm.col(pt_id) + diff_vec_yx_warped;
hess_pts(12, pt_id) = pt_inc_warped(0) / pt_inc_warped(2);
hess_pts(13, pt_id) = pt_inc_warped(1) / pt_inc_warped(2);
pt_dec_warped = curr_pts_hm.col(pt_id) - diff_vec_yx_warped;
hess_pts(14, pt_id) = pt_dec_warped(0) / pt_dec_warped(2);
hess_pts(15, pt_id) = pt_dec_warped(1) / pt_dec_warped(2);
}
}
void ProjectiveBase::applyWarpToCorners(Matrix24d &warped_corners, const Matrix24d &orig_corners,
const VectorXd &ssm_state){
getWarpFromState(warp_mat, ssm_state);
for(unsigned int corner_id = 0; corner_id < 4; corner_id++){
applyWarpToPt(warped_corners(0, corner_id), warped_corners(1, corner_id),
orig_corners(0, corner_id), orig_corners(1, corner_id), warp_mat);
}
}
void ProjectiveBase::applyWarpToPts(Matrix2Xd &warped_pts, const Matrix2Xd &orig_pts,
const VectorXd &ssm_state){
getWarpFromState(warp_mat, ssm_state);
int n_pts = orig_pts.cols();
for(int pt_id = 0; pt_id < n_pts; ++pt_id){
applyWarpToPt(warped_pts(0, pt_id), warped_pts(1, pt_id),
orig_pts(0, pt_id), orig_pts(1, pt_id), warp_mat);
}
}
void ProjectiveBase::applyWarpToPt(double &warped_x, double &warped_y, double x, double y,
const ProjWarpT &warp){
double discr = warp(2, 0)*x + warp(2, 1)*y + warp(2, 2);
warped_x = (warp(0, 0)*x + warp(0, 1)*y + warp(0, 2)) / discr;
warped_y = (warp(1, 0)*x + warp(1, 1)*y + warp(1, 2)) / discr;
}
// -------------------------------------------------------------------------- //
// --------------------------- Stochastic Sampler --------------------------- //
// -------------------------------------------------------------------------- //
void ProjectiveBase::initializeSampler(const VectorXd &_state_sigma,
const VectorXd &_state_mean){
VectorXd state_sigma(state_size), state_mean(state_size);
if(_state_sigma.size() == 1){
state_sigma.fill(_state_sigma[0]);
} else if(_state_sigma.size() != state_size){
throw utils::InvalidArgument(
cv::format("ProjectiveBase::initializeSampler :: SSM sigma has invalid size %d\n",
_state_sigma.size()));
} else{
state_sigma = _state_sigma;
}
if(_state_mean.size() == 1){
state_mean.fill(_state_mean[0]);
} else if(_state_mean.size() != state_size){
throw utils::InvalidArgument(
cv::format("ProjectiveBase::initializeSampler :: SSM mean has invalid size %d\n",
_state_mean.size()));
} else{
state_mean = _state_mean;
}
printf("Initializing %s sampler with sigma: ", name.c_str());
utils::printMatrix(state_sigma.transpose(), nullptr, "%e");
state_perturbation.resize(state_size);
rand_gen.resize(state_size);
rand_dist.resize(state_size);
boost::random_device r;
for(unsigned int state_id = 0; state_id < state_size; ++state_id) {
boost::random::seed_seq seed{ r(), r(), r(), r(), r(), r(), r(), r() };
rand_gen[state_id] = SampleGenT(seed);
rand_dist[state_id] = SampleDistT(state_mean[state_id], state_sigma[state_id]);
}
is_initialized.sampler = true;
}
void ProjectiveBase::estimateStateSigma(VectorXd &state_sigma, double pix_sigma){
MatrixXd ssm_grad_norm(n_pts, state_size);
Matrix2Xd pix_ssm_grad;
pix_ssm_grad.resize(Eigen::NoChange, state_size);
for(unsigned int pt_id = 0; pt_id < n_pts; pt_id++){
getCurrPixGrad(pix_ssm_grad, pt_id);
ssm_grad_norm.row(pt_id) = pix_ssm_grad.colwise().norm();
}
VectorXd ssm_grad_norm_mean = ssm_grad_norm.colwise().mean();
for(unsigned int state_id = 0; state_id < state_size; ++state_id){
state_sigma(state_id) = pix_sigma / ssm_grad_norm_mean(state_id);
}
}
void ProjectiveBase::setSampler(const VectorXd &state_sigma,
const VectorXd &state_mean){
assert(state_sigma.size() == state_size);
assert(state_mean.size() == state_size);
for(unsigned int state_id = 0; state_id < state_size; ++state_id){
rand_dist[state_id].param(DistParamT(state_mean[state_id], state_sigma[state_id]));
}
}
void ProjectiveBase::setSamplerMean(const VectorXd &state_mean){
assert(state_mean.size() == state_size);
for(unsigned int state_id = 0; state_id < state_size; ++state_id){
double state_sigma = rand_dist[state_id].sigma();
rand_dist[state_id].param(DistParamT(state_mean[state_id], state_sigma));
}
}
void ProjectiveBase::setSamplerSigma(const VectorXd &state_sigma){
assert(state_sigma.size() == state_size);
for(unsigned int state_id = 0; state_id < state_size; ++state_id){
double state_mean = rand_dist[state_id].mean();
rand_dist[state_id].param(DistParamT(state_mean, state_sigma[state_id]));
}
}
VectorXd ProjectiveBase::getSamplerSigma(){
VectorXd sampler_sigma(state_size);
for(unsigned int state_id = 0; state_id < state_size; ++state_id){
sampler_sigma(state_id) = rand_dist[state_id].sigma();
}
return sampler_sigma;
}
VectorXd ProjectiveBase::getSamplerMean(){
VectorXd sampler_mean(state_size);
for(unsigned int state_id = 0; state_id < state_size; ++state_id){
sampler_mean(state_id) = rand_dist[state_id].mean();
}
return sampler_mean;
}
// use Random Walk model to generate perturbed sample
void ProjectiveBase::additiveRandomWalk(VectorXd &perturbed_state,
const VectorXd &base_state){
generatePerturbation(state_perturbation);
perturbed_state = base_state + state_perturbation;
}
void ProjectiveBase::compositionalRandomWalk(VectorXd &perturbed_state,
const VectorXd &base_state){
generatePerturbation(state_perturbation);
ProjWarpT base_warp, warp_perturbation;
getWarpFromState(base_warp, base_state);
getWarpFromState(warp_perturbation, state_perturbation);
ProjWarpT perturbed_warp = base_warp * warp_perturbation;
getStateFromWarp(perturbed_state, perturbed_warp);
}
// use first order Auto Regressive model to generate perturbed sample
void ProjectiveBase::additiveAutoRegression1(VectorXd &perturbed_state, VectorXd &perturbed_ar,
const VectorXd &base_state, const VectorXd &base_ar, double a){
generatePerturbation(state_perturbation);
perturbed_state = base_state + base_ar + state_perturbation;
perturbed_ar = a*(perturbed_state - base_state);
}
void ProjectiveBase::compositionalAutoRegression1(VectorXd &perturbed_state, VectorXd &perturbed_ar,
const VectorXd &base_state, const VectorXd &base_ar, double a){
generatePerturbation(state_perturbation);
ProjWarpT base_warp, warp_perturbation, warp_ar;
getWarpFromState(base_warp, base_state);
getWarpFromState(warp_perturbation, state_perturbation);
getWarpFromState(warp_ar, base_ar);
ProjWarpT perturbed_warp = base_warp * warp_ar * warp_perturbation;
ProjWarpT perturbed_ar_warp = base_warp.inverse() * perturbed_warp;
//utils::printMatrix(base_warp, "base_warp");
//utils::printMatrix(warp_ar, "warp_ar");
//utils::printMatrix(warp_perturbation, "warp_perturbation");
//utils::printMatrix(perturbed_warp, "perturbed_warp");
getStateFromWarp(perturbed_state, perturbed_warp);
getStateFromWarp(perturbed_ar, perturbed_ar_warp);
perturbed_ar *= a;
}
void ProjectiveBase::generatePerturbation(VectorXd &perturbation){
assert(perturbation.size() == state_size);
for(unsigned int state_id = 0; state_id < state_size; ++state_id){
perturbation(state_id) = rand_dist[state_id](rand_gen[state_id]);
}
}
void ProjectiveBase::generatePerturbedPts(VectorXd &perturbed_pts){
VectorXd state_update(state_size);
generatePerturbation(state_update);
getPerturbedPts(perturbed_pts, state_update);
}
void ProjectiveBase::getPerturbedPts(VectorXd &perturbed_pts,
const VectorXd &state_perturbation){
Matrix3d warp_perturbation;
getWarpFromState(warp_perturbation, state_perturbation);
utils::dehomogenize(curr_warp * warp_perturbation * init_pts_hm, perturbed_pts);
}
void ProjectiveBase::estimateMeanOfSamples(VectorXd &sample_mean,
const std::vector<VectorXd> &samples, int n_samples){
sample_mean.setZero();
for(int sample_id = 0; sample_id < n_samples; sample_id++){
sample_mean += (samples[sample_id] - sample_mean) / (sample_id + 1);
}
}
void ProjectiveBase::getIdentityWarp(VectorXd &identity_warp){
identity_warp.setZero();
}
void ProjectiveBase::composeWarps(VectorXd &composed_state, const VectorXd &state_1,
const VectorXd &state_2){
ProjWarpT warp_1, warp_2;
getWarpFromState(warp_1, state_1);
getWarpFromState(warp_2, state_2);
ProjWarpT composed_warp = warp_2*warp_1;
getStateFromWarp(composed_state, composed_warp);
}
_MTF_END_NAMESPACE
|
#include "Enem.h"
Enem::Enem()
{
mySprite = LoadTexture("barb.png");
position = { 0, 0 };
// destination = { 0, 0 };
isActive = true;
speed.x = GetRandomValue(15, 70);
speed.y = GetRandomValue(15, 70);
int xNeg = GetRandomValue(0, 1);
int yNeg = GetRandomValue(0, 1);
if(xNeg == 0) {
speed.x *= -1;
}
if (yNeg == 0) {
speed.y *= -1;
}
// more random
int oneWay = GetRandomValue(0, 30);
if (oneWay == 0) {
speed.x = 0;
}
if (oneWay == 1) {
speed.y = 0;
}
}
Enem::~Enem()
{
// UnloadTexture(mySprite);
}
void Enem::update()
{
// move
position.x += speed.x * GetFrameTime();
position.y -= speed.y * GetFrameTime();
}
void Enem::draw()
{
// if alive
//if (isActive) {
// // offset for size
// DrawTexture(mySprite, position.x - 4, position.y - 8, WHITE);
//}
DrawTexture(mySprite, position.x - 5, position.y - 10, WHITE);
}
|
//
// $Id: PercolatorXmlReader.cpp 6870 2014-11-03 19:12:11Z chambm $
//
//
// Original author: Barbara Frewen <frewen@u.washington.edu>
//
// Copyright 2012 University of Washington - Seattle, WA 98195
//
// 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.
//
/**
* Class definition for PercolatorXmlReader, a class for parsing the
* xml output from percolator, versions 1.15 and later.
*/
#include <cctype>
#include "PercolatorXmlReader.h"
#include "BlibMaker.h"
#include <boost/filesystem.hpp>
#include "AminoAcidMasses.h"
using namespace std;
namespace fs = boost::filesystem;
namespace BiblioSpec {
PercolatorXmlReader::PercolatorXmlReader(BlibBuilder& maker,
const char* file,
const ProgressIndicator* progress)
: BuildParser(maker, file, progress),
currentState_(START_STATE),
qvalueThreshold_(getScoreThreshold(SQT))
{
this->setFileName(file); // this is done for the saxhandler
qvalueBuffer_ = new char[256];
qvalueBuffer_[0] = '\0';
qvalueBufferPosition_ = qvalueBuffer_;
AminoAcidMasses::initializeMass(masses_, 0);
}
PercolatorXmlReader::~PercolatorXmlReader()
{
delete [] qvalueBuffer_;
}
/**
* \brief Implementation of BuildParser virtual function. Reads the
* Percolator xml file and populates the vector of PSMs with the
* information.
*/
bool PercolatorXmlReader::parseFile() {
parse(); // the saxhandler will read the file and store the psms
vector<std::string> extensions;
extensions.push_back(".ms2");
extensions.push_back(".cms2");
extensions.push_back(".bms2");
extensions.push_back(".pms2");
vector<std::string> dirs;
dirs.push_back("../sequest/");
dirs.push_back("../");
dirs.push_back("../../");
BlibBuilder tmpBuilder;
if( fileMap_.size() > 1 )
initSpecFileProgress((int)fileMap_.size());
// for each source file, read the .sqt for mods info, add spec to lib
map<string, vector<PSM*> >::iterator mapAccess = fileMap_.begin();
for(; mapAccess != fileMap_.end(); ++mapAccess){
// filenameInput is the input source file, without the extension, may or may not be a full directory path
string filenameInput = mapAccess->first;
fs::path spectrumFullPath(filenameInput);
fs::path spectrumParentPath = spectrumFullPath.parent_path();
fs::path filename = spectrumFullPath.filename();
if (spectrumFullPath.has_parent_path())
{
// if the filename contains a parent path (references other directories), extract the basename
// and add the path to the directories to search
dirs.push_back(spectrumParentPath.string());
}
// set the filename for the file containing the spectra
setSpecFileName(filename.string(), extensions, dirs);
if (spectrumFullPath.has_parent_path())
{
// if the file had a parent path, remove that parent path from the dirs
dirs.pop_back();
}
vector<PSM*>& psms = mapAccess->second;
// create an SQTReader and get mods
// this is the preceeding path for the spectrum file
string fullFilename = getPath(getSpecFileName());
// replaceExtension(filename, "sqt");
// add on the name of the spectrum file as an sqt
fullFilename += filename.string();
fullFilename += ".sqt";
ifstream file(fullFilename.c_str());
// if the file from the path of the spectrum file can't be read
// try opening the file in the path of the perc xml file
if(!file.good()) {
fullFilename = getPath(getFileName());
fullFilename += filename.string();
fullFilename += ".sqt";
file.open(fullFilename.c_str());
}
// if the file still can't be read, try looking in the current directory
if(!file.good()) {
fullFilename = filename.string();
fullFilename += ".sqt";
}
file.close();
SQTreader modsReader(tmpBuilder, fullFilename.c_str(), NULL);
try{
modsReader.openRead(false);
} catch(BlibException& e){
const char* msg = e.what();
if( strncmp(msg, "Couldn't open", strlen("Couldn't open")) == 0 ){
e.addMessage(" SQT file required for reading modifications.");
throw e;
}// ignore warning that perc wasn't run on the sqt
}
applyModifications(psms, modsReader);
psms_ = psms; // transfer to BuildParser list
buildTables(PERCOLATOR_QVALUE);
clearVector(psms_);
}
return true;
}
/**
* Called when each start tag is read from the file.
*/
void PercolatorXmlReader::startElement(const XML_Char* name,
const XML_Char** attributes){
switch(currentState_){
case START_STATE:
if(isElement("percolator_output", name)){
currentState_ = ROOT_STATE;
}
break;
case ROOT_STATE:
if(isElement("psms", name)){
currentState_ = PSMS_STATE;
} else if(isElement("peptides", name)){
currentState_ = PEPTIDES_STATE;
}
break;
case PSMS_STATE:
if(isElement("psm", name)){
parseId(attributes);
} else if(isElement("q_value", name)){
currentState_ = QVALUE_STATE;
qvalueBufferPosition_ = qvalueBuffer_;//reset ptr into buffer
} else if(isElement("peptide_seq", name)){
parseSequence(attributes);
}
break;
case IGNORE_PSM_STATE:
case QVALUE_STATE: //shouldn't actually get here
case PEPTIDES_STATE:
return;
}
}
/**
* Called when each closing tag is read from the file.
*/
void PercolatorXmlReader::endElement(const XML_Char* name) {
switch(currentState_){
case PSMS_STATE:
if(isElement("psms", name)){
currentState_ = ROOT_STATE;
} else if(isElement("psm", name)){
addCurPSM();
}
break;
case IGNORE_PSM_STATE:
if(isElement("psm", name)){
currentState_ = PSMS_STATE;
}
break;
case QVALUE_STATE:
if(isElement("q_value", name)){
// add the q-value to the curPSM_
curPSM_->score = atof(qvalueBuffer_);
if( curPSM_->score > qvalueThreshold_ ){
currentState_ = IGNORE_PSM_STATE;
} else {
currentState_ = PSMS_STATE;
}
}
break;
default:
return;
}
}
/**
* Given the attributes of a 'psm' tag, start a new PSM in which to
* store data. Extract the filename, scan number, and charge from the
* id.
*/
void PercolatorXmlReader::parseId(const XML_Char** attributes){
const char* isdecoy = getAttrValue("p:decoy", attributes);
if( isdecoy == NULL || strcmp("true", isdecoy) == 0 ){
currentState_ = IGNORE_PSM_STATE;
return;
}
// if we have a current PSM, overwrite it, if not create a new one
if( curPSM_ == NULL ){
curPSM_ = new PSM();
}
// extract the filename, scan number, and charge from the id
const char* idStr = getRequiredAttrValue("p:psm_id", attributes);
char* buffer = new char[strlen(idStr) + 1];
strcpy(buffer, idStr);
// collect all tokens and interpret right to left in case filename has _
vector<string> tokens;
char* token = strtok(buffer, "_");
while( token != NULL ){
tokens.push_back(token);
token = strtok(NULL, "_");
}
delete [] buffer;
if( tokens.size() < 4 ){
throw BlibException(false, "Error parsing psm_id '%s'.", idStr);
}
// tokens arranged as name, scan, charge, something
tokens.pop_back(); // pop the last token whose meaning I've never known
curPSM_->charge = atoi(tokens.back().c_str()); // charge
tokens.pop_back();
curPSM_->specKey = atoi(tokens.back().c_str()); // scan number
tokens.pop_back();
// reconstruct remaining tokens into a filename
string filename = tokens.front();
vector<string>::iterator it = tokens.begin();
it++; // we already added the first, so skip it
for(; it < tokens.end(); ++it){
filename += "_";
filename += (*it);
}
// hijack the specName field to store the filename
curPSM_->specName = filename;
}
/**
* Read the seq attribute and add it to the current PSM.
*/
void PercolatorXmlReader::parseSequence(const XML_Char** attributes){
if(curPSM_ == NULL){
throw BlibException(false, "Encountered a peptide sequence with no "
"spectrum to assign it to.");
}
string seq = getRequiredAttrValue("seq", attributes);
curPSM_->unmodSeq.clear();
// consume all bracketed mods and add them as SeqMods to the PSM
int aaCount = 0;
for (size_t i = 0; i < seq.length(); ++i)
{
char cur = seq[i];
switch (cur)
{
case '[':
{
size_t modClose = seq.find("]", ++i);
if (modClose == string::npos)
{
throw BlibException(false, "Sequence '%s' has opening bracket "
"with no closing bracket.", seq.c_str());
}
// get delta mass
string modSeq = seq.substr(i, modClose - i);
double modMass;
try
{
modMass = boost::lexical_cast<double>(modSeq);
}
catch (boost::bad_lexical_cast& e)
{
throw BlibException(false, "Sequence '%s' has an unreadable modification. (%s)",
seq.c_str(), e.what());
}
double deltaMass;
// if the bracketed modification is + or - a number, assume it's a delta mass
if (modSeq[0] == '-' || modSeq[0] == '+')
{
deltaMass = modMass;
}
// if there is no +/- in the bracketed mass, assume it's monoisotopic residue mass + modification mass
else
{
if (i == 1)
throw BlibException(false, "Error assigning modification to amino acid in sequence %s", seq.c_str());
string residue(1, seq[i-1]);
double residueMass = getPeptideMass(residue, masses_);
deltaMass = modMass - residueMass;
}
// add seqmod to psm
curPSM_->mods.push_back(SeqMod(aaCount, deltaMass));
i = modClose;
}
break;
case ']':
{
throw BlibException(false, "Sequence '%s' has closing bracket with no "
"opening bracket.", seq.c_str());
}
break;
default:
{
if (isalpha(cur))
{
++aaCount;
}
curPSM_->unmodSeq += toupper(cur);
}
break;
}
}
}
/**
* Read all values between tags. We only want the q-values, so only
* read if we are in the QVALUES_STATE.
*/
void PercolatorXmlReader::characters(const XML_Char *s, int len){
if( currentState_ != QVALUE_STATE ){
return;
}
// copy len characters into current position in the qvalue buffer
strncpy(qvalueBufferPosition_, s, len);
qvalueBufferPosition_[len] = '\0';
// move the current position to the end
qvalueBufferPosition_ += len;
}
/**
* Evaluate the current PSM and save it with the appropriate filename
* if it passes the q-value threshold.
*/
void PercolatorXmlReader::addCurPSM(){
if(curPSM_ == NULL)
throw BlibException(false, "No PSM was read for this 'psm' tag.");
if(curPSM_->score < qvalueThreshold_){ // add the psm to the map
// retrieve and remove the filename from the psm
string filename = curPSM_->specName;
curPSM_->specName.clear();
Verbosity::comment(V_DETAIL, "For file %s adding PSM: "
"scan %d, charge %d, sequence '%s'.",
filename.c_str(), curPSM_->specKey,
curPSM_->charge, curPSM_->unmodSeq.c_str());
map<string, vector<PSM*> >::iterator mapAccess =
fileMap_.find(filename);
if( mapAccess == fileMap_.end() ){ // not found, add the file
vector<PSM*> tmpPsms(1, curPSM_);
fileMap_[filename] = tmpPsms;
} else { // add this psm to existing file entry
(mapAccess->second).push_back(curPSM_);
}
curPSM_ = NULL;
}
}
/**
* Use the SQTreader to translate the sequences with modification
* symbols to a vector of mods, a seq with bracketed masses, and an
* unmodified seq.
*/
void PercolatorXmlReader::applyModifications(vector<PSM*>& psms,
SQTreader& modsReader){
size_t numPsms = psms.size();
for(size_t i=0; i < numPsms; i++){
PSM* psm = psms[i];
// we were temporarily storing the modified seq here
string modSeq = psm->unmodSeq;
psm->unmodSeq.clear();
modsReader.parseModifiedSeq(modSeq.c_str(), psm->unmodSeq,
psm->mods, false);
}
}
} // namespace
/*
* Local Variables:
* mode: c
* c-basic-offset: 4
* End:
*/
|
/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2017 ScyllaDB.
*/
#pragma once
#include <seastar/util/noncopyable_function.hh>
#include <seastar/util/optimized_optional.hh>
#include <seastar/util/std-compat.hh>
#include <boost/intrusive/list.hpp>
#include <exception>
namespace bi = boost::intrusive;
namespace seastar {
/// \addtogroup fiber-module
/// @{
/// Exception thrown when an \ref abort_source object has been
/// notified by the \ref abort_source::request_abort() method.
class abort_requested_exception : public std::exception {
public:
virtual const char* what() const noexcept override {
return "abort requested";
}
};
/// Facility to communicate a cancellation request to a fiber.
/// Callbacks can be registered with the \c abort_source, which are called
/// atomically with a call to request_abort().
class abort_source {
using subscription_callback_type = noncopyable_function<void() noexcept>;
public:
/// Represents a handle to the callback registered by a given fiber. Ending the
/// lifetime of the \c subscription will unregister the callback, if it hasn't
/// been invoked yet.
class subscription : public bi::list_base_hook<bi::link_mode<bi::auto_unlink>> {
friend class abort_source;
subscription_callback_type _target;
explicit subscription(abort_source& as, subscription_callback_type target)
: _target(std::move(target)) {
as._subscriptions->push_back(*this);
}
void on_abort() {
_target();
}
public:
subscription() = default;
subscription(subscription&& other) noexcept(std::is_nothrow_move_constructible<subscription_callback_type>::value)
: _target(std::move(other._target)) {
subscription_list_type::node_algorithms::swap_nodes(other.this_ptr(), this_ptr());
}
subscription& operator=(subscription&& other) noexcept(std::is_nothrow_move_assignable<subscription_callback_type>::value) {
if (this != &other) {
_target = std::move(other._target);
if (is_linked()) {
subscription_list_type::node_algorithms::unlink(this_ptr());
}
subscription_list_type::node_algorithms::swap_nodes(other.this_ptr(), this_ptr());
}
return *this;
}
explicit operator bool() const noexcept {
return is_linked();
}
};
private:
using subscription_list_type = bi::list<subscription, bi::constant_time_size<false>>;
std::optional<subscription_list_type> _subscriptions = subscription_list_type();
public:
/// Delays the invocation of the callback \c f until \ref request_abort() is called.
/// \returns an engaged \ref optimized_optional containing a \ref subscription that can be used to control
/// the lifetime of the callback \c f, if \ref abort_requested() is \c false. Otherwise,
/// returns a disengaged \ref optimized_optional.
[[nodiscard]]
optimized_optional<subscription> subscribe(subscription_callback_type f) noexcept(std::is_nothrow_move_constructible<subscription_callback_type>::value) {
if (abort_requested()) {
return { };
}
return { subscription(*this, std::move(f)) };
}
/// Requests that the target operation be aborted. Current subscriptions
/// are invoked inline with this call, and no new ones can be registered.
void request_abort() {
std::exchange(_subscriptions, std::nullopt)->clear_and_dispose([] (subscription* s) { s->on_abort(); });
}
/// Returns whether an abort has been requested.
bool abort_requested() const noexcept {
return !_subscriptions;
}
/// Throws a \ref abort_requested_exception if cancellation has been requested.
void check() const {
if (abort_requested()) {
throw abort_requested_exception();
}
}
};
/// @}
}
|
#include <string>
#include <stdexcept>
#include <fstream>
#include <vector>
#include <ctime>
#include "SFML/Graphics.hpp"
#include "SFML/Audio.hpp"
#include "chip8.hpp"
#include "cpu.hpp"
// 0x0NNN
#define ADDR (opcode & 0x0FFF)
// 0x000N
#define N (opcode & 0x000F)
// 0x0X00
#define X ((opcode & 0x0F00) >> 8)
// 0x00Y0
#define Y ((opcode & 0x00F0) >> 4)
// 0x00KK
#define KK (opcode & 0x00FF)
#define V(x) registers.V[x]
CPU::CPU() {
initialize();
srand(time(NULL));
}
CPU::~CPU() {
delete[] memory;
delete[] display;
delete[] keyboard;
}
void CPU::initialize() {
memory = new u8[MEMORY_SIZE];
display = new u8[DISPLAY_SIZE];
keyboard = new u8[KEY_COUNT];
// Initialize arrays
for (u16 i = 0; i < MEMORY_SIZE; i++) {
memory[i] = 0;
}
for (u16 i = 0; i < DISPLAY_SIZE; i++) {
display[i] = 0;
}
for (u8 i = 0; i < KEY_COUNT; i++) {
keyboard[i] = 0;
}
opcode = 0;
playSound = false;
running = true;
ready = false;
// Store fontsent in memory
for(u16 i = FONTSET_START; i < FONTSET_END; i++) {
memory[i] = FONTSET[i - FONTSET_START];
}
}
void CPU::incrementPC() {
registers.PC += 2;
}
void CPU::error(std::string errorMsg = "") {
throw std::runtime_error(errorMsg);
}
bool CPU::load(std::string fileDir) {
std::ifstream file(fileDir, std::ios::in | std::ios::binary);
if (file.fail()) {
// error("File could not be opened.");
return false;
}
std::vector<u8> vec {
std::istreambuf_iterator<char>(file),
std::istreambuf_iterator<char>()
};
u16 i = PROGRAM_START;
for (auto j = vec.begin(); j != vec.end(); j++) {
memory[i++] = *j;
}
ready = true;
return true;
}
void CPU::emulate() {
if (!ready) return;
// opcodes are 16 bits and the memory is an 8 bit array. So read 8 bits,
// shift left 8 times, bitwise AND with the rest of the bits to concatenate.
opcode = (memory[registers.PC] << 8) | memory[registers.PC + 1];
// Compare the first 4 bits
switch (opcode & 0xF000) {
// 0~~~
case 0x0000:
// 00E0
if (KK == 0xE0) {
for (u16 i = 0; i < DISPLAY_SIZE; i++) {
display[i] = 0;
}
incrementPC();
}
// 00EE
else if (KK == 0xEE) {
if (registers.SP > 0) {
stack.pop(registers.PC, registers.SP);
} else {
error("Tried to pop item from stack while SP <= 0.");
}
}
// 0000
else if (KK == 0x00) {
incrementPC();
} else {
error("Unknown opcode.");
}
break;
// 1NNN
case 0x1000:
registers.PC = ADDR;
break;
// 2NNN
case 0x2000:
if (registers.SP == STACK_SIZE - 1) {
error("Stack overflow.");
} else {
stack.push(registers.PC, registers.SP);
registers.PC = ADDR;
}
break;
// 3XKK
case 0x3000:
if (V(X) == KK) {
incrementPC();
}
incrementPC();
break;
// 4XKK
case 0x4000:
if (V(X) != KK) {
incrementPC();
}
incrementPC();
break;
// 5XY0
case 0x5000:
if (V(X) == V(Y)) {
incrementPC();
}
incrementPC();
break;
// 6XKK
case 0x6000:
V(X) = KK;
incrementPC();
break;
// 7XKK
case 0x7000:
V(X) += KK;
incrementPC();
break;
// 8XY~
case 0x8000:
switch (N) {
// 8XY0
case 0x0:
V(X) = V(Y);
break;
// 8XY1
case 0x1:
V(X) = V(X) | V(Y);
break;
// 8XY2
case 0x2:
V(X) = V(X) & V(Y);
break;
// 8XY3
case 0x3:
V(X) = V(X) ^ V(Y);
break;
// 8XY4
case 0x4:
if (V(X) + V(Y) > 0xFF) {
V(0xF) = 1;
} else {
V(0xF) = 0;
}
V(X) = (V(X) + V(Y)) & 0xFF;
break;
// 8XY5
case 0x5:
if (V(X) >= V(Y)) {
V(0xF) = 1;
} else {
V(0xF) = 0;
}
V(X) -= V(Y);
break;
// 8XY6
case 0x6:
V(0xF) = V(X) & 0x1;
V(X) >>= 1;
break;
// 8XY7
case 0x7:
if (V(Y) >= V(X)) {
V(0xF) = 1;
} else {
V(0xF) = 0;
}
V(X) = V(Y) - V(X);
break;
// 8XYE
case 0xE:
V(0xF) = (V(X) & 0x80) >> 7;
V(X) <<= 1;
break;
}
incrementPC();
break;
// 9XY0
case 0x9000:
if (V(X) != V(Y)) {
incrementPC();
}
incrementPC();
break;
// ANNN
case 0xA000:
registers.I = ADDR;
incrementPC();
break;
// BNNN
case 0xB000:
registers.PC = ADDR + V(0);
break;
// CXKK
case 0xC000:
V(X) = (rand() % 0xFF) & KK;
incrementPC();
break;
// DXYN
case 0xD000:
// y-axis
for (u8 i = 0; i < N; i++) {
// x-axis
for (u8 j = 0; j < 8; j++) {
if ((memory[registers.I + i] & (0x80 >> j)) != 0) {
u16 pos = (V(X) + j + DISPLAY_WIDTH * (V(Y) + i)) % DISPLAY_SIZE;
if (pos < 0) pos += DISPLAY_SIZE;
V(0xF) = display[pos];
display[pos] ^= 1;
}
}
}
incrementPC();
break;
// EX~~
case 0xE000: {
u8 index;
for (index = 0; index < KEY_COUNT; index++) {
if (KEYS[index] == V(X)) {
break;
}
}
// EX9E
if (KK == 0x9E) {
if (keyboard[index] == 1) {
incrementPC();
}
incrementPC();
}
// EXA1
else if(KK == 0xA1) {
if (keyboard[index] != 1) {
incrementPC();
}
incrementPC();
} else {
error("Unknown opcode.");
}}
break;
// FX~~
case 0xF000:
switch(KK) {
// FX07
case 0x07:
V(X) = registers.DT;
break;
// FX0A
case 0x0A: {
u8 input = 0;
for (u8 i = 0; i < KEY_COUNT; i++) {
if (keyboard[i] == 1) {
input = KEYS[i];
break;
}
}
if (input != 0) {
V(X) = input;
} else {
return;
}}
break;
// FX15
case 0x15:
registers.DT = V(X);
break;
// FX18
case 0x18:
registers.ST = V(X);
break;
// FX1E
case 0x1E:
registers.I += V(X);
break;
// FX29
case 0x29:
registers.I = V(X) * 5 + FONTSET_START;
break;
// FX33
case 0x33:
memory[registers.I] = V(X) / 100;
memory[registers.I + 1] = (V(X) / 10) % 10;
memory[registers.I + 2] = V(X) % 10;
break;
// FX55
case 0x55:
for (u8 i = 0; i <= X; i++) {
memory[registers.I + i] = V(i);
}
break;
// FX65
case 0x65:
for (u8 i = 0; i <= X; i++) {
V(i) = memory[registers.I + i];
}
break;
default:
error("Unknown opcode.");
break;
}
incrementPC();
break;
default:
error("Unknown opcode.");
break;
}
}
void CPU::decrementTimers() {
if (!ready) return;
if (registers.DT > 0) {
registers.DT--;
}
if (registers.ST > 0) {
if (registers.ST == 1) {
playSound = true;
}
registers.ST--;
}
}
bool CPU::isRunning() {
return running;
}
#undef X
void CPU::displayCycle() {
int scale = 20;
sf::RenderWindow window(sf::VideoMode(DISPLAY_WIDTH * scale, DISPLAY_HEIGHT * scale), "CHIP-8");
window.setFramerateLimit(60);
sf::Uint8 *pixels = new sf::Uint8[DISPLAY_WIDTH * DISPLAY_HEIGHT * 4];
sf::Texture texture;
texture.create(DISPLAY_WIDTH, DISPLAY_HEIGHT);
sf::Sprite sprite(texture);
sprite.setScale(scale, scale);
sf::SoundBuffer soundBuffer;
sf::Sound *sound;
if (!soundBuffer.loadFromFile("res/sound.wav")) {
sound = nullptr;
} else {
sound = new sf::Sound;
sound->setBuffer(soundBuffer);
}
bool menu = true;
sf::String msg("ENTER to run the program\nESCAPE to return to this screen\n\nDirectory to the program: ");
sf::String input;
sf::Text inputText;
inputText.setString(msg + "_");
sf::Font font;
if (!font.loadFromFile("res/arial.ttf")) exit(1);
inputText.setFont(font);
sf::Event event;
while (window.isOpen()) {
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
running = false;
} else if (menu && event.type == sf::Event::TextEntered && event.text.unicode < 128) {
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Enter)) {
if (load(static_cast<std::string>(input))) {
menu = false;
ready = true;
} else {
inputText.setString(inputText.getString() + "\n\nFile could not be opened.");
}
} else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Backspace) && input.getSize() > 0) {
input.erase(input.getSize() - 1, 1);
inputText.setString(msg + input + "_");
} else if (event.text.unicode >= 32) {
input += event.text.unicode;
inputText.setString(msg + input + "_");
}
}
}
for (auto i = 0; i < KEY_COUNT; i++) {
keyboard[i] = 0;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Num1)) {
keyboard[0] = 1;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Num2)) {
keyboard[1] = 1;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Num3)) {
keyboard[2] = 1;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Num4)) {
keyboard[3] = 1;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Q)) {
keyboard[4] = 1;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) {
keyboard[5] = 1;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::E)) {
keyboard[6] = 1;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::R)) {
keyboard[7] = 1;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) {
keyboard[8] = 1;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) {
keyboard[9] = 1;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) {
keyboard[10] = 1;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::F)) {
keyboard[11] = 1;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Z)) {
keyboard[12] = 1;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::X)) {
keyboard[13] = 1;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::C)) {
keyboard[14] = 1;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::V)) {
keyboard[15] = 1;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) {
this->~CPU();
initialize();
registers.initialize();
stack.initialize();
input.clear();
inputText.setString(msg);
menu = true;
}
if (sound != nullptr && playSound) {
sound->play();
playSound = false;
}
window.clear(sf::Color::Black);
if (menu) {
window.draw(inputText);
} else {
for (int i = 0; i < DISPLAY_SIZE * 4; i += 4) {
for (int j = 0; j < 4; j++) {
pixels[i + j] = display[i / 4] == 1 ? 255 : 0;
}
}
texture.update(pixels);
window.draw(sprite);
}
window.display();
}
}
|
//========= Copyright Valve Corporation, All rights reserved. ============//
// c_bot_npc.cpp
#include "cbase.h"
#include "NextBot/C_NextBot.h"
#include "c_bot_npc.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#undef NextBot
//-----------------------------------------------------------------------------
IMPLEMENT_CLIENTCLASS_DT( C_BotNPC, DT_BotNPC, CBotNPC )
RecvPropEHandle( RECVINFO( m_laserTarget ) ),
RecvPropBool( RECVINFO( m_isNuking ) ),
END_RECV_TABLE()
//-----------------------------------------------------------------------------
C_BotNPC::C_BotNPC()
{
}
//-----------------------------------------------------------------------------
C_BotNPC::~C_BotNPC()
{
if ( m_laserBeamEffect )
{
ParticleProp()->StopEmissionAndDestroyImmediately( m_laserBeamEffect );
m_laserBeamEffect = NULL;
}
if ( m_nukeEffect )
{
ParticleProp()->StopEmissionAndDestroyImmediately( m_nukeEffect );
m_nukeEffect = NULL;
}
}
//-----------------------------------------------------------------------------
void C_BotNPC::Spawn( void )
{
BaseClass::Spawn();
m_vecViewOffset = Vector( 0, 0, 180.0f );
SetNextClientThink( CLIENT_THINK_ALWAYS );
}
//-----------------------------------------------------------------------------
void C_BotNPC::ClientThink( void )
{
if ( m_laserTarget )
{
if ( !m_laserBeamEffect )
{
m_laserBeamEffect = ParticleProp()->Create( "laser_sight_beam", PATTACH_POINT_FOLLOW, LookupAttachment( "head" ) );
}
if ( m_laserBeamEffect )
{
m_laserBeamEffect->SetSortOrigin( m_laserBeamEffect->GetRenderOrigin() );
m_laserBeamEffect->SetControlPoint( 2, Vector( 0, 255, 0 ) );
m_laserBeamEffect->SetControlPoint( 1, m_laserTarget->WorldSpaceCenter() );
}
}
else
{
// shut off the laser
if ( m_laserBeamEffect )
{
ParticleProp()->StopEmissionAndDestroyImmediately( m_laserBeamEffect );
m_laserBeamEffect = NULL;
}
}
if ( m_isNuking )
{
if ( !m_nukeEffect )
{
m_nukeEffect = ParticleProp()->Create( "charge_up", PATTACH_POINT_FOLLOW, LookupAttachment( "head" ) );
}
}
else
{
if ( m_nukeEffect )
{
ParticleProp()->StopEmissionAndDestroyImmediately( m_nukeEffect );
m_nukeEffect = NULL;
}
}
}
//-----------------------------------------------------------------------------
// Return the origin for player observers tracking this target
Vector C_BotNPC::GetObserverCamOrigin( void )
{
return EyePosition();
}
//-----------------------------------------------------------------------------
void C_BotNPC::FireEvent( const Vector& origin, const QAngle& angles, int event, const char *options )
{
if ( event == 7001 )
{
EmitSound( "RobotBoss.Footstep" );
/*
ParticleProp()->Create( "halloween_boss_foot_impact", PATTACH_ABSORIGIN, 0 );
*/
}
}
|
#include <algorithm>
#include <cassert>
#include <cstring>
#include "p2p.h"
#include "p2p_api.h"
#ifdef P2P_USER_NAMESPACE
#error API build must not use custom namespace
#endif
namespace {
struct packing_traits {
enum p2p_packing packing;
p2p_unpack_func unpack;
p2p_pack_func pack;
p2p_pack_func pack_one_fill;
bool native_endian;
unsigned char subsample_w;
unsigned char subsample_h;
bool is_nv;
unsigned char bytes_per_sample; // Only used to copy luma plane for NV12.
unsigned char nv_shift; // Extra LSB to shift away for MS P010/P210, etc.
};
#define CASE(x, ...) \
{ p2p_##x, &p2p::packed_to_planar<p2p::packed_##x>::unpack, &p2p::planar_to_packed<p2p::packed_##x, false>::pack, &p2p::planar_to_packed<p2p::packed_##x, true>::pack, ##__VA_ARGS__ }
#define CASE2(x, ...) \
CASE(x##_be, std::is_same<p2p::native_endian_t, p2p::big_endian_t>::value, ##__VA_ARGS__), \
CASE(x##_le, std::is_same<p2p::native_endian_t, p2p::little_endian_t>::value, ##__VA_ARGS__), \
CASE(x, true, ##__VA_ARGS__)
const packing_traits traits_table[] = {
CASE2(rgb24, 0, 0),
CASE2(argb32, 0, 0),
CASE2(ayuv, 0, 0),
CASE2(rgb48, 0, 0),
CASE2(argb64, 0, 0),
CASE2(rgb30, 0, 0),
CASE2(y410, 0, 0),
CASE2(y416, 0, 0),
CASE(yuy2, true, 1, 0),
CASE(uyvy, true, 1, 0),
CASE2(y210, 1, 0),
CASE2(y216, 1, 0),
CASE2(v210, 1, 0),
CASE2(v216, 1, 0),
CASE2(nv12, 1, 1, true, 1),
CASE2(p010, 1, 1, true, 2, 6),
CASE2(p016, 1, 1, true, 2),
CASE2(p210, 1, 0, true, 2, 6),
CASE2(p216, 1, 0, true, 2),
CASE2(rgba32, 0, 0),
CASE2(rgba64, 0, 0),
CASE2(abgr64, 0, 0),
CASE2(bgr48, 0, 0),
CASE2(bgra64, 0, 0),
};
#undef CASE2
#undef CASE
const packing_traits &lookup_traits(enum p2p_packing packing)
{
assert(packing >= 0);
assert(packing < sizeof(traits_table) / sizeof(traits_table[0]));
const packing_traits &traits = traits_table[packing];
assert(traits.packing == packing);
assert(traits.subsample_h == 0 || traits.is_nv);
return traits;
}
template <class T>
T *increment_ptr(T *ptr, ptrdiff_t n)
{
return (T *)((const unsigned char *)ptr + n);
}
void copy_plane_fast(const void *src, void *dst, ptrdiff_t src_stride, ptrdiff_t dst_stride,
unsigned linesize, unsigned height)
{
for (unsigned i = 0; i < height; ++i) {
memcpy(dst, src, linesize);
src = increment_ptr(src, src_stride);
dst = increment_ptr(dst, dst_stride);
}
}
void unpack_nv16_plane(const void *src, void *dst, ptrdiff_t src_stride, ptrdiff_t dst_stride,
const packing_traits &traits, unsigned width, unsigned height)
{
assert(traits.bytes_per_sample == 2);
for (unsigned i = 0; i < height; ++i) {
std::transform(static_cast<const uint16_t *>(src), static_cast<const uint16_t *>(src) + width, static_cast<uint16_t *>(dst), [=](uint16_t x)
{
x = traits.native_endian ? x : (x >> 8) | (x << 8);
return x >> traits.nv_shift;
});
src = increment_ptr(src, src_stride);
dst = increment_ptr(dst, dst_stride);
}
}
void pack_nv16_plane(const void *src, void *dst, ptrdiff_t src_stride, ptrdiff_t dst_stride,
const packing_traits &traits, unsigned width, unsigned height)
{
assert(traits.bytes_per_sample == 2);
for (unsigned i = 0; i < height; ++i) {
std::transform(static_cast<const uint16_t *>(src), static_cast<const uint16_t *>(src) + width, static_cast<uint16_t *>(dst), [=](uint16_t x)
{
x = x << traits.nv_shift;
return traits.native_endian ? x : (x >> 8) | (x << 8);
});
src = increment_ptr(src, src_stride);
dst = increment_ptr(dst, dst_stride);
}
}
} // namespace
p2p_unpack_func p2p_select_unpack_func(enum p2p_packing packing)
{
return lookup_traits(packing).unpack;
}
p2p_pack_func p2p_select_pack_func(enum p2p_packing packing)
{
return p2p_select_pack_func_ex(packing, 0);
}
p2p_pack_func p2p_select_pack_func_ex(enum p2p_packing packing, int alpha_one_fill)
{
const packing_traits &traits = lookup_traits(packing);
return alpha_one_fill ? traits.pack_one_fill : traits.pack;
}
void p2p_unpack_frame(const struct p2p_buffer_param *param, unsigned long flags)
{
const packing_traits &traits = lookup_traits(param->packing);
// Process interleaved plane.
const void *src_p = traits.is_nv ? param->src[1] : param->src[0];
ptrdiff_t src_stride = traits.is_nv ? param->src_stride[1] : param->src_stride[0];
void *dst_p[4] = { param->dst[0], param->dst[1], param->dst[2], param->dst[3] };
for (unsigned i = 0; i < (param->height >> traits.subsample_h); ++i) {
traits.unpack(src_p, dst_p, 0, param->width);
src_p = increment_ptr(src_p, src_stride);
if (!traits.is_nv) {
dst_p[0] = increment_ptr(dst_p[0], param->dst_stride[0]);
dst_p[3] = increment_ptr(dst_p[3], param->dst_stride[3]);
}
dst_p[1] = increment_ptr(dst_p[1], param->dst_stride[1]);
dst_p[2] = increment_ptr(dst_p[2], param->dst_stride[2]);
}
if (traits.is_nv && !(flags & P2P_SKIP_UNPACKED_PLANES) && param->src[0] && param->dst[0]) {
if ((traits.bytes_per_sample == 1 || traits.native_endian) && !traits.nv_shift) {
copy_plane_fast(param->src[0], param->dst[0], param->src_stride[0], param->dst_stride[0],
traits.bytes_per_sample * param->width, param->height);
} else {
unpack_nv16_plane(param->src[0], param->dst[0], param->src_stride[0], param->dst_stride[0], traits, param->width, param->height);
}
}
}
void p2p_pack_frame(const struct p2p_buffer_param *param, unsigned long flags)
{
const packing_traits &traits = lookup_traits(param->packing);
p2p_pack_func pack_func = flags & P2P_ALPHA_SET_ONE ? traits.pack_one_fill : traits.pack;
// Process interleaved plane.
const void *src_p[4] = { param->src[0], param->src[1], param->src[2], param->src[3] };
void *dst_p = traits.is_nv ? param->dst[1] : param->dst[0];
ptrdiff_t dst_stride = traits.is_nv ? param->dst_stride[1] : param->dst_stride[0];
for (unsigned i = 0; i < (param->height >> traits.subsample_h); ++i) {
pack_func(src_p, dst_p, 0, param->width);
if (!traits.is_nv) {
src_p[0] = increment_ptr(src_p[0], param->src_stride[0]);
src_p[3] = increment_ptr(src_p[3], param->src_stride[3]);
}
src_p[1] = increment_ptr(src_p[1], param->src_stride[1]);
src_p[2] = increment_ptr(src_p[2], param->src_stride[2]);
dst_p = increment_ptr(dst_p, dst_stride);
}
if (traits.is_nv && !(flags & P2P_SKIP_UNPACKED_PLANES) && param->src[0] && param->dst[0]) {
if ((traits.bytes_per_sample == 1 || traits.native_endian) && !traits.nv_shift) {
copy_plane_fast(param->src[0], param->dst[0], param->src_stride[0], param->dst_stride[0],
traits.bytes_per_sample * param->width, param->height);
} else {
pack_nv16_plane(param->src[0], param->dst[0], param->src_stride[0], param->dst_stride[0], traits, param->width, param->height);
}
}
}
|
#pragma once
#include "frc/smartdashboard/Smartdashboard.h"
#include "networktables/NetworkTable.h"
#include "networktables/NetworkTableInstance.h"
class LimeLight
{
std::shared_ptr<NetworkTable> table = nt::NetworkTableInstance::GetDefault().GetTable("limelight");
public:
enum class LED_Mode { Keep_Current = 0,
Force_Off,
Blink,
Force_On };
enum class Camera_Mode { Vision_Processor = 0,
Driver_Camera };
enum class Stream_Mode { Standard = 0,
PiP_Main,
PiP_Secondary };
enum class Snapshot_Mode { OFF = 0,
ON };
[[nodiscard]] double getX() const; // [-27.0, 27.0] For LimeLight-1
[[nodiscard]] double getY() const; // [-20.5, 20.5] For LimeLight-1
[[nodiscard]] double getArea() const; // % of image
[[nodiscard]] double getSkew() const; // [-90, 0]
[[nodiscard]] bool hasTarget() const;
[[nodiscard]] int getShortSideLength() const; // [0, 320]
[[nodiscard]] int getLongSideLength() const; // [0, 320]
[[nodiscard]] int getHorizontalSideLength() const; // [0, 320]
[[nodiscard]] int getVerticalSideLength() const; // [0, 320]
// Camera Translation not implimented because of unclear documentation
// Corners not implimented because slightly difficult and we arent using it here
// Advanced Usage section not implimented becuase im too bored to do so
[[nodiscard]] int getPipe() const;
[[nodiscard]] double getLatency_ms() const;
void setLEDMode(LED_Mode mode);
void setCameraMode(Camera_Mode mode);
void setPipeline(unsigned pipe);
void setStream(Stream_Mode mode);
void setSnapshot(Snapshot_Mode mode);
};
|
//===--- AllocBoxToStack.cpp - Promote alloc_box to alloc_stack -----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "allocbox-to-stack"
#include "swift/SIL/Dominance.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILCloner.h"
#include "swift/SILOptimizer/Utils/SILOptFunctionBuilder.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/Local.h"
#include "swift/SILOptimizer/Utils/SpecializationMangler.h"
#include "swift/SILOptimizer/Utils/StackNesting.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Debug.h"
using namespace swift;
STATISTIC(NumStackPromoted, "Number of alloc_box's promoted to the stack");
//===----------------------------------------------------------------------===//
// SIL Utilities for alloc_box Promotion
//===----------------------------------------------------------------------===//
static SILValue stripOffCopyValue(SILValue V) {
while (auto *CVI = dyn_cast<CopyValueInst>(V)) {
V = CVI->getOperand();
}
return V;
}
/// \brief Returns True if the operand or one of its users is captured.
static bool useCaptured(Operand *UI) {
auto *User = UI->getUser();
// These instructions do not cause the address to escape.
if (isa<DebugValueInst>(User) || isa<DebugValueAddrInst>(User)
|| isa<StrongReleaseInst>(User) || isa<StrongRetainInst>(User)
|| isa<DestroyValueInst>(User))
return false;
if (auto *Store = dyn_cast<StoreInst>(User)) {
if (Store->getDest() == UI->get())
return false;
} else if (auto *Assign = dyn_cast<AssignInst>(User)) {
if (Assign->getDest() == UI->get())
return false;
}
return true;
}
//===----------------------------------------------------------------------===//
// Liveness for alloc_box Promotion
//===----------------------------------------------------------------------===//
// Is any successor of BB in the LiveIn set?
static bool successorHasLiveIn(SILBasicBlock *BB,
llvm::SmallPtrSetImpl<SILBasicBlock *> &LiveIn) {
for (auto &Succ : BB->getSuccessors())
if (LiveIn.count(Succ))
return true;
return false;
}
// Propagate liveness backwards from an initial set of blocks in our
// LiveIn set.
static void propagateLiveness(llvm::SmallPtrSetImpl<SILBasicBlock*> &LiveIn,
SILBasicBlock *DefBB) {
// First populate a worklist of predecessors.
llvm::SmallVector<SILBasicBlock*, 64> Worklist;
for (auto *BB : LiveIn)
for (auto Pred : BB->getPredecessorBlocks())
Worklist.push_back(Pred);
// Now propagate liveness backwards until we hit the alloc_box.
while (!Worklist.empty()) {
auto *BB = Worklist.pop_back_val();
// If it's already in the set, then we've already queued and/or
// processed the predecessors.
if (BB == DefBB || !LiveIn.insert(BB).second)
continue;
for (auto Pred : BB->getPredecessorBlocks())
Worklist.push_back(Pred);
}
}
// Walk backwards in BB looking for strong_release, destroy_value, or
// dealloc_box of the given value, and add it to releases.
static bool addLastRelease(SILValue V, SILBasicBlock *BB,
llvm::SmallVectorImpl<SILInstruction*> &Releases) {
for (auto I = BB->rbegin(); I != BB->rend(); ++I) {
if (isa<StrongReleaseInst>(*I) || isa<DeallocBoxInst>(*I) ||
isa<DestroyValueInst>(*I)) {
if (stripOffCopyValue(I->getOperand(0)) != V)
continue;
Releases.push_back(&*I);
return true;
}
}
return false;
}
// Find the final releases of the alloc_box along any given path.
// These can include paths from a release back to the alloc_box in a
// loop.
static bool
getFinalReleases(SILValue Box,
llvm::SmallVectorImpl<SILInstruction *> &Releases) {
llvm::SmallPtrSet<SILBasicBlock*, 16> LiveIn;
llvm::SmallPtrSet<SILBasicBlock*, 16> UseBlocks;
auto *DefBB = Box->getParentBlock();
auto seenRelease = false;
SILInstruction *OneRelease = nullptr;
// We'll treat this like a liveness problem where the alloc_box is
// the def. Each block that has a use of the owning pointer has the
// value live-in unless it is the block with the alloc_box.
llvm::SmallVector<Operand *, 32> Worklist(Box->use_begin(), Box->use_end());
while (!Worklist.empty()) {
auto *Op = Worklist.pop_back_val();
auto *User = Op->getUser();
auto *BB = User->getParent();
if (isa<ProjectBoxInst>(User))
continue;
if (BB != DefBB)
LiveIn.insert(BB);
// Also keep track of the blocks with uses.
UseBlocks.insert(BB);
// If we have a copy value or a mark_uninitialized, add its uses to the work
// list and continue.
if (isa<MarkUninitializedInst>(User) || isa<CopyValueInst>(User)) {
copy(cast<SingleValueInstruction>(User)->getUses(),
std::back_inserter(Worklist));
continue;
}
// Try to speed up the trivial case of single release/dealloc.
if (isa<StrongReleaseInst>(User) || isa<DeallocBoxInst>(User) ||
isa<DestroyValueInst>(User)) {
if (!seenRelease)
OneRelease = User;
else
OneRelease = nullptr;
seenRelease = true;
}
}
// Only a single release/dealloc? We're done!
if (OneRelease) {
Releases.push_back(OneRelease);
return true;
}
propagateLiveness(LiveIn, DefBB);
// Now examine each block we saw a use in. If it has no successors
// that are in LiveIn, then the last use in the block is the final
// release/dealloc.
for (auto *BB : UseBlocks)
if (!successorHasLiveIn(BB, LiveIn))
if (!addLastRelease(Box, BB, Releases))
return false;
return true;
}
//===----------------------------------------------------------------------===//
// alloc_box Escape Analysis
//===----------------------------------------------------------------------===//
/// This is a list we use to store a set of indices. We create the set by
/// sorting, uniquing at the appropriate time. The reason why it makes sense to
/// just use a sorted vector with std::count is because generally functions do
/// not have that many arguments and even fewer promoted arguments.
using ArgIndexList = llvm::SmallVector<unsigned, 8>;
static bool partialApplyEscapes(SILValue V, bool examineApply);
/// Could this operand to an apply escape that function by being
/// stored or returned?
static bool applyArgumentEscapes(FullApplySite Apply, Operand *O) {
SILFunction *F = Apply.getReferencedFunction();
// If we cannot examine the function body, assume the worst.
if (!F || F->empty())
return true;
// Check the uses of the operand, but do not recurse down into other
// apply instructions.
auto calleeArg = F->getArgument(Apply.getCalleeArgIndex(*O));
return partialApplyEscapes(calleeArg, /* examineApply = */ false);
}
static bool partialApplyEscapes(SILValue V, bool examineApply) {
SILModuleConventions ModConv(*V->getModule());
llvm::SmallVector<Operand *, 32> Worklist(V->use_begin(), V->use_end());
while (!Worklist.empty()) {
Operand *Op = Worklist.pop_back_val();
// These instructions do not cause the address to escape.
if (!useCaptured(Op))
continue;
auto *User = Op->getUser();
// If we have a copy_value, the copy value does not cause an escape, but its
// uses might do so... so add the copy_value's uses to the worklist and
// continue.
if (auto CVI = dyn_cast<CopyValueInst>(User)) {
copy(CVI->getUses(), std::back_inserter(Worklist));
continue;
}
if (auto Apply = FullApplySite::isa(User)) {
// Applying a function does not cause the function to escape.
if (!Apply.isArgumentOperand(*Op))
continue;
// apply instructions do not capture the pointer when it is passed
// indirectly
if (Apply.getArgumentConvention(*Op).isIndirectConvention())
continue;
// Optionally drill down into an apply to see if the operand is
// captured in or returned from the apply.
if (examineApply && !applyArgumentEscapes(Apply, Op))
continue;
}
// partial_apply instructions do not allow the pointer to escape
// when it is passed indirectly, unless the partial_apply itself
// escapes
if (auto *PartialApply = dyn_cast<PartialApplyInst>(User)) {
auto Args = PartialApply->getArguments();
auto Params = PartialApply->getSubstCalleeType()->getParameters();
Params = Params.slice(Params.size() - Args.size(), Args.size());
if (ModConv.isSILIndirect(Params[Op->getOperandNumber() - 1])) {
if (partialApplyEscapes(PartialApply, /*examineApply = */ true))
return true;
continue;
}
}
return true;
}
return false;
}
static SILInstruction *findUnexpectedBoxUse(SILValue Box,
bool examinePartialApply,
bool inAppliedFunction,
llvm::SmallVectorImpl<Operand *> &);
/// checkPartialApplyBody - Check the body of a partial apply to see
/// if the box pointer argument passed to it has uses that would
/// disqualify it from being promoted to a stack location. Return
/// true if this partial apply will not block our promoting the box.
static bool checkPartialApplyBody(Operand *O) {
SILFunction *F = ApplySite(O->getUser()).getReferencedFunction();
// If we cannot examine the function body, assume the worst.
if (!F || F->empty())
return false;
// We don't actually use these because we're not recursively
// rewriting the partial applies we find.
llvm::SmallVector<Operand *, 1> PromotedOperands;
auto calleeArg = F->getArgument(ApplySite(O->getUser()).getCalleeArgIndex(*O));
return !findUnexpectedBoxUse(calleeArg, /* examinePartialApply = */ false,
/* inAppliedFunction = */ true,
PromotedOperands);
}
/// Validate that the uses of a pointer to a box do not eliminate it from
/// consideration for promotion to a stack element. Optionally examine the body
/// of partial_apply to see if there is an unexpected use inside. Return the
/// instruction with the unexpected use if we find one.
static SILInstruction *
findUnexpectedBoxUse(SILValue Box, bool examinePartialApply,
bool inAppliedFunction,
llvm::SmallVectorImpl<Operand *> &PromotedOperands) {
assert((Box->getType().is<SILBoxType>()
|| Box->getType()
== SILType::getNativeObjectType(Box->getType().getASTContext()))
&& "Expected an object pointer!");
llvm::SmallVector<Operand *, 4> LocalPromotedOperands;
// Scan all of the uses of the retain count value, collecting all
// the releases and validating that we don't have an unexpected
// user.
llvm::SmallVector<Operand *, 32> Worklist(Box->use_begin(), Box->use_end());
while (!Worklist.empty()) {
auto *Op = Worklist.pop_back_val();
auto *User = Op->getUser();
// Retains and releases are fine. Deallocs are fine if we're not
// examining a function that the alloc_box was passed into.
// Projections are fine as well.
if (isa<StrongRetainInst>(User) || isa<StrongReleaseInst>(User) ||
isa<ProjectBoxInst>(User) || isa<DestroyValueInst>(User) ||
(!inAppliedFunction && isa<DeallocBoxInst>(User)))
continue;
// If our user instruction is a copy_value or a marked_uninitialized, visit
// the users recursively.
if (isa<MarkUninitializedInst>(User) || isa<CopyValueInst>(User)) {
copy(cast<SingleValueInstruction>(User)->getUses(),
std::back_inserter(Worklist));
continue;
}
// For partial_apply, if we've been asked to examine the body, the
// uses of the argument are okay there, and the partial_apply
// itself cannot escape, then everything is fine.
if (auto *PAI = dyn_cast<PartialApplyInst>(User))
if (examinePartialApply && checkPartialApplyBody(Op) &&
!partialApplyEscapes(PAI, /* examineApply = */ true)) {
LocalPromotedOperands.push_back(Op);
continue;
}
return User;
}
PromotedOperands.append(LocalPromotedOperands.begin(),
LocalPromotedOperands.end());
return nullptr;
}
/// canPromoteAllocBox - Can we promote this alloc_box to an alloc_stack?
static bool canPromoteAllocBox(AllocBoxInst *ABI,
llvm::SmallVectorImpl<Operand *> &PromotedOperands){
// Scan all of the uses of the address of the box to see if any
// disqualifies the box from being promoted to the stack.
if (auto *User = findUnexpectedBoxUse(ABI,
/* examinePartialApply = */ true,
/* inAppliedFunction = */ false,
PromotedOperands)) {
(void)User;
// Otherwise, we have an unexpected use.
LLVM_DEBUG(llvm::dbgs() << "*** Failed to promote alloc_box in @"
<< ABI->getFunction()->getName() << ": " << *ABI
<< " Due to user: " << *User << "\n");
return false;
}
// Okay, it looks like this value doesn't escape.
return true;
}
//===----------------------------------------------------------------------===//
// alloc_box Promotion
//===----------------------------------------------------------------------===//
namespace {
// Pass context and per-function analysis results.
struct AllocBoxToStackState {
SILFunctionTransform *T;
bool CFGChanged = false;
llvm::SmallVector<AllocBoxInst *, 8> Promotable;
llvm::SmallVector<Operand *, 8> PromotedOperands;
AllocBoxToStackState(SILFunctionTransform *T) : T(T) {}
};
} // anonymous namespace
static void replaceProjectBoxUsers(SILValue HeapBox, SILValue StackBox) {
llvm::SmallVector<Operand *, 8> Worklist(HeapBox->use_begin(),
HeapBox->use_end());
while (!Worklist.empty()) {
auto *Op = Worklist.pop_back_val();
if (auto *PBI = dyn_cast<ProjectBoxInst>(Op->getUser())) {
// This may result in an alloc_stack being used by begin_access [dynamic].
PBI->replaceAllUsesWith(StackBox);
continue;
}
auto *CVI = dyn_cast<CopyValueInst>(Op->getUser());
if (!CVI)
continue;
copy(CVI->getUses(), std::back_inserter(Worklist));
}
}
/// rewriteAllocBoxAsAllocStack - Replace uses of the alloc_box with a
/// new alloc_stack, but do not delete the alloc_box yet.
static bool rewriteAllocBoxAsAllocStack(AllocBoxInst *ABI) {
LLVM_DEBUG(llvm::dbgs() << "*** Promoting alloc_box to stack: " << *ABI);
SILValue HeapBox = ABI;
Optional<MarkUninitializedInst::Kind> Kind;
if (HeapBox->hasOneUse()) {
auto *User = HeapBox->getSingleUse()->getUser();
if (auto *MUI = dyn_cast<MarkUninitializedInst>(User)) {
HeapBox = MUI;
Kind = MUI->getKind();
}
}
llvm::SmallVector<SILInstruction *, 4> FinalReleases;
if (!getFinalReleases(HeapBox, FinalReleases))
return false;
// Promote this alloc_box to an alloc_stack. Insert the alloc_stack
// at the beginning of the function.
SILBuilderWithScope Builder(ABI);
assert(ABI->getBoxType()->getLayout()->getFields().size() == 1
&& "rewriting multi-field box not implemented");
auto *ASI = Builder.createAllocStack(
ABI->getLoc(), ABI->getBoxType()->getFieldType(ABI->getModule(), 0),
ABI->getVarInfo());
// Transfer a mark_uninitialized if we have one.
SILValue StackBox = ASI;
if (Kind) {
StackBox =
Builder.createMarkUninitialized(ASI->getLoc(), ASI, Kind.getValue());
}
// Replace all uses of the address of the box's contained value with
// the address of the stack location.
replaceProjectBoxUsers(HeapBox, StackBox);
assert(ABI->getBoxType()->getLayout()->getFields().size() == 1
&& "promoting multi-field box not implemented");
auto &Lowering = ABI->getModule()
.getTypeLowering(ABI->getBoxType()->getFieldType(ABI->getModule(), 0));
auto Loc = CleanupLocation::get(ABI->getLoc());
for (auto LastRelease : FinalReleases) {
SILBuilderWithScope Builder(LastRelease);
if (!isa<DeallocBoxInst>(LastRelease)&& !Lowering.isTrivial()) {
// For non-trivial types, insert destroys for each final release-like
// instruction we found that isn't an explicit dealloc_box.
Builder.emitDestroyAddrAndFold(Loc, StackBox);
}
Builder.createDeallocStack(Loc, ASI);
}
// Remove any retain and release instructions. Since all uses of project_box
// are gone, this only walks through uses of the box itself (the retain count
// pointer).
llvm::SmallVector<SILInstruction *, 8> Worklist;
std::transform(ABI->use_begin(), ABI->use_end(), std::back_inserter(Worklist),
[](Operand *Op) -> SILInstruction * { return Op->getUser(); });
while (!Worklist.empty()) {
auto *User = Worklist.pop_back_val();
// Look through any mark_uninitialized, copy_values.
if (isa<MarkUninitializedInst>(User) || isa<CopyValueInst>(User)) {
auto Inst = cast<SingleValueInstruction>(User);
transform(Inst->getUses(), std::back_inserter(Worklist),
[](Operand *Op) -> SILInstruction * { return Op->getUser(); });
Inst->replaceAllUsesWithUndef();
Inst->eraseFromParent();
continue;
}
assert(isa<StrongReleaseInst>(User) || isa<StrongRetainInst>(User) ||
isa<DeallocBoxInst>(User) || isa<ProjectBoxInst>(User) ||
isa<DestroyValueInst>(User));
User->eraseFromParent();
}
return true;
}
namespace {
/// \brief A SILCloner subclass which clones a closure function while
/// promoting some of its box parameters to stack addresses.
class PromotedParamCloner : public SILClonerWithScopes<PromotedParamCloner> {
public:
friend class SILInstructionVisitor<PromotedParamCloner>;
friend class SILCloner<PromotedParamCloner>;
PromotedParamCloner(SILOptFunctionBuilder &FuncBuilder, SILFunction *Orig, IsSerialized_t Serialized,
ArgIndexList &PromotedArgIndices,
llvm::StringRef ClonedName);
void populateCloned();
SILFunction *getCloned() { return &getBuilder().getFunction(); }
private:
static SILFunction *initCloned(SILOptFunctionBuilder &FuncBuilder,
SILFunction *Orig, IsSerialized_t Serialized,
ArgIndexList &PromotedArgIndices,
llvm::StringRef ClonedName);
void visitStrongReleaseInst(StrongReleaseInst *Inst);
void visitDestroyValueInst(DestroyValueInst *Inst);
void visitStrongRetainInst(StrongRetainInst *Inst);
void visitCopyValueInst(CopyValueInst *Inst);
void visitProjectBoxInst(ProjectBoxInst *Inst);
SILFunction *Orig;
ArgIndexList &PromotedArgIndices;
// The values in the original function that are promoted to stack
// references.
llvm::SmallSet<SILValue, 4> PromotedParameters;
};
} // end anonymous namespace
PromotedParamCloner::PromotedParamCloner(SILOptFunctionBuilder &FuncBuilder,
SILFunction *Orig,
IsSerialized_t Serialized,
ArgIndexList &PromotedArgIndices,
llvm::StringRef ClonedName)
: SILClonerWithScopes<PromotedParamCloner>(
*initCloned(FuncBuilder, Orig, Serialized, PromotedArgIndices,
ClonedName)),
Orig(Orig), PromotedArgIndices(PromotedArgIndices) {
assert(Orig->getDebugScope()->getParentFunction() !=
getCloned()->getDebugScope()->getParentFunction());
}
static std::string getClonedName(SILFunction *F, IsSerialized_t Serialized,
ArgIndexList &PromotedArgIndices) {
auto P = Demangle::SpecializationPass::AllocBoxToStack;
Mangle::FunctionSignatureSpecializationMangler Mangler(P, Serialized, F);
for (unsigned i : PromotedArgIndices) {
Mangler.setArgumentBoxToStack(i);
}
return Mangler.mangle();
}
/// \brief Create the function corresponding to the clone of the
/// original closure with the signature modified to reflect promoted
/// parameters (which are specified by PromotedArgIndices).
SILFunction *PromotedParamCloner::
initCloned(SILOptFunctionBuilder &FuncBuilder, SILFunction *Orig,
IsSerialized_t Serialized, ArgIndexList &PromotedArgIndices,
llvm::StringRef ClonedName) {
SILModule &M = Orig->getModule();
SmallVector<SILParameterInfo, 4> ClonedInterfaceArgTys;
// Generate a new parameter list with deleted parameters removed.
SILFunctionType *OrigFTI = Orig->getLoweredFunctionType();
unsigned Index = Orig->getConventions().getSILArgIndexOfFirstParam();
for (auto ¶m : OrigFTI->getParameters()) {
if (count(PromotedArgIndices, Index)) {
auto boxTy = param.getSILStorageType().castTo<SILBoxType>();
assert(boxTy->getLayout()->getFields().size() == 1
&& "promoting compound box not implemented");
SILType paramTy;
{
Lowering::GenericContextScope scope(Orig->getModule().Types,
OrigFTI->getGenericSignature());
paramTy = boxTy->getFieldType(Orig->getModule(), 0);
}
auto promotedParam = SILParameterInfo(paramTy.getASTType(),
ParameterConvention::Indirect_InoutAliasable);
ClonedInterfaceArgTys.push_back(promotedParam);
} else {
ClonedInterfaceArgTys.push_back(param);
}
++Index;
}
// Create the new function type for the cloned function with some of
// the parameters promoted.
auto ClonedTy = SILFunctionType::get(
OrigFTI->getGenericSignature(), OrigFTI->getExtInfo(),
OrigFTI->getCoroutineKind(), OrigFTI->getCalleeConvention(),
ClonedInterfaceArgTys, OrigFTI->getYields(),
OrigFTI->getResults(), OrigFTI->getOptionalErrorResult(),
M.getASTContext(), OrigFTI->getWitnessMethodConformanceOrNone());
assert((Orig->isTransparent() || Orig->isBare() || Orig->getLocation())
&& "SILFunction missing location");
assert((Orig->isTransparent() || Orig->isBare() || Orig->getDebugScope())
&& "SILFunction missing DebugScope");
assert(!Orig->isGlobalInit() && "Global initializer cannot be cloned");
auto *Fn = FuncBuilder.createFunction(
SILLinkage::Shared, ClonedName, ClonedTy, Orig->getGenericEnvironment(),
Orig->getLocation(), Orig->isBare(), IsNotTransparent, Serialized,
Orig->getEntryCount(), Orig->isThunk(), Orig->getClassSubclassScope(),
Orig->getInlineStrategy(), Orig->getEffectsKind(), Orig,
Orig->getDebugScope());
for (auto &Attr : Orig->getSemanticsAttrs()) {
Fn->addSemanticsAttr(Attr);
}
if (!Orig->hasQualifiedOwnership()) {
Fn->setUnqualifiedOwnership();
}
return Fn;
}
/// \brief Populate the body of the cloned closure, modifying instructions as
/// necessary to take into consideration the removed parameters.
void
PromotedParamCloner::populateCloned() {
SILFunction *Cloned = getCloned();
// Create arguments for the entry block
SILBasicBlock *OrigEntryBB = &*Orig->begin();
SILBasicBlock *ClonedEntryBB = Cloned->createBasicBlock();
unsigned ArgNo = 0;
auto I = OrigEntryBB->args_begin(), E = OrigEntryBB->args_end();
while (I != E) {
if (count(PromotedArgIndices, ArgNo)) {
// Create a new argument with the promoted type.
auto boxTy = (*I)->getType().castTo<SILBoxType>();
assert(boxTy->getLayout()->getFields().size() == 1
&& "promoting multi-field boxes not implemented yet");
auto promotedTy = boxTy->getFieldType(Cloned->getModule(), 0);
auto *promotedArg =
ClonedEntryBB->createFunctionArgument(promotedTy, (*I)->getDecl());
PromotedParameters.insert(*I);
// Map any projections of the box to the promoted argument.
for (auto use : (*I)->getUses()) {
if (auto project = dyn_cast<ProjectBoxInst>(use->getUser())) {
ValueMap.insert(std::make_pair(project, promotedArg));
}
}
} else {
// Create a new argument which copies the original argument.
SILValue MappedValue = ClonedEntryBB->createFunctionArgument(
(*I)->getType(), (*I)->getDecl());
ValueMap.insert(std::make_pair(*I, MappedValue));
}
++ArgNo;
++I;
}
getBuilder().setInsertionPoint(ClonedEntryBB);
BBMap.insert(std::make_pair(OrigEntryBB, ClonedEntryBB));
// Recursively visit original BBs in depth-first preorder, starting with the
// entry block, cloning all instructions other than terminators.
visitSILBasicBlock(OrigEntryBB);
// Now iterate over the BBs and fix up the terminators.
for (auto BI = BBMap.begin(), BE = BBMap.end(); BI != BE; ++BI) {
getBuilder().setInsertionPoint(BI->second);
visit(BI->first->getTerminator());
}
}
/// \brief Handle a strong_release instruction during cloning of a closure; if
/// it is a strong release of a promoted box argument, then it is replaced with
/// a ReleaseValue of the new object type argument, otherwise it is handled
/// normally.
void
PromotedParamCloner::visitStrongReleaseInst(StrongReleaseInst *Inst) {
// If it's a release of a promoted parameter, just drop the instruction.
if (PromotedParameters.count(Inst->getOperand()))
return;
SILCloner<PromotedParamCloner>::visitStrongReleaseInst(Inst);
}
/// \brief Handle a strong_release instruction during cloning of a closure; if
/// it is a strong release of a promoted box argument, then it is replaced with
/// a ReleaseValue of the new object type argument, otherwise it is handled
/// normally.
void PromotedParamCloner::visitDestroyValueInst(DestroyValueInst *Inst) {
// If we are a destroy of a promoted parameter, just drop the instruction. We
// look through copy_value to preserve current behavior.
SILInstruction *Tmp = Inst;
while (auto *CopyOp = dyn_cast<CopyValueInst>(Tmp->getOperand(0))) {
Tmp = CopyOp;
}
if (PromotedParameters.count(Tmp->getOperand(0)))
return;
SILCloner<PromotedParamCloner>::visitDestroyValueInst(Inst);
}
void
PromotedParamCloner::visitStrongRetainInst(StrongRetainInst *Inst) {
// If it's a retain of a promoted parameter, just drop the instruction.
if (PromotedParameters.count(Inst->getOperand()))
return;
SILCloner<PromotedParamCloner>::visitStrongRetainInst(Inst);
}
void PromotedParamCloner::visitCopyValueInst(CopyValueInst *CVI) {
// If it's a copy of a promoted parameter, just drop the instruction.
auto *Tmp = CVI;
while (auto *CopyOp = dyn_cast<CopyValueInst>(Tmp->getOperand())) {
Tmp = CopyOp;
}
if (PromotedParameters.count(Tmp->getOperand()))
return;
SILCloner<PromotedParamCloner>::visitCopyValueInst(CVI);
}
void PromotedParamCloner::visitProjectBoxInst(ProjectBoxInst *Inst) {
// If it's a projection of a promoted parameter, drop the instruction.
// Its uses will be replaced by the promoted address.
// and replace its uses with
if (PromotedParameters.count(Inst->getOperand()))
return;
SILCloner<PromotedParamCloner>::visitProjectBoxInst(Inst);
}
/// Specialize a partial_apply by promoting the parameters indicated by
/// indices. We expect these parameters to be replaced by stack address
/// references.
static PartialApplyInst *
specializePartialApply(SILOptFunctionBuilder &FuncBuilder,
PartialApplyInst *PartialApply,
ArgIndexList &PromotedCalleeArgIndices,
AllocBoxToStackState &pass) {
auto *FRI = cast<FunctionRefInst>(PartialApply->getCallee());
assert(FRI && "Expected a direct partial_apply!");
auto *F = FRI->getReferencedFunction();
assert(F && "Expected a referenced function!");
IsSerialized_t Serialized = IsNotSerialized;
if (PartialApply->getFunction()->isSerialized())
Serialized = IsSerializable;
std::string ClonedName =
getClonedName(F, Serialized, PromotedCalleeArgIndices);
auto &M = PartialApply->getModule();
SILFunction *ClonedFn;
if (auto *PrevFn = M.lookUpFunction(ClonedName)) {
assert(PrevFn->isSerialized() == Serialized);
ClonedFn = PrevFn;
} else {
// Clone the function the existing partial_apply references.
PromotedParamCloner Cloner(FuncBuilder, F, Serialized,
PromotedCalleeArgIndices,
ClonedName);
Cloner.populateCloned();
ClonedFn = Cloner.getCloned();
pass.T->addFunctionToPassManagerWorklist(ClonedFn, F);
}
// Now create the new partial_apply using the cloned function.
llvm::SmallVector<SILValue, 16> Args;
ValueLifetimeAnalysis::Frontier PAFrontier;
// Promote the arguments that need promotion.
for (auto &O : PartialApply->getArgumentOperands()) {
auto CalleeArgIndex = ApplySite(O.getUser()).getCalleeArgIndex(O);
if (!count(PromotedCalleeArgIndices, CalleeArgIndex)) {
Args.push_back(O.get());
continue;
}
// If this argument is promoted, it is a box that we're turning into an
// address because we've proven we can keep this value on the stack. The
// partial_apply had ownership of this box so we must now release it
// explicitly when the partial_apply is released.
auto *Box = cast<SingleValueInstruction>(O.get());
assert((isa<AllocBoxInst>(Box) || isa<CopyValueInst>(Box)) &&
"Expected either an alloc box or a copy of an alloc box");
SILBuilder B(Box);
Args.push_back(B.createProjectBox(Box->getLoc(), Box, 0));
if (PAFrontier.empty()) {
ValueLifetimeAnalysis VLA(PartialApply);
pass.CFGChanged |= !VLA.computeFrontier(
PAFrontier, ValueLifetimeAnalysis::AllowToModifyCFG);
assert(!PAFrontier.empty() && "partial_apply must have at least one use "
"to release the returned function");
}
// Insert destroys of the box at each point where the partial_apply becomes
// dead.
for (SILInstruction *FrontierInst : PAFrontier) {
SILBuilderWithScope Builder(FrontierInst);
Builder.createDestroyValue(PartialApply->getLoc(), Box);
}
}
SILBuilderWithScope Builder(PartialApply);
// Build the function_ref and partial_apply.
SILValue FunctionRef = Builder.createFunctionRef(PartialApply->getLoc(),
ClonedFn);
return Builder.createPartialApply(
PartialApply->getLoc(), FunctionRef, PartialApply->getSubstitutionMap(),
Args,
PartialApply->getType().getAs<SILFunctionType>()->getCalleeConvention());
}
static void rewritePartialApplies(AllocBoxToStackState &pass) {
llvm::DenseMap<PartialApplyInst *, ArgIndexList> IndexMap;
ArgIndexList Indices;
// Build a map from partial_apply to the indices of the operands
// that will be promoted in our rewritten version.
for (auto *O : pass.PromotedOperands) {
auto CalleeArgIndexNumber = ApplySite(O->getUser()).getCalleeArgIndex(*O);
Indices.clear();
Indices.push_back(CalleeArgIndexNumber);
auto *PartialApply = cast<PartialApplyInst>(O->getUser());
llvm::DenseMap<PartialApplyInst *, ArgIndexList>::iterator It;
bool Inserted;
std::tie(It, Inserted) = IndexMap.insert(std::make_pair(PartialApply,
Indices));
if (!Inserted)
It->second.push_back(CalleeArgIndexNumber);
}
// Clone the referenced function of each partial_apply, removing the
// operands that we will not need, and remove the existing
// partial_apply.
SILOptFunctionBuilder FuncBuilder(*pass.T);
for (auto &It : IndexMap) {
auto *PartialApply = It.first;
auto &Indices = It.second;
// Sort the indices and unique them.
std::sort(Indices.begin(), Indices.end());
Indices.erase(std::unique(Indices.begin(), Indices.end()), Indices.end());
PartialApplyInst *Replacement =
specializePartialApply(FuncBuilder, PartialApply, Indices, pass);
PartialApply->replaceAllUsesWith(Replacement);
auto *FRI = cast<FunctionRefInst>(PartialApply->getCallee());
PartialApply->eraseFromParent();
// TODO: Erase from module if there are no more uses.
if (FRI->use_empty())
FRI->eraseFromParent();
}
}
/// Clone closure bodies and rewrite partial applies. Returns the number of
/// alloc_box allocations promoted.
static unsigned rewritePromotedBoxes(AllocBoxToStackState &pass) {
// First we'll rewrite any partial applies that we can to remove the
// box container pointer from the operands.
rewritePartialApplies(pass);
unsigned Count = 0;
auto rend = pass.Promotable.rend();
for (auto I = pass.Promotable.rbegin(); I != rend; ++I) {
auto *ABI = *I;
if (rewriteAllocBoxAsAllocStack(ABI)) {
++Count;
ABI->eraseFromParent();
}
}
return Count;
}
namespace {
class AllocBoxToStack : public SILFunctionTransform {
/// The entry point to the transformation.
void run() override {
// Don't rerun on deserialized functions. Nothing should have changed.
if (getFunction()->wasDeserializedCanonical())
return;
AllocBoxToStackState pass(this);
for (auto &BB : *getFunction()) {
for (auto &I : BB)
if (auto *ABI = dyn_cast<AllocBoxInst>(&I))
if (canPromoteAllocBox(ABI, pass.PromotedOperands))
pass.Promotable.push_back(ABI);
}
if (!pass.Promotable.empty()) {
auto Count = rewritePromotedBoxes(pass);
NumStackPromoted += Count;
if (Count) {
StackNesting SN;
if (SN.correctStackNesting(getFunction()) == StackNesting::Changes::CFG)
pass.CFGChanged = true;
}
invalidateAnalysis(
pass.CFGChanged
? SILAnalysis::InvalidationKind::FunctionBody
: SILAnalysis::InvalidationKind::CallsAndInstructions);
}
}
};
} // end anonymous namespace
SILTransform *swift::createAllocBoxToStack() {
return new AllocBoxToStack();
}
|
/***************************************************************
* Name: IUserModel.cpp
* Purpose: Code AWServiceCommonData
* Author: David Lecoconnier (david.lecoconnier@free.fr)
* Created: 2016-09-27
* Copyright: David Lecoconnier (http://www.getfux.fr)
* License:
**************************************************************/
#include "IUserModel.h"
using namespace AWS;
IUserModel::IUserModel(const std::string& name) :
m_name(name)
{
//ctor
}
IUserModel::~IUserModel()
{
//dtor
}
const std::string& IUserModel::getName() const
{
return m_name;
}
|
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads
// UNSUPPORTED: c++03, c++11
// This test requires the dylib support introduced in D68480, which shipped in
// macOS 11.0.
// XFAIL: use_system_cxx_lib && x86_64-apple-macosx10.15
// XFAIL: use_system_cxx_lib && x86_64-apple-macosx10.14
// XFAIL: use_system_cxx_lib && x86_64-apple-macosx10.13
// XFAIL: use_system_cxx_lib && x86_64-apple-macosx10.12
// XFAIL: use_system_cxx_lib && x86_64-apple-macosx10.11
// XFAIL: use_system_cxx_lib && x86_64-apple-macosx10.10
// XFAIL: use_system_cxx_lib && x86_64-apple-macosx10.9
// <semaphore>
#include <cassert>
#include <semaphore>
#include <thread>
#include "make_test_thread.h"
#include "test_macros.h"
int main(int, char**)
{
std::counting_semaphore<> s(1);
assert(s.try_acquire());
s.release();
assert(s.try_acquire());
s.release(2);
std::thread t = support::make_test_thread([&](){
assert(s.try_acquire());
});
t.join();
assert(s.try_acquire());
return 0;
}
|
#include "PlayerEntity.h"
#include "Engine.h"
#include "MapManager.h"
#include "CreatureManager.h"
#include "FireballEntity.h"
#include "GamePlayLogicEntity.h"
#include <Windows.h>
#include <cstdio>
#include <glm/glm.hpp>
#include <glm/gtx/transform.hpp>
#include <cmath>
using namespace glm;
void PlayerEntity::OnCreate()
{
camera = engine->GetCamera();
mouseScaleX = 0.001f;
mouseScaleY = 0.001f;
turnSpeed = 2.0f;
MeshEntity* meshEntity = dynamic_cast<MeshEntity*>(engine->CreateEntity("MeshEntity"));
meshEntity->LoadMeshFromFile("assets/sword.mesh");
meshEntity->SetParent(this);
meshEntity->SetPosition(0.2f, -0.15f, 0.6f);
meshEntity->SetScale(0.2f, 0.2f, 0.2f);
}
void PlayerEntity::OnUpdate(float deltaTime)
{
constexpr float angle90 = 3.1415926f * 0.5f;
vec3 pos = vec3(GetPositionX(), GetPositionY(), GetPositionZ());
if (HP < MaxHP)
{
recoverTimer += deltaTime;
if (recoverTimer > 1.0f)
{
recoverTimer -= 1.0f;
HP++;
}
}
if (flyingTimer > 0.0f)
{
flyingTimer -= deltaTime;
vec3 dir = vec3(flyingDirX, 0.0f, flyingDirZ);
pos += dir * 4.0f * deltaTime;
MapManager::instance()->CollideWithMap(pos.x, pos.y, Radius);
SetPositionX(pos.x);
SetPositionZ(pos.z);
}
else
{
float anglePitch = GetRotationX();
float angleYaw = GetRotationY();
angleYaw += engine->GetMousePositionDeltaX() * mouseScaleX;
anglePitch += engine->GetMousePositionDeltaY() * mouseScaleY;
if (anglePitch > angle90)
anglePitch = angle90;
else if (anglePitch < -angle90)
anglePitch = -angle90;
if (engine->IsKeyDown('A')) {
pos.x -= deltaTime * Speed * cos(angleYaw);
pos.z += deltaTime * Speed * sin(angleYaw);
}
else if (engine->IsKeyDown('D')) {
pos.x += deltaTime * Speed * cos(angleYaw);
pos.z -= deltaTime * Speed * sin(angleYaw);
}
if (engine->IsKeyDown('W'))
{
pos.x += deltaTime * Speed * sin(angleYaw);
pos.z += deltaTime * Speed * cos(angleYaw);
}
else if (engine->IsKeyDown('S'))
{
pos.x -= deltaTime * Speed * sin(angleYaw);
pos.z -= deltaTime * Speed * cos(angleYaw);
}
MapManager::instance()->CollideWithMap(pos.x, pos.z, Radius);
if (MapManager::instance()->IsInExit(pos.x, pos.z))
{
MapManager::instance()->SetVisible(false);
CreatureManager::instance()->ShutDown();
GamePlayLogicEntity::instance()->SetGameWin();
}
SetPositionX(pos.x);
SetPositionZ(pos.z);
SetRotationX(anglePitch);
SetRotationY(angleYaw);
}
UpdateWorldMatrix();
const mat4& worldMat = *reinterpret_cast<const mat4*>(GetWorldMatrix());
camera->SetViewMatrix(reinterpret_cast<float*>(&(inverse(worldMat))));
if (flyingTimer <= 0.0f)
{
if (fireCoolDown > 0.0f)
{
fireCoolDown -= deltaTime;
}
else if (engine->IsKeyDown(VK_LBUTTON))
{
fireCoolDown = 0.5f;
FireballEntity* fireball = dynamic_cast<FireballEntity*>(engine->CreateEntity("FireballEntity"));
fireball->SetOwner(this);
vec4 worldPos = vec4(pos, 1.0f);
vec4 frontPos = worldMat * vec4(0.0f, 0.0f, 1.0f, 1.0f);
vec3 dir = normalize(vec3(frontPos - worldPos));
fireball->SetPosition(frontPos.x, frontPos.y, frontPos.z);
fireball->SetDirection(dir.x, dir.y, dir.z);
}
}
}
#pragma warning(disable: 4996) // we are not using sprintf_s
void PlayerEntity::OnOverlay()
{
float color[] = { 1.0f, 0.0f, 0.0f };
char buf[16];
sprintf(buf, "HP%d", HP);
Engine::instance()->PrintText(2, -8, buf, false, color);
}
void PlayerEntity::OnDamage(int damage)
{
}
void PlayerEntity::OnDie()
{
MapManager::instance()->SetVisible(false);
CreatureManager::instance()->ShutDown();
GamePlayLogicEntity::instance()->SetGameLose();
}
void PlayerEntity::OnHit(HitInfo * hitInfo)
{
flyingTimer = 0.5f;
flyingDirX = -hitInfo->dirX;
flyingDirY = -hitInfo->dirY;
flyingDirZ = -hitInfo->dirZ;
}
|
/*Exercise 3 - Repeatition
Convert the C program given below which calculates the Factorial of a number that you input from the keyboard to a C++ program.
Please Note that the input command in C++ is std::cin. This is a representation of the Keyboard.*/
#include<stdio.h>
#include<iostream>
int main()
{
int no;
long fac;
printf("Enter a Number : ");
scanf("%d", &no);
cout<<"Enter a Number :";
cin>>no;
fac = 1;
for (int r=no; r >= 1; r--) {
fac = fac * r;
}
printf("Factorial of %d is %ld\n", no, fac);
cout<<"Factorial of "<<no<<" is "<<fac<<endl;
return 0;
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "util.h"
#include "sync.h"
#include "strlcpy.h"
#include "version.h"
#include "ui_interface.h"
#include <boost/algorithm/string/join.hpp>
// Work around clang compilation problem in Boost 1.46:
// /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup
// See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
// http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
namespace boost {
namespace program_options {
std::string to_internal(const std::string&);
}
}
#include <boost/program_options/detail/config_file.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/foreach.hpp>
#include <boost/thread.hpp>
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include <stdarg.h>
#ifdef WIN32
#ifdef _MSC_VER
#pragma warning(disable:4786)
#pragma warning(disable:4804)
#pragma warning(disable:4805)
#pragma warning(disable:4717)
#endif
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <io.h> /* for _commit */
#include "shlobj.h"
#elif defined(__linux__)
# include <sys/prctl.h>
#endif
#ifndef WIN32
#include <execinfo.h>
#endif
using namespace std;
map<string, string> mapArgs;
map<string, vector<string> > mapMultiArgs;
bool fDebug = false;
bool fDebugNet = false;
bool fPrintToConsole = false;
bool fPrintToDebugger = false;
bool fRequestShutdown = false;
bool fShutdown = false;
bool fDaemon = false;
bool fServer = false;
bool fCommandLine = false;
string strMiscWarning;
bool fTestNet = false;
bool fNoListen = false;
bool fLogTimestamps = false;
CMedianFilter<int64_t> vTimeOffsets(200,0);
bool fReopenDebugLog = false;
// Init OpenSSL library multithreading support
static CCriticalSection** ppmutexOpenSSL;
void locking_callback(int mode, int i, const char* file, int line)
{
if (mode & CRYPTO_LOCK) {
ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
} else {
LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
}
}
LockedPageManager LockedPageManager::instance;
// Init
class CInit
{
public:
CInit()
{
// Init OpenSSL library multithreading support
ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
for (int i = 0; i < CRYPTO_num_locks(); i++)
ppmutexOpenSSL[i] = new CCriticalSection();
CRYPTO_set_locking_callback(locking_callback);
#ifdef WIN32
// Seed random number generator with screen scrape and other hardware sources
RAND_screen();
#endif
// Seed random number generator with performance counter
RandAddSeed();
}
~CInit()
{
// Shutdown OpenSSL library multithreading support
CRYPTO_set_locking_callback(NULL);
for (int i = 0; i < CRYPTO_num_locks(); i++)
delete ppmutexOpenSSL[i];
OPENSSL_free(ppmutexOpenSSL);
}
}
instance_of_cinit;
void RandAddSeed()
{
// Seed with CPU performance counter
int64_t nCounter = GetPerformanceCounter();
RAND_add(&nCounter, sizeof(nCounter), 1.5);
memset(&nCounter, 0, sizeof(nCounter));
}
void RandAddSeedPerfmon()
{
RandAddSeed();
// This can take up to 2 seconds, so only do it every 10 minutes
static int64_t nLastPerfmon;
if (GetTime() < nLastPerfmon + 10 * 60)
return;
nLastPerfmon = GetTime();
#ifdef WIN32
// Don't need this on Linux, OpenSSL automatically uses /dev/urandom
// Seed with the entire set of perfmon data
unsigned char pdata[250000];
memset(pdata, 0, sizeof(pdata));
unsigned long nSize = sizeof(pdata);
long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
RegCloseKey(HKEY_PERFORMANCE_DATA);
if (ret == ERROR_SUCCESS)
{
RAND_add(pdata, nSize, nSize/100.0);
memset(pdata, 0, nSize);
printf("RandAddSeed() %lu bytes\n", nSize);
}
#endif
}
uint64_t GetRand(uint64_t nMax)
{
if (nMax == 0)
return 0;
// The range of the random source must be a multiple of the modulus
// to give every possible output value an equal possibility
uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax;
uint64_t nRand = 0;
do
RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
while (nRand >= nRange);
return (nRand % nMax);
}
int GetRandInt(int nMax)
{
return GetRand(nMax);
}
uint256 GetRandHash()
{
uint256 hash;
RAND_bytes((unsigned char*)&hash, sizeof(hash));
return hash;
}
static FILE* fileout = NULL;
inline int OutputDebugStringF(const char* pszFormat, ...)
{
int ret = 0;
if (fPrintToConsole)
{
// print to console
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
ret = vprintf(pszFormat, arg_ptr);
va_end(arg_ptr);
}
else if (!fPrintToDebugger)
{
// print to debug.log
if (!fileout)
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
fileout = fopen(pathDebug.string().c_str(), "a");
if (fileout) setbuf(fileout, NULL); // unbuffered
}
if (fileout)
{
static bool fStartedNewLine = true;
// This routine may be called by global destructors during shutdown.
// Since the order of destruction of static/global objects is undefined,
// allocate mutexDebugLog on the heap the first time this routine
// is called to avoid crashes during shutdown.
static boost::mutex* mutexDebugLog = NULL;
if (mutexDebugLog == NULL) mutexDebugLog = new boost::mutex();
boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
// reopen the log file, if requested
if (fReopenDebugLog) {
fReopenDebugLog = false;
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
setbuf(fileout, NULL); // unbuffered
}
// Debug print useful for profiling
if (fLogTimestamps && fStartedNewLine)
fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
if (pszFormat[strlen(pszFormat) - 1] == '\n')
fStartedNewLine = true;
else
fStartedNewLine = false;
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
ret = vfprintf(fileout, pszFormat, arg_ptr);
va_end(arg_ptr);
}
}
#ifdef WIN32
if (fPrintToDebugger)
{
static CCriticalSection cs_OutputDebugStringF;
// accumulate and output a line at a time
{
LOCK(cs_OutputDebugStringF);
static std::string buffer;
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
buffer += vstrprintf(pszFormat, arg_ptr);
va_end(arg_ptr);
int line_start = 0, line_end;
while((line_end = buffer.find('\n', line_start)) != -1)
{
OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str());
line_start = line_end + 1;
}
buffer.erase(0, line_start);
}
}
#endif
return ret;
}
string vstrprintf(const char *format, va_list ap)
{
char buffer[50000];
char* p = buffer;
int limit = sizeof(buffer);
int ret;
while (true)
{
va_list arg_ptr;
va_copy(arg_ptr, ap);
#ifdef WIN32
ret = _vsnprintf(p, limit, format, arg_ptr);
#else
ret = vsnprintf(p, limit, format, arg_ptr);
#endif
va_end(arg_ptr);
if (ret >= 0 && ret < limit)
break;
if (p != buffer)
delete[] p;
limit *= 2;
p = new char[limit];
if (p == NULL)
throw std::bad_alloc();
}
string str(p, p+ret);
if (p != buffer)
delete[] p;
return str;
}
string real_strprintf(const char *format, int dummy, ...)
{
va_list arg_ptr;
va_start(arg_ptr, dummy);
string str = vstrprintf(format, arg_ptr);
va_end(arg_ptr);
return str;
}
string real_strprintf(const std::string &format, int dummy, ...)
{
va_list arg_ptr;
va_start(arg_ptr, dummy);
string str = vstrprintf(format.c_str(), arg_ptr);
va_end(arg_ptr);
return str;
}
bool error(const char *format, ...)
{
va_list arg_ptr;
va_start(arg_ptr, format);
std::string str = vstrprintf(format, arg_ptr);
va_end(arg_ptr);
printf("ERROR: %s\n", str.c_str());
return false;
}
void ParseString(const string& str, char c, vector<string>& v)
{
if (str.empty())
return;
string::size_type i1 = 0;
string::size_type i2;
while (true)
{
i2 = str.find(c, i1);
if (i2 == str.npos)
{
v.push_back(str.substr(i1));
return;
}
v.push_back(str.substr(i1, i2-i1));
i1 = i2+1;
}
}
string FormatMoney(int64_t n, bool fPlus)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
int64_t n_abs = (n > 0 ? n : -n);
int64_t quotient = n_abs/COIN;
int64_t remainder = n_abs%COIN;
string str = strprintf("%"PRId64".%08"PRId64, quotient, remainder);
// Right-trim excess zeros before the decimal point:
int nTrim = 0;
for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
++nTrim;
if (nTrim)
str.erase(str.size()-nTrim, nTrim);
if (n < 0)
str.insert((unsigned int)0, 1, '-');
else if (fPlus && n > 0)
str.insert((unsigned int)0, 1, '+');
return str;
}
bool ParseMoney(const string& str, int64_t& nRet)
{
return ParseMoney(str.c_str(), nRet);
}
bool ParseMoney(const char* pszIn, int64_t& nRet)
{
string strWhole;
int64_t nUnits = 0;
const char* p = pszIn;
while (isspace(*p))
p++;
for (; *p; p++)
{
if (*p == '.')
{
p++;
int64_t nMult = CENT*10;
while (isdigit(*p) && (nMult > 0))
{
nUnits += nMult * (*p++ - '0');
nMult /= 10;
}
break;
}
if (isspace(*p))
break;
if (!isdigit(*p))
return false;
strWhole.insert(strWhole.end(), *p);
}
for (; *p; p++)
if (!isspace(*p))
return false;
if (strWhole.size() > 10) // guard against 63 bit overflow
return false;
if (nUnits < 0 || nUnits > COIN)
return false;
int64_t nWhole = atoi64(strWhole);
int64_t nValue = nWhole*COIN + nUnits;
nRet = nValue;
return true;
}
static const signed char phexdigit[256] =
{ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
bool IsHex(const string& str)
{
BOOST_FOREACH(unsigned char c, str)
{
if (phexdigit[c] < 0)
return false;
}
return (str.size() > 0) && (str.size()%2 == 0);
}
vector<unsigned char> ParseHex(const char* psz)
{
// convert hex dump to vector
vector<unsigned char> vch;
while (true)
{
while (isspace(*psz))
psz++;
signed char c = phexdigit[(unsigned char)*psz++];
if (c == (signed char)-1)
break;
unsigned char n = (c << 4);
c = phexdigit[(unsigned char)*psz++];
if (c == (signed char)-1)
break;
n |= c;
vch.push_back(n);
}
return vch;
}
vector<unsigned char> ParseHex(const string& str)
{
return ParseHex(str.c_str());
}
static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
{
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
if (name.find("-no") == 0)
{
std::string positive("-");
positive.append(name.begin()+3, name.end());
if (mapSettingsRet.count(positive) == 0)
{
bool value = !GetBoolArg(name);
mapSettingsRet[positive] = (value ? "1" : "0");
}
}
}
void ParseParameters(int argc, const char* const argv[])
{
mapArgs.clear();
mapMultiArgs.clear();
for (int i = 1; i < argc; i++)
{
char psz[10000];
strlcpy(psz, argv[i], sizeof(psz));
char* pszValue = (char*)"";
if (strchr(psz, '='))
{
pszValue = strchr(psz, '=');
*pszValue++ = '\0';
}
#ifdef WIN32
_strlwr(psz);
if (psz[0] == '/')
psz[0] = '-';
#endif
if (psz[0] != '-')
break;
mapArgs[psz] = pszValue;
mapMultiArgs[psz].push_back(pszValue);
}
// New 0.6 features:
BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
{
string name = entry.first;
// interpret --foo as -foo (as long as both are not set)
if (name.find("--") == 0)
{
std::string singleDash(name.begin()+1, name.end());
if (mapArgs.count(singleDash) == 0)
mapArgs[singleDash] = entry.second;
name = singleDash;
}
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
InterpretNegativeSetting(name, mapArgs);
}
}
std::string GetArg(const std::string& strArg, const std::string& strDefault)
{
if (mapArgs.count(strArg))
return mapArgs[strArg];
return strDefault;
}
int64_t GetArg(const std::string& strArg, int64_t nDefault)
{
if (mapArgs.count(strArg))
return atoi64(mapArgs[strArg]);
return nDefault;
}
bool GetBoolArg(const std::string& strArg, bool fDefault)
{
if (mapArgs.count(strArg))
{
if (mapArgs[strArg].empty())
return true;
return (atoi(mapArgs[strArg]) != 0);
}
return fDefault;
}
bool SoftSetArg(const std::string& strArg, const std::string& strValue)
{
if (mapArgs.count(strArg))
return false;
mapArgs[strArg] = strValue;
return true;
}
bool SoftSetBoolArg(const std::string& strArg, bool fValue)
{
if (fValue)
return SoftSetArg(strArg, std::string("1"));
else
return SoftSetArg(strArg, std::string("0"));
}
string EncodeBase64(const unsigned char* pch, size_t len)
{
static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
string strRet="";
strRet.reserve((len+2)/3*4);
int mode=0, left=0;
const unsigned char *pchEnd = pch+len;
while (pch<pchEnd)
{
int enc = *(pch++);
switch (mode)
{
case 0: // we have no bits
strRet += pbase64[enc >> 2];
left = (enc & 3) << 4;
mode = 1;
break;
case 1: // we have two bits
strRet += pbase64[left | (enc >> 4)];
left = (enc & 15) << 2;
mode = 2;
break;
case 2: // we have four bits
strRet += pbase64[left | (enc >> 6)];
strRet += pbase64[enc & 63];
mode = 0;
break;
}
}
if (mode)
{
strRet += pbase64[left];
strRet += '=';
if (mode == 1)
strRet += '=';
}
return strRet;
}
string EncodeBase64(const string& str)
{
return EncodeBase64((const unsigned char*)str.c_str(), str.size());
}
vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
{
static const int decode64_table[256] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
if (pfInvalid)
*pfInvalid = false;
vector<unsigned char> vchRet;
vchRet.reserve(strlen(p)*3/4);
int mode = 0;
int left = 0;
while (1)
{
int dec = decode64_table[(unsigned char)*p];
if (dec == -1) break;
p++;
switch (mode)
{
case 0: // we have no bits and get 6
left = dec;
mode = 1;
break;
case 1: // we have 6 bits and keep 4
vchRet.push_back((left<<2) | (dec>>4));
left = dec & 15;
mode = 2;
break;
case 2: // we have 4 bits and get 6, we keep 2
vchRet.push_back((left<<4) | (dec>>2));
left = dec & 3;
mode = 3;
break;
case 3: // we have 2 bits and get 6
vchRet.push_back((left<<6) | dec);
mode = 0;
break;
}
}
if (pfInvalid)
switch (mode)
{
case 0: // 4n base64 characters processed: ok
break;
case 1: // 4n+1 base64 character processed: impossible
*pfInvalid = true;
break;
case 2: // 4n+2 base64 characters processed: require '=='
if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
*pfInvalid = true;
break;
case 3: // 4n+3 base64 characters processed: require '='
if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
*pfInvalid = true;
break;
}
return vchRet;
}
string DecodeBase64(const string& str)
{
vector<unsigned char> vchRet = DecodeBase64(str.c_str());
return string((const char*)&vchRet[0], vchRet.size());
}
string EncodeBase32(const unsigned char* pch, size_t len)
{
static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
string strRet="";
strRet.reserve((len+4)/5*8);
int mode=0, left=0;
const unsigned char *pchEnd = pch+len;
while (pch<pchEnd)
{
int enc = *(pch++);
switch (mode)
{
case 0: // we have no bits
strRet += pbase32[enc >> 3];
left = (enc & 7) << 2;
mode = 1;
break;
case 1: // we have three bits
strRet += pbase32[left | (enc >> 6)];
strRet += pbase32[(enc >> 1) & 31];
left = (enc & 1) << 4;
mode = 2;
break;
case 2: // we have one bit
strRet += pbase32[left | (enc >> 4)];
left = (enc & 15) << 1;
mode = 3;
break;
case 3: // we have four bits
strRet += pbase32[left | (enc >> 7)];
strRet += pbase32[(enc >> 2) & 31];
left = (enc & 3) << 3;
mode = 4;
break;
case 4: // we have two bits
strRet += pbase32[left | (enc >> 5)];
strRet += pbase32[enc & 31];
mode = 0;
}
}
static const int nPadding[5] = {0, 6, 4, 3, 1};
if (mode)
{
strRet += pbase32[left];
for (int n=0; n<nPadding[mode]; n++)
strRet += '=';
}
return strRet;
}
string EncodeBase32(const string& str)
{
return EncodeBase32((const unsigned char*)str.c_str(), str.size());
}
vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
{
static const int decode32_table[256] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
if (pfInvalid)
*pfInvalid = false;
vector<unsigned char> vchRet;
vchRet.reserve((strlen(p))*5/8);
int mode = 0;
int left = 0;
while (1)
{
int dec = decode32_table[(unsigned char)*p];
if (dec == -1) break;
p++;
switch (mode)
{
case 0: // we have no bits and get 5
left = dec;
mode = 1;
break;
case 1: // we have 5 bits and keep 2
vchRet.push_back((left<<3) | (dec>>2));
left = dec & 3;
mode = 2;
break;
case 2: // we have 2 bits and keep 7
left = left << 5 | dec;
mode = 3;
break;
case 3: // we have 7 bits and keep 4
vchRet.push_back((left<<1) | (dec>>4));
left = dec & 15;
mode = 4;
break;
case 4: // we have 4 bits, and keep 1
vchRet.push_back((left<<4) | (dec>>1));
left = dec & 1;
mode = 5;
break;
case 5: // we have 1 bit, and keep 6
left = left << 5 | dec;
mode = 6;
break;
case 6: // we have 6 bits, and keep 3
vchRet.push_back((left<<2) | (dec>>3));
left = dec & 7;
mode = 7;
break;
case 7: // we have 3 bits, and keep 0
vchRet.push_back((left<<5) | dec);
mode = 0;
break;
}
}
if (pfInvalid)
switch (mode)
{
case 0: // 8n base32 characters processed: ok
break;
case 1: // 8n+1 base32 characters processed: impossible
case 3: // +3
case 6: // +6
*pfInvalid = true;
break;
case 2: // 8n+2 base32 characters processed: require '======'
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
*pfInvalid = true;
break;
case 4: // 8n+4 base32 characters processed: require '===='
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
*pfInvalid = true;
break;
case 5: // 8n+5 base32 characters processed: require '==='
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
*pfInvalid = true;
break;
case 7: // 8n+7 base32 characters processed: require '='
if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
*pfInvalid = true;
break;
}
return vchRet;
}
string DecodeBase32(const string& str)
{
vector<unsigned char> vchRet = DecodeBase32(str.c_str());
return string((const char*)&vchRet[0], vchRet.size());
}
bool WildcardMatch(const char* psz, const char* mask)
{
while (true)
{
switch (*mask)
{
case '\0':
return (*psz == '\0');
case '*':
return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
case '?':
if (*psz == '\0')
return false;
break;
default:
if (*psz != *mask)
return false;
break;
}
psz++;
mask++;
}
}
bool WildcardMatch(const string& str, const string& mask)
{
return WildcardMatch(str.c_str(), mask.c_str());
}
static std::string FormatException(std::exception* pex, const char* pszThread)
{
#ifdef WIN32
char pszModule[MAX_PATH] = "";
GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
#else
const char* pszModule = "KTXcoin";
#endif
if (pex)
return strprintf(
"EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
else
return strprintf(
"UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
}
void LogException(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n%s", message.c_str());
}
void PrintException(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n\n************************\n%s\n", message.c_str());
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
throw;
}
void LogStackTrace() {
printf("\n\n******* exception encountered *******\n");
if (fileout)
{
#ifndef WIN32
void* pszBuffer[32];
size_t size;
size = backtrace(pszBuffer, 32);
backtrace_symbols_fd(pszBuffer, size, fileno(fileout));
#endif
}
}
void PrintExceptionContinue(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n\n************************\n%s\n", message.c_str());
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
}
boost::filesystem::path GetDefaultDataDir()
{
namespace fs = boost::filesystem;
// Windows < Vista: C:\Documents and Settings\Username\Application Data\KTXcoin
// Windows >= Vista: C:\Users\Username\AppData\Roaming\KTXcoin
// Mac: ~/Library/Application Support/KTXcoin
// Unix: ~/.KTXcoin
#ifdef WIN32
// Windows
return GetSpecialFolderPath(CSIDL_APPDATA) / "KTXcoinhome";
#else
fs::path pathRet;
char* pszHome = getenv("HOME");
if (pszHome == NULL || strlen(pszHome) == 0)
pathRet = fs::path("/");
else
pathRet = fs::path(pszHome);
#ifdef MAC_OSX
// Mac
pathRet /= "Library/Application Support";
fs::create_directory(pathRet);
return pathRet / "KTXcoinhome";
#else
// Unix
return pathRet / ".KTXcoinhome";
#endif
#endif
}
const boost::filesystem::path &GetDataDir(bool fNetSpecific)
{
namespace fs = boost::filesystem;
static fs::path pathCached[2];
static CCriticalSection csPathCached;
static bool cachedPath[2] = {false, false};
fs::path &path = pathCached[fNetSpecific];
// This can be called during exceptions by printf, so we cache the
// value so we don't have to do memory allocations after that.
if (cachedPath[fNetSpecific])
return path;
LOCK(csPathCached);
if (mapArgs.count("-datadir")) {
path = fs::system_complete(mapArgs["-datadir"]);
if (!fs::is_directory(path)) {
path = "";
return path;
}
} else {
path = GetDefaultDataDir();
}
if (fNetSpecific && fTestNet)
path /= "testnet";
fs::create_directory(path);
cachedPath[fNetSpecific]=true;
return path;
}//KTXcoin
boost::filesystem::path GetConfigFile()
{
boost::filesystem::path pathConfigFile(GetArg("-conf", "KTXcoin.conf"));
if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
return pathConfigFile;
}
void ReadConfigFile(map<string, string>& mapSettingsRet,
map<string, vector<string> >& mapMultiSettingsRet)
{
boost::filesystem::ifstream streamConfig(GetConfigFile());
if (!streamConfig.good())
return; // No bitcoin.conf file is OK
set<string> setOptions;
setOptions.insert("*");
for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
{
// Don't overwrite existing settings so command line settings override bitcoin.conf
string strKey = string("-") + it->string_key;
if (mapSettingsRet.count(strKey) == 0)
{
mapSettingsRet[strKey] = it->value[0];
// interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
InterpretNegativeSetting(strKey, mapSettingsRet);
}
mapMultiSettingsRet[strKey].push_back(it->value[0]);
}
}
boost::filesystem::path GetPidFile()
{
boost::filesystem::path pathPidFile(GetArg("-pid", "KTXcoind.pid"));
if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
return pathPidFile;
}
#ifndef WIN32
void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
{
FILE* file = fopen(path.string().c_str(), "w");
if (file)
{
fprintf(file, "%d\n", pid);
fclose(file);
}
}
#endif
bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
{
#ifdef WIN32
return MoveFileExA(src.string().c_str(), dest.string().c_str(),
MOVEFILE_REPLACE_EXISTING);
#else
int rc = std::rename(src.string().c_str(), dest.string().c_str());
return (rc == 0);
#endif /* WIN32 */
}
void FileCommit(FILE *fileout)
{
fflush(fileout); // harmless if redundantly called
#ifdef WIN32
_commit(_fileno(fileout));
#else
fsync(fileno(fileout));
#endif
}
void ShrinkDebugFile()
{
// Scroll debug.log if it's getting too big
boost::filesystem::path pathLog = GetDataDir() / "debug.log";
FILE* file = fopen(pathLog.string().c_str(), "r");
if (file && boost::filesystem::file_size(pathLog) > 10 * 1000000)
{
// Restart the file with some of the end
char pch[200000];
fseek(file, -sizeof(pch), SEEK_END);
int nBytes = fread(pch, 1, sizeof(pch), file);
fclose(file);
file = fopen(pathLog.string().c_str(), "w");
if (file)
{
fwrite(pch, 1, nBytes, file);
fclose(file);
}
}
}
//
// "Never go to sea with two chronometers; take one or three."
// Our three time sources are:
// - System clock
// - Median of other nodes clocks
// - The user (asking the user to fix the system clock if the first two disagree)
//
static int64_t nMockTime = 0; // For unit testing
int64_t GetTime()
{
if (nMockTime) return nMockTime;
return time(NULL);
}
void SetMockTime(int64_t nMockTimeIn)
{
nMockTime = nMockTimeIn;
}
static int64_t nTimeOffset = 0;
int64_t GetTimeOffset()
{
return nTimeOffset;
}
int64_t GetAdjustedTime()
{
return GetTime() + GetTimeOffset();
}
void AddTimeData(const CNetAddr& ip, int64_t nTime)
{
int64_t nOffsetSample = nTime - GetTime();
// Ignore duplicates
static set<CNetAddr> setKnown;
if (!setKnown.insert(ip).second)
return;
// Add data
vTimeOffsets.input(nOffsetSample);
printf("Added time data, samples %d, offset %+"PRId64" (%+"PRId64" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
{
int64_t nMedian = vTimeOffsets.median();
std::vector<int64_t> vSorted = vTimeOffsets.sorted();
// Only let other nodes change our time by so much
if (abs64(nMedian) < 70 * 60)
{
nTimeOffset = nMedian;
}
else
{
nTimeOffset = 0;
static bool fDone;
if (!fDone)
{
// If nobody has a time different than ours but within 5 minutes of ours, give a warning
bool fMatch = false;
BOOST_FOREACH(int64_t nOffset, vSorted)
if (nOffset != 0 && abs64(nOffset) < 5 * 60)
fMatch = true;
if (!fMatch)
{
fDone = true;
string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong KTXcoin will not work properly.");
strMiscWarning = strMessage;
printf("*** %s\n", strMessage.c_str());
uiInterface.ThreadSafeMessageBox(strMessage+" ", string("KTXcoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION);
}
}
}
if (fDebug) {
BOOST_FOREACH(int64_t n, vSorted)
printf("%+"PRId64" ", n);
printf("| ");
}
printf("nTimeOffset = %+"PRId64" (%+"PRId64" minutes)\n", nTimeOffset, nTimeOffset/60);
}
}
string FormatVersion(int nVersion)
{
if (nVersion%100 == 0)
return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
else
return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
}
string FormatFullVersion()
{
return CLIENT_BUILD;
}
// Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
{
std::ostringstream ss;
ss << "/";
ss << name << ":" << FormatVersion(nClientVersion);
if (!comments.empty())
ss << "(" << boost::algorithm::join(comments, "; ") << ")";
ss << "/";
return ss.str();
}
#ifdef WIN32
boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
{
namespace fs = boost::filesystem;
char pszPath[MAX_PATH] = "";
if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
{
return fs::path(pszPath);
}
printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
return fs::path("");
}
#endif
void runCommand(std::string strCommand)
{
int nErr = ::system(strCommand.c_str());
if (nErr)
printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
}
void RenameThread(const char* name)
{
#if defined(PR_SET_NAME)
// Only the first 15 characters are used (16 - NUL terminator)
::prctl(PR_SET_NAME, name, 0, 0, 0);
#elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
// TODO: This is currently disabled because it needs to be verified to work
// on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
// removed.
pthread_set_name_np(pthread_self(), name);
// This is XCode 10.6-and-later; bring back if we drop 10.5 support:
// #elif defined(MAC_OSX)
// pthread_setname_np(name);
#else
// Prevent warnings for unused parameters...
(void)name;
#endif
}
bool NewThread(void(*pfn)(void*), void* parg)
{
try
{
boost::thread(pfn, parg); // thread detaches when out of scope
} catch(boost::thread_resource_error &e) {
printf("Error creating thread: %s\n", e.what());
return false;
}
return true;
}
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <gtest/gtest.h>
#include "EnumClinitAnalysis.h"
#include "verify/VerifyUtil.h"
using namespace optimize_enums;
namespace {
const char* enum_usesvalueof_name = "Lcom/facebook/redextest/UsesValueOf;";
const char* enum_usesvaluesmethod_name =
"Lcom/facebook/redextest/UsesValuesMethod;";
const char* enum_usesnothing_name = "Lcom/facebook/redextest/UsesNothing;";
const char* enum_captured_name = "Lcom/facebook/redextest/Captured;";
const char* enum_usedastypeclass_name =
"Lcom/facebook/redextest/UsedAsTypeClass;";
const char* enum_upcasted_name = "Lcom/facebook/redextest/Upcasted;";
const char* enum_upcastedtoserializable_name =
"Lcom/facebook/redextest/UpcastedToSerializable;";
const char* enum_instancefieldofserializable_name =
"Lcom/facebook/redextest/InstanceFieldOfSerializable;";
bool has_valueof_method(DexType* enum_type) {
auto proto = DexProto::get_proto(
enum_type,
DexTypeList::get_type_list({DexType::get_type("Ljava/lang/String;")}));
return DexMethod::get_method(
enum_type, DexString::make_string("valueOf"), proto) != nullptr;
}
bool has_values_method(DexType* enum_type) {
auto proto = DexProto::get_proto(make_array_type(enum_type),
DexTypeList::get_type_list({}));
return DexMethod::get_method(
enum_type, DexString::make_string("values"), proto) != nullptr;
}
bool has_values_field(DexType* enum_type) {
return DexField::get_field(enum_type,
DexString::make_string("$VALUES"),
make_array_type(enum_type)) != nullptr;
}
} // namespace
/**
* Test that the generated methods `valueOf()` and `values()` are removed if
* safe.
*/
TEST_F(PostVerify, transform) {
// UsesValueOf class
auto enum_cls = find_class_named(classes, enum_usesvalueof_name);
ASSERT_NE(enum_cls, nullptr);
EXPECT_TRUE(is_enum(enum_cls));
EXPECT_TRUE(has_valueof_method(enum_cls->get_type()));
EXPECT_TRUE(has_values_method(enum_cls->get_type()));
EXPECT_TRUE(has_values_field(enum_cls->get_type()));
// UsesValuesMethod class
enum_cls = find_class_named(classes, enum_usesvaluesmethod_name);
ASSERT_NE(enum_cls, nullptr);
EXPECT_TRUE(is_enum(enum_cls));
EXPECT_FALSE(has_valueof_method(enum_cls->get_type()));
EXPECT_TRUE(has_values_method(enum_cls->get_type()));
EXPECT_TRUE(has_values_field(enum_cls->get_type()));
// UsesNothing class
enum_cls = find_class_named(classes, enum_usesnothing_name);
ASSERT_NE(enum_cls, nullptr);
EXPECT_TRUE(is_enum(enum_cls));
EXPECT_FALSE(has_valueof_method(enum_cls->get_type()));
EXPECT_FALSE(has_values_method(enum_cls->get_type()));
EXPECT_FALSE(has_values_field(enum_cls->get_type()));
// Captured class
enum_cls = find_class_named(classes, enum_captured_name);
ASSERT_NE(enum_cls, nullptr);
EXPECT_TRUE(is_enum(enum_cls));
EXPECT_TRUE(has_valueof_method(enum_cls->get_type()));
EXPECT_TRUE(has_values_method(enum_cls->get_type()));
EXPECT_TRUE(has_values_field(enum_cls->get_type()));
// UsedAsTypeClass class
enum_cls = find_class_named(classes, enum_usedastypeclass_name);
ASSERT_NE(enum_cls, nullptr);
EXPECT_TRUE(is_enum(enum_cls));
EXPECT_TRUE(has_valueof_method(enum_cls->get_type()));
EXPECT_TRUE(has_values_method(enum_cls->get_type()));
EXPECT_TRUE(has_values_field(enum_cls->get_type()));
// Upcasted class
enum_cls = find_class_named(classes, enum_upcasted_name);
ASSERT_NE(enum_cls, nullptr);
EXPECT_TRUE(is_enum(enum_cls));
EXPECT_TRUE(has_valueof_method(enum_cls->get_type()));
EXPECT_TRUE(has_values_method(enum_cls->get_type()));
EXPECT_TRUE(has_values_field(enum_cls->get_type()));
// UpcastedToSerializable class
enum_cls = find_class_named(classes, enum_upcastedtoserializable_name);
ASSERT_NE(enum_cls, nullptr);
EXPECT_TRUE(is_enum(enum_cls));
EXPECT_TRUE(has_valueof_method(enum_cls->get_type()));
EXPECT_TRUE(has_values_method(enum_cls->get_type()));
EXPECT_TRUE(has_values_field(enum_cls->get_type()));
// InstanceOfSerializable class
enum_cls = find_class_named(classes, enum_instancefieldofserializable_name);
ASSERT_NE(enum_cls, nullptr);
EXPECT_TRUE(is_enum(enum_cls));
EXPECT_TRUE(has_valueof_method(enum_cls->get_type()));
EXPECT_TRUE(has_values_method(enum_cls->get_type()));
EXPECT_TRUE(has_values_field(enum_cls->get_type()));
}
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "raw_ptr_to_gc_managed_class_error.h"
namespace blink {
void HeapObject::trace(Visitor* visitor) {
visitor->trace(m_objs);
}
}
|
#include "engine.h"
#define NUMCAUSTICS 32
static Texture *caustictex[NUMCAUSTICS] = { NULL };
void loadcaustics(bool force)
{
static bool needcaustics = false;
if(force) needcaustics = true;
if(!caustics || !needcaustics) return;
useshaderbyname("caustics");
if(caustictex[0]) return;
loopi(NUMCAUSTICS)
{
defformatstring(name, "<grey><noswizzle>media/texture/mat_water/caustic/caust%.2d.png", i);
caustictex[i] = textureload(name);
}
}
void cleanupcaustics()
{
loopi(NUMCAUSTICS) caustictex[i] = NULL;
}
VARFR(causticscale, 0, 50, 10000, preloadwatershaders());
VARFR(causticmillis, 0, 75, 1000, preloadwatershaders());
FVARR(causticcontrast, 0, 0.6f, 2);
FVARR(causticoffset, 0, 0.7f, 1);
VARFP(caustics, 0, 1, 1, { loadcaustics(); preloadwatershaders(); });
void setupcaustics(int tmu, float surface = -1e16f)
{
if(!caustictex[0]) loadcaustics(true);
vec s = vec(0.011f, 0, 0.0066f).mul(100.0f/causticscale), t = vec(0, 0.011f, 0.0066f).mul(100.0f/causticscale);
int tex = (lastmillis/causticmillis)%NUMCAUSTICS;
float frac = float(lastmillis%causticmillis)/causticmillis;
loopi(2)
{
glActiveTexture_(GL_TEXTURE0+tmu+i);
glBindTexture(GL_TEXTURE_2D, caustictex[(tex+i)%NUMCAUSTICS]->id);
}
glActiveTexture_(GL_TEXTURE0);
float blendscale = causticcontrast, blendoffset = 1;
if(surface > -1e15f)
{
float bz = surface + camera1->o.z + (vertwater ? WATER_AMPLITUDE : 0);
matrix4 m(vec4(s.x, t.x, 0, 0),
vec4(s.y, t.y, 0, 0),
vec4(s.z, t.z, -1, 0),
vec4( 0, 0, bz, 1));
m.mul(worldmatrix);
GLOBALPARAM(causticsmatrix, m);
blendscale *= 0.5f;
blendoffset = 0;
}
else
{
GLOBALPARAM(causticsS, s);
GLOBALPARAM(causticsT, t);
}
GLOBALPARAMF(causticsblend, blendscale*(1-frac), blendscale*frac, blendoffset - causticoffset*blendscale);
}
void rendercaustics(float surface, float syl, float syr)
{
if(!caustics || !causticscale || !causticmillis) return;
glBlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
setupcaustics(0, surface);
SETSHADER(caustics);
gle::defvertex(2);
gle::begin(GL_TRIANGLE_STRIP);
gle::attribf(1, -1);
gle::attribf(-1, -1);
gle::attribf(1, syr);
gle::attribf(-1, syl);
gle::end();
}
void renderwaterfog(int mat, float surface)
{
glDepthFunc(GL_NOTEQUAL);
glDepthMask(GL_FALSE);
glDepthRange(1, 1);
glEnable(GL_BLEND);
glActiveTexture_(GL_TEXTURE9);
if(msaalight) glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, msdepthtex);
else glBindTexture(GL_TEXTURE_RECTANGLE, gdepthtex);
glActiveTexture_(GL_TEXTURE0);
vec p[4] =
{
invcamprojmatrix.perspectivetransform(vec(-1, -1, -1)),
invcamprojmatrix.perspectivetransform(vec(-1, 1, -1)),
invcamprojmatrix.perspectivetransform(vec(1, -1, -1)),
invcamprojmatrix.perspectivetransform(vec(1, 1, -1))
};
float bz = surface + camera1->o.z + (vertwater ? WATER_AMPLITUDE : 0),
syl = p[1].z > p[0].z ? 2*(bz - p[0].z)/(p[1].z - p[0].z) - 1 : 1,
syr = p[3].z > p[2].z ? 2*(bz - p[2].z)/(p[3].z - p[2].z) - 1 : 1;
if((mat&MATF_VOLUME) == MAT_WATER)
{
const bvec &deepcolor = getwaterdeepcolour(mat);
int deep = getwaterdeep(mat);
GLOBALPARAMF(waterdeepcolor, deepcolor.x*ldrscaleb, deepcolor.y*ldrscaleb, deepcolor.z*ldrscaleb);
vec deepfade = getwaterdeepfade(mat).tocolor().mul(deep);
GLOBALPARAMF(waterdeepfade,
deepfade.x ? calcfogdensity(deepfade.x) : -1e4f,
deepfade.y ? calcfogdensity(deepfade.y) : -1e4f,
deepfade.z ? calcfogdensity(deepfade.z) : -1e4f,
deep ? calcfogdensity(deep) : -1e4f);
rendercaustics(surface, syl, syr);
}
else
{
GLOBALPARAMF(waterdeepcolor, 0, 0, 0);
GLOBALPARAMF(waterdeepfade, -1e4f, -1e4f, -1e4f, -1e4f);
}
GLOBALPARAMF(waterheight, bz);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
SETSHADER(waterfog);
gle::defvertex(3);
gle::begin(GL_TRIANGLE_STRIP);
gle::attribf(1, -1, 1);
gle::attribf(-1, -1, 1);
gle::attribf(1, syr, 1);
gle::attribf(-1, syl, 1);
gle::end();
glDisable(GL_BLEND);
glDepthFunc(GL_LESS);
glDepthMask(GL_TRUE);
glDepthRange(0, 1);
}
/* vertex water */
VARP(watersubdiv, 0, 2, 3);
VARP(waterlod, 0, 1, 3);
static int wx1, wy1, wx2, wy2, wsize;
static float whscale, whoffset;
#define VERTW(vertw, defbody, body) \
static inline void def##vertw() \
{ \
gle::defvertex(); \
defbody; \
} \
static inline void vertw(float v1, float v2, float v3) \
{ \
float angle = (v1-wx1)*(v2-wy1)*(v1-wx2)*(v2-wy2)*whscale+whoffset; \
float s = angle - int(angle) - 0.5f; \
s *= 8 - fabs(s)*16; \
float h = WATER_AMPLITUDE*s-WATER_OFFSET; \
gle::attribf(v1, v2, v3+h); \
body; \
}
#define VERTWN(vertw, defbody, body) \
static inline void def##vertw() \
{ \
gle::defvertex(); \
defbody; \
} \
static inline void vertw(float v1, float v2, float v3) \
{ \
float h = -WATER_OFFSET; \
gle::attribf(v1, v2, v3+h); \
body; \
}
#define VERTWT(vertwt, defbody, body) \
VERTW(vertwt, defbody, { \
float v = angle - int(angle+0.25f) - 0.25f; \
v *= 8 - fabs(v)*16; \
float duv = 0.5f*v; \
body; \
})
static float wxscale = 1.0f, wyscale = 1.0f, wscroll = 0.0f;
VERTW(vertwt, {
gle::deftexcoord0();
}, {
gle::attribf(wxscale*v1, wyscale*v2);
})
VERTWN(vertwtn, {
gle::deftexcoord0();
}, {
gle::attribf(wxscale*v1, wyscale*v2);
})
VERTW(vertl, {
gle::deftexcoord0();
}, {
gle::attribf(wxscale*(v1+wscroll), wyscale*(v2+wscroll));
})
VERTWN(vertln, {
gle::deftexcoord0();
}, {
gle::attribf(wxscale*(v1+wscroll), wyscale*(v2+wscroll));
})
#define renderwaterstrips(vertw, z) { \
def##vertw(); \
gle::begin(GL_TRIANGLE_STRIP, 2*(wy2-wy1 + 1)*(wx2-wx1)/subdiv); \
for(int x = wx1; x<wx2; x += subdiv) \
{ \
vertw(x, wy1, z); \
vertw(x+subdiv, wy1, z); \
for(int y = wy1; y<wy2; y += subdiv) \
{ \
vertw(x, y+subdiv, z); \
vertw(x+subdiv, y+subdiv, z); \
} \
gle::multidraw(); \
} \
xtraverts += gle::end(); \
}
void rendervertwater(int subdiv, int xo, int yo, int z, int size, int mat)
{
wx1 = xo;
wy1 = yo;
wx2 = wx1 + size,
wy2 = wy1 + size;
wsize = size;
whscale = 59.0f/(23.0f*wsize*wsize)/(2*M_PI);
ASSERT((wx1 & (subdiv - 1)) == 0);
ASSERT((wy1 & (subdiv - 1)) == 0);
switch(mat)
{
case MAT_WATER:
{
whoffset = fmod(float(lastmillis/600.0f/(2*M_PI)), 1.0f);
renderwaterstrips(vertwt, z);
break;
}
case MAT_LAVA:
{
whoffset = fmod(float(lastmillis/2000.0f/(2*M_PI)), 1.0f);
renderwaterstrips(vertl, z);
break;
}
}
}
int calcwatersubdiv(int x, int y, int z, int size)
{
float dist;
if(camera1->o.x >= x && camera1->o.x < x + size &&
camera1->o.y >= y && camera1->o.y < y + size)
dist = fabs(camera1->o.z - float(z));
else
dist = vec(x + size/2, y + size/2, z + size/2).dist(camera1->o) - size*1.42f/2;
int subdiv = watersubdiv + int(dist) / (32 << waterlod);
return subdiv >= 31 ? INT_MAX : 1<<subdiv;
}
int renderwaterlod(int x, int y, int z, int size, int mat)
{
if(size <= (32 << waterlod))
{
int subdiv = calcwatersubdiv(x, y, z, size);
if(subdiv < size * 2) rendervertwater(min(subdiv, size), x, y, z, size, mat);
return subdiv;
}
else
{
int subdiv = calcwatersubdiv(x, y, z, size);
if(subdiv >= size)
{
if(subdiv < size * 2) rendervertwater(size, x, y, z, size, mat);
return subdiv;
}
int childsize = size / 2,
subdiv1 = renderwaterlod(x, y, z, childsize, mat),
subdiv2 = renderwaterlod(x + childsize, y, z, childsize, mat),
subdiv3 = renderwaterlod(x + childsize, y + childsize, z, childsize, mat),
subdiv4 = renderwaterlod(x, y + childsize, z, childsize, mat),
minsubdiv = subdiv1;
minsubdiv = min(minsubdiv, subdiv2);
minsubdiv = min(minsubdiv, subdiv3);
minsubdiv = min(minsubdiv, subdiv4);
if(minsubdiv < size * 2)
{
if(minsubdiv >= size) rendervertwater(size, x, y, z, size, mat);
else
{
if(subdiv1 >= size) rendervertwater(childsize, x, y, z, childsize, mat);
if(subdiv2 >= size) rendervertwater(childsize, x + childsize, y, z, childsize, mat);
if(subdiv3 >= size) rendervertwater(childsize, x + childsize, y + childsize, z, childsize, mat);
if(subdiv4 >= size) rendervertwater(childsize, x, y + childsize, z, childsize, mat);
}
}
return minsubdiv;
}
}
#define renderwaterquad(vertwn, z) \
{ \
if(gle::attribbuf.empty()) { def##vertwn(); gle::begin(GL_QUADS); } \
vertwn(x, y, z); \
vertwn(x+rsize, y, z); \
vertwn(x+rsize, y+csize, z); \
vertwn(x, y+csize, z); \
xtraverts += 4; \
}
void renderflatwater(int x, int y, int z, int rsize, int csize, int mat)
{
switch(mat)
{
case MAT_WATER:
renderwaterquad(vertwtn, z);
break;
case MAT_LAVA:
renderwaterquad(vertln, z);
break;
}
}
VARFP(vertwater, 0, 1, 1, allchanged());
static inline void renderwater(const materialsurface &m, int mat = MAT_WATER)
{
if(!vertwater || drawtex == DRAWTEX_MINIMAP) renderflatwater(m.o.x, m.o.y, m.o.z, m.rsize, m.csize, mat);
else if(renderwaterlod(m.o.x, m.o.y, m.o.z, m.csize, mat) >= int(m.csize) * 2)
rendervertwater(m.csize, m.o.x, m.o.y, m.o.z, m.csize, mat);
}
#define WATERVARS(name) \
CVAR0R(name##colour, 0x01212C); \
CVAR0R(name##deepcolour, 0x010A10); \
CVAR0R(name##deepfade, 0x60BFFF); \
CVAR0R(name##refractcolour, 0xFFFFFF); \
VARR(name##fog, 0, 30, 10000); \
VARR(name##deep, 0, 50, 10000); \
VARR(name##spec, 0, 150, 200); \
FVARR(name##refract, 0, 0.1f, 1e3f); \
CVARR(name##fallcolour, 0); \
CVARR(name##fallrefractcolour, 0); \
VARR(name##fallspec, 0, 150, 200); \
FVARR(name##fallrefract, 0, 0.1f, 1e3f);
WATERVARS(water)
WATERVARS(water2)
WATERVARS(water3)
WATERVARS(water4)
GETMATIDXVAR(water, colour, const bvec &)
GETMATIDXVAR(water, deepcolour, const bvec &)
GETMATIDXVAR(water, deepfade, const bvec &)
GETMATIDXVAR(water, refractcolour, const bvec &)
GETMATIDXVAR(water, fallcolour, const bvec &)
GETMATIDXVAR(water, fallrefractcolour, const bvec &)
GETMATIDXVAR(water, fog, int)
GETMATIDXVAR(water, deep, int)
GETMATIDXVAR(water, spec, int)
GETMATIDXVAR(water, refract, float)
GETMATIDXVAR(water, fallspec, int)
GETMATIDXVAR(water, fallrefract, float)
#define LAVAVARS(name) \
CVAR0R(name##colour, 0xFF4000); \
VARR(name##fog, 0, 50, 10000); \
FVARR(name##glowmin, 0, 0.25f, 2); \
FVARR(name##glowmax, 0, 1.0f, 2); \
VARR(name##spec, 0, 25, 200);
LAVAVARS(lava)
LAVAVARS(lava2)
LAVAVARS(lava3)
LAVAVARS(lava4)
GETMATIDXVAR(lava, colour, const bvec &)
GETMATIDXVAR(lava, fog, int)
GETMATIDXVAR(lava, glowmin, float)
GETMATIDXVAR(lava, glowmax, float)
GETMATIDXVAR(lava, spec, int)
VARFP(waterreflect, 0, 1, 1, { preloadwatershaders(); });
VARR(waterreflectstep, 1, 32, 10000);
VARFP(waterenvmap, 0, 1, 1, { preloadwatershaders(); });
VARFP(waterfallenv, 0, 1, 1, preloadwatershaders());
void preloadwatershaders(bool force)
{
static bool needwater = false;
if(force) needwater = true;
if(!needwater) return;
if(caustics && causticscale && causticmillis)
{
if(waterreflect) useshaderbyname("waterreflectcaustics");
else if(waterenvmap) useshaderbyname("waterenvcaustics");
else useshaderbyname("watercaustics");
}
else
{
if(waterreflect) useshaderbyname("waterreflect");
else if(waterenvmap) useshaderbyname("waterenv");
else useshaderbyname("water");
}
useshaderbyname("underwater");
if(waterfallenv) useshaderbyname("waterfallenv");
useshaderbyname("waterfall");
useshaderbyname("waterfog");
useshaderbyname("waterminimap");
}
static float wfwave = 0.0f, wfscroll = 0.0f, wfxscale = 1.0f, wfyscale = 1.0f;
static void renderwaterfall(const materialsurface &m, float offset, const vec *normal = NULL)
{
if(gle::attribbuf.empty())
{
gle::defvertex();
if(normal) gle::defnormal();
gle::deftexcoord0();
gle::begin(GL_QUADS);
}
float x = m.o.x, y = m.o.y, zmin = m.o.z, zmax = zmin;
if(m.ends&1) zmin += -WATER_OFFSET-WATER_AMPLITUDE;
if(m.ends&2) zmax += wfwave;
int csize = m.csize, rsize = m.rsize;
#define GENFACEORIENT(orient, v0, v1, v2, v3) \
case orient: v0 v1 v2 v3 break;
#undef GENFACEVERTX
#define GENFACEVERTX(orient, vert, mx,my,mz, sx,sy,sz) \
{ \
vec v(mx sx, my sy, mz sz); \
gle::attribf(v.x, v.y, v.z); \
GENFACENORMAL \
gle::attribf(wfxscale*v.y, -wfyscale*(v.z+wfscroll)); \
}
#undef GENFACEVERTY
#define GENFACEVERTY(orient, vert, mx,my,mz, sx,sy,sz) \
{ \
vec v(mx sx, my sy, mz sz); \
gle::attribf(v.x, v.y, v.z); \
GENFACENORMAL \
gle::attribf(wfxscale*v.x, -wfyscale*(v.z+wfscroll)); \
}
#define GENFACENORMAL gle::attribf(n.x, n.y, n.z);
if(normal)
{
vec n = *normal;
switch(m.orient) { GENFACEVERTSXY(x, x, y, y, zmin, zmax, /**/, + csize, /**/, + rsize, + offset, - offset) }
}
#undef GENFACENORMAL
#define GENFACENORMAL
else switch(m.orient) { GENFACEVERTSXY(x, x, y, y, zmin, zmax, /**/, + csize, /**/, + rsize, + offset, - offset) }
#undef GENFACENORMAL
#undef GENFACEORIENT
#undef GENFACEVERTX
#define GENFACEVERTX(o,n, x,y,z, xv,yv,zv) GENFACEVERT(o,n, x,y,z, xv,yv,zv)
#undef GENFACEVERTY
#define GENFACEVERTY(o,n, x,y,z, xv,yv,zv) GENFACEVERT(o,n, x,y,z, xv,yv,zv)
}
void renderlava()
{
loopk(4)
{
if(lavasurfs[k].empty() && (drawtex == DRAWTEX_MINIMAP || lavafallsurfs[k].empty())) continue;
MatSlot &lslot = lookupmaterialslot(MAT_LAVA+k);
SETSHADER(lava);
float t = lastmillis/2000.0f;
t -= floor(t);
t = 1.0f - 2*fabs(t-0.5f);
t = 0.5f + 0.5f*t;
float glowmin = getlavaglowmin(k), glowmax = getlavaglowmax(k);
int spec = getlavaspec(k);
LOCALPARAMF(lavaglow, 0.5f*(glowmin + (glowmax-glowmin)*t));
LOCALPARAMF(lavaspec, spec/100.0f);
if(lavasurfs[k].length())
{
Texture *tex = lslot.sts.inrange(0) ? lslot.sts[0].t: notexture;
wxscale = TEX_SCALE/(tex->xs*lslot.scale);
wyscale = TEX_SCALE/(tex->ys*lslot.scale);
wscroll = lastmillis/1000.0f;
glBindTexture(GL_TEXTURE_2D, tex->id);
glActiveTexture_(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, lslot.sts.inrange(1) ? lslot.sts[1].t->id : notexture->id);
glActiveTexture_(GL_TEXTURE0);
gle::normal(vec(0, 0, 1));
vector<materialsurface> &surfs = lavasurfs[k];
loopv(surfs) renderwater(surfs[i], MAT_LAVA);
xtraverts += gle::end();
}
if(drawtex != DRAWTEX_MINIMAP && lavafallsurfs[k].length())
{
Texture *tex = lslot.sts.inrange(2) ? lslot.sts[2].t : (lslot.sts.inrange(0) ? lslot.sts[0].t : notexture);
float angle = fmod(float(lastmillis/2000.0f/(2*M_PI)), 1.0f),
s = angle - int(angle) - 0.5f;
s *= 8 - fabs(s)*16;
wfwave = vertwater ? WATER_AMPLITUDE*s-WATER_OFFSET : -WATER_OFFSET;
wfscroll = 16.0f*lastmillis/3000.0f;
wfxscale = TEX_SCALE/(tex->xs*lslot.scale);
wfyscale = TEX_SCALE/(tex->ys*lslot.scale);
glBindTexture(GL_TEXTURE_2D, tex->id);
glActiveTexture_(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, lslot.sts.inrange(2) ? (lslot.sts.inrange(3) ? lslot.sts[3].t->id : notexture->id) : (lslot.sts.inrange(1) ? lslot.sts[1].t->id : notexture->id));
glActiveTexture_(GL_TEXTURE0);
vector<materialsurface> &surfs = lavafallsurfs[k];
loopv(surfs)
{
materialsurface &m = surfs[i];
renderwaterfall(m, 0.1f, &matnormals[m.orient]);
}
xtraverts += gle::end();
}
}
}
void renderwaterfalls()
{
loopk(4)
{
vector<materialsurface> &surfs = waterfallsurfs[k];
if(surfs.empty()) continue;
MatSlot &wslot = lookupmaterialslot(MAT_WATER+k);
Texture *tex = wslot.sts.inrange(2) ? wslot.sts[2].t : (wslot.sts.inrange(0) ? wslot.sts[0].t : notexture);
float angle = fmod(float(lastmillis/600.0f/(2*M_PI)), 1.0f),
s = angle - int(angle) - 0.5f;
s *= 8 - fabs(s)*16;
wfwave = vertwater ? WATER_AMPLITUDE*s-WATER_OFFSET : -WATER_OFFSET;
wfscroll = 16.0f*lastmillis/1000.0f;
wfxscale = TEX_SCALE/(tex->xs*wslot.scale);
wfyscale = TEX_SCALE/(tex->ys*wslot.scale);
bvec color = getwaterfallcolour(k), refractcolor = getwaterfallrefractcolour(k);
if(color.iszero()) color = getwatercolour(k);
if(refractcolor.iszero()) refractcolor = getwaterrefractcolour(k);
float colorscale = (0.5f/255), refractscale = colorscale/ldrscale;
float refract = getwaterfallrefract(k);
int spec = getwaterfallspec(k);
GLOBALPARAMF(waterfallcolor, color.x*colorscale, color.y*colorscale, color.z*colorscale);
GLOBALPARAMF(waterfallrefract, refractcolor.x*refractscale, refractcolor.y*refractscale, refractcolor.z*refractscale, refract*viewh);
GLOBALPARAMF(waterfallspec, spec/100.0f);
if(waterfallenv) SETSHADER(waterfallenv);
else SETSHADER(waterfall);
glBindTexture(GL_TEXTURE_2D, tex->id);
glActiveTexture_(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, wslot.sts.inrange(2) ? (wslot.sts.inrange(3) ? wslot.sts[3].t->id : notexture->id) : (wslot.sts.inrange(1) ? wslot.sts[1].t->id : notexture->id));
if(waterfallenv)
{
glActiveTexture_(GL_TEXTURE3);
glBindTexture(GL_TEXTURE_CUBE_MAP, lookupenvmap(wslot));
}
glActiveTexture_(GL_TEXTURE0);
loopv(surfs)
{
materialsurface &m = surfs[i];
renderwaterfall(m, 0.1f, &matnormals[m.orient]);
}
xtraverts += gle::end();
}
}
void renderwater()
{
loopk(4)
{
vector<materialsurface> &surfs = watersurfs[k];
if(surfs.empty()) continue;
MatSlot &wslot = lookupmaterialslot(MAT_WATER+k);
Texture *tex = wslot.sts.inrange(0) ? wslot.sts[0].t: notexture;
wxscale = TEX_SCALE/(tex->xs*wslot.scale);
wyscale = TEX_SCALE/(tex->ys*wslot.scale);
wscroll = 0.0f;
glBindTexture(GL_TEXTURE_2D, tex->id);
glActiveTexture_(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, wslot.sts.inrange(1) ? wslot.sts[1].t->id : notexture->id);
if(caustics && causticscale && causticmillis) setupcaustics(2);
if(waterenvmap && !waterreflect && drawtex != DRAWTEX_MINIMAP)
{
glActiveTexture_(GL_TEXTURE4);
glBindTexture(GL_TEXTURE_CUBE_MAP, lookupenvmap(wslot));
}
glActiveTexture_(GL_TEXTURE0);
float colorscale = 0.5f/255, refractscale = colorscale/ldrscale, reflectscale = 0.5f/ldrscale;
const bvec &color = getwatercolour(k);
const bvec &deepcolor = getwaterdeepcolour(k);
const bvec &refractcolor = getwaterrefractcolour(k);
int fog = getwaterfog(k), deep = getwaterdeep(k), spec = getwaterspec(k);
float refract = getwaterrefract(k);
GLOBALPARAMF(watercolor, color.x*colorscale, color.y*colorscale, color.z*colorscale);
GLOBALPARAMF(waterdeepcolor, deepcolor.x*colorscale, deepcolor.y*colorscale, deepcolor.z*colorscale);
float fogdensity = fog ? calcfogdensity(fog) : -1e4f;
GLOBALPARAMF(waterfog, fogdensity);
vec deepfade = getwaterdeepfade(k).tocolor().mul(deep);
GLOBALPARAMF(waterdeepfade,
deepfade.x ? calcfogdensity(deepfade.x) : -1e4f,
deepfade.y ? calcfogdensity(deepfade.y) : -1e4f,
deepfade.z ? calcfogdensity(deepfade.z) : -1e4f,
deep ? calcfogdensity(deep) : -1e4f);
GLOBALPARAMF(waterspec, spec/100.0f);
GLOBALPARAMF(waterreflect, reflectscale, reflectscale, reflectscale, waterreflectstep);
GLOBALPARAMF(waterrefract, refractcolor.x*refractscale, refractcolor.y*refractscale, refractcolor.z*refractscale, refract*viewh);
#define SETWATERSHADER(which, name) \
do { \
static Shader *name##shader = NULL; \
if(!name##shader) name##shader = lookupshaderbyname(#name); \
which##shader = name##shader; \
} while(0)
Shader *aboveshader = NULL;
if(drawtex == DRAWTEX_MINIMAP) SETWATERSHADER(above, waterminimap);
else if(caustics && causticscale && causticmillis)
{
if(waterreflect) SETWATERSHADER(above, waterreflectcaustics);
else if(waterenvmap) SETWATERSHADER(above, waterenvcaustics);
else SETWATERSHADER(above, watercaustics);
}
else
{
if(waterreflect) SETWATERSHADER(above, waterreflect);
else if(waterenvmap) SETWATERSHADER(above, waterenv);
else SETWATERSHADER(above, water);
}
Shader *belowshader = NULL;
if(drawtex != DRAWTEX_MINIMAP) SETWATERSHADER(below, underwater);
aboveshader->set();
loopv(surfs)
{
materialsurface &m = surfs[i];
if(camera1->o.z < m.o.z - WATER_OFFSET) continue;
renderwater(m);
}
xtraverts += gle::end();
if(belowshader)
{
belowshader->set();
loopv(surfs)
{
materialsurface &m = surfs[i];
if(camera1->o.z >= m.o.z - WATER_OFFSET) continue;
renderwater(m);
}
xtraverts += gle::end();
}
}
}
|
/*
* Copyright (c) 2021, Tim Flynn <trflynn89@pm.me>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/AllOf.h>
#include <AK/AnyOf.h>
#include <AK/Array.h>
#include <AK/CharacterTypes.h>
#include <AK/Find.h>
#include <AK/Function.h>
#include <AK/QuickSort.h>
#include <AK/TypeCasts.h>
#include <LibJS/Runtime/Array.h>
#include <LibJS/Runtime/GlobalObject.h>
#include <LibJS/Runtime/Intl/AbstractOperations.h>
#include <LibJS/Runtime/Intl/Locale.h>
#include <LibUnicode/Locale.h>
namespace JS::Intl {
// 6.2.2 IsStructurallyValidLanguageTag ( locale ), https://tc39.es/ecma402/#sec-isstructurallyvalidlanguagetag
Optional<Unicode::LocaleID> is_structurally_valid_language_tag(StringView locale)
{
auto contains_duplicate_variant = [](auto& variants) {
if (variants.is_empty())
return false;
quick_sort(variants);
for (size_t i = 0; i < variants.size() - 1; ++i) {
if (variants[i].equals_ignoring_case(variants[i + 1]))
return true;
}
return false;
};
// IsStructurallyValidLanguageTag returns true if all of the following conditions hold, false otherwise:
// locale can be generated from the EBNF grammar for unicode_locale_id in Unicode Technical Standard #35 LDML § 3.2 Unicode Locale Identifier;
auto locale_id = Unicode::parse_unicode_locale_id(locale);
if (!locale_id.has_value())
return {};
// locale does not use any of the backwards compatibility syntax described in Unicode Technical Standard #35 LDML § 3.3 BCP 47 Conformance;
// https://unicode.org/reports/tr35/#BCP_47_Conformance
if (locale.contains('_') || locale_id->language_id.is_root || !locale_id->language_id.language.has_value())
return {};
// the unicode_language_id within locale contains no duplicate unicode_variant_subtag subtags; and
if (contains_duplicate_variant(locale_id->language_id.variants))
return {};
// if locale contains an extensions* component, that component
Vector<char> unique_keys;
for (auto& extension : locale_id->extensions) {
// does not contain any other_extensions components with duplicate [alphanum-[tTuUxX]] subtags,
// contains at most one unicode_locale_extensions component,
// contains at most one transformed_extensions component, and
char key = extension.visit(
[](Unicode::LocaleExtension const&) { return 'u'; },
[](Unicode::TransformedExtension const&) { return 't'; },
[](Unicode::OtherExtension const& ext) { return static_cast<char>(to_ascii_lowercase(ext.key)); });
if (unique_keys.contains_slow(key))
return {};
unique_keys.append(key);
// if a transformed_extensions component that contains a tlang component is present, then
// the tlang component contains no duplicate unicode_variant_subtag subtags.
if (auto* transformed = extension.get_pointer<Unicode::TransformedExtension>()) {
auto& language = transformed->language;
if (language.has_value() && contains_duplicate_variant(language->variants))
return {};
}
}
return locale_id;
}
// 6.2.3 CanonicalizeUnicodeLocaleId ( locale ), https://tc39.es/ecma402/#sec-canonicalizeunicodelocaleid
String canonicalize_unicode_locale_id(Unicode::LocaleID& locale)
{
// Note: This implementation differs from the spec in how Step 3 is implemented. The spec assumes
// the input to this method is a string, and is written such that operations are performed on parts
// of that string. LibUnicode gives us the parsed locale in a structure, so we can mutate that
// structure directly. From a footnote in the spec:
//
// The third step of this algorithm ensures that a Unicode locale extension sequence in the
// returned language tag contains:
// * only the first instance of any attribute duplicated in the input, and
// * only the first keyword for a given key in the input.
for (auto& extension : locale.extensions) {
if (!extension.has<Unicode::LocaleExtension>())
continue;
auto& locale_extension = extension.get<Unicode::LocaleExtension>();
auto attributes = move(locale_extension.attributes);
for (auto& attribute : attributes) {
if (!locale_extension.attributes.contains_slow(attribute))
locale_extension.attributes.append(move(attribute));
}
auto keywords = move(locale_extension.keywords);
for (auto& keyword : keywords) {
if (!any_of(locale_extension.keywords, [&](auto const& k) { return k.key == keyword.key; }))
locale_extension.keywords.append(move(keyword));
}
break;
}
// 1. Let localeId be the string locale after performing the algorithm to transform it to canonical syntax per Unicode Technical Standard #35 LDML § 3.2.1 Canonical Unicode Locale Identifiers.
// 2. Let localeId be the string localeId after performing the algorithm to transform it to canonical form.
auto locale_id = Unicode::canonicalize_unicode_locale_id(locale);
VERIFY(locale_id.has_value());
// 4. Return localeId.
return locale_id.release_value();
}
// 6.3.1 IsWellFormedCurrencyCode ( currency ), https://tc39.es/ecma402/#sec-canonicalcodefordisplaynames
bool is_well_formed_currency_code(StringView currency)
{
// 1. Let normalized be the result of mapping currency to upper case as described in 6.1.
// 2. If the number of elements in normalized is not 3, return false.
if (currency.length() != 3)
return false;
// 3. If normalized contains any character that is not in the range "A" to "Z" (U+0041 to U+005A), return false.
if (!all_of(currency, is_ascii_alpha))
return false;
// 4. Return true.
return true;
}
// 6.5.1 IsWellFormedUnitIdentifier ( unitIdentifier ), https://tc39.es/ecma402/#sec-iswellformedunitidentifier
bool is_well_formed_unit_identifier(StringView unit_identifier)
{
// 6.5.2 IsSanctionedSimpleUnitIdentifier ( unitIdentifier ), https://tc39.es/ecma402/#sec-iswellformedunitidentifier
constexpr auto is_sanctioned_simple_unit_identifier = [](StringView unit_identifier) {
// 1. If unitIdentifier is listed in Table 2 below, return true.
// 2. Else, return false.
static constexpr auto sanctioned_units = AK::Array { "acre"sv, "bit"sv, "byte"sv, "celsius"sv, "centimeter"sv, "day"sv, "degree"sv, "fahrenheit"sv, "fluid-ounce"sv, "foot"sv, "gallon"sv, "gigabit"sv, "gigabyte"sv, "gram"sv, "hectare"sv, "hour"sv, "inch"sv, "kilobit"sv, "kilobyte"sv, "kilogram"sv, "kilometer"sv, "liter"sv, "megabit"sv, "megabyte"sv, "meter"sv, "mile"sv, "mile-scandinavian"sv, "milliliter"sv, "millimeter"sv, "millisecond"sv, "minute"sv, "month"sv, "ounce"sv, "percent"sv, "petabyte"sv, "pound"sv, "second"sv, "stone"sv, "terabit"sv, "terabyte"sv, "week"sv, "yard"sv, "year"sv };
return find(sanctioned_units.begin(), sanctioned_units.end(), unit_identifier) != sanctioned_units.end();
};
// 1. If the result of IsSanctionedSimpleUnitIdentifier(unitIdentifier) is true, then
if (is_sanctioned_simple_unit_identifier(unit_identifier)) {
// a. Return true.
return true;
}
auto indices = unit_identifier.find_all("-per-"sv);
// 2. If the substring "-per-" does not occur exactly once in unitIdentifier, then
if (indices.size() != 1) {
// a. Return false.
return false;
}
// 3. Let numerator be the substring of unitIdentifier from the beginning to just before "-per-".
auto numerator = unit_identifier.substring_view(0, indices[0]);
// 4. If the result of IsSanctionedSimpleUnitIdentifier(numerator) is false, then
if (!is_sanctioned_simple_unit_identifier(numerator)) {
// a. Return false.
return false;
}
// 5. Let denominator be the substring of unitIdentifier from just after "-per-" to the end.
auto denominator = unit_identifier.substring_view(indices[0] + 5);
// 6. If the result of IsSanctionedSimpleUnitIdentifier(denominator) is false, then
if (!is_sanctioned_simple_unit_identifier(denominator)) {
// a. Return false.
return false;
}
// 7. Return true.
return true;
}
// 9.2.1 CanonicalizeLocaleList ( locales ), https://tc39.es/ecma402/#sec-canonicalizelocalelist
Vector<String> canonicalize_locale_list(GlobalObject& global_object, Value locales)
{
auto& vm = global_object.vm();
// 1. If locales is undefined, then
if (locales.is_undefined()) {
// a. Return a new empty List.
return {};
}
// 2. Let seen be a new empty List.
Vector<String> seen;
Object* object = nullptr;
// 3. If Type(locales) is String or Type(locales) is Object and locales has an [[InitializedLocale]] internal slot, then
if (locales.is_string() || (locales.is_object() && is<Locale>(locales.as_object()))) {
// a. Let O be CreateArrayFromList(« locales »).
object = Array::create_from(global_object, { locales });
}
// 4. Else,
else {
// a. Let O be ? ToObject(locales).
object = locales.to_object(global_object);
if (vm.exception())
return {};
}
// 5. Let len be ? ToLength(? Get(O, "length")).
auto length_value = object->get(vm.names.length);
if (vm.exception())
return {};
auto length = length_value.to_length(global_object);
if (vm.exception())
return {};
// 6. Let k be 0.
// 7. Repeat, while k < len,
for (size_t k = 0; k < length; ++k) {
// a. Let Pk be ToString(k).
auto property_key = PropertyName { k };
// b. Let kPresent be ? HasProperty(O, Pk).
auto key_present = object->has_property(property_key);
if (vm.exception())
return {};
// c. If kPresent is true, then
if (key_present) {
// i. Let kValue be ? Get(O, Pk).
auto key_value = object->get(property_key);
if (vm.exception())
return {};
// ii. If Type(kValue) is not String or Object, throw a TypeError exception.
if (!key_value.is_string() && !key_value.is_object()) {
vm.throw_exception<TypeError>(global_object, ErrorType::NotAnObjectOrString, key_value.to_string_without_side_effects());
return {};
}
String tag;
// iii. If Type(kValue) is Object and kValue has an [[InitializedLocale]] internal slot, then
if (key_value.is_object() && is<Locale>(key_value.as_object())) {
// 1. Let tag be kValue.[[Locale]].
tag = static_cast<Locale const&>(key_value.as_object()).locale();
}
// iv. Else,
else {
// 1. Let tag be ? ToString(kValue).
tag = key_value.to_string(global_object);
if (vm.exception())
return {};
}
// v. If IsStructurallyValidLanguageTag(tag) is false, throw a RangeError exception.
auto locale_id = is_structurally_valid_language_tag(tag);
if (!locale_id.has_value()) {
vm.throw_exception<RangeError>(global_object, ErrorType::IntlInvalidLanguageTag, tag);
return {};
}
// vi. Let canonicalizedTag be CanonicalizeUnicodeLocaleId(tag).
auto canonicalized_tag = JS::Intl::canonicalize_unicode_locale_id(*locale_id);
// vii. If canonicalizedTag is not an element of seen, append canonicalizedTag as the last element of seen.
if (!seen.contains_slow(canonicalized_tag))
seen.append(move(canonicalized_tag));
}
// d. Increase k by 1.
}
return seen;
}
// 9.2.2 BestAvailableLocale ( availableLocales, locale ), https://tc39.es/ecma402/#sec-bestavailablelocale
Optional<String> best_available_locale(StringView const& locale)
{
// 1. Let candidate be locale.
StringView candidate = locale;
// 2. Repeat,
while (true) {
// a. If availableLocales contains an element equal to candidate, return candidate.
if (Unicode::is_locale_available(candidate))
return candidate;
// b. Let pos be the character index of the last occurrence of "-" (U+002D) within candidate. If that character does not occur, return undefined.
auto pos = candidate.find_last('-');
if (!pos.has_value())
return {};
// c. If pos ≥ 2 and the character "-" occurs at index pos-2 of candidate, decrease pos by 2.
if ((*pos >= 2) && (candidate[*pos - 2] == '-'))
pos = *pos - 2;
// d. Let candidate be the substring of candidate from position 0, inclusive, to position pos, exclusive.
candidate = candidate.substring_view(0, *pos);
}
}
struct MatcherResult {
String locale;
Vector<Unicode::Extension> extensions {};
};
// 9.2.3 LookupMatcher ( availableLocales, requestedLocales ), https://tc39.es/ecma402/#sec-lookupmatcher
static MatcherResult lookup_matcher(Vector<String> const& requested_locales)
{
// 1. Let result be a new Record.
MatcherResult result {};
// 2. For each element locale of requestedLocales, do
for (auto const& locale : requested_locales) {
auto locale_id = Unicode::parse_unicode_locale_id(locale);
VERIFY(locale_id.has_value());
// a. Let noExtensionsLocale be the String value that is locale with any Unicode locale extension sequences removed.
auto extensions = locale_id->remove_extension_type<Unicode::LocaleExtension>();
auto no_extensions_locale = locale_id->to_string();
// b. Let availableLocale be BestAvailableLocale(availableLocales, noExtensionsLocale).
auto available_locale = best_available_locale(no_extensions_locale);
// c. If availableLocale is not undefined, then
if (available_locale.has_value()) {
// i. Set result.[[locale]] to availableLocale.
result.locale = available_locale.release_value();
// ii. If locale and noExtensionsLocale are not the same String value, then
if (locale != no_extensions_locale) {
// 1. Let extension be the String value consisting of the substring of the Unicode locale extension sequence within locale.
// 2. Set result.[[extension]] to extension.
result.extensions.extend(move(extensions));
}
// iii. Return result.
return result;
}
}
// 3. Let defLocale be DefaultLocale().
// 4. Set result.[[locale]] to defLocale.
result.locale = Unicode::default_locale();
// 5. Return result.
return result;
}
// 9.2.4 BestFitMatcher ( availableLocales, requestedLocales ), https://tc39.es/ecma402/#sec-bestfitmatcher
static MatcherResult best_fit_matcher(Vector<String> const& requested_locales)
{
// The algorithm is implementation dependent, but should produce results that a typical user of the requested locales would
// perceive as at least as good as those produced by the LookupMatcher abstract operation.
return lookup_matcher(requested_locales);
}
// 9.2.6 InsertUnicodeExtensionAndCanonicalize ( locale, extension ), https://tc39.es/ecma402/#sec-insert-unicode-extension-and-canonicalize
String insert_unicode_extension_and_canonicalize(Unicode::LocaleID locale, Unicode::LocaleExtension extension)
{
// Note: This implementation differs from the spec in how the extension is inserted. The spec assumes
// the input to this method is a string, and is written such that operations are performed on parts
// of that string. LibUnicode gives us the parsed locale in a structure, so we can mutate that
// structure directly.
locale.extensions.append(move(extension));
return JS::Intl::canonicalize_unicode_locale_id(locale);
}
template<typename T>
static auto& find_key_in_value(T& value, StringView key)
{
if (key == "nu"sv)
return value.nu;
// If you hit this point, you must add any missing keys from [[RelevantExtensionKeys]] to LocaleOptions and LocaleResult.
VERIFY_NOT_REACHED();
}
// 9.2.7 ResolveLocale ( availableLocales, requestedLocales, options, relevantExtensionKeys, localeData ), https://tc39.es/ecma402/#sec-resolvelocale
LocaleResult resolve_locale(Vector<String> const& requested_locales, LocaleOptions const& options, Vector<StringView> const& relevant_extension_keys)
{
// 1. Let matcher be options.[[localeMatcher]].
auto const& matcher = options.locale_matcher;
MatcherResult matcher_result;
// 2. If matcher is "lookup", then
if (matcher.is_string() && (matcher.as_string().string() == "lookup"sv)) {
// a. Let r be LookupMatcher(availableLocales, requestedLocales).
matcher_result = lookup_matcher(requested_locales);
}
// 3. Else,
else {
// a. Let r be BestFitMatcher(availableLocales, requestedLocales).
matcher_result = best_fit_matcher(requested_locales);
}
// 4. Let foundLocale be r.[[locale]].
auto found_locale = move(matcher_result.locale);
// 5. Let result be a new Record.
LocaleResult result {};
// 6. Set result.[[dataLocale]] to foundLocale.
result.data_locale = found_locale;
// 7. If r has an [[extension]] field, then
Vector<Unicode::Keyword> keywords;
for (auto& extension : matcher_result.extensions) {
if (!extension.has<Unicode::LocaleExtension>())
continue;
// a. Let components be ! UnicodeExtensionComponents(r.[[extension]]).
auto& components = extension.get<Unicode::LocaleExtension>();
// b. Let keywords be components.[[Keywords]].
keywords = move(components.keywords);
break;
}
// 8. Let supportedExtension be "-u".
Unicode::LocaleExtension supported_extension {};
// 9. For each element key of relevantExtensionKeys, do
for (auto const& key : relevant_extension_keys) {
// a. Let foundLocaleData be localeData.[[<foundLocale>]].
// b. Assert: Type(foundLocaleData) is Record.
// c. Let keyLocaleData be foundLocaleData.[[<key>]].
// d. Assert: Type(keyLocaleData) is List.
auto key_locale_data = Unicode::get_locale_key_mapping(found_locale, key);
// e. Let value be keyLocaleData[0].
// f. Assert: Type(value) is either String or Null.
Optional<String> value;
if (!key_locale_data.is_empty())
value = key_locale_data[0];
// g. Let supportedExtensionAddition be "".
Optional<Unicode::Keyword> supported_extension_addition {};
// h. If r has an [[extension]] field, then
for (auto& entry : keywords) {
// i. If keywords contains an element whose [[Key]] is the same as key, then
if (entry.key != key)
continue;
// 1. Let entry be the element of keywords whose [[Key]] is the same as key.
// 2. Let requestedValue be entry.[[Value]].
auto requested_value = entry.value;
// 3. If requestedValue is not the empty String, then
if (!requested_value.is_empty()) {
// a. If keyLocaleData contains requestedValue, then
if (key_locale_data.contains_slow(requested_value)) {
// i. Let value be requestedValue.
value = move(requested_value);
// ii. Let supportedExtensionAddition be the string-concatenation of "-", key, "-", and value.
supported_extension_addition = Unicode::Keyword { key, move(entry.value) };
}
}
// 4. Else if keyLocaleData contains "true", then
else if (key_locale_data.contains_slow("true"sv)) {
// a. Let value be "true".
value = "true"sv;
// b. Let supportedExtensionAddition be the string-concatenation of "-" and key.
supported_extension_addition = Unicode::Keyword { key, {} };
}
break;
}
// i. If options has a field [[<key>]], then
// i. Let optionsValue be options.[[<key>]].
// ii. Assert: Type(optionsValue) is either String, Undefined, or Null.
auto options_value = find_key_in_value(options, key);
// iii. If Type(optionsValue) is String, then
if (options_value.has_value()) {
// 1. Let optionsValue be the string optionsValue after performing the algorithm steps to transform Unicode extension values to canonical syntax per Unicode Technical Standard #35 LDML § 3.2.1 Canonical Unicode Locale Identifiers, treating key as ukey and optionsValue as uvalue productions.
// 2. Let optionsValue be the string optionsValue after performing the algorithm steps to replace Unicode extension values with their canonical form per Unicode Technical Standard #35 LDML § 3.2.1 Canonical Unicode Locale Identifiers, treating key as ukey and optionsValue as uvalue productions.
Unicode::canonicalize_unicode_extension_values(key, *options_value, true);
// 3. If optionsValue is the empty String, then
if (options_value->is_empty()) {
// a. Let optionsValue be "true".
options_value = "true"sv;
}
}
// iv. If keyLocaleData contains optionsValue, then
if (options_value.has_value() && key_locale_data.contains_slow(*options_value)) {
// 1. If SameValue(optionsValue, value) is false, then
if (options_value != value) {
// a. Let value be optionsValue.
value = move(options_value);
// b. Let supportedExtensionAddition be "".
supported_extension_addition.clear();
}
}
// j. Set result.[[<key>]] to value.
find_key_in_value(result, key) = move(value);
// k. Append supportedExtensionAddition to supportedExtension.
if (supported_extension_addition.has_value())
supported_extension.keywords.append(supported_extension_addition.release_value());
}
// 10. If the number of elements in supportedExtension is greater than 2, then
if (!supported_extension.keywords.is_empty()) {
auto locale_id = Unicode::parse_unicode_locale_id(found_locale);
VERIFY(locale_id.has_value());
// a. Let foundLocale be InsertUnicodeExtensionAndCanonicalize(foundLocale, supportedExtension).
found_locale = insert_unicode_extension_and_canonicalize(locale_id.release_value(), move(supported_extension));
}
// 11. Set result.[[locale]] to foundLocale.
result.locale = move(found_locale);
// 12. Return result.
return result;
}
// 9.2.8 LookupSupportedLocales ( availableLocales, requestedLocales ), https://tc39.es/ecma402/#sec-lookupsupportedlocales
Vector<String> lookup_supported_locales(Vector<String> const& requested_locales)
{
// 1. Let subset be a new empty List.
Vector<String> subset;
// 2. For each element locale of requestedLocales, do
for (auto const& locale : requested_locales) {
auto locale_id = Unicode::parse_unicode_locale_id(locale);
VERIFY(locale_id.has_value());
// a. Let noExtensionsLocale be the String value that is locale with any Unicode locale extension sequences removed.
locale_id->remove_extension_type<Unicode::LocaleExtension>();
auto no_extensions_locale = locale_id->to_string();
// b. Let availableLocale be BestAvailableLocale(availableLocales, noExtensionsLocale).
auto available_locale = best_available_locale(no_extensions_locale);
// c. If availableLocale is not undefined, append locale to the end of subset.
if (available_locale.has_value())
subset.append(locale);
}
// 3. Return subset.
return subset;
}
// 9.2.9 BestFitSupportedLocales ( availableLocales, requestedLocales ), https://tc39.es/ecma402/#sec-bestfitsupportedlocales
Vector<String> best_fit_supported_locales(Vector<String> const& requested_locales)
{
// The BestFitSupportedLocales abstract operation returns the subset of the provided BCP 47
// language priority list requestedLocales for which availableLocales has a matching locale
// when using the Best Fit Matcher algorithm. Locales appear in the same order in the returned
// list as in requestedLocales. The steps taken are implementation dependent.
// :yakbrain:
return lookup_supported_locales(requested_locales);
}
// 9.2.10 SupportedLocales ( availableLocales, requestedLocales, options ), https://tc39.es/ecma402/#sec-supportedlocales
Array* supported_locales(GlobalObject& global_object, Vector<String> const& requested_locales, Value options)
{
auto& vm = global_object.vm();
// 1. Set options to ? CoerceOptionsToObject(options).
auto* options_object = coerce_options_to_object(global_object, options);
if (vm.exception())
return {};
// 2. Let matcher be ? GetOption(options, "localeMatcher", "string", « "lookup", "best fit" », "best fit").
auto matcher = get_option(global_object, options_object, vm.names.localeMatcher, Value::Type::String, { "lookup"sv, "best fit"sv }, "best fit"sv);
if (vm.exception())
return {};
Vector<String> supported_locales;
// 3. If matcher is "best fit", then
if (matcher.as_string().string() == "best fit"sv) {
// a. Let supportedLocales be BestFitSupportedLocales(availableLocales, requestedLocales).
supported_locales = best_fit_supported_locales(requested_locales);
}
// 4. Else,
else {
// a. Let supportedLocales be LookupSupportedLocales(availableLocales, requestedLocales).
supported_locales = lookup_supported_locales(requested_locales);
}
// 5. Return CreateArrayFromList(supportedLocales).
return Array::create_from<String>(global_object, supported_locales, [&vm](auto& locale) { return js_string(vm, locale); });
}
// 9.2.12 CoerceOptionsToObject ( options ), https://tc39.es/ecma402/#sec-coerceoptionstoobject
Object* coerce_options_to_object(GlobalObject& global_object, Value options)
{
// 1. If options is undefined, then
if (options.is_undefined()) {
// a. Return ! OrdinaryObjectCreate(null).
return Object::create(global_object, nullptr);
}
// 2. Return ? ToObject(options).
return options.to_object(global_object);
}
// 9.2.13 GetOption ( options, property, type, values, fallback ), https://tc39.es/ecma402/#sec-getoption
Value get_option(GlobalObject& global_object, Value options, PropertyName const& property, Value::Type type, Vector<StringView> const& values, Fallback fallback)
{
auto& vm = global_object.vm();
// 1. Assert: Type(options) is Object.
VERIFY(options.is_object());
// 2. Let value be ? Get(options, property).
auto value = options.get(global_object, property);
if (vm.exception())
return {};
// 3. If value is undefined, return fallback.
if (value.is_undefined()) {
return fallback.visit(
[](Empty) { return js_undefined(); },
[](bool f) { return Value(f); },
[&vm](StringView f) { return Value(js_string(vm, f)); });
}
// 4. Assert: type is "boolean" or "string".
VERIFY((type == Value::Type::Boolean) || (type == Value::Type::String));
// 5. If type is "boolean", then
if (type == Value::Type::Boolean) {
// a. Let value be ! ToBoolean(value).
value = Value(value.to_boolean());
}
// 6. If type is "string", then
else {
// a. Let value be ? ToString(value).
value = value.to_primitive_string(global_object);
if (vm.exception())
return {};
}
// 7. If values is not undefined and values does not contain an element equal to value, throw a RangeError exception.
if (!values.is_empty()) {
// Note: Every location in the spec that invokes GetOption with type=boolean also has values=undefined.
VERIFY(value.is_string());
if (!values.contains_slow(value.as_string().string())) {
vm.throw_exception<RangeError>(global_object, ErrorType::OptionIsNotValidValue, value.to_string_without_side_effects(), property.as_string());
return {};
}
}
// 8. Return value.
return value;
}
// 9.2.14 DefaultNumberOption ( value, minimum, maximum, fallback ), https://tc39.es/ecma402/#sec-defaultnumberoption
Optional<int> default_number_option(GlobalObject& global_object, Value value, int minimum, int maximum, Optional<int> fallback)
{
auto& vm = global_object.vm();
// 1. If value is undefined, return fallback.
if (value.is_undefined())
return fallback;
// 2. Let value be ? ToNumber(value).
value = value.to_number(global_object);
if (vm.exception())
return {};
// 3. If value is NaN or less than minimum or greater than maximum, throw a RangeError exception.
if (value.is_nan() || (value.as_double() < minimum) || (value.as_double() > maximum)) {
vm.throw_exception<RangeError>(global_object, ErrorType::IntlNumberIsNaNOrOutOfRange, value, minimum, maximum);
return {};
}
// 4. Return floor(value).
return floor(value.as_double());
}
// 9.2.15 GetNumberOption ( options, property, minimum, maximum, fallback ), https://tc39.es/ecma402/#sec-getnumberoption
Optional<int> get_number_option(GlobalObject& global_object, Object& options, PropertyName const& property, int minimum, int maximum, Optional<int> fallback)
{
auto& vm = global_object.vm();
// 1. Assert: Type(options) is Object.
// 2. Let value be ? Get(options, property).
auto value = options.get(property);
if (vm.exception())
return {};
// 3. Return ? DefaultNumberOption(value, minimum, maximum, fallback).
return default_number_option(global_object, value, minimum, maximum, fallback);
}
// 9.2.16 PartitionPattern ( pattern ), https://tc39.es/ecma402/#sec-partitionpattern
Vector<PatternPartition> partition_pattern(StringView pattern)
{
// 1. Let result be a new empty List.
Vector<PatternPartition> result;
// 2. Let beginIndex be ! StringIndexOf(pattern, "{", 0).
auto begin_index = pattern.find('{', 0);
// 3. Let endIndex be 0.
size_t end_index = 0;
// 4. Let nextIndex be 0.
size_t next_index = 0;
// 5. Let length be the number of code units in pattern.
// 6. Repeat, while beginIndex is an integer index into pattern,
while (begin_index.has_value()) {
// a. Set endIndex to ! StringIndexOf(pattern, "}", beginIndex).
end_index = pattern.find('}', *begin_index).value();
// b. Assert: endIndex is greater than beginIndex.
VERIFY(end_index > *begin_index);
// c. If beginIndex is greater than nextIndex, then
if (*begin_index > next_index) {
// i. Let literal be a substring of pattern from position nextIndex, inclusive, to position beginIndex, exclusive.
auto literal = pattern.substring_view(next_index, *begin_index - next_index);
// ii. Append a new Record { [[Type]]: "literal", [[Value]]: literal } as the last element of the list result.
result.append({ "literal"sv, literal });
}
// d. Let p be the substring of pattern from position beginIndex, exclusive, to position endIndex, exclusive.
auto partition = pattern.substring_view(*begin_index + 1, end_index - *begin_index - 1);
// e. Append a new Record { [[Type]]: p, [[Value]]: undefined } as the last element of the list result.
result.append({ partition, {} });
// f. Set nextIndex to endIndex + 1.
next_index = end_index + 1;
// g. Set beginIndex to ! StringIndexOf(pattern, "{", nextIndex).
begin_index = pattern.find('{', next_index);
}
// 7. If nextIndex is less than length, then
if (next_index < pattern.length()) {
// a. Let literal be the substring of pattern from position nextIndex, inclusive, to position length, exclusive.
auto literal = pattern.substring_view(next_index);
// b. Append a new Record { [[Type]]: "literal", [[Value]]: literal } as the last element of the list result.
result.append({ "literal"sv, literal });
}
// 8. Return result.
return result;
}
// 12.1.1 CanonicalCodeForDisplayNames ( type, code ), https://tc39.es/ecma402/#sec-canonicalcodefordisplaynames
Value canonical_code_for_display_names(GlobalObject& global_object, DisplayNames::Type type, StringView code)
{
auto& vm = global_object.vm();
// 1. If type is "language", then
if (type == DisplayNames::Type::Language) {
// a. If code does not match the unicode_language_id production, throw a RangeError exception.
if (!Unicode::parse_unicode_language_id(code).has_value()) {
vm.throw_exception<RangeError>(global_object, ErrorType::OptionIsNotValidValue, code, "language"sv);
return {};
}
// b. If IsStructurallyValidLanguageTag(code) is false, throw a RangeError exception.
auto locale_id = is_structurally_valid_language_tag(code);
if (!locale_id.has_value()) {
vm.throw_exception<RangeError>(global_object, ErrorType::IntlInvalidLanguageTag, code);
return {};
}
// c. Set code to CanonicalizeUnicodeLocaleId(code).
// d. Return code.
auto canonicalized_tag = JS::Intl::canonicalize_unicode_locale_id(*locale_id);
return js_string(vm, move(canonicalized_tag));
}
// 2. If type is "region", then
if (type == DisplayNames::Type::Region) {
// a. If code does not match the unicode_region_subtag production, throw a RangeError exception.
if (!Unicode::is_unicode_region_subtag(code)) {
vm.throw_exception<RangeError>(global_object, ErrorType::OptionIsNotValidValue, code, "region"sv);
return {};
}
// b. Let code be the result of mapping code to upper case as described in 6.1.
// c. Return code.
return js_string(vm, code.to_uppercase_string());
}
// 3. If type is "script", then
if (type == DisplayNames::Type::Script) {
// a. If code does not match the unicode_script_subtag production, throw a RangeError exception.
if (!Unicode::is_unicode_script_subtag(code)) {
vm.throw_exception<RangeError>(global_object, ErrorType::OptionIsNotValidValue, code, "script"sv);
return {};
}
// b. Let code be the result of mapping the first character in code to upper case, and mapping the second, third, and fourth character in code to lower case, as described in 6.1.
// c. Return code.
return js_string(vm, code.to_titlecase_string());
}
// 4. Assert: type is "currency".
VERIFY(type == DisplayNames::Type::Currency);
// 5. If ! IsWellFormedCurrencyCode(code) is false, throw a RangeError exception.
if (!is_well_formed_currency_code(code)) {
vm.throw_exception<RangeError>(global_object, ErrorType::OptionIsNotValidValue, code, "currency"sv);
return {};
}
// 6. Let code be the result of mapping code to upper case as described in 6.1.
// 7. Return code.
return js_string(vm, code.to_uppercase_string());
}
}
|
/*************************************************************************
* Copyright 2018 Reegan Troy Layzell
*
* 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 "rush/core/source_manager.hpp"
|
#include "Metal.h"
Metal::Metal(const color3& a)
{
albedo = a;
}
Metal::Metal(const color3& a, double f)
{
albedo = a;
fuzz = f;
}
bool Metal::Scatter(const Ray& RayIn, const hitRecord& record, color3& attenuation, Ray& scattered) const
{
vec3 reflected = Reflect(RayIn.dir.normalized(), record.normal);
if (fuzz)
{
scattered = Ray(record.p, reflected + fuzz * RandomInHitUintSphere());
}
else
{
scattered = Ray(record.p, reflected);
}
attenuation = albedo;
return (scattered.dir.dot(record.normal) > 0);
}
|
/*
GEODIFF - MIT License
Copyright (C) 2020 Martin Dobias
*/
#include "changesetreader.h"
#include "geodiffutils.hpp"
#include "changesetvarint.h"
#include "portableendian.h"
#include <assert.h>
#include <memory.h>
#include <sstream>
ChangesetReader::ChangesetReader() = default;
ChangesetReader::~ChangesetReader() = default;
bool ChangesetReader::open( const std::string &filename )
{
try
{
mBuffer.reset( new Buffer );
mBuffer->read( filename );
}
catch ( GeoDiffException )
{
return false;
}
return true;
}
bool ChangesetReader::nextEntry( ChangesetEntry &entry )
{
while ( 1 )
{
if ( mOffset >= mBuffer->size() )
break; // EOF
int type = readByte();
if ( type == 'T' )
{
readTableRecord();
// and now continue reading, we want an entry
}
else if ( type == ChangesetEntry::OpInsert || type == ChangesetEntry::OpUpdate || type == ChangesetEntry::OpDelete )
{
int indirect = readByte();
if ( type != ChangesetEntry::OpInsert )
readRowValues( entry.oldValues );
else
entry.oldValues.erase( entry.oldValues.begin(), entry.oldValues.end() );
if ( type != ChangesetEntry::OpDelete )
readRowValues( entry.newValues );
else
entry.newValues.erase( entry.newValues.begin(), entry.newValues.end() );
entry.op = static_cast<ChangesetEntry::OperationType>( type );
entry.table = &mCurrentTable;
return true; // we're done!
}
else
{
throwReaderError( "Unknown entry type " + std::to_string( type ) );
}
}
return false;
}
bool ChangesetReader::isEmpty() const
{
return mBuffer->size() == 0;
}
void ChangesetReader::rewind()
{
mOffset = 0;
mCurrentTable = ChangesetTable();
}
char ChangesetReader::readByte()
{
if ( mOffset >= mBuffer->size() )
throwReaderError( "readByte: at the end of buffer" );
const char *ptr = mBuffer->c_buf() + mOffset;
++mOffset;
return *ptr;
}
int ChangesetReader::readVarint()
{
u32 value;
const unsigned char *ptr = ( const unsigned char * )mBuffer->c_buf() + mOffset;
int nBytes = getVarint32( ptr, value );
mOffset += nBytes;
return value;
}
std::string ChangesetReader::readNullTerminatedString()
{
const char *ptr = mBuffer->c_buf() + mOffset;
int count = 0;
while ( mOffset + count < mBuffer->size() && ptr[count] )
++count;
if ( mOffset + count >= mBuffer->size() )
throwReaderError( "readNullTerminatedString: at the end of buffer" );
mOffset += count + 1;
return std::string( ptr, count );
}
void ChangesetReader::readRowValues( std::vector<Value> &values )
{
// let's ensure we have the right size of array
if ( values.size() != mCurrentTable.columnCount() )
{
values.resize( mCurrentTable.columnCount() );
}
for ( size_t i = 0; i < mCurrentTable.columnCount(); ++i )
{
int type = readByte();
if ( type == Value::TypeInt ) // 0x01
{
// 64-bit int (big endian)
int64_t v;
uint64_t x;
memcpy( &x, mBuffer->c_buf() + mOffset, 8 );
mOffset += 8;
x = be64toh( x ); // convert big endian to host
memcpy( &v, &x, 8 );
values[i].setInt( v );
}
else if ( type == Value::TypeDouble ) // 0x02
{
// 64-bit double (big endian)
double v;
uint64_t x;
memcpy( &x, mBuffer->c_buf() + mOffset, 8 );
mOffset += 8;
x = be64toh( x ); // convert big endian to host
memcpy( &v, &x, 8 );
values[i].setDouble( v );
}
else if ( type == Value::TypeText || type == Value::TypeBlob ) // 0x03 or 0x04
{
int len = readVarint();
if ( mOffset + len > mBuffer->size() )
throwReaderError( "readRowValues: text/blob: at the end of buffer" );
values[i].setString( type == Value::TypeText ? Value::TypeText : Value::TypeBlob, mBuffer->c_buf() + mOffset, len );
mOffset += len;
}
else if ( type == Value::TypeNull ) // 0x05
{
values[i].setNull();
}
else if ( type == Value::TypeUndefined ) // undefined value (different from NULL)
{
values[i].setUndefined();
}
else
{
throwReaderError( "readRowValues: unexpected entry type" );
}
}
}
void ChangesetReader::readTableRecord()
{
/* A 'table' record consists of:
**
** * A constant 'T' character,
** * Number of columns in said table (a varint),
** * An array of nCol bytes (sPK),
** * A nul-terminated table name.
*/
int nCol = readVarint();
if ( nCol < 0 || nCol > 65536 )
throwReaderError( "readByte: unexpected number of columns" );
mCurrentTable.primaryKeys.clear();
for ( int i = 0; i < nCol; ++i )
{
mCurrentTable.primaryKeys.push_back( readByte() );
}
mCurrentTable.name = readNullTerminatedString();
}
void ChangesetReader::throwReaderError( const std::string &message )
{
std::ostringstream stringStream;
stringStream << "Reader error at offset " << mOffset << ":\n" << message;
std::string str = stringStream.str();
throw GeoDiffException( str );
}
|
//
// Copyright 2019 DreamWorks Animation
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
/// @file FuserOpenSubdiv.cpp
///
/// @author Jonathan Egstad
#include <Fuser/ArgConstants.h> // for attrib names constants
#include <Fuser/Node.h>
#include <Fuser/MeshPrimitive.h>
#include <Fuser/ExecuteTargetContexts.h> // for MeshTessellateContext
//#include <DDImage/PrimitiveContext.h>
#if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8)
#else
// Turn off -Wconversion warnings when including Opensubdiv headers:
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wconversion"
# include <opensubdiv/far/topologyDescriptor.h>
# include <opensubdiv/far/primvarRefiner.h>
# pragma GCC diagnostic pop
#endif
namespace Fsr {
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
// Wrap Fuser vector classes for OpenSubdiv use.
// See opensubdiv/far/primvarRefiner.h and opensubdiv/hbr/fvarData.h:
// <snip>
// Interpolation methods template both the source and destination
// data buffer classes. Client-code is expected to provide interfaces
// that implement the functions specific to its primitive variable
// data layout. Template APIs must implement the following:
//
// class MySource {
// MySource & operator[](int index);
// };
//
// class MyDestination {
// void Clear();
// void AddWithWeight(MySource const & value, float weight);
// void AddWithWeight(MyDestination const & value, float weight);
// };
// </snip>
//
// Fsr::Vec classes already have [] defined so we just need to expose
// setToZero() and implement AddWithWeight().
class OsdFloat
{
public:
void Clear() { val = 0.0f; }
void AddWithWeight(OsdFloat const& b, float weight) { val += b.val*weight; }
protected:
float val;
};
class OsdVec2f : public Fsr::Vec2f
{
public:
void Clear() { setToZero(); }
void AddWithWeight(OsdVec2f const& b, float weight) { *this += b*weight; }
};
class OsdVec3f : public Fsr::Vec3f
{
public:
void Clear() { setToZero(); }
void AddWithWeight(OsdVec3f const& b, float weight) { *this += b*weight; }
};
class OsdVec4f : public Fsr::Vec4f
{
public:
void Clear() { setToZero(); }
void AddWithWeight(OsdVec4f const& b, float weight) { *this += b*weight; }
};
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
/*!
*/
class FuserOpenSubdiv : public Fsr::Node
{
public:
//! For create() method to instantiate this node by name.
static const Fsr::Node::Description description;
//! Returns the class name, must implement.
/*virtual*/ const char* fuserNodeClass() const { return description.fuserNodeClass(); }
//!
FuserOpenSubdiv(const Fsr::ArgSet& args,
Fsr::Node* parent) :
Fsr::Node(args, parent)
{
//std::cout << " FuserOpenSubdiv::ctor(" << this << ")" << std::endl;
#if 0
if (m_debug)
{
std::cout << " FuserOpenSubdiv::ctor(" << this << ")" << std::endl;
}
#endif
}
//!
~FuserOpenSubdiv()
{
//std::cout << " FuserOpenSubdiv::dtor(" << this << ")" << std::endl;
}
/*! Called before execution to allow node to update local data from args.
Updates time value and possibly local matrix transform.
*/
/*virtual*/ void _validateState(const Fsr::NodeContext& exec_ctx,
bool for_real)
{
//std::cout << " FuserOpenSubdiv::_validateState(" << this << ")" << std::endl;
Fsr::Node::_validateState(exec_ctx, for_real);
}
//! Prints an unrecognized-target warning in debug mode and returns 0 (success).
/*virtual*/ int _execute(const Fsr::NodeContext& target_context,
const char* target_name,
void* target,
void* src0,
void* src1)
{
// We need a context and a target name to figure out what to do:
if (!target_name || !target_name[0])
return -1; // no context target!
//std::cout << " FuserOpenSubdiv::execute(" << this << ") target='" << target_name << "'";
//std::cout << " [" << target_context.args() << " ]" << std::endl;
if (strcmp(target_name, Fsr::MeshTessellateContext::name)==0)
{
Fsr::MeshTessellateContext* tessellate_ctx =
reinterpret_cast<Fsr::MeshTessellateContext*>(target);
// Any null pointers throw a coding error:
if (!tessellate_ctx)
return error("null objects in target '%s'. This is likely a coding error", target_name);
subdivideGenericMesh(target_context.args(), *tessellate_ctx);
return 0; // success
}
else if (strcmp(target_name, Fsr::MeshPrimitive::TessellateContext::name)==0)
{
Fsr::MeshPrimitive::TessellateContext* tessellate_ctx =
reinterpret_cast<Fsr::MeshPrimitive::TessellateContext*>(target);
// Any null pointers throw a coding error:
if (!tessellate_ctx || !tessellate_ctx->vbuffers)
return error("null objects in target '%s'. This is likely a coding error", target_name);
subdivideVertexBuffer(target_context.args(), *tessellate_ctx->vbuffers);
return 0; // success
}
// Don't throw an error on an unrecognized target:
if (debug())
{
std::cerr << fuserNodeClass() << ": warning, cannot handle target type '" << target_name << "'";
std::cerr << ", ignoring." << std::endl;
}
return 0; // no user-abort
}
//! Return the appropriate refiner object for the given arguments and topology descriptor.
OpenSubdiv::Far::TopologyRefiner* getRefiner(const Fsr::ArgSet& exec_args,
int32_t nRefinementLevels,
const OpenSubdiv::Far::TopologyDescriptor& desc);
//!
void subdivideGenericMesh(const Fsr::ArgSet& exec_args,
Fsr::MeshTessellateContext& tess_ctx);
//!
void subdivideVertexBuffer(const Fsr::ArgSet& exec_args,
Fsr::PointBasedPrimitive::VertexBuffers& vbuffers);
};
//-------------------------------------------------------------------------
/*! Return the appropriate refiner object for the given arguments.
*/
OpenSubdiv::Far::TopologyRefiner*
FuserOpenSubdiv::getRefiner(const Fsr::ArgSet& exec_args,
int32_t nRefinementLevels,
const OpenSubdiv::Far::TopologyDescriptor& desc)
{
const std::string scheme = exec_args.getString("subd:scheme", "catmullclark"/*default*/);
OpenSubdiv::Sdc::SchemeType type;
if (scheme == "catmullclark") type = OpenSubdiv::Sdc::SCHEME_CATMARK;
else if (scheme == "loop" ) type = OpenSubdiv::Sdc::SCHEME_LOOP;
else if (scheme == "bilinear" ) type = OpenSubdiv::Sdc::SCHEME_BILINEAR;
else
{
// TODO: throw unrecognized-scheme warning
type = OpenSubdiv::Sdc::SCHEME_CATMARK;
}
// TODO: these are set to DWA defaults, also check primvars copied in from file meshes:
OpenSubdiv::Sdc::Options options;
options.SetVtxBoundaryInterpolation(OpenSubdiv::Sdc::Options::VTX_BOUNDARY_EDGE_AND_CORNER);
options.SetFVarLinearInterpolation(OpenSubdiv::Sdc::Options::FVAR_LINEAR_CORNERS_ONLY);
options.SetCreasingMethod(OpenSubdiv::Sdc::Options::CREASE_UNIFORM);
options.SetTriangleSubdivision(OpenSubdiv::Sdc::Options::TRI_SUB_CATMARK);
// Create a FarTopologyRefiner from the descriptor:
OpenSubdiv::Far::TopologyRefiner* refiner =
OpenSubdiv::Far::TopologyRefinerFactory<OpenSubdiv::Far::TopologyDescriptor>::Create(desc,
OpenSubdiv::Far::TopologyRefinerFactory<OpenSubdiv::Far::TopologyDescriptor>::Options(type, options));
assert(refiner);
// Declare how we're doing refinement to the desired target level:
// TODO: support other refinement types like adaptive?
if (1)
{
// TODO: these are set to DWA defaults, also check primvars copied in from file meshes:
OpenSubdiv::Far::TopologyRefiner::UniformOptions refine_options(nRefinementLevels);
refine_options.orderVerticesFromFacesFirst = false;
refine_options.fullTopologyInLastLevel = false;
refiner->RefineUniform(refine_options);
}
else
{
// TODO: these are set to DWA defaults, also check primvars copied in from file meshes:
OpenSubdiv::Far::TopologyRefiner::AdaptiveOptions refine_options(nRefinementLevels);
refine_options.secondaryLevel = 15;
refine_options.useSingleCreasePatch = false;
refine_options.useInfSharpPatch = false;
refine_options.considerFVarChannels = false;
refine_options.orderVerticesFromFacesFirst = false;
refiner->RefineAdaptive(refine_options);
}
return refiner;
}
//!
void
FuserOpenSubdiv::subdivideGenericMesh(const Fsr::ArgSet& exec_args,
Fsr::MeshTessellateContext& tess_ctx)
{
if (!tess_ctx.verts_per_face ||
!tess_ctx.vert_position_indices ||
tess_ctx.position_lists.size() == 0 ||
!tess_ctx.position_lists[0])
return; // don't crash...
const int32_t nSrcFaces = (int32_t)tess_ctx.verts_per_face->size();
const int32_t nSrcVerts = (int32_t)tess_ctx.vert_position_indices->size();
const int32_t nSrcPoints = (int32_t)tess_ctx.position_lists[0]->size();
if (nSrcFaces == 0 || nSrcVerts == 0 || nSrcPoints == 0)
return; // don't crash...
const int32_t current_subd_level = exec_args.getInt("subd:current_level", 0/*default*/);
const int32_t target_subd_level = exec_args.getInt("subd:target_level", 0/*default*/);
//const std::string subd_scheme = exec_args.getString("subd:scheme");
const int nRefinementLevels = (target_subd_level - current_subd_level);
//std::cout << " FuserOpenSubdiv::subdivide()";
//std::cout << ", nSrcFaces=" << nSrcFaces;
//std::cout << ", nSrcVerts=" << nSrcVerts;
//std::cout << ", nSrcPoints=" << nSrcPoints;
//std::cout << ", current_subd_level=" << current_subd_level;
//std::cout << ", target_subd_level=" << target_subd_level;
//std::cout << std::endl;
#if 0
std::cout << "src faces:" << std::endl;
for (size_t p=0; p < tess_ctx.verts_per_face->size(); ++p)
std::cout << " " << p << ": " << (*tess_ctx.verts_per_face)[p] << std::endl;
std::cout << "src point indices:" << std::endl;
for (size_t p=0; p < tess_ctx.vert_position_indices->size(); ++p)
std::cout << " " << p << ": " << (*tess_ctx.vert_position_indices)[p] << std::endl;
for (size_t j=0; j < tess_ctx.position_lists.size(); ++j)
{
Fsr::Vec3fList& P_list = *tess_ctx.position_lists[j];
std::cout << "src points[" << j << "]:" << std::endl;
for (size_t i=0; i < P_list.size(); ++i)
std::cout << " " << i << P_list[i] << std::endl;
}
//for (size_t j=0; j < tess_ctx.vert_vec3_attribs.size(); ++j)
//{
// Fsr::Vec3fList& vec3_list = *tess_ctx.vert_vec3_attribs[j];
// std::cout << "src vec3s[" << j << "]:" << std::endl;
// for (size_t i=0; i < vec3_list.size(); ++i)
// std::cout << " " << i << vec3_list[i] << std::endl;
//}
#endif
if (nRefinementLevels <= 0)
return; // no need to further subdivide
// Attribs are already expanded to vertex rate so the primvar index arrays
// will all point at the same indice array:
std::vector<int32_t> fvarIndices(nSrcVerts);
for (int32_t i=0; i < nSrcVerts; ++i)
fvarIndices[i] = i;
// Get number of Fvars and set up channel list:
const int32_t nFvarChans = (int32_t)(tess_ctx.vert_float_attribs.size() +
tess_ctx.vert_vec2_attribs.size() +
tess_ctx.vert_vec3_attribs.size() +
tess_ctx.vert_vec4_attribs.size());
OpenSubdiv::Far::TopologyDescriptor::FVarChannel primvar_channels[nFvarChans];
for (size_t i=0; i < nFvarChans; ++i)
{
primvar_channels[i].numValues = nSrcVerts;
primvar_channels[i].valueIndices = fvarIndices.data();
}
OpenSubdiv::Far::TopologyDescriptor desc;
desc.numVertices = nSrcPoints; // points count, not verts!
desc.numFaces = nSrcFaces;
desc.numVertsPerFace = reinterpret_cast<const int32_t*>(tess_ctx.verts_per_face->data());
desc.vertIndicesPerFace = reinterpret_cast<const int32_t*>(tess_ctx.vert_position_indices->data()); // at per-vert rate, not per-face!!!!
//
desc.numFVarChannels = nFvarChans;
desc.fvarChannels = primvar_channels;
// Create a FarTopologyRefiner from the descriptor:
OpenSubdiv::Far::TopologyRefiner* refiner = getRefiner(exec_args, nRefinementLevels, desc);
OpenSubdiv::Far::PrimvarRefiner primvarRefiner(*refiner);
//const size_t nTotalRefinedFaces = refiner->GetNumFacesTotal();
const size_t nTotalRefinedVerts = (nFvarChans > 0) ?
refiner->GetNumFVarValuesTotal(0/*fvarChannelIdx*/) : 0;
const size_t nTotalRefinedPoints = refiner->GetNumVerticesTotal();
//std::cout << " nTotalRefinedFaces=" << refiner->GetNumFacesTotal();
//std::cout << ", nTotalRefinedPoints=" << nTotalRefinedPoints;
//std::cout << ", nTotalRefinedVerts=" << nTotalRefinedVerts;
//std::cout << std::endl;
// Source pointer lists to swap during refinement loop:
// TODO: make a struct to hold these...
std::vector<OsdVec3f*> srcPositions(tess_ctx.position_lists.size());
std::vector<OsdFloat*> srcFloatAttribs(tess_ctx.vert_float_attribs.size());
std::vector<OsdVec2f*> srcVec2Attribs(tess_ctx.vert_vec2_attribs.size());
std::vector<OsdVec3f*> srcVec3Attribs(tess_ctx.vert_vec3_attribs.size());
std::vector<OsdVec4f*> srcVec4Attribs(tess_ctx.vert_vec4_attribs.size());
// Destination buffers to accommodate the new verts/points being added:
std::vector<Fsr::Vec3fList> refined_position_lists(tess_ctx.position_lists.size()); // point rate
std::vector<Fsr::FloatList> refined_vert_float_attribs(tess_ctx.vert_float_attribs.size()); // face-vertex rate
std::vector<Fsr::Vec2fList> refined_vert_vec2_attribs(tess_ctx.vert_vec2_attribs.size()); // face-vertex rate
std::vector<Fsr::Vec3fList> refined_vert_vec3_attribs(tess_ctx.vert_vec3_attribs.size()); // face-vertex rate
std::vector<Fsr::Vec4fList> refined_vert_vec4_attribs(tess_ctx.vert_vec4_attribs.size()); // face-vertex rate
//------------------------------------------
// Initialize positions buffers:
for (size_t i=0; i < refined_position_lists.size(); ++i)
{
#if DEBUG
assert(tess_ctx.position_lists[i] != NULL);
assert(tess_ctx.position_lists[i]->size() == nSrcPoints);
#endif
srcPositions[i] = reinterpret_cast<OsdVec3f*>(tess_ctx.position_lists[i]->data());
refined_position_lists[i].resize(nTotalRefinedPoints);
}
if (nFvarChans > 0)
{
//------------------------------------------
// Initialize fvars buffers:
for (size_t i=0; i < refined_vert_float_attribs.size(); ++i)
{
#if DEBUG
assert(tess_ctx.vert_float_attribs[i] != NULL);
assert(tess_ctx.vert_float_attribs[i]->size() == nSrcVerts);
#endif
srcFloatAttribs[i] = reinterpret_cast<OsdFloat*>(tess_ctx.vert_float_attribs[i]->data());
refined_vert_float_attribs[i].resize(nTotalRefinedVerts);
}
for (size_t i=0; i < refined_vert_vec2_attribs.size(); ++i)
{
#if DEBUG
assert(tess_ctx.vert_vec2_attribs[i] != NULL);
assert(tess_ctx.vert_vec2_attribs[i]->size() == nSrcVerts);
#endif
srcVec2Attribs[i] = reinterpret_cast<OsdVec2f*>(tess_ctx.vert_vec2_attribs[i]->data());
refined_vert_vec2_attribs[i].resize(nTotalRefinedVerts);
}
for (size_t i=0; i < refined_vert_vec3_attribs.size(); ++i)
{
#if DEBUG
assert(tess_ctx.vert_vec3_attribs[i] != NULL);
assert(tess_ctx.vert_vec3_attribs[i]->size() == nSrcVerts);
#endif
srcVec3Attribs[i] = reinterpret_cast<OsdVec3f*>(tess_ctx.vert_vec3_attribs[i]->data());
refined_vert_vec3_attribs[i].resize(nTotalRefinedVerts);
}
for (size_t i=0; i < refined_vert_vec4_attribs.size(); ++i)
{
#if DEBUG
assert(tess_ctx.vert_vec4_attribs[i] != NULL);
assert(tess_ctx.vert_vec4_attribs[i]->size() == nSrcVerts);
#endif
srcVec4Attribs[i] = reinterpret_cast<OsdVec4f*>(tess_ctx.vert_vec4_attribs[i]->data());
refined_vert_vec4_attribs[i].resize(nTotalRefinedVerts);
}
}
// Refine mesh attributes to desired level:
for (int srcLevel=0; srcLevel < nRefinementLevels; ++srcLevel)
{
const int dstLevel = (srcLevel + 1);
//std::cout << " srcLevel " << srcLevel << " dstLevel " << dstLevel << std::endl;
//------------------------------------------
// Positions:
for (size_t i=0; i < refined_position_lists.size(); ++i)
{
OsdVec3f* dst = (srcLevel == 0) ?
reinterpret_cast<OsdVec3f*>(refined_position_lists[i].data()) :
srcPositions[i];
dst += refiner->GetLevel(srcLevel).GetNumVertices();
primvarRefiner.Interpolate(dstLevel, srcPositions[i], dst);
srcPositions[i] = dst;
}
if (nFvarChans > 0)
{
//------------------------------------------
// FVars:
uint32_t fvar_chan = 0;
for (size_t i=0; i < refined_vert_float_attribs.size(); ++i, ++fvar_chan)
{
const size_t nSrcFVars = refiner->GetLevel(srcLevel).GetNumFVarValues(fvar_chan);
OsdFloat* src = srcFloatAttribs[i];
OsdFloat* dst = ((srcLevel == 0) ?
reinterpret_cast<OsdFloat*>(refined_vert_float_attribs[i].data()) :
src) + nSrcFVars;
primvarRefiner.InterpolateFaceVarying(dstLevel, src, dst, fvar_chan);
srcFloatAttribs[i] = dst;
}
for (size_t i=0; i < refined_vert_vec2_attribs.size(); ++i, ++fvar_chan)
{
const size_t nSrcFVars = refiner->GetLevel(srcLevel).GetNumFVarValues(fvar_chan);
OsdVec2f* src = srcVec2Attribs[i];
OsdVec2f* dst = ((srcLevel == 0) ?
reinterpret_cast<OsdVec2f*>(refined_vert_vec2_attribs[i].data()) :
src) + nSrcFVars;
primvarRefiner.InterpolateFaceVarying(dstLevel, src, dst, fvar_chan);
srcVec2Attribs[i] = dst;
}
for (size_t i=0; i < refined_vert_vec3_attribs.size(); ++i, ++fvar_chan)
{
const size_t nSrcFVars = refiner->GetLevel(srcLevel).GetNumFVarValues(fvar_chan);
OsdVec3f* src = srcVec3Attribs[i];
OsdVec3f* dst = ((srcLevel == 0) ?
reinterpret_cast<OsdVec3f*>(refined_vert_vec3_attribs[i].data()) :
src) + nSrcFVars;
primvarRefiner.InterpolateFaceVarying(dstLevel, src, dst, fvar_chan);
srcVec3Attribs[i] = dst;
}
for (size_t i=0; i < refined_vert_vec4_attribs.size(); ++i, ++fvar_chan)
{
const size_t nSrcFVars = refiner->GetLevel(srcLevel).GetNumFVarValues(fvar_chan);
OsdVec4f* src = srcVec4Attribs[i];
OsdVec4f* dst = ((srcLevel == 0) ?
reinterpret_cast<OsdVec4f*>(refined_vert_vec4_attribs[i].data()) :
src) + nSrcFVars;
primvarRefiner.InterpolateFaceVarying(dstLevel, src, dst, fvar_chan);
srcVec4Attribs[i] = dst;
}
}
}
// Copy refined point/vert data.
// We need to expand out the point/vert indices back to the flattened point-rate/vertex-rate:
const OpenSubdiv::Far::TopologyLevel& refLastLevel = refiner->GetLevel(nRefinementLevels);
const int32_t nLevelFaces = refLastLevel.GetNumFaces();
const int32_t nLevelVerts = nLevelFaces*4; // always quads
const int32_t nLevelPoints = refLastLevel.GetNumVertices();
const int32_t nLevelFVars = (nFvarChans > 0) ?
refLastLevel.GetNumFVarValues(0/*fvarChannelIdx*/) : 0;
// Gets the starting point & facevert index in the highest refinement level:
const int32_t levelPointsStart = (refiner->GetNumVerticesTotal() - nLevelPoints);
const int32_t levelFVarsStart = (nFvarChans > 0) ?
(refiner->GetNumFVarValuesTotal(0/*fvarChannelIdx*/) - nLevelFVars) : 0;
//std::cout << " final level " << current_subd_level+nRefinementLevels << ": nLevelFaces=" << nLevelFaces;
//std::cout << ", nLevelPoints=" << nLevelPoints;
//std::cout << ", nLevelFVars=" << nLevelFVars;
//std::cout << ", levelPointsStart=" << levelPointsStart;
//std::cout << ", levelFVarsStart=" << levelFVarsStart;
//std::cout << std::endl;
// Point data is copied straight over:
#if DEBUG
assert((levelPointsStart + nLevelPoints) <= nTotalRefinedPoints);
#endif
for (size_t i=0; i < tess_ctx.position_lists.size(); ++i)
{
tess_ctx.position_lists[i]->resize(nLevelPoints);
memcpy(tess_ctx.position_lists[i]->data(), refined_position_lists[i].data()+levelPointsStart, sizeof(Fsr::Vec3f)*nLevelPoints);
}
if (nFvarChans > 0)
{
for (size_t i=0; i < tess_ctx.vert_float_attribs.size(); ++i)
tess_ctx.vert_float_attribs[i]->resize(nLevelVerts);
for (size_t i=0; i < tess_ctx.vert_vec2_attribs.size(); ++i)
tess_ctx.vert_vec2_attribs[i]->resize(nLevelVerts);
for (size_t i=0; i < tess_ctx.vert_vec3_attribs.size(); ++i)
tess_ctx.vert_vec3_attribs[i]->resize(nLevelVerts);
for (size_t i=0; i < tess_ctx.vert_vec4_attribs.size(); ++i)
tess_ctx.vert_vec4_attribs[i]->resize(nLevelVerts);
}
//
tess_ctx.all_quads = false;
tess_ctx.all_tris = false;
uint32_t nFaceVerts;
switch (refiner->GetSchemeType())
{
default:
case OpenSubdiv::Sdc::SCHEME_CATMARK: nFaceVerts = 4; tess_ctx.all_quads = true; break;
case OpenSubdiv::Sdc::SCHEME_LOOP: nFaceVerts = 3; tess_ctx.all_tris = true; break;
case OpenSubdiv::Sdc::SCHEME_BILINEAR: nFaceVerts = 4; tess_ctx.all_quads = true; break;
}
// Face-vert attrib data needs to be de-referenced via face indices:
tess_ctx.verts_per_face->resize(nLevelFaces);
tess_ctx.vert_position_indices->resize(nLevelVerts);
uint32_t face_vert_start = 0; // global vert count
for (int32_t f=0; f < nLevelFaces; ++f)
{
const OpenSubdiv::Far::ConstIndexArray facevert_position_indices = refLastLevel.GetFaceVertices(f);
#if DEBUG
assert(facevert_position_indices.size() == nFaceVerts); // all refined faces should be same
#endif
(*tess_ctx.verts_per_face)[f] = nFaceVerts; // refined face vert count
for (uint32_t v=0; v < nFaceVerts; ++v)
(*tess_ctx.vert_position_indices)[face_vert_start+v] = facevert_position_indices[v];
// Flatten-copy the primvar values back the vert-rate buffers:
if (nFvarChans > 0)
{
//------------------------------------------
// FVars:
uint32_t fvar_chan = 0;
for (size_t i=0; i < tess_ctx.vert_float_attribs.size(); ++i, ++fvar_chan)
{
const OpenSubdiv::Far::ConstIndexArray face_fvar_indices = refLastLevel.GetFaceFVarValues(f, fvar_chan);
//
const float* src = refined_vert_float_attribs[i].data() + levelFVarsStart;
float* dst = tess_ctx.vert_float_attribs[i]->data() + face_vert_start;
for (int v=0; v < nFaceVerts; ++v)
*dst++ = src[face_fvar_indices[v]];
}
for (size_t i=0; i < tess_ctx.vert_vec2_attribs.size(); ++i, ++fvar_chan)
{
const OpenSubdiv::Far::ConstIndexArray face_fvar_indices = refLastLevel.GetFaceFVarValues(f, fvar_chan);
//
const Fsr::Vec2f* src = refined_vert_vec2_attribs[i].data() + levelFVarsStart;
Fsr::Vec2f* dst = tess_ctx.vert_vec2_attribs[i]->data() + face_vert_start;
for (int v=0; v < nFaceVerts; ++v)
*dst++ = src[face_fvar_indices[v]];
}
for (size_t i=0; i < tess_ctx.vert_vec3_attribs.size(); ++i, ++fvar_chan)
{
const OpenSubdiv::Far::ConstIndexArray face_fvar_indices = refLastLevel.GetFaceFVarValues(f, fvar_chan);
//
const Fsr::Vec3f* src = refined_vert_vec3_attribs[i].data() + levelFVarsStart;
Fsr::Vec3f* dst = tess_ctx.vert_vec3_attribs[i]->data() + face_vert_start;
for (int v=0; v < nFaceVerts; ++v)
*dst++ = src[face_fvar_indices[v]];
}
for (size_t i=0; i < tess_ctx.vert_vec4_attribs.size(); ++i, ++fvar_chan)
{
const OpenSubdiv::Far::ConstIndexArray face_fvar_indices = refLastLevel.GetFaceFVarValues(f, fvar_chan);
//
const Fsr::Vec4f* src = refined_vert_vec4_attribs[i].data() + levelFVarsStart;
Fsr::Vec4f* dst = tess_ctx.vert_vec4_attribs[i]->data() + face_vert_start;
for (int v=0; v < nFaceVerts; ++v)
*dst++ = src[face_fvar_indices[v]];
}
}
face_vert_start += nFaceVerts;
}
}
/*!
*/
void
FuserOpenSubdiv::subdivideVertexBuffer(const Fsr::ArgSet& exec_args,
Fsr::PointBasedPrimitive::VertexBuffers& vbuffers)
{
const int32_t nSrcPoints = (int32_t)vbuffers.numPoints();
const int32_t nSrcVerts = (int32_t)vbuffers.numVerts();
const int32_t nSrcFaces = (int32_t)vbuffers.numFaces();
if (nSrcPoints == 0 || nSrcVerts == 0 || nSrcFaces == 0)
return; // don't crash...
const int32_t current_subd_level = exec_args.getInt("subd:current_level", 0/*default*/);
const int32_t target_subd_level = exec_args.getInt("subd:target_level", 0/*default*/);
const int nRefinementLevels = (target_subd_level - current_subd_level);
//std::cout << " FuserOpenSubdiv::subdivideVertexBuffer()";
//std::cout << ", nSrcVerts=" << nSrcVerts;
//std::cout << ", nSrcFaces=" << nSrcFaces;
//std::cout << ", current_subd_level=" << current_subd_level;
//std::cout << ", target_subd_level=" << target_subd_level;
//std::cout << std::endl;
if (nRefinementLevels <= 0)
return; // no need to further subdivide
// VertexBuffers are already expanded to vertex rate (point-rate attribs are promoted
// to vertex-rate) so the primvar index arrays will all point at the same array:
std::vector<int32_t> fvarIndices(nSrcVerts);
for (int32_t i=0; i < nSrcVerts; ++i)
fvarIndices[i] = i;
// MUST HAVE AT LEAST ONE FVAR SO WE CAN SIZE THE VERTEX-RATE ARRAYS!
// vbuffer.Pidx is guaranteed to be the vertex-rate count, but after
// refinement we need to use one of the fvar channels to find the
// new vertex count since the point count will no longer match.
// Always enable UV fvar even if it's filled with zeros.
const int32_t nFvarChans = 1 + 1;
const int32_t uv_fvar_chan = 0; // TODO: this may be empty, handle this!
const int32_t Cf_fvar_chan = 1; // TODO: this may be empty, handle this!
OpenSubdiv::Far::TopologyDescriptor::FVarChannel primvar_channels[nFvarChans];
{
// TODO: support more than just UV/Cf primvars? Probably not for ScanlineRender.
primvar_channels[uv_fvar_chan].numValues = nSrcVerts;
primvar_channels[uv_fvar_chan].valueIndices = fvarIndices.data();
primvar_channels[Cf_fvar_chan].numValues = nSrcVerts;
primvar_channels[Cf_fvar_chan].valueIndices = fvarIndices.data();
}
OpenSubdiv::Far::TopologyDescriptor desc;
desc.numVertices = nSrcPoints; // points count, not verts!
desc.numFaces = nSrcFaces;
desc.numVertsPerFace = reinterpret_cast<const int32_t*>(vbuffers.vertsPerFace.data());
desc.vertIndicesPerFace = reinterpret_cast<const int32_t*>(vbuffers.Pidx.data()); // at per-vert rate, not per-face!!!!
//
desc.numFVarChannels = nFvarChans;
desc.fvarChannels = primvar_channels;
// Create a FarTopologyRefiner from the descriptor:
OpenSubdiv::Far::TopologyRefiner* refiner = getRefiner(exec_args, nRefinementLevels, desc);
//std::cout << " GetNumFVarValuesTotal=" << refiner->GetNumFVarValuesTotal(uv_fvar_chan);
//std::cout << ", GetNumFacesTotal=" << refiner->GetNumFacesTotal();
//std::cout << ", GetNumVerticesTotal=" << refiner->GetNumVerticesTotal();
//std::cout << std::endl;
// Create a destination vertex buffer to accommodate the new verts/points to be added:
Fsr::PointBasedPrimitive::VertexBuffers refine_vbuffers(refiner->GetNumVerticesTotal(),
refiner->GetNumFVarValuesTotal(uv_fvar_chan));
{
// TODO: this doesn't need to be a VertexBuffer object, just a list of vectors tied
// to the primvars we want to refine.
// Copy the current level data:
memcpy(refine_vbuffers.PL.data(), vbuffers.PL.data(), sizeof(Fsr::Vec3f)*nSrcPoints);
memcpy(refine_vbuffers.UV.data(), vbuffers.UV.data(), sizeof(Fsr::Vec4f)*nSrcVerts );
memcpy(refine_vbuffers.Cf.data(), vbuffers.Cf.data(), sizeof(Fsr::Vec4f)*nSrcVerts );
}
// Refine mesh to desired level:
OpenSubdiv::Far::PrimvarRefiner primvarRefiner(*refiner);
OsdVec3f* srcPoints = reinterpret_cast<OsdVec3f*>(refine_vbuffers.PL.data());
OsdVec4f* srcUVs = reinterpret_cast<OsdVec4f*>(refine_vbuffers.UV.data());
OsdVec4f* srcColors = reinterpret_cast<OsdVec4f*>(refine_vbuffers.Cf.data());
for (int level=1; level <= nRefinementLevels; ++level)
{
OsdVec3f* dstPoints = srcPoints + refiner->GetLevel(level-1).GetNumVertices();
OsdVec4f* dstUVs = srcUVs + refiner->GetLevel(level-1).GetNumFVarValues(uv_fvar_chan);
OsdVec4f* dstColors = srcColors + refiner->GetLevel(level-1).GetNumFVarValues(Cf_fvar_chan);
primvarRefiner.Interpolate(level, srcPoints, dstPoints);
primvarRefiner.InterpolateFaceVarying(level, srcUVs, dstUVs, uv_fvar_chan);
primvarRefiner.InterpolateFaceVarying(level, srcColors, dstColors, Cf_fvar_chan);
srcPoints = dstPoints;
srcUVs = dstUVs;
srcColors = dstColors;
}
// Copy refined point/vert data back to source vbuffer.
// We need to expand out the point/vert indices back to the flattened point-rate/vertex-rate:
const OpenSubdiv::Far::TopologyLevel& refLastLevel = refiner->GetLevel(nRefinementLevels);
const int32_t nLevelFaces = refLastLevel.GetNumFaces();
const int32_t nLevelVerts = nLevelFaces*4; // always quads
const int32_t nLevelPoints = refLastLevel.GetNumVertices();
const int32_t nLevelUVs = refLastLevel.GetNumFVarValues(uv_fvar_chan);
const int32_t nLevelColors = refLastLevel.GetNumFVarValues(Cf_fvar_chan);
//std::cout << " refLastLevel: nLevelFaces=" << nLevelFaces;
//std::cout << ", nLevelPoints=" << nLevelPoints;
//std::cout << ", nLevelUVs=" << nLevelUVs;
//std::cout << ", nLevelColors=" << nLevelColors;
// Gets the starting vert index in the highest refinement level:
const int32_t levelPointsStart = (refiner->GetNumVerticesTotal() - nLevelPoints);
const int32_t levelUVsStart = (refiner->GetNumFVarValuesTotal(uv_fvar_chan) - nLevelUVs );
const int32_t levelColorsStart = (refiner->GetNumFVarValuesTotal(Cf_fvar_chan) - nLevelColors);
//std::cout << ",levelPointsStart=" << levelPointsStart;
//std::cout << ", levelUVsStart=" << levelUVsStart;
//std::cout << ", levelColorsStart=" << levelColorsStart;
//std::cout << std::endl;
vbuffers.resizePoints(nLevelPoints);
vbuffers.resizeVerts(nLevelVerts);
vbuffers.setAllQuadsMode(); // no need to fill vbuffers.vertsPerFace
// Point data is copied straight over:
//std::cout << " refine_vbuffers: numPoints=" << refine_vbuffers.numPoints();
//std::cout << ", numVerts=" << refine_vbuffers.numVerts();
//std::cout << std::endl;
assert((levelPointsStart + nLevelPoints) <= refine_vbuffers.numPoints());
memcpy(vbuffers.PL.data(), refine_vbuffers.PL.data()+levelPointsStart, sizeof(Fsr::Vec3f)*nLevelPoints);
uint32_t v0 = 0; // global vert count
for (int32_t f=0; f < nLevelFaces; ++f)
{
const OpenSubdiv::Far::ConstIndexArray fPidx = refLastLevel.GetFaceVertices(f);
#if DEBUG
assert(fPidx.size() == 4); // all refined Catmull faces should be quads
#endif
for (int i=0; i < 4; ++i)
vbuffers.Pidx[v0+i] = fPidx[i];
// Flatten-copy the primvar values back the VertexBuffer vert-rate buffers:
{
// TODO: these should be in a primvar loop
const OpenSubdiv::Far::ConstIndexArray fUVidx = refLastLevel.GetFaceFVarValues(f, uv_fvar_chan);
for (int i=0; i < 4; ++i)
vbuffers.UV[v0+i] = refine_vbuffers.UV[levelUVsStart + fUVidx[i]];
const OpenSubdiv::Far::ConstIndexArray fCfidx = refLastLevel.GetFaceFVarValues(f, Cf_fvar_chan);
for (int i=0; i < 4; ++i)
vbuffers.Cf[v0+i] = refine_vbuffers.Cf[levelColorsStart + fCfidx[i]];
}
v0 += 4;
}
}
//------------------------------------------------------------------------------
/*!
*/
static Fsr::Node* buildOpenSubdiv(const char* builder_class,
const Fsr::ArgSet& args,
Fsr::Node* parent)
{
return new FuserOpenSubdiv(args, parent);
}
// Register plugin:
/*static*/ FSR_EXPORT
const Fsr::Node::Description
FuserOpenSubdiv::description("OpenSubdiv"/*plugin name*/, buildOpenSubdiv/*ctor*/);
} // namespace Fsr
// end of FuserOpenSubdiv.cpp
//
// Copyright 2019 DreamWorks Animation
//
|
/*
* @lc app=leetcode id=332 lang=cpp
*
* [332] Reconstruct Itinerary
*/
#include <set>
#include <vector>
#include <map>
#include <string>
using namespace std;
class Solution {
public:
vector<string> ans;
map<string,set<string>> G;
map<string,map<string, int>> remain_visits;
int N;
bool DFS_visit(string from, int stop_cnt)
{
for (auto cur_level: G[from])
if (remain_visits[from][cur_level] > 0)
{
// forward
remain_visits[from][cur_level]--;
ans.push_back(cur_level);
if (stop_cnt == N - 1)
return true;
else
if (DFS_visit(cur_level, stop_cnt+1))
return true;
else
{
// backward
remain_visits[from][cur_level]++;
ans.pop_back();
}
}
// did not find a solution
return false;
}
vector<string> findItinerary(vector<vector<string>>& tickets) {
const int E = tickets.size();
N = E + 1; // number of stops
for (int i = 0; i < E;i++)
if ( G.find(tickets[i][0]) == G.end() )
{
// not found
G[tickets[i][0]] = set<string> {};
G[tickets[i][0]].insert(tickets[i][1]);
remain_visits[tickets[i][0]] = map<string, int>{};
remain_visits[tickets[i][0]][tickets[i][1]] = 1;
}
else
{
auto it = G[tickets[i][0]].find(tickets[i][1]);
if (it != G[tickets[i][0]].end()) // duplicate element!
remain_visits[tickets[i][0]][tickets[i][1]]++;
else
{
G[tickets[i][0]].insert(tickets[i][1]);
remain_visits[tickets[i][0]][tickets[i][1]] = 1;
}
}
ans.push_back("JFK");
DFS_visit("JFK", 1);
return ans;
}
};
|
/*
* Phusion Passenger - https://www.phusionpassenger.com/
* Copyright (c) 2010-2013 Phusion
*
* "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui.
*
* 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 <iomanip>
#include <cstdlib>
#include <fcntl.h>
#include <unistd.h>
#include <Logging.h>
#include <StaticString.h>
#include <Utils/StrIntUtils.h>
#include <Utils/IOUtils.h>
namespace Passenger {
int _logLevel = 0;
int _logOutput = STDERR_FILENO;
static bool printAppOutputAsDebuggingMessages = false;
int
getLogLevel() {
return _logLevel;
}
void
setLogLevel(int value) {
_logLevel = value;
}
bool
setDebugFile(const char *logFile) {
int fd = open(logFile, O_WRONLY | O_CREAT | O_APPEND, 0644);
if (fd != -1) {
_logOutput = fd;
return true;
} else {
return false;
}
}
void
_prepareLogEntry(std::stringstream &sstream, const char *file, unsigned int line) {
time_t the_time;
struct tm the_tm;
char datetime_buf[60];
struct timeval tv;
if (startsWith(file, "ext/")) {
file += sizeof("ext/") - 1;
if (startsWith(file, "common/")) {
file += sizeof("common/") - 1;
if (startsWith(file, "ApplicationPool2/")) {
file += sizeof("Application") - 1;
}
}
}
the_time = time(NULL);
localtime_r(&the_time, &the_tm);
strftime(datetime_buf, sizeof(datetime_buf) - 1, "%F %H:%M:%S", &the_tm);
gettimeofday(&tv, NULL);
sstream <<
"[ " << datetime_buf << "." << std::setfill('0') << std::setw(4) <<
(unsigned long) (tv.tv_usec / 100) <<
" " << std::dec << getpid() << "/" <<
std::hex << pthread_self() << std::dec <<
" " << file << ":" << line <<
" ]: ";
}
static void
_writeLogEntry(const StaticString &str) {
try {
writeExact(_logOutput, str.data(), str.size());
} catch (const SystemException &) {
/* The most likely reason why this fails is when the user has setup
* Apache to log to a pipe (e.g. to a log rotation script). Upon
* restarting the web server, the process that reads from the pipe
* shuts down, so we can't write to it anymore. That's why we
* just ignore write errors. It doesn't make sense to abort for
* something like this.
*/
}
}
void
_writeLogEntry(const std::string &str) {
_writeLogEntry(StaticString(str));
}
static void
realPrintAppOutput(char *buf, unsigned int bufSize,
const char *pidStr, unsigned int pidStrLen,
const char *channelName, unsigned int channelNameLen,
const char *message, unsigned int messageLen)
{
char *pos = buf;
char *end = buf + bufSize;
pos = appendData(pos, end, "App ");
pos = appendData(pos, end, pidStr, pidStrLen);
pos = appendData(pos, end, " ");
pos = appendData(pos, end, channelName, channelNameLen);
pos = appendData(pos, end, ": ");
pos = appendData(pos, end, message, messageLen);
pos = appendData(pos, end, "\n");
_writeLogEntry(StaticString(buf, pos - buf));
}
void
printAppOutput(pid_t pid, const char *channelName, const char *message, unsigned int size) {
if (printAppOutputAsDebuggingMessages) {
P_DEBUG("App " << pid << " " << channelName << ": " << StaticString(message, size));
} else {
char pidStr[sizeof("4294967295")];
unsigned int pidStrLen, channelNameLen, totalLen;
try {
pidStrLen = integerToOtherBase<pid_t, 10>(pid, pidStr, sizeof(pidStr));
} catch (const std::length_error &) {
pidStr[0] = '?';
pidStr[1] = '\0';
pidStrLen = 1;
}
channelNameLen = strlen(channelName);
totalLen = (sizeof("App X Y: \n") - 2) + pidStrLen + channelNameLen + size;
if (totalLen < 1024) {
char buf[1024];
realPrintAppOutput(buf, sizeof(buf),
pidStr, pidStrLen,
channelName, channelNameLen,
message, size);
} else {
DynamicBuffer buf(totalLen);
realPrintAppOutput(buf.data, totalLen,
pidStr, pidStrLen,
channelName, channelNameLen,
message, size);
}
}
}
void
setPrintAppOutputAsDebuggingMessages(bool enabled) {
printAppOutputAsDebuggingMessages = enabled;
}
} // namespace Passenger
|
/*
* Copyright (c) 2016, Humanoid Lab, Georgia Tech Research Corporation
* Copyright (c) 2016-2017, Graphics Lab, Georgia Tech Research Corporation
* Copyright (c) 2016-2017, Personal Robotics Lab, Carnegie Mellon University
* All rights reserved.
*
* This file is provided under the following "BSD-style" License:
* 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.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef DART_DYNAMICS_SHAPENODE_HPP_
#define DART_DYNAMICS_SHAPENODE_HPP_
#include <Eigen/Dense>
#include "dart/common/Signal.hpp"
#include "dart/dynamics/detail/ShapeNode.hpp"
namespace dart {
namespace dynamics {
class VisualAspect;
class CollisionAspect;
class DynamicsAspect;
class ShapeNode : public detail::ShapeNodeCompositeBase
{
public:
friend class BodyNode;
using ShapeUpdatedSignal
= common::Signal<void(const ShapeNode* thisShapeNode,
const ShapePtr& oldShape,
const ShapePtr& newShape)>;
using RelativeTransformUpdatedSignal
= common::Signal<void(const ShapeNode* thisShapeNode,
const Eigen::Isometry3d& oldTransform,
const Eigen::Isometry3d& newTransform)>;
using BasicProperties = common::Composite::MakeProperties<
NameAspect,
FixedFrame,
ShapeFrame>;
using Properties = common::Composite::Properties;
/// Destructor
virtual ~ShapeNode() = default;
/// Set the Properties of this ShapeNode
void setProperties(const Properties& properties);
/// Get the Properties of this ShapeNode
const Properties getShapeNodeProperties() const;
/// Copy the properties of another ShapeNode
void copy(const ShapeNode& other);
/// Copy the properties of another ShapeNode
void copy(const ShapeNode* other);
/// Same as copy(const ShapeNode&)
ShapeNode& operator=(const ShapeNode& other);
/// Set transformation of this shape node relative to the parent frame
void setRelativeTransform(const Eigen::Isometry3d& transform) override;
/// Set rotation of this shape node relative to the parent frame
void setRelativeRotation(const Eigen::Matrix3d& rotation);
/// Get rotation of this shape node relative to the parent frame
Eigen::Matrix3d getRelativeRotation() const;
/// Set translation of this shape node relative to the parent frame
void setRelativeTranslation(const Eigen::Vector3d& translation);
/// Same as setRelativeTranslation(offset)
void setOffset(const Eigen::Vector3d& offset);
/// Get translation of this shape node relative to the parent frame
Eigen::Vector3d getRelativeTranslation() const;
/// Same as getRelativeTranslation()
Eigen::Vector3d getOffset() const;
// Documentation inherited
ShapeNode* asShapeNode() override;
// Documentation inherited
const ShapeNode* asShapeNode() const override;
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
protected:
/// Constructor used by the Skeleton class
ShapeNode(BodyNode* bodyNode, const BasicProperties& properties);
/// Constructor used by the Skeleton class
ShapeNode(BodyNode* bodyNode, const ShapePtr& shape,
const std::string& name = "ShapeNode");
/// Create a clone of this ShapeNode. This may only be called by the Skeleton
/// class.
Node* cloneNode(BodyNode* parent) const override;
};
} // namespace dynamics
} // namespace dart
#endif // DART_DYNAMICS_SHAPENODE_HPP_
|
//===- InstCombineAddSub.cpp ------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the visit functions for add, fadd, sub, and fsub.
//
//===----------------------------------------------------------------------===//
#include "InstCombineInternal.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/AlignOf.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/KnownBits.h"
#include <cassert>
#include <utility>
using namespace llvm;
using namespace PatternMatch;
#define DEBUG_TYPE "instcombine"
namespace {
/// Class representing coefficient of floating-point addend.
/// This class needs to be highly efficient, which is especially true for
/// the constructor. As of I write this comment, the cost of the default
/// constructor is merely 4-byte-store-zero (Assuming compiler is able to
/// perform write-merging).
///
class FAddendCoef {
public:
// The constructor has to initialize a APFloat, which is unnecessary for
// most addends which have coefficient either 1 or -1. So, the constructor
// is expensive. In order to avoid the cost of the constructor, we should
// reuse some instances whenever possible. The pre-created instances
// FAddCombine::Add[0-5] embodies this idea.
FAddendCoef() = default;
~FAddendCoef();
// If possible, don't define operator+/operator- etc because these
// operators inevitably call FAddendCoef's constructor which is not cheap.
void operator=(const FAddendCoef &A);
void operator+=(const FAddendCoef &A);
void operator*=(const FAddendCoef &S);
void set(short C) {
assert(!insaneIntVal(C) && "Insane coefficient");
IsFp = false; IntVal = C;
}
void set(const APFloat& C);
void negate();
bool isZero() const { return isInt() ? !IntVal : getFpVal().isZero(); }
Value *getValue(Type *) const;
bool isOne() const { return isInt() && IntVal == 1; }
bool isTwo() const { return isInt() && IntVal == 2; }
bool isMinusOne() const { return isInt() && IntVal == -1; }
bool isMinusTwo() const { return isInt() && IntVal == -2; }
private:
bool insaneIntVal(int V) { return V > 4 || V < -4; }
APFloat *getFpValPtr()
{ return reinterpret_cast<APFloat *>(&FpValBuf.buffer[0]); }
const APFloat *getFpValPtr() const
{ return reinterpret_cast<const APFloat *>(&FpValBuf.buffer[0]); }
const APFloat &getFpVal() const {
assert(IsFp && BufHasFpVal && "Incorret state");
return *getFpValPtr();
}
APFloat &getFpVal() {
assert(IsFp && BufHasFpVal && "Incorret state");
return *getFpValPtr();
}
bool isInt() const { return !IsFp; }
// If the coefficient is represented by an integer, promote it to a
// floating point.
void convertToFpType(const fltSemantics &Sem);
// Construct an APFloat from a signed integer.
// TODO: We should get rid of this function when APFloat can be constructed
// from an *SIGNED* integer.
APFloat createAPFloatFromInt(const fltSemantics &Sem, int Val);
bool IsFp = false;
// True iff FpValBuf contains an instance of APFloat.
bool BufHasFpVal = false;
// The integer coefficient of an individual addend is either 1 or -1,
// and we try to simplify at most 4 addends from neighboring at most
// two instructions. So the range of <IntVal> falls in [-4, 4]. APInt
// is overkill of this end.
short IntVal = 0;
AlignedCharArrayUnion<APFloat> FpValBuf;
};
/// FAddend is used to represent floating-point addend. An addend is
/// represented as <C, V>, where the V is a symbolic value, and C is a
/// constant coefficient. A constant addend is represented as <C, 0>.
class FAddend {
public:
FAddend() = default;
void operator+=(const FAddend &T) {
assert((Val == T.Val) && "Symbolic-values disagree");
Coeff += T.Coeff;
}
Value *getSymVal() const { return Val; }
const FAddendCoef &getCoef() const { return Coeff; }
bool isConstant() const { return Val == nullptr; }
bool isZero() const { return Coeff.isZero(); }
void set(short Coefficient, Value *V) {
Coeff.set(Coefficient);
Val = V;
}
void set(const APFloat &Coefficient, Value *V) {
Coeff.set(Coefficient);
Val = V;
}
void set(const ConstantFP *Coefficient, Value *V) {
Coeff.set(Coefficient->getValueAPF());
Val = V;
}
void negate() { Coeff.negate(); }
/// Drill down the U-D chain one step to find the definition of V, and
/// try to break the definition into one or two addends.
static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1);
/// Similar to FAddend::drillDownOneStep() except that the value being
/// splitted is the addend itself.
unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const;
private:
void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; }
// This addend has the value of "Coeff * Val".
Value *Val = nullptr;
FAddendCoef Coeff;
};
/// FAddCombine is the class for optimizing an unsafe fadd/fsub along
/// with its neighboring at most two instructions.
///
class FAddCombine {
public:
FAddCombine(InstCombiner::BuilderTy &B) : Builder(B) {}
Value *simplify(Instruction *FAdd);
private:
using AddendVect = SmallVector<const FAddend *, 4>;
Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota);
/// Convert given addend to a Value
Value *createAddendVal(const FAddend &A, bool& NeedNeg);
/// Return the number of instructions needed to emit the N-ary addition.
unsigned calcInstrNumber(const AddendVect& Vect);
Value *createFSub(Value *Opnd0, Value *Opnd1);
Value *createFAdd(Value *Opnd0, Value *Opnd1);
Value *createFMul(Value *Opnd0, Value *Opnd1);
Value *createFNeg(Value *V);
Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
void createInstPostProc(Instruction *NewInst, bool NoNumber = false);
// Debugging stuff are clustered here.
#ifndef NDEBUG
unsigned CreateInstrNum;
void initCreateInstNum() { CreateInstrNum = 0; }
void incCreateInstNum() { CreateInstrNum++; }
#else
void initCreateInstNum() {}
void incCreateInstNum() {}
#endif
InstCombiner::BuilderTy &Builder;
Instruction *Instr = nullptr;
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
//
// Implementation of
// {FAddendCoef, FAddend, FAddition, FAddCombine}.
//
//===----------------------------------------------------------------------===//
FAddendCoef::~FAddendCoef() {
if (BufHasFpVal)
getFpValPtr()->~APFloat();
}
void FAddendCoef::set(const APFloat& C) {
APFloat *P = getFpValPtr();
if (isInt()) {
// As the buffer is meanless byte stream, we cannot call
// APFloat::operator=().
new(P) APFloat(C);
} else
*P = C;
IsFp = BufHasFpVal = true;
}
void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
if (!isInt())
return;
APFloat *P = getFpValPtr();
if (IntVal > 0)
new(P) APFloat(Sem, IntVal);
else {
new(P) APFloat(Sem, 0 - IntVal);
P->changeSign();
}
IsFp = BufHasFpVal = true;
}
APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
if (Val >= 0)
return APFloat(Sem, Val);
APFloat T(Sem, 0 - Val);
T.changeSign();
return T;
}
void FAddendCoef::operator=(const FAddendCoef &That) {
if (That.isInt())
set(That.IntVal);
else
set(That.getFpVal());
}
void FAddendCoef::operator+=(const FAddendCoef &That) {
enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
if (isInt() == That.isInt()) {
if (isInt())
IntVal += That.IntVal;
else
getFpVal().add(That.getFpVal(), RndMode);
return;
}
if (isInt()) {
const APFloat &T = That.getFpVal();
convertToFpType(T.getSemantics());
getFpVal().add(T, RndMode);
return;
}
APFloat &T = getFpVal();
T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode);
}
void FAddendCoef::operator*=(const FAddendCoef &That) {
if (That.isOne())
return;
if (That.isMinusOne()) {
negate();
return;
}
if (isInt() && That.isInt()) {
int Res = IntVal * (int)That.IntVal;
assert(!insaneIntVal(Res) && "Insane int value");
IntVal = Res;
return;
}
const fltSemantics &Semantic =
isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
if (isInt())
convertToFpType(Semantic);
APFloat &F0 = getFpVal();
if (That.isInt())
F0.multiply(createAPFloatFromInt(Semantic, That.IntVal),
APFloat::rmNearestTiesToEven);
else
F0.multiply(That.getFpVal(), APFloat::rmNearestTiesToEven);
}
void FAddendCoef::negate() {
if (isInt())
IntVal = 0 - IntVal;
else
getFpVal().changeSign();
}
Value *FAddendCoef::getValue(Type *Ty) const {
return isInt() ?
ConstantFP::get(Ty, float(IntVal)) :
ConstantFP::get(Ty->getContext(), getFpVal());
}
// The definition of <Val> Addends
// =========================================
// A + B <1, A>, <1,B>
// A - B <1, A>, <1,B>
// 0 - B <-1, B>
// C * A, <C, A>
// A + C <1, A> <C, NULL>
// 0 +/- 0 <0, NULL> (corner case)
//
// Legend: A and B are not constant, C is constant
unsigned FAddend::drillValueDownOneStep
(Value *Val, FAddend &Addend0, FAddend &Addend1) {
Instruction *I = nullptr;
if (!Val || !(I = dyn_cast<Instruction>(Val)))
return 0;
unsigned Opcode = I->getOpcode();
if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) {
ConstantFP *C0, *C1;
Value *Opnd0 = I->getOperand(0);
Value *Opnd1 = I->getOperand(1);
if ((C0 = dyn_cast<ConstantFP>(Opnd0)) && C0->isZero())
Opnd0 = nullptr;
if ((C1 = dyn_cast<ConstantFP>(Opnd1)) && C1->isZero())
Opnd1 = nullptr;
if (Opnd0) {
if (!C0)
Addend0.set(1, Opnd0);
else
Addend0.set(C0, nullptr);
}
if (Opnd1) {
FAddend &Addend = Opnd0 ? Addend1 : Addend0;
if (!C1)
Addend.set(1, Opnd1);
else
Addend.set(C1, nullptr);
if (Opcode == Instruction::FSub)
Addend.negate();
}
if (Opnd0 || Opnd1)
return Opnd0 && Opnd1 ? 2 : 1;
// Both operands are zero. Weird!
Addend0.set(APFloat(C0->getValueAPF().getSemantics()), nullptr);
return 1;
}
if (I->getOpcode() == Instruction::FMul) {
Value *V0 = I->getOperand(0);
Value *V1 = I->getOperand(1);
if (ConstantFP *C = dyn_cast<ConstantFP>(V0)) {
Addend0.set(C, V1);
return 1;
}
if (ConstantFP *C = dyn_cast<ConstantFP>(V1)) {
Addend0.set(C, V0);
return 1;
}
}
return 0;
}
// Try to break *this* addend into two addends. e.g. Suppose this addend is
// <2.3, V>, and V = X + Y, by calling this function, we obtain two addends,
// i.e. <2.3, X> and <2.3, Y>.
unsigned FAddend::drillAddendDownOneStep
(FAddend &Addend0, FAddend &Addend1) const {
if (isConstant())
return 0;
unsigned BreakNum = FAddend::drillValueDownOneStep(Val, Addend0, Addend1);
if (!BreakNum || Coeff.isOne())
return BreakNum;
Addend0.Scale(Coeff);
if (BreakNum == 2)
Addend1.Scale(Coeff);
return BreakNum;
}
Value *FAddCombine::simplify(Instruction *I) {
assert(I->hasAllowReassoc() && I->hasNoSignedZeros() &&
"Expected 'reassoc'+'nsz' instruction");
// Currently we are not able to handle vector type.
if (I->getType()->isVectorTy())
return nullptr;
assert((I->getOpcode() == Instruction::FAdd ||
I->getOpcode() == Instruction::FSub) && "Expect add/sub");
// Save the instruction before calling other member-functions.
Instr = I;
FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1);
// Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1.
unsigned Opnd0_ExpNum = 0;
unsigned Opnd1_ExpNum = 0;
if (!Opnd0.isConstant())
Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1);
// Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1.
if (OpndNum == 2 && !Opnd1.isConstant())
Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1);
// Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1
if (Opnd0_ExpNum && Opnd1_ExpNum) {
AddendVect AllOpnds;
AllOpnds.push_back(&Opnd0_0);
AllOpnds.push_back(&Opnd1_0);
if (Opnd0_ExpNum == 2)
AllOpnds.push_back(&Opnd0_1);
if (Opnd1_ExpNum == 2)
AllOpnds.push_back(&Opnd1_1);
// Compute instruction quota. We should save at least one instruction.
unsigned InstQuota = 0;
Value *V0 = I->getOperand(0);
Value *V1 = I->getOperand(1);
InstQuota = ((!isa<Constant>(V0) && V0->hasOneUse()) &&
(!isa<Constant>(V1) && V1->hasOneUse())) ? 2 : 1;
if (Value *R = simplifyFAdd(AllOpnds, InstQuota))
return R;
}
if (OpndNum != 2) {
// The input instruction is : "I=0.0 +/- V". If the "V" were able to be
// splitted into two addends, say "V = X - Y", the instruction would have
// been optimized into "I = Y - X" in the previous steps.
//
const FAddendCoef &CE = Opnd0.getCoef();
return CE.isOne() ? Opnd0.getSymVal() : nullptr;
}
// step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1]
if (Opnd1_ExpNum) {
AddendVect AllOpnds;
AllOpnds.push_back(&Opnd0);
AllOpnds.push_back(&Opnd1_0);
if (Opnd1_ExpNum == 2)
AllOpnds.push_back(&Opnd1_1);
if (Value *R = simplifyFAdd(AllOpnds, 1))
return R;
}
// step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1]
if (Opnd0_ExpNum) {
AddendVect AllOpnds;
AllOpnds.push_back(&Opnd1);
AllOpnds.push_back(&Opnd0_0);
if (Opnd0_ExpNum == 2)
AllOpnds.push_back(&Opnd0_1);
if (Value *R = simplifyFAdd(AllOpnds, 1))
return R;
}
return nullptr;
}
Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
unsigned AddendNum = Addends.size();
assert(AddendNum <= 4 && "Too many addends");
// For saving intermediate results;
unsigned NextTmpIdx = 0;
FAddend TmpResult[3];
// Points to the constant addend of the resulting simplified expression.
// If the resulting expr has constant-addend, this constant-addend is
// desirable to reside at the top of the resulting expression tree. Placing
// constant close to supper-expr(s) will potentially reveal some optimization
// opportunities in super-expr(s).
const FAddend *ConstAdd = nullptr;
// Simplified addends are placed <SimpVect>.
AddendVect SimpVect;
// The outer loop works on one symbolic-value at a time. Suppose the input
// addends are : <a1, x>, <b1, y>, <a2, x>, <c1, z>, <b2, y>, ...
// The symbolic-values will be processed in this order: x, y, z.
for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
const FAddend *ThisAddend = Addends[SymIdx];
if (!ThisAddend) {
// This addend was processed before.
continue;
}
Value *Val = ThisAddend->getSymVal();
unsigned StartIdx = SimpVect.size();
SimpVect.push_back(ThisAddend);
// The inner loop collects addends sharing same symbolic-value, and these
// addends will be later on folded into a single addend. Following above
// example, if the symbolic value "y" is being processed, the inner loop
// will collect two addends "<b1,y>" and "<b2,Y>". These two addends will
// be later on folded into "<b1+b2, y>".
for (unsigned SameSymIdx = SymIdx + 1;
SameSymIdx < AddendNum; SameSymIdx++) {
const FAddend *T = Addends[SameSymIdx];
if (T && T->getSymVal() == Val) {
// Set null such that next iteration of the outer loop will not process
// this addend again.
Addends[SameSymIdx] = nullptr;
SimpVect.push_back(T);
}
}
// If multiple addends share same symbolic value, fold them together.
if (StartIdx + 1 != SimpVect.size()) {
FAddend &R = TmpResult[NextTmpIdx ++];
R = *SimpVect[StartIdx];
for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
R += *SimpVect[Idx];
// Pop all addends being folded and push the resulting folded addend.
SimpVect.resize(StartIdx);
if (Val) {
if (!R.isZero()) {
SimpVect.push_back(&R);
}
} else {
// Don't push constant addend at this time. It will be the last element
// of <SimpVect>.
ConstAdd = &R;
}
}
}
assert((NextTmpIdx <= array_lengthof(TmpResult) + 1) &&
"out-of-bound access");
if (ConstAdd)
SimpVect.push_back(ConstAdd);
Value *Result;
if (!SimpVect.empty())
Result = createNaryFAdd(SimpVect, InstrQuota);
else {
// The addition is folded to 0.0.
Result = ConstantFP::get(Instr->getType(), 0.0);
}
return Result;
}
Value *FAddCombine::createNaryFAdd
(const AddendVect &Opnds, unsigned InstrQuota) {
assert(!Opnds.empty() && "Expect at least one addend");
// Step 1: Check if the # of instructions needed exceeds the quota.
unsigned InstrNeeded = calcInstrNumber(Opnds);
if (InstrNeeded > InstrQuota)
return nullptr;
initCreateInstNum();
// step 2: Emit the N-ary addition.
// Note that at most three instructions are involved in Fadd-InstCombine: the
// addition in question, and at most two neighboring instructions.
// The resulting optimized addition should have at least one less instruction
// than the original addition expression tree. This implies that the resulting
// N-ary addition has at most two instructions, and we don't need to worry
// about tree-height when constructing the N-ary addition.
Value *LastVal = nullptr;
bool LastValNeedNeg = false;
// Iterate the addends, creating fadd/fsub using adjacent two addends.
for (const FAddend *Opnd : Opnds) {
bool NeedNeg;
Value *V = createAddendVal(*Opnd, NeedNeg);
if (!LastVal) {
LastVal = V;
LastValNeedNeg = NeedNeg;
continue;
}
if (LastValNeedNeg == NeedNeg) {
LastVal = createFAdd(LastVal, V);
continue;
}
if (LastValNeedNeg)
LastVal = createFSub(V, LastVal);
else
LastVal = createFSub(LastVal, V);
LastValNeedNeg = false;
}
if (LastValNeedNeg) {
LastVal = createFNeg(LastVal);
}
#ifndef NDEBUG
assert(CreateInstrNum == InstrNeeded &&
"Inconsistent in instruction numbers");
#endif
return LastVal;
}
Value *FAddCombine::createFSub(Value *Opnd0, Value *Opnd1) {
Value *V = Builder.CreateFSub(Opnd0, Opnd1);
if (Instruction *I = dyn_cast<Instruction>(V))
createInstPostProc(I);
return V;
}
Value *FAddCombine::createFNeg(Value *V) {
Value *Zero = cast<Value>(ConstantFP::getZeroValueForNegation(V->getType()));
Value *NewV = createFSub(Zero, V);
if (Instruction *I = dyn_cast<Instruction>(NewV))
createInstPostProc(I, true); // fneg's don't receive instruction numbers.
return NewV;
}
Value *FAddCombine::createFAdd(Value *Opnd0, Value *Opnd1) {
Value *V = Builder.CreateFAdd(Opnd0, Opnd1);
if (Instruction *I = dyn_cast<Instruction>(V))
createInstPostProc(I);
return V;
}
Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
Value *V = Builder.CreateFMul(Opnd0, Opnd1);
if (Instruction *I = dyn_cast<Instruction>(V))
createInstPostProc(I);
return V;
}
void FAddCombine::createInstPostProc(Instruction *NewInstr, bool NoNumber) {
NewInstr->setDebugLoc(Instr->getDebugLoc());
// Keep track of the number of instruction created.
if (!NoNumber)
incCreateInstNum();
// Propagate fast-math flags
NewInstr->setFastMathFlags(Instr->getFastMathFlags());
}
// Return the number of instruction needed to emit the N-ary addition.
// NOTE: Keep this function in sync with createAddendVal().
unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
unsigned OpndNum = Opnds.size();
unsigned InstrNeeded = OpndNum - 1;
// The number of addends in the form of "(-1)*x".
unsigned NegOpndNum = 0;
// Adjust the number of instructions needed to emit the N-ary add.
for (const FAddend *Opnd : Opnds) {
if (Opnd->isConstant())
continue;
// The constant check above is really for a few special constant
// coefficients.
if (isa<UndefValue>(Opnd->getSymVal()))
continue;
const FAddendCoef &CE = Opnd->getCoef();
if (CE.isMinusOne() || CE.isMinusTwo())
NegOpndNum++;
// Let the addend be "c * x". If "c == +/-1", the value of the addend
// is immediately available; otherwise, it needs exactly one instruction
// to evaluate the value.
if (!CE.isMinusOne() && !CE.isOne())
InstrNeeded++;
}
if (NegOpndNum == OpndNum)
InstrNeeded++;
return InstrNeeded;
}
// Input Addend Value NeedNeg(output)
// ================================================================
// Constant C C false
// <+/-1, V> V coefficient is -1
// <2/-2, V> "fadd V, V" coefficient is -2
// <C, V> "fmul V, C" false
//
// NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
Value *FAddCombine::createAddendVal(const FAddend &Opnd, bool &NeedNeg) {
const FAddendCoef &Coeff = Opnd.getCoef();
if (Opnd.isConstant()) {
NeedNeg = false;
return Coeff.getValue(Instr->getType());
}
Value *OpndVal = Opnd.getSymVal();
if (Coeff.isMinusOne() || Coeff.isOne()) {
NeedNeg = Coeff.isMinusOne();
return OpndVal;
}
if (Coeff.isTwo() || Coeff.isMinusTwo()) {
NeedNeg = Coeff.isMinusTwo();
return createFAdd(OpndVal, OpndVal);
}
NeedNeg = false;
return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
}
// Checks if any operand is negative and we can convert add to sub.
// This function checks for following negative patterns
// ADD(XOR(OR(Z, NOT(C)), C)), 1) == NEG(AND(Z, C))
// ADD(XOR(AND(Z, C), C), 1) == NEG(OR(Z, ~C))
// XOR(AND(Z, C), (C + 1)) == NEG(OR(Z, ~C)) if C is even
static Value *checkForNegativeOperand(BinaryOperator &I,
InstCombiner::BuilderTy &Builder) {
Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
// This function creates 2 instructions to replace ADD, we need at least one
// of LHS or RHS to have one use to ensure benefit in transform.
if (!LHS->hasOneUse() && !RHS->hasOneUse())
return nullptr;
Value *X = nullptr, *Y = nullptr, *Z = nullptr;
const APInt *C1 = nullptr, *C2 = nullptr;
// if ONE is on other side, swap
if (match(RHS, m_Add(m_Value(X), m_One())))
std::swap(LHS, RHS);
if (match(LHS, m_Add(m_Value(X), m_One()))) {
// if XOR on other side, swap
if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
std::swap(X, RHS);
if (match(X, m_Xor(m_Value(Y), m_APInt(C1)))) {
// X = XOR(Y, C1), Y = OR(Z, C2), C2 = NOT(C1) ==> X == NOT(AND(Z, C1))
// ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, AND(Z, C1))
if (match(Y, m_Or(m_Value(Z), m_APInt(C2))) && (*C2 == ~(*C1))) {
Value *NewAnd = Builder.CreateAnd(Z, *C1);
return Builder.CreateSub(RHS, NewAnd, "sub");
} else if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && (*C1 == *C2)) {
// X = XOR(Y, C1), Y = AND(Z, C2), C2 == C1 ==> X == NOT(OR(Z, ~C1))
// ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, OR(Z, ~C1))
Value *NewOr = Builder.CreateOr(Z, ~(*C1));
return Builder.CreateSub(RHS, NewOr, "sub");
}
}
}
// Restore LHS and RHS
LHS = I.getOperand(0);
RHS = I.getOperand(1);
// if XOR is on other side, swap
if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
std::swap(LHS, RHS);
// C2 is ODD
// LHS = XOR(Y, C1), Y = AND(Z, C2), C1 == (C2 + 1) => LHS == NEG(OR(Z, ~C2))
// ADD(LHS, RHS) == SUB(RHS, OR(Z, ~C2))
if (match(LHS, m_Xor(m_Value(Y), m_APInt(C1))))
if (C1->countTrailingZeros() == 0)
if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && *C1 == (*C2 + 1)) {
Value *NewOr = Builder.CreateOr(Z, ~(*C2));
return Builder.CreateSub(RHS, NewOr, "sub");
}
return nullptr;
}
/// Wrapping flags may allow combining constants separated by an extend.
static Instruction *foldNoWrapAdd(BinaryOperator &Add,
InstCombiner::BuilderTy &Builder) {
Value *Op0 = Add.getOperand(0), *Op1 = Add.getOperand(1);
Type *Ty = Add.getType();
Constant *Op1C;
if (!match(Op1, m_Constant(Op1C)))
return nullptr;
// Try this match first because it results in an add in the narrow type.
// (zext (X +nuw C2)) + C1 --> zext (X + (C2 + trunc(C1)))
Value *X;
const APInt *C1, *C2;
if (match(Op1, m_APInt(C1)) &&
match(Op0, m_OneUse(m_ZExt(m_NUWAdd(m_Value(X), m_APInt(C2))))) &&
C1->isNegative() && C1->sge(-C2->sext(C1->getBitWidth()))) {
Constant *NewC =
ConstantInt::get(X->getType(), *C2 + C1->trunc(C2->getBitWidth()));
return new ZExtInst(Builder.CreateNUWAdd(X, NewC), Ty);
}
// More general combining of constants in the wide type.
// (sext (X +nsw NarrowC)) + C --> (sext X) + (sext(NarrowC) + C)
Constant *NarrowC;
if (match(Op0, m_OneUse(m_SExt(m_NSWAdd(m_Value(X), m_Constant(NarrowC)))))) {
Constant *WideC = ConstantExpr::getSExt(NarrowC, Ty);
Constant *NewC = ConstantExpr::getAdd(WideC, Op1C);
Value *WideX = Builder.CreateSExt(X, Ty);
return BinaryOperator::CreateAdd(WideX, NewC);
}
// (zext (X +nuw NarrowC)) + C --> (zext X) + (zext(NarrowC) + C)
if (match(Op0, m_OneUse(m_ZExt(m_NUWAdd(m_Value(X), m_Constant(NarrowC)))))) {
Constant *WideC = ConstantExpr::getZExt(NarrowC, Ty);
Constant *NewC = ConstantExpr::getAdd(WideC, Op1C);
Value *WideX = Builder.CreateZExt(X, Ty);
return BinaryOperator::CreateAdd(WideX, NewC);
}
return nullptr;
}
Instruction *InstCombiner::foldAddWithConstant(BinaryOperator &Add) {
Value *Op0 = Add.getOperand(0), *Op1 = Add.getOperand(1);
Constant *Op1C;
if (!match(Op1, m_Constant(Op1C)))
return nullptr;
if (Instruction *NV = foldBinOpIntoSelectOrPhi(Add))
return NV;
Value *X;
Constant *Op00C;
// add (sub C1, X), C2 --> sub (add C1, C2), X
if (match(Op0, m_Sub(m_Constant(Op00C), m_Value(X))))
return BinaryOperator::CreateSub(ConstantExpr::getAdd(Op00C, Op1C), X);
Value *Y;
// add (sub X, Y), -1 --> add (not Y), X
if (match(Op0, m_OneUse(m_Sub(m_Value(X), m_Value(Y)))) &&
match(Op1, m_AllOnes()))
return BinaryOperator::CreateAdd(Builder.CreateNot(Y), X);
// zext(bool) + C -> bool ? C + 1 : C
if (match(Op0, m_ZExt(m_Value(X))) &&
X->getType()->getScalarSizeInBits() == 1)
return SelectInst::Create(X, AddOne(Op1C), Op1);
// ~X + C --> (C-1) - X
if (match(Op0, m_Not(m_Value(X))))
return BinaryOperator::CreateSub(SubOne(Op1C), X);
const APInt *C;
if (!match(Op1, m_APInt(C)))
return nullptr;
// (X | C2) + C --> (X | C2) ^ C2 iff (C2 == -C)
const APInt *C2;
if (match(Op0, m_Or(m_Value(), m_APInt(C2))) && *C2 == -*C)
return BinaryOperator::CreateXor(Op0, ConstantInt::get(Add.getType(), *C2));
if (C->isSignMask()) {
// If wrapping is not allowed, then the addition must set the sign bit:
// X + (signmask) --> X | signmask
if (Add.hasNoSignedWrap() || Add.hasNoUnsignedWrap())
return BinaryOperator::CreateOr(Op0, Op1);
// If wrapping is allowed, then the addition flips the sign bit of LHS:
// X + (signmask) --> X ^ signmask
return BinaryOperator::CreateXor(Op0, Op1);
}
// Is this add the last step in a convoluted sext?
// add(zext(xor i16 X, -32768), -32768) --> sext X
Type *Ty = Add.getType();
if (match(Op0, m_ZExt(m_Xor(m_Value(X), m_APInt(C2)))) &&
C2->isMinSignedValue() && C2->sext(Ty->getScalarSizeInBits()) == *C)
return CastInst::Create(Instruction::SExt, X, Ty);
if (C->isOneValue() && Op0->hasOneUse()) {
// add (sext i1 X), 1 --> zext (not X)
// TODO: The smallest IR representation is (select X, 0, 1), and that would
// not require the one-use check. But we need to remove a transform in
// visitSelect and make sure that IR value tracking for select is equal or
// better than for these ops.
if (match(Op0, m_SExt(m_Value(X))) &&
X->getType()->getScalarSizeInBits() == 1)
return new ZExtInst(Builder.CreateNot(X), Ty);
// Shifts and add used to flip and mask off the low bit:
// add (ashr (shl i32 X, 31), 31), 1 --> and (not X), 1
const APInt *C3;
if (match(Op0, m_AShr(m_Shl(m_Value(X), m_APInt(C2)), m_APInt(C3))) &&
C2 == C3 && *C2 == Ty->getScalarSizeInBits() - 1) {
Value *NotX = Builder.CreateNot(X);
return BinaryOperator::CreateAnd(NotX, ConstantInt::get(Ty, 1));
}
}
return nullptr;
}
// Matches multiplication expression Op * C where C is a constant. Returns the
// constant value in C and the other operand in Op. Returns true if such a
// match is found.
static bool MatchMul(Value *E, Value *&Op, APInt &C) {
const APInt *AI;
if (match(E, m_Mul(m_Value(Op), m_APInt(AI)))) {
C = *AI;
return true;
}
if (match(E, m_Shl(m_Value(Op), m_APInt(AI)))) {
C = APInt(AI->getBitWidth(), 1);
C <<= *AI;
return true;
}
return false;
}
// Matches remainder expression Op % C where C is a constant. Returns the
// constant value in C and the other operand in Op. Returns the signedness of
// the remainder operation in IsSigned. Returns true if such a match is
// found.
static bool MatchRem(Value *E, Value *&Op, APInt &C, bool &IsSigned) {
const APInt *AI;
IsSigned = false;
if (match(E, m_SRem(m_Value(Op), m_APInt(AI)))) {
IsSigned = true;
C = *AI;
return true;
}
if (match(E, m_URem(m_Value(Op), m_APInt(AI)))) {
C = *AI;
return true;
}
if (match(E, m_And(m_Value(Op), m_APInt(AI))) && (*AI + 1).isPowerOf2()) {
C = *AI + 1;
return true;
}
return false;
}
// Matches division expression Op / C with the given signedness as indicated
// by IsSigned, where C is a constant. Returns the constant value in C and the
// other operand in Op. Returns true if such a match is found.
static bool MatchDiv(Value *E, Value *&Op, APInt &C, bool IsSigned) {
const APInt *AI;
if (IsSigned && match(E, m_SDiv(m_Value(Op), m_APInt(AI)))) {
C = *AI;
return true;
}
if (!IsSigned) {
if (match(E, m_UDiv(m_Value(Op), m_APInt(AI)))) {
C = *AI;
return true;
}
if (match(E, m_LShr(m_Value(Op), m_APInt(AI)))) {
C = APInt(AI->getBitWidth(), 1);
C <<= *AI;
return true;
}
}
return false;
}
// Returns whether C0 * C1 with the given signedness overflows.
static bool MulWillOverflow(APInt &C0, APInt &C1, bool IsSigned) {
bool overflow;
if (IsSigned)
(void)C0.smul_ov(C1, overflow);
else
(void)C0.umul_ov(C1, overflow);
return overflow;
}
// Simplifies X % C0 + (( X / C0 ) % C1) * C0 to X % (C0 * C1), where (C0 * C1)
// does not overflow.
Value *InstCombiner::SimplifyAddWithRemainder(BinaryOperator &I) {
Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Value *X, *MulOpV;
APInt C0, MulOpC;
bool IsSigned;
// Match I = X % C0 + MulOpV * C0
if (((MatchRem(LHS, X, C0, IsSigned) && MatchMul(RHS, MulOpV, MulOpC)) ||
(MatchRem(RHS, X, C0, IsSigned) && MatchMul(LHS, MulOpV, MulOpC))) &&
C0 == MulOpC) {
Value *RemOpV;
APInt C1;
bool Rem2IsSigned;
// Match MulOpC = RemOpV % C1
if (MatchRem(MulOpV, RemOpV, C1, Rem2IsSigned) &&
IsSigned == Rem2IsSigned) {
Value *DivOpV;
APInt DivOpC;
// Match RemOpV = X / C0
if (MatchDiv(RemOpV, DivOpV, DivOpC, IsSigned) && X == DivOpV &&
C0 == DivOpC && !MulWillOverflow(C0, C1, IsSigned)) {
Value *NewDivisor =
ConstantInt::get(X->getType()->getContext(), C0 * C1);
return IsSigned ? Builder.CreateSRem(X, NewDivisor, "srem")
: Builder.CreateURem(X, NewDivisor, "urem");
}
}
}
return nullptr;
}
/// Fold
/// (1 << NBits) - 1
/// Into:
/// ~(-(1 << NBits))
/// Because a 'not' is better for bit-tracking analysis and other transforms
/// than an 'add'. The new shl is always nsw, and is nuw if old `and` was.
static Instruction *canonicalizeLowbitMask(BinaryOperator &I,
InstCombiner::BuilderTy &Builder) {
Value *NBits;
if (!match(&I, m_Add(m_OneUse(m_Shl(m_One(), m_Value(NBits))), m_AllOnes())))
return nullptr;
Constant *MinusOne = Constant::getAllOnesValue(NBits->getType());
Value *NotMask = Builder.CreateShl(MinusOne, NBits, "notmask");
// Be wary of constant folding.
if (auto *BOp = dyn_cast<BinaryOperator>(NotMask)) {
// Always NSW. But NUW propagates from `add`.
BOp->setHasNoSignedWrap();
BOp->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
}
return BinaryOperator::CreateNot(NotMask, I.getName());
}
static Instruction *foldToUnsignedSaturatedAdd(BinaryOperator &I) {
assert(I.getOpcode() == Instruction::Add && "Expecting add instruction");
Type *Ty = I.getType();
auto getUAddSat = [&]() {
return Intrinsic::getDeclaration(I.getModule(), Intrinsic::uadd_sat, Ty);
};
// add (umin X, ~Y), Y --> uaddsat X, Y
Value *X, *Y;
if (match(&I, m_c_Add(m_c_UMin(m_Value(X), m_Not(m_Value(Y))),
m_Deferred(Y))))
return CallInst::Create(getUAddSat(), { X, Y });
// add (umin X, ~C), C --> uaddsat X, C
const APInt *C, *NotC;
if (match(&I, m_Add(m_UMin(m_Value(X), m_APInt(NotC)), m_APInt(C))) &&
*C == ~*NotC)
return CallInst::Create(getUAddSat(), { X, ConstantInt::get(Ty, *C) });
return nullptr;
}
Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
if (Value *V = SimplifyAddInst(I.getOperand(0), I.getOperand(1),
I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
SQ.getWithInstruction(&I)))
return replaceInstUsesWith(I, V);
if (SimplifyAssociativeOrCommutative(I))
return &I;
if (Instruction *X = foldVectorBinop(I))
return X;
// (A*B)+(A*C) -> A*(B+C) etc
if (Value *V = SimplifyUsingDistributiveLaws(I))
return replaceInstUsesWith(I, V);
if (Instruction *X = foldAddWithConstant(I))
return X;
if (Instruction *X = foldNoWrapAdd(I, Builder))
return X;
// FIXME: This should be moved into the above helper function to allow these
// transforms for general constant or constant splat vectors.
Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Type *Ty = I.getType();
if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Value *XorLHS = nullptr; ConstantInt *XorRHS = nullptr;
if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
unsigned TySizeBits = Ty->getScalarSizeInBits();
const APInt &RHSVal = CI->getValue();
unsigned ExtendAmt = 0;
// If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
// If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
if (XorRHS->getValue() == -RHSVal) {
if (RHSVal.isPowerOf2())
ExtendAmt = TySizeBits - RHSVal.logBase2() - 1;
else if (XorRHS->getValue().isPowerOf2())
ExtendAmt = TySizeBits - XorRHS->getValue().logBase2() - 1;
}
if (ExtendAmt) {
APInt Mask = APInt::getHighBitsSet(TySizeBits, ExtendAmt);
if (!MaskedValueIsZero(XorLHS, Mask, 0, &I))
ExtendAmt = 0;
}
if (ExtendAmt) {
Constant *ShAmt = ConstantInt::get(Ty, ExtendAmt);
Value *NewShl = Builder.CreateShl(XorLHS, ShAmt, "sext");
return BinaryOperator::CreateAShr(NewShl, ShAmt);
}
// If this is a xor that was canonicalized from a sub, turn it back into
// a sub and fuse this add with it.
if (LHS->hasOneUse() && (XorRHS->getValue()+1).isPowerOf2()) {
KnownBits LHSKnown = computeKnownBits(XorLHS, 0, &I);
if ((XorRHS->getValue() | LHSKnown.Zero).isAllOnesValue())
return BinaryOperator::CreateSub(ConstantExpr::getAdd(XorRHS, CI),
XorLHS);
}
// (X + signmask) + C could have gotten canonicalized to (X^signmask) + C,
// transform them into (X + (signmask ^ C))
if (XorRHS->getValue().isSignMask())
return BinaryOperator::CreateAdd(XorLHS,
ConstantExpr::getXor(XorRHS, CI));
}
}
if (Ty->isIntOrIntVectorTy(1))
return BinaryOperator::CreateXor(LHS, RHS);
// X + X --> X << 1
if (LHS == RHS) {
auto *Shl = BinaryOperator::CreateShl(LHS, ConstantInt::get(Ty, 1));
Shl->setHasNoSignedWrap(I.hasNoSignedWrap());
Shl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
return Shl;
}
Value *A, *B;
if (match(LHS, m_Neg(m_Value(A)))) {
// -A + -B --> -(A + B)
if (match(RHS, m_Neg(m_Value(B))))
return BinaryOperator::CreateNeg(Builder.CreateAdd(A, B));
// -A + B --> B - A
return BinaryOperator::CreateSub(RHS, A);
}
// Canonicalize sext to zext for better value tracking potential.
// add A, sext(B) --> sub A, zext(B)
if (match(&I, m_c_Add(m_Value(A), m_OneUse(m_SExt(m_Value(B))))) &&
B->getType()->isIntOrIntVectorTy(1))
return BinaryOperator::CreateSub(A, Builder.CreateZExt(B, Ty));
// A + -B --> A - B
if (match(RHS, m_Neg(m_Value(B))))
return BinaryOperator::CreateSub(LHS, B);
if (Value *V = checkForNegativeOperand(I, Builder))
return replaceInstUsesWith(I, V);
// (A + 1) + ~B --> A - B
// ~B + (A + 1) --> A - B
if (match(&I, m_c_BinOp(m_Add(m_Value(A), m_One()), m_Not(m_Value(B)))))
return BinaryOperator::CreateSub(A, B);
// X % C0 + (( X / C0 ) % C1) * C0 => X % (C0 * C1)
if (Value *V = SimplifyAddWithRemainder(I)) return replaceInstUsesWith(I, V);
// A+B --> A|B iff A and B have no bits set in common.
if (haveNoCommonBitsSet(LHS, RHS, DL, &AC, &I, &DT))
return BinaryOperator::CreateOr(LHS, RHS);
// FIXME: We already did a check for ConstantInt RHS above this.
// FIXME: Is this pattern covered by another fold? No regression tests fail on
// removal.
if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
// (X & FF00) + xx00 -> (X+xx00) & FF00
Value *X;
ConstantInt *C2;
if (LHS->hasOneUse() &&
match(LHS, m_And(m_Value(X), m_ConstantInt(C2))) &&
CRHS->getValue() == (CRHS->getValue() & C2->getValue())) {
// See if all bits from the first bit set in the Add RHS up are included
// in the mask. First, get the rightmost bit.
const APInt &AddRHSV = CRHS->getValue();
// Form a mask of all bits from the lowest bit added through the top.
APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
// See if the and mask includes all of these bits.
APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
if (AddRHSHighBits == AddRHSHighBitsAnd) {
// Okay, the xform is safe. Insert the new add pronto.
Value *NewAdd = Builder.CreateAdd(X, CRHS, LHS->getName());
return BinaryOperator::CreateAnd(NewAdd, C2);
}
}
}
// add (select X 0 (sub n A)) A --> select X A n
{
SelectInst *SI = dyn_cast<SelectInst>(LHS);
Value *A = RHS;
if (!SI) {
SI = dyn_cast<SelectInst>(RHS);
A = LHS;
}
if (SI && SI->hasOneUse()) {
Value *TV = SI->getTrueValue();
Value *FV = SI->getFalseValue();
Value *N;
// Can we fold the add into the argument of the select?
// We check both true and false select arguments for a matching subtract.
if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
// Fold the add into the true select value.
return SelectInst::Create(SI->getCondition(), N, A);
if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
// Fold the add into the false select value.
return SelectInst::Create(SI->getCondition(), A, N);
}
}
if (Instruction *Ext = narrowMathIfNoOverflow(I))
return Ext;
// (add (xor A, B) (and A, B)) --> (or A, B)
// (add (and A, B) (xor A, B)) --> (or A, B)
if (match(&I, m_c_BinOp(m_Xor(m_Value(A), m_Value(B)),
m_c_And(m_Deferred(A), m_Deferred(B)))))
return BinaryOperator::CreateOr(A, B);
// (add (or A, B) (and A, B)) --> (add A, B)
// (add (and A, B) (or A, B)) --> (add A, B)
if (match(&I, m_c_BinOp(m_Or(m_Value(A), m_Value(B)),
m_c_And(m_Deferred(A), m_Deferred(B))))) {
I.setOperand(0, A);
I.setOperand(1, B);
return &I;
}
// TODO(jingyue): Consider willNotOverflowSignedAdd and
// willNotOverflowUnsignedAdd to reduce the number of invocations of
// computeKnownBits.
bool Changed = false;
if (!I.hasNoSignedWrap() && willNotOverflowSignedAdd(LHS, RHS, I)) {
Changed = true;
I.setHasNoSignedWrap(true);
}
if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedAdd(LHS, RHS, I)) {
Changed = true;
I.setHasNoUnsignedWrap(true);
}
if (Instruction *V = canonicalizeLowbitMask(I, Builder))
return V;
if (Instruction *SatAdd = foldToUnsignedSaturatedAdd(I))
return SatAdd;
return Changed ? &I : nullptr;
}
/// Factor a common operand out of fadd/fsub of fmul/fdiv.
static Instruction *factorizeFAddFSub(BinaryOperator &I,
InstCombiner::BuilderTy &Builder) {
assert((I.getOpcode() == Instruction::FAdd ||
I.getOpcode() == Instruction::FSub) && "Expecting fadd/fsub");
assert(I.hasAllowReassoc() && I.hasNoSignedZeros() &&
"FP factorization requires FMF");
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Value *X, *Y, *Z;
bool IsFMul;
if ((match(Op0, m_OneUse(m_FMul(m_Value(X), m_Value(Z)))) &&
match(Op1, m_OneUse(m_c_FMul(m_Value(Y), m_Specific(Z))))) ||
(match(Op0, m_OneUse(m_FMul(m_Value(Z), m_Value(X)))) &&
match(Op1, m_OneUse(m_c_FMul(m_Value(Y), m_Specific(Z))))))
IsFMul = true;
else if (match(Op0, m_OneUse(m_FDiv(m_Value(X), m_Value(Z)))) &&
match(Op1, m_OneUse(m_FDiv(m_Value(Y), m_Specific(Z)))))
IsFMul = false;
else
return nullptr;
// (X * Z) + (Y * Z) --> (X + Y) * Z
// (X * Z) - (Y * Z) --> (X - Y) * Z
// (X / Z) + (Y / Z) --> (X + Y) / Z
// (X / Z) - (Y / Z) --> (X - Y) / Z
bool IsFAdd = I.getOpcode() == Instruction::FAdd;
Value *XY = IsFAdd ? Builder.CreateFAddFMF(X, Y, &I)
: Builder.CreateFSubFMF(X, Y, &I);
// Bail out if we just created a denormal constant.
// TODO: This is copied from a previous implementation. Is it necessary?
const APFloat *C;
if (match(XY, m_APFloat(C)) && !C->isNormal())
return nullptr;
return IsFMul ? BinaryOperator::CreateFMulFMF(XY, Z, &I)
: BinaryOperator::CreateFDivFMF(XY, Z, &I);
}
Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
if (Value *V = SimplifyFAddInst(I.getOperand(0), I.getOperand(1),
I.getFastMathFlags(),
SQ.getWithInstruction(&I)))
return replaceInstUsesWith(I, V);
if (SimplifyAssociativeOrCommutative(I))
return &I;
if (Instruction *X = foldVectorBinop(I))
return X;
if (Instruction *FoldedFAdd = foldBinOpIntoSelectOrPhi(I))
return FoldedFAdd;
Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Value *X;
// (-X) + Y --> Y - X
if (match(LHS, m_FNeg(m_Value(X))))
return BinaryOperator::CreateFSubFMF(RHS, X, &I);
// Y + (-X) --> Y - X
if (match(RHS, m_FNeg(m_Value(X))))
return BinaryOperator::CreateFSubFMF(LHS, X, &I);
// Check for (fadd double (sitofp x), y), see if we can merge this into an
// integer add followed by a promotion.
if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
Value *LHSIntVal = LHSConv->getOperand(0);
Type *FPType = LHSConv->getType();
// TODO: This check is overly conservative. In many cases known bits
// analysis can tell us that the result of the addition has less significant
// bits than the integer type can hold.
auto IsValidPromotion = [](Type *FTy, Type *ITy) {
Type *FScalarTy = FTy->getScalarType();
Type *IScalarTy = ITy->getScalarType();
// Do we have enough bits in the significand to represent the result of
// the integer addition?
unsigned MaxRepresentableBits =
APFloat::semanticsPrecision(FScalarTy->getFltSemantics());
return IScalarTy->getIntegerBitWidth() <= MaxRepresentableBits;
};
// (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
// ... if the constant fits in the integer value. This is useful for things
// like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
// requires a constant pool load, and generally allows the add to be better
// instcombined.
if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
if (IsValidPromotion(FPType, LHSIntVal->getType())) {
Constant *CI =
ConstantExpr::getFPToSI(CFP, LHSIntVal->getType());
if (LHSConv->hasOneUse() &&
ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
willNotOverflowSignedAdd(LHSIntVal, CI, I)) {
// Insert the new integer add.
Value *NewAdd = Builder.CreateNSWAdd(LHSIntVal, CI, "addconv");
return new SIToFPInst(NewAdd, I.getType());
}
}
// (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
Value *RHSIntVal = RHSConv->getOperand(0);
// It's enough to check LHS types only because we require int types to
// be the same for this transform.
if (IsValidPromotion(FPType, LHSIntVal->getType())) {
// Only do this if x/y have the same type, if at least one of them has a
// single use (so we don't increase the number of int->fp conversions),
// and if the integer add will not overflow.
if (LHSIntVal->getType() == RHSIntVal->getType() &&
(LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
willNotOverflowSignedAdd(LHSIntVal, RHSIntVal, I)) {
// Insert the new integer add.
Value *NewAdd = Builder.CreateNSWAdd(LHSIntVal, RHSIntVal, "addconv");
return new SIToFPInst(NewAdd, I.getType());
}
}
}
}
// Handle specials cases for FAdd with selects feeding the operation
if (Value *V = SimplifySelectsFeedingBinaryOp(I, LHS, RHS))
return replaceInstUsesWith(I, V);
if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
if (Instruction *F = factorizeFAddFSub(I, Builder))
return F;
if (Value *V = FAddCombine(Builder).simplify(&I))
return replaceInstUsesWith(I, V);
}
return nullptr;
}
/// Optimize pointer differences into the same array into a size. Consider:
/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
Type *Ty) {
// If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
// this.
bool Swapped = false;
GEPOperator *GEP1 = nullptr, *GEP2 = nullptr;
// For now we require one side to be the base pointer "A" or a constant
// GEP derived from it.
if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
// (gep X, ...) - X
if (LHSGEP->getOperand(0) == RHS) {
GEP1 = LHSGEP;
Swapped = false;
} else if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
// (gep X, ...) - (gep X, ...)
if (LHSGEP->getOperand(0)->stripPointerCasts() ==
RHSGEP->getOperand(0)->stripPointerCasts()) {
GEP2 = RHSGEP;
GEP1 = LHSGEP;
Swapped = false;
}
}
}
if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
// X - (gep X, ...)
if (RHSGEP->getOperand(0) == LHS) {
GEP1 = RHSGEP;
Swapped = true;
} else if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
// (gep X, ...) - (gep X, ...)
if (RHSGEP->getOperand(0)->stripPointerCasts() ==
LHSGEP->getOperand(0)->stripPointerCasts()) {
GEP2 = LHSGEP;
GEP1 = RHSGEP;
Swapped = true;
}
}
}
if (!GEP1)
// No GEP found.
return nullptr;
if (GEP2) {
// (gep X, ...) - (gep X, ...)
//
// Avoid duplicating the arithmetic if there are more than one non-constant
// indices between the two GEPs and either GEP has a non-constant index and
// multiple users. If zero non-constant index, the result is a constant and
// there is no duplication. If one non-constant index, the result is an add
// or sub with a constant, which is no larger than the original code, and
// there's no duplicated arithmetic, even if either GEP has multiple
// users. If more than one non-constant indices combined, as long as the GEP
// with at least one non-constant index doesn't have multiple users, there
// is no duplication.
unsigned NumNonConstantIndices1 = GEP1->countNonConstantIndices();
unsigned NumNonConstantIndices2 = GEP2->countNonConstantIndices();
if (NumNonConstantIndices1 + NumNonConstantIndices2 > 1 &&
((NumNonConstantIndices1 > 0 && !GEP1->hasOneUse()) ||
(NumNonConstantIndices2 > 0 && !GEP2->hasOneUse()))) {
return nullptr;
}
}
// Emit the offset of the GEP and an intptr_t.
Value *Result = EmitGEPOffset(GEP1);
// If we had a constant expression GEP on the other side offsetting the
// pointer, subtract it from the offset we have.
if (GEP2) {
Value *Offset = EmitGEPOffset(GEP2);
Result = Builder.CreateSub(Result, Offset);
}
// If we have p - gep(p, ...) then we have to negate the result.
if (Swapped)
Result = Builder.CreateNeg(Result, "diff.neg");
return Builder.CreateIntCast(Result, Ty, true);
}
Instruction *InstCombiner::visitSub(BinaryOperator &I) {
if (Value *V = SimplifySubInst(I.getOperand(0), I.getOperand(1),
I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
SQ.getWithInstruction(&I)))
return replaceInstUsesWith(I, V);
if (Instruction *X = foldVectorBinop(I))
return X;
// (A*B)-(A*C) -> A*(B-C) etc
if (Value *V = SimplifyUsingDistributiveLaws(I))
return replaceInstUsesWith(I, V);
// If this is a 'B = x-(-A)', change to B = x+A.
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
if (Value *V = dyn_castNegVal(Op1)) {
BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
assert(BO->getOpcode() == Instruction::Sub &&
"Expected a subtraction operator!");
if (BO->hasNoSignedWrap() && I.hasNoSignedWrap())
Res->setHasNoSignedWrap(true);
} else {
if (cast<Constant>(Op1)->isNotMinSignedValue() && I.hasNoSignedWrap())
Res->setHasNoSignedWrap(true);
}
return Res;
}
if (I.getType()->isIntOrIntVectorTy(1))
return BinaryOperator::CreateXor(Op0, Op1);
// Replace (-1 - A) with (~A).
if (match(Op0, m_AllOnes()))
return BinaryOperator::CreateNot(Op1);
// (~X) - (~Y) --> Y - X
Value *X, *Y;
if (match(Op0, m_Not(m_Value(X))) && match(Op1, m_Not(m_Value(Y))))
return BinaryOperator::CreateSub(Y, X);
// (X + -1) - Y --> ~Y + X
if (match(Op0, m_OneUse(m_Add(m_Value(X), m_AllOnes()))))
return BinaryOperator::CreateAdd(Builder.CreateNot(Op1), X);
// Y - (X + 1) --> ~X + Y
if (match(Op1, m_OneUse(m_Add(m_Value(X), m_One()))))
return BinaryOperator::CreateAdd(Builder.CreateNot(X), Op0);
if (Constant *C = dyn_cast<Constant>(Op0)) {
bool IsNegate = match(C, m_ZeroInt());
Value *X;
if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
// 0 - (zext bool) --> sext bool
// C - (zext bool) --> bool ? C - 1 : C
if (IsNegate)
return CastInst::CreateSExtOrBitCast(X, I.getType());
return SelectInst::Create(X, SubOne(C), C);
}
if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
// 0 - (sext bool) --> zext bool
// C - (sext bool) --> bool ? C + 1 : C
if (IsNegate)
return CastInst::CreateZExtOrBitCast(X, I.getType());
return SelectInst::Create(X, AddOne(C), C);
}
// C - ~X == X + (1+C)
if (match(Op1, m_Not(m_Value(X))))
return BinaryOperator::CreateAdd(X, AddOne(C));
// Try to fold constant sub into select arguments.
if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
if (Instruction *R = FoldOpIntoSelect(I, SI))
return R;
// Try to fold constant sub into PHI values.
if (PHINode *PN = dyn_cast<PHINode>(Op1))
if (Instruction *R = foldOpIntoPhi(I, PN))
return R;
Constant *C2;
// C-(C2-X) --> X+(C-C2)
if (match(Op1, m_Sub(m_Constant(C2), m_Value(X))))
return BinaryOperator::CreateAdd(X, ConstantExpr::getSub(C, C2));
// C-(X+C2) --> (C-C2)-X
if (match(Op1, m_Add(m_Value(X), m_Constant(C2))))
return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
}
const APInt *Op0C;
if (match(Op0, m_APInt(Op0C))) {
unsigned BitWidth = I.getType()->getScalarSizeInBits();
// -(X >>u 31) -> (X >>s 31)
// -(X >>s 31) -> (X >>u 31)
if (Op0C->isNullValue()) {
Value *X;
const APInt *ShAmt;
if (match(Op1, m_LShr(m_Value(X), m_APInt(ShAmt))) &&
*ShAmt == BitWidth - 1) {
Value *ShAmtOp = cast<Instruction>(Op1)->getOperand(1);
return BinaryOperator::CreateAShr(X, ShAmtOp);
}
if (match(Op1, m_AShr(m_Value(X), m_APInt(ShAmt))) &&
*ShAmt == BitWidth - 1) {
Value *ShAmtOp = cast<Instruction>(Op1)->getOperand(1);
return BinaryOperator::CreateLShr(X, ShAmtOp);
}
if (Op1->hasOneUse()) {
Value *LHS, *RHS;
SelectPatternFlavor SPF = matchSelectPattern(Op1, LHS, RHS).Flavor;
if (SPF == SPF_ABS || SPF == SPF_NABS) {
// This is a negate of an ABS/NABS pattern. Just swap the operands
// of the select.
SelectInst *SI = cast<SelectInst>(Op1);
Value *TrueVal = SI->getTrueValue();
Value *FalseVal = SI->getFalseValue();
SI->setTrueValue(FalseVal);
SI->setFalseValue(TrueVal);
// Don't swap prof metadata, we didn't change the branch behavior.
return replaceInstUsesWith(I, SI);
}
}
}
// Turn this into a xor if LHS is 2^n-1 and the remaining bits are known
// zero.
if (Op0C->isMask()) {
KnownBits RHSKnown = computeKnownBits(Op1, 0, &I);
if ((*Op0C | RHSKnown.Zero).isAllOnesValue())
return BinaryOperator::CreateXor(Op1, Op0);
}
}
{
Value *Y;
// X-(X+Y) == -Y X-(Y+X) == -Y
if (match(Op1, m_c_Add(m_Specific(Op0), m_Value(Y))))
return BinaryOperator::CreateNeg(Y);
// (X-Y)-X == -Y
if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
return BinaryOperator::CreateNeg(Y);
}
// (sub (or A, B), (xor A, B)) --> (and A, B)
{
Value *A, *B;
if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
return BinaryOperator::CreateAnd(A, B);
}
{
Value *Y;
// ((X | Y) - X) --> (~X & Y)
if (match(Op0, m_OneUse(m_c_Or(m_Value(Y), m_Specific(Op1)))))
return BinaryOperator::CreateAnd(
Y, Builder.CreateNot(Op1, Op1->getName() + ".not"));
}
if (Op1->hasOneUse()) {
Value *X = nullptr, *Y = nullptr, *Z = nullptr;
Constant *C = nullptr;
// (X - (Y - Z)) --> (X + (Z - Y)).
if (match(Op1, m_Sub(m_Value(Y), m_Value(Z))))
return BinaryOperator::CreateAdd(Op0,
Builder.CreateSub(Z, Y, Op1->getName()));
// (X - (X & Y)) --> (X & ~Y)
if (match(Op1, m_c_And(m_Value(Y), m_Specific(Op0))))
return BinaryOperator::CreateAnd(Op0,
Builder.CreateNot(Y, Y->getName() + ".not"));
// 0 - (X sdiv C) -> (X sdiv -C) provided the negation doesn't overflow.
// TODO: This could be extended to match arbitrary vector constants.
const APInt *DivC;
if (match(Op0, m_Zero()) && match(Op1, m_SDiv(m_Value(X), m_APInt(DivC))) &&
!DivC->isMinSignedValue() && *DivC != 1) {
Constant *NegDivC = ConstantInt::get(I.getType(), -(*DivC));
Instruction *BO = BinaryOperator::CreateSDiv(X, NegDivC);
BO->setIsExact(cast<BinaryOperator>(Op1)->isExact());
return BO;
}
// 0 - (X << Y) -> (-X << Y) when X is freely negatable.
if (match(Op1, m_Shl(m_Value(X), m_Value(Y))) && match(Op0, m_Zero()))
if (Value *XNeg = dyn_castNegVal(X))
return BinaryOperator::CreateShl(XNeg, Y);
// Subtracting -1/0 is the same as adding 1/0:
// sub [nsw] Op0, sext(bool Y) -> add [nsw] Op0, zext(bool Y)
// 'nuw' is dropped in favor of the canonical form.
if (match(Op1, m_SExt(m_Value(Y))) &&
Y->getType()->getScalarSizeInBits() == 1) {
Value *Zext = Builder.CreateZExt(Y, I.getType());
BinaryOperator *Add = BinaryOperator::CreateAdd(Op0, Zext);
Add->setHasNoSignedWrap(I.hasNoSignedWrap());
return Add;
}
// X - A*-B -> X + A*B
// X - -A*B -> X + A*B
Value *A, *B;
if (match(Op1, m_c_Mul(m_Value(A), m_Neg(m_Value(B)))))
return BinaryOperator::CreateAdd(Op0, Builder.CreateMul(A, B));
// X - A*C -> X + A*-C
// No need to handle commuted multiply because multiply handling will
// ensure constant will be move to the right hand side.
if (match(Op1, m_Mul(m_Value(A), m_Constant(C))) && !isa<ConstantExpr>(C)) {
Value *NewMul = Builder.CreateMul(A, ConstantExpr::getNeg(C));
return BinaryOperator::CreateAdd(Op0, NewMul);
}
}
{
// ~A - Min/Max(~A, O) -> Max/Min(A, ~O) - A
// ~A - Min/Max(O, ~A) -> Max/Min(A, ~O) - A
// Min/Max(~A, O) - ~A -> A - Max/Min(A, ~O)
// Min/Max(O, ~A) - ~A -> A - Max/Min(A, ~O)
// So long as O here is freely invertible, this will be neutral or a win.
Value *LHS, *RHS, *A;
Value *NotA = Op0, *MinMax = Op1;
SelectPatternFlavor SPF = matchSelectPattern(MinMax, LHS, RHS).Flavor;
if (!SelectPatternResult::isMinOrMax(SPF)) {
NotA = Op1;
MinMax = Op0;
SPF = matchSelectPattern(MinMax, LHS, RHS).Flavor;
}
if (SelectPatternResult::isMinOrMax(SPF) &&
match(NotA, m_Not(m_Value(A))) && (NotA == LHS || NotA == RHS)) {
if (NotA == LHS)
std::swap(LHS, RHS);
// LHS is now O above and expected to have at least 2 uses (the min/max)
// NotA is epected to have 2 uses from the min/max and 1 from the sub.
if (IsFreeToInvert(LHS, !LHS->hasNUsesOrMore(3)) &&
!NotA->hasNUsesOrMore(4)) {
// Note: We don't generate the inverse max/min, just create the not of
// it and let other folds do the rest.
Value *Not = Builder.CreateNot(MinMax);
if (NotA == Op0)
return BinaryOperator::CreateSub(Not, A);
else
return BinaryOperator::CreateSub(A, Not);
}
}
}
// Optimize pointer differences into the same array into a size. Consider:
// &A[10] - &A[0]: we should compile this to "10".
Value *LHSOp, *RHSOp;
if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
match(Op1, m_PtrToInt(m_Value(RHSOp))))
if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
return replaceInstUsesWith(I, Res);
// trunc(p)-trunc(q) -> trunc(p-q)
if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
return replaceInstUsesWith(I, Res);
// Canonicalize a shifty way to code absolute value to the common pattern.
// There are 2 potential commuted variants.
// We're relying on the fact that we only do this transform when the shift has
// exactly 2 uses and the xor has exactly 1 use (otherwise, we might increase
// instructions).
Value *A;
const APInt *ShAmt;
Type *Ty = I.getType();
if (match(Op1, m_AShr(m_Value(A), m_APInt(ShAmt))) &&
Op1->hasNUses(2) && *ShAmt == Ty->getScalarSizeInBits() - 1 &&
match(Op0, m_OneUse(m_c_Xor(m_Specific(A), m_Specific(Op1))))) {
// B = ashr i32 A, 31 ; smear the sign bit
// sub (xor A, B), B ; flip bits if negative and subtract -1 (add 1)
// --> (A < 0) ? -A : A
Value *Cmp = Builder.CreateICmpSLT(A, ConstantInt::getNullValue(Ty));
// Copy the nuw/nsw flags from the sub to the negate.
Value *Neg = Builder.CreateNeg(A, "", I.hasNoUnsignedWrap(),
I.hasNoSignedWrap());
return SelectInst::Create(Cmp, Neg, A);
}
if (Instruction *Ext = narrowMathIfNoOverflow(I))
return Ext;
bool Changed = false;
if (!I.hasNoSignedWrap() && willNotOverflowSignedSub(Op0, Op1, I)) {
Changed = true;
I.setHasNoSignedWrap(true);
}
if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedSub(Op0, Op1, I)) {
Changed = true;
I.setHasNoUnsignedWrap(true);
}
return Changed ? &I : nullptr;
}
/// This eliminates floating-point negation in either 'fneg(X)' or
/// 'fsub(-0.0, X)' form by combining into a constant operand.
static Instruction *foldFNegIntoConstant(Instruction &I) {
Value *X;
Constant *C;
// Fold negation into constant operand. This is limited with one-use because
// fneg is assumed better for analysis and cheaper in codegen than fmul/fdiv.
// -(X * C) --> X * (-C)
// FIXME: It's arguable whether these should be m_OneUse or not. The current
// belief is that the FNeg allows for better reassociation opportunities.
if (match(&I, m_FNeg(m_OneUse(m_FMul(m_Value(X), m_Constant(C))))))
return BinaryOperator::CreateFMulFMF(X, ConstantExpr::getFNeg(C), &I);
// -(X / C) --> X / (-C)
if (match(&I, m_FNeg(m_OneUse(m_FDiv(m_Value(X), m_Constant(C))))))
return BinaryOperator::CreateFDivFMF(X, ConstantExpr::getFNeg(C), &I);
// -(C / X) --> (-C) / X
if (match(&I, m_FNeg(m_OneUse(m_FDiv(m_Constant(C), m_Value(X))))))
return BinaryOperator::CreateFDivFMF(ConstantExpr::getFNeg(C), X, &I);
return nullptr;
}
Instruction *InstCombiner::visitFNeg(UnaryOperator &I) {
Value *Op = I.getOperand(0);
if (Value *V = SimplifyFNegInst(Op, I.getFastMathFlags(),
SQ.getWithInstruction(&I)))
return replaceInstUsesWith(I, V);
if (Instruction *X = foldFNegIntoConstant(I))
return X;
Value *X, *Y;
// If we can ignore the sign of zeros: -(X - Y) --> (Y - X)
if (I.hasNoSignedZeros() &&
match(Op, m_OneUse(m_FSub(m_Value(X), m_Value(Y)))))
return BinaryOperator::CreateFSubFMF(Y, X, &I);
return nullptr;
}
Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
if (Value *V = SimplifyFSubInst(I.getOperand(0), I.getOperand(1),
I.getFastMathFlags(),
SQ.getWithInstruction(&I)))
return replaceInstUsesWith(I, V);
if (Instruction *X = foldVectorBinop(I))
return X;
// Subtraction from -0.0 is the canonical form of fneg.
// fsub nsz 0, X ==> fsub nsz -0.0, X
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
if (I.hasNoSignedZeros() && match(Op0, m_PosZeroFP()))
return BinaryOperator::CreateFNegFMF(Op1, &I);
if (Instruction *X = foldFNegIntoConstant(I))
return X;
Value *X, *Y;
Constant *C;
// If Op0 is not -0.0 or we can ignore -0.0: Z - (X - Y) --> Z + (Y - X)
// Canonicalize to fadd to make analysis easier.
// This can also help codegen because fadd is commutative.
// Note that if this fsub was really an fneg, the fadd with -0.0 will get
// killed later. We still limit that particular transform with 'hasOneUse'
// because an fneg is assumed better/cheaper than a generic fsub.
if (I.hasNoSignedZeros() || CannotBeNegativeZero(Op0, SQ.TLI)) {
if (match(Op1, m_OneUse(m_FSub(m_Value(X), m_Value(Y))))) {
Value *NewSub = Builder.CreateFSubFMF(Y, X, &I);
return BinaryOperator::CreateFAddFMF(Op0, NewSub, &I);
}
}
if (isa<Constant>(Op0))
if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
if (Instruction *NV = FoldOpIntoSelect(I, SI))
return NV;
// X - C --> X + (-C)
// But don't transform constant expressions because there's an inverse fold
// for X + (-Y) --> X - Y.
if (match(Op1, m_Constant(C)) && !isa<ConstantExpr>(Op1))
return BinaryOperator::CreateFAddFMF(Op0, ConstantExpr::getFNeg(C), &I);
// X - (-Y) --> X + Y
if (match(Op1, m_FNeg(m_Value(Y))))
return BinaryOperator::CreateFAddFMF(Op0, Y, &I);
// Similar to above, but look through a cast of the negated value:
// X - (fptrunc(-Y)) --> X + fptrunc(Y)
Type *Ty = I.getType();
if (match(Op1, m_OneUse(m_FPTrunc(m_FNeg(m_Value(Y))))))
return BinaryOperator::CreateFAddFMF(Op0, Builder.CreateFPTrunc(Y, Ty), &I);
// X - (fpext(-Y)) --> X + fpext(Y)
if (match(Op1, m_OneUse(m_FPExt(m_FNeg(m_Value(Y))))))
return BinaryOperator::CreateFAddFMF(Op0, Builder.CreateFPExt(Y, Ty), &I);
// Handle special cases for FSub with selects feeding the operation
if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
return replaceInstUsesWith(I, V);
if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
// (Y - X) - Y --> -X
if (match(Op0, m_FSub(m_Specific(Op1), m_Value(X))))
return BinaryOperator::CreateFNegFMF(X, &I);
// Y - (X + Y) --> -X
// Y - (Y + X) --> -X
if (match(Op1, m_c_FAdd(m_Specific(Op0), m_Value(X))))
return BinaryOperator::CreateFNegFMF(X, &I);
// (X * C) - X --> X * (C - 1.0)
if (match(Op0, m_FMul(m_Specific(Op1), m_Constant(C)))) {
Constant *CSubOne = ConstantExpr::getFSub(C, ConstantFP::get(Ty, 1.0));
return BinaryOperator::CreateFMulFMF(Op1, CSubOne, &I);
}
// X - (X * C) --> X * (1.0 - C)
if (match(Op1, m_FMul(m_Specific(Op0), m_Constant(C)))) {
Constant *OneSubC = ConstantExpr::getFSub(ConstantFP::get(Ty, 1.0), C);
return BinaryOperator::CreateFMulFMF(Op0, OneSubC, &I);
}
if (Instruction *F = factorizeFAddFSub(I, Builder))
return F;
// TODO: This performs reassociative folds for FP ops. Some fraction of the
// functionality has been subsumed by simple pattern matching here and in
// InstSimplify. We should let a dedicated reassociation pass handle more
// complex pattern matching and remove this from InstCombine.
if (Value *V = FAddCombine(Builder).simplify(&I))
return replaceInstUsesWith(I, V);
}
return nullptr;
}
|
#include "Core/Core.h"
#include <angelscript.h>
#include "AngelState.h"
#include <SDL_mixer.h>
#include "Math/Math.h"
#include "Asset/AssetManager.h"
using namespace asset;
using namespace math;
namespace script
{
int convertVolumef(float vol)
{
return (int)(max(min(vol, 1.0f), 0.0f) * MIX_MAX_VOLUME);
}
int angelSound_playSound(AssetRef asset, float volume)
{
AssetManager* assetManager = AngelState::getCurrent()->getAssetManager();
int channel = Mix_PlayChannel(-1, assetManager->getSound(asset), 0);
Mix_Volume(channel, convertVolumef(volume));
//Return channel so that the volume can be changed anytime
return channel;
}
void angelSound_setSoundVolume(int channel, float volume)
{
Mix_Volume(channel, convertVolumef(volume));
}
void angelSound_playMusic(AssetRef asset, float volume, bool loops)
{
AssetManager* assetManager = AngelState::getCurrent()->getAssetManager();
Mix_Music* music = assetManager->streamMusic(asset);
Mix_PlayMusic(music, loops ? -1 : 1);
Mix_VolumeMusic(convertVolumef(volume));
}
bool angelSound_isMusicPlaying()
{
return (Mix_PlayingMusic() != 0);
}
void angelSound_setMusicVolume(float volume)
{
Mix_VolumeMusic(convertVolumef(volume));
}
void angelSound_RegisterTypes(asIScriptEngine* engine)
{
AS_VERIFY(engine->RegisterGlobalFunction("int playSound(AssetRef asset, float volume = 1.0f)", asFUNCTION(angelSound_playSound), asCALL_CDECL));
AS_VERIFY(engine->RegisterGlobalFunction("void setSoundVolume(int channel, float volume)", asFUNCTION(angelSound_setSoundVolume), asCALL_CDECL));
AS_VERIFY(engine->RegisterGlobalFunction("void playMusic(AssetRef asset, float volume, bool loops)", asFUNCTION(angelSound_playMusic), asCALL_CDECL));
AS_VERIFY(engine->RegisterGlobalFunction("bool isMusicPlaying()", asFUNCTION(angelSound_isMusicPlaying), asCALL_CDECL));
AS_VERIFY(engine->RegisterGlobalFunction("void setMusicVolume(float volume)", asFUNCTION(angelSound_setMusicVolume), asCALL_CDECL));
}
}
|
/*++
Copyright (c) 2015 Microsoft Corporation
Module Name:
rlimit.cpp
Abstract:
Resource limit container.
Author:
Nikolaj Bjorner (nbjorner) 2015-09-28
Revision History:
--*/
#include "util/rlimit.h"
#include "util/common_msgs.h"
#include "util/mutex.h"
static DECLARE_MUTEX(g_rlimit_mux);
void initialize_rlimit() {
ALLOC_MUTEX(g_rlimit_mux);
}
void finalize_rlimit() {
DEALLOC_MUTEX(g_rlimit_mux);
}
reslimit::reslimit():
m_cancel(0),
m_suspend(false),
m_count(0),
m_limit(std::numeric_limits<uint64_t>::max()) {
}
uint64_t reslimit::count() const {
return m_count;
}
bool reslimit::inc() {
++m_count;
return not_canceled();
}
bool reslimit::inc(unsigned offset) {
m_count += offset;
return not_canceled();
}
void reslimit::push(unsigned delta_limit) {
uint64_t new_limit = delta_limit ? delta_limit + m_count : std::numeric_limits<uint64_t>::max();
if (new_limit <= m_count) {
new_limit = std::numeric_limits<uint64_t>::max();
}
m_limits.push_back(m_limit);
m_limit = std::min(new_limit, m_limit);
m_cancel = 0;
}
void reslimit::pop() {
if (m_count > m_limit) {
m_count = m_limit;
}
m_limit = m_limits.back();
m_limits.pop_back();
m_cancel = 0;
}
char const* reslimit::get_cancel_msg() const {
if (m_cancel > 0) {
return Z3_CANCELED_MSG;
}
else {
return Z3_MAX_RESOURCE_MSG;
}
}
void reslimit::push_child(reslimit* r) {
lock_guard lock(*g_rlimit_mux);
m_children.push_back(r);
}
void reslimit::pop_child() {
lock_guard lock(*g_rlimit_mux);
m_children.pop_back();
}
void reslimit::cancel() {
lock_guard lock(*g_rlimit_mux);
set_cancel(m_cancel+1);
}
void reslimit::reset_cancel() {
lock_guard lock(*g_rlimit_mux);
set_cancel(0);
}
void reslimit::inc_cancel() {
lock_guard lock(*g_rlimit_mux);
set_cancel(m_cancel+1);
}
void reslimit::dec_cancel() {
lock_guard lock(*g_rlimit_mux);
if (m_cancel > 0) {
set_cancel(m_cancel-1);
}
}
void reslimit::set_cancel(unsigned f) {
m_cancel = f;
for (unsigned i = 0; i < m_children.size(); ++i) {
m_children[i]->set_cancel(f);
}
}
|
/*=============================================================================
Copyright (c) 2003 Vaclav Vesely
http://spirit.sourceforge.net/
Use, modification and distribution is subject to the Boost Software
License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#include <boost/spirit/include/classic_core.hpp>
#include <boost/spirit/include/classic_assign_actor.hpp>
#include <boost/core/lightweight_test.hpp>
using namespace boost;
using namespace BOOST_SPIRIT_CLASSIC_NS;
int main()
{
rule<parser_context<int> > int_rule = int_p;
int result(0);
parse("123", int_rule[assign_a(result)]);
BOOST_TEST(result == 123);
return boost::report_errors();
}
|
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/greengrass/model/ListFunctionDefinitionVersionsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/http/URI.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <utility>
using namespace Aws::Greengrass::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws::Http;
ListFunctionDefinitionVersionsRequest::ListFunctionDefinitionVersionsRequest() :
m_functionDefinitionIdHasBeenSet(false),
m_maxResultsHasBeenSet(false),
m_nextTokenHasBeenSet(false)
{
}
Aws::String ListFunctionDefinitionVersionsRequest::SerializePayload() const
{
return {};
}
void ListFunctionDefinitionVersionsRequest::AddQueryStringParameters(URI& uri) const
{
Aws::StringStream ss;
if(m_maxResultsHasBeenSet)
{
ss << m_maxResults;
uri.AddQueryStringParameter("MaxResults", ss.str());
ss.str("");
}
if(m_nextTokenHasBeenSet)
{
ss << m_nextToken;
uri.AddQueryStringParameter("NextToken", ss.str());
ss.str("");
}
}
|
/*
* This file contains code from "C++ Primer, Fourth Edition", by Stanley B.
* Lippman, Jose Lajoie, and Barbara E. Moo, and is covered under the
* copyright and warranty notices given in that book:
*
* "Copyright (c) 2005 by Objectwrite, Inc., Jose Lajoie, and Barbara E. Moo."
*
*
* "The authors and publisher have taken care in the preparation of this book,
* but make no expressed or implied warranty of any kind and assume no
* responsibility for errors or omissions. No liability is assumed for
* incidental or consequential damages in connection with or arising out of the
* use of the information or programs contained herein."
*
* Permission is granted for this code to be used for educational purposes in
* association with the book, given proper citation if and when posted or
* reproduced.Any commercial use of this code requires the explicit written
* permission of the publisher, Addison-Wesley Professional, a division of
* Pearson Education, Inc. Send your request for permission, stating clearly
* what code you would like to use, and in what specific way, to the following
* address:
*
* Pearson Education, Inc.
* Rights and Contracts Department
* 75 Arlington Street, Suite 300
* Boston, MA 02216
* Fax: (617) 848-7047
*/
#include <iostream>
using std::cout; using std::endl;
#include "Queue.h"
int main()
{
// the class Queue<int> is instantiated
// new expression requires that Queue<int> be defined
Queue<int> *p_qi = new Queue<int>;
int ival;
for (ival = 0; ival != 10; ++ival)
// the member function push() is instantiated
p_qi->push(ival);
int err_cnt = 0;
for (ival = 0; ival != 10; ++ival) {
// the member function front is instantiated
int qval = p_qi->front();
if (ival != qval) err_cnt++;
p_qi->pop(); // instantiates pop
}
if (!err_cnt)
cout << "!! queue executed ok" << endl;
else
cout << "?? " << err_cnt << " Queue errors" << endl;
delete p_qi; // deletes elements in the queue
return 0;
}
|
// generated from rosidl_typesupport_introspection_cpp/resource/idl__type_support.cpp.em
// with input from halodi_msgs:msg/ImuMeasurement.idl
// generated code does not contain a copyright notice
#include "array"
#include "cstddef"
#include "string"
#include "vector"
#include "rosidl_generator_c/message_type_support_struct.h"
#include "rosidl_typesupport_cpp/message_type_support.hpp"
#include "rosidl_typesupport_interface/macros.h"
#include "halodi_msgs/msg/imu_measurement__struct.hpp"
#include "rosidl_typesupport_introspection_cpp/field_types.hpp"
#include "rosidl_typesupport_introspection_cpp/identifier.hpp"
#include "rosidl_typesupport_introspection_cpp/message_introspection.hpp"
#include "rosidl_typesupport_introspection_cpp/message_type_support_decl.hpp"
#include "rosidl_typesupport_introspection_cpp/visibility_control.h"
namespace halodi_msgs
{
namespace msg
{
namespace rosidl_typesupport_introspection_cpp
{
void ImuMeasurement_init_function(
void * message_memory, rosidl_generator_cpp::MessageInitialization _init)
{
new (message_memory) halodi_msgs::msg::ImuMeasurement(_init);
}
void ImuMeasurement_fini_function(void * message_memory)
{
auto typed_message = static_cast<halodi_msgs::msg::ImuMeasurement *>(message_memory);
typed_message->~ImuMeasurement();
}
static const ::rosidl_typesupport_introspection_cpp::MessageMember ImuMeasurement_message_member_array[4] = {
{
"imu", // name
::rosidl_typesupport_introspection_cpp::ROS_TYPE_MESSAGE, // type
0, // upper bound of string
::rosidl_typesupport_introspection_cpp::get_message_type_support_handle<halodi_msgs::msg::ImuName>(), // members of sub message
false, // is array
0, // array size
false, // is upper bound
offsetof(halodi_msgs::msg::ImuMeasurement, imu), // bytes offset in struct
nullptr, // default value
nullptr, // size() function pointer
nullptr, // get_const(index) function pointer
nullptr, // get(index) function pointer
nullptr // resize(index) function pointer
},
{
"orientation", // name
::rosidl_typesupport_introspection_cpp::ROS_TYPE_MESSAGE, // type
0, // upper bound of string
::rosidl_typesupport_introspection_cpp::get_message_type_support_handle<geometry_msgs::msg::Quaternion>(), // members of sub message
false, // is array
0, // array size
false, // is upper bound
offsetof(halodi_msgs::msg::ImuMeasurement, orientation), // bytes offset in struct
nullptr, // default value
nullptr, // size() function pointer
nullptr, // get_const(index) function pointer
nullptr, // get(index) function pointer
nullptr // resize(index) function pointer
},
{
"angular_velocity", // name
::rosidl_typesupport_introspection_cpp::ROS_TYPE_MESSAGE, // type
0, // upper bound of string
::rosidl_typesupport_introspection_cpp::get_message_type_support_handle<geometry_msgs::msg::Vector3>(), // members of sub message
false, // is array
0, // array size
false, // is upper bound
offsetof(halodi_msgs::msg::ImuMeasurement, angular_velocity), // bytes offset in struct
nullptr, // default value
nullptr, // size() function pointer
nullptr, // get_const(index) function pointer
nullptr, // get(index) function pointer
nullptr // resize(index) function pointer
},
{
"linear_acceleration", // name
::rosidl_typesupport_introspection_cpp::ROS_TYPE_MESSAGE, // type
0, // upper bound of string
::rosidl_typesupport_introspection_cpp::get_message_type_support_handle<geometry_msgs::msg::Vector3>(), // members of sub message
false, // is array
0, // array size
false, // is upper bound
offsetof(halodi_msgs::msg::ImuMeasurement, linear_acceleration), // bytes offset in struct
nullptr, // default value
nullptr, // size() function pointer
nullptr, // get_const(index) function pointer
nullptr, // get(index) function pointer
nullptr // resize(index) function pointer
}
};
static const ::rosidl_typesupport_introspection_cpp::MessageMembers ImuMeasurement_message_members = {
"halodi_msgs::msg", // message namespace
"ImuMeasurement", // message name
4, // number of fields
sizeof(halodi_msgs::msg::ImuMeasurement),
ImuMeasurement_message_member_array, // message members
ImuMeasurement_init_function, // function to initialize message memory (memory has to be allocated)
ImuMeasurement_fini_function // function to terminate message instance (will not free memory)
};
static const rosidl_message_type_support_t ImuMeasurement_message_type_support_handle = {
::rosidl_typesupport_introspection_cpp::typesupport_identifier,
&ImuMeasurement_message_members,
get_message_typesupport_handle_function,
};
} // namespace rosidl_typesupport_introspection_cpp
} // namespace msg
} // namespace halodi_msgs
namespace rosidl_typesupport_introspection_cpp
{
template<>
ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_PUBLIC
const rosidl_message_type_support_t *
get_message_type_support_handle<halodi_msgs::msg::ImuMeasurement>()
{
return &::halodi_msgs::msg::rosidl_typesupport_introspection_cpp::ImuMeasurement_message_type_support_handle;
}
} // namespace rosidl_typesupport_introspection_cpp
#ifdef __cplusplus
extern "C"
{
#endif
ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_PUBLIC
const rosidl_message_type_support_t *
ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_introspection_cpp, halodi_msgs, msg, ImuMeasurement)() {
return &::halodi_msgs::msg::rosidl_typesupport_introspection_cpp::ImuMeasurement_message_type_support_handle;
}
#ifdef __cplusplus
}
#endif
|
#include <QtGlobal>
// Automatically generated by extract_strings.py
#ifdef __GNUC__
#define UNUSED __attribute__((unused))
#else
#define UNUSED
#endif
static const char UNUSED *bitcoin_strings[] = {QT_TRANSLATE_NOOP("bitcoin-core", "To use the %s option"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"%s, you must set a rpcpassword in the configuration file:\n"
" %s\n"
"It is recommended you use the following random password:\n"
"rpcuser=egamingcoinrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"The username and password MUST NOT be the same.\n"
"If the file does not exist, create it with owner-readable-only file "
"permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"Egamingcoin Alert\" admin@foo."
"com\n"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"An error occurred while setting up the RPC port %u for listening on IPv6, "
"falling back to IPv4: %s"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"An error occurred while setting up the RPC port %u for listening on IPv4: %s"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"You must set rpcpassword=<password> in the configuration file:\n"
"%s\n"
"If the file does not exist, create it with owner-readable-only file "
"permissions."),
QT_TRANSLATE_NOOP("bitcoin-core", "Egamingcoin version"),
QT_TRANSLATE_NOOP("bitcoin-core", "Usage:"),
QT_TRANSLATE_NOOP("bitcoin-core", "Send command to -server or egamingcoind"),
QT_TRANSLATE_NOOP("bitcoin-core", "List commands"),
QT_TRANSLATE_NOOP("bitcoin-core", "Get help for a command"),
QT_TRANSLATE_NOOP("bitcoin-core", "Egamingcoin"),
QT_TRANSLATE_NOOP("bitcoin-core", "Options:"),
QT_TRANSLATE_NOOP("bitcoin-core", "This help message"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify configuration file (default: egamingcoin.conf)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify pid file (default: egamingcoind.pid)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify data directory"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify wallet file (within data directory)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Set database cache size in megabytes (default: 25)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Set database disk log size in megabytes (default: 100)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify connection timeout in milliseconds (default: 5000)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Connect through socks proxy"),
QT_TRANSLATE_NOOP("bitcoin-core", "Select the version of socks proxy to use (4-5, default: 5)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Use proxy to reach tor hidden services (default: same as -proxy)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Allow DNS lookups for -addnode, -seednode and -connect"),
QT_TRANSLATE_NOOP("bitcoin-core", "Listen for connections on <port> (default: 35291 or testnet: 45291)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Maintain at most <n> connections to peers (default: 125)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Add a node to connect to and attempt to keep the connection open"),
QT_TRANSLATE_NOOP("bitcoin-core", "Connect only to the specified node(s)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Connect to a node to retrieve peer addresses, and disconnect"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify your own public address"),
QT_TRANSLATE_NOOP("bitcoin-core", "Only connect to nodes in network <net> (IPv4, IPv6 or Tor)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Discover own IP address (default: 1 when listening and no -externalip)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Find peers using internet relay chat (default: 0)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Accept connections from outside (default: 1 if no -proxy or -connect)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Bind to given address. Use [host]:port notation for IPv6"),
QT_TRANSLATE_NOOP("bitcoin-core", "Find peers using DNS lookup (default: 1)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Stake your coins to support network and gain reward (default: 1)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Sync time with other nodes. Disable if time on your system is precise e.g. "
"syncing with NTP (default: 1)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Sync checkpoints policy (default: strict)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Threshold for disconnecting misbehaving peers (default: 100)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Number of seconds to keep misbehaving peers from reconnecting (default: "
"86400)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Use UPnP to map the listening port (default: 1 when listening)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Use UPnP to map the listening port (default: 0)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Detach block and address databases. Increases shutdown time (default: 0)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Fee per KB to add to transactions you send"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"When creating transactions, ignore inputs with value less than this "
"(default: 0.01)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Accept command line and JSON-RPC commands"),
QT_TRANSLATE_NOOP("bitcoin-core", "Run in the background as a daemon and accept commands"),
QT_TRANSLATE_NOOP("bitcoin-core", "Use the test network"),
QT_TRANSLATE_NOOP("bitcoin-core", "Output extra debugging information. Implies all other -debug* options"),
QT_TRANSLATE_NOOP("bitcoin-core", "Output extra network debugging information"),
QT_TRANSLATE_NOOP("bitcoin-core", "Prepend debug output with timestamp"),
QT_TRANSLATE_NOOP("bitcoin-core", "Shrink debug.log file on client startup (default: 1 when no -debug)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Send trace/debug info to console instead of debug.log file"),
QT_TRANSLATE_NOOP("bitcoin-core", "Send trace/debug info to debugger"),
QT_TRANSLATE_NOOP("bitcoin-core", "Username for JSON-RPC connections"),
QT_TRANSLATE_NOOP("bitcoin-core", "Password for JSON-RPC connections"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Listen for JSON-RPC connections on <port> (default: 35292 or testnet: 45292)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Allow JSON-RPC connections from specified IP address"),
QT_TRANSLATE_NOOP("bitcoin-core", "Send commands to node running on <ip> (default: 127.0.0.1)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Execute command when the best block changes (%s in cmd is replaced by block "
"hash)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Execute command when a wallet transaction changes (%s in cmd is replaced by "
"TxID)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Require a confirmations for change (default: 0)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Enforce transaction scripts to use canonical PUSH operators (default: 1)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Execute command when a relevant alert is received (%s in cmd is replaced by "
"message)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Upgrade wallet to latest format"),
QT_TRANSLATE_NOOP("bitcoin-core", "Set key pool size to <n> (default: 100)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Rescan the block chain for missing wallet transactions"),
QT_TRANSLATE_NOOP("bitcoin-core", "Attempt to recover private keys from a corrupt wallet.dat"),
QT_TRANSLATE_NOOP("bitcoin-core", "How many blocks to check at startup (default: 2500, 0 = all)"),
QT_TRANSLATE_NOOP("bitcoin-core", "How thorough the block verification is (0-6, default: 1)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Imports blocks from external blk000?.dat file"),
QT_TRANSLATE_NOOP("bitcoin-core", "Block creation options:"),
QT_TRANSLATE_NOOP("bitcoin-core", "Set minimum block size in bytes (default: 0)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Set maximum block size in bytes (default: 250000)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Set maximum size of high-priority/low-fee transactions in bytes (default: "
"27000)"),
QT_TRANSLATE_NOOP("bitcoin-core", "SSL options: (see the Bitcoin Wiki for SSL setup instructions)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Use OpenSSL (https) for JSON-RPC connections"),
QT_TRANSLATE_NOOP("bitcoin-core", "Server certificate file (default: server.cert)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Server private key (default: server.pem)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:"
"@STRENGTH)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -paytxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Warning: -paytxfee is set very high! This is the transaction fee you will "
"pay if you send a transaction."),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -mininput=<amount>: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Wallet %s resides outside data directory %s."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Cannot obtain a lock on data directory %s. Egamingcoin is probably already "
"running."),
QT_TRANSLATE_NOOP("bitcoin-core", "Verifying database integrity..."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Error initializing database environment %s! To recover, BACKUP THAT "
"DIRECTORY, then remove everything from it except for wallet.dat."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as "
"wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect "
"you should restore from a backup."),
QT_TRANSLATE_NOOP("bitcoin-core", "wallet.dat corrupt, salvage failed"),
QT_TRANSLATE_NOOP("bitcoin-core", "Unknown -socks proxy version requested: %i"),
QT_TRANSLATE_NOOP("bitcoin-core", "Unknown network specified in -onlynet: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid -proxy address: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid -tor address: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Cannot resolve -bind address: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Failed to listen on any port. Use -listen=0 if you want this."),
QT_TRANSLATE_NOOP("bitcoin-core", "Cannot resolve -externalip address: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -reservebalance=<amount>"),
QT_TRANSLATE_NOOP("bitcoin-core", "Unable to sign checkpoint, wrong checkpointkey?\n"),
QT_TRANSLATE_NOOP("bitcoin-core", "Loading block index..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Error loading blkindex.dat"),
QT_TRANSLATE_NOOP("bitcoin-core", "Loading wallet..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat: Wallet corrupted"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Warning: error reading wallet.dat! All keys read correctly, but transaction "
"data or address book entries might be missing or incorrect."),
QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat: Wallet requires newer version of Egamingcoin"),
QT_TRANSLATE_NOOP("bitcoin-core", "Wallet needed to be rewritten: restart Egamingcoin to complete"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat"),
QT_TRANSLATE_NOOP("bitcoin-core", "Cannot downgrade wallet"),
QT_TRANSLATE_NOOP("bitcoin-core", "Cannot initialize keypool"),
QT_TRANSLATE_NOOP("bitcoin-core", "Cannot write default address"),
QT_TRANSLATE_NOOP("bitcoin-core", "Rescanning..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Importing blockchain data file."),
QT_TRANSLATE_NOOP("bitcoin-core", "Importing bootstrap blockchain data file."),
QT_TRANSLATE_NOOP("bitcoin-core", "Loading addresses..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Error: could not start node"),
QT_TRANSLATE_NOOP("bitcoin-core", "Done loading"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Unable to bind to %s on this computer. Egamingcoin is probably already running."),
QT_TRANSLATE_NOOP("bitcoin-core", "Unable to bind to %s on this computer (bind returned error %d, %s)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error: Wallet locked, unable to create transaction "),
QT_TRANSLATE_NOOP("bitcoin-core", "Error: Wallet unlocked for staking only, unable to create transaction."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Error: This transaction requires a transaction fee of at least %s because of "
"its amount, complexity, or use of recently received funds "),
QT_TRANSLATE_NOOP("bitcoin-core", "Error: Transaction creation failed "),
QT_TRANSLATE_NOOP("bitcoin-core", "Sending..."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Error: The transaction was rejected. This might happen if some of the coins "
"in your wallet were already spent, such as if you used a copy of wallet.dat "
"and coins were spent in the copy but not marked as spent here."),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount"),
QT_TRANSLATE_NOOP("bitcoin-core", "Insufficient funds"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Warning: Please check that your computer's date and time are correct! If "
"your clock is wrong Egamingcoin will not work properly."),
QT_TRANSLATE_NOOP("bitcoin-core", "Warning: This version is obsolete, upgrade required!"),
QT_TRANSLATE_NOOP("bitcoin-core", "WARNING: syncronized checkpoint violation detected, but skipped!"),
QT_TRANSLATE_NOOP("bitcoin-core", "Warning: Disk space is low!"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"WARNING: Invalid checkpoint found! Displayed transactions may not be "
"correct! You may need to upgrade, or notify developers."),
};
|
#pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/REDhash.hpp>
#include <RED4ext/Types/generated/user/SettingsVar.hpp>
namespace RED4ext
{
namespace user {
struct SettingsVarListName : user::SettingsVar
{
static constexpr const char* NAME = "userSettingsVarListName";
static constexpr const char* ALIAS = "ConfigVarListName";
};
RED4EXT_ASSERT_SIZE(SettingsVarListName, 0x48);
} // namespace user
using ConfigVarListName = user::SettingsVarListName;
} // namespace RED4ext
|
/*=========================================================================
*
* Copyright NumFOCUS
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkCSVFileReaderBase.h"
#include <fstream>
namespace itk
{
CSVFileReaderBase::CSVFileReaderBase()
{
this->m_FileName = "";
this->m_FieldDelimiterCharacter = ',';
this->m_StringDelimiterCharacter = '"';
this->m_HasColumnHeaders = true;
this->m_HasRowHeaders = true;
this->m_UseStringDelimiterCharacter = false;
this->m_Line = "";
this->m_EndOfColumnHeadersLine = 0;
}
void
CSVFileReaderBase::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "File Name: " << this->m_FileName << std::endl;
os << indent << "FieldDelimiterCharacter: " << this->m_FieldDelimiterCharacter << std::endl;
os << indent << "StringDelimier Character: " << this->m_StringDelimiterCharacter << std::endl;
os << indent << "Has Row Headers : " << this->m_HasRowHeaders << std::endl;
os << indent << "Has Column Headers: " << this->m_HasColumnHeaders << std::endl;
os << indent << "Use of String Delimiter character: " << this->m_UseStringDelimiterCharacter << std::endl;
os << indent << "Position of end of column headers: " << this->m_EndOfColumnHeadersLine << std::endl;
}
void
CSVFileReaderBase::PrepareForParsing()
{
if (this->m_FileName.empty())
{
itkExceptionMacro(<< "There is no file name provided!"
<< "Please provide a filename.");
}
if (this->m_UseStringDelimiterCharacter && !(this->m_HasRowHeaders || this->m_HasColumnHeaders))
{
itkWarningMacro(<< " Use string delimiter has been set to on"
<< "but row and/or column headers indicators are off!");
}
if (this->m_UseStringDelimiterCharacter && this->m_FieldDelimiterCharacter == this->m_StringDelimiterCharacter)
{
itkExceptionMacro(<< "The same character has been set for the string"
<< "delimiter and the field delimiter character!");
}
}
void
CSVFileReaderBase::GetDataDimension(SizeValueType & rows, SizeValueType & cols)
{
this->m_InputStream.seekg(0);
rows = 0;
cols = 0;
std::string line;
std::string cell;
unsigned int prev_cols = 0;
unsigned int current_cols = 0;
unsigned int max_cols = 0;
bool isSame = true;
// If column headers exist,
if (this->m_HasColumnHeaders)
{
std::getline(this->m_InputStream, line);
this->m_EndOfColumnHeadersLine = this->m_InputStream.tellg();
// Count the number of headers
std::stringstream linestream(line);
if (this->m_UseStringDelimiterCharacter)
{
int cellnum = 0;
while (std::getline(linestream, cell, this->m_StringDelimiterCharacter))
{
if (cellnum % 2 != 0)
{
prev_cols++;
}
cellnum++;
}
}
// if not using StringDelimiter, just count using the field delimiter
// character
else
{
while (std::getline(linestream, cell, this->m_FieldDelimiterCharacter))
{
prev_cols++;
}
}
// previous columns now holds the number of headers minus the first header,
// if there are row headers
if (this->m_HasRowHeaders)
{
prev_cols -= 1;
}
max_cols = prev_cols;
}
// Count the number of entries in each of the following lines
while (std::getline(this->m_InputStream, line))
{
cols = 0;
std::stringstream linestream(line);
// If row headers exist, move past (but do not count) the row header in
// each line.
if (this->m_HasRowHeaders)
{
if (this->m_UseStringDelimiterCharacter)
{
for (int k = 0; k < 2; ++k)
{
std::getline(linestream, cell, this->m_StringDelimiterCharacter);
}
std::getline(linestream, cell, this->m_FieldDelimiterCharacter);
}
else
{
std::getline(linestream, cell, this->m_FieldDelimiterCharacter);
}
}
// Count the entries
while (std::getline(linestream, cell, this->m_FieldDelimiterCharacter))
{
cols++;
}
rows++;
// Determine the max #columns and #rows
current_cols = cols;
if (!this->m_HasColumnHeaders && rows == 1)
{
prev_cols = cols;
max_cols = cols;
}
if (current_cols != prev_cols)
{
isSame = false;
if (current_cols > max_cols)
{
max_cols = current_cols;
}
prev_cols = current_cols;
}
}
// If the number of entries is not consistent across each row, display a
// warning to the user.
if (!isSame)
{
itkWarningMacro(<< "Warning: Data appears to contain missing data! "
<< "These will be set to NaN.");
}
cols = max_cols;
this->m_InputStream.clear();
this->m_InputStream.seekg(0);
}
/** Function to get the next entry from the file. */
void
CSVFileReaderBase::GetNextField(std::string & str)
{
/** The process below is as follows: we check if this->m_Line is empty. If it is
* then we have to get a new line. If not, we have to get the fields that
* this->m_Line contains. We check if the line we're on contains column headers.
* If so, we get a column header and then delete it from this->m_Line.
* If we're not on the column header line, we're either getting a row header
* or a data field. If we're on a new line and row headers exist, the
* assumption is the first field we get from the line is the row header.
* After that, we get data fields. Once we get a field, delete it from
* this->m_Line. This way the next field that we need to get is always at the
* beginning of this->m_Line. */
std::string empty;
// Check that we are not at the end of the file
itkDebugMacro(<< "m_Line: " << m_Line);
if (!this->m_InputStream.eof())
{
bool OnANewLine = false;
bool OnColumnHeadersLine = false;
if (this->m_Line.empty())
{
std::getline(this->m_InputStream, this->m_Line);
OnANewLine = true;
}
if (this->m_InputStream.tellg() <= this->m_EndOfColumnHeadersLine)
{
OnColumnHeadersLine = true;
}
if (OnColumnHeadersLine)
{
std::istringstream linestream(this->m_Line);
// if the string delimiter character is being used, delimit using it
if (this->m_UseStringDelimiterCharacter)
{
// move past the first string delimiter
std::getline(linestream, empty, this->m_StringDelimiterCharacter);
// get the string within the string delimiters
std::getline(linestream, str, this->m_StringDelimiterCharacter);
// move past the field delimiter
std::getline(linestream, empty, this->m_FieldDelimiterCharacter);
// erase this entry from this->m_Line
this->m_Line.erase(0, str.size() + 3);
}
// if string delimiter not being used, just delimit using the field
// delimiter
else
{
std::getline(linestream, str, this->m_FieldDelimiterCharacter);
this->m_Line.erase(0, str.size() + 1);
}
}
else
{
/** if we're not on the column headers line, but we're on a new line, and
* row headers exist and the string delimiter is being used. */
if (this->m_HasRowHeaders && OnANewLine && this->m_UseStringDelimiterCharacter)
{
std::istringstream linestream(this->m_Line);
// move past the first string delimiter
std::getline(linestream, empty, this->m_StringDelimiterCharacter);
// get the string within the string delimiters
std::getline(linestream, str, this->m_StringDelimiterCharacter);
// move past the field delimiter
std::getline(linestream, empty, this->m_FieldDelimiterCharacter);
// erase this entry from this->m_Line
this->m_Line.erase(0, str.size() + 3);
OnANewLine = false;
}
// for any other entry, just get the next entry using the field delimiter
else
{
std::istringstream linestream(this->m_Line);
std::getline(linestream, str, this->m_FieldDelimiterCharacter);
this->m_Line.erase(0, str.size() + 1);
}
}
}
// Alert the user if end of file is reached
else
{
itkExceptionMacro(<< "End of file reached. No more entries");
}
}
} // end namespace itk
|
// Copyright (c) 2019 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "qt/mninfodialog.h"
#include "qt/forms/ui_mninfodialog.h"
#include "walletmodel.h"
#include "wallet/wallet.h"
#include "guiutil.h"
#include "qt/qtutils.h"
#include <QDateTime>
MnInfoDialog::MnInfoDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::MnInfoDialog)
{
ui->setupUi(this);
this->setStyleSheet(parent->styleSheet());
setCssProperty(ui->frame, "container-dialog");
ui->labelTitle->setText(tr("Master Node Information"));
setCssProperty(ui->labelTitle, "text-title-dialog");
setCssTextLabelDialog({ui->labelAmount, ui->labelSend, ui->labelInputs, ui->labelFee, ui->labelId});
setCssProperty({ui->labelDivider1, ui->labelDivider4, ui->labelDivider6, ui->labelDivider7, ui->labelDivider8, ui->labelDivider9}, "container-divider");
setCssTextBodyDialog({ui->textAmount, ui->textAddress, ui->textInputs, ui->textStatus, ui->textId, ui->textExport});
setCssProperty({ui->pushCopy, ui->pushCopyId, ui->pushExport}, "ic-copy-big");
setCssProperty(ui->btnEsc, "ic-close");
connect(ui->btnEsc, SIGNAL(clicked()), this, SLOT(closeDialog()));
connect(ui->pushCopy, &QPushButton::clicked, [this](){ copyInform(pubKey, "Master Node public key copied"); });
connect(ui->pushCopyId, &QPushButton::clicked, [this](){ copyInform(txId, "Collateral tx id copied"); });
connect(ui->pushExport, &QPushButton::clicked, [this](){ exportMN = true; accept(); });
}
void MnInfoDialog::setData(QString pubKey, QString name, QString address, QString txId, QString outputIndex, QString status){
this->pubKey = pubKey;
this->txId = txId;
QString shortPubKey = pubKey;
QString shortTxId = txId;
if(shortPubKey.length() > 20) {
shortPubKey = shortPubKey.left(13) + "..." + shortPubKey.right(13);
}
if(shortTxId.length() > 20) {
shortTxId = shortTxId.left(12) + "..." + shortTxId.right(12);
}
ui->textId->setText(shortPubKey);
ui->textAddress->setText(address);
ui->textAmount->setText(shortTxId);
ui->textInputs->setText(outputIndex);
ui->textStatus->setText(status);
}
void MnInfoDialog::copyInform(QString& copyStr, QString message){
GUIUtil::setClipboard(copyStr);
if(!snackBar) snackBar = new SnackBar(nullptr, this);
snackBar->setText(tr(message.toStdString().c_str()));
snackBar->resize(this->width(), snackBar->height());
openDialog(snackBar, this);
}
void MnInfoDialog::closeDialog(){
if(snackBar && snackBar->isVisible()) snackBar->hide();
close();
}
MnInfoDialog::~MnInfoDialog(){
if(snackBar) delete snackBar;
delete ui;
}
|
#pragma once
#include "IModule.hpp"
#include "InverseKinematics.hpp"
#include "Servomechanism.hpp"
// local Y axis is used as look direction
class Yaml;
class Turret : public IModule
{
private:
int m_targetIndex;
Servomechanism servo;
InverseKinematics ik;
const glm::vec4& getTarget() {
return vehicle.fireControlUnit->getTarget(m_targetIndex);
}
public:
Turret(const std::string& name, Vehicle& vehicle, IModule* parent, const Yaml& yaml)
: IModule(name, vehicle, parent), servo(yaml), ik(yaml) {
m_targetIndex = vehicle.fireControlUnit->idForTurret();
}
void update(float dt) override {
auto [x, y, z] = ik.calculate(getTransform(), vehicle.fireControlUnit->getTarget(m_targetIndex));
servo.updateTarget(x, y, z);
servo.run(dt);
this->transform(servo.getTransform());
}
};
class GunServo : public IModule
{
private:
int m_targetIndex;
Servomechanism servo;
InverseKinematics ik;
const glm::vec4& getTarget() {
return vehicle.fireControlUnit->getTarget(m_targetIndex);
}
public:
GunServo(const std::string& name, Vehicle& vehicle, IModule* parent, const Yaml& yaml)
: IModule(name, vehicle, parent), servo(yaml), ik(yaml) {
m_targetIndex = vehicle.fireControlUnit->idForGunServo();
}
void update(float dt) override {
auto [x, y, z] = ik.calculate(getTransform(), vehicle.fireControlUnit->getTarget(m_targetIndex));
servo.updateTarget(x, y, z);
servo.run(dt);
this->transform(servo.getTransform());
}
};
class Gun : public IModule
{
private:
int m_targetIndex;
const glm::vec4& getTarget() {
return vehicle.fireControlUnit->getTarget(m_targetIndex);
}
public:
Gun(const std::string& name, Vehicle& vehicle, IModule* parent) : IModule(name, vehicle, parent) {
m_targetIndex = vehicle.fireControlUnit->idForGun(reinterpret_cast<u64>(parent));
}
void update(float dt) override {
this->transform(glm::mat4(1));
}
std::string resource;
};
|
// Copyright 2012 Cloudera Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "parquet/parquet.h"
#include "parquet/encodings/encodings.h"
#include "parquet/compression/codec.h"
#include <algorithm>
#include <string>
#include <string.h>
#include <thrift/protocol/TDebugProtocol.h>
const int DATA_PAGE_SIZE = 64 * 1024;
namespace parquet_cpp {
using parquet::CompressionCodec;
using parquet::Encoding;
using parquet::FieldRepetitionType;
using parquet::PageType;
using parquet::SchemaElement;
using parquet::Type;
InMemoryInputStream::InMemoryInputStream(const uint8_t* buffer, int64_t len) :
buffer_(buffer), len_(len), offset_(0) {
}
const uint8_t* InMemoryInputStream::Peek(int num_to_peek, int* num_bytes) {
*num_bytes = std::min(static_cast<int64_t>(num_to_peek), len_ - offset_);
return buffer_ + offset_;
}
const uint8_t* InMemoryInputStream::Read(int num_to_read, int* num_bytes) {
const uint8_t* result = Peek(num_to_read, num_bytes);
offset_ += *num_bytes;
return result;
}
ColumnReader::~ColumnReader() {
}
ColumnReader::ColumnReader(const parquet::ColumnMetaData* metadata,
const SchemaElement* schema, InputStream* stream)
: metadata_(metadata),
schema_(schema),
stream_(stream),
current_decoder_(NULL),
num_buffered_values_(0),
num_decoded_values_(0),
buffered_values_offset_(0) {
int value_byte_size;
switch (metadata->type) {
case parquet::Type::BOOLEAN:
value_byte_size = 1;
break;
case parquet::Type::INT32:
value_byte_size = sizeof(int32_t);
break;
case parquet::Type::INT64:
value_byte_size = sizeof(int64_t);
break;
case parquet::Type::FLOAT:
value_byte_size = sizeof(float);
break;
case parquet::Type::DOUBLE:
value_byte_size = sizeof(double);
break;
case parquet::Type::BYTE_ARRAY:
value_byte_size = sizeof(ByteArray);
break;
default:
ParquetException::NYI("Unsupported type");
}
switch (metadata->codec) {
case CompressionCodec::UNCOMPRESSED:
break;
case CompressionCodec::SNAPPY:
decompressor_.reset(new SnappyCodec());
break;
default:
ParquetException::NYI("Reading compressed data");
}
config_ = Config::DefaultConfig();
values_buffer_.resize(config_.batch_size * value_byte_size);
}
void ColumnReader::BatchDecode() {
buffered_values_offset_ = 0;
uint8_t* buf = &values_buffer_[0];
int batch_size = config_.batch_size;
switch (metadata_->type) {
case parquet::Type::BOOLEAN:
num_decoded_values_ =
current_decoder_->GetBool(reinterpret_cast<bool*>(buf), batch_size);
break;
case parquet::Type::INT32:
num_decoded_values_ =
current_decoder_->GetInt32(reinterpret_cast<int32_t*>(buf), batch_size);
break;
case parquet::Type::INT64:
num_decoded_values_ =
current_decoder_->GetInt64(reinterpret_cast<int64_t*>(buf), batch_size);
break;
case parquet::Type::FLOAT:
num_decoded_values_ =
current_decoder_->GetFloat(reinterpret_cast<float*>(buf), batch_size);
break;
case parquet::Type::DOUBLE:
num_decoded_values_ =
current_decoder_->GetDouble(reinterpret_cast<double*>(buf), batch_size);
break;
case parquet::Type::BYTE_ARRAY:
num_decoded_values_ =
current_decoder_->GetByteArray(reinterpret_cast<ByteArray*>(buf), batch_size);
break;
default:
ParquetException::NYI("Unsupported type.");
}
}
// PLAIN_DICTIONARY is deprecated but used to be used as a dictionary index
// encoding.
static bool IsDictionaryIndexEncoding(const Encoding::type& e) {
return e == Encoding::RLE_DICTIONARY || e == Encoding::PLAIN_DICTIONARY;
}
bool ColumnReader::ReadNewPage() {
// Loop until we find the next data page.
while (true) {
int bytes_read = 0;
const uint8_t* buffer = stream_->Peek(DATA_PAGE_SIZE, &bytes_read);
if (bytes_read == 0) return false;
uint32_t header_size = bytes_read;
DeserializeThriftMsg(buffer, &header_size, ¤t_page_header_);
stream_->Read(header_size, &bytes_read);
int compressed_len = current_page_header_.compressed_page_size;
int uncompressed_len = current_page_header_.uncompressed_page_size;
// Read the compressed data page.
buffer = stream_->Read(compressed_len, &bytes_read);
if (bytes_read != compressed_len) ParquetException::EofException();
// Uncompress it if we need to
if (decompressor_ != NULL) {
// Grow the uncompressed buffer if we need to.
if (uncompressed_len > decompression_buffer_.size()) {
decompression_buffer_.resize(uncompressed_len);
}
decompressor_->Decompress(
compressed_len, buffer, uncompressed_len, &decompression_buffer_[0]);
buffer = &decompression_buffer_[0];
}
if (current_page_header_.type == PageType::DICTIONARY_PAGE) {
std::unordered_map<Encoding::type, std::shared_ptr<Decoder> >::iterator it =
decoders_.find(Encoding::RLE_DICTIONARY);
if (it != decoders_.end()) {
throw ParquetException("Column cannot have more than one dictionary.");
}
PlainDecoder dictionary(schema_->type);
dictionary.SetData(current_page_header_.dictionary_page_header.num_values,
buffer, uncompressed_len);
std::shared_ptr<Decoder> decoder(
new DictionaryDecoder(schema_->type, &dictionary));
decoders_[Encoding::RLE_DICTIONARY] = decoder;
current_decoder_ = decoders_[Encoding::RLE_DICTIONARY].get();
continue;
} else if (current_page_header_.type == PageType::DATA_PAGE) {
// Read a data page.
num_buffered_values_ = current_page_header_.data_page_header.num_values;
// Read definition levels.
if (schema_->repetition_type != FieldRepetitionType::REQUIRED) {
int num_definition_bytes = *reinterpret_cast<const uint32_t*>(buffer);
buffer += sizeof(uint32_t);
definition_level_decoder_.reset(
new RleDecoder(buffer, num_definition_bytes, 1));
buffer += num_definition_bytes;
uncompressed_len -= sizeof(uint32_t);
uncompressed_len -= num_definition_bytes;
}
// TODO: repetition levels
// Get a decoder object for this page or create a new decoder if this is the
// first page with this encoding.
Encoding::type encoding = current_page_header_.data_page_header.encoding;
if (IsDictionaryIndexEncoding(encoding)) encoding = Encoding::RLE_DICTIONARY;
std::unordered_map<Encoding::type, std::shared_ptr<Decoder> >::iterator it =
decoders_.find(encoding);
if (it != decoders_.end()) {
current_decoder_ = it->second.get();
} else {
switch (encoding) {
case Encoding::PLAIN: {
std::shared_ptr<Decoder> decoder;
if (schema_->type == Type::BOOLEAN) {
decoder.reset(new BoolDecoder());
} else {
decoder.reset(new PlainDecoder(schema_->type));
}
decoders_[encoding] = decoder;
current_decoder_ = decoder.get();
break;
}
case Encoding::RLE_DICTIONARY:
throw ParquetException("Dictionary page must be before data page.");
case Encoding::DELTA_BINARY_PACKED:
case Encoding::DELTA_LENGTH_BYTE_ARRAY:
case Encoding::DELTA_BYTE_ARRAY:
ParquetException::NYI("Unsupported encoding");
default:
throw ParquetException("Unknown encoding type.");
}
}
current_decoder_->SetData(num_buffered_values_, buffer, uncompressed_len);
return true;
} else {
// We don't know what this page type is. We're allowed to skip non-data pages.
continue;
}
}
return true;
}
} // namespace parquet_cpp
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
while(t--){
long n, k, sum_dad = 0, sum_son = 0;
cin >> n >> k;
std::vector<long> v(n);
for (long i = 0; i < n; ++i)
{
cin >> v[i];
}
sort(v.begin(), v.end());
k = (n - k < k) ? (n - k) : k;
for(int i = 0; i < n; ++i)
{
if(i < k)
sum_son += v[i];
else
sum_dad += v[i];
}
// cout << sum_dad << endl;
// cout << sum_son << endl;
cout << abs(sum_dad - sum_son) << endl;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.