text
stringlengths 5
1.04M
|
|---|
/* Copyright (c) 2011-2015 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any purpose
* with or without fee is hereby granted, provided that the above copyright
* notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
* RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
* CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "TestUtil.h"
#include "InfUdDriver.h"
#include "IpAddress.h"
#include "MockFastTransport.h"
namespace RAMCloud {
class InfUdDriverTest : public ::testing::Test {
public:
Context context;
TestLog::Enable logEnabler;
InfUdDriverTest()
: context()
, logEnabler()
{}
// Used to wait for data to arrive on a driver by invoking the
// dispatcher's polling loop; gives up if a long time goes by with
// no data.
const char *receivePacket(MockFastTransport *transport) {
transport->packetData.clear();
uint64_t start = Cycles::rdtsc();
while (true) {
context.dispatch->poll();
if (transport->packetData.size() != 0) {
return transport->packetData.c_str();
}
if (Cycles::toSeconds(Cycles::rdtsc() - start) > .1) {
return "no packet arrived";
}
}
}
private:
DISALLOW_COPY_AND_ASSIGN(InfUdDriverTest);
};
TEST_F(InfUdDriverTest, basics) {
// Send a packet from a client-style driver to a server-style
// driver.
ServiceLocator serverLocator("fast+infud:");
InfUdDriver *server =
new InfUdDriver(&context, &serverLocator, false);
MockFastTransport serverTransport(&context, server);
InfUdDriver *client =
new InfUdDriver(&context, NULL, false);
MockFastTransport clientTransport(&context, client);
Driver::Address* serverAddress =
client->newAddress(ServiceLocator(server->getServiceLocator()));
Buffer message;
const char *testString = "This is a sample message";
message.appendExternal(testString, downCast<uint32_t>(strlen(testString)));
Buffer::Iterator iterator(&message);
client->sendPacket(serverAddress, "header:", 7, &iterator);
TestLog::reset();
EXPECT_STREQ("header:This is a sample message",
receivePacket(&serverTransport));
EXPECT_EQ("", TestLog::get());
// Send a response back in the other direction.
message.reset();
message.appendExternal("response", 8);
Buffer::Iterator iterator2(&message);
server->sendPacket(serverTransport.sender, "h:", 2, &iterator2);
EXPECT_STREQ("h:response", receivePacket(&clientTransport));
delete serverAddress;
}
} // namespace RAMCloud
|
//
// Copyright (c) 2019 Maxime Pinard
//
// Distributed under the MIT license
// See accompanying file LICENSE or copy at
// https://opensource.org/licenses/MIT
//
#include "solver/algorithms/memetic.hpp"
#include "solver/data/solution.hpp"
#include "common/utils/logger.hpp"
uscp::memetic::position_serial uscp::memetic::position::serialize() const noexcept
{
position_serial serial;
serial.generation = generation;
serial.rwls_cumulative_position = rwls_cumulative_position.serialize();
serial.time = time;
return serial;
}
bool uscp::memetic::position::load(const uscp::memetic::position_serial& serial) noexcept
{
generation = serial.generation;
if(!rwls_cumulative_position.load(serial.rwls_cumulative_position))
{
LOGGER->warn("Failed to load rwls cumulative position");
return false;
}
time = serial.time;
return true;
}
uscp::memetic::config_serial uscp::memetic::config::serialize() const noexcept
{
config_serial serial;
serial.stopping_criterion = stopping_criterion.serialize();
serial.rwls_stopping_criterion = rwls_stopping_criterion.serialize();
return serial;
}
bool uscp::memetic::config::load(const uscp::memetic::config_serial& serial) noexcept
{
if(!stopping_criterion.load(serial.stopping_criterion))
{
LOGGER->warn("Failed to load stopping criterion");
return false;
}
if(!rwls_stopping_criterion.load(serial.rwls_stopping_criterion))
{
LOGGER->warn("Failed to load rwls stopping criterion");
return false;
}
return true;
}
uscp::memetic::report::report(const uscp::problem::instance& problem) noexcept
: solution_final(problem), found_at(), solve_config(), crossover_operator()
{
}
uscp::memetic::report_serial uscp::memetic::report::serialize() const noexcept
{
report_serial serial;
serial.solution_final = solution_final.serialize();
serial.points_weights_final = points_weights_final;
serial.found_at = found_at.serialize();
serial.ended_at = ended_at.serialize();
serial.solve_config = solve_config.serialize();
serial.crossover_operator = crossover_operator;
serial.wcrossover_operator = wcrossover_operator;
return serial;
}
bool uscp::memetic::report::load(const uscp::memetic::report_serial& serial) noexcept
{
if(!solution_final.load(serial.solution_final))
{
LOGGER->warn("Failed to load final solution");
return false;
}
points_weights_final = serial.points_weights_final;
if(!found_at.load(serial.found_at))
{
LOGGER->warn("Failed to load solution found at position");
return false;
}
if(!ended_at.load(serial.ended_at))
{
LOGGER->warn("Failed to load solution ended at position");
return false;
}
if(!solve_config.load(serial.solve_config))
{
LOGGER->warn("Failed to load solving config");
return false;
}
crossover_operator = serial.crossover_operator;
wcrossover_operator = serial.wcrossover_operator;
return true;
}
uscp::memetic::report uscp::memetic::expand(const uscp::memetic::report& reduced_report) noexcept
{
if(!reduced_report.solution_final.problem.reduction.has_value())
{
LOGGER->error("Tried to expand report of non-reduced instance");
return reduced_report;
}
report expanded_report(*reduced_report.solution_final.problem.reduction->parent_instance);
expanded_report.solution_final = expand(reduced_report.solution_final);
expanded_report.points_weights_final = expand_points_info(reduced_report.solution_final.problem,
reduced_report.points_weights_final);
expanded_report.found_at = reduced_report.found_at;
expanded_report.ended_at = reduced_report.ended_at;
expanded_report.solve_config = reduced_report.solve_config;
expanded_report.crossover_operator = reduced_report.crossover_operator;
expanded_report.wcrossover_operator = reduced_report.wcrossover_operator;
return expanded_report;
}
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/md_history_ui.h"
#include "build/build_config.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/browsing_history_handler.h"
#include "chrome/browser/ui/webui/metrics_handler.h"
#include "chrome/common/url_constants.h"
#include "components/search/search.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
#include "grit/browser_resources.h"
#include "grit/components_strings.h"
#include "grit/theme_resources.h"
#include "ui/base/resource/resource_bundle.h"
#if !defined(OS_ANDROID)
#include "chrome/browser/ui/webui/foreign_session_handler.h"
#include "chrome/browser/ui/webui/history_login_handler.h"
#endif
namespace {
content::WebUIDataSource* CreateMdHistoryUIHTMLSource() {
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUIHistoryHost);
// Localized strings (alphabetical order).
source->AddLocalizedString("title", IDS_HISTORY_TITLE);
// TODO(tsergeant): File resources (alphabetical order).
source->SetDefaultResource(IDR_MD_HISTORY_HISTORY_HTML);
source->SetJsonPath("strings.js");
return source;
}
} // namespace
MdHistoryUI::MdHistoryUI(content::WebUI* web_ui) : WebUIController(web_ui) {
web_ui->AddMessageHandler(new BrowsingHistoryHandler());
web_ui->AddMessageHandler(new MetricsHandler());
// On mobile we deal with foreign sessions differently.
#if !defined(OS_ANDROID)
if (search::IsInstantExtendedAPIEnabled()) {
web_ui->AddMessageHandler(new browser_sync::ForeignSessionHandler());
web_ui->AddMessageHandler(new HistoryLoginHandler());
}
#endif
Profile* profile = Profile::FromWebUI(web_ui);
content::WebUIDataSource::Add(profile, CreateMdHistoryUIHTMLSource());
}
MdHistoryUI::~MdHistoryUI() {}
base::RefCountedMemory* MdHistoryUI::GetFaviconResourceBytes(
ui::ScaleFactor scale_factor) {
return ResourceBundle::GetSharedInstance().LoadDataResourceBytesForScale(
IDR_HISTORY_FAVICON, scale_factor);
}
|
#include <functional>
#include <iostream>
auto escape(std::string const& s) -> std::string
{
std::string escaped;
escaped += '"';
for (auto c : s) {
if (c == '\\' || c == '"') {
escaped += '\\';
}
escaped += c;
}
escaped += '"';
return escaped;
}
auto main() -> int
{
unsigned len = 0;
// Parse the input
for (std::string line; std::getline(std::cin, line);) {
std::string escaped = escape(line);
len += escaped.length() - line.length();
std::cout << line << ": " << line.length() << " memory bytes, " << escaped.length()
<< " escaped bytes, difference: " << escaped.length() - line.length() << "\n";
}
std::cout << len << "\n";
return 0;
}
|
#include "NetList.h"
#include "imgui/imgui.h"
NetList::NetList(TcharStringCallback cbNetSelected) {
cbNetSelected_ = cbNetSelected;
}
NetList::~NetList() {}
void NetList::Draw(const char *title, bool *p_open, Board *board) {
if (title && p_open) { }
// TODO: export / fix dimensions & behaviour
int width = 400;
int height = 640;
ImGui::SetNextWindowSize(ImVec2(width, height));
ImGui::Begin("Net List");
ImGui::Columns(1, "part_infos");
ImGui::Separator();
ImGui::Text("Name");
ImGui::NextColumn();
ImGui::Separator();
if (board) {
auto nets = board->Nets();
static int selected = -1;
string net_name = "";
ImGuiListClipper clipper;
clipper.Begin(nets.size());
while (clipper.Step()) {
for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) {
net_name = nets.at(i)->name;
if (ImGui::Selectable(
net_name.c_str(), selected == i, ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowDoubleClick)) {
selected = i;
if (ImGui::IsMouseDoubleClicked(0)) {
cbNetSelected_(net_name.c_str());
}
}
ImGui::NextColumn();
}
}
clipper.End();
}
ImGui::Columns(1);
ImGui::Separator();
ImGui::End();
}
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The BiblePay Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "amount.h"
#include "chain.h"
#include "chainparams.h"
#include "checkpoints.h"
#include "rpcpog.h"
#include "rpcpodc.h"
#include "kjv.h"
#include "coins.h"
#include "core_io.h"
#include "consensus/validation.h"
#include "instantx.h"
#include "validation.h"
#include "policy/policy.h"
#include "primitives/transaction.h"
#include "rpc/server.h"
#include "streams.h"
#include "spork.h"
#include "sync.h"
#include "txdb.h"
#include "txmempool.h"
#include "util.h"
#include "utilstrencodings.h"
#include "hash.h"
#include "governance-classes.h"
#include "evo/specialtx.h"
#include "evo/cbtx.h"
#include "smartcontract-client.h"
#include "smartcontract-server.h"
#include "masternode-sync.h"
#include <stdint.h>
#include <univalue.h>
#include <boost/thread/thread.hpp> // boost::thread::interrupt
#include <boost/algorithm/string.hpp> // boost::trim
#include <mutex>
#include <condition_variable>
struct CUpdatedBlock
{
uint256 hash;
int height;
};
static std::mutex cs_blockchange;
static std::condition_variable cond_blockchange;
static CUpdatedBlock latestblock;
extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry);
void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex);
UniValue protx_register(const JSONRPCRequest& request);
UniValue protx(const JSONRPCRequest& request);
UniValue _bls(const JSONRPCRequest& request);
UniValue hexblocktocoinbase(const JSONRPCRequest& request);
double GetDifficulty(const CBlockIndex* blockindex)
{
// Floating point number that is a multiple of the minimum difficulty,
// minimum difficulty = 1.0.
if (blockindex == NULL)
{
if (chainActive.Tip() == NULL)
return 1.0;
else
blockindex = chainActive.Tip();
}
int nShift = (blockindex->nBits >> 24) & 0xff;
double dDiff =
(double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);
while (nShift < 29)
{
dDiff *= 256.0;
nShift++;
}
while (nShift > 29)
{
dDiff /= 256.0;
nShift--;
}
return dDiff * POBH_FACTOR;
}
UniValue blockheaderToJSON(const CBlockIndex* blockindex)
{
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex()));
int confirmations = -1;
// Only report confirmations if the block is on the main chain
if (chainActive.Contains(blockindex))
confirmations = chainActive.Height() - blockindex->nHeight + 1;
result.push_back(Pair("confirmations", confirmations));
result.push_back(Pair("height", blockindex->nHeight));
result.push_back(Pair("version", blockindex->nVersion));
result.push_back(Pair("versionHex", strprintf("%08x", blockindex->nVersion)));
result.push_back(Pair("merkleroot", blockindex->hashMerkleRoot.GetHex()));
result.push_back(Pair("time", (int64_t)blockindex->nTime));
result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast()));
result.push_back(Pair("nonce", (uint64_t)blockindex->nNonce));
result.push_back(Pair("bits", strprintf("%08x", blockindex->nBits)));
result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex()));
if (blockindex->pprev)
result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
CBlockIndex *pnext = chainActive.Next(blockindex);
if (pnext)
result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex()));
return result;
}
UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails = false)
{
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex()));
int confirmations = -1;
// Only report confirmations if the block is on the main chain
if (chainActive.Contains(blockindex))
confirmations = chainActive.Height() - blockindex->nHeight + 1;
result.push_back(Pair("confirmations", confirmations));
result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
result.push_back(Pair("height", blockindex->nHeight));
result.push_back(Pair("version", block.nVersion));
result.push_back(Pair("versionHex", strprintf("%08x", block.nVersion)));
result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
UniValue txs(UniValue::VARR);
for(const auto& tx : block.vtx)
{
if(txDetails)
{
UniValue objTx(UniValue::VOBJ);
TxToJSON(*tx, uint256(), objTx);
txs.push_back(objTx);
}
else
txs.push_back(tx->GetHash().GetHex());
}
result.push_back(Pair("tx", txs));
if (!block.vtx[0]->vExtraPayload.empty()) {
CCbTx cbTx;
if (GetTxPayload(block.vtx[0]->vExtraPayload, cbTx)) {
UniValue cbTxObj;
cbTx.ToJson(cbTxObj);
result.push_back(Pair("cbTx", cbTxObj));
}
}
result.push_back(Pair("time", block.GetBlockTime()));
result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast()));
result.push_back(Pair("hrtime", TimestampToHRDate(block.GetBlockTime())));
result.push_back(Pair("nonce", (uint64_t)block.nNonce));
result.push_back(Pair("bits", strprintf("%08x", block.nBits)));
result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex()));
result.push_back(Pair("subsidy", block.vtx[0]->vout[0].nValue/COIN));
result.push_back(Pair("anti-botnet-weight", GetABNWeight(block, false)));
std::string sCPK;
CheckABNSignature(block, sCPK);
if (!sCPK.empty())
result.push_back(Pair("cpk", sCPK));
result.push_back(Pair("blockversion", GetBlockVersion(block.vtx[0]->vout[0].sTxOutMessage)));
if (block.vtx.size() > 1)
result.push_back(Pair("sanctuary_reward", block.vtx[0]->vout[1].nValue/COIN));
// BiblePay
bool bShowPrayers = true;
if (blockindex->pprev)
{
result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
const Consensus::Params& consensusParams = Params().GetConsensus();
std::string sVerses = GetBibleHashVerses(block.GetHash(), block.GetBlockTime(), blockindex->pprev->nTime, blockindex->pprev->nHeight, blockindex->pprev);
if (bShowPrayers) result.push_back(Pair("verses", sVerses));
// Check work against BibleHash
bool f7000;
bool f8000;
bool f9000;
bool fTitheBlocksActive;
GetMiningParams(blockindex->pprev->nHeight, f7000, f8000, f9000, fTitheBlocksActive);
arith_uint256 hashTarget = arith_uint256().SetCompact(blockindex->nBits);
uint256 hashWork = blockindex->GetBlockHash();
uint256 bibleHash = BibleHashClassic(hashWork, block.GetBlockTime(), blockindex->pprev->nTime, false, blockindex->pprev->nHeight, blockindex->pprev, false, f7000, f8000, f9000, fTitheBlocksActive, blockindex->nNonce, consensusParams);
bool bSatisfiesBibleHash = (UintToArith256(bibleHash) <= hashTarget);
if (fDebugSpam)
result.push_back(Pair("satisfiesbiblehash", bSatisfiesBibleHash ? "true" : "false"));
result.push_back(Pair("biblehash", bibleHash.GetHex()));
result.push_back(Pair("chaindata", block.vtx[0]->vout[0].sTxOutMessage));
bool fEnabled = sporkManager.IsSporkActive(SPORK_30_QUANTITATIVE_TIGHTENING_ENABLED);
if (fEnabled)
{
double dPriorPrice = 0;
double dPriorPhase = 0;
double dQTPct = GetQTPhase(false, -1, blockindex->nHeight, dPriorPrice, dPriorPhase) / 100;
result.push_back(Pair("qt_pct", dQTPct));
}
}
CBlockIndex *pnext = chainActive.Next(blockindex);
if (pnext)
result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex()));
// Genesis Block only:
if (blockindex && blockindex->nHeight==0)
{
int iStart=0;
int iEnd=0;
// Display a verse from Genesis 1:1 for The Genesis Block:
GetBookStartEnd("gen", iStart, iEnd);
std::string sVerse = GetVerse("gen", 1, 1, iStart - 1, iEnd);
boost::trim(sVerse);
result.push_back(Pair("verses", sVerse));
}
return result;
}
UniValue getblockcount(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
"getblockcount\n"
"\nReturns the number of blocks in the longest blockchain.\n"
"\nResult:\n"
"n (numeric) The current block count\n"
"\nExamples:\n"
+ HelpExampleCli("getblockcount", "")
+ HelpExampleRpc("getblockcount", "")
);
LOCK(cs_main);
return chainActive.Height();
}
UniValue getbestblockhash(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
"getbestblockhash\n"
"\nReturns the hash of the best (tip) block in the longest blockchain.\n"
"\nResult:\n"
"\"hex\" (string) the block hash hex encoded\n"
"\nExamples:\n"
+ HelpExampleCli("getbestblockhash", "")
+ HelpExampleRpc("getbestblockhash", "")
);
LOCK(cs_main);
return chainActive.Tip()->GetBlockHash().GetHex();
}
void RPCNotifyBlockChange(bool ibd, const CBlockIndex * pindex)
{
if(pindex) {
std::lock_guard<std::mutex> lock(cs_blockchange);
latestblock.hash = pindex->GetBlockHash();
latestblock.height = pindex->nHeight;
}
cond_blockchange.notify_all();
}
UniValue waitfornewblock(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() > 1)
throw std::runtime_error(
"waitfornewblock (timeout)\n"
"\nWaits for a specific new block and returns useful info about it.\n"
"\nReturns the current block on timeout or exit.\n"
"\nArguments:\n"
"1. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n"
"\nResult:\n"
"{ (json object)\n"
" \"hash\" : { (string) The blockhash\n"
" \"height\" : { (int) Block height\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("waitfornewblock", "1000")
+ HelpExampleRpc("waitfornewblock", "1000")
);
int timeout = 0;
if (request.params.size() > 0)
timeout = request.params[0].get_int();
CUpdatedBlock block;
{
std::unique_lock<std::mutex> lock(cs_blockchange);
block = latestblock;
if(timeout)
cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&block]{return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); });
else
cond_blockchange.wait(lock, [&block]{return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); });
block = latestblock;
}
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("hash", block.hash.GetHex()));
ret.push_back(Pair("height", block.height));
return ret;
}
UniValue waitforblock(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw std::runtime_error(
"waitforblock <blockhash> (timeout)\n"
"\nWaits for a specific new block and returns useful info about it.\n"
"\nReturns the current block on timeout or exit.\n"
"\nArguments:\n"
"1. \"blockhash\" (required, string) Block hash to wait for.\n"
"2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n"
"\nResult:\n"
"{ (json object)\n"
" \"hash\" : { (string) The blockhash\n"
" \"height\" : { (int) Block height\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
+ HelpExampleRpc("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
);
int timeout = 0;
uint256 hash = uint256S(request.params[0].get_str());
if (request.params.size() > 1)
timeout = request.params[1].get_int();
CUpdatedBlock block;
{
std::unique_lock<std::mutex> lock(cs_blockchange);
if(timeout)
cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&hash]{return latestblock.hash == hash || !IsRPCRunning();});
else
cond_blockchange.wait(lock, [&hash]{return latestblock.hash == hash || !IsRPCRunning(); });
block = latestblock;
}
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("hash", block.hash.GetHex()));
ret.push_back(Pair("height", block.height));
return ret;
}
UniValue waitforblockheight(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw std::runtime_error(
"waitforblockheight <height> (timeout)\n"
"\nWaits for (at least) block height and returns the height and hash\n"
"of the current tip.\n"
"\nReturns the current block on timeout or exit.\n"
"\nArguments:\n"
"1. height (required, int) Block height to wait for (int)\n"
"2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n"
"\nResult:\n"
"{ (json object)\n"
" \"hash\" : { (string) The blockhash\n"
" \"height\" : { (int) Block height\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("waitforblockheight", "\"100\", 1000")
+ HelpExampleRpc("waitforblockheight", "\"100\", 1000")
);
int timeout = 0;
int height = request.params[0].get_int();
if (request.params.size() > 1)
timeout = request.params[1].get_int();
CUpdatedBlock block;
{
std::unique_lock<std::mutex> lock(cs_blockchange);
if(timeout)
cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&height]{return latestblock.height >= height || !IsRPCRunning();});
else
cond_blockchange.wait(lock, [&height]{return latestblock.height >= height || !IsRPCRunning(); });
block = latestblock;
}
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("hash", block.hash.GetHex()));
ret.push_back(Pair("height", block.height));
return ret;
}
UniValue getdifficulty(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
"getdifficulty\n"
"\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
"\nResult:\n"
"n.nnn (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
"\nExamples:\n"
+ HelpExampleCli("getdifficulty", "")
+ HelpExampleRpc("getdifficulty", "")
);
LOCK(cs_main);
return GetDifficulty();
}
std::string EntryDescriptionString()
{
return " \"size\" : n, (numeric) transaction size in bytes\n"
" \"fee\" : n, (numeric) transaction fee in " + CURRENCY_UNIT + "\n"
" \"modifiedfee\" : n, (numeric) transaction fee with fee deltas used for mining priority\n"
" \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n"
" \"height\" : n, (numeric) block height when transaction entered pool\n"
" \"startingpriority\" : n, (numeric) DEPRECATED. Priority when transaction entered pool\n"
" \"currentpriority\" : n, (numeric) DEPRECATED. Transaction priority now\n"
" \"descendantcount\" : n, (numeric) number of in-mempool descendant transactions (including this one)\n"
" \"descendantsize\" : n, (numeric) size of in-mempool descendants (including this one)\n"
" \"descendantfees\" : n, (numeric) modified fees (see above) of in-mempool descendants (including this one)\n"
" \"ancestorcount\" : n, (numeric) number of in-mempool ancestor transactions (including this one)\n"
" \"ancestorsize\" : n, (numeric) size of in-mempool ancestors (including this one)\n"
" \"ancestorfees\" : n, (numeric) modified fees (see above) of in-mempool ancestors (including this one)\n"
" \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n"
" \"transactionid\", (string) parent transaction id\n"
" ... ],\n"
" \"instantsend\" : true|false, (boolean) True if this transaction was sent as an InstantSend one\n"
" \"instantlock\" : true|false (boolean) True if this transaction was locked via InstantSend\n";
}
void entryToJSON(UniValue &info, const CTxMemPoolEntry &e)
{
AssertLockHeld(mempool.cs);
info.push_back(Pair("size", (int)e.GetTxSize()));
info.push_back(Pair("fee", ValueFromAmount(e.GetFee())));
info.push_back(Pair("modifiedfee", ValueFromAmount(e.GetModifiedFee())));
info.push_back(Pair("time", e.GetTime()));
info.push_back(Pair("height", (int)e.GetHeight()));
info.push_back(Pair("descendantcount", e.GetCountWithDescendants()));
info.push_back(Pair("descendantsize", e.GetSizeWithDescendants()));
info.push_back(Pair("descendantfees", e.GetModFeesWithDescendants()));
info.push_back(Pair("ancestorcount", e.GetCountWithAncestors()));
info.push_back(Pair("ancestorsize", e.GetSizeWithAncestors()));
info.push_back(Pair("ancestorfees", e.GetModFeesWithAncestors()));
const CTransaction& tx = e.GetTx();
std::set<std::string> setDepends;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
if (mempool.exists(txin.prevout.hash))
setDepends.insert(txin.prevout.hash.ToString());
}
UniValue depends(UniValue::VARR);
BOOST_FOREACH(const std::string& dep, setDepends)
{
depends.push_back(dep);
}
info.push_back(Pair("depends", depends));
info.push_back(Pair("instantsend", instantsend.HasTxLockRequest(tx.GetHash())));
info.push_back(Pair("instantlock", instantsend.IsLockedInstantSendTransaction(tx.GetHash())));
}
UniValue mempoolToJSON(bool fVerbose = false)
{
if (fVerbose)
{
LOCK(mempool.cs);
UniValue o(UniValue::VOBJ);
BOOST_FOREACH(const CTxMemPoolEntry& e, mempool.mapTx)
{
const uint256& hash = e.GetTx().GetHash();
UniValue info(UniValue::VOBJ);
entryToJSON(info, e);
o.push_back(Pair(hash.ToString(), info));
}
return o;
}
else
{
std::vector<uint256> vtxid;
mempool.queryHashes(vtxid);
UniValue a(UniValue::VARR);
BOOST_FOREACH(const uint256& hash, vtxid)
a.push_back(hash.ToString());
return a;
}
}
UniValue getrawmempool(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() > 1)
throw std::runtime_error(
"getrawmempool ( verbose )\n"
"\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n"
"\nHint: use getmempoolentry to fetch a specific transaction from the mempool.\n"
"\nArguments:\n"
"1. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n"
"\nResult: (for verbose = false):\n"
"[ (json array of string)\n"
" \"transactionid\" (string) The transaction id\n"
" ,...\n"
"]\n"
"\nResult: (for verbose = true):\n"
"{ (json object)\n"
" \"transactionid\" : { (json object)\n"
+ EntryDescriptionString()
+ " }, ...\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getrawmempool", "true")
+ HelpExampleRpc("getrawmempool", "true")
);
bool fVerbose = false;
if (request.params.size() > 0)
fVerbose = request.params[0].get_bool();
return mempoolToJSON(fVerbose);
}
UniValue getmempoolancestors(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
throw std::runtime_error(
"getmempoolancestors txid (verbose)\n"
"\nIf txid is in the mempool, returns all in-mempool ancestors.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id (must be in mempool)\n"
"2. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n"
"\nResult (for verbose=false):\n"
"[ (json array of strings)\n"
" \"transactionid\" (string) The transaction id of an in-mempool ancestor transaction\n"
" ,...\n"
"]\n"
"\nResult (for verbose=true):\n"
"{ (json object)\n"
" \"transactionid\" : { (json object)\n"
+ EntryDescriptionString()
+ " }, ...\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getmempoolancestors", "\"mytxid\"")
+ HelpExampleRpc("getmempoolancestors", "\"mytxid\"")
);
}
bool fVerbose = false;
if (request.params.size() > 1)
fVerbose = request.params[1].get_bool();
uint256 hash = ParseHashV(request.params[0], "parameter 1");
LOCK(mempool.cs);
CTxMemPool::txiter it = mempool.mapTx.find(hash);
if (it == mempool.mapTx.end()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
}
CTxMemPool::setEntries setAncestors;
uint64_t noLimit = std::numeric_limits<uint64_t>::max();
std::string dummy;
mempool.CalculateMemPoolAncestors(*it, setAncestors, noLimit, noLimit, noLimit, noLimit, dummy, false);
if (!fVerbose) {
UniValue o(UniValue::VARR);
BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors) {
o.push_back(ancestorIt->GetTx().GetHash().ToString());
}
return o;
} else {
UniValue o(UniValue::VOBJ);
BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors) {
const CTxMemPoolEntry &e = *ancestorIt;
const uint256& _hash = e.GetTx().GetHash();
UniValue info(UniValue::VOBJ);
entryToJSON(info, e);
o.push_back(Pair(_hash.ToString(), info));
}
return o;
}
}
UniValue getmempooldescendants(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
throw std::runtime_error(
"getmempooldescendants txid (verbose)\n"
"\nIf txid is in the mempool, returns all in-mempool descendants.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id (must be in mempool)\n"
"2. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n"
"\nResult (for verbose=false):\n"
"[ (json array of strings)\n"
" \"transactionid\" (string) The transaction id of an in-mempool descendant transaction\n"
" ,...\n"
"]\n"
"\nResult (for verbose=true):\n"
"{ (json object)\n"
" \"transactionid\" : { (json object)\n"
+ EntryDescriptionString()
+ " }, ...\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getmempooldescendants", "\"mytxid\"")
+ HelpExampleRpc("getmempooldescendants", "\"mytxid\"")
);
}
bool fVerbose = false;
if (request.params.size() > 1)
fVerbose = request.params[1].get_bool();
uint256 hash = ParseHashV(request.params[0], "parameter 1");
LOCK(mempool.cs);
CTxMemPool::txiter it = mempool.mapTx.find(hash);
if (it == mempool.mapTx.end()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
}
CTxMemPool::setEntries setDescendants;
mempool.CalculateDescendants(it, setDescendants);
// CTxMemPool::CalculateDescendants will include the given tx
setDescendants.erase(it);
if (!fVerbose) {
UniValue o(UniValue::VARR);
BOOST_FOREACH(CTxMemPool::txiter descendantIt, setDescendants) {
o.push_back(descendantIt->GetTx().GetHash().ToString());
}
return o;
} else {
UniValue o(UniValue::VOBJ);
BOOST_FOREACH(CTxMemPool::txiter descendantIt, setDescendants) {
const CTxMemPoolEntry &e = *descendantIt;
const uint256& _hash = e.GetTx().GetHash();
UniValue info(UniValue::VOBJ);
entryToJSON(info, e);
o.push_back(Pair(_hash.ToString(), info));
}
return o;
}
}
UniValue getmempoolentry(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1) {
throw std::runtime_error(
"getmempoolentry txid\n"
"\nReturns mempool data for given transaction\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id (must be in mempool)\n"
"\nResult:\n"
"{ (json object)\n"
+ EntryDescriptionString()
+ "}\n"
"\nExamples:\n"
+ HelpExampleCli("getmempoolentry", "\"mytxid\"")
+ HelpExampleRpc("getmempoolentry", "\"mytxid\"")
);
}
uint256 hash = ParseHashV(request.params[0], "parameter 1");
LOCK(mempool.cs);
CTxMemPool::txiter it = mempool.mapTx.find(hash);
if (it == mempool.mapTx.end()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
}
const CTxMemPoolEntry &e = *it;
UniValue info(UniValue::VOBJ);
entryToJSON(info, e);
return info;
}
UniValue getblockhashes(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 2)
throw std::runtime_error(
"getblockhashes timestamp\n"
"\nReturns array of hashes of blocks within the timestamp range provided.\n"
"\nArguments:\n"
"1. high (numeric, required) The newer block timestamp\n"
"2. low (numeric, required) The older block timestamp\n"
"\nResult:\n"
"[\n"
" \"hash\" (string) The block hash\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getblockhashes", "1231614698 1231024505")
+ HelpExampleRpc("getblockhashes", "1231614698, 1231024505")
);
unsigned int high = request.params[0].get_int();
unsigned int low = request.params[1].get_int();
std::vector<uint256> blockHashes;
if (!GetTimestampIndex(high, low, blockHashes)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for block hashes");
}
UniValue result(UniValue::VARR);
for (std::vector<uint256>::const_iterator it=blockHashes.begin(); it!=blockHashes.end(); it++) {
result.push_back(it->GetHex());
}
return result;
}
UniValue getblockhash(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"getblockhash height\n"
"\nReturns hash of block in best-block-chain at height provided.\n"
"\nArguments:\n"
"1. height (numeric, required) The height index\n"
"\nResult:\n"
"\"hash\" (string) The block hash\n"
"\nExamples:\n"
+ HelpExampleCli("getblockhash", "1000")
+ HelpExampleRpc("getblockhash", "1000")
);
LOCK(cs_main);
int nHeight = request.params[0].get_int();
if (nHeight < 0 || nHeight > chainActive.Height())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
CBlockIndex* pblockindex = chainActive[nHeight];
return pblockindex->GetBlockHash().GetHex();
}
UniValue getblockheader(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw std::runtime_error(
"getblockheader \"hash\" ( verbose )\n"
"\nIf verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n"
"If verbose is true, returns an Object with information about blockheader <hash>.\n"
"\nArguments:\n"
"1. \"hash\" (string, required) The block hash\n"
"2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n"
"\nResult (for verbose = true):\n"
"{\n"
" \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
" \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
" \"height\" : n, (numeric) The block height or index\n"
" \"version\" : n, (numeric) The block version\n"
" \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n"
" \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
" \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"nonce\" : n, (numeric) The nonce\n"
" \"bits\" : \"1d00ffff\", (string) The bits\n"
" \"difficulty\" : x.xxx, (numeric) The difficulty\n"
" \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n"
" \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
" \"nextblockhash\" : \"hash\", (string) The hash of the next block\n"
"}\n"
"\nResult (for verbose=false):\n"
"\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
"\nExamples:\n"
+ HelpExampleCli("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
+ HelpExampleRpc("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
);
LOCK(cs_main);
std::string strHash = request.params[0].get_str();
uint256 hash(uint256S(strHash));
bool fVerbose = true;
if (request.params.size() > 1)
fVerbose = request.params[1].get_bool();
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlockIndex* pblockindex = mapBlockIndex[hash];
if (!fVerbose)
{
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
ssBlock << pblockindex->GetBlockHeader();
std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
return strHex;
}
return blockheaderToJSON(pblockindex);
}
UniValue getblockheaders(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 3)
throw std::runtime_error(
"getblockheaders \"hash\" ( count verbose )\n"
"\nReturns an array of items with information about <count> blockheaders starting from <hash>.\n"
"\nIf verbose is false, each item is a string that is serialized, hex-encoded data for a single blockheader.\n"
"If verbose is true, each item is an Object with information about a single blockheader.\n"
"\nArguments:\n"
"1. \"hash\" (string, required) The block hash\n"
"2. count (numeric, optional, default/max=" + strprintf("%s", MAX_HEADERS_RESULTS) +")\n"
"3. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n"
"\nResult (for verbose = true):\n"
"[ {\n"
" \"hash\" : \"hash\", (string) The block hash\n"
" \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
" \"height\" : n, (numeric) The block height or index\n"
" \"version\" : n, (numeric) The block version\n"
" \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
" \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"nonce\" : n, (numeric) The nonce\n"
" \"bits\" : \"1d00ffff\", (string) The bits\n"
" \"difficulty\" : x.xxx, (numeric) The difficulty\n"
" \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n"
" \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
" \"nextblockhash\" : \"hash\", (string) The hash of the next block\n"
"}, {\n"
" ...\n"
" },\n"
"...\n"
"]\n"
"\nResult (for verbose=false):\n"
"[\n"
" \"data\", (string) A string that is serialized, hex-encoded data for block header.\n"
" ...\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getblockheaders", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 2000")
+ HelpExampleRpc("getblockheaders", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 2000")
);
LOCK(cs_main);
std::string strHash = request.params[0].get_str();
uint256 hash(uint256S(strHash));
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
int nCount = MAX_HEADERS_RESULTS;
if (request.params.size() > 1)
nCount = request.params[1].get_int();
if (nCount <= 0 || nCount > (int)MAX_HEADERS_RESULTS)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Count is out of range");
bool fVerbose = true;
if (request.params.size() > 2)
fVerbose = request.params[2].get_bool();
CBlockIndex* pblockindex = mapBlockIndex[hash];
UniValue arrHeaders(UniValue::VARR);
if (!fVerbose)
{
for (; pblockindex; pblockindex = chainActive.Next(pblockindex))
{
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
ssBlock << pblockindex->GetBlockHeader();
std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
arrHeaders.push_back(strHex);
if (--nCount <= 0)
break;
}
return arrHeaders;
}
for (; pblockindex; pblockindex = chainActive.Next(pblockindex))
{
arrHeaders.push_back(blockheaderToJSON(pblockindex));
if (--nCount <= 0)
break;
}
return arrHeaders;
}
UniValue getblock(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw std::runtime_error(
"getblock \"blockhash\" ( verbosity ) \n"
"\nIf verbosity is 0, returns a string that is serialized, hex-encoded data for block 'hash'.\n"
"If verbosity is 1, returns an Object with information about block <hash>.\n"
"If verbosity is 2, returns an Object with information about block <hash> and information about each transaction. \n"
"\nArguments:\n"
"1. \"blockhash\" (string, required) The block hash\n"
"2. verbosity (numeric, optional, default=1) 0 for hex-encoded data, 1 for a json object, and 2 for json object with transaction data\n"
"\nResult (for verbosity = 0):\n"
"\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
"\nResult (for verbose = 1):\n"
"{\n"
" \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
" \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
" \"size\" : n, (numeric) The block size\n"
" \"height\" : n, (numeric) The block height or index\n"
" \"version\" : n, (numeric) The block version\n"
" \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n"
" \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
" \"tx\" : [ (array of string) The transaction ids\n"
" \"transactionid\" (string) The transaction id\n"
" ,...\n"
" ],\n"
" \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"nonce\" : n, (numeric) The nonce\n"
" \"bits\" : \"1d00ffff\", (string) The bits\n"
" \"difficulty\" : x.xxx, (numeric) The difficulty\n"
" \"chainwork\" : \"xxxx\", (string) Expected number of hashes required to produce the chain up to this block (in hex)\n"
" \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
" \"nextblockhash\" : \"hash\" (string) The hash of the next block\n"
"}\n"
"\nResult (for verbosity = 2):\n"
"{\n"
" ..., Same output as verbosity = 1.\n"
" \"tx\" : [ (array of Objects) The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 \"tx\" result.\n"
" ,...\n"
" ],\n"
" ,... Same output as verbosity = 1.\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getblock", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"")
+ HelpExampleRpc("getblock", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"")
);
LOCK(cs_main);
std::string strHash = request.params[0].get_str();
uint256 hash(uint256S(strHash));
int verbosity = 1;
if (request.params.size() > 1) {
if(request.params[1].isNum())
verbosity = request.params[1].get_int();
else
verbosity = request.params[1].get_bool() ? 1 : 0;
}
int NUMBER_LENGTH_NON_HASH = 10;
if (strHash.length() < NUMBER_LENGTH_NON_HASH && !strHash.empty())
{
CBlockIndex* bindex = FindBlockByHeight(cdbl(strHash, 0));
if (bindex==NULL)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found by height");
hash = bindex->GetBlockHash();
}
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hash];
if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0)
throw JSONRPCError(RPC_INTERNAL_ERROR, "Block not available (pruned data)");
if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus()))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
if (verbosity <= 0)
{
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
ssBlock << block;
std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
return strHex;
}
return blockToJSON(block, pblockindex, verbosity >= 2);
}
struct CCoinsStats
{
int nHeight;
uint256 hashBlock;
uint64_t nTransactions;
uint64_t nTransactionOutputs;
uint256 hashSerialized;
uint64_t nDiskSize;
CAmount nTotalAmount;
CCoinsStats() : nHeight(0), nTransactions(0), nTransactionOutputs(0), nTotalAmount(0) {}
};
static void ApplyStats(CCoinsStats &stats, CHashWriter& ss, const uint256& hash, const std::map<uint32_t, Coin>& outputs)
{
assert(!outputs.empty());
ss << hash;
ss << VARINT(outputs.begin()->second.nHeight * 2 + outputs.begin()->second.fCoinBase);
stats.nTransactions++;
for (const auto output : outputs) {
ss << VARINT(output.first + 1);
ss << *(const CScriptBase*)(&output.second.out.scriptPubKey);
ss << VARINT(output.second.out.nValue);
stats.nTransactionOutputs++;
stats.nTotalAmount += output.second.out.nValue;
}
ss << VARINT(0);
}
//! Calculate statistics about the unspent transaction output set
static bool GetUTXOStats(CCoinsView *view, CCoinsStats &stats)
{
std::unique_ptr<CCoinsViewCursor> pcursor(view->Cursor());
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
stats.hashBlock = pcursor->GetBestBlock();
{
LOCK(cs_main);
stats.nHeight = mapBlockIndex.find(stats.hashBlock)->second->nHeight;
}
ss << stats.hashBlock;
uint256 prevkey;
std::map<uint32_t, Coin> outputs;
while (pcursor->Valid()) {
boost::this_thread::interruption_point();
COutPoint key;
Coin coin;
if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {
if (!outputs.empty() && key.hash != prevkey) {
ApplyStats(stats, ss, prevkey, outputs);
outputs.clear();
}
prevkey = key.hash;
outputs[key.n] = std::move(coin);
} else {
return error("%s: unable to read value", __func__);
}
pcursor->Next();
}
if (!outputs.empty()) {
ApplyStats(stats, ss, prevkey, outputs);
}
stats.hashSerialized = ss.GetHash();
stats.nDiskSize = view->EstimateSize();
return true;
}
UniValue pruneblockchain(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"pruneblockchain\n"
"\nArguments:\n"
"1. \"height\" (numeric, required) The block height to prune up to. May be set to a discrete height, or a unix timestamp\n"
" to prune blocks whose block time is at least 2 hours older than the provided timestamp.\n"
"\nResult:\n"
"n (numeric) Height of the last block pruned.\n"
"\nExamples:\n"
+ HelpExampleCli("pruneblockchain", "1000")
+ HelpExampleRpc("pruneblockchain", "1000"));
if (!fPruneMode)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Cannot prune blocks because node is not in prune mode.");
LOCK(cs_main);
int heightParam = request.params[0].get_int();
if (heightParam < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative block height.");
// Height value more than a billion is too high to be a block height, and
// too low to be a block time (corresponds to timestamp from Sep 2001).
if (heightParam > 1000000000) {
// Add a 2 hour buffer to include blocks which might have had old timestamps
CBlockIndex* pindex = chainActive.FindEarliestAtLeast(heightParam - 7200);
if (!pindex) {
throw JSONRPCError(RPC_INTERNAL_ERROR, "Could not find block with at least the specified timestamp.");
}
heightParam = pindex->nHeight;
}
unsigned int height = (unsigned int) heightParam;
unsigned int chainHeight = (unsigned int) chainActive.Height();
if (chainHeight < Params().PruneAfterHeight())
throw JSONRPCError(RPC_INTERNAL_ERROR, "Blockchain is too short for pruning.");
else if (height > chainHeight)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Blockchain is shorter than the attempted prune height.");
else if (height > chainHeight - MIN_BLOCKS_TO_KEEP) {
LogPrint("rpc", "Attempt to prune blocks close to the tip. Retaining the minimum number of blocks.");
height = chainHeight - MIN_BLOCKS_TO_KEEP;
}
PruneBlockFilesManual(height);
return uint64_t(height);
}
UniValue gettxoutsetinfo(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
"gettxoutsetinfo\n"
"\nReturns statistics about the unspent transaction output set.\n"
"Note this call may take some time.\n"
"\nResult:\n"
"{\n"
" \"height\":n, (numeric) The current block height (index)\n"
" \"bestblock\": \"hex\", (string) the best block hash hex\n"
" \"transactions\": n, (numeric) The number of transactions\n"
" \"txouts\": n, (numeric) The number of unspent transaction outputs\n"
" \"hash_serialized\": \"hash\", (string) The serialized hash\n"
" \"disk_size\": n, (numeric) The estimated size of the chainstate on disk\n"
" \"total_amount\": x.xxx (numeric) The total amount\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("gettxoutsetinfo", "")
+ HelpExampleRpc("gettxoutsetinfo", "")
);
UniValue ret(UniValue::VOBJ);
CCoinsStats stats;
FlushStateToDisk();
if (GetUTXOStats(pcoinsdbview, stats)) {
ret.push_back(Pair("height", (int64_t)stats.nHeight));
ret.push_back(Pair("bestblock", stats.hashBlock.GetHex()));
ret.push_back(Pair("transactions", (int64_t)stats.nTransactions));
ret.push_back(Pair("txouts", (int64_t)stats.nTransactionOutputs));
ret.push_back(Pair("hash_serialized_2", stats.hashSerialized.GetHex()));
ret.push_back(Pair("disk_size", stats.nDiskSize));
ret.push_back(Pair("total_amount", ValueFromAmount(stats.nTotalAmount)));
} else {
throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to read UTXO set");
}
return ret;
}
UniValue gettxout(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 2 || request.params.size() > 3)
throw std::runtime_error(
"gettxout \"txid\" n ( include_mempool )\n"
"\nReturns details about an unspent transaction output.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"2. n (numeric, required) vout number\n"
"3. include_mempool (boolean, optional) Whether to include the mempool\n"
"\nResult:\n"
"{\n"
" \"bestblock\" : \"hash\", (string) the block hash\n"
" \"confirmations\" : n, (numeric) The number of confirmations\n"
" \"value\" : x.xxx, (numeric) The transaction value in " + CURRENCY_UNIT + "\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"code\", (string) \n"
" \"hex\" : \"hex\", (string) \n"
" \"reqSigs\" : n, (numeric) Number of required signatures\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n"
" \"addresses\" : [ (array of string) array of biblepay addresses\n"
" \"address\" (string) biblepay address\n"
" ,...\n"
" ]\n"
" },\n"
" \"version\" : n, (numeric) The version\n"
" \"coinbase\" : true|false (boolean) Coinbase or not\n"
"}\n"
"\nExamples:\n"
"\nGet unspent transactions\n"
+ HelpExampleCli("listunspent", "") +
"\nView the details\n"
+ HelpExampleCli("gettxout", "\"txid\" 1") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("gettxout", "\"txid\", 1")
);
LOCK(cs_main);
UniValue ret(UniValue::VOBJ);
std::string strHash = request.params[0].get_str();
uint256 hash(uint256S(strHash));
int n = request.params[1].get_int();
COutPoint out(hash, n);
bool fMempool = true;
if (request.params.size() > 2)
fMempool = request.params[2].get_bool();
Coin coin;
if (fMempool) {
LOCK(mempool.cs);
CCoinsViewMemPool view(pcoinsTip, mempool);
if (!view.GetCoin(out, coin) || mempool.isSpent(out)) { // TODO: filtering spent coins should be done by the CCoinsViewMemPool
return NullUniValue;
}
} else {
if (!pcoinsTip->GetCoin(out, coin)) {
return NullUniValue;
}
}
BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
CBlockIndex *pindex = it->second;
ret.push_back(Pair("bestblock", pindex->GetBlockHash().GetHex()));
if (coin.nHeight == MEMPOOL_HEIGHT) {
ret.push_back(Pair("confirmations", 0));
} else {
ret.push_back(Pair("confirmations", (int64_t)(pindex->nHeight - coin.nHeight + 1)));
}
ret.push_back(Pair("value", ValueFromAmount(coin.out.nValue)));
UniValue o(UniValue::VOBJ);
ScriptPubKeyToJSON(coin.out.scriptPubKey, o, true);
ret.push_back(Pair("scriptPubKey", o));
ret.push_back(Pair("coinbase", (bool)coin.fCoinBase));
return ret;
}
UniValue verifychain(const JSONRPCRequest& request)
{
int nCheckLevel = GetArg("-checklevel", DEFAULT_CHECKLEVEL);
int nCheckDepth = GetArg("-checkblocks", DEFAULT_CHECKBLOCKS);
if (request.fHelp || request.params.size() > 2)
throw std::runtime_error(
"verifychain ( checklevel nblocks )\n"
"\nVerifies blockchain database.\n"
"\nArguments:\n"
"1. checklevel (numeric, optional, 0-4, default=" + strprintf("%d", nCheckLevel) + ") How thorough the block verification is.\n"
"2. nblocks (numeric, optional, default=" + strprintf("%d", nCheckDepth) + ", 0=all) The number of blocks to check.\n"
"\nResult:\n"
"true|false (boolean) Verified or not\n"
"\nExamples:\n"
+ HelpExampleCli("verifychain", "")
+ HelpExampleRpc("verifychain", "")
);
LOCK(cs_main);
if (request.params.size() > 0)
nCheckLevel = request.params[0].get_int();
if (request.params.size() > 1)
nCheckDepth = request.params[1].get_int();
return CVerifyDB().VerifyDB(Params(), pcoinsTip, nCheckLevel, nCheckDepth);
}
/** Implementation of IsSuperMajority with better feedback */
static UniValue SoftForkMajorityDesc(int version, CBlockIndex* pindex, const Consensus::Params& consensusParams)
{
UniValue rv(UniValue::VOBJ);
bool activated = false;
switch(version)
{
case 2:
activated = pindex->nHeight >= consensusParams.BIP34Height;
break;
case 3:
activated = pindex->nHeight >= consensusParams.BIP66Height;
break;
case 4:
activated = pindex->nHeight >= consensusParams.BIP65Height;
break;
}
rv.push_back(Pair("status", activated));
return rv;
}
static UniValue SoftForkDesc(const std::string &name, int version, CBlockIndex* pindex, const Consensus::Params& consensusParams)
{
UniValue rv(UniValue::VOBJ);
rv.push_back(Pair("id", name));
rv.push_back(Pair("version", version));
rv.push_back(Pair("reject", SoftForkMajorityDesc(version, pindex, consensusParams)));
return rv;
}
static UniValue BIP9SoftForkDesc(const Consensus::Params& consensusParams, Consensus::DeploymentPos id)
{
UniValue rv(UniValue::VOBJ);
const ThresholdState thresholdState = VersionBitsTipState(consensusParams, id);
switch (thresholdState) {
case THRESHOLD_DEFINED: rv.push_back(Pair("status", "defined")); break;
case THRESHOLD_STARTED: rv.push_back(Pair("status", "started")); break;
case THRESHOLD_LOCKED_IN: rv.push_back(Pair("status", "locked_in")); break;
case THRESHOLD_ACTIVE: rv.push_back(Pair("status", "active")); break;
case THRESHOLD_FAILED: rv.push_back(Pair("status", "failed")); break;
}
if (THRESHOLD_STARTED == thresholdState)
{
rv.push_back(Pair("bit", consensusParams.vDeployments[id].bit));
int nBlockCount = VersionBitsCountBlocksInWindow(chainActive.Tip(), consensusParams, id);
int64_t nPeriod = consensusParams.vDeployments[id].nWindowSize ? consensusParams.vDeployments[id].nWindowSize : consensusParams.nMinerConfirmationWindow;
int64_t nThreshold = consensusParams.vDeployments[id].nThreshold ? consensusParams.vDeployments[id].nThreshold : consensusParams.nRuleChangeActivationThreshold;
int64_t nWindowStart = chainActive.Height() - (chainActive.Height() % nPeriod);
rv.push_back(Pair("period", nPeriod));
rv.push_back(Pair("threshold", nThreshold));
rv.push_back(Pair("windowStart", nWindowStart));
rv.push_back(Pair("windowBlocks", nBlockCount));
rv.push_back(Pair("windowProgress", std::min(1.0, (double)nBlockCount / nThreshold)));
}
rv.push_back(Pair("startTime", consensusParams.vDeployments[id].nStartTime));
rv.push_back(Pair("timeout", consensusParams.vDeployments[id].nTimeout));
rv.push_back(Pair("since", VersionBitsTipStateSinceHeight(consensusParams, id)));
return rv;
}
void BIP9SoftForkDescPushBack(UniValue& bip9_softforks, const std::string &name, const Consensus::Params& consensusParams, Consensus::DeploymentPos id)
{
// Deployments with timeout value of 0 are hidden.
// A timeout value of 0 guarantees a softfork will never be activated.
// This is used when softfork codes are merged without specifying the deployment schedule.
if (consensusParams.vDeployments[id].nTimeout > 0)
bip9_softforks.push_back(Pair(name, BIP9SoftForkDesc(consensusParams, id)));
}
UniValue getblockchaininfo(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
"getblockchaininfo\n"
"Returns an object containing various state info regarding blockchain processing.\n"
"\nResult:\n"
"{\n"
" \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
" \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
" \"headers\": xxxxxx, (numeric) the current number of headers we have validated\n"
" \"bestblockhash\": \"...\", (string) the hash of the currently best block\n"
" \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
" \"mediantime\": xxxxxx, (numeric) median time for the current best block\n"
" \"verificationprogress\": xxxx, (numeric) estimate of verification progress [0..1]\n"
" \"chainwork\": \"xxxx\" (string) total amount of work in active chain, in hexadecimal\n"
" \"pruned\": xx, (boolean) if the blocks are subject to pruning\n"
" \"pruneheight\": xxxxxx, (numeric) lowest-height complete block stored\n"
" \"softforks\": [ (array) status of softforks in progress\n"
" {\n"
" \"id\": \"xxxx\", (string) name of softfork\n"
" \"version\": xx, (numeric) block version\n"
" \"reject\": { (object) progress toward rejecting pre-softfork blocks\n"
" \"status\": xx, (boolean) true if threshold reached\n"
" },\n"
" }, ...\n"
" ],\n"
" \"bip9_softforks\": { (object) status of BIP9 softforks in progress\n"
" \"xxxx\" : { (string) name of the softfork\n"
" \"status\": \"xxxx\", (string) one of \"defined\", \"started\", \"locked_in\", \"active\", \"failed\"\n"
" \"bit\": xx, (numeric) the bit (0-28) in the block version field used to signal this softfork (only for \"started\" status)\n"
" \"period\": xx, (numeric) the window size/period for this softfork (only for \"started\" status)\n"
" \"threshold\": xx, (numeric) the threshold for this softfork (only for \"started\" status)\n"
" \"windowStart\": xx, (numeric) the starting block height of the current window (only for \"started\" status)\n"
" \"windowBlocks\": xx, (numeric) the number of blocks in the current window that had the version bit set for this softfork (only for \"started\" status)\n"
" \"windowProgress\": xx, (numeric) the progress (between 0 and 1) for activation of this softfork (only for \"started\" status)\n"
" \"startTime\": xx, (numeric) the minimum median time past of a block at which the bit gains its meaning\n"
" \"timeout\": xx, (numeric) the median time past of a block at which the deployment is considered failed if not yet locked in\n"
" \"since\": xx (numeric) height of the first block to which the status applies\n"
" }\n"
" }\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getblockchaininfo", "")
+ HelpExampleRpc("getblockchaininfo", "")
);
LOCK(cs_main);
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("chain", Params().NetworkIDString()));
obj.push_back(Pair("blocks", (int)chainActive.Height()));
obj.push_back(Pair("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1));
obj.push_back(Pair("bestblockhash", chainActive.Tip()->GetBlockHash().GetHex()));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("mediantime", (int64_t)chainActive.Tip()->GetMedianTimePast()));
obj.push_back(Pair("verificationprogress", GuessVerificationProgress(Params().TxData(), chainActive.Tip())));
obj.push_back(Pair("chainwork", chainActive.Tip()->nChainWork.GetHex()));
obj.push_back(Pair("pruned", fPruneMode));
const Consensus::Params& consensusParams = Params().GetConsensus();
CBlockIndex* tip = chainActive.Tip();
UniValue softforks(UniValue::VARR);
UniValue bip9_softforks(UniValue::VOBJ);
softforks.push_back(SoftForkDesc("bip34", 2, tip, consensusParams));
softforks.push_back(SoftForkDesc("bip66", 3, tip, consensusParams));
softforks.push_back(SoftForkDesc("bip65", 4, tip, consensusParams));
bool fDIP0008Active = VersionBitsState(chainActive.Tip()->pprev, Params().GetConsensus(), Consensus::DEPLOYMENT_DIP0008, versionbitscache) == THRESHOLD_ACTIVE;
bool fChainLocksActive = sporkManager.IsSporkActive(SPORK_19_CHAINLOCKS_ENABLED);
obj.push_back(Pair("dip0008active", fDIP0008Active));
obj.push_back(Pair("chainlocks_active", fChainLocksActive));
/*
DEPLOYMENT_CSV is a blockchain vote to store the <median time past> int64_t unixtime in the block.tx.nLockTime field. Since the bitcoin behavior is to store the height, and we have pre-existing business logic that calculates height delta from this field, we don't want to switch to THRESHOLD_ACTIVE here. Additionally, BiblePay enforces the allowable mining window (for block timestamps) to be within a 15 minute range.
If we ever want to enable DEPLOYMENT_CSV, we need to change the chainparam deployment window to be the future, and check the POG business logic for height delta calculations.
BIP9SoftForkDescPushBack(bip9_softforks, "csv", consensusParams, Consensus::DEPLOYMENT_CSV);
DIP0001 is a vote to allow up to 2MB blocks. BiblePay moved to 2MB blocks before DIP1 and therefore our vote never started, but our code uses the 2MB hardcoded literal (matching dash). So we want to comment out this DIP1 versionbits response as it does not reflect our environment.
BIP9SoftForkDescPushBack(bip9_softforks, "csv", consensusParams, Consensus::DEPLOYMENT_CSV);
BIP9SoftForkDescPushBack(bip9_softforks, "dip0001", consensusParams, Consensus::DEPLOYMENT_DIP0001);
*/
BIP9SoftForkDescPushBack(bip9_softforks, "dip0003", consensusParams, Consensus::DEPLOYMENT_DIP0003);
BIP9SoftForkDescPushBack(bip9_softforks, "bip147", consensusParams, Consensus::DEPLOYMENT_BIP147);
obj.push_back(Pair("softforks", softforks));
obj.push_back(Pair("bip9_softforks", bip9_softforks));
if (fPruneMode)
{
CBlockIndex *block = chainActive.Tip();
while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA))
block = block->pprev;
obj.push_back(Pair("pruneheight", block->nHeight));
}
return obj;
}
UniValue getchaintips(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() > 4)
throw std::runtime_error(
"getchaintips ( count branchlen minimum_difficulty )\n"
"Return information about all known tips in the block tree,"
" including the main chain as well as orphaned branches.\n"
"\nArguments:\n"
"1. count (numeric, optional) only show this much of latest tips\n"
"2. branchlen (numeric, optional) only show tips that have equal or greater length of branch\n"
"3. minimum_diff(numeric, optional) only show tips that have equal or greater difficulty\n"
"4. minimum_branch_length(numeric, optional) only show tips that have equal or greater branch length\n"
"\nResult:\n"
"[\n"
" {\n"
" \"height\": xxxx, (numeric) height of the chain tip\n"
" \"hash\": \"xxxx\", (string) block hash of the tip\n"
" \"difficulty\" : x.xxx, (numeric) The difficulty\n"
" \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n"
" \"branchlen\": 0 (numeric) zero for main chain\n"
" \"status\": \"active\" (string) \"active\" for the main chain\n"
" },\n"
" {\n"
" \"height\": xxxx,\n"
" \"hash\": \"xxxx\",\n"
" \"difficulty\" : x.xxx,\n"
" \"chainwork\" : \"0000...1f3\"\n"
" \"branchlen\": 1 (numeric) length of branch connecting the tip to the main chain\n"
" \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n"
" }\n"
"]\n"
"Possible values for status:\n"
"1. \"invalid\" This branch contains at least one invalid block\n"
"2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n"
"3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n"
"4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n"
"5. \"active\" This is the tip of the active main chain, which is certainly valid\n"
"\nExamples:\n"
+ HelpExampleCli("getchaintips", "")
+ HelpExampleRpc("getchaintips", "")
);
LOCK(cs_main);
/* Build up a list of chain tips. We start with the list of all
known blocks, and successively remove blocks that appear as pprev
of another block. */
std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;
BOOST_FOREACH(const PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex)
{
if (item.second != NULL) setTips.insert(item.second);
}
BOOST_FOREACH(const PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex)
{
if (item.second != NULL)
{
if (item.second->pprev != NULL)
{
const CBlockIndex* pprev = item.second->pprev;
if (pprev) setTips.erase(pprev);
}
}
}
// Always report the currently active tip.
setTips.insert(chainActive.Tip());
int nBranchMin = -1;
int nCountMax = INT_MAX;
if(request.params.size() >= 1)
nCountMax = request.params[0].get_int();
if(request.params.size() == 2)
nBranchMin = request.params[1].get_int();
double nMinDiff = 0;
if (request.params.size() == 3)
nMinDiff = cdbl(request.params[2].get_str(), 4);
double nMinBranchLen = 0;
if (request.params.size() == 4)
nMinBranchLen = cdbl(request.params[3].get_str(), 0);
/* Construct the output array. */
UniValue res(UniValue::VARR);
BOOST_FOREACH(const CBlockIndex* block, setTips)
{
const CBlockIndex* pindexFork = chainActive.FindFork(block);
const int branchLen = block->nHeight - chainActive.FindFork(block)->nHeight;
if(branchLen < nBranchMin) continue;
if(nCountMax-- < 1) break;
UniValue obj(UniValue::VOBJ);
bool bInclude = true;
if (nMinDiff > 0 && GetDifficulty(block) < nMinDiff)
bInclude = false;
if (block->nHeight < (chainActive.Tip()->nHeight * .65))
bInclude = false;
if (nMinBranchLen > 0 && branchLen < nMinBranchLen)
bInclude = false;
if (bInclude)
{
obj.push_back(Pair("height", block->nHeight));
bool bSuperblock = (CSuperblock::IsValidBlockHeight(block->nHeight) || CSuperblock::IsSmartContract(block->nHeight));
obj.push_back(Pair("superblock", bSuperblock));
obj.push_back(Pair("hash", block->phashBlock->GetHex()));
obj.push_back(Pair("difficulty", GetDifficulty(block)));
obj.push_back(Pair("chainwork", block->nChainWork.GetHex()));
obj.push_back(Pair("branchlen", branchLen));
obj.push_back(Pair("forkpoint", pindexFork->phashBlock->GetHex()));
obj.push_back(Pair("forkheight", pindexFork->nHeight));
std::string status;
if (chainActive.Contains(block))
{
// This block is part of the currently active chain.
status = "active";
} else if (block->nStatus & BLOCK_FAILED_MASK) {
// This block or one of its ancestors is invalid.
status = "invalid";
} else if (block->nChainTx == 0) {
// This block cannot be connected because full block data for it or one of its parents is missing.
status = "headers-only";
} else if (block->IsValid(BLOCK_VALID_SCRIPTS)) {
// This block is fully validated, but no longer part of the active chain. It was probably the active block once, but was reorganized.
status = "valid-fork";
} else if (block->IsValid(BLOCK_VALID_TREE)) {
// The headers for this block are valid, but it has not been validated. It was probably never part of the most-work chain.
status = "valid-headers";
} else {
// No clue.
status = "unknown";
}
obj.push_back(Pair("status", status));
res.push_back(obj);
}
}
return res;
}
UniValue mempoolInfoToJSON()
{
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("size", (int64_t) mempool.size()));
ret.push_back(Pair("bytes", (int64_t) mempool.GetTotalTxSize()));
ret.push_back(Pair("usage", (int64_t) mempool.DynamicMemoryUsage()));
size_t maxmempool = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
ret.push_back(Pair("maxmempool", (int64_t) maxmempool));
ret.push_back(Pair("mempoolminfee", ValueFromAmount(mempool.GetMinFee(maxmempool).GetFeePerK())));
// ret.push_back(Pair("instantsendlocks", (int64_t)llmq::quorumInstantSendManager->GetInstantSendLockCount()));
return ret;
}
UniValue getmempoolinfo(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
"getmempoolinfo\n"
"\nReturns details on the active state of the TX memory pool.\n"
"\nResult:\n"
"{\n"
" \"size\": xxxxx, (numeric) Current tx count\n"
" \"bytes\": xxxxx, (numeric) Sum of all tx sizes\n"
" \"usage\": xxxxx, (numeric) Total memory usage for the mempool\n"
" \"maxmempool\": xxxxx, (numeric) Maximum memory usage for the mempool\n"
" \"mempoolminfee\": xxxxx (numeric) Minimum fee for tx to be accepted\n"
" \"instantsendlocks\": xxxxx, (numeric) Number of unconfirmed instant send locks\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getmempoolinfo", "")
+ HelpExampleRpc("getmempoolinfo", "")
);
return mempoolInfoToJSON();
}
UniValue preciousblock(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"preciousblock \"blockhash\"\n"
"\nTreats a block as if it were received before others with the same work.\n"
"\nA later preciousblock call can override the effect of an earlier one.\n"
"\nThe effects of preciousblock are not retained across restarts.\n"
"\nArguments:\n"
"1. \"blockhash\" (string, required) the hash of the block to mark as precious\n"
"\nResult:\n"
"\nExamples:\n"
+ HelpExampleCli("preciousblock", "\"blockhash\"")
+ HelpExampleRpc("preciousblock", "\"blockhash\"")
);
std::string strHash = request.params[0].get_str();
uint256 hash(uint256S(strHash));
CBlockIndex* pblockindex;
{
LOCK(cs_main);
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
pblockindex = mapBlockIndex[hash];
}
CValidationState state;
PreciousBlock(state, Params(), pblockindex);
if (!state.IsValid()) {
throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason());
}
return NullUniValue;
}
UniValue invalidateblock(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"invalidateblock \"blockhash\"\n"
"\nPermanently marks a block as invalid, as if it violated a consensus rule.\n"
"\nArguments:\n"
"1. \"blockhash\" (string, required) the hash of the block to mark as invalid\n"
"\nResult:\n"
"\nExamples:\n"
+ HelpExampleCli("invalidateblock", "\"blockhash\"")
+ HelpExampleRpc("invalidateblock", "\"blockhash\"")
);
std::string strHash = request.params[0].get_str();
uint256 hash(uint256S(strHash));
CValidationState state;
{
LOCK(cs_main);
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlockIndex* pblockindex = mapBlockIndex[hash];
InvalidateBlock(state, Params(), pblockindex);
}
if (state.IsValid()) {
ActivateBestChain(state, Params());
}
if (!state.IsValid()) {
throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason());
}
return NullUniValue;
}
uint256 Sha256001(int nType, int nVersion, std::string data)
{
CHash256 ctx;
unsigned char *val = new unsigned char[data.length()+1];
strcpy((char *)val, data.c_str());
ctx.Write(val, data.length()+1);
uint256 result;
ctx.Finalize((unsigned char*)&result);
return result;
}
std::string ScanSanctuaryConfigFile(std::string sName)
{
int linenumber = 1;
boost::filesystem::path pathMasternodeConfigFile = GetMasternodeConfigFile();
boost::filesystem::ifstream streamConfig(pathMasternodeConfigFile);
if (!streamConfig.good())
return std::string();
for(std::string line; std::getline(streamConfig, line); linenumber++)
{
if(line.empty()) continue;
std::istringstream iss(line);
std::string comment, alias, ip, privKey, txHash, outputIndex;
if (iss >> comment)
{
if(comment.at(0) == '#') continue;
iss.str(line);
iss.clear();
}
if (comment == sName)
{
streamConfig.close();
return line;
}
}
streamConfig.close();
return std::string();
}
std::string ScanDeterministicConfigFile(std::string sName)
{
int linenumber = 1;
boost::filesystem::path pathDeterministicFile = GetDeterministicConfigFile();
boost::filesystem::ifstream streamConfig(pathDeterministicFile);
if (!streamConfig.good())
return std::string();
//Format: Sanctuary_Name IP:port(40000=prod,40001=testnet) BLS_Public_Key BLS_Private_Key Collateral_output_txid Collateral_output_index Pro-Registration-TxId Pro-Reg-Collateral-Address Pro-Reg-Se$
for(std::string line; std::getline(streamConfig, line); linenumber++)
{
if(line.empty()) continue;
std::istringstream iss(line);
std::string sanctuary_name, ip, blsPubKey, BlsPrivKey, colOutputTxId, colOutputIndex, ProRegTxId, ProRegCollAddress, ProRegCollAddFundSentTxId;
if (iss >> sanctuary_name)
{
if(sanctuary_name.at(0) == '#') continue;
iss.str(line);
iss.clear();
}
if (sanctuary_name == sName)
{
streamConfig.close();
return line;
}
}
streamConfig.close();
return std::string();
}
boost::filesystem::path GetGenericFilePath(std::string sPath)
{
boost::filesystem::path pathConfigFile(sPath);
if (!pathConfigFile.is_complete())
pathConfigFile = GetDataDir() / pathConfigFile;
return pathConfigFile;
}
void AppendSanctuaryFile(std::string sFile, std::string sData)
{
boost::filesystem::path pathDeterministicConfigFile = GetGenericFilePath(sFile);
boost::filesystem::ifstream streamConfig(pathDeterministicConfigFile);
bool fReadable = streamConfig.good();
if (fReadable)
streamConfig.close();
FILE* configFile = fopen(pathDeterministicConfigFile.string().c_str(), "a");
if (configFile != nullptr)
{
if (!fReadable)
{
std::string strHeader = "# Deterministic Sanctuary Configuration File\n"
"# Format: Sanctuary_Name IP:port(40000=prod,40001=testnet) BLS_Public_Key BLS_Private_Key Collateral_output_txid Collateral_output_index Pro-Registration-TxId Pro-Reg-Collateral-Address Pro-Reg-Sent-TxId\n";
fwrite(strHeader.c_str(), std::strlen(strHeader.c_str()), 1, configFile);
}
}
fwrite(sData.c_str(), std::strlen(sData.c_str()), 1, configFile);
fclose(configFile);
}
void BoincHelpfulHint(UniValue& e)
{
e.push_back(Pair("Step 1", "Log into your WCG account at 'worldcommunitygrid.org' with your WCG E-mail address and WCG password."));
e.push_back(Pair("Step 2", "Click Settings | My Profile. Record your 'Username' and 'Verification Code' and your 'CPID' (Cross-Project-ID)."));
e.push_back(Pair("Step 3", "Click Settings | Data Sharing. Ensure the 'Display my Data' radio button is selected. Click Save. "));
e.push_back(Pair("Step 4", "Click My Contribution | My Team. If you are not part of Team 'BiblePay' click Join Team | Search | BiblePay | Select BiblePay | Click Join Team | Save."));
e.push_back(Pair("Step 5", "NOTE: After choosing your team, and starting your research, please give WCG 24 hours for the CPID to propagate into BBP. In the mean time you can start Boinc research - and ensure the computer is performing WCG tasks. "));
e.push_back(Pair("Step 6", "From our RPC console, type, exec associate your_username your_verification_code"));
e.push_back(Pair("Step 7", "Wait for 5 blocks to pass. Then type 'exec rac' again, and see if you are linked! "));
e.push_back(Pair("Step 8", "Once you are linked you will receive daily rewards. Please read about our minimum stake requirements per RAC here: wiki.biblepay.org/PODC"));
}
UniValue exec(const JSONRPCRequest& request)
{
if (request.fHelp || (request.params.size() != 1 && request.params.size() != 2 && request.params.size() != 3 && request.params.size() != 4
&& request.params.size() != 5 && request.params.size() != 6 && request.params.size() != 7))
throw std::runtime_error(
"exec <string::itemname> <string::parameter> \r\n"
"Executes an RPC command by name. run exec COMMAND for more info \r\n"
"Available Commands:\r\n"
);
std::string sItem = request.params[0].get_str();
if (sItem.empty()) throw std::runtime_error("Command argument invalid.");
UniValue results(UniValue::VOBJ);
results.push_back(Pair("Command",sItem));
if (sItem == "biblehash")
{
if (request.params.size() != 6)
throw std::runtime_error("You must specify blockhash, blocktime, prevblocktime, prevheight, and nonce IE: run biblehash blockhash 12345 12234 100 256.");
std::string sBlockHash = request.params[1].get_str();
std::string sBlockTime = request.params[2].get_str();
std::string sPrevBlockTime = request.params[3].get_str();
std::string sPrevHeight = request.params[4].get_str();
std::string sNonce = request.params[5].get_str();
int64_t nHeight = cdbl(sPrevHeight,0);
uint256 blockHash = uint256S("0x" + sBlockHash);
int64_t nBlockTime = (int64_t)cdbl(sBlockTime,0);
int64_t nPrevBlockTime = (int64_t)cdbl(sPrevBlockTime,0);
unsigned int nNonce = cdbl(sNonce,0);
if (!sBlockHash.empty() && nBlockTime > 0 && nPrevBlockTime > 0 && nHeight >= 0)
{
bool f7000;
bool f8000;
bool f9000;
bool fTitheBlocksActive;
const Consensus::Params& consensusParams = Params().GetConsensus();
GetMiningParams(nHeight, f7000, f8000, f9000, fTitheBlocksActive);
uint256 hash = BibleHashClassic(blockHash, nBlockTime, nPrevBlockTime, true, nHeight, NULL, false, f7000, f8000, f9000, fTitheBlocksActive, nNonce, consensusParams);
results.push_back(Pair("BibleHash",hash.GetHex()));
uint256 hash2 = BibleHashV2(blockHash, nBlockTime, nPrevBlockTime, true, nHeight);
results.push_back(Pair("BibleHashV2", hash2.GetHex()));
}
}
else if (sItem == "subsidy")
{
// Used by the Pools
if (request.params.size() != 2)
throw std::runtime_error("You must specify height.");
std::string sHeight = request.params[1].get_str();
int64_t nHeight = (int64_t)cdbl(sHeight,0);
if (nHeight >= 1 && nHeight <= chainActive.Tip()->nHeight)
{
CBlockIndex* pindex = FindBlockByHeight(nHeight);
const Consensus::Params& consensusParams = Params().GetConsensus();
if (pindex)
{
CBlock block;
if (ReadBlockFromDisk(block, pindex, consensusParams))
{
results.push_back(Pair("subsidy", block.vtx[0]->vout[0].nValue/COIN));
std::string sRecipient = PubKeyToAddress(block.vtx[0]->vout[0].scriptPubKey);
results.push_back(Pair("recipient", sRecipient));
results.push_back(Pair("blockversion", GetBlockVersion(block.vtx[0]->vout[0].sTxOutMessage)));
results.push_back(Pair("minerguid", ExtractXML(block.vtx[0]->vout[0].sTxOutMessage,"<MINERGUID>","</MINERGUID>")));
}
}
}
else
{
results.push_back(Pair("error","block not found"));
}
}
else if (sItem == "pinfo")
{
// Used by the Pools
results.push_back(Pair("height", chainActive.Tip()->nHeight));
int64_t nElapsed = GetAdjustedTime() - chainActive.Tip()->nTime;
int64_t nMN = nElapsed * 256;
if (nElapsed > (30 * 60))
nMN=999999999;
if (nMN < 512) nMN = 512;
results.push_back(Pair("pinfo", nMN));
results.push_back(Pair("elapsed", nElapsed));
}
else if (sItem == "poom_payments")
{
if (request.params.size() != 3)
throw std::runtime_error("You must specify poom_payments charity_name type [XML/Auto].");
std::string sCharity = request.params[1].get_str();
std::string sType = request.params[2].get_str();
std::string sDest = GetSporkValue(sCharity + "-RECEIVE-ADDRESS");
if (sDest.empty())
throw std::runtime_error("Unable to find charity " + sCharity);
std::string CP = SearchChain(BLOCKS_PER_DAY * 31, sDest);
int payment_id = 0;
if (sType == "XML")
{
results.push_back(Pair("payments", CP));
}
else
{
std::vector<std::string> vRows = Split(CP.c_str(), "<row>");
for (int i = 0; i < vRows.size(); i++)
{
std::string sCPK = ExtractXML(vRows[i], "<cpk>", "</cpk>");
std::string sChildID = ExtractXML(vRows[i], "<childid>", "</childid>");
std::string sAmount = ExtractXML(vRows[i], "<amount>", "</amount>");
std::string sUSD = ExtractXML(vRows[i], "<amount_usd>", "</amount_usd>");
std::string sBlock = ExtractXML(vRows[i], "<block>", "</block>");
std::string sTXID = ExtractXML(vRows[i], "<txid>", "</txid>");
if (!sChildID.empty())
{
payment_id++;
results.push_back(Pair("Payment #", payment_id));
results.push_back(Pair("CPK", sCPK));
results.push_back(Pair("childid", sChildID));
results.push_back(Pair("Amount", sAmount));
results.push_back(Pair("Amount_USD", sUSD));
results.push_back(Pair("Block #", sBlock));
results.push_back(Pair("TXID", sTXID));
}
}
}
}
else if (sItem == "versioncheck")
{
std::string sNarr = GetVersionAlert();
std::string sGithubVersion = GetGithubVersion();
std::string sCurrentVersion = FormatFullVersion();
results.push_back(Pair("Github_version", sGithubVersion));
results.push_back(Pair("Current_version", sCurrentVersion));
if (!sNarr.empty()) results.push_back(Pair("Alert", sNarr));
}
else if (sItem == "sins")
{
std::string sEntry = "";
int iSpecificEntry = 0;
UniValue aDataList = GetDataList("SIN", 7, iSpecificEntry, "", sEntry);
return aDataList;
}
else if (sItem == "reassesschains")
{
int iWorkDone = ReassessAllChains();
results.push_back(Pair("progress", iWorkDone));
}
else if (sItem == "autounlockpasswordlength")
{
results.push_back(Pair("Length", (double)msEncryptedString.size()));
}
else if (sItem == "readverse")
{
if (request.params.size() != 3 && request.params.size() != 4 && request.params.size() != 5)
throw std::runtime_error("You must specify Book and Chapter: IE 'readverse CO2 10'. \nOptionally you may enter the Language (EN/CN) IE 'readverse CO2 10 CN'. \nOptionally you may enter the VERSE #, IE: 'readverse CO2 10 EN 2'. To see a list of books: run getbooks.");
std::string sBook = request.params[1].get_str();
int iChapter = cdbl(request.params[2].get_str(),0);
int iVerse = 0;
if (request.params.size() > 3)
{
msLanguage = request.params[3].get_str();
}
if (request.params.size() > 4)
iVerse = cdbl(request.params[4].get_str(), 0);
if (request.params.size() == 4) iVerse = cdbl(request.params[3].get_str(), 0);
results.push_back(Pair("Book", sBook));
results.push_back(Pair("Chapter", iChapter));
results.push_back(Pair("Language", msLanguage));
if (iVerse > 0) results.push_back(Pair("Verse", iVerse));
int iStart = 0;
int iEnd = 0;
GetBookStartEnd(sBook, iStart, iEnd);
for (int i = iVerse; i < BIBLE_VERSE_COUNT; i++)
{
std::string sVerse = GetVerseML(msLanguage, sBook, iChapter, i, iStart - 1, iEnd);
if (iVerse > 0 && i > iVerse) break;
if (!sVerse.empty())
{
std::string sKey = sBook + " " + RoundToString(iChapter, 0) + ":" + RoundToString(i, 0);
results.push_back(Pair(sKey, sVerse));
}
}
}
else if (sItem == "dsql_select")
{
if (request.params.size() != 2)
throw std::runtime_error("You must specify dsql_select \"query\".");
std::string sSQL = request.params[1].get_str();
std::string sJson = DSQL_Ansi92Query(sSQL);
UniValue u(UniValue::VOBJ);
u.read(sJson);
std::string sSerialized = u.write().c_str();
results.push_back(Pair("dsql_query", sJson));
}
else if (sItem == "bipfs_file")
{
if (request.params.size() != 3)
throw std::runtime_error("You must specify exec bipfs_file path webpath. IE: exec bipfs_file armageddon.jpg mycpk/armageddon.jpg");
std::string sPath = request.params[1].get_str();
std::string sWebPath = request.params[2].get_str();
std::string sResponse = BIPFS_UploadSingleFile(sPath, sWebPath);
std::string sFee = ExtractXML(sResponse, "<FEE>", "</FEE>");
std::string sErrors = ExtractXML(sResponse, "<ERRORS>", "</ERRORS>");
std::string sSize = ExtractXML(sResponse, "<SIZE>", "</SIZE>");
results.push_back(Pair("Fee", sFee));
results.push_back(Pair("Size", sSize));
results.push_back(Pair("Errors", sErrors));
}
else if (sItem == "bipfs_folder")
{
if (request.params.size() != 3)
throw std::runtime_error("You must specify exec bipfs_folder path webpath. IE: exec bipfs_folder foldername mycpk/mywebpath");
std::string sDirPath = request.params[1].get_str();
std::string sWebPath = request.params[2].get_str();
std::vector<std::string> skipList;
std::vector<std::string> g = GetVectorOfFilesInDirectory(sDirPath, skipList);
for (auto sFileName : g)
{
results.push_back(Pair("Processing File", sFileName));
std::string sRelativeFileName = strReplace(sFileName, sDirPath, "");
std::string sFullWebPath = Path_Combine(sWebPath, sRelativeFileName);
std::string sFullSourcePath = Path_Combine(sDirPath, sFileName);
LogPrintf("Iterated Filename %s, RelativeFile %s, FullWebPath %s",
sFileName.c_str(), sRelativeFileName.c_str(), sFullWebPath.c_str());
std::string sResponse = BIPFS_UploadSingleFile(sFullSourcePath, sFullWebPath);
results.push_back(Pair("SourcePath", sFullSourcePath));
results.push_back(Pair("FileName", sFileName));
results.push_back(Pair("WebPath", sFullWebPath));
std::string sFee = ExtractXML(sResponse, "<FEE>", "</FEE>");
std::string sErrors = ExtractXML(sResponse, "<ERRORS>", "</ERRORS>");
std::string sSize = ExtractXML(sResponse, "<SIZE>", "</SIZE>");
std::string sHash = ExtractXML(sResponse, "<hash>", "</hash>");
results.push_back(Pair("Fee", sFee));
results.push_back(Pair("Size", sSize));
results.push_back(Pair("Hash", sHash));
results.push_back(Pair("Errors", sErrors));
}
}
else if (sItem == "testgscvote")
{
int iNextSuperblock = 0;
int iLastSuperblock = GetLastGSCSuperblockHeight(chainActive.Tip()->nHeight, iNextSuperblock);
std::string sContract = GetGSCContract(0, true); // As of iLastSuperblock height
results.push_back(Pair("end_height", iLastSuperblock));
results.push_back(Pair("contract", sContract));
std::string sAddresses;
std::string sAmounts;
int iVotes = 0;
uint256 uGovObjHash = uint256S("0x0");
uint256 uPAMHash = GetPAMHashByContract(sContract);
results.push_back(Pair("pam_hash", uPAMHash.GetHex()));
GetGSCGovObjByHeight(iNextSuperblock, uPAMHash, iVotes, uGovObjHash, sAddresses, sAmounts);
std::string sError;
results.push_back(Pair("govobjhash", uGovObjHash.GetHex()));
results.push_back(Pair("Addresses", sAddresses));
results.push_back(Pair("Amounts", sAmounts));
double dTotal = AddVector(sAmounts, "|");
results.push_back(Pair("Total_Target_Spend", dTotal));
if (uGovObjHash == uint256S("0x0"))
{
// create the contract
std::string sQuorumTrigger = SerializeSanctuaryQuorumTrigger(iLastSuperblock, iNextSuperblock, sContract);
std::string sGobjectHash;
SubmitGSCTrigger(sQuorumTrigger, sGobjectHash, sError);
results.push_back(Pair("quorum_hex", sQuorumTrigger));
// Add the contract explanation as JSON
std::vector<unsigned char> v = ParseHex(sQuorumTrigger);
std::string sMyQuorumTrigger(v.begin(), v.end());
UniValue u(UniValue::VOBJ);
u.read(sMyQuorumTrigger);
std::string sMyJsonQuorumTrigger = u.write().c_str();
results.push_back(Pair("quorum_json", sMyJsonQuorumTrigger));
results.push_back(Pair("quorum_gobject_trigger_hash", sGobjectHash));
results.push_back(Pair("quorum_error", sError));
}
results.push_back(Pair("gsc_protocol_version", PROTOCOL_VERSION));
double nMinGSCProtocolVersion = GetSporkDouble("MIN_GSC_PROTO_VERSION", 0);
bool bVersionSufficient = (PROTOCOL_VERSION >= nMinGSCProtocolVersion);
results.push_back(Pair("min_gsc_proto_version", nMinGSCProtocolVersion));
results.push_back(Pair("version_sufficient", bVersionSufficient));
results.push_back(Pair("votes_for_my_contract", iVotes));
int iRequiredVotes = GetRequiredQuorumLevel(iNextSuperblock);
results.push_back(Pair("required_votes", iRequiredVotes));
results.push_back(Pair("last_superblock", iLastSuperblock));
results.push_back(Pair("next_superblock", iNextSuperblock));
CAmount nLastLimit = CSuperblock::GetPaymentsLimit(iLastSuperblock, false);
results.push_back(Pair("last_payments_limit", (double)nLastLimit/COIN));
CAmount nNextLimit = CSuperblock::GetPaymentsLimit(iNextSuperblock, false);
results.push_back(Pair("next_payments_limit", (double)nNextLimit/COIN));
bool fOverBudget = IsOverBudget(iNextSuperblock, sAmounts);
results.push_back(Pair("overbudget", fOverBudget));
if (fOverBudget)
results.push_back(Pair("! CAUTION !", "Superblock exceeds budget, will be rejected."));
bool fTriggered = CSuperblockManager::IsSuperblockTriggered(iNextSuperblock);
results.push_back(Pair("next_superblock_triggered", fTriggered));
std::string sReqPay = CSuperblockManager::GetRequiredPaymentsString(iNextSuperblock);
results.push_back(Pair("next_superblock_req_payments", sReqPay));
bool bRes = VoteForGSCContract(iNextSuperblock, sContract, sError);
results.push_back(Pair("vote_result", bRes));
results.push_back(Pair("vote_error", sError));
}
else if (sItem == "blocktohex")
{
std::string sBlockHex = request.params[1].get_str();
CBlock block;
if (!DecodeHexBlk(block, sBlockHex))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
ssBlock << block;
std::string sBlockHex1 = HexStr(ssBlock.begin(), ssBlock.end());
CTransaction txCoinbase;
std::string sTxCoinbaseHex1 = EncodeHexTx(*block.vtx[0]);
results.push_back(Pair("blockhex", sBlockHex1));
results.push_back(Pair("txhex", sTxCoinbaseHex1));
}
else if (sItem == "hexblocktocoinbase")
{
if (request.params.size() != 2)
throw std::runtime_error("You must specify the block serialization hex.");
JSONRPCRequest myCommand;
myCommand.params.setArray();
myCommand.params.push_back(request.params[1].get_str());
results = hexblocktocoinbase(myCommand);
}
else if (sItem == "search")
{
if (request.params.size() != 2 && request.params.size() != 3)
throw std::runtime_error("You must specify type: IE 'exec search PRAYER'. Optionally you may enter a search phrase: IE 'exec search PRAYER MOTHER'.");
std::string sType = request.params[1].get_str();
std::string sSearch = "";
if (request.params.size() == 3)
sSearch = request.params[2].get_str();
int iSpecificEntry = 0;
std::string sEntry = "";
int iDays = 30;
UniValue aDataList = GetDataList(sType, iDays, iSpecificEntry, sSearch, sEntry);
return aDataList;
}
else if (sItem == "getsporkdouble")
{
std::string sType = request.params[1].get_str();
double dValue = GetSporkDouble(sType, 0);
results.push_back(Pair(sType, dValue));
}
else if (sItem == "persistsporkmessage")
{
std::string sError = "You must specify type, key, value: IE 'exec persistsporkmessage dcccomputingprojectname rosetta'";
if (request.params.size() != 4)
throw std::runtime_error(sError);
std::string sType = request.params[1].get_str();
std::string sPrimaryKey = request.params[2].get_str();
std::string sValue = request.params[3].get_str();
if (sType.empty() || sPrimaryKey.empty() || sValue.empty())
throw std::runtime_error(sError);
sError;
double dFee = fProd ? 10 : 5001;
std::string sResult = SendBlockchainMessage(sType, sPrimaryKey, sValue, dFee, true, "", sError);
results.push_back(Pair("Sent", sValue));
results.push_back(Pair("TXID", sResult));
if (!sError.empty()) results.push_back(Pair("Error", sError));
}
else if (sItem == "getabnweight")
{
CAmount nTotalReq = 0;
double dABN = pwalletMain->GetAntiBotNetWalletWeight(0, nTotalReq);
double dMin = 0;
double dDebug = 0;
if (request.params.size() > 1)
dMin = cdbl(request.params[1].get_str(), 2);
if (request.params.size() > 2)
dDebug = cdbl(request.params[2].get_str(), 2);
results.push_back(Pair("version", 2.6));
results.push_back(Pair("weight", dABN));
results.push_back(Pair("total_required", nTotalReq / COIN));
if (dMin > 0)
{
dABN = pwalletMain->GetAntiBotNetWalletWeight(dMin, nTotalReq);
if (dDebug == 1)
{
std::string sData = ReadCache("coin", "age");
if (sData.length() < 1000000)
results.push_back(Pair("coin_age_data_pre_select", sData));
}
results.push_back(Pair("weight " + RoundToString(dMin, 2), dABN));
results.push_back(Pair("total_required " + RoundToString(dMin, 2), nTotalReq/COIN));
}
}
else if (sItem == "getpoints")
{
if (request.params.size() < 2)
throw std::runtime_error("You must specify the txid.");
std::string sTxId = request.params[1].get_str();
uint256 hashBlock = uint256();
CTransactionRef tx;
uint256 uTx = ParseHashV(sTxId, "txid");
double nCoinAge = 0;
CAmount nDonation = 0;
if (GetTransaction(uTx, tx, Params().GetConsensus(), hashBlock, true))
{
CBlockIndex* pblockindex = mapBlockIndex[hashBlock];
if (!pblockindex)
throw std::runtime_error("bad blockindex for this tx.");
GetTransactionPoints(pblockindex, tx, nCoinAge, nDonation);
std::string sDiary = ExtractXML(tx->GetTxMessage(), "<diary>", "</diary>");
std::string sCampaignName;
std::string sCPK = GetTxCPK(tx, sCampaignName);
double nPoints = CalculatePoints(sCampaignName, sDiary, nCoinAge, nDonation, sCPK);
results.push_back(Pair("pog_points", nPoints));
results.push_back(Pair("coin_age", nCoinAge));
results.push_back(Pair("diary_entry", sDiary));
results.push_back(Pair("orphan_donation", (double)nDonation / COIN));
}
else
{
results.push_back(Pair("error", "not found"));
}
}
else if (sItem == "auditabntx")
{
if (request.params.size() < 2)
throw std::runtime_error("You must specify the txid.");
std::string sTxId = request.params[1].get_str();
uint256 hashBlock = uint256();
uint256 uTx = ParseHashV(sTxId, "txid");
COutPoint out1(uTx, 0);
BBPVin b = GetBBPVIN(out1, 0);
double nCoinAge = 0;
CAmount nDonation = 0;
std::string sCPK;
std::string sCampaignName;
std::string sDiary;
if (b.Found)
{
CBlockIndex* pblockindex = mapBlockIndex[b.HashBlock];
int64_t nBlockTime = GetAdjustedTime();
if (pblockindex != NULL)
{
nBlockTime = pblockindex->GetBlockTime();
GetTransactionPoints(pblockindex, b.TxRef, nCoinAge, nDonation);
std::string sCPK = GetTxCPK(b.TxRef, sCampaignName);
results.push_back(Pair("campaign_name", sCampaignName));
results.push_back(Pair("coin_age", nCoinAge));
}
// For each VIN
for (int i = 0; i < (int)b.TxRef->vin.size(); i++)
{
const COutPoint &outpoint = b.TxRef->vin[i].prevout;
BBPVin bIn = GetBBPVIN(outpoint, nBlockTime);
if (bIn.Found)
{
results.push_back(Pair("Vin # " + RoundToString(i, 0), RoundToString((double)bIn.Amount/COIN, 2) + "bbp - " + bIn.Destination
+ " - Coin*Age: " + RoundToString(bIn.CoinAge, 0)));
}
}
// For each VOUT
for (int i = 0; i < b.TxRef->vout.size(); i++)
{
CAmount nOutAmount = b.TxRef->vout[i].nValue;
std::string sDest = PubKeyToAddress(b.TxRef->vout[i].scriptPubKey);
results.push_back(Pair("VOUT #" + RoundToString(i, 0), RoundToString((double)nOutAmount/COIN, 2) + "bbp - " + sDest));
}
}
else
{
results.push_back(Pair("error", "not found"));
}
}
else if (sItem == "createabn")
{
std::string sError;
std::string sXML;
WriteCache("vin", "coinage", "", GetAdjustedTime());
WriteCache("availablecoins", "age", "", GetAdjustedTime());
WriteCache("coin", "age", "", GetAdjustedTime());
double dTargetWeight = 0;
if (request.params.size() > 1)
dTargetWeight = cdbl(request.params[1].get_str(), 2);
CReserveKey reserveKey(pwalletMain);
CWalletTx wtx = CreateAntiBotNetTx(chainActive.Tip(), dTargetWeight, reserveKey, sXML, "ppk", sError);
results.push_back(Pair("xml", sXML));
results.push_back(Pair("err", sError));
if (sError.empty())
{
results.push_back(Pair("coin_age_data_selected", ReadCache("availablecoins", "age")));
results.push_back(Pair("success", wtx.GetHash().GetHex()));
double nAuditedWeight = GetAntiBotNetWeight(chainActive.Tip()->GetBlockTime(), wtx.tx, true, "");
std::string sData = ReadCache("coin", "age");
if (sData.length() < 1000000)
results.push_back(Pair("coin_age_data_pre_select", sData));
results.push_back(Pair("audited_weight", nAuditedWeight));
results.push_back(Pair("vin_coin_age_data", ReadCache("vin", "coinage")));
}
else
{
results.push_back(Pair("age_data", ReadCache("availablecoins", "age")));
if (true)
{
double nAuditedWeight = GetAntiBotNetWeight(chainActive.Tip()->GetBlockTime(), wtx.tx, true, "");
results.push_back(Pair("vin_coin_age_data", ReadCache("vin", "coinage")));
std::string sData1 = ReadCache("coin", "age");
if (sData1.length() < 1000000)
results.push_back(Pair("coin_age_data_pre_select", sData1));
results.push_back(Pair("total_audited_weight", nAuditedWeight));
}
results.push_back(Pair("tx_create_error", sError));
}
}
else if (sItem == "cpk")
{
std::string sError;
if (request.params.size() != 2 && request.params.size() != 3 && request.params.size() != 4 && request.params.size() != 5)
throw std::runtime_error("You must specify exec cpk nickname [optional e-mail address] [optional vendortype=church/user/vendor] [optional: force=true/false].");
std::string sNickName = request.params[1].get_str();
bool fForce = false;
std::string sEmail;
std::string sVendorType;
if (request.params.size() >= 3)
sEmail = request.params[2].get_str();
if (request.params.size() >= 4)
sVendorType = request.params[3].get_str();
if (request.params.size() >= 5)
fForce = request.params[4].get_str() == "true" ? true : false;
bool fAdv = AdvertiseChristianPublicKeypair("cpk", sNickName, sEmail, sVendorType, false, fForce, 0, "", sError);
results.push_back(Pair("Results", fAdv));
if (!fAdv)
results.push_back(Pair("Error", sError));
}
else if (sItem == "sendmanyxml")
{
// BiblePay Pools: Allows pools to send a multi-output tx with ease
// Format: exec sendmanyxml from_account xml_payload comment
LOCK2(cs_main, pwalletMain->cs_wallet);
std::string strAccount = request.params[1].get_str();
if (strAccount == "*")
throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name");
std::string sXML = request.params[2].get_str();
int nMinDepth = 1;
CWalletTx wtx;
wtx.strFromAccount = strAccount;
wtx.mapValue["comment"] = request.params[3].get_str();
std::set<CBitcoinAddress> setAddress;
std::vector<CRecipient> vecSend;
CAmount totalAmount = 0;
std::string sRecipients = ExtractXML(sXML, "<RECIPIENTS>","</RECIPIENTS>");
std::vector<std::string> vRecips = Split(sRecipients.c_str(), "<ROW>");
for (int i = 0; i < (int)vRecips.size(); i++)
{
std::string sRecip = vRecips[i];
if (!sRecip.empty())
{
std::string sRecipient = ExtractXML(sRecip, "<RECIPIENT>","</RECIPIENT>");
double dAmount = cdbl(ExtractXML(sRecip,"<AMOUNT>","</AMOUNT>"),4);
if (!sRecipient.empty() && dAmount > 0)
{
CBitcoinAddress address(sRecipient);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Biblepay address: ") + sRecipient);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ") + sRecipient);
setAddress.insert(address);
CScript scriptPubKey = GetScriptForDestination(address.Get());
CAmount nAmount = dAmount * COIN;
if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
totalAmount += nAmount;
bool fSubtractFeeFromAmount = false;
CRecipient recipient = {scriptPubKey, nAmount, false, fSubtractFeeFromAmount};
vecSend.push_back(recipient);
}
}
}
EnsureWalletIsUnlocked(pwalletMain);
// Check funds
CAmount nBalance = pwalletMain->GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE, false);
if (totalAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
CReserveKey keyChange(pwalletMain);
CAmount nFeeRequired = 0;
int nChangePosRet = -1;
std::string strFailReason;
bool fUseInstantSend = false;
bool fUsePrivateSend = false;
CValidationState state;
bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, nChangePosRet, strFailReason, NULL, true, fUsePrivateSend ? ONLY_DENOMINATED : ALL_COINS, fUseInstantSend);
if (!fCreated)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason);
if (!pwalletMain->CommitTransaction(wtx, keyChange, g_connman.get(), state, NetMsgType::TX))
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed");
results.push_back(Pair("txid", wtx.GetHash().GetHex()));
}
else if (sItem == "unjoin")
{
if (request.params.size() != 2)
throw std::runtime_error("You must specify the project_name to un-join.");
std::string sProject = request.params[1].get_str();
std::string sError;
if (!CheckCampaign(sProject))
throw std::runtime_error("Campaign does not exist.");
bool fAdv = AdvertiseChristianPublicKeypair("cpk-" + sProject, "", "", "", true, false, 0, "", sError);
results.push_back(Pair("Results", fAdv));
if (!fAdv)
results.push_back(Pair("Error", sError));
}
else if (sItem == "register")
{
if (request.params.size() != 2)
throw std::runtime_error("The purpose of this command is to register your nickname with BMS (the decentralized biblepay web). This feature will not be available until December 2019. \nYou must specify your nickname.");
std::string sProject = "cpk-bmsuser";
std::string sNN;
sNN = request.params[1].get_str();
boost::to_lower(sProject);
std::string sError;
bool fAdv = AdvertiseChristianPublicKeypair(sProject, "", sNN, "", false, true, 0, "", sError);
results.push_back(Pair("Results", fAdv));
if (!fAdv)
results.push_back(Pair("Error", sError));
}
else if (sItem == "tuhi")
{
UpdateHealthInformation(0);
}
else if (sItem == "funddsql")
{
if (request.params.size() != 2)
throw std::runtime_error("funddsql: Make a DSQL payment. Usage: funddsql amount.");
EnsureWalletIsUnlocked(pwalletMain);
CAmount nAmount = cdbl(request.params[1].get_str(), 2) * COIN;
if (nAmount < 1)
throw std::runtime_error("Amount must be > 0.");
// Ensure the DSQL server knows about it
std::string sResult = BIPFS_Payment(nAmount, "", "");
std::string sHash = ExtractXML(sResult, "<hash>", "</hash>");
std::string sErrorsDSQL = ExtractXML(sResult, "<ERRORS>", "</ERRORS>");
std::string sTXID = ExtractXML(sResult, "<TXID>", "</TXID>");
results.push_back(Pair("TXID", sTXID));
if (!sErrorsDSQL.empty())
results.push_back(Pair("DSQL Errors", sErrorsDSQL));
results.push_back(Pair("DSQL Hash", sHash));
}
else if (sItem == "blscommand")
{
if (request.params.size() != 2)
throw std::runtime_error("You must specify blscommand masternodeprivkey masternodeblsprivkey.");
std::string sMNP = request.params[1].get_str();
std::string sMNBLSPrivKey = request.params[2].get_str();
std::string sCommand = "masternodeblsprivkey=" + sMNBLSPrivKey;
std::string sEnc = EncryptAES256(sCommand, sMNP);
std::string sCPK = DefaultRecAddress("Christian-Public-Key");
std::string sXML = "<blscommand>" + sEnc + "</blscommand>";
std::string sError;
std::string sResult = SendBlockchainMessage("bls", sCPK, sXML, 1, false, "", sError);
if (!sError.empty())
results.push_back(Pair("Errors", sError));
results.push_back(Pair("blsmessage", sXML));
}
else if (sItem == "testaes")
{
std::string sEnc = EncryptAES256("test", "abc");
std::string sDec = DecryptAES256(sEnc, "abc");
results.push_back(Pair("Enc", sEnc));
results.push_back(Pair("Dec", sDec));
}
else if (sItem == "associate")
{
if (request.params.size() != 2 && request.params.size() != 3 && request.params.size() != 4)
throw std::runtime_error("Associate v1.2: You must specify exec associate wcg_username wcg_verificationcode. (WCG | LogIn | My Profile | Copy down your 'Username' AND 'VERIFICATION CODE').");
std::string sUserName;
std::string sVerificationCode;
if (request.params.size() > 1)
sUserName = request.params[1].get_str();
if (request.params.size() > 2)
sVerificationCode = request.params[2].get_str();
bool fForce = false;
if (request.params.size() > 3)
fForce = request.params[3].get_str() == "true" ? true : false;
// PODC 2.0 : Verify the user inside WCG before succeeding
// Step 1
double nPoints = 0;
int nID = GetWCGMemberID(sUserName, sVerificationCode, nPoints);
if (nID == 0)
throw std::runtime_error("Unable to find " + sUserName + ". Please type exec rac to see helpful hints to proceed. ");
results.push_back(Pair("wcg_member_id", nID));
results.push_back(Pair("wcg_points", nPoints));
Researcher r = GetResearcherByID(nID);
if (!r.found && nID > 0)
{
std::string sErr = "Sorry, we found you as a researcher in WCG, but we were unable to locate you on the team. "
"You may still participate but the daily escrow requirements are higher for non BiblePay researchers. "
"NOTE: Your RAC must be > 256 if you are not on team biblepay. Please navigate to web.biblepay.org, click PODC research, and type in your CPID in the search box. If your rac < 256 please build up your RAC first, then re-associate. ";
throw std::runtime_error(sErr.c_str());
}
results.push_back(Pair("cpid", r.cpid));
results.push_back(Pair("rac", r.rac));
results.push_back(Pair("researcher_nickname", r.nickname));
std::string sError;
// Step 2 : Advertise the keypair association with the CPID (and join the researcher to the campaign).
if (!CheckCampaign("wcg"))
throw std::runtime_error("Campaign wcg does not exist.");
if (r.cpid.length() != 32)
{
throw std::runtime_error("Sorry, unable to save your researcher record because your WCG CPID is empty. Please log into your WCG account and verify you are part of team BiblePay, and that the WCG verification code matches.");
}
std::string sEncVC = EncryptAES256(sVerificationCode, r.cpid);
bool fAdv = AdvertiseChristianPublicKeypair("cpk-wcg", "", sUserName + "|" + sEncVC + "|" + RoundToString(nID, 0) + "|" + r.cpid, "", false, fForce, 0, "", sError);
if (!fAdv)
{
results.push_back(Pair("Error", sError));
}
else
{
// Step 3: Create external purse
bool fCreated = CreateExternalPurse(sError);
if (!sError.empty())
results.push_back(Pair("External Purse Creation Error", sError));
else
{
std::string sEFA = DefaultRecAddress("Christian-Public-Key");
results.push_back(Pair("Purse Status", "Successful"));
results.push_back(Pair("External Purse Address", sEFA));
results.push_back(Pair("Remember", "Now you must fund your external address with enough capital to make daily PODC/GSC stakes."));
}
// (Dev notes: In step 2, we already joined the cpk to wcg - equivalent to 'exec join wcg' so we do not need to do that here).
results.push_back(Pair("Results", fAdv));
results.push_back(Pair("Welcome Aboard!",
"You have successfully joined the BiblePay Proof Of Distributed Comuting (PODC) grid, and now you can help cure cancer, AIDS, and make the world a better place! God Bless You!"));
}
}
else if (sItem == "join")
{
if (request.params.size() != 2 && request.params.size() != 3 && request.params.size() != 4)
throw std::runtime_error("You must specify the project_name. Optionally specify your nickname or sanctuary IP address. Optionally specify force=true/false.");
std::string sProject = request.params[1].get_str();
std::string sOptData;
bool fForce = false;
if (request.params.size() > 2)
sOptData = request.params[2].get_str();
if (request.params.size() > 3)
fForce = request.params[3].get_str() == "true" ? true : false;
boost::to_lower(sProject);
std::string sError;
if (!CheckCampaign(sProject))
throw std::runtime_error("Campaign does not exist.");
bool fAdv = AdvertiseChristianPublicKeypair("cpk-" + sProject, "", sOptData, "", false, true, 0, "", sError);
results.push_back(Pair("Results", fAdv));
if (!fAdv)
results.push_back(Pair("Error", sError));
if (fAdv && sProject == "healing")
{
std::string sURL = "https://wiki.biblepay.org/BiblePay_Healing_Campaign";
std::string sNarr = "Please read this guide: " + sURL + " with critical instructions before attempting Spiritual Warfare or Street Healing. Thank you for joining the BiblePay Healing campaign. ";
results.push_back(Pair("Warning!", sNarr));
}
}
else if (sItem == "getcampaigns")
{
UniValue c = GetCampaigns();
return c;
}
else if (sItem == "checkcpk")
{
if (request.params.size() != 2)
throw std::runtime_error("You must specify campaign name.");
std::string sType = request.params[1].get_str();
std::string sError;
bool fEnrolled = Enrolled(sType, sError);
if (!sError.empty())
results.push_back(Pair("Error", sError));
results.push_back(Pair("Enrolled_Results", fEnrolled));
}
else if (sItem == "bankroll")
{
if (request.params.size() != 3)
throw std::runtime_error("You must specify type: IE 'exec bankroll quantity denomination'. IE exec bankroll 10 100 (creates ten 100 BBP bills).");
double nQty = cdbl(request.params[1].get_str(), 0);
CAmount denomination = cdbl(request.params[2].get_str(), 4) * COIN;
std::string sError = "";
std::string sTxId = CreateBankrollDenominations(nQty, denomination, sError);
if (!sError.empty())
{
if (sError == "Signing transaction failed")
sError += ". (Please ensure your wallet is unlocked).";
results.push_back(Pair("Error", sError));
}
else
{
results.push_back(Pair("TXID", sTxId));
}
}
else if (sItem == "health")
{
// This command pulls the best-superblock (the one with the highest votes for the next height)
bool bImpossible = (!masternodeSync.IsSynced() || fLiteMode);
int iNextSuperblock = 0;
int iLastSuperblock = GetLastGSCSuperblockHeight(chainActive.Tip()->nHeight, iNextSuperblock);
std::string sAddresses;
std::string sAmounts;
int iVotes = 0;
uint256 uGovObjHash = uint256S("0x0");
uint256 uPAMHash = uint256S("0x0");
GetGSCGovObjByHeight(iNextSuperblock, uPAMHash, iVotes, uGovObjHash, sAddresses, sAmounts);
uint256 hPam = GetPAMHash(sAddresses, sAmounts);
results.push_back(Pair("pam_hash", hPam.GetHex()));
std::string sContract = GetGSCContract(iLastSuperblock, true);
uint256 hPAMHash2 = GetPAMHashByContract(sContract);
results.push_back(Pair("pam_hash_internal", hPAMHash2.GetHex()));
if (hPAMHash2 != hPam)
{
results.push_back(Pair("WARNING", "Our internal PAM hash disagrees with the network. "));
}
results.push_back(Pair("govobjhash", uGovObjHash.GetHex()));
int iRequiredVotes = GetRequiredQuorumLevel(iNextSuperblock);
results.push_back(Pair("Amounts", sAmounts));
results.push_back(Pair("Addresses", sAddresses));
results.push_back(Pair("votes", iVotes));
results.push_back(Pair("required_votes", iRequiredVotes));
results.push_back(Pair("last_superblock", iLastSuperblock));
results.push_back(Pair("next_superblock", iNextSuperblock));
bool fTriggered = CSuperblockManager::IsSuperblockTriggered(iNextSuperblock);
results.push_back(Pair("next_superblock_triggered", fTriggered));
if (bImpossible)
{
results.push_back(Pair("WARNING", "Running in Lite Mode or Sanctuaries are not synced."));
}
bool fHealthy = (!sAmounts.empty() && !sAddresses.empty() && uGovObjHash != uint256S("0x0")) || bImpossible;
results.push_back(Pair("Healthy", fHealthy));
bool fPassing = (iVotes >= iRequiredVotes);
results.push_back(Pair("GSC_Voted_In", fPassing));
}
else if (sItem == "watchman")
{
std::string sContract;
std::string sResponse = WatchmanOnTheWall(true, sContract);
results.push_back(Pair("Response", sResponse));
results.push_back(Pair("Contract", sContract));
}
else if (sItem == "getgschashes")
{
int iNextSuperblock = 0;
int iLastSuperblock = GetLastGSCSuperblockHeight(chainActive.Tip()->nHeight, iNextSuperblock);
std::string sContract = GetGSCContract(0, true); // As of iLastSuperblock height
results.push_back(Pair("Contract", sContract));
uint256 hPAMHash = GetPAMHashByContract(sContract);
std::string sData;
GetGovObjDataByPamHash(iNextSuperblock, hPAMHash, sData);
results.push_back(Pair("Data", sData));
}
else if (sItem == "masterclock")
{
const Consensus::Params& consensusParams = Params().GetConsensus();
CBlockIndex* pblockindexGenesis = FindBlockByHeight(0);
CBlock blockGenesis;
int64_t nBlockSpacing = 60 * 7;
if (ReadBlockFromDisk(blockGenesis, pblockindexGenesis, consensusParams))
{
int64_t nEpoch = blockGenesis.GetBlockTime();
int64_t nNow = chainActive.Tip()->GetMedianTimePast();
int64_t nElapsed = nNow - nEpoch;
int64_t nTargetBlockCount = nElapsed / nBlockSpacing;
results.push_back(Pair("Elapsed Time (Seconds)", nElapsed));
results.push_back(Pair("Actual Blocks", chainActive.Tip()->nHeight));
results.push_back(Pair("Target Block Count", nTargetBlockCount));
double nClockAdjustment = 1.00 - ((double)chainActive.Tip()->nHeight / (double)nTargetBlockCount + .01);
std::string sLTNarr = nClockAdjustment > 0 ? "Slow" : "Fast";
results.push_back(Pair("Long Term Target DGW adjustment", nClockAdjustment));
results.push_back(Pair("Long Term Trend Narr", sLTNarr));
CBlockIndex* pblockindexRecent = FindBlockByHeight(chainActive.Tip()->nHeight * .90);
CBlock blockRecent;
if (ReadBlockFromDisk(blockRecent, pblockindexRecent, consensusParams))
{
int64_t nBlockSpan = chainActive.Tip()->nHeight - (chainActive.Tip()->nHeight * .90);
int64_t nTimeSpan = chainActive.Tip()->GetMedianTimePast() - blockRecent.GetBlockTime();
int64_t nProjectedBlockCount = nTimeSpan / nBlockSpacing;
double nRecentTrend = 1.00 - ((double)nBlockSpan / (double)nProjectedBlockCount + .01);
std::string sNarr = nRecentTrend > 0 ? "Slow" : "Fast";
results.push_back(Pair("Recent Trend", nRecentTrend));
results.push_back(Pair("Recent Trend Narr", sNarr));
double nGrandAdjustment = nClockAdjustment + nRecentTrend;
results.push_back(Pair("Recommended Next DGW adjustment", nGrandAdjustment));
}
}
}
else if (sItem == "antigpu")
{
if (request.params.size() != 2)
throw std::runtime_error("You must specify height.");
int nHeight = cdbl(request.params[1].get_str(), 0);
CBlockIndex* pblockindex = FindBlockByHeight(nHeight);
if (pblockindex == NULL)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlock block;
const Consensus::Params& consensusParams = Params().GetConsensus();
if (ReadBlockFromDisk(block, pblockindex, consensusParams))
{
std::string sMsg = GetTransactionMessage(block.vtx[0]);
int nABNLocator = (int)cdbl(ExtractXML(sMsg, "<abnlocator>", "</abnlocator>"), 0);
if (block.vtx.size() >= nABNLocator)
{
CTransactionRef tx = block.vtx[nABNLocator];
std::string sCPK = ExtractXML(tx->GetTxMessage(), "<abncpk>", "</abncpk>");
results.push_back(Pair("anti_gpu_xml", tx->GetTxMessage()));
results.push_back(Pair("cpk", sCPK));
bool fValid = CheckAntiBotNetSignature(tx, "abn", "");
results.push_back(Pair("sig_valid", fValid));
bool fAntiGPU = AntiGPU(block, pblockindex->pprev);
results.push_back(Pair("anti-gpu", fAntiGPU));
}
}
else
{
results.push_back(Pair("error", "Unable to read block."));
}
}
else if (sItem == "price")
{
double dBBP = GetCryptoPrice("bbp");
double dBTC = GetCryptoPrice("btc");
double dDASH = GetCryptoPrice("dash");
results.push_back(Pair("BBP/BTC", RoundToString(dBBP, 12)));
results.push_back(Pair("DASH/BTC", RoundToString(dDASH, 12)));
results.push_back(Pair("BTC/USD", dBTC));
double nPrice = GetBBPPrice();
double nDashPriceUSD = dBTC * dDASH;
results.push_back(Pair("DASH/USD", nDashPriceUSD));
results.push_back(Pair("BBP/USD", nPrice));
}
else if (sItem == "sentgsc")
{
if (request.params.size() > 3)
throw std::runtime_error("sentgsc: Reports on the GSC transmissions and ABN transmissions over the last 7 days. You may optionally specify the CPK and the height: sentgsc cpk height.");
std::string sMyCPK;
if (request.params.size() > 1)
sMyCPK = request.params[1].get_str();
if (sMyCPK.empty())
sMyCPK = DefaultRecAddress("Christian-Public-Key");
double nHeight = 0;
if (request.params.size() > 2)
nHeight = cdbl(request.params[2].get_str(), 0);
UniValue s = SentGSCCReport(nHeight, sMyCPK);
return s;
}
else if (sItem == "revivesanc")
{
// Sanctuary Revival - BiblePay
// The purpose of this command is to make it easy to Revive a POSE-banned deterministic sanctuary. (In contrast to knowing how to create and send the protx update_service command).
std::string sExtraHelp = "NOTE: If you do not have a deterministic.conf file, you can still revive your sanctuary this way: protx update_service proreg_txID sanctuaryIP:Port sanctuary_blsPrivateKey\n\n NOTE: You can right click on the sanctuary in the Sanctuaries Tab in QT and obtain the proreg_txID, and, you can write the IP down from the list. You still need to find your sanctuaryBLSPrivKey.\n";
if (request.params.size() != 2)
throw std::runtime_error("You must specify exec revivesanc sanctuary_name (where the sanctuary_name matches the name in the deterministic.conf file).\n\n" + sExtraHelp);
std::string sSearch = request.params[1].get_str();
std::string sSanc = ScanDeterministicConfigFile(sSearch);
if (sSanc.empty())
throw std::runtime_error("Unable to find sanctuary " + sSearch + " in deterministic.conf file.");
std::vector<std::string> vSanc = Split(sSanc.c_str(), " ");
if (vSanc.size() < 9)
throw std::runtime_error("Sanctuary entry in deterministic.conf corrupted (does not contain at least 9 parts.) Format should be: Sanctuary_Name IP:port(40000=prod,40001=testnet) BLS_Public_Key BLS_Private_Key Collateral_output_txid Collateral_output_index Pro-Registration-TxId Pro-Reg-Collateral-Address Pro-Reg-funding-sent-txid.");
std::string sSancName = vSanc[0];
std::string sSancIP = vSanc[1];
std::string sBLSPrivKey = vSanc[3];
std::string sProRegTxId = vSanc[8];
std::string sSummary = "Creating protx update_service command for Sanctuary " + sSancName + " with IP " + sSancIP + " with origin pro-reg-txid=" + sProRegTxId;
sSummary += "(protx update_service " + sProRegTxId + " " + sSancIP + " " + sBLSPrivKey + ").";
LogPrintf("\nCreating ProTx_Update_service %s for Sanc [%s].\n", sSummary, sSanc);
std::string sError;
results.push_back(Pair("Summary", sSummary));
JSONRPCRequest newRequest;
newRequest.params.setArray();
newRequest.params.push_back("update_service");
newRequest.params.push_back(sProRegTxId);
newRequest.params.push_back(sSancIP);
newRequest.params.push_back(sBLSPrivKey);
UniValue rProReg = protx(newRequest);
results.push_back(rProReg);
// If we made it this far and an error was not thrown:
results.push_back(Pair("Results", "Sent sanctuary revival pro-tx successfully. Please wait for the sanctuary list to be updated to ensure the sanctuary is revived. This usually takes one to fifteen minutes."));
}
else if (sItem == "diagnosewcgpoints")
{
// This diagnosis command simply checks the cpid's WCG point level from the WCG API for debug purposes
std::string sSearch = request.params[1].get_str();
if (sSearch.empty())
throw std::runtime_error("empty cpid");
int nID = GetWCGIdByCPID(sSearch);
if (nID == 0)
throw std::runtime_error("unknown cpid");
results.push_back(Pair("wcg_id", nID));
results.push_back(Pair("cpid", sSearch));
}
else if (sItem == "upgradesanc")
{
if (request.params.size() != 3)
throw std::runtime_error("You must specify exec upgradesanc sanctuary_name (where the sanctuary_name matches the name in the masternode.conf file) 0/1 (where 0=dry-run, 1=real). NOTE: Please be sure your masternode.conf has a carriage return after the end of every sanctuary entry (otherwise we can't parse each entry correctly). ");
std::string sSearch = request.params[1].get_str();
int iDryRun = cdbl(request.params[2].get_str(), 0);
std::string sSanc = ScanSanctuaryConfigFile(sSearch);
if (sSanc.empty())
throw std::runtime_error("Unable to find sanctuary " + sSearch + " in masternode.conf file.");
// Legacy Sanc (masternode.conf) data format: sanc_name, ip, mnp, collat, collat ordinal
std::vector<std::string> vSanc = Split(sSanc.c_str(), " ");
if (vSanc.size() < 5)
throw std::runtime_error("Sanctuary entry in masternode.conf corrupted (does not contain 5 parts.)");
std::string sSancName = vSanc[0];
std::string sSancIP = vSanc[1];
std::string sMNP = vSanc[2];
std::string sCollateralTXID = vSanc[3];
std::string sCollateralTXIDOrdinal = vSanc[4];
double dColOrdinal = cdbl(sCollateralTXIDOrdinal, 0);
if (sCollateralTXIDOrdinal.length() != 1 || dColOrdinal > 9 || sCollateralTXID.length() < 16)
{
throw std::runtime_error("Sanctuary entry in masternode.conf corrupted (collateral txid missing, or there is no newline at the end of the entry in the masternode.conf file.)");
}
std::string sSummary = "Creating protx_register command for Sanctuary " + sSancName + " with IP " + sSancIP + " with TXID " + sCollateralTXID;
// Step 1: Fund the protx fee
// 1a. Create the new deterministic-sanctuary reward address
std::string sPayAddress = DefaultRecAddress(sSancName + "-d"); //d means deterministic
CBitcoinAddress baPayAddress(sPayAddress);
std::string sVotingAddress = DefaultRecAddress(sSancName + "-v"); //v means voting
CBitcoinAddress baVotingAddress(sVotingAddress);
std::string sError;
std::string sData = "<protx></protx>"; // Reserved for future use
CWalletTx wtx;
bool fSubtractFee = false;
bool fInstantSend = false;
// 1b. We must send 1BBP to ourself first here, as the deterministic sanctuaries future fund receiving address must be prefunded with enough funds to cover the non-financial transaction transmission below
bool fSent = RPCSendMoney(sError, baPayAddress.Get(), 1 * COIN, fSubtractFee, wtx, fInstantSend, sData);
if (!sError.empty() || !fSent)
throw std::runtime_error("Unable to fund protx_register fee: " + sError);
results.push_back(Pair("Summary", sSummary));
// Generate BLS keypair (This is the keypair for the sanctuary - the BLS public key goes in the chain, the private key goes into the Sanctuaries biblepay.conf file like this: masternodeblsprivkey=nnnnn
JSONRPCRequest myBLS;
myBLS.params.setArray();
myBLS.params.push_back("generate");
UniValue myBLSPair = _bls(myBLS);
std::string myBLSPublic = myBLSPair["public"].getValStr();
std::string myBLSPrivate = myBLSPair["secret"].getValStr();
JSONRPCRequest newRequest;
newRequest.params.setArray();
// Pro-tx-register_prepare preparation format: protx register_prepare 1.55mm_collateralHash 1.55mm_index_collateralIndex ipv4:port_ipAndPort home_voting_address_ownerKeyAddr blsPubKey_operatorPubKey delegate_or_home_votingKeyAddr 0_pctOf_operatorReward payout_address_payoutAddress optional_(feeSourceAddress_of_Pro_tx_fee)
newRequest.params.push_back("register_prepare");
newRequest.params.push_back(sCollateralTXID);
newRequest.params.push_back(sCollateralTXIDOrdinal);
newRequest.params.push_back(sSancIP);
newRequest.params.push_back(sVotingAddress); // Home Voting Address
newRequest.params.push_back(myBLSPublic); // Remote Sanctuary Public Key (Private and public keypair is stored in deterministicsanctuary.conf on the controller wallet)
newRequest.params.push_back(sVotingAddress); // Delegates Voting address (This is a person that can vote for you if you want) - in our case its the same
newRequest.params.push_back("0"); // Pct of rewards to share with Operator (This is the amount of reward we want to share with a Sanc Operator - IE a hosting company)
newRequest.params.push_back(sPayAddress); // Rewards Pay To Address (This can be changed to be a wallet outside of your wallet, maybe a hardware wallet)
// 1c. First send the pro-tx-register_prepare command, and look for the tx, collateralAddress and signMessage response:
UniValue rProReg = protx(newRequest);
std::string sProRegTxId = rProReg["tx"].getValStr();
std::string sProCollAddr = rProReg["collateralAddress"].getValStr();
std::string sProSignMessage = rProReg["signMessage"].getValStr();
if (sProSignMessage.empty() || sProRegTxId.empty())
throw std::runtime_error("Failed to create pro reg tx.");
// Step 2: Sign the Pro-Reg Tx
JSONRPCRequest newSig;
newSig.params.setArray();
newSig.params.push_back(sProCollAddr);
newSig.params.push_back(sProSignMessage);
std::string sProSignature = SignMessageEvo(sProCollAddr, sProSignMessage, sError);
if (!sError.empty())
throw std::runtime_error("Unable to sign pro-reg-tx: " + sError);
std::string sSentTxId;
if (iDryRun == 1)
{
// Note: If this is Not a dry-run, go ahead and submit the non-financial transaction to the network here:
JSONRPCRequest newSend;
newSend.params.setArray();
newSend.params.push_back("register_submit");
newSend.params.push_back(sProRegTxId);
newSend.params.push_back(sProSignature);
UniValue rProReg = protx(newSend);
results.push_back(rProReg);
sSentTxId = rProReg.getValStr();
}
// Step 3: Report this info back to the user
results.push_back(Pair("bls_public_key", myBLSPublic));
results.push_back(Pair("bls_private_key", myBLSPrivate));
results.push_back(Pair("pro_reg_txid", sProRegTxId));
results.push_back(Pair("pro_reg_collateral_address", sProCollAddr));
results.push_back(Pair("pro_reg_signed_message", sProSignMessage));
results.push_back(Pair("pro_reg_signature", sProSignature));
results.push_back(Pair("sent_txid", sSentTxId));
// Step 4: Store the new deterministic sanctuary in deterministicsanc.conf
std::string sDSD = sSancName + " " + sSancIP + " " + myBLSPublic + " " + myBLSPrivate + " " + sCollateralTXID + " " + sCollateralTXIDOrdinal + " " + sProRegTxId + " " + sProCollAddr + " " + sSentTxId + "\n";
if (iDryRun == 1)
AppendSanctuaryFile("deterministic.conf", sDSD);
}
else if (sItem == "rac")
{
// Query the WCG RAC from the last known quorum - this lets the users see that their CPID is producing RAC on team biblepay
// This command should also confirm the CPID link status
// So: Display WCG Rac in team BBP, Link Status, and external-purse weight need to be shown.
// This command can knock out most troubleshooting issues all in one swoop.
if (request.params.size() > 2)
throw std::runtime_error("Rac v1.1: You must specify exec rac [optional=someone elses cpid or nickname].");
std::string sSearch;
if (request.params.size() > 1)
sSearch = request.params[1].get_str();
if (!sSearch.empty() && sSearch.length() != 32)
{
BoincHelpfulHint(results);
return results;
}
// First verify the user has a CPK...
CPK myCPK = GetMyCPK("cpk");
if (myCPK.sAddress.empty() && sSearch.empty())
{
results.push_back(Pair("Error", "Sorry, you do not have a CPK. First please create your CPK by typing 'exec cpk your_nickname'. This adds your CPK to the chain. Please wait 3 or more blocks after adding your CPK before you move on to the next step. "));
BoincHelpfulHint(results);
return results;
}
// Next check the link status (of the exec join wcg->cpid)...
std::string sCPID = GetResearcherCPID(sSearch);
LogPrintf("\nFound researcher cpid %s", sCPID);
UniValue e(UniValue::VOBJ);
if (sCPID.empty())
{
results.push_back(Pair("Error", "Not Linked. First, you must link your researcher CPID in the chain using 'exec associate'."));
BoincHelpfulHint(results);
return results;
}
results.push_back(Pair("cpid", sCPID));
Researcher r = mvResearchers[sCPID];
if (!r.found && sCPID.length() != 32)
{
results.push_back(Pair("Error", "Not Linked. First, you must link your researcher CPID in the chain using 'exec associate'."));
BoincHelpfulHint(results);
return results;
}
else if (!r.found && sCPID.length() == 32)
{
results.push_back(Pair("temporary_cpid", sCPID));
results.push_back(Pair("Error", "Your CPID is linked to your CPK, but we are unable to find your research records in WCG; most likely because you are not in team BiblePay yet."));
BoincHelpfulHint(results);
return results;
}
else
{
std::string sMyCPK = GetCPKByCPID(sCPID);
results.push_back(Pair("CPK", sMyCPK));
if (r.teamid > 0)
results.push_back(Pair("wcg_teamid", r.teamid));
int nHeight = GetNextPODCTransmissionHeight(chainActive.Tip()->nHeight);
results.push_back(Pair("next_podc_gsc_transmission", nHeight));
std::string sTeamName = TeamToName(r.teamid);
double nConfiguration = GetSporkDouble("PODCTeamConfiguration", 0);
if (nConfiguration == 1)
{
bool fWhitelisted = sTeamName == "Unknown" ? false : true;
if (!fWhitelisted)
results.push_back(Pair("Warning!", "** You must join team BiblePay or a whitelisted team to be compensated for Research Activity in PODC. **"));
}
if (!sTeamName.empty())
results.push_back(Pair("team_name", sTeamName));
if (!r.nickname.empty())
results.push_back(Pair("researcher_nickname", r.nickname));
if (!r.country.empty())
results.push_back(Pair("researcher_country", r.country));
if (r.totalcredit > 0)
results.push_back(Pair("total_wcg_boinc_credit", r.totalcredit));
if (r.wcgpoints > 0)
results.push_back(Pair("total_wcg_points", r.wcgpoints));
// Print out the current coin age requirements
double nCAR = GetNecessaryCoinAgePercentageForPODC();
CAmount nReqCoins = 0;
double nTotalCoinAge = pwalletMain->GetAntiBotNetWalletWeight(0, nReqCoins);
results.push_back(Pair("external_purse_total_coin_age", nTotalCoinAge));
results.push_back(Pair("coin_age_percent_required", nCAR));
double nCoinAgeReq = GetRequiredCoinAgeForPODC(r.rac, r.teamid);
if (nTotalCoinAge < nCoinAgeReq)
{
results.push_back(Pair("NOTE!", "Coins must have a maturity of at least 5 confirms for your coin*age to count. (See current depth in coin control)."));
}
if (nTotalCoinAge < nCoinAgeReq || nTotalCoinAge == 0)
{
results.push_back(Pair("WARNING!", "BiblePay requires staking collateral to be stored in your Christian-Public-Key (External Purse) to be available for GSC transmissions. You currently do not have enough coin age in your external purse. This means your PODC reward will be reduced to a commensurate amount of RAC. Please read our PODC 2.0 guide about sending bankroll notes to yourself. "));
}
results.push_back(Pair("coin_age_required", nCoinAgeReq));
results.push_back(Pair("wcg_id", r.id));
results.push_back(Pair("rac", r.rac));
}
}
else if (sItem == "navdsql")
{
BBPResult b = GetDecentralizedURL();
results.push_back(Pair("data", b.Response));
results.push_back(Pair("error(s)", b.ErrorCode));
}
else if (sItem == "analyze")
{
if (request.params.size() != 3)
throw std::runtime_error("You must specify height and nickname.");
int nHeight = cdbl(request.params[1].get_str(), 0);
std::string sNickName = request.params[2].get_str();
WriteCache("analysis", "user", sNickName, GetAdjustedTime());
UniValue p = GetProminenceLevels(nHeight + BLOCKS_PER_DAY, "");
std::string sData1 = ReadCache("analysis", "data_1");
std::string sData2 = ReadCache("analysis", "data_2");
results.push_back(Pair("Campaign", "Totals"));
std::vector<std::string> v = Split(sData2.c_str(), "\n");
for (int i = 0; i < (int)v.size(); i++)
{
std::string sRow = v[i];
results.push_back(Pair(RoundToString(i, 0), sRow));
}
results.push_back(Pair("Campaign", "Points"));
v = Split(sData1.c_str(), "\n");
for (int i = 0; i < (int)v.size(); i++)
{
std::string sRow = v[i];
results.push_back(Pair(RoundToString(i, 0), sRow));
}
}
else if (sItem == "debugtool1")
{
std::string sBlock = request.params[1].get_str();
int nHeight = (int)cdbl(sBlock,0);
if (nHeight < 0 || nHeight > chainActive.Tip()->nHeight)
throw std::runtime_error("Block number out of range.");
CBlockIndex* pblockindex = FindBlockByHeight(nHeight);
const Consensus::Params& consensusParams = Params().GetConsensus();
double dDiff = GetDifficulty(pblockindex);
double dDiffThreshhold = fProd ? 1000 : 1;
results.push_back(Pair("diff", dDiff));
bool f1 = dDiff > dDiffThreshhold;
results.push_back(Pair("f1", f1));
CBlock block;
ReadBlockFromDisk(block, pblockindex, consensusParams);
double nMinRequiredABNWeight = GetSporkDouble("requiredabnweight", 0);
double nABNHeight = GetSporkDouble("abnheight", 0);
results.push_back(Pair("abnheight", nABNHeight));
results.push_back(Pair("fprod", fProd));
results.push_back(Pair("consensusABNHeight", consensusParams.ABNHeight));
bool f10 = (nABNHeight > 0 && nHeight > consensusParams.ABNHeight && nHeight > nABNHeight && nMinRequiredABNWeight > 0);
results.push_back(Pair("f10_abnheight", f10));
results.push_back(Pair("LateBlock", LateBlock(block, pblockindex, 60)));
bool fLBI = LateBlockIndex(pblockindex, 60);
results.push_back(Pair("LBI", fLBI));
results.push_back(Pair("abnreqweight", nMinRequiredABNWeight));
results.push_back(Pair("abnheight", nABNHeight));
}
else if (sItem == "dailysponsorshipcap")
{
if (request.params.size() != 2)
throw std::runtime_error("You must specify the charity name.");
std::string sCharity = request.params[1].get_str();
if (sCharity != "cameroon-one" && sCharity != "kairos")
throw std::runtime_error("Invalid charity name.");
double nCap = GetProminenceCap(sCharity, 1333, .50);
results.push_back(Pair("cap", nCap));
}
else if (sItem == "cleantips")
{
if (chainActive.Tip()->nHeight < 2000)
throw JSONRPCError(RPC_TYPE_ERROR, "Please sync first.");
std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;
BOOST_FOREACH(const PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex)
{
if (item.second != NULL) setTips.insert(item.second);
}
BOOST_FOREACH(const PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex)
{
if (item.second != NULL)
{
if (item.second->pprev != NULL)
{
const CBlockIndex* pprev = item.second->pprev;
if (pprev)
setTips.erase(pprev);
}
}
}
BOOST_FOREACH(const CBlockIndex* block, setTips)
{
if (block->nHeight < (chainActive.Tip()->nHeight - 1000))
{
const CBlockIndex* pindexFork = chainActive.FindFork(block);
const CBlockIndex* pcopy = block;
while (true)
{
if (!pcopy->pprev || pcopy->pprev == pindexFork)
break;
mapBlockIndex.erase(pcopy->GetBlockHash());
pcopy = pcopy->pprev;
results.push_back(Pair("erasing", pcopy->nHeight));
}
}
}
}
else if (sItem == "vectoroffiles")
{
std::string dirPath = "/testbed";
std::vector<std::string> skipList;
std::vector<std::string> g = GetVectorOfFilesInDirectory(dirPath, skipList);
// Iterate over the vector and print all files
for (auto str : g)
{
results.push_back(Pair("File", str));
}
}
else if (sItem == "testhttps")
{
std::string sURL = "https://" + GetSporkValue("bms");
std::string sRestfulURL = "BMS/LAST_MANDATORY_VERSION";
std::string sResponse = BiblepayHTTPSPost(false, 0, "", "", "", sURL, sRestfulURL, 443, "", 25, 10000, 1);
results.push_back(Pair(sRestfulURL, sResponse));
}
else if (sItem == "sendmessage")
{
std::string sError = "You must specify type, key, value: IE 'exec sendmessage PRAYER mother Please_pray_for_my_mother._She_has_this_disease.'";
if (request.params.size() != 4)
throw std::runtime_error(sError);
std::string sType = request.params[1].get_str();
std::string sPrimaryKey = request.params[2].get_str();
std::string sValue = request.params[3].get_str();
if (sType.empty() || sPrimaryKey.empty() || sValue.empty())
throw std::runtime_error(sError);
std::string sResult = SendBlockchainMessage(sType, sPrimaryKey, sValue, 1, false, "", sError);
results.push_back(Pair("Sent", sValue));
results.push_back(Pair("TXID", sResult));
results.push_back(Pair("Error", sError));
}
else if (sItem == "getgovlimit")
{
const Consensus::Params& consensusParams = Params().GetConsensus();
int nBits = 486585255;
int nHeight = cdbl(request.params[1].get_str(), 0);
CAmount nLimit = CSuperblock::GetPaymentsLimit(nHeight, false);
CAmount nReward = GetBlockSubsidy(nBits, nHeight, consensusParams, false);
CAmount nRewardGov = GetBlockSubsidy(nBits, nHeight, consensusParams, true);
CAmount nSanc = GetMasternodePayment(nHeight, nReward);
results.push_back(Pair("Limit", (double)nLimit/COIN));
results.push_back(Pair("Subsidy", (double)nReward/COIN));
results.push_back(Pair("Sanc", (double)nSanc/COIN));
// Evo Audit: 14700 gross, @98400=13518421, @129150=13225309/Daily = @129170=1013205
results.push_back(Pair("GovernanceSubsidy", (double)nRewardGov/COIN));
// Dynamic Whale Staking
double dTotalWhalePayments = 0;
std::vector<WhaleStake> dws = GetPayableWhaleStakes(nHeight, dTotalWhalePayments);
results.push_back(Pair("DWS payables owed", dTotalWhalePayments));
results.push_back(Pair("DWS quantity", (int)dws.size()));
// GovLimit total
int nLastSuperblock = 0;
int nNextSuperblock = 0;
GetGovSuperblockHeights(nNextSuperblock, nLastSuperblock);
nLastSuperblock += 20;
CBlockIndex* pindex = FindBlockByHeight(nLastSuperblock);
CBlock block;
// Todo: Move this report to a dedicated area
if (false)
{
results.push_back(Pair("GetGovLimit", "Report v1.1"));
for (int nHeight = nLastSuperblock; nHeight > 0; nHeight -= BLOCKS_PER_DAY)
{
CBlockIndex* pindex = FindBlockByHeight(nHeight);
if (pindex)
{
CAmount nTotal = 0;
if (ReadBlockFromDisk(block, pindex, consensusParams))
{
for (unsigned int i = 0; i < block.vtx[0]->vout.size(); i++)
{
nTotal += block.vtx[0]->vout[i].nValue;
}
if (nTotal/COIN > MAX_BLOCK_SUBSIDY && block.vtx[0]->vout.size() < 7)
{
std::string sRow = "Total: " + RoundToString(nTotal/COIN, 2) + ", Size: " + RoundToString(block.vtx.size(), 0);
results.push_back(Pair(RoundToString(nHeight, 0), sRow));
}
}
}
}
}
}
else if (sItem == "hexblocktojson")
{
std::string sHex = request.params[1].get_str();
CBlock block;
if (!DecodeHexBlk(block, sHex))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
return blockToJSON(block, NULL, true);
}
else if (sItem == "hextxtojson")
{
std::string sHex = request.params[1].get_str();
CMutableTransaction tx;
if (!DecodeHexTx(tx, request.params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Tx decode failed");
UniValue objTx(UniValue::VOBJ);
TxToJSON(tx, uint256(), objTx);
results.push_back(objTx);
}
else if (sItem == "hextxtojson2")
{
std::string sHex = request.params[1].get_str();
CMutableTransaction tx;
DecodeHexTx(tx, request.params[0].get_str());
UniValue objTx(UniValue::VOBJ);
TxToJSON(tx, uint256(), objTx);
results.push_back(objTx);
}
else if (sItem == "blocktohex")
{
std::string sBlock = request.params[1].get_str();
int nHeight = (int)cdbl(sBlock,0);
if (nHeight < 0 || nHeight > chainActive.Tip()->nHeight)
throw std::runtime_error("Block number out of range.");
CBlockIndex* pblockindex = FindBlockByHeight(nHeight);
if (pblockindex==NULL)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlock block;
const Consensus::Params& consensusParams = Params().GetConsensus();
ReadBlockFromDisk(block, pblockindex, consensusParams);
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
ssBlock << block;
std::string sBlockHex = HexStr(ssBlock.begin(), ssBlock.end());
CTransaction txCoinbase;
std::string sTxCoinbaseHex = EncodeHexTx(*block.vtx[0]);
results.push_back(Pair("blockhex", sBlockHex));
results.push_back(Pair("txhex", sTxCoinbaseHex));
}
else if (sItem == "getarg")
{
// Allows user to display a configuration value (useful if you are not sure if you entered a config value in your file)
std::string sArg = request.params[1].get_str();
std::string sValue = GetArg("-" + sArg, "");
results.push_back(Pair("arg v2.0", sValue));
}
else if (sItem == "createpurse")
{
std::string sError;
// Dont even try unless unlocked
// Note: We automatically do this in 'exec associate'. This is useful if someone missed it.
bool fCreated = CreateExternalPurse(sError);
if (!sError.empty())
results.push_back(Pair("Error", sError));
else
{
std::string sEFA = DefaultRecAddress("Christian-Public-Key");
results.push_back(Pair("Status", "Successful"));
results.push_back(Pair("Address", sEFA));
std::string sPubFile = GetEPArg(true);
results.push_back(Pair("PubFundAddress", sPubFile));
results.push_back(Pair("Remember", "Now you must fund your external address with enough capital to make daily PODC/GSC stakes."));
}
}
else if (sItem == "testdp")
{
BBPResult b = DSQL_ReadOnlyQuery("BMS/BBP_PRICE_QUOTE");
results.push_back(Pair("PQ", b.Response));
b = DSQL_ReadOnlyQuery("BMS/SANCTUARY_HEALTH_REQUEST");
results.push_back(Pair("HR", b.Response));
UpdateHealthInformation(1);
}
else if (sItem == "getwcgmemberid")
{
if (request.params.size() < 3)
throw std::runtime_error("Please specify exec wcg_user_name wcg_verification_code.");
std::string sUN = request.params[1].get_str();
std::string sVC = request.params[2].get_str();
double nPoints = 0;
int nID = GetWCGMemberID(sUN, sVC, nPoints);
results.push_back(Pair("ID", nID));
}
else if (sItem == "dws")
{
// Expirimental Feature: Dynamic Whale Stake
// exec dws amount duration_in_days 0=test/1=authorize
const Consensus::Params& consensusParams = Params().GetConsensus();
std::string sHowey = "By typing I_AGREE in uppercase, you agree to the following conditions:"
"\n1. I AM MAKING A SELF DIRECTED DECISION TO BURN THIS BIBLEPAY, AND DO NOT EXPECT AN INCREASE IN VALUE."
"\n2. I HAVE NOT BEEN PROMISED A PROFIT, AND BIBLEPAY IS NOT PROMISING ME ANY HOPES OF PROFIT IN ANY WAY."
"\n3. BIBLEPAY IS NOT ACTING AS A COMMON ENTERPRISE OR THIRD PARTY IN THIS ENDEAVOR."
"\n4. I HOLD BIBLEPAY AS A HARMLESS UTILITY."
"\n5. I REALIZE I AM RISKING 100% OF MY CRYPTO-HOLDINGS BY BURNING IT, AND BIBLEPAY IS NOT OBLIGATED TO REFUND MY CRYPTO-HOLDINGS OR GIVE ME ANY REWARD.";
std::string sHelp = "You must specify exec dws amount duration_in_days 0=test/I_AGREE=Authorize [optional=SPECIFIC_STAKE_RETURN_ADDRESS (If Left Empty, we will send your stake back to your CPK)].\n" + sHowey;
if (request.params.size() != 4 && request.params.size() != 5)
throw std::runtime_error(sHelp.c_str());
double nAmt = cdbl(request.params[1].get_str(), 2);
double nDuration = cdbl(request.params[2].get_str(), 0);
std::string sAuthorize = request.params[3].get_str();
std::string sReturnAddress = DefaultRecAddress("Christian-Public-Key");
std::string sCPK = DefaultRecAddress("Christian-Public-Key");
CBitcoinAddress returnAddress(sReturnAddress);
if (request.params.size() == 5)
{
sReturnAddress = request.params[4].get_str();
returnAddress = CBitcoinAddress(sReturnAddress);
}
if (!returnAddress.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Biblepay return address: ") + sReturnAddress);
if (nAmt < 100 || nAmt > 1000000)
throw std::runtime_error("Sorry, amount must be between 100 BBP and 1,000,000 BBP.");
if (nDuration < 7 || nDuration > 365)
throw std::runtime_error("Sorry, duration must be between 7 days and 365 days.");
if (fProd && chainActive.Tip()->nHeight < consensusParams.PODC2_CUTOVER_HEIGHT)
throw std::runtime_error("Sorry, this feature is not available yet. Please wait until the mandatory upgrade height passes. ");
double nTotalStakes = GetWhaleStakesInMemoryPool(sCPK);
if (nTotalStakes > 256000)
throw std::runtime_error("Sorry, you currently have " + RoundToString(nTotalStakes, 2) + "BBP in whale stakes pending at height "
+ RoundToString(chainActive.Tip()->nHeight, 0) + ". Please wait until the current block passes before issuing a new DWS. ");
results.push_back(Pair("Staking Amount", nAmt));
results.push_back(Pair("Duration", nDuration));
int64_t nStakeTime = GetAdjustedTime();
int64_t nReclaimTime = (86400 * nDuration) + nStakeTime;
WhaleMetric wm = GetWhaleMetrics(chainActive.Tip()->nHeight, true);
results.push_back(Pair("Reclaim Date", TimestampToHRDate(nReclaimTime)));
results.push_back(Pair("Return Address", sReturnAddress));
results.push_back(Pair("DWU", RoundToString(GetDWUBasedOnMaturity(nDuration, wm.DWU) * 100, 4)));
std::string sPK = "DWS-" + sReturnAddress + "-" + RoundToString(nReclaimTime, 0);
std::string sPayload = "<MT>DWS</MT><MK>" + sPK + "</MK><MV><dws><returnaddress>" + sReturnAddress + "</returnaddress><burnheight>"
+ RoundToString(chainActive.Tip()->nHeight, 0)
+ "</burnheight><cpk>" + sCPK + "</cpk><burntime>" + RoundToString(GetAdjustedTime(), 0) + "</burntime><dwu>" + RoundToString(wm.DWU, 4) + "</dwu><duration>"
+ RoundToString(nDuration, 0) + "</duration><duedate>" + TimestampToHRDate(nReclaimTime) + "</duedate><amount>" + RoundToString(nAmt, 2) + "</amount></dws></MV>";
CBitcoinAddress toAddress(consensusParams.BurnAddress);
if (!toAddress.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Burn-To Address: ") + consensusParams.BurnAddress);
if (sAuthorize == "I_AGREE")
{
bool fSubtractFee = false;
bool fInstantSend = false;
std::string sError;
CWalletTx wtx;
// Dry Run step 1:
std::vector<CRecipient> vecDryRun;
int nChangePosRet = -1;
CScript scriptDryRun = GetScriptForDestination(toAddress.Get());
CAmount nSend = nAmt * COIN;
CRecipient recipientDryRun = {scriptDryRun, nSend, false, fSubtractFee};
vecDryRun.push_back(recipientDryRun);
double dMinCoinAge = 1;
CAmount nFeeRequired = 0;
CReserveKey reserveKey(pwalletMain);
bool fSent = pwalletMain->CreateTransaction(vecDryRun, wtx, reserveKey, nFeeRequired, nChangePosRet, sError, NULL, true,
ALL_COINS, fInstantSend, 0, sPayload, dMinCoinAge, 0, 0, "");
// Verify the transaction first:
std::string sError2;
bool fSent2 = VerifyDynamicWhaleStake(wtx.tx, sError2);
sError += sError2;
if (!fSent || !sError.empty())
{
results.push_back(Pair("Error (Not Sent)", sError));
}
else
{
CValidationState state;
if (!pwalletMain->CommitTransaction(wtx, reserveKey, g_connman.get(), state, NetMsgType::TX))
{
throw JSONRPCError(RPC_WALLET_ERROR, "Whale-Stake-Commit failed.");
}
results.push_back(Pair("Results", "Burn was successful. You will receive your original BBP back on the Reclaim Date, plus the stake reward. Please give the wallet an extra 48 hours after the reclaim date to process the return stake. "));
results.push_back(Pair("TXID", wtx.GetHash().GetHex()));
}
}
else
{
results.push_back(Pair("Test Mode", sHowey));
}
}
else if (sItem == "dwsquote")
{
if (request.params.size() != 1 && request.params.size() != 2 && request.params.size() != 3)
throw std::runtime_error("You must specify exec dwsquote [optional 1=my whale stakes only, 2=all whale stakes] [optional 1=Include Paid/Unpaid, 2=Include Unpaid only (default)].");
std::string sCPK = DefaultRecAddress("Christian-Public-Key");
double dDetails = 0;
if (request.params.size() > 1)
dDetails = cdbl(request.params[1].get_str(), 0);
double dPaid = 2;
if (request.params.size() > 2)
dPaid = cdbl(request.params[2].get_str(), 0);
if (dDetails == 1 || dDetails == 2)
{
std::vector<WhaleStake> w = GetDWS(true);
results.push_back(Pair("Total DWS Quantity", (int)w.size()));
for (int i = 0; i < w.size(); i++)
{
WhaleStake ws = w[i];
bool fIncForPayment = (!ws.paid && dPaid == 2) || (dPaid == 1);
if (ws.found && fIncForPayment && ((dDetails == 2) || (dDetails==1 && ws.CPK == sCPK)))
{
// results.push_back(Pair("Return Address", ws.ReturnAddress));
int nRewardHeight = GetWhaleStakeSuperblockHeight(ws.MaturityHeight);
std::string sRow = "Burned: " + RoundToString(ws.Amount, 2) + ", Reward: " + RoundToString(ws.TotalOwed, 2) + ", DWU: "
+ RoundToString(ws.ActualDWU*100, 4) + ", Duration: " + RoundToString(ws.Duration, 0) + ", BurnHeight: " + RoundToString(ws.BurnHeight, 0)
+ ", RewardHeight: " + RoundToString(nRewardHeight, 0) + " [" + RoundToString(ws.MaturityHeight, 0) + "], MaturityDate: " + TimestampToHRDate(ws.MaturityTime);
std::string sKey = ws.CPK + " " + RoundToString(i+1, 0);
// ToDo: Add parameter to show the return_to_address if user desires it
results.push_back(Pair(sKey, sRow));
}
}
}
results.push_back(Pair("Metrics", "v1.1"));
// Call out for Whale Metrics
WhaleMetric wm = GetWhaleMetrics(chainActive.Tip()->nHeight, true);
results.push_back(Pair("Total Future Commitments", wm.nTotalFutureCommitments));
results.push_back(Pair("Total Gross Future Commitments", wm.nTotalGrossFutureCommitments));
results.push_back(Pair("Total Commitments Due Today", wm.nTotalCommitmentsDueToday));
results.push_back(Pair("Total Gross Commitments Due Today", wm.nTotalGrossCommitmentsDueToday));
results.push_back(Pair("Total Burns Today", wm.nTotalBurnsToday));
results.push_back(Pair("Total Gross Burns Today", wm.nTotalGrossBurnsToday));
results.push_back(Pair("Total Monthly Commitments", wm.nTotalMonthlyCommitments));
results.push_back(Pair("Total Gross Monthly Commitments", wm.nTotalGrossMonthlyCommitments));
results.push_back(Pair("Total Annual Reward", wm.nTotalAnnualReward));
results.push_back(Pair("Saturation Percent Annual", RoundToString(wm.nSaturationPercentAnnual * 100, 8)));
results.push_back(Pair("Saturation Percent Monthly", RoundToString(wm.nSaturationPercentMonthly * 100, 8)));
results.push_back(Pair("30 day DWU", RoundToString(GetDWUBasedOnMaturity(30, wm.DWU) * 100, 4)));
results.push_back(Pair("90 day DWU", RoundToString(GetDWUBasedOnMaturity(90, wm.DWU) * 100, 4)));
results.push_back(Pair("180 day DWU", RoundToString(GetDWUBasedOnMaturity(180, wm.DWU) * 100, 4)));
results.push_back(Pair("365 day DWU", RoundToString(GetDWUBasedOnMaturity(365, wm.DWU) * 100, 4)));
}
else if (sItem == "boinc1")
{
// This command is only for dev debugging; will be removed soon.
// Probe the external purse for the necessary coins
CAmount nMatched = 0;
CAmount nTotal = 0;
std::string sEFA = DefaultRecAddress("Christian-Public-Key");
std::vector<COutput> cCoins = pwalletMain->GetExternalPurseBalance(sEFA, 1*COIN, nMatched, nTotal);
// results.push_back(Pair("purse size", cCoins.size()));
results.push_back(Pair("purse amount matched", (double)nMatched/COIN));
results.push_back(Pair("purse total", (double)nTotal/COIN));
bool fSubtractFee = false;
bool fInstantSend = false;
std::string sError;
CWalletTx wtx;
std::string s1 = "<DATA/>";
std::string sPubFile = GetEPArg(true);
if (sPubFile.empty())
{
results.push_back(Pair("Error", "pubkey not accessible."));
}
else
{
CBitcoinAddress cbEFA;
if (!cbEFA.SetString(sEFA))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to use external purse address.");
double dMinCoinAge = 5;
bool fSent = FundWithExternalPurse(sError, cbEFA.Get(), 1 * COIN, fSubtractFee, wtx, fInstantSend, nMatched, s1, dMinCoinAge, sEFA);
if (fSent)
results.push_back(Pair("txid", wtx.GetHash().GetHex()));
if (!fSent)
results.push_back(Pair("error", sError));
}
}
else if (sItem == "lresearchers")
{
std::map<std::string, Researcher> r = GetPayableResearchers();
BOOST_FOREACH(const PAIRTYPE(const std::string, Researcher)& myResearcher, r)
{
results.push_back(Pair("cpid", myResearcher.second.cpid));
results.push_back(Pair("rac", myResearcher.second.rac));
results.push_back(Pair("nickname", myResearcher.second.nickname));
}
}
else if (sItem == "pobh")
{
std::string sInput = request.params[1].get_str();
double d1 = cdbl(request.params[2].get_str(), 0);
uint256 hSource = uint256S("0x" + sInput);
uint256 h = BibleHashDebug(hSource, d1 == 1);
results.push_back(Pair("in-hash", hSource.GetHex()));
results.push_back(Pair("out-hash", h.GetHex()));
}
else if (sItem == "xnonce")
{
const Consensus::Params& consensusParams = Params().GetConsensus();
int nHeight = consensusParams.ANTI_GPU_HEIGHT + 1;
double dNonce = cdbl(request.params[1].get_str(), 0);
bool fNonce = CheckNonce(true, (int)dNonce, nHeight, 1, 301, consensusParams);
results.push_back(Pair("result", fNonce));
}
else if (sItem == "xbbp")
{
std::string p1 = request.params[1].get_str();
uint256 h1 = uint256S("0x" + p1);
results.push_back(Pair("uint256_h1", h1.GetHex()));
bool f7000 = false;
bool f8000 = false;
bool f9000 = false;
bool fTitheBlocksActive = false;
int nHeight = 1;
GetMiningParams(nHeight, f7000, f8000, f9000, fTitheBlocksActive);
int64_t nTime = 10;
int64_t nPrevTime = 1;
int64_t nPrevHeight = 1;
int64_t nNonce = 10;
bool bMining = true;
const Consensus::Params& consensusParams = Params().GetConsensus();
uint256 uh1_out = BibleHashClassic(h1, nTime, nPrevTime, bMining, nPrevHeight, NULL, false, f7000, f8000, f9000, fTitheBlocksActive, nNonce, consensusParams);
results.push_back(Pair("h1_out", uh1_out.GetHex()));
}
else if (sItem == "XBBP")
{
std::string smd1 = "BiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePayBiblePay";
uint256 hMax = uint256S("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");
arith_uint256 aMax = UintToArith256(hMax);
arith_uint256 aMax420 = aMax * 420;
uint256 hMaxResult = ArithToUint256(aMax420);
results.push_back(Pair("hMax", hMax.GetHex()));
results.push_back(Pair("hMaxResult", hMaxResult.GetHex()));
arith_uint256 bnDiff = aMax - aMax420;
uint256 hDiff = ArithToUint256(bnDiff);
results.push_back(Pair("bnDiff", hDiff.GetHex()));
arith_uint256 aDiv = aMax420 / 1260;
uint256 hDivResult = ArithToUint256(aDiv);
results.push_back(Pair("bnDivision", hDivResult.GetHex()));
std::vector<unsigned char> vch1 = std::vector<unsigned char>(smd1.begin(), smd1.end());
std::string smd2="biblepay";
std::vector<unsigned char> vch2 = std::vector<unsigned char>(smd2.begin(), smd2.end());
uint256 hSMD10 = Sha256001(1,170001,smd2);
uint256 h1 = SerializeHash(vch1);
uint256 hSMD2 = SerializeHash(vch2);
uint256 h2 = HashBiblePay(vch1.begin(),vch1.end());
uint256 h3 = HashBiblePay(h2.begin(),h2.end());
uint256 h4 = HashBiblePay(h3.begin(),h3.end());
uint256 h5 = HashBiblePay(h4.begin(),h4.end());
uint256 h00 = HashX11(vch1.begin(), vch1.end());
uint256 hGroestl = HashGroestl(vch1.begin(), vch1.end());
uint256 hBiblepayIsolated = HashBiblepayIsolated(vch1.begin(), vch1.end());
uint256 hBiblePayTest = HashBiblePay(vch1.begin(), vch1.end());
bool f7000 = false;
bool f8000 = false;
bool f9000 = false;
bool fTitheBlocksActive = false;
int nHeight = 1;
GetMiningParams(nHeight, f7000, f8000, f9000, fTitheBlocksActive);
f7000 = false;
f8000 = false;
f9000 = false;
fTitheBlocksActive = false;
int64_t nTime = 3;
int64_t nPrevTime = 2;
int64_t nPrevHeight = 1;
int64_t nNonce = 10;
uint256 inHash = uint256S("0x1234");
bool bMining = true;
const Consensus::Params& consensusParams = Params().GetConsensus();
uint256 uBibleHash = BibleHashClassic(inHash, nTime, nPrevTime, bMining, nPrevHeight, NULL, false, f7000, f8000, f9000, fTitheBlocksActive, nNonce, consensusParams);
std::vector<unsigned char> vchPlaintext = std::vector<unsigned char>(inHash.begin(), inHash.end());
std::vector<unsigned char> vchCiphertext;
BibleEncryptE(vchPlaintext, vchCiphertext);
/* Try to discover AES256 empty encryption value */
uint256 hBlank = uint256S("0x0");
std::vector<unsigned char> vchBlank = std::vector<unsigned char>(hBlank.begin(), hBlank.end());
std::vector<unsigned char> vchBlankEncrypted;
BibleEncryptE(vchBlank, vchBlankEncrypted);
std::string sBlankBase64 = EncodeBase64(VectToString(vchBlankEncrypted));
results.push_back(Pair("Blank_Base64", sBlankBase64));
std::string sCipher64 = EncodeBase64(VectToString(vchCiphertext));
std::string sBibleMD5 = BibleMD5(sCipher64);
std::string sBibleMD51234 = BibleMD5("1234");
results.push_back(Pair("h_sha256", hSMD10.GetHex()));
results.push_back(Pair("AES_Cipher64", sCipher64));
results.push_back(Pair("AES_BibleMD5", sBibleMD5));
results.push_back(Pair("Plain_BibleMD5_1234", sBibleMD51234));
results.push_back(Pair("biblehash", uBibleHash.GetHex()));
results.push_back(Pair("h00_biblepay", h00.GetHex()));
results.push_back(Pair("h_Groestl", hGroestl.GetHex()));
results.push_back(Pair("h_BiblePayIsolated", hBiblepayIsolated.GetHex()));
results.push_back(Pair("h_BiblePayTest", hBiblePayTest.GetHex()));
results.push_back(Pair("h1",h1.GetHex()));
results.push_back(Pair("h2",h2.GetHex()));
results.push_back(Pair("hSMD2", hSMD2.GetHex()));
results.push_back(Pair("h3",h3.GetHex()));
results.push_back(Pair("h4",h4.GetHex()));
results.push_back(Pair("h5",h5.GetHex()));
uint256 startHash = uint256S("0x010203040506070809101112");
}
else
{
results.push_back(Pair("Error", "Command not found"));
}
return results;
}
UniValue reconsiderblock(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"reconsiderblock \"blockhash\"\n"
"\nRemoves invalidity status of a block and its descendants, reconsider them for activation.\n"
"This can be used to undo the effects of invalidateblock.\n"
"\nArguments:\n"
"1. \"blockhash\" (string, required) the hash of the block to reconsider\n"
"\nResult:\n"
"\nExamples:\n"
+ HelpExampleCli("reconsiderblock", "\"blockhash\"")
+ HelpExampleRpc("reconsiderblock", "\"blockhash\"")
);
std::string strHash = request.params[0].get_str();
uint256 hash(uint256S(strHash));
{
LOCK(cs_main);
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlockIndex* pblockindex = mapBlockIndex[hash];
ResetBlockFailureFlags(pblockindex);
}
CValidationState state;
ActivateBestChain(state, Params());
if (!state.IsValid()) {
throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason());
}
return NullUniValue;
}
UniValue getspecialtxes(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 5)
throw std::runtime_error(
"getspecialtxes \"blockhash\" ( type count skip verbosity ) \n"
"Returns an array of special transactions found in the specified block\n"
"\nIf verbosity is 0, returns tx hash for each transaction.\n"
"If verbosity is 1, returns hex-encoded data for each transaction.\n"
"If verbosity is 2, returns an Object with information for each transaction.\n"
"\nArguments:\n"
"1. \"blockhash\" (string, required) The block hash\n"
"2. type (numeric, optional, default=-1) Filter special txes by type, -1 means all types\n"
"3. count (numeric, optional, default=10) The number of transactions to return\n"
"4. skip (numeric, optional, default=0) The number of transactions to skip\n"
"5. verbosity (numeric, optional, default=0) 0 for hashes, 1 for hex-encoded data, and 2 for json object\n"
"\nResult (for verbosity = 0):\n"
"[\n"
" \"txid\" : \"xxxx\", (string) The transaction id\n"
"]\n"
"\nResult (for verbosity = 1):\n"
"[\n"
" \"data\", (string) A string that is serialized, hex-encoded data for the transaction\n"
"]\n"
"\nResult (for verbosity = 2):\n"
"[ (array of Objects) The transactions in the format of the getrawtransaction RPC.\n"
" ...,\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getspecialtxes", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"")
+ HelpExampleRpc("getspecialtxes", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"")
);
LOCK(cs_main);
std::string strHash = request.params[0].get_str();
uint256 hash(uint256S(strHash));
int nTxType = -1;
if (request.params.size() > 1) {
nTxType = request.params[1].get_int();
}
int nCount = 10;
if (request.params.size() > 2) {
nCount = request.params[2].get_int();
if (nCount < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
}
int nSkip = 0;
if (request.params.size() > 3) {
nSkip = request.params[3].get_int();
if (nSkip < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative skip");
}
int nVerbosity = 0;
if (request.params.size() > 4) {
nVerbosity = request.params[4].get_int();
if (nVerbosity < 0 || nVerbosity > 2) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Verbosity must be in range 0..2");
}
}
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hash];
if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0)
throw JSONRPCError(RPC_INTERNAL_ERROR, "Block not available (pruned data)");
if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus()))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
int nTxNum = 0;
UniValue result(UniValue::VARR);
for(const auto& tx : block.vtx)
{
if (tx->nVersion != 3 || tx->nType == TRANSACTION_NORMAL // ensure it's in fact a special tx
|| (nTxType != -1 && tx->nType != nTxType)) { // ensure special tx type matches filter, if given
continue;
}
nTxNum++;
if (nTxNum <= nSkip) continue;
if (nTxNum > nSkip + nCount) break;
switch (nVerbosity)
{
case 0 : result.push_back(tx->GetHash().GetHex()); break;
case 1 : result.push_back(EncodeHexTx(*tx)); break;
case 2 :
{
UniValue objTx(UniValue::VOBJ);
TxToJSON(*tx, uint256(), objTx);
result.push_back(objTx);
break;
}
default : throw JSONRPCError(RPC_INTERNAL_ERROR, "Unsupported verbosity");
}
}
return result;
}
static const CRPCCommand commands[] =
{ // category name actor (function) okSafe argNames
// --------------------- ------------------------ ----------------------- ------ ----------
{ "blockchain", "getblockchaininfo", &getblockchaininfo, true, {} },
{ "blockchain", "getbestblockhash", &getbestblockhash, true, {} },
{ "blockchain", "getblockcount", &getblockcount, true, {} },
{ "blockchain", "getblock", &getblock, true, {"blockhash","verbosity|verbose"} },
{ "blockchain", "getblockhashes", &getblockhashes, true, {"high","low"} },
{ "blockchain", "getblockhash", &getblockhash, true, {"height"} },
{ "blockchain", "getblockheader", &getblockheader, true, {"blockhash","verbose"} },
{ "blockchain", "getblockheaders", &getblockheaders, true, {"blockhash","count","verbose"} },
{ "blockchain", "getchaintips", &getchaintips, true, {"count","branchlen"} },
{ "blockchain", "getdifficulty", &getdifficulty, true, {} },
{ "blockchain", "getmempoolancestors", &getmempoolancestors, true, {"txid","verbose"} },
{ "blockchain", "getmempooldescendants", &getmempooldescendants, true, {"txid","verbose"} },
{ "blockchain", "getmempoolentry", &getmempoolentry, true, {"txid"} },
{ "blockchain", "getmempoolinfo", &getmempoolinfo, true, {} },
{ "blockchain", "getrawmempool", &getrawmempool, true, {"verbose"} },
{ "blockchain", "getspecialtxes", &getspecialtxes, true, {"blockhash", "type", "count", "skip", "verbosity"} },
{ "blockchain", "gettxout", &gettxout, true, {"txid","n","include_mempool"} },
{ "blockchain", "gettxoutsetinfo", &gettxoutsetinfo, true, {} },
{ "blockchain", "pruneblockchain", &pruneblockchain, true, {"height"} },
{ "blockchain", "verifychain", &verifychain, true, {"checklevel","nblocks"} },
{ "blockchain", "preciousblock", &preciousblock, true, {"blockhash"} },
/* Not shown in help */
{ "hidden", "exec", &exec, true, {"1","2","3","4","5","6","7"} },
{ "hidden", "invalidateblock", &invalidateblock, true, {"blockhash"} },
{ "hidden", "reconsiderblock", &reconsiderblock, true, {"blockhash"} },
{ "hidden", "waitfornewblock", &waitfornewblock, true, {"timeout"} },
{ "hidden", "waitforblock", &waitforblock, true, {"blockhash","timeout"} },
{ "hidden", "waitforblockheight", &waitforblockheight, true, {"height","timeout"} },
};
void RegisterBlockchainRPCCommands(CRPCTable &t)
{
for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
t.appendCommand(commands[vcidx].name, &commands[vcidx]);
}
|
/*
* 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.
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/BitOps.hpp>
#include <xercesc/util/TranscodingException.hpp>
#include <xercesc/util/XML256TableTranscoder.hpp>
#include <xercesc/util/XMLString.hpp>
#include <string.h>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// XML256TableTranscoder: Public Destructor
// ---------------------------------------------------------------------------
XML256TableTranscoder::~XML256TableTranscoder()
{
// We don't own the tables, we just reference them
}
// ---------------------------------------------------------------------------
// XML256TableTranscoder: Implementation of the transcoder API
// ---------------------------------------------------------------------------
XMLSize_t
XML256TableTranscoder::transcodeFrom(const XMLByte* const srcData
, const XMLSize_t srcCount
, XMLCh* const toFill
, const XMLSize_t maxChars
, XMLSize_t& bytesEaten
, unsigned char* const charSizes)
{
//
// Calculate the max chars we can do here. Its the lesser of the
// max output chars and the number of chars in the source.
//
const XMLSize_t countToDo = srcCount < maxChars ? srcCount : maxChars;
//
// Loop through the count we have to do and map each char via the
// lookup table.
//
const XMLByte* srcPtr = srcData;
const XMLByte* endPtr = (srcPtr + countToDo);
XMLCh* outPtr = toFill;
while (srcPtr < endPtr)
{
const XMLCh uniCh = fFromTable[*srcPtr++];
if (uniCh != 0xFFFF)
{
*outPtr++ = uniCh;
continue;
}
}
// Set the bytes eaten
bytesEaten = countToDo;
// Set the character sizes to the fixed size
memset(charSizes, 1, countToDo);
// Return the chars we transcoded
return countToDo;
}
XMLSize_t
XML256TableTranscoder::transcodeTo( const XMLCh* const srcData
, const XMLSize_t srcCount
, XMLByte* const toFill
, const XMLSize_t maxBytes
, XMLSize_t& charsEaten
, const UnRepOpts options)
{
//
// Calculate the max chars we can do here. Its the lesser of the
// max output chars and the number of chars in the source.
//
const XMLSize_t countToDo = srcCount < maxBytes ? srcCount : maxBytes;
//
// Loop through the count we have to do and map each char via the
// lookup table.
//
const XMLCh* srcPtr = srcData;
const XMLCh* endPtr = (srcPtr + countToDo);
XMLByte* outPtr = toFill;
XMLByte nextOut;
while (srcPtr < endPtr)
{
//
// Get the next src char out to a temp, then do a binary search
// of the 'to' table for this entry.
//
if ((nextOut = xlatOneTo(*srcPtr))!=0)
{
*outPtr++ = nextOut;
srcPtr++;
continue;
}
//
// Its not representable so, according to the options, either
// throw or use the replacement.
//
if (options == UnRep_Throw)
{
XMLCh tmpBuf[17];
XMLString::binToText((unsigned int)*srcPtr, tmpBuf, 16, 16, getMemoryManager());
ThrowXMLwithMemMgr2
(
TranscodingException
, XMLExcepts::Trans_Unrepresentable
, tmpBuf
, getEncodingName()
, getMemoryManager()
);
}
// Eat the source char and use the replacement char
srcPtr++;
*outPtr++ = 0x3F;
}
// Set the chars eaten
charsEaten = countToDo;
// Return the bytes we transcoded
return countToDo;
}
bool XML256TableTranscoder::canTranscodeTo(const unsigned int toCheck)
{
return (xlatOneTo(toCheck) != 0);
}
// ---------------------------------------------------------------------------
// XML256TableTranscoder: Hidden constructor
// ---------------------------------------------------------------------------
XML256TableTranscoder::
XML256TableTranscoder( const XMLCh* const encodingName
, const XMLSize_t blockSize
, const XMLCh* const fromTable
, const XMLTransService::TransRec* const toTable
, const XMLSize_t toTableSize
, MemoryManager* const manager) :
XMLTranscoder(encodingName, blockSize, manager)
, fFromTable(fromTable)
, fToSize(toTableSize)
, fToTable(toTable)
{
}
// ---------------------------------------------------------------------------
// XML256TableTranscoder: Private helper methods
// ---------------------------------------------------------------------------
XMLByte XML256TableTranscoder::xlatOneTo(const XMLCh toXlat) const
{
XMLSize_t lowOfs = 0;
XMLSize_t hiOfs = fToSize - 1;
do
{
// Calc the mid point of the low and high offset.
const XMLSize_t midOfs = ((hiOfs - lowOfs) / 2) + lowOfs;
//
// If our test char is greater than the mid point char, then
// we move up to the upper half. Else we move to the lower
// half. If its equal, then its our guy.
//
if (toXlat > fToTable[midOfs].intCh)
{
lowOfs = midOfs;
}
else if (toXlat < fToTable[midOfs].intCh)
{
hiOfs = midOfs;
}
else
{
return fToTable[midOfs].extCh;
}
} while (lowOfs + 1 < hiOfs);
// Check the high end of the range otherwise the
// last item in the table may never be found.
if (toXlat == fToTable[hiOfs].intCh)
{
return fToTable[hiOfs].extCh;
}
return 0;
}
XERCES_CPP_NAMESPACE_END
|
/*
* Copyright 2016 neurodata (http://neurodata.io/)
* Written by Disa Mhembere (disa@jhu.edu)
*
* This file is part of knor
*
* 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 CURRENT_KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <random>
#include <stdexcept>
#include "fcm_coordinator.hpp"
#include "fcm.hpp"
#include "io.hpp"
#include "clusters.hpp"
#ifdef _OPENMP
#include <omp.h>
#endif
namespace knor {
fcm_coordinator::fcm_coordinator(const std::string fn, const size_t nrow,
const size_t ncol, const unsigned k, const unsigned max_iters,
const unsigned nnodes, const unsigned nthreads,
const double* centers, const kbase::init_t it,
const double tolerance, const kbase::dist_t dt,
const unsigned fuzzindex) :
coordinator(fn, nrow, ncol, k, max_iters,
nnodes, nthreads, centers, it, tolerance, dt),
fuzzindex(fuzzindex) {
#ifdef _OPENMP
omp_set_num_threads(nthreads);
#endif
this->centers = base::dense_matrix<double>::create(k, ncol);
this->prev_centers = base::dense_matrix<double>::create(k, ncol);
this->um = base::dense_matrix<double>::create(k, nrow);
if (centers)
this->centers->set(centers);
build_thread_state();
}
void fcm_coordinator::build_thread_state() {
// NUMA node affinity binding policy is round-robin
unsigned thds_row = nrow / nthreads;
for (unsigned thd_id = 0; thd_id < nthreads; thd_id++) {
std::pair<unsigned, unsigned> tup = get_rid_len_tup(thd_id);
thd_max_row_idx.push_back((thd_id*thds_row) + tup.second);
threads.push_back(
fcm::create((thd_id % nnodes),
thd_id, tup.first, tup.second,
ncol, k, fuzzindex, um, centers, fn, _dist_t));
threads[thd_id]->set_parent_cond(&cond);
threads[thd_id]->set_parent_pending_threads(&pending_threads);
threads[thd_id]->start(WAIT); // Thread puts itself to sleep
}
}
fcm_coordinator::~fcm_coordinator() {
delete (centers);
delete (prev_centers);
delete (um);
}
void fcm_coordinator::forgy_init() {
#if 1
std::default_random_engine generator;
std::uniform_int_distribution<unsigned> distribution(0, nrow-1);
for (unsigned clust_idx = 0; clust_idx < k; clust_idx++) { // 0...k
unsigned rand_idx = distribution(generator);
centers->set_row(get_thd_data(rand_idx), clust_idx);
}
#else
// Testing for iris with k = 3
assert(k == 3);
centers->set_row(get_thd_data(91),0);
centers->set_row(get_thd_data(63),1);
centers->set_row(get_thd_data(103),2);
#endif
}
void fcm_coordinator::update_contribution_matrix() {
std::vector<double> colsums;
um->sum(0, colsums); // k x nrow
um->div_eq_pow(colsums, 0, fuzzindex);
}
void fcm_coordinator::update_centers() {
if (threads.size() == 1) {
centers->copy_from(std::static_pointer_cast<fcm>(
threads[0])->get_innerprod());
} else {
auto sum = *(std::static_pointer_cast<fcm>(threads[0])->get_innerprod()) +
*(std::static_pointer_cast<fcm>(threads[1])->get_innerprod());
centers->copy_from(sum);
delete (sum);
for (size_t tid = 2; tid < threads.size(); tid++) {
*centers += *(std::static_pointer_cast<fcm>(
threads[tid])->get_innerprod());
}
}
// Take sum along axis
std::vector<double> sum;
um->sum(1, sum);
centers->div_eq(sum, 1);
}
/**
* Main driver
*/
base::cluster_t fcm_coordinator::run(double* allocd_data,
const bool numa_opt) {
#ifdef PROFILER
ProfilerStart("fcm_coordinator.perf");
#endif
if (!allocd_data) {
wake4run(ALLOC_DATA);
wait4complete();
} else if (allocd_data) {
set_thread_data_ptr(allocd_data);
}
struct timeval start, end;
gettimeofday(&start , NULL);
run_init(); // Initialize clusters
// Run kmeans loop
bool converged = false;
size_t iter = 0;
if (max_iters > 0)
iter++;
while (iter <= max_iters && max_iters > 0) {
#ifndef BIND
std::cout << "Running iteration: " << iter << std::endl;
#endif
// Compute new um
wake4run(E);
wait4complete();
update_contribution_matrix();
#if VERBOSE
#ifndef BIND
std::cout << "After Estep contribution matrix is: \n";
um->print();
#endif
#endif
// Compute new centers
prev_centers->copy_from(centers);
wake4run(M);
wait4complete();
update_centers();
#if VERBOSE
#ifndef BIND
std::cout << "After Mstep centers are: \n";
centers->print();
#endif
#endif
auto diff = (*centers - *prev_centers);
auto frob_norm = diff->frobenius_norm();
#ifndef BIND
std::cout << "Centers frob diff: " << frob_norm << "\n\n";
#endif
if (frob_norm < tolerance) {
converged = true;
delete (diff);
break;
}
delete (diff);
iter++;
}
#ifdef PROFILER
ProfilerStop();
#endif
gettimeofday(&end, NULL);
#ifndef BIND
printf("\n\nAlgorithmic time taken = %.6f sec\n",
kbase::time_diff(start, end));
printf("\n******************************************\n");
#endif
if (converged) {
#ifndef BIND
printf("Fuzzy C-means converged in %lu iterations\n", iter);
#endif
} else {
#ifndef BIND
printf("[Warning]: Fuzzy C-means failed to converge in %lu"
" iterations\n", iter);
#endif
}
um->argmax(1, cluster_assignments);
cluster_assignment_counts.assign(k, 0);
for (auto const& i : cluster_assignments)
cluster_assignment_counts[i]++;
#ifndef BIND
printf("Final cluster assignment count:\n");
kbase::print(cluster_assignment_counts);
printf("\n******************************************\n");
#endif
return kbase::cluster_t(this->nrow, this->ncol, iter, this->k,
&cluster_assignments[0], &cluster_assignment_counts[0],
centers->as_vector());
}
}
|
/* Starshatter OpenSource Distribution
Copyright (c) 1997-2004, Destroyer Studios LLC.
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 "Destroyer Studios" 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.
SUBSYSTEM: Magic.exe
FILE: TextureMapDialog.cpp
AUTHOR: John DiCamillo
OVERVIEW
========
Texture Mapping Dialog implementation file
*/
#include "stdafx.h"
#include "Magic.h"
#include "MagicDoc.h"
#include "MagicView.h"
#include "Selection.h"
#include "TextureMapDialog.h"
#include "Thumbnail.h"
#include "Bitmap.h"
#include "Solid.h"
#include "Polygon.h"
#include "Pcx.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// +--------------------------------------------------------------------+
// TextureMapDialog dialog
// +--------------------------------------------------------------------+
TextureMapDialog::TextureMapDialog(MagicView* pParent)
: CDialog(TextureMapDialog::IDD, pParent), doc(0), material(0), model(0), blank(0)
{
//{{AFX_DATA_INIT(TextureMapDialog)
mMaterialIndex = -1;
mFlip = FALSE;
mMirror = FALSE;
mRotate = FALSE;
mScaleV = 0.0;
mAxis = -1;
mScaleU = 0.0;
mMapType = -1;
//}}AFX_DATA_INIT
Color gray = Color::LightGray;
blank = new Bitmap(1,1,&gray);
blank->ScaleTo(128,128);
if (pParent) {
doc = pParent->GetDocument();
if (doc && doc->GetSolid()) {
model = doc->GetSolid()->GetModel();
}
if (doc && doc->GetSelection()) {
Selection* seln = doc->GetSelection();
if (seln->GetPolys().size() > 0) {
material = seln->GetPolys().first()->material;
mMaterialIndex = model->GetMaterials().index(material) + 1;
}
}
}
}
TextureMapDialog::~TextureMapDialog()
{
delete blank;
}
void TextureMapDialog::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(TextureMapDialog)
DDX_Control(pDX, IDC_MAPPING, mMapping);
DDX_Control(pDX, IDC_MATERIAL, mMaterialList);
DDX_Control(pDX, IDC_TEXTURE_PREVIEW, mMaterialThumb);
DDX_CBIndex(pDX, IDC_MATERIAL, mMaterialIndex);
DDX_Check(pDX, IDC_ALIGN_FLIP, mFlip);
DDX_Check(pDX, IDC_ALIGN_MIRROR, mMirror);
DDX_Check(pDX, IDC_ALIGN_ROTATE, mRotate);
DDX_Text(pDX, IDC_SCALE_V, mScaleV);
DDX_Radio(pDX, IDC_ALIGN_X, mAxis);
DDX_Text(pDX, IDC_SCALE_U, mScaleU);
DDX_CBIndex(pDX, IDC_MAPPING, mMapType);
//}}AFX_DATA_MAP
if (pDX->m_bSaveAndValidate) {
mMaterialIndex = mMaterialList.GetCurSel()-1;
}
}
BEGIN_MESSAGE_MAP(TextureMapDialog, CDialog)
//{{AFX_MSG_MAP(TextureMapDialog)
ON_WM_PAINT()
ON_CBN_SELCHANGE(IDC_MATERIAL, OnSelectMaterial)
ON_BN_CLICKED(IDC_ALIGN_X, OnAlign)
ON_BN_CLICKED(IDC_ALIGN_Y, OnAlign)
ON_BN_CLICKED(IDC_ALIGN_Z, OnAlign)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
// +--------------------------------------------------------------------+
// TextureMapDialog message handlers
// +--------------------------------------------------------------------+
BOOL TextureMapDialog::OnInitDialog()
{
CDialog::OnInitDialog();
mMaterialList.AddString("<none>");
if (model && model->NumMaterials()) {
ListIter<Material> iter = model->GetMaterials();
while (++iter) {
Material* mtl = iter.value();
mMaterialList.AddString(mtl->name);
}
}
mMaterialList.SetCurSel(mMaterialIndex);
mMapping.SetCurSel(0);
if (material) {
material->CreateThumbnail();
ThumbPreview(mMaterialThumb.GetSafeHwnd(), material->thumbnail);
}
return TRUE;
}
// +--------------------------------------------------------------------+
void TextureMapDialog::OnPaint()
{
CPaintDC dc(this); // device context for painting
if (material && material->thumbnail) {
ThumbPreview(mMaterialThumb.GetSafeHwnd(), material->thumbnail);
}
else {
ThumbPreview(mMaterialThumb.GetSafeHwnd(), blank);
}
}
void TextureMapDialog::OnSelectMaterial()
{
mMaterialIndex = mMaterialList.GetCurSel()-1;
material = 0;
if (model && mMaterialIndex >= 0 && mMaterialIndex < model->NumMaterials()) {
material = model->GetMaterials()[mMaterialIndex];
}
if (material) {
material->CreateThumbnail();
ThumbPreview(mMaterialThumb.GetSafeHwnd(), material->thumbnail);
}
else {
ThumbPreview(mMaterialThumb.GetSafeHwnd(), blank);
}
}
void TextureMapDialog::OnAlign()
{
if (mMapping.GetCurSel() == 0) {
mMapping.SetCurSel(1);
UpdateData(TRUE);
mScaleU = 1;
mScaleV = 1;
mMaterialIndex++;
UpdateData(FALSE);
}
}
|
#pragma once
#include <eosio/chain/account_object.hpp>
#include <eosio/chain/controller.hpp>
#include <eosio/chain/exceptions.hpp>
#include <eosio/chain/generated_transaction_object.hpp>
#include <eosio/chain/global_property_object.hpp>
#include <eosio/chain/permission_link_object.hpp>
#include <eosio/chain/permission_object.hpp>
#include <eosio/chain/protocol_state_object.hpp>
#include <eosio/chain/resource_limits.hpp>
#include <eosio/chain/resource_limits_private.hpp>
#include <eosio/chain/trace.hpp>
#include <eosio/chain_plugin/chain_plugin.hpp>
#include <eosio/state_history_plugin/state_history_plugin.hpp>
#include <type_traits>
template <typename T>
struct history_serial_wrapper {
const chainbase::database& db;
const T& obj;
};
template <typename T>
history_serial_wrapper<std::decay_t<T>> make_history_serial_wrapper(const chainbase::database& db, const T& obj) {
return {db, obj};
}
template <typename P, typename T>
struct history_context_wrapper {
const chainbase::database& db;
const P& context;
const T& obj;
};
template <typename P, typename T>
history_context_wrapper<std::decay_t<P>, std::decay_t<T>>
make_history_context_wrapper(const chainbase::database& db, const P& context, const T& obj) {
return {db, context, obj};
}
namespace fc {
template <typename T>
const T& as_type(const T& x) {
return x;
}
template <typename ST, typename T>
datastream<ST>& history_serialize_container(datastream<ST>& ds, const chainbase::database& db, const T& v) {
fc::raw::pack(ds, unsigned_int(v.size()));
for (auto& x : v)
ds << make_history_serial_wrapper(db, x);
return ds;
}
template <typename ST, typename T>
datastream<ST>& history_serialize_container(datastream<ST>& ds, const chainbase::database& db,
const std::vector<std::shared_ptr<T>>& v) {
fc::raw::pack(ds, unsigned_int(v.size()));
for (auto& x : v) {
EOS_ASSERT(!!x, eosio::chain::plugin_exception, "null inside container");
ds << make_history_serial_wrapper(db, *x);
}
return ds;
}
template <typename ST, typename P, typename T>
datastream<ST>& history_context_serialize_container(datastream<ST>& ds, const chainbase::database& db, const P& context,
const std::vector<T>& v) {
fc::raw::pack(ds, unsigned_int(v.size()));
for (const auto& x : v) {
ds << make_history_context_wrapper(db, context, x);
}
return ds;
}
template <typename ST, typename T>
datastream<ST>& operator<<(datastream<ST>& ds, const history_serial_big_vector_wrapper<T>& obj) {
FC_ASSERT(obj.obj.size() <= 1024 * 1024 * 1024);
fc::raw::pack(ds, unsigned_int((uint32_t)obj.obj.size()));
for (auto& x : obj.obj)
fc::raw::pack(ds, x);
return ds;
}
template <typename ST>
inline void history_pack_varuint64(datastream<ST>& ds, uint64_t val) {
do {
uint8_t b = uint8_t(val) & 0x7f;
val >>= 7;
b |= ((val > 0) << 7);
ds.write((char*)&b, 1);
} while (val);
}
template <typename ST>
void history_pack_big_bytes(datastream<ST>& ds, const eosio::chain::bytes& v) {
history_pack_varuint64(ds, v.size());
if (v.size())
ds.write(&v.front(), (uint32_t)v.size());
}
template <typename ST>
void history_pack_big_bytes(datastream<ST>& ds, const fc::optional<eosio::chain::bytes>& v) {
fc::raw::pack(ds, v.valid());
if (v)
history_pack_big_bytes(ds, *v);
}
template <typename ST, typename T>
datastream<ST>& operator<<(datastream<ST>& ds, const history_serial_wrapper<std::vector<T>>& obj) {
return history_serialize_container(ds, obj.db, obj.obj);
}
template <typename ST, typename P, typename T>
datastream<ST>& operator<<(datastream<ST>& ds, const history_context_wrapper<P, std::vector<T>>& obj) {
return history_context_serialize_container(ds, obj.db, obj.context, obj.obj);
}
template <typename ST, typename First, typename Second>
datastream<ST>& operator<<(datastream<ST>& ds, const history_serial_wrapper<std::pair<First, Second>>& obj) {
fc::raw::pack(ds, obj.obj.first);
fc::raw::pack(ds, obj.obj.second);
return ds;
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds, const history_serial_wrapper<eosio::chain::account_object>& obj) {
fc::raw::pack(ds, fc::unsigned_int(0));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.name.to_uint64_t()));
fc::raw::pack(ds, as_type<eosio::chain::block_timestamp_type>(obj.obj.creation_date));
fc::raw::pack(ds, as_type<eosio::chain::shared_string>(obj.obj.abi));
return ds;
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds,
const history_serial_wrapper<eosio::chain::account_metadata_object>& obj) {
fc::raw::pack(ds, fc::unsigned_int(0));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.name.to_uint64_t()));
fc::raw::pack(ds, as_type<bool>(obj.obj.is_privileged()));
fc::raw::pack(ds, as_type<fc::time_point>(obj.obj.last_code_update));
bool has_code = obj.obj.code_hash != eosio::chain::digest_type();
fc::raw::pack(ds, has_code);
if (has_code) {
fc::raw::pack(ds, as_type<uint8_t>(obj.obj.vm_type));
fc::raw::pack(ds, as_type<uint8_t>(obj.obj.vm_version));
fc::raw::pack(ds, as_type<eosio::chain::digest_type>(obj.obj.code_hash));
}
return ds;
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds, const history_serial_wrapper<eosio::chain::code_object>& obj) {
fc::raw::pack(ds, fc::unsigned_int(0));
fc::raw::pack(ds, as_type<uint8_t>(obj.obj.vm_type));
fc::raw::pack(ds, as_type<uint8_t>(obj.obj.vm_version));
fc::raw::pack(ds, as_type<eosio::chain::digest_type>(obj.obj.code_hash));
fc::raw::pack(ds, as_type<eosio::chain::shared_string>(obj.obj.code));
return ds;
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds, const history_serial_wrapper<eosio::chain::table_id_object>& obj) {
fc::raw::pack(ds, fc::unsigned_int(0));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.code.to_uint64_t()));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.scope.to_uint64_t()));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.table.to_uint64_t()));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.payer.to_uint64_t()));
return ds;
}
template <typename ST>
datastream<ST>&
operator<<(datastream<ST>& ds,
const history_context_wrapper<eosio::chain::table_id_object, eosio::chain::key_value_object>& obj) {
fc::raw::pack(ds, fc::unsigned_int(0));
fc::raw::pack(ds, as_type<uint64_t>(obj.context.code.to_uint64_t()));
fc::raw::pack(ds, as_type<uint64_t>(obj.context.scope.to_uint64_t()));
fc::raw::pack(ds, as_type<uint64_t>(obj.context.table.to_uint64_t()));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.primary_key));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.payer.to_uint64_t()));
fc::raw::pack(ds, as_type<eosio::chain::shared_string>(obj.obj.value));
return ds;
}
template <typename ST, typename T>
void serialize_secondary_index_data(datastream<ST>& ds, const T& obj) {
fc::raw::pack(ds, obj);
}
template <typename ST>
void serialize_secondary_index_data(datastream<ST>& ds, const float64_t& obj) {
uint64_t i;
memcpy(&i, &obj, sizeof(i));
fc::raw::pack(ds, i);
}
template <typename ST>
void serialize_secondary_index_data(datastream<ST>& ds, const float128_t& obj) {
__uint128_t i;
memcpy(&i, &obj, sizeof(i));
fc::raw::pack(ds, i);
}
template <typename ST>
void serialize_secondary_index_data(datastream<ST>& ds, const eosio::chain::key256_t& obj) {
auto rev = [&](__uint128_t x) {
char* ch = reinterpret_cast<char*>(&x);
std::reverse(ch, ch + sizeof(x));
return x;
};
fc::raw::pack(ds, rev(obj[0]));
fc::raw::pack(ds, rev(obj[1]));
}
template <typename ST, typename T>
datastream<ST>& serialize_secondary_index(datastream<ST>& ds, const eosio::chain::table_id_object& context,
const T& obj) {
fc::raw::pack(ds, fc::unsigned_int(0));
fc::raw::pack(ds, as_type<uint64_t>(context.code.to_uint64_t()));
fc::raw::pack(ds, as_type<uint64_t>(context.scope.to_uint64_t()));
fc::raw::pack(ds, as_type<uint64_t>(context.table.to_uint64_t()));
fc::raw::pack(ds, as_type<uint64_t>(obj.primary_key));
fc::raw::pack(ds, as_type<uint64_t>(obj.payer.to_uint64_t()));
serialize_secondary_index_data(ds, obj.secondary_key);
return ds;
}
template <typename ST>
datastream<ST>&
operator<<(datastream<ST>& ds,
const history_context_wrapper<eosio::chain::table_id_object, eosio::chain::index64_object>& obj) {
return serialize_secondary_index(ds, obj.context, obj.obj);
}
template <typename ST>
datastream<ST>&
operator<<(datastream<ST>& ds,
const history_context_wrapper<eosio::chain::table_id_object, eosio::chain::index128_object>& obj) {
return serialize_secondary_index(ds, obj.context, obj.obj);
}
template <typename ST>
datastream<ST>&
operator<<(datastream<ST>& ds,
const history_context_wrapper<eosio::chain::table_id_object, eosio::chain::index256_object>& obj) {
return serialize_secondary_index(ds, obj.context, obj.obj);
}
template <typename ST>
datastream<ST>&
operator<<(datastream<ST>& ds,
const history_context_wrapper<eosio::chain::table_id_object, eosio::chain::index_double_object>& obj) {
return serialize_secondary_index(ds, obj.context, obj.obj);
}
template <typename ST>
datastream<ST>& operator<<(
datastream<ST>& ds,
const history_context_wrapper<eosio::chain::table_id_object, eosio::chain::index_long_double_object>& obj) {
return serialize_secondary_index(ds, obj.context, obj.obj);
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds,
const history_serial_wrapper<eosio::chain::shared_block_signing_authority_v0>& obj) {
fc::raw::pack(ds, as_type<uint32_t>(obj.obj.threshold));
history_serialize_container(ds, obj.db,
as_type<eosio::chain::shared_vector<eosio::chain::shared_key_weight>>(obj.obj.keys));
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds, const history_serial_wrapper<eosio::chain::shared_producer_authority>& obj) {
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.producer_name.to_uint64_t()));
fc::raw::pack(ds, as_type<eosio::chain::shared_block_signing_authority>(obj.obj.authority));
return ds;
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds,
const history_serial_wrapper<eosio::chain::shared_producer_authority_schedule>& obj) {
fc::raw::pack(ds, as_type<uint32_t>(obj.obj.version));
history_serialize_container(ds, obj.db,
as_type<eosio::chain::shared_vector<eosio::chain::shared_producer_authority>>(obj.obj.producers));
return ds;
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds, const history_serial_wrapper<eosio::chain::chain_config>& obj) {
fc::raw::pack(ds, fc::unsigned_int(0));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.max_block_net_usage));
fc::raw::pack(ds, as_type<uint32_t>(obj.obj.target_block_net_usage_pct));
fc::raw::pack(ds, as_type<uint32_t>(obj.obj.max_transaction_net_usage));
fc::raw::pack(ds, as_type<uint32_t>(obj.obj.base_per_transaction_net_usage));
fc::raw::pack(ds, as_type<uint32_t>(obj.obj.net_usage_leeway));
fc::raw::pack(ds, as_type<uint32_t>(obj.obj.context_free_discount_net_usage_num));
fc::raw::pack(ds, as_type<uint32_t>(obj.obj.context_free_discount_net_usage_den));
fc::raw::pack(ds, as_type<uint32_t>(obj.obj.max_block_cpu_usage));
fc::raw::pack(ds, as_type<uint32_t>(obj.obj.target_block_cpu_usage_pct));
fc::raw::pack(ds, as_type<uint32_t>(obj.obj.max_transaction_cpu_usage));
fc::raw::pack(ds, as_type<uint32_t>(obj.obj.min_transaction_cpu_usage));
fc::raw::pack(ds, as_type<uint32_t>(obj.obj.max_transaction_lifetime));
fc::raw::pack(ds, as_type<uint32_t>(obj.obj.deferred_trx_expiration_window));
fc::raw::pack(ds, as_type<uint32_t>(obj.obj.max_transaction_delay));
fc::raw::pack(ds, as_type<uint32_t>(obj.obj.max_inline_action_size));
fc::raw::pack(ds, as_type<uint16_t>(obj.obj.max_inline_action_depth));
fc::raw::pack(ds, as_type<uint16_t>(obj.obj.max_authority_depth));
return ds;
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds,
const history_serial_wrapper<eosio::chain::global_property_object>& obj) {
fc::raw::pack(ds, fc::unsigned_int(1));
fc::raw::pack(ds, as_type<optional<eosio::chain::block_num_type>>(obj.obj.proposed_schedule_block_num));
fc::raw::pack(ds, make_history_serial_wrapper(
obj.db, as_type<eosio::chain::shared_producer_authority_schedule>(obj.obj.proposed_schedule)));
fc::raw::pack(ds, make_history_serial_wrapper(obj.db, as_type<eosio::chain::chain_config>(obj.obj.configuration)));
fc::raw::pack(ds, as_type<eosio::chain::chain_id_type>(obj.obj.chain_id));
return ds;
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds,
const history_serial_wrapper<eosio::chain::generated_transaction_object>& obj) {
fc::raw::pack(ds, fc::unsigned_int(0));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.sender.to_uint64_t()));
fc::raw::pack(ds, as_type<__uint128_t>(obj.obj.sender_id));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.payer.to_uint64_t()));
fc::raw::pack(ds, as_type<eosio::chain::transaction_id_type>(obj.obj.trx_id));
fc::raw::pack(ds, as_type<eosio::chain::shared_string>(obj.obj.packed_trx));
return ds;
}
template <typename ST>
datastream<ST>&
operator<<(datastream<ST>& ds,
const history_serial_wrapper<eosio::chain::protocol_state_object::activated_protocol_feature>& obj) {
fc::raw::pack(ds, fc::unsigned_int(0));
fc::raw::pack(ds, as_type<eosio::chain::digest_type>(obj.obj.feature_digest));
fc::raw::pack(ds, as_type<uint32_t>(obj.obj.activation_block_num));
return ds;
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds, const history_serial_wrapper<eosio::chain::protocol_state_object>& obj) {
fc::raw::pack(ds, fc::unsigned_int(0));
history_serialize_container(ds, obj.db, obj.obj.activated_protocol_features);
return ds;
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds, const history_serial_wrapper<eosio::chain::shared_key_weight>& obj) {
fc::raw::pack(ds, as_type<eosio::chain::public_key_type>(obj.obj.key));
fc::raw::pack(ds, as_type<uint16_t>(obj.obj.weight));
return ds;
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds, const history_serial_wrapper<eosio::chain::permission_level>& obj) {
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.actor.to_uint64_t()));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.permission.to_uint64_t()));
return ds;
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds,
const history_serial_wrapper<eosio::chain::permission_level_weight>& obj) {
fc::raw::pack(ds, make_history_serial_wrapper(obj.db, as_type<eosio::chain::permission_level>(obj.obj.permission)));
fc::raw::pack(ds, as_type<uint16_t>(obj.obj.weight));
return ds;
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds, const history_serial_wrapper<eosio::chain::wait_weight>& obj) {
fc::raw::pack(ds, as_type<uint32_t>(obj.obj.wait_sec));
fc::raw::pack(ds, as_type<uint16_t>(obj.obj.weight));
return ds;
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds, const history_serial_wrapper<eosio::chain::shared_authority>& obj) {
fc::raw::pack(ds, as_type<uint32_t>(obj.obj.threshold));
history_serialize_container(ds, obj.db, obj.obj.keys);
history_serialize_container(ds, obj.db, obj.obj.accounts);
history_serialize_container(ds, obj.db, obj.obj.waits);
return ds;
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds, const history_serial_wrapper<eosio::chain::permission_object>& obj) {
fc::raw::pack(ds, fc::unsigned_int(0));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.owner.to_uint64_t()));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.name.to_uint64_t()));
if (obj.obj.parent._id) {
auto& index = obj.db.get_index<eosio::chain::permission_index>();
const auto* parent = index.find(obj.obj.parent);
if (!parent) {
auto& undo = index.stack().back();
auto it = undo.removed_values.find(obj.obj.parent);
EOS_ASSERT(it != undo.removed_values.end(), eosio::chain::plugin_exception,
"can not find parent of permission_object");
parent = &it->second;
}
fc::raw::pack(ds, as_type<uint64_t>(parent->name.to_uint64_t()));
} else {
fc::raw::pack(ds, as_type<uint64_t>(0));
}
fc::raw::pack(ds, as_type<fc::time_point>(obj.obj.last_updated));
fc::raw::pack(ds, make_history_serial_wrapper(obj.db, as_type<eosio::chain::shared_authority>(obj.obj.auth)));
return ds;
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds,
const history_serial_wrapper<eosio::chain::permission_link_object>& obj) {
fc::raw::pack(ds, fc::unsigned_int(0));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.account.to_uint64_t()));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.code.to_uint64_t()));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.message_type.to_uint64_t()));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.required_permission.to_uint64_t()));
return ds;
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds,
const history_serial_wrapper<eosio::chain::resource_limits::resource_limits_object>& obj) {
EOS_ASSERT(!obj.obj.pending, eosio::chain::plugin_exception,
"accepted_block sent while resource_limits_object in pending state");
fc::raw::pack(ds, fc::unsigned_int(0));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.owner.to_uint64_t()));
fc::raw::pack(ds, as_type<int64_t>(obj.obj.net_weight));
fc::raw::pack(ds, as_type<int64_t>(obj.obj.cpu_weight));
fc::raw::pack(ds, as_type<int64_t>(obj.obj.ram_bytes));
return ds;
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds,
const history_serial_wrapper<eosio::chain::resource_limits::usage_accumulator>& obj) {
fc::raw::pack(ds, fc::unsigned_int(0));
fc::raw::pack(ds, as_type<uint32_t>(obj.obj.last_ordinal));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.value_ex));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.consumed));
return ds;
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds,
const history_serial_wrapper<eosio::chain::resource_limits::resource_usage_object>& obj) {
fc::raw::pack(ds, fc::unsigned_int(0));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.owner.to_uint64_t()));
fc::raw::pack(ds, make_history_serial_wrapper(
obj.db, as_type<eosio::chain::resource_limits::usage_accumulator>(obj.obj.net_usage)));
fc::raw::pack(ds, make_history_serial_wrapper(
obj.db, as_type<eosio::chain::resource_limits::usage_accumulator>(obj.obj.cpu_usage)));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.ram_usage));
return ds;
}
template <typename ST>
datastream<ST>&
operator<<(datastream<ST>& ds,
const history_serial_wrapper<eosio::chain::resource_limits::resource_limits_state_object>& obj) {
fc::raw::pack(ds, fc::unsigned_int(0));
fc::raw::pack(ds, make_history_serial_wrapper(obj.db, as_type<eosio::chain::resource_limits::usage_accumulator>(
obj.obj.average_block_net_usage)));
fc::raw::pack(ds, make_history_serial_wrapper(obj.db, as_type<eosio::chain::resource_limits::usage_accumulator>(
obj.obj.average_block_cpu_usage)));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.total_net_weight));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.total_cpu_weight));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.total_ram_bytes));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.virtual_net_limit));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.virtual_cpu_limit));
return ds;
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds,
const history_serial_wrapper<eosio::chain::resource_limits::ratio>& obj) {
fc::raw::pack(ds, fc::unsigned_int(0));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.numerator));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.denominator));
return ds;
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds,
const history_serial_wrapper<eosio::chain::resource_limits::elastic_limit_parameters>& obj) {
fc::raw::pack(ds, fc::unsigned_int(0));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.target));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.max));
fc::raw::pack(ds, as_type<uint32_t>(obj.obj.periods));
fc::raw::pack(ds, as_type<uint32_t>(obj.obj.max_multiplier));
fc::raw::pack(
ds, make_history_serial_wrapper(obj.db, as_type<eosio::chain::resource_limits::ratio>(obj.obj.contract_rate)));
fc::raw::pack(
ds, make_history_serial_wrapper(obj.db, as_type<eosio::chain::resource_limits::ratio>(obj.obj.expand_rate)));
return ds;
}
template <typename ST>
datastream<ST>&
operator<<(datastream<ST>& ds,
const history_serial_wrapper<eosio::chain::resource_limits::resource_limits_config_object>& obj) {
fc::raw::pack(ds, fc::unsigned_int(0));
fc::raw::pack(
ds, make_history_serial_wrapper(
obj.db, as_type<eosio::chain::resource_limits::elastic_limit_parameters>(obj.obj.cpu_limit_parameters)));
fc::raw::pack(
ds, make_history_serial_wrapper(
obj.db, as_type<eosio::chain::resource_limits::elastic_limit_parameters>(obj.obj.net_limit_parameters)));
fc::raw::pack(ds, as_type<uint32_t>(obj.obj.account_cpu_usage_average_window));
fc::raw::pack(ds, as_type<uint32_t>(obj.obj.account_net_usage_average_window));
return ds;
};
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds, const history_serial_wrapper<eosio::chain::action>& obj) {
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.account.to_uint64_t()));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.name.to_uint64_t()));
history_serialize_container(ds, obj.db, as_type<std::vector<eosio::chain::permission_level>>(obj.obj.authorization));
fc::raw::pack(ds, as_type<eosio::bytes>(obj.obj.data));
return ds;
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds, const history_serial_wrapper<eosio::chain::action_receipt>& obj) {
fc::raw::pack(ds, fc::unsigned_int(0));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.receiver.to_uint64_t()));
fc::raw::pack(ds, as_type<eosio::chain::digest_type>(obj.obj.act_digest));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.global_sequence));
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.recv_sequence));
history_serialize_container(ds, obj.db, as_type<flat_map<eosio::name, uint64_t>>(obj.obj.auth_sequence));
fc::raw::pack(ds, as_type<fc::unsigned_int>(obj.obj.code_sequence));
fc::raw::pack(ds, as_type<fc::unsigned_int>(obj.obj.abi_sequence));
return ds;
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds, const history_serial_wrapper<eosio::chain::account_delta>& obj) {
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.account.to_uint64_t()));
fc::raw::pack(ds, as_type<int64_t>(obj.obj.delta));
return ds;
}
inline fc::optional<uint64_t> cap_error_code( const fc::optional<uint64_t>& error_code ) {
fc::optional<uint64_t> result;
if (!error_code) return result;
const uint64_t upper_limit = static_cast<uint64_t>(eosio::chain::system_error_code::generic_system_error);
if (*error_code >= upper_limit) {
result = upper_limit;
return result;
}
result = error_code;
return result;
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds, const history_context_wrapper<bool, eosio::chain::action_trace>& obj) {
bool debug_mode = obj.context;
fc::raw::pack(ds, fc::unsigned_int(0));
fc::raw::pack(ds, as_type<fc::unsigned_int>(obj.obj.action_ordinal));
fc::raw::pack(ds, as_type<fc::unsigned_int>(obj.obj.creator_action_ordinal));
fc::raw::pack(ds, bool(obj.obj.receipt));
if (obj.obj.receipt) {
fc::raw::pack(ds, make_history_serial_wrapper(obj.db, as_type<eosio::chain::action_receipt>(*obj.obj.receipt)));
}
fc::raw::pack(ds, as_type<uint64_t>(obj.obj.receiver.to_uint64_t()));
fc::raw::pack(ds, make_history_serial_wrapper(obj.db, as_type<eosio::chain::action>(obj.obj.act)));
fc::raw::pack(ds, as_type<bool>(obj.obj.context_free));
fc::raw::pack(ds, as_type<int64_t>(debug_mode ? obj.obj.elapsed.count() : 0));
if (debug_mode)
fc::raw::pack(ds, as_type<std::string>(obj.obj.console));
else
fc::raw::pack(ds, std::string{});
history_serialize_container(ds, obj.db, as_type<flat_set<eosio::chain::account_delta>>(obj.obj.account_ram_deltas));
fc::optional<std::string> e;
if (obj.obj.except) {
if (debug_mode)
e = obj.obj.except->to_string();
else
e = "Y";
}
fc::raw::pack(ds, as_type<fc::optional<std::string>>(e));
fc::raw::pack(ds, as_type<fc::optional<uint64_t>>(debug_mode ? obj.obj.error_code
: cap_error_code(obj.obj.error_code)));
return ds;
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds,
const history_context_wrapper<std::pair<uint8_t, bool>,
eosio::augmented_transaction_trace>& obj) {
auto& trace = *obj.obj.trace;
bool debug_mode = obj.context.second;
fc::raw::pack(ds, fc::unsigned_int(0));
fc::raw::pack(ds, as_type<eosio::chain::transaction_id_type>(trace.id));
if (trace.receipt) {
if (trace.failed_dtrx_trace && trace.receipt->status.value == eosio::chain::transaction_receipt_header::soft_fail)
fc::raw::pack(ds, uint8_t(eosio::chain::transaction_receipt_header::executed));
else
fc::raw::pack(ds, as_type<uint8_t>(trace.receipt->status.value));
fc::raw::pack(ds, as_type<uint32_t>(trace.receipt->cpu_usage_us));
fc::raw::pack(ds, as_type<fc::unsigned_int>(trace.receipt->net_usage_words));
} else {
fc::raw::pack(ds, uint8_t(obj.context.first));
fc::raw::pack(ds, uint32_t(0));
fc::raw::pack(ds, fc::unsigned_int(0));
}
fc::raw::pack(ds, as_type<int64_t>(debug_mode ? trace.elapsed.count() : 0));
fc::raw::pack(ds, as_type<uint64_t>(trace.net_usage));
fc::raw::pack(ds, as_type<bool>(trace.scheduled));
history_context_serialize_container(ds, obj.db, debug_mode,
as_type<std::vector<eosio::chain::action_trace>>(trace.action_traces));
fc::raw::pack(ds, bool(trace.account_ram_delta));
if (trace.account_ram_delta) {
fc::raw::pack(
ds, make_history_serial_wrapper(obj.db, as_type<eosio::chain::account_delta>(*trace.account_ram_delta)));
}
fc::optional<std::string> e;
if (trace.except) {
if (debug_mode)
e = trace.except->to_string();
else
e = "Y";
}
fc::raw::pack(ds, as_type<fc::optional<std::string>>(e));
fc::raw::pack(ds, as_type<fc::optional<uint64_t>>(debug_mode ? trace.error_code
: cap_error_code(trace.error_code)));
fc::raw::pack(ds, bool(trace.failed_dtrx_trace));
if (trace.failed_dtrx_trace) {
uint8_t stat = eosio::chain::transaction_receipt_header::hard_fail;
if (trace.receipt && trace.receipt->status.value == eosio::chain::transaction_receipt_header::soft_fail)
stat = eosio::chain::transaction_receipt_header::soft_fail;
std::pair<uint8_t, bool> context = std::make_pair(stat, debug_mode);
fc::raw::pack( //
ds, make_history_context_wrapper(
obj.db, context, eosio::augmented_transaction_trace{trace.failed_dtrx_trace, obj.obj.partial}));
}
bool include_partial = obj.obj.partial && !trace.failed_dtrx_trace;
fc::raw::pack(ds, include_partial);
if (include_partial) {
auto& partial = *obj.obj.partial;
fc::raw::pack(ds, fc::unsigned_int(0));
fc::raw::pack(ds, as_type<eosio::chain::time_point_sec>(partial.expiration));
fc::raw::pack(ds, as_type<uint16_t>(partial.ref_block_num));
fc::raw::pack(ds, as_type<uint32_t>(partial.ref_block_prefix));
fc::raw::pack(ds, as_type<fc::unsigned_int>(partial.max_net_usage_words));
fc::raw::pack(ds, as_type<uint8_t>(partial.max_cpu_usage_ms));
fc::raw::pack(ds, as_type<fc::unsigned_int>(partial.delay_sec));
fc::raw::pack(ds, as_type<eosio::chain::extensions_type>(partial.transaction_extensions));
fc::raw::pack(ds, as_type<std::vector<eosio::chain::signature_type>>(partial.signatures));
fc::raw::pack(ds, as_type<std::vector<eosio::bytes>>(partial.context_free_data));
}
return ds;
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds,
const history_context_wrapper<bool, eosio::augmented_transaction_trace>& obj) {
std::pair<uint8_t, bool> context = std::make_pair(eosio::chain::transaction_receipt_header::hard_fail, obj.context);
ds << make_history_context_wrapper(obj.db, context, obj.obj);
return ds;
}
template <typename ST>
datastream<ST>& operator<<(datastream<ST>& ds, const eosio::get_blocks_result_v0& obj) {
fc::raw::pack(ds, obj.head);
fc::raw::pack(ds, obj.last_irreversible);
fc::raw::pack(ds, obj.this_block);
fc::raw::pack(ds, obj.prev_block);
history_pack_big_bytes(ds, obj.block);
history_pack_big_bytes(ds, obj.traces);
history_pack_big_bytes(ds, obj.deltas);
return ds;
}
} // namespace fc
|
/*
* Copyright (c) 2017, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder 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.
*/
/**
* @file
* This file includes definition for data types used by Thread border agent.
*/
#ifndef OTBR_COMMON_TYPES_HPP_
#define OTBR_COMMON_TYPES_HPP_
#include "openthread-br/config.h"
#include <netinet/in.h>
#include <stdint.h>
#include <string.h>
#include <string>
#include <vector>
#include "common/byteswap.hpp"
#ifndef IN6ADDR_ANY
/**
* Any IPv6 address literal.
*
*/
#define IN6ADDR_ANY "::"
#endif
#define OTBR_IP6_ADDRESS_SIZE 16
#define OTBR_IP6_PREFIX_SIZE 8
#define OTBR_NETWORK_KEY_SIZE 16
#define OTBR_PSKC_SIZE 16
/**
* Forward declaration for otIp6Prefix to avoid including <openthread/ip6.h>
*
*/
struct otIp6Prefix;
/**
* This enumeration represents error codes used throughout OpenThread Border Router.
*/
enum otbrError
{
OTBR_ERROR_NONE = 0, ///< No error.
OTBR_ERROR_ERRNO = -1, ///< Error defined by errno.
OTBR_ERROR_DBUS = -2, ///< DBus error.
OTBR_ERROR_MDNS = -3, ///< mDNS error.
OTBR_ERROR_OPENTHREAD = -4, ///< OpenThread error.
OTBR_ERROR_REST = -5, ///< Rest Server error.
OTBR_ERROR_SMCROUTE = -6, ///< SMCRoute error.
OTBR_ERROR_NOT_FOUND = -7, ///< Not found.
OTBR_ERROR_PARSE = -8, ///< Parse error.
OTBR_ERROR_NOT_IMPLEMENTED = -9, ///< Not implemented error.
OTBR_ERROR_INVALID_ARGS = -10, ///< Invalid arguments error.
OTBR_ERROR_DUPLICATED = -11, ///< Duplicated operation, resource or name.
};
namespace otbr {
enum
{
kSizePSKc = 16, ///< Size of PSKc.
kSizeNetworkName = 16, ///< Max size of Network Name.
kSizeExtPanId = 8, ///< Size of Extended PAN ID.
kSizeEui64 = 8, ///< Size of Eui64.
kSizeExtAddr = kSizeEui64, ///< Size of Extended Address.
};
static constexpr char kSolicitedMulticastAddressPrefix[] = "ff02::01:ff00:0";
static constexpr char kLinkLocalAllNodesMulticastAddress[] = "ff02::01";
/**
* This class implements the Ipv6 address functionality.
*
*/
class Ip6Address
{
public:
/**
* Default constructor.
*
*/
Ip6Address(void)
{
m64[0] = 0;
m64[1] = 0;
}
/**
* Constructor with an 16-bit Thread locator.
*
* @param[in] aLocator 16-bit Thread locator, RLOC or ALOC.
*
*/
Ip6Address(uint16_t aLocator)
{
m64[0] = 0;
m32[2] = 0;
m16[6] = 0;
m8[14] = aLocator >> 8;
m8[15] = aLocator & 0xff;
}
/**
* Constructor with an Ip6 address.
*
* @param[in] aAddress The Ip6 address.
*
*/
Ip6Address(const uint8_t (&aAddress)[16]);
/**
* This method overloads `<` operator and compares if the Ip6 address is smaller than the other address.
*
* @param[in] aOther The other Ip6 address to compare with.
*
* @returns Whether the Ip6 address is smaller than the other address.
*
*/
bool operator<(const Ip6Address &aOther) const { return memcmp(this, &aOther, sizeof(Ip6Address)) < 0; }
/**
* This method overloads `==` operator and compares if the Ip6 address is equal to the other address.
*
* @param[in] aOther The other Ip6 address to compare with.
*
* @returns Whether the Ip6 address is equal to the other address.
*
*/
bool operator==(const Ip6Address &aOther) const { return m64[0] == aOther.m64[0] && m64[1] == aOther.m64[1]; }
/**
* Retrieve the 16-bit Thread locator.
*
* @returns RLOC16 or ALOC16.
*
*/
uint16_t ToLocator(void) const { return static_cast<uint16_t>(m8[14] << 8 | m8[15]); }
/**
* This method returns the solicited node multicast address.
*
* @returns The solicited node multicast address.
*
*/
Ip6Address ToSolicitedNodeMulticastAddress(void) const;
/**
* This method returns the string representation for the Ip6 address.
*
* @returns The string representation of the Ip6 address.
*
*/
std::string ToString(void) const;
/**
* This method indicates whether or not the Ip6 address is the Unspecified Address.
*
* @retval TRUE If the Ip6 address is the Unspecified Address.
* @retval FALSE If the Ip6 address is not the Unspecified Address.
*
*/
bool IsUnspecified(void) const { return m64[0] == 0 && m64[1] == 0; }
/**
* This method returns if the Ip6 address is a multicast address.
*
* @returns Whether the Ip6 address is a multicast address.
*
*/
bool IsMulticast(void) const { return m8[0] == 0xff; }
/**
* This method returns if the Ip6 address is a link-local address.
*
* @returns Whether the Ip6 address is a link-local address.
*
*/
bool IsLinkLocal(void) const { return (m16[0] & bswap_16(0xffc0)) == bswap_16(0xfe80); }
/**
* This method returns whether or not the Ip6 address is the Loopback Address.
*
* @retval TRUE If the Ip6 address is the Loopback Address.
* @retval FALSE If the Ip6 address is not the Loopback Address.
*
*/
bool IsLoopback(void) const { return (m32[0] == 0 && m32[1] == 0 && m32[2] == 0 && m32[3] == htobe32(1)); }
/**
* This function returns the wellknown Link Local All Nodes Multicast Address (ff02::1).
*
* @returns The Link Local All Nodes Multicast Address.
*
*/
static const Ip6Address &GetLinkLocalAllNodesMulticastAddress(void)
{
static Ip6Address sLinkLocalAllNodesMulticastAddress = FromString(kLinkLocalAllNodesMulticastAddress);
return sLinkLocalAllNodesMulticastAddress;
}
/**
* This function returns the wellknown Solicited Node Multicast Address Prefix (ff02::01:ff00:0).
*
* @returns The Solicited Node Multicast Address Prefix.
*
*/
static const Ip6Address &GetSolicitedMulticastAddressPrefix(void)
{
static Ip6Address sSolicitedMulticastAddressPrefix = FromString(kSolicitedMulticastAddressPrefix);
return sSolicitedMulticastAddressPrefix;
}
/**
* This function converts Ip6 addresses from text to `Ip6Address`.
*
* @param[in] aStr The Ip6 address text.
* @param[out] aAddr A reference to `Ip6Address` to output the Ip6 address.
*
* @retval OTBR_ERROR_NONE If the Ip6 address was successfully converted.
* @retval OTBR_ERROR_INVALID_ARGS If @p `aStr` is not a valid string representing of Ip6 address.
*
*/
static otbrError FromString(const char *aStr, Ip6Address &aAddr);
/**
* This method copies the Ip6 address to a `sockaddr_in6` structure.
*
* @param[out] aSockAddr The `sockaddr_in6` structure to copy the Ip6 address to.
*
*/
void CopyTo(struct sockaddr_in6 &aSockAddr) const;
/**
* This method copies the Ip6 address from a `sockaddr_in6` structure.
*
* @param[in] aSockAddr The `sockaddr_in6` structure to copy the Ip6 address from.
*
*/
void CopyFrom(const struct sockaddr_in6 &aSockAddr);
/**
* This method copies the Ip6 address to a `in6_addr` structure.
*
* @param[out] aIn6Addr The `in6_addr` structure to copy the Ip6 address to.
*
*/
void CopyTo(struct in6_addr &aIn6Addr) const;
/**
* This method copies the Ip6 address from a `in6_addr` structure.
*
* @param[in] aIn6Addr The `in6_addr` structure to copy the Ip6 address from.
*
*/
void CopyFrom(const struct in6_addr &aIn6Addr);
union
{
uint8_t m8[16];
uint16_t m16[8];
uint32_t m32[4];
uint64_t m64[2];
};
private:
static Ip6Address FromString(const char *aStr);
};
/**
* This class represents a Ipv6 prefix.
*
*/
class Ip6Prefix
{
public:
/**
* Default constructor.
*
*/
Ip6Prefix(void) { Clear(); }
/**
* This method sets the Ip6 prefix to an `otIp6Prefix` value.
*
* @param[in] aPrefix The `otIp6Prefix` value to set the Ip6 prefix.
*
*/
void Set(const otIp6Prefix &aPrefix);
/**
* This method returns the string representation for the Ip6 prefix.
*
* @returns The string representation of the Ip6 prefix.
*
*/
std::string ToString(void) const;
/**
* This method clears the Ip6 prefix to be unspecified.
*
*/
void Clear(void) { memset(reinterpret_cast<void *>(this), 0, sizeof(*this)); }
/**
* This method returns if the Ip6 prefix is valid.
*
* @returns If the Ip6 prefix is valid.
*
*/
bool IsValid(void) const { return mLength > 0 && mLength <= 128; }
Ip6Address mPrefix; ///< The IPv6 prefix.
uint8_t mLength; ///< The IPv6 prefix length (in bits).
};
/**
* This class represents an ethernet MAC address.
*/
class MacAddress
{
public:
/**
* Default constructor.
*
*/
MacAddress(void)
{
m16[0] = 0;
m16[1] = 0;
m16[2] = 0;
}
/**
* This method returns the string representation for the MAC address.
*
* @returns The string representation of the MAC address.
*
*/
std::string ToString(void) const;
union
{
uint8_t m8[6];
uint16_t m16[3];
};
};
} // namespace otbr
#endif // OTBR_COMMON_TYPES_HPP_
|
// Copyright (c) 2013-2016 The Bitcoin Core developers
// Copyright (c) 2017-2020 The Raven Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <primitives/block.h>
#include "hash.h"
#include "crypto/common.h"
#include "crypto/hmac_sha512.h"
#include "pubkey.h"
#include "util/strencodings.h"
#include <crypto/ethash/include/ethash/progpow.hpp>
//TODO remove these
double algoHashTotal[16];
int algoHashHits[16];
inline uint32_t ROTL32(uint32_t x, int8_t r)
{
return (x << r) | (x >> (32 - r));
}
unsigned int MurmurHash3(unsigned int nHashSeed, const std::vector<unsigned char>& vDataToHash)
{
// The following is MurmurHash3 (x86_32), see http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp
uint32_t h1 = nHashSeed;
const uint32_t c1 = 0xcc9e2d51;
const uint32_t c2 = 0x1b873593;
const int nblocks = vDataToHash.size() / 4;
//----------
// body
const uint8_t* blocks = vDataToHash.data();
for (int i = 0; i < nblocks; ++i) {
uint32_t k1 = ReadLE32(blocks + i*4);
k1 *= c1;
k1 = ROTL32(k1, 15);
k1 *= c2;
h1 ^= k1;
h1 = ROTL32(h1, 13);
h1 = h1 * 5 + 0xe6546b64;
}
//----------
// tail
const uint8_t* tail = vDataToHash.data() + nblocks * 4;
uint32_t k1 = 0;
switch (vDataToHash.size() & 3) {
case 3:
k1 ^= tail[2] << 16;
case 2:
k1 ^= tail[1] << 8;
case 1:
k1 ^= tail[0];
k1 *= c1;
k1 = ROTL32(k1, 15);
k1 *= c2;
h1 ^= k1;
}
//----------
// finalization
h1 ^= vDataToHash.size();
h1 ^= h1 >> 16;
h1 *= 0x85ebca6b;
h1 ^= h1 >> 13;
h1 *= 0xc2b2ae35;
h1 ^= h1 >> 16;
return h1;
}
void BIP32Hash(const ChainCode &chainCode, unsigned int nChild, unsigned char header, const unsigned char data[32], unsigned char output[64])
{
unsigned char num[4];
num[0] = (nChild >> 24) & 0xFF;
num[1] = (nChild >> 16) & 0xFF;
num[2] = (nChild >> 8) & 0xFF;
num[3] = (nChild >> 0) & 0xFF;
CHMAC_SHA512(chainCode.begin(), chainCode.size()).Write(&header, 1).Write(data, 32).Write(num, 4).Finalize(output);
}
#define ROTL(x, b) (uint64_t)(((x) << (b)) | ((x) >> (64 - (b))))
#define SIPROUND do { \
v0 += v1; v1 = ROTL(v1, 13); v1 ^= v0; \
v0 = ROTL(v0, 32); \
v2 += v3; v3 = ROTL(v3, 16); v3 ^= v2; \
v0 += v3; v3 = ROTL(v3, 21); v3 ^= v0; \
v2 += v1; v1 = ROTL(v1, 17); v1 ^= v2; \
v2 = ROTL(v2, 32); \
} while (0)
CSipHasher::CSipHasher(uint64_t k0, uint64_t k1)
{
v[0] = 0x736f6d6570736575ULL ^ k0;
v[1] = 0x646f72616e646f6dULL ^ k1;
v[2] = 0x6c7967656e657261ULL ^ k0;
v[3] = 0x7465646279746573ULL ^ k1;
count = 0;
tmp = 0;
}
CSipHasher& CSipHasher::Write(uint64_t data)
{
uint64_t v0 = v[0], v1 = v[1], v2 = v[2], v3 = v[3];
assert(count % 8 == 0);
v3 ^= data;
SIPROUND;
SIPROUND;
v0 ^= data;
v[0] = v0;
v[1] = v1;
v[2] = v2;
v[3] = v3;
count += 8;
return *this;
}
CSipHasher& CSipHasher::Write(const unsigned char* data, size_t size)
{
uint64_t v0 = v[0], v1 = v[1], v2 = v[2], v3 = v[3];
uint64_t t = tmp;
int c = count;
while (size--) {
t |= ((uint64_t)(*(data++))) << (8 * (c % 8));
c++;
if ((c & 7) == 0) {
v3 ^= t;
SIPROUND;
SIPROUND;
v0 ^= t;
t = 0;
}
}
v[0] = v0;
v[1] = v1;
v[2] = v2;
v[3] = v3;
count = c;
tmp = t;
return *this;
}
uint64_t CSipHasher::Finalize() const
{
uint64_t v0 = v[0], v1 = v[1], v2 = v[2], v3 = v[3];
uint64_t t = tmp | (((uint64_t)count) << 56);
v3 ^= t;
SIPROUND;
SIPROUND;
v0 ^= t;
v2 ^= 0xFF;
SIPROUND;
SIPROUND;
SIPROUND;
SIPROUND;
return v0 ^ v1 ^ v2 ^ v3;
}
uint64_t SipHashUint256(uint64_t k0, uint64_t k1, const uint256& val)
{
/* Specialized implementation for efficiency */
uint64_t d = val.GetUint64(0);
uint64_t v0 = 0x736f6d6570736575ULL ^ k0;
uint64_t v1 = 0x646f72616e646f6dULL ^ k1;
uint64_t v2 = 0x6c7967656e657261ULL ^ k0;
uint64_t v3 = 0x7465646279746573ULL ^ k1 ^ d;
SIPROUND;
SIPROUND;
v0 ^= d;
d = val.GetUint64(1);
v3 ^= d;
SIPROUND;
SIPROUND;
v0 ^= d;
d = val.GetUint64(2);
v3 ^= d;
SIPROUND;
SIPROUND;
v0 ^= d;
d = val.GetUint64(3);
v3 ^= d;
SIPROUND;
SIPROUND;
v0 ^= d;
v3 ^= ((uint64_t)4) << 59;
SIPROUND;
SIPROUND;
v0 ^= ((uint64_t)4) << 59;
v2 ^= 0xFF;
SIPROUND;
SIPROUND;
SIPROUND;
SIPROUND;
return v0 ^ v1 ^ v2 ^ v3;
}
uint64_t SipHashUint256Extra(uint64_t k0, uint64_t k1, const uint256& val, uint32_t extra)
{
/* Specialized implementation for efficiency */
uint64_t d = val.GetUint64(0);
uint64_t v0 = 0x736f6d6570736575ULL ^ k0;
uint64_t v1 = 0x646f72616e646f6dULL ^ k1;
uint64_t v2 = 0x6c7967656e657261ULL ^ k0;
uint64_t v3 = 0x7465646279746573ULL ^ k1 ^ d;
SIPROUND;
SIPROUND;
v0 ^= d;
d = val.GetUint64(1);
v3 ^= d;
SIPROUND;
SIPROUND;
v0 ^= d;
d = val.GetUint64(2);
v3 ^= d;
SIPROUND;
SIPROUND;
v0 ^= d;
d = val.GetUint64(3);
v3 ^= d;
SIPROUND;
SIPROUND;
v0 ^= d;
d = (((uint64_t)36) << 56) | extra;
v3 ^= d;
SIPROUND;
SIPROUND;
v0 ^= d;
v2 ^= 0xFF;
SIPROUND;
SIPROUND;
SIPROUND;
SIPROUND;
return v0 ^ v1 ^ v2 ^ v3;
}
uint256 KAWPOWHash(const CBlockHeader& blockHeader, uint256& mix_hash)
{
static ethash::epoch_context_ptr context{nullptr, nullptr};
// Get the context from the block height
const auto epoch_number = ethash::get_epoch_number(blockHeader.nHeight);
if (!context || context->epoch_number != epoch_number)
context = ethash::create_epoch_context(epoch_number);
// Build the header_hash
uint256 nHeaderHash = blockHeader.GetKAWPOWHeaderHash();
const auto header_hash = to_hash256(nHeaderHash.GetHex());
// ProgPow hash
const auto result = progpow::hash(*context, blockHeader.nHeight, header_hash, blockHeader.nNonce64);
mix_hash = uint256S(to_hex(result.mix_hash));
return uint256S(to_hex(result.final_hash));
}
uint256 KAWPOWHash_OnlyMix(const CBlockHeader& blockHeader)
{
// Build the header_hash
uint256 nHeaderHash = blockHeader.GetKAWPOWHeaderHash();
const auto header_hash = to_hash256(nHeaderHash.GetHex());
// ProgPow hash
const auto result = progpow::hash_no_verify(blockHeader.nHeight, header_hash, to_hash256(blockHeader.mix_hash.GetHex()), blockHeader.nNonce64);
return uint256S(to_hex(result));
}
|
#include "pch.h"
#include "fe.h"
void fe_invert(fe out,const fe z)
{
fe t0;
fe t1;
fe t2;
fe t3;
int i;
#include "pow225521.h"
return;
}
|
#pragma once
#include "ANNarchy.hpp"
class Network;
template<typename PrePopulation, typename PostPopulation>
class cppSynapse_$class_name {
public:
cppSynapse_$class_name(Network* net, PrePopulation* pre, PostPopulation* post){
this->net = net;
this->post = post;
this->pre = pre;
// Initialize arrays
$initialize_arrays
};
// Network
Network* net;
// Populations
PrePopulation* pre;
PostPopulation* post;
// Attributes
$declared_attributes
// Collect inputs (weighted sum or spike transmission)
void collect_inputs(){
$collect_inputs_method
};
// Update method
void update(){
$update_method
};
};
|
// RUN: %clang_cc1 -fsyntax-only -verify %s -DTEST1
// RUN: %clang_cc1 -fsyntax-only -verify %s -DTEST2
// RUN: %clang_cc1 -fsyntax-only -verify %s -DTEST3
// RUN: %clang_cc1 -fsyntax-only -verify %s -DTEST4
// RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++14 -DTEST5
// RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++14 -DTEST6
// RUN: %clang_cc1 -fsyntax-only -verify %s -DTEST7
// RUN: %clang_cc1 -fsyntax-only -verify %s -DTEST8
// RUN: %clang_cc1 -fsyntax-only -verify %s -DTEST9
// RUN: %clang_cc1 -fsyntax-only -verify %s -DTEST10 -ffreestanding
#if TEST1
int main; // expected-error{{main cannot be declared as global variable}}
#elif TEST2
// expected-no-diagnostics
int f () {
int main;
return main;
}
#elif TEST3
// expected-no-diagnostics
void x(int main) {};
int y(int main);
#elif TEST4
// expected-no-diagnostics
class A {
static int main;
};
#elif TEST5
// expected-no-diagnostics
template<class T> constexpr T main;
#elif TEST6
extern template<class T> constexpr T main; //expected-error{{expected unqualified-id}}
#elif TEST7
// expected-no-diagnostics
namespace foo {
int main;
}
#elif TEST8
void z(void)
{
extern int main; // expected-error{{main cannot be declared as global variable}}
}
#elif TEST9
// expected-no-diagnostics
int q(void)
{
static int main;
return main;
}
#elif TEST10
// expected-no-diagnostics
int main;
#else
#error Unknown Test
#endif
|
/////////////////////////////////////////////////////////////////////////////
// Name: src/osx/carbon/window.cpp
// Purpose: wxWindowMac
// Author: Stefan Csomor
// Modified by:
// Created: 1998-01-01
// Copyright: (c) Stefan Csomor
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#include "wx/wxprec.h"
#include "wx/window.h"
#ifndef WX_PRECOMP
#include "wx/log.h"
#include "wx/app.h"
#include "wx/utils.h"
#include "wx/panel.h"
#include "wx/frame.h"
#include "wx/dc.h"
#include "wx/dcclient.h"
#include "wx/button.h"
#include "wx/menu.h"
#include "wx/dialog.h"
#include "wx/settings.h"
#include "wx/msgdlg.h"
#include "wx/scrolbar.h"
#include "wx/statbox.h"
#include "wx/textctrl.h"
#include "wx/toolbar.h"
#include "wx/layout.h"
#include "wx/statusbr.h"
#include "wx/menuitem.h"
#include "wx/treectrl.h"
#include "wx/listctrl.h"
#endif
#include "wx/tooltip.h"
#include "wx/spinctrl.h"
#include "wx/geometry.h"
#if wxUSE_LISTCTRL
#include "wx/listctrl.h"
#endif
#if wxUSE_TREECTRL
#include "wx/treectrl.h"
#endif
#if wxUSE_CARET
#include "wx/caret.h"
#endif
#if wxUSE_POPUPWIN
#include "wx/popupwin.h"
#endif
#if wxUSE_DRAG_AND_DROP
#include "wx/dnd.h"
#endif
#if wxOSX_USE_CARBON
#include "wx/osx/uma.h"
#else
#include "wx/osx/private.h"
// bring in theming
#include <Carbon/Carbon.h>
#endif
#define MAC_SCROLLBAR_SIZE 15
#define MAC_SMALL_SCROLLBAR_SIZE 11
#include <string.h>
#define wxMAC_DEBUG_REDRAW 0
#ifndef wxMAC_DEBUG_REDRAW
#define wxMAC_DEBUG_REDRAW 0
#endif
// Get the window with the focus
WXWidget wxWidgetImpl::FindFocus()
{
ControlRef control = NULL ;
GetKeyboardFocus( GetUserFocusWindow() , &control ) ;
return control;
}
// no compositing to take into account under carbon
wxWidgetImpl* wxWidgetImpl::FindBestFromWXWidget(WXWidget control)
{
return FindFromWXWidget(control);
}
// ---------------------------------------------------------------------------
// Carbon Events
// ---------------------------------------------------------------------------
static const EventTypeSpec eventList[] =
{
{ kEventClassCommand, kEventProcessCommand } ,
{ kEventClassCommand, kEventCommandUpdateStatus } ,
{ kEventClassControl , kEventControlGetClickActivation } ,
{ kEventClassControl , kEventControlHit } ,
{ kEventClassTextInput, kEventTextInputUnicodeForKeyEvent } ,
{ kEventClassTextInput, kEventTextInputUpdateActiveInputArea } ,
{ kEventClassControl , kEventControlDraw } ,
{ kEventClassControl , kEventControlVisibilityChanged } ,
{ kEventClassControl , kEventControlEnabledStateChanged } ,
{ kEventClassControl , kEventControlHiliteChanged } ,
{ kEventClassControl , kEventControlActivate } ,
{ kEventClassControl , kEventControlDeactivate } ,
{ kEventClassControl , kEventControlSetFocusPart } ,
{ kEventClassControl , kEventControlFocusPartChanged } ,
{ kEventClassService , kEventServiceGetTypes },
{ kEventClassService , kEventServiceCopy },
{ kEventClassService , kEventServicePaste },
// { kEventClassControl , kEventControlInvalidateForSizeChange } , // 10.3 only
// { kEventClassControl , kEventControlBoundsChanged } ,
} ;
static pascal OSStatus wxMacWindowControlEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
{
OSStatus result = eventNotHandledErr ;
static wxWindowMac* targetFocusWindow = NULL;
static wxWindowMac* formerFocusWindow = NULL;
wxMacCarbonEvent cEvent( event ) ;
ControlRef controlRef ;
wxWindowMac* thisWindow = (wxWindowMac*) data ;
cEvent.GetParameter( kEventParamDirectObject , &controlRef ) ;
switch ( GetEventKind( event ) )
{
case kEventControlDraw :
{
HIShapeRef updateRgn = NULL ;
HIMutableShapeRef allocatedRgn = NULL ;
wxRegion visRegion = thisWindow->MacGetVisibleRegion() ;
// according to the docs: redraw entire control if param not present
if ( cEvent.GetParameter<HIShapeRef>(kEventParamShape, &updateRgn) != noErr )
{
updateRgn = visRegion.GetWXHRGN();
}
else
{
if ( thisWindow->MacGetLeftBorderSize() != 0 || thisWindow->MacGetTopBorderSize() != 0 )
{
// as this update region is in native window locals we must adapt it to wx window local
allocatedRgn = HIShapeCreateMutableCopy(updateRgn);
HIShapeOffset(allocatedRgn, thisWindow->MacGetLeftBorderSize() , thisWindow->MacGetTopBorderSize());
// hide the given region by the new region that must be shifted
updateRgn = allocatedRgn ;
}
}
#if wxMAC_DEBUG_REDRAW
if ( thisWindow->MacIsUserPane() )
{
static float color = 0.5 ;
static int channel = 0 ;
HIRect bounds;
CGContextRef cgContext = cEvent.GetParameter<CGContextRef>(kEventParamCGContextRef) ;
HIViewGetBounds( controlRef, &bounds );
CGContextSetRGBFillColor( cgContext, channel == 0 ? color : 0.5 ,
channel == 1 ? color : 0.5 , channel == 2 ? color : 0.5 , 1 );
CGContextFillRect( cgContext, bounds );
color += 0.1 ;
if ( color > 0.9 )
{
color = 0.5 ;
channel++ ;
if ( channel == 3 )
channel = 0 ;
}
}
#endif
{
CGContextRef cgContext = NULL ;
OSStatus err = cEvent.GetParameter<CGContextRef>(kEventParamCGContextRef, &cgContext) ;
if ( err != noErr )
{
// for non-composite drawing, since we don't support it ourselves, send it through the
// the default handler
// CallNextEventHandler( handler,event ) ;
// result = noErr ;
if ( allocatedRgn )
CFRelease( allocatedRgn ) ;
break;
}
thisWindow->MacSetCGContextRef( cgContext ) ;
{
wxMacCGContextStateSaver sg( cgContext ) ;
CGFloat alpha = (CGFloat)1.0 ;
{
wxWindow* iter = thisWindow ;
while ( iter )
{
alpha *= (CGFloat)( iter->GetTransparent()/255.0 ) ;
if ( iter->IsTopLevel() )
iter = NULL ;
else
iter = iter->GetParent() ;
}
}
CGContextSetAlpha( cgContext, alpha ) ;
if ( thisWindow->GetBackgroundStyle() == wxBG_STYLE_TRANSPARENT )
{
HIRect bounds;
HIViewGetBounds( controlRef, &bounds );
CGContextClearRect( cgContext, bounds );
}
if ( !HIShapeIsEmpty(updateRgn) )
{
// refcount increase because wxRegion constructor takes ownership of the native region
CFRetain(updateRgn);
thisWindow->GetUpdateRegion() = wxRegion(updateRgn);
if ( !thisWindow->MacDoRedraw( cEvent.GetTicks() ) )
{
// for native controls: call their native paint method
if ( !thisWindow->MacIsUserPane() ||
( thisWindow->IsTopLevel() && thisWindow->GetBackgroundStyle() == wxBG_STYLE_SYSTEM ) )
{
if ( thisWindow->GetBackgroundStyle() != wxBG_STYLE_TRANSPARENT )
{
CallNextEventHandler( handler,event ) ;
result = noErr ;
}
}
}
else
{
result = noErr ;
}
thisWindow->MacPaintChildrenBorders();
}
thisWindow->MacSetCGContextRef( NULL ) ;
}
}
if ( allocatedRgn )
CFRelease( allocatedRgn ) ;
}
break ;
case kEventControlVisibilityChanged :
// we might have two native controls attributed to the same wxWindow instance
// eg a scrollview and an embedded textview, make sure we only fire for the 'outer'
// control, as otherwise native and wx visibility are different
if ( thisWindow->GetPeer() != NULL && thisWindow->GetPeer()->GetControlRef() == controlRef )
{
thisWindow->MacVisibilityChanged() ;
}
break ;
case kEventControlEnabledStateChanged :
thisWindow->MacEnabledStateChanged();
break ;
case kEventControlHiliteChanged :
thisWindow->MacHiliteChanged() ;
break ;
case kEventControlActivate :
case kEventControlDeactivate :
// FIXME: we should have a virtual function for this!
#if wxUSE_TREECTRL
if ( thisWindow->IsKindOf( CLASSINFO( wxTreeCtrl ) ) )
thisWindow->Refresh();
#endif
#if wxUSE_LISTCTRL
if ( thisWindow->IsKindOf( CLASSINFO( wxListCtrl ) ) )
thisWindow->Refresh();
#endif
break ;
//
// focus handling
// different handling on OS X
//
case kEventControlFocusPartChanged :
// the event is emulated by wxmac for systems lower than 10.5
{
ControlPartCode previousControlPart = cEvent.GetParameter<ControlPartCode>(kEventParamControlPreviousPart , typeControlPartCode );
ControlPartCode currentControlPart = cEvent.GetParameter<ControlPartCode>(kEventParamControlCurrentPart , typeControlPartCode );
if ( thisWindow->MacGetTopLevelWindow() && thisWindow->GetPeer()->NeedsFocusRect() )
{
thisWindow->MacInvalidateBorders();
}
if ( currentControlPart == 0 )
{
// kill focus
#if wxUSE_CARET
if ( thisWindow->GetCaret() )
thisWindow->GetCaret()->OnKillFocus();
#endif
wxLogTrace(wxT("Focus"), wxT("focus lost(%p)"), static_cast<void*>(thisWindow));
// remove this as soon as posting the synthesized event works properly
static bool inKillFocusEvent = false ;
if ( !inKillFocusEvent )
{
inKillFocusEvent = true ;
wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
event.SetEventObject(thisWindow);
event.SetWindow(targetFocusWindow);
thisWindow->HandleWindowEvent(event) ;
inKillFocusEvent = false ;
targetFocusWindow = NULL;
}
}
else if ( previousControlPart == 0 )
{
// set focus
// panel wants to track the window which was the last to have focus in it
wxLogTrace(wxT("Focus"), wxT("focus set(%p)"), static_cast<void*>(thisWindow));
wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
thisWindow->HandleWindowEvent(eventFocus);
#if wxUSE_CARET
if ( thisWindow->GetCaret() )
thisWindow->GetCaret()->OnSetFocus();
#endif
wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
event.SetEventObject(thisWindow);
event.SetWindow(formerFocusWindow);
thisWindow->HandleWindowEvent(event) ;
formerFocusWindow = NULL;
}
}
break;
case kEventControlSetFocusPart :
{
Boolean focusEverything = false ;
if ( cEvent.GetParameter<Boolean>(kEventParamControlFocusEverything , &focusEverything ) == noErr )
{
// put a breakpoint here to catch focus everything events
}
ControlPartCode controlPart = cEvent.GetParameter<ControlPartCode>(kEventParamControlPart , typeControlPartCode );
if ( controlPart != kControlFocusNoPart )
{
targetFocusWindow = thisWindow;
wxLogTrace(wxT("Focus"), wxT("focus to be set(%p)"), static_cast<void*>(thisWindow));
}
else
{
formerFocusWindow = thisWindow;
wxLogTrace(wxT("Focus"), wxT("focus to be lost(%p)"), static_cast<void*>(thisWindow));
}
ControlPartCode previousControlPart = 0;
verify_noerr( HIViewGetFocusPart(controlRef, &previousControlPart));
if ( thisWindow->MacIsUserPane() )
{
if ( controlPart != kControlFocusNoPart )
cEvent.SetParameter<ControlPartCode>( kEventParamControlPart, typeControlPartCode, 1 ) ;
result = noErr ;
}
else
result = CallNextEventHandler(handler, event);
}
break ;
case kEventControlHit :
result = thisWindow->MacControlHit( handler , event ) ;
break ;
case kEventControlGetClickActivation :
{
// fix to always have a proper activation for DataBrowser controls (stay in bkgnd otherwise)
WindowRef owner = cEvent.GetParameter<WindowRef>(kEventParamWindowRef);
if ( !IsWindowActive(owner) )
{
cEvent.SetParameter(kEventParamClickActivation,typeClickActivationResult, (UInt32) kActivateAndIgnoreClick) ;
result = noErr ;
}
}
break ;
default :
break ;
}
return result ;
}
static pascal OSStatus
wxMacWindowServiceEventHandler(EventHandlerCallRef WXUNUSED(handler),
EventRef event,
void *data)
{
OSStatus result = eventNotHandledErr ;
wxMacCarbonEvent cEvent( event ) ;
ControlRef controlRef ;
wxWindowMac* thisWindow = (wxWindowMac*) data ;
wxTextCtrl* textCtrl = wxDynamicCast( thisWindow , wxTextCtrl ) ;
cEvent.GetParameter( kEventParamDirectObject , &controlRef ) ;
switch ( GetEventKind( event ) )
{
case kEventServiceGetTypes :
if ( textCtrl )
{
long from, to ;
textCtrl->GetSelection( &from , &to ) ;
CFMutableArrayRef copyTypes = 0 , pasteTypes = 0;
if ( from != to )
copyTypes = cEvent.GetParameter< CFMutableArrayRef >( kEventParamServiceCopyTypes , typeCFMutableArrayRef ) ;
if ( textCtrl->IsEditable() )
pasteTypes = cEvent.GetParameter< CFMutableArrayRef >( kEventParamServicePasteTypes , typeCFMutableArrayRef ) ;
static const OSType textDataTypes[] = { kTXNTextData /* , 'utxt', 'PICT', 'MooV', 'AIFF' */ };
for ( size_t i = 0 ; i < WXSIZEOF(textDataTypes) ; ++i )
{
CFStringRef typestring = CreateTypeStringWithOSType(textDataTypes[i]);
if ( typestring )
{
if ( copyTypes )
CFArrayAppendValue(copyTypes, typestring) ;
if ( pasteTypes )
CFArrayAppendValue(pasteTypes, typestring) ;
CFRelease( typestring ) ;
}
}
result = noErr ;
}
break ;
case kEventServiceCopy :
if ( textCtrl )
{
long from, to ;
textCtrl->GetSelection( &from , &to ) ;
wxString val = textCtrl->GetValue() ;
val = val.Mid( from , to - from ) ;
PasteboardRef pasteboard = cEvent.GetParameter<PasteboardRef>( kEventParamPasteboardRef, typePasteboardRef );
verify_noerr( PasteboardClear( pasteboard ) ) ;
PasteboardSynchronize( pasteboard );
// TODO add proper conversion
CFDataRef data = CFDataCreate( kCFAllocatorDefault, (const UInt8*)val.c_str(), val.length() );
PasteboardPutItemFlavor( pasteboard, (PasteboardItemID) 1, CFSTR("com.apple.traditional-mac-plain-text"), data, 0);
CFRelease( data );
result = noErr ;
}
break ;
case kEventServicePaste :
if ( textCtrl )
{
PasteboardRef pasteboard = cEvent.GetParameter<PasteboardRef>( kEventParamPasteboardRef, typePasteboardRef );
PasteboardSynchronize( pasteboard );
ItemCount itemCount;
verify_noerr( PasteboardGetItemCount( pasteboard, &itemCount ) );
for( UInt32 itemIndex = 1; itemIndex <= itemCount; itemIndex++ )
{
PasteboardItemID itemID;
if ( PasteboardGetItemIdentifier( pasteboard, itemIndex, &itemID ) == noErr )
{
CFDataRef flavorData = NULL;
if ( PasteboardCopyItemFlavorData( pasteboard, itemID, CFSTR("com.apple.traditional-mac-plain-text"), &flavorData ) == noErr )
{
CFIndex flavorDataSize = CFDataGetLength( flavorData );
char *content = new char[flavorDataSize+1] ;
memcpy( content, CFDataGetBytePtr( flavorData ), flavorDataSize );
content[flavorDataSize]=0;
CFRelease( flavorData );
#if wxUSE_UNICODE
textCtrl->WriteText( wxString( content , wxConvLocal ) );
#else
textCtrl->WriteText( wxString( content ) ) ;
#endif
delete[] content ;
result = noErr ;
}
}
}
}
break ;
default:
break ;
}
return result ;
}
WXDLLEXPORT pascal OSStatus wxMacUnicodeTextEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
{
OSStatus result = eventNotHandledErr ;
wxWindowMac* focus = (wxWindowMac*) data ;
wchar_t* uniChars = NULL ;
UInt32 when = EventTimeToTicks( GetEventTime( event ) ) ;
UniChar* charBuf = NULL;
ByteCount dataSize = 0 ;
int numChars = 0 ;
UniChar buf[2] ;
if ( GetEventParameter( event, kEventParamTextInputSendText, typeUnicodeText, NULL, 0 , &dataSize, NULL ) == noErr )
{
numChars = dataSize / sizeof( UniChar) + 1;
charBuf = buf ;
if ( (size_t) numChars * 2 > sizeof(buf) )
charBuf = new UniChar[ numChars ] ;
else
charBuf = buf ;
uniChars = new wchar_t[ numChars ] ;
GetEventParameter( event, kEventParamTextInputSendText, typeUnicodeText, NULL, dataSize , NULL , charBuf ) ;
charBuf[ numChars - 1 ] = 0;
// the resulting string will never have more chars than the utf16 version, so this is safe
wxMBConvUTF16 converter ;
numChars = converter.MB2WC( uniChars , (const char*)charBuf , numChars ) ;
}
switch ( GetEventKind( event ) )
{
case kEventTextInputUpdateActiveInputArea :
{
// An IME input event may return several characters, but we need to send one char at a time to
// EVT_CHAR
for (int pos=0 ; pos < numChars ; pos++)
{
WXEVENTREF formerEvent = wxTheApp->MacGetCurrentEvent() ;
WXEVENTHANDLERCALLREF formerHandler = wxTheApp->MacGetCurrentEventHandlerCallRef() ;
wxTheApp->MacSetCurrentEvent( event , handler ) ;
UInt32 message = uniChars[pos] < 128 ? (char)uniChars[pos] : '?';
/*
NB: faking a charcode here is problematic. The kEventTextInputUpdateActiveInputArea event is sent
multiple times to update the active range during inline input, so this handler will often receive
uncommited text, which should usually not trigger side effects. It might be a good idea to check the
kEventParamTextInputSendFixLen parameter and verify if input is being confirmed (see CarbonEvents.h).
On the other hand, it can be useful for some applications to react to uncommitted text (for example,
to update a status display), as long as it does not disrupt the inline input session. Ideally, wx
should add new event types to support advanced text input. For now, I would keep things as they are.
However, the code that was being used caused additional problems:
UInt32 message = (0 << 8) + ((char)uniChars[pos] );
Since it simply truncated the unichar to the last byte, it ended up causing weird bugs with inline
input, such as switching to another field when one attempted to insert the character U+4E09 (the kanji
for "three"), because it was truncated to 09 (kTabCharCode), which was later "converted" to WXK_TAB
(still 09) in wxMacTranslateKey; or triggering the default button when one attempted to insert U+840D
(the kanji for "name"), which got truncated to 0D and interpreted as a carriage return keypress.
Note that even single-byte characters could have been misinterpreted, since MacRoman charcodes only
overlap with Unicode within the (7-bit) ASCII range.
But simply passing a NUL charcode would disable text updated events, because wxTextCtrl::OnChar checks
for codes within a specific range. Therefore I went for the solution seen above, which keeps ASCII
characters as they are and replaces the rest with '?', ensuring that update events are triggered.
It would be better to change wxTextCtrl::OnChar to look at the actual unicode character instead, but
I don't have time to look into that right now.
-- CL
*/
if ( wxTheApp->MacSendCharEvent( focus , message , 0 , when , uniChars[pos] ) )
{
result = noErr ;
}
wxTheApp->MacSetCurrentEvent( formerEvent , formerHandler ) ;
}
}
break ;
case kEventTextInputUnicodeForKeyEvent :
{
UInt32 keyCode, modifiers ;
EventRef rawEvent ;
unsigned char charCode ;
GetEventParameter( event, kEventParamTextInputSendKeyboardEvent, typeEventRef, NULL, sizeof(rawEvent), NULL, &rawEvent ) ;
GetEventParameter( rawEvent, kEventParamKeyMacCharCodes, typeChar, NULL, 1, NULL, &charCode );
GetEventParameter( rawEvent, kEventParamKeyCode, typeUInt32, NULL, sizeof(UInt32), NULL, &keyCode );
GetEventParameter( rawEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(UInt32), NULL, &modifiers );
UInt32 message = (keyCode << 8) + charCode;
// An IME input event may return several characters, but we need to send one char at a time to
// EVT_CHAR
for (int pos=0 ; pos < numChars ; pos++)
{
WXEVENTREF formerEvent = wxTheApp->MacGetCurrentEvent() ;
WXEVENTHANDLERCALLREF formerHandler = wxTheApp->MacGetCurrentEventHandlerCallRef() ;
wxTheApp->MacSetCurrentEvent( event , handler ) ;
if ( wxTheApp->MacSendCharEvent( focus , message , modifiers , when , uniChars[pos] ) )
{
result = noErr ;
}
wxTheApp->MacSetCurrentEvent( formerEvent , formerHandler ) ;
}
}
break;
default:
break ;
}
delete [] uniChars ;
if ( charBuf != buf )
delete [] charBuf ;
return result ;
}
static pascal OSStatus
wxMacWindowCommandEventHandler(EventHandlerCallRef WXUNUSED(handler),
EventRef event,
void *data)
{
OSStatus result = eventNotHandledErr ;
wxWindowMac* focus = (wxWindowMac*) data ;
HICommand command ;
wxMacCarbonEvent cEvent( event ) ;
cEvent.GetParameter<HICommand>(kEventParamDirectObject,typeHICommand,&command) ;
wxMenuItem* item = NULL ;
wxMenu* itemMenu = wxFindMenuFromMacCommand( command , item ) ;
if ( item )
{
wxASSERT( itemMenu != NULL ) ;
switch ( cEvent.GetKind() )
{
case kEventProcessCommand :
if ( itemMenu->HandleCommandProcess( item, focus ) )
result = noErr;
break ;
case kEventCommandUpdateStatus:
if ( itemMenu->HandleCommandUpdateStatus( item, focus ) )
result = noErr;
break ;
default :
break ;
}
}
return result ;
}
pascal OSStatus wxMacWindowEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
{
EventRef formerEvent = (EventRef) wxTheApp->MacGetCurrentEvent() ;
EventHandlerCallRef formerEventHandlerCallRef = (EventHandlerCallRef) wxTheApp->MacGetCurrentEventHandlerCallRef() ;
wxTheApp->MacSetCurrentEvent( event , handler ) ;
OSStatus result = eventNotHandledErr ;
switch ( GetEventClass( event ) )
{
case kEventClassCommand :
result = wxMacWindowCommandEventHandler( handler , event , data ) ;
break ;
case kEventClassControl :
result = wxMacWindowControlEventHandler( handler, event, data ) ;
break ;
case kEventClassService :
result = wxMacWindowServiceEventHandler( handler, event , data ) ;
break ;
case kEventClassTextInput :
result = wxMacUnicodeTextEventHandler( handler , event , data ) ;
break ;
default :
break ;
}
wxTheApp->MacSetCurrentEvent( formerEvent, formerEventHandlerCallRef ) ;
return result ;
}
DEFINE_ONE_SHOT_HANDLER_GETTER( wxMacWindowEventHandler )
// ---------------------------------------------------------------------------
// Scrollbar Tracking for all
// ---------------------------------------------------------------------------
pascal void wxMacLiveScrollbarActionProc( ControlRef control , ControlPartCode partCode ) ;
pascal void wxMacLiveScrollbarActionProc( ControlRef control , ControlPartCode partCode )
{
if ( partCode != 0)
{
wxWindow* wx = wxFindWindowFromWXWidget( (WXWidget) control ) ;
if ( wx )
{
wxEventType scrollEvent = wxEVT_NULL;
switch ( partCode )
{
case kControlUpButtonPart:
scrollEvent = wxEVT_SCROLL_LINEUP;
break;
case kControlDownButtonPart:
scrollEvent = wxEVT_SCROLL_LINEDOWN;
break;
case kControlPageUpPart:
scrollEvent = wxEVT_SCROLL_PAGEUP;
break;
case kControlPageDownPart:
scrollEvent = wxEVT_SCROLL_PAGEDOWN;
break;
case kControlIndicatorPart:
scrollEvent = wxEVT_SCROLL_THUMBTRACK;
// when this is called as a live proc, mouse is always still down
// so no need for thumbrelease
// scrollEvent = wxEVT_SCROLL_THUMBRELEASE;
break;
}
wx->TriggerScrollEvent(scrollEvent) ;
}
}
}
wxMAC_DEFINE_PROC_GETTER( ControlActionUPP , wxMacLiveScrollbarActionProc ) ;
wxWidgetImplType* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer,
wxWindowMac* WXUNUSED(parent),
wxWindowID WXUNUSED(id),
const wxPoint& pos,
const wxSize& size,
long WXUNUSED(style),
long WXUNUSED(extraStyle))
{
OSStatus err = noErr;
Rect bounds = wxMacGetBoundsForControl( wxpeer , pos , size ) ;
wxMacControl* c = new wxMacControl(wxpeer, false, true) ;
UInt32 features = 0
| kControlSupportsEmbedding
| kControlSupportsLiveFeedback
| kControlGetsFocusOnClick
// | kControlHasSpecialBackground
// | kControlSupportsCalcBestRect
| kControlHandlesTracking
| kControlSupportsFocus
| kControlWantsActivate
| kControlWantsIdle ;
err =::CreateUserPaneControl( MAC_WXHWND(wxpeer->GetParent()->MacGetTopLevelWindowRef()) , &bounds, features , c->GetControlRefAddr() );
verify_noerr( err );
return c;
}
void wxMacControl::InstallEventHandler( WXWidget control )
{
wxWidgetImpl::Associate( control ? control : (WXWidget) m_controlRef , this ) ;
::InstallControlEventHandler( control ? (ControlRef) control : m_controlRef , GetwxMacWindowEventHandlerUPP(),
GetEventTypeCount(eventList), eventList, GetWXPeer(), NULL);
}
IMPLEMENT_DYNAMIC_CLASS( wxMacControl , wxWidgetImpl )
wxMacControl::wxMacControl()
{
Init();
}
wxMacControl::wxMacControl(wxWindowMac* peer , bool isRootControl, bool isUserPane ) :
wxWidgetImpl( peer, isRootControl, isUserPane )
{
Init();
}
wxMacControl::~wxMacControl()
{
if ( m_controlRef && !IsRootControl() )
{
wxASSERT_MSG( m_controlRef != NULL , wxT("Control Handle already NULL, Dispose called twice ?") );
wxASSERT_MSG( IsValidControlHandle(m_controlRef) , wxT("Invalid Control Handle (maybe already released) in Dispose") );
wxWidgetImpl::RemoveAssociations( this ) ;
// we cannot check the ref count here anymore, as autorelease objects might delete their refs later
// we can have situations when being embedded, where the control gets deleted behind our back, so only
// CFRelease if we are safe
if ( IsValidControlHandle(m_controlRef) )
CFRelease(m_controlRef);
}
m_controlRef = NULL;
}
void wxMacControl::Init()
{
m_controlRef = NULL;
m_macControlEventHandler = NULL;
}
void wxMacControl::RemoveFromParent()
{
// nothing to do here for carbon
HIViewRemoveFromSuperview(m_controlRef);
}
void wxMacControl::Embed( wxWidgetImpl *parent )
{
HIViewAddSubview((ControlRef)parent->GetWXWidget(), m_controlRef);
}
void wxMacControl::SetNeedsDisplay( const wxRect* rect )
{
if ( !IsVisible() )
return;
if ( rect != NULL )
{
HIRect updatearea = CGRectMake( rect->x , rect->y , rect->width , rect->height);
HIViewSetNeedsDisplayInRect( m_controlRef, &updatearea, true );
}
else
HIViewSetNeedsDisplay( m_controlRef , true );
}
void wxMacControl::Raise()
{
verify_noerr( HIViewSetZOrder( m_controlRef, kHIViewZOrderAbove, NULL ) );
}
void wxMacControl::Lower()
{
verify_noerr( HIViewSetZOrder( m_controlRef, kHIViewZOrderBelow, NULL ) );
}
void wxMacControl::GetContentArea(int &left , int &top , int &width , int &height) const
{
HIShapeRef rgn = NULL;
Rect content ;
if ( HIViewCopyShape(m_controlRef, kHIViewContentMetaPart, &rgn) == noErr)
{
CGRect cgrect;
HIShapeGetBounds(rgn, &cgrect);
content = (Rect){ (short)cgrect.origin.y,
(short)cgrect.origin.x,
(short)(cgrect.origin.y+cgrect.size.height),
(short)(cgrect.origin.x+cgrect.size.width) };
CFRelease(rgn);
}
else
{
GetControlBounds(m_controlRef, &content);
content.right -= content.left;
content.left = 0;
content.bottom -= content.top;
content.top = 0;
}
left = content.left;
top = content.top;
width = content.right - content.left ;
height = content.bottom - content.top ;
}
void wxMacControl::Move(int x, int y, int width, int height)
{
UInt32 attr = 0 ;
GetWindowAttributes( GetControlOwner(m_controlRef) , &attr ) ;
HIRect hir = CGRectMake(x,y,width,height);
if ( !(attr & kWindowCompositingAttribute) )
{
HIRect parent;
HIViewGetFrame( HIViewGetSuperview(m_controlRef), &parent );
hir.origin.x += parent.origin.x;
hir.origin.y += parent.origin.y;
}
HIViewSetFrame ( m_controlRef , &hir );
}
void wxMacControl::GetPosition( int &x, int &y ) const
{
Rect r;
GetControlBounds( m_controlRef , &r );
x = r.left;
y = r.top;
UInt32 attr = 0 ;
GetWindowAttributes( GetControlOwner(m_controlRef) , &attr ) ;
if ( !(attr & kWindowCompositingAttribute) )
{
HIRect parent;
HIViewGetFrame( HIViewGetSuperview(m_controlRef), &parent );
x -= (int)parent.origin.x;
y -= (int)parent.origin.y;
}
}
void wxMacControl::GetSize( int &width, int &height ) const
{
Rect r;
GetControlBounds( m_controlRef , &r );
width = r.right - r.left;
height = r.bottom - r.top;
}
void wxMacControl::SetControlSize( wxWindowVariant variant )
{
ControlSize size ;
switch ( variant )
{
case wxWINDOW_VARIANT_NORMAL :
size = kControlSizeNormal;
break ;
case wxWINDOW_VARIANT_SMALL :
size = kControlSizeSmall;
break ;
case wxWINDOW_VARIANT_MINI :
// not always defined in the headers
size = 3 ;
break ;
case wxWINDOW_VARIANT_LARGE :
size = kControlSizeLarge;
break ;
default:
wxFAIL_MSG(wxT("unexpected window variant"));
break ;
}
SetData<ControlSize>(kControlEntireControl, kControlSizeTag, &size ) ;
}
void wxMacControl::ScrollRect( const wxRect *rect, int dx, int dy )
{
if (GetNeedsDisplay() )
{
// because HIViewScrollRect does not scroll the already invalidated area we have two options:
// in case there is already a pending redraw on that area
// either immediate redraw or full invalidate
#if 1
// is the better overall solution, as it does not slow down scrolling
SetNeedsDisplay() ;
#else
// this would be the preferred version for fast drawing controls
HIViewRender(GetControlRef()) ;
#endif
}
// note there currently is a bug in OSX (10.3 +?) which makes inefficient refreshes in case an entire control
// area is scrolled, this does not occur if width and height are 2 pixels less,
// TODO: write optimal workaround
HIRect scrollarea = CGRectMake( rect->x , rect->y , rect->width , rect->height);
HIViewScrollRect ( m_controlRef , &scrollarea , dx ,dy );
#if 0
// this would be the preferred version for fast drawing controls
HIViewRender(GetControlRef()) ;
#endif
}
bool wxMacControl::CanFocus() const
{
// TODO : evaluate performance hits by looking up this value, eventually cache the results for a 1 sec or so
// CAUTION : the value returned currently is 0 or 2, I've also found values of 1 having the same meaning,
// but the value range is nowhere documented
Boolean keyExistsAndHasValidFormat ;
CFIndex fullKeyboardAccess = CFPreferencesGetAppIntegerValue( CFSTR("AppleKeyboardUIMode" ) ,
kCFPreferencesCurrentApplication, &keyExistsAndHasValidFormat );
if ( keyExistsAndHasValidFormat && fullKeyboardAccess > 0 )
{
return true ;
}
else
{
UInt32 features = 0 ;
GetControlFeatures( m_controlRef, &features ) ;
return features & ( kControlSupportsFocus | kControlGetsFocusOnClick ) ;
}
}
bool wxMacControl::GetNeedsDisplay() const
{
return HIViewGetNeedsDisplay( m_controlRef );
}
void wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
{
HIPoint hiPoint;
hiPoint.x = pt->x;
hiPoint.y = pt->y;
HIViewConvertPoint( &hiPoint , (ControlRef) from->GetWXWidget() , (ControlRef) to->GetWXWidget() );
pt->x = (int)hiPoint.x;
pt->y = (int)hiPoint.y;
}
bool wxMacControl::SetFocus()
{
// as we cannot rely on the control features to find out whether we are in full keyboard mode,
// we can only leave in case of an error
OSStatus err = SetKeyboardFocus( GetControlOwner( m_controlRef ), m_controlRef, kControlFocusNextPart );
if ( err == errCouldntSetFocus )
return false ;
SetUserFocusWindow(GetControlOwner( m_controlRef ) );
return true;
}
bool wxMacControl::HasFocus() const
{
ControlRef control;
GetKeyboardFocus( GetUserFocusWindow() , &control );
return control == m_controlRef;
}
void wxMacControl::SetCursor(const wxCursor& cursor)
{
wxWindowMac *mouseWin = 0 ;
WindowRef window = GetControlOwner( m_controlRef ) ;
wxNonOwnedWindow* tlwwx = wxNonOwnedWindow::GetFromWXWindow( (WXWindow) window ) ;
if ( tlwwx != NULL )
{
ControlPartCode part ;
ControlRef control ;
Point pt ;
HIPoint hiPoint ;
HIGetMousePosition(kHICoordSpaceWindow, window, &hiPoint);
pt.h = hiPoint.x;
pt.v = hiPoint.y;
control = FindControlUnderMouse( pt , window , &part ) ;
if ( control )
mouseWin = wxFindWindowFromWXWidget( (WXWidget) control ) ;
}
if ( mouseWin == tlwwx && !wxIsBusy() )
cursor.MacInstall() ;
}
void wxMacControl::CaptureMouse()
{
}
void wxMacControl::ReleaseMouse()
{
}
//
// subclass specifics
//
OSStatus wxMacControl::GetData(ControlPartCode inPartCode , ResType inTag , Size inBufferSize , void * inOutBuffer , Size * outActualSize ) const
{
return ::GetControlData( m_controlRef , inPartCode , inTag , inBufferSize , inOutBuffer , outActualSize );
}
OSStatus wxMacControl::GetDataSize(ControlPartCode inPartCode , ResType inTag , Size * outActualSize ) const
{
return ::GetControlDataSize( m_controlRef , inPartCode , inTag , outActualSize );
}
OSStatus wxMacControl::SetData(ControlPartCode inPartCode , ResType inTag , Size inSize , const void * inData)
{
return ::SetControlData( m_controlRef , inPartCode , inTag , inSize , inData );
}
OSStatus wxMacControl::SendEvent( EventRef event , OptionBits inOptions )
{
return SendEventToEventTargetWithOptions( event,
HIObjectGetEventTarget( (HIObjectRef) m_controlRef ), inOptions );
}
OSStatus wxMacControl::SendHICommand( HICommand &command , OptionBits inOptions )
{
wxMacCarbonEvent event( kEventClassCommand , kEventCommandProcess );
event.SetParameter<HICommand>(kEventParamDirectObject,command);
return SendEvent( event , inOptions );
}
OSStatus wxMacControl::SendHICommand( UInt32 commandID , OptionBits inOptions )
{
HICommand command;
memset( &command, 0 , sizeof(command) );
command.commandID = commandID;
return SendHICommand( command , inOptions );
}
void wxMacControl::PerformClick()
{
HIViewSimulateClick (m_controlRef, kControlButtonPart, 0, NULL );
}
wxInt32 wxMacControl::GetValue() const
{
return ::GetControl32BitValue( m_controlRef );
}
wxInt32 wxMacControl::GetMaximum() const
{
return ::GetControl32BitMaximum( m_controlRef );
}
wxInt32 wxMacControl::GetMinimum() const
{
return ::GetControl32BitMinimum( m_controlRef );
}
void wxMacControl::SetValue( wxInt32 v )
{
::SetControl32BitValue( m_controlRef , v );
}
void wxMacControl::SetMinimum( wxInt32 v )
{
::SetControl32BitMinimum( m_controlRef , v );
}
void wxMacControl::SetMaximum( wxInt32 v )
{
::SetControl32BitMaximum( m_controlRef , v );
}
void wxMacControl::SetValueAndRange( SInt32 value , SInt32 minimum , SInt32 maximum )
{
::SetControl32BitMinimum( m_controlRef , minimum );
::SetControl32BitMaximum( m_controlRef , maximum );
::SetControl32BitValue( m_controlRef , value );
}
void wxMacControl::VisibilityChanged(bool WXUNUSED(shown))
{
}
void wxMacControl::SuperChangedPosition()
{
}
void wxMacControl::SetFont( const wxFont & font , const wxColour& foreground , long windowStyle, bool ignoreBlack )
{
m_font = font;
HIViewPartCode part = 0;
HIThemeTextHorizontalFlush flush = kHIThemeTextHorizontalFlushDefault;
if ( ( windowStyle & wxALIGN_MASK ) & wxALIGN_CENTER_HORIZONTAL )
flush = kHIThemeTextHorizontalFlushCenter;
else if ( ( windowStyle & wxALIGN_MASK ) & wxALIGN_RIGHT )
flush = kHIThemeTextHorizontalFlushRight;
HIViewSetTextFont( m_controlRef , part , (CTFontRef) font.OSXGetCTFont() );
HIViewSetTextHorizontalFlush( m_controlRef, part, flush );
if ( foreground != *wxBLACK || ignoreBlack == false )
{
ControlFontStyleRec fontStyle;
foreground.GetRGBColor( &fontStyle.foreColor );
fontStyle.flags = kControlUseForeColorMask;
::SetControlFontStyle( m_controlRef , &fontStyle );
}
#if wxOSX_USE_ATSU_TEXT
ControlFontStyleRec fontStyle;
if ( font.MacGetThemeFontID() != kThemeCurrentPortFont )
{
switch ( font.MacGetThemeFontID() )
{
case kThemeSmallSystemFont :
fontStyle.font = kControlFontSmallSystemFont;
break;
case 109 : // mini font
fontStyle.font = -5;
break;
case kThemeSystemFont :
fontStyle.font = kControlFontBigSystemFont;
break;
default :
fontStyle.font = kControlFontBigSystemFont;
break;
}
fontStyle.flags = kControlUseFontMask;
}
else
{
fontStyle.font = font.MacGetFontNum();
fontStyle.style = font.MacGetFontStyle();
fontStyle.size = font.GetPointSize();
fontStyle.flags = kControlUseFontMask | kControlUseFaceMask | kControlUseSizeMask;
}
fontStyle.just = teJustLeft;
fontStyle.flags |= kControlUseJustMask;
if ( ( windowStyle & wxALIGN_MASK ) & wxALIGN_CENTER_HORIZONTAL )
fontStyle.just = teJustCenter;
else if ( ( windowStyle & wxALIGN_MASK ) & wxALIGN_RIGHT )
fontStyle.just = teJustRight;
// we only should do this in case of a non-standard color, as otherwise 'disabled' controls
// won't get grayed out by the system anymore
if ( foreground != *wxBLACK || ignoreBlack == false )
{
foreground.GetRGBColor( &fontStyle.foreColor );
fontStyle.flags |= kControlUseForeColorMask;
}
::SetControlFontStyle( m_controlRef , &fontStyle );
#endif
}
void wxMacControl::SetBackgroundColour( const wxColour &WXUNUSED(col) )
{
// HITextViewSetBackgroundColor( m_textView , color );
}
bool wxMacControl::SetBackgroundStyle(wxBackgroundStyle style)
{
if ( style != wxBG_STYLE_PAINT )
{
OSStatus err = HIViewChangeFeatures(m_controlRef , 0 , kHIViewIsOpaque);
verify_noerr( err );
}
else
{
OSStatus err = HIViewChangeFeatures(m_controlRef , kHIViewIsOpaque , 0);
verify_noerr( err );
}
return true ;
}
void wxMacControl::SetRange( SInt32 minimum , SInt32 maximum )
{
::SetControl32BitMinimum( m_controlRef , minimum );
::SetControl32BitMaximum( m_controlRef , maximum );
}
short wxMacControl::HandleKey( SInt16 keyCode, SInt16 charCode, EventModifiers modifiers )
{
return HandleControlKey( m_controlRef , keyCode , charCode , modifiers );
}
void wxMacControl::SetActionProc( ControlActionUPP actionProc )
{
SetControlAction( m_controlRef , actionProc );
}
SInt32 wxMacControl::GetViewSize() const
{
return GetControlViewSize( m_controlRef );
}
bool wxMacControl::IsVisible() const
{
return IsControlVisible( m_controlRef );
}
void wxMacControl::SetVisibility( bool visible )
{
SetControlVisibility( m_controlRef , visible, true );
}
bool wxMacControl::IsEnabled() const
{
return IsControlEnabled( m_controlRef );
}
bool wxMacControl::IsActive() const
{
return IsControlActive( m_controlRef );
}
void wxMacControl::Enable( bool enable )
{
if ( enable )
EnableControl( m_controlRef );
else
DisableControl( m_controlRef );
}
void wxMacControl::SetDrawingEnabled( bool enable )
{
if ( enable )
{
HIViewSetDrawingEnabled( m_controlRef , true );
HIViewSetNeedsDisplay( m_controlRef, true);
}
else
{
HIViewSetDrawingEnabled( m_controlRef , false );
}
}
void wxMacControl::GetRectInWindowCoords( Rect *r )
{
GetControlBounds( m_controlRef , r ) ;
WindowRef tlwref = GetControlOwner( m_controlRef ) ;
wxNonOwnedWindow* tlwwx = wxNonOwnedWindow::GetFromWXWindow( (WXWindow) tlwref ) ;
if ( tlwwx != NULL )
{
ControlRef rootControl = tlwwx->GetPeer()->GetControlRef() ;
HIPoint hiPoint = CGPointMake( 0 , 0 ) ;
HIViewConvertPoint( &hiPoint , HIViewGetSuperview(m_controlRef) , rootControl ) ;
OffsetRect( r , (short) hiPoint.x , (short) hiPoint.y ) ;
}
}
void wxMacControl::GetBestRect( wxRect *rect ) const
{
short baselineoffset;
Rect r = {0,0,0,0};
GetBestControlRect( m_controlRef , &r , &baselineoffset );
*rect = wxRect( r.left, r.top, r.right - r.left, r.bottom-r.top );
}
void wxMacControl::GetBestRect( Rect *r ) const
{
short baselineoffset;
GetBestControlRect( m_controlRef , r , &baselineoffset );
}
void wxMacControl::SetLabel( const wxString &title , wxFontEncoding encoding)
{
SetControlTitleWithCFString( m_controlRef , wxCFStringRef( title , encoding ) );
}
void wxMacControl::GetFeatures( UInt32 * features )
{
GetControlFeatures( m_controlRef , features );
}
void wxMacControl::PulseGauge()
{
}
// SetNeedsDisplay would not invalidate the children
static void InvalidateControlAndChildren( HIViewRef control )
{
HIViewSetNeedsDisplay( control , true );
UInt16 childrenCount = 0;
OSStatus err = CountSubControls( control , &childrenCount );
if ( err == errControlIsNotEmbedder )
return;
wxASSERT_MSG( err == noErr , wxT("Unexpected error when accessing subcontrols") );
for ( UInt16 i = childrenCount; i >=1; --i )
{
HIViewRef child;
err = GetIndexedSubControl( control , i , & child );
if ( err == errControlIsNotEmbedder )
return;
InvalidateControlAndChildren( child );
}
}
void wxMacControl::InvalidateWithChildren()
{
InvalidateControlAndChildren( m_controlRef );
}
OSType wxMacCreator = 'WXMC';
OSType wxMacControlProperty = 'MCCT';
void wxMacControl::SetReferenceInNativeControl()
{
void * data = this;
verify_noerr( SetControlProperty ( m_controlRef ,
wxMacCreator,wxMacControlProperty, sizeof(data), &data ) );
}
wxMacControl* wxMacControl::GetReferenceFromNativeControl(ControlRef control)
{
wxMacControl* ctl = NULL;
ByteCount actualSize;
if ( GetControlProperty( control ,wxMacCreator,wxMacControlProperty, sizeof(ctl) ,
&actualSize , &ctl ) == noErr )
{
return ctl;
}
return NULL;
}
wxBitmap wxMacControl::GetBitmap() const
{
return wxNullBitmap;
}
void wxMacControl::SetBitmap( const wxBitmap& WXUNUSED(bmp) )
{
// implemented in the respective subclasses
}
void wxMacControl::SetBitmapPosition( wxDirection WXUNUSED(dir) )
{
// implemented in the same subclasses that implement SetBitmap()
}
void wxMacControl::SetScrollThumb( wxInt32 WXUNUSED(pos), wxInt32 WXUNUSED(viewsize) )
{
// implemented in respective subclass
}
//
// Tab Control
//
OSStatus wxMacControl::SetTabEnabled( SInt16 tabNo , bool enable )
{
return ::SetTabEnabled( m_controlRef , tabNo , enable );
}
// Control Factory
wxWidgetImplType* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now )
{
// There is a bug in 10.2.X for ::GetRootControl returning the window view instead of
// the content view, so we have to retrieve it explicitly
wxMacControl* contentview = new wxMacControl(now , true /*isRootControl*/);
HIViewFindByID( HIViewGetRoot( (WindowRef) now->GetWXWindow() ) , kHIViewWindowContentID ,
contentview->GetControlRefAddr() ) ;
if ( !contentview->IsOk() )
{
// compatibility mode fallback
GetRootControl( (WindowRef) now->GetWXWindow() , contentview->GetControlRefAddr() ) ;
}
// the root control level handler
if ( !now->IsNativeWindowWrapper() )
contentview->InstallEventHandler() ;
return contentview;
}
|
/*
Copyright (c) 2011, Intel Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
This file implements simple task systems that provide the three
entrypoints used by ispc-generated to code to handle 'launch' and 'sync'
statements in ispc programs. See the section "Task Parallelism: Language
Syntax" in the ispc documentation for information about using task
parallelism in ispc programs, and see the section "Task Parallelism:
Runtime Requirements" for information about the task-related entrypoints
that are implemented here.
There are three task systems in this file: one built using Microsoft's
Concurrency Runtime, one built with Apple's Grand Central Dispatch, and
one built on top of bare pthreads.
*/
#if defined(_WIN32) || defined(_WIN64)
#define ISPC_IS_WINDOWS
#define ISPC_USE_CONCRT
#elif defined(__linux__)
#define ISPC_IS_LINUX
#define ISPC_USE_PTHREADS
#elif defined(__APPLE__)
#define ISPC_IS_APPLE
#define ISPC_USE_GCD
#endif
#define DBG(x)
#ifdef ISPC_IS_WINDOWS
#define NOMINMAX
#include <windows.h>
#endif // ISPC_IS_WINDOWS
#ifdef ISPC_USE_CONCRT
#include <concrt.h>
using namespace Concurrency;
#endif // ISPC_USE_CONCRT
#ifdef ISPC_USE_GCD
#include <dispatch/dispatch.h>
#include <pthread.h>
#endif // ISPC_USE_GCD
#ifdef ISPC_USE_PTHREADS
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <sys/sysctl.h>
#include <vector>
#include <algorithm>
#endif // ISPC_USE_PTHREADS
#ifdef ISPC_IS_LINUX
#include <malloc.h>
#endif // ISPC_IS_LINUX
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <algorithm>
// Signature of ispc-generated 'task' functions
typedef void (*TaskFuncType)(void *data, int threadIndex, int threadCount,
int taskIndex, int taskCount);
// Small structure used to hold the data for each task
struct TaskInfo {
TaskFuncType func;
void *data;
int taskIndex, taskCount;
#if defined(ISPC_IS_WINDOWS)
event taskEvent;
#endif
};
///////////////////////////////////////////////////////////////////////////
// TaskGroupBase
#define LOG_TASK_QUEUE_CHUNK_SIZE 14
#define MAX_TASK_QUEUE_CHUNKS 8
#define TASK_QUEUE_CHUNK_SIZE (1<<LOG_TASK_QUEUE_CHUNK_SIZE)
#define MAX_LAUNCHED_TASKS (MAX_TASK_QUEUE_CHUNKS * TASK_QUEUE_CHUNK_SIZE)
#define NUM_MEM_BUFFERS 16
class TaskGroup;
/** The TaskGroupBase structure provides common functionality for "task
groups"; a task group is the set of tasks launched from within a single
ispc function. When the function is ready to return, it waits for all
of the tasks in its task group to finish before it actually returns.
*/
class TaskGroupBase {
public:
void Reset();
int AllocTaskInfo(int count);
TaskInfo *GetTaskInfo(int index);
void *AllocMemory(int64_t size, int32_t alignment);
protected:
TaskGroupBase();
~TaskGroupBase();
int nextTaskInfoIndex;
private:
/* We allocate blocks of TASK_QUEUE_CHUNK_SIZE TaskInfo structures as
needed by the calling function. We hold up to MAX_TASK_QUEUE_CHUNKS
of these (and then exit at runtime if more than this many tasks are
launched.)
*/
TaskInfo *taskInfo[MAX_TASK_QUEUE_CHUNKS];
/* We also allocate chunks of memory to service ISPCAlloc() calls. The
memBuffers[] array holds pointers to this memory. The first element
of this array is initialized to point to mem and then any subsequent
elements required are initialized with dynamic allocation.
*/
int curMemBuffer, curMemBufferOffset;
int memBufferSize[NUM_MEM_BUFFERS];
char *memBuffers[NUM_MEM_BUFFERS];
char mem[256];
};
inline TaskGroupBase::TaskGroupBase() {
nextTaskInfoIndex = 0;
curMemBuffer = 0;
curMemBufferOffset = 0;
memBuffers[0] = mem;
memBufferSize[0] = sizeof(mem) / sizeof(mem[0]);
for (int i = 1; i < NUM_MEM_BUFFERS; ++i) {
memBuffers[i] = NULL;
memBufferSize[i] = 0;
}
for (int i = 0; i < MAX_TASK_QUEUE_CHUNKS; ++i)
taskInfo[i] = NULL;
}
inline TaskGroupBase::~TaskGroupBase() {
// Note: don't delete memBuffers[0], since it points to the start of
// the "mem" member!
for (int i = 1; i < NUM_MEM_BUFFERS; ++i)
delete[] memBuffers[i];
}
inline void
TaskGroupBase::Reset() {
nextTaskInfoIndex = 0;
curMemBuffer = 0;
curMemBufferOffset = 0;
}
inline int
TaskGroupBase::AllocTaskInfo(int count) {
int ret = nextTaskInfoIndex;
nextTaskInfoIndex += count;
return ret;
}
inline TaskInfo *
TaskGroupBase::GetTaskInfo(int index) {
int chunk = (index >> LOG_TASK_QUEUE_CHUNK_SIZE);
int offset = index & (TASK_QUEUE_CHUNK_SIZE-1);
if (chunk == MAX_TASK_QUEUE_CHUNKS) {
fprintf(stderr, "A total of %d tasks have been launched from the "
"current function--the simple built-in task system can handle "
"no more. You can increase the values of TASK_QUEUE_CHUNK_SIZE "
"and LOG_TASK_QUEUE_CHUNK_SIZE to work around this limitation. "
"Sorry! Exiting.\n", index);
exit(1);
}
if (taskInfo[chunk] == NULL)
taskInfo[chunk] = new TaskInfo[TASK_QUEUE_CHUNK_SIZE];
return &taskInfo[chunk][offset];
}
inline void *
TaskGroupBase::AllocMemory(int64_t size, int32_t alignment) {
char *basePtr = memBuffers[curMemBuffer];
int64_t iptr = (int64_t)(basePtr + curMemBufferOffset);
iptr = (iptr + (alignment-1)) & ~(alignment-1);
int newOffset = int(iptr + size - (int64_t)basePtr);
if (newOffset < memBufferSize[curMemBuffer]) {
curMemBufferOffset = newOffset;
return (char *)iptr;
}
++curMemBuffer;
curMemBufferOffset = 0;
assert(curMemBuffer < NUM_MEM_BUFFERS);
int allocSize = 1 << (12 + curMemBuffer);
allocSize = std::max(int(size+alignment), allocSize);
char *newBuf = new char[allocSize];
memBufferSize[curMemBuffer] = allocSize;
memBuffers[curMemBuffer] = newBuf;
return AllocMemory(size, alignment);
}
///////////////////////////////////////////////////////////////////////////
// Atomics and the like
#ifndef ISPC_IS_WINDOWS
static inline void
lMemFence() {
__asm__ __volatile__("mfence":::"memory");
}
#endif // !ISPC_IS_WINDOWS
#if (__SIZEOF_POINTER__ == 4) || defined(__i386__) || defined(_WIN32)
#define ISPC_POINTER_BYTES 4
#elif (__SIZEOF_POINTER__ == 8) || defined(__x86_64__) || defined(__amd64__) || defined(_WIN64)
#define ISPC_POINTER_BYTES 8
#else
#error "Pointer size unknown!"
#endif // __SIZEOF_POINTER__
static void *
lAtomicCompareAndSwapPointer(void **v, void *newValue, void *oldValue) {
#ifdef ISPC_IS_WINDOWS
return InterlockedCompareExchangePointer(v, newValue, oldValue);
#else
void *result;
#if (ISPC_POINTER_BYTES == 4)
__asm__ __volatile__("lock\ncmpxchgd %2,%1"
: "=a"(result), "=m"(*v)
: "q"(newValue), "0"(oldValue)
: "memory");
#else
__asm__ __volatile__("lock\ncmpxchgq %2,%1"
: "=a"(result), "=m"(*v)
: "q"(newValue), "0"(oldValue)
: "memory");
#endif // ISPC_POINTER_BYTES
lMemFence();
return result;
#endif // ISPC_IS_WINDOWS
}
#ifndef ISPC_IS_WINDOWS
static int32_t
lAtomicCompareAndSwap32(volatile int32_t *v, int32_t newValue, int32_t oldValue) {
int32_t result;
__asm__ __volatile__("lock\ncmpxchgl %2,%1"
: "=a"(result), "=m"(*v)
: "q"(newValue), "0"(oldValue)
: "memory");
lMemFence();
return result;
}
#endif // !ISPC_IS_WINDOWS
///////////////////////////////////////////////////////////////////////////
#ifdef ISPC_USE_CONCRT
// With ConcRT, we don't need to extend TaskGroupBase at all.
class TaskGroup : public TaskGroupBase {
public:
void Launch(int baseIndex, int count);
void Sync();
};
#endif // ISPC_USE_CONCRT
#ifdef ISPC_USE_GCD
/* With Grand Central Dispatch, we associate a GCD dispatch group with each
task group. (We'll later wait on this dispatch group when we need to
wait on all of the tasks in the group to finish.)
*/
class TaskGroup : public TaskGroupBase {
public:
TaskGroup() {
gcdGroup = dispatch_group_create();
}
void Launch(int baseIndex, int count);
void Sync();
private:
dispatch_group_t gcdGroup;
};
#endif // ISPC_USE_GCD
#ifdef ISPC_USE_PTHREADS
static void *lTaskEntry(void *arg);
class TaskGroup : public TaskGroupBase {
public:
TaskGroup() {
numUnfinishedTasks = 0;
waitingTasks.reserve(128);
inActiveList = false;
}
void Reset() {
TaskGroupBase::Reset();
numUnfinishedTasks = 0;
assert(inActiveList == false);
lMemFence();
}
void Launch(int baseIndex, int count);
void Sync();
private:
friend void *lTaskEntry(void *arg);
int32_t numUnfinishedTasks;
int32_t pad[3];
std::vector<int> waitingTasks;
bool inActiveList;
};
#endif // ISPC_USE_PTHREADS
///////////////////////////////////////////////////////////////////////////
// Grand Central Dispatch
#ifdef ISPC_USE_GCD
/* A simple task system for ispc programs based on Apple's Grand Central
Dispatch. */
static dispatch_queue_t gcdQueue;
static volatile int32_t lock = 0;
static void
InitTaskSystem() {
if (gcdQueue != NULL)
return;
while (1) {
if (lAtomicCompareAndSwap32(&lock, 1, 0) == 0) {
if (gcdQueue == NULL) {
gcdQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
assert(gcdQueue != NULL);
lMemFence();
}
lock = 0;
break;
}
}
}
static void
lRunTask(void *ti) {
TaskInfo *taskInfo = (TaskInfo *)ti;
// FIXME: these are bogus values; may cause bugs in code that depends
// on them having unique values in different threads.
int threadIndex = 0;
int threadCount = 1;
// Actually run the task
taskInfo->func(taskInfo->data, threadIndex, threadCount,
taskInfo->taskIndex, taskInfo->taskCount);
}
inline void
TaskGroup::Launch(int baseIndex, int count) {
for (int i = 0; i < count; ++i) {
TaskInfo *ti = GetTaskInfo(baseIndex + i);
dispatch_group_async_f(gcdGroup, gcdQueue, ti, lRunTask);
}
}
inline void
TaskGroup::Sync() {
dispatch_group_wait(gcdGroup, DISPATCH_TIME_FOREVER);
}
#endif // ISPC_USE_GCD
///////////////////////////////////////////////////////////////////////////
// Concurrency Runtime
#ifdef ISPC_USE_CONCRT
static void
InitTaskSystem() {
// No initialization needed
}
static void __cdecl
lRunTask(LPVOID param) {
TaskInfo *ti = (TaskInfo *)param;
// Actually run the task.
// FIXME: like the GCD implementation for OS X, this is passing bogus
// values for the threadIndex and threadCount builtins, which in turn
// will cause bugs in code that uses those.
int threadIndex = 0;
int threadCount = 1;
ti->func(ti->data, threadIndex, threadCount, ti->taskIndex, ti->taskCount);
// Signal the event that this task is done
ti->taskEvent.set();
}
inline void
TaskGroup::Launch(int baseIndex, int count) {
for (int i = 0; i < count; ++i)
CurrentScheduler::ScheduleTask(lRunTask, GetTaskInfo(baseIndex + i));
}
inline void
TaskGroup::Sync() {
for (int i = 0; i < nextTaskInfoIndex; ++i) {
TaskInfo *ti = GetTaskInfo(i);
ti->taskEvent.wait();
ti->taskEvent.reset();
}
}
#endif // ISPC_USE_CONCRT
///////////////////////////////////////////////////////////////////////////
// pthreads
#ifdef ISPC_USE_PTHREADS
static volatile int32_t lock = 0;
static int nThreads;
static pthread_t *threads = NULL;
static pthread_mutex_t taskSysMutex;
static std::vector<TaskGroup *> activeTaskGroups;
static sem_t *workerSemaphore;
static inline int32_t
lAtomicAdd(int32_t *v, int32_t delta) {
int32_t origValue;
__asm__ __volatile__("lock\n"
"xaddl %0,%1"
: "=r"(origValue), "=m"(*v) : "0"(delta)
: "memory");
return origValue;
}
static void *
lTaskEntry(void *arg) {
int threadIndex = (int)((int64_t)arg);
int threadCount = nThreads;
while (1) {
int err;
//
// Wait on the semaphore until we're woken up due to the arrival of
// more work.
//
if ((err = sem_wait(workerSemaphore)) != 0) {
fprintf(stderr, "Error from sem_wait: %s\n", strerror(err));
exit(1);
}
//
// Acquire the mutex
//
if ((err = pthread_mutex_lock(&taskSysMutex)) != 0) {
fprintf(stderr, "Error from pthread_mutex_lock: %s\n", strerror(err));
exit(1);
}
if (activeTaskGroups.size() == 0) {
//
// Task queue is empty, go back and wait on the semaphore
//
if ((err = pthread_mutex_unlock(&taskSysMutex)) != 0) {
fprintf(stderr, "Error from pthread_mutex_unlock: %s\n", strerror(err));
exit(1);
}
continue;
}
//
// Get the last task group on the active list and the last task
// from its waiting tasks list.
//
TaskGroup *tg = activeTaskGroups.back();
assert(tg->waitingTasks.size() > 0);
int taskNumber = tg->waitingTasks.back();
tg->waitingTasks.pop_back();
if (tg->waitingTasks.size() == 0) {
// We just took the last task from this task group, so remove
// it from the active list.
activeTaskGroups.pop_back();
tg->inActiveList = false;
}
if ((err = pthread_mutex_unlock(&taskSysMutex)) != 0) {
fprintf(stderr, "Error from pthread_mutex_unlock: %s\n", strerror(err));
exit(1);
}
//
// And now actually run the task
//
DBG(fprintf(stderr, "running task %d from group %p\n", taskNumber, tg));
TaskInfo *myTask = tg->GetTaskInfo(taskNumber);
myTask->func(myTask->data, threadIndex, threadCount, myTask->taskIndex,
myTask->taskCount);
//
// Decrement the "number of unfinished tasks" counter in the task
// group.
//
lMemFence();
lAtomicAdd(&tg->numUnfinishedTasks, -1);
}
pthread_exit(NULL);
return 0;
}
static void
InitTaskSystem() {
if (threads == NULL) {
while (1) {
if (lAtomicCompareAndSwap32(&lock, 1, 0) == 0) {
if (threads == NULL) {
// We launch one fewer thread than there are cores,
// since the main thread here will also grab jobs from
// the task queue itself.
nThreads = sysconf(_SC_NPROCESSORS_ONLN) - 1;
int err;
if ((err = pthread_mutex_init(&taskSysMutex, NULL)) != 0) {
fprintf(stderr, "Error creating mutex: %s\n", strerror(err));
exit(1);
}
char name[32];
sprintf(name, "ispc_task.%d", (int)getpid());
workerSemaphore = sem_open(name, O_CREAT, S_IRUSR|S_IWUSR, 0);
if (!workerSemaphore) {
fprintf(stderr, "Error creating semaphore: %s\n", strerror(err));
exit(1);
}
threads = (pthread_t *)malloc(nThreads * sizeof(pthread_t));
for (intptr_t i = 0; i < nThreads; ++i) {
err = pthread_create(&threads[i], NULL, &lTaskEntry, (void *) i);
if (err != 0) {
fprintf(stderr, "Error creating pthread %lu: %s\n", i, strerror(err));
exit(1);
}
}
activeTaskGroups.reserve(64);
}
// Make sure all of the above goes to memory before we
// clear the lock.
lMemFence();
lock = 0;
break;
}
}
}
}
inline void
TaskGroup::Launch(int baseCoord, int count) {
//
// Acquire mutex, add task
//
int err;
if ((err = pthread_mutex_lock(&taskSysMutex)) != 0) {
fprintf(stderr, "Error from pthread_mutex_lock: %s\n", strerror(err));
exit(1);
}
// Add the corresponding set of tasks to the waiting-to-be-run list for
// this task group.
//
// FIXME: it's a little ugly to hold a global mutex for this when we
// only need to make sure no one else is accessing this task group's
// waitingTasks list. (But a small experiment in switching to a
// per-TaskGroup mutex showed worse performance!)
for (int i = 0; i < count; ++i)
waitingTasks.push_back(baseCoord + i);
// Add the task group to the global active list if it isn't there
// already.
if (inActiveList == false) {
activeTaskGroups.push_back(this);
inActiveList = true;
}
if ((err = pthread_mutex_unlock(&taskSysMutex)) != 0) {
fprintf(stderr, "Error from pthread_mutex_unlock: %s\n", strerror(err));
exit(1);
}
//
// Update the count of the number of tasks left to run in this task
// group.
//
lMemFence();
lAtomicAdd(&numUnfinishedTasks, count);
//
// Post to the worker semaphore to wake up worker threads that are
// sleeping waiting for tasks to show up
//
for (int i = 0; i < count; ++i)
if ((err = sem_post(workerSemaphore)) != 0) {
fprintf(stderr, "Error from sem_post: %s\n", strerror(err));
exit(1);
}
}
inline void
TaskGroup::Sync() {
DBG(fprintf(stderr, "syncing %p - %d unfinished\n", tg, numUnfinishedTasks));
while (numUnfinishedTasks > 0) {
// All of the tasks in this group aren't finished yet. We'll try
// to help out here since we don't have anything else to do...
DBG(fprintf(stderr, "while syncing %p - %d unfinished\n", tg,
numUnfinishedTasks));
//
// Acquire the global task system mutex to grab a task to work on
//
int err;
if ((err = pthread_mutex_lock(&taskSysMutex)) != 0) {
fprintf(stderr, "Error from pthread_mutex_lock: %s\n", strerror(err));
exit(1);
}
TaskInfo *myTask = NULL;
TaskGroup *runtg = this;
if (waitingTasks.size() > 0) {
int taskNumber = waitingTasks.back();
waitingTasks.pop_back();
if (waitingTasks.size() == 0) {
// There's nothing left to start running from this group,
// so remove it from the active task list.
activeTaskGroups.erase(std::find(activeTaskGroups.begin(),
activeTaskGroups.end(), this));
inActiveList = false;
}
myTask = GetTaskInfo(taskNumber);
DBG(fprintf(stderr, "running task %d from group %p in sync\n", taskNumber, tg));
}
else {
// Other threads are already working on all of the tasks in
// this group, so we can't help out by running one ourself.
// We'll try to run one from another group to make ourselves
// useful here.
if (activeTaskGroups.size() == 0) {
// No active task groups left--there's nothing for us to do.
if ((err = pthread_mutex_unlock(&taskSysMutex)) != 0) {
fprintf(stderr, "Error from pthread_mutex_unlock: %s\n", strerror(err));
exit(1);
}
// FIXME: We basically end up busy-waiting here, which is
// extra wasteful in a world with hyperthreading. It would
// be much better to put this thread to sleep on a
// condition variable that was signaled when the last task
// in this group was finished.
sleep(0);
continue;
}
// Get a task to run from another task group.
runtg = activeTaskGroups.back();
assert(runtg->waitingTasks.size() > 0);
int taskNumber = runtg->waitingTasks.back();
runtg->waitingTasks.pop_back();
if (runtg->waitingTasks.size() == 0) {
// There's left to start running from this group, so remove
// it from the active task list.
activeTaskGroups.pop_back();
runtg->inActiveList = false;
}
myTask = runtg->GetTaskInfo(taskNumber);
DBG(fprintf(stderr, "running task %d from other group %p in sync\n",
taskNumber, runtg));
}
if ((err = pthread_mutex_unlock(&taskSysMutex)) != 0) {
fprintf(stderr, "Error from pthread_mutex_unlock: %s\n", strerror(err));
exit(1);
}
//
// Do work for _myTask_
//
// FIXME: bogus values for thread index/thread count here as well..
myTask->func(myTask->data, 0, 1, myTask->taskIndex, myTask->taskCount);
//
// Decrement the number of unfinished tasks counter
//
lMemFence();
lAtomicAdd(&runtg->numUnfinishedTasks, -1);
}
DBG(fprintf(stderr, "sync for %p done!n", tg));
}
#endif // ISPC_USE_PTHREADS
///////////////////////////////////////////////////////////////////////////
#define MAX_FREE_TASK_GROUPS 64
static TaskGroup *freeTaskGroups[MAX_FREE_TASK_GROUPS];
static inline TaskGroup *
AllocTaskGroup() {
for (int i = 0; i < MAX_FREE_TASK_GROUPS; ++i) {
TaskGroup *tg = freeTaskGroups[i];
if (tg != NULL) {
void *ptr = lAtomicCompareAndSwapPointer((void **)(&freeTaskGroups[i]), NULL, tg);
if (ptr != NULL) {
assert(ptr == tg);
return (TaskGroup *)ptr;
}
}
}
return new TaskGroup;
}
static inline void
FreeTaskGroup(TaskGroup *tg) {
tg->Reset();
for (int i = 0; i < MAX_FREE_TASK_GROUPS; ++i) {
if (freeTaskGroups[i] == NULL) {
void *ptr = lAtomicCompareAndSwapPointer((void **)&freeTaskGroups[i], tg, NULL);
if (ptr == NULL)
return;
}
}
delete tg;
}
///////////////////////////////////////////////////////////////////////////
// ispc expects these functions to have C linkage / not be mangled
extern "C" {
void ISPCLaunch(void **handlePtr, void *f, void *data, int count);
void *ISPCAlloc(void **handlePtr, int64_t size, int32_t alignment);
void ISPCSync(void *handle);
}
void
ISPCLaunch(void **taskGroupPtr, void *func, void *data, int count) {
TaskGroup *taskGroup;
if (*taskGroupPtr == NULL) {
InitTaskSystem();
taskGroup = AllocTaskGroup();
*taskGroupPtr = taskGroup;
}
else
taskGroup = (TaskGroup *)(*taskGroupPtr);
int baseIndex = taskGroup->AllocTaskInfo(count);
for (int i = 0; i < count; ++i) {
TaskInfo *ti = taskGroup->GetTaskInfo(baseIndex+i);
ti->func = (TaskFuncType)func;
ti->data = data;
ti->taskIndex = i;
ti->taskCount = count;
}
taskGroup->Launch(baseIndex, count);
}
void
ISPCSync(void *h) {
TaskGroup *taskGroup = (TaskGroup *)h;
if (taskGroup != NULL) {
taskGroup->Sync();
FreeTaskGroup(taskGroup);
}
}
void *
ISPCAlloc(void **taskGroupPtr, int64_t size, int32_t alignment) {
TaskGroup *taskGroup;
if (*taskGroupPtr == NULL) {
InitTaskSystem();
taskGroup = AllocTaskGroup();
*taskGroupPtr = taskGroup;
}
else
taskGroup = (TaskGroup *)(*taskGroupPtr);
return taskGroup->AllocMemory(size, alignment);
}
|
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* contains source code from the article "Radix Sort Revisited".
* \file IceRevisitedRadix.cpp
* \author Pierre Terdiman
* \date April, 4, 2000
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Revisited Radix Sort.
* This is my new radix routine:
* - it uses indices and doesn't recopy the values anymore, hence wasting less ram
* - it creates all the histograms in one run instead of four
* - it sorts words faster than dwords and bytes faster than words
* - it correctly sorts negative floating-point values by patching the offsets
* - it automatically takes advantage of temporal coherence
* - multiple keys support is a side effect of temporal coherence
* - it may be worth recoding in asm... (mainly to use FCOMI, FCMOV, etc) [it's probably memory-bound anyway]
*
* History:
* - 08.15.98: very first version
* - 04.04.00: recoded for the radix article
* - 12.xx.00: code lifting
* - 09.18.01: faster CHECK_PASS_VALIDITY thanks to Mark D. Shattuck (who provided other tips, not included here)
* - 10.11.01: added local ram support
* - 01.20.02: bugfix! In very particular cases the last pass was skipped in the float code-path, leading to incorrect
*sorting......
*
* \class RadixSort
* \author Pierre Terdiman
* \version 1.3
* \date August, 15, 1998
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
To do:
- add an offset parameter between two input values (avoid some data recopy sometimes)
- unroll ? asm ?
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Precompiled Header
#include <ork/gfx/radixsort.h>
#include <ork/pch.h>
namespace ork {
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
RadixSort::RadixSort()
: _indices(nullptr)
, _indices2(nullptr)
, _currentSize(0)
, _previousSize(0)
, _totalCalls(0)
, _numBhits(0) {
_histogram = new uint32_t[HISTOSIZE];
_offset = new uint32_t[HISTOSIZE];
resetIndices();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Destructor.
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
RadixSort::~RadixSort() {
delete[] _offset;
delete[] _histogram;
if (_indices2)
delete[] _indices2;
if (_indices)
delete[] _indices;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void RadixSort::CHECK_RESIZE(size_t n) {
if (n > _currentSize) {
if (_indices)
delete[] _indices;
if (_indices2)
delete[] _indices2;
_indices = new uint32_t[n];
_indices2 = new uint32_t[n];
_currentSize = n;
}
// Initialize indices so that the input buffer is read in sequential order
resetIndices();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define CHECK_PASS_VALIDITY(pass) \
/* Shortcut to current counters */ \
uint32_t* CurCount = &_histogram[pass << 8]; \
\
/* Reset flag. The sorting pass is supposed to be performed. (default) */ \
bool PerformPass = true; \
\
/* Check pass validity */ \
\
/* If all values have the same byte, sorting is useless. */ \
/* It may happen when sorting bytes or words instead of dwords. */ \
/* This routine actually sorts words faster than dwords, and bytes */ \
/* faster than words. Standard running time (O(4*n))is reduced to O(2*n) */ \
/* for words and O(n) for bytes. Running time for floats depends on actual values... */ \
\
/* Get first byte */ \
uint8_t UniqueVal = *(((uint8_t*)input) + pass); \
\
/* Check that byte's counter */ \
if (CurCount[UniqueVal] == nb) \
PerformPass = false;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Main sort routine.
* This one is for integer values. After the call, _indices contains a list of indices in sorted order, i.e. in the order you may
*process your data. \param input [in] a list of integer values to sort
* \param nb [in] number of values to sort
* \param signedvalues [in] true to handle negative values, false if you know your input buffer only contains positive
*values \return Self-Reference
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
RadixSort& RadixSort::Sort(const uint32_t* input, size_t nb, bool signedvalues) {
// Checkings
if (!input || !nb)
return *this;
// Stats
_totalCalls++;
// resize lists if needed
CHECK_RESIZE(nb);
// Create histograms (counters). Counters for all passes are created in one run.
// Pros: read input buffer once instead of four times
// Cons: _histogram is 4Kb instead of 1Kb
// We must take care of signed/unsigned values for temporal coherence.... I just
// have 2 code paths even if just a single opcode changes. Self-modifying code, someone?
if (!signedvalues) {
bool AlreadySorted = CREATE_HISTOGRAMS<uint32_t>(input, nb);
if (AlreadySorted) {
return *this;
}
} else {
bool AlreadySorted = CREATE_HISTOGRAMS<S32>((S32*)input, nb);
if (AlreadySorted) {
return *this;
}
}
// Compute #negative values involved if needed
uint32_t NbNegativeValues = 0;
if (signedvalues) {
// An efficient way to compute the number of negatives values we'll have to deal with is simply to sum the 128
// last values of the last histogram. Last histogram because that's the one for the Most Significant Byte,
// responsible for the sign. 128 last values because the 128 first ones are related to positive numbers.
uint32_t* h3 = &_histogram[768];
for (uint32_t i = 128; i < 256; i++)
NbNegativeValues += h3[i]; // 768 for last histogram, 128 for negative part
}
// Radix sort, j is the pass number (0=LSB, 3=MSB)
for (uint32_t j = 0; j < 4; j++) {
uint32_t k = j;
CHECK_PASS_VALIDITY(k);
// Sometimes the fourth (negative) pass is skipped because all numbers are negative and the MSB is 0xFF (for example). This is
// not a problem, numbers are correctly sorted anyway.
if (PerformPass) {
// Should we care about negative values?
if (k != 3 || !signedvalues) {
// Here we deal with positive values only
// Create offsets
_offset[0] = 0;
for (uint32_t i = 1; i < 256; i++)
_offset[i] = _offset[i - 1] + CurCount[i - 1];
} else {
// This is a special case to correctly handle negative integers. They're sorted in the right order but at the wrong place.
// Create biased offsets, in order for negative numbers to be sorted as well
_offset[0] = NbNegativeValues; // First positive number takes place after the negative ones
for (uint32_t i = 1; i < 128; i++)
_offset[i] = _offset[i - 1] + CurCount[i - 1]; // 1 to 128 for positive numbers
// Fixing the wrong place for negative values
_offset[128] = 0;
for (uint32_t i = 129; i < 256; i++)
_offset[i] = _offset[i - 1] + CurCount[i - 1];
}
// Perform Radix Sort
uint8_t* InputBytes = (uint8_t*)input;
uint32_t* Indices = _indices;
uint32_t* IndicesEnd = &_indices[nb];
InputBytes += k;
while (Indices != IndicesEnd) {
uint32_t id = *Indices++;
_indices2[_offset[InputBytes[id << 2]]++] = id;
}
// Swap pointers for next pass. Valid indices - the most recent ones - are in _indices after the swap.
uint32_t* Tmp = _indices;
_indices = _indices2;
_indices2 = Tmp;
}
}
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Main sort routine.
* This one is for floating-point values. After the call, _indices contains a list of indices in sorted order, i.e. in the order
*you may process your data. \param input [in] a list of floating-point values to sort \param nb [in]
*number of values to sort \return Self-Reference \warning only sorts IEEE floating-point values
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
RadixSort& RadixSort::Sort(const float* input2, size_t nb) {
// Checkings
if (!input2 || !nb)
return *this;
// Stats
_totalCalls++;
uint32_t* input = (uint32_t*)input2;
// resize lists if needed
CHECK_RESIZE(nb);
// Create histograms (counters). Counters for all passes are created in one run.
// Pros: read input buffer once instead of four times
// Cons: _histogram is 4Kb instead of 1Kb
// Floating-point values are always supposed to be signed values, so there's only one code path there.
// Please note the floating point comparison needed for temporal coherence! Although the resulting asm code
// is dreadful, this is surprisingly not such a performance hit - well, I suppose that's a big one on first
// generation Pentiums....We can't make comparison on integer representations because, as Chris said, it just
// wouldn't work with mixed positive/negative values....
{ CREATE_HISTOGRAMS<float>(input2, nb); }
// Compute #negative values involved if needed
uint32_t NbNegativeValues = 0;
// An efficient way to compute the number of negatives values we'll have to deal with is simply to sum the 128
// last values of the last histogram. Last histogram because that's the one for the Most Significant Byte,
// responsible for the sign. 128 last values because the 128 first ones are related to positive numbers.
uint32_t* h3 = &_histogram[768];
for (uint32_t i = 128; i < 256; i++)
NbNegativeValues += h3[i]; // 768 for last histogram, 128 for negative part
// Radix sort, j is the pass number (0=LSB, 3=MSB)
for (uint32_t j = 0; j < 4; j++) {
uint32_t k = j;
// Should we care about negative values?
if (k != 3) {
// Here we deal with positive values only
CHECK_PASS_VALIDITY(k);
if (PerformPass) {
// Create offsets
_offset[0] = 0;
for (uint32_t i = 1; i < 256; i++)
_offset[i] = _offset[i - 1] + CurCount[i - 1];
// Perform Radix Sort
uint8_t* InputBytes = (uint8_t*)input;
uint32_t* Indices = _indices;
uint32_t* IndicesEnd = &_indices[nb];
InputBytes += k;
while (Indices != IndicesEnd) {
uint32_t id = *Indices++;
_indices2[_offset[InputBytes[id << 2]]++] = id;
}
// Swap pointers for next pass. Valid indices - the most recent ones - are in _indices after the swap.
uint32_t* Tmp = _indices;
_indices = _indices2;
_indices2 = Tmp;
}
} else {
// This is a special case to correctly handle negative values
CHECK_PASS_VALIDITY(k);
if (PerformPass) {
// Create biased offsets, in order for negative numbers to be sorted as well
_offset[0] = NbNegativeValues; // First positive number takes place after the negative ones
for (uint32_t i = 1; i < 128; i++)
_offset[i] = _offset[i - 1] + CurCount[i - 1]; // 1 to 128 for positive numbers
// We must reverse the sorting order for negative numbers!
_offset[255] = 0;
for (uint32_t i = 0; i < 127; i++)
_offset[254 - i] = _offset[255 - i] + CurCount[255 - i]; // Fixing the wrong order for negative values
for (uint32_t i = 128; i < 256; i++)
_offset[i] += CurCount[i]; // Fixing the wrong place for negative values
// Perform Radix Sort
for (uint32_t i = 0; i < nb; i++) {
uint32_t Radix = input[_indices[i]] >> 24; // Radix byte, same as above. AND is useless here (uint32_t).
// ### cmp to be killed. Not good. Later.
if (Radix < 128)
_indices2[_offset[Radix]++] = _indices[i]; // Number is positive, same as above
else
_indices2[--_offset[Radix]] = _indices[i]; // Number is negative, flip the sorting order
}
// Swap pointers for next pass. Valid indices - the most recent ones - are in _indices after the swap.
uint32_t* Tmp = _indices;
_indices = _indices2;
_indices2 = Tmp;
} else {
// The pass is useless, yet we still have to reverse the order of current list if all values are negative.
if (UniqueVal >= 128) {
for (uint32_t i = 0; i < nb; i++)
_indices2[i] = _indices[nb - i - 1];
// Swap pointers for next pass. Valid indices - the most recent ones - are in _indices after the swap.
uint32_t* Tmp = _indices;
_indices = _indices2;
_indices2 = Tmp;
}
}
}
}
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Resets the inner indices. After the call, _indices is reset.
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void RadixSort::resetIndices() {
for (uint32_t i = 0; i < _currentSize; i++)
_indices[i] = i;
}
} // namespace ork
|
// SplitHandler.cpp
#include "StdAfx.h"
#include "../../Common/ComTry.h"
#include "../../Common/MyString.h"
#include "../../Windows/PropVariant.h"
#include "../Common/ProgressUtils.h"
#include "../Common/RegisterArc.h"
#include "../Compress/CopyCoder.h"
#include "Common/MultiStream.h"
using namespace NWindows;
namespace NArchive {
namespace NSplit {
static const Byte kProps[] =
{
kpidPath,
kpidSize
};
static const Byte kArcProps[] =
{
kpidNumVolumes,
kpidTotalPhySize
};
class CHandler final :
public IInArchive,
public IInArchiveGetStream,
public CMyUnknownImp
{
CObjectVector<CMyComPtr<IInStream> > _streams;
CRecordVector<UInt64> _sizes;
UString _subName;
UInt64 _totalSize;
HRESULT Open2(IInStream *stream, IArchiveOpenCallback *callback);
public:
MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream)
INTERFACE_IInArchive(;)
STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
};
IMP_IInArchive_Props
IMP_IInArchive_ArcProps
STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
{
NCOM::CPropVariant prop;
switch (propID)
{
case kpidMainSubfile: prop = (UInt32)0; break;
case kpidPhySize: if (!_sizes.IsEmpty()) prop = _sizes[0]; break;
case kpidTotalPhySize: prop = _totalSize; break;
case kpidNumVolumes: prop = (UInt32)_streams.Size(); break;
}
prop.Detach(value);
return S_OK;
}
struct CSeqName final
{
UString _unchangedPart;
UString _changedPart;
bool _splitStyle;
bool GetNextName(UString &s)
{
{
unsigned i = _changedPart.Len();
for (;;)
{
wchar_t c = _changedPart[--i];
if (_splitStyle)
{
if (c == 'z')
{
_changedPart.ReplaceOneCharAtPos(i, L'a');
if (i == 0)
return false;
continue;
}
else if (c == 'Z')
{
_changedPart.ReplaceOneCharAtPos(i, L'A');
if (i == 0)
return false;
continue;
}
}
else
{
if (c == '9')
{
_changedPart.ReplaceOneCharAtPos(i, L'0');
if (i == 0)
{
_changedPart.InsertAtFront(L'1');
break;
}
continue;
}
}
c++;
_changedPart.ReplaceOneCharAtPos(i, c);
break;
}
}
s = _unchangedPart + _changedPart;
return true;
}
};
HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
{
Close();
if (!callback)
return S_FALSE;
CMyComPtr<IArchiveOpenVolumeCallback> volumeCallback;
callback->QueryInterface(IID_IArchiveOpenVolumeCallback, (void **)&volumeCallback);
if (!volumeCallback)
return S_FALSE;
UString name;
{
NCOM::CPropVariant prop;
RINOK(volumeCallback->GetProperty(kpidName, &prop));
if (prop.vt != VT_BSTR)
return S_FALSE;
name = prop.bstrVal;
}
int dotPos = name.ReverseFind_Dot();
const UString prefix = name.Left(dotPos + 1);
const UString ext = name.Ptr(dotPos + 1);
UString ext2 = ext;
ext2.MakeLower_Ascii();
CSeqName seqName;
unsigned numLetters = 2;
bool splitStyle = false;
if (ext2.Len() >= 2 && StringsAreEqual_Ascii(ext2.RightPtr(2), "aa"))
{
splitStyle = true;
while (numLetters < ext2.Len())
{
if (ext2[ext2.Len() - numLetters - 1] != 'a')
break;
numLetters++;
}
}
else if (ext.Len() >= 2 && StringsAreEqual_Ascii(ext2.RightPtr(2), "01"))
{
while (numLetters < ext2.Len())
{
if (ext2[ext2.Len() - numLetters - 1] != '0')
break;
numLetters++;
}
if (numLetters != ext.Len())
return S_FALSE;
}
else
return S_FALSE;
seqName._unchangedPart = prefix + ext.Left(ext2.Len() - numLetters);
seqName._changedPart = ext.RightPtr(numLetters);
seqName._splitStyle = splitStyle;
if (prefix.Len() < 1)
_subName = "file";
else
_subName.SetFrom(prefix, prefix.Len() - 1);
UInt64 size;
{
/*
NCOM::CPropVariant prop;
RINOK(volumeCallback->GetProperty(kpidSize, &prop));
if (prop.vt != VT_UI8)
return E_INVALIDARG;
size = prop.uhVal.QuadPart;
*/
RINOK(stream->Seek(0, STREAM_SEEK_END, &size));
RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL));
}
_totalSize += size;
_sizes.Add(size);
_streams.Add(stream);
{
const UInt64 numFiles = _streams.Size();
RINOK(callback->SetCompleted(&numFiles, NULL));
}
for (;;)
{
UString fullName;
if (!seqName.GetNextName(fullName))
break;
CMyComPtr<IInStream> nextStream;
HRESULT result = volumeCallback->GetStream(fullName, &nextStream);
if (result == S_FALSE)
break;
if (result != S_OK)
return result;
if (!nextStream)
break;
{
/*
NCOM::CPropVariant prop;
RINOK(volumeCallback->GetProperty(kpidSize, &prop));
if (prop.vt != VT_UI8)
return E_INVALIDARG;
size = prop.uhVal.QuadPart;
*/
RINOK(nextStream->Seek(0, STREAM_SEEK_END, &size));
RINOK(nextStream->Seek(0, STREAM_SEEK_SET, NULL));
}
_totalSize += size;
_sizes.Add(size);
_streams.Add(nextStream);
{
const UInt64 numFiles = _streams.Size();
RINOK(callback->SetCompleted(&numFiles, NULL));
}
}
if (_streams.Size() == 1)
{
if (splitStyle)
return S_FALSE;
}
return S_OK;
}
STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback)
{
COM_TRY_BEGIN
HRESULT res = Open2(stream, callback);
if (res != S_OK)
Close();
return res;
COM_TRY_END
}
STDMETHODIMP CHandler::Close()
{
_totalSize = 0;
_subName.Empty();
_streams.Clear();
_sizes.Clear();
return S_OK;
}
STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems)
{
*numItems = _streams.IsEmpty() ? 0 : 1;
return S_OK;
}
STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value)
{
NCOM::CPropVariant prop;
switch (propID)
{
case kpidPath: prop = _subName; break;
case kpidSize:
case kpidPackSize:
prop = _totalSize;
break;
}
prop.Detach(value);
return S_OK;
}
STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
Int32 testMode, IArchiveExtractCallback *extractCallback)
{
COM_TRY_BEGIN
if (numItems == 0)
return S_OK;
if (numItems != (UInt32)(Int32)-1 && (numItems != 1 || indices[0] != 0))
return E_INVALIDARG;
UInt64 currentTotalSize = 0;
RINOK(extractCallback->SetTotal(_totalSize));
CMyComPtr<ISequentialOutStream> outStream;
Int32 askMode = testMode ?
NExtract::NAskMode::kTest :
NExtract::NAskMode::kExtract;
RINOK(extractCallback->GetStream(0, &outStream, askMode));
if (!testMode && !outStream)
return S_OK;
RINOK(extractCallback->PrepareOperation(askMode));
NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder;
CMyComPtr<ICompressCoder> copyCoder = copyCoderSpec;
CLocalProgress *lps = new CLocalProgress;
CMyComPtr<ICompressProgressInfo> progress = lps;
lps->Init(extractCallback, false);
FOR_VECTOR (i, _streams)
{
lps->InSize = lps->OutSize = currentTotalSize;
RINOK(lps->SetCur());
IInStream *inStream = _streams[i];
RINOK(inStream->Seek(0, STREAM_SEEK_SET, NULL));
RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress));
currentTotalSize += copyCoderSpec->TotalSize;
}
outStream.Release();
return extractCallback->SetOperationResult(NExtract::NOperationResult::kOK);
COM_TRY_END
}
STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream)
{
COM_TRY_BEGIN
if (index != 0)
return E_INVALIDARG;
*stream = 0;
CMultiStream *streamSpec = new CMultiStream;
CMyComPtr<ISequentialInStream> streamTemp = streamSpec;
FOR_VECTOR (i, _streams)
{
CMultiStream::CSubStreamInfo subStreamInfo;
subStreamInfo.Stream = _streams[i];
subStreamInfo.Size = _sizes[i];
streamSpec->Streams.Add(subStreamInfo);
}
streamSpec->Init();
*stream = streamTemp.Detach();
return S_OK;
COM_TRY_END
}
REGISTER_ARC_I_NO_SIG(
"Split", "001", 0, 0xEA,
0,
0,
NULL)
}}
#if defined(LIBPLZMA_USING_REGISTRATORS)
uint64_t plzma_registrator_2(void) {
return NArchive::NSplit::g_ArcInfo.Flags;
}
#endif
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <wallet/wallet.h>
#include <chain.h>
#include <consensus/consensus.h>
#include <consensus/validation.h>
#include <fs.h>
#include <interfaces/chain.h>
#include <interfaces/wallet.h>
#include <key.h>
#include <key_io.h>
#include <optional.h>
#include <policy/fees.h>
#include <policy/policy.h>
#include <primitives/block.h>
#include <primitives/transaction.h>
#include <script/descriptor.h>
#include <script/script.h>
#include <script/signingprovider.h>
#include <txmempool.h>
#include <util/bip32.h>
#include <util/error.h>
#include <util/fees.h>
#include <util/moneystr.h>
#include <util/rbf.h>
#include <util/translation.h>
#include <wallet/coincontrol.h>
#include <wallet/fees.h>
#include <miner.h>
#include <qtep/qtepledger.h>
#include <algorithm>
#include <assert.h>
#include <boost/algorithm/string/replace.hpp>
const std::map<uint64_t,std::string> WALLET_FLAG_CAVEATS{
{WALLET_FLAG_AVOID_REUSE,
"You need to rescan the blockchain in order to correctly mark used "
"destinations in the past. Until this is done, some destinations may "
"be considered unused, even if the opposite is the case."
},
};
static const size_t OUTPUT_GROUP_MAX_ENTRIES = 10;
static RecursiveMutex cs_wallets;
static std::vector<std::shared_ptr<CWallet>> vpwallets GUARDED_BY(cs_wallets);
static std::list<LoadWalletFn> g_load_wallet_fns GUARDED_BY(cs_wallets);
CConnman* CWallet::defaultConnman = 0;
bool AddWallet(const std::shared_ptr<CWallet>& wallet)
{
LOCK(cs_wallets);
assert(wallet);
std::vector<std::shared_ptr<CWallet>>::const_iterator i = std::find(vpwallets.begin(), vpwallets.end(), wallet);
if (i != vpwallets.end()) return false;
vpwallets.push_back(wallet);
wallet->ConnectScriptPubKeyManNotifiers();
return true;
}
bool RemoveWallet(const std::shared_ptr<CWallet>& wallet)
{
assert(wallet);
// Unregister with the validation interface which also drops shared ponters.
wallet->m_chain_notifications_handler.reset();
LOCK(cs_wallets);
std::vector<std::shared_ptr<CWallet>>::iterator i = std::find(vpwallets.begin(), vpwallets.end(), wallet);
if (i == vpwallets.end()) return false;
vpwallets.erase(i);
return true;
}
bool HasWallets()
{
LOCK(cs_wallets);
return !vpwallets.empty();
}
std::vector<std::shared_ptr<CWallet>> GetWallets()
{
LOCK(cs_wallets);
return vpwallets;
}
std::shared_ptr<CWallet> GetWallet(const std::string& name)
{
LOCK(cs_wallets);
for (const std::shared_ptr<CWallet>& wallet : vpwallets) {
if (wallet->GetName() == name) return wallet;
}
return nullptr;
}
std::unique_ptr<interfaces::Handler> HandleLoadWallet(LoadWalletFn load_wallet)
{
LOCK(cs_wallets);
auto it = g_load_wallet_fns.emplace(g_load_wallet_fns.end(), std::move(load_wallet));
return interfaces::MakeHandler([it] { LOCK(cs_wallets); g_load_wallet_fns.erase(it); });
}
static Mutex g_loading_wallet_mutex;
static Mutex g_wallet_release_mutex;
static std::condition_variable g_wallet_release_cv;
static std::set<std::string> g_loading_wallet_set GUARDED_BY(g_loading_wallet_mutex);
static std::set<std::string> g_unloading_wallet_set GUARDED_BY(g_wallet_release_mutex);
// Custom deleter for shared_ptr<CWallet>.
static void ReleaseWallet(CWallet* wallet)
{
const std::string name = wallet->GetName();
wallet->WalletLogPrintf("Releasing wallet\n");
wallet->StopStake();
wallet->Flush();
delete wallet;
// Wallet is now released, notify UnloadWallet, if any.
{
LOCK(g_wallet_release_mutex);
if (g_unloading_wallet_set.erase(name) == 0) {
// UnloadWallet was not called for this wallet, all done.
return;
}
}
g_wallet_release_cv.notify_all();
}
void UnloadWallet(std::shared_ptr<CWallet>&& wallet)
{
// Mark wallet for unloading.
const std::string name = wallet->GetName();
{
LOCK(g_wallet_release_mutex);
auto it = g_unloading_wallet_set.insert(name);
assert(it.second);
}
// The wallet can be in use so it's not possible to explicitly unload here.
// Notify the unload intent so that all remaining shared pointers are
// released.
wallet->NotifyUnload();
// Time to ditch our shared_ptr and wait for ReleaseWallet call.
wallet.reset();
{
WAIT_LOCK(g_wallet_release_mutex, lock);
while (g_unloading_wallet_set.count(name) == 1) {
g_wallet_release_cv.wait(lock);
}
}
}
namespace {
std::shared_ptr<CWallet> LoadWalletInternal(interfaces::Chain& chain, const WalletLocation& location, std::string& error, std::vector<std::string>& warnings)
{
try {
if (!CWallet::Verify(chain, location, false, error, warnings)) {
error = "Wallet file verification failed: " + error;
return nullptr;
}
std::shared_ptr<CWallet> wallet = CWallet::CreateWalletFromFile(chain, location, error, warnings);
if (!wallet) {
error = "Wallet loading failed: " + error;
return nullptr;
}
AddWallet(wallet);
wallet->postInitProcess();
return wallet;
} catch (const std::runtime_error& e) {
error = e.what();
return nullptr;
}
}
} // namespace
std::shared_ptr<CWallet> LoadWallet(interfaces::Chain& chain, const WalletLocation& location, std::string& error, std::vector<std::string>& warnings)
{
auto result = WITH_LOCK(g_loading_wallet_mutex, return g_loading_wallet_set.insert(location.GetName()));
if (!result.second) {
error = "Wallet already being loading.";
return nullptr;
}
auto wallet = LoadWalletInternal(chain, location, error, warnings);
WITH_LOCK(g_loading_wallet_mutex, g_loading_wallet_set.erase(result.first));
return wallet;
}
std::shared_ptr<CWallet> LoadWallet(interfaces::Chain& chain, const std::string& name, std::string& error, std::vector<std::string>& warnings)
{
return LoadWallet(chain, WalletLocation(name), error, warnings);
}
WalletCreationStatus CreateWallet(interfaces::Chain& chain, const SecureString& passphrase, uint64_t wallet_creation_flags, const std::string& name, std::string& error, std::vector<std::string>& warnings, std::shared_ptr<CWallet>& result)
{
// Indicate that the wallet is actually supposed to be blank and not just blank to make it encrypted
bool create_blank = (wallet_creation_flags & WALLET_FLAG_BLANK_WALLET);
// Born encrypted wallets need to be created blank first.
if (!passphrase.empty()) {
wallet_creation_flags |= WALLET_FLAG_BLANK_WALLET;
}
// Check the wallet file location
WalletLocation location(name);
if (location.Exists()) {
error = "Wallet " + location.GetName() + " already exists.";
return WalletCreationStatus::CREATION_FAILED;
}
// Wallet::Verify will check if we're trying to create a wallet with a duplicate name.
if (!CWallet::Verify(chain, location, false, error, warnings)) {
error = "Wallet file verification failed: " + error;
return WalletCreationStatus::CREATION_FAILED;
}
// Do not allow a passphrase when private keys are disabled
if (!passphrase.empty() && (wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
error = "Passphrase provided but private keys are disabled. A passphrase is only used to encrypt private keys, so cannot be used for wallets with private keys disabled.";
return WalletCreationStatus::CREATION_FAILED;
}
// Make the wallet
std::shared_ptr<CWallet> wallet = CWallet::CreateWalletFromFile(chain, location, error, warnings, wallet_creation_flags);
if (!wallet) {
error = "Wallet creation failed: " + error;
return WalletCreationStatus::CREATION_FAILED;
}
// Encrypt the wallet
if (!passphrase.empty() && !(wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
if (!wallet->EncryptWallet(passphrase)) {
error = "Error: Wallet created but failed to encrypt.";
return WalletCreationStatus::ENCRYPTION_FAILED;
}
if (!create_blank) {
// Unlock the wallet
if (!wallet->Unlock(passphrase)) {
error = "Error: Wallet was encrypted but could not be unlocked";
return WalletCreationStatus::ENCRYPTION_FAILED;
}
// Set a seed for the wallet
{
LOCK(wallet->cs_wallet);
for (auto spk_man : wallet->GetActiveScriptPubKeyMans()) {
if (!spk_man->SetupGeneration()) {
error = "Unable to generate initial keys";
return WalletCreationStatus::CREATION_FAILED;
}
}
}
// Relock the wallet
wallet->Lock();
}
}
AddWallet(wallet);
wallet->postInitProcess();
result = wallet;
return WalletCreationStatus::SUCCESS;
}
const uint256 CWalletTx::ABANDON_HASH(UINT256_ONE());
/** @defgroup mapWallet
*
* @{
*/
std::string COutput::ToString() const
{
return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->tx->vout[i].nValue));
}
const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
{
LOCK(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
if (it == mapWallet.end())
return nullptr;
return &(it->second);
}
void CWallet::UpgradeKeyMetadata()
{
if (IsLocked() || IsWalletFlagSet(WALLET_FLAG_KEY_ORIGIN_METADATA)) {
return;
}
auto spk_man = GetLegacyScriptPubKeyMan();
if (!spk_man) {
return;
}
spk_man->UpgradeKeyMetadata();
SetWalletFlag(WALLET_FLAG_KEY_ORIGIN_METADATA);
}
bool CWallet::Unlock(const SecureString& strWalletPassphrase, bool accept_no_keys)
{
CCrypter crypter;
CKeyingMaterial _vMasterKey;
{
LOCK(cs_wallet);
for (const MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
{
if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
continue; // try another master key
if (Unlock(_vMasterKey, accept_no_keys)) {
// Now that we've unlocked, upgrade the key metadata
UpgradeKeyMetadata();
return true;
}
}
}
return false;
}
bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
{
bool fWasLocked = IsLocked();
{
LOCK(cs_wallet);
Lock();
CCrypter crypter;
CKeyingMaterial _vMasterKey;
for (MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
{
if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
return false;
if (Unlock(_vMasterKey))
{
int64_t nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
pMasterKey.second.nDeriveIterations = static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))));
nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime)))) / 2;
if (pMasterKey.second.nDeriveIterations < 25000)
pMasterKey.second.nDeriveIterations = 25000;
WalletLogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey))
return false;
WalletBatch(*database).WriteMasterKey(pMasterKey.first, pMasterKey.second);
if (fWasLocked)
Lock();
return true;
}
}
}
return false;
}
void CWallet::chainStateFlushed(const CBlockLocator& loc)
{
WalletBatch batch(*database);
batch.WriteBestBlock(loc);
}
void CWallet::SetMinVersion(enum WalletFeature nVersion, WalletBatch* batch_in, bool fExplicit)
{
LOCK(cs_wallet);
if (nWalletVersion >= nVersion)
return;
// when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
if (fExplicit && nVersion > nWalletMaxVersion)
nVersion = FEATURE_LATEST;
nWalletVersion = nVersion;
if (nVersion > nWalletMaxVersion)
nWalletMaxVersion = nVersion;
{
WalletBatch* batch = batch_in ? batch_in : new WalletBatch(*database);
if (nWalletVersion > 40000)
batch->WriteMinVersion(nWalletVersion);
if (!batch_in)
delete batch;
}
}
bool CWallet::SetMaxVersion(int nVersion)
{
LOCK(cs_wallet);
// cannot downgrade below current version
if (nWalletVersion > nVersion)
return false;
nWalletMaxVersion = nVersion;
return true;
}
std::set<uint256> CWallet::GetConflicts(const uint256& txid) const
{
std::set<uint256> result;
AssertLockHeld(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
if (it == mapWallet.end())
return result;
const CWalletTx& wtx = it->second;
std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
for (const CTxIn& txin : wtx.tx->vin)
{
if (mapTxSpends.count(txin.prevout) <= 1)
continue; // No conflict if zero or one spends
range = mapTxSpends.equal_range(txin.prevout);
for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
result.insert(_it->second);
}
return result;
}
bool CWallet::HasWalletSpend(const uint256& txid) const
{
AssertLockHeld(cs_wallet);
auto iter = mapTxSpends.lower_bound(COutPoint(txid, 0));
return (iter != mapTxSpends.end() && iter->first.hash == txid);
}
void CWallet::Flush(bool shutdown)
{
if(shutdown)
StopStake();
database->Flush(shutdown);
}
void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
{
// We want all the wallet transactions in range to have the same metadata as
// the oldest (smallest nOrderPos).
// So: find smallest nOrderPos:
int nMinOrderPos = std::numeric_limits<int>::max();
const CWalletTx* copyFrom = nullptr;
for (TxSpends::iterator it = range.first; it != range.second; ++it) {
const CWalletTx* wtx = &mapWallet.at(it->second);
if (wtx->nOrderPos < nMinOrderPos) {
nMinOrderPos = wtx->nOrderPos;
copyFrom = wtx;
}
}
if (!copyFrom) {
return;
}
// Now copy data from copyFrom to rest:
for (TxSpends::iterator it = range.first; it != range.second; ++it)
{
const uint256& hash = it->second;
CWalletTx* copyTo = &mapWallet.at(hash);
if (copyFrom == copyTo) continue;
assert(copyFrom && "Oldest wallet transaction in range assumed to have been found.");
if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
copyTo->mapValue = copyFrom->mapValue;
copyTo->vOrderForm = copyFrom->vOrderForm;
// fTimeReceivedIsTxTime not copied on purpose
// nTimeReceived not copied on purpose
copyTo->nTimeSmart = copyFrom->nTimeSmart;
copyTo->fFromMe = copyFrom->fFromMe;
// nOrderPos not copied on purpose
// cached members not copied on purpose
}
}
/**
* Outpoint is spent if any non-conflicted transaction
* spends it:
*/
bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
{
const COutPoint outpoint(hash, n);
std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
range = mapTxSpends.equal_range(outpoint);
for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
{
const uint256& wtxid = it->second;
std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
if (mit != mapWallet.end()) {
int depth = mit->second.GetDepthInMainChain();
if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
return true; // Spent
}
}
return false;
}
void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
{
mapTxSpends.insert(std::make_pair(outpoint, wtxid));
setLockedCoins.erase(outpoint);
std::pair<TxSpends::iterator, TxSpends::iterator> range;
range = mapTxSpends.equal_range(outpoint);
SyncMetaData(range);
}
void CWallet::RemoveFromSpends(const COutPoint& outpoint, const uint256& wtxid)
{
std::pair<TxSpends::iterator, TxSpends::iterator> range;
range = mapTxSpends.equal_range(outpoint);
TxSpends::iterator it = range.first;
for(; it != range.second; ++ it)
{
if(it->second == wtxid)
{
mapTxSpends.erase(it);
break;
}
}
range = mapTxSpends.equal_range(outpoint);
if(range.first != range.second)
SyncMetaData(range);
}
void CWallet::AddToSpends(const uint256& wtxid)
{
auto it = mapWallet.find(wtxid);
assert(it != mapWallet.end());
CWalletTx& thisTx = it->second;
if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
return;
for (const CTxIn& txin : thisTx.tx->vin)
AddToSpends(txin.prevout, wtxid);
}
void CWallet::RemoveFromSpends(const uint256& wtxid)
{
assert(mapWallet.count(wtxid));
CWalletTx& thisTx = mapWallet.at(wtxid);
if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
return;
for(const CTxIn& txin : thisTx.tx->vin)
RemoveFromSpends(txin.prevout, wtxid);
}
bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
{
if (IsCrypted())
return false;
CKeyingMaterial _vMasterKey;
_vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
GetStrongRandBytes(&_vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
CMasterKey kMasterKey;
kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
GetStrongRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
CCrypter crypter;
int64_t nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
kMasterKey.nDeriveIterations = static_cast<unsigned int>(2500000 / ((double)(GetTimeMillis() - nStartTime)));
nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + static_cast<unsigned int>(kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime)))) / 2;
if (kMasterKey.nDeriveIterations < 25000)
kMasterKey.nDeriveIterations = 25000;
WalletLogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
return false;
if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey))
return false;
{
LOCK(cs_wallet);
mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
WalletBatch* encrypted_batch = new WalletBatch(*database);
if (!encrypted_batch->TxnBegin()) {
delete encrypted_batch;
encrypted_batch = nullptr;
return false;
}
encrypted_batch->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
for (const auto& spk_man_pair : m_spk_managers) {
auto spk_man = spk_man_pair.second.get();
if (!spk_man->Encrypt(_vMasterKey, encrypted_batch)) {
encrypted_batch->TxnAbort();
delete encrypted_batch;
encrypted_batch = nullptr;
// We now probably have half of our keys encrypted in memory, and half not...
// die and let the user reload the unencrypted wallet.
assert(false);
}
}
// Encryption was introduced in version 0.4.0
SetMinVersion(FEATURE_WALLETCRYPT, encrypted_batch, true);
if (!encrypted_batch->TxnCommit()) {
delete encrypted_batch;
encrypted_batch = nullptr;
// We now have keys encrypted in memory, but not on disk...
// die to avoid confusion and let the user reload the unencrypted wallet.
assert(false);
}
delete encrypted_batch;
encrypted_batch = nullptr;
Lock();
Unlock(strWalletPassphrase);
// if we are using HD, replace the HD seed with a new one
if (auto spk_man = GetLegacyScriptPubKeyMan()) {
if (spk_man->IsHDEnabled()) {
if (!spk_man->SetupGeneration(true)) {
return false;
}
}
}
Lock();
// Need to completely rewrite the wallet file; if we don't, bdb might keep
// bits of the unencrypted private key in slack space in the database file.
database->Rewrite();
// BDB seems to have a bad habit of writing old data into
// slack space in .dat files; that is bad if the old data is
// unencrypted private keys. So:
database->ReloadDbEnv();
}
NotifyStatusChanged(this);
return true;
}
DBErrors CWallet::ReorderTransactions()
{
LOCK(cs_wallet);
WalletBatch batch(*database);
// Old wallets didn't have any defined order for transactions
// Probably a bad idea to change the output of this
// First: get all CWalletTx into a sorted-by-time multimap.
typedef std::multimap<int64_t, CWalletTx*> TxItems;
TxItems txByTime;
for (auto& entry : mapWallet)
{
CWalletTx* wtx = &entry.second;
txByTime.insert(std::make_pair(wtx->nTimeReceived, wtx));
}
nOrderPosNext = 0;
std::vector<int64_t> nOrderPosOffsets;
for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
{
CWalletTx *const pwtx = (*it).second;
int64_t& nOrderPos = pwtx->nOrderPos;
if (nOrderPos == -1)
{
nOrderPos = nOrderPosNext++;
nOrderPosOffsets.push_back(nOrderPos);
if (!batch.WriteTx(*pwtx))
return DBErrors::LOAD_FAIL;
}
else
{
int64_t nOrderPosOff = 0;
for (const int64_t& nOffsetStart : nOrderPosOffsets)
{
if (nOrderPos >= nOffsetStart)
++nOrderPosOff;
}
nOrderPos += nOrderPosOff;
nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
if (!nOrderPosOff)
continue;
// Since we're changing the order, write it back
if (!batch.WriteTx(*pwtx))
return DBErrors::LOAD_FAIL;
}
}
batch.WriteOrderPosNext(nOrderPosNext);
return DBErrors::LOAD_OK;
}
int64_t CWallet::IncOrderPosNext(WalletBatch* batch)
{
AssertLockHeld(cs_wallet);
int64_t nRet = nOrderPosNext++;
if (batch) {
batch->WriteOrderPosNext(nOrderPosNext);
} else {
WalletBatch(*database).WriteOrderPosNext(nOrderPosNext);
}
return nRet;
}
void CWallet::MarkDirty()
{
{
LOCK(cs_wallet);
for (std::pair<const uint256, CWalletTx>& item : mapWallet)
item.second.MarkDirty();
}
}
bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
{
LOCK(cs_wallet);
auto mi = mapWallet.find(originalHash);
// There is a bug if MarkReplaced is not called on an existing wallet transaction.
assert(mi != mapWallet.end());
CWalletTx& wtx = (*mi).second;
// Ensure for now that we're not overwriting data
assert(wtx.mapValue.count("replaced_by_txid") == 0);
wtx.mapValue["replaced_by_txid"] = newHash.ToString();
WalletBatch batch(*database, "r+");
bool success = true;
if (!batch.WriteTx(wtx)) {
WalletLogPrintf("%s: Updating batch tx %s failed\n", __func__, wtx.GetHash().ToString());
success = false;
}
NotifyTransactionChanged(this, originalHash, CT_UPDATED);
return success;
}
void CWallet::SetSpentKeyState(WalletBatch& batch, const uint256& hash, unsigned int n, bool used, std::set<CTxDestination>& tx_destinations)
{
AssertLockHeld(cs_wallet);
const CWalletTx* srctx = GetWalletTx(hash);
if (!srctx) return;
CTxDestination dst;
if (ExtractDestination(srctx->tx->vout[n].scriptPubKey, dst)) {
if (IsMine(dst)) {
if (used && !GetDestData(dst, "used", nullptr)) {
if (AddDestData(batch, dst, "used", "p")) { // p for "present", opposite of absent (null)
tx_destinations.insert(dst);
}
} else if (!used && GetDestData(dst, "used", nullptr)) {
EraseDestData(batch, dst, "used");
}
}
}
}
bool CWallet::IsSpentKey(const uint256& hash, unsigned int n) const
{
AssertLockHeld(cs_wallet);
CTxDestination dst;
const CWalletTx* srctx = GetWalletTx(hash);
if (srctx) {
assert(srctx->tx->vout.size() > n);
LegacyScriptPubKeyMan* spk_man = GetLegacyScriptPubKeyMan();
// When descriptor wallets arrive, these additional checks are
// likely superfluous and can be optimized out
assert(spk_man != nullptr);
for (const auto& keyid : GetAffectedKeys(srctx->tx->vout[n].scriptPubKey, *spk_man)) {
WitnessV0KeyHash wpkh_dest(keyid);
if (GetDestData(wpkh_dest, "used", nullptr)) {
return true;
}
ScriptHash sh_wpkh_dest(GetScriptForDestination(wpkh_dest));
if (GetDestData(sh_wpkh_dest, "used", nullptr)) {
return true;
}
PKHash pkh_dest(keyid);
if (GetDestData(pkh_dest, "used", nullptr)) {
return true;
}
}
}
return false;
}
bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
{
LOCK(cs_wallet);
WalletBatch batch(*database, "r+", fFlushOnClose);
uint256 hash = wtxIn.GetHash();
if (IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE)) {
// Mark used destinations
std::set<CTxDestination> tx_destinations;
for (const CTxIn& txin : wtxIn.tx->vin) {
const COutPoint& op = txin.prevout;
SetSpentKeyState(batch, op.hash, op.n, true, tx_destinations);
}
MarkDestinationsDirty(tx_destinations);
}
// Inserts only if not already there, returns tx inserted or tx found
std::pair<std::map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(std::make_pair(hash, wtxIn));
CWalletTx& wtx = (*ret.first).second;
wtx.BindWallet(this);
bool fInsertedNew = ret.second;
if (fInsertedNew) {
wtx.nTimeReceived = chain().getAdjustedTime();
wtx.nOrderPos = IncOrderPosNext(&batch);
wtx.m_it_wtxOrdered = wtxOrdered.insert(std::make_pair(wtx.nOrderPos, &wtx));
wtx.nTimeSmart = ComputeTimeSmart(wtx);
AddToSpends(hash);
}
bool fUpdated = false;
if (!fInsertedNew)
{
if (wtxIn.m_confirm.status != wtx.m_confirm.status) {
wtx.m_confirm.status = wtxIn.m_confirm.status;
wtx.m_confirm.nIndex = wtxIn.m_confirm.nIndex;
wtx.m_confirm.hashBlock = wtxIn.m_confirm.hashBlock;
wtx.m_confirm.block_height = wtxIn.m_confirm.block_height;
fUpdated = true;
} else {
assert(wtx.m_confirm.nIndex == wtxIn.m_confirm.nIndex);
assert(wtx.m_confirm.hashBlock == wtxIn.m_confirm.hashBlock);
assert(wtx.m_confirm.block_height == wtxIn.m_confirm.block_height);
}
if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
{
wtx.fFromMe = wtxIn.fFromMe;
fUpdated = true;
}
// If we have a witness-stripped version of this transaction, and we
// see a new version with a witness, then we must be upgrading a pre-segwit
// wallet. Store the new version of the transaction with the witness,
// as the stripped-version must be invalid.
// TODO: Store all versions of the transaction, instead of just one.
if (wtxIn.tx->HasWitness() && !wtx.tx->HasWitness()) {
wtx.SetTx(wtxIn.tx);
fUpdated = true;
}
if(fUpdated && wtx.IsCoinStake())
{
AddToSpends(hash);
}
}
// Update unspent addresses
if(fUpdateAddressUnspentCache)
{
std::map<COutPoint, CScriptCache> insertScriptCache;
for (unsigned int i = 0; i < wtxIn.tx->vout.size(); i++) {
isminetype mine = IsMine(wtxIn.tx->vout[i]);
if (!(IsSpent(hash, i)) && mine != ISMINE_NO &&
!IsLockedCoin(hash, i) && (wtxIn.tx->vout[i].nValue > 0) &&
// Check if the staking coin is dust
wtxIn.tx->vout[i].nValue >= m_staker_min_utxo_size)
{
// Get the script data for the coin
COutPoint prevout = COutPoint(hash, i);
const CScriptCache& scriptCache = GetScriptCache(prevout, wtxIn.tx->vout[i].scriptPubKey, &insertScriptCache);
// Check that the script is not a contract script
if(scriptCache.contract || !scriptCache.keyIdOk)
continue;
if(mapAddressUnspentCache.find(scriptCache.keyId) == mapAddressUnspentCache.end())
{
mapAddressUnspentCache[scriptCache.keyId] = true;
}
}
}
}
//// debug print
WalletLogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
// Write to disk
if (fInsertedNew || fUpdated)
if (!batch.WriteTx(wtx))
return false;
// Break debit/credit balance caches:
wtx.MarkDirty();
// Notify UI of new or updated transaction
NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
#if HAVE_SYSTEM
// notify an external script when a wallet transaction comes in or is updated
std::string strCmd = gArgs.GetArg("-walletnotify", "");
if (!strCmd.empty())
{
boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
#ifndef WIN32
// Substituting the wallet name isn't currently supported on windows
// because windows shell escaping has not been implemented yet:
// https://github.com/bitcoin/bitcoin/pull/13339#issuecomment-537384875
// A few ways it could be implemented in the future are described in:
// https://github.com/bitcoin/bitcoin/pull/13339#issuecomment-461288094
boost::replace_all(strCmd, "%w", ShellEscape(GetName()));
#endif
std::thread t(runCommand, strCmd);
t.detach(); // thread runs free
}
#endif
return true;
}
void CWallet::LoadToWallet(CWalletTx& wtxIn)
{
// If wallet doesn't have a chain (e.g bitcoin-wallet), lock can't be taken.
auto locked_chain = LockChain();
if (locked_chain) {
Optional<int> block_height = locked_chain->getBlockHeight(wtxIn.m_confirm.hashBlock);
if (block_height) {
// Update cached block height variable since it not stored in the
// serialized transaction.
wtxIn.m_confirm.block_height = *block_height;
} else if (wtxIn.isConflicted() || wtxIn.isConfirmed()) {
// If tx block (or conflicting block) was reorged out of chain
// while the wallet was shutdown, change tx status to UNCONFIRMED
// and reset block height, hash, and index. ABANDONED tx don't have
// associated blocks and don't need to be updated. The case where a
// transaction was reorged out while online and then reconfirmed
// while offline is covered by the rescan logic.
wtxIn.setUnconfirmed();
wtxIn.m_confirm.hashBlock = uint256();
wtxIn.m_confirm.block_height = 0;
wtxIn.m_confirm.nIndex = 0;
}
}
uint256 hash = wtxIn.GetHash();
const auto& ins = mapWallet.emplace(hash, wtxIn);
CWalletTx& wtx = ins.first->second;
wtx.BindWallet(this);
if (/* insertion took place */ ins.second) {
wtx.m_it_wtxOrdered = wtxOrdered.insert(std::make_pair(wtx.nOrderPos, &wtx));
}
AddToSpends(hash);
for (const CTxIn& txin : wtx.tx->vin) {
auto it = mapWallet.find(txin.prevout.hash);
if (it != mapWallet.end()) {
CWalletTx& prevtx = it->second;
if (prevtx.isConflicted()) {
MarkConflicted(prevtx.m_confirm.hashBlock, prevtx.m_confirm.block_height, wtx.GetHash());
}
}
}
}
bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, CWalletTx::Confirmation confirm, bool fUpdate)
{
const CTransaction& tx = *ptx;
{
AssertLockHeld(cs_wallet);
if (!confirm.hashBlock.IsNull()) {
for (const CTxIn& txin : tx.vin) {
std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
while (range.first != range.second) {
if (range.first->second != tx.GetHash()) {
WalletLogPrintf("Transaction %s (in block %s) conflicts with wallet transaction %s (both spend %s:%i)\n", tx.GetHash().ToString(), confirm.hashBlock.ToString(), range.first->second.ToString(), range.first->first.hash.ToString(), range.first->first.n);
MarkConflicted(confirm.hashBlock, confirm.block_height, range.first->second);
}
range.first++;
}
}
}
bool fExisted = mapWallet.count(tx.GetHash()) != 0;
if (fExisted && !fUpdate) return false;
if (fExisted || IsMine(tx) || IsFromMe(tx))
{
/* Check if any keys in the wallet keypool that were supposed to be unused
* have appeared in a new transaction. If so, remove those keys from the keypool.
* This can happen when restoring an old wallet backup that does not contain
* the mostly recently created transactions from newer versions of the wallet.
*/
// loop though all outputs
for (const CTxOut& txout: tx.vout) {
for (const auto& spk_man_pair : m_spk_managers) {
spk_man_pair.second->MarkUnusedAddresses(txout.scriptPubKey);
}
}
CWalletTx wtx(this, ptx);
// Block disconnection override an abandoned tx as unconfirmed
// which means user may have to call abandontransaction again
wtx.m_confirm = confirm;
return AddToWallet(wtx, false);
}
}
return false;
}
bool CWallet::TransactionCanBeAbandoned(const uint256& hashTx) const
{
auto locked_chain = chain().lock();
LOCK(cs_wallet);
const CWalletTx* wtx = GetWalletTx(hashTx);
return wtx && !wtx->isAbandoned() && wtx->GetDepthInMainChain() == 0 && !wtx->InMempool();
}
void CWallet::MarkInputsDirty(const CTransactionRef& tx)
{
for (const CTxIn& txin : tx->vin) {
auto it = mapWallet.find(txin.prevout.hash);
if (it != mapWallet.end()) {
it->second.MarkDirty();
}
}
}
bool CWallet::AbandonTransaction(const uint256& hashTx)
{
auto locked_chain = chain().lock(); // Temporary. Removed in upcoming lock cleanup
LOCK(cs_wallet);
WalletBatch batch(*database, "r+");
std::set<uint256> todo;
std::set<uint256> done;
// Can't mark abandoned if confirmed or in mempool
auto it = mapWallet.find(hashTx);
assert(it != mapWallet.end());
CWalletTx& origtx = it->second;
if (origtx.GetDepthInMainChain() != 0 || origtx.InMempool()) {
return false;
}
todo.insert(hashTx);
while (!todo.empty()) {
uint256 now = *todo.begin();
todo.erase(now);
done.insert(now);
auto it = mapWallet.find(now);
assert(it != mapWallet.end());
CWalletTx& wtx = it->second;
int currentconfirm = wtx.GetDepthInMainChain();
// If the orig tx was not in block, none of its spends can be
assert(currentconfirm <= 0);
// if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
if (currentconfirm == 0 && !wtx.isAbandoned()) {
// If the orig tx was not in block/mempool, none of its spends can be in mempool
assert(!wtx.InMempool());
wtx.setAbandoned();
wtx.MarkDirty();
batch.WriteTx(wtx);
NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
// Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
while (iter != mapTxSpends.end() && iter->first.hash == now) {
if (!done.count(iter->second)) {
todo.insert(iter->second);
}
iter++;
}
// If a transaction changes 'conflicted' state, that changes the balance
// available of the outputs it spends. So force those to be recomputed
MarkInputsDirty(wtx.tx);
}
}
return true;
}
void CWallet::MarkConflicted(const uint256& hashBlock, int conflicting_height, const uint256& hashTx)
{
auto locked_chain = chain().lock();
LOCK(cs_wallet);
int conflictconfirms = (m_last_block_processed_height - conflicting_height + 1) * -1;
// If number of conflict confirms cannot be determined, this means
// that the block is still unknown or not yet part of the main chain,
// for example when loading the wallet during a reindex. Do nothing in that
// case.
if (conflictconfirms >= 0)
return;
// Do not flush the wallet here for performance reasons
WalletBatch batch(*database, "r+", false);
std::set<uint256> todo;
std::set<uint256> done;
todo.insert(hashTx);
while (!todo.empty()) {
uint256 now = *todo.begin();
todo.erase(now);
done.insert(now);
auto it = mapWallet.find(now);
assert(it != mapWallet.end());
CWalletTx& wtx = it->second;
int currentconfirm = wtx.GetDepthInMainChain();
if (conflictconfirms < currentconfirm) {
// Block is 'more conflicted' than current confirm; update.
// Mark transaction as conflicted with this block.
wtx.m_confirm.nIndex = 0;
wtx.m_confirm.hashBlock = hashBlock;
wtx.m_confirm.block_height = conflicting_height;
wtx.setConflicted();
wtx.MarkDirty();
batch.WriteTx(wtx);
// Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
while (iter != mapTxSpends.end() && iter->first.hash == now) {
if (!done.count(iter->second)) {
todo.insert(iter->second);
}
iter++;
}
// If a transaction changes 'conflicted' state, that changes the balance
// available of the outputs it spends. So force those to be recomputed
MarkInputsDirty(wtx.tx);
}
}
}
void CWallet::SyncTransaction(const CTransactionRef& ptx, CWalletTx::Confirmation confirm, bool update_tx)
{
if (confirm.hashBlock.IsNull() && confirm.nIndex == -1)
{
// wallets need to refund inputs when disconnecting coinstake
const CTransaction& tx = *ptx;
if (tx.IsCoinStake() && IsFromMe(tx))
{
DisableTransaction(tx);
return;
}
}
if (!AddToWalletIfInvolvingMe(ptx, confirm, update_tx))
return; // Not one of ours
// If a transaction changes 'conflicted' state, that changes the balance
// available of the outputs it spends. So force those to be
// recomputed, also:
MarkInputsDirty(ptx);
}
void CWallet::transactionAddedToMempool(const CTransactionRef& tx) {
LOCK(cs_wallet);
SyncTransaction(tx, {CWalletTx::Status::UNCONFIRMED, /* block height */ 0, /* block hash */ {}, /* index */ 0});
auto it = mapWallet.find(tx->GetHash());
if (it != mapWallet.end()) {
it->second.fInMempool = true;
}
}
void CWallet::transactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason) {
LOCK(cs_wallet);
auto it = mapWallet.find(tx->GetHash());
if (it != mapWallet.end()) {
it->second.fInMempool = false;
}
// Handle transactions that were removed from the mempool because they
// conflict with transactions in a newly connected block.
if (reason == MemPoolRemovalReason::CONFLICT) {
// Call SyncNotifications, so external -walletnotify notifications will
// be triggered for these transactions. Set Status::UNCONFIRMED instead
// of Status::CONFLICTED for a few reasons:
//
// 1. The transactionRemovedFromMempool callback does not currently
// provide the conflicting block's hash and height, and for backwards
// compatibility reasons it may not be not safe to store conflicted
// wallet transactions with a null block hash. See
// https://github.com/bitcoin/bitcoin/pull/18600#discussion_r420195993.
// 2. For most of these transactions, the wallet's internal conflict
// detection in the blockConnected handler will subsequently call
// MarkConflicted and update them with CONFLICTED status anyway. This
// applies to any wallet transaction that has inputs spent in the
// block, or that has ancestors in the wallet with inputs spent by
// the block.
// 3. Longstanding behavior since the sync implementation in
// https://github.com/bitcoin/bitcoin/pull/9371 and the prior sync
// implementation before that was to mark these transactions
// unconfirmed rather than conflicted.
//
// Nothing described above should be seen as an unchangeable requirement
// when improving this code in the future. The wallet's heuristics for
// distinguishing between conflicted and unconfirmed transactions are
// imperfect, and could be improved in general, see
// https://github.com/bitcoin-core/bitcoin-devwiki/wiki/Wallet-Transaction-Conflict-Tracking
SyncTransaction(tx, {CWalletTx::Status::UNCONFIRMED, /* block height */ 0, /* block hash */ {}, /* index */ 0});
}
}
void CWallet::blockConnected(const CBlock& block, int height)
{
const uint256& block_hash = block.GetHash();
auto locked_chain = chain().lock();
LOCK(cs_wallet);
m_last_block_processed_height = height;
m_last_block_processed = block_hash;
for (size_t index = 0; index < block.vtx.size(); index++) {
SyncTransaction(block.vtx[index], {CWalletTx::Status::CONFIRMED, height, block_hash, (int)index});
transactionRemovedFromMempool(block.vtx[index], MemPoolRemovalReason::BLOCK);
}
}
void CWallet::blockDisconnected(const CBlock& block, int height)
{
auto locked_chain = chain().lock();
LOCK(cs_wallet);
// At block disconnection, this will change an abandoned transaction to
// be unconfirmed, whether or not the transaction is added back to the mempool.
// User may have to call abandontransaction again. It may be addressed in the
// future with a stickier abandoned state or even removing abandontransaction call.
m_last_block_processed_height = height - 1;
m_last_block_processed = block.hashPrevBlock;
for (const CTransactionRef& ptx : block.vtx) {
int index = ptx->IsCoinStake() ? -1 : 0;
SyncTransaction(ptx, {CWalletTx::Status::UNCONFIRMED, /* block height */ 0, /* block hash */ {}, index});
}
}
void CWallet::updatedBlockTip()
{
m_best_block_time = GetTime();
}
void CWallet::BlockUntilSyncedToCurrentChain() const {
AssertLockNotHeld(cs_wallet);
// Skip the queue-draining stuff if we know we're caught up with
// ::ChainActive().Tip(), otherwise put a callback in the validation interface queue and wait
// for the queue to drain enough to execute it (indicating we are caught up
// at least with the time we entered this function).
uint256 last_block_hash = WITH_LOCK(cs_wallet, return m_last_block_processed);
chain().waitForNotificationsIfTipChanged(last_block_hash);
}
isminetype CWallet::IsMine(const CTxIn &txin) const
{
{
LOCK(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.tx->vout.size())
return IsMine(prev.tx->vout[txin.prevout.n]);
}
}
return ISMINE_NO;
}
// Note that this function doesn't distinguish between a 0-valued input,
// and a not-"is mine" (according to the filter) input.
CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
{
{
LOCK(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.tx->vout.size())
if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
return prev.tx->vout[txin.prevout.n].nValue;
}
}
return 0;
}
isminetype CWallet::IsMine(const CTxOut& txout) const
{
return IsMine(txout.scriptPubKey);
}
isminetype CWallet::IsMine(const CTxDestination& dest) const
{
return IsMine(GetScriptForDestination(dest));
}
isminetype CWallet::IsMine(const CScript& script) const
{
isminetype result = ISMINE_NO;
for (const auto& spk_man_pair : m_spk_managers) {
result = std::max(result, spk_man_pair.second->IsMine(script));
}
return result;
}
CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
{
if (!MoneyRange(txout.nValue))
throw std::runtime_error(std::string(__func__) + ": value out of range");
return ((IsMine(txout) & filter) ? txout.nValue : 0);
}
bool CWallet::IsChange(const CTxOut& txout) const
{
return IsChange(txout.scriptPubKey);
}
bool CWallet::IsChange(const CScript& script) const
{
// TODO: fix handling of 'change' outputs. The assumption is that any
// payment to a script that is ours, but is not in the address book
// is change. That assumption is likely to break when we implement multisignature
// wallets that return change back into a multi-signature-protected address;
// a better way of identifying which outputs are 'the send' and which are
// 'the change' will need to be implemented (maybe extend CWalletTx to remember
// which output, if any, was change).
if (IsMine(script))
{
CTxDestination address;
if (!ExtractDestination(script, address))
return true;
LOCK(cs_wallet);
if (!FindAddressBookEntry(address)) {
return true;
}
}
return false;
}
CAmount CWallet::GetChange(const CTxOut& txout) const
{
if (!MoneyRange(txout.nValue))
throw std::runtime_error(std::string(__func__) + ": value out of range");
return (IsChange(txout) ? txout.nValue : 0);
}
bool CWallet::IsMine(const CTransaction& tx) const
{
for (const CTxOut& txout : tx.vout)
if (IsMine(txout))
return true;
return false;
}
bool CWallet::IsFromMe(const CTransaction& tx) const
{
return (GetDebit(tx, ISMINE_ALL) > 0);
}
CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
{
CAmount nDebit = 0;
for (const CTxIn& txin : tx.vin)
{
nDebit += GetDebit(txin, filter);
if (!MoneyRange(nDebit))
throw std::runtime_error(std::string(__func__) + ": value out of range");
}
return nDebit;
}
bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
{
LOCK(cs_wallet);
for (const CTxIn& txin : tx.vin)
{
auto mi = mapWallet.find(txin.prevout.hash);
if (mi == mapWallet.end())
return false; // any unknown inputs can't be from us
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n >= prev.tx->vout.size())
return false; // invalid input!
if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
return false;
}
return true;
}
CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
{
CAmount nCredit = 0;
for (const CTxOut& txout : tx.vout)
{
nCredit += GetCredit(txout, filter);
if (!MoneyRange(nCredit))
throw std::runtime_error(std::string(__func__) + ": value out of range");
}
return nCredit;
}
CAmount CWallet::GetChange(const CTransaction& tx) const
{
CAmount nChange = 0;
for (const CTxOut& txout : tx.vout)
{
nChange += GetChange(txout);
if (!MoneyRange(nChange))
throw std::runtime_error(std::string(__func__) + ": value out of range");
}
return nChange;
}
bool CWallet::IsHDEnabled() const
{
bool result = true;
for (const auto& spk_man_pair : m_spk_managers) {
result &= spk_man_pair.second->IsHDEnabled();
}
return result;
}
bool CWallet::CanGetAddresses(bool internal) const
{
LOCK(cs_wallet);
if (m_spk_managers.empty()) return false;
for (OutputType t : OUTPUT_TYPES) {
auto spk_man = GetScriptPubKeyMan(t, internal);
if (spk_man && spk_man->CanGetAddresses(internal)) {
return true;
}
}
return false;
}
void CWallet::SetWalletFlag(uint64_t flags)
{
LOCK(cs_wallet);
m_wallet_flags |= flags;
if (!WalletBatch(*database).WriteWalletFlags(m_wallet_flags))
throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
}
void CWallet::UnsetWalletFlag(uint64_t flag)
{
WalletBatch batch(*database);
UnsetWalletFlagWithDB(batch, flag);
}
void CWallet::UnsetWalletFlagWithDB(WalletBatch& batch, uint64_t flag)
{
LOCK(cs_wallet);
m_wallet_flags &= ~flag;
if (!batch.WriteWalletFlags(m_wallet_flags))
throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
}
void CWallet::UnsetBlankWalletFlag(WalletBatch& batch)
{
UnsetWalletFlagWithDB(batch, WALLET_FLAG_BLANK_WALLET);
}
bool CWallet::IsWalletFlagSet(uint64_t flag) const
{
return (m_wallet_flags & flag);
}
bool CWallet::SetWalletFlags(uint64_t overwriteFlags, bool memonly)
{
LOCK(cs_wallet);
m_wallet_flags = overwriteFlags;
if (((overwriteFlags & KNOWN_WALLET_FLAGS) >> 32) ^ (overwriteFlags >> 32)) {
// contains unknown non-tolerable wallet flags
return false;
}
if (!memonly && !WalletBatch(*database).WriteWalletFlags(m_wallet_flags)) {
throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
}
return true;
}
int64_t CWalletTx::GetTxTime() const
{
int64_t n = nTimeSmart;
return n ? n : nTimeReceived;
}
// Helper for producing a max-sized low-S low-R signature (eg 71 bytes)
// or a max-sized low-S signature (e.g. 72 bytes) if use_max_sig is true
bool CWallet::DummySignInput(CTxIn &tx_in, const CTxOut &txout, bool use_max_sig) const
{
// Fill in dummy signatures for fee calculation.
const CScript& scriptPubKey = txout.scriptPubKey;
SignatureData sigdata;
std::unique_ptr<SigningProvider> provider = GetSolvingProvider(scriptPubKey);
if (!provider) {
// We don't know about this scriptpbuKey;
return false;
}
if (!ProduceSignature(*provider, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, scriptPubKey, sigdata)) {
return false;
}
UpdateInput(tx_in, sigdata);
return true;
}
// Helper for producing a bunch of max-sized low-S low-R signatures (eg 71 bytes)
bool CWallet::DummySignTx(CMutableTransaction &txNew, const std::vector<CTxOut> &txouts, bool use_max_sig) const
{
// Fill in dummy signatures for fee calculation.
int nIn = 0;
for (const auto& txout : txouts)
{
if (!DummySignInput(txNew.vin[nIn], txout, use_max_sig)) {
return false;
}
nIn++;
}
return true;
}
bool CWallet::ImportScripts(const std::set<CScript> scripts, int64_t timestamp)
{
auto spk_man = GetLegacyScriptPubKeyMan();
if (!spk_man) {
return false;
}
LOCK(spk_man->cs_KeyStore);
return spk_man->ImportScripts(scripts, timestamp);
}
bool CWallet::ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp)
{
auto spk_man = GetLegacyScriptPubKeyMan();
if (!spk_man) {
return false;
}
LOCK(spk_man->cs_KeyStore);
return spk_man->ImportPrivKeys(privkey_map, timestamp);
}
bool CWallet::ImportPubKeys(const std::vector<CKeyID>& ordered_pubkeys, const std::map<CKeyID, CPubKey>& pubkey_map, const std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>>& key_origins, const bool add_keypool, const bool internal, const int64_t timestamp)
{
auto spk_man = GetLegacyScriptPubKeyMan();
if (!spk_man) {
return false;
}
LOCK(spk_man->cs_KeyStore);
return spk_man->ImportPubKeys(ordered_pubkeys, pubkey_map, key_origins, add_keypool, internal, timestamp);
}
bool CWallet::ImportScriptPubKeys(const std::string& label, const std::set<CScript>& script_pub_keys, const bool have_solving_data, const bool apply_label, const int64_t timestamp)
{
auto spk_man = GetLegacyScriptPubKeyMan();
if (!spk_man) {
return false;
}
LOCK(spk_man->cs_KeyStore);
if (!spk_man->ImportScriptPubKeys(script_pub_keys, have_solving_data, timestamp)) {
return false;
}
if (apply_label) {
WalletBatch batch(*database);
for (const CScript& script : script_pub_keys) {
CTxDestination dest;
ExtractDestination(script, dest);
if (IsValidDestination(dest)) {
SetAddressBookWithDB(batch, dest, label, "receive");
}
}
}
return true;
}
int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, bool use_max_sig)
{
std::vector<CTxOut> txouts;
for (const CTxIn& input : tx.vin) {
const auto mi = wallet->mapWallet.find(input.prevout.hash);
// Can not estimate size without knowing the input details
if (mi == wallet->mapWallet.end()) {
return -1;
}
assert(input.prevout.n < mi->second.tx->vout.size());
txouts.emplace_back(mi->second.tx->vout[input.prevout.n]);
}
return CalculateMaximumSignedTxSize(tx, wallet, txouts, use_max_sig);
}
// txouts needs to be in the order of tx.vin
int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const std::vector<CTxOut>& txouts, bool use_max_sig)
{
CMutableTransaction txNew(tx);
if (!wallet->DummySignTx(txNew, txouts, use_max_sig)) {
return -1;
}
return GetVirtualTransactionSize(CTransaction(txNew));
}
int CalculateMaximumSignedInputSize(const CTxOut& txout, const CWallet* wallet, bool use_max_sig)
{
CMutableTransaction txn;
txn.vin.push_back(CTxIn(COutPoint()));
if (!wallet->DummySignInput(txn.vin[0], txout, use_max_sig)) {
return -1;
}
return GetVirtualTransactionInputSize(txn.vin[0]);
}
void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
std::list<COutputEntry>& listSent, CAmount& nFee, const isminefilter& filter) const
{
nFee = 0;
listReceived.clear();
listSent.clear();
// Compute fee:
CAmount nDebit = GetDebit(filter);
if (nDebit > 0) // debit>0 means we signed/sent this transaction
{
CAmount nValueOut = tx->GetValueOut();
nFee = nDebit - nValueOut;
}
// Sent/received.
for (unsigned int i = 0; i < tx->vout.size(); ++i)
{
const CTxOut& txout = tx->vout[i];
isminetype fIsMine = pwallet->IsMine(txout);
// Only need to handle txouts if AT LEAST one of these is true:
// 1) they debit from us (sent)
// 2) the output is to us (received)
if (nDebit > 0)
{
// Don't report 'change' txouts
if (pwallet->IsChange(txout))
continue;
}
else if (!(fIsMine & filter))
continue;
// In either case, we need to get the destination address
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
{
pwallet->WalletLogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
this->GetHash().ToString());
address = CNoDestination();
}
COutputEntry output = {address, txout.nValue, (int)i};
// If we are debited by the transaction, add the output as a "sent" entry
if (nDebit > 0)
listSent.push_back(output);
// If we are receiving the output, add it as a "received" entry
if (fIsMine & filter)
listReceived.push_back(output);
}
}
/**
* Scan active chain for relevant transactions after importing keys. This should
* be called whenever new keys are added to the wallet, with the oldest key
* creation time.
*
* @return Earliest timestamp that could be successfully scanned from. Timestamp
* returned will be higher than startTime if relevant blocks could not be read.
*/
int64_t CWallet::RescanFromTime(int64_t startTime, const WalletRescanReserver& reserver, bool update)
{
// Find starting block. May be null if nCreateTime is greater than the
// highest blockchain timestamp, in which case there is nothing that needs
// to be scanned.
uint256 start_block;
{
auto locked_chain = chain().lock();
const Optional<int> start_height = locked_chain->findFirstBlockWithTimeAndHeight(startTime - TIMESTAMP_WINDOW, 0, &start_block);
const Optional<int> tip_height = locked_chain->getHeight();
WalletLogPrintf("%s: Rescanning last %i blocks\n", __func__, tip_height && start_height ? *tip_height - *start_height + 1 : 0);
}
if (!start_block.IsNull()) {
// TODO: this should take into account failure by ScanResult::USER_ABORT
ScanResult result = ScanForWalletTransactions(start_block, {} /* stop_block */, reserver, update);
if (result.status == ScanResult::FAILURE) {
int64_t time_max;
if (!chain().findBlock(result.last_failed_block, nullptr /* block */, nullptr /* time */, &time_max)) {
throw std::logic_error("ScanForWalletTransactions returned invalid block hash");
}
return time_max + TIMESTAMP_WINDOW + 1;
}
}
return startTime;
}
/**
* Scan the block chain (starting in start_block) for transactions
* from or to us. If fUpdate is true, found transactions that already
* exist in the wallet will be updated.
*
* @param[in] start_block Scan starting block. If block is not on the active
* chain, the scan will return SUCCESS immediately.
* @param[in] stop_block Scan ending block. If block is not on the active
* chain, the scan will continue until it reaches the
* chain tip.
*
* @return ScanResult returning scan information and indicating success or
* failure. Return status will be set to SUCCESS if scan was
* successful. FAILURE if a complete rescan was not possible (due to
* pruning or corruption). USER_ABORT if the rescan was aborted before
* it could complete.
*
* @pre Caller needs to make sure start_block (and the optional stop_block) are on
* the main chain after to the addition of any new keys you want to detect
* transactions for.
*/
CWallet::ScanResult CWallet::ScanForWalletTransactions(const uint256& start_block, const uint256& stop_block, const WalletRescanReserver& reserver, bool fUpdate)
{
int64_t nNow = GetTime();
int64_t start_time = GetTimeMillis();
assert(reserver.isReserved());
uint256 block_hash = start_block;
ScanResult result;
WalletLogPrintf("Rescan started from block %s...\n", start_block.ToString());
fAbortRescan = false;
ShowProgress(strprintf("%s " + _("Rescanning...").translated, GetDisplayName()), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
uint256 tip_hash;
// The way the 'block_height' is initialized is just a workaround for the gcc bug #47679 since version 4.6.0.
Optional<int> block_height = MakeOptional(false, int());
double progress_begin;
double progress_end;
{
auto locked_chain = chain().lock();
if (Optional<int> tip_height = locked_chain->getHeight()) {
tip_hash = locked_chain->getBlockHash(*tip_height);
}
block_height = locked_chain->getBlockHeight(block_hash);
progress_begin = chain().guessVerificationProgress(block_hash);
progress_end = chain().guessVerificationProgress(stop_block.IsNull() ? tip_hash : stop_block);
}
double progress_current = progress_begin;
while (block_height && !fAbortRescan && !chain().shutdownRequested()) {
m_scanning_progress = (progress_current - progress_begin) / (progress_end - progress_begin);
if (*block_height % 100 == 0 && progress_end - progress_begin > 0.0) {
ShowProgress(strprintf("%s " + _("Rescanning...").translated, GetDisplayName()), std::max(1, std::min(99, (int)(m_scanning_progress * 100))));
}
if (GetTime() >= nNow + 60) {
nNow = GetTime();
WalletLogPrintf("Still rescanning. At block %d. Progress=%f\n", *block_height, progress_current);
}
CBlock block;
if (chain().findBlock(block_hash, &block) && !block.IsNull()) {
auto locked_chain = chain().lock();
LOCK(cs_wallet);
if (!locked_chain->getBlockHeight(block_hash)) {
// Abort scan if current block is no longer active, to prevent
// marking transactions as coming from the wrong block.
// TODO: This should return success instead of failure, see
// https://github.com/bitcoin/bitcoin/pull/14711#issuecomment-458342518
result.last_failed_block = block_hash;
result.status = ScanResult::FAILURE;
break;
}
for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
SyncTransaction(block.vtx[posInBlock], {CWalletTx::Status::CONFIRMED, *block_height, block_hash, (int)posInBlock}, fUpdate);
}
// scan succeeded, record block as most recent successfully scanned
result.last_scanned_block = block_hash;
result.last_scanned_height = *block_height;
} else {
// could not scan block, keep scanning but record this block as the most recent failure
result.last_failed_block = block_hash;
result.status = ScanResult::FAILURE;
}
if (block_hash == stop_block) {
break;
}
{
auto locked_chain = chain().lock();
Optional<int> tip_height = locked_chain->getHeight();
if (!tip_height || *tip_height <= block_height || !locked_chain->getBlockHeight(block_hash)) {
// break successfully when rescan has reached the tip, or
// previous block is no longer on the chain due to a reorg
break;
}
// increment block and verification progress
block_hash = locked_chain->getBlockHash(++*block_height);
progress_current = chain().guessVerificationProgress(block_hash);
// handle updated tip hash
const uint256 prev_tip_hash = tip_hash;
tip_hash = locked_chain->getBlockHash(*tip_height);
if (stop_block.IsNull() && prev_tip_hash != tip_hash) {
// in case the tip has changed, update progress max
progress_end = chain().guessVerificationProgress(tip_hash);
}
}
}
ShowProgress(strprintf("%s " + _("Rescanning...").translated, GetDisplayName()), 100); // hide progress dialog in GUI
if (block_height && fAbortRescan) {
WalletLogPrintf("Rescan aborted at block %d. Progress=%f\n", *block_height, progress_current);
result.status = ScanResult::USER_ABORT;
} else if (block_height && chain().shutdownRequested()) {
WalletLogPrintf("Rescan interrupted by shutdown request at block %d. Progress=%f\n", *block_height, progress_current);
result.status = ScanResult::USER_ABORT;
} else {
WalletLogPrintf("Rescan completed in %15dms\n", GetTimeMillis() - start_time);
}
return result;
}
void CWallet::ReacceptWalletTransactions()
{
// If transactions aren't being broadcasted, don't let them into local mempool either
if (!fBroadcastTransactions)
return;
std::map<int64_t, CWalletTx*> mapSorted;
// Sort pending wallet transactions based on their initial wallet insertion order
for (std::pair<const uint256, CWalletTx>& item : mapWallet) {
const uint256& wtxid = item.first;
CWalletTx& wtx = item.second;
assert(wtx.GetHash() == wtxid);
int nDepth = wtx.GetDepthInMainChain();
if (!(wtx.IsCoinBase() || wtx.IsCoinStake()) && (nDepth == 0 && !wtx.isAbandoned())) {
mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
}
}
// Try to add wallet transactions to memory pool
for (const std::pair<const int64_t, CWalletTx*>& item : mapSorted) {
CWalletTx& wtx = *(item.second);
std::string unused_err_string;
wtx.SubmitMemoryPoolAndRelay(unused_err_string, false);
}
}
bool CWalletTx::SubmitMemoryPoolAndRelay(std::string& err_string, bool relay)
{
// Can't relay if wallet is not broadcasting
if (!pwallet->GetBroadcastTransactions()) return false;
// Don't relay abandoned transactions
if (isAbandoned()) return false;
// Don't try to submit coinbase transactions. These would fail anyway but would
// cause log spam.
if (IsCoinBase() || IsCoinStake()) return false;
// Don't try to submit conflicted or confirmed transactions.
if (GetDepthInMainChain() != 0) return false;
// Submit transaction to mempool for relay
pwallet->WalletLogPrintf("Submitting wtx %s to mempool for relay\n", GetHash().ToString());
// We must set fInMempool here - while it will be re-set to true by the
// entered-mempool callback, if we did not there would be a race where a
// user could call sendmoney in a loop and hit spurious out of funds errors
// because we think that this newly generated transaction's change is
// unavailable as we're not yet aware that it is in the mempool.
//
// Irrespective of the failure reason, un-marking fInMempool
// out-of-order is incorrect - it should be unmarked when
// TransactionRemovedFromMempool fires.
bool ret = pwallet->chain().broadcastTransaction(tx, pwallet->m_default_max_tx_fee, relay, err_string);
fInMempool |= ret;
return ret;
}
std::set<uint256> CWalletTx::GetConflicts() const
{
std::set<uint256> result;
if (pwallet != nullptr)
{
uint256 myHash = GetHash();
result = pwallet->GetConflicts(myHash);
result.erase(myHash);
}
return result;
}
CAmount CWalletTx::GetCachableAmount(AmountType type, const isminefilter& filter, bool recalculate) const
{
auto& amount = m_amounts[type];
if (recalculate || !amount.m_cached[filter]) {
amount.Set(filter, type == DEBIT ? pwallet->GetDebit(*tx, filter) : pwallet->GetCredit(*tx, filter));
m_is_cache_empty = false;
}
return amount.m_value[filter];
}
CAmount CWalletTx::GetDebit(const isminefilter& filter) const
{
if (tx->vin.empty())
return 0;
CAmount debit = 0;
if (filter & ISMINE_SPENDABLE) {
debit += GetCachableAmount(DEBIT, ISMINE_SPENDABLE);
}
if (filter & ISMINE_WATCH_ONLY) {
debit += GetCachableAmount(DEBIT, ISMINE_WATCH_ONLY);
}
return debit;
}
CAmount CWalletTx::GetCredit(const isminefilter& filter) const
{
// Must wait until coinbase is safely deep enough in the chain before valuing it
if (IsImmatureCoinBase())
return 0;
CAmount credit = 0;
if (filter & ISMINE_SPENDABLE) {
// GetBalance can assume transactions in mapWallet won't change
credit += GetCachableAmount(CREDIT, ISMINE_SPENDABLE);
}
if (filter & ISMINE_WATCH_ONLY) {
credit += GetCachableAmount(CREDIT, ISMINE_WATCH_ONLY);
}
return credit;
}
CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
{
if (IsImmatureCoinBase() && IsInMainChain()) {
return GetCachableAmount(IMMATURE_CREDIT, ISMINE_SPENDABLE, !fUseCache);
}
return 0;
}
CAmount CWalletTx::GetStakeCredit(bool fUseCache) const
{
if (IsImmatureCoinStake() && IsInMainChain()) {
return GetCachableAmount(IMMATURE_CREDIT, ISMINE_SPENDABLE, !fUseCache);
}
return 0;
}
CAmount CWalletTx::GetAvailableCredit(bool fUseCache, const isminefilter& filter) const
{
if (pwallet == nullptr)
return 0;
// Avoid caching ismine for NO or ALL cases (could remove this check and simplify in the future).
bool allow_cache = (filter & ISMINE_ALL) && (filter & ISMINE_ALL) != ISMINE_ALL;
// Must wait until coinbase is safely deep enough in the chain before valuing it
if (IsImmature())
return 0;
if (fUseCache && allow_cache && m_amounts[AVAILABLE_CREDIT].m_cached[filter]) {
return m_amounts[AVAILABLE_CREDIT].m_value[filter];
}
bool allow_used_addresses = (filter & ISMINE_USED) || !pwallet->IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE);
CAmount nCredit = 0;
uint256 hashTx = GetHash();
for (unsigned int i = 0; i < tx->vout.size(); i++)
{
if (!pwallet->IsSpent(hashTx, i) && (allow_used_addresses || !pwallet->IsSpentKey(hashTx, i))) {
const CTxOut &txout = tx->vout[i];
nCredit += pwallet->GetCredit(txout, filter);
if (!MoneyRange(nCredit))
throw std::runtime_error(std::string(__func__) + " : value out of range");
}
}
if (allow_cache) {
m_amounts[AVAILABLE_CREDIT].Set(filter, nCredit);
m_is_cache_empty = false;
}
return nCredit;
}
CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool fUseCache) const
{
if (IsImmatureCoinBase() && IsInMainChain()) {
return GetCachableAmount(IMMATURE_CREDIT, ISMINE_WATCH_ONLY, !fUseCache);
}
return 0;
}
CAmount CWalletTx::GetStakeWatchOnlyCredit(const bool fUseCache) const
{
if (IsImmatureCoinStake() && IsInMainChain()) {
return GetCachableAmount(IMMATURE_CREDIT, ISMINE_WATCH_ONLY, !fUseCache);
}
return 0;
}
CAmount CWalletTx::GetChange() const
{
if (fChangeCached)
return nChangeCached;
nChangeCached = pwallet->GetChange(*tx);
fChangeCached = true;
return nChangeCached;
}
bool CWalletTx::InMempool() const
{
return fInMempool;
}
bool CWalletTx::IsTrusted(interfaces::Chain::Lock& locked_chain) const
{
std::set<uint256> s;
return IsTrusted(locked_chain, s);
}
bool CWalletTx::IsTrusted(interfaces::Chain::Lock& locked_chain, std::set<uint256>& trusted_parents) const
{
// Quick answer in most cases
if (!locked_chain.checkFinalTx(*tx)) return false;
int nDepth = GetDepthInMainChain();
if (nDepth >= 1) return true;
if (nDepth < 0) return false;
// using wtx's cached debit
if (!pwallet->m_spend_zero_conf_change || !IsFromMe(ISMINE_ALL)) return false;
// Don't trust unconfirmed transactions from us unless they are in the mempool.
if (!InMempool()) return false;
// Trusted if all inputs are from us and are in the mempool:
for (const CTxIn& txin : tx->vin)
{
// Transactions not sent by us: not trusted
const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
if (parent == nullptr) return false;
const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
// Check that this specific input being spent is trusted
if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE) return false;
// If we've already trusted this parent, continue
if (trusted_parents.count(parent->GetHash())) continue;
// Recurse to check that the parent is also trusted
if (!parent->IsTrusted(locked_chain, trusted_parents)) return false;
trusted_parents.insert(parent->GetHash());
}
return true;
}
bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
{
CMutableTransaction tx1 {*this->tx};
CMutableTransaction tx2 {*_tx.tx};
for (auto& txin : tx1.vin) txin.scriptSig = CScript();
for (auto& txin : tx2.vin) txin.scriptSig = CScript();
return CTransaction(tx1) == CTransaction(tx2);
}
// Rebroadcast transactions from the wallet. We do this on a random timer
// to slightly obfuscate which transactions come from our wallet.
//
// Ideally, we'd only resend transactions that we think should have been
// mined in the most recent block. Any transaction that wasn't in the top
// blockweight of transactions in the mempool shouldn't have been mined,
// and so is probably just sitting in the mempool waiting to be confirmed.
// Rebroadcasting does nothing to speed up confirmation and only damages
// privacy.
void CWallet::ResendWalletTransactions()
{
// During reindex, importing and IBD, old wallet transactions become
// unconfirmed. Don't resend them as that would spam other nodes.
if (!chain().isReadyToBroadcast()) return;
// Do this infrequently and randomly to avoid giving away
// that these are our transactions.
if (GetTime() < nNextResend || !fBroadcastTransactions) return;
bool fFirst = (nNextResend == 0);
nNextResend = GetTime() + GetRand(30 * 60);
if (fFirst) return;
// Only do it if there's been a new block since last time
if (m_best_block_time < nLastResend) return;
nLastResend = GetTime();
int submitted_tx_count = 0;
{ // locked_chain and cs_wallet scope
auto locked_chain = chain().lock();
LOCK(cs_wallet);
// Relay transactions
for (std::pair<const uint256, CWalletTx>& item : mapWallet) {
CWalletTx& wtx = item.second;
// Attempt to rebroadcast all txes more than 5 minutes older than
// the last block. SubmitMemoryPoolAndRelay() will not rebroadcast
// any confirmed or conflicting txs.
if (wtx.nTimeReceived > m_best_block_time - 5 * 60) continue;
std::string unused_err_string;
if (wtx.SubmitMemoryPoolAndRelay(unused_err_string, true)) ++submitted_tx_count;
}
} // locked_chain and cs_wallet
if (submitted_tx_count > 0) {
WalletLogPrintf("%s: resubmit %u unconfirmed transactions\n", __func__, submitted_tx_count);
}
}
/** @} */ // end of mapWallet
void MaybeResendWalletTxs()
{
for (const std::shared_ptr<CWallet>& pwallet : GetWallets()) {
pwallet->ResendWalletTransactions();
}
}
/** @defgroup Actions
*
* @{
*/
CWallet::Balance CWallet::GetBalance(const int min_depth, bool avoid_reuse) const
{
Balance ret;
isminefilter reuse_filter = avoid_reuse ? ISMINE_NO : ISMINE_USED;
{
auto locked_chain = chain().lock();
LOCK(cs_wallet);
std::set<uint256> trusted_parents;
for (const auto& entry : mapWallet)
{
const CWalletTx& wtx = entry.second;
const bool is_trusted{wtx.IsTrusted(*locked_chain, trusted_parents)};
const int tx_depth{wtx.GetDepthInMainChain()};
const CAmount tx_credit_mine{wtx.GetAvailableCredit(/* fUseCache */ true, ISMINE_SPENDABLE | reuse_filter)};
const CAmount tx_credit_watchonly{wtx.GetAvailableCredit(/* fUseCache */ true, ISMINE_WATCH_ONLY | reuse_filter)};
if (is_trusted && tx_depth >= min_depth) {
ret.m_mine_trusted += tx_credit_mine;
ret.m_watchonly_trusted += tx_credit_watchonly;
}
if (!is_trusted && tx_depth == 0 && wtx.InMempool()) {
ret.m_mine_untrusted_pending += tx_credit_mine;
ret.m_watchonly_untrusted_pending += tx_credit_watchonly;
}
ret.m_mine_immature += wtx.GetImmatureCredit();
ret.m_watchonly_immature += wtx.GetImmatureWatchOnlyCredit();
ret.m_mine_stake += wtx.GetStakeCredit();
ret.m_watchonly_stake += wtx.GetStakeWatchOnlyCredit();
}
}
return ret;
}
CAmount CWallet::GetAvailableBalance(const CCoinControl* coinControl) const
{
auto locked_chain = chain().lock();
LOCK(cs_wallet);
CAmount balance = 0;
std::vector<COutput> vCoins;
AvailableCoins(*locked_chain, vCoins, true, coinControl);
for (const COutput& out : vCoins) {
if (out.fSpendable) {
balance += out.tx->tx->vout[out.i].nValue;
}
}
return balance;
}
void CWallet::AvailableCoins(interfaces::Chain::Lock& locked_chain, std::vector<COutput>& vCoins, bool fOnlySafe, const CCoinControl* coinControl, const CAmount& nMinimumAmount, const CAmount& nMaximumAmount, const CAmount& nMinimumSumAmount, const uint64_t nMaximumCount) const
{
AssertLockHeld(cs_wallet);
vCoins.clear();
CAmount nTotal = 0;
// Either the WALLET_FLAG_AVOID_REUSE flag is not set (in which case we always allow), or we default to avoiding, and only in the case where
// a coin control object is provided, and has the avoid address reuse flag set to false, do we allow already used addresses
bool allow_used_addresses = !IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE) || (coinControl && !coinControl->m_avoid_address_reuse);
const int min_depth = {coinControl ? coinControl->m_min_depth : DEFAULT_MIN_DEPTH};
const int max_depth = {coinControl ? coinControl->m_max_depth : DEFAULT_MAX_DEPTH};
std::set<uint256> trusted_parents;
for (const auto& entry : mapWallet)
{
const uint256& wtxid = entry.first;
const CWalletTx& wtx = entry.second;
if (!locked_chain.checkFinalTx(*wtx.tx)) {
continue;
}
if (wtx.IsImmature())
continue;
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < 0)
continue;
// We should not consider coins which aren't at least in our mempool
// It's possible for these to be conflicted via ancestors which we may never be able to detect
if (nDepth == 0 && !wtx.InMempool())
continue;
bool safeTx = wtx.IsTrusted(locked_chain, trusted_parents);
// We should not consider coins from transactions that are replacing
// other transactions.
//
// Example: There is a transaction A which is replaced by bumpfee
// transaction B. In this case, we want to prevent creation of
// a transaction B' which spends an output of B.
//
// Reason: If transaction A were initially confirmed, transactions B
// and B' would no longer be valid, so the user would have to create
// a new transaction C to replace B'. However, in the case of a
// one-block reorg, transactions B' and C might BOTH be accepted,
// when the user only wanted one of them. Specifically, there could
// be a 1-block reorg away from the chain where transactions A and C
// were accepted to another chain where B, B', and C were all
// accepted.
if (nDepth == 0 && wtx.mapValue.count("replaces_txid")) {
safeTx = false;
}
// Similarly, we should not consider coins from transactions that
// have been replaced. In the example above, we would want to prevent
// creation of a transaction A' spending an output of A, because if
// transaction B were initially confirmed, conflicting with A and
// A', we wouldn't want to the user to create a transaction D
// intending to replace A', but potentially resulting in a scenario
// where A, A', and D could all be accepted (instead of just B and
// D, or just A and A' like the user would want).
if (nDepth == 0 && wtx.mapValue.count("replaced_by_txid")) {
safeTx = false;
}
if (fOnlySafe && !safeTx) {
continue;
}
if (nDepth < min_depth || nDepth > max_depth) {
continue;
}
for (unsigned int i = 0; i < wtx.tx->vout.size(); i++) {
if (wtx.tx->vout[i].nValue < nMinimumAmount || wtx.tx->vout[i].nValue > nMaximumAmount)
continue;
if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(COutPoint(entry.first, i)))
continue;
if (IsLockedCoin(entry.first, i))
continue;
if (IsSpent(wtxid, i))
continue;
isminetype mine = IsMine(wtx.tx->vout[i]);
if (mine == ISMINE_NO) {
continue;
}
if (!allow_used_addresses && IsSpentKey(wtxid, i)) {
continue;
}
std::unique_ptr<SigningProvider> provider = GetSolvingProvider(wtx.tx->vout[i].scriptPubKey);
bool solvable = provider ? IsSolvable(*provider, wtx.tx->vout[i].scriptPubKey) : false;
bool spendable = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (((mine & ISMINE_WATCH_ONLY) != ISMINE_NO) && (coinControl && coinControl->fAllowWatchOnly && solvable));
vCoins.push_back(COutput(&wtx, i, nDepth, spendable, solvable, safeTx, (coinControl && coinControl->fAllowWatchOnly)));
// Checks the sum amount of all UTXO's.
if (nMinimumSumAmount != MAX_MONEY) {
nTotal += wtx.tx->vout[i].nValue;
if (nTotal >= nMinimumSumAmount) {
return;
}
}
// Checks the maximum number of UTXO's.
if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
return;
}
}
}
}
const CScriptCache& CWallet::GetScriptCache(const COutPoint& prevout, const CScript& scriptPubKey, std::map<COutPoint, CScriptCache>* _insertScriptCache) const
{
auto it = prevoutScriptCache.find(prevout);
if(it == prevoutScriptCache.end())
{
std::map<COutPoint, CScriptCache>& insertScriptCache = _insertScriptCache == nullptr ? prevoutScriptCache : *_insertScriptCache;
if((int32_t)insertScriptCache.size() > m_staker_max_utxo_script_cache)
{
insertScriptCache.clear();
}
// The script check for utxo is expensive operations, so cache the data for further use
CScriptCache scriptCache;
scriptCache.contract = scriptPubKey.HasOpCall() || scriptPubKey.HasOpCreate();
if(!scriptCache.contract)
{
scriptCache.keyId = ExtractPublicKeyHash(scriptPubKey, &(scriptCache.keyIdOk));
if(scriptCache.keyIdOk)
{
std::unique_ptr<SigningProvider> provider = GetSolvingProvider(scriptPubKey);
scriptCache.solvable = provider ? IsSolvable(*provider, scriptPubKey) : false;
}
}
insertScriptCache[prevout] = scriptCache;
return insertScriptCache[prevout];
}
return it->second;
}
bool valueUtxoSort(const std::pair<COutPoint,CAmount>& a,
const std::pair<COutPoint,CAmount>& b) {
return a.second > b.second;
}
std::map<CTxDestination, std::vector<COutput>> CWallet::ListCoins(interfaces::Chain::Lock& locked_chain) const
{
AssertLockHeld(cs_wallet);
std::map<CTxDestination, std::vector<COutput>> result;
std::vector<COutput> availableCoins;
AvailableCoins(locked_chain, availableCoins);
for (const COutput& coin : availableCoins) {
CTxDestination address;
if ((coin.fSpendable || (IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && coin.fSolvable)) &&
ExtractDestination(FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey, address)) {
result[address].emplace_back(std::move(coin));
}
}
std::vector<COutPoint> lockedCoins;
ListLockedCoins(lockedCoins);
// Include watch-only for LegacyScriptPubKeyMan wallets without private keys
const bool include_watch_only = GetLegacyScriptPubKeyMan() && IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
const isminetype is_mine_filter = include_watch_only ? ISMINE_WATCH_ONLY : ISMINE_SPENDABLE;
for (const COutPoint& output : lockedCoins) {
auto it = mapWallet.find(output.hash);
if (it != mapWallet.end()) {
int depth = it->second.GetDepthInMainChain();
if (depth >= 0 && output.n < it->second.tx->vout.size() &&
IsMine(it->second.tx->vout[output.n]) == is_mine_filter
) {
CTxDestination address;
if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
result[address].emplace_back(
&it->second, output.n, depth, true /* spendable */, true /* solvable */, false /* safe */);
}
}
}
}
return result;
}
const CTxOut& CWallet::FindNonChangeParentOutput(const CTransaction& tx, int output) const
{
const CTransaction* ptx = &tx;
int n = output;
while (IsChange(ptx->vout[n]) && ptx->vin.size() > 0) {
const COutPoint& prevout = ptx->vin[0].prevout;
auto it = mapWallet.find(prevout.hash);
if (it == mapWallet.end() || it->second.tx->vout.size() <= prevout.n ||
!IsMine(it->second.tx->vout[prevout.n])) {
break;
}
ptx = it->second.tx.get();
n = prevout.n;
}
return ptx->vout[n];
}
bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const CoinEligibilityFilter& eligibility_filter, std::vector<OutputGroup> groups,
std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CoinSelectionParams& coin_selection_params, bool& bnb_used) const
{
setCoinsRet.clear();
nValueRet = 0;
std::vector<OutputGroup> utxo_pool;
if (coin_selection_params.use_bnb) {
// Get long term estimate
FeeCalculation feeCalc;
CCoinControl temp;
temp.m_confirm_target = 1008;
CFeeRate long_term_feerate = GetMinimumFeeRate(*this, temp, &feeCalc);
// Calculate cost of change
CAmount cost_of_change = GetDiscardRate(*this).GetFee(coin_selection_params.change_spend_size) + coin_selection_params.effective_fee.GetFee(coin_selection_params.change_output_size);
// Filter by the min conf specs and add to utxo_pool and calculate effective value
for (OutputGroup& group : groups) {
if (!group.EligibleForSpending(eligibility_filter)) continue;
group.fee = 0;
group.long_term_fee = 0;
group.effective_value = 0;
for (auto it = group.m_outputs.begin(); it != group.m_outputs.end(); ) {
const CInputCoin& coin = *it;
CAmount effective_value = coin.txout.nValue - (coin.m_input_bytes < 0 ? 0 : coin_selection_params.effective_fee.GetFee(coin.m_input_bytes));
// Only include outputs that are positive effective value (i.e. not dust)
if (effective_value > 0) {
group.fee += coin.m_input_bytes < 0 ? 0 : coin_selection_params.effective_fee.GetFee(coin.m_input_bytes);
group.long_term_fee += coin.m_input_bytes < 0 ? 0 : long_term_feerate.GetFee(coin.m_input_bytes);
if (coin_selection_params.m_subtract_fee_outputs) {
group.effective_value += coin.txout.nValue;
} else {
group.effective_value += effective_value;
}
++it;
} else {
it = group.Discard(coin);
}
}
if (group.effective_value > 0) utxo_pool.push_back(group);
}
// Calculate the fees for things that aren't inputs
CAmount not_input_fees = coin_selection_params.effective_fee.GetFee(coin_selection_params.tx_noinputs_size);
bnb_used = true;
return SelectCoinsBnB(utxo_pool, nTargetValue, cost_of_change, setCoinsRet, nValueRet, not_input_fees);
} else {
// Filter by the min conf specs and add to utxo_pool
for (const OutputGroup& group : groups) {
if (!group.EligibleForSpending(eligibility_filter)) continue;
utxo_pool.push_back(group);
}
bnb_used = false;
return KnapsackSolver(nTargetValue, utxo_pool, setCoinsRet, nValueRet);
}
}
bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl& coin_control, CoinSelectionParams& coin_selection_params, bool& bnb_used) const
{
std::vector<COutput> vCoins(vAvailableCoins);
CAmount value_to_select = nTargetValue;
// Default to bnb was not used. If we use it, we set it later
bnb_used = false;
// coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
if (coin_control.HasSelected() && !coin_control.fAllowOtherInputs)
{
for (const COutput& out : vCoins)
{
if (!out.fSpendable)
continue;
nValueRet += out.tx->tx->vout[out.i].nValue;
setCoinsRet.insert(out.GetInputCoin());
}
return (nValueRet >= nTargetValue);
}
// calculate value from preset inputs and store them
std::set<CInputCoin> setPresetCoins;
CAmount nValueFromPresetInputs = 0;
std::vector<COutPoint> vPresetInputs;
coin_control.ListSelected(vPresetInputs);
for (const COutPoint& outpoint : vPresetInputs)
{
std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
if (it != mapWallet.end())
{
const CWalletTx& wtx = it->second;
// Clearly invalid input, fail
if (wtx.tx->vout.size() <= outpoint.n) {
return false;
}
// Just to calculate the marginal byte size
CInputCoin coin(wtx.tx, outpoint.n, wtx.GetSpendSize(outpoint.n, false));
nValueFromPresetInputs += coin.txout.nValue;
if (coin.m_input_bytes <= 0) {
return false; // Not solvable, can't estimate size for fee
}
coin.effective_value = coin.txout.nValue - coin_selection_params.effective_fee.GetFee(coin.m_input_bytes);
if (coin_selection_params.use_bnb) {
value_to_select -= coin.effective_value;
} else {
value_to_select -= coin.txout.nValue;
}
setPresetCoins.insert(coin);
} else {
return false; // TODO: Allow non-wallet inputs
}
}
// remove preset inputs from vCoins
for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coin_control.HasSelected();)
{
if (setPresetCoins.count(it->GetInputCoin()))
it = vCoins.erase(it);
else
++it;
}
// form groups from remaining coins; note that preset coins will not
// automatically have their associated (same address) coins included
if (coin_control.m_avoid_partial_spends && vCoins.size() > OUTPUT_GROUP_MAX_ENTRIES) {
// Cases where we have 11+ outputs all pointing to the same destination may result in
// privacy leaks as they will potentially be deterministically sorted. We solve that by
// explicitly shuffling the outputs before processing
Shuffle(vCoins.begin(), vCoins.end(), FastRandomContext());
}
std::vector<OutputGroup> groups = GroupOutputs(vCoins, !coin_control.m_avoid_partial_spends);
unsigned int limit_ancestor_count;
unsigned int limit_descendant_count;
chain().getPackageLimits(limit_ancestor_count, limit_descendant_count);
size_t max_ancestors = (size_t)std::max<int64_t>(1, limit_ancestor_count);
size_t max_descendants = (size_t)std::max<int64_t>(1, limit_descendant_count);
bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
bool res = value_to_select <= 0 ||
SelectCoinsMinConf(value_to_select, CoinEligibilityFilter(1, 6, 0), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used) ||
SelectCoinsMinConf(value_to_select, CoinEligibilityFilter(1, 1, 0), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used) ||
(m_spend_zero_conf_change && SelectCoinsMinConf(value_to_select, CoinEligibilityFilter(0, 1, 2), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used)) ||
(m_spend_zero_conf_change && SelectCoinsMinConf(value_to_select, CoinEligibilityFilter(0, 1, std::min((size_t)4, max_ancestors/3), std::min((size_t)4, max_descendants/3)), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used)) ||
(m_spend_zero_conf_change && SelectCoinsMinConf(value_to_select, CoinEligibilityFilter(0, 1, max_ancestors/2, max_descendants/2), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used)) ||
(m_spend_zero_conf_change && SelectCoinsMinConf(value_to_select, CoinEligibilityFilter(0, 1, max_ancestors-1, max_descendants-1), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used)) ||
(m_spend_zero_conf_change && !fRejectLongChains && SelectCoinsMinConf(value_to_select, CoinEligibilityFilter(0, 1, std::numeric_limits<uint64_t>::max()), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
// because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
util::insert(setCoinsRet, setPresetCoins);
// add preset inputs to the total value selected
nValueRet += nValueFromPresetInputs;
return res;
}
bool CWallet::SignTransaction(CMutableTransaction& tx) const
{
AssertLockHeld(cs_wallet);
// Build coins map
std::map<COutPoint, Coin> coins;
for (auto& input : tx.vin) {
std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
return false;
}
const CWalletTx& wtx = mi->second;
coins[input.prevout] = Coin(wtx.tx->vout[input.prevout.n], wtx.m_confirm.block_height, wtx.IsCoinBase(), wtx.IsCoinStake());
}
std::map<int, std::string> input_errors;
return SignTransaction(tx, coins, SIGHASH_ALL, input_errors);
}
bool CWallet::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, std::string>& input_errors) const
{
// Sign the tx with ScriptPubKeyMans
// Because each ScriptPubKeyMan can sign more than one input, we need to keep track of each ScriptPubKeyMan that has signed this transaction.
// Each iteration, we may sign more txins than the txin that is specified in that iteration.
// We assume that each input is signed by only one ScriptPubKeyMan.
std::set<uint256> visited_spk_mans;
for (unsigned int i = 0; i < tx.vin.size(); i++) {
// Get the prevout
CTxIn& txin = tx.vin[i];
auto coin = coins.find(txin.prevout);
if (coin == coins.end() || coin->second.IsSpent()) {
input_errors[i] = "Input not found or already spent";
continue;
}
// Check if this input is complete
SignatureData sigdata = DataFromTransaction(tx, i, coin->second.out);
if (sigdata.complete) {
continue;
}
// Input needs to be signed, find the right ScriptPubKeyMan
std::set<ScriptPubKeyMan*> spk_mans = GetScriptPubKeyMans(coin->second.out.scriptPubKey, sigdata);
if (spk_mans.size() == 0) {
input_errors[i] = "Unable to sign input, missing keys";
continue;
}
for (auto& spk_man : spk_mans) {
// If we've already been signed by this spk_man, skip it
if (visited_spk_mans.count(spk_man->GetID()) > 0) {
continue;
}
// Sign the tx.
// spk_man->SignTransaction will return true if the transaction is complete,
// so we can exit early and return true if that happens.
if (spk_man->SignTransaction(tx, coins, sighash, input_errors)) {
return true;
}
// Add this spk_man to visited_spk_mans so we can skip it later
visited_spk_mans.insert(spk_man->GetID());
}
}
return false;
}
TransactionError CWallet::FillPSBT(PartiallySignedTransaction& psbtx, bool& complete, int sighash_type, bool sign, bool bip32derivs) const
{
LOCK(cs_wallet);
// Get all of the previous transactions
for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
const CTxIn& txin = psbtx.tx->vin[i];
PSBTInput& input = psbtx.inputs.at(i);
if (PSBTInputSigned(input)) {
continue;
}
// If we have no utxo, grab it from the wallet.
if (!input.non_witness_utxo) {
const uint256& txhash = txin.prevout.hash;
const auto it = mapWallet.find(txhash);
if (it != mapWallet.end()) {
const CWalletTx& wtx = it->second;
// We only need the non_witness_utxo, which is a superset of the witness_utxo.
// The signing code will switch to the smaller witness_utxo if this is ok.
input.non_witness_utxo = wtx.tx;
}
}
}
// Fill in information from ScriptPubKeyMans
// Because each ScriptPubKeyMan may be able to fill more than one input, we need to keep track of each ScriptPubKeyMan that has filled this psbt.
// Each iteration, we may fill more inputs than the input that is specified in that iteration.
// We assume that each input is filled by only one ScriptPubKeyMan
std::set<uint256> visited_spk_mans;
for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
const CTxIn& txin = psbtx.tx->vin[i];
PSBTInput& input = psbtx.inputs.at(i);
if (PSBTInputSigned(input)) {
continue;
}
// Get the scriptPubKey to know which ScriptPubKeyMan to use
CScript script;
if (!input.witness_utxo.IsNull()) {
script = input.witness_utxo.scriptPubKey;
} else if (input.non_witness_utxo) {
if (txin.prevout.n >= input.non_witness_utxo->vout.size()) {
return TransactionError::MISSING_INPUTS;
}
script = input.non_witness_utxo->vout[txin.prevout.n].scriptPubKey;
} else {
// There's no UTXO so we can just skip this now
continue;
}
SignatureData sigdata;
input.FillSignatureData(sigdata);
std::set<ScriptPubKeyMan*> spk_mans = GetScriptPubKeyMans(script, sigdata);
if (spk_mans.size() == 0) {
continue;
}
for (auto& spk_man : spk_mans) {
// If we've already been signed by this spk_man, skip it
if (visited_spk_mans.count(spk_man->GetID()) > 0) {
continue;
}
// Fill in the information from the spk_man
TransactionError res = spk_man->FillPSBT(psbtx, sighash_type, sign, bip32derivs);
if (res != TransactionError::OK) {
return res;
}
// Add this spk_man to visited_spk_mans so we can skip it later
visited_spk_mans.insert(spk_man->GetID());
}
}
// Complete if every input is now signed
complete = true;
for (const auto& input : psbtx.inputs) {
complete &= PSBTInputSigned(input);
}
return TransactionError::OK;
}
SigningResult CWallet::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
{
SignatureData sigdata;
CScript script_pub_key = GetScriptForDestination(pkhash);
for (const auto& spk_man_pair : m_spk_managers) {
if (spk_man_pair.second->CanProvide(script_pub_key, sigdata)) {
return spk_man_pair.second->SignMessage(message, pkhash, str_sig);
}
}
return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
}
bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl coinControl)
{
std::vector<CRecipient> vecSend;
// Turn the txout set into a CRecipient vector.
for (size_t idx = 0; idx < tx.vout.size(); idx++) {
const CTxOut& txOut = tx.vout[idx];
CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
vecSend.push_back(recipient);
}
coinControl.fAllowOtherInputs = true;
for (const CTxIn& txin : tx.vin) {
coinControl.Select(txin.prevout);
}
// Acquire the locks to prevent races to the new locked unspents between the
// CreateTransaction call and LockCoin calls (when lockUnspents is true).
auto locked_chain = chain().lock();
LOCK(cs_wallet);
CAmount nGasFee = GetTxGasFee(tx);
CTransactionRef tx_new;
if (!CreateTransaction(*locked_chain, vecSend, tx_new, nFeeRet, nChangePosInOut, strFailReason, coinControl, false, nGasFee)) {
return false;
}
if (nChangePosInOut != -1) {
tx.vout.insert(tx.vout.begin() + nChangePosInOut, tx_new->vout[nChangePosInOut]);
}
// Copy output sizes from new transaction; they may have had the fee
// subtracted from them.
for (unsigned int idx = 0; idx < tx.vout.size(); idx++) {
tx.vout[idx].nValue = tx_new->vout[idx].nValue;
}
// Add new txins while keeping original txin scriptSig/order.
for (const CTxIn& txin : tx_new->vin) {
if (!coinControl.IsSelected(txin.prevout)) {
tx.vin.push_back(txin);
if (lockUnspents) {
LockCoin(txin.prevout);
}
}
}
return true;
}
static bool IsCurrentForAntiFeeSniping(interfaces::Chain& chain, interfaces::Chain::Lock& locked_chain)
{
if (chain.isInitialBlockDownload()) {
return false;
}
constexpr int64_t MAX_ANTI_FEE_SNIPING_TIP_AGE = 8 * 60 * 60; // in seconds
if (locked_chain.getBlockTime(*locked_chain.getHeight()) < (GetTime() - MAX_ANTI_FEE_SNIPING_TIP_AGE)) {
return false;
}
return true;
}
/**
* Return a height-based locktime for new transactions (uses the height of the
* current chain tip unless we are not synced with the current chain
*/
static uint32_t GetLocktimeForNewTransaction(interfaces::Chain& chain, interfaces::Chain::Lock& locked_chain)
{
uint32_t const height = locked_chain.getHeight().get_value_or(-1);
uint32_t locktime;
// Discourage fee sniping.
//
// For a large miner the value of the transactions in the best block and
// the mempool can exceed the cost of deliberately attempting to mine two
// blocks to orphan the current best block. By setting nLockTime such that
// only the next block can include the transaction, we discourage this
// practice as the height restricted and limited blocksize gives miners
// considering fee sniping fewer options for pulling off this attack.
//
// A simple way to think about this is from the wallet's point of view we
// always want the blockchain to move forward. By setting nLockTime this
// way we're basically making the statement that we only want this
// transaction to appear in the next block; we don't want to potentially
// encourage reorgs by allowing transactions to appear at lower heights
// than the next block in forks of the best chain.
//
// Of course, the subsidy is high enough, and transaction volume low
// enough, that fee sniping isn't a problem yet, but by implementing a fix
// now we ensure code won't be written that makes assumptions about
// nLockTime that preclude a fix later.
if (IsCurrentForAntiFeeSniping(chain, locked_chain)) {
locktime = height;
// Secondly occasionally randomly pick a nLockTime even further back, so
// that transactions that are delayed after signing for whatever reason,
// e.g. high-latency mix networks and some CoinJoin implementations, have
// better privacy.
if (GetRandInt(10) == 0)
locktime = std::max(0, (int)locktime - GetRandInt(100));
} else {
// If our chain is lagging behind, we can't discourage fee sniping nor help
// the privacy of high-latency transactions. To avoid leaking a potentially
// unique "nLockTime fingerprint", set nLockTime to a constant.
locktime = 0;
}
assert(locktime <= height);
assert(locktime < LOCKTIME_THRESHOLD);
return locktime;
}
OutputType CWallet::TransactionChangeType(OutputType change_type, const std::vector<CRecipient>& vecSend)
{
// If -changetype is specified, always use that change type.
if (change_type != OutputType::CHANGE_AUTO) {
return change_type;
}
// if m_default_address_type is legacy, use legacy address as change (even
// if some of the outputs are P2WPKH or P2WSH).
if (m_default_address_type == OutputType::LEGACY) {
return OutputType::LEGACY;
}
// if any destination is P2WPKH or P2WSH, use P2WPKH for the change
// output.
for (const auto& recipient : vecSend) {
// Check if any destination contains a witness program:
int witnessversion = 0;
std::vector<unsigned char> witnessprogram;
if (recipient.scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
return OutputType::BECH32;
}
}
// else use m_default_address_type for change
return m_default_address_type;
}
bool CWallet::CreateTransaction(interfaces::Chain::Lock& locked_chain, const std::vector<CRecipient>& vecSend, CTransactionRef& tx, CAmount& nFeeRet,
int& nChangePosInOut, std::string& strFailReason, const CCoinControl& coin_control, bool sign, CAmount nGasFee, bool hasSender, const CTxDestination& signSenderAddress)
{
CAmount nValue = 0;
const OutputType change_type = TransactionChangeType(coin_control.m_change_type ? *coin_control.m_change_type : m_default_change_type, vecSend);
ReserveDestination reservedest(this, change_type);
int nChangePosRequest = nChangePosInOut;
unsigned int nSubtractFeeFromAmount = 0;
COutPoint senderInput;
if(hasSender && coin_control.HasSelected()){
std::vector<COutPoint> vSenderInputs;
coin_control.ListSelected(vSenderInputs);
senderInput=vSenderInputs[0];
}
for (const auto& recipient : vecSend)
{
if (nValue < 0 || recipient.nAmount < 0)
{
strFailReason = _("Transaction amounts must not be negative").translated;
return false;
}
nValue += recipient.nAmount;
if (recipient.fSubtractFeeFromAmount)
nSubtractFeeFromAmount++;
}
if (vecSend.empty())
{
strFailReason = _("Transaction must have at least one recipient").translated;
return false;
}
CMutableTransaction txNew;
txNew.nLockTime = GetLocktimeForNewTransaction(chain(), locked_chain);
FeeCalculation feeCalc;
CAmount nFeeNeeded;
int nBytes;
{
std::set<CInputCoin> setCoins;
std::vector<CInputCoin> vCoins;
auto locked_chain = chain().lock();
LOCK(cs_wallet);
{
std::vector<COutput> vAvailableCoins;
AvailableCoins(*locked_chain, vAvailableCoins, true, &coin_control, 1, MAX_MONEY, MAX_MONEY, 0);
CoinSelectionParams coin_selection_params; // Parameters for coin selection, init with dummy
// Create change script that will be used if we need change
// TODO: pass in scriptChange instead of reservedest so
// change transaction isn't always pay-to-bitcoin-address
CScript scriptChange;
// coin control: send change to custom address
if (!boost::get<CNoDestination>(&coin_control.destChange)) {
scriptChange = GetScriptForDestination(coin_control.destChange);
} else { // no coin control: send change to newly generated address
// Note: We use a new key here to keep it from being obvious which side is the change.
// The drawback is that by not reusing a previous key, the change may be lost if a
// backup is restored, if the backup doesn't have the new private key for the change.
// If we reused the old key, it would be possible to add code to look for and
// rediscover unknown transactions that were written with keys of ours to recover
// post-backup change.
// Reserve a new key pair from key pool
if (!CanGetAddresses(true)) {
strFailReason = _("Can't generate a change-address key. No keys in the internal keypool and can't generate any keys.").translated;
return false;
}
CTxDestination dest;
bool ret = reservedest.GetReservedDestination(dest, true);
if (!ret)
{
strFailReason = "Keypool ran out, please call keypoolrefill first";
return false;
}
scriptChange = GetScriptForDestination(dest);
}
CTxOut change_prototype_txout(0, scriptChange);
coin_selection_params.change_output_size = GetSerializeSize(change_prototype_txout);
CFeeRate discard_rate = GetDiscardRate(*this);
// Get the fee rate to use effective values in coin selection
CFeeRate nFeeRateNeeded = GetMinimumFeeRate(*this, coin_control, &feeCalc);
nFeeRet = 0;
bool pick_new_inputs = true;
CAmount nValueIn = 0;
// BnB selector is the only selector used when this is true.
// That should only happen on the first pass through the loop.
coin_selection_params.use_bnb = true;
coin_selection_params.m_subtract_fee_outputs = nSubtractFeeFromAmount != 0; // If we are doing subtract fee from recipient, don't use effective values
// Start with no fee and loop until there is enough fee
while (true)
{
nChangePosInOut = nChangePosRequest;
txNew.vin.clear();
txNew.vout.clear();
bool fFirst = true;
CAmount nValueToSelect = nValue;
if (nSubtractFeeFromAmount == 0)
nValueToSelect += nFeeRet;
// vouts to the payees
if (!coin_selection_params.m_subtract_fee_outputs) {
coin_selection_params.tx_noinputs_size = 11; // Static vsize overhead + outputs vsize. 4 nVersion, 4 nLocktime, 1 input count, 1 output count, 1 witness overhead (dummy, flag, stack size)
}
for (const auto& recipient : vecSend)
{
CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
if (recipient.fSubtractFeeFromAmount)
{
assert(nSubtractFeeFromAmount != 0);
txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
if (fFirst) // first receiver pays the remainder not divisible by output count
{
fFirst = false;
txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
}
}
// Include the fee cost for outputs. Note this is only used for BnB right now
if (!coin_selection_params.m_subtract_fee_outputs) {
coin_selection_params.tx_noinputs_size += ::GetSerializeSize(txout, PROTOCOL_VERSION);
}
if (IsDust(txout, chain().relayDustFee()))
{
if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
{
if (txout.nValue < 0)
strFailReason = _("The transaction amount is too small to pay the fee").translated;
else
strFailReason = _("The transaction amount is too small to send after the fee has been deducted").translated;
}
else
strFailReason = _("Transaction amount too small").translated;
return false;
}
txNew.vout.push_back(txout);
}
// Choose coins to use
bool bnb_used = false;
if (pick_new_inputs) {
nValueIn = 0;
setCoins.clear();
int change_spend_size = CalculateMaximumSignedInputSize(change_prototype_txout, this);
// If the wallet doesn't know how to sign change output, assume p2sh-p2wpkh
// as lower-bound to allow BnB to do it's thing
if (change_spend_size == -1) {
coin_selection_params.change_spend_size = DUMMY_NESTED_P2WPKH_INPUT_SIZE;
} else {
coin_selection_params.change_spend_size = (size_t)change_spend_size;
}
coin_selection_params.effective_fee = nFeeRateNeeded;
if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, coin_control, coin_selection_params, bnb_used))
{
// If BnB was used, it was the first pass. No longer the first pass and continue loop with knapsack.
if (bnb_used) {
coin_selection_params.use_bnb = false;
continue;
}
else {
strFailReason = _("Insufficient funds").translated;
return false;
}
}
} else {
bnb_used = false;
}
const CAmount nChange = nValueIn - nValueToSelect;
if (nChange > 0)
{
// send change to existing address
if (!m_use_change_address &&
boost::get<CNoDestination>(&coin_control.destChange) &&
setCoins.size() > 0)
{
// setCoins will be added as inputs to the new transaction
// Set the first input script as change script for the new transaction
auto pcoin = setCoins.begin();
scriptChange = pcoin->txout.scriptPubKey;
change_prototype_txout = CTxOut(0, scriptChange);
coin_selection_params.change_output_size = GetSerializeSize(change_prototype_txout);
}
// Fill a vout to ourself
CTxOut newTxOut(nChange, scriptChange);
// Never create dust outputs; if we would, just
// add the dust to the fee.
// The nChange when BnB is used is always going to go to fees.
if (IsDust(newTxOut, discard_rate) || bnb_used)
{
nChangePosInOut = -1;
nFeeRet += nChange;
}
else
{
if (nChangePosInOut == -1)
{
// Insert change txn at random position:
nChangePosInOut = GetRandInt(txNew.vout.size()+1);
}
else if ((unsigned int)nChangePosInOut > txNew.vout.size())
{
strFailReason = _("Change index out of range").translated;
return false;
}
std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
txNew.vout.insert(position, newTxOut);
}
} else {
nChangePosInOut = -1;
}
// Move sender input to position 0
vCoins.clear();
std::copy(setCoins.begin(), setCoins.end(), std::back_inserter(vCoins));
if(hasSender && coin_control.HasSelected()){
for (std::vector<CInputCoin>::size_type i = 0 ; i != vCoins.size(); i++){
if(vCoins[i].outpoint==senderInput){
if(i==0)break;
iter_swap(vCoins.begin(),vCoins.begin()+i);
break;
}
}
}
// Dummy fill vin for maximum size estimation
//
for (const auto& coin : vCoins) {
txNew.vin.push_back(CTxIn(coin.outpoint,CScript()));
}
nBytes = CalculateMaximumSignedTxSize(CTransaction(txNew), this, coin_control.fAllowWatchOnly);
if (nBytes < 0) {
strFailReason = _("Signing transaction failed").translated;
return false;
}
nFeeNeeded = GetMinimumFee(*this, nBytes, coin_control, &feeCalc)+nGasFee;
if (feeCalc.reason == FeeReason::FALLBACK && !m_allow_fallback_fee) {
// eventually allow a fallback fee
strFailReason = _("Fee estimation failed. Fallbackfee is disabled. Wait a few blocks or enable -fallbackfee.").translated;
return false;
}
if (nFeeRet >= nFeeNeeded) {
// Reduce fee to only the needed amount if possible. This
// prevents potential overpayment in fees if the coins
// selected to meet nFeeNeeded result in a transaction that
// requires less fee than the prior iteration.
// If we have no change and a big enough excess fee, then
// try to construct transaction again only without picking
// new inputs. We now know we only need the smaller fee
// (because of reduced tx size) and so we should add a
// change output. Only try this once.
if (nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 && pick_new_inputs) {
unsigned int tx_size_with_change = nBytes + coin_selection_params.change_output_size + 2; // Add 2 as a buffer in case increasing # of outputs changes compact size
CAmount fee_needed_with_change = GetMinimumFee(*this, tx_size_with_change, coin_control, nullptr)+nGasFee;
CAmount minimum_value_for_change = GetDustThreshold(change_prototype_txout, discard_rate);
if (nFeeRet >= fee_needed_with_change + minimum_value_for_change) {
pick_new_inputs = false;
nFeeRet = fee_needed_with_change;
continue;
}
}
// If we have change output already, just increase it
if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
CAmount extraFeePaid = nFeeRet - nFeeNeeded;
std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
change_position->nValue += extraFeePaid;
nFeeRet -= extraFeePaid;
}
break; // Done, enough fee included.
}
else if (!pick_new_inputs) {
// This shouldn't happen, we should have had enough excess
// fee to pay for the new output and still meet nFeeNeeded
// Or we should have just subtracted fee from recipients and
// nFeeNeeded should not have changed
strFailReason = _("Transaction fee and change calculation failed").translated;
return false;
}
// Try to reduce change to include necessary fee
if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
// Only reduce change if remaining amount is still a large enough output.
if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
change_position->nValue -= additionalFeeNeeded;
nFeeRet += additionalFeeNeeded;
break; // Done, able to increase fee from change
}
}
// If subtracting fee from recipients, we now know what fee we
// need to subtract, we have no reason to reselect inputs
if (nSubtractFeeFromAmount > 0) {
pick_new_inputs = false;
}
// Include more fee and try again.
nFeeRet = nFeeNeeded;
coin_selection_params.use_bnb = false;
continue;
}
}
// Shuffle selected coins and fill in final vin
txNew.vin.clear();
std::vector<CInputCoin> selected_coins(vCoins.begin(), vCoins.end());
int shuffleOffset = 0;
if(hasSender && coin_control.HasSelected() && selected_coins.size() > 0 && selected_coins[0].outpoint==senderInput){
shuffleOffset = 1;
}
Shuffle(selected_coins.begin() + shuffleOffset, selected_coins.end(), FastRandomContext());
// Note how the sequence number is set to non-maxint so that
// the nLockTime set above actually works.
//
// BIP125 defines opt-in RBF as any nSequence < maxint-1, so
// we use the highest possible value in that range (maxint-2)
// to avoid conflicting with other possible uses of nSequence,
// and in the spirit of "smallest possible change from prior
// behavior."
const uint32_t nSequence = coin_control.m_signal_bip125_rbf.get_value_or(m_signal_rbf) ? MAX_BIP125_RBF_SEQUENCE : (CTxIn::SEQUENCE_FINAL - 1);
for (const auto& coin : selected_coins) {
txNew.vin.push_back(CTxIn(coin.outpoint, CScript(), nSequence));
}
if (sign)
{
// Signing transaction outputs
int nOut = 0;
for (const auto& output : txNew.vout)
{
if(output.scriptPubKey.HasOpSender())
{
const CScript& scriptPubKey = GetScriptForDestination(signSenderAddress);
SignatureData sigdata;
auto spk_man = GetLegacyScriptPubKeyMan();
if (!ProduceSignature(*spk_man, MutableTransactionSignatureOutputCreator(&txNew, nOut, output.nValue, SIGHASH_ALL), scriptPubKey, sigdata))
{
strFailReason = _("Signing transaction output failed").translated;
return false;
}
else
{
if(!UpdateOutput(txNew.vout.at(nOut), sigdata))
{
strFailReason = _("Update transaction output failed").translated;
return false;
}
}
}
nOut++;
}
}
if (sign && !SignTransaction(txNew)) {
strFailReason = _("Signing transaction failed").translated;
return false;
}
// Return the constructed transaction data.
tx = MakeTransactionRef(std::move(txNew));
// Limit size
if (GetTransactionWeight(*tx) > MAX_STANDARD_TX_WEIGHT)
{
strFailReason = _("Transaction too large").translated;
return false;
}
}
if (!tx->HasCreateOrCall() && nFeeRet > m_default_max_tx_fee) {
strFailReason = TransactionErrorString(TransactionError::MAX_FEE_EXCEEDED);
return false;
}
if (gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
// Lastly, ensure this tx will pass the mempool's chain limits
if (!chain().checkChainLimits(tx)) {
strFailReason = _("Transaction has too long of a mempool chain").translated;
return false;
}
}
// Before we return success, we assume any change key will be used to prevent
// accidental re-use.
reservedest.KeepDestination();
WalletLogPrintf("Fee Calculation: Fee:%d Bytes:%u Needed:%d Tgt:%d (requested %d) Reason:\"%s\" Decay %.5f: Estimation: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out) Fail: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out)\n",
nFeeRet, nBytes, nFeeNeeded, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
feeCalc.est.pass.start, feeCalc.est.pass.end,
100 * feeCalc.est.pass.withinTarget / (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool),
feeCalc.est.pass.withinTarget, feeCalc.est.pass.totalConfirmed, feeCalc.est.pass.inMempool, feeCalc.est.pass.leftMempool,
feeCalc.est.fail.start, feeCalc.est.fail.end,
100 * feeCalc.est.fail.withinTarget / (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool),
feeCalc.est.fail.withinTarget, feeCalc.est.fail.totalConfirmed, feeCalc.est.fail.inMempool, feeCalc.est.fail.leftMempool);
return true;
}
void CWallet::CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector<std::pair<std::string, std::string>> orderForm)
{
auto locked_chain = chain().lock();
LOCK(cs_wallet);
CWalletTx wtxNew(this, std::move(tx));
wtxNew.mapValue = std::move(mapValue);
wtxNew.vOrderForm = std::move(orderForm);
wtxNew.fTimeReceivedIsTxTime = true;
wtxNew.fFromMe = true;
WalletLogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString()); /* Continued */
// Add tx to wallet, because if it has change it's also ours,
// otherwise just for transaction history.
AddToWallet(wtxNew);
// Notify that old coins are spent
for (const CTxIn& txin : wtxNew.tx->vin) {
CWalletTx &coin = mapWallet.at(txin.prevout.hash);
coin.BindWallet(this);
NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
}
// Get the inserted-CWalletTx from mapWallet so that the
// fInMempool flag is cached properly
CWalletTx& wtx = mapWallet.at(wtxNew.GetHash());
if (!fBroadcastTransactions) {
// Don't submit tx to the mempool
return;
}
std::string err_string;
if (!wtx.SubmitMemoryPoolAndRelay(err_string, true)) {
WalletLogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", err_string);
// TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
}
}
uint64_t CWallet::GetStakeWeight(interfaces::Chain::Lock& locked_chain, uint64_t* pStakerWeight, uint64_t* pDelegateWeight) const
{
uint64_t nWeight = 0;
uint64_t nStakerWeight = 0;
uint64_t nDelegateWeight = 0;
if(pStakerWeight) *pStakerWeight = nStakerWeight;
if(pDelegateWeight) *pDelegateWeight = nDelegateWeight;
// Choose coins to use
const auto bal = GetBalance();
CAmount nBalance = bal.m_mine_trusted;
if(IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS))
nBalance += bal.m_watchonly_trusted;
if (nBalance <= m_reserve_balance)
return nWeight;
std::set<std::pair<const CWalletTx*,unsigned int> > setCoins;
CAmount nValueIn = 0;
CAmount nTargetValue = nBalance - m_reserve_balance;
if (!SelectCoinsForStaking(locked_chain, nTargetValue, setCoins, nValueIn))
return nWeight;
if (setCoins.empty())
return nWeight;
int nHeight = GetLastBlockHeight() + 1;
int coinbaseMaturity = Params().GetConsensus().CoinbaseMaturity(nHeight);
bool canSuperStake = false;
for(std::pair<const CWalletTx*,unsigned int> pcoin : setCoins)
{
if (pcoin.first->GetDepthInMainChain() >= coinbaseMaturity)
{
// Compute staker weight
CAmount nValue = pcoin.first->tx->vout[pcoin.second].nValue;
nStakerWeight += nValue;
// Check if the staker can super stake
if(!canSuperStake && nValue >= DEFAULT_STAKING_MIN_UTXO_VALUE)
canSuperStake = true;
}
}
if(canSuperStake)
{
// Get the weight of the delegated coins
std::vector<COutPoint> vDelegateCoins;
std::map<uint160, CAmount> mDelegateWeight;
SelectDelegateCoinsForStaking(locked_chain, vDelegateCoins, mDelegateWeight);
for(const COutPoint &prevout : vDelegateCoins)
{
Coin coinPrev;
if(!::ChainstateActive().CoinsTip().GetCoin(prevout, coinPrev)){
continue;
}
nDelegateWeight += coinPrev.out.nValue;
}
}
nWeight = nStakerWeight + nDelegateWeight;
if(pStakerWeight) *pStakerWeight = nStakerWeight;
if(pDelegateWeight) *pDelegateWeight = nDelegateWeight;
return nWeight;
}
bool CWallet::CreateCoinStakeFromMine(interfaces::Chain::Lock& locked_chain, const FillableSigningProvider& keystore, unsigned int nBits, const CAmount& nTotalFees, uint32_t nTimeBlock, CMutableTransaction& tx, CKey& key, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoins, std::vector<COutPoint>& setSelectedCoins, bool selectedOnly, bool sign, COutPoint& headerPrevout)
{
CBlockIndex* pindexPrev = ::ChainActive().Tip();
arith_uint256 bnTargetPerCoinDay;
bnTargetPerCoinDay.SetCompact(nBits);
struct CMutableTransaction txNew(tx);
txNew.vin.clear();
txNew.vout.clear();
// Mark coin stake transaction
CScript scriptEmpty;
scriptEmpty.clear();
txNew.vout.push_back(CTxOut(0, scriptEmpty));
// Choose coins to use
const auto bal = GetBalance();
CAmount nBalance = bal.m_mine_trusted;
if(IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS))
nBalance += bal.m_watchonly_trusted;
if (nBalance <= m_reserve_balance)
return false;
std::vector<std::pair<const CWalletTx*,unsigned int>> vwtxPrev;
if (setCoins.empty())
return false;
if(stakeCache.size() > setCoins.size() + 100){
//Determining if the cache is still valid is harder than just clearing it when it gets too big, so instead just clear it
//when it has more than 100 entries more than the actual setCoins.
stakeCache.clear();
}
if(!fHasMinerStakeCache && gArgs.GetBoolArg("-stakecache", DEFAULT_STAKE_CACHE)) {
for(const std::pair<const CWalletTx*,unsigned int> &pcoin : setCoins)
{
boost::this_thread::interruption_point();
COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
CacheKernel(stakeCache, prevoutStake, pindexPrev, ::ChainstateActive().CoinsTip()); //this will do a 2 disk loads per op
}
}
std::map<COutPoint, CStakeCache>& cache = fHasMinerStakeCache ? minerStakeCache : stakeCache;
int64_t nCredit = 0;
CScript scriptPubKeyKernel;
CScript aggregateScriptPubKeyHashKernel;
// Populate the list with the selected coins
std::set<std::pair<const CWalletTx*,unsigned int> > setSelected;
if(selectedOnly)
{
for(const COutPoint& prevoutStake : setSelectedCoins)
{
auto it = mapWallet.find(prevoutStake.hash);
if (it != mapWallet.end()) {
setSelected.insert(std::make_pair(&it->second, prevoutStake.n));
}
}
}
std::set<std::pair<const CWalletTx*,unsigned int> >& setPrevouts = selectedOnly ? setSelected : setCoins;
for(const std::pair<const CWalletTx*,unsigned int> &pcoin : setPrevouts)
{
bool fKernelFound = false;
boost::this_thread::interruption_point();
// Search backward in time from the given txNew timestamp
// Search nSearchInterval seconds back up to nMaxStakeSearchInterval
COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
if (CheckKernel(pindexPrev, nBits, nTimeBlock, prevoutStake, ::ChainstateActive().CoinsTip(), cache))
{
// Found a kernel
LogPrint(BCLog::COINSTAKE, "CreateCoinStake : kernel found\n");
std::vector<valtype> vSolutions;
CScript scriptPubKeyOut;
scriptPubKeyKernel = pcoin.first->tx->vout[pcoin.second].scriptPubKey;
txnouttype whichType = Solver(scriptPubKeyKernel, vSolutions);
if (whichType == TX_NONSTANDARD)
{
LogPrint(BCLog::COINSTAKE, "CreateCoinStake : failed to parse kernel\n");
break;
}
LogPrint(BCLog::COINSTAKE, "CreateCoinStake : parsed kernel type=%d\n", whichType);
if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
{
LogPrint(BCLog::COINSTAKE, "CreateCoinStake : no support for kernel type=%d\n", whichType);
break; // only support pay to public key and pay to address
}
if (whichType == TX_PUBKEYHASH) // pay to address type
{
// convert to pay to public key type
uint160 hash160(vSolutions[0]);
CKeyID pubKeyHash(hash160);
CPubKey pubKeyKernel;
if (!GetKernelKey(pubKeyHash, keystore, sign, pubKeyKernel, key))
{
LogPrint(BCLog::COINSTAKE, "CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
break; // unable to find corresponding public key
}
scriptPubKeyOut << pubKeyKernel.getvch() << OP_CHECKSIG;
aggregateScriptPubKeyHashKernel = scriptPubKeyKernel;
}
if (whichType == TX_PUBKEY)
{
valtype& vchPubKey = vSolutions[0];
CPubKey pubKey(vchPubKey);
uint160 hash160(Hash160(vchPubKey));
CKeyID pubKeyHash(hash160);
CPubKey pubKeyKernel;
if (!GetKernelKey(pubKeyHash, keystore, sign, pubKeyKernel, key))
{
LogPrint(BCLog::COINSTAKE, "CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
break; // unable to find corresponding public key
}
if (pubKeyKernel != pubKey)
{
LogPrint(BCLog::COINSTAKE, "CreateCoinStake : invalid key for kernel type=%d\n", whichType);
break; // keys mismatch
}
scriptPubKeyOut = scriptPubKeyKernel;
aggregateScriptPubKeyHashKernel = CScript() << OP_DUP << OP_HASH160 << ToByteVector(hash160) << OP_EQUALVERIFY << OP_CHECKSIG;
}
txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
nCredit += pcoin.first->tx->vout[pcoin.second].nValue;
vwtxPrev.push_back(pcoin);
txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
LogPrint(BCLog::COINSTAKE, "CreateCoinStake : added kernel type=%d\n", whichType);
fKernelFound = true;
}
if (fKernelFound)
{
headerPrevout = prevoutStake;
break; // if kernel is found stop searching
}
}
if (nCredit == 0 || nCredit > nBalance - m_reserve_balance)
return false;
for(const std::pair<const CWalletTx*,unsigned int> &pcoin : setCoins)
{
// Attempt to add more inputs
// Only add coins of the same key/address as kernel
if (txNew.vout.size() == 2 && ((pcoin.first->tx->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->tx->vout[pcoin.second].scriptPubKey == aggregateScriptPubKeyHashKernel))
&& pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
{
// Stop adding more inputs if already too many inputs
if (txNew.vin.size() >= GetStakeMaxCombineInputs())
break;
// Stop adding inputs if reached reserve limit
if (nCredit + pcoin.first->tx->vout[pcoin.second].nValue > nBalance - m_reserve_balance)
break;
// Do not add additional significant input
if (pcoin.first->tx->vout[pcoin.second].nValue >= GetStakeCombineThreshold())
continue;
txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
nCredit += pcoin.first->tx->vout[pcoin.second].nValue;
vwtxPrev.push_back(pcoin);
}
}
const Consensus::Params& consensusParams = Params().GetConsensus();
int64_t nRewardPiece = 0;
// Calculate reward
{
int64_t nReward = nTotalFees + GetBlockSubsidy(pindexPrev->nHeight + 1, consensusParams);
if (nReward < 0)
return false;
if(pindexPrev->nHeight < consensusParams.nFirstMPoSBlock || pindexPrev->nHeight >= consensusParams.nLastMPoSBlock)
{
// Keep whole reward
nCredit += nReward;
}
else
{
// Split the reward when mpos is used
nRewardPiece = nReward / consensusParams.nMPoSRewardRecipients;
nCredit += nRewardPiece + nReward % consensusParams.nMPoSRewardRecipients;
}
}
if (nCredit >= GetStakeSplitThreshold())
{
for(unsigned int i = 0; i < GetStakeSplitOutputs() - 1; i++)
txNew.vout.push_back(CTxOut(0, txNew.vout[1].scriptPubKey)); //split stake
}
// Set output amount
if (txNew.vout.size() == GetStakeSplitOutputs() + 1)
{
CAmount nValue = (nCredit / GetStakeSplitOutputs() / CENT) * CENT;
for(unsigned int i = 1; i < GetStakeSplitOutputs(); i++)
txNew.vout[i].nValue = nValue;
txNew.vout[GetStakeSplitOutputs()].nValue = nCredit - nValue * (GetStakeSplitOutputs() - 1);
}
else
txNew.vout[1].nValue = nCredit;
if(pindexPrev->nHeight >= consensusParams.nFirstMPoSBlock && pindexPrev->nHeight < consensusParams.nLastMPoSBlock)
{
if(!CreateMPoSOutputs(txNew, nRewardPiece, pindexPrev->nHeight, consensusParams))
return error("CreateCoinStake : failed to create MPoS reward outputs");
}
// Append the Refunds To Sender to the transaction outputs
for(unsigned int i = 2; i < tx.vout.size(); i++)
{
txNew.vout.push_back(tx.vout[i]);
}
// Sign the input coins
if(sign)
{
int nIn = 0;
for(const std::pair<const CWalletTx*,unsigned int> &pcoin : vwtxPrev)
{
if (!SignSignature(keystore, *pcoin.first->tx, txNew, nIn++, SIGHASH_ALL))
return error("CreateCoinStake : failed to sign coinstake");
}
}
// Successfully generated coinstake
tx = txNew;
return true;
}
bool CWallet::CreateCoinStakeFromDelegate(interfaces::Chain::Lock& locked_chain, const FillableSigningProvider &keystore, unsigned int nBits, const CAmount& nTotalFees, uint32_t nTimeBlock, CMutableTransaction& tx, CKey& key, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoins, std::vector<COutPoint>& setDelegateCoins, bool sign, std::vector<unsigned char>& vchPoD, COutPoint& headerPrevout)
{
CBlockIndex* pindexPrev = ::ChainActive().Tip();
arith_uint256 bnTargetPerCoinDay;
bnTargetPerCoinDay.SetCompact(nBits);
struct CMutableTransaction txNew(tx);
txNew.vin.clear();
txNew.vout.clear();
// Mark coin stake transaction
CScript scriptEmpty;
scriptEmpty.clear();
txNew.vout.push_back(CTxOut(0, scriptEmpty));
std::vector<std::pair<const CWalletTx*,unsigned int>> vwtxPrev;
if (setDelegateCoins.empty())
return false;
if(stakeDelegateCache.size() > setDelegateCoins.size() + 100){
//Determining if the cache is still valid is harder than just clearing it when it gets too big, so instead just clear it
//when it has more than 100 entries more than the actual setCoins.
stakeDelegateCache.clear();
}
if(!fHasMinerStakeCache && gArgs.GetBoolArg("-stakecache", DEFAULT_STAKE_CACHE)) {
for(const COutPoint &prevoutStake : setDelegateCoins)
{
boost::this_thread::interruption_point();
CacheKernel(stakeDelegateCache, prevoutStake, pindexPrev, ::ChainstateActive().CoinsTip()); //this will do a 2 disk loads per op
}
}
std::map<COutPoint, CStakeCache>& cache = fHasMinerStakeCache ? minerStakeCache : stakeDelegateCache;
int64_t nCredit = 0;
CScript scriptPubKeyKernel;
CScript scriptPubKeyStaker;
Delegation delegation;
bool delegateOutputExist = false;
for(const COutPoint &prevoutStake : setDelegateCoins)
{
bool fKernelFound = false;
boost::this_thread::interruption_point();
// Search backward in time from the given txNew timestamp
// Search nSearchInterval seconds back up to nMaxStakeSearchInterval
if (CheckKernel(pindexPrev, nBits, nTimeBlock, prevoutStake, ::ChainstateActive().CoinsTip(), cache))
{
// Found a kernel
LogPrint(BCLog::COINSTAKE, "CreateCoinStake : kernel found\n");
std::vector<valtype> vSolutions;
Coin coinPrev;
if(!::ChainstateActive().CoinsTip().GetCoin(prevoutStake, coinPrev)){
if(!GetSpentCoinFromMainChain(pindexPrev, prevoutStake, &coinPrev)) {
return error("CreateCoinStake: Could not find coin and it was not at the tip");
}
}
scriptPubKeyKernel = coinPrev.out.scriptPubKey;
txnouttype whichType = Solver(scriptPubKeyKernel, vSolutions);
if (whichType == TX_NONSTANDARD)
{
LogPrint(BCLog::COINSTAKE, "CreateCoinStake : failed to parse kernel\n");
break;
}
LogPrint(BCLog::COINSTAKE, "CreateCoinStake : parsed kernel type=%d\n", whichType);
if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
{
LogPrint(BCLog::COINSTAKE, "CreateCoinStake : no support for kernel type=%d\n", whichType);
break; // only support pay to public key and pay to address
}
if (whichType == TX_PUBKEYHASH) // pay to address type
{
// convert to pay to public key type
uint160 hash160(vSolutions[0]);
if(!GetDelegationStaker(hash160, delegation))
return error("CreateCoinStake: Failed to find delegation");
CKeyID pubKeyHash(delegation.staker);
CPubKey pubKeyKernel;
if (!GetKernelKey(pubKeyHash, keystore, sign, pubKeyKernel, key))
{
LogPrint(BCLog::COINSTAKE, "CreateCoinStake : failed to get staker key for kernel type=%d\n", whichType);
break; // unable to find corresponding public key
}
scriptPubKeyStaker << pubKeyKernel.getvch() << OP_CHECKSIG;
}
if (whichType == TX_PUBKEY)
{
valtype& vchPubKey = vSolutions[0];
uint160 hash160(Hash160(vchPubKey));;
if(!GetDelegationStaker(hash160, delegation))
return error("CreateCoinStake: Failed to find delegation");
CKeyID pubKeyHash(delegation.staker);
CPubKey pubKeyKernel;
if (!GetKernelKey(pubKeyHash, keystore, sign, pubKeyKernel, key))
{
LogPrint(BCLog::COINSTAKE, "CreateCoinStake : failed to get staker key for kernel type=%d\n", whichType);
break; // unable to find corresponding public key
}
scriptPubKeyStaker <<pubKeyKernel.getvch() << OP_CHECKSIG;
}
delegateOutputExist = IsDelegateOutputExist(delegation.fee);
PKHash superStakerAddress(delegation.staker);
COutPoint prevoutSuperStaker;
CAmount nValueSuperStaker = 0;
const CWalletTx* pcoinSuperStaker = GetCoinSuperStaker(setCoins, superStakerAddress, prevoutSuperStaker, nValueSuperStaker);
if(!pcoinSuperStaker)
{
LogPrint(BCLog::COINSTAKE, "CreateCoinStake : failed to get utxo for super staker %s\n", EncodeDestination(superStakerAddress));
break; // unable to find utxo from the super staker
}
txNew.vin.push_back(CTxIn(prevoutSuperStaker));
nCredit += nValueSuperStaker;
vwtxPrev.push_back(std::make_pair(pcoinSuperStaker, prevoutSuperStaker.n));
txNew.vout.push_back(CTxOut(0, scriptPubKeyStaker));
if(delegateOutputExist)
{
txNew.vout.push_back(CTxOut(0, scriptPubKeyKernel));
}
LogPrint(BCLog::COINSTAKE, "CreateCoinStake : added kernel type=%d\n", whichType);
fKernelFound = true;
}
if (fKernelFound)
{
headerPrevout = prevoutStake;
break; // if kernel is found stop searching
}
}
if (nCredit == 0)
return false;
const Consensus::Params& consensusParams = Params().GetConsensus();
int64_t nRewardPiece = 0;
int64_t nRewardOffline = 0;
// Calculate reward
{
int64_t nTotalReward = nTotalFees + GetBlockSubsidy(pindexPrev->nHeight + 1, consensusParams);
if (nTotalReward < 0)
return false;
if(pindexPrev->nHeight < consensusParams.nFirstMPoSBlock || pindexPrev->nHeight >= consensusParams.nLastMPoSBlock)
{
// Keep whole reward
int64_t nRewardStaker = 0;
if(!SplitOfflineStakeReward(nTotalReward, delegation.fee, nRewardOffline, nRewardStaker))
return error("CreateCoinStake: Failed to split reward");
nCredit += nRewardStaker;
}
else
{
// Split the reward when mpos is used
nRewardPiece = nTotalReward / consensusParams.nMPoSRewardRecipients;
int64_t nRewardStaker = 0;
int64_t nReward = nRewardPiece + nTotalReward % consensusParams.nMPoSRewardRecipients;
if(!SplitOfflineStakeReward(nReward, delegation.fee, nRewardOffline, nRewardStaker))
return error("CreateCoinStake: Failed to split reward");
nCredit += nRewardStaker;
}
}
// Set output amount
txNew.vout[1].nValue = nCredit;
if(delegateOutputExist)
{
txNew.vout[2].nValue = nRewardOffline;
}
if(pindexPrev->nHeight >= consensusParams.nFirstMPoSBlock && pindexPrev->nHeight < consensusParams.nLastMPoSBlock)
{
if(!CreateMPoSOutputs(txNew, nRewardPiece, pindexPrev->nHeight, consensusParams))
return error("CreateCoinStake : failed to create MPoS reward outputs");
}
// Append the Refunds To Sender to the transaction outputs
for(unsigned int i = 2; i < tx.vout.size(); i++)
{
txNew.vout.push_back(tx.vout[i]);
}
// Sign the input coins
if(sign)
{
int nIn = 0;
for(const std::pair<const CWalletTx*,unsigned int> &pcoin : vwtxPrev)
{
if (!SignSignature(keystore, *pcoin.first->tx, txNew, nIn++, SIGHASH_ALL))
return error("CreateCoinStake : failed to sign coinstake");
}
}
// Successfully generated coinstake
tx = txNew;
// Save Proof Of Delegation
vchPoD = delegation.PoD;
return true;
}
bool CWallet::GetDelegationStaker(const uint160& keyid, Delegation& delegation)
{
std::map<uint160, Delegation>::iterator it = m_delegations_staker.find(keyid);
if(it == m_delegations_staker.end())
return false;
delegation = it->second;
return true;
}
const CWalletTx* CWallet::GetCoinSuperStaker(const std::set<std::pair<const CWalletTx*,unsigned int> >& setCoins, const PKHash& superStaker, COutPoint& prevout, CAmount& nValueRet)
{
for(const std::pair<const CWalletTx*,unsigned int> &pcoin : setCoins)
{
CAmount nValue = pcoin.first->tx->vout[pcoin.second].nValue;
if(nValue < DEFAULT_STAKING_MIN_UTXO_VALUE)
continue;
CScript scriptPubKey = pcoin.first->tx->vout[pcoin.second].scriptPubKey;
bool OK = false;
PKHash pkhash = ExtractPublicKeyHash(scriptPubKey, &OK);
if(OK && pkhash == superStaker)
{
nValueRet = nValue;
prevout = COutPoint(pcoin.first->GetHash(), pcoin.second);
return pcoin.first;
}
}
return 0;
}
bool CWallet::CanSuperStake(const std::set<std::pair<const CWalletTx*,unsigned int> >& setCoins, const std::vector<COutPoint>& setDelegateCoins) const
{
bool canSuperStake = false;
if(setDelegateCoins.size() > 0)
{
for(const std::pair<const CWalletTx*,unsigned int> &pcoin : setCoins)
{
CAmount nValue = pcoin.first->tx->vout[pcoin.second].nValue;
if(nValue >= DEFAULT_STAKING_MIN_UTXO_VALUE)
{
canSuperStake = true;
break;
}
}
}
return canSuperStake;
}
bool CWallet::CreateCoinStake(interfaces::Chain::Lock& locked_chain, const FillableSigningProvider& keystore, unsigned int nBits, const CAmount& nTotalFees, uint32_t nTimeBlock, CMutableTransaction& tx, CKey& key, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoins, std::vector<COutPoint>& setSelectedCoins, std::vector<COutPoint>& setDelegateCoins, bool selectedOnly, bool sign, std::vector<unsigned char>& vchPoD, COutPoint& headerPrevout)
{
// Can super stake
bool canSuperStake = CanSuperStake(setCoins, setDelegateCoins);
// Create coinstake from coins that are delegated to me
if(canSuperStake && CreateCoinStakeFromDelegate(locked_chain, keystore, nBits, nTotalFees, nTimeBlock, tx, key, setCoins, setDelegateCoins, sign, vchPoD, headerPrevout))
return true;
// Create coinstake from coins that are mine
if(setCoins.size() > 0 && CreateCoinStakeFromMine(locked_chain, keystore, nBits, nTotalFees, nTimeBlock, tx, key, setCoins, setSelectedCoins, selectedOnly, sign, headerPrevout))
return true;
// Fail to create coinstake
return false;
}
DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
{
// Even if we don't use this lock in this function, we want to preserve
// lock order in LoadToWallet if query of chain state is needed to know
// tx status. If lock can't be taken (e.g bitcoin-wallet), tx confirmation
// status may be not reliable.
auto locked_chain = LockChain();
LOCK(cs_wallet);
fFirstRunRet = false;
DBErrors nLoadWalletRet = WalletBatch(*database,"cr+").LoadWallet(this);
if (nLoadWalletRet == DBErrors::NEED_REWRITE)
{
if (database->Rewrite("\x04pool"))
{
for (const auto& spk_man_pair : m_spk_managers) {
spk_man_pair.second->RewriteDB();
}
}
}
// This wallet is in its first run if there are no ScriptPubKeyMans and it isn't blank or no privkeys
fFirstRunRet = m_spk_managers.empty() && !IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && !IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET);
if (fFirstRunRet) {
assert(m_external_spk_managers.empty());
assert(m_internal_spk_managers.empty());
}
if (nLoadWalletRet != DBErrors::LOAD_OK)
return nLoadWalletRet;
return DBErrors::LOAD_OK;
}
DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
{
AssertLockHeld(cs_wallet);
DBErrors nZapSelectTxRet = WalletBatch(*database, "cr+").ZapSelectTx(vHashIn, vHashOut);
for (uint256 hash : vHashOut) {
const auto& it = mapWallet.find(hash);
wtxOrdered.erase(it->second.m_it_wtxOrdered);
mapWallet.erase(it);
NotifyTransactionChanged(this, hash, CT_DELETED);
}
if (nZapSelectTxRet == DBErrors::NEED_REWRITE)
{
if (database->Rewrite("\x04pool"))
{
for (const auto& spk_man_pair : m_spk_managers) {
spk_man_pair.second->RewriteDB();
}
}
}
if (nZapSelectTxRet != DBErrors::LOAD_OK)
return nZapSelectTxRet;
MarkDirty();
return DBErrors::LOAD_OK;
}
DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
{
DBErrors nZapWalletTxRet = WalletBatch(*database,"cr+").ZapWalletTx(vWtx);
if (nZapWalletTxRet == DBErrors::NEED_REWRITE)
{
if (database->Rewrite("\x04pool"))
{
for (const auto& spk_man_pair : m_spk_managers) {
spk_man_pair.second->RewriteDB();
}
}
}
if (nZapWalletTxRet != DBErrors::LOAD_OK)
return nZapWalletTxRet;
return DBErrors::LOAD_OK;
}
bool CWallet::SetAddressBookWithDB(WalletBatch& batch, const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
{
bool fUpdated = false;
{
LOCK(cs_wallet);
std::map<CTxDestination, CAddressBookData>::iterator mi = m_address_book.find(address);
fUpdated = (mi != m_address_book.end() && !mi->second.IsChange());
m_address_book[address].SetLabel(strName);
if (!strPurpose.empty()) /* update purpose only if requested */
m_address_book[address].purpose = strPurpose;
}
NotifyAddressBookChanged(this, address, strName, IsMine(address) != ISMINE_NO,
strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
if (!strPurpose.empty() && !batch.WritePurpose(EncodeDestination(address), strPurpose))
return false;
return batch.WriteName(EncodeDestination(address), strName);
}
bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
{
WalletBatch batch(*database);
return SetAddressBookWithDB(batch, address, strName, strPurpose);
}
bool CWallet::DelAddressBook(const CTxDestination& address)
{
// If we want to delete receiving addresses, we need to take care that DestData "used" (and possibly newer DestData) gets preserved (and the "deleted" address transformed into a change entry instead of actually being deleted)
// NOTE: This isn't a problem for sending addresses because they never have any DestData yet!
// When adding new DestData, it should be considered here whether to retain or delete it (or move it?).
if (IsMine(address)) {
WalletLogPrintf("%s called with IsMine address, NOT SUPPORTED. Please report this bug! %s\n", __func__, PACKAGE_BUGREPORT);
return false;
}
{
LOCK(cs_wallet);
// Delete destdata tuples associated with address
std::string strAddress = EncodeDestination(address);
for (const std::pair<const std::string, std::string> &item : m_address_book[address].destdata)
{
WalletBatch(*database).EraseDestData(strAddress, item.first);
}
m_address_book.erase(address);
}
NotifyAddressBookChanged(this, address, "", IsMine(address) != ISMINE_NO, "", CT_DELETED);
WalletBatch(*database).ErasePurpose(EncodeDestination(address));
return WalletBatch(*database).EraseName(EncodeDestination(address));
}
size_t CWallet::KeypoolCountExternalKeys() const
{
AssertLockHeld(cs_wallet);
unsigned int count = 0;
for (auto spk_man : GetActiveScriptPubKeyMans()) {
count += spk_man->KeypoolCountExternalKeys();
}
return count;
}
unsigned int CWallet::GetKeyPoolSize() const
{
AssertLockHeld(cs_wallet);
unsigned int count = 0;
for (auto spk_man : GetActiveScriptPubKeyMans()) {
count += spk_man->GetKeyPoolSize();
}
return count;
}
bool CWallet::TopUpKeyPool(unsigned int kpSize)
{
LOCK(cs_wallet);
bool res = true;
for (auto spk_man : GetActiveScriptPubKeyMans()) {
res &= spk_man->TopUp(kpSize);
}
return res;
}
bool CWallet::GetNewDestination(const OutputType type, const std::string label, CTxDestination& dest, std::string& error)
{
LOCK(cs_wallet);
error.clear();
bool result = false;
auto spk_man = GetScriptPubKeyMan(type, false /* internal */);
if (spk_man) {
spk_man->TopUp();
result = spk_man->GetNewDestination(type, dest, error);
}
if (result) {
SetAddressBook(dest, label, "receive");
}
return result;
}
bool CWallet::GetNewChangeDestination(const OutputType type, CTxDestination& dest, std::string& error)
{
LOCK(cs_wallet);
error.clear();
ReserveDestination reservedest(this, type);
if (!reservedest.GetReservedDestination(dest, true)) {
error = "Error: Keypool ran out, please call keypoolrefill first";
return false;
}
reservedest.KeepDestination();
return true;
}
int64_t CWallet::GetOldestKeyPoolTime() const
{
LOCK(cs_wallet);
int64_t oldestKey = std::numeric_limits<int64_t>::max();
for (const auto& spk_man_pair : m_spk_managers) {
oldestKey = std::min(oldestKey, spk_man_pair.second->GetOldestKeyPoolTime());
}
return oldestKey;
}
void CWallet::MarkDestinationsDirty(const std::set<CTxDestination>& destinations) {
for (auto& entry : mapWallet) {
CWalletTx& wtx = entry.second;
if (wtx.m_is_cache_empty) continue;
for (unsigned int i = 0; i < wtx.tx->vout.size(); i++) {
CTxDestination dst;
if (ExtractDestination(wtx.tx->vout[i].scriptPubKey, dst) && destinations.count(dst)) {
wtx.MarkDirty();
break;
}
}
}
}
std::map<CTxDestination, CAmount> CWallet::GetAddressBalances(interfaces::Chain::Lock& locked_chain) const
{
std::map<CTxDestination, CAmount> balances;
{
LOCK(cs_wallet);
std::set<uint256> trusted_parents;
for (const auto& walletEntry : mapWallet)
{
const CWalletTx& wtx = walletEntry.second;
if (!wtx.IsTrusted(locked_chain, trusted_parents))
continue;
if (wtx.IsImmature())
continue;
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < (wtx.IsFromMe(ISMINE_ALL) ? 0 : 1))
continue;
for (unsigned int i = 0; i < wtx.tx->vout.size(); i++)
{
CTxDestination addr;
if (!IsMine(wtx.tx->vout[i]))
continue;
if(!ExtractDestination(wtx.tx->vout[i].scriptPubKey, addr))
continue;
CAmount n = IsSpent(walletEntry.first, i) ? 0 : wtx.tx->vout[i].nValue;
if (!balances.count(addr))
balances[addr] = 0;
balances[addr] += n;
}
}
}
return balances;
}
std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings() const
{
AssertLockHeld(cs_wallet);
std::set< std::set<CTxDestination> > groupings;
std::set<CTxDestination> grouping;
for (const auto& walletEntry : mapWallet)
{
const CWalletTx& wtx = walletEntry.second;
if (wtx.tx->vin.size() > 0)
{
bool any_mine = false;
// group all input addresses with each other
for (const CTxIn& txin : wtx.tx->vin)
{
CTxDestination address;
if(!IsMine(txin)) /* If this input isn't mine, ignore it */
continue;
if(!ExtractDestination(mapWallet.at(txin.prevout.hash).tx->vout[txin.prevout.n].scriptPubKey, address))
continue;
grouping.insert(address);
any_mine = true;
}
// group change with input addresses
if (any_mine)
{
for (const CTxOut& txout : wtx.tx->vout)
if (IsChange(txout))
{
CTxDestination txoutAddr;
if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
continue;
grouping.insert(txoutAddr);
}
}
if (grouping.size() > 0)
{
groupings.insert(grouping);
grouping.clear();
}
}
// group lone addrs by themselves
for (const auto& txout : wtx.tx->vout)
if (IsMine(txout))
{
CTxDestination address;
if(!ExtractDestination(txout.scriptPubKey, address))
continue;
grouping.insert(address);
groupings.insert(grouping);
grouping.clear();
}
}
std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
for (std::set<CTxDestination> _grouping : groupings)
{
// make a set of all the groups hit by this new group
std::set< std::set<CTxDestination>* > hits;
std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
for (const CTxDestination& address : _grouping)
if ((it = setmap.find(address)) != setmap.end())
hits.insert((*it).second);
// merge all hit groups into a new single group and delete old groups
std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
for (std::set<CTxDestination>* hit : hits)
{
merged->insert(hit->begin(), hit->end());
uniqueGroupings.erase(hit);
delete hit;
}
uniqueGroupings.insert(merged);
// update setmap
for (const CTxDestination& element : *merged)
setmap[element] = merged;
}
std::set< std::set<CTxDestination> > ret;
for (const std::set<CTxDestination>* uniqueGrouping : uniqueGroupings)
{
ret.insert(*uniqueGrouping);
delete uniqueGrouping;
}
return ret;
}
std::set<CTxDestination> CWallet::GetLabelAddresses(const std::string& label) const
{
LOCK(cs_wallet);
std::set<CTxDestination> result;
for (const std::pair<const CTxDestination, CAddressBookData>& item : m_address_book)
{
if (item.second.IsChange()) continue;
const CTxDestination& address = item.first;
const std::string& strName = item.second.GetLabel();
if (strName == label)
result.insert(address);
}
return result;
}
// disable transaction (only for coinstake)
void CWallet::DisableTransaction(const CTransaction &tx)
{
if (!tx.IsCoinStake() || !IsFromMe(tx))
return; // only disconnecting coinstake requires marking input unspent
uint256 hash = tx.GetHash();
if(AbandonTransaction(hash))
{
LOCK(cs_wallet);
RemoveFromSpends(hash);
for(const CTxIn& txin : tx.vin)
{
auto it = mapWallet.find(txin.prevout.hash);
if (it != mapWallet.end()) {
CWalletTx &coin = it->second;
coin.BindWallet(this);
NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
}
}
CWalletTx& wtx = mapWallet.at(hash);
wtx.BindWallet(this);
NotifyTransactionChanged(this, hash, CT_DELETED);
}
}
bool ReserveDestination::GetReservedDestination(CTxDestination& dest, bool internal)
{
m_spk_man = pwallet->GetScriptPubKeyMan(type, internal);
if (!m_spk_man) {
return false;
}
if (nIndex == -1)
{
m_spk_man->TopUp();
CKeyPool keypool;
if (!m_spk_man->GetReservedDestination(type, internal, address, nIndex, keypool)) {
return false;
}
fInternal = keypool.fInternal;
}
dest = address;
return true;
}
void ReserveDestination::KeepDestination()
{
if (nIndex != -1) {
m_spk_man->KeepDestination(nIndex, type);
}
nIndex = -1;
address = CNoDestination();
}
void ReserveDestination::ReturnDestination()
{
if (nIndex != -1) {
m_spk_man->ReturnDestination(nIndex, fInternal, address);
}
nIndex = -1;
address = CNoDestination();
}
void CWallet::LockCoin(const COutPoint& output)
{
AssertLockHeld(cs_wallet);
setLockedCoins.insert(output);
}
void CWallet::UnlockCoin(const COutPoint& output)
{
AssertLockHeld(cs_wallet);
setLockedCoins.erase(output);
}
void CWallet::UnlockAllCoins()
{
AssertLockHeld(cs_wallet);
setLockedCoins.clear();
}
bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
{
#ifndef DEBUG_LOCKORDER
AssertLockHeld(cs_wallet);
#endif
COutPoint outpt(hash, n);
return (setLockedCoins.count(outpt) > 0);
}
void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
{
AssertLockHeld(cs_wallet);
for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
it != setLockedCoins.end(); it++) {
COutPoint outpt = (*it);
vOutpts.push_back(outpt);
}
}
/** @} */ // end of Actions
void CWallet::GetKeyBirthTimes(interfaces::Chain::Lock& locked_chain, std::map<CKeyID, int64_t>& mapKeyBirth) const {
AssertLockHeld(cs_wallet);
mapKeyBirth.clear();
LegacyScriptPubKeyMan* spk_man = GetLegacyScriptPubKeyMan();
assert(spk_man != nullptr);
LOCK(spk_man->cs_KeyStore);
// get birth times for keys with metadata
for (const auto& entry : spk_man->mapKeyMetadata) {
if (entry.second.nCreateTime) {
mapKeyBirth[entry.first] = entry.second.nCreateTime;
}
}
// map in which we'll infer heights of other keys
const Optional<int> tip_height = locked_chain.getHeight();
const int max_height = tip_height && *tip_height > 144 ? *tip_height - 144 : 0; // the tip can be reorganized; use a 144-block safety margin
std::map<CKeyID, int> mapKeyFirstBlock;
for (const CKeyID &keyid : spk_man->GetKeys()) {
if (mapKeyBirth.count(keyid) == 0)
mapKeyFirstBlock[keyid] = max_height;
}
// if there are no such keys, we're done
if (mapKeyFirstBlock.empty())
return;
// find first block that affects those keys, if there are any left
for (const auto& entry : mapWallet) {
// iterate over all wallet transactions...
const CWalletTx &wtx = entry.second;
if (Optional<int> height = locked_chain.getBlockHeight(wtx.m_confirm.hashBlock)) {
// ... which are already in a block
for (const CTxOut &txout : wtx.tx->vout) {
// iterate over all their outputs
for (const auto &keyid : GetAffectedKeys(txout.scriptPubKey, *spk_man)) {
// ... and all their affected keys
std::map<CKeyID, int>::iterator rit = mapKeyFirstBlock.find(keyid);
if (rit != mapKeyFirstBlock.end() && *height < rit->second)
rit->second = *height;
}
}
}
}
// Extract block timestamps for those keys
for (const auto& entry : mapKeyFirstBlock)
mapKeyBirth[entry.first] = locked_chain.getBlockTime(entry.second) - TIMESTAMP_WINDOW; // block times can be 2h off
}
/**
* Compute smart timestamp for a transaction being added to the wallet.
*
* Logic:
* - If sending a transaction, assign its timestamp to the current time.
* - If receiving a transaction outside a block, assign its timestamp to the
* current time.
* - If receiving a block with a future timestamp, assign all its (not already
* known) transactions' timestamps to the current time.
* - If receiving a block with a past timestamp, before the most recent known
* transaction (that we care about), assign all its (not already known)
* transactions' timestamps to the same timestamp as that most-recent-known
* transaction.
* - If receiving a block with a past timestamp, but after the most recent known
* transaction, assign all its (not already known) transactions' timestamps to
* the block time.
*
* For more information see CWalletTx::nTimeSmart,
* https://bitcointalk.org/?topic=54527, or
* https://github.com/bitcoin/bitcoin/pull/1393.
*/
unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
{
unsigned int nTimeSmart = wtx.nTimeReceived;
if (!wtx.isUnconfirmed() && !wtx.isAbandoned()) {
int64_t blocktime;
if (chain().findBlock(wtx.m_confirm.hashBlock, nullptr /* block */, &blocktime)) {
int64_t latestNow = wtx.nTimeReceived;
int64_t latestEntry = 0;
// Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
int64_t latestTolerated = latestNow + 300;
const TxItems& txOrdered = wtxOrdered;
for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
CWalletTx* const pwtx = it->second;
if (pwtx == &wtx) {
continue;
}
int64_t nSmartTime;
nSmartTime = pwtx->nTimeSmart;
if (!nSmartTime) {
nSmartTime = pwtx->nTimeReceived;
}
if (nSmartTime <= latestTolerated) {
latestEntry = nSmartTime;
if (nSmartTime > latestNow) {
latestNow = nSmartTime;
}
break;
}
}
nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
} else {
WalletLogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.m_confirm.hashBlock.ToString());
}
}
return nTimeSmart;
}
bool CWallet::AddDestData(WalletBatch& batch, const CTxDestination &dest, const std::string &key, const std::string &value)
{
if (boost::get<CNoDestination>(&dest))
return false;
m_address_book[dest].destdata.insert(std::make_pair(key, value));
return batch.WriteDestData(EncodeDestination(dest), key, value);
}
bool CWallet::EraseDestData(WalletBatch& batch, const CTxDestination &dest, const std::string &key)
{
if (!m_address_book[dest].destdata.erase(key))
return false;
return batch.EraseDestData(EncodeDestination(dest), key);
}
void CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
{
m_address_book[dest].destdata.insert(std::make_pair(key, value));
}
bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
{
std::map<CTxDestination, CAddressBookData>::const_iterator i = m_address_book.find(dest);
if(i != m_address_book.end())
{
CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
if(j != i->second.destdata.end())
{
if(value)
*value = j->second;
return true;
}
}
return false;
}
std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
{
std::vector<std::string> values;
for (const auto& address : m_address_book) {
for (const auto& data : address.second.destdata) {
if (!data.first.compare(0, prefix.size(), prefix)) {
values.emplace_back(data.second);
}
}
}
return values;
}
bool CWallet::Verify(interfaces::Chain& chain, const WalletLocation& location, bool salvage_wallet, std::string& error_string, std::vector<std::string>& warnings)
{
// Do some checking on wallet path. It should be either a:
//
// 1. Path where a directory can be created.
// 2. Path to an existing directory.
// 3. Path to a symlink to a directory.
// 4. For backwards compatibility, the name of a data file in -walletdir.
LOCK(cs_wallets);
const fs::path& wallet_path = location.GetPath();
fs::file_type path_type = fs::symlink_status(wallet_path).type();
if (!(path_type == fs::file_not_found || path_type == fs::directory_file ||
(path_type == fs::symlink_file && fs::is_directory(wallet_path)) ||
(path_type == fs::regular_file && fs::path(location.GetName()).filename() == location.GetName()))) {
error_string = strprintf(
"Invalid -wallet path '%s'. -wallet path should point to a directory where wallet.dat and "
"database/log.?????????? files can be stored, a location where such a directory could be created, "
"or (for backwards compatibility) the name of an existing data file in -walletdir (%s)",
location.GetName(), GetWalletDir());
return false;
}
// Make sure that the wallet path doesn't clash with an existing wallet path
if (IsWalletLoaded(wallet_path)) {
error_string = strprintf("Error loading wallet %s. Duplicate -wallet filename specified.", location.GetName());
return false;
}
// Keep same database environment instance across Verify/Recover calls below.
std::unique_ptr<WalletDatabase> database = WalletDatabase::Create(wallet_path);
try {
if (!WalletBatch::VerifyEnvironment(wallet_path, error_string)) {
return false;
}
} catch (const fs::filesystem_error& e) {
error_string = strprintf("Error loading wallet %s. %s", location.GetName(), fsbridge::get_filesystem_error_message(e));
return false;
}
if (salvage_wallet) {
// Recover readable keypairs:
CWallet dummyWallet(&chain, WalletLocation(), WalletDatabase::CreateDummy());
std::string backup_filename;
// Even if we don't use this lock in this function, we want to preserve
// lock order in LoadToWallet if query of chain state is needed to know
// tx status. If lock can't be taken, tx confirmation status may be not
// reliable.
auto locked_chain = dummyWallet.LockChain();
if (!WalletBatch::Recover(wallet_path, (void *)&dummyWallet, WalletBatch::RecoverKeysOnlyFilter, backup_filename)) {
return false;
}
}
return WalletBatch::VerifyDatabaseFile(wallet_path, warnings, error_string);
}
std::shared_ptr<CWallet> CWallet::CreateWalletFromFile(interfaces::Chain& chain, const WalletLocation& location, std::string& error, std::vector<std::string>& warnings, uint64_t wallet_creation_flags)
{
const std::string walletFile = WalletDataFilePath(location.GetPath()).string();
// needed to restore wallet transaction meta data after -zapwallettxes
std::vector<CWalletTx> vWtx;
if (gArgs.GetBoolArg("-zapwallettxes", false)) {
chain.initMessage(_("Zapping all transactions from wallet...").translated);
std::unique_ptr<CWallet> tempWallet = MakeUnique<CWallet>(&chain, location, WalletDatabase::Create(location.GetPath()));
DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
if (nZapWalletRet != DBErrors::LOAD_OK) {
error = strprintf(_("Error loading %s: Wallet corrupted").translated, walletFile);
return nullptr;
}
}
chain.initMessage(_("Loading wallet...").translated);
int64_t nStart = GetTimeMillis();
bool fFirstRun = true;
// TODO: Can't use std::make_shared because we need a custom deleter but
// should be possible to use std::allocate_shared.
std::shared_ptr<CWallet> walletInstance(new CWallet(&chain, location, WalletDatabase::Create(location.GetPath())), ReleaseWallet);
DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
if (nLoadWalletRet != DBErrors::LOAD_OK) {
if (nLoadWalletRet == DBErrors::CORRUPT) {
error = strprintf(_("Error loading %s: Wallet corrupted").translated, walletFile);
return nullptr;
}
else if (nLoadWalletRet == DBErrors::NONCRITICAL_ERROR)
{
warnings.push_back(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
" or address book entries might be missing or incorrect.").translated,
walletFile));
}
else if (nLoadWalletRet == DBErrors::TOO_NEW) {
error = strprintf(_("Error loading %s: Wallet requires newer version of %s").translated, walletFile, PACKAGE_NAME);
return nullptr;
}
else if (nLoadWalletRet == DBErrors::NEED_REWRITE)
{
error = strprintf(_("Wallet needed to be rewritten: restart %s to complete").translated, PACKAGE_NAME);
return nullptr;
}
else {
error = strprintf(_("Error loading %s").translated, walletFile);
return nullptr;
}
}
int prev_version = walletInstance->GetVersion();
if (gArgs.GetBoolArg("-upgradewallet", fFirstRun))
{
int nMaxVersion = gArgs.GetArg("-upgradewallet", 0);
if (nMaxVersion == 0) // the -upgradewallet without argument case
{
walletInstance->WalletLogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
nMaxVersion = FEATURE_LATEST;
walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
}
else
walletInstance->WalletLogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
if (nMaxVersion < walletInstance->GetVersion())
{
error = _("Cannot downgrade wallet").translated;
return nullptr;
}
walletInstance->SetMaxVersion(nMaxVersion);
}
// Upgrade to HD if explicit upgrade
if (gArgs.GetBoolArg("-upgradewallet", false)) {
LOCK(walletInstance->cs_wallet);
// Do not upgrade versions to any version between HD_SPLIT and FEATURE_PRE_SPLIT_KEYPOOL unless already supporting HD_SPLIT
int max_version = walletInstance->GetVersion();
if (!walletInstance->CanSupportFeature(FEATURE_HD_SPLIT) && max_version >= FEATURE_HD_SPLIT && max_version < FEATURE_PRE_SPLIT_KEYPOOL) {
error = _("Cannot upgrade a non HD split wallet without upgrading to support pre split keypool. Please use -upgradewallet=169900 or -upgradewallet with no version specified.").translated;
return nullptr;
}
for (auto spk_man : walletInstance->GetActiveScriptPubKeyMans()) {
if (!spk_man->Upgrade(prev_version, error)) {
return nullptr;
}
}
}
if (fFirstRun)
{
// ensure this wallet.dat can only be opened by clients supporting HD with chain split and expects no default key
walletInstance->SetMinVersion(FEATURE_LATEST);
walletInstance->SetWalletFlags(wallet_creation_flags, false);
// Always create LegacyScriptPubKeyMan for now
walletInstance->SetupLegacyScriptPubKeyMan();
if (!(wallet_creation_flags & (WALLET_FLAG_DISABLE_PRIVATE_KEYS | WALLET_FLAG_BLANK_WALLET))) {
LOCK(walletInstance->cs_wallet);
for (auto spk_man : walletInstance->GetActiveScriptPubKeyMans()) {
if (!spk_man->SetupGeneration()) {
error = _("Unable to generate initial keys").translated;
return nullptr;
}
}
}
auto locked_chain = chain.lock();
walletInstance->chainStateFlushed(locked_chain->getTipLocator());
} else if (wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS) {
// Make it impossible to disable private keys after creation
error = strprintf(_("Error loading %s: Private keys can only be disabled during creation").translated, walletFile);
return NULL;
} else if (walletInstance->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
for (auto spk_man : walletInstance->GetActiveScriptPubKeyMans()) {
if (spk_man->HavePrivateKeys()) {
warnings.push_back(strprintf(_("Warning: Private keys detected in wallet {%s} with disabled private keys").translated, walletFile));
break;
}
}
}
if (!gArgs.GetArg("-addresstype", "").empty() && !ParseOutputType(gArgs.GetArg("-addresstype", ""), walletInstance->m_default_address_type)) {
error = strprintf(_("Unknown address type '%s'").translated, gArgs.GetArg("-addresstype", ""));
return nullptr;
}
if (!gArgs.GetArg("-changetype", "").empty() && !ParseOutputType(gArgs.GetArg("-changetype", ""), walletInstance->m_default_change_type)) {
error = strprintf(_("Unknown change type '%s'").translated, gArgs.GetArg("-changetype", ""));
return nullptr;
}
if (gArgs.IsArgSet("-mintxfee")) {
CAmount n = 0;
if (!ParseMoney(gArgs.GetArg("-mintxfee", ""), n) || 0 == n) {
error = AmountErrMsg("mintxfee", gArgs.GetArg("-mintxfee", "")).translated;
return nullptr;
}
if (n > HIGH_TX_FEE_PER_KB) {
warnings.push_back(AmountHighWarn("-mintxfee").translated + " " +
_("This is the minimum transaction fee you pay on every transaction.").translated);
}
walletInstance->m_min_fee = CFeeRate(n);
}
if (gArgs.IsArgSet("-fallbackfee")) {
CAmount nFeePerK = 0;
if (!ParseMoney(gArgs.GetArg("-fallbackfee", ""), nFeePerK)) {
error = strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'").translated, gArgs.GetArg("-fallbackfee", ""));
return nullptr;
}
if (nFeePerK > HIGH_TX_FEE_PER_KB) {
warnings.push_back(AmountHighWarn("-fallbackfee").translated + " " +
_("This is the transaction fee you may pay when fee estimates are not available.").translated);
}
walletInstance->m_fallback_fee = CFeeRate(nFeePerK);
}
// Disable fallback fee in case value was set to 0, enable if non-null value
walletInstance->m_allow_fallback_fee = walletInstance->m_fallback_fee.GetFeePerK() != 0;
if (gArgs.IsArgSet("-discardfee")) {
CAmount nFeePerK = 0;
if (!ParseMoney(gArgs.GetArg("-discardfee", ""), nFeePerK)) {
error = strprintf(_("Invalid amount for -discardfee=<amount>: '%s'").translated, gArgs.GetArg("-discardfee", ""));
return nullptr;
}
if (nFeePerK > HIGH_TX_FEE_PER_KB) {
warnings.push_back(AmountHighWarn("-discardfee").translated + " " +
_("This is the transaction fee you may discard if change is smaller than dust at this level").translated);
}
walletInstance->m_discard_rate = CFeeRate(nFeePerK);
}
if (gArgs.IsArgSet("-paytxfee")) {
CAmount nFeePerK = 0;
if (!ParseMoney(gArgs.GetArg("-paytxfee", ""), nFeePerK)) {
error = AmountErrMsg("paytxfee", gArgs.GetArg("-paytxfee", "")).translated;
return nullptr;
}
if (nFeePerK > HIGH_TX_FEE_PER_KB) {
warnings.push_back(AmountHighWarn("-paytxfee").translated + " " +
_("This is the transaction fee you will pay if you send a transaction.").translated);
}
walletInstance->m_pay_tx_fee = CFeeRate(nFeePerK, 1000);
if (walletInstance->m_pay_tx_fee < chain.relayMinFee()) {
error = strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)").translated,
gArgs.GetArg("-paytxfee", ""), chain.relayMinFee().ToString());
return nullptr;
}
}
if (gArgs.IsArgSet("-maxtxfee")) {
CAmount nMaxFee = 0;
if (!ParseMoney(gArgs.GetArg("-maxtxfee", ""), nMaxFee)) {
error = AmountErrMsg("maxtxfee", gArgs.GetArg("-maxtxfee", "")).translated;
return nullptr;
}
if (nMaxFee > HIGH_MAX_TX_FEE) {
warnings.push_back(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction.").translated);
}
if (CFeeRate(nMaxFee, 1000) < chain.relayMinFee()) {
error = strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)").translated,
gArgs.GetArg("-maxtxfee", ""), chain.relayMinFee().ToString());
return nullptr;
}
walletInstance->m_default_max_tx_fee = nMaxFee;
}
if (chain.relayMinFee().GetFeePerK() > HIGH_TX_FEE_PER_KB) {
warnings.push_back(AmountHighWarn("-minrelaytxfee").translated + " " +
_("The wallet will avoid paying less than the minimum relay fee.").translated);
}
walletInstance->m_confirm_target = gArgs.GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
walletInstance->m_spend_zero_conf_change = gArgs.GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
walletInstance->m_signal_rbf = gArgs.GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF);
if(!ParseMoney(gArgs.GetArg("-reservebalance", FormatMoney(DEFAULT_RESERVE_BALANCE)), walletInstance->m_reserve_balance))
walletInstance->m_reserve_balance = DEFAULT_RESERVE_BALANCE;
walletInstance->m_use_change_address = gArgs.GetBoolArg("-usechangeaddress", DEFAULT_USE_CHANGE_ADDRESS);
if(!ParseMoney(gArgs.GetArg("-stakingminutxovalue", FormatMoney(DEFAULT_STAKING_MIN_UTXO_VALUE)), walletInstance->m_staking_min_utxo_value))
walletInstance->m_staking_min_utxo_value = DEFAULT_STAKING_MIN_UTXO_VALUE;
if(!ParseMoney(gArgs.GetArg("-minstakerutxosize", FormatMoney(DEFAULT_STAKER_MIN_UTXO_SIZE)), walletInstance->m_staker_min_utxo_size))
walletInstance->m_staker_min_utxo_size = DEFAULT_STAKER_MIN_UTXO_SIZE;
if (gArgs.IsArgSet("-stakingminfee"))
{
int nStakingMinFee = gArgs.GetArg("-stakingminfee", DEFAULT_STAKING_MIN_FEE);
if(nStakingMinFee < 0 || nStakingMinFee > 100)
{
chain.initError(strprintf(_("Invalid percentage value for -stakingminfee=<n>: '%d' (must be between 0 and 100)").translated, nStakingMinFee));
return nullptr;
}
walletInstance->m_staking_min_fee = nStakingMinFee;
}
walletInstance->m_staker_max_utxo_script_cache = gArgs.GetArg("-maxstakerutxoscriptcache", DEFAULT_STAKER_MAX_UTXO_SCRIPT_CACHE);
walletInstance->m_num_threads = gArgs.GetArg("-stakerthreads", GetNumCores());
walletInstance->m_num_threads = std::max(1, walletInstance->m_num_threads);
walletInstance->m_ledger_id = gArgs.GetArg("-stakerledgerid", "");
walletInstance->WalletLogPrintf("Wallet completed loading in %15dms\n", GetTimeMillis() - nStart);
// Try to top up keypool. No-op if the wallet is locked.
walletInstance->TopUpKeyPool();
auto locked_chain = chain.lock();
LOCK(walletInstance->cs_wallet);
int rescan_height = 0;
if (!gArgs.GetBoolArg("-rescan", false))
{
WalletBatch batch(*walletInstance->database);
CBlockLocator locator;
if (batch.ReadBestBlock(locator)) {
if (const Optional<int> fork_height = locked_chain->findLocatorFork(locator)) {
rescan_height = *fork_height;
}
}
}
const Optional<int> tip_height = locked_chain->getHeight();
if (tip_height) {
walletInstance->m_last_block_processed = locked_chain->getBlockHash(*tip_height);
walletInstance->m_last_block_processed_height = *tip_height;
} else {
walletInstance->m_last_block_processed.SetNull();
walletInstance->m_last_block_processed_height = -1;
}
if (tip_height && *tip_height != rescan_height)
{
// We can't rescan beyond non-pruned blocks, stop and throw an error.
// This might happen if a user uses an old wallet within a pruned node
// or if they ran -disablewallet for a longer time, then decided to re-enable
if (chain.havePruned()) {
// Exit early and print an error.
// If a block is pruned after this check, we will load the wallet,
// but fail the rescan with a generic error.
int block_height = *tip_height;
while (block_height > 0 && locked_chain->haveBlockOnDisk(block_height - 1) && rescan_height != block_height) {
--block_height;
}
if (rescan_height != block_height) {
error = _("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)").translated;
return nullptr;
}
}
chain.initMessage(_("Rescanning...").translated);
walletInstance->WalletLogPrintf("Rescanning last %i blocks (from block %i)...\n", *tip_height - rescan_height, rescan_height);
// No need to read and scan block if block was created before
// our wallet birthday (as adjusted for block time variability)
// The way the 'time_first_key' is initialized is just a workaround for the gcc bug #47679 since version 4.6.0.
Optional<int64_t> time_first_key = MakeOptional(false, int64_t());;
for (auto spk_man : walletInstance->GetAllScriptPubKeyMans()) {
int64_t time = spk_man->GetTimeFirstKey();
if (!time_first_key || time < *time_first_key) time_first_key = time;
}
if (time_first_key) {
if (Optional<int> first_block = locked_chain->findFirstBlockWithTimeAndHeight(*time_first_key - TIMESTAMP_WINDOW, rescan_height, nullptr)) {
rescan_height = *first_block;
}
}
{
WalletRescanReserver reserver(walletInstance.get());
if (!reserver.reserve() || (ScanResult::SUCCESS != walletInstance->ScanForWalletTransactions(locked_chain->getBlockHash(rescan_height), {} /* stop block */, reserver, true /* update */).status)) {
error = _("Failed to rescan the wallet during initialization").translated;
return nullptr;
}
}
walletInstance->chainStateFlushed(locked_chain->getTipLocator());
walletInstance->database->IncrementUpdateCounter();
// Restore wallet transaction metadata after -zapwallettxes=1
if (gArgs.GetBoolArg("-zapwallettxes", false) && gArgs.GetArg("-zapwallettxes", "1") != "2")
{
WalletBatch batch(*walletInstance->database);
for (const CWalletTx& wtxOld : vWtx)
{
uint256 hash = wtxOld.GetHash();
std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
if (mi != walletInstance->mapWallet.end())
{
const CWalletTx* copyFrom = &wtxOld;
CWalletTx* copyTo = &mi->second;
copyTo->mapValue = copyFrom->mapValue;
copyTo->vOrderForm = copyFrom->vOrderForm;
copyTo->nTimeReceived = copyFrom->nTimeReceived;
copyTo->nTimeSmart = copyFrom->nTimeSmart;
copyTo->fFromMe = copyFrom->fFromMe;
copyTo->nOrderPos = copyFrom->nOrderPos;
batch.WriteTx(*copyTo);
}
}
}
}
{
LOCK(cs_wallets);
for (auto& load_wallet : g_load_wallet_fns) {
load_wallet(interfaces::MakeWallet(walletInstance));
}
}
// Register with the validation interface. It's ok to do this after rescan since we're still holding locked_chain.
walletInstance->m_chain_notifications_handler = walletInstance->chain().handleNotifications(walletInstance);
walletInstance->SetBroadcastTransactions(gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
{
walletInstance->WalletLogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
walletInstance->WalletLogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
walletInstance->WalletLogPrintf("m_address_book.size() = %u\n", walletInstance->m_address_book.size());
}
if(!fReindex)
// Clean not reverted coinstake transactions
walletInstance->CleanCoinStake();
return walletInstance;
}
const CAddressBookData* CWallet::FindAddressBookEntry(const CTxDestination& dest, bool allow_change) const
{
const auto& address_book_it = m_address_book.find(dest);
if (address_book_it == m_address_book.end()) return nullptr;
if ((!allow_change) && address_book_it->second.IsChange()) {
return nullptr;
}
return &address_book_it->second;
}
void CWallet::postInitProcess()
{
auto locked_chain = chain().lock();
LOCK(cs_wallet);
// Add wallet transactions that aren't already in a block to mempool
// Do this here as mempool requires genesis block to be loaded
ReacceptWalletTransactions();
// Update wallet transactions with current mempool transactions.
chain().requestMempoolTransactions(*this);
// Start mine proof-of-stake blocks in the background
if (gArgs.GetBoolArg("-staking", DEFAULT_STAKE)) {
StartStake();
}
}
bool CWallet::BackupWallet(const std::string& strDest) const
{
return database->Backup(strDest);
}
bool CWallet::LoadToken(const CTokenInfo &token)
{
uint256 hash = token.GetHash();
mapToken[hash] = token;
return true;
}
bool CWallet::LoadTokenTx(const CTokenTx &tokenTx)
{
uint256 hash = tokenTx.GetHash();
mapTokenTx[hash] = tokenTx;
return true;
}
bool CWallet::AddTokenEntry(const CTokenInfo &token, bool fFlushOnClose)
{
LOCK(cs_wallet);
WalletBatch batch(*database, "r+", fFlushOnClose);
uint256 hash = token.GetHash();
bool fInsertedNew = true;
std::map<uint256, CTokenInfo>::iterator it = mapToken.find(hash);
if(it!=mapToken.end())
{
fInsertedNew = false;
}
// Write to disk
CTokenInfo wtoken = token;
if(!fInsertedNew)
{
wtoken.nCreateTime = chain().getAdjustedTime();
}
else
{
wtoken.nCreateTime = it->second.nCreateTime;
}
if (!batch.WriteToken(wtoken))
return false;
mapToken[hash] = wtoken;
NotifyTokenChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
// Refresh token tx
if(fInsertedNew)
{
for(auto it = mapTokenTx.begin(); it != mapTokenTx.end(); it++)
{
uint256 tokenTxHash = it->second.GetHash();
NotifyTokenTransactionChanged(this, tokenTxHash, CT_UPDATED);
}
}
LogPrintf("AddTokenEntry %s\n", wtoken.GetHash().ToString());
return true;
}
bool CWallet::AddTokenTxEntry(const CTokenTx &tokenTx, bool fFlushOnClose)
{
LOCK(cs_wallet);
WalletBatch batch(*database, "r+", fFlushOnClose);
uint256 hash = tokenTx.GetHash();
bool fInsertedNew = true;
std::map<uint256, CTokenTx>::iterator it = mapTokenTx.find(hash);
if(it!=mapTokenTx.end())
{
fInsertedNew = false;
}
// Write to disk
CTokenTx wtokenTx = tokenTx;
if(!fInsertedNew)
{
wtokenTx.strLabel = it->second.strLabel;
}
const CBlockIndex *pIndex = ChainActive()[wtokenTx.blockNumber];
wtokenTx.nCreateTime = pIndex ? pIndex->GetBlockTime() : chain().getAdjustedTime();
if (!batch.WriteTokenTx(wtokenTx))
return false;
mapTokenTx[hash] = wtokenTx;
NotifyTokenTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
LogPrintf("AddTokenTxEntry %s\n", wtokenTx.GetHash().ToString());
return true;
}
CKeyPool::CKeyPool()
{
nTime = GetTime();
fInternal = false;
m_pre_split = false;
}
CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
{
nTime = GetTime();
vchPubKey = vchPubKeyIn;
fInternal = internalIn;
m_pre_split = false;
}
int CWalletTx::GetDepthInMainChain() const
{
assert(pwallet != nullptr);
#ifndef DEBUG_LOCKORDER
AssertLockHeld(pwallet->cs_wallet);
#endif
if (isUnconfirmed() || isAbandoned()) return 0;
return (pwallet->GetLastBlockHeight() - m_confirm.block_height + 1) * (isConflicted() ? -1 : 1);
}
int CWalletTx::GetBlocksToMaturity() const
{
if (!(IsCoinBase() || IsCoinStake()))
return 0;
int chain_depth = GetDepthInMainChain();
int nHeight = pwallet->GetLastBlockHeight() + 1;
int coinbaseMaturity = Params().GetConsensus().CoinbaseMaturity(nHeight);
return std::max(0, (coinbaseMaturity+1) - chain_depth);
}
bool CWalletTx::IsImmature() const
{
// note GetBlocksToMaturity is 0 for non-coinbase tx
return GetBlocksToMaturity() > 0;
}
bool CWalletTx::IsImmatureCoinBase() const
{
return IsCoinBase() && IsImmature();
}
bool CWalletTx::IsImmatureCoinStake() const
{
return IsCoinStake() && IsImmature();
}
std::vector<OutputGroup> CWallet::GroupOutputs(const std::vector<COutput>& outputs, bool single_coin) const {
std::vector<OutputGroup> groups;
std::map<CTxDestination, OutputGroup> gmap;
CTxDestination dst;
for (const auto& output : outputs) {
if (output.fSpendable) {
CInputCoin input_coin = output.GetInputCoin();
size_t ancestors, descendants;
chain().getTransactionAncestry(output.tx->GetHash(), ancestors, descendants);
if (!single_coin && ExtractDestination(output.tx->tx->vout[output.i].scriptPubKey, dst)) {
// Limit output groups to no more than 10 entries, to protect
// against inadvertently creating a too-large transaction
// when using -avoidpartialspends
if (gmap[dst].m_outputs.size() >= OUTPUT_GROUP_MAX_ENTRIES) {
groups.push_back(gmap[dst]);
gmap.erase(dst);
}
gmap[dst].Insert(input_coin, output.nDepth, output.tx->IsFromMe(ISMINE_ALL), ancestors, descendants);
} else {
groups.emplace_back(input_coin, output.nDepth, output.tx->IsFromMe(ISMINE_ALL), ancestors, descendants);
}
}
}
if (!single_coin) {
for (const auto& it : gmap) groups.push_back(it.second);
}
return groups;
}
bool CWallet::IsCrypted() const
{
return HasEncryptionKeys();
}
bool CWallet::IsLocked() const
{
if (!IsCrypted()) {
return false;
}
LOCK(cs_wallet);
return vMasterKey.empty();
}
bool CWallet::Lock()
{
if (!IsCrypted())
return false;
{
LOCK(cs_wallet);
vMasterKey.clear();
}
NotifyStatusChanged(this);
return true;
}
bool CWallet::Unlock(const CKeyingMaterial& vMasterKeyIn, bool accept_no_keys)
{
{
LOCK(cs_wallet);
for (const auto& spk_man_pair : m_spk_managers) {
if (!spk_man_pair.second->CheckDecryptionKey(vMasterKeyIn, accept_no_keys)) {
return false;
}
}
vMasterKey = vMasterKeyIn;
}
NotifyStatusChanged(this);
return true;
}
std::set<ScriptPubKeyMan*> CWallet::GetActiveScriptPubKeyMans() const
{
std::set<ScriptPubKeyMan*> spk_mans;
for (bool internal : {false, true}) {
for (OutputType t : OUTPUT_TYPES) {
auto spk_man = GetScriptPubKeyMan(t, internal);
if (spk_man) {
spk_mans.insert(spk_man);
}
}
}
return spk_mans;
}
std::set<ScriptPubKeyMan*> CWallet::GetAllScriptPubKeyMans() const
{
std::set<ScriptPubKeyMan*> spk_mans;
for (const auto& spk_man_pair : m_spk_managers) {
spk_mans.insert(spk_man_pair.second.get());
}
return spk_mans;
}
ScriptPubKeyMan* CWallet::GetScriptPubKeyMan(const OutputType& type, bool internal) const
{
const std::map<OutputType, ScriptPubKeyMan*>& spk_managers = internal ? m_internal_spk_managers : m_external_spk_managers;
std::map<OutputType, ScriptPubKeyMan*>::const_iterator it = spk_managers.find(type);
if (it == spk_managers.end()) {
WalletLogPrintf("%s scriptPubKey Manager for output type %d does not exist\n", internal ? "Internal" : "External", static_cast<int>(type));
return nullptr;
}
return it->second;
}
std::set<ScriptPubKeyMan*> CWallet::GetScriptPubKeyMans(const CScript& script, SignatureData& sigdata) const
{
std::set<ScriptPubKeyMan*> spk_mans;
for (const auto& spk_man_pair : m_spk_managers) {
if (spk_man_pair.second->CanProvide(script, sigdata)) {
spk_mans.insert(spk_man_pair.second.get());
}
}
return spk_mans;
}
ScriptPubKeyMan* CWallet::GetScriptPubKeyMan(const CScript& script) const
{
SignatureData sigdata;
for (const auto& spk_man_pair : m_spk_managers) {
if (spk_man_pair.second->CanProvide(script, sigdata)) {
return spk_man_pair.second.get();
}
}
return nullptr;
}
ScriptPubKeyMan* CWallet::GetScriptPubKeyMan(const uint256& id) const
{
if (m_spk_managers.count(id) > 0) {
return m_spk_managers.at(id).get();
}
return nullptr;
}
std::unique_ptr<SigningProvider> CWallet::GetSolvingProvider(const CScript& script) const
{
SignatureData sigdata;
return GetSolvingProvider(script, sigdata);
}
std::unique_ptr<SigningProvider> CWallet::GetSolvingProvider(const CScript& script, SignatureData& sigdata) const
{
for (const auto& spk_man_pair : m_spk_managers) {
if (spk_man_pair.second->CanProvide(script, sigdata)) {
return spk_man_pair.second->GetSolvingProvider(script);
}
}
return nullptr;
}
LegacyScriptPubKeyMan* CWallet::GetLegacyScriptPubKeyMan() const
{
// Legacy wallets only have one ScriptPubKeyMan which is a LegacyScriptPubKeyMan.
// Everything in m_internal_spk_managers and m_external_spk_managers point to the same legacyScriptPubKeyMan.
auto it = m_internal_spk_managers.find(OutputType::LEGACY);
if (it == m_internal_spk_managers.end()) return nullptr;
return dynamic_cast<LegacyScriptPubKeyMan*>(it->second);
}
LegacyScriptPubKeyMan* CWallet::GetOrCreateLegacyScriptPubKeyMan()
{
SetupLegacyScriptPubKeyMan();
return GetLegacyScriptPubKeyMan();
}
void CWallet::SetupLegacyScriptPubKeyMan()
{
if (!m_internal_spk_managers.empty() || !m_external_spk_managers.empty() || !m_spk_managers.empty()) {
return;
}
auto spk_manager = std::unique_ptr<ScriptPubKeyMan>(new LegacyScriptPubKeyMan(*this));
for (const auto& type : OUTPUT_TYPES) {
m_internal_spk_managers[type] = spk_manager.get();
m_external_spk_managers[type] = spk_manager.get();
}
m_spk_managers[spk_manager->GetID()] = std::move(spk_manager);
}
const CKeyingMaterial& CWallet::GetEncryptionKey() const
{
return vMasterKey;
}
bool CWallet::HasEncryptionKeys() const
{
return !mapMasterKeys.empty();
}
void CWallet::ConnectScriptPubKeyManNotifiers()
{
for (const auto& spk_man : GetActiveScriptPubKeyMans()) {
spk_man->NotifyWatchonlyChanged.connect(NotifyWatchonlyChanged);
spk_man->NotifyCanGetAddressesChanged.connect(NotifyCanGetAddressesChanged);
}
}
uint256 CTokenInfo::GetHash() const
{
return SerializeHash(*this, SER_GETHASH, 0);
}
uint256 CTokenTx::GetHash() const
{
return SerializeHash(*this, SER_GETHASH, 0);
}
uint256 CDelegationInfo::GetHash() const
{
return SerializeHash(*this, SER_GETHASH, 0);
}
uint256 CSuperStakerInfo::GetHash() const
{
return SerializeHash(*this, SER_GETHASH, 0);
}
bool CWallet::GetTokenTxDetails(const CTokenTx &wtx, uint256 &credit, uint256 &debit, std::string &tokenSymbol, uint8_t &decimals) const
{
LOCK(cs_wallet);
bool ret = false;
for(auto it = mapToken.begin(); it != mapToken.end(); it++)
{
CTokenInfo info = it->second;
if(wtx.strContractAddress == info.strContractAddress)
{
if(wtx.strSenderAddress == info.strSenderAddress)
{
debit = wtx.nValue;
tokenSymbol = info.strTokenSymbol;
decimals = info.nDecimals;
ret = true;
}
if(wtx.strReceiverAddress == info.strSenderAddress)
{
credit = wtx.nValue;
tokenSymbol = info.strTokenSymbol;
decimals = info.nDecimals;
ret = true;
}
}
}
return ret;
}
bool CWallet::IsTokenTxMine(const CTokenTx &wtx) const
{
LOCK(cs_wallet);
bool ret = false;
for(auto it = mapToken.begin(); it != mapToken.end(); it++)
{
CTokenInfo info = it->second;
if(wtx.strContractAddress == info.strContractAddress)
{
if(wtx.strSenderAddress == info.strSenderAddress ||
wtx.strReceiverAddress == info.strSenderAddress)
{
ret = true;
}
}
}
return ret;
}
bool CWallet::RemoveTokenEntry(const uint256 &tokenHash, bool fFlushOnClose)
{
LOCK(cs_wallet);
WalletBatch batch(*database, "r+", fFlushOnClose);
bool fFound = false;
std::map<uint256, CTokenInfo>::iterator it = mapToken.find(tokenHash);
if(it!=mapToken.end())
{
fFound = true;
}
if(fFound)
{
// Remove from disk
if (!batch.EraseToken(tokenHash))
return false;
mapToken.erase(it);
NotifyTokenChanged(this, tokenHash, CT_DELETED);
// Refresh token tx
for(auto it = mapTokenTx.begin(); it != mapTokenTx.end(); it++)
{
uint256 tokenTxHash = it->second.GetHash();
NotifyTokenTransactionChanged(this, tokenTxHash, CT_UPDATED);
}
}
LogPrintf("RemoveTokenEntry %s\n", tokenHash.ToString());
return true;
}
bool CWallet::CleanTokenTxEntries(bool fFlushOnClose)
{
LOCK(cs_wallet);
// Open db
WalletBatch batch(*database, "r+", fFlushOnClose);
// Get all token transaction hashes
std::vector<uint256> tokenTxHashes;
for(auto it = mapTokenTx.begin(); it != mapTokenTx.end(); it++)
{
tokenTxHashes.push_back(it->first);
}
// Remove existing entries
for(size_t i = 0; i < tokenTxHashes.size(); i++)
{
// Get the I entry
uint256 hashTxI = tokenTxHashes[i];
auto itTxI = mapTokenTx.find(hashTxI);
if(itTxI == mapTokenTx.end()) continue;
CTokenTx tokenTxI = itTxI->second;
for(size_t j = 0; j < tokenTxHashes.size(); j++)
{
// Skip the same entry
if(i == j) continue;
// Get the J entry
uint256 hashTxJ = tokenTxHashes[j];
auto itTxJ = mapTokenTx.find(hashTxJ);
if(itTxJ == mapTokenTx.end()) continue;
CTokenTx tokenTxJ = itTxJ->second;
// Compare I and J entries
if(tokenTxI.strContractAddress != tokenTxJ.strContractAddress) continue;
if(tokenTxI.strSenderAddress != tokenTxJ.strSenderAddress) continue;
if(tokenTxI.strReceiverAddress != tokenTxJ.strReceiverAddress) continue;
if(tokenTxI.blockHash != tokenTxJ.blockHash) continue;
if(tokenTxI.blockNumber != tokenTxJ.blockNumber) continue;
if(tokenTxI.transactionHash != tokenTxJ.transactionHash) continue;
// Delete the lower entry from disk
size_t nLower = uintTou256(tokenTxI.nValue) < uintTou256(tokenTxJ.nValue) ? i : j;
auto itTx = nLower == i ? itTxI : itTxJ;
uint256 hashTx = nLower == i ? hashTxI : hashTxJ;
if (!batch.EraseTokenTx(hashTx))
return false;
mapTokenTx.erase(itTx);
NotifyTokenTransactionChanged(this, hashTx, CT_DELETED);
break;
}
}
return true;
}
bool CWallet::SetContractBook(const std::string &strAddress, const std::string &strName, const std::string &strAbi)
{
bool fUpdated = false;
{
LOCK(cs_wallet); // mapContractBook
auto mi = mapContractBook.find(strAddress);
fUpdated = mi != mapContractBook.end();
mapContractBook[strAddress].name = strName;
mapContractBook[strAddress].abi = strAbi;
}
NotifyContractBookChanged(this, strAddress, strName, strAbi, (fUpdated ? CT_UPDATED : CT_NEW) );
WalletBatch batch(*database, "r+", true);
bool ret = batch.WriteContractData(strAddress, "name", strName);
ret &= batch.WriteContractData(strAddress, "abi", strAbi);
return ret;
}
bool CWallet::DelContractBook(const std::string &strAddress)
{
{
LOCK(cs_wallet); // mapContractBook
mapContractBook.erase(strAddress);
}
NotifyContractBookChanged(this, strAddress, "", "", CT_DELETED);
WalletBatch batch(*database, "r+", true);
bool ret = batch.EraseContractData(strAddress, "name");
ret &= batch.EraseContractData(strAddress, "abi");
return ret;
}
bool CWallet::LoadContractData(const std::string &address, const std::string &key, const std::string &value)
{
bool ret = true;
if(key == "name")
{
mapContractBook[address].name = value;
}
else if(key == "abi")
{
mapContractBook[address].abi = value;
}
else
{
ret = false;
}
return ret;
}
bool CWallet::LoadDelegation(const CDelegationInfo &delegation)
{
uint256 hash = delegation.GetHash();
mapDelegation[hash] = delegation;
return true;
}
bool CWallet::AddDelegationEntry(const CDelegationInfo& delegation, bool fFlushOnClose)
{
LOCK(cs_wallet);
WalletBatch batch(*database, "r+", fFlushOnClose);
uint256 hash = delegation.GetHash();
bool fInsertedNew = true;
std::map<uint256, CDelegationInfo>::iterator it = mapDelegation.find(hash);
if(it!=mapDelegation.end())
{
fInsertedNew = false;
}
// Write to disk
CDelegationInfo wdelegation = delegation;
if(!fInsertedNew)
{
wdelegation.nCreateTime = chain().getAdjustedTime();
}
else
{
wdelegation.nCreateTime = it->second.nCreateTime;
}
if (!batch.WriteDelegation(wdelegation))
return false;
mapDelegation[hash] = wdelegation;
NotifyDelegationChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
if(fInsertedNew)
{
LogPrintf("AddDelegationEntry %s\n", wdelegation.GetHash().ToString());
}
return true;
}
bool CWallet::RemoveDelegationEntry(const uint256& delegationHash, bool fFlushOnClose)
{
LOCK(cs_wallet);
WalletBatch batch(*database, "r+", fFlushOnClose);
bool fFound = false;
std::map<uint256, CDelegationInfo>::iterator it = mapDelegation.find(delegationHash);
if(it!=mapDelegation.end())
{
fFound = true;
}
if(fFound)
{
// Remove from disk
if (!batch.EraseDelegation(delegationHash))
return false;
mapDelegation.erase(it);
NotifyDelegationChanged(this, delegationHash, CT_DELETED);
}
LogPrintf("RemoveDelegationEntry %s\n", delegationHash.ToString());
return true;
}
bool CWallet::LoadSuperStaker(const CSuperStakerInfo &superStaker)
{
uint256 hash = superStaker.GetHash();
mapSuperStaker[hash] = superStaker;
return true;
}
bool CWallet::AddSuperStakerEntry(const CSuperStakerInfo& superStaker, bool fFlushOnClose)
{
LOCK(cs_wallet);
WalletBatch batch(*database, "r+", fFlushOnClose);
uint256 hash = superStaker.GetHash();
bool fInsertedNew = true;
std::map<uint256, CSuperStakerInfo>::iterator it = mapSuperStaker.find(hash);
if(it!=mapSuperStaker.end())
{
fInsertedNew = false;
}
// Write to disk
CSuperStakerInfo wsuperStaker = superStaker;
if(!fInsertedNew)
{
wsuperStaker.nCreateTime = chain().getAdjustedTime();
}
else
{
wsuperStaker.nCreateTime = it->second.nCreateTime;
}
if (!batch.WriteSuperStaker(wsuperStaker))
return false;
mapSuperStaker[hash] = wsuperStaker;
NotifySuperStakerChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
if(fInsertedNew)
{
LogPrintf("AddSuperStakerEntry %s\n", wsuperStaker.GetHash().ToString());
}
else
{
fUpdatedSuperStaker = true;
}
return true;
}
bool CWallet::RemoveSuperStakerEntry(const uint256& superStakerHash, bool fFlushOnClose)
{
LOCK(cs_wallet);
WalletBatch batch(*database, "r+", fFlushOnClose);
bool fFound = false;
std::map<uint256, CSuperStakerInfo>::iterator it = mapSuperStaker.find(superStakerHash);
if(it!=mapSuperStaker.end())
{
fFound = true;
}
if(fFound)
{
// Remove from disk
if (!batch.EraseSuperStaker(superStakerHash))
return false;
mapSuperStaker.erase(it);
NotifySuperStakerChanged(this, superStakerHash, CT_DELETED);
}
LogPrintf("RemoveSuperStakerEntry %s\n", superStakerHash.ToString());
return true;
}
void CWallet::StakeQteps(bool fStake, CConnman* connman)
{
::StakeQteps(fStake, this, connman, stakeThread);
}
void CWallet::StartStake(CConnman *connman)
{
if(IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS))
{
m_enabled_staking = !m_ledger_id.empty() && QtepLedger::instance().toolExists();
}
else
{
m_enabled_staking = true;
}
StakeQteps(true, connman);
}
void CWallet::StopStake()
{
if(!stakeThread)
{
if(m_enabled_staking)
m_enabled_staking = false;
}
else
{
m_stop_staking_thread = true;
m_enabled_staking = false;
StakeQteps(false, 0);
stakeThread = 0;
m_stop_staking_thread = false;
}
}
bool CWallet::IsStakeClosing()
{
return chain().shutdownRequested() || m_stop_staking_thread;
}
void CWallet::updateDelegationsStaker(const std::map<uint160, Delegation> &delegations_staker)
{
LOCK(cs_wallet);
// Notify for updated and deleted delegation items
for (std::map<uint160, Delegation>::iterator it=m_delegations_staker.begin(); it!=m_delegations_staker.end();)
{
uint160 addressDelegate = it->first;
std::map<uint160, Delegation>::const_iterator delegation = delegations_staker.find(addressDelegate);
if(delegation == delegations_staker.end())
{
it = m_delegations_staker.erase(it);
m_delegations_weight.erase(addressDelegate);
NotifyDelegationsStakerChanged(this, addressDelegate, CT_DELETED);
}
else
{
if(delegation->second != it->second)
{
it->second = delegation->second;
NotifyDelegationsStakerChanged(this, addressDelegate, CT_UPDATED);
}
it++;
}
}
// Notify for new delegation items
for (std::map<uint160, Delegation>::const_iterator it=delegations_staker.begin(); it!=delegations_staker.end(); it++)
{
if(m_delegations_staker.find(it->first) == m_delegations_staker.end())
{
m_delegations_staker[it->first] = it->second;
NotifyDelegationsStakerChanged(this, it->first, CT_NEW);
}
}
}
void CWallet::updateDelegationsWeight(const std::map<uint160, CAmount>& delegations_weight)
{
LOCK(cs_wallet);
for (std::map<uint160, CAmount>::const_iterator mi = delegations_weight.begin(); mi != delegations_weight.end(); mi++)
{
bool updated = true;
uint160 delegate = mi->first;
CAmount weight = mi->second;
std::map<uint160, CAmount>::iterator it = m_delegations_weight.find(delegate);
if(it != m_delegations_weight.end())
{
if(it->second == weight)
{
updated = false;
}
}
m_delegations_weight[delegate] = weight;
if(updated && m_delegations_staker.find(delegate) != m_delegations_staker.end())
{
NotifyDelegationsStakerChanged(this, delegate, CT_UPDATED);
}
}
for (std::map<uint256, CSuperStakerInfo>::iterator mi = mapSuperStaker.begin(); mi != mapSuperStaker.end(); mi++)
{
uint256 hash = mi->first;
NotifySuperStakerChanged(this, hash, CT_UPDATED);
}
}
uint64_t CWallet::GetSuperStakerWeight(const uint160 &staker) const
{
LOCK(cs_wallet);
uint64_t nWeight = 0;
auto iterator = m_have_coin_superstaker.find(staker);
if (iterator != m_have_coin_superstaker.end() && iterator->second)
{
for (std::map<uint160, Delegation>::const_iterator it=m_delegations_staker.begin(); it!=m_delegations_staker.end(); it++)
{
if(it->second.staker == staker)
{
uint160 delegate = it->first;
std::map<uint160, CAmount>::const_iterator mi = m_delegations_weight.find(delegate);
if(mi != m_delegations_weight.end())
{
nWeight += mi->second;
}
}
}
}
return nWeight;
}
bool CWallet::GetSuperStaker(CSuperStakerInfo &info, const uint160 &stakerAddress) const
{
LOCK(cs_wallet);
for (std::map<uint256, CSuperStakerInfo>::const_iterator it=mapSuperStaker.begin(); it!=mapSuperStaker.end(); it++)
{
if(it->second.stakerAddress == stakerAddress)
{
info = it->second;
return true;
}
}
return false;
}
void CWallet::GetStakerAddressBalance(interfaces::Chain::Lock &locked_chain, const PKHash &staker, CAmount &balance, CAmount &stake, CAmount& weight) const
{
AssertLockHeld(cs_main);
AssertLockHeld(cs_wallet);
balance = 0;
stake = 0;
weight = 0;
int nHeight = GetLastBlockHeight() + 1;
int coinbaseMaturity = Params().GetConsensus().CoinbaseMaturity(nHeight);
std::map<COutPoint, uint32_t> immatureStakes = locked_chain.getImmatureStakes();
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const uint256& wtxid = it->first;
const CWalletTx* pcoin = &(*it).second;
int nDepth = pcoin->GetDepthInMainChain();
if (nDepth < 1)
continue;
uint256 hashBlock = pcoin->m_confirm.hashBlock;
bool fHasProofOfDelegation = false;
CBlockIndex* blockIndex = LookupBlockIndex(hashBlock);
if(!blockIndex)
continue;
fHasProofOfDelegation = blockIndex->HasProofOfDelegation();
bool isImature = pcoin->GetBlocksToMaturity() == 0;
for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
{
bool OK = false;
PKHash keyId = ExtractPublicKeyHash(pcoin->tx->vout[i].scriptPubKey, &OK);
if(OK && keyId == staker)
{
isminetype mine = IsMine(pcoin->tx->vout[i]);
if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO &&
!IsLockedCoin((*it).first, i) && (pcoin->tx->vout[i].nValue > 0))
{
CAmount nValue = pcoin->tx->vout[i].nValue;
if(isImature)
{
balance += nValue;
if(nDepth >= coinbaseMaturity && nValue >= DEFAULT_STAKING_MIN_UTXO_VALUE)
{
COutPoint prevout = COutPoint(pcoin->tx->GetHash(), i);
if(immatureStakes.find(prevout) == immatureStakes.end())
{
weight += nValue;
}
}
}
else if(pcoin->IsCoinStake() && fHasProofOfDelegation)
{
stake += nValue;
}
}
}
}
}
}
void CWallet::updateHaveCoinSuperStaker(const std::set<std::pair<const CWalletTx *, unsigned int> > &setCoins)
{
LOCK(cs_wallet);
m_have_coin_superstaker.clear();
COutPoint prevout;
CAmount nValueRet = 0;
for (const auto& entry : mapSuperStaker) {
if(GetCoinSuperStaker(setCoins, PKHash(entry.second.stakerAddress), prevout, nValueRet))
{
m_have_coin_superstaker[entry.second.stakerAddress] = true;
}
}
}
void CWallet::UpdateMinerStakeCache(bool fStakeCache, const std::vector<COutPoint> &prevouts, CBlockIndex *pindexPrev )
{
if(minerStakeCache.size() > prevouts.size() + 100){
minerStakeCache.clear();
}
if(fStakeCache)
{
for(const COutPoint &prevoutStake : prevouts)
{
boost::this_thread::interruption_point();
CacheKernel(minerStakeCache, prevoutStake, pindexPrev, ::ChainstateActive().CoinsTip());
}
if(!fHasMinerStakeCache) fHasMinerStakeCache = true;
}
}
void CWallet::CleanCoinStake()
{
auto locked_chain = chain().lock();
LOCK(cs_wallet);
// Search the coinstake transactions and abandon transactions that are not confirmed in the blocks
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* wtx = &(*it).second;
if (wtx && wtx->m_confirm.hashBlock.IsNull() && wtx->m_confirm.nIndex <= 0)
{
// Wallets need to refund inputs when disconnecting coinstake
const CTransaction& tx = *(wtx->tx);
if (tx.IsCoinStake() && IsFromMe(tx) && !wtx->isAbandoned())
{
WalletLogPrintf("%s: Revert coinstake tx %s\n", __func__, wtx->GetHash().ToString());
DisableTransaction(tx);
}
}
}
}
void CWallet::AvailableCoinsForStaking(const std::vector<uint256>& maturedTx, size_t from, size_t to, const std::map<COutPoint, uint32_t>& immatureStakes, std::vector<std::pair<const CWalletTx *, unsigned int> >& vCoins, std::map<COutPoint, CScriptCache>* insertScriptCache) const
{
for(size_t i = from; i < to; i++)
{
std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(maturedTx[i]);
if(it == mapWallet.end()) continue;
const uint256& wtxid = it->first;
const CWalletTx* pcoin = &(*it).second;
for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
isminetype mine = IsMine(pcoin->tx->vout[i]);
if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO &&
!IsLockedCoin((*it).first, i) && (pcoin->tx->vout[i].nValue > 0) &&
// Check if the staking coin is dust
pcoin->tx->vout[i].nValue >= m_staker_min_utxo_size)
{
// Get the script data for the coin
COutPoint prevout = COutPoint(pcoin->GetHash(), i);
const CScriptCache& scriptCache = GetScriptCache(prevout, pcoin->tx->vout[i].scriptPubKey, insertScriptCache);
// Check that the script is not a contract script
if(scriptCache.contract || !scriptCache.keyIdOk)
continue;
// Check that the address is not delegated to other staker
if(m_my_delegations.find(scriptCache.keyId) != m_my_delegations.end())
continue;
// Check prevout maturity
if(immatureStakes.find(prevout) == immatureStakes.end())
{
// Check if script is spendable
bool spendable = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (((mine & ISMINE_WATCH_ONLY) != ISMINE_NO) && scriptCache.solvable);
if(spendable)
vCoins.push_back(std::make_pair(pcoin, i));
}
}
}
}
}
bool CWallet::SelectCoinsForStaking(interfaces::Chain::Lock &locked_chain, CAmount &nTargetValue, std::set<std::pair<const CWalletTx *, unsigned int> > &setCoinsRet, CAmount &nValueRet) const
{
std::vector<std::pair<const CWalletTx *, unsigned int> > vCoins;
vCoins.clear();
int nHeight = GetLastBlockHeight() + 1;
int coinbaseMaturity = Params().GetConsensus().CoinbaseMaturity(nHeight);
std::map<COutPoint, uint32_t> immatureStakes = locked_chain.getImmatureStakes();
std::vector<uint256> maturedTx;
const bool include_watch_only = GetLegacyScriptPubKeyMan() && IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
const isminetype is_mine_filter = include_watch_only ? ISMINE_WATCH_ONLY : ISMINE_SPENDABLE;
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
// Check the cached data for available coins for the tx
const CWalletTx* pcoin = &(*it).second;
const CAmount tx_credit_mine{pcoin->GetAvailableCredit(/* fUseCache */ true, is_mine_filter | ISMINE_NO)};
if(tx_credit_mine == 0)
continue;
const uint256& wtxid = it->first;
int nDepth = pcoin->GetDepthInMainChain();
if (nDepth < 1)
continue;
if (nDepth < coinbaseMaturity)
continue;
if (pcoin->GetBlocksToMaturity() > 0)
continue;
maturedTx.push_back(wtxid);
}
size_t listSize = maturedTx.size();
int numThreads = std::min(m_num_threads, (int)listSize);
if(numThreads < 2)
{
AvailableCoinsForStaking(maturedTx, 0, listSize, immatureStakes, vCoins, nullptr);
}
else
{
size_t chunk = listSize / numThreads;
for(int i = 0; i < numThreads; i++)
{
size_t from = i * chunk;
size_t to = i == (numThreads -1) ? listSize : from + chunk;
threads.create_thread([this, from, to, &maturedTx, &immatureStakes, &vCoins]{
std::vector<std::pair<const CWalletTx *, unsigned int> > tmpCoins;
std::map<COutPoint, CScriptCache> tmpInsertScriptCache;
AvailableCoinsForStaking(maturedTx, from, to, immatureStakes, tmpCoins, &tmpInsertScriptCache);
LOCK(cs_worker);
vCoins.insert(vCoins.end(), tmpCoins.begin(), tmpCoins.end());
if((int32_t)prevoutScriptCache.size() > m_staker_max_utxo_script_cache)
{
prevoutScriptCache.clear();
}
prevoutScriptCache.insert(tmpInsertScriptCache.begin(), tmpInsertScriptCache.end());
});
}
threads.join_all();
}
setCoinsRet.clear();
nValueRet = 0;
for(const std::pair<const CWalletTx*,unsigned int> &output : vCoins)
{
const CWalletTx *pcoin = output.first;
int i = output.second;
// Stop if we've chosen enough inputs
if (nValueRet >= nTargetValue)
break;
int64_t n = pcoin->tx->vout[i].nValue;
std::pair<int64_t,std::pair<const CWalletTx*,unsigned int> > coin = std::make_pair(n,std::make_pair(pcoin, i));
if (n >= nTargetValue)
{
// If input value is greater or equal to target then simply insert
// it into the current subset and exit
setCoinsRet.insert(coin.second);
nValueRet += coin.first;
break;
}
else if (n < nTargetValue + CENT)
{
setCoinsRet.insert(coin.second);
nValueRet += coin.first;
}
}
return true;
}
bool CWallet::AvailableDelegateCoinsForStaking(const std::vector<uint160>& delegations, size_t from, size_t to, int32_t height, const std::map<COutPoint, uint32_t>& immatureStakes, const std::map<uint256, CSuperStakerInfo>& mapStakers, std::vector<std::pair<COutPoint,CAmount>>& vUnsortedDelegateCoins, std::map<uint160, CAmount> &mDelegateWeight) const
{
for(size_t i = from; i < to; i++)
{
std::map<uint160, Delegation>::const_iterator it = m_delegations_staker.find(delegations[i]);
if(it == m_delegations_staker.end()) continue;
const PKHash& keyid = PKHash(it->first);
const Delegation* delegation = &(*it).second;
// Set default delegate stake weight
CAmount weight = 0;
mDelegateWeight[it->first] = weight;
// Get super staker custom configuration
CAmount staking_min_utxo_value = m_staking_min_utxo_value;
uint8_t staking_min_fee = m_staking_min_fee;
for (std::map<uint256, CSuperStakerInfo>::const_iterator it=mapStakers.begin(); it!=mapStakers.end(); it++)
{
if(it->second.stakerAddress == delegation->staker)
{
CSuperStakerInfo info = it->second;
if(info.fCustomConfig)
{
staking_min_utxo_value = info.nMinDelegateUtxo;
staking_min_fee = info.nMinFee;
}
}
}
// Check for min staking fee
if(delegation->fee < staking_min_fee)
continue;
// Decode address
uint256 hashBytes;
int type = 0;
if (!DecodeIndexKey(EncodeDestination(keyid), hashBytes, type)) {
return error("Invalid address");
}
// Get address utxos
std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > unspentOutputs;
if (!GetAddressUnspent(hashBytes, type, unspentOutputs)) {
throw error("No information available for address");
}
// Add the utxos to the list if they are mature and at least the minimum value
int coinbaseMaturity = Params().GetConsensus().CoinbaseMaturity(height + 1);
for (std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> >::const_iterator i=unspentOutputs.begin(); i!=unspentOutputs.end(); i++) {
int nDepth = height - i->second.blockHeight + 1;
if (nDepth < coinbaseMaturity)
continue;
if(i->second.satoshis < staking_min_utxo_value)
continue;
COutPoint prevout = COutPoint(i->first.txhash, i->first.index);
if(immatureStakes.find(prevout) == immatureStakes.end())
{
vUnsortedDelegateCoins.push_back(std::make_pair(prevout, i->second.satoshis));
weight+= i->second.satoshis;
}
}
// Update delegate stake weight
mDelegateWeight[it->first] = weight;
}
return true;
}
bool CWallet::SelectDelegateCoinsForStaking(interfaces::Chain::Lock &locked_chain, std::vector<COutPoint> &setDelegateCoinsRet, std::map<uint160, CAmount> &mDelegateWeight) const
{
AssertLockHeld(cs_main);
AssertLockHeld(cs_wallet);
setDelegateCoinsRet.clear();
std::vector<std::pair<COutPoint,CAmount>> vUnsortedDelegateCoins;
int32_t const height = locked_chain.getHeight().get_value_or(-1);
if (height == -1) {
return error("Invalid blockchain height");
}
std::map<COutPoint, uint32_t> immatureStakes = locked_chain.getImmatureStakes();
std::map<uint256, CSuperStakerInfo> mapStakers = mapSuperStaker;
std::vector<uint160> delegations;
for (std::map<uint160, Delegation>::const_iterator it = m_delegations_staker.begin(); it != m_delegations_staker.end(); ++it)
{
delegations.push_back(it->first);
}
size_t listSize = delegations.size();
int numThreads = std::min(m_num_threads, (int)listSize);
bool ret = true;
if(numThreads < 2)
{
ret = AvailableDelegateCoinsForStaking(delegations, 0, listSize, height, immatureStakes, mapStakers, vUnsortedDelegateCoins, mDelegateWeight);
}
else
{
size_t chunk = listSize / numThreads;
for(int i = 0; i < numThreads; i++)
{
size_t from = i * chunk;
size_t to = i == (numThreads -1) ? listSize : from + chunk;
threads.create_thread([this, from, to, height, &delegations, &immatureStakes, &mapStakers, &ret, &vUnsortedDelegateCoins, &mDelegateWeight]{
std::vector<std::pair<COutPoint,CAmount>> tmpUnsortedDelegateCoins;
std::map<uint160, CAmount> tmpDelegateWeight;
bool tmpRet = AvailableDelegateCoinsForStaking(delegations, from, to, height, immatureStakes, mapStakers, tmpUnsortedDelegateCoins, tmpDelegateWeight);
LOCK(cs_worker);
ret &= tmpRet;
vUnsortedDelegateCoins.insert(vUnsortedDelegateCoins.end(), tmpUnsortedDelegateCoins.begin(), tmpUnsortedDelegateCoins.end());
mDelegateWeight.insert(tmpDelegateWeight.begin(), tmpDelegateWeight.end());
});
}
threads.join_all();
}
std::sort(vUnsortedDelegateCoins.begin(), vUnsortedDelegateCoins.end(), valueUtxoSort);
for(auto utxo : vUnsortedDelegateCoins){
setDelegateCoinsRet.push_back(utxo.first);
}
vUnsortedDelegateCoins.clear();
return ret;
}
void CWallet::AvailableAddress(const std::vector<uint256> &maturedTx, size_t from, size_t to, std::map<uint160, bool> &mapAddress, std::map<COutPoint, CScriptCache> *insertScriptCache) const
{
for(size_t i = from; i < to; i++)
{
std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(maturedTx[i]);
if(it == mapWallet.end()) continue;
const uint256& wtxid = it->first;
const CWalletTx* pcoin = &(*it).second;
for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
isminetype mine = IsMine(pcoin->tx->vout[i]);
if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO &&
!IsLockedCoin((*it).first, i) && (pcoin->tx->vout[i].nValue > 0) &&
// Check if the staking coin is dust
pcoin->tx->vout[i].nValue >= m_staker_min_utxo_size)
{
// Get the script data for the coin
COutPoint prevout = COutPoint(pcoin->GetHash(), i);
const CScriptCache& scriptCache = GetScriptCache(prevout, pcoin->tx->vout[i].scriptPubKey, insertScriptCache);
// Check that the script is not a contract script
if(scriptCache.contract || !scriptCache.keyIdOk)
continue;
bool spendable = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (((mine & ISMINE_WATCH_ONLY) != ISMINE_NO) && scriptCache.solvable);
if(spendable)
{
if(mapAddress.find(scriptCache.keyId) == mapAddress.end())
{
mapAddress[scriptCache.keyId] = true;
}
}
}
}
}
}
void CWallet::SelectAddress(interfaces::Chain::Lock &locked_chain, std::map<uint160, bool> &mapAddress) const
{
std::vector<uint256> maturedTx;
const bool include_watch_only = GetLegacyScriptPubKeyMan() && IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
const isminetype is_mine_filter = include_watch_only ? ISMINE_WATCH_ONLY : ISMINE_SPENDABLE;
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
// Check the cached data for available coins for the tx
const CWalletTx* pcoin = &(*it).second;
const CAmount tx_credit_mine{pcoin->GetAvailableCredit(/* fUseCache */ true, is_mine_filter | ISMINE_NO)};
if(tx_credit_mine == 0)
continue;
const uint256& wtxid = it->first;
int nDepth = pcoin->GetDepthInMainChain();
if (nDepth < 1)
continue;
if (pcoin->GetBlocksToMaturity() > 0)
continue;
maturedTx.push_back(wtxid);
}
size_t listSize = maturedTx.size();
int numThreads = std::min(m_num_threads, (int)listSize);
if(numThreads < 2)
{
AvailableAddress(maturedTx, 0, listSize, mapAddress, nullptr);
}
else
{
size_t chunk = listSize / numThreads;
for(int i = 0; i < numThreads; i++)
{
size_t from = i * chunk;
size_t to = i == (numThreads -1) ? listSize : from + chunk;
threads.create_thread([this, from, to, &maturedTx, &mapAddress]{
std::map<uint160, bool> tmpAddresses;
std::map<COutPoint, CScriptCache> tmpInsertScriptCache;
AvailableAddress(maturedTx, from, to, tmpAddresses, &tmpInsertScriptCache);
LOCK(cs_worker);
mapAddress.insert(tmpAddresses.begin(), tmpAddresses.end());
if((int32_t)prevoutScriptCache.size() > m_staker_max_utxo_script_cache)
{
prevoutScriptCache.clear();
}
prevoutScriptCache.insert(tmpInsertScriptCache.begin(), tmpInsertScriptCache.end());
});
}
threads.join_all();
}
}
bool CWallet::GetSenderDest(const CTransaction &tx, CTxDestination &txSenderDest, bool sign) const
{
// Initialize variables
CScript senderPubKey;
// Get sender destination
if(tx.HasOpSender())
{
// Get destination from the outputs
for(CTxOut out : tx.vout)
{
if(out.scriptPubKey.HasOpSender())
{
if(sign)
{
ExtractSenderData(out.scriptPubKey, &senderPubKey, 0);
}
else
{
GetSenderPubKey(out.scriptPubKey, senderPubKey);
}
break;
}
}
}
else
{
// Get destination from the inputs
if(tx.vin.size() > 0 && mapWallet.find(tx.vin[0].prevout.hash) != mapWallet.end())
{
senderPubKey = mapWallet.at(tx.vin[0].prevout.hash).tx->vout[tx.vin[0].prevout.n].scriptPubKey;
}
}
// Extract destination from script
return ExtractDestination(senderPubKey, txSenderDest);
}
bool CWallet::GetHDKeyPath(const CTxDestination &dest, std::string &hdkeypath) const
{
CScript scriptPubKey = GetScriptForDestination(dest);
ScriptPubKeyMan* spk_man = GetScriptPubKeyMan(scriptPubKey);
if (spk_man) {
if (const CKeyMetadata* meta = spk_man->GetMetadata(dest)) {
if (meta->has_key_origin) {
hdkeypath = WriteHDKeypath(meta->key_origin.path);
return true;
}
}
}
return false;
}
bool CWallet::GetKernelKey(const CKeyID &pubKeyHash, const FillableSigningProvider &keystore, bool canSign, CPubKey &pubKeyKernel, CKey &keyKernel) const
{
bool found = false;
if(canSign)
{
found = keystore.GetKey(pubKeyHash, keyKernel);
if(found)
{
pubKeyKernel = keyKernel.GetPubKey();
}
}
else
{
found = keystore.GetPubKey(pubKeyHash, pubKeyKernel);
}
return found;
}
|
/*
* Copyright 2010-2016 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/glacier/model/InventoryRetrievalJobDescription.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Glacier
{
namespace Model
{
InventoryRetrievalJobDescription::InventoryRetrievalJobDescription() :
m_formatHasBeenSet(false),
m_startDateHasBeenSet(false),
m_endDateHasBeenSet(false),
m_limitHasBeenSet(false),
m_markerHasBeenSet(false)
{
}
InventoryRetrievalJobDescription::InventoryRetrievalJobDescription(const JsonValue& jsonValue) :
m_formatHasBeenSet(false),
m_startDateHasBeenSet(false),
m_endDateHasBeenSet(false),
m_limitHasBeenSet(false),
m_markerHasBeenSet(false)
{
*this = jsonValue;
}
InventoryRetrievalJobDescription& InventoryRetrievalJobDescription::operator =(const JsonValue& jsonValue)
{
if(jsonValue.ValueExists("Format"))
{
m_format = jsonValue.GetString("Format");
m_formatHasBeenSet = true;
}
if(jsonValue.ValueExists("StartDate"))
{
m_startDate = jsonValue.GetString("StartDate");
m_startDateHasBeenSet = true;
}
if(jsonValue.ValueExists("EndDate"))
{
m_endDate = jsonValue.GetString("EndDate");
m_endDateHasBeenSet = true;
}
if(jsonValue.ValueExists("Limit"))
{
m_limit = jsonValue.GetString("Limit");
m_limitHasBeenSet = true;
}
if(jsonValue.ValueExists("Marker"))
{
m_marker = jsonValue.GetString("Marker");
m_markerHasBeenSet = true;
}
return *this;
}
JsonValue InventoryRetrievalJobDescription::Jsonize() const
{
JsonValue payload;
if(m_formatHasBeenSet)
{
payload.WithString("Format", m_format);
}
if(m_startDateHasBeenSet)
{
payload.WithString("StartDate", m_startDate);
}
if(m_endDateHasBeenSet)
{
payload.WithString("EndDate", m_endDate);
}
if(m_limitHasBeenSet)
{
payload.WithString("Limit", m_limit);
}
if(m_markerHasBeenSet)
{
payload.WithString("Marker", m_marker);
}
return payload;
}
} // namespace Model
} // namespace Glacier
} // namespace Aws
|
/******************************************************************************
* Copyright 2017 The Apollo 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 "modules/perception/traffic_light/onboard/tl_proc_subnode.h"
#include <algorithm>
#include "modules/common/adapters/adapter_manager.h"
#include "modules/perception/common/perception_gflags.h"
#include "modules/perception/lib/base/timer.h"
#include "modules/perception/onboard/subnode_helper.h"
#include "modules/perception/traffic_light/base/tl_shared_data.h"
#include "modules/perception/traffic_light/base/utils.h"
#include "modules/perception/traffic_light/recognizer/unity_recognize.h"
#include "modules/perception/traffic_light/rectify/cropbox.h"
#include "modules/perception/traffic_light/rectify/unity_rectify.h"
#include "modules/perception/traffic_light/reviser/color_decision.h"
DEFINE_string(traffic_light_rectifier, "",
"the rectifier enabled for traffic_light");
DEFINE_string(traffic_light_recognizer, "",
"the recognizer enabled for traffic_light");
DEFINE_string(traffic_light_reviser, "",
"the reviser enabled for traffic_light");
namespace apollo {
namespace perception {
namespace traffic_light {
using apollo::common::ErrorCode;
using apollo::common::Status;
TLProcSubnode::~TLProcSubnode() { preprocessing_data_ = nullptr; }
bool TLProcSubnode::InitInternal() {
RegisterFactoryUnityRectify();
RegisterFactoryUnityRecognize();
RegisterFactoryColorReviser();
if (!InitSharedData()) {
AERROR << "TLProcSubnode init shared data failed.";
return false;
}
if (!InitRectifier()) {
AERROR << "TLProcSubnode init rectifier failed.";
return false;
}
if (!InitRecognizer()) {
AERROR << "TLProcSubnode init recognizer failed.";
return false;
}
if (!InitReviser()) {
AERROR << "TLProcSubnode init reviser failed.";
return false;
}
// init image_border
ConfigManager *config_manager = ConfigManager::instance();
std::string model_name("TLProcSubnode");
const ModelConfig *model_config(nullptr);
if (!config_manager->GetModelConfig(model_name, &model_config)) {
AERROR << "TLProcSubnode not found model: " << model_name;
return false;
}
if (!model_config->GetValue("image_border", &image_border_)) {
AERROR << "TLProcSubnode Failed to find Conf: "
<< "image_border.";
return false;
}
if (!model_config->GetValue("valid_ts_interval", &valid_ts_interval_)) {
AERROR << "TLProcSubnode Failed to find Conf: "
<< "valid_ts_interval.";
return false;
}
AINFO << "TLProcSubnode init successfully. ";
return true;
}
bool TLProcSubnode::ProcEvent(const Event &event) {
const double proc_subnode_handle_event_start_ts = TimeUtil::GetCurrentTime();
PERF_FUNCTION();
// get up-stream data
const double timestamp = event.timestamp;
const std::string device_id = event.reserve;
AINFO << "Detect Start ts:" << GLOG_TIMESTAMP(timestamp);
std::string key;
if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id, &key)) {
AERROR << "TLProcSubnode produce_shared_data_key failed."
<< " ts:" << timestamp << " device_id:" << device_id;
return false;
}
SharedDataPtr<ImageLights> image_lights;
if (!preprocessing_data_->Get(key, &image_lights)) {
AERROR << "TLProcSubnode failed to get shared data,"
<< " name:" << preprocessing_data_->name()
<< ", time: " << GLOG_TIMESTAMP(timestamp);
return false;
}
AINFO << "TLProcSubnode get shared data ok,ts: " << GLOG_TIMESTAMP(timestamp);
// preprocess send a msg -> proc receive a msg
double enter_proc_latency = (proc_subnode_handle_event_start_ts -
image_lights->preprocess_send_timestamp);
if (TimeUtil::GetCurrentTime() - event.local_timestamp > valid_ts_interval_) {
AERROR << "TLProcSubnode failed to process image"
<< "Because images are too old"
<< ",current time: " << GLOG_TIMESTAMP(TimeUtil::GetCurrentTime())
<< ", event time: " << GLOG_TIMESTAMP(event.local_timestamp);
return false;
}
// verify image_lights from cameras
RectifyOption rectify_option;
if (!VerifyImageLights(*image_lights, &rectify_option.camera_id)) {
AERROR << "TLProcSubnode invalid image_lights ";
return false;
}
if (!image_lights->image->GenerateMat()) {
AERROR << "TLProcSubnode failed to generate mat";
return false;
}
// using rectifier to rectify the region.
const double before_rectify_ts = TimeUtil::GetCurrentTime();
if (!rectifier_->Rectify(*(image_lights->image), rectify_option,
(image_lights->lights).get())) {
AERROR << "TLProcSubnode failed to rectify the regions "
<< "ts:" << GLOG_TIMESTAMP(timestamp)
<< " Image:" << *(image_lights->image);
return false;
}
const double detection_latency =
TimeUtil::GetCurrentTime() - before_rectify_ts;
// update image_border
MutexLock lock(&mutex_);
// int cam_id = static_cast<int>(image_lights->camera_id);
ComputeImageBorder(*image_lights,
&image_border_size[image_lights->camera_id]);
AINFO << "TLProcSubnode update image_border size: "
<< image_border_size[image_lights->camera_id]
<< " ts: " << GLOG_TIMESTAMP(timestamp)
<< " CameraId: " << image_lights->camera_id;
image_lights->offset = image_border_size[image_lights->camera_id];
// recognize_status
const double before_recognization_ts = TimeUtil::GetCurrentTime();
if (!recognizer_->RecognizeStatus(*(image_lights->image), RecognizeOption(),
(image_lights->lights).get())) {
AERROR << "TLProcSubnode failed to recognize lights,"
<< " ts:" << GLOG_TIMESTAMP(timestamp)
<< " image:" << image_lights->image;
return false;
}
const double recognization_latency =
TimeUtil::GetCurrentTime() - before_recognization_ts;
// revise status
const double before_revise_ts = TimeUtil::GetCurrentTime();
if (!reviser_->Revise(ReviseOption(event.timestamp),
image_lights->lights.get())) {
AERROR << "TLReviserSubnode revise data failed. "
<< "sub_event:" << event.to_string();
return false;
}
const double revise_latency = TimeUtil::GetCurrentTime() - before_revise_ts;
PublishMessage(image_lights);
AINFO << "TLProcSubnode process traffic_light, "
<< " msg_ts: " << GLOG_TIMESTAMP(timestamp)
<< " from device_id: " << device_id << " get "
<< image_lights->lights->size() << " lights."
<< " detection_latency: " << detection_latency * 1000 << " ms."
<< " recognization_latency: " << recognization_latency * 1000 << " ms."
<< " revise_latency: " << revise_latency * 1000 << " ms."
<< " TLProcSubnode::handle_event latency: "
<< (TimeUtil::GetCurrentTime() - proc_subnode_handle_event_start_ts) *
1000
<< " ms."
<< " enter_proc_latency: " << enter_proc_latency * 1000 << " ms."
<< " preprocess_latency: "
<< (image_lights->preprocess_send_timestamp -
image_lights->preprocess_receive_timestamp) *
1000
<< " ms.";
return true;
}
bool TLProcSubnode::InitSharedData() {
CHECK_NOTNULL(shared_data_manager_);
const std::string preprocessing_data_name("TLPreprocessingData");
preprocessing_data_ = dynamic_cast<TLPreprocessingData *>(
shared_data_manager_->GetSharedData(preprocessing_data_name));
if (preprocessing_data_ == nullptr) {
AERROR << "TLProcSubnode failed to get shared data instance: "
<< preprocessing_data_name;
return false;
}
AINFO << "Init shared data successfully, "
<< "preprocessing_data: " << preprocessing_data_->name();
return true;
}
bool TLProcSubnode::InitRectifier() {
rectifier_.reset(BaseRectifierRegisterer::GetInstanceByName(
FLAGS_traffic_light_rectifier));
if (!rectifier_) {
AERROR << "TLProcSubnode new rectifier failed. rectifier name:"
<< FLAGS_traffic_light_rectifier << " failed.";
return false;
}
if (!rectifier_->Init()) {
AERROR << "TLProcSubnode init rectifier failed. rectifier name:"
<< FLAGS_traffic_light_rectifier << " failed.";
return false;
}
return true;
}
bool TLProcSubnode::InitRecognizer() {
recognizer_.reset(BaseRecognizerRegisterer::GetInstanceByName(
FLAGS_traffic_light_recognizer));
if (!recognizer_) {
AERROR << "TLProcSubnode new recognizer failed. name:"
<< FLAGS_traffic_light_recognizer;
return false;
}
if (!recognizer_->Init()) {
AERROR << "TLProcSubnode init recognizer failed.";
return false;
}
return true;
}
bool TLProcSubnode::InitReviser() {
reviser_.reset(
BaseReviserRegisterer::GetInstanceByName(FLAGS_traffic_light_reviser));
if (reviser_ == nullptr) {
AERROR << "TLProcSubnode new reviser failed. name:"
<< FLAGS_traffic_light_reviser;
return false;
}
if (!reviser_->Init()) {
AERROR << "TLProcSubnode init reviser failed. name:"
<< FLAGS_traffic_light_reviser;
return false;
}
return true;
}
double TLProcSubnode::GetMeanDistance(const double ts,
const Eigen::Matrix4d &car_pose,
const LightPtrs &lights) const {
if (lights.empty()) {
AWARN << "get_mean_distance failed. lights is empty, "
<< "while it should not be. ts:" << GLOG_TIMESTAMP(ts);
return DBL_MAX;
}
double distance = 0.0;
for (const LightPtr &light : lights) {
auto light_distance = Distance2Stopline(car_pose, light->info.stop_line());
if (light_distance < 0) {
AWARN << "get_mean_distance failed. lights stop line data is illegal, "
<< "ts:" << GLOG_TIMESTAMP(ts);
return DBL_MAX;
}
distance += light_distance;
}
return distance / lights.size();
}
bool TLProcSubnode::VerifyImageLights(const ImageLights &image_lights,
CameraId *selection) const {
if (!image_lights.image || !image_lights.image->contain_image()) {
AERROR << "TLProcSubnode image_lights has no image, "
<< "verify_image_lights failed.";
return false;
}
const int cam_id = static_cast<int>(image_lights.camera_id);
if (cam_id < 0 || cam_id >= kCountCameraId) {
AERROR << "TLProcSubnode image_lights unknown camera id: " << cam_id
<< " verify_image_lights failed.";
return false;
}
for (LightPtr light : *(image_lights.lights)) {
if (!BoxIsValid(light->region.projection_roi, image_lights.image->size())) {
ClearBox(&(light->region.projection_roi));
continue;
}
}
*selection = image_lights.camera_id;
return true;
}
bool TLProcSubnode::ComputeImageBorder(const ImageLights &image_lights,
int *image_border) {
if (!image_lights.image) {
AERROR << "TLProcSubnode image_lights has no image, "
<< "compute_image_border failed.";
return false;
}
auto camera_id = static_cast<int>(image_lights.camera_id);
if (camera_id < 0 || camera_id >= kCountCameraId) {
AERROR << "TLProcSubnode image_lights unknown camera selection, "
<< "compute_image_border failed, "
<< "camera_id: " << kCameraIdToStr.at(image_lights.camera_id);
return false;
}
// check lights info
if (image_lights.lights->empty()) {
AINFO << "TLProcSubnode image_lights no lights info, "
<< "no need to update image border, reset image border size to 100";
*image_border = 100;
return true;
}
LightPtrs &lights_ref = *(image_lights.lights.get());
int max_offset = -1;
for (size_t i = 0; i < lights_ref.size(); ++i) {
if (lights_ref[i]->region.is_detected) {
cv::Rect rectified_roi = lights_ref[i]->region.rectified_roi;
cv::Rect projection_roi = lights_ref[i]->region.projection_roi;
// pick up traffic light with biggest offset
int offset = 0;
ComputeRectsOffset(projection_roi, rectified_roi, &offset);
max_offset = std::max(max_offset, offset);
}
}
if (max_offset != -1) {
*image_border = max_offset;
}
return true;
}
void TLProcSubnode::ComputeRectsOffset(const cv::Rect &rect1,
const cv::Rect &rect2, int *offset) {
cv::Point center1(rect1.x + rect1.width / 2, rect1.y + rect1.height / 2);
cv::Point center2(rect2.x + rect2.width / 2, rect2.y + rect2.height / 2);
cv::Point pt1;
cv::Point pt2;
// record the max lateral and longitudinal offset
if (center2.y <= center1.y) {
if (center2.x >= center1.x) {
pt1 = cv::Point(rect1.x + rect1.width, rect1.y);
pt2 = cv::Point(rect2.x + rect2.width, rect2.y);
} else {
pt1 = cv::Point(rect1.x, rect1.y);
pt2 = cv::Point(rect2.x, rect2.y);
}
} else {
if (center2.x >= center1.x) {
pt1 = cv::Point(rect1.x + rect1.width, rect1.y + rect1.height);
pt2 = cv::Point(rect2.x + rect2.width, rect2.y + rect2.height);
} else {
pt1 = cv::Point(rect1.x, rect1.y + rect1.height);
pt2 = cv::Point(rect2.x, rect2.y + rect2.height);
}
}
*offset = std::max(abs(pt1.x - pt2.x), abs(pt1.y - pt2.y));
}
bool TLProcSubnode::PublishMessage(
const std::shared_ptr<ImageLights> &image_lights) {
Timer timer;
timer.Start();
const auto &lights = image_lights->lights;
cv::Mat img = image_lights->image->mat();
TrafficLightDetection result;
common::Header *header = result.mutable_header();
header->set_timestamp_sec(ros::Time::now().toSec());
header->set_sequence_num(seq_num_++);
uint64_t timestamp = static_cast<uint64_t>(image_lights->image->ts()*1e9);
header->set_camera_timestamp(timestamp);
// add traffic light result
for (size_t i = 0; i < lights->size(); i++) {
TrafficLight *light_result = result.add_traffic_light();
light_result->set_id(lights->at(i)->info.id().id());
light_result->set_confidence(lights->at(i)->status.confidence);
light_result->set_color(lights->at(i)->status.color);
}
// set contain_lights
result.set_contain_lights(image_lights->num_signals > 0);
// add traffic light debug info
TrafficLightDebug *light_debug = result.mutable_traffic_light_debug();
// set signal number
AINFO << "TLOutputSubnode num_signals: " << image_lights->num_signals
<< ", camera_id: " << kCameraIdToStr.at(image_lights->camera_id)
<< ", is_pose_valid: " << image_lights->is_pose_valid
<< ", ts: " << GLOG_TIMESTAMP(image_lights->timestamp);
light_debug->set_signal_num(image_lights->num_signals);
// Crop ROI
if (lights->size() > 0 && lights->at(0)->region.debug_roi.size() > 0) {
auto &crop_roi = lights->at(0)->region.debug_roi[0];
auto tl_cropbox = light_debug->mutable_cropbox();
tl_cropbox->set_x(crop_roi.x);
tl_cropbox->set_y(crop_roi.y);
tl_cropbox->set_width(crop_roi.width);
tl_cropbox->set_height(crop_roi.height);
}
// Rectified ROI
for (size_t i = 0; i < lights->size(); ++i) {
auto &rectified_roi = lights->at(i)->region.rectified_roi;
auto tl_rectified_box = light_debug->add_box();
tl_rectified_box->set_x(rectified_roi.x);
tl_rectified_box->set_y(rectified_roi.y);
tl_rectified_box->set_width(rectified_roi.width);
tl_rectified_box->set_height(rectified_roi.height);
tl_rectified_box->set_color(lights->at(i)->status.color);
tl_rectified_box->set_selected(true);
}
// Projection ROI
for (size_t i = 0; i < lights->size(); ++i) {
auto &projection_roi = lights->at(i)->region.projection_roi;
auto tl_projection_box = light_debug->add_box();
tl_projection_box->set_x(projection_roi.x);
tl_projection_box->set_y(projection_roi.y);
tl_projection_box->set_width(projection_roi.width);
tl_projection_box->set_height(projection_roi.height);
}
// debug ROI (candidate detection boxes)
if (lights->size() > 0 && lights->at(0)->region.debug_roi.size() > 0) {
for (size_t i = 1; i < lights->at(0)->region.debug_roi.size(); ++i) {
auto &debug_roi = lights->at(0)->region.debug_roi[i];
auto tl_debug_box = light_debug->add_box();
tl_debug_box->set_x(debug_roi.x);
tl_debug_box->set_y(debug_roi.y);
tl_debug_box->set_width(debug_roi.width);
tl_debug_box->set_height(debug_roi.height);
}
}
light_debug->set_ts_diff_pos(image_lights->diff_image_pose_ts);
light_debug->set_ts_diff_sys(image_lights->diff_image_sys_ts);
light_debug->set_valid_pos(image_lights->is_pose_valid);
light_debug->set_project_error(image_lights->offset);
light_debug->set_camera_id(image_lights->camera_id);
if (lights->size() > 0) {
double distance = Distance2Stopline(image_lights->pose.pose(),
lights->at(0)->info.stop_line());
light_debug->set_distance_to_stop_line(distance);
}
if (FLAGS_output_debug_img) {
char filename[200];
snprintf(filename, sizeof(filename), "img/%lf_%s.jpg",
image_lights->image->ts(),
image_lights->image->camera_id_str().c_str());
for (size_t i = 0; i < lights->size(); i++) {
cv::Rect rect = lights->at(i)->region.rectified_roi;
cv::Scalar color;
switch (lights->at(i)->status.color) {
case BLACK:
color = cv::Scalar(0, 0, 0);
break;
case GREEN:
color = cv::Scalar(0, 255, 0);
break;
case RED:
color = cv::Scalar(0, 0, 255);
break;
case YELLOW:
color = cv::Scalar(0, 255, 255);
break;
default:
color = cv::Scalar(0, 76, 153);
}
cv::rectangle(img, rect, color, 2);
cv::rectangle(img, lights->at(i)->region.projection_roi,
cv::Scalar(255, 255, 0), 2);
auto &crop_roi = lights->at(0)->region.debug_roi[0];
cv::rectangle(img, crop_roi, cv::Scalar(0, 255, 255), 2);
}
// draw camera timestamp
int pos_y = 40;
std::string ts_text = cv::format("img ts=%lf", image_lights->timestamp);
cv::putText(img, ts_text, cv::Point(30, pos_y), cv::FONT_HERSHEY_PLAIN, 3.0,
CV_RGB(128, 255, 0), 2);
// draw distance to stopline
pos_y += 50;
double distance = light_debug->distance_to_stop_line();
if (lights->size() > 0) {
std::string dis2sl_text = cv::format("dis2sl=%lf", distance);
cv::putText(img, dis2sl_text, cv::Point(30, pos_y),
cv::FONT_HERSHEY_PLAIN, 3.0, CV_RGB(128, 255, 0), 2);
}
// draw "Signals Num"
pos_y += 50;
if (light_debug->valid_pos()) {
std::string signal_txt = "Signals Num: " + std::to_string(lights->size());
cv::putText(img, signal_txt, cv::Point(30, pos_y), cv::FONT_HERSHEY_PLAIN,
3.0, CV_RGB(255, 0, 0), 2);
}
// draw "No Pose info."
pos_y += 50;
if (!light_debug->valid_pos()) {
cv::putText(img, "No Valid Pose.", cv::Point(30, pos_y),
cv::FONT_HERSHEY_PLAIN, 3.0, CV_RGB(255, 0, 0), 2);
}
// if image's timestamp is too early or too old
// draw timestamp difference between image and pose
pos_y += 50;
std::string diff_img_pose_ts_str =
"ts diff: " + std::to_string(light_debug->ts_diff_pos());
cv::putText(img, diff_img_pose_ts_str, cv::Point(30, pos_y),
cv::FONT_HERSHEY_PLAIN, 3.0, CV_RGB(255, 0, 0), 2);
pos_y += 50;
std::string diff_img_sys_ts_str =
"ts diff sys: " + std::to_string(light_debug->ts_diff_sys());
cv::putText(img, diff_img_sys_ts_str, cv::Point(30, pos_y),
cv::FONT_HERSHEY_PLAIN, 3.0, CV_RGB(255, 0, 0), 2);
pos_y += 50;
{
std::string signal_txt =
"camera id: " + image_lights->image->camera_id_str();
cv::putText(img, signal_txt, cv::Point(30, pos_y), cv::FONT_HERSHEY_PLAIN,
3.0, CV_RGB(255, 0, 0), 2);
}
// draw image border size (offset between hdmap-box and detection-box)
// if (light_debug->project_error() > 100) {
std::string img_border_txt =
"Offset size: " + std::to_string(light_debug->project_error());
constexpr int kPosYOffset = 1000;
cv::putText(img, img_border_txt, cv::Point(30, kPosYOffset),
cv::FONT_HERSHEY_PLAIN, 3.0, CV_RGB(255, 0, 0), 2);
// }
cv::resize(img, img, cv::Size(960, 540));
cv::imwrite(filename, img);
cv::imshow("debug", img);
cv::waitKey(10);
}
common::adapter::AdapterManager::PublishTrafficLightDetection(result);
auto process_time =
TimeUtil::GetCurrentTime() - image_lights->preprocess_receive_timestamp;
AINFO << "Publish message "
<< " ts:" << GLOG_TIMESTAMP(image_lights->timestamp)
<< " device:" << image_lights->image->camera_id_str() << " consuming "
<< process_time * 1000 << " ms."
<< " number of lights:" << lights->size()
<< " lights:" << result.ShortDebugString();
timer.End("TLProcSubnode::Publish message");
return true;
}
Status TLProcSubnode::ProcEvents() {
Event event;
const EventMeta &event_meta = sub_meta_events_[0];
if (!event_manager_->Subscribe(event_meta.event_id, &event)) {
AERROR << "Failed to subscribe event: " << event_meta.event_id;
return Status(ErrorCode::PERCEPTION_ERROR, "Failed to subscribe event.");
}
if (!ProcEvent(event)) {
AERROR << "TLProcSubnode failed to handle event. "
<< "event:" << event.to_string();
return Status(ErrorCode::PERCEPTION_ERROR,
"TLProcSubnode failed to handle event.");
}
return Status::OK();
}
} // namespace traffic_light
} // namespace perception
} // namespace apollo
|
#ifndef ODFAEG_Z_SORTING_RENDER_COMPONENT_HPP
#define ODFAEG_Z_SORTING_RENDER_COMPONENT_HPP
#include "renderWindow.h"
#include "entityManager.h"
#include "heavyComponent.h"
#include "../Physics/particuleSystem.h"
/**
*\namespace odfaeg
* the namespace of the Opensource Development Framework Adapted for Every Games.
*/
namespace odfaeg {
namespace graphic {
/**
* \file OITRenderComponent.h
* \class OITRenderComponent
* \author Duroisin.L
* \version 1.0
* \date 1/02/2014
* \brief represent a component used to render the entities of a scene.
*/
class ODFAEG_GRAPHICS_API ZSortingRenderComponent : public HeavyComponent {
public :
ZSortingRenderComponent (RenderWindow& window, int layer, std::string expression, EntityManager& scene);
void loadShaders();
void pushEvent(window::IEvent event, RenderWindow& rw);
bool needToUpdate();
void changeVisibleEntities(Entity* toRemove, Entity* toAdd, EntityManager* em);
std::string getExpression();
bool loadEntitiesOnComponent(std::vector<Entity*> vEntities);
void cutIntersectingVA();
void setView(View view);
void setExpression(std::string expression);
std::vector<Entity*> getEntities();
void draw(RenderTarget& target, RenderStates states);
View& getView();
int getLayer();
void clear() {
}
void drawNextFrame() {
}
void draw(Drawable& drawable, RenderStates states) {
}
void updateParticleSystems();
void updateTransformMatrices();
void updateSceneVertices();
private :
Batcher batcher;
View view;
std::vector<Instance> m_instances;
std::vector<Entity*> visibleEntities;
std::string expression;
bool update;
EntityManager& scene;
Shader instancedRenderingShader, shader;
};
}
}
#endif
|
#include "pch.h"
#include "Service.h"
using namespace WinSys;
Service::Service(wil::unique_schandle handle) noexcept : _handle(std::move(handle)) {}
bool Service::Start() {
return Start(std::vector<const wchar_t*>());
}
bool Service::Start(const std::vector<const wchar_t*>& args) {
return ::StartService(_handle.get(), static_cast<DWORD>(args.size()), const_cast<PCWSTR*>(args.data())) ? true : false;
}
bool Service::Stop() {
SERVICE_STATUS status;
return ::ControlService(_handle.get(), SERVICE_CONTROL_STOP, &status) ? true : false;
}
ServiceStatusProcess Service::GetStatus() const {
ServiceStatusProcess status{};
DWORD len;
::QueryServiceStatusEx(_handle.get(), SC_STATUS_PROCESS_INFO, (BYTE*)&status, sizeof(status), &len);
return status;
}
std::vector<ServiceTrigger> Service::GetTriggers() const {
std::vector<ServiceTrigger> triggers;
DWORD needed;
::QueryServiceConfig2(_handle.get(), SERVICE_CONFIG_TRIGGER_INFO, nullptr, 0, &needed);
if (::GetLastError() != ERROR_INSUFFICIENT_BUFFER)
return triggers;
auto buffer = std::make_unique<BYTE[]>(needed);
if (!::QueryServiceConfig2(_handle.get(), SERVICE_CONFIG_TRIGGER_INFO, buffer.get(), needed, &needed))
return triggers;
auto info = reinterpret_cast<SERVICE_TRIGGER_INFO*>(buffer.get());
triggers.reserve(info->cTriggers);
for (DWORD i = 0; i < info->cTriggers; i++) {
const auto& tinfo = info->pTriggers[i];
ServiceTrigger trigger;
trigger.Type = static_cast<ServiceTriggerType>(tinfo.dwTriggerType);
trigger.TriggerSubtype = tinfo.pTriggerSubtype;
trigger.Action = static_cast<ServiceTriggerAction>(tinfo.dwAction);
triggers.push_back(trigger);
}
return triggers;
}
std::vector<std::wstring> Service::GetRequiredPrivileges() const {
std::vector<std::wstring> privileges;
DWORD needed;
::QueryServiceConfig2(_handle.get(), SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO, nullptr, 0, &needed);
if (::GetLastError() != ERROR_INSUFFICIENT_BUFFER)
return privileges;
auto buffer = std::make_unique<BYTE[]>(needed);
if (!::QueryServiceConfig2(_handle.get(), SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO, buffer.get(), needed, &needed))
return privileges;
auto info = reinterpret_cast<SERVICE_REQUIRED_PRIVILEGES_INFO*>(buffer.get());
auto p = info->pmszRequiredPrivileges;
while (p && *p) {
privileges.emplace_back(p);
p += ::wcslen(p) + 1;
}
return privileges;
}
ServiceSidType WinSys::Service::GetSidType() const {
ServiceSidType type;
DWORD len;
if (::QueryServiceConfig2(_handle.get(), SERVICE_CONFIG_SERVICE_SID_INFO, (BYTE*)&type, sizeof(type), &len))
return type;
return ServiceSidType::Unknown;
}
std::unique_ptr<WinSys::Service> Service::Open(const std::wstring & name, ServiceAccessMask access) noexcept {
auto hService = ServiceManager::OpenServiceHandle(name, access);
if (!hService)
return nullptr;
return std::make_unique<WinSys::Service>(std::move(hService));
}
bool Service::Refresh(ServiceInfo& info) {
DWORD bytes;
return ::QueryServiceStatusEx(_handle.get(), SC_STATUS_PROCESS_INFO, (BYTE*)&info._status, sizeof(SERVICE_STATUS_PROCESS), &bytes);
}
bool Service::Pause() {
SERVICE_STATUS status;
return ::ControlService(_handle.get(), SERVICE_CONTROL_PAUSE, &status) ? true : false;
}
bool Service::Continue() {
SERVICE_STATUS status;
return ::ControlService(_handle.get(), SERVICE_CONTROL_CONTINUE, &status) ? true : false;
}
|
#include "solution.h"
using namespace std;
bool Solution::lemonadeChange(vector<int>& bills)
{
int dol_5_count = 0;
int dol_10_count = 0;
for (int &bill : bills)
{
switch (bill)
{
case 5:
dol_5_count++;
break;
case 10:
if (dol_5_count > 0)
{
dol_5_count--;
dol_10_count++;
}
else
return false;
break;
case 20:
if (dol_10_count > 0 && dol_5_count > 0)
{
dol_5_count--;
dol_10_count--;
}
else if (dol_5_count > 2)
{
dol_5_count-=3;
}
else
return false;
break;
default:
break;
}
}
return true;
}
|
/* S H _ O S L . C
* BRL-CAD
*
* Copyright (c) 2004-2019 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this file; see the file named COPYING for more
* information.
*/
/** @file liboptical/sh_osl.c
*
* This shader is an interface for OSL shading system. More information
* when more features are implemented.
*
*/
#include "common.h"
#include <stdlib.h>
#include <stddef.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "./liboslrend.h"
#include "vmath.h"
#include "raytrace.h"
#include "optical.h"
#include "optical/light.h"
#define OSL_MAGIC 0x1837 /* make this a unique number for each shader */
#define CK_OSL_SP(_p) BU_CKMAG(_p, OSL_MAGIC, "osl_specific")
/* Oslrenderer system */
OSLRenderer *oslr = NULL;
/* Every time a thread reaches osl_render for the first time,
we save the address of their own buffers, which is an ugly way to
identify them */
std::vector<struct resource *> visited_addrs;
/* Holds information about the context necessary to correctly execute a
shader */
std::vector<void *> thread_infos;
/* Save default a_hit */
int (*default_a_hit)(struct application *, struct partition *, struct seg *);
/* Save default a_miss */
int (*default_a_miss)(struct application *);
/*
* The shader specific structure contains all variables which are unique
* to any particular use of the shader.
*/
struct osl_specific {
uint32_t magic; /* magic # for memory validity check */
ShadingAttribStateRef shader_ref; /* Reference to this shader in OSLRender system */
};
/* The default values for the variables in the shader specific structure */
static const
struct osl_specific osl_defaults = {
OSL_MAGIC,
};
#define SHDR_NULL ((struct osl_specific *)0)
#define SHDR_O(m) bu_offsetof(struct osl_specific, m)
/* description of how to parse/print the arguments to the shader */
struct bu_structparse osl_print_tab[] = {
{"", 0, (char *)0, 0, BU_STRUCTPARSE_FUNC_NULL, NULL, NULL }
};
extern "C" {
HIDDEN int osl_setup(register struct region *rp, struct bu_vls *matparm,
void **dpp, const struct mfuncs *mfp,
struct rt_i *rtip);
HIDDEN int osl_render(struct application *ap, const struct partition *pp,
struct shadework *swp, void *dp);
HIDDEN void osl_print(register struct region *rp, void *dp);
HIDDEN void osl_free(void *cp);
}
/* The "mfuncs" structure defines the external interface to the shader.
* Note that more than one shader "name" can be associated with a given
* shader by defining more than one mfuncs struct in this array.
* See sh_phong.c for an example of building more than one shader "name"
* from a set of source functions. There you will find that "glass" "mirror"
* and "plastic" are all names for the same shader with different default
* values for the parameters.
*/
struct mfuncs osl_mfuncs[] = {
{MF_MAGIC, "osl", 0, MFI_NORMAL|MFI_HIT|MFI_UV, 0, osl_setup, osl_render, osl_print, osl_free },
{0, (char *)0, 0, 0, 0, 0, 0, 0, 0 }
};
int
osl_parse_edge(char *edge, ShaderEdge &sh_edge)
{
/* Split string around # */
const char *item;
ShaderParam sh_param1, sh_param2;
/* Name of the first shader */
if ((item = strtok(edge, "#")) == NULL) {
fprintf(stderr, "[Error] Expecting the first shader name, found NULL.\n");
return -1;
}
sh_param1.layername = item;
/* Parameter of the first shader */
if ((item = strtok(NULL, "#")) == NULL) {
fprintf(stderr, "[Error] Expecting the parameter of the first shader, found NULL.\n");
return -1;
}
sh_param1.paramname = item;
/* Name of the first shader */
if ((item = strtok(NULL, "#")) == NULL) {
fprintf(stderr, "[Error] Expecting the second shader name, found NULL.\n");
return -1;
}
sh_param2.layername = item;
/* Name of the first shader */
if ((item = strtok(NULL, "#")) == NULL) {
fprintf(stderr, "[Error] Expecting the parameter of the second shader, found NULL.\n");
return -1;
}
sh_param2.paramname = item;
sh_edge = std::make_pair(sh_param1, sh_param2);
}
int
osl_parse_shader(char *shadername, ShaderInfo &sh_info)
{
/* Split string around # */
const char *item;
item = strtok(shadername, "#");
/* We are going to look for shader in ../shaders/ */
sh_info.shadername = "../shaders/" + std::string(item);
/* Check for parameters */
while ((item = strtok(NULL, "#")) != NULL) {
/* Setting layer name, in case we're doing a shader group */
if (BU_STR_EQUAL(item, "layername")) {
/* Get the name of the layer being set */
item = strtok(NULL, "#");
if (item == NULL) {
fprintf(stderr, "[Error] Missing layer name\n");
return -1;
}
sh_info.layername = std::string(item);
}
else {
/* Name of the parameter */
std::string param_name = item;
/* Get the type of parameter being set */
item = strtok(NULL, "#");
if (item == NULL) {
fprintf(stderr, "[Error] Missing parameter type\n");
return -1;
}
else if (BU_STR_EQUAL(item, "int")) {
item = strtok(NULL, "#");
if (item == NULL) {
fprintf(stderr, "[Error] Missing float value\n");
return -1;
}
int value = atoi(item);
sh_info.iparam.push_back(std::make_pair(param_name, value));
}
else if (BU_STR_EQUAL(item, "float")) {
item = strtok(NULL, "#");
if (item == NULL) {
fprintf(stderr, "[Error] Missing float value\n");
return -1;
}
float value = atof(item);
sh_info.fparam.push_back(std::make_pair(param_name, value));
}
else if (BU_STR_EQUAL(item, "color")) {
Color3 color_value;
for (int i=0; i<3; i++) {
item = strtok(NULL, "#");
if (item == NULL) {
fprintf(stderr, "[Error] Missing %d-th component of color value\n", i);
return -1;
}
color_value[i] = atof(item);
}
sh_info.cparam.push_back(std::make_pair(param_name, color_value));
}
else if (BU_STR_EQUAL(item, "normal") || BU_STR_EQUAL(item, "point") || BU_STR_EQUAL(item, "vector")) {
TypeDesc type;
std::string type_name(item);
if (BU_STR_EQUAL(item, "normal")) type = TypeDesc::TypeNormal;
else if (BU_STR_EQUAL(item, "point")) type = TypeDesc::TypePoint;
else if (BU_STR_EQUAL(item, "vector")) type = TypeDesc::TypeVector;
Vec3 vec_value;
for (int i=0; i<3; i++) {
item = strtok(NULL, "#");
if (item == NULL) {
fprintf(stderr, "[Error] Missing %d-th component of %s value\n", i, type_name.c_str());
return -1;
}
vec_value[i] = atof(item);
}
ShaderInfo::TypeVec type_vec(type, vec_value);
sh_info.vparam.push_back(std::make_pair(param_name, type_vec));
}
else if (BU_STR_EQUAL(item, "matrix")) {
fprintf(stderr, "matrix\n");
Matrix44 mat_value;
for (int i=0; i<4; i++)
for (int j=0; j<4; j++) {
item = strtok(NULL, "#");
if (item == NULL) {
fprintf(stderr, "[Error] Missing %d-th component of matrix value\n", i*4 + j);
return -1;
}
mat_value[i][j] = atof(item);
fprintf(stderr, "%.2lf ", mat_value[i][j]);
}
fprintf(stderr, "\n");
sh_info.mparam.push_back(std::make_pair(param_name, mat_value));
}
else if (BU_STR_EQUAL(item, "string")) {
item = strtok(NULL, "#");
if (item == NULL) {
fprintf(stderr, "[Error] Missing string\n");
return -1;
}
std::string string_value = item;
sh_info.sparam.push_back(std::make_pair(param_name, string_value));
}
else {
/* FIXME: add support to TypePoint, TypeVector, TypeNormal parameters */
fprintf(stderr, "[Error] Unknown parameter type\n");
return -1;
}
}
}
}
/**
* This function parses the input shaders
* Example:
* shadername=color#Cin#point#0.0#0.0#1.0
* shadername=glass
* shadername=checker#K#float#4.0
* join=color#Cout#shader#Cin1
* join=glass#Cout#shader#Cin1
**/
int
osl_parse(const struct bu_vls *in_vls, ShaderGroupInfo &group_info)
{
struct bu_vls vls = BU_VLS_INIT_ZERO;
register char *cp;
char *name;
char *value;
int retval;
BU_CK_VLS(in_vls);
/* Duplicate the input string. This algorithm is destructive. */
bu_vls_vlscat(&vls, in_vls);
cp = bu_vls_addr(&vls);
while (*cp) {
/* NAME = VALUE white-space-separator */
/* skip any leading whitespace */
while (*cp != '\0' && isspace(*cp))
cp++;
/* Find equal sign */
name = cp;
while (*cp != '\0' && *cp != '=')
cp++;
if (*cp == '\0') {
if (name == cp) break;
/* end of string in middle of arg */
bu_log("bu_structparse: input keyword '%s' is not followed by '=' in '%s'\nInput must be in keyword=value format.\n",
name, bu_vls_addr(in_vls));
bu_vls_free(&vls);
return -2;
}
*cp++ = '\0';
/* Find end of value. */
if (*cp == '"') {
/* strings are double-quote (") delimited skip leading " &
* find terminating " while skipping escaped quotes (\")
*/
for (value = ++cp; *cp != '\0'; ++cp)
if (*cp == '"' &&
(cp == value || *(cp-1) != '\\'))
break;
if (*cp != '"') {
bu_log("bu_structparse: keyword '%s'=\" without closing \"\n",
name);
bu_vls_free(&vls);
return -3;
}
} else {
/* non-strings are white-space delimited */
value = cp;
while (*cp != '\0' && !isspace(*cp))
cp++;
}
if (*cp != '\0')
*cp++ = '\0';
if (BU_STR_EQUAL(name, "shadername")) {
ShaderInfo sh_info;
osl_parse_shader(value, sh_info);
group_info.shader_layers.push_back(sh_info);
}
else if (BU_STR_EQUAL(name, "join")) {
ShaderEdge sh_edge;
osl_parse_edge(value, sh_edge);
group_info.shader_edges.push_back(sh_edge);
}
}
bu_vls_free(&vls);
return 0;
}
/*
* This routine is called (at prep time)
* once for each region which uses this shader.
* Any shader-specific initialization should be done here.
*
* Returns:
* 1 success
* 0 success, but delete region
* -1 failure
*/
extern "C" {
HIDDEN int osl_setup(register struct region *rp, struct bu_vls *matparm,
void **dpp, const struct mfuncs *mfp,
struct rt_i *rtip)
{
register struct osl_specific *osl_sp;
/* check the arguments */
RT_CHECK_RTI(rtip);
BU_CK_VLS(matparm);
RT_CK_REGION(rp);
if (optical_debug&OPTICAL_DEBUG_SHADE)
bu_log("osl_setup(%s)\n", rp->reg_name);
/* Get memory for the shader parameters and shader-specific data */
BU_GET(osl_sp, struct osl_specific);
*dpp = (char *)osl_sp;
/* -----------------------------------
* Initialize the osl specific values
* -----------------------------------
*/
osl_sp->magic = OSL_MAGIC;
/* Parse the user's arguments to fill osl specifics */
ShaderGroupInfo group_info;
if (osl_parse(matparm, group_info) < 0) {
return -1;
}
/* -----------------------------------
* Initialize osl render system
* -----------------------------------
*/
/* If OSL system was not initialized yet, do it */
if (oslr == NULL) {
oslr = new OSLRenderer();
}
/* Add this shader to OSL system */
osl_sp->shader_ref = oslr->AddShader(group_info);
if (optical_debug&OPTICAL_DEBUG_SHADE) {
bu_struct_print(" Parameters:", osl_print_tab, (char *)osl_sp);
}
return 1;
}
HIDDEN void osl_print(register struct region *rp, void *dp)
{
bu_struct_print(rp->reg_name, osl_print_tab, (char *)dp);
}
HIDDEN void osl_free(void *cp)
{
register struct osl_specific *osl_sp =
(struct osl_specific *)cp;
BU_PUT(cp, struct osl_specific);
}
/*
* Callback function to be called whenever a refraction ray hits an object
*/
int
osl_refraction_hit(struct application *ap, struct partition *PartHeadp, struct seg *finished_segs)
{
/* iterating over partitions, this will keep track of the current
* partition we're working on.
*/
struct partition *pp;
/* will serve as a pointer to the solid primitive we hit */
struct soltab *stp;
/* will contain surface curvature information at the entry */
struct curvature cur;
/* will contain our hit point coordinate */
point_t pt;
/* will contain normal vector where ray enters geometry */
vect_t inormal;
/* will contain normal vector where ray exits geometry */
vect_t onormal;
struct shadework sw;
/* iterate over each partition until we get back to the head.
* each partition corresponds to a specific homogeneous region of
* material.
*/
for (pp=PartHeadp->pt_forw; pp != PartHeadp; pp = pp->pt_forw) {
register const struct mfuncs *mfp;
register const struct region *rp;
memset((char *)&sw, 0, sizeof(sw));
sw.sw_transmit = sw.sw_reflect = 0.0;
sw.sw_refrac_index = 1.0;
sw.sw_extinction = 0;
sw.sw_xmitonly = 0; /* want full data */
sw.sw_inputs = 0; /* no fields filled yet */
sw.sw_segs = finished_segs;
VSETALL(sw.sw_color, 1);
VSETALL(sw.sw_basecolor, 1);
rp = pp->pt_regionp;
mfp = (struct mfuncs *)pp->pt_regionp->reg_mfuncs;
/* Determine the hit point */
sw.sw_hit = *(pp->pt_outhit); /* struct copy */
VJOIN1(sw.sw_hit.hit_point, ap->a_ray.r_pt, sw.sw_hit.hit_dist, ap->a_ray.r_dir);
/* Determine the normal point */
stp = pp->pt_outseg->seg_stp;
RT_HIT_NORMAL(sw.sw_hit.hit_normal, &(sw.sw_hit), stp, &(ap->a_ray), pp->pt_outflip);
/* Invoke the actual shader (may be a tree of them) */
if (mfp && mfp->mf_render)
(void)mfp->mf_render(ap, pp, &sw, rp->reg_udata);
VMOVE(ap->a_color, sw.sw_color);
}
return 1;
}
/*
* This is called (from viewshade() in shade.c) once for each hit point
* to be shaded. The purpose here is to fill in values in the shadework
* structure.
*/
HIDDEN int osl_render(struct application *ap, const struct partition *pp,
struct shadework *swp, void *dp)
/* defined in ../h/shadework.h */
/* ptr to the shader-specific struct */
{
register struct osl_specific *osl_sp =
(struct osl_specific *)dp;
void * thread_info;
int nsamples; /* Number of samples */
/* check the validity of the arguments we got */
RT_AP_CHECK(ap);
RT_CHECK_PT(pp);
CK_OSL_SP(osl_sp);
if (optical_debug&OPTICAL_DEBUG_SHADE)
bu_struct_print("osl_render Parameters:", osl_print_tab,
(char *)osl_sp);
bu_semaphore_acquire(BU_SEM_SYSCALL);
/* Check if it is the first time this thread is calling this function */
bool visited = false;
for (size_t i = 0; i < visited_addrs.size(); i++) {
if (ap->a_resource == visited_addrs[i]) {
visited = true;
thread_info = thread_infos[i];
break;
}
}
if (!visited) {
visited_addrs.push_back(ap->a_resource);
/* Get thread specific information from OSLRender system */
thread_info = oslr->CreateThreadInfo();
thread_infos.push_back(thread_info);
}
if (ap->a_level == 0) {
default_a_hit = ap->a_hit; /* save the default hit callback (colorview @ rt) */
default_a_miss = ap->a_miss;
}
bu_semaphore_release(BU_SEM_SYSCALL);
Color3 acc_color(0.0f);
/* -----------------------------------
* Fill in all necessary information for the OSL renderer
* -----------------------------------
*/
RenderInfo info;
/* Set hit point */
VMOVE(info.P, swp->sw_hit.hit_point);
/* Set normal at the point */
VMOVE(info.N, swp->sw_hit.hit_normal);
/* Set incidence ray direction */
VMOVE(info.I, ap->a_ray.r_dir);
/* U-V mapping stuff */
info.u = swp->sw_uv.uv_u;
info.v = swp->sw_uv.uv_v;
VSETALL(info.dPdu, 0.0f);
VSETALL(info.dPdv, 0.0f);
/* x and y pixel coordinates */
info.screen_x = ap->a_x;
info.screen_y = ap->a_y;
info.depth = ap->a_level;
info.surfacearea = 1.0f;
info.shader_ref = osl_sp->shader_ref;
/* We assume that the only information that will be written is thread_info,
so that oslr->QueryColor is thread safe */
info.thread_info = thread_info;
// Ray-tracing (local illumination)
/* We only perform reflection if application decides to */
info.doreflection = 0;
info.out_ray_type = 0;
Color3 weight = oslr->QueryColor(&info);
/* Fire another ray */
if ((info.out_ray_type & RAY_REFLECT) || (info.out_ray_type & RAY_TRANSMIT)) {
struct application new_ap;
RT_APPLICATION_INIT(&new_ap);
new_ap = *ap; /* struct copy */
new_ap.a_onehit = 1;
new_ap.a_hit = default_a_hit;
new_ap.a_level = info.depth + 1;
new_ap.a_flag = 0;
VMOVE(new_ap.a_ray.r_dir, info.out_ray.dir);
VMOVE(new_ap.a_ray.r_pt, info.out_ray.origin);
/* This next ray represents refraction */
if (info.out_ray_type & RAY_TRANSMIT) {
/* Displace the hit point a little bit in the direction
of the next ray */
Vec3 tmp;
VSCALE(tmp, info.out_ray.dir, 1e-4);
VADD2(new_ap.a_ray.r_pt, new_ap.a_ray.r_pt, tmp);
new_ap.a_onehit = 1;
new_ap.a_refrac_index = 1.5;
new_ap.a_flag = 2; /* mark as refraction */
new_ap.a_hit = osl_refraction_hit;
}
(void)rt_shootray(&new_ap);
Color3 rec;
VMOVE(rec, new_ap.a_color);
Color3 res = rec*weight;
VMOVE(swp->sw_color, res);
}
else {
/* Final color */
VMOVE(swp->sw_color, weight);
}
return 1;
}
}
/*
* Local Variables:
* mode: C++
* tab-width: 8
* indent-tabs-mode: t
* c-file-style: "stroustrup"
* End:
* ex: shiftwidth=4 tabstop=8
*/
|
//
// Created by Nicholas Newdigate on 18/07/2020.
//
#ifndef TEENSY_RESAMPLING_WAVSDREADER_READER_MONO_LOOP_FORWARD_TESTS_CPP
#define TEENSY_RESAMPLING_WAVSDREADER_READER_MONO_LOOP_FORWARD_TESTS_CPP
#include <boost/test/unit_test.hpp>
#include "ResamplingReaderFixture.h"
BOOST_AUTO_TEST_SUITE(test_wav_mono_loop_forward_playback)
uint16_t test_sndhdrdata_sndhdr_wav[] = {
0x4952, 0x4646, 0x0038, 0x0000, 0x4157, 0x4556,
0x6d66, 0x2074, 0x0010, 0x0000, 0x0001, 0x0001,
0xac44, 0x0000, 0xb110, 0x0002, 0x0004, 0x0010,
0x6164, 0x6174, 0x0014, 0x0000
};
unsigned int test_sndhdrdata_sndhdr_wav_len = 22; // 22 int16_t = 44 bytes = size of wave header
BOOST_FIXTURE_TEST_CASE(ReadForwardLoopAtRegularPlaybackRate, ResamplingReaderFixture) {
const uint32_t expectedDataSize = 32; // = 64 bytes
test_sndhdrdata_sndhdr_wav[20] = expectedDataSize * 2;
printf("test_wav_mono_loop_forward_playback::ReadForwardAtRegularPlaybackRate(%d)\n", expectedDataSize);
int16_t mockFileBytes[expectedDataSize + test_sndhdrdata_sndhdr_wav_len];
for (int16_t i = 0; i < test_sndhdrdata_sndhdr_wav_len; i++) {
mockFileBytes[i] = test_sndhdrdata_sndhdr_wav[i];
}
for (int16_t i = 0; i < expectedDataSize; i++) {
mockFileBytes[i + test_sndhdrdata_sndhdr_wav_len] = i;
}
SD.setSDCardFileData((char*) mockFileBytes, (expectedDataSize + test_sndhdrdata_sndhdr_wav_len) * 2);
resamplingSdReader->begin();
resamplingSdReader->setPlaybackRate(1.0);
resamplingSdReader->playWav("test2.bin");
resamplingSdReader->setLoopType(looptype_repeat);
int16_t actual[256];
int16_t *buffers[1] = { actual };
int j = 0, bytesRead = 0, total_bytes_read = 0, currentExpected = 0;
bool assertionsPass = true;
do {
bytesRead = resamplingSdReader->read((void**)buffers, 256 ); // 256 samples
total_bytes_read += bytesRead;
//printf("j:%d bytesRead: %d \n", j, bytesRead);
for (int i=0; i < bytesRead/2; i++) {
printf("\t\t[%x]:%x", currentExpected, actual[i]);
if (currentExpected != actual[i]) {
assertionsPass = false;
BOOST_FAIL("Value not as expected!!!");
}
currentExpected++;
currentExpected %= expectedDataSize;
}
printf("\n");
j++;
} while (j < 100);
printf("total_bytes_read: %d \n", total_bytes_read);
resamplingSdReader->close();
BOOST_CHECK_EQUAL( true, assertionsPass);
}
BOOST_FIXTURE_TEST_CASE(ReadForwardLoopAtRegularPlaybackRateWithLoopFinish, ResamplingReaderFixture) {
const uint32_t expectedDataSize = 32; // = 64 bytes
test_sndhdrdata_sndhdr_wav[20] = expectedDataSize * 2;
printf("test_wav_mono_loop_forward_playback::ReadForwardAtRegularPlaybackRate(%d)\n", expectedDataSize);
int16_t mockFileBytes[expectedDataSize + test_sndhdrdata_sndhdr_wav_len];
for (int16_t i = 0; i < test_sndhdrdata_sndhdr_wav_len; i++) {
mockFileBytes[i] = test_sndhdrdata_sndhdr_wav[i];
}
for (int16_t i = 0; i < expectedDataSize; i++) {
mockFileBytes[i + test_sndhdrdata_sndhdr_wav_len] = i;
}
SD.setSDCardFileData((char*) mockFileBytes, (expectedDataSize + test_sndhdrdata_sndhdr_wav_len) * 2);
resamplingSdReader->begin();
resamplingSdReader->setPlaybackRate(1.0);
resamplingSdReader->playWav("test2.bin");
resamplingSdReader->setLoopType(looptype_repeat);
resamplingSdReader->setLoopFinish(8);
int16_t actual[256];
int16_t *buffers[1] = { actual };
int j = 0, samplesRead = 0, total_bytes_read = 0, currentExpected = 0;
bool assertionsPass = true;
do {
samplesRead = resamplingSdReader->read((void**)buffers, 256 ); // 256 samples
total_bytes_read += samplesRead * 2;
printf("j:%d samplesRead: %d \n", j, samplesRead);
for (int i=0; i < samplesRead; i++) {
printf("\t\t[%x]:%x", currentExpected, actual[i]);
if (currentExpected != actual[i]) {
assertionsPass = false;
BOOST_FAIL("Value not as expected!!!");
}
currentExpected++;
currentExpected %= 8;
}
printf("\n");
j++;
} while (j < 100);
printf("total_bytes_read: %d \n", total_bytes_read);
resamplingSdReader->close();
BOOST_CHECK_EQUAL( true, assertionsPass);
}
BOOST_FIXTURE_TEST_CASE(ReadForwardLoopAtRegularPlaybackRateWithLoopStartAndFinish, ResamplingReaderFixture) {
const uint32_t expectedDataSize = 32; // = 64 bytes
test_sndhdrdata_sndhdr_wav[20] = expectedDataSize * 2;
printf("test_wav_mono_loop_forward_playback::ReadForwardAtRegularPlaybackRate(%d)\n", expectedDataSize);
int16_t mockFileBytes[expectedDataSize + test_sndhdrdata_sndhdr_wav_len];
for (int16_t i = 0; i < test_sndhdrdata_sndhdr_wav_len; i++) {
mockFileBytes[i] = test_sndhdrdata_sndhdr_wav[i];
}
for (int16_t i = 0; i < expectedDataSize; i++) {
mockFileBytes[i + test_sndhdrdata_sndhdr_wav_len] = i;
}
SD.setSDCardFileData((char*) mockFileBytes, (expectedDataSize + test_sndhdrdata_sndhdr_wav_len) * 2);
resamplingSdReader->begin();
resamplingSdReader->setPlaybackRate(1.0);
resamplingSdReader->playWav("test2.bin");
resamplingSdReader->setLoopType(looptype_repeat);
resamplingSdReader->setLoopFinish(8);
int16_t actual[256];
int16_t *buffers[1] = { actual };
int j = 0, samplesRead = 0, total_bytes_read = 0, currentExpected = 0;
bool assertionsPass = true;
do {
samplesRead = resamplingSdReader->read((void**)buffers, 256 ); // 256 samples
total_bytes_read += samplesRead * 2;
printf("j:%d bytesRead: %d \n", j, total_bytes_read);
for (int i=0; i < samplesRead; i++) {
printf("\t\t[%x]:%x", currentExpected, actual[i]);
if (currentExpected != actual[i]) {
assertionsPass = false;
BOOST_FAIL("Value not as expected!!!");
}
currentExpected++;
currentExpected %= 8;
}
printf("\n");
j++;
} while (j < 100);
printf("total_bytes_read: %d \n", total_bytes_read);
resamplingSdReader->close();
BOOST_CHECK_EQUAL( true, assertionsPass);
}
BOOST_FIXTURE_TEST_CASE(ReadForwardLoopAtHalfPlaybackRate, ResamplingReaderFixture) {
const uint32_t size_of_datasource = 800;
test_sndhdrdata_sndhdr_wav[20] = size_of_datasource * 2;
printf("ReadForwardAtRegularPlaybackRate(%d)\n", size_of_datasource);
int16_t dataSource[size_of_datasource];
for (int16_t i = 0; i < size_of_datasource; i++) {
dataSource[i] = i;
}
SD.setSDCardFileData((char*) dataSource, size_of_datasource * 2);
const int16_t expectedSize = size_of_datasource * 2;
int16_t expected[expectedSize];
for (int16_t i = 0; i < expectedSize; i++) {
expected[i] = i / 2;
}
resamplingSdReader->begin();
resamplingSdReader->setPlaybackRate(0.5);
resamplingSdReader->playWav("test2.bin");
resamplingSdReader->setLoopType(looptype_none);
int16_t actual[expectedSize];
int16_t *buffers[1] = { actual };
int j = 0, samplesRead = 0, total_bytes_read = 0;
do {
samplesRead = resamplingSdReader->read((void**)buffers, 256 );
total_bytes_read += samplesRead * 2;
printf("j:%d samplesRead: %d: ", j, samplesRead);
for (int i=0; i < samplesRead; i++) {
printf("\t\t[%x]:%x", expected[j * 256 + i], actual[j + i]);
}
printf("\n");
if (samplesRead != 0)
BOOST_CHECK_EQUAL_COLLECTIONS(&expected[j * 256], &expected[j * 256 + samplesRead - 1], &actual[0], &actual[samplesRead - 1]);
j++;
} while (samplesRead > 0);
printf("total_bytes_read: %d \n", total_bytes_read);
resamplingSdReader->close();
}
BOOST_AUTO_TEST_SUITE_END()
#endif //TEENSY_RESAMPLING_WAVSDREADER_READER_MONO_LOOP_FORWARD_TESTS_CPP
|
/**************************************************************************/
/* */
/* WWIV Version 5.x */
/* Copyright (C)1998-2020, WWIV Software Services */
/* */
/* 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 "bbs/asv.h"
#include <cstdint>
#include "bbs/application.h"
#include "bbs/bbs.h"
#include "bbs/confutil.h"
#include "bbs/uedit.h"
#include "bbs/xfer.h"
using std::string;
void set_autoval(int n) {
auto_val(n, a()->user());
a()->reset_effective_sl();
changedsl();
}
|
/*
* Implementation of the Knuth-Morris-Pratt algorithm
*
* "Introduction to Algorithms" Thomas H. Corman and other
*
* */
#include <string>
#include <vector>
#include <iostream>
using namespace std;
void compute_prefix(vector<size_t> &prefix, const string &needle){
const size_t m = needle.length();
size_t k = string::pos;
prefix.push_back(k);
for(size_t q=1; q < m; q++){
while(k < string::npos && needle[k + 1] != needle[q]){
k = prefix[k];
}
if(needle[k + 1] == needle[q]){
k++;
}
prefix.push_back(k);
}
}
size_t kmp_matcher(const string &haystack, const string &needle){
if(haystack.empty() || needle.empty()){
return string::npos;
}
const size_t n = haystack.length();
const size_t m = needle.length();
vector<size_t> prefix;
prefix.reserve(m);
compute_prefix(prefix, needle);
size_t q = string::npos;
for(size_t i=0; i < n; i++){
while(q < string::npos && needle[q + 1] != haystack[i]){
q = prefix[q];
}
if(needle[q + 1] == haystack[i]){
q++;
}
if(q == m - 1){
return i - m + 1;
}
}
return string::npos;
}
int main(int argc, char* argv[]){
if(argc < 3){
cout << "Usage: <haystack> <needle>" << endl;
return 0;
}
size_t offset = string::npos;
string haystack = argv[1];
string needle = argv[2];
offset = kmp_matcher(haystack, needle);
cout << offset << endl;
return 0;
}
|
#include "ThingerTaskController.h"
ThingerTaskController TaskController;
|
/*
Copyright (c) 2017-2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Tests for copy_if and remove_copy_if
#include "pstl_test_config.h"
#include "pstl/execution"
#include "pstl/algorithm"
#include "utils.h"
using namespace TestUtils;
struct run_copy_if
{
#if __PSTL_ICC_16_VC14_TEST_PAR_TBB_RT_RELEASE_64_BROKEN // dummy specializations to skip testing in case of broken configuration
template <typename InputIterator, typename OutputIterator, typename OutputIterator2, typename Size,
typename Predicate, typename T>
void
operator()(pstl::execution::parallel_policy, InputIterator first, InputIterator last, OutputIterator out_first,
OutputIterator out_last, OutputIterator2 expected_first, OutputIterator2 expected_last, Size n,
Predicate pred, T trash)
{
}
template <typename InputIterator, typename OutputIterator, typename OutputIterator2, typename Size,
typename Predicate, typename T>
void
operator()(pstl::execution::parallel_unsequenced_policy, InputIterator first, InputIterator last,
OutputIterator out_first, OutputIterator out_last, OutputIterator2 expected_first,
OutputIterator2 expected_last, Size n, Predicate pred, T trash)
{
}
#endif
template <typename Policy, typename InputIterator, typename OutputIterator, typename OutputIterator2, typename Size,
typename Predicate, typename T>
void
operator()(Policy&& exec, InputIterator first, InputIterator last, OutputIterator out_first,
OutputIterator out_last, OutputIterator2 expected_first, OutputIterator2 expected_last, Size n,
Predicate pred, T trash)
{
// Cleaning
std::fill_n(expected_first, n, trash);
std::fill_n(out_first, n, trash);
// Run copy_if
auto i = copy_if(first, last, expected_first, pred);
auto k = copy_if(exec, first, last, out_first, pred);
EXPECT_EQ_N(expected_first, out_first, n, "wrong copy_if effect");
for (size_t j = 0; j < GuardSize; ++j)
{
++k;
}
EXPECT_TRUE(out_last == k, "wrong return value from copy_if");
// Cleaning
std::fill_n(expected_first, n, trash);
std::fill_n(out_first, n, trash);
// Run remove_copy_if
i = remove_copy_if(first, last, expected_first, [=](const T& x) { return !pred(x); });
k = remove_copy_if(exec, first, last, out_first, [=](const T& x) { return !pred(x); });
EXPECT_EQ_N(expected_first, out_first, n, "wrong remove_copy_if effect");
for (size_t j = 0; j < GuardSize; ++j)
{
++k;
}
EXPECT_TRUE(out_last == k, "wrong return value from remove_copy_if");
}
};
template <typename T, typename Predicate, typename Convert>
void
test(T trash, Predicate pred, Convert convert, bool check_weakness = true)
{
// Try sequences of various lengths.
for (size_t n = 0; n <= 100000; n = n <= 16 ? n + 1 : size_t(3.1415 * n))
{
// count is number of output elements, plus a handful
// more for sake of detecting buffer overruns.
size_t count = GuardSize;
Sequence<T> in(n, [&](size_t k) -> T {
T val = convert(n ^ k);
count += pred(val) ? 1 : 0;
return val;
});
Sequence<T> out(count, [=](size_t) { return trash; });
Sequence<T> expected(count, [=](size_t) { return trash; });
if (check_weakness)
{
auto expected_result = copy_if(in.cfbegin(), in.cfend(), expected.begin(), pred);
size_t m = expected_result - expected.begin();
EXPECT_TRUE(n / 4 <= m && m <= 3 * (n + 1) / 4, "weak test for copy_if");
}
invoke_on_all_policies(run_copy_if(), in.begin(), in.end(), out.begin(), out.end(), expected.begin(),
expected.end(), count, pred, trash);
invoke_on_all_policies(run_copy_if(), in.cbegin(), in.cend(), out.begin(), out.end(), expected.begin(),
expected.end(), count, pred, trash);
}
}
struct test_non_const
{
template <typename Policy, typename InputIterator, typename OutputInterator>
void
operator()(Policy&& exec, InputIterator input_iter, OutputInterator out_iter)
{
auto is_even = [&](float64_t v) {
uint32_t i = (uint32_t)v;
return i % 2 == 0;
};
copy_if(exec, input_iter, input_iter, out_iter, non_const(is_even));
invoke_if(exec, [&]() { remove_copy_if(exec, input_iter, input_iter, out_iter, non_const(is_even)); });
}
};
int32_t
main()
{
test<float64_t>(-666.0, [](const float64_t& x) { return x * x <= 1024; },
[](size_t j) { return ((j + 1) % 7 & 2) != 0 ? float64_t(j % 32) : float64_t(j % 33 + 34); });
test<int32_t>(-666, [](const int32_t& x) { return x != 42; },
[](size_t j) { return ((j + 1) % 5 & 2) != 0 ? int32_t(j + 1) : 42; });
#if !__PSTL_ICC_17_TEST_MAC_RELEASE_32_BROKEN
test<Number>(Number(42, OddTag()), IsMultiple(3, OddTag()), [](int32_t j) { return Number(j, OddTag()); });
#endif
#if !__PSTL_ICC_16_17_TEST_REDUCTION_RELEASE_BROKEN
test<int32_t>(-666, [](const int32_t& x) { return true; }, [](size_t j) { return j; }, false);
#endif
test_algo_basic_double<int32_t>(run_for_rnd_fw<test_non_const>());
std::cout << done() << std::endl;
return 0;
}
|
/* Copyright 2019 Google Inc. 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 "llvm/Support/CommandLine.h"
#include "llvm/Support/InitLLVM.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/ToolOutputFile.h"
#include "mlir/Pass/Pass.h" // TF:local_config_mlir
#include "mlir/Pass/PassManager.h" // TF:local_config_mlir
#include "mlir/Support/FileUtilities.h" // TF:local_config_mlir
#include "mlir/Support/MlirOptMain.h" // TF:local_config_mlir
#include "tensorflow/compiler/mlir/init_mlir.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/platform/logging.h"
// NOLINTNEXTLINE
static llvm::cl::opt<std::string> input_filename(llvm::cl::Positional,
llvm::cl::desc("<input file>"),
llvm::cl::init("-"));
// NOLINTNEXTLINE
static llvm::cl::opt<std::string> output_filename(
"o", llvm::cl::desc("Output filename"), llvm::cl::value_desc("filename"),
llvm::cl::init("-"));
// NOLINTNEXTLINE
static llvm::cl::opt<bool> split_input_file(
"split-input-file",
llvm::cl::desc("Split the input file into pieces and process each "
"chunk independently"),
llvm::cl::init(false));
// NOLINTNEXTLINE
static llvm::cl::opt<bool> verify_diagnostics(
"verify-diagnostics",
llvm::cl::desc("Check that emitted diagnostics match "
"expected-* lines on the corresponding line"),
llvm::cl::init(false));
// NOLINTNEXTLINE
static llvm::cl::opt<bool> verify_passes(
"verify-each",
llvm::cl::desc("Run the verifier after each transformation pass"),
llvm::cl::init(true));
int main(int argc, char **argv) {
tensorflow::InitMlir y(&argc, &argv);
// Register any pass manager command line options.
mlir::registerPassManagerCLOptions();
// Parse pass names in main to ensure static initialization completed.
mlir::PassPipelineCLParser pass_pipeline("", "Compiler passes to run");
llvm::cl::ParseCommandLineOptions(argc, argv,
"TF MLIR modular optimizer driver\n");
// Set up the input file.
std::string error_message;
auto file = mlir::openInputFile(input_filename, &error_message);
QCHECK(file) << error_message;
auto output = mlir::openOutputFile(output_filename, &error_message);
QCHECK(output) << error_message;
if (failed(mlir::MlirOptMain(output->os(), std::move(file), pass_pipeline,
split_input_file, verify_diagnostics,
verify_passes)))
return 1;
output->keep();
return 0;
}
|
#include "GraphLoadingValidationDialog.h"
using namespace ComplexNetsGui;
GraphLoadingValidationDialog::GraphLoadingValidationDialog(QWidget* parent) : QDialog(parent)
{
this->mainWindow = static_cast<MainWindow*>(parent);
if (this->objectName().isEmpty())
this->setObjectName(QString::fromUtf8("Dialog"));
this->resize(257, 268);
buttonBox = new QDialogButtonBox(this);
buttonBox->setObjectName(QString::fromUtf8("buttonBox"));
buttonBox->setGeometry(QRect(40, 220, 171, 32));
buttonBox->setOrientation(Qt::Horizontal);
buttonBox->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Ok);
groupBox = new QGroupBox(this);
groupBox->setObjectName(QString::fromUtf8("groupBox"));
groupBox->setGeometry(QRect(10, 20, 241, 91));
verticalLayoutWidget_2 = new QWidget(groupBox);
verticalLayoutWidget_2->setObjectName(QString::fromUtf8("verticalLayoutWidget_2"));
verticalLayoutWidget_2->setGeometry(QRect(10, 30, 160, 52));
verticalLayout_2 = new QVBoxLayout(verticalLayoutWidget_2);
verticalLayout_2->setObjectName(QString::fromUtf8("verticalLayout_2"));
verticalLayout_2->setContentsMargins(0, 0, 0, 0);
radioButton_3 = new QRadioButton(verticalLayoutWidget_2);
radioButton_3->setObjectName(QString::fromUtf8("radioButton_3"));
verticalLayout_2->addWidget(radioButton_3);
radioButton_4 = new QRadioButton(verticalLayoutWidget_2);
connect(radioButton_4, SIGNAL(toggled(bool)), this, SLOT(radioButton4Changed(bool)));
radioButton_4->setObjectName(QString::fromUtf8("radioButton_4"));
verticalLayout_2->addWidget(radioButton_4);
groupBox_2 = new QGroupBox(this);
groupBox_2->setObjectName(QString::fromUtf8("groupBox_2"));
groupBox_2->setGeometry(QRect(10, 120, 241, 91));
verticalLayoutWidget = new QWidget(groupBox_2);
verticalLayoutWidget->setObjectName(QString::fromUtf8("verticalLayoutWidget"));
verticalLayoutWidget->setGeometry(QRect(10, 30, 160, 52));
verticalLayout = new QVBoxLayout(verticalLayoutWidget);
verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
verticalLayout->setContentsMargins(0, 0, 0, 0);
radioButton = new QRadioButton(verticalLayoutWidget);
radioButton->setObjectName(QString::fromUtf8("radioButton"));
verticalLayout->addWidget(radioButton);
radioButton_2 = new QRadioButton(verticalLayoutWidget);
radioButton_2->setObjectName(QString::fromUtf8("radioButton_2"));
verticalLayout->addWidget(radioButton_2);
radioButton_3->setChecked(true);
radioButton_4->setChecked(false);
radioButton_3->setEnabled(true);
radioButton_4->setEnabled(true);
radioButton->setChecked(true);
retranslateUi();
QObject::connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
QObject::connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
QMetaObject::connectSlotsByName(this);
}
void GraphLoadingValidationDialog::retranslateUi()
{
this->setWindowTitle(QApplication::translate("Dialog", "Load graph", 0));
groupBox->setTitle(QApplication::translate("Dialog", "Undirected or directed graph", 0));
radioButton_3->setText(QApplication::translate("Dialog", "Undirected graph", 0));
radioButton_4->setText(QApplication::translate("Dialog", "Directed graph", 0));
groupBox_2->setTitle(QApplication::translate("Dialog", "Unweighted or weighted graph", 0));
radioButton->setText(QApplication::translate("Dialog", "Unweighted graph", 0));
radioButton_2->setText(QApplication::translate("Dialog", "Weighted graph", 0));
}
bool GraphLoadingValidationDialog::isMultigraph() const
{
return true;
}
bool GraphLoadingValidationDialog::isWeigthed() const
{
return !radioButton->isChecked();
// return checkBox->isChecked();
}
bool GraphLoadingValidationDialog::isDirected() const
{
return !radioButton_3->isChecked();
// return checkBox_2->isChecked();
}
// TODO within this signal handler we could disable all functionality that it isnt supported by
// directed graph yet
// or throw signals to let other components know
void GraphLoadingValidationDialog::radioButton4Changed(bool checked)
{
if (checked)
{
radioButton->setChecked(true);
radioButton_2->setEnabled(false);
}
else
{
radioButton_2->setEnabled(true);
}
this->mainWindow->disableActions();
}
GraphLoadingValidationDialog::~GraphLoadingValidationDialog() {}
|
// -----------------------------------------------------------------------------------------------------
// Copyright (c) 2006-2019, Knut Reinert & Freie Universität Berlin
// Copyright (c) 2016-2019, Knut Reinert & MPI für molekulare Genetik
// This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License
// shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE
// -----------------------------------------------------------------------------------------------------
#include <type_traits>
#include <gtest/gtest.h>
#include <seqan3/core/pod_tuple.hpp>
using namespace seqan3;
// default/zero construction
TEST(pod_tuple_ctr, ctr)
{
[[maybe_unused]] pod_tuple<int, long, float> t1;
}
// aggregate initialization
TEST(pod_tuple_aggr, aggr)
{
[[maybe_unused]] pod_tuple<int, long, float> t1{4, 7l, 3.0f};
}
// zero initialization
TEST(pod_tuple_zro, zro)
{
pod_tuple<int, long, float> t1{0, 0, 0};
pod_tuple<int, long, float> t2{};
EXPECT_EQ(t1, t2);
}
// copy construction
TEST(pod_tuple_cp_ctr, cp_ctr)
{
pod_tuple<int, long, float> t1{4, 7l, 3.0f};
pod_tuple<int, long, float> t2{t1};
pod_tuple<int, long, float> t3(t1);
EXPECT_EQ(t1, t2);
EXPECT_EQ(t2, t3);
}
// move construction
TEST(pod_tuple_mv_ctr, mv_ctr)
{
pod_tuple<int, long, float> t0{4, 7l, 3.0f};
pod_tuple<int, long, float> t1{4, 7l, 3.0f};
pod_tuple<int, long, float> t2{std::move(t1)};
EXPECT_EQ(t2, t0);
pod_tuple<int, long, float> t3(std::move(t2));
EXPECT_EQ(t3, t0);
}
// copy assignment
TEST(pod_tuple_cp_assgn, cp_assgn)
{
pod_tuple<int, long, float> t1{4, 7l, 3.0f};
pod_tuple<int, long, float> t2;
pod_tuple<int, long, float> t3;
t2 = t1;
t3 = t1;
EXPECT_EQ(t1, t2);
EXPECT_EQ(t2, t3);
}
// move assignment
TEST(pod_tuple_mv_assgn, mv_assgn)
{
pod_tuple<int, long, float> t0{4, 7l, 3.0f};
pod_tuple<int, long, float> t1{4, 7l, 3.0f};
pod_tuple<int, long, float> t2;
pod_tuple<int, long, float> t3;
t2 = std::move(t1);
EXPECT_EQ(t2, t0);
t3 = std::move(t2);
EXPECT_EQ(t3, t0);
}
// swap
TEST(pod_tuple_swap, swap)
{
pod_tuple<int, long, float> t0{4, 7l, 3.0f};
pod_tuple<int, long, float> t1{4, 7l, 3.0f};
pod_tuple<int, long, float> t2{};
pod_tuple<int, long, float> t3{};
std::swap(t1, t2);
EXPECT_EQ(t2, t0);
EXPECT_EQ(t1, t3);
}
// get<1>
TEST(pod_tuple_get_i, get_i)
{
pod_tuple<int, long, float> t0{4, 7l, 3.0f};
static_assert(std::is_same_v<decltype(seqan3::get<0>(t0)), int &>);
static_assert(std::is_same_v<decltype(seqan3::get<1>(t0)), long &>);
static_assert(std::is_same_v<decltype(seqan3::get<2>(t0)), float &>);
EXPECT_EQ(seqan3::get<0>(t0), 4);
EXPECT_EQ(seqan3::get<1>(t0), 7l);
EXPECT_EQ(seqan3::get<2>(t0), 3.0f);
}
// std::get<1>
TEST(pod_tuple, stdget_i)
{
pod_tuple<int, long, float> t0{4, 7l, 3.0f};
static_assert(std::is_same_v<decltype(std::get<0>(t0)), int &>);
static_assert(std::is_same_v<decltype(std::get<1>(t0)), long &>);
static_assert(std::is_same_v<decltype(std::get<2>(t0)), float &>);
EXPECT_EQ(std::get<0>(t0), 4);
EXPECT_EQ(std::get<1>(t0), 7l);
EXPECT_EQ(std::get<2>(t0), 3.0f);
}
// structured bindings
TEST(pod_tuple_struct_binding, struct_binding)
{
pod_tuple<int, long, float> t0{4, 7l, 3.0f};
auto [ i, l, f ] = t0;
EXPECT_EQ(i, 4);
EXPECT_EQ(l, 7l);
EXPECT_EQ(f, 3.0f);
}
// get<type>
TEST(pod_tuple_get_type, get_type)
{
using pt = pod_tuple<int, long, float>;
using ptc = pt const;
pt t0{4, 7l, 3.0f};
ptc t1{4, 7l, 3.0f};
static_assert(std::is_same_v<decltype(seqan3::get<int>(t0)), int &>);
static_assert(std::is_same_v<decltype(seqan3::get<long>(t0)), long &>);
static_assert(std::is_same_v<decltype(seqan3::get<float>(t0)), float &>);
static_assert(std::is_same_v<decltype(seqan3::get<int>(t1)), int const &>);
static_assert(std::is_same_v<decltype(seqan3::get<long>(t1)), long const &>);
static_assert(std::is_same_v<decltype(seqan3::get<float>(t1)), float const &>);
static_assert(std::is_same_v<decltype(seqan3::get<int>(pt{4, 7l, 3.0f})), int &&>);
static_assert(std::is_same_v<decltype(seqan3::get<long>(pt{4, 7l, 3.0f})), long &&>);
static_assert(std::is_same_v<decltype(seqan3::get<float>(pt{4, 7l, 3.0f})), float &&>);
static_assert(std::is_same_v<decltype(seqan3::get<int>(ptc{4, 7l, 3.0f})), int const &&>);
static_assert(std::is_same_v<decltype(seqan3::get<long>(ptc{4, 7l, 3.0f})), long const &&>);
static_assert(std::is_same_v<decltype(seqan3::get<float>(ptc{4, 7l, 3.0f})), float const &&>);
EXPECT_EQ(seqan3::get<int>(t0), 4);
EXPECT_EQ(seqan3::get<long>(t0), 7l);
EXPECT_EQ(seqan3::get<float>(t0), 3.0f);
EXPECT_EQ(seqan3::get<int>(t1), 4);
EXPECT_EQ(seqan3::get<long>(t1), 7l);
EXPECT_EQ(seqan3::get<float>(t1), 3.0f);
EXPECT_EQ(seqan3::get<int>(pt{4, 7l, 3.0f}), 4);
EXPECT_EQ(seqan3::get<long>(pt{4, 7l, 3.0f}), 7l);
EXPECT_EQ(seqan3::get<float>(pt{4, 7l, 3.0f}), 3.0f);
EXPECT_EQ(seqan3::get<int>(ptc{4, 7l, 3.0f}), 4);
EXPECT_EQ(seqan3::get<long>(ptc{4, 7l, 3.0f}), 7l);
EXPECT_EQ(seqan3::get<float>(ptc{4, 7l, 3.0f}), 3.0f);
}
// std::get<type>
TEST(pod_tuple_get_type, stdget_type)
{
using pt = pod_tuple<int, long, float>;
using ptc = pt const;
pt t0{4, 7l, 3.0f};
ptc t1{4, 7l, 3.0f};
static_assert(std::is_same_v<decltype(std::get<int>(t0)), int &>);
static_assert(std::is_same_v<decltype(std::get<long>(t0)), long &>);
static_assert(std::is_same_v<decltype(std::get<float>(t0)), float &>);
static_assert(std::is_same_v<decltype(std::get<int>(t1)), int const &>);
static_assert(std::is_same_v<decltype(std::get<long>(t1)), long const &>);
static_assert(std::is_same_v<decltype(std::get<float>(t1)), float const &>);
static_assert(std::is_same_v<decltype(std::get<int>(pt{4, 7l, 3.0f})), int &&>);
static_assert(std::is_same_v<decltype(std::get<long>(pt{4, 7l, 3.0f})), long &&>);
static_assert(std::is_same_v<decltype(std::get<float>(pt{4, 7l, 3.0f})), float &&>);
static_assert(std::is_same_v<decltype(std::get<int>(ptc{4, 7l, 3.0f})), int const &&>);
static_assert(std::is_same_v<decltype(std::get<long>(ptc{4, 7l, 3.0f})), long const &&>);
static_assert(std::is_same_v<decltype(std::get<float>(ptc{4, 7l, 3.0f})), float const &&>);
EXPECT_EQ(std::get<int>(t0), 4);
EXPECT_EQ(std::get<long>(t0), 7l);
EXPECT_EQ(std::get<float>(t0), 3.0f);
EXPECT_EQ(std::get<int>(t1), 4);
EXPECT_EQ(std::get<long>(t1), 7l);
EXPECT_EQ(std::get<float>(t1), 3.0f);
EXPECT_EQ(std::get<int>(pt{4, 7l, 3.0f}), 4);
EXPECT_EQ(std::get<long>(pt{4, 7l, 3.0f}), 7l);
EXPECT_EQ(std::get<float>(pt{4, 7l, 3.0f}), 3.0f);
EXPECT_EQ(std::get<int>(ptc{4, 7l, 3.0f}), 4);
EXPECT_EQ(std::get<long>(ptc{4, 7l, 3.0f}), 7l);
EXPECT_EQ(std::get<float>(ptc{4, 7l, 3.0f}), 3.0f);
}
// std::tuple_element
TEST(pod_tuple_tuple_element, tuple_element)
{
using pt = pod_tuple<int, long, float>;
static_assert(std::is_same_v<std::tuple_element_t<0, pt>, int>);
static_assert(std::is_same_v<std::tuple_element_t<1, pt>, long>);
static_assert(std::is_same_v<std::tuple_element_t<2, pt>, float>);
static_assert(std::tuple_size_v<pt> == 3);
}
// type deduction
TEST(pod_tuple_type_deduce, type_deduce)
{
pod_tuple t0{4, 7l, 3.0f};
using pt = decltype(t0);
static_assert(std::is_same_v<std::tuple_element_t<0, pt>, int>);
static_assert(std::is_same_v<std::tuple_element_t<1, pt>, long>);
static_assert(std::is_same_v<std::tuple_element_t<2, pt>, float>);
}
// comparison operators
TEST(pod_tuple_cmp, cmp)
{
pod_tuple<int, long, float> t0{4, 6l, 4.0f};
pod_tuple<int, long, float> t1{4, 7l, 3.0f};
pod_tuple<int, long, float> t2{4, 7l, 4.0f};
EXPECT_LT(t0, t1);
EXPECT_LE(t0, t1);
EXPECT_LE(t1, t1);
EXPECT_EQ(t1, t1);
EXPECT_GE(t1, t1);
EXPECT_GE(t2, t1);
EXPECT_GT(t2, t1);
}
|
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/imm/model/ListImagesResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Imm;
using namespace AlibabaCloud::Imm::Model;
ListImagesResult::ListImagesResult() :
ServiceResult()
{}
ListImagesResult::ListImagesResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
ListImagesResult::~ListImagesResult()
{}
void ListImagesResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allImagesNode = value["Images"]["ImagesItem"];
for (auto valueImagesImagesItem : allImagesNode)
{
ImagesItem imagesObject;
if(!valueImagesImagesItem["FacesModifyTime"].isNull())
imagesObject.facesModifyTime = valueImagesImagesItem["FacesModifyTime"].asString();
if(!valueImagesImagesItem["OCRModifyTime"].isNull())
imagesObject.oCRModifyTime = valueImagesImagesItem["OCRModifyTime"].asString();
if(!valueImagesImagesItem["OCRStatus"].isNull())
imagesObject.oCRStatus = valueImagesImagesItem["OCRStatus"].asString();
if(!valueImagesImagesItem["SourcePosition"].isNull())
imagesObject.sourcePosition = valueImagesImagesItem["SourcePosition"].asString();
if(!valueImagesImagesItem["Exif"].isNull())
imagesObject.exif = valueImagesImagesItem["Exif"].asString();
if(!valueImagesImagesItem["ImageUri"].isNull())
imagesObject.imageUri = valueImagesImagesItem["ImageUri"].asString();
if(!valueImagesImagesItem["ImageWidth"].isNull())
imagesObject.imageWidth = std::stoi(valueImagesImagesItem["ImageWidth"].asString());
if(!valueImagesImagesItem["ImageFormat"].isNull())
imagesObject.imageFormat = valueImagesImagesItem["ImageFormat"].asString();
if(!valueImagesImagesItem["SourceType"].isNull())
imagesObject.sourceType = valueImagesImagesItem["SourceType"].asString();
if(!valueImagesImagesItem["ModifyTime"].isNull())
imagesObject.modifyTime = valueImagesImagesItem["ModifyTime"].asString();
if(!valueImagesImagesItem["FileSize"].isNull())
imagesObject.fileSize = std::stoi(valueImagesImagesItem["FileSize"].asString());
if(!valueImagesImagesItem["SourceUri"].isNull())
imagesObject.sourceUri = valueImagesImagesItem["SourceUri"].asString();
if(!valueImagesImagesItem["CreateTime"].isNull())
imagesObject.createTime = valueImagesImagesItem["CreateTime"].asString();
if(!valueImagesImagesItem["FacesStatus"].isNull())
imagesObject.facesStatus = valueImagesImagesItem["FacesStatus"].asString();
if(!valueImagesImagesItem["RemarksA"].isNull())
imagesObject.remarksA = valueImagesImagesItem["RemarksA"].asString();
if(!valueImagesImagesItem["ImageHeight"].isNull())
imagesObject.imageHeight = std::stoi(valueImagesImagesItem["ImageHeight"].asString());
if(!valueImagesImagesItem["RemarksB"].isNull())
imagesObject.remarksB = valueImagesImagesItem["RemarksB"].asString();
if(!valueImagesImagesItem["ImageTime"].isNull())
imagesObject.imageTime = valueImagesImagesItem["ImageTime"].asString();
if(!valueImagesImagesItem["Orientation"].isNull())
imagesObject.orientation = valueImagesImagesItem["Orientation"].asString();
if(!valueImagesImagesItem["Location"].isNull())
imagesObject.location = valueImagesImagesItem["Location"].asString();
if(!valueImagesImagesItem["OCRFailReason"].isNull())
imagesObject.oCRFailReason = valueImagesImagesItem["OCRFailReason"].asString();
if(!valueImagesImagesItem["FacesFailReason"].isNull())
imagesObject.facesFailReason = valueImagesImagesItem["FacesFailReason"].asString();
if(!valueImagesImagesItem["TagsFailReason"].isNull())
imagesObject.tagsFailReason = valueImagesImagesItem["TagsFailReason"].asString();
if(!valueImagesImagesItem["TagsModifyTime"].isNull())
imagesObject.tagsModifyTime = valueImagesImagesItem["TagsModifyTime"].asString();
if(!valueImagesImagesItem["CelebrityStatus"].isNull())
imagesObject.celebrityStatus = valueImagesImagesItem["CelebrityStatus"].asString();
if(!valueImagesImagesItem["CelebrityModifyTime"].isNull())
imagesObject.celebrityModifyTime = valueImagesImagesItem["CelebrityModifyTime"].asString();
if(!valueImagesImagesItem["CelebrityFailReason"].isNull())
imagesObject.celebrityFailReason = valueImagesImagesItem["CelebrityFailReason"].asString();
if(!valueImagesImagesItem["TagsStatus"].isNull())
imagesObject.tagsStatus = valueImagesImagesItem["TagsStatus"].asString();
if(!valueImagesImagesItem["RemarksC"].isNull())
imagesObject.remarksC = valueImagesImagesItem["RemarksC"].asString();
if(!valueImagesImagesItem["RemarksD"].isNull())
imagesObject.remarksD = valueImagesImagesItem["RemarksD"].asString();
if(!valueImagesImagesItem["ExternalId"].isNull())
imagesObject.externalId = valueImagesImagesItem["ExternalId"].asString();
if(!valueImagesImagesItem["AddressModifyTime"].isNull())
imagesObject.addressModifyTime = valueImagesImagesItem["AddressModifyTime"].asString();
if(!valueImagesImagesItem["AddressStatus"].isNull())
imagesObject.addressStatus = valueImagesImagesItem["AddressStatus"].asString();
if(!valueImagesImagesItem["AddressFailReason"].isNull())
imagesObject.addressFailReason = valueImagesImagesItem["AddressFailReason"].asString();
if(!valueImagesImagesItem["RemarksArrayA"].isNull())
imagesObject.remarksArrayA = valueImagesImagesItem["RemarksArrayA"].asString();
if(!valueImagesImagesItem["RemarksArrayB"].isNull())
imagesObject.remarksArrayB = valueImagesImagesItem["RemarksArrayB"].asString();
if(!valueImagesImagesItem["ImageQualityStatus"].isNull())
imagesObject.imageQualityStatus = valueImagesImagesItem["ImageQualityStatus"].asString();
if(!valueImagesImagesItem["ImageQualityFailReason"].isNull())
imagesObject.imageQualityFailReason = valueImagesImagesItem["ImageQualityFailReason"].asString();
if(!valueImagesImagesItem["ImageQualityModifyTime"].isNull())
imagesObject.imageQualityModifyTime = valueImagesImagesItem["ImageQualityModifyTime"].asString();
if(!valueImagesImagesItem["CroppingSuggestionStatus"].isNull())
imagesObject.croppingSuggestionStatus = valueImagesImagesItem["CroppingSuggestionStatus"].asString();
if(!valueImagesImagesItem["CroppingSuggestionFailReason"].isNull())
imagesObject.croppingSuggestionFailReason = valueImagesImagesItem["CroppingSuggestionFailReason"].asString();
if(!valueImagesImagesItem["CroppingSuggestionModifyTime"].isNull())
imagesObject.croppingSuggestionModifyTime = valueImagesImagesItem["CroppingSuggestionModifyTime"].asString();
auto allCroppingSuggestionNode = valueImagesImagesItem["CroppingSuggestion"]["CroppingSuggestionItem"];
for (auto valueImagesImagesItemCroppingSuggestionCroppingSuggestionItem : allCroppingSuggestionNode)
{
ImagesItem::CroppingSuggestionItem croppingSuggestionObject;
if(!valueImagesImagesItemCroppingSuggestionCroppingSuggestionItem["AspectRatio"].isNull())
croppingSuggestionObject.aspectRatio = valueImagesImagesItemCroppingSuggestionCroppingSuggestionItem["AspectRatio"].asString();
if(!valueImagesImagesItemCroppingSuggestionCroppingSuggestionItem["Score"].isNull())
croppingSuggestionObject.score = std::stof(valueImagesImagesItemCroppingSuggestionCroppingSuggestionItem["Score"].asString());
auto croppingBoundaryNode = value["CroppingBoundary"];
if(!croppingBoundaryNode["Width"].isNull())
croppingSuggestionObject.croppingBoundary.width = std::stoi(croppingBoundaryNode["Width"].asString());
if(!croppingBoundaryNode["Height"].isNull())
croppingSuggestionObject.croppingBoundary.height = std::stoi(croppingBoundaryNode["Height"].asString());
if(!croppingBoundaryNode["Left"].isNull())
croppingSuggestionObject.croppingBoundary.left = std::stoi(croppingBoundaryNode["Left"].asString());
if(!croppingBoundaryNode["Top"].isNull())
croppingSuggestionObject.croppingBoundary.top = std::stoi(croppingBoundaryNode["Top"].asString());
imagesObject.croppingSuggestion.push_back(croppingSuggestionObject);
}
auto allFacesNode = valueImagesImagesItem["Faces"]["FacesItem"];
for (auto valueImagesImagesItemFacesFacesItem : allFacesNode)
{
ImagesItem::FacesItem facesObject;
if(!valueImagesImagesItemFacesFacesItem["Age"].isNull())
facesObject.age = std::stoi(valueImagesImagesItemFacesFacesItem["Age"].asString());
if(!valueImagesImagesItemFacesFacesItem["GenderConfidence"].isNull())
facesObject.genderConfidence = std::stof(valueImagesImagesItemFacesFacesItem["GenderConfidence"].asString());
if(!valueImagesImagesItemFacesFacesItem["Attractive"].isNull())
facesObject.attractive = std::stof(valueImagesImagesItemFacesFacesItem["Attractive"].asString());
if(!valueImagesImagesItemFacesFacesItem["Gender"].isNull())
facesObject.gender = valueImagesImagesItemFacesFacesItem["Gender"].asString();
if(!valueImagesImagesItemFacesFacesItem["FaceConfidence"].isNull())
facesObject.faceConfidence = std::stof(valueImagesImagesItemFacesFacesItem["FaceConfidence"].asString());
if(!valueImagesImagesItemFacesFacesItem["Emotion"].isNull())
facesObject.emotion = valueImagesImagesItemFacesFacesItem["Emotion"].asString();
if(!valueImagesImagesItemFacesFacesItem["FaceId"].isNull())
facesObject.faceId = valueImagesImagesItemFacesFacesItem["FaceId"].asString();
if(!valueImagesImagesItemFacesFacesItem["EmotionConfidence"].isNull())
facesObject.emotionConfidence = std::stof(valueImagesImagesItemFacesFacesItem["EmotionConfidence"].asString());
if(!valueImagesImagesItemFacesFacesItem["GroupId"].isNull())
facesObject.groupId = valueImagesImagesItemFacesFacesItem["GroupId"].asString();
if(!valueImagesImagesItemFacesFacesItem["FaceQuality"].isNull())
facesObject.faceQuality = std::stof(valueImagesImagesItemFacesFacesItem["FaceQuality"].asString());
auto emotionDetailsNode = value["EmotionDetails"];
if(!emotionDetailsNode["SAD"].isNull())
facesObject.emotionDetails.sAD = std::stof(emotionDetailsNode["SAD"].asString());
if(!emotionDetailsNode["CALM"].isNull())
facesObject.emotionDetails.cALM = std::stof(emotionDetailsNode["CALM"].asString());
if(!emotionDetailsNode["ANGRY"].isNull())
facesObject.emotionDetails.aNGRY = std::stof(emotionDetailsNode["ANGRY"].asString());
if(!emotionDetailsNode["HAPPY"].isNull())
facesObject.emotionDetails.hAPPY = std::stof(emotionDetailsNode["HAPPY"].asString());
if(!emotionDetailsNode["SCARED"].isNull())
facesObject.emotionDetails.sCARED = std::stof(emotionDetailsNode["SCARED"].asString());
if(!emotionDetailsNode["DISGUSTED"].isNull())
facesObject.emotionDetails.dISGUSTED = std::stof(emotionDetailsNode["DISGUSTED"].asString());
if(!emotionDetailsNode["SURPRISED"].isNull())
facesObject.emotionDetails.sURPRISED = std::stof(emotionDetailsNode["SURPRISED"].asString());
auto faceAttributesNode = value["FaceAttributes"];
if(!faceAttributesNode["GlassesConfidence"].isNull())
facesObject.faceAttributes.glassesConfidence = std::stof(faceAttributesNode["GlassesConfidence"].asString());
if(!faceAttributesNode["Glasses"].isNull())
facesObject.faceAttributes.glasses = faceAttributesNode["Glasses"].asString();
if(!faceAttributesNode["RaceConfidence"].isNull())
facesObject.faceAttributes.raceConfidence = std::stof(faceAttributesNode["RaceConfidence"].asString());
if(!faceAttributesNode["Beard"].isNull())
facesObject.faceAttributes.beard = faceAttributesNode["Beard"].asString();
if(!faceAttributesNode["MaskConfidence"].isNull())
facesObject.faceAttributes.maskConfidence = std::stof(faceAttributesNode["MaskConfidence"].asString());
if(!faceAttributesNode["Race"].isNull())
facesObject.faceAttributes.race = faceAttributesNode["Race"].asString();
if(!faceAttributesNode["BeardConfidence"].isNull())
facesObject.faceAttributes.beardConfidence = std::stof(faceAttributesNode["BeardConfidence"].asString());
if(!faceAttributesNode["Mask"].isNull())
facesObject.faceAttributes.mask = faceAttributesNode["Mask"].asString();
auto faceBoundaryNode = faceAttributesNode["FaceBoundary"];
if(!faceBoundaryNode["Top"].isNull())
facesObject.faceAttributes.faceBoundary.top = std::stoi(faceBoundaryNode["Top"].asString());
if(!faceBoundaryNode["Height"].isNull())
facesObject.faceAttributes.faceBoundary.height = std::stoi(faceBoundaryNode["Height"].asString());
if(!faceBoundaryNode["Width"].isNull())
facesObject.faceAttributes.faceBoundary.width = std::stoi(faceBoundaryNode["Width"].asString());
if(!faceBoundaryNode["Left"].isNull())
facesObject.faceAttributes.faceBoundary.left = std::stoi(faceBoundaryNode["Left"].asString());
auto headPoseNode = faceAttributesNode["HeadPose"];
if(!headPoseNode["Pitch"].isNull())
facesObject.faceAttributes.headPose.pitch = std::stof(headPoseNode["Pitch"].asString());
if(!headPoseNode["Roll"].isNull())
facesObject.faceAttributes.headPose.roll = std::stof(headPoseNode["Roll"].asString());
if(!headPoseNode["Yaw"].isNull())
facesObject.faceAttributes.headPose.yaw = std::stof(headPoseNode["Yaw"].asString());
imagesObject.faces.push_back(facesObject);
}
auto allTagsNode = valueImagesImagesItem["Tags"]["TagsItem"];
for (auto valueImagesImagesItemTagsTagsItem : allTagsNode)
{
ImagesItem::TagsItem tagsObject;
if(!valueImagesImagesItemTagsTagsItem["TagConfidence"].isNull())
tagsObject.tagConfidence = std::stof(valueImagesImagesItemTagsTagsItem["TagConfidence"].asString());
if(!valueImagesImagesItemTagsTagsItem["TagLevel"].isNull())
tagsObject.tagLevel = std::stoi(valueImagesImagesItemTagsTagsItem["TagLevel"].asString());
if(!valueImagesImagesItemTagsTagsItem["TagName"].isNull())
tagsObject.tagName = valueImagesImagesItemTagsTagsItem["TagName"].asString();
if(!valueImagesImagesItemTagsTagsItem["ParentTagName"].isNull())
tagsObject.parentTagName = valueImagesImagesItemTagsTagsItem["ParentTagName"].asString();
imagesObject.tags.push_back(tagsObject);
}
auto allOCRNode = valueImagesImagesItem["OCR"]["OCRItem"];
for (auto valueImagesImagesItemOCROCRItem : allOCRNode)
{
ImagesItem::OCRItem oCRObject;
if(!valueImagesImagesItemOCROCRItem["OCRContents"].isNull())
oCRObject.oCRContents = valueImagesImagesItemOCROCRItem["OCRContents"].asString();
if(!valueImagesImagesItemOCROCRItem["OCRConfidence"].isNull())
oCRObject.oCRConfidence = std::stof(valueImagesImagesItemOCROCRItem["OCRConfidence"].asString());
auto oCRBoundaryNode = value["OCRBoundary"];
if(!oCRBoundaryNode["Left"].isNull())
oCRObject.oCRBoundary.left = std::stoi(oCRBoundaryNode["Left"].asString());
if(!oCRBoundaryNode["Left"].isNull())
oCRObject.oCRBoundary.left1 = std::stoi(oCRBoundaryNode["Left"].asString());
if(!oCRBoundaryNode["Width"].isNull())
oCRObject.oCRBoundary.width = std::stoi(oCRBoundaryNode["Width"].asString());
if(!oCRBoundaryNode["Height"].isNull())
oCRObject.oCRBoundary.height = std::stoi(oCRBoundaryNode["Height"].asString());
imagesObject.oCR.push_back(oCRObject);
}
auto allCelebrityNode = valueImagesImagesItem["Celebrity"]["CelebrityItem"];
for (auto valueImagesImagesItemCelebrityCelebrityItem : allCelebrityNode)
{
ImagesItem::CelebrityItem celebrityObject;
if(!valueImagesImagesItemCelebrityCelebrityItem["CelebrityName"].isNull())
celebrityObject.celebrityName = valueImagesImagesItemCelebrityCelebrityItem["CelebrityName"].asString();
if(!valueImagesImagesItemCelebrityCelebrityItem["CelebrityGender"].isNull())
celebrityObject.celebrityGender = valueImagesImagesItemCelebrityCelebrityItem["CelebrityGender"].asString();
if(!valueImagesImagesItemCelebrityCelebrityItem["CelebrityConfidence"].isNull())
celebrityObject.celebrityConfidence = std::stof(valueImagesImagesItemCelebrityCelebrityItem["CelebrityConfidence"].asString());
if(!valueImagesImagesItemCelebrityCelebrityItem["CelebrityLibraryName"].isNull())
celebrityObject.celebrityLibraryName = valueImagesImagesItemCelebrityCelebrityItem["CelebrityLibraryName"].asString();
auto celebrityBoundaryNode = value["CelebrityBoundary"];
if(!celebrityBoundaryNode["Left"].isNull())
celebrityObject.celebrityBoundary.left = std::stoi(celebrityBoundaryNode["Left"].asString());
if(!celebrityBoundaryNode["Top"].isNull())
celebrityObject.celebrityBoundary.top = std::stoi(celebrityBoundaryNode["Top"].asString());
if(!celebrityBoundaryNode["Width"].isNull())
celebrityObject.celebrityBoundary.width = std::stoi(celebrityBoundaryNode["Width"].asString());
if(!celebrityBoundaryNode["Height"].isNull())
celebrityObject.celebrityBoundary.height = std::stoi(celebrityBoundaryNode["Height"].asString());
imagesObject.celebrity.push_back(celebrityObject);
}
auto imageQualityNode = value["ImageQuality"];
if(!imageQualityNode["OverallScore"].isNull())
imagesObject.imageQuality.overallScore = std::stof(imageQualityNode["OverallScore"].asString());
if(!imageQualityNode["ClarityScore"].isNull())
imagesObject.imageQuality.clarityScore = std::stof(imageQualityNode["ClarityScore"].asString());
if(!imageQualityNode["Clarity"].isNull())
imagesObject.imageQuality.clarity = std::stof(imageQualityNode["Clarity"].asString());
if(!imageQualityNode["ExposureScore"].isNull())
imagesObject.imageQuality.exposureScore = std::stof(imageQualityNode["ExposureScore"].asString());
if(!imageQualityNode["Exposure"].isNull())
imagesObject.imageQuality.exposure = std::stof(imageQualityNode["Exposure"].asString());
if(!imageQualityNode["ContrastScore"].isNull())
imagesObject.imageQuality.contrastScore = std::stof(imageQualityNode["ContrastScore"].asString());
if(!imageQualityNode["Contrast"].isNull())
imagesObject.imageQuality.contrast = std::stof(imageQualityNode["Contrast"].asString());
if(!imageQualityNode["ColorScore"].isNull())
imagesObject.imageQuality.colorScore = std::stof(imageQualityNode["ColorScore"].asString());
if(!imageQualityNode["Color"].isNull())
imagesObject.imageQuality.color = std::stof(imageQualityNode["Color"].asString());
if(!imageQualityNode["CompositionScore"].isNull())
imagesObject.imageQuality.compositionScore = std::stof(imageQualityNode["CompositionScore"].asString());
auto addressNode = value["Address"];
if(!addressNode["AddressLine"].isNull())
imagesObject.address.addressLine = addressNode["AddressLine"].asString();
if(!addressNode["Country"].isNull())
imagesObject.address.country = addressNode["Country"].asString();
if(!addressNode["Province"].isNull())
imagesObject.address.province = addressNode["Province"].asString();
if(!addressNode["City"].isNull())
imagesObject.address.city = addressNode["City"].asString();
if(!addressNode["District"].isNull())
imagesObject.address.district = addressNode["District"].asString();
if(!addressNode["Township"].isNull())
imagesObject.address.township = addressNode["Township"].asString();
images_.push_back(imagesObject);
}
if(!value["SetId"].isNull())
setId_ = value["SetId"].asString();
if(!value["NextMarker"].isNull())
nextMarker_ = value["NextMarker"].asString();
}
std::vector<ListImagesResult::ImagesItem> ListImagesResult::getImages()const
{
return images_;
}
std::string ListImagesResult::getSetId()const
{
return setId_;
}
std::string ListImagesResult::getNextMarker()const
{
return nextMarker_;
}
|
/******************************************************************************
* Copyright 2018 The Apollo 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.
*****************************************************************************/
/**
* @file
* @brief This file provides the implementation of the class "NaviPathDecider".
*/
#include "modules/planning/navi/decider/navi_path_decider.h"
#include <algorithm>
#include <limits>
#include <utility>
#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/common/log.h"
#include "modules/common/math/vec2d.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/proto/sl_boundary.pb.h"
namespace apollo {
namespace planning {
using apollo::common::Status;
using apollo::common::math::Box2d;
using apollo::common::math::Vec2d;
NaviPathDecider::NaviPathDecider() : Task("NaviPathDecider") {
// TODO(all): Add your other initialization.
}
bool NaviPathDecider::Init(const PlanningConfig& config) {
move_dest_lane_config_talbe_.clear();
max_speed_levels_.clear();
config_ = config.navi_planner_config().navi_path_decider_config();
auto move_dest_lane_config_talbe = config_.move_dest_lane_config_talbe();
for (const auto& item : move_dest_lane_config_talbe.lateral_shift()) {
double max_speed_level = item.max_speed();
double max_move_dest_lane_shift_y = item.max_move_dest_lane_shift_y();
if (move_dest_lane_config_talbe_.find(max_speed_level) ==
move_dest_lane_config_talbe_.end()) {
move_dest_lane_config_talbe_.emplace(
std::make_pair(max_speed_level, max_move_dest_lane_shift_y));
max_speed_levels_.push_back(max_speed_level);
}
}
AINFO << "Maximum speeds and move to dest lane config: ";
for (const auto& data : move_dest_lane_config_talbe_) {
auto max_speed = data.first;
auto max_move_dest_lane_shift_y = data.second;
AINFO << "[max_speed : " << max_speed
<< " ,max move dest lane shift y : " << max_move_dest_lane_shift_y
<< "]";
}
max_keep_lane_distance_ = config_.max_keep_lane_distance();
max_keep_lane_shift_y_ = config_.max_keep_lane_shift_y();
min_keep_lane_offset_ = config_.min_keep_lane_offset();
keep_lane_shift_compensation_ = config_.keep_lane_shift_compensation();
start_plan_point_from_ = config_.start_plan_point_from();
move_dest_lane_compensation_ = config_.move_dest_lane_compensation();
is_init_ = obstacle_decider_.Init(config);
return is_init_;
}
Status NaviPathDecider::Execute(Frame* frame,
ReferenceLineInfo* const reference_line_info) {
Task::Execute(frame, reference_line_info);
vehicle_state_ = frame->vehicle_state();
cur_reference_line_lane_id_ = reference_line_info->Lanes().Id();
auto ret = Process(reference_line_info->reference_line(),
frame->PlanningStartPoint(), frame->obstacles(),
reference_line_info->path_decision(),
reference_line_info->mutable_path_data());
RecordDebugInfo(reference_line_info->path_data());
if (ret != Status::OK()) {
reference_line_info->SetDrivable(false);
AERROR << "Reference Line " << reference_line_info->Lanes().Id()
<< " is not drivable after " << Name();
}
return ret;
}
apollo::common::Status NaviPathDecider::Process(
const ReferenceLine& reference_line,
const common::TrajectoryPoint& init_point,
const std::vector<const Obstacle*>& obstacles,
PathDecision* const path_decision, PathData* const path_data) {
CHECK_NOTNULL(path_decision);
CHECK_NOTNULL(path_data);
start_plan_point_.set_x(vehicle_state_.x());
start_plan_point_.set_y(vehicle_state_.y());
start_plan_point_.set_theta(vehicle_state_.heading());
start_plan_v_ = vehicle_state_.linear_velocity();
start_plan_a_ = vehicle_state_.linear_acceleration();
if (start_plan_point_from_ == 1) {
// start plan point from planning schedule
start_plan_point_.set_x(init_point.path_point().x());
start_plan_point_.set_y(init_point.path_point().y());
start_plan_point_.set_theta(init_point.path_point().theta());
start_plan_v_ = init_point.v();
start_plan_a_ = init_point.a();
}
// intercept path points from reference line
std::vector<apollo::common::PathPoint> path_points;
if (!GetBasicPathData(reference_line, &path_points)) {
AERROR << "Get path points from reference line failed";
return Status(apollo::common::ErrorCode::PLANNING_ERROR,
"NaviPathDecider GetBasicPathData");
}
// according to the position of the start plan point and the reference line,
// the path trajectory intercepted from the reference line is shifted on the
// y-axis to adc.
double dest_ref_line_y = path_points[0].y();
ADEBUG << "in current plan cycle, adc to ref line distance : "
<< dest_ref_line_y << "lane id : " << cur_reference_line_lane_id_;
MoveToDestLane(dest_ref_line_y, &path_points);
KeepLane(dest_ref_line_y, &path_points);
DiscretizedPath discretized_path(path_points);
path_data->SetReferenceLine(&(reference_line_info_->reference_line()));
if (!path_data->SetDiscretizedPath(discretized_path)) {
AERROR << "Set path data failed.";
return Status(apollo::common::ErrorCode::PLANNING_ERROR,
"NaviPathDecider SetDiscretizedPath");
}
return Status::OK();
}
void NaviPathDecider::MoveToDestLane(
const double dest_ref_line_y,
std::vector<common::PathPoint>* const path_points) {
double dest_lateral_distance = std::fabs(dest_ref_line_y);
if (dest_lateral_distance < max_keep_lane_distance_) {
return;
}
// calculate lateral shift range and theta chage ratio
double max_shift_y = CalculateDistanceToDestLane();
double actual_start_point_y = std::copysign(max_shift_y, dest_ref_line_y);
// lateral shift path_points to the max_y
double lateral_shift_value = -dest_ref_line_y + actual_start_point_y;
// The steering wheel is more sensitive to the left than to the right and
// requires a compensation value to the right
lateral_shift_value =
lateral_shift_value > 0.0
? (lateral_shift_value - move_dest_lane_compensation_)
: lateral_shift_value;
ADEBUG << "in current plan cycle move to dest lane, adc shift to dest "
"reference line : "
<< lateral_shift_value;
std::transform(path_points->begin(), path_points->end(), path_points->begin(),
[lateral_shift_value](common::PathPoint& old_path_point) {
common::PathPoint new_path_point = old_path_point;
double new_path_point_y =
old_path_point.y() + lateral_shift_value;
new_path_point.set_y(new_path_point_y);
return new_path_point;
});
return;
}
void NaviPathDecider::KeepLane(
const double dest_ref_line_y,
std::vector<common::PathPoint>* const path_points) {
double dest_lateral_distance = std::fabs(dest_ref_line_y);
if (dest_lateral_distance <= max_keep_lane_distance_) {
auto& reference_line = reference_line_info_->reference_line();
auto obstacles = frame_->obstacles();
auto* path_decision = reference_line_info_->path_decision();
double actual_dest_point_y =
NudgeProcess(reference_line, *path_points, obstacles, *path_decision,
vehicle_state_);
double actual_dest_lateral_distance = std::fabs(actual_dest_point_y);
double actual_shift_y = 0.0;
if (actual_dest_lateral_distance > min_keep_lane_offset_) {
double lateral_shift_value = 0.0;
lateral_shift_value =
(actual_dest_lateral_distance < max_keep_lane_shift_y_ +
min_keep_lane_offset_ -
keep_lane_shift_compensation_)
? (actual_dest_lateral_distance - min_keep_lane_offset_ +
keep_lane_shift_compensation_)
: max_keep_lane_shift_y_;
actual_shift_y = std::copysign(lateral_shift_value, actual_dest_point_y);
}
ADEBUG << "in current plan cycle keep lane, actual dest : "
<< actual_dest_point_y << " adc shift to dest : " << actual_shift_y;
std::transform(
path_points->begin(), path_points->end(), path_points->begin(),
[actual_shift_y](common::PathPoint& old_path_point) {
common::PathPoint new_path_point = old_path_point;
double new_path_point_y = old_path_point.y() + actual_shift_y;
new_path_point.set_y(new_path_point_y);
return new_path_point;
});
}
return;
}
void NaviPathDecider::RecordDebugInfo(const PathData& path_data) {
const auto& path_points = path_data.discretized_path().path_points();
auto* ptr_optimized_path = reference_line_info_->mutable_debug()
->mutable_planning_data()
->add_path();
ptr_optimized_path->set_name(Name());
ptr_optimized_path->mutable_path_point()->CopyFrom(
{path_points.begin(), path_points.end()});
}
bool NaviPathDecider::GetBasicPathData(
const ReferenceLine& reference_line,
std::vector<common::PathPoint>* const path_points) {
CHECK_NOTNULL(path_points);
double min_path_len = config_.min_path_length();
// get min path plan lenth s = v0 * t + 1 / 2.0 * a * t^2
double path_len = start_plan_v_ * config_.min_look_forward_time() +
start_plan_a_ * pow(0.1, 2) / 2.0;
path_len = std::max(path_len, min_path_len);
const double reference_line_len = reference_line.Length();
if (reference_line_len < path_len) {
AERROR << "Reference line is too short to generate path trajectory( s = "
<< reference_line_len << ").";
return false;
}
// get the start plan point project s on refernce line and get the length of
// reference line
auto start_plan_point_project = reference_line.GetReferencePoint(
start_plan_point_.x(), start_plan_point_.y());
common::SLPoint sl_point;
if (!reference_line.XYToSL(start_plan_point_project.ToPathPoint(0.0),
&sl_point)) {
AERROR << "Failed to get start plan point s from reference "
"line.";
return false;
}
auto start_plan_point_project_s = sl_point.has_s() ? sl_point.s() : 0.0;
// get basic path points form reference_line
ADEBUG << "Basic path data len ; " << reference_line_len;
constexpr double KDenseSampleUnit = 0.50;
constexpr double KSparseSmapleUnit = 2.0;
for (double s = start_plan_point_project_s; s < reference_line_len;
s += ((s < path_len) ? KDenseSampleUnit : KSparseSmapleUnit)) {
const auto& ref_point = reference_line.GetReferencePoint(s);
auto path_point = ref_point.ToPathPoint(s - start_plan_point_project_s);
path_points->emplace_back(path_point);
}
if (path_points->empty()) {
AERROR << "path poins is empty.";
return false;
}
return true;
}
bool NaviPathDecider::IsSafeChangeLane(const ReferenceLine& reference_line,
const PathDecision& path_decision) {
const auto& adc_param =
common::VehicleConfigHelper::GetConfig().vehicle_param();
Vec2d adc_position(start_plan_point_.x(), start_plan_point_.y());
Vec2d vec_to_center(
(adc_param.front_edge_to_center() - adc_param.back_edge_to_center()) /
2.0,
(adc_param.left_edge_to_center() - adc_param.right_edge_to_center()) /
2.0);
Vec2d adc_center(adc_position +
vec_to_center.rotate(start_plan_point_.theta()));
Box2d adc_box(adc_center, start_plan_point_.theta(), adc_param.length(),
adc_param.width());
SLBoundary adc_sl_boundary;
if (!reference_line.GetSLBoundary(adc_box, &adc_sl_boundary)) {
AERROR << "Failed to get ADC boundary from box: " << adc_box.DebugString();
return false;
}
for (const auto* path_obstacle : path_decision.path_obstacles().Items()) {
const auto& sl_boundary = path_obstacle->PerceptionSLBoundary();
constexpr double kLateralShift = 6.0;
if (sl_boundary.start_l() < -kLateralShift ||
sl_boundary.end_l() > kLateralShift) {
continue;
}
constexpr double kSafeTime = 3.0;
constexpr double kForwardMinSafeDistance = 6.0;
constexpr double kBackwardMinSafeDistance = 8.0;
const double kForwardSafeDistance = std::max(
kForwardMinSafeDistance, ((vehicle_state_.linear_velocity() -
path_obstacle->obstacle()->Speed()) *
kSafeTime));
const double kBackwardSafeDistance = std::max(
kBackwardMinSafeDistance, ((path_obstacle->obstacle()->Speed() -
vehicle_state_.linear_velocity()) *
kSafeTime));
if (sl_boundary.end_s() >
adc_sl_boundary.start_s() - kBackwardSafeDistance &&
sl_boundary.start_s() <
adc_sl_boundary.end_s() + kForwardSafeDistance) {
return false;
}
}
return true;
}
double NaviPathDecider::NudgeProcess(
const ReferenceLine& reference_line,
const std::vector<common::PathPoint>& path_data_points,
const std::vector<const Obstacle*>& obstacles,
const PathDecision& path_decision,
const common::VehicleState& vehicle_state) {
double nudge_position_y = 0.0;
if (!FLAGS_enable_nudge_decision) {
nudge_position_y = path_data_points[0].y();
return nudge_position_y;
}
// get nudge latteral position
int lane_obstacles_num = 0;
constexpr double KNudgeEpsilon = 1e-6;
double nudge_distance = obstacle_decider_.GetNudgeDistance(
obstacles, reference_line, path_decision, path_data_points, vehicle_state,
&lane_obstacles_num);
// adjust plan start point
if (std::fabs(nudge_distance) > KNudgeEpsilon) {
ADEBUG << "need latteral nudge distance : " << nudge_distance;
nudge_position_y = nudge_distance;
last_lane_id_to_nudge_flag_[cur_reference_line_lane_id_] = true;
} else {
// no nudge distance but current lane has obstacles ,keepping path in
// the last nudge path direction
bool last_plan_has_nudge = false;
if (last_lane_id_to_nudge_flag_.find(cur_reference_line_lane_id_) !=
last_lane_id_to_nudge_flag_.end()) {
last_plan_has_nudge =
last_lane_id_to_nudge_flag_[cur_reference_line_lane_id_];
}
if (last_plan_has_nudge && lane_obstacles_num != 0) {
ADEBUG << "Keepping last nudge path direction";
nudge_position_y = vehicle_state_.y();
} else {
// not need nudge or not need nudge keepping
last_lane_id_to_nudge_flag_[cur_reference_line_lane_id_] = false;
nudge_position_y = path_data_points[0].y();
}
}
return nudge_position_y;
}
double NaviPathDecider::CalculateDistanceToDestLane() {
// match an appropriate lateral shift param from the configuration file
// based on the current state of the vehicle state
double move_distance = 0.0;
double max_adc_speed =
start_plan_v_ + start_plan_a_ * 1.0 / FLAGS_planning_loop_rate;
auto max_speed_level_itr = std::upper_bound(
max_speed_levels_.begin(), max_speed_levels_.end(), max_adc_speed);
if (max_speed_level_itr != max_speed_levels_.end()) {
auto max_speed_level = *max_speed_level_itr;
move_distance = move_dest_lane_config_talbe_[max_speed_level];
}
return move_distance;
}
} // namespace planning
} // namespace apollo
|
#include "Tetris.h"
#include <iostream>
Tetris::Tetris()
{
system("pause");
}
|
//
// AKPinkNoiseDSPKernel.hpp
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
#ifndef AKPinkNoiseDSPKernel_hpp
#define AKPinkNoiseDSPKernel_hpp
#import "DSPKernel.hpp"
#import "ParameterRamper.hpp"
#import <AudioKit/AudioKit-Swift.h>
extern "C" {
#include "soundpipe.h"
}
enum {
amplitudeAddress = 0
};
class AKPinkNoiseDSPKernel : public DSPKernel {
public:
// MARK: Member Functions
AKPinkNoiseDSPKernel() {}
void init(int channelCount, double inSampleRate) {
channels = channelCount;
sampleRate = float(inSampleRate);
sp_create(&sp);
sp->sr = sampleRate;
sp->nchan = channels;
sp_pinknoise_create(&pinknoise);
sp_pinknoise_init(sp, pinknoise);
pinknoise->amp = 1;
amplitudeRamper.init();
}
void start() {
started = true;
}
void stop() {
started = false;
}
void destroy() {
sp_pinknoise_destroy(&pinknoise);
sp_destroy(&sp);
}
void reset() {
resetted = true;
amplitudeRamper.reset();
}
void setAmplitude(float value) {
amplitude = clamp(value, 0.0f, 1.0f);
amplitudeRamper.setImmediate(amplitude);
}
void setParameter(AUParameterAddress address, AUValue value) {
switch (address) {
case amplitudeAddress:
amplitudeRamper.setUIValue(clamp(value, 0.0f, 1.0f));
break;
}
}
AUValue getParameter(AUParameterAddress address) {
switch (address) {
case amplitudeAddress:
return amplitudeRamper.getUIValue();
default: return 0.0f;
}
}
void startRamp(AUParameterAddress address, AUValue value, AUAudioFrameCount duration) override {
switch (address) {
case amplitudeAddress:
amplitudeRamper.startRamp(clamp(value, 0.0f, 1.0f), duration);
break;
}
}
void setBuffer(AudioBufferList *outBufferList) {
outBufferListPtr = outBufferList;
}
void process(AUAudioFrameCount frameCount, AUAudioFrameCount bufferOffset) override {
for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) {
int frameOffset = int(frameIndex + bufferOffset);
amplitude = amplitudeRamper.getAndStep();
pinknoise->amp = (float)amplitude;
float temp = 0;
for (int channel = 0; channel < channels; ++channel) {
float *out = (float *)outBufferListPtr->mBuffers[channel].mData + frameOffset;
if (started) {
if (channel == 0) {
sp_pinknoise_compute(sp, pinknoise, nil, &temp);
}
*out = temp;
} else {
*out = 0.0;
}
}
}
}
// MARK: Member Variables
private:
int channels = AKSettings.numberOfChannels;
float sampleRate = AKSettings.sampleRate;
AudioBufferList *outBufferListPtr = nullptr;
sp_data *sp;
sp_pinknoise *pinknoise;
float amplitude = 1;
public:
bool started = false;
bool resetted = false;
ParameterRamper amplitudeRamper = 1;
};
#endif /* AKPinkNoiseDSPKernel_hpp */
|
#pragma once
#include <Register/Utility.hpp>
namespace Kvasir {
//Multi-function Serial Interface 0
namespace Mfs0UartScr{ ///<Serial Control Register
using Addr = Register::Address<0x40038001,0xffffff60,0x00000000,unsigned char>;
///Programmable Clear bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> upcl{};
///Received interrupt enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> rie{};
///Transmit interrupt enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> tie{};
///Transmit bus idle interrupt enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> tbie{};
///Received operation enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> rxe{};
///Transmission operation enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> txe{};
}
namespace Mfs0UartSmr{ ///<Serial Mode Register
using Addr = Register::Address<0x40038000,0xffffff12,0x00000000,unsigned char>;
///Operation mode set bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,5),Register::ReadWriteAccess,unsigned> md{};
///Stop bit length select bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> sbl{};
///Transfer direction select bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> bds{};
///Serial data output enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> soe{};
}
namespace Mfs0UartSsr{ ///<Serial Status Register
using Addr = Register::Address<0x40038005,0xffffff40,0x00000000,unsigned char>;
///Received error flag clear bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> rec{};
///Parity error flag bit (only functions in operation mode 0)
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> pe{};
///Framing error flag bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> fre{};
///Overrun error flag bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ore{};
///Received data full flag bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> rdrf{};
///Transmit data empty flag bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> tdre{};
///Transmit bus idle flag
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> tbi{};
}
namespace Mfs0UartEscr{ ///<Extended Communication Control Register
using Addr = Register::Address<0x40038004,0xffffff00,0x00000000,unsigned char>;
///Flow control enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> flwen{};
///Extension stop bit length select bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> esbl{};
///Inverted serial data format bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> inv{};
///Parity enable bit (only functions in operation mode 0)
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> pen{};
///Parity select bit (only functions in operation mode 0)
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> p{};
///Data length select bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,0),Register::ReadWriteAccess,unsigned> l{};
}
namespace Mfs0UartRdr{ ///<Received Data Register
using Addr = Register::Address<0x40038008,0xfffffe00,0x00000000,unsigned>;
///Data
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> d{};
}
namespace Mfs0UartTdr{ ///<Transmit Data Register
using Addr = Register::Address<0x40038008,0xfffffe00,0x00000000,unsigned>;
///Data
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,0),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> d{};
}
namespace Mfs0UartBgr{ ///<Baud Rate Generator Registers
using Addr = Register::Address<0x4003800c,0xffff0000,0x00000000,unsigned>;
///External clock select bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> ext{};
///Baud Rate Generator Registers 1
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,8),Register::ReadWriteAccess,unsigned> bgr1{};
///Baud Rate Generator Registers 0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> bgr0{};
}
namespace Mfs0UartFcr1{ ///<FIFO Control Register 1
using Addr = Register::Address<0x40038015,0xffffffe0,0x00000000,unsigned char>;
///Re-transmission data lost detect enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> flste{};
///Received FIFO idle detection enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> friie{};
///Transmit FIFO data request bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> fdrq{};
///Transmit FIFO interrupt enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> ftie{};
///FIFO select bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> fsel{};
}
namespace Mfs0UartFcr0{ ///<FIFO Control Register 0
using Addr = Register::Address<0x40038014,0xffffff80,0x00000000,unsigned char>;
///FIFO re-transmit data lost flag bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> flst{};
///FIFO pointer reload bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> fld{};
///FIFO pointer save bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> fset{};
///FIFO2 reset bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> fcl2{};
///FIFO1 reset bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> fcl1{};
///FIFO2 operation enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> fe2{};
///FIFO1 operation enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> fe1{};
}
namespace Mfs0UartFbyte1{ ///<FIFO Byte Register 1
using Addr = Register::Address<0x40038018,0xffffffff,0x00000000,unsigned char>;
}
namespace Mfs0UartFbyte2{ ///<FIFO Byte Register 2
using Addr = Register::Address<0x40038019,0xffffffff,0x00000000,unsigned char>;
}
namespace Mfs0CsioScr{ ///<Serial Control Register
using Addr = Register::Address<0x40038001,0xffffff00,0x00000000,unsigned char>;
///Programmable clear bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> upcl{};
///Master/Slave function select bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> ms{};
///SPI corresponding bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> spi{};
///Received interrupt enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> rie{};
///Transmit interrupt enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> tie{};
///Transmit bus idle interrupt enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> tbie{};
///Data received enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> rxe{};
///Data transmission enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> txe{};
}
namespace Mfs0CsioSmr{ ///<Serial Mode Register
using Addr = Register::Address<0x40038000,0xffffff10,0x00000000,unsigned char>;
///Operation mode set bits
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,5),Register::ReadWriteAccess,unsigned> md{};
///Serial clock invert bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> scinv{};
///Transfer direction select bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> bds{};
///Master mode serial clock output enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> scke{};
///Serial data output enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> soe{};
}
namespace Mfs0CsioSsr{ ///<Serial Status Register
using Addr = Register::Address<0x40038005,0xffffff60,0x00000000,unsigned char>;
///Received error flag clear bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> rec{};
///Access Width Control bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> awc{};
///Overrun error flag bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ore{};
///Received data full flag bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> rdrf{};
///Transmit data empty flag bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> tdre{};
///Transmit bus idle flag bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> tbi{};
}
namespace Mfs0CsioEscr{ ///<Extended Communication Control Register
using Addr = Register::Address<0x40038004,0xffffff00,0x00000000,unsigned char>;
///Serial output pin set bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> sop{};
///Bit3 of Data length select bits
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> l3{};
///Serial Chip Select Format enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> csfe{};
///Data transmit/received wait select bits
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,3),Register::ReadWriteAccess,unsigned> wt{};
///Data length select bits
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,0),Register::ReadWriteAccess,unsigned> l{};
}
namespace Mfs0CsioRdr{ ///<Received Data Register
using Addr = Register::Address<0x40038008,0xffff0000,0x00000000,unsigned>;
///Data
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> d{};
}
namespace Mfs0CsioTdr{ ///<Transmit Data Register
using Addr = Register::Address<0x40038008,0xffff0000,0x00000000,unsigned>;
///Data
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> d{};
}
namespace Mfs0CsioBgr{ ///<Baud Rate Generator Registers
using Addr = Register::Address<0x4003800c,0xffff8000,0x00000000,unsigned>;
///Baud Rate Generator Registers 1
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,8),Register::ReadWriteAccess,unsigned> bgr1{};
///Baud Rate Generator Registers 0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> bgr0{};
}
namespace Mfs0CsioFcr1{ ///<FIFO Control Register 1
using Addr = Register::Address<0x40038015,0xffffffe0,0x00000000,unsigned char>;
///Re-transmission data lost detect enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> flste{};
///Received FIFO idle detection enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> friie{};
///Transmit FIFO data request bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> fdrq{};
///Transmit FIFO interrupt enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> ftie{};
///FIFO select bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> fsel{};
}
namespace Mfs0CsioFcr0{ ///<FIFO Control Register 0
using Addr = Register::Address<0x40038014,0xffffff80,0x00000000,unsigned char>;
///FIFO re-transmit data lost flag bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> flst{};
///FIFO pointer reload bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> fld{};
///FIFO pointer save bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> fset{};
///FIFO2 reset bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> fcl2{};
///FIFO1 reset bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> fcl1{};
///FIFO2 operation enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> fe2{};
///FIFO1 operation enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> fe1{};
}
namespace Mfs0CsioFbyte1{ ///<FIFO Byte Register 1
using Addr = Register::Address<0x40038018,0xffffffff,0x00000000,unsigned char>;
}
namespace Mfs0CsioFbyte2{ ///<FIFO Byte Register 2
using Addr = Register::Address<0x40038019,0xffffffff,0x00000000,unsigned char>;
}
namespace Mfs0CsioScstr0{ ///<Serial Chip Select Timing Register 0
using Addr = Register::Address<0x4003801c,0xffffff00,0x00000000,unsigned char>;
///Serial Chip Select Hold Delay bits
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> cshd{};
}
namespace Mfs0CsioScstr1{ ///<Serial Chip Select Timing Register 1
using Addr = Register::Address<0x4003801d,0xffffff00,0x00000000,unsigned char>;
///Serial Chip Select Setup Delay bits
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> cssu{};
}
namespace Mfs0CsioScstr2{ ///<Serial Chip Select Timing Registers 2/3
using Addr = Register::Address<0x40038020,0xffff0000,0x00000000,unsigned>;
///Serial Chip Deselect bits
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> csds{};
}
namespace Mfs0CsioScstr3{ ///<Serial Chip Select Timing Registers 3
using Addr = Register::Address<0x40038021,0xffffffff,0x00000000,unsigned char>;
}
namespace Mfs0CsioSacsr{ ///<Serial Support Control Register
using Addr = Register::Address<0x40038024,0xffffc620,0x00000000,unsigned>;
///Transfer Byte Error Enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> tbeen{};
///Chip Select Error Interupt Enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> cseie{};
///Chip Select Error Flag
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> cse{};
///Timer Interrupt Flag
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> tint{};
///Timer Interrupt Enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> tinte{};
///Synchronous Transmission Enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> tsyne{};
///Timer Operation Clock Division bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,1),Register::ReadWriteAccess,unsigned> tdiv{};
///Serial Timer Enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> tmre{};
}
namespace Mfs0CsioStmr{ ///<Serial Timer Register
using Addr = Register::Address<0x40038028,0xffff0000,0x00000000,unsigned>;
///Timer Data bits
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> tm{};
}
namespace Mfs0CsioStmcr{ ///<Serial Timer Comparison Register
using Addr = Register::Address<0x4003802c,0xffff0000,0x00000000,unsigned>;
///Compare bits
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> tc{};
}
namespace Mfs0CsioScscr{ ///<Serial Chip Select Control Status Register
using Addr = Register::Address<0x40038030,0xffff0000,0x00000000,unsigned>;
///Serial Chip Select Active Start bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,14),Register::ReadWriteAccess,unsigned> sst{};
///Serial Chip Select Active End bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,12),Register::ReadWriteAccess,unsigned> sed{};
///Serial Chip Select Active Display bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,10),Register::ReadWriteAccess,unsigned> scd{};
///Serial Chip Select Active Hold bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> scam{};
///Serial Chip Select Timing Operation Clock Division bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,6),Register::ReadWriteAccess,unsigned> cdiv{};
///Serial Chip Select Level Setting bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> cslvl{};
///Serial Chip Select Enable bit with SCS3 pin
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> csen3{};
///Serial Chip Select Enable bit with SCS2 pin
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> csen2{};
///Serial Chip Select Enable bit with SCS1 pin
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> csen1{};
///Serial Chip Select Enable bit with SCS0 pin
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> csen0{};
///Serial Chip Select Output Enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> csoe{};
}
namespace Mfs0CsioScsfr0{ ///<Serial Chip Select Format Register 0
using Addr = Register::Address<0x40038034,0xffffff00,0x00000000,unsigned char>;
///Serial Chip Select 1 Level Setting bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> cs1cslvl{};
///Serial Clock Invert bit of Serial Chip Select 1
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> cs1scinv{};
///SPI corresponding bit of Serial Chip Select 1
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> cs1spi{};
///Transfer direction select bit of Serial Chip Select 1
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,0),Register::ReadWriteAccess,unsigned> cs1l{};
}
namespace Mfs0CsioScsfr1{ ///<Serial Chip Select Format Register 1
using Addr = Register::Address<0x40038035,0xffffff00,0x00000000,unsigned char>;
///Serial Chip Select 2 Level Setting bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> cs2cslvl{};
///Serial Clock Invert bit of Serial Chip Select 2
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> cs2scinv{};
///SPI corresponding bit of Serial Chip Select 2
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> cs2spi{};
///Transfer direction select bit of Serial Chip Select 2
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,0),Register::ReadWriteAccess,unsigned> cs2l{};
}
namespace Mfs0CsioScsfr2{ ///<Serial Chip Select Format Register 2
using Addr = Register::Address<0x40038038,0xffffff00,0x00000000,unsigned char>;
///Serial Chip Select 3 Level Setting bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> cs3cslvl{};
///Serial Clock Invert bit of Serial Chip Select 3
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> cs3scinv{};
///SPI corresponding bit of Serial Chip Select 3
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> cs3spi{};
///Transfer direction select bit of Serial Chip Select 3
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,0),Register::ReadWriteAccess,unsigned> cs3l{};
}
namespace Mfs0CsioTbyte0{ ///<Transfer Byte Register 0
using Addr = Register::Address<0x4003803c,0xffffffff,0x00000000,unsigned char>;
}
namespace Mfs0CsioTbyte1{ ///<Transfer Byte Register 1
using Addr = Register::Address<0x4003803d,0xffffffff,0x00000000,unsigned char>;
}
namespace Mfs0CsioTbyte2{ ///<Transfer Byte Register 2
using Addr = Register::Address<0x40038040,0xffffffff,0x00000000,unsigned char>;
}
namespace Mfs0CsioTbyte3{ ///<Transfer Byte Register 3
using Addr = Register::Address<0x40038041,0xffffffff,0x00000000,unsigned char>;
}
namespace Mfs0LinScr{ ///<Serial Control Register
using Addr = Register::Address<0x40038001,0xffffff00,0x00000000,unsigned char>;
///Programmable clear bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> upcl{};
///Master/Slave function select bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> ms{};
///LIN Break Field setting bit (valid in master mode only)
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> lbr{};
///Received interrupt enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> rie{};
///Transmit interrupt enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> tie{};
///Transmit bus idle interrupt enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> tbie{};
///Data reception enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> rxe{};
///Data transmission enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> txe{};
}
namespace Mfs0LinSmr{ ///<Serial Mode Register
using Addr = Register::Address<0x40038000,0xffffff06,0x00000000,unsigned char>;
///Operation mode setting bits
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,5),Register::ReadWriteAccess,unsigned> md{};
///Wake-up control bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> wucr{};
///Stop bit length select bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> sbl{};
///Serial data output enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> soe{};
}
namespace Mfs0LinSsr{ ///<Serial Status Register
using Addr = Register::Address<0x40038005,0xffffff40,0x00000000,unsigned char>;
///Received Error flag clear bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> rec{};
///LIN Break field detection flag bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> lbd{};
///Framing error flag bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> fre{};
///Overrun error flag bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ore{};
///Received data full flag bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> rdrf{};
///Transmit data empty flag bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> tdre{};
///Transmit bus idle flag bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> tbi{};
}
namespace Mfs0LinEscr{ ///<Extended Communication Control Register
using Addr = Register::Address<0x40038004,0xffffffa0,0x00000000,unsigned char>;
///Extended stop bit length select bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> esbl{};
///LIN Break field detect interrupt enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> lbie{};
///LIN Break field length select bits (valid in master mode only)
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,2),Register::ReadWriteAccess,unsigned> lbl{};
///LIN Break delimiter length select bits (valid in master mode only)
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,unsigned> del{};
}
namespace Mfs0LinRdr{ ///<Received Data Register
using Addr = Register::Address<0x40038008,0xffffff00,0x00000000,unsigned>;
///Data
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> d{};
}
namespace Mfs0LinTdr{ ///<Transmit Data Register
using Addr = Register::Address<0x40038008,0xffffff00,0x00000000,unsigned>;
///Data
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> d{};
}
namespace Mfs0LinBgr{ ///<Baud Rate Generator Registers
using Addr = Register::Address<0x4003800c,0xffff0000,0x00000000,unsigned>;
///External clock select bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> ext{};
///Baud Rate Generator Registers 1
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,8),Register::ReadWriteAccess,unsigned> bgr1{};
///Baud Rate Generator Registers 0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> bgr0{};
}
namespace Mfs0LinFcr1{ ///<FIFO Control Register 1
using Addr = Register::Address<0x40038015,0xffffffe0,0x00000000,unsigned char>;
///Re-transmission data lost detect enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> flste{};
///Received FIFO idle detection enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> friie{};
///Transmit FIFO data request bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> fdrq{};
///Transmit FIFO interrupt enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> ftie{};
///FIFO select bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> fsel{};
}
namespace Mfs0LinFcr0{ ///<FIFO Control Register 0
using Addr = Register::Address<0x40038014,0xffffff80,0x00000000,unsigned char>;
///FIFO re-transmit data lost flag bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> flst{};
///FIFO pointer reload bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> fld{};
///FIFO pointer save bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> fset{};
///FIFO2 reset bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> fcl2{};
///FIFO1 reset bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> fcl1{};
///FIFO2 operation enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> fe2{};
///FIFO1 operation enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> fe1{};
}
namespace Mfs0LinFbyte1{ ///<FIFO Byte Register 1
using Addr = Register::Address<0x40038018,0xffffffff,0x00000000,unsigned char>;
}
namespace Mfs0LinFbyte2{ ///<FIFO Byte Register 2
using Addr = Register::Address<0x40038019,0xffffffff,0x00000000,unsigned char>;
}
namespace Mfs0I2cIbcr{ ///<I2C Bus Control Register
using Addr = Register::Address<0x40038001,0xffffff00,0x00000000,unsigned char>;
///Master/slave select bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> mss{};
///Operation flag/iteration start condition generation bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> actScc{};
///Data byte acknowledge enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> acke{};
///Wait selection bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> wsel{};
///Condition detection interrupt enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> cnde{};
///Interrupt enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> inte{};
///Bus error flag bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ber{};
///interrupt flag bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> int_{};
}
namespace Mfs0I2cSmr{ ///<Serial Mode Register
using Addr = Register::Address<0x40038000,0xffffff13,0x00000000,unsigned char>;
///operation mode set bits
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,5),Register::ReadWriteAccess,unsigned> md{};
///Received interrupt enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> rie{};
///Transmit interrupt enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> tie{};
}
namespace Mfs0I2cIbsr{ ///<I2C Bus Status Register
using Addr = Register::Address<0x40038004,0xffffff00,0x00000000,unsigned char>;
///First byte bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> fbt{};
///Acknowledge flag bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> rack{};
///Reserved address detection bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> rsa{};
///Data direction bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> trx{};
///Arbitration lost bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> al{};
///Iteration start condition check bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> rsc{};
///Stop condition check bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> spc{};
///Bus state bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> bb{};
}
namespace Mfs0I2cSsr{ ///<Serial Status Register
using Addr = Register::Address<0x40038005,0xffffff00,0x00000000,unsigned char>;
///Received error flag clear bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> rec{};
///Transmit empty flag set bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> tset{};
///DMA mode enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> dma{};
///Transmit bus idle interrupt enable bit (Effective only when DMA mode is enabled)
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> tbie{};
///Overrun error flag bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ore{};
///Received data full flag bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> rdrf{};
///Transmit data empty flag bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> tdre{};
///Transmit bus idle flag bit (Effective only when DMA mode is enabled)
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> tbi{};
}
namespace Mfs0I2cRdr{ ///<Received Data Register
using Addr = Register::Address<0x40038008,0xffffff00,0x00000000,unsigned>;
///Data
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> d{};
}
namespace Mfs0I2cTdr{ ///<Transmit Data Register
using Addr = Register::Address<0x40038008,0xffffff00,0x00000000,unsigned>;
///Data
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> d{};
}
namespace Mfs0I2cBgr{ ///<Baud Rate Generator Registers
using Addr = Register::Address<0x4003800c,0xffff8000,0x00000000,unsigned>;
///Baud Rate Generator Registers 1
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,8),Register::ReadWriteAccess,unsigned> bgr1{};
///Baud Rate Generator Registers 0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> bgr0{};
}
namespace Mfs0I2cIsmk{ ///<7-bit Slave Address Mask Register
using Addr = Register::Address<0x40038011,0xffffff00,0x00000000,unsigned char>;
///I2C interface operation enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> en{};
///Slave address mask bits
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,0),Register::ReadWriteAccess,unsigned> sm{};
}
namespace Mfs0I2cIsba{ ///<7-bit Slave Address Register
using Addr = Register::Address<0x40038010,0xffffff00,0x00000000,unsigned char>;
///Slave address enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> saen{};
///7-bit slave address
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,0),Register::ReadWriteAccess,unsigned> sa{};
}
namespace Mfs0I2cFcr1{ ///<FIFO Control Register 1
using Addr = Register::Address<0x40038015,0xffffffe0,0x00000000,unsigned char>;
///Re-transmission data lost detect enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> flste{};
///Received FIFO idle detection enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> friie{};
///Transmit FIFO data request bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> fdrq{};
///Transmit FIFO interrupt enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> ftie{};
///FIFO select bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> fsel{};
}
namespace Mfs0I2cFcr0{ ///<FIFO Control Register 0
using Addr = Register::Address<0x40038014,0xffffff80,0x00000000,unsigned char>;
///FIFO re-transmit data lost flag bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> flst{};
///FIFO pointer reload bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> fld{};
///FIFO pointer save bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> fset{};
///FIFO2 reset bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> fcl2{};
///FIFO1 reset bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> fcl1{};
///FIFO2 operation enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> fe2{};
///FIFO1 operation enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> fe1{};
}
namespace Mfs0I2cFbyte1{ ///<FIFO Byte Register 1
using Addr = Register::Address<0x40038018,0xffffffff,0x00000000,unsigned char>;
}
namespace Mfs0I2cFbyte2{ ///<FIFO Byte Register 2
using Addr = Register::Address<0x40038019,0xffffffff,0x00000000,unsigned char>;
}
namespace Mfs0I2cNfcr{ ///<Noise Filter Control Register
using Addr = Register::Address<0x4003801c,0xffffffe0,0x00000000,unsigned char>;
///Noise Filter Time Select bits
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,0),Register::ReadWriteAccess,unsigned> nft{};
}
namespace Mfs0I2cEibcr{ ///<Extension I2C Bus Control Register
using Addr = Register::Address<0x4003801d,0xffffffc0,0x00000000,unsigned char>;
///SDA status bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> sdas{};
///SCL status bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> scls{};
///SDA output control bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> sdac{};
///SCL output control bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> sclc{};
///Serial output enabled bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> soce{};
///Bus error control bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> bec{};
}
}
|
/* $Id: VBoxAboutDlg.cpp 71553 2018-03-28 17:28:44Z vboxsync $ */
/** @file
* VBox Qt GUI - VBoxAboutDlg class implementation.
*/
/*
* Copyright (C) 2006-2018 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#ifdef VBOX_WITH_PRECOMPILED_HEADERS
# include <precomp.h>
#else /* !VBOX_WITH_PRECOMPILED_HEADERS */
/* Qt includes: */
# include <QDialogButtonBox>
# include <QDir>
# include <QEvent>
# include <QLabel>
# include <QPainter>
# include <QPushButton>
# include <QStyle>
# include <QVBoxLayout>
/* GUI includes: */
# include "UIConverter.h"
# include "UIExtraDataManager.h"
# include "UIIconPool.h"
# include "VBoxAboutDlg.h"
# include "VBoxGlobal.h"
/* Other VBox includes: */
# include <iprt/path.h>
# include <VBox/version.h> /* VBOX_VENDOR */
#endif /* !VBOX_WITH_PRECOMPILED_HEADERS */
VBoxAboutDlg::VBoxAboutDlg(QWidget *pParent, const QString &strVersion)
#ifdef VBOX_WS_MAC
// No need for About dialog parent on macOS.
// First of all, non of other native apps (Safari, App Store, iTunes) centers About dialog according the app itself, they do
// it according to screen instead, we should do it as well. Besides that since About dialog is not modal, it will be in
// conflict with modal dialogs if there will be a parent passed, because the dialog will not have own event-loop in that case.
: QIWithRetranslateUI2<QIDialog>(0)
, m_pPseudoParent(pParent)
#else
// On other hosts we will keep the current behavior for now.
// First of all it's quite difficult to find native (Metro UI) Windows app which have About dialog at all. But non-native
// cross-platform apps (Qt Creator, VLC) centers About dialog according the app exactly.
: QIWithRetranslateUI2<QIDialog>(pParent)
, m_pPseudoParent(0)
#endif
, m_strVersion(strVersion)
, m_pMainLayout(0)
, m_pLabel(0)
{
/* Prepare: */
prepare();
}
bool VBoxAboutDlg::event(QEvent *pEvent)
{
/* Set fixed-size for dialog: */
if (pEvent->type() == QEvent::Polish)
setFixedSize(m_size);
/* Call to base-class: */
return QIDialog::event(pEvent);
}
void VBoxAboutDlg::paintEvent(QPaintEvent *)
{
/* Draw About-VirtualBox background image: */
QPainter painter(this);
painter.drawPixmap(0, 0, m_pixmap);
}
void VBoxAboutDlg::retranslateUi()
{
setWindowTitle(tr("VirtualBox - About"));
const QString strAboutText = tr("VirtualBox Graphical User Interface");
#ifdef VBOX_BLEEDING_EDGE
const QString strVersionText = "EXPERIMENTAL build %1 - " + QString(VBOX_BLEEDING_EDGE);
#else
const QString strVersionText = tr("Version %1");
#endif
#ifdef VBOX_OSE
m_strAboutText = strAboutText + " " + strVersionText.arg(m_strVersion) + "\n"
+ QString("%1 2004-" VBOX_C_YEAR " " VBOX_VENDOR).arg(QChar(0xa9));
#else
m_strAboutText = strAboutText + "\n" + strVersionText.arg(m_strVersion);
#endif
m_strAboutText = m_strAboutText + QString(" (Qt%1)").arg(qVersion());
m_strAboutText = m_strAboutText + "\n" + QString("Copyright %1 %2 %3 and/or its affiliates. All rights reserved.")
.arg(QChar(0xa9)).arg(VBOX_C_YEAR).arg(VBOX_VENDOR);
AssertPtrReturnVoid(m_pLabel);
m_pLabel->setText(m_strAboutText);
}
void VBoxAboutDlg::prepare()
{
/* Delete dialog on close: */
setAttribute(Qt::WA_DeleteOnClose);
/* Make sure the dialog is deleted on pseudo-parent destruction: */
if (m_pPseudoParent)
connect(m_pPseudoParent, &QObject::destroyed, this, &VBoxAboutDlg::close);
/* Choose default image: */
QString strPath(":/about.png");
/* Branding: Use a custom about splash picture if set: */
const QString strSplash = vboxGlobal().brandingGetKey("UI/AboutSplash");
if (vboxGlobal().brandingIsActive() && !strSplash.isEmpty())
{
char szExecPath[1024];
RTPathExecDir(szExecPath, 1024);
QString strTmpPath = QString("%1/%2").arg(szExecPath).arg(strSplash);
if (QFile::exists(strTmpPath))
strPath = strTmpPath;
}
/* Load image: */
const int iIconMetric = QApplication::style()->pixelMetric(QStyle::PM_LargeIconSize);
const double dRatio = (double)iIconMetric / 32;
const QIcon icon = UIIconPool::iconSet(strPath);
m_size = icon.availableSizes().value(0, QSize(640, 480));
m_size *= dRatio;
m_pixmap = icon.pixmap(m_size);
// WORKAROUND:
// Since we don't have x3 and x4 HiDPI icons yet,
// and we hadn't enabled automatic up-scaling for now,
// we have to make sure m_pixmap is upscaled to required size.
const QSize actualSize = m_pixmap.size() / m_pixmap.devicePixelRatio();
if ( actualSize.width() < m_size.width()
|| actualSize.height() < m_size.height())
m_pixmap = m_pixmap.scaled(m_size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
/* Prepare main-layout: */
prepareMainLayout();
/* Translate: */
retranslateUi();
}
void VBoxAboutDlg::prepareMainLayout()
{
/* Create main-layout: */
m_pMainLayout = new QVBoxLayout(this);
if (m_pMainLayout)
{
/* Prepare label: */
prepareLabel();
/* Prepare close-button: */
prepareCloseButton();
}
}
void VBoxAboutDlg::prepareLabel()
{
/* Create label for version text: */
m_pLabel = new QLabel;
if (m_pLabel)
{
/* Prepare label for version text: */
QPalette palette;
/* Branding: Set a different text color (because splash also could be white),
* otherwise use white as default color: */
const QString strColor = vboxGlobal().brandingGetKey("UI/AboutTextColor");
if (!strColor.isEmpty())
palette.setColor(QPalette::WindowText, QColor(strColor).name());
else
palette.setColor(QPalette::WindowText, Qt::black);
m_pLabel->setPalette(palette);
m_pLabel->setTextInteractionFlags(Qt::TextSelectableByMouse);
m_pLabel->setFont(font());
/* Add label to the main-layout: */
m_pMainLayout->addWidget(m_pLabel);
m_pMainLayout->setAlignment(m_pLabel, Qt::AlignRight | Qt::AlignBottom);
}
}
void VBoxAboutDlg::prepareCloseButton()
{
/* Create button-box: */
QDialogButtonBox *pButtonBox = new QDialogButtonBox;
if (pButtonBox)
{
/* Create close-button: */
QPushButton *pCloseButton = pButtonBox->addButton(QDialogButtonBox::Close);
AssertPtrReturnVoid(pCloseButton);
/* Prepare close-button: */
connect(pButtonBox, SIGNAL(rejected()), this, SLOT(reject()));
/* Add button-box to the main-layout: */
m_pMainLayout->addWidget(pButtonBox);
}
}
|
#include <Rcpp.h>
#include "individual.h"
#include "patch.h"
#include "simulate_hd_space.h"
// assure number of breeders/patch is even
int _make_even(int const n)
{
if (n < 1)
{
return(2);
}
if (n % 2 != 0)
{
return(n+1);
}
return(n);
}
SimulateHDSpatial::SimulateHDSpatial(
int const Npatches
,int const NbreedersPatch
,double const v
,double const c
,double const init_pHawk
,double const dispersal
,bool const is_pure = true
,int const output_nth_timestep = 1
,double const mu = 0.01
,double const mu_d = 0.01
,int const max_time = 500) :
rng_r((std::random_device())()) // init random number generator
,uniform(0.0, 1.0)
,pop(Npatches, Patch(_make_even(NbreedersPatch)))
,Npatches{Npatches}
,Nbp{_make_even(NbreedersPatch)}
,v{v}
,c{c}
,payoff_matrix{{v/2,0},{v,(v-c)/2}}
,generation{0}
,init_pHawk{init_pHawk}
,d{dispersal}
,relatedness_regression{0.0}
,is_pure{is_pure}
,output_nth_timestep{output_nth_timestep}
,mu{mu}
,mu_d{mu_d}
,max_time{max_time}
{
int id_ctr = 0;
// loop through all the patches
for (size_t patch_idx = 0; patch_idx < Npatches; ++patch_idx)
{
assert(pop[patch_idx].breeders.size() == Nbp);
assert(pop[patch_idx].payoffs.size() == Nbp);
for (size_t ind_idx = 0; ind_idx < Nbp; ++ind_idx)
{
// initialize this population
pop[patch_idx].breeders[ind_idx].is_hawk =
uniform(rng_r) < init_pHawk;
pop[patch_idx].breeders[ind_idx].payoff = 0.0;
pop[patch_idx].breeders[ind_idx].prob_hawk = init_pHawk;
pop[patch_idx].breeders[ind_idx].disperse[0] = d;
pop[patch_idx].breeders[ind_idx].disperse[1] = d;
// give everybody a unique id
pop[patch_idx].breeders[ind_idx].id = id_ctr++;
}
}
} // SimulateHDSpatial::SimulateHDSpatial()
// interact within patches and reproduce
void SimulateHDSpatial::interact_reproduce()
{
bool ind1_is_hawk,ind2_is_hawk, d1, d2;
double baseline_fitness = c;
double sum_payoffs = 0.0;
double local_sum_payoffs = 0.0;
double local_sum_d = 0.0;
double payoff1, payoff2;
// attempt at calculating relatedness - does not work!
double covzizj=0.0;
double varzi=0.0;
double meanzi=0.0;
double total_cov = 0.0;
double total_var = 0.0;
// make a distribution of payoffs from which we can sample
// later on
std::vector<double> payoffs_immigrant_parents(pop.size() * Nbp);
// counter to keep track of payoff distribution()
int payoff_idx = 0;
for (size_t patch_idx = 0;
patch_idx < pop.size(); ++patch_idx)
{
// nonzero
assert(pop[patch_idx].breeders.size() > 0);
// even number?
assert(pop[patch_idx].breeders.size() % 2 == 0);
// shuffle stack of breeders so that
// we can have interactions
// within random pairs
if (pop[patch_idx].breeders.size() > 2)
{
// shuffle stack of breeders so that we can have interactions
// within random pairs
std::shuffle(pop[patch_idx].breeders.begin()
,pop[patch_idx].breeders.end()
,rng_r);
}
local_sum_payoffs = 0.0;
local_sum_d = 0.0;
assert(pop[patch_idx].breeders.size() == Nbp);
assert(pop[patch_idx].payoffs.size() == Nbp);
covzizj = 0.0;
varzi = 0.0;
meanzi = 0.0;
// loop through pairs
for (size_t ind_idx = 0;
ind_idx < pop[patch_idx].breeders.size(); ind_idx+=2)
{
// cov zi, zj
// we multiply x 2 as interaction
// takes place from ind 1 to ind 2
// and from ind 1 to ind 2
covzizj += 2 * pop[patch_idx].breeders[ind_idx].id
* pop[patch_idx].breeders[ind_idx + 1].id;
// update variance for ind 1
varzi += pop[patch_idx].breeders[ind_idx].id
* pop[patch_idx].breeders[ind_idx].id;
// update variance for ind 2
varzi += pop[patch_idx].breeders[ind_idx + 1].id
* pop[patch_idx].breeders[ind_idx + 1].id;
// update mean
meanzi += pop[patch_idx].breeders[ind_idx].id
+ pop[patch_idx].breeders[ind_idx + 1].id;
assert(ind_idx + 1 < pop[patch_idx].breeders.size());
ind1_is_hawk = pop[patch_idx].breeders[ind_idx].is_hawk;
d1 = pop[patch_idx].breeders[ind_idx].disperse[ind1_is_hawk];
assert(d1 >= 0);
assert(d1 <= 1);
ind2_is_hawk = pop[patch_idx].breeders[ind_idx+1].is_hawk;
d2 = pop[patch_idx].breeders[ind_idx + 1].disperse[ind2_is_hawk];
assert(d2 >= 0.0);
assert(d2 <= 1.0);
payoff1 = payoff2 = baseline_fitness;
// if we have HH we need to calculate
// payoff stochastically
if (ind1_is_hawk && ind2_is_hawk)
{
if (uniform(rng_r) < 0.5)
{
payoff1 += v;
payoff2 += -c;
}
else
{
payoff1 += -c;
payoff2 += v;
}
}
else
{
// payoff ind 1
payoff1 += payoff_matrix[ind1_is_hawk][ind2_is_hawk];
// payoff ind 2
payoff2 += payoff_matrix[ind2_is_hawk][ind1_is_hawk];
}
sum_payoffs += d1 * payoff1 + d2 * payoff2;
local_sum_payoffs += (1.0 - d1) * payoff1 + (1.0 - d2) * payoff2;
assert(payoff_idx + 2 <= payoffs_immigrant_parents.size());
payoffs_immigrant_parents[payoff_idx++] = d1 * payoff1;
payoffs_immigrant_parents[payoff_idx++] = d2 * payoff2;
pop[patch_idx].payoffs[ind_idx] = (1.0 - d1) * payoff1;
pop[patch_idx].payoffs[ind_idx + 1] = (1.0 - d2) * payoff2;
pop[patch_idx].breeders[ind_idx].payoff = (1.0 - d1) * payoff1;
pop[patch_idx].breeders[ind_idx + 1].payoff = (1.0 - d2) * payoff2;
} // size_t ind_idx = 0, ind_idx += 2
meanzi /= Nbp;
covzizj = covzizj / Nbp - meanzi * meanzi;
varzi = varzi / Nbp - meanzi * meanzi;
total_cov += covzizj;
total_var += varzi;
pop[patch_idx].total_payoff = local_sum_payoffs;
assert(local_sum_payoffs >= 0);
} // end for (size_t patch_idx = 0;
// patch_idx < pop.size(); ++patch_idx)
// meanzi /= Nbp * pop.size();
//
// covzizj = covzizj / (Nbp * pop.size()) - meanzi * meanzi;
//
// varzi = varzi / (Nbp * pop.size()) - meanzi * meanzi;
relatedness_regression = total_cov / total_var;
// make a vector of individuals to use for recruiting purposes
std::vector <Individual> recruits(Nbp);
// make a probability distribution of global payoffs
std::discrete_distribution<int> immigrant_payoffs(
payoffs_immigrant_parents.begin()
,payoffs_immigrant_parents.end());
// aux variable reflecting prob
// to sample local parent
double prob_local;
// total prob of immigration per patch
double immigrants_per_patch = sum_payoffs / Npatches;
double locals_per_patch;
// now recruit
for (int patch_idx = 0; patch_idx < pop.size(); ++patch_idx)
{
assert(pop[patch_idx].total_payoff >= 0.0);
assert(pop[patch_idx].total_payoff <=
Nbp * (baseline_fitness + v));
// sample local parent
locals_per_patch = pop[patch_idx].total_payoff;
// competition function
prob_local = locals_per_patch /
(locals_per_patch + immigrants_per_patch);
// make distribution of local payoffs
std::discrete_distribution<int> local_payoffs(
pop[patch_idx].payoffs.begin()
,pop[patch_idx].payoffs.end());
int sample, patch_sample_idx, parent_sample_idx;
for (int ind_idx = 0; ind_idx < Nbp; ++ind_idx)
{
if (uniform(rng_r) < prob_local)
{
// sample local
parent_sample_idx = local_payoffs(rng_r);
patch_sample_idx = patch_idx;
} // end prob_local
else // sample a global individual
{
sample = immigrant_payoffs(rng_r);
// get parent index
parent_sample_idx = sample % Nbp;
// get patch idx
patch_sample_idx = int(floor((double) sample / Nbp)) % Npatches;
}
assert(parent_sample_idx >= 0);
assert(parent_sample_idx < Nbp);
assert(parent_sample_idx < pop[patch_sample_idx].breeders.size());
assert(ind_idx < Nbp);
assert(ind_idx >= 0);
create_kid(
pop[patch_sample_idx].breeders[parent_sample_idx]
,recruits[ind_idx]
);
} //end for int ind_idx;
assert(pop[patch_idx].breeders.size() == recruits.size());
pop[patch_idx].breeders = recruits;
} // end for (int patch_idx = 0;
//patch_idx < pop.size(); ++patch_idx)
} // end void SimulateHDSpatial::interact_reproduce()
void SimulateHDSpatial::create_kid(Individual &parent, Individual &kid)
{
kid.payoff = 0.0;
kid.prob_hawk = is_pure ?
0.0
:
mutate_prob(parent.prob_hawk, mu);
kid.is_hawk = is_pure ?
mutate(parent.is_hawk)
:
uniform(rng_r) < kid.prob_hawk;
kid.disperse[0] = mutate_prob(parent.disperse[0], mu_d);
kid.disperse[1] = mutate_prob(parent.disperse[1], mu_d);
kid.id = parent.id;
if (uniform(rng_r) < mu_id)
{
++kid.id;
}
} // end create_kid()
double SimulateHDSpatial::mutate_prob(double const orig_val, double const mu)
{
double val = orig_val;
if (uniform(rng_r) < mu)
{
std::normal_distribution<double> mu_val(0.0, 0.1);
val += mu_val(rng_r);
if (val < 0.0)
{
val = 0.0;
}
else if (val > 1.0)
{
val = 1.0;
}
}
return(val);
}
bool SimulateHDSpatial::mutate(bool const val)
{
bool tval = val;
if (uniform(rng_r) < mu)
{
tval = !tval;
}
return(tval);
}
Rcpp::DataFrame SimulateHDSpatial::run()
{
// get a whole bunch of zero-filled vectors for the stats
Rcpp::NumericVector freqHawk(floor((double)max_time / output_nth_timestep));
Rcpp::NumericVector sd_freqHawk(floor((double)max_time / output_nth_timestep));
Rcpp::NumericVector mean_pHawk(floor((double)max_time / output_nth_timestep));
Rcpp::NumericVector sd_pHawk(floor((double)max_time / output_nth_timestep));
Rcpp::NumericVector timestep_vec(floor((double)max_time / output_nth_timestep));
Rcpp::NumericVector dHawk(floor((double)max_time / output_nth_timestep));
Rcpp::NumericVector dDove(floor((double)max_time / output_nth_timestep));
Rcpp::NumericVector relatedness(floor((double)max_time / output_nth_timestep));
double fHawk = 0.0;
double sd_fHawk = 0.0;
double pHawk_x = 0.0;
double sd_pHawk_x = 0.0;
double dHawk_x = 0.0;
double dDove_x = 0.0;
int stats_ctr = 0;
for (generation = 0; generation < max_time; ++generation)
{
if (generation % output_nth_timestep == 0)
{
stats(fHawk, sd_fHawk, pHawk_x, sd_pHawk_x, dHawk_x, dDove_x);
assert(stats_ctr < floor((double)max_time / output_nth_timestep));
freqHawk[stats_ctr] = fHawk;
sd_freqHawk[stats_ctr] = sd_fHawk;
mean_pHawk[stats_ctr] = pHawk_x;
sd_pHawk[stats_ctr] = sd_pHawk_x;
timestep_vec[stats_ctr] = generation;
dHawk[stats_ctr] = dHawk_x;
dDove[stats_ctr] = dDove_x;
relatedness[stats_ctr] = relatedness_regression;
++stats_ctr;
}
// check for user interruption
Rcpp::checkUserInterrupt();
interact_reproduce();
}
Rcpp::DataFrame simulation_data = Rcpp::DataFrame::create(
Rcpp::Named("generation") = timestep_vec
,Rcpp::Named("freq_Hawk") = freqHawk
,Rcpp::Named("sd_freqHawk") = sd_freqHawk
,Rcpp::Named("mean_pHawk") = mean_pHawk
,Rcpp::Named("sd_pHawk") = sd_pHawk
,Rcpp::Named("dHawk") = dHawk
,Rcpp::Named("dDove") = dDove
// ,Rcpp::Named("relatedness") = relatedness
);
return(simulation_data);
}// end SimulateHDSpatial::run()
// write stats
void SimulateHDSpatial::stats(
double &freq_Hawk
,double &sd_freq_Hawk
,double &mean_pHawk
,double &sd_pHawk
,double &mean_dHawk
,double &mean_dDove
)
{
freq_Hawk = 0.0;
sd_freq_Hawk = 0.0;
mean_pHawk = 0.0;
mean_dHawk = 0.0;
mean_dDove = 0.0;
sd_pHawk = 0.0;
double ss_freq_Hawk = 0.0;
double ss_pHawk = 0.0;
bool h;
double p, d;
for (size_t patch_idx = 0; patch_idx < pop.size(); ++patch_idx)
{
for (size_t ind_idx = 0;
ind_idx < pop[patch_idx].breeders.size(); ++ind_idx)
{
h = pop[patch_idx].breeders[ind_idx].is_hawk;
d = pop[patch_idx].breeders[ind_idx].disperse[0];
mean_dDove += d;
d = pop[patch_idx].breeders[ind_idx].disperse[1];
mean_dHawk += d;
freq_Hawk += h;
ss_freq_Hawk += h * h;
p = pop[patch_idx].breeders[ind_idx].prob_hawk;
assert(p >= 0);
assert(p <= 1.0);
mean_pHawk += p;
ss_pHawk += p * p;
}
}
int totalN = pop.size() * Nbp;
freq_Hawk /= totalN;
mean_pHawk /= totalN;
mean_dHawk /= totalN;
mean_dDove /= totalN;
ss_pHawk /= totalN;
ss_freq_Hawk /= totalN;
sd_freq_Hawk = ss_freq_Hawk - freq_Hawk * freq_Hawk;
sd_freq_Hawk = sd_freq_Hawk < 0.0 ? 0.0 : sqrt(sd_freq_Hawk);
sd_pHawk = ss_pHawk - mean_pHawk * mean_pHawk;
sd_pHawk = sd_pHawk < 0.0 ? 0.0 : sqrt(sd_pHawk);
} //end stats()
|
//
// main.cpp
// target2
//
// Created by Jayanth Raman on 12/12/16.
// Copyright © 2016 Jayanth Raman. All rights reserved.
//
// This target was added after the common group with shared_stuff was created.
// In the project settings > Build Phases, shared_stuff.cpp was manually added
// to Build Phases > Compile Sources.
#include <iostream>
#include "shared_stuff.hpp"
int main(int argc, const char * argv[]) {
std::cout << "target2 says Hello!\n";
auto shared = Shared();
shared.action1();
return 0;
}
|
#include "instructions/nop.hpp"
#include "helpers.hpp"
#include <stdexcept>
using namespace M68K;
using namespace INSTRUCTION;
Nop::Nop(uint16_t opcode) : Instruction(opcode){
;
}
void Nop::execute(CPUState& cpu_state){
uint32_t pc = cpu_state.registers.get(REG_PC, SIZE_LONG);
pc += SIZE_WORD;
cpu_state.registers.set(REG_PC, SIZE_LONG, pc);
}
std::string Nop::disassembly(CPUState& cpu_state){
uint32_t pc = cpu_state.registers.get(REG_PC, SIZE_LONG);
pc += SIZE_WORD;
cpu_state.registers.set(REG_PC, SIZE_LONG, pc);
return "nop";
}
std::shared_ptr<INSTRUCTION::Instruction> Nop::create(uint16_t opcode){
return std::make_shared<Nop>(opcode);
}
|
// Distributed under the MIT License.
// See LICENSE.txt for details.
#pragma once
namespace ScalarAdvection {
/*!
* \brief Finite difference functionality for ScalarAdvection system
*/
namespace fd {}
} // namespace ScalarAdvection
|
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
#include "stdafx.h"
// Displays a friendly name for a passed in functional
// category. If the category is not known by this function
// the GUID will be displayed in string form.
void DisplayFunctionalCategory(
_In_ REFGUID functionalCategory)
{
if (IsEqualGUID(WPD_FUNCTIONAL_CATEGORY_STORAGE, functionalCategory))
{
wprintf(L"WPD_FUNCTIONAL_CATEGORY_STORAGE");
}
else if (IsEqualGUID(WPD_FUNCTIONAL_CATEGORY_STILL_IMAGE_CAPTURE, functionalCategory))
{
wprintf(L"WPD_FUNCTIONAL_CATEGORY_STILL_IMAGE_CAPTURE");
}
else if (IsEqualGUID(WPD_FUNCTIONAL_CATEGORY_AUDIO_CAPTURE, functionalCategory))
{
wprintf(L"WPD_FUNCTIONAL_CATEGORY_AUDIO_CAPTURE");
}
else if (IsEqualGUID(WPD_FUNCTIONAL_CATEGORY_SMS, functionalCategory))
{
wprintf(L"WPD_FUNCTIONAL_CATEGORY_SMS");
}
else if (IsEqualGUID(WPD_FUNCTIONAL_CATEGORY_RENDERING_INFORMATION, functionalCategory))
{
wprintf(L"WPD_FUNCTIONAL_CATEGORY_RENDERING_INFORMATION");
}
else
{
wprintf(L"%ws", (PCWSTR)CGuidToString(functionalCategory));
}
}
// Displays a friendly name for a passed in event
// If the event is not known by this function
// the GUID will be displayed in string form.
void DisplayEvent(
_In_ REFGUID event)
{
if (IsEqualGUID(WPD_EVENT_OBJECT_ADDED, event))
{
wprintf(L"WPD_EVENT_OBJECT_ADDED");
}
else if (IsEqualGUID(WPD_EVENT_OBJECT_REMOVED, event))
{
wprintf(L"WPD_EVENT_OBJECT_REMOVED");
}
else if (IsEqualGUID(WPD_EVENT_OBJECT_UPDATED, event))
{
wprintf(L"WPD_EVENT_OBJECT_UPDATED");
}
else if (IsEqualGUID(WPD_EVENT_DEVICE_RESET, event))
{
wprintf(L"WPD_EVENT_DEVICE_RESET");
}
else if (IsEqualGUID(WPD_EVENT_DEVICE_CAPABILITIES_UPDATED, event))
{
wprintf(L"WPD_EVENT_DEVICE_CAPABILITIES_UPDATED");
}
else if (IsEqualGUID(WPD_EVENT_STORAGE_FORMAT, event))
{
wprintf(L"WPD_EVENT_STORAGE_FORMAT");
}
else
{
wprintf(L"%ws", (PCWSTR)CGuidToString(event));
}
}
// Displays a friendly name for a passed in content type
// If the content type is not known by this function
// the GUID will be displayed in string form.
void DisplayContentType(
_In_ REFGUID contentType)
{
if (IsEqualGUID(WPD_CONTENT_TYPE_FUNCTIONAL_OBJECT, contentType))
{
wprintf(L"WPD_CONTENT_TYPE_FUNCTIONAL_OBJECT");
}
else if (IsEqualGUID(WPD_CONTENT_TYPE_FOLDER, contentType))
{
wprintf(L"WPD_CONTENT_TYPE_FOLDER");
}
else if (IsEqualGUID(WPD_CONTENT_TYPE_IMAGE, contentType))
{
wprintf(L"WPD_CONTENT_TYPE_IMAGE");
}
else if (IsEqualGUID(WPD_CONTENT_TYPE_DOCUMENT, contentType))
{
wprintf(L"WPD_CONTENT_TYPE_DOCUMENT");
}
else if (IsEqualGUID(WPD_CONTENT_TYPE_CONTACT, contentType))
{
wprintf(L"WPD_CONTENT_TYPE_CONTACT");
}
else if (IsEqualGUID(WPD_CONTENT_TYPE_AUDIO, contentType))
{
wprintf(L"WPD_CONTENT_TYPE_AUDIO");
}
else if (IsEqualGUID(WPD_CONTENT_TYPE_VIDEO, contentType))
{
wprintf(L"WPD_CONTENT_TYPE_VIDEO");
}
else if (IsEqualGUID(WPD_CONTENT_TYPE_TASK, contentType))
{
wprintf(L"WPD_CONTENT_TYPE_TASK");
}
else if (IsEqualGUID(WPD_CONTENT_TYPE_APPOINTMENT, contentType))
{
wprintf(L"WPD_CONTENT_TYPE_APPOINTMENT");
}
else if (IsEqualGUID(WPD_CONTENT_TYPE_EMAIL, contentType))
{
wprintf(L"WPD_CONTENT_TYPE_EMAIL");
}
else if (IsEqualGUID(WPD_CONTENT_TYPE_MEMO, contentType))
{
wprintf(L"WPD_CONTENT_TYPE_MEMO");
}
else if (IsEqualGUID(WPD_CONTENT_TYPE_UNSPECIFIED, contentType))
{
wprintf(L"WPD_CONTENT_TYPE_UNSPECIFIED");
}
else
{
wprintf(L"%ws", (PCWSTR)CGuidToString(contentType));
}
}
// Display the basic event options for the passed in event.
void DisplayEventOptions(
_In_ IPortableDeviceCapabilities* capabilities,
_In_ REFGUID event)
{
ComPtr<IPortableDeviceValues> eventOptions;
HRESULT hr = capabilities->GetEventOptions(event, &eventOptions);
if (FAILED(hr))
{
wprintf(L"! Failed to get even options, hr = 0x%lx\n", hr);
}
else
{
wprintf(L"Event Options:\n");
// Read the WPD_EVENT_OPTION_IS_BROADCAST_EVENT value to see if the event is
// a broadcast event. If the read fails, assume FALSE
BOOL isBroadcastEvent = FALSE;
hr = eventOptions->GetBoolValue(WPD_EVENT_OPTION_IS_BROADCAST_EVENT, &isBroadcastEvent);
if (SUCCEEDED(hr))
{
wprintf(L"\tWPD_EVENT_OPTION_IS_BROADCAST_EVENT = %ws\n", isBroadcastEvent ? L"TRUE" : L"FALSE");
}
else
{
wprintf(L"! Failed to get WPD_EVENT_OPTION_IS_BROADCAST_EVENT (assuming FALSE), hr = 0x%lx\n", hr);
}
}
}
// Display all functional object identifiers contained in an IPortableDevicePropVariantCollection
// NOTE: These values are assumed to be in VT_LPWSTR VarType format.
void DisplayFunctionalObjectIDs(
_In_ IPortableDevicePropVariantCollection* functionalObjectIDs)
{
DWORD numObjectIDs = 0;
// Get the total number of object identifiers in the collection.
HRESULT hr = functionalObjectIDs->GetCount(&numObjectIDs);
if (SUCCEEDED(hr))
{
// Loop through the collection and displaying each object identifier found.
// This loop prints a comma-separated list of the object identifiers.
for (DWORD objectIDIndex = 0; objectIDIndex < numObjectIDs; objectIDIndex++)
{
PROPVARIANT objectID = {0};
hr = functionalObjectIDs->GetAt(objectIDIndex, &objectID);
if (SUCCEEDED(hr))
{
// We have a functional object identifier. It is assumed that
// object identifiers are returned as VT_LPWSTR varTypes.
if (objectID.vt == VT_LPWSTR &&
objectID.pwszVal != nullptr)
{
// Display the object identifiers separated by commas
wprintf(L"%ws", objectID.pwszVal);
if ((objectIDIndex + 1) < numObjectIDs)
{
wprintf(L", ");
}
}
else
{
wprintf(L"! Invalid functional object identifier found\n");
}
}
PropVariantClear(&objectID);
}
}
}
// List all functional objects on the device
void ListFunctionalObjects(
_In_ IPortableDevice* device)
{
//<SnippetCapabilities7>
ComPtr<IPortableDeviceCapabilities> capabilities;
ComPtr<IPortableDevicePropVariantCollection> functionalCategories;
DWORD numFunctionalCategories = 0;
HRESULT hr = S_OK;
// Get an IPortableDeviceCapabilities interface from the IPortableDevice interface to
// access the device capabilities-specific methods.
hr = device->Capabilities(&capabilities);
if (FAILED(hr))
{
wprintf(L"! Failed to get IPortableDeviceCapabilities from IPortableDevice, hr = 0x%lx\n", hr);
}
// Get all functional categories supported by the device.
// We will use these categories to enumerate functional objects
// that fall within them.
if (SUCCEEDED(hr))
{
hr = capabilities->GetFunctionalCategories(&functionalCategories);
if (FAILED(hr))
{
wprintf(L"! Failed to get functional categories from the device, hr = 0x%lx\n", hr);
}
}
// Get the number of functional categories found on the device.
if (SUCCEEDED(hr))
{
hr = functionalCategories->GetCount(&numFunctionalCategories);
if (FAILED(hr))
{
wprintf(L"! Failed to get number of functional categories, hr = 0x%lx\n", hr);
}
}
wprintf(L"\n%u Functional Categories Found on the device\n\n", numFunctionalCategories);
// Loop through each functional category and get the list of
// functional object identifiers associated with a particular
// category.
if (SUCCEEDED(hr))
{
for (DWORD index = 0; index < numFunctionalCategories; index++)
{
PROPVARIANT pv = {0};
hr = functionalCategories->GetAt(index, &pv);
if (SUCCEEDED(hr))
{
// We have a functional category. It is assumed that
// functional categories are returned as VT_CLSID varTypes.
if (pv.vt == VT_CLSID &&
pv.puuid != nullptr)
{
// Display the functional category name
wprintf(L"Functional Category: ");
DisplayFunctionalCategory(*pv.puuid);
wprintf(L"\n");
// Display the object identifiers for all
// functional objects within this category
ComPtr<IPortableDevicePropVariantCollection> functionalObjectIDs;
hr = capabilities->GetFunctionalObjects(*pv.puuid, &functionalObjectIDs);
if (SUCCEEDED(hr))
{
wprintf(L"Functional Objects: ");
DisplayFunctionalObjectIDs(functionalObjectIDs.Get());
wprintf(L"\n\n");
}
else
{
wprintf(L"! Failed to get functional objects, hr = 0x%lx\n", hr);
}
}
else
{
wprintf(L"! Invalid functional category found\n");
}
}
PropVariantClear(&pv);
}
}
//</SnippetCapabilities7>
}
// Display all content types contained in an IPortableDevicePropVariantCollection
// NOTE: These values are assumed to be in VT_CLSID VarType format.
void DisplayContentTypes(
_In_ IPortableDevicePropVariantCollection* contentTypes)
{
if (contentTypes == nullptr)
{
wprintf(L"! A nullptr IPortableDevicePropVariantCollection interface pointer was received\n");
return;
}
// Get the total number of content types in the collection.
DWORD numContentTypes = 0;
HRESULT hr = contentTypes->GetCount(&numContentTypes);
if (SUCCEEDED(hr))
{
// Loop through the collection and displaying each content type found.
// This loop prints a comma-separated list of the content types.
for (DWORD contentTypeIndex = 0; contentTypeIndex < numContentTypes; contentTypeIndex++)
{
PROPVARIANT contentType = {0};
hr = contentTypes->GetAt(contentTypeIndex, &contentType);
if (SUCCEEDED(hr))
{
// We have a content type. It is assumed that
// content types are returned as VT_CLSID varTypes.
if (contentType.vt == VT_CLSID &&
contentType.puuid != nullptr)
{
// Display the content types separated by commas
DisplayContentType(*contentType.puuid);
if ((contentTypeIndex + 1) < numContentTypes)
{
wprintf(L", ");
}
}
else
{
wprintf(L"! Invalid content type found\n");
}
}
PropVariantClear(&contentType);
}
}
}
// List all functional categories on the device
void ListFunctionalCategories(
_In_ IPortableDevice* device)
{
//<SnippetCapabilities1>
ComPtr<IPortableDeviceCapabilities> capabilities;
ComPtr<IPortableDevicePropVariantCollection> functionalCategories;
DWORD numCategories = 0;
HRESULT hr = S_OK;
// Get an IPortableDeviceCapabilities interface from the IPortableDevice interface to
// access the device capabilities-specific methods.
hr = device->Capabilities(&capabilities);
if (FAILED(hr))
{
wprintf(L"! Failed to get IPortableDeviceCapabilities from IPortableDevice, hr = 0x%lx\n", hr);
}
// Get all functional categories supported by the device.
if (SUCCEEDED(hr))
{
hr = capabilities->GetFunctionalCategories(&functionalCategories);
if (FAILED(hr))
{
wprintf(L"! Failed to get functional categories from the device, hr = 0x%lx\n", hr);
}
}
//</SnippetCapabilities1>
// Get the number of functional categories found on the device.
//<SnippetCapabilities2>
if (SUCCEEDED(hr))
{
hr = functionalCategories->GetCount(&numCategories);
if (FAILED(hr))
{
wprintf(L"! Failed to get number of functional categories, hr = 0x%lx\n", hr);
}
}
wprintf(L"\n%u Functional Categories Found on the device\n\n", numCategories);
// Loop through each functional category and display its name
if (SUCCEEDED(hr))
{
for (DWORD index = 0; index < numCategories; index++)
{
PROPVARIANT pv = {0};
hr = functionalCategories->GetAt(index, &pv);
if (SUCCEEDED(hr))
{
// We have a functional category. It is assumed that
// functional categories are returned as VT_CLSID varTypes.
if (pv.vt == VT_CLSID &&
pv.puuid != nullptr)
{
// Display the functional category name
DisplayFunctionalCategory(*pv.puuid);
wprintf(L"\n");
}
}
PropVariantClear(&pv);
}
}
//</SnippetCapabilities2>
}
// List supported content types the device supports
void ListSupportedContentTypes(
_In_ IPortableDevice* device)
{
//<SnippetCapabilities3>
ComPtr<IPortableDeviceCapabilities> capabilities;
ComPtr<IPortableDevicePropVariantCollection> functionalCategories;
DWORD numCategories = 0;
HRESULT hr = S_OK;
// Get an IPortableDeviceCapabilities interface from the IPortableDevice interface to
// access the device capabilities-specific methods.
hr = device->Capabilities(&capabilities);
if (FAILED(hr))
{
wprintf(L"! Failed to get IPortableDeviceCapabilities from IPortableDevice, hr = 0x%lx\n", hr);
}
// Get all functional categories supported by the device.
// We will use these categories to enumerate functional objects
// that fall within them.
if (SUCCEEDED(hr))
{
hr = capabilities->GetFunctionalCategories(&functionalCategories);
if (FAILED(hr))
{
wprintf(L"! Failed to get functional categories from the device, hr = 0x%lx\n", hr);
}
}
// Get the number of functional categories found on the device.
if (SUCCEEDED(hr))
{
hr = functionalCategories->GetCount(&numCategories);
if (FAILED(hr))
{
wprintf(L"! Failed to get number of functional categories, hr = 0x%lx\n", hr);
}
}
wprintf(L"\n%u Functional Categories Found on the device\n\n", numCategories);
// Loop through each functional category and display its name and supported content types.
if (SUCCEEDED(hr))
{
for (DWORD index = 0; index < numCategories; index++)
{
PROPVARIANT pv = {0};
hr = functionalCategories->GetAt(index, &pv);
if (SUCCEEDED(hr))
{
// We have a functional category. It is assumed that
// functional categories are returned as VT_CLSID varTypes.
if (pv.vt == VT_CLSID &&
pv.puuid != nullptr)
{
// Display the functional category name
wprintf(L"Functional Category: ");
DisplayFunctionalCategory(*pv.puuid);
wprintf(L"\n");
// Display the content types supported for this category
ComPtr<IPortableDevicePropVariantCollection> contentTypes;
hr = capabilities->GetSupportedContentTypes(*pv.puuid, &contentTypes);
if (SUCCEEDED(hr))
{
wprintf(L"Supported Content Types: ");
DisplayContentTypes(contentTypes.Get());
wprintf(L"\n\n");
}
else
{
wprintf(L"! Failed to get supported content types from the device, hr = 0x%lx\n", hr);
}
}
else
{
wprintf(L"! Invalid functional category found\n");
}
}
PropVariantClear(&pv);
}
}
//</SnippetCapabilities3>
}
// Determines if a device supports a particular functional category.
BOOL SupportsFunctionalCategory(
_In_ IPortableDevice* device,
_In_ REFGUID functionalCategory)
{
ComPtr<IPortableDeviceCapabilities> capabilities;
ComPtr<IPortableDevicePropVariantCollection> functionalCategories;
BOOL isSupported = FALSE;
DWORD numCategories = 0;
// Get an IPortableDeviceCapabilities interface from the IPortableDevice interface to
// access the device capabilities-specific methods.
HRESULT hr = device->Capabilities(&capabilities);
if (FAILED(hr))
{
wprintf(L"! Failed to get IPortableDeviceCapabilities from IPortableDevice, hr = 0x%lx\n", hr);
}
// Get all functional categories supported by the device.
// We will use these categories to search for a particular functional category.
// There is typically only 1 of these types of functional categories.
if (SUCCEEDED(hr))
{
hr = capabilities->GetFunctionalCategories(&functionalCategories);
if (FAILED(hr))
{
wprintf(L"! Failed to get functional categories from the device, hr = 0x%lx\n", hr);
}
}
// Get the number of functional categories found on the device.
if (SUCCEEDED(hr))
{
hr = functionalCategories->GetCount(&numCategories);
if (FAILED(hr))
{
wprintf(L"! Failed to get number of functional categories, hr = 0x%lx\n", hr);
}
}
// Loop through each functional category and find the passed in category
if (SUCCEEDED(hr))
{
for (DWORD dwIndex = 0; dwIndex < numCategories; dwIndex++)
{
PROPVARIANT pv = {0};
hr = functionalCategories->GetAt(dwIndex, &pv);
if (SUCCEEDED(hr))
{
// We have a functional category. It is assumed that
// functional categories are returned as VT_CLSID varTypes.
if (pv.vt == VT_CLSID &&
pv.puuid != nullptr)
{
isSupported = IsEqualGUID(functionalCategory, *pv.puuid);
}
else
{
wprintf(L"! Invalid functional category found\n");
}
}
PropVariantClear(&pv);
// If the device supports the category, exit the for loop.
// NOTE: We are exiting after calling PropVariantClear to make
// sure we free any allocated data in the PROPVARIANT returned
// from the GetAt() method call.
if (isSupported == TRUE)
{
break;
}
}
}
return isSupported;
}
// Determines if a device supports a particular command.
BOOL SupportsCommand(
_In_ IPortableDevice* device,
_In_ REFPROPERTYKEY command)
{
ComPtr<IPortableDeviceCapabilities> capabilities;
ComPtr<IPortableDeviceKeyCollection> commands;
BOOL isSupported = FALSE;
DWORD numCommands = 0;
// Get an IPortableDeviceCapabilities interface from the IPortableDevice interface to
// access the device capabilities-specific methods.
HRESULT hr = device->Capabilities(&capabilities);
if (FAILED(hr))
{
wprintf(L"! Failed to get IPortableDeviceCapabilities from IPortableDevice, hr = 0x%lx\n", hr);
}
// Get all commands supported by the device.
// We will use these commands to search for a particular functional category.
if (SUCCEEDED(hr))
{
hr = capabilities->GetSupportedCommands(&commands);
if (FAILED(hr))
{
wprintf(L"! Failed to get supported commands from the device, hr = 0x%lx\n", hr);
}
}
// Get the number of supported commands found on the device.
if (SUCCEEDED(hr))
{
hr = commands->GetCount(&numCommands);
if (FAILED(hr))
{
wprintf(L"! Failed to get number of supported commands, hr = 0x%lx\n", hr);
}
}
// Loop through each functional category and find the passed in category
if (SUCCEEDED(hr))
{
for (DWORD index = 0; index < numCommands; index++)
{
PROPERTYKEY key = WPD_PROPERTY_NULL;
hr = commands->GetAt(index, &key);
if (SUCCEEDED(hr))
{
isSupported = IsEqualPropertyKey(command, key);
}
// If the device supports the category, exit the for loop.
if (isSupported == TRUE)
{
break;
}
}
}
return isSupported;
}
// Reads the WPD_RENDERING_INFORMATION_PROFILES properties on the device.
HRESULT ReadProfileInformationProperties(
_In_ IPortableDevice* device,
_In_ PCWSTR functionalObjectID,
_COM_Outptr_ IPortableDeviceValuesCollection** renderingInfoProfiles)
{
*renderingInfoProfiles = nullptr;
ComPtr<IPortableDeviceValuesCollection> renderingInfoProfilesTemp;
ComPtr<IPortableDeviceContent> content;
ComPtr<IPortableDeviceProperties> properties;
ComPtr<IPortableDeviceKeyCollection> propertiesToRead;
ComPtr<IPortableDeviceValues> objectProperties;
// Get an IPortableDeviceContent interface from the IPortableDevice interface to
// access the content-specific methods.
HRESULT hr = device->Content(&content);
if (FAILED(hr))
{
wprintf(L"! Failed to get IPortableDeviceContent from IPortableDevice, hr = 0x%lx\n", hr);
}
// Get an IPortableDeviceProperties interface from the IPortableDeviceContent interface
// to access the property-specific methods.
if (SUCCEEDED(hr))
{
hr = content->Properties(&properties);
if (FAILED(hr))
{
wprintf(L"! Failed to get IPortableDeviceProperties from IPortableDevice, hr = 0x%lx\n", hr);
}
}
// CoCreate an IPortableDeviceKeyCollection interface to hold the the property keys
// we wish to read WPD_RENDERING_INFORMATION_PROFILES)
hr = CoCreateInstance(CLSID_PortableDeviceKeyCollection,
nullptr,
CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&propertiesToRead));
if (SUCCEEDED(hr))
{
// Populate the IPortableDeviceKeyCollection with the keys we wish to read.
// NOTE: We are not handling any special error cases here so we can proceed with
// adding as many of the target properties as we can.
HRESULT tempHr = S_OK;
tempHr = propertiesToRead->Add(WPD_RENDERING_INFORMATION_PROFILES);
if (FAILED(tempHr))
{
wprintf(L"! Failed to add WPD_RENDERING_INFORMATION_PROFILES to IPortableDeviceKeyCollection, hr= 0x%lx\n", tempHr);
}
}
// Call GetValues() passing the collection of specified PROPERTYKEYs.
if (SUCCEEDED(hr))
{
hr = properties->GetValues(functionalObjectID, // The object whose properties we are reading
propertiesToRead.Get(), // The properties we want to read
&objectProperties); // Driver supplied property values for the specified object
if (FAILED(hr))
{
wprintf(L"! Failed to get all properties for object '%ws', hr= 0x%lx\n", functionalObjectID, hr);
}
}
// Read the WPD_RENDERING_INFORMATION_PROFILES
if (SUCCEEDED(hr))
{
hr = objectProperties->GetIPortableDeviceValuesCollectionValue(WPD_RENDERING_INFORMATION_PROFILES,
&renderingInfoProfilesTemp);
if (FAILED(hr))
{
wprintf(L"! Failed to get WPD_RENDERING_INFORMATION_PROFILES from rendering information, hr= 0x%lx\n", hr);
}
}
// QueryInterface the interface into the out-going parameters.
if (SUCCEEDED(hr))
{
*renderingInfoProfiles = renderingInfoProfilesTemp.Detach();
}
return hr;
}
void DisplayExpectedValues(
_In_ IPortableDeviceValues* expectedValues)
{
// 1) Determine what type of valid values should be displayed by reading the
// WPD_PROPERTY_ATTRIBUTE_FORM property.
DWORD formAttribute = WPD_PROPERTY_ATTRIBUTE_FORM_UNSPECIFIED;
HRESULT hr = expectedValues->GetUnsignedIntegerValue(WPD_PROPERTY_ATTRIBUTE_FORM, &formAttribute);
if (FAILED(hr))
{
wprintf(L"! Failed to get WPD_PROPERTY_ATTRIBUTE_FORM from expected value set, hr = 0x%lx\n", hr);
}
// 2) Switch on the attribute form to determine what expected value properties to read.
if (SUCCEEDED(hr))
{
switch(formAttribute)
{
case WPD_PROPERTY_ATTRIBUTE_FORM_RANGE:
{
DWORD rangeMin = 0;
DWORD rangeMax = 0;
DWORD rangeStep = 0;
hr = expectedValues->GetUnsignedIntegerValue(WPD_PROPERTY_ATTRIBUTE_RANGE_MIN, &rangeMin);
if (FAILED(hr))
{
wprintf(L"! Failed to get WPD_PROPERTY_ATTRIBUTE_RANGE_MIN from expected values collection, hr = 0x%lx\n", hr);
}
hr = expectedValues->GetUnsignedIntegerValue(WPD_PROPERTY_ATTRIBUTE_RANGE_MAX, &rangeMax);
if (FAILED(hr))
{
wprintf(L"! Failed to get WPD_PROPERTY_ATTRIBUTE_RANGE_MAX from expected values collection, hr = 0x%lx\n", hr);
}
hr = expectedValues->GetUnsignedIntegerValue(WPD_PROPERTY_ATTRIBUTE_RANGE_STEP, &rangeStep);
if (FAILED(hr))
{
wprintf(L"! Failed to get WPD_PROPERTY_ATTRIBUTE_RANGE_STEP from expected values collection, hr = 0x%lx\n", hr);
}
wprintf(L"MIN: %u, MAX: %u, STEP: %u\n", rangeMin, rangeMax, rangeStep);
}
break;
default:
wprintf(L"* DisplayExpectedValues helper function did not display attributes for form %u", formAttribute);
break;
}
}
}
// Displays a rendering profile.
void DisplayRenderingProfile(
_In_ IPortableDeviceValues* profile)
{
DWORD totalBitrate = 0;
DWORD channelCount = 0;
DWORD audioFormatCode = 0;
GUID objectFormat = WPD_OBJECT_FORMAT_UNSPECIFIED;
// Display WPD_MEDIA_TOTAL_BITRATE
HRESULT hr = profile->GetUnsignedIntegerValue(WPD_MEDIA_TOTAL_BITRATE, &totalBitrate);
if (SUCCEEDED(hr))
{
wprintf(L"Total Bitrate: %u\n", totalBitrate);
}
// If we fail to read the total bitrate as a single value, then it must be
// a valid value set. (i.e. returning IPortableDeviceValues as the value which
// contains properties describing the valid values for this property.)
if (hr == DISP_E_TYPEMISMATCH)
{
ComPtr<IPortableDeviceValues> expectedValues;
hr = profile->GetIPortableDeviceValuesValue(WPD_MEDIA_TOTAL_BITRATE, &expectedValues);
if (SUCCEEDED(hr))
{
wprintf(L"Total Bitrate: ");
DisplayExpectedValues(expectedValues.Get());
}
}
// If we are still a failure here, report the error
if (FAILED(hr))
{
wprintf(L"! Failed to get WPD_MEDIA_TOTAL_BITRATE from rendering profile, hr = 0x%lx\n", hr);
}
// Display WPD_AUDIO_CHANNEL_COUNT
hr = profile->GetUnsignedIntegerValue(WPD_AUDIO_CHANNEL_COUNT, &channelCount);
if (SUCCEEDED(hr))
{
wprintf(L"Channel Count: %u\n", channelCount);
}
else
{
wprintf(L"! Failed to get WPD_AUDIO_CHANNEL_COUNT from rendering profile, hr = 0x%lx\n", hr);
}
// Display WPD_AUDIO_FORMAT_CODE
hr = profile->GetUnsignedIntegerValue(WPD_AUDIO_FORMAT_CODE, &audioFormatCode);
if (SUCCEEDED(hr))
{
wprintf(L"Audio Format Code: %u\n", audioFormatCode);
}
else
{
wprintf(L"! Failed to get WPD_AUDIO_FORMAT_CODE from rendering profile, hr = 0x%lx\n", hr);
}
// Display WPD_OBJECT_FORMAT
hr = profile->GetGuidValue(WPD_OBJECT_FORMAT, &objectFormat);
if (SUCCEEDED(hr))
{
wprintf(L"Object Format: %ws\n", (PCWSTR)(PCWSTR)CGuidToString(objectFormat));
}
else
{
wprintf(L"! Failed to get WPD_OBJECT_FORMAT from rendering profile, hr = 0x%lx\n", hr);
}
}
// List rendering capabilities the device supports
void ListRenderingCapabilityInformation(
_In_ IPortableDevice* device)
{
HRESULT hr = S_OK;
ComPtr<IPortableDeviceCapabilities> capabilities;
ComPtr<IPortableDevicePropVariantCollection> renderingInfoObjects;
ComPtr<IPortableDeviceValuesCollection> renderingInfoProfiles;
if (SupportsFunctionalCategory(device, WPD_FUNCTIONAL_CATEGORY_RENDERING_INFORMATION) == FALSE)
{
wprintf(L"This device does not support device rendering information to display\n");
return;
}
// Get an IPortableDeviceCapabilities interface from the IPortableDevice interface to
// access the device capabilities-specific methods.
hr = device->Capabilities(&capabilities);
if (FAILED(hr))
{
wprintf(L"! Failed to get IPortableDeviceCapabilities from IPortableDevice, hr = 0x%lx\n", hr);
}
// Get the functional object identifier for the rendering information object
if (SUCCEEDED(hr))
{
hr = capabilities->GetFunctionalObjects(WPD_FUNCTIONAL_CATEGORY_RENDERING_INFORMATION, &renderingInfoObjects);
if (FAILED(hr))
{
wprintf(L"! Failed to get functional objects, hr = 0x%lx\n", hr);
}
}
// Assume the device only has one rendering information object for this example.
// We are going to request the first Object Identifier found in the collection.
if (SUCCEEDED(hr))
{
PROPVARIANT pv = {0};
hr = renderingInfoObjects->GetAt(0, &pv);
if (SUCCEEDED(hr) &&
pv.vt == VT_LPWSTR &&
pv.pwszVal != nullptr)
{
hr = ReadProfileInformationProperties(device,
pv.pwszVal,
&renderingInfoProfiles);
// Error output statements are performed by the helper function, so they
// are omitted here.
// Display all rendering profiles
if (SUCCEEDED(hr))
{
// Get the number of profiles supported by the device
DWORD numProfiles = 0;
hr = renderingInfoProfiles->GetCount(&numProfiles);
if (FAILED(hr))
{
wprintf(L"! Failed to get number of profiles supported by the device, hr = 0x%lx\n", hr);
}
wprintf(L"%u Rendering Profiles are supported by this device\n", numProfiles);
if (SUCCEEDED(hr))
{
for (DWORD index = 0; index < numProfiles; index++)
{
ComPtr<IPortableDeviceValues> profile;
hr = renderingInfoProfiles->GetAt(index, &profile);
if (SUCCEEDED(hr))
{
wprintf(L"\nProfile #%u:\n", index);
DisplayRenderingProfile(profile.Get());
wprintf(L"\n\n");
}
else
{
wprintf(L"! Failed to get rendering profile at index '%u', hr = 0x%lx\n", index, hr);
}
}
}
}
}
else
{
wprintf(L"! Failed to get first rendering object's identifier, hr = 0x%lx\n", hr);
}
PropVariantClear(&pv);
}
}
// List all supported events on the device
void ListSupportedEvents(
_In_ IPortableDevice* device)
{
//<SnippetCapabilities4>
ComPtr<IPortableDeviceCapabilities> capabilities;
ComPtr<IPortableDevicePropVariantCollection> events;
DWORD numEvents = 0;
HRESULT hr = S_OK;
// Get an IPortableDeviceCapabilities interface from the IPortableDevice interface to
// access the device capabilities-specific methods.
hr = device->Capabilities(&capabilities);
if (FAILED(hr))
{
wprintf(L"! Failed to get IPortableDeviceCapabilities from IPortableDevice, hr = 0x%lx\n", hr);
}
//</SnippetCapabilities4>
// Get all events supported by the device.
//<SnippetCapabilities5>
if (SUCCEEDED(hr))
{
hr = capabilities->GetSupportedEvents(&events);
if (FAILED(hr))
{
wprintf(L"! Failed to get supported events from the device, hr = 0x%lx\n", hr);
}
}
//</SnippetCapabilities5>
// Get the number of supported events found on the device.
//<SnippetCapabilities6>
if (SUCCEEDED(hr))
{
hr = events->GetCount(&numEvents);
if (FAILED(hr))
{
wprintf(L"! Failed to get number of supported events, hr = 0x%lx\n", hr);
}
}
wprintf(L"\n%u Supported Events Found on the device\n\n", numEvents);
// Loop through each event and display its name
if (SUCCEEDED(hr))
{
for (DWORD index = 0; index < numEvents; index++)
{
PROPVARIANT pv = {0};
hr = events->GetAt(index, &pv);
if (SUCCEEDED(hr))
{
// We have an event. It is assumed that
// events are returned as VT_CLSID varTypes.
if (pv.vt == VT_CLSID &&
pv.puuid != nullptr)
{
// Display the event name
DisplayEvent(*pv.puuid);
wprintf(L"\n");
// Display the event options
DisplayEventOptions(capabilities.Get(), *pv.puuid);
wprintf(L"\n");
}
}
PropVariantClear(&pv);
}
}
//</SnippetCapabilities6>
}
|
// codeforces/644div3/D/main.cpp
// author: @___Johniel
// github: https://github.com/johniel/
#include <bits/stdc++.h>
#define each(i, c) for (auto& i : c)
#define unless(cond) if (!(cond))
using namespace std;
template<typename P, typename Q> ostream& operator << (ostream& os, pair<P, Q> p) { os << "(" << p.first << "," << p.second << ")"; return os; }
template<typename P, typename Q> istream& operator >> (istream& is, pair<P, Q>& p) { is >> p.first >> p.second; return is; }
template<typename T> ostream& operator << (ostream& os, vector<T> v) { os << "("; for (auto& i: v) os << i << ","; os << ")"; return os; }
template<typename T> istream& operator >> (istream& is, vector<T>& v) { for (auto& i: v) is >> i; return is; }
template<typename T> ostream& operator << (ostream& os, set<T> s) { os << "#{"; for (auto& i: s) os << i << ","; os << "}"; return os; }
template<typename K, typename V> ostream& operator << (ostream& os, map<K, V> m) { os << "{"; for (auto& i: m) os << i << ","; os << "}"; return os; }
template<typename T> inline T setmax(T& a, T b) { return a = std::max(a, b); }
template<typename T> inline T setmin(T& a, T b) { return a = std::min(a, b); }
using lli = long long int;
using ull = unsigned long long;
using point = complex<double>;
using str = string;
template<typename T> using vec = vector<T>;
constexpr array<int, 8> di({0, 1, -1, 0, 1, -1, 1, -1});
constexpr array<int, 8> dj({1, 0, 0, -1, 1, -1, -1, 1});
constexpr lli mod = 1e9 + 7;
int main(int argc, char *argv[])
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.setf(ios_base::fixed);
cout.precision(15);
int _;
cin >> _;
lli n, k;
while (cin >> n >> k) {
lli mn = 1LL << 60;
for (lli i = 1; i * i <= n && i <= k; ++i) {
if (n % i == 0) {
setmin(mn, n / i);
lli j = n / i;
if (j <= k) {
setmin(mn, i);
}
}
}
cout << mn << endl;
}
return 0;
}
|
/**
* BCL to FASTQ file converter
* Copyright (c) 2007-2017 Illumina, Inc.
*
* This software is covered by the accompanying EULA
* and certain third party copyright/licenses, and any user of this
* source file is bound by the terms therein.
*
* \file FileExistenceVerifier.cpp
*
* \brief Implementation of FileExistenceVerifier.
*
* \author Aaron Day
*/
#include "layout/FileExistenceVerifier.hh"
#include "layout/LaneInfo.hh"
#include "data/FilterFile.hh"
#include "data/PositionsFile.hh"
#include "data/BclFile.hh"
#include "data/CbclFile.hh"
namespace bcl2fastq
{
namespace layout
{
void FileExistenceVerifier::verifyAllFilesExist(const boost::filesystem::path& inputDir,
const boost::filesystem::path& intensitiesDir,
const LaneInfo& laneInfo,
const common::TileFileMap& tileFileNameMap,
common::TileAggregationMode aggregateTilesMode,
bool isPatternedFlowcell,
bool ignoreMissingBcls,
bool ignoreMissingFilters,
bool ignoreMissingPositions)
{
if (aggregateTilesMode == common::TileAggregationMode::AGGREGATED)
{
verifyFilesExist(inputDir,
intensitiesDir,
laneInfo,
tileFileNameMap,
aggregateTilesMode,
isPatternedFlowcell,
ignoreMissingBcls,
ignoreMissingFilters,
ignoreMissingPositions);
}
else
{
for (const auto& tileInfo : laneInfo.getTileInfos())
{
verifyFilesExist(inputDir,
intensitiesDir,
laneInfo,
tileFileNameMap,
aggregateTilesMode,
isPatternedFlowcell,
ignoreMissingBcls,
ignoreMissingFilters,
ignoreMissingPositions,
tileInfo.getNumber());
}
}
}
void FileExistenceVerifier::verifyFilesExist(const boost::filesystem::path& inputDir,
const boost::filesystem::path& intensitiesDir,
const LaneInfo& laneInfo,
const common::TileFileMap& tileFileNameMap,
common::TileAggregationMode aggregateTilesMode,
bool isPatternedFlowcell,
bool ignoreMissingBcls,
bool ignoreMissingFilters,
bool ignoreMissingPositions,
const common::TileNumber tileNumber /*= 0*/)
{
for (const auto& readInfo : laneInfo.readInfos())
{
if (!ignoreMissingBcls)
{
for (const layout::CycleInfo &cycleInfo : readInfo.cycleInfos())
{
verifyBclFileExists(inputDir,
aggregateTilesMode,
laneInfo.getNumber(),
cycleInfo.getNumber(),
tileNumber,
tileFileNameMap);
}
}
if (!ignoreMissingFilters)
{
verifyFilterFileExists(inputDir,
aggregateTilesMode,
laneInfo.getNumber(),
tileNumber,
readInfo.getNumber());
}
}
if (!ignoreMissingPositions)
{
verifyPositionsFileExists(intensitiesDir,
aggregateTilesMode,
isPatternedFlowcell,
laneInfo.getNumber(),
tileNumber);
}
}
void FileExistenceVerifier::verifyBclFileExists(const boost::filesystem::path& inputDir,
common::TileAggregationMode aggregateTilesMode,
common::LaneNumber laneNumber,
common::CycleNumber cycleNumber,
common::TileNumber tileNumber,
const common::TileFileMap& tileFileNameMap)
{
boost::filesystem::path fileName;
switch (aggregateTilesMode)
{
case common::TileAggregationMode::AGGREGATED:
data::BclFile::getAndVerifyFileName(inputDir,
laneNumber,
cycleNumber,
false,
fileName);
break;
case common::TileAggregationMode::NON_AGGREGATED:
data::BclFile::getAndVerifyFileName(inputDir,
laneNumber,
tileNumber,
cycleNumber,
false,
fileName);
break;
case common::TileAggregationMode::CBCL:
fileName = data::CbclFileReader::getFileName(inputDir,
laneNumber,
cycleNumber,
tileNumber,
tileFileNameMap,
false);
break;
default:
BCL2FASTQ_ASSERT_MSG(false, "Unexpected aggregation mode type");
}
}
void FileExistenceVerifier::verifyFilterFileExists(const boost::filesystem::path& inputDir,
common::TileAggregationMode aggregateTilesMode,
common::LaneNumber laneNumber,
common::TileNumber tileNumber,
common::ReadNumber readNumber)
{
size_t headerSize = 0;
boost::filesystem::path filePath;
if (!(data::FilterFile::doesFileExist(inputDir,
aggregateTilesMode == common::TileAggregationMode::AGGREGATED,
laneNumber,
tileNumber,
headerSize,
filePath)))
{
throwException("filter",
aggregateTilesMode,
laneNumber,
tileNumber);
}
}
void FileExistenceVerifier::verifyPositionsFileExists(const boost::filesystem::path& intensitiesDir,
common::TileAggregationMode aggregateTilesMode,
bool isPatternedFlowcell,
common::LaneNumber laneNumber,
common::TileNumber tileNumber)
{
size_t headerSize = 0;
boost::filesystem::path posFilePath;
if (!data::PositionsFileFactory::doesFileExist(intensitiesDir,
aggregateTilesMode == common::TileAggregationMode::AGGREGATED ||
aggregateTilesMode == common::TileAggregationMode::CBCL,
isPatternedFlowcell,
laneNumber,
tileNumber,
headerSize,
posFilePath))
{
throwException("positions",
aggregateTilesMode,
laneNumber,
tileNumber);
}
}
void FileExistenceVerifier::throwException(const std::string& fileType,
common::TileAggregationMode aggregateTilesMode,
common::LaneNumber laneNumber,
common::TileNumber tileNumber)
{
std::stringstream str;
str << "Unable to find " << fileType << " file for lane: " << laneNumber;
if (aggregateTilesMode == common::TileAggregationMode::NON_AGGREGATED)
{
str << " and tile: " << tileNumber;
}
str << std::endl;
BOOST_THROW_EXCEPTION(common::IoError(ENOENT, str.str()));
}
} // namespace layout
} // namespace bcl2fastq
|
#include "pch.h"
#include <vcpkg/base/cofffilereader.h>
#include <vcpkg/base/files.h>
#include <vcpkg/base/system.print.h>
#include <vcpkg/base/system.process.h>
#include <vcpkg/base/util.h>
#include <vcpkg/build.h>
#include <vcpkg/packagespec.h>
#include <vcpkg/postbuildlint.buildtype.h>
#include <vcpkg/postbuildlint.h>
#include <vcpkg/vcpkgpaths.h>
using vcpkg::Build::BuildInfo;
using vcpkg::Build::BuildPolicy;
using vcpkg::Build::PreBuildInfo;
namespace vcpkg::PostBuildLint
{
static auto not_extension_pred(const Files::Filesystem& fs, const std::string& ext)
{
return [&fs, ext](const fs::path& path) { return fs.is_directory(path) || path.extension() != ext; };
}
enum class LintStatus
{
SUCCESS = 0,
ERROR_DETECTED = 1
};
struct OutdatedDynamicCrt
{
std::string name;
std::regex regex;
OutdatedDynamicCrt(const std::string& name, const std::string& regex_as_string)
: name(name), regex(std::regex(regex_as_string, std::regex_constants::icase))
{
}
};
static Span<const OutdatedDynamicCrt> get_outdated_dynamic_crts(const Optional<std::string>& toolset_version)
{
static const std::vector<OutdatedDynamicCrt> V_NO_120 = {
{"msvcp100.dll", R"(msvcp100\.dll)"},
{"msvcp100d.dll", R"(msvcp100d\.dll)"},
{"msvcp110.dll", R"(msvcp110\.dll)"},
{"msvcp110_win.dll", R"(msvcp110_win\.dll)"},
{"msvcp60.dll", R"(msvcp60\.dll)"},
{"msvcp60.dll", R"(msvcp60\.dll)"},
{"msvcrt.dll", R"(msvcrt\.dll)"},
{"msvcr100.dll", R"(msvcr100\.dll)"},
{"msvcr100d.dll", R"(msvcr100d\.dll)"},
{"msvcr100_clr0400.dll", R"(msvcr100_clr0400\.dll)"},
{"msvcr110.dll", R"(msvcr110\.dll)"},
{"msvcrt20.dll", R"(msvcrt20\.dll)"},
{"msvcrt40.dll", R"(msvcrt40\.dll)"},
};
static const std::vector<OutdatedDynamicCrt> V_NO_MSVCRT = [&]() {
auto ret = V_NO_120;
ret.push_back({"msvcp120.dll", R"(msvcp120\.dll)"});
ret.push_back({"msvcp120_clr0400.dll", R"(msvcp120_clr0400\.dll)"});
ret.push_back({"msvcr120.dll", R"(msvcr120\.dll)"});
ret.push_back({"msvcr120_clr0400.dll", R"(msvcr120_clr0400\.dll)"});
return ret;
}();
const auto tsv = toolset_version.get();
if (tsv && (*tsv) == "v120")
{
return V_NO_120;
}
// Default case for all version >= VS 2015.
return V_NO_MSVCRT;
}
static LintStatus check_for_files_in_include_directory(const Files::Filesystem& fs,
const Build::BuildPolicies& policies,
const fs::path& package_dir)
{
if (policies.is_enabled(BuildPolicy::EMPTY_INCLUDE_FOLDER))
{
return LintStatus::SUCCESS;
}
const fs::path include_dir = package_dir / "include";
if (!fs.exists(include_dir) || fs.is_empty(include_dir))
{
System::print2(System::Color::warning,
"The folder /include is empty or not present. This indicates the library was not correctly "
"installed.\n");
return LintStatus::ERROR_DETECTED;
}
return LintStatus::SUCCESS;
}
static LintStatus check_for_restricted_include_files(const Files::Filesystem& fs,
const Build::BuildPolicies& policies,
const fs::path& package_dir)
{
if (policies.is_enabled(BuildPolicy::ALLOW_RESTRICTED_HEADERS))
{
return LintStatus::SUCCESS;
}
// These files are taken from the libc6-dev package on Ubuntu inside /usr/include/x86_64-linux-gnu/sys/
static constexpr StringLiteral restricted_sys_filenames[] = {
"acct.h", "auxv.h", "bitypes.h", "cdefs.h", "debugreg.h", "dir.h", "elf.h",
"epoll.h", "errno.h", "eventfd.h", "fanotify.h", "fcntl.h", "file.h", "fsuid.h",
"gmon.h", "gmon_out.h", "inotify.h", "io.h", "ioctl.h", "ipc.h", "kd.h",
"klog.h", "mman.h", "mount.h", "msg.h", "mtio.h", "param.h", "pci.h",
"perm.h", "personality.h", "poll.h", "prctl.h", "procfs.h", "profil.h", "ptrace.h",
"queue.h", "quota.h", "random.h", "raw.h", "reboot.h", "reg.h", "resource.h",
"select.h", "sem.h", "sendfile.h", "shm.h", "signal.h", "signalfd.h", "socket.h",
"socketvar.h", "soundcard.h", "stat.h", "statfs.h", "statvfs.h", "stropts.h", "swap.h",
"syscall.h", "sysctl.h", "sysinfo.h", "syslog.h", "sysmacros.h", "termios.h", "time.h",
"timeb.h", "timerfd.h", "times.h", "timex.h", "ttychars.h", "ttydefaults.h", "types.h",
"ucontext.h", "uio.h", "un.h", "unistd.h", "user.h", "ustat.h", "utsname.h",
"vfs.h", "vlimit.h", "vm86.h", "vt.h", "vtimes.h", "wait.h", "xattr.h",
};
// These files are taken from the libc6-dev package on Ubuntu inside the /usr/include/ folder
static constexpr StringLiteral restricted_crt_filenames[] = {
"_G_config.h", "aio.h", "aliases.h", "alloca.h", "ar.h", "argp.h",
"argz.h", "assert.h", "byteswap.h", "complex.h", "cpio.h", "crypt.h",
"ctype.h", "dirent.h", "dlfcn.h", "elf.h", "endian.h", "envz.h",
"err.h", "errno.h", "error.h", "execinfo.h", "fcntl.h", "features.h",
"fenv.h", "fmtmsg.h", "fnmatch.h", "fstab.h", "fts.h", "ftw.h",
"gconv.h", "getopt.h", "glob.h", "gnu-versions.h", "grp.h", "gshadow.h",
"iconv.h", "ifaddrs.h", "inttypes.h", "langinfo.h", "lastlog.h", "libgen.h",
"libintl.h", "libio.h", "limits.h", "link.h", "locale.h", "malloc.h",
"math.h", "mcheck.h", "memory.h", "mntent.h", "monetary.h", "mqueue.h",
"netash", "netdb.h", "nl_types.h", "nss.h", "obstack.h", "paths.h",
"poll.h", "printf.h", "proc_service.h", "pthread.h", "pty.h", "pwd.h",
"re_comp.h", "regex.h", "regexp.h", "resolv.h", "sched.h", "search.h",
"semaphore.h", "setjmp.h", "sgtty.h", "shadow.h", "signal.h", "spawn.h",
"stab.h", "stdc-predef.h", "stdint.h", "stdio.h", "stdio_ext.h", "stdlib.h",
"string.h", "strings.h", "stropts.h", "syscall.h", "sysexits.h", "syslog.h",
"tar.h", "termio.h", "termios.h", "tgmath.h", "thread_db.h", "time.h",
"ttyent.h", "uchar.h", "ucontext.h", "ulimit.h", "unistd.h", "ustat.h",
"utime.h", "utmp.h", "utmpx.h", "values.h", "wait.h", "wchar.h",
"wctype.h", "wordexp.h",
};
// These files are general names that have shown to be problematic in the past
static constexpr StringLiteral restricted_general_filenames[] = {
"json.h",
"parser.h",
"lexer.h",
"config.h",
"local.h",
"slice.h",
"platform.h",
};
static constexpr Span<const StringLiteral> restricted_lists[] = {
restricted_sys_filenames, restricted_crt_filenames, restricted_general_filenames};
const fs::path include_dir = package_dir / "include";
auto files = fs.get_files_non_recursive(include_dir);
auto filenames_v = Util::fmap(files, [](const auto& file) { return file.filename().u8string(); });
std::set<std::string> filenames_s(filenames_v.begin(), filenames_v.end());
std::vector<fs::path> violations;
for (auto&& flist : restricted_lists)
for (auto&& f : flist)
{
if (Util::Sets::contains(filenames_s, f))
{
violations.push_back(fs::u8path("include") / fs::u8path(f.c_str()));
}
}
if (!violations.empty())
{
System::print2(System::Color::warning,
"Restricted headers paths are present. These files can prevent the core C++ runtime and "
"other packages from compiling correctly:\n");
Files::print_paths(violations);
System::print2("In exceptional circumstances, this policy can be disabled via ",
Build::to_cmake_variable(BuildPolicy::ALLOW_RESTRICTED_HEADERS),
"\n");
return LintStatus::ERROR_DETECTED;
}
return LintStatus::SUCCESS;
}
static LintStatus check_for_files_in_debug_include_directory(const Files::Filesystem& fs,
const fs::path& package_dir)
{
const fs::path debug_include_dir = package_dir / "debug" / "include";
std::vector<fs::path> files_found = fs.get_files_recursive(debug_include_dir);
Util::erase_remove_if(
files_found, [&fs](const fs::path& path) { return fs.is_directory(path) || path.extension() == ".ifc"; });
if (!files_found.empty())
{
System::print2(System::Color::warning,
"Include files should not be duplicated into the /debug/include directory. If this cannot "
"be disabled in the project cmake, use\n"
" file(REMOVE_RECURSE \"${CURRENT_PACKAGES_DIR}/debug/include\")\n");
return LintStatus::ERROR_DETECTED;
}
return LintStatus::SUCCESS;
}
static LintStatus check_for_files_in_debug_share_directory(const Files::Filesystem& fs, const fs::path& package_dir)
{
const fs::path debug_share = package_dir / "debug" / "share";
if (fs.exists(debug_share))
{
System::print2(System::Color::warning,
"/debug/share should not exist. Please reorganize any important files, then use\n"
" file(REMOVE_RECURSE \"${CURRENT_PACKAGES_DIR}/debug/share\")\n");
return LintStatus::ERROR_DETECTED;
}
return LintStatus::SUCCESS;
}
static LintStatus check_folder_lib_cmake(const Files::Filesystem& fs,
const fs::path& package_dir,
const PackageSpec& spec)
{
const fs::path lib_cmake = package_dir / "lib" / "cmake";
if (fs.exists(lib_cmake))
{
System::printf(System::Color::warning,
"The /lib/cmake folder should be merged with /debug/lib/cmake and moved to "
"/share/%s/cmake.\nPlease use the helper function `vcpkg_fixup_cmake_targets()`\n",
spec.name());
return LintStatus::ERROR_DETECTED;
}
return LintStatus::SUCCESS;
}
static LintStatus check_for_misplaced_cmake_files(const Files::Filesystem& fs,
const fs::path& package_dir,
const PackageSpec& spec)
{
std::vector<fs::path> dirs = {
package_dir / "cmake",
package_dir / "debug" / "cmake",
package_dir / "lib" / "cmake",
package_dir / "debug" / "lib" / "cmake",
};
std::vector<fs::path> misplaced_cmake_files;
for (auto&& dir : dirs)
{
auto files = fs.get_files_recursive(dir);
for (auto&& file : files)
{
if (!fs.is_directory(file) && file.extension() == ".cmake")
misplaced_cmake_files.push_back(std::move(file));
}
}
if (!misplaced_cmake_files.empty())
{
System::printf(
System::Color::warning,
"The following cmake files were found outside /share/%s. Please place cmake files in /share/%s.\n",
spec.name(),
spec.name());
Files::print_paths(misplaced_cmake_files);
return LintStatus::ERROR_DETECTED;
}
return LintStatus::SUCCESS;
}
static LintStatus check_folder_debug_lib_cmake(const Files::Filesystem& fs,
const fs::path& package_dir,
const PackageSpec& spec)
{
const fs::path lib_cmake_debug = package_dir / "debug" / "lib" / "cmake";
if (fs.exists(lib_cmake_debug))
{
System::printf(System::Color::warning,
"The /debug/lib/cmake folder should be merged with /lib/cmake into /share/%s\n",
spec.name());
return LintStatus::ERROR_DETECTED;
}
return LintStatus::SUCCESS;
}
static LintStatus check_for_dlls_in_lib_dir(const Files::Filesystem& fs, const fs::path& package_dir)
{
std::vector<fs::path> dlls = fs.get_files_recursive(package_dir / "lib");
Util::erase_remove_if(dlls, not_extension_pred(fs, ".dll"));
if (!dlls.empty())
{
System::print2(System::Color::warning,
"\nThe following dlls were found in /lib or /debug/lib. Please move them to /bin or "
"/debug/bin, respectively.\n");
Files::print_paths(dlls);
return LintStatus::ERROR_DETECTED;
}
return LintStatus::SUCCESS;
}
static LintStatus check_for_copyright_file(const Files::Filesystem& fs,
const PackageSpec& spec,
const VcpkgPaths& paths)
{
const fs::path packages_dir = paths.packages / spec.dir();
const fs::path copyright_file = packages_dir / "share" / spec.name() / "copyright";
if (fs.exists(copyright_file))
{
return LintStatus::SUCCESS;
}
const fs::path current_buildtrees_dir = paths.build_dir(spec);
const fs::path current_buildtrees_dir_src = current_buildtrees_dir / "src";
std::vector<fs::path> potential_copyright_files;
// We only search in the root of each unpacked source archive to reduce false positives
auto src_dirs = fs.get_files_non_recursive(current_buildtrees_dir_src);
for (auto&& src_dir : src_dirs)
{
if (!fs.is_directory(src_dir)) continue;
for (auto&& src_file : fs.get_files_non_recursive(src_dir))
{
const std::string filename = src_file.filename().string();
if (filename == "LICENSE" || filename == "LICENSE.txt" || filename == "COPYING")
{
potential_copyright_files.push_back(src_file);
}
}
}
System::printf(System::Color::warning,
"The software license must be available at ${CURRENT_PACKAGES_DIR}/share/%s/copyright\n",
spec.name());
if (potential_copyright_files.size() == 1)
{
// if there is only one candidate, provide the cmake lines needed to place it in the proper location
const fs::path found_file = potential_copyright_files[0];
auto found_relative_native = found_file.native();
found_relative_native.erase(current_buildtrees_dir.native().size() +
1); // The +1 is needed to remove the "/"
const fs::path relative_path = found_relative_native;
System::printf("\n configure_file(\"${CURRENT_BUILDTREES_DIR}/%s/%s\" "
"\"${CURRENT_PACKAGES_DIR}/share/%s/copyright\" COPYONLY)\n",
relative_path.generic_string(),
found_file.filename().generic_string(),
spec.name());
}
else if (potential_copyright_files.size() > 1)
{
System::print2(System::Color::warning, "The following files are potential copyright files:\n");
Files::print_paths(potential_copyright_files);
}
return LintStatus::ERROR_DETECTED;
}
static LintStatus check_for_exes(const Files::Filesystem& fs, const fs::path& package_dir)
{
std::vector<fs::path> exes = fs.get_files_recursive(package_dir / "bin");
Util::erase_remove_if(exes, not_extension_pred(fs, ".exe"));
if (!exes.empty())
{
System::print2(
System::Color::warning,
"The following EXEs were found in /bin or /debug/bin. EXEs are not valid distribution targets.\n");
Files::print_paths(exes);
return LintStatus::ERROR_DETECTED;
}
return LintStatus::SUCCESS;
}
static LintStatus check_exports_of_dlls(const Build::BuildPolicies& policies,
const std::vector<fs::path>& dlls,
const fs::path& dumpbin_exe)
{
if (policies.is_enabled(BuildPolicy::DLLS_WITHOUT_EXPORTS)) return LintStatus::SUCCESS;
std::vector<fs::path> dlls_with_no_exports;
for (const fs::path& dll : dlls)
{
const std::string cmd_line =
Strings::format(R"("%s" /exports "%s")", dumpbin_exe.u8string(), dll.u8string());
System::ExitCodeAndOutput ec_data = System::cmd_execute_and_capture_output(cmd_line);
Checks::check_exit(VCPKG_LINE_INFO, ec_data.exit_code == 0, "Running command:\n %s\n failed", cmd_line);
if (ec_data.output.find("ordinal hint RVA name") == std::string::npos)
{
dlls_with_no_exports.push_back(dll);
}
}
if (!dlls_with_no_exports.empty())
{
System::print2(System::Color::warning, "The following DLLs have no exports:\n");
Files::print_paths(dlls_with_no_exports);
System::print2(System::Color::warning, "DLLs without any exports are likely a bug in the build script.\n");
System::printf(System::Color::warning,
"If this is intended, add the following line in the portfile:\n"
" SET(%s enabled)\n",
to_cmake_variable(BuildPolicy::DLLS_WITHOUT_EXPORTS));
return LintStatus::ERROR_DETECTED;
}
return LintStatus::SUCCESS;
}
static LintStatus check_uwp_bit_of_dlls(const std::string& expected_system_name,
const std::vector<fs::path>& dlls,
const fs::path dumpbin_exe)
{
if (expected_system_name != "WindowsStore")
{
return LintStatus::SUCCESS;
}
std::vector<fs::path> dlls_with_improper_uwp_bit;
for (const fs::path& dll : dlls)
{
const std::string cmd_line =
Strings::format(R"("%s" /headers "%s")", dumpbin_exe.u8string(), dll.u8string());
System::ExitCodeAndOutput ec_data = System::cmd_execute_and_capture_output(cmd_line);
Checks::check_exit(VCPKG_LINE_INFO, ec_data.exit_code == 0, "Running command:\n %s\n failed", cmd_line);
if (ec_data.output.find("App Container") == std::string::npos)
{
dlls_with_improper_uwp_bit.push_back(dll);
}
}
if (!dlls_with_improper_uwp_bit.empty())
{
System::print2(System::Color::warning, "The following DLLs do not have the App Container bit set:\n");
Files::print_paths(dlls_with_improper_uwp_bit);
System::print2(System::Color::warning, "This bit is required for Windows Store apps.\n");
return LintStatus::ERROR_DETECTED;
}
return LintStatus::SUCCESS;
}
struct FileAndArch
{
fs::path file;
std::string actual_arch;
};
#if defined(_WIN32)
static std::string get_actual_architecture(const MachineType& machine_type)
{
switch (machine_type)
{
case MachineType::AMD64:
case MachineType::IA64: return "x64";
case MachineType::I386: return "x86";
case MachineType::ARM:
case MachineType::ARMNT: return "arm";
case MachineType::ARM64: return "arm64";
default: return "Machine Type Code = " + std::to_string(static_cast<uint16_t>(machine_type));
}
}
#endif
#if defined(_WIN32)
static void print_invalid_architecture_files(const std::string& expected_architecture,
std::vector<FileAndArch> binaries_with_invalid_architecture)
{
System::print2(System::Color::warning, "The following files were built for an incorrect architecture:\n\n");
for (const FileAndArch& b : binaries_with_invalid_architecture)
{
System::print2(" ",
b.file.u8string(),
"\n"
"Expected ",
expected_architecture,
", but was: ",
b.actual_arch,
"\n\n");
}
}
static LintStatus check_dll_architecture(const std::string& expected_architecture,
const std::vector<fs::path>& files)
{
std::vector<FileAndArch> binaries_with_invalid_architecture;
for (const fs::path& file : files)
{
Checks::check_exit(VCPKG_LINE_INFO,
file.extension() == ".dll",
"The file extension was not .dll: %s",
file.generic_string());
const CoffFileReader::DllInfo info = CoffFileReader::read_dll(file);
const std::string actual_architecture = get_actual_architecture(info.machine_type);
if (expected_architecture != actual_architecture)
{
binaries_with_invalid_architecture.push_back({file, actual_architecture});
}
}
if (!binaries_with_invalid_architecture.empty())
{
print_invalid_architecture_files(expected_architecture, binaries_with_invalid_architecture);
return LintStatus::ERROR_DETECTED;
}
return LintStatus::SUCCESS;
}
#endif
static LintStatus check_lib_architecture(const std::string& expected_architecture,
const std::vector<fs::path>& files)
{
#if defined(_WIN32)
std::vector<FileAndArch> binaries_with_invalid_architecture;
for (const fs::path& file : files)
{
Checks::check_exit(VCPKG_LINE_INFO,
file.extension() == ".lib",
"The file extension was not .lib: %s",
file.generic_string());
CoffFileReader::LibInfo info = CoffFileReader::read_lib(file);
// This is zero for folly's debug library
// TODO: Why?
if (info.machine_types.size() == 0) return LintStatus::SUCCESS;
Checks::check_exit(VCPKG_LINE_INFO,
info.machine_types.size() == 1,
"Found more than 1 architecture in file %s",
file.generic_string());
const std::string actual_architecture = get_actual_architecture(info.machine_types.at(0));
if (expected_architecture != actual_architecture)
{
binaries_with_invalid_architecture.push_back({file, actual_architecture});
}
}
if (!binaries_with_invalid_architecture.empty())
{
print_invalid_architecture_files(expected_architecture, binaries_with_invalid_architecture);
return LintStatus::ERROR_DETECTED;
}
#endif
Util::unused(expected_architecture, files);
return LintStatus::SUCCESS;
}
static LintStatus check_no_dlls_present(const std::vector<fs::path>& dlls)
{
if (dlls.empty())
{
return LintStatus::SUCCESS;
}
System::print2(System::Color::warning,
"DLLs should not be present in a static build, but the following DLLs were found:\n");
Files::print_paths(dlls);
return LintStatus::ERROR_DETECTED;
}
static LintStatus check_matching_debug_and_release_binaries(const std::vector<fs::path>& debug_binaries,
const std::vector<fs::path>& release_binaries)
{
const size_t debug_count = debug_binaries.size();
const size_t release_count = release_binaries.size();
if (debug_count == release_count)
{
return LintStatus::SUCCESS;
}
System::printf(System::Color::warning,
"Mismatching number of debug and release binaries. Found %zd for debug but %zd for release.\n",
debug_count,
release_count);
System::print2("Debug binaries\n");
Files::print_paths(debug_binaries);
System::print2("Release binaries\n");
Files::print_paths(release_binaries);
if (debug_count == 0)
{
System::print2(System::Color::warning, "Debug binaries were not found\n");
}
if (release_count == 0)
{
System::print2(System::Color::warning, "Release binaries were not found\n");
}
System::print2("\n");
return LintStatus::ERROR_DETECTED;
}
static LintStatus check_lib_files_are_available_if_dlls_are_available(const Build::BuildPolicies& policies,
const size_t lib_count,
const size_t dll_count,
const fs::path& lib_dir)
{
if (policies.is_enabled(BuildPolicy::DLLS_WITHOUT_LIBS)) return LintStatus::SUCCESS;
if (lib_count == 0 && dll_count != 0)
{
System::print2(System::Color::warning, "Import libs were not present in ", lib_dir.u8string(), "\n");
System::printf(System::Color::warning,
"If this is intended, add the following line in the portfile:\n"
" SET(%s enabled)\n",
to_cmake_variable(BuildPolicy::DLLS_WITHOUT_LIBS));
return LintStatus::ERROR_DETECTED;
}
return LintStatus::SUCCESS;
}
static LintStatus check_bin_folders_are_not_present_in_static_build(const Files::Filesystem& fs,
const fs::path& package_dir)
{
const fs::path bin = package_dir / "bin";
const fs::path debug_bin = package_dir / "debug" / "bin";
if (!fs.exists(bin) && !fs.exists(debug_bin))
{
return LintStatus::SUCCESS;
}
if (fs.exists(bin))
{
System::printf(System::Color::warning,
R"(There should be no bin\ directory in a static build, but %s is present.)"
"\n",
bin.u8string());
}
if (fs.exists(debug_bin))
{
System::printf(System::Color::warning,
R"(There should be no debug\bin\ directory in a static build, but %s is present.)"
"\n",
debug_bin.u8string());
}
System::print2(
System::Color::warning,
R"(If the creation of bin\ and/or debug\bin\ cannot be disabled, use this in the portfile to remove them)"
"\n"
"\n"
R"###( if(VCPKG_LIBRARY_LINKAGE STREQUAL "static"))###"
"\n"
R"###( file(REMOVE_RECURSE "${CURRENT_PACKAGES_DIR}/bin" "${CURRENT_PACKAGES_DIR}/debug/bin"))###"
"\n"
R"###( endif())###"
"\n\n");
return LintStatus::ERROR_DETECTED;
}
static LintStatus check_no_empty_folders(const Files::Filesystem& fs, const fs::path& dir)
{
std::vector<fs::path> empty_directories = fs.get_files_recursive(dir);
Util::erase_remove_if(empty_directories, [&fs](const fs::path& current) {
return !fs.is_directory(current) || !fs.is_empty(current);
});
if (!empty_directories.empty())
{
System::print2(System::Color::warning, "There should be no empty directories in ", dir.u8string(), "\n");
System::print2("The following empty directories were found:\n");
Files::print_paths(empty_directories);
System::print2(
System::Color::warning,
"If a directory should be populated but is not, this might indicate an error in the portfile.\n"
"If the directories are not needed and their creation cannot be disabled, use something like this in "
"the portfile to remove them:\n"
"\n"
R"###( file(REMOVE_RECURSE "${CURRENT_PACKAGES_DIR}/a/dir" "${CURRENT_PACKAGES_DIR}/some/other/dir"))###"
"\n"
"\n"
"\n");
return LintStatus::ERROR_DETECTED;
}
return LintStatus::SUCCESS;
}
struct BuildTypeAndFile
{
fs::path file;
BuildType build_type;
};
static LintStatus check_crt_linkage_of_libs(const BuildType& expected_build_type,
const std::vector<fs::path>& libs,
const fs::path dumpbin_exe)
{
std::vector<BuildType> bad_build_types(BuildTypeC::VALUES.cbegin(), BuildTypeC::VALUES.cend());
bad_build_types.erase(std::remove(bad_build_types.begin(), bad_build_types.end(), expected_build_type),
bad_build_types.end());
std::vector<BuildTypeAndFile> libs_with_invalid_crt;
for (const fs::path& lib : libs)
{
const std::string cmd_line =
Strings::format(R"("%s" /directives "%s")", dumpbin_exe.u8string(), lib.u8string());
System::ExitCodeAndOutput ec_data = System::cmd_execute_and_capture_output(cmd_line);
Checks::check_exit(VCPKG_LINE_INFO,
ec_data.exit_code == 0,
"Running command:\n %s\n failed with message:\n%s",
cmd_line,
ec_data.output);
for (const BuildType& bad_build_type : bad_build_types)
{
if (std::regex_search(ec_data.output.cbegin(), ec_data.output.cend(), bad_build_type.crt_regex()))
{
libs_with_invalid_crt.push_back({lib, bad_build_type});
break;
}
}
}
if (!libs_with_invalid_crt.empty())
{
System::printf(System::Color::warning,
"Expected %s crt linkage, but the following libs had invalid crt linkage:\n\n",
expected_build_type.to_string());
for (const BuildTypeAndFile& btf : libs_with_invalid_crt)
{
System::printf(" %s: %s\n", btf.file.generic_string(), btf.build_type.to_string());
}
System::print2("\n");
System::print2(System::Color::warning,
"To inspect the lib files, use:\n dumpbin.exe /directives mylibfile.lib\n");
return LintStatus::ERROR_DETECTED;
}
return LintStatus::SUCCESS;
}
struct OutdatedDynamicCrtAndFile
{
fs::path file;
OutdatedDynamicCrt outdated_crt;
};
static LintStatus check_outdated_crt_linkage_of_dlls(const std::vector<fs::path>& dlls,
const fs::path dumpbin_exe,
const BuildInfo& build_info,
const PreBuildInfo& pre_build_info)
{
if (build_info.policies.is_enabled(BuildPolicy::ALLOW_OBSOLETE_MSVCRT)) return LintStatus::SUCCESS;
std::vector<OutdatedDynamicCrtAndFile> dlls_with_outdated_crt;
for (const fs::path& dll : dlls)
{
const auto cmd_line = Strings::format(R"("%s" /dependents "%s")", dumpbin_exe.u8string(), dll.u8string());
System::ExitCodeAndOutput ec_data = System::cmd_execute_and_capture_output(cmd_line);
Checks::check_exit(VCPKG_LINE_INFO, ec_data.exit_code == 0, "Running command:\n %s\n failed", cmd_line);
for (const OutdatedDynamicCrt& outdated_crt : get_outdated_dynamic_crts(pre_build_info.platform_toolset))
{
if (std::regex_search(ec_data.output.cbegin(), ec_data.output.cend(), outdated_crt.regex))
{
dlls_with_outdated_crt.push_back({dll, outdated_crt});
break;
}
}
}
if (!dlls_with_outdated_crt.empty())
{
System::print2(System::Color::warning, "Detected outdated dynamic CRT in the following files:\n\n");
for (const OutdatedDynamicCrtAndFile& btf : dlls_with_outdated_crt)
{
System::print2(" ", btf.file.u8string(), ": ", btf.outdated_crt.name, "\n");
}
System::print2("\n");
System::print2(System::Color::warning,
"To inspect the dll files, use:\n dumpbin.exe /dependents mydllfile.dll\n");
return LintStatus::ERROR_DETECTED;
}
return LintStatus::SUCCESS;
}
static LintStatus check_no_files_in_dir(const Files::Filesystem& fs, const fs::path& dir)
{
std::vector<fs::path> misplaced_files = fs.get_files_non_recursive(dir);
Util::erase_remove_if(misplaced_files, [&fs](const fs::path& path) {
const std::string filename = path.filename().generic_string();
if (Strings::case_insensitive_ascii_equals(filename, "CONTROL") ||
Strings::case_insensitive_ascii_equals(filename, "BUILD_INFO"))
{
return true;
}
return fs.is_directory(path);
});
if (!misplaced_files.empty())
{
System::print2(System::Color::warning, "The following files are placed in\n", dir.u8string(), ":\n");
Files::print_paths(misplaced_files);
System::print2(System::Color::warning, "Files cannot be present in those directories.\n\n");
return LintStatus::ERROR_DETECTED;
}
return LintStatus::SUCCESS;
}
static void operator+=(size_t& left, const LintStatus& right) { left += static_cast<size_t>(right); }
static size_t perform_all_checks_and_return_error_count(const PackageSpec& spec,
const VcpkgPaths& paths,
const PreBuildInfo& pre_build_info,
const BuildInfo& build_info)
{
const auto& fs = paths.get_filesystem();
// for dumpbin
const Toolset& toolset = paths.get_toolset(pre_build_info);
const fs::path package_dir = paths.package_dir(spec);
size_t error_count = 0;
if (build_info.policies.is_enabled(BuildPolicy::EMPTY_PACKAGE))
{
return error_count;
}
error_count += check_for_files_in_include_directory(fs, build_info.policies, package_dir);
error_count += check_for_restricted_include_files(fs, build_info.policies, package_dir);
error_count += check_for_files_in_debug_include_directory(fs, package_dir);
error_count += check_for_files_in_debug_share_directory(fs, package_dir);
error_count += check_folder_lib_cmake(fs, package_dir, spec);
error_count += check_for_misplaced_cmake_files(fs, package_dir, spec);
error_count += check_folder_debug_lib_cmake(fs, package_dir, spec);
error_count += check_for_dlls_in_lib_dir(fs, package_dir);
error_count += check_for_dlls_in_lib_dir(fs, package_dir / "debug");
error_count += check_for_copyright_file(fs, spec, paths);
error_count += check_for_exes(fs, package_dir);
error_count += check_for_exes(fs, package_dir / "debug");
const fs::path debug_lib_dir = package_dir / "debug" / "lib";
const fs::path release_lib_dir = package_dir / "lib";
const fs::path debug_bin_dir = package_dir / "debug" / "bin";
const fs::path release_bin_dir = package_dir / "bin";
std::vector<fs::path> debug_libs = fs.get_files_recursive(debug_lib_dir);
Util::erase_remove_if(debug_libs, not_extension_pred(fs, ".lib"));
std::vector<fs::path> release_libs = fs.get_files_recursive(release_lib_dir);
Util::erase_remove_if(release_libs, not_extension_pred(fs, ".lib"));
if (!pre_build_info.build_type)
error_count += check_matching_debug_and_release_binaries(debug_libs, release_libs);
if (!build_info.policies.is_enabled(BuildPolicy::SKIP_ARCHITECTURE_CHECK))
{
std::vector<fs::path> libs;
libs.insert(libs.cend(), debug_libs.cbegin(), debug_libs.cend());
libs.insert(libs.cend(), release_libs.cbegin(), release_libs.cend());
error_count += check_lib_architecture(pre_build_info.target_architecture, libs);
}
std::vector<fs::path> debug_dlls = fs.get_files_recursive(debug_bin_dir);
Util::erase_remove_if(debug_dlls, not_extension_pred(fs, ".dll"));
std::vector<fs::path> release_dlls = fs.get_files_recursive(release_bin_dir);
Util::erase_remove_if(release_dlls, not_extension_pred(fs, ".dll"));
switch (build_info.library_linkage)
{
case Build::LinkageType::DYNAMIC:
{
if (!pre_build_info.build_type)
error_count += check_matching_debug_and_release_binaries(debug_dlls, release_dlls);
error_count += check_lib_files_are_available_if_dlls_are_available(
build_info.policies, debug_libs.size(), debug_dlls.size(), debug_lib_dir);
error_count += check_lib_files_are_available_if_dlls_are_available(
build_info.policies, release_libs.size(), release_dlls.size(), release_lib_dir);
std::vector<fs::path> dlls;
dlls.insert(dlls.cend(), debug_dlls.cbegin(), debug_dlls.cend());
dlls.insert(dlls.cend(), release_dlls.cbegin(), release_dlls.cend());
if (!toolset.dumpbin.empty() && !build_info.policies.is_enabled(BuildPolicy::SKIP_DUMPBIN_CHECKS))
{
error_count += check_exports_of_dlls(build_info.policies, dlls, toolset.dumpbin);
error_count += check_uwp_bit_of_dlls(pre_build_info.cmake_system_name, dlls, toolset.dumpbin);
error_count +=
check_outdated_crt_linkage_of_dlls(dlls, toolset.dumpbin, build_info, pre_build_info);
}
#if defined(_WIN32)
error_count += check_dll_architecture(pre_build_info.target_architecture, dlls);
#endif
break;
}
case Build::LinkageType::STATIC:
{
auto dlls = release_dlls;
dlls.insert(dlls.end(), debug_dlls.begin(), debug_dlls.end());
error_count += check_no_dlls_present(dlls);
error_count += check_bin_folders_are_not_present_in_static_build(fs, package_dir);
if (!toolset.dumpbin.empty() && !build_info.policies.is_enabled(BuildPolicy::SKIP_DUMPBIN_CHECKS))
{
if (!build_info.policies.is_enabled(BuildPolicy::ONLY_RELEASE_CRT))
{
error_count += check_crt_linkage_of_libs(
BuildType::value_of(Build::ConfigurationType::DEBUG, build_info.crt_linkage),
debug_libs,
toolset.dumpbin);
}
error_count += check_crt_linkage_of_libs(
BuildType::value_of(Build::ConfigurationType::RELEASE, build_info.crt_linkage),
release_libs,
toolset.dumpbin);
}
break;
}
default: Checks::unreachable(VCPKG_LINE_INFO);
}
error_count += check_no_empty_folders(fs, package_dir);
error_count += check_no_files_in_dir(fs, package_dir);
error_count += check_no_files_in_dir(fs, package_dir / "debug");
return error_count;
}
size_t perform_all_checks(const PackageSpec& spec,
const VcpkgPaths& paths,
const PreBuildInfo& pre_build_info,
const BuildInfo& build_info,
const fs::path& port_dir)
{
System::print2("-- Performing post-build validation\n");
const size_t error_count = perform_all_checks_and_return_error_count(spec, paths, pre_build_info, build_info);
if (error_count != 0)
{
const fs::path portfile = port_dir / "portfile.cmake";
System::print2(System::Color::error,
"Found ",
error_count,
" error(s). Please correct the portfile:\n ",
portfile.u8string(),
"\n");
}
System::print2("-- Performing post-build validation done\n");
return error_count;
}
}
|
// Game
// Convert as many humans to as you can to survive in this post-apocalyptic wasteland.
// DO NOT MODIFY THIS FILE
// Never try to directly create an instance of this class, or modify its member variables.
// Instead, you should only be reading its variables and calling its functions.
#include "game.hpp"
#include "../../joueur/src/base_ai.hpp"
#include "../../joueur/src/any.hpp"
#include "../../joueur/src/exceptions.hpp"
#include "../../joueur/src/delta.hpp"
#include "game_object.hpp"
#include "job.hpp"
#include "player.hpp"
#include "structure.hpp"
#include "tile.hpp"
#include "unit.hpp"
#include "impl/catastrophe.hpp"
#include <type_traits>
namespace cpp_client
{
namespace catastrophe
{
/// <summary>
/// Gets the Tile at a specified (x, y) position
/// </summary>
/// <param name="x">integer between 0 and the mapWidth</param>
/// <param name="y">integer between 0 and the mapHeight</param>
/// <returns>the Tile at (x, y) or null if out of bounds
Tile Game_::get_tile_at(const int x, const int y)
{
if(x < 0 || y < 0 || x >= map_width || y >= map_height) {
// out of bounds
return nullptr;
}
return tiles[x + y * map_width];
}
} // catastrophe
} // cpp_client
|
#ifndef OPENGLWINDOW_HPP_
#define OPENGLWINDOW_HPP_
#include <imgui.h>
#include <random>
#include "abcg.hpp"
#include "asteroids.hpp"
#include "bullets.hpp"
#include "ship.hpp"
#include "starlayers.hpp"
class OpenGLWindow : public abcg::OpenGLWindow {
protected:
void handleEvent(SDL_Event& event) override;
void initializeGL() override;
void paintGL() override;
void paintUI() override;
void resizeGL(int width, int height) override;
void terminateGL() override;
private:
GLuint m_starsProgram{};
GLuint m_objectsProgram{};
int m_viewportWidth{};
int m_viewportHeight{};
GameData m_gameData;
Asteroids m_asteroids;
Bullets m_bullets;
Ship m_ship;
StarLayers m_starLayers;
abcg::ElapsedTimer m_restartWaitTimer;
ImFont* m_font{};
std::default_random_engine m_randomEngine;
void checkCollisions();
void checkWinCondition();
void restart();
void update();
};
#endif
|
class Solution {
public:
int threeSumMulti(vector<int>& A, int target) {
unordered_map<int,long> c;
for(int a:A) c[a]++;
long res = 0;
for(auto it:c)
for(auto it2:c){
int i = it.first, j=it2.first, k= target-i-j;
if(!c.count(k)) continue;
if(i==j && j==k)
res+=c[i] * (c[i]-1) * (c[i]-2)/6;
else if(i==j && j!=k)
res += c[i]*(c[i]-1) / 2 * c[k];
else if(i<j && j<k)
res+=c[i]*c[j]*c[k];
}
return res%int(1e9+7);
}
};
|
/**
* @file unit_test_fnd_concepts_signed_integral.cpp
*
* @brief signed_integral のテスト
*
* @author myoukaku
*/
#include <bksge/fnd/concepts/signed_integral.hpp>
#include <bksge/fnd/config.hpp>
#include <cstdint> // WCHAR_MIN
#include <climits> // CHAR_MIN
#if defined(BKSGE_HAS_CXX20_CONCEPTS)
# define BKSGE_SIGNED_INTEGRAL_TEST(B, T) \
static_assert(B == bksge::signed_integral<T>, "")
#else
# define BKSGE_SIGNED_INTEGRAL_TEST(B, T) \
static_assert(B == bksge::signed_integral<T>::value, "")
#endif
namespace bksge_concepts_test
{
namespace signed_integral_test
{
// signed integer types
BKSGE_SIGNED_INTEGRAL_TEST(true, signed char);
BKSGE_SIGNED_INTEGRAL_TEST(true, signed short);
BKSGE_SIGNED_INTEGRAL_TEST(true, signed int);
BKSGE_SIGNED_INTEGRAL_TEST(true, signed long);
BKSGE_SIGNED_INTEGRAL_TEST(true, signed long long);
// unsigned integer types
BKSGE_SIGNED_INTEGRAL_TEST(false, unsigned char);
BKSGE_SIGNED_INTEGRAL_TEST(false, unsigned short);
BKSGE_SIGNED_INTEGRAL_TEST(false, unsigned int);
BKSGE_SIGNED_INTEGRAL_TEST(false, unsigned long);
BKSGE_SIGNED_INTEGRAL_TEST(false, unsigned long long);
// other integral types
BKSGE_SIGNED_INTEGRAL_TEST(false, bool);
#if CHAR_MIN < 0
BKSGE_SIGNED_INTEGRAL_TEST(true, char);
#else
BKSGE_SIGNED_INTEGRAL_TEST(false, char);
#endif
#if WCHAR_MIN < 0
BKSGE_SIGNED_INTEGRAL_TEST(true, wchar_t);
#else
BKSGE_SIGNED_INTEGRAL_TEST(false, wchar_t);
#endif
#if defined(BKSGE_HAS_CXX11_CHAR16_T)
BKSGE_SIGNED_INTEGRAL_TEST(false, char16_t);
#endif
#if defined(BKSGE_HAS_CXX11_CHAR32_T)
BKSGE_SIGNED_INTEGRAL_TEST(false, char32_t);
#endif
#if 0//defined(BKSGE_HAS_CXX20_CHAR8_T)
BKSGE_SIGNED_INTEGRAL_TEST(false, char8_t);
#endif
BKSGE_SIGNED_INTEGRAL_TEST(false, void);
BKSGE_SIGNED_INTEGRAL_TEST(false, float);
BKSGE_SIGNED_INTEGRAL_TEST(false, int&);
BKSGE_SIGNED_INTEGRAL_TEST(false, int&);
BKSGE_SIGNED_INTEGRAL_TEST(false, int&&);
BKSGE_SIGNED_INTEGRAL_TEST(false, const int&);
BKSGE_SIGNED_INTEGRAL_TEST(false, int[]);
BKSGE_SIGNED_INTEGRAL_TEST(false, int[2]);
BKSGE_SIGNED_INTEGRAL_TEST(false, int());
BKSGE_SIGNED_INTEGRAL_TEST(false, int(*)());
BKSGE_SIGNED_INTEGRAL_TEST(false, int(&)());
enum E { };
BKSGE_SIGNED_INTEGRAL_TEST(false, E);
enum class CE { };
BKSGE_SIGNED_INTEGRAL_TEST(false, CE);
struct A { };
BKSGE_SIGNED_INTEGRAL_TEST(false, A);
union B { };
BKSGE_SIGNED_INTEGRAL_TEST(false, B);
} // namespace signed_integral_test
} // namespace bksge_concepts_test
#undef BKSGE_SIGNED_INTEGRAL_TEST
|
#include "upgrade/boot_loader/ImageUpgrader.hpp"
namespace application
{
ImageUpgrader::ImageUpgrader(const char* targetName, Decryptor& decryptor)
: targetName(targetName)
, decryptor(decryptor)
{}
const char* ImageUpgrader::TargetName() const
{
return targetName;
}
Decryptor& ImageUpgrader::ImageDecryptor()
{
return decryptor;
}
}
|
//
// ip/detail/impl/endpoint.ipp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2010 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_ASIO_IP_DETAIL_IMPL_ENDPOINT_IPP
#define BOOST_ASIO_IP_DETAIL_IMPL_ENDPOINT_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#include <cstring>
#if !defined(BOOST_NO_IOSTREAM)
# include <sstream>
#endif // !defined(BOOST_NO_IOSTREAM)
#include <boost/asio/detail/socket_ops.hpp>
#include <boost/asio/detail/throw_error.hpp>
#include <boost/asio/error.hpp>
#include <boost/asio/ip/detail/endpoint.hpp>
#include <boost/asio/detail/push_options.hpp>
namespace boost {
namespace asio {
namespace ip {
namespace detail {
endpoint::endpoint()
: data_()
{
data_.v4.sin_family = AF_INET;
data_.v4.sin_port = 0;
data_.v4.sin_addr.s_addr = INADDR_ANY;
}
endpoint::endpoint(int family, unsigned short port_num)
: data_()
{
using namespace std; // For memcpy.
if (family == PF_INET)
{
data_.v4.sin_family = AF_INET;
data_.v4.sin_port =
boost::asio::detail::socket_ops::host_to_network_short(port_num);
data_.v4.sin_addr.s_addr = INADDR_ANY;
}
else
{
data_.v6.sin6_family = AF_INET6;
data_.v6.sin6_port =
boost::asio::detail::socket_ops::host_to_network_short(port_num);
data_.v6.sin6_flowinfo = 0;
boost::asio::detail::in6_addr_type tmp_addr = IN6ADDR_ANY_INIT;
data_.v6.sin6_addr = tmp_addr;
data_.v6.sin6_scope_id = 0;
}
}
endpoint::endpoint(const boost::asio::ip::address& addr,
unsigned short port_num)
: data_()
{
using namespace std; // For memcpy.
if (addr.is_v4())
{
data_.v4.sin_family = AF_INET;
data_.v4.sin_port =
boost::asio::detail::socket_ops::host_to_network_short(port_num);
data_.v4.sin_addr.s_addr =
boost::asio::detail::socket_ops::host_to_network_long(
addr.to_v4().to_ulong());
}
else
{
data_.v6.sin6_family = AF_INET6;
data_.v6.sin6_port =
boost::asio::detail::socket_ops::host_to_network_short(port_num);
data_.v6.sin6_flowinfo = 0;
boost::asio::ip::address_v6 v6_addr = addr.to_v6();
boost::asio::ip::address_v6::bytes_type bytes = v6_addr.to_bytes();
memcpy(data_.v6.sin6_addr.s6_addr, bytes.elems, 16);
data_.v6.sin6_scope_id = v6_addr.scope_id();
}
}
void endpoint::resize(std::size_t size)
{
if (size > sizeof(boost::asio::detail::sockaddr_storage_type))
{
boost::system::error_code ec(boost::asio::error::invalid_argument);
boost::asio::detail::throw_error(ec);
}
}
unsigned short endpoint::port() const
{
if (is_v4())
{
return boost::asio::detail::socket_ops::network_to_host_short(
data_.v4.sin_port);
}
else
{
return boost::asio::detail::socket_ops::network_to_host_short(
data_.v6.sin6_port);
}
}
void endpoint::port(unsigned short port_num)
{
if (is_v4())
{
data_.v4.sin_port
= boost::asio::detail::socket_ops::host_to_network_short(port_num);
}
else
{
data_.v6.sin6_port
= boost::asio::detail::socket_ops::host_to_network_short(port_num);
}
}
boost::asio::ip::address endpoint::address() const
{
using namespace std; // For memcpy.
if (is_v4())
{
return boost::asio::ip::address_v4(
boost::asio::detail::socket_ops::network_to_host_long(
data_.v4.sin_addr.s_addr));
}
else
{
boost::asio::ip::address_v6::bytes_type bytes;
memcpy(bytes.elems, data_.v6.sin6_addr.s6_addr, 16);
return boost::asio::ip::address_v6(bytes, data_.v6.sin6_scope_id);
}
}
void endpoint::address(const boost::asio::ip::address& addr)
{
endpoint tmp_endpoint(addr, port());
data_ = tmp_endpoint.data_;
}
bool operator==(const endpoint& e1, const endpoint& e2)
{
return e1.address() == e2.address() && e1.port() == e2.port();
}
bool operator<(const endpoint& e1, const endpoint& e2)
{
if (e1.address() < e2.address())
return true;
if (e1.address() != e2.address())
return false;
return e1.port() < e2.port();
}
#if !defined(BOOST_NO_IOSTREAM)
std::string endpoint::to_string(boost::system::error_code& ec) const
{
std::string a = address().to_string(ec);
if (ec)
return std::string();
std::ostringstream tmp_os;
tmp_os.imbue(std::locale::classic());
if (is_v4())
tmp_os << a;
else
tmp_os << '[' << a << ']';
tmp_os << ':' << port();
return tmp_os.str();
}
#endif // !defined(BOOST_NO_IOSTREAM)
} // namespace detail
} // namespace ip
} // namespace asio
} // namespace boost
#include <boost/asio/detail/pop_options.hpp>
#endif // BOOST_ASIO_IP_DETAIL_IMPL_ENDPOINT_IPP
|
// Copyright (c) 2014-2018 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparams.h"
#include "validation.h"
#include "test/test_bitcoinhard.h"
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(subsidy_tests, TestingSetup)
BOOST_AUTO_TEST_CASE(block_subsidy_test)
{
const Consensus::Params& consensusParams = Params(CBaseChainParams::MAIN).GetConsensus();
uint32_t nPrevBits;
int32_t nPrevHeight;
CAmount nSubsidy;
// details for block 4249 (subsidy returned will be for block 4250)
nPrevBits = 0x1c4a47c4;
nPrevHeight = 4249;
nSubsidy = GetBlockSubsidy(nPrevBits, nPrevHeight, consensusParams, false);
BOOST_CHECK_EQUAL(nSubsidy, 50000000000ULL);
// details for block 4501 (subsidy returned will be for block 4502)
nPrevBits = 0x1c4a47c4;
nPrevHeight = 4501;
nSubsidy = GetBlockSubsidy(nPrevBits, nPrevHeight, consensusParams, false);
BOOST_CHECK_EQUAL(nSubsidy, 5600000000ULL);
// details for block 5464 (subsidy returned will be for block 5465)
nPrevBits = 0x1c29ec00;
nPrevHeight = 5464;
nSubsidy = GetBlockSubsidy(nPrevBits, nPrevHeight, consensusParams, false);
BOOST_CHECK_EQUAL(nSubsidy, 2100000000ULL);
// details for block 5465 (subsidy returned will be for block 5466)
nPrevBits = 0x1c29ec00;
nPrevHeight = 5465;
nSubsidy = GetBlockSubsidy(nPrevBits, nPrevHeight, consensusParams, false);
BOOST_CHECK_EQUAL(nSubsidy, 12200000000ULL);
// details for block 17588 (subsidy returned will be for block 17589)
nPrevBits = 0x1c08ba34;
nPrevHeight = 17588;
nSubsidy = GetBlockSubsidy(nPrevBits, nPrevHeight, consensusParams, false);
BOOST_CHECK_EQUAL(nSubsidy, 6100000000ULL);
// details for block 99999 (subsidy returned will be for block 100000)
nPrevBits = 0x1b10cf42;
nPrevHeight = 99999;
nSubsidy = GetBlockSubsidy(nPrevBits, nPrevHeight, consensusParams, false);
BOOST_CHECK_EQUAL(nSubsidy, 500000000ULL);
// details for block 210239 (subsidy returned will be for block 210240)
nPrevBits = 0x1b11548e;
nPrevHeight = 210239;
nSubsidy = GetBlockSubsidy(nPrevBits, nPrevHeight, consensusParams, false);
BOOST_CHECK_EQUAL(nSubsidy, 500000000ULL);
// 1st subsidy reduction happens here
// details for block 210240 (subsidy returned will be for block 210241)
nPrevBits = 0x1b10d50b;
nPrevHeight = 210240;
nSubsidy = GetBlockSubsidy(nPrevBits, nPrevHeight, consensusParams, false);
BOOST_CHECK_EQUAL(nSubsidy, 464285715ULL);
}
BOOST_AUTO_TEST_SUITE_END()
|
#include "GameEngine.h"
#include <GameEngineBase/GameEngineWindow.h>
#include "GameEngineLevel.h"
std::map<std::string, GameEngineLevel*> GameEngine::AllLevel_;
GameEngineLevel* GameEngine::CurrentLevel_ = nullptr;
GameEngineLevel* GameEngine::NextLevel_ = nullptr;
GameEngine* GameEngine::UserContents_ = nullptr;
GameEngine::GameEngine()
{
}
GameEngine::~GameEngine()
{
}
void GameEngine::GameInit()
{
}
void GameEngine::GameLoop()
{
}
void GameEngine::GameEnd()
{
}
void GameEngine::WindowCreate()
{
GameEngineWindow::GetInst_().CreateGameWindow(nullptr, "GameWindow");
GameEngineWindow::GetInst_().ShowGameWindow();
GameEngineWindow::GetInst_().MessageLoop(EngineInit, EngineLoop);
}
void GameEngine::EngineInit()
{
UserContents_->GameInit();
}
void GameEngine::EngineLoop()
{
UserContents_->GameLoop();
if (nullptr != NextLevel_)
{
CurrentLevel_ = NextLevel_;
NextLevel_ = nullptr;
}
if (nullptr == CurrentLevel_)
{
MsgBoxAssert("Level is nullptr => GameEngine Loop Error");
}
CurrentLevel_->Update();
}
void GameEngine::EngineEnd()
{
UserContents_->GameEnd();
std::map<std::string, GameEngineLevel*>::iterator StartIter = AllLevel_.begin();
std::map<std::string, GameEngineLevel*>::iterator EndIter = AllLevel_.end();
for (; StartIter != EndIter; ++StartIter)
{
if (nullptr == StartIter->second)
{
continue;
}
delete StartIter->second;
}
GameEngineWindow::Destroy();
}
void GameEngine::ChangeLevel(const std::string& _Name)
{
std::map<std::string, GameEngineLevel*>::iterator FindIter = AllLevel_.find(_Name);
if (AllLevel_.end() == FindIter)
{
MsgBoxAssert("Level Find Error");
return;
}
NextLevel_ = FindIter->second;
}
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "conlib.h"
#include "Map.h"
#include "Player.h"
#include "Timer.h"
int main()
{
Map map
{
"########################################################################################################################",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# $ $ #",
"# #",
"# #",
"# #",
"# #",
"# % #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# $ $ #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# $ $ #",
"# #",
"########################################################################################################################",
};
srand(unsigned(time(nullptr)));
const int fps = 20;
unsigned prevtime;
auto player = std::make_shared<Player>();
map.place(player, 8, 8);
consize(120, 50);
setCursorType(CursorType::No);
clrscr();
while (1)
{
prevtime = gettick();
if (_kbhit())
{
int ch = getkey();
#ifdef _DEBUG
gotoxy(0, 0);
printf(" ");
gotoxy(0, 0);
printf("0x%04x", ch);
#endif
switch (ch)
{
case Right:
player->move(1, 0);
break;
case Left:
player->move(-1, 0);
break;
case Top:
player->move(0, -1);
break;
case Down:
player->move(0, 1);
break;
case 'Q':
player->attack();
break;
}
}
Timer::get().runTick();
map.draw(player->getX() - map.getWidth() / 2, player->getY() - map.getHeight() / 2,
2, 2, 100, 35);
player->printinfo(2, 38);
gotoxy(0, 0);
int dt = int(gettick() - prevtime);
int ms = 1000 / fps - dt;
if (ms > 0)
delay(ms);
}
}
|
/**
* @file : instruction_set.cpp
*/
#include "../../../includes/cpu_emulator/processor_util/instruction_set.hpp"
namespace TakiMatrix::processor {
instruction::instruction(enum instruction_type type,
const std::shared_ptr<matrix_object>& operand_first,
const std::shared_ptr<matrix_object>& operand_second,
std::shared_ptr<matrix_object>& result)
:m_instruction_type(type), m_operand_first(operand_first),
m_operand_second(operand_second), m_result(result) { }
instruction::instruction(enum instruction_type type,
const std::shared_ptr<matrix_object>& operand_first,
const std::shared_ptr<matrix_object>& operand_second,
std::shared_ptr<matrix_object>& result,
const std::function<float(float)>& functor)
:m_instruction_type(type), m_operand_first(operand_first),
m_operand_second(operand_second), m_result(result), m_functor(functor) { }
std::shared_ptr<matrix_object> instruction::result_ptr() { return m_result; }
std::shared_ptr<matrix_object> instruction::first_operand_ptr()
{
return m_operand_first;
}
std::shared_ptr<matrix_object> instruction::second_operand_ptr()
{
return m_operand_second;
}
const std::function<float(float)> instruction::functor() { return m_functor; }
instruction_type instruction::type() { return m_instruction_type; }
} // namespace TakiMatrix::processor
|
#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>
using namespace std;
int main(){
int N; vector<int> v;
cin >> N;
while(N--){
int temp;
cin >> temp;
v.push_back(temp);
}
int sum=0;
sort(v.begin(), v.end(), greater<int>()); // Descending order. 내림차순
for(int i=0;i<v.size();i++){
sum+=v[i]*(i+1);
}
cout << sum;
return 0;
}
|
#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=peepcoinrpc\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 \"Peepcoin 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", "Peepcoin version"),
QT_TRANSLATE_NOOP("bitcoin-core", "Usage:"),
QT_TRANSLATE_NOOP("bitcoin-core", "Send command to -server or peepcoind"),
QT_TRANSLATE_NOOP("bitcoin-core", "List commands"),
QT_TRANSLATE_NOOP("bitcoin-core", "Get help for a command"),
QT_TRANSLATE_NOOP("bitcoin-core", "Peepcoin"),
QT_TRANSLATE_NOOP("bitcoin-core", "Options:"),
QT_TRANSLATE_NOOP("bitcoin-core", "This help message"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify configuration file (default: peepcoin.conf)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify pid file (default: peepcoind.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: 8193 or testnet: 18193)"),
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: 8194 or testnet: 18194)"),
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: 500, 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. Peepcoin 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 Peepcoin"),
QT_TRANSLATE_NOOP("bitcoin-core", "Wallet needed to be rewritten: restart Peepcoin 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. Peepcoin 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 Peepcoin 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."),
};
|
#include "roadlr/roadlr.hpp"
#include "utils/python_embedding.hpp"
#include "utils/vvs.h"
#include "utils/opencx.hpp"
#include <chrono>
#include <thread>
using namespace dg;
using namespace std;
#define RECOGNIZER RoadLRRecognizer
void test_image_run(RECOGNIZER& recognizer, bool recording = false, const char* image_file = "sample.png", int nItr = 5)
{
printf("#### Test Image Run ####################\n");
cv::Mat image = cv::imread(image_file);
VVS_CHECK_TRUE(!image.empty());
cv::namedWindow(image_file);
for (int i = 1; i <= nItr; i++)
{
dg::Timestamp ts = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count() / 1000.0;
VVS_CHECK_TRUE(recognizer.apply(image, ts));
printf("iteration: %d (it took %lf seconds)\n", i, recognizer.procTime());
recognizer.print();
cv::Mat image_result = image.clone();
recognizer.draw(image_result);
cv::imshow(image_file, image_result);
int key = cv::waitKey(1000);
if (key == cx::KEY_SPACE) key = cv::waitKey(0);
if (key == cx::KEY_ESC) break;
if (recording)
{
string fname = cv::format("%s_result.png", recognizer.name());
cv::imwrite(fname, image_result);
}
}
cv::destroyWindow(image_file);
}
void test_video_run(RECOGNIZER& recognizer, bool recording = false, int fps = 10, const char* video_file = "data/191115_ETRI.avi")
{
printf("#### Test Video Run ####################\n");
cv::VideoCapture video_data;
VVS_CHECK_TRUE(video_data.open(video_file));
cx::VideoWriter video;
std::ofstream log;
if (recording)
{
char sztime[255];
time_t start_t;
time(&start_t);
tm _tm = *localtime(&start_t);
strftime(sztime, 255, "%y%m%d_%H%M%S", &_tm);
video.open(cv::format("%s_%s.avi", recognizer.name(), sztime), fps);
log.open(cv::format("%s_%s.txt", recognizer.name(), sztime), ios::out);
}
cv::namedWindow(video_file);
int i = 1;
while (1)
{
int frame_i = (int)video_data.get(cv::CAP_PROP_POS_FRAMES);
cv::Mat image;
video_data >> image;
if (image.empty()) break;
dg::Timestamp ts = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count() / 1000.0;
VVS_CHECK_TRUE(recognizer.apply(image, ts));
printf("iteration: %d (it took %lf seconds)\n", i++, recognizer.procTime());
recognizer.print();
// draw frame number & fps
std::string fn = cv::format("#%d (FPS: %.1lf)", frame_i, 1.0 / recognizer.procTime());
cv::putText(image, fn.c_str(), cv::Point(20, 50), cv::FONT_HERSHEY_PLAIN, 2.0, cv::Scalar(0, 0, 0), 4);
cv::putText(image, fn.c_str(), cv::Point(20, 50), cv::FONT_HERSHEY_PLAIN, 2.0, cv::Scalar(0, 255, 255), 2);
recognizer.draw(image);
if (recording)
{
video << image;
recognizer.write(log);
}
cv::imshow(video_file, image);
int key = cv::waitKey(1);
if (key == cx::KEY_SPACE) key = cv::waitKey(0);
if (key == 83) // Right Key
{
int fi = (int)video_data.get(cv::CAP_PROP_POS_FRAMES);
video_data.set(cv::CAP_PROP_POS_FRAMES, fi + 30);
}
if (key == cx::KEY_ESC) break;
}
cv::destroyWindow(video_file);
}
void procfunc(bool recording, int rec_fps, const char* video_path)
{
// Initialize Python module
RECOGNIZER recognizer;
if (!recognizer.initialize("./../src/roadlr", "roadlr", "roadlr_recognizer")) return;
printf("Initialization: it took %.3lf seconds\n\n\n", recognizer.procTime());
// Run the Python module
//test_image_run(recognizer, false, cv::format("%s_sample.png", recognizer.name()).c_str());
test_video_run(recognizer, recording, rec_fps, video_path);
// Clear the Python module
recognizer.clear();
}
int main()
{
bool recording = false;
int rec_fps = 15;
bool threaded_run = false;
int video_sel = 0;
const char* video_path[] = {
"data/ETRI/191115_151140_images.avi",
"data/ETRI/200219_150153_images.avi",
"data/ETRI/200326_132938_images.avi",
"data/ETRI/200429_131714_images.avi",
"data/ETRI/200429_140025_images.avi"
};
// Initialize the Python interpreter
init_python_environment("python3", "", threaded_run);
if(threaded_run)
{
std::thread* test_thread = new std::thread(procfunc, recording, rec_fps, video_path[video_sel]);
test_thread->join();
}
else
{
procfunc(recording, rec_fps, video_path[video_sel]);
}
// Close the Python Interpreter
close_python_environment();
printf("done..\n");
return 0;
}
|
// MIT License
//
// Copyright (c) 2022 Egor Kupaev
//
// 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 "Impl/SystemBuilderImpl.hpp"
namespace CuEngine::Platform
{
SystemBuilder::SystemBuilder() noexcept : m_Pimpl()
{}
SystemBuilder::SystemBuilder(SystemBuilder && other) noexcept = default;
SystemBuilder & SystemBuilder::operator=(SystemBuilder && other) noexcept = default;
SystemBuilder::~SystemBuilder() noexcept = default;
System SystemBuilder::Build() const
{
return System(m_Pimpl->Build());
}
Impl::SystemBuilder & SystemBuilder::GetImpl() noexcept
{
return *m_Pimpl;
}
} // namespace CuEngine::Platform
|
// Copyright 2018 The clvk authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <unordered_set>
#include "init.hpp"
#include "memory.hpp"
#include "queue.hpp"
cvk_executor_thread_pool gThreadPool;
_cl_command_queue::_cl_command_queue(cvk_context* ctx, cvk_device* device,
cl_command_queue_properties properties)
: api_object(ctx), m_device(device), m_properties(properties),
m_executor(nullptr), m_vulkan_queue(device->vulkan_queue_allocate()),
m_command_pool(device->vulkan_device(), m_vulkan_queue.queue_family()) {
m_groups.push_back(std::make_unique<cvk_command_group>());
if (properties & CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE) {
cvk_warn_fn("out-of-order execution enabled, will be ignored");
}
}
cl_int cvk_command_queue::init() {
if (m_command_pool.init() != VK_SUCCESS) {
return CL_OUT_OF_RESOURCES;
}
return CL_SUCCESS;
}
_cl_command_queue::~_cl_command_queue() {
if (m_executor != nullptr) {
gThreadPool.return_executor(m_executor);
}
}
void cvk_command_queue::enqueue_command(cvk_command* cmd, cvk_event** event) {
std::lock_guard<std::mutex> lock(m_lock);
m_groups.back()->commands.push_back(cmd);
cvk_debug_fn("enqueued command %p, event %p", cmd, cmd->event());
cmd->event()->set_profiling_info_from_monotonic_clock(
CL_PROFILING_COMMAND_QUEUED);
if (event != nullptr) {
// The event will be returned to the app, retain it for the user
cmd->event()->retain();
*event = cmd->event();
cvk_debug_fn("returning event %p", *event);
}
}
void cvk_command_queue::enqueue_command_with_deps(cvk_command* cmd,
cl_uint num_dep_events,
cvk_event* const* dep_events,
cvk_event** event) {
cmd->set_dependencies(num_dep_events, dep_events);
enqueue_command(cmd, event);
}
cl_int cvk_command_queue::enqueue_command_with_deps(
cvk_command* cmd, bool blocking, cl_uint num_dep_events,
cvk_event* const* dep_events, cvk_event** event) {
cmd->set_dependencies(num_dep_events, dep_events);
cvk_event* evt;
enqueue_command(cmd, &evt);
cl_int err = CL_SUCCESS;
if (blocking) {
err = wait_for_events(1, &evt);
}
if (event != nullptr) {
*event = evt;
} else {
evt->release();
}
return err;
}
cl_int cvk_command_queue::wait_for_events(cl_uint num_events,
const cl_event* event_list) {
cl_int ret = CL_SUCCESS;
// Create set of queues to flush
std::unordered_set<cvk_command_queue*> queues_to_flush;
for (cl_uint i = 0; i < num_events; i++) {
cvk_event* event = event_list[i];
if (!event->is_user_event()) {
queues_to_flush.insert(event->queue());
}
}
// Flush queues
for (auto q : queues_to_flush) {
cl_int qerr = q->flush();
if (qerr != CL_SUCCESS) {
return qerr;
}
}
// Now wait for all the events
for (cl_uint i = 0; i < num_events; i++) {
cvk_event* event = event_list[i];
if (event->wait() != CL_COMPLETE) {
ret = CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST;
}
}
return ret;
}
void cvk_executor_thread::executor() {
std::unique_lock<std::mutex> lock(m_lock);
while (!m_shutdown) {
if (m_groups.size() == 0) {
m_cv.wait(lock);
}
if (m_shutdown) {
continue;
}
auto group = std::move(m_groups.front());
m_groups.pop_front();
cvk_debug_fn("received group %p", group.get());
lock.unlock();
while (group->commands.size() > 0) {
cvk_command* cmd = group->commands.front();
cvk_debug_fn("executing command %p, event %p", cmd, cmd->event());
if (m_profiling && cmd->is_profiled_by_executor()) {
cmd->event()->set_profiling_info_from_monotonic_clock(
CL_PROFILING_COMMAND_START);
}
cl_int status = cmd->execute();
cvk_debug_fn("command returned %d", status);
if (m_profiling && cmd->is_profiled_by_executor()) {
cmd->event()->set_profiling_info_from_monotonic_clock(
CL_PROFILING_COMMAND_END);
}
cmd->event()->set_status(status);
group->commands.pop_front();
delete cmd;
}
lock.lock();
}
}
cl_int cvk_command_queue::flush(cvk_event** event) {
cvk_info_fn("queue = %p, event = %p", this, event);
// Get command group to the executor's queue
std::unique_ptr<cvk_command_group> group;
{
std::lock_guard<std::mutex> lock(m_lock);
if (m_groups.front()->commands.size() == 0) {
return CL_SUCCESS;
}
group = std::move(m_groups.front());
m_groups.pop_front();
m_groups.push_back(std::make_unique<cvk_command_group>());
}
cvk_debug_fn("groups.size() = %zu", m_groups.size());
CVK_ASSERT(group->commands.size() > 0);
// Set event state and profiling info
for (auto cmd : group->commands) {
cmd->event()->set_status(CL_SUBMITTED);
if (has_property(CL_QUEUE_PROFILING_ENABLE)) {
cmd->event()->set_profiling_info_from_monotonic_clock(
CL_PROFILING_COMMAND_SUBMIT);
}
}
// Create execution thread if it doesn't exist
{
std::lock_guard<std::mutex> lock(m_lock);
if (m_executor == nullptr) {
m_executor = gThreadPool.get_executor(this);
}
}
if (event != nullptr) {
auto ev = group->commands.back()->event();
ev->retain();
*event = ev;
cvk_debug_fn("returned event %p", *event);
}
// Submit command group to executor
m_executor->send_group(std::move(group));
return CL_SUCCESS;
}
VkResult cvk_command_pool::allocate_command_buffer(VkCommandBuffer* cmdbuf) {
std::lock_guard<std::mutex> lock(m_lock);
VkCommandBufferAllocateInfo commandBufferAllocateInfo = {
VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, 0, m_command_pool,
VK_COMMAND_BUFFER_LEVEL_PRIMARY,
1 // commandBufferCount
};
return vkAllocateCommandBuffers(m_device, &commandBufferAllocateInfo,
cmdbuf);
}
void cvk_command_pool::free_command_buffer(VkCommandBuffer buf) {
std::lock_guard<std::mutex> lock(m_lock);
vkFreeCommandBuffers(m_device, m_command_pool, 1, &buf);
}
bool cvk_command_buffer::begin() {
if (!m_queue->allocate_command_buffer(&m_command_buffer)) {
return false;
}
m_queue->command_pool_lock();
VkCommandBufferBeginInfo beginInfo = {
VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, nullptr,
VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
nullptr // pInheritanceInfo
};
VkResult res = vkBeginCommandBuffer(m_command_buffer, &beginInfo);
if (res != VK_SUCCESS) {
return false;
}
return true;
}
bool cvk_command_buffer::submit_and_wait() {
auto& queue = m_queue->vulkan_queue();
VkResult res = queue.submit(m_command_buffer);
if (res != VK_SUCCESS) {
return false;
}
res = queue.wait_idle();
if (res != VK_SUCCESS) {
return false;
}
return true;
}
cl_int cvk_command_kernel::build() {
auto vklimits = m_queue->device()->vulkan_limits();
// Check we have a valid dispatch size
for (cl_uint i = 0; i < 3; ++i) {
if (m_num_wg[i] > vklimits.maxComputeWorkGroupCount[i]) {
cvk_error_fn("global work size exceeds device limits");
// There is no suitable error code to report this
// use something
return CL_INVALID_WORK_ITEM_SIZE;
}
}
if (m_wg_size[0] * m_wg_size[1] * m_wg_size[2] >
vklimits.maxComputeWorkGroupInvocations) {
return CL_INVALID_WORK_GROUP_SIZE;
}
for (int i = 0; i < 3; i++) {
if (m_wg_size[i] > vklimits.maxComputeWorkGroupSize[i]) {
return CL_INVALID_WORK_ITEM_SIZE;
}
}
// TODO check against the size specified at compile time, if any
// TODO CL_INVALID_KERNEL_ARGS if the kernel argument values have not been
// specified.
// Setup descriptors
if (!m_kernel->setup_descriptor_set(&m_descriptor_set, m_argument_values)) {
return CL_OUT_OF_RESOURCES;
}
// Create query pool
VkQueryPoolCreateInfo query_pool_create_info = {
VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO,
nullptr,
0, // flags
VK_QUERY_TYPE_TIMESTAMP, // queryType
NUM_POOL_QUERIES_PER_KERNEL, // queryCount
0, // pipelineStatistics
};
bool profiling = m_queue->has_property(CL_QUEUE_PROFILING_ENABLE);
if (profiling && !is_profiled_by_executor()) {
auto vkdev = m_queue->device()->vulkan_device();
auto res = vkCreateQueryPool(vkdev, &query_pool_create_info, nullptr,
&m_query_pool);
if (res != VK_SUCCESS) {
return CL_OUT_OF_RESOURCES;
}
}
if (!m_command_buffer.begin()) {
return CL_OUT_OF_RESOURCES;
}
std::vector<VkSpecializationMapEntry> mapEntries = {
{0, 0 * sizeof(uint32_t), sizeof(uint32_t)},
{1, 1 * sizeof(uint32_t), sizeof(uint32_t)},
{2, 2 * sizeof(uint32_t), sizeof(uint32_t)},
};
std::vector<uint32_t> specConstantData = {m_wg_size[0], m_wg_size[1],
m_wg_size[2]};
uint32_t constantDataOffset = specConstantData.size() * sizeof(uint32_t);
for (auto const& spec_value :
m_argument_values->specialization_constants()) {
VkSpecializationMapEntry entry = {spec_value.first, constantDataOffset,
sizeof(uint32_t)};
mapEntries.push_back(entry);
specConstantData.push_back(spec_value.second);
constantDataOffset += sizeof(uint32_t);
}
VkSpecializationInfo specializationInfo = {
static_cast<uint32_t>(mapEntries.size()),
mapEntries.data(),
specConstantData.size() * sizeof(uint32_t),
specConstantData.data(),
};
m_pipeline = m_kernel->create_pipeline(specializationInfo);
if (m_pipeline == VK_NULL_HANDLE) {
return CL_OUT_OF_RESOURCES;
}
vkCmdBindPipeline(m_command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE,
m_pipeline);
if (profiling && !is_profiled_by_executor()) {
vkCmdResetQueryPool(m_command_buffer, m_query_pool, 0,
NUM_POOL_QUERIES_PER_KERNEL);
vkCmdWriteTimestamp(m_command_buffer,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, m_query_pool,
POOL_QUERY_KERNEL_START);
}
vkCmdBindDescriptorSets(m_command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE,
m_kernel->pipeline_layout(), 0, 1,
&m_descriptor_set, 0, 0);
vkCmdDispatch(m_command_buffer, m_num_wg[0], m_num_wg[1], m_num_wg[2]);
VkMemoryBarrier memoryBarrier = {
VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_MEMORY_WRITE_BIT,
VK_ACCESS_HOST_READ_BIT | VK_ACCESS_HOST_WRITE_BIT};
vkCmdPipelineBarrier(m_command_buffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
VK_PIPELINE_STAGE_HOST_BIT,
0, // dependencyFlags
1, // memoryBarrierCount
&memoryBarrier,
0, // bufferMemoryBarrierCount
nullptr, // pBufferMemoryBarriers
0, // imageMemoryBarrierCount
nullptr); // pImageMemoryBarriers
if (profiling && !is_profiled_by_executor()) {
vkCmdWriteTimestamp(m_command_buffer,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, m_query_pool,
POOL_QUERY_KERNEL_END);
}
if (!m_command_buffer.end()) {
return CL_OUT_OF_RESOURCES;
}
return CL_SUCCESS;
}
cl_int cvk_command_kernel::do_action() {
if (!m_command_buffer.submit_and_wait()) {
return CL_OUT_OF_RESOURCES;
}
bool profiling = m_queue->has_property(CL_QUEUE_PROFILING_ENABLE);
if (profiling && !is_profiled_by_executor()) {
uint64_t timestamps[NUM_POOL_QUERIES_PER_KERNEL];
auto dev = m_queue->device();
vkGetQueryPoolResults(
dev->vulkan_device(), m_query_pool, 0, NUM_POOL_QUERIES_PER_KERNEL,
sizeof(timestamps), timestamps, sizeof(uint64_t),
VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
auto nsPerTick = dev->vulkan_limits().timestampPeriod;
auto ts_start_raw = timestamps[POOL_QUERY_KERNEL_START];
auto ts_end_raw = timestamps[POOL_QUERY_KERNEL_END];
uint64_t ts_start, ts_end;
// Most implementations seem to use 1 ns = 1 tick, handle this as a
// special case to not lose precision.
if (nsPerTick == 1.0) {
ts_start = ts_start_raw;
ts_end = ts_end_raw;
} else {
ts_start = ts_start_raw * nsPerTick;
ts_end = ts_start_raw * nsPerTick;
}
m_event->set_profiling_info(CL_PROFILING_COMMAND_START, ts_start);
m_event->set_profiling_info(CL_PROFILING_COMMAND_END, ts_end);
}
return CL_COMPLETE;
}
cl_int cvk_command_copy::do_action() {
bool success = false;
switch (m_type) {
case CL_COMMAND_WRITE_BUFFER:
success = m_mem->copy_from(m_ptr, m_offset, m_size);
break;
case CL_COMMAND_READ_BUFFER:
success = m_mem->copy_to(m_ptr, m_offset, m_size);
break;
default:
CVK_ASSERT(false);
break;
}
return success ? CL_COMPLETE : CL_OUT_OF_RESOURCES;
}
struct rectangle {
public:
void set_params(size_t* origin, size_t slicep, size_t rowp,
size_t elem_size) {
m_origin[0] = origin[0];
m_origin[1] = origin[1];
m_origin[2] = origin[2];
m_slice_pitch = slicep;
m_row_pitch = rowp;
m_elem_size = elem_size;
}
size_t get_row_offset(size_t slice, size_t row) {
return m_slice_pitch * (m_origin[2] + slice) +
m_row_pitch * (m_origin[1] + row) + m_origin[0] * m_elem_size;
}
private:
size_t m_origin[3];
size_t m_slice_pitch;
size_t m_row_pitch;
size_t m_elem_size;
};
struct memobj_map_holder {
memobj_map_holder(cvk_mem* memobj) : m_mem(memobj), m_mapped(false) {
CVK_ASSERT(memobj != nullptr);
}
~memobj_map_holder() {
if (m_mapped) {
m_mem->unmap();
}
}
bool CHECK_RETURN map() {
m_mapped = m_mem->map();
return m_mapped;
}
private:
cvk_mem* m_mem;
bool m_mapped;
};
void cvk_rectangle_copier::do_copy(direction dir, void* src_base,
void* dst_base) {
rectangle ra, rb;
ra.set_params(m_a_origin, m_a_slice_pitch, m_a_row_pitch, m_elem_size);
rb.set_params(m_b_origin, m_b_slice_pitch, m_b_row_pitch, m_elem_size);
rectangle *rsrc, *rdst;
if (dir == direction::A_TO_B) {
rsrc = &ra;
rdst = &rb;
} else {
CVK_ASSERT(dir == direction::B_TO_A);
rsrc = &rb;
rdst = &ra;
}
for (size_t slice = 0; slice < m_region[2]; slice++) {
// cvk_debug_fn("slice = %zu", slice);
for (size_t row = 0; row < m_region[1]; row++) {
// cvk_debug_fn("row = %zu (size = %zu)", row, m_region[0]);
auto dst =
pointer_offset(dst_base, rdst->get_row_offset(slice, row));
auto src =
pointer_offset(src_base, rsrc->get_row_offset(slice, row));
memcpy(dst, src, m_region[0] * m_elem_size);
}
}
}
cl_int cvk_command_copy_host_buffer_rect::do_action() {
memobj_map_holder map_holder{m_buffer};
if (!map_holder.map()) {
return CL_OUT_OF_RESOURCES;
}
cvk_rectangle_copier::direction dir;
void *src_base, *dst_base;
switch (m_type) {
case CL_COMMAND_READ_BUFFER_RECT:
case CL_COMMAND_READ_IMAGE:
dst_base = m_hostptr;
src_base = m_buffer->host_va();
dir = cvk_rectangle_copier::direction::A_TO_B;
break;
case CL_COMMAND_WRITE_BUFFER_RECT:
case CL_COMMAND_WRITE_IMAGE:
dst_base = m_buffer->host_va();
src_base = m_hostptr;
dir = cvk_rectangle_copier::direction::B_TO_A;
break;
default:
return CL_INVALID_OPERATION;
}
m_copier.do_copy(dir, src_base, dst_base);
return CL_COMPLETE;
}
cl_int cvk_command_copy_buffer_rect::do_action() {
memobj_map_holder src_map_holder{m_src_buffer};
memobj_map_holder dst_map_holder{m_dst_buffer};
if (!src_map_holder.map()) {
return CL_OUT_OF_RESOURCES;
}
if (!dst_map_holder.map()) {
return CL_OUT_OF_RESOURCES;
}
auto dir = cvk_rectangle_copier::direction::A_TO_B;
auto src_base = m_src_buffer->host_va();
auto dst_base = m_dst_buffer->host_va();
m_copier.do_copy(dir, src_base, dst_base);
return CL_COMPLETE;
}
cl_int cvk_command_copy_buffer::do_action() {
bool success =
m_src_buffer->copy_to(m_dst_buffer, m_src_offset, m_dst_offset, m_size);
return success ? CL_COMPLETE : CL_OUT_OF_RESOURCES;
}
cl_int cvk_command_fill_buffer::do_action() {
memobj_map_holder map_holder{m_mem};
if (!map_holder.map()) {
return CL_OUT_OF_RESOURCES;
}
auto begin = pointer_offset(m_mem->host_va(), m_offset);
auto end = pointer_offset(begin, m_size);
auto address = begin;
while (address < end) {
memcpy(address, m_pattern.data(), m_pattern_size);
address = pointer_offset(address, m_pattern_size);
}
return CL_COMPLETE;
}
cl_int cvk_command_map_buffer::do_action() {
bool success = true;
if (m_mem->has_flags(CL_MEM_USE_HOST_PTR)) {
success = m_mem->copy_to(m_mem->host_ptr(), m_offset, m_size);
}
return success ? CL_COMPLETE : CL_OUT_OF_RESOURCES;
}
cl_int cvk_command_unmap_buffer::do_action() {
m_mem->unmap();
return CL_COMPLETE;
}
cl_int cvk_command_unmap_image::do_action() {
// TODO flush caches on non-coherent memory
m_image->remove_mapping(m_mapped_ptr);
if (m_needs_copy) {
auto err = m_cmd_copy.do_action();
if (err != CL_COMPLETE) {
return err;
}
}
return CL_COMPLETE;
}
VkImageSubresourceLayers prepare_subresource(cvk_image* image,
std::array<size_t, 3> origin,
std::array<size_t, 3> region) {
uint32_t baseArrayLayer = 0;
uint32_t layerCount = 1;
switch (image->type()) {
case CL_MEM_OBJECT_IMAGE1D_ARRAY:
baseArrayLayer = origin[1];
layerCount = region[1];
break;
case CL_MEM_OBJECT_IMAGE2D_ARRAY:
baseArrayLayer = origin[2];
layerCount = region[2];
break;
}
VkImageSubresourceLayers ret = {VK_IMAGE_ASPECT_COLOR_BIT, // aspectMask
0, // mipLevel
baseArrayLayer, layerCount};
return ret;
}
VkOffset3D prepare_offset(cvk_image* image, std::array<size_t, 3> origin) {
auto x = static_cast<int32_t>(origin[0]);
auto y = static_cast<int32_t>(origin[1]);
auto z = static_cast<int32_t>(origin[2]);
switch (image->type()) {
case CL_MEM_OBJECT_IMAGE1D_ARRAY:
y = 0;
z = 0;
break;
case CL_MEM_OBJECT_IMAGE2D_ARRAY:
z = 0;
break;
}
VkOffset3D offset = {x, y, z};
return offset;
}
VkExtent3D prepare_extent(cvk_image* image, std::array<size_t, 3> region) {
uint32_t extentHeight = region[1];
uint32_t extentDepth = region[2];
switch (image->type()) {
case CL_MEM_OBJECT_IMAGE1D_ARRAY:
extentHeight = 1;
extentDepth = 1;
break;
case CL_MEM_OBJECT_IMAGE2D_ARRAY:
extentDepth = 1;
break;
}
VkExtent3D extent = {static_cast<uint32_t>(region[0]), extentHeight,
extentDepth};
return extent;
}
VkBufferImageCopy prepare_buffer_image_copy(cvk_image* image,
size_t bufferOffset,
std::array<size_t, 3> origin,
std::array<size_t, 3> region) {
uint32_t extentHeight = region[1];
uint32_t extentDepth = region[2];
uint32_t baseArrayLayer = 0;
uint32_t layerCount = 1;
switch (image->type()) {
case CL_MEM_OBJECT_IMAGE1D_ARRAY:
baseArrayLayer = origin[1];
layerCount = region[1];
extentHeight = 1;
extentDepth = 1;
break;
case CL_MEM_OBJECT_IMAGE2D_ARRAY:
baseArrayLayer = origin[2];
layerCount = region[2];
extentDepth = 1;
break;
}
VkImageSubresourceLayers subResource = {
VK_IMAGE_ASPECT_COLOR_BIT, // aspectMask
0, // mipLevel
baseArrayLayer, layerCount};
VkOffset3D offset = prepare_offset(image, origin);
cvk_debug_fn("offset: %d, %d, %d", offset.x, offset.y, offset.z);
VkExtent3D extent = {static_cast<uint32_t>(region[0]), extentHeight,
extentDepth};
cvk_debug_fn("extent: %u, %u, %u", extent.width, extent.height,
extent.depth);
// Tightly pack the data in the destination buffer
VkBufferImageCopy ret = {
bufferOffset, // bufferOffset
0, // bufferRowLength
0, // bufferImageHeight
subResource, // imageSubresource
offset, // imageOffset
extent, // imageExtent
};
return ret;
}
cl_int cvk_command_map_image::build(void** map_ptr) {
// Get a mapping
if (!m_image->find_or_create_mapping(m_mapping, m_origin, m_region,
m_flags)) {
return CL_OUT_OF_RESOURCES;
}
*map_ptr = m_mapping.ptr;
// TODO deal with CL_MEM_USE_HOST_PTR
if (needs_copy()) {
m_cmd_copy = std::make_unique<cvk_command_buffer_image_copy>(
CL_COMMAND_MAP_IMAGE, m_queue, m_mapping.buffer, m_image, 0,
m_origin, m_region);
cl_int err = m_cmd_copy->build();
if (err != CL_SUCCESS) {
return err;
}
}
return CL_SUCCESS;
}
cl_int cvk_command_map_image::do_action() {
if (needs_copy()) {
auto err = m_cmd_copy->do_action();
if (err != CL_COMPLETE) {
return CL_OUT_OF_RESOURCES;
}
}
// TODO invalidate buffer if the memory isn't coherent
return CL_COMPLETE;
}
void cvk_command_buffer_image_copy::build_inner_image_to_buffer(
const VkBufferImageCopy& region) {
VkImageSubresourceRange subresourceRange = {
VK_IMAGE_ASPECT_COLOR_BIT, // aspectMask
0, // baseMipLevel
VK_REMAINING_MIP_LEVELS, // levelCount
0, // baseArrayLayer
VK_REMAINING_ARRAY_LAYERS, // layerCount
};
VkImageMemoryBarrier imageBarrier = {
VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
nullptr,
VK_ACCESS_MEMORY_WRITE_BIT, // srcAccessMask
VK_ACCESS_TRANSFER_READ_BIT, // dstAccessMask
VK_IMAGE_LAYOUT_GENERAL, // oldLayout
VK_IMAGE_LAYOUT_GENERAL, // newLayout
0, // srcQueueFamilyIndex
0, // dstQueueFamilyIndex
m_image->vulkan_image(), // image
subresourceRange,
};
vkCmdPipelineBarrier(m_command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT,
0, // dependencyFlags
0, // memoryBarrierCount
nullptr, // pMemoryBarriers
0, // bufferMemoryBarrierCount
nullptr, // pBufferMemoryBarriers
1, // imageMemoryBarrierCount
&imageBarrier); // pImageMemoryBarriers
vkCmdCopyImageToBuffer(m_command_buffer, m_image->vulkan_image(),
VK_IMAGE_LAYOUT_GENERAL, m_buffer->vulkan_buffer(),
1, ®ion);
}
void cvk_command_buffer_image_copy::build_inner_buffer_to_image(
const VkBufferImageCopy& region) {
VkBufferMemoryBarrier bufferBarrier = {
VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER,
nullptr,
VK_ACCESS_MEMORY_WRITE_BIT,
VK_ACCESS_TRANSFER_READ_BIT,
0, // srcQueueFamilyIndex
0, // dstQueueFamilyIndex
m_buffer->vulkan_buffer(),
0, // offset
VK_WHOLE_SIZE};
vkCmdPipelineBarrier(m_command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT,
0, // dependencyFlags
0, // memoryBarrierCount
nullptr, // pMemoryBarriers
1, // bufferMemoryBarrierCount
&bufferBarrier, // pBufferMemoryBarriers
0, // imageMemoryBarrierCount
nullptr); // pImageMemoryBarriers
vkCmdCopyBufferToImage(m_command_buffer, m_buffer->vulkan_buffer(),
m_image->vulkan_image(), VK_IMAGE_LAYOUT_GENERAL, 1,
®ion);
}
cl_int cvk_command_buffer_image_copy::build() {
if (!m_command_buffer.begin()) {
return CL_OUT_OF_RESOURCES;
}
VkBufferImageCopy region =
prepare_buffer_image_copy(m_image, m_offset, m_origin, m_region);
switch (type()) {
case CL_COMMAND_COPY_IMAGE_TO_BUFFER:
case CL_COMMAND_MAP_IMAGE:
build_inner_image_to_buffer(region);
break;
case CL_COMMAND_COPY_BUFFER_TO_IMAGE:
case CL_COMMAND_UNMAP_MEM_OBJECT:
build_inner_buffer_to_image(region);
break;
default:
CVK_ASSERT(false);
break;
}
VkMemoryBarrier memoryBarrier = {
VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_TRANSFER_WRITE_BIT,
VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_MEMORY_READ_BIT};
vkCmdPipelineBarrier(
m_command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT,
// TODO HOST only when the dest buffer is an image mapping buffer
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
0, // dependencyFlags
1, // memoryBarrierCount
&memoryBarrier,
0, // bufferMemoryBarrierCount
nullptr, // pBufferMemoryBarriers
0, // imageMemoryBarrierCount
nullptr); // pImageMemoryBarriers
if (!m_command_buffer.end()) {
return CL_OUT_OF_RESOURCES;
}
return CL_SUCCESS;
}
cl_int cvk_command_buffer_image_copy::do_action() {
if (!m_command_buffer.submit_and_wait()) {
return CL_OUT_OF_RESOURCES;
}
return CL_COMPLETE;
}
cl_int cvk_command_image_image_copy::build() {
if (!m_command_buffer.begin()) {
return CL_OUT_OF_RESOURCES;
}
VkImageSubresourceLayers srcSubresource =
prepare_subresource(m_src_image, m_src_origin, m_region);
VkOffset3D srcOffset = prepare_offset(m_src_image, m_src_origin);
VkImageSubresourceLayers dstSubresource =
prepare_subresource(m_dst_image, m_dst_origin, m_region);
VkOffset3D dstOffset = prepare_offset(m_dst_image, m_dst_origin);
VkExtent3D extent = prepare_extent(m_src_image, m_region);
VkImageCopy region = {srcSubresource, srcOffset, dstSubresource, dstOffset,
extent};
vkCmdCopyImage(m_command_buffer, m_src_image->vulkan_image(),
VK_IMAGE_LAYOUT_GENERAL, m_dst_image->vulkan_image(),
VK_IMAGE_LAYOUT_GENERAL, 1, ®ion);
if (!m_command_buffer.end()) {
return CL_OUT_OF_RESOURCES;
}
return CL_SUCCESS;
}
cl_int cvk_command_image_image_copy::do_action() {
if (!m_command_buffer.submit_and_wait()) {
return CL_OUT_OF_RESOURCES;
}
return CL_COMPLETE;
}
cl_int cvk_command_fill_image::do_action() {
// TODO use bigger memcpy's when possible
size_t num_elems = m_region[2] * m_region[1] * m_region[0];
for (size_t elem = 0; elem < num_elems; elem++) {
auto dst = pointer_offset(m_ptr, elem * m_pattern_size);
memcpy(dst, m_pattern.data(), m_pattern_size);
}
return CL_COMPLETE;
}
|
/**********************************************************************
Golgotha Forever - A portable, free 3D strategy and FPS game.
Copyright (C) 1999 Golgotha Forever Developers
Sources contained in this distribution were derived from
Crack Dot Com's public release of Golgotha which can be
found here: http://www.crack.com
All changes and new works are licensed under the GPL:
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
For the full license, see COPYING.
***********************************************************************/
#include "pch.h"
#include "gui/browse_tree.h"
#include "window/style.h"
#include "window/colorwin.h"
#include "window/win_evt.h"
void i4_vertical_compact_window_class::compact()
{
sw32 my=0,largest_width=0;
i4_parent_window_class::win_iter w;
for (w=children.begin();
w!=children.end(); ++w)
{
if (w->width()>largest_width)
{
largest_width=w->width();
}
}
for (w=children.begin();
w!=children.end(); ++w)
{
if (center)
{
w->private_move(x() + largest_width/2-(sw32)w->width()/2 - w->x(), y() + my - w->y());
}
else
{
w->private_move(0, y() + my - w->y());
}
my+=w->height();
}
if (width()!=largest_width || my!=height())
{
resize(largest_width, my);
}
}
void i4_horizontal_compact_window_class::compact()
{
sw32 mx=0,largest_height=0;
i4_parent_window_class::win_iter w;
for (w=children.begin();
w!=children.end(); ++w)
{
if (w->height()>largest_height)
{
largest_height=w->height();
}
}
for (w=children.begin();
w!=children.end(); ++w)
{
if (center)
{
w->private_move(x() + mx - w->x(), y() + largest_height/2-(sw32)w->height()/2 - w->y());
}
else
{
w->private_move(x() + mx - w->x(), 0);
}
mx+=w->width();
}
if (mx!=width() || largest_height!=height())
{
resize(mx, largest_height);
}
}
void i4_vertical_compact_window_class::receive_event(i4_event * ev)
{
if (ev->type()==i4_event::WINDOW_MESSAGE)
{
CAST_PTR(mess,i4_window_message_class,ev);
if (mess->sub_type==i4_window_message_class::NOTIFY_RESIZE)
{
CAST_PTR(res,i4_window_notify_resize_class,ev);
sw32 ow=res->from()->width(), oh=res->from()->height();
res->from()->private_resize(res->new_width, res->new_height);
compact();
res->from()->private_resize(ow, oh);
note_undrawn(0,0, width()-1, height()-1);
}
else
{
i4_parent_window_class::receive_event(ev);
}
}
else
{
i4_parent_window_class::receive_event(ev);
}
}
void i4_vertical_compact_window_class::parent_draw(i4_draw_context_class &context)
{
i4_rect_list_class child_clip(&context.clip,0,0);
child_clip.intersect_list(&undrawn_area);
child_clip.swap(&context.clip);
local_image->clear(color,context);
child_clip.swap(&context.clip);
}
void i4_horizontal_compact_window_class::receive_event(i4_event * ev)
{
if (ev->type()==i4_event::WINDOW_MESSAGE)
{
CAST_PTR(mess,i4_window_message_class,ev);
if (mess->sub_type==i4_window_message_class::NOTIFY_RESIZE)
{
CAST_PTR(res,i4_window_notify_resize_class,ev);
sw32 ow=res->from()->width(), oh=res->from()->height();
res->from()->private_resize(res->new_width, res->new_height);
compact();
res->from()->private_resize(ow, oh);
note_undrawn(0,0, width()-1, height()-1);
}
else
{
i4_parent_window_class::receive_event(ev);
}
}
else
{
i4_parent_window_class::receive_event(ev);
}
}
void i4_horizontal_compact_window_class::parent_draw(i4_draw_context_class &context)
{
i4_rect_list_class child_clip(&context.clip,0,0);
child_clip.intersect_list(&undrawn_area);
child_clip.swap(&context.clip);
local_image->clear(color,context);
child_clip.swap(&context.clip);
}
class i4_browse_toggle_class :
public i4_window_class
{
public:
void name(char * buffer)
{
static_name(buffer,"browse_toggle");
}
enum {
EXPANDED, COMPACTED, NO_CHILDREN
} state;
i4_browse_window_class * browse_parent;
i4_graphical_style_class * style;
i4_browse_toggle_class(i4_graphical_style_class * style,
i4_browse_window_class * browse_parent,
i4_bool show_plus_minus,
i4_bool expanded,
i4_bool has_a_child)
: i4_window_class(style->icon_hint->plus_icon->width()+4,
style->icon_hint->plus_icon->height()),
browse_parent(browse_parent),
style(style)
{
if (show_plus_minus)
{
if (expanded)
{
state=EXPANDED;
}
else
{
state=COMPACTED;
}
}
else
{
state=NO_CHILDREN;
}
}
virtual void draw(i4_draw_context_class &context)
{
local_image->clear(style->color_hint->window.passive.medium, context);
if (state!=NO_CHILDREN)
{
if (state==EXPANDED)
{
style->icon_hint->plus_icon->put_image_trans(local_image, 0,0, 0, context);
}
else
{
style->icon_hint->minus_icon->put_image_trans(local_image, 0,0, 0, context);
}
}
}
virtual void receive_event(i4_event * ev)
{
if (ev->type()==i4_event::MOUSE_BUTTON_DOWN && state!=NO_CHILDREN)
{
if (state==EXPANDED)
{
state=COMPACTED;
browse_parent->compress();
}
else
{
state=EXPANDED;
browse_parent->expand();
}
request_redraw();
}
}
} ;
void i4_browse_window_class::add_arranged_child(i4_window_class * child)
{
title_area->add_child(0,0,child);
((i4_horizontal_compact_window_class *)title_area)->compact();
private_resize(0,0);
arrange_right_down();
if (child_object)
{
child_object->move(x_start(), 0);
}
resize_to_fit_children();
}
void i4_browse_window_class::compress()
{
if (child_object && expanded)
{
expanded=i4_F;
i4_parent_window_class::remove_child(child_object);
resize_to_fit_children();
}
}
void i4_browse_window_class::expand()
{
if (child_object && !expanded)
{
expanded=i4_T;
i4_parent_window_class::add_child(0,0,child_object);
private_resize(0,0);
arrange_right_down();
if (child_object)
{
child_object->move(x_start(), 0);
}
resize_to_fit_children();
}
}
void i4_browse_window_class::replace_object(i4_window_class * object)
{
if (child_object)
{
if (expanded)
{
remove_child(child_object);
}
delete child_object;
child_object=0;
/*
if (((i4_browse_toggle_class *)toggle_button)->state == i4_browse_toggle_class::EXPANDED)
((i4_browse_toggle_class *)toggle_button)->state=i4_browse_toggle_class::COMPACTED;
else if (((i4_browse_toggle_class *)toggle_button)->state == i4_browse_toggle_class::COMPACTED)
((i4_browse_toggle_class *)toggle_button)->state=i4_browse_toggle_class::EXPANDED;
*/
toggle_button->request_redraw();
private_resize(0,0);
resize_to_fit_children();
}
if (object)
{
child_object=object;
if (expanded)
{
i4_parent_window_class::add_child(0,0,object);
}
private_resize(0,0);
arrange_right_down();
object->move(x_start(), 0);
resize_to_fit_children();
}
}
class i4_browse_title_container_class :
public i4_parent_window_class
{
public:
i4_browse_title_container_class() :
i4_parent_window_class(0,0)
{
}
void name(char * buffer)
{
static_name(buffer,"browse title container");
}
};
i4_browse_window_class::i4_browse_window_class(i4_graphical_style_class * style,
i4_window_class * title_object,
i4_window_class * child_obj,
i4_bool show_plus_minus,
i4_bool expanded)
: style(style),
expanded(expanded),
i4_parent_window_class(0,0)
{
toggle_button=0;
child_object=0;
title_area=new i4_horizontal_compact_window_class(style->color_hint->window.passive.medium,
i4_T);
((i4_horizontal_compact_window_class *)title_area)->compact();
i4_parent_window_class::add_child(0,0,title_area);
toggle_button=new i4_browse_toggle_class(style, this,
show_plus_minus,
expanded,
(i4_bool)(child_obj!=0));
title_area->add_child(0,0,toggle_button);
if (title_object)
{
add_arranged_child(title_object);
}
if (child_obj)
{
replace_object(child_obj);
}
}
sw32 i4_browse_window_class::x_start()
{
return style->icon_hint->plus_icon->width() + 10;
}
void i4_browse_window_class::receive_event(i4_event * ev)
{
if (ev->type()==i4_event::WINDOW_MESSAGE)
{
CAST_PTR(mess,i4_window_message_class,ev);
if (mess->sub_type==i4_window_message_class::NOTIFY_RESIZE)
{
CAST_PTR(resize,i4_window_notify_resize_class,ev);
note_undrawn(0,0, width()-1, height()-1);
w16 ow=resize->from()->width(),
oh=resize->from()->height();
resize->from()->private_resize(resize->new_width,resize->new_height);
private_resize(0,0);
arrange_right_down();
if (child_object)
{
child_object->move(x_start(), 0);
}
resize_to_fit_children();
note_undrawn(0,0, width()-1, height()-1);
resize->from()->private_resize(ow, oh);
}
else
{
i4_parent_window_class::receive_event(ev);
}
}
else
{
i4_parent_window_class::receive_event(ev);
}
}
void i4_browse_window_class::parent_draw(i4_draw_context_class &context)
{
i4_rect_list_class child_clip(&context.clip,0,0);
child_clip.intersect_list(&undrawn_area);
child_clip.swap(&context.clip);
local_image->clear(style->color_hint->window.passive.medium,context);
child_clip.swap(&context.clip);
}
|
// Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <sge/projectile/body/solidity/solid.hpp>
sge::projectile::body::solidity::solid::solid(sge::projectile::body::mass const &_mass)
: mass_(_mass)
{
}
sge::projectile::body::mass const &sge::projectile::body::solidity::solid::mass() const
{
return mass_;
}
|
// Copyright (c) 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 <vector>
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/message_loop/message_loop.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/prefs/session_startup_pref.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/sessions/session_restore.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/startup/startup_browser_creator.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
typedef InProcessBrowserTest StartupBrowserCreatorTest;
// Chrome OS doesn't support multiprofile.
// And BrowserWindow::IsActive() always returns false in tests on MAC.
// And this test is useless without that functionality.
#if !defined(OS_CHROMEOS) && !defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorTest, LastUsedProfileActivated) {
ProfileManager* profile_manager = g_browser_process->profile_manager();
// Create 4 profiles, they will be scheduled for destruction when the last
// browser window they are associated to will be closed.
Profile* profile_1 = profile_manager->GetProfile(
profile_manager->user_data_dir().Append(FILE_PATH_LITERAL(
"New Profile 1")));
ASSERT_TRUE(profile_1);
Profile* profile_2 = profile_manager->GetProfile(
profile_manager->user_data_dir().Append(FILE_PATH_LITERAL(
"New Profile 2")));
ASSERT_TRUE(profile_2);
Profile* profile_3 = profile_manager->GetProfile(
profile_manager->user_data_dir().Append(FILE_PATH_LITERAL(
"New Profile 3")));
ASSERT_TRUE(profile_3);
Profile* profile_4 = profile_manager->GetProfile(
profile_manager->user_data_dir().Append(FILE_PATH_LITERAL(
"New Profile 4")));
ASSERT_TRUE(profile_4);
SessionStartupPref pref_urls(SessionStartupPref::URLS);
pref_urls.urls.push_back(ui_test_utils::GetTestUrl(
base::FilePath(base::FilePath::kCurrentDirectory),
base::FilePath(FILE_PATH_LITERAL("title1.html"))));
SessionStartupPref::SetStartupPref(profile_1, pref_urls);
SessionStartupPref::SetStartupPref(profile_2, pref_urls);
SessionStartupPref::SetStartupPref(profile_3, pref_urls);
SessionStartupPref::SetStartupPref(profile_4, pref_urls);
// Do a simple non-process-startup browser launch.
base::CommandLine dummy(base::CommandLine::NO_PROGRAM);
StartupBrowserCreator browser_creator;
std::vector<Profile*> last_opened_profiles;
last_opened_profiles.push_back(profile_1);
last_opened_profiles.push_back(profile_2);
last_opened_profiles.push_back(profile_3);
last_opened_profiles.push_back(profile_4);
browser_creator.Start(dummy, profile_manager->user_data_dir(), profile_2,
last_opened_profiles);
while (!browser_creator.ActivatedProfile())
base::MessageLoop::current()->RunUntilIdle();
Browser* new_browser = NULL;
// The last used profile (the profile_2 in this case) must be active.
ASSERT_EQ(1u, chrome::GetBrowserCount(profile_2,
browser()->host_desktop_type()));
new_browser = FindBrowserWithProfile(profile_2,
browser()->host_desktop_type());
ASSERT_TRUE(new_browser);
EXPECT_TRUE(new_browser->window()->IsActive());
// All other profiles browser should not be active.
ASSERT_EQ(1u, chrome::GetBrowserCount(profile_1,
browser()->host_desktop_type()));
new_browser = FindBrowserWithProfile(profile_1,
browser()->host_desktop_type());
ASSERT_TRUE(new_browser);
EXPECT_FALSE(new_browser->window()->IsActive());
ASSERT_EQ(1u, chrome::GetBrowserCount(profile_3,
browser()->host_desktop_type()));
new_browser = FindBrowserWithProfile(profile_3,
browser()->host_desktop_type());
ASSERT_TRUE(new_browser);
EXPECT_FALSE(new_browser->window()->IsActive());
ASSERT_EQ(1u, chrome::GetBrowserCount(profile_4,
browser()->host_desktop_type()));
new_browser = FindBrowserWithProfile(profile_4,
browser()->host_desktop_type());
ASSERT_TRUE(new_browser);
EXPECT_FALSE(new_browser->window()->IsActive());
}
#endif // !OS_MACOSX && !OS_CHROMEOS
|
// Copyright (c) 2015-2018 The Ebits developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/platformstyle.h>
#include <qt/guiconstants.h>
#include <QApplication>
#include <QColor>
#include <QImage>
#include <QPalette>
static const struct {
const char *platformId;
/** Show images on push buttons */
const bool imagesOnButtons;
/** Colorize single-color icons */
const bool colorizeIcons;
/** Extra padding/spacing in transactionview */
const bool useExtraSpacing;
} platform_styles[] = {
{"macosx", false, false, true},
{"windows", true, false, false},
/* Other: linux, unix, ... */
{"other", true, true, false}
};
static const unsigned platform_styles_count = sizeof(platform_styles)/sizeof(*platform_styles);
namespace {
/* Local functions for colorizing single-color images */
void MakeSingleColorImage(QImage& img, const QColor& colorbase)
{
img = img.convertToFormat(QImage::Format_ARGB32);
for (int x = img.width(); x--; )
{
for (int y = img.height(); y--; )
{
const QRgb rgb = img.pixel(x, y);
img.setPixel(x, y, qRgba(colorbase.red(), colorbase.green(), colorbase.blue(), qAlpha(rgb)));
}
}
}
QIcon ColorizeIcon(const QIcon& ico, const QColor& colorbase)
{
QIcon new_ico;
for (const QSize& sz : ico.availableSizes())
{
QImage img(ico.pixmap(sz).toImage());
MakeSingleColorImage(img, colorbase);
new_ico.addPixmap(QPixmap::fromImage(img));
}
return new_ico;
}
QImage ColorizeImage(const QString& filename, const QColor& colorbase)
{
QImage img(filename);
MakeSingleColorImage(img, colorbase);
return img;
}
QIcon ColorizeIcon(const QString& filename, const QColor& colorbase)
{
return QIcon(QPixmap::fromImage(ColorizeImage(filename, colorbase)));
}
}
PlatformStyle::PlatformStyle(const QString &_name, bool _imagesOnButtons, bool _colorizeIcons, bool _useExtraSpacing):
name(_name),
imagesOnButtons(_imagesOnButtons),
colorizeIcons(_colorizeIcons),
useExtraSpacing(_useExtraSpacing),
singleColor(0,0,0),
textColor(0,0,0)
{
// Determine icon highlighting color
if (colorizeIcons) {
const QColor colorHighlightBg(QApplication::palette().color(QPalette::Highlight));
const QColor colorHighlightFg(QApplication::palette().color(QPalette::HighlightedText));
const QColor colorText(QApplication::palette().color(QPalette::WindowText));
const int colorTextLightness = colorText.lightness();
QColor colorbase;
if (abs(colorHighlightBg.lightness() - colorTextLightness) < abs(colorHighlightFg.lightness() - colorTextLightness))
colorbase = colorHighlightBg;
else
colorbase = colorHighlightFg;
singleColor = colorbase;
}
// Determine text color
textColor = QColor(QApplication::palette().color(QPalette::WindowText));
}
QImage PlatformStyle::SingleColorImage(const QString& filename) const
{
if (!colorizeIcons)
return QImage(filename);
return ColorizeImage(filename, SingleColor());
}
QIcon PlatformStyle::SingleColorIcon(const QString& filename) const
{
if (!colorizeIcons)
return QIcon(filename);
return ColorizeIcon(filename, SingleColor());
}
QIcon PlatformStyle::SingleColorIcon(const QIcon& icon) const
{
if (!colorizeIcons)
return icon;
return ColorizeIcon(icon, SingleColor());
}
QIcon PlatformStyle::TextColorIcon(const QString& filename) const
{
return ColorizeIcon(filename, TextColor());
}
QIcon PlatformStyle::TextColorIcon(const QIcon& icon) const
{
return ColorizeIcon(icon, TextColor());
}
const PlatformStyle *PlatformStyle::instantiate(const QString &platformId)
{
for (unsigned x=0; x<platform_styles_count; ++x)
{
if (platformId == platform_styles[x].platformId)
{
return new PlatformStyle(
platform_styles[x].platformId,
platform_styles[x].imagesOnButtons,
platform_styles[x].colorizeIcons,
platform_styles[x].useExtraSpacing);
}
}
return 0;
}
|
// Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/ledger/bin/storage/impl/split.h"
#include <lib/callback/waiter.h>
#include <lib/fit/function.h>
#include <limits>
#include <memory>
#include <sstream>
#include "src/ledger/bin/storage/impl/constants.h"
#include "src/ledger/bin/storage/impl/file_index.h"
#include "src/ledger/bin/storage/impl/file_index_generated.h"
#include "src/ledger/bin/storage/impl/object_digest.h"
#include "src/ledger/bin/storage/impl/object_identifier_encoding.h"
#include "src/ledger/bin/storage/public/data_source.h"
#include "src/ledger/bin/storage/public/types.h"
#include "src/ledger/third_party/bup/bupsplit.h"
#include "src/lib/fxl/macros.h"
#include "src/lib/fxl/memory/ref_ptr.h"
namespace storage {
namespace {
constexpr size_t kMinChunkSize = 4 * 1024;
constexpr size_t kMaxChunkSize = std::numeric_limits<uint16_t>::max();
constexpr size_t kBitsPerLevel = 4;
// Empiric maximal size for an identifier in an index file. This should be the
// smallest possible number that allow the Split tests to pass.
constexpr size_t kMaxIdentifierSize = 77;
// The max number of identifiers that an index can contain so that the file size
// is less than |kMaxChunkSize|.
constexpr size_t kMaxIdentifiersPerIndex = kMaxChunkSize / kMaxIdentifierSize;
using ObjectIdentifierAndSize = FileIndexSerialization::ObjectIdentifierAndSize;
struct ChunkAndSize {
std::unique_ptr<DataSource::DataChunk> chunk;
uint64_t size;
};
// Handles the successive callbacks from the DataSource.
//
// Algorithm:
// This class keeps track of a list of identifiers per level. For each level,
// the list must be aggregated into an index file, or if alone at the highest
// level when the algorithm ends, sent to the client.
// The algorithm reads data from the source and feeds it to the rolling hash.
// For each chunk cut by the rolling hash, the identifier of the chunk is added
// at level 0. The rolling hash algorithm also returns the number of index files
// that need to be built. An index file is also built as soon as a level
// contains |kMaxIdentifiersPerIndex| identifiers.
// When the algorithm builds the index at level |n| it does the following:
// For all levels from 0 to |n|:
// - Build the index file at the given level. As a special case, if there is
// a single object at the given level, just move it to the next level and
// continue.
// - Send the index file to the client.
// - Add the identifier of the index file at the next level.
class SplitContext {
public:
explicit SplitContext(
fit::function<ObjectIdentifier(ObjectDigest)> make_object_identifier,
fit::function<void(IterationStatus, std::unique_ptr<Piece>)> callback,
ObjectType object_type)
: make_object_identifier_(std::move(make_object_identifier)),
callback_(std::move(callback)),
object_type_(object_type),
roll_sum_split_(kMinChunkSize, kMaxChunkSize) {}
SplitContext(SplitContext&& other) = default;
~SplitContext() {}
void AddChunk(std::unique_ptr<DataSource::DataChunk> chunk,
DataSource::Status status) {
if (status == DataSource::Status::ERROR) {
callback_(IterationStatus::ERROR, nullptr);
return;
}
FXL_DCHECK(chunk || status == DataSource::Status::DONE);
if (chunk) {
ProcessChunk(std::move(chunk));
}
if (status != DataSource::Status::DONE) {
return;
}
if (!current_chunks_.empty()) {
// The remaining data needs to be sent even if it is not chunked at an
// expected cut point.
BuildAndSendNextChunk(views_.back().size());
}
// No data remains.
FXL_DCHECK(current_chunks_.empty());
// The final id to send exists.
FXL_DCHECK(!current_identifiers_per_level_.back().empty());
// This traverses the stack of indices, sending each level until a single
// top level index is produced.
for (size_t i = 0; i < current_identifiers_per_level_.size(); ++i) {
if (current_identifiers_per_level_[i].empty()) {
continue;
}
// At the top of the stack with a single element, the algorithm is
// finished. The top-level object_identifier is the unique element.
if (i == current_identifiers_per_level_.size() - 1 &&
current_identifiers_per_level_[i].size() == 1) {
// This identifier may be recomputed by SendDone, so this is not
// necessarily the final value that we are going to send, but we check
// that we last called |SendInProgress| on it for consistency.
FXL_DCHECK(current_identifiers_per_level_[i][0].identifier ==
latest_piece_.identifier);
SendDone();
return;
}
BuildIndexAtLevel(i);
}
FXL_NOTREACHED();
}
private:
// Information about a piece of data (chunk or index) to be sent.
struct PendingPiece {
ObjectIdentifier identifier;
std::unique_ptr<DataSource::DataChunk> data;
bool ready() { return data != nullptr; }
};
// Returns the object identifier for |data| of the given |type|, and invokes
// |callback_| with IN_PROGRESS status. Actually defers sending the object
// until the next call of this method, because the last object needs to be
// treated differently in |SendDone|. |children| must contain the identifiers
// of the children pieces if |type| is INDEX, and be empty otherwise.
ObjectIdentifier SendInProgress(PieceType type,
std::unique_ptr<DataSource::DataChunk> data) {
if (latest_piece_.ready()) {
callback_(
IterationStatus::IN_PROGRESS,
std::make_unique<DataChunkPiece>(std::move(latest_piece_.identifier),
std::move(latest_piece_.data)));
}
auto data_view = data->Get();
// object_type for inner (IN_PROGRESS) pieces is always BLOB, regardless of
// the overall |object_type_|. It may need to be TREE_NODE if this is the
// very last piece (DONE), but we do not know it at this stage. We account
// for this by recomputing the object digest in |SendDone|. It does not
// matter if we return a wrong identifier here, because it will not be used
// at all if we are at the root piece.
ObjectDigest object_digest =
ComputeObjectDigest(type, ObjectType::BLOB, data_view);
latest_piece_.identifier =
make_object_identifier_(std::move(object_digest));
latest_piece_.data = std::move(data);
return latest_piece_.identifier;
}
// Recomputes the object identifier for the last object to send: since it is
// the root of the piece hierarchy, it needs to have the |tree_node| bit set
// if we are splitting a TreeNode. Then sends this object identifier as DONE.
void SendDone() {
FXL_DCHECK(latest_piece_.ready());
auto data_view = latest_piece_.data->Get();
ObjectDigest object_digest = ComputeObjectDigest(
GetObjectDigestInfo(latest_piece_.identifier.object_digest())
.piece_type,
object_type_, data_view);
latest_piece_.identifier =
make_object_identifier_(std::move(object_digest));
callback_(IterationStatus::DONE, std::make_unique<DataChunkPiece>(
std::move(latest_piece_.identifier),
std::move(latest_piece_.data)));
}
std::vector<ObjectIdentifierAndSize>& GetCurrentIdentifiersAtLevel(
size_t level) {
if (level >= current_identifiers_per_level_.size()) {
FXL_DCHECK(level == current_identifiers_per_level_.size());
current_identifiers_per_level_.resize(level + 1);
}
return current_identifiers_per_level_[level];
}
// Appends the given chunk to the unprocessed data and processes as much data
// as possible using the rolling hash to determine where to cut the stream in
// pieces.
void ProcessChunk(std::unique_ptr<DataSource::DataChunk> chunk) {
views_.push_back(chunk->Get());
current_chunks_.push_back(std::move(chunk));
while (!views_.empty()) {
size_t bits;
size_t split_index = roll_sum_split_.Feed(views_.back(), &bits);
if (split_index == 0) {
return;
}
BuildAndSendNextChunk(split_index);
size_t level = GetLevel(bits);
for (size_t i = 0; i < level; ++i) {
FXL_DCHECK(!current_identifiers_per_level_[i].empty());
BuildIndexAtLevel(i);
}
}
}
void BuildAndSendNextChunk(size_t split_index) {
auto data = BuildNextChunk(split_index);
auto size = data->Get().size();
auto identifier = SendInProgress(PieceType::CHUNK, std::move(data));
AddIdentifierAtLevel(0, {std::move(identifier), size});
}
void AddIdentifierAtLevel(size_t level, ObjectIdentifierAndSize data) {
GetCurrentIdentifiersAtLevel(level).push_back(std::move(data));
if (current_identifiers_per_level_[level].size() <
kMaxIdentifiersPerIndex) {
// The level is not full, more identifiers can be added.
return;
}
FXL_DCHECK(current_identifiers_per_level_[level].size() ==
kMaxIdentifiersPerIndex);
// The level contains the max number of identifiers. Creating the index
// file.
AddIdentifierAtLevel(
level + 1,
BuildAndSendIndex(std::move(current_identifiers_per_level_[level])));
current_identifiers_per_level_[level].clear();
}
void BuildIndexAtLevel(size_t level) {
auto objects = std::move(current_identifiers_per_level_[level]);
current_identifiers_per_level_[level].clear();
if (objects.size() == 1) {
AddIdentifierAtLevel(level + 1, std::move(objects.front()));
} else {
auto id_and_size = BuildAndSendIndex(std::move(objects));
AddIdentifierAtLevel(level + 1, std::move(id_and_size));
}
}
ObjectIdentifierAndSize BuildAndSendIndex(
std::vector<ObjectIdentifierAndSize> identifiers_and_sizes) {
FXL_DCHECK(identifiers_and_sizes.size() > 1);
FXL_DCHECK(identifiers_and_sizes.size() <= kMaxIdentifiersPerIndex);
std::unique_ptr<DataSource::DataChunk> chunk;
size_t total_size;
FileIndexSerialization::BuildFileIndex(identifiers_and_sizes, &chunk,
&total_size);
FXL_DCHECK(chunk->Get().size() <= kMaxChunkSize)
<< "Expected maximum of: " << kMaxChunkSize
<< ", but got: " << chunk->Get().size();
auto identifier = SendInProgress(PieceType::INDEX, std::move(chunk));
return {std::move(identifier), total_size};
}
static size_t GetLevel(size_t bits) {
FXL_DCHECK(bits >= bup::kBlobBits);
return (bits - bup::kBlobBits) / kBitsPerLevel;
}
std::unique_ptr<DataSource::DataChunk> BuildNextChunk(size_t index) {
FXL_DCHECK(current_chunks_.size() == views_.size());
FXL_DCHECK(!current_chunks_.empty());
FXL_DCHECK(views_.back().size() >= index);
if (views_.size() == 1 && views_.front().size() == index &&
views_.front().size() == current_chunks_.front()->Get().size()) {
std::unique_ptr<DataSource::DataChunk> result =
std::move(current_chunks_.front());
views_.clear();
current_chunks_.clear();
return result;
}
std::string data;
size_t total_size = index;
for (size_t i = 0; i + 1 < views_.size(); ++i) {
total_size += views_[i].size();
}
data.reserve(total_size);
for (size_t i = 0; i + 1 < views_.size(); ++i) {
data.append(views_[i].data(), views_[i].size());
}
fxl::StringView last = views_.back();
data.append(last.data(), index);
if (index < last.size()) {
views_.clear();
if (current_chunks_.size() > 1) {
std::swap(current_chunks_.front(), current_chunks_.back());
current_chunks_.resize(1);
}
views_.push_back(last.substr(index));
} else {
current_chunks_.clear();
views_.clear();
}
FXL_DCHECK(current_chunks_.size() == views_.size());
return DataSource::DataChunk::Create(std::move(data));
}
fit::function<ObjectIdentifier(ObjectDigest)> make_object_identifier_;
fit::function<void(IterationStatus, std::unique_ptr<Piece>)> callback_;
// The object encoded by DataSource.
const ObjectType object_type_;
bup::RollSumSplit roll_sum_split_;
// The list of chunks from the initial source that are not yet entirely
// consumed.
std::vector<std::unique_ptr<DataSource::DataChunk>> current_chunks_;
// The list of data that has not yet been consumed. For all indexes, the view
// at the given index is a view to the chunk at the same index.
std::vector<fxl::StringView> views_;
// List of unsent indices per level.
std::vector<std::vector<ObjectIdentifierAndSize>>
current_identifiers_per_level_;
// The most recent piece that is entirely consumed but not yet sent to
// |callback_|.
PendingPiece latest_piece_;
FXL_DISALLOW_COPY_AND_ASSIGN(SplitContext);
};
class CollectPiecesState
: public fxl::RefCountedThreadSafe<CollectPiecesState> {
public:
fit::function<void(ObjectIdentifier,
fit::function<void(Status, fxl::StringView)>)>
data_accessor;
fit::function<bool(IterationStatus, ObjectIdentifier)> callback;
bool running = true;
};
void CollectPiecesInternal(ObjectIdentifier root,
fxl::RefPtr<CollectPiecesState> state,
fit::closure on_done) {
if (!state->callback(IterationStatus::IN_PROGRESS, root)) {
on_done();
return;
}
if (GetObjectDigestInfo(root.object_digest()).piece_type !=
PieceType::INDEX) {
on_done();
return;
}
state->data_accessor(root, [state, on_done = std::move(on_done)](
Status status, fxl::StringView data) mutable {
if (!state->running) {
on_done();
return;
}
if (status != Status::OK) {
FXL_LOG(WARNING) << "Unable to read object content.";
state->running = false;
on_done();
return;
}
auto waiter = fxl::MakeRefCounted<callback::CompletionWaiter>();
status = ForEachIndexChild(data, [&](ObjectIdentifier identifier) {
CollectPiecesInternal(std::move(identifier), state,
waiter->NewCallback());
return Status::OK;
});
if (status != Status::OK) {
state->running = false;
on_done();
return;
}
waiter->Finalize(std::move(on_done));
});
}
} // namespace
void SplitDataSource(
DataSource* source, ObjectType object_type,
fit::function<ObjectIdentifier(ObjectDigest)> make_object_identifier,
fit::function<void(IterationStatus, std::unique_ptr<Piece>)> callback) {
SplitContext context(std::move(make_object_identifier), std::move(callback),
object_type);
source->Get([context = std::move(context)](
std::unique_ptr<DataSource::DataChunk> chunk,
DataSource::Status status) mutable {
context.AddChunk(std::move(chunk), status);
});
}
Status ForEachIndexChild(fxl::StringView index_content,
fit::function<Status(ObjectIdentifier)> callback) {
const FileIndex* file_index;
Status status =
FileIndexSerialization::ParseFileIndex(index_content, &file_index);
if (status != Status::OK) {
return status;
}
for (const auto* child : *file_index->children()) {
Status status = callback(ToObjectIdentifier(child->object_identifier()));
if (status != Status::OK) {
return status;
}
}
return Status::OK;
}
void CollectPieces(
ObjectIdentifier root,
fit::function<void(ObjectIdentifier,
fit::function<void(Status, fxl::StringView)>)>
data_accessor,
fit::function<bool(IterationStatus, ObjectIdentifier)> callback) {
auto state = fxl::MakeRefCounted<CollectPiecesState>();
state->data_accessor = std::move(data_accessor);
state->callback = std::move(callback);
CollectPiecesInternal(root, state, [state] {
IterationStatus final_status =
state->running ? IterationStatus::DONE : IterationStatus::ERROR;
state->callback(final_status, {});
});
}
} // namespace storage
|
/* NAME:
QD3DDrawContext.cpp
DESCRIPTION:
Entry point for Quesa API calls. Performs parameter checking and
then forwards each API call to the equivalent E3xxxxx routine.
COPYRIGHT:
Copyright (c) 1999-2021, Quesa Developers. All rights reserved.
For the current release of Quesa, please see:
<https://github.com/jwwalker/Quesa>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
o Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
o 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.
o Neither the name of Quesa 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 files
//-----------------------------------------------------------------------------
#include "E3Prefix.h"
#include "E3DrawContext.h"
//=============================================================================
// Internal constants
//-----------------------------------------------------------------------------
// Internal constants go here
//=============================================================================
// Internal types
//-----------------------------------------------------------------------------
// Internal types go here
//=============================================================================
// Internal macros
//-----------------------------------------------------------------------------
// Internal macros go here
//=============================================================================
// Public functions
//-----------------------------------------------------------------------------
// Q3DrawContext_GetType : Quesa API entry point.
//-----------------------------------------------------------------------------
#pragma mark -
TQ3ObjectType
Q3DrawContext_GetType(TQ3DrawContextObject drawContext)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( drawContext ), kQ3ObjectTypeInvalid ) ;
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3DrawContext_GetType(drawContext));
}
//=============================================================================
// Q3DrawContext_SetData : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3DrawContext_SetData(TQ3DrawContextObject context, const TQ3DrawContextData *contextData)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( context ), kQ3Failure ) ;
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(contextData), kQ3Failure);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3DrawContext_SetData(context, contextData));
}
//=============================================================================
// Q3DrawContext_GetData : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3DrawContext_GetData(TQ3DrawContextObject context, TQ3DrawContextData *contextData)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( context ), kQ3Failure ) ;
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(contextData), kQ3Failure);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3DrawContext_GetData(context, contextData));
}
//=============================================================================
// Q3DrawContext_SetClearImageColor : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3DrawContext_SetClearImageColor(TQ3DrawContextObject context, const TQ3ColorARGB *color)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( context ), kQ3Failure ) ;
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(color), kQ3Failure);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3DrawContext_SetClearImageColor(context, color));
}
//=============================================================================
// Q3DrawContext_GetClearImageColor : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3DrawContext_GetClearImageColor(TQ3DrawContextObject context, TQ3ColorARGB *color)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( context ), kQ3Failure ) ;
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(color), kQ3Failure);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3DrawContext_GetClearImageColor(context, color));
}
//=============================================================================
// Q3DrawContext_SetPane : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3DrawContext_SetPane(TQ3DrawContextObject context, const TQ3Area *pane)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( context ), kQ3Failure ) ;
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(pane), kQ3Failure);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3DrawContext_SetPane(context, pane));
}
//=============================================================================
// Q3DrawContext_GetPane : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3DrawContext_GetPane(TQ3DrawContextObject context, TQ3Area *pane)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( context ), kQ3Failure ) ;
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(pane), kQ3Failure);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return ( (E3DrawContext*) context )->GetPane ( pane ) ;
}
//=============================================================================
// Q3DrawContext_SetPaneState : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3DrawContext_SetPaneState(TQ3DrawContextObject context, TQ3Boolean state)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( context ), kQ3Failure ) ;
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3DrawContext_SetPaneState(context, state));
}
//=============================================================================
// Q3DrawContext_GetPaneState : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3DrawContext_GetPaneState(TQ3DrawContextObject context, TQ3Boolean *state)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( context ), kQ3Failure ) ;
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(state), kQ3Failure);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3DrawContext_GetPaneState(context, state));
}
//=============================================================================
// Q3DrawContext_SetClearImageMethod : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3DrawContext_SetClearImageMethod(TQ3DrawContextObject context, TQ3DrawContextClearImageMethod method)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( context ), kQ3Failure ) ;
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3DrawContext_SetClearImageMethod(context, method));
}
//=============================================================================
// Q3DrawContext_GetClearImageMethod : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3DrawContext_GetClearImageMethod(TQ3DrawContextObject context, TQ3DrawContextClearImageMethod *method)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( context ), kQ3Failure ) ;
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(method), kQ3Failure);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3DrawContext_GetClearImageMethod(context, method));
}
//=============================================================================
// Q3DrawContext_SetMask : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3DrawContext_SetMask(TQ3DrawContextObject context, const TQ3Bitmap *mask)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( context ), kQ3Failure ) ;
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(mask), kQ3Failure);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3DrawContext_SetMask(context, mask));
}
//=============================================================================
// Q3DrawContext_GetMask : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3DrawContext_GetMask(TQ3DrawContextObject context, TQ3Bitmap *mask)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( context ), kQ3Failure ) ;
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(mask), kQ3Failure);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3DrawContext_GetMask(context, mask));
}
//=============================================================================
// Q3DrawContext_SetMaskState : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3DrawContext_SetMaskState(TQ3DrawContextObject context, TQ3Boolean state)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( context ), kQ3Failure ) ;
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3DrawContext_SetMaskState(context, state));
}
//=============================================================================
// Q3DrawContext_GetMaskState : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3DrawContext_GetMaskState(TQ3DrawContextObject context, TQ3Boolean *state)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( context ), kQ3Failure ) ;
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(state), kQ3Failure);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3DrawContext_GetMaskState(context, state));
}
//=============================================================================
// Q3DrawContext_SetDoubleBufferState : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3DrawContext_SetDoubleBufferState(TQ3DrawContextObject context, TQ3Boolean state)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( context ), kQ3Failure ) ;
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3DrawContext_SetDoubleBufferState(context, state));
}
//=============================================================================
// Q3DrawContext_GetDoubleBufferState : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3DrawContext_GetDoubleBufferState(TQ3DrawContextObject context, TQ3Boolean *state)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( context ), kQ3Failure ) ;
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(state), kQ3Failure);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3DrawContext_GetDoubleBufferState(context, state));
}
#pragma mark -
/*!
* @function
* Q3GenericDrawContext_New
* @discussion
* Create a new Generic draw context object.
*
* @param contextPane The pane area for the generic draw context object.
* @result The new draw context object.
*/
TQ3DrawContextObject _Nonnull
Q3GenericDrawContext_New (
const TQ3Area * _Nonnull contextPane )
{
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return E3GenericDrawContext_New(contextPane);
}
#pragma mark -
//=============================================================================
// Q3PixmapDrawContext_New : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3DrawContextObject
Q3PixmapDrawContext_New(const TQ3PixmapDrawContextData *contextData)
{
// Release build checks
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(contextData), nullptr);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3PixmapDrawContext_New(contextData));
}
//=============================================================================
// Q3PixmapDrawContext_SetPixmap : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3PixmapDrawContext_SetPixmap(TQ3DrawContextObject drawContext, const TQ3Pixmap *pixmap)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( drawContext ), kQ3Failure ) ;
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(pixmap), kQ3Failure);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3PixmapDrawContext_SetPixmap(drawContext, pixmap));
}
//=============================================================================
// Q3PixmapDrawContext_GetPixmap : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3PixmapDrawContext_GetPixmap(TQ3DrawContextObject drawContext, TQ3Pixmap *pixmap)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( drawContext ), kQ3Failure ) ;
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(pixmap), kQ3Failure);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3PixmapDrawContext_GetPixmap(drawContext, pixmap));
}
//=============================================================================
// Q3XBuffers_New : Quesa API entry point.
//-----------------------------------------------------------------------------
#pragma mark -
#if QUESA_OS_UNIX
TQ3XBufferObject
Q3XBuffers_New(Display *dpy, TQ3Uns32 numBuffers, Window window)
{
// Release build checks
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(dpy), nullptr);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3XBuffers_New(dpy, numBuffers, window));
}
//=============================================================================
// Q3XBuffers_Swap : Quesa API entry point.
//-----------------------------------------------------------------------------
void
Q3XBuffers_Swap(Display *dpy, TQ3XBufferObject buffers)
{
// Release build checks
Q3_REQUIRE(Q3_VALID_PTR(dpy));
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
E3XBuffers_Swap(dpy, buffers);
}
//=============================================================================
// Q3X_GetVisualInfo : Quesa API entry point.
//-----------------------------------------------------------------------------
XVisualInfo *
Q3X_GetVisualInfo(Display *dpy, Screen *screen)
{
// Release build checks
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(dpy), nullptr);
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(screen), nullptr);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3X_GetVisualInfo(dpy, screen));
}
//=============================================================================
// Q3XDrawContext_New : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3DrawContextObject
Q3XDrawContext_New(const TQ3XDrawContextData *drawContextData)
{
// Release build checks
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(drawContextData), nullptr);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3XDrawContext_New(drawContextData));
}
//=============================================================================
// Q3XDrawContext_SetDisplay : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3XDrawContext_SetDisplay(TQ3DrawContextObject drawContext, const Display *display)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( drawContext ), kQ3Failure ) ;
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(display), kQ3Failure);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3XDrawContext_SetDisplay(drawContext, display));
}
//=============================================================================
// Q3XDrawContext_GetDisplay : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3XDrawContext_GetDisplay(TQ3DrawContextObject drawContext, Display **display)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( drawContext ), kQ3Failure ) ;
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(display), kQ3Failure);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3XDrawContext_GetDisplay(drawContext, display));
}
//=============================================================================
// Q3XDrawContext_SetDrawable : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3XDrawContext_SetDrawable(TQ3DrawContextObject drawContext, Drawable drawable)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( drawContext ), kQ3Failure ) ;
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3XDrawContext_SetDrawable(drawContext, drawable));
}
//=============================================================================
// Q3XDrawContext_GetDrawable : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3XDrawContext_GetDrawable(TQ3DrawContextObject drawContext, Drawable *drawable)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( drawContext ), kQ3Failure ) ;
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(drawable), kQ3Failure);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3XDrawContext_GetDrawable(drawContext, drawable));
}
//=============================================================================
// Q3XDrawContext_SetVisual : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3XDrawContext_SetVisual(TQ3DrawContextObject drawContext, const Visual *visual)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( drawContext ), kQ3Failure ) ;
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(visual), kQ3Failure);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3XDrawContext_SetVisual(drawContext, visual));
}
//=============================================================================
// Q3XDrawContext_GetVisual : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3XDrawContext_GetVisual(TQ3DrawContextObject drawContext, Visual **visual)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( drawContext ), kQ3Failure ) ;
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(visual), kQ3Failure);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3XDrawContext_GetVisual(drawContext, visual));
}
//=============================================================================
// Q3XDrawContext_SetColormap : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3XDrawContext_SetColormap(TQ3DrawContextObject drawContext, Colormap colormap)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( drawContext ), kQ3Failure ) ;
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3XDrawContext_SetColormap(drawContext, colormap));
}
//=============================================================================
// Q3XDrawContext_GetColormap : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3XDrawContext_GetColormap(TQ3DrawContextObject drawContext, Colormap *colormap)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( drawContext ), kQ3Failure ) ;
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(colormap), kQ3Failure);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3XDrawContext_GetColormap(drawContext, colormap));
}
//=============================================================================
// Q3XDrawContext_SetColormapData : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3XDrawContext_SetColormapData(TQ3DrawContextObject drawContext, const TQ3XColormapData *colormapData)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( drawContext ), kQ3Failure ) ;
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(colormapData), kQ3Failure);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3XDrawContext_SetColormapData(drawContext, colormapData));
}
//=============================================================================
// Q3XDrawContext_GetColormapData : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3XDrawContext_GetColormapData(TQ3DrawContextObject drawContext, TQ3XColormapData *colormapData)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( drawContext ), kQ3Failure ) ;
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(colormapData), kQ3Failure);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3XDrawContext_GetColormapData(drawContext, colormapData));
}
#endif // QUESA_OS_UNIX
//=============================================================================
// Q3Win32DCDrawContext_New : Quesa API entry point.
//-----------------------------------------------------------------------------
#pragma mark -
#if QUESA_OS_WIN32
TQ3DrawContextObject
Q3Win32DCDrawContext_New(const TQ3Win32DCDrawContextData *drawContextData)
{
// Release build checks
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(drawContextData), nullptr);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3Win32DCDrawContext_New(drawContextData));
}
//=============================================================================
// Q3Win32DCDrawContext_SetDC : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3Win32DCDrawContext_SetDC(TQ3DrawContextObject drawContext, HDC newHDC)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( drawContext ), kQ3Failure ) ;
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3Win32DCDrawContext_SetDC(drawContext, newHDC));
}
//=============================================================================
// Q3Win32DCDrawContext_GetDC : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3Win32DCDrawContext_GetDC(TQ3DrawContextObject drawContext, HDC *curHDC)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( drawContext ), kQ3Failure ) ;
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(curHDC), kQ3Failure);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3Win32DCDrawContext_GetDC(drawContext, curHDC));
}
#if !defined(QD3D_NO_DIRECTDRAW)
//=============================================================================
// Q3DDSurfaceDrawContext_New : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3DrawContextObject
Q3DDSurfaceDrawContext_New(const TQ3DDSurfaceDrawContextData *drawContextData)
{
// Release build checks
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(drawContextData), nullptr);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3DDSurfaceDrawContext_New(drawContextData));
}
//=============================================================================
// Q3DDSurfaceDrawContext_SetDirectDrawSurface : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3DDSurfaceDrawContext_SetDirectDrawSurface(TQ3DrawContextObject drawContext, const TQ3DDSurfaceDescriptor *ddSurfaceDescriptor)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( drawContext ), kQ3Failure ) ;
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(ddSurfaceDescriptor), kQ3Failure);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3DDSurfaceDrawContext_SetDirectDrawSurface(drawContext, ddSurfaceDescriptor));
}
//=============================================================================
// Q3DDSurfaceDrawContext_GetDirectDrawSurface : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3DDSurfaceDrawContext_GetDirectDrawSurface(TQ3DrawContextObject drawContext, TQ3DDSurfaceDescriptor *ddSurfaceDescriptor)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( drawContext ), kQ3Failure ) ;
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(ddSurfaceDescriptor), kQ3Failure);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3DDSurfaceDrawContext_GetDirectDrawSurface(drawContext, ddSurfaceDescriptor));
}
#endif // QD3D_NO_DIRECTDRAW
#endif // QUESA_OS_WIN32
//=============================================================================
// Q3CocoaDrawContext_New : Quesa API entry point.
//-----------------------------------------------------------------------------
#pragma mark -
#if QUESA_OS_COCOA
TQ3DrawContextObject
Q3CocoaDrawContext_New(const TQ3CocoaDrawContextData *drawContextData)
{
// Release build checks
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(drawContextData), nullptr);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3CocoaDrawContext_New(drawContextData));
}
//=============================================================================
// Q3CocoaDrawContext_SetNSView : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3CocoaDrawContext_SetNSView(TQ3DrawContextObject drawContext, void *nsView)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( drawContext ), kQ3Failure ) ;
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3CocoaDrawContext_SetNSView(drawContext, nsView));
}
//=============================================================================
// Q3CocoaDrawContext_GetNSView : Quesa API entry point.
//-----------------------------------------------------------------------------
TQ3Status
Q3CocoaDrawContext_GetNSView(TQ3DrawContextObject drawContext, void **nsView)
{
// Release build checks
Q3_REQUIRE_OR_RESULT( E3DrawContext_IsOfMyClass ( drawContext ), kQ3Failure ) ;
Q3_REQUIRE_OR_RESULT(Q3_VALID_PTR(nsView), kQ3Failure);
// Debug build checks
// Call the bottleneck
E3System_Bottleneck();
// Call our implementation
return(E3CocoaDrawContext_GetNSView(drawContext, nsView));
}
#endif // QUESA_OS_COCOA
|
#include <gtest/gtest-message.h> // for Message
#include <gtest/gtest-test-part.h> // for TestPartResult, SuiteApiResolver, TestFactoryImpl
#include <memory> // for allocator, __shared_ptr_access, shared_ptr
#include <string> // for string, basic_string
#include <vector> // for vector
#include "ftxui/component/captured_mouse.hpp" // for ftxui
#include "ftxui/component/component.hpp" // for Menu
#include "ftxui/component/component_base.hpp" // for ComponentBase
#include "ftxui/component/component_options.hpp" // for MenuOption
#include "ftxui/component/event.hpp" // for Event, Event::ArrowDown, Event::Return
#include "ftxui/util/ref.hpp" // for Ref
#include "gtest/gtest_pred_impl.h" // for Test, EXPECT_EQ, TEST
using namespace ftxui;
TEST(MenuTest, RemoveEntries) {
int focused_entry = 0;
int selected = 0;
std::vector<std::string> entries = {"1", "2", "3"};
MenuOption option;
option.focused_entry = &focused_entry;
auto menu = Menu(&entries, &selected, option);
EXPECT_EQ(selected, 0);
EXPECT_EQ(focused_entry, 0);
menu->OnEvent(Event::ArrowDown);
menu->OnEvent(Event::ArrowDown);
menu->OnEvent(Event::Return);
EXPECT_EQ(selected, 2);
EXPECT_EQ(focused_entry, 2);
entries.resize(2);
EXPECT_EQ(selected, 2);
EXPECT_EQ(focused_entry, 2);
(void)menu->Render();
EXPECT_EQ(selected, 1);
EXPECT_EQ(focused_entry, 1);
}
// Copyright 2022 Arthur Sonzogni. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
|
#include "object.h"
#include <vector>
#include <string>
using namespace similarity;
int main(int argc, char* argv[]) {
std::vector<string> strs = {
"xyz", "beagcfa", "cea", "cb",
"d", "c", "bdaf", "ddcd",
"egbfa", "a", "fba", "bcccfe",
"ab", "bfgbfdc", "bcbbgf", "bfbb"
};
for (int i = 0; i < 16; ++i) {
LabelType label = i * 1000 + i;
IdType id = i + 1;
Object* obj = new Object(id, label, strs[i].size(), strs[i].c_str());
std::string tmp(obj->data(), obj->datalength());
std::cout << tmp << std::endl;
delete obj;
}
return 0;
};
|
#include "scripthelper.h"
void ScriptHelper::BBSetCameraPosition(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBIsPathable(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBTeleportToKeyLocation(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBTeleportToPosition(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBGetNearestPassablePosition(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBForEachUnitInTargetAreaAddBuff(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBForEachUnitInTargetArea(sol::stack_object passThrough, sol::stack_object perBlockParams, sol::stack_object subBlocks)
{
}
void ScriptHelper::BBForEachUnitInTargetAreaRandom(sol::stack_object passThrough, sol::stack_object perBlockParams, sol::stack_object subBlocks)
{
}
void ScriptHelper::BBForNClosestUnitsInTargetArea(sol::stack_object passThrough, sol::stack_object perBlockParams, sol::stack_object subBlocks)
{
}
void ScriptHelper::BBForEachChampion(sol::stack_object passThrough, sol::stack_object perBlockParams, sol::stack_object subBlocks)
{
}
void ScriptHelper::BBForEachUnitInTargetRectangle(sol::stack_object passThrough, sol::stack_object perBlockParams, sol::stack_object subBlocks)
{
}
void ScriptHelper::BBGetRandomPointInAreaUnit(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBGetRandomPointInAreaPosition(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBGetUnitPosition(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBGetSkinID(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBGetPointByUnitFacingOffset(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBGetMissilePosFromID(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBModifyPosition(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBIncFlatPARPoolMod(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBIncFlatPARRegenMod(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBIncPercentPARPoolMod(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBIncPercentPARRegenMod(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBIncPermanentFlatPARPoolMod(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBIncPermanentFlatPARRegenMod(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBIncPermanentPercentPARPoolMod(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBIncPermanentPercentPARRegenMod(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBGetFlatPARPoolMod(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBGetFlatPARRegenMod(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBGetPercentPARPoolMod(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBGetPercentPARRegenMod(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBApplyDamage(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBApplyStun(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBApplyPacified(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBApplyNet(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBApplyDisarm(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBApplySuppression(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBApplySilence(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBApplyRoot(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBApplyTaunt(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBApplyCharm(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBApplyFear(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBApplySleep(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBApplyNearSight(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBApplyNoRender(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBApplyForceRenderParticles(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBApplyStealth(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBApplyRevealSpecificUnit(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBApplySuppressCallForHelp(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBApplyCallForHelpSuppresser(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBApplyIgnoreCallForHelp(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBIncPAR(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBIncGold(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
float ScriptHelper::BBLuaGetGold(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
return 0;
}
void ScriptHelper::BBIncHealth(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBDrawDefaultHitEffects(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBGetCastSpellTargetPos(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBAdjustCastInfoCenterAOE(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSpawnPet(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSpawnMinion(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBCloneUnit(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBCloneUnitPet(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBIncExp(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBForEachPetInTarget(sol::stack_object passThrough, sol::stack_object perBlockParams, sol::stack_object subBlocks)
{
}
void ScriptHelper::BBSetDodgePiercing(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSetStateDisableAmbientGold(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSetStunned(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSetPacified(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSetNetted(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSetDisarmed(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSetRooted(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSetSuppressCallForHelp(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSetCallForHelpSuppresser(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBRedirectGold(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSetTargetingType(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSetSpell(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSetBuffCasterUnit(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSetTriggerUnit(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSetUnit(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBInvalidateUnit(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBForceDead(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSetIgnoreCallForHelp(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSpellBuffAdd(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBTimeChannelTickExecute(sol::stack_object passThrough, sol::stack_object perBlockParams, sol::stack_object subBlocks)
{
}
void ScriptHelper::BBBreak(sol::stack_object passThrough, sol::stack_object perBlockParams, sol::stack_object subBlocks)
{
}
void ScriptHelper::BBSpellBuffRemoveType(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSpellBuffRemove(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSpellBuffRemoveCurrent(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSpellBuffClear(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBGetBuffRemainingDuration(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSpellEffectCreate(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSpellEffectRemove(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBStopChanneling(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBStopMove(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBMove(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBMoveAway(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBDestroyMissile(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBDestroyMissileForTarget(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSpellCast(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBCancelAutoAttack(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBOverrideAutoAttack(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBRemoveOverrideAutoAttack(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSetAutoAttackTargetingFlags(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSetPetReturnRadius(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBCreateItem(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSealSpellSlot(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSetBuffToolTipVar(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSetSpellToolTipVar(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBLinkVisibility(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBIsInBrush(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBGetHeightDifference(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBRemoveLinkVisibility(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSetNearSight(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBGetNearSight(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBGetPetOwner(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBStartTrackingCollisions(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBStopMoveBlock(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBStopCurrentOverrideAnimation(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBPreloadCharacter(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBPreloadParticle(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBPreloadSpell(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBDispellPositiveBuffs(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBDispellNegativeBuffs(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBRemovePerceptionBubble(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBAddUnitPerceptionBubble(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBAddPosPerceptionBubble(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBPlayAnimation(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBUnlockAnimation(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBGetNumberOfHeroesOnTeam(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBCanSeeTarget(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBPushCharacterData(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSetSlotSpellCooldownTimeVer2(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBPopCharacterData(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBPopAllCharacterData(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBPushCharacterFade(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBPopCharacterFade(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBForEachPointAroundCircle(sol::stack_object passThrough, sol::stack_object perBlockParams, sol::stack_object subBlocks)
{
}
void ScriptHelper::BBSetCharacterDebugRadius(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBForEachPointOnLine(sol::stack_object passThrough, sol::stack_object perBlockParams, sol::stack_object subBlocks)
{
}
void ScriptHelper::BBFaceDirection(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBGetGameTime(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBGetChampionBySkinName(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBPauseAnimation(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBEnableWallOfGrassTracking(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBShowHealthBar(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBClearOverrideAnimation(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBOverrideAnimation(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBIncSpellLevel(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSetPARCostInc(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBGetPARCostInc(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSetPARMultiplicativeCostInc(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBGetPARMultiplicativeCostInc(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSetInCastTable(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBOverrideCastRange(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBGetCastRange(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBAddDebugCircle(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBRemoveDebugCircle(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBModifyDebugCircleRadius(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBModifyDebugCircleColor(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBApplyAssistMarker(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBSkipNextAutoAttack(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBIncMaxHealth(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
void ScriptHelper::BBGetIsZombie(sol::stack_object passThrough, sol::stack_object perBlockParams)
{
}
float ScriptHelper::GetCFParam(sol::stack_object passThrough, sol::stack_object perBlockParams, std::string parramName)
{
return 0;
}
|
/*
******************************************************************************
* Copyright (C) 2001-2009, International Business Machines
* Corporation and others. All Rights Reserved.
******************************************************************************
*
* File ucoleitr.cpp
*
* Modification History:
*
* Date Name Description
* 02/15/2001 synwee Modified all methods to process its own function
* instead of calling the equivalent c++ api (coleitr.h)
******************************************************************************/
#include "unicode/utypes.h"
#if !UCONFIG_NO_COLLATION
#include "unicode/ucoleitr.h"
#include "unicode/ustring.h"
#include "unicode/sortkey.h"
#include "unicode/uobject.h"
#include "ucol_imp.h"
#include "cmemory.h"
U_NAMESPACE_USE
#define BUFFER_LENGTH 100
#define DEFAULT_BUFFER_SIZE 16
#define BUFFER_GROW 8
#define ARRAY_SIZE(array) (sizeof array / sizeof array[0])
#define ARRAY_COPY(dst, src, count) uprv_memcpy((void *) (dst), (void *) (src), (count) * sizeof (src)[0])
#define NEW_ARRAY(type, count) (type *) uprv_malloc((count) * sizeof(type))
#define GROW_ARRAY(array, newSize) uprv_realloc((void *) (array), (newSize) * sizeof (array)[0])
#define DELETE_ARRAY(array) uprv_free((void *) (array))
typedef struct collIterate collIterator;
struct RCEI
{
uint32_t ce;
int32_t low;
int32_t high;
};
U_NAMESPACE_BEGIN
struct RCEBuffer
{
RCEI defaultBuffer[DEFAULT_BUFFER_SIZE];
RCEI *buffer;
int32_t bufferIndex;
int32_t bufferSize;
RCEBuffer();
~RCEBuffer();
UBool empty() const;
void put(uint32_t ce, int32_t ixLow, int32_t ixHigh);
const RCEI *get();
};
RCEBuffer::RCEBuffer()
{
buffer = defaultBuffer;
bufferIndex = 0;
bufferSize = DEFAULT_BUFFER_SIZE;
}
RCEBuffer::~RCEBuffer()
{
if (buffer != defaultBuffer) {
DELETE_ARRAY(buffer);
}
}
UBool RCEBuffer::empty() const
{
return bufferIndex <= 0;
}
void RCEBuffer::put(uint32_t ce, int32_t ixLow, int32_t ixHigh)
{
if (bufferIndex >= bufferSize) {
RCEI *newBuffer = NEW_ARRAY(RCEI, bufferSize + BUFFER_GROW);
ARRAY_COPY(newBuffer, buffer, bufferSize);
if (buffer != defaultBuffer) {
DELETE_ARRAY(buffer);
}
buffer = newBuffer;
bufferSize += BUFFER_GROW;
}
buffer[bufferIndex].ce = ce;
buffer[bufferIndex].low = ixLow;
buffer[bufferIndex].high = ixHigh;
bufferIndex += 1;
}
const RCEI *RCEBuffer::get()
{
if (bufferIndex > 0) {
return &buffer[--bufferIndex];
}
return NULL;
}
struct PCEI
{
uint64_t ce;
int32_t low;
int32_t high;
};
struct PCEBuffer
{
PCEI defaultBuffer[DEFAULT_BUFFER_SIZE];
PCEI *buffer;
int32_t bufferIndex;
int32_t bufferSize;
PCEBuffer();
~PCEBuffer();
void reset();
UBool empty() const;
void put(uint64_t ce, int32_t ixLow, int32_t ixHigh);
const PCEI *get();
};
PCEBuffer::PCEBuffer()
{
buffer = defaultBuffer;
bufferIndex = 0;
bufferSize = DEFAULT_BUFFER_SIZE;
}
PCEBuffer::~PCEBuffer()
{
if (buffer != defaultBuffer) {
DELETE_ARRAY(buffer);
}
}
void PCEBuffer::reset()
{
bufferIndex = 0;
}
UBool PCEBuffer::empty() const
{
return bufferIndex <= 0;
}
void PCEBuffer::put(uint64_t ce, int32_t ixLow, int32_t ixHigh)
{
if (bufferIndex >= bufferSize) {
PCEI *newBuffer = NEW_ARRAY(PCEI, bufferSize + BUFFER_GROW);
ARRAY_COPY(newBuffer, buffer, bufferSize);
if (buffer != defaultBuffer) {
DELETE_ARRAY(buffer);
}
buffer = newBuffer;
bufferSize += BUFFER_GROW;
}
buffer[bufferIndex].ce = ce;
buffer[bufferIndex].low = ixLow;
buffer[bufferIndex].high = ixHigh;
bufferIndex += 1;
}
const PCEI *PCEBuffer::get()
{
if (bufferIndex > 0) {
return &buffer[--bufferIndex];
}
return NULL;
}
/*
* This inherits from UObject so that
* it can be allocated by new and the
* constructor for PCEBuffer is called.
*/
struct UCollationPCE : public UObject
{
PCEBuffer pceBuffer;
UCollationStrength strength;
UBool toShift;
UBool isShifted;
uint32_t variableTop;
UCollationPCE(UCollationElements *elems);
~UCollationPCE();
void init(const UCollator *coll);
virtual UClassID getDynamicClassID() const;
static UClassID getStaticClassID();
};
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(UCollationPCE)
UCollationPCE::UCollationPCE(UCollationElements *elems)
{
init(elems->iteratordata_.coll);
}
void UCollationPCE::init(const UCollator *coll)
{
UErrorCode status = U_ZERO_ERROR;
strength = ucol_getStrength(coll);
toShift = ucol_getAttribute(coll, UCOL_ALTERNATE_HANDLING, &status) == UCOL_SHIFTED;
isShifted = FALSE;
variableTop = coll->variableTopValue << 16;
}
UCollationPCE::~UCollationPCE()
{
// nothing to do
}
U_NAMESPACE_END
inline uint64_t processCE(UCollationElements *elems, uint32_t ce)
{
uint64_t primary = 0, secondary = 0, tertiary = 0, quaternary = 0;
// This is clean, but somewhat slow...
// We could apply the mask to ce and then
// just get all three orders...
switch(elems->pce->strength) {
default:
tertiary = ucol_tertiaryOrder(ce);
/* note fall-through */
case UCOL_SECONDARY:
secondary = ucol_secondaryOrder(ce);
/* note fall-through */
case UCOL_PRIMARY:
primary = ucol_primaryOrder(ce);
}
// **** This should probably handle continuations too. ****
// **** That means that we need 24 bits for the primary ****
// **** instead of the 16 that we're currently using. ****
// **** So we can lay out the 64 bits as: 24.12.12.16. ****
// **** Another complication with continuations is that ****
// **** the *second* CE is marked as a continuation, so ****
// **** we always have to peek ahead to know how long ****
// **** the primary is... ****
if (elems->pce->toShift && (elems->pce->variableTop > ce && primary != 0)
|| (elems->pce->isShifted && primary == 0)) {
if (primary == 0) {
return UCOL_IGNORABLE;
}
if (elems->pce->strength >= UCOL_QUATERNARY) {
quaternary = primary;
}
primary = secondary = tertiary = 0;
elems->pce->isShifted = TRUE;
} else {
if (elems->pce->strength >= UCOL_QUATERNARY) {
quaternary = 0xFFFF;
}
elems->pce->isShifted = FALSE;
}
return primary << 48 | secondary << 32 | tertiary << 16 | quaternary;
}
U_CAPI void U_EXPORT2
uprv_init_pce(const UCollationElements *elems)
{
if (elems->pce != NULL) {
elems->pce->init(elems->iteratordata_.coll);
}
}
/* public methods ---------------------------------------------------- */
U_CAPI UCollationElements* U_EXPORT2
ucol_openElements(const UCollator *coll,
const UChar *text,
int32_t textLength,
UErrorCode *status)
{
UCollationElements *result;
if (U_FAILURE(*status)) {
return NULL;
}
result = (UCollationElements *)uprv_malloc(sizeof(UCollationElements));
/* test for NULL */
if (result == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
return NULL;
}
result->reset_ = TRUE;
result->isWritable = FALSE;
result->pce = NULL;
if (text == NULL) {
textLength = 0;
}
uprv_init_collIterate(coll, text, textLength, &result->iteratordata_);
return result;
}
U_CAPI void U_EXPORT2
ucol_closeElements(UCollationElements *elems)
{
if (elems != NULL) {
collIterate *ci = &elems->iteratordata_;
if (ci != NULL) {
if (ci->writableBuffer != ci->stackWritableBuffer) {
uprv_free(ci->writableBuffer);
}
if (ci->extendCEs) {
uprv_free(ci->extendCEs);
}
if (ci->offsetBuffer) {
uprv_free(ci->offsetBuffer);
}
}
if (elems->isWritable && elems->iteratordata_.string != NULL)
{
uprv_free(elems->iteratordata_.string);
}
if (elems->pce != NULL) {
delete elems->pce;
}
uprv_free(elems);
}
}
U_CAPI void U_EXPORT2
ucol_reset(UCollationElements *elems)
{
collIterate *ci = &(elems->iteratordata_);
elems->reset_ = TRUE;
ci->pos = ci->string;
if ((ci->flags & UCOL_ITER_HASLEN) == 0 || ci->endp == NULL) {
ci->endp = ci->string + u_strlen(ci->string);
}
ci->CEpos = ci->toReturn = ci->CEs;
ci->flags = (ci->flags & UCOL_FORCE_HAN_IMPLICIT) | UCOL_ITER_HASLEN;
if (ci->coll->normalizationMode == UCOL_ON) {
ci->flags |= UCOL_ITER_NORM;
}
if (ci->stackWritableBuffer != ci->writableBuffer) {
uprv_free(ci->writableBuffer);
ci->writableBuffer = ci->stackWritableBuffer;
ci->writableBufSize = UCOL_WRITABLE_BUFFER_SIZE;
}
ci->fcdPosition = NULL;
//ci->offsetReturn = ci->offsetStore = NULL;
ci->offsetRepeatCount = ci->offsetRepeatValue = 0;
}
U_CAPI void U_EXPORT2
ucol_forceHanImplicit(UCollationElements *elems, UErrorCode *status)
{
if (U_FAILURE(*status)) {
return;
}
if (elems == NULL) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
elems->iteratordata_.flags |= UCOL_FORCE_HAN_IMPLICIT;
}
U_CAPI int32_t U_EXPORT2
ucol_next(UCollationElements *elems,
UErrorCode *status)
{
int32_t result;
if (U_FAILURE(*status)) {
return UCOL_NULLORDER;
}
elems->reset_ = FALSE;
result = (int32_t)ucol_getNextCE(elems->iteratordata_.coll,
&elems->iteratordata_,
status);
if (result == UCOL_NO_MORE_CES) {
result = UCOL_NULLORDER;
}
return result;
}
U_CAPI int64_t U_EXPORT2
ucol_nextProcessed(UCollationElements *elems,
int32_t *ixLow,
int32_t *ixHigh,
UErrorCode *status)
{
const UCollator *coll = elems->iteratordata_.coll;
int64_t result = UCOL_IGNORABLE;
uint32_t low = 0, high = 0;
if (U_FAILURE(*status)) {
return UCOL_PROCESSED_NULLORDER;
}
if (elems->pce == NULL) {
elems->pce = new UCollationPCE(elems);
} else {
elems->pce->pceBuffer.reset();
}
elems->reset_ = FALSE;
do {
low = ucol_getOffset(elems);
uint32_t ce = (uint32_t) ucol_getNextCE(coll, &elems->iteratordata_, status);
high = ucol_getOffset(elems);
if (ce == UCOL_NO_MORE_CES) {
result = UCOL_PROCESSED_NULLORDER;
break;
}
result = processCE(elems, ce);
} while (result == UCOL_IGNORABLE);
if (ixLow != NULL) {
*ixLow = low;
}
if (ixHigh != NULL) {
*ixHigh = high;
}
return result;
}
U_CAPI int32_t U_EXPORT2
ucol_previous(UCollationElements *elems,
UErrorCode *status)
{
if(U_FAILURE(*status)) {
return UCOL_NULLORDER;
}
else
{
int32_t result;
if (elems->reset_ && (elems->iteratordata_.pos == elems->iteratordata_.string)) {
if (elems->iteratordata_.endp == NULL) {
elems->iteratordata_.endp = elems->iteratordata_.string +
u_strlen(elems->iteratordata_.string);
elems->iteratordata_.flags |= UCOL_ITER_HASLEN;
}
elems->iteratordata_.pos = elems->iteratordata_.endp;
elems->iteratordata_.fcdPosition = elems->iteratordata_.endp;
}
elems->reset_ = FALSE;
result = (int32_t)ucol_getPrevCE(elems->iteratordata_.coll,
&(elems->iteratordata_),
status);
if (result == UCOL_NO_MORE_CES) {
result = UCOL_NULLORDER;
}
return result;
}
}
U_CAPI int64_t U_EXPORT2
ucol_previousProcessed(UCollationElements *elems,
int32_t *ixLow,
int32_t *ixHigh,
UErrorCode *status)
{
const UCollator *coll = elems->iteratordata_.coll;
int64_t result = UCOL_IGNORABLE;
// int64_t primary = 0, secondary = 0, tertiary = 0, quaternary = 0;
// UCollationStrength strength = ucol_getStrength(coll);
// UBool toShift = ucol_getAttribute(coll, UCOL_ALTERNATE_HANDLING, status) == UCOL_SHIFTED;
// uint32_t variableTop = coll->variableTopValue;
int32_t low = 0, high = 0;
if (U_FAILURE(*status)) {
return UCOL_PROCESSED_NULLORDER;
}
if (elems->reset_ &&
(elems->iteratordata_.pos == elems->iteratordata_.string)) {
if (elems->iteratordata_.endp == NULL) {
elems->iteratordata_.endp = elems->iteratordata_.string +
u_strlen(elems->iteratordata_.string);
elems->iteratordata_.flags |= UCOL_ITER_HASLEN;
}
elems->iteratordata_.pos = elems->iteratordata_.endp;
elems->iteratordata_.fcdPosition = elems->iteratordata_.endp;
}
if (elems->pce == NULL) {
elems->pce = new UCollationPCE(elems);
} else {
//elems->pce->pceBuffer.reset();
}
elems->reset_ = FALSE;
while (elems->pce->pceBuffer.empty()) {
// buffer raw CEs up to non-ignorable primary
RCEBuffer rceb;
uint32_t ce;
// **** do we need to reset rceb, or will it always be empty at this point ****
do {
high = ucol_getOffset(elems);
ce = ucol_getPrevCE(coll, &elems->iteratordata_, status);
low = ucol_getOffset(elems);
if (ce == UCOL_NO_MORE_CES) {
if (! rceb.empty()) {
break;
}
goto finish;
}
rceb.put(ce, low, high);
} while ((ce & UCOL_PRIMARYMASK) == 0);
// process the raw CEs
while (! rceb.empty()) {
const RCEI *rcei = rceb.get();
result = processCE(elems, rcei->ce);
if (result != UCOL_IGNORABLE) {
elems->pce->pceBuffer.put(result, rcei->low, rcei->high);
}
}
}
finish:
if (elems->pce->pceBuffer.empty()) {
// **** Is -1 the right value for ixLow, ixHigh? ****
if (ixLow != NULL) {
*ixLow = -1;
}
if (ixHigh != NULL) {
*ixHigh = -1
;
}
return UCOL_PROCESSED_NULLORDER;
}
const PCEI *pcei = elems->pce->pceBuffer.get();
if (ixLow != NULL) {
*ixLow = pcei->low;
}
if (ixHigh != NULL) {
*ixHigh = pcei->high;
}
return pcei->ce;
}
U_CAPI int32_t U_EXPORT2
ucol_getMaxExpansion(const UCollationElements *elems,
int32_t order)
{
uint8_t result;
#if 0
UCOL_GETMAXEXPANSION(elems->iteratordata_.coll, (uint32_t)order, result);
#else
const UCollator *coll = elems->iteratordata_.coll;
const uint32_t *start;
const uint32_t *limit;
const uint32_t *mid;
uint32_t strengthMask = 0;
uint32_t mOrder = (uint32_t) order;
switch (coll->strength)
{
default:
strengthMask |= UCOL_TERTIARYORDERMASK;
/* fall through */
case UCOL_SECONDARY:
strengthMask |= UCOL_SECONDARYORDERMASK;
/* fall through */
case UCOL_PRIMARY:
strengthMask |= UCOL_PRIMARYORDERMASK;
}
mOrder &= strengthMask;
start = (coll)->endExpansionCE;
limit = (coll)->lastEndExpansionCE;
while (start < limit - 1) {
mid = start + ((limit - start) >> 1);
if (mOrder <= (*mid & strengthMask)) {
limit = mid;
} else {
start = mid;
}
}
// FIXME: with a masked search, there might be more than one hit,
// so we need to look forward and backward from the match to find all
// of the hits...
if ((*start & strengthMask) == mOrder) {
result = *((coll)->expansionCESize + (start - (coll)->endExpansionCE));
} else if ((*limit & strengthMask) == mOrder) {
result = *(coll->expansionCESize + (limit - coll->endExpansionCE));
} else if ((mOrder & 0xFFFF) == 0x00C0) {
result = 2;
} else {
result = 1;
}
#endif
return result;
}
U_CAPI void U_EXPORT2
ucol_setText( UCollationElements *elems,
const UChar *text,
int32_t textLength,
UErrorCode *status)
{
if (U_FAILURE(*status)) {
return;
}
if (elems->isWritable && elems->iteratordata_.string != NULL)
{
uprv_free(elems->iteratordata_.string);
}
if (text == NULL) {
textLength = 0;
}
elems->isWritable = FALSE;
/* free offset buffer to avoid memory leak before initializing. */
ucol_freeOffsetBuffer(&(elems->iteratordata_));
uprv_init_collIterate(elems->iteratordata_.coll, text, textLength,
&elems->iteratordata_);
elems->reset_ = TRUE;
}
U_CAPI int32_t U_EXPORT2
ucol_getOffset(const UCollationElements *elems)
{
const collIterate *ci = &(elems->iteratordata_);
if (ci->offsetRepeatCount > 0 && ci->offsetRepeatValue != 0) {
return ci->offsetRepeatValue;
}
if (ci->offsetReturn != NULL) {
return *ci->offsetReturn;
}
// while processing characters in normalization buffer getOffset will
// return the next non-normalized character.
// should be inline with the old implementation since the old codes uses
// nextDecomp in normalizer which also decomposes the string till the
// first base character is found.
if (ci->flags & UCOL_ITER_INNORMBUF) {
if (ci->fcdPosition == NULL) {
return 0;
}
return (int32_t)(ci->fcdPosition - ci->string);
}
else {
return (int32_t)(ci->pos - ci->string);
}
}
U_CAPI void U_EXPORT2
ucol_setOffset(UCollationElements *elems,
int32_t offset,
UErrorCode *status)
{
if (U_FAILURE(*status)) {
return;
}
// this methods will clean up any use of the writable buffer and points to
// the original string
collIterate *ci = &(elems->iteratordata_);
ci->pos = ci->string + offset;
ci->CEpos = ci->toReturn = ci->CEs;
if (ci->flags & UCOL_ITER_INNORMBUF) {
ci->flags = ci->origFlags;
}
if ((ci->flags & UCOL_ITER_HASLEN) == 0) {
ci->endp = ci->string + u_strlen(ci->string);
ci->flags |= UCOL_ITER_HASLEN;
}
ci->fcdPosition = NULL;
elems->reset_ = FALSE;
ci->offsetReturn = NULL;
ci->offsetStore = ci->offsetBuffer;
ci->offsetRepeatCount = ci->offsetRepeatValue = 0;
}
U_CAPI int32_t U_EXPORT2
ucol_primaryOrder (int32_t order)
{
order &= UCOL_PRIMARYMASK;
return (order >> UCOL_PRIMARYORDERSHIFT);
}
U_CAPI int32_t U_EXPORT2
ucol_secondaryOrder (int32_t order)
{
order &= UCOL_SECONDARYMASK;
return (order >> UCOL_SECONDARYORDERSHIFT);
}
U_CAPI int32_t U_EXPORT2
ucol_tertiaryOrder (int32_t order)
{
return (order & UCOL_TERTIARYMASK);
}
void ucol_freeOffsetBuffer(collIterate *s) {
if (s != NULL && s->offsetBuffer != NULL) {
uprv_free(s->offsetBuffer);
s->offsetBuffer = NULL;
s->offsetBufferSize = 0;
}
}
#endif /* #if !UCONFIG_NO_COLLATION */
|
#pragma once
#ifndef _ENTITYSYSTEM_COMPONENTDATACONVERSION_HPP_
#define _ENTITYSYSTEM_COMPONENTDATACONVERSION_HPP_
#include "ComponentDataTypes.hpp"
namespace Fnd
{
namespace EntitySystem
{
class EntitySystem;
}
namespace ContentManager
{
class ContentManager;
}
}
namespace Fnd
{
namespace EntitySystem
{
template <typename T>
void ConvertFromString( const std::string& as_string, T& t );
}
}
#endif
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <fstream>
#include "itkGrayscaleMorphologicalClosingImageFilter.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkTextOutput.h"
#include "itkNumericTraits.h"
#include "itkFilterWatcher.h"
#include "itkSimpleFilterWatcher.h"
int itkOptGrayscaleMorphologicalClosingImageFilterTest(int ac, char* av[] )
{
// Comment the following if you want to use the itk text output window
itk::OutputWindow::SetInstance(itk::TextOutput::New());
if(ac < 7)
{
std::cerr << "Usage: " << av[0] << " InputImage BASIC HISTO ANCHOR VHGW SafeBorder" << std::endl;
return -1;
}
unsigned int const dim = 2;
typedef itk::Image<unsigned char, dim> ImageType;
typedef itk::ImageFileReader<ImageType> ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(av[1]);
// Create a filter
typedef itk::FlatStructuringElement<dim> SRType;
typedef itk::GrayscaleMorphologicalClosingImageFilter< ImageType, ImageType, SRType > FilterType;
FilterType::Pointer filter = FilterType::New();
filter->SetInput( reader->GetOutput() );
itk::SimpleFilterWatcher watcher(filter, "filter");
typedef FilterType::RadiusType RadiusType;
// test default values
RadiusType r1;
r1.Fill( 1 );
if ( filter->GetRadius() != r1 )
{
std::cerr << "Wrong default Radius: " << filter->GetRadius() << std::endl;
return EXIT_FAILURE;
}
if ( filter->GetAlgorithm() != FilterType::HISTO )
{
std::cerr << "Wrong default algorithm." << std::endl;
return EXIT_FAILURE;
}
if ( filter->GetSafeBorder() != true )
{
std::cerr << "Wrong default safe border." << std::endl;
return EXIT_FAILURE;
}
try
{
filter->SetRadius( 20 );
filter->SetSafeBorder( atoi(av[6]) );
typedef itk::ImageFileWriter< ImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput( filter->GetOutput() );
filter->SetAlgorithm( FilterType::BASIC );
writer->SetFileName( av[2] );
writer->Update();
filter->SetAlgorithm( FilterType::HISTO );
writer->SetFileName( av[3] );
writer->Update();
filter->SetAlgorithm( FilterType::ANCHOR );
writer->SetFileName( av[4] );
writer->Update();
filter->SetAlgorithm( FilterType::VHGW );
writer->SetFileName( av[5] );
writer->Update();
}
catch (itk::ExceptionObject& e)
{
std::cerr << "Exception detected: " << e.GetDescription();
return EXIT_FAILURE;
}
// Generate test image
typedef itk::ImageFileWriter<ImageType> WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput( filter->GetOutput() );
writer->SetFileName( av[2] );
writer->Update();
return EXIT_SUCCESS;
}
|
/****************************************************************************
Copyright (C) 2013 Henry van Merode. All rights reserved.
Copyright (c) 2015 Chukong Technologies Inc.
http://www.cocos2d-x.org
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 "CCPUBehaviourTranslator.h"
#include "extensions/Particle3D/PU/CCPUParticleSystem3D.h"
#include "extensions/Particle3D/PU/CCPUBehaviourManager.h"
NS_CC_BEGIN
PUBehaviourTranslator::PUBehaviourTranslator()
:_behaviour(nullptr)
{
}
//-------------------------------------------------------------------------
void PUBehaviourTranslator::translate(PUScriptCompiler* compiler, PUAbstractNode *node)
{
PUObjectAbstractNode* obj = reinterpret_cast<PUObjectAbstractNode*>(node);
PUObjectAbstractNode* parent = obj->parent ? reinterpret_cast<PUObjectAbstractNode*>(obj->parent) : 0;
// The name of the obj is the type of the Behaviour
std::string type;
if(!obj->name.empty())
{
type = obj->name;
}
else
{
//compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, obj->file, obj->line);
return;
}
//// Get the factory
//ParticleBehaviourFactory* behaviourFactory = ParticleSystemManager::getSingletonPtr()->getBehaviourFactory(type);
//if (!behaviourFactory)
//{
// //compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, obj->file, obj->line);
// return;
//}
PUScriptTranslator *particleBehaviourTranlator = PUBehaviourManager::Instance()->getTranslator(type);
if (!particleBehaviourTranlator) return;
// Create the Behaviour
_behaviour = PUBehaviourManager::Instance()->createBehaviour(type);
if (!_behaviour)
{
//compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, obj->file, obj->line);
return;
}
_behaviour->setBehaviourType(type);
if (parent && parent->context)
{
PUParticleSystem3D* system = static_cast<PUParticleSystem3D*>(parent->context);
system->addBehaviourTemplate(_behaviour);
}
else
{
//// It is an alias
//_behaviour->setAliasName(parent->name);
//ParticleSystemManager::getSingletonPtr()->addAlias(mBehaviour);
}
// Set it in the context
obj->context = _behaviour;
// Run through properties
for(PUAbstractNodeList::iterator i = obj->children.begin(); i != obj->children.end(); ++i)
{
// No properties of its own
if((*i)->type == ANT_PROPERTY)
{
PUPropertyAbstractNode* prop = reinterpret_cast<PUPropertyAbstractNode*>((*i));
if (particleBehaviourTranlator->translateChildProperty(compiler, *i))
{
// Parsed the property by another translator; do nothing
}
else
{
errorUnexpectedProperty(compiler, prop);
}
}
else if((*i)->type == ANT_OBJECT)
{
if (particleBehaviourTranlator->translateChildObject(compiler, *i))
{
// Parsed the object by another translator; do nothing
}
else
{
processNode(compiler, *i);
}
}
else
{
errorUnexpectedToken(compiler, *i);
}
}
}
NS_CC_END
|
//=======================================================================
// Copyright Baptiste Wicht 2013-2018.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://www.opensource.org/licenses/MIT)
//=======================================================================
#ifndef ITERATOR_HPP
#define ITERATOR_HPP
#include <type_traits.hpp>
#include <utility.hpp>
#include <types.hpp>
#include <enable_if.hpp>
namespace std {
template <typename Iterator>
size_t distance(Iterator it, Iterator end) {
// For now, we only have random access iterator
return end - it;
}
/*!
* \brief Reverse iterator adapter
*/
template <typename Iterator>
struct reverse_iterator {
using iterator_type = Iterator; ///< The iterator type
using value_type = typename std::iterator_traits<Iterator>::value_type; ///< The value type
using difference_type = typename std::iterator_traits<Iterator>::difference_type; ///< The difference type
using pointer = typename std::iterator_traits<Iterator>::pointer; ///< The pointer type
using reference = typename std::iterator_traits<Iterator>::reference; ///< The reference type
reverse_iterator(Iterator it)
: it(it) {
//Nothing else
}
/*!
* \brief Returns a reference to the pointed element
*/
reference operator*() {
return *it;
}
reverse_iterator& operator++() {
--it;
return *this;
}
reverse_iterator& operator--() {
++it;
return *this;
}
bool operator==(const reverse_iterator& rhs) {
return it == rhs.it;
}
bool operator!=(const reverse_iterator& rhs) {
return it != rhs.it;
}
private:
iterator_type it;
};
template <typename Container>
struct back_insert_iterator {
using container_type = Container; ///< The container type
using value_type = void; ///< The value type
using difference_type = void; ///< The difference type
using reference = void; ///< The reference type
using const_reference = void; ///< The const reference type
container_type& container;
explicit back_insert_iterator(container_type& container)
: container(container) {}
back_insert_iterator& operator=(const typename container_type::value_type& value) {
container.push_back(value);
return *this;
}
back_insert_iterator& operator=(typename container_type::value_type&& value) {
container.push_back(std::move(value));
return *this;
}
back_insert_iterator& operator*() {
return *this;
}
back_insert_iterator& operator++() {
return *this;
}
back_insert_iterator& operator++(int) {
return *this;
}
};
template <typename Container>
struct front_insert_iterator {
using container_type = Container; ///< The container type
using value_type = void; ///< The value type
using difference_type = void; ///< The difference type
using reference = void; ///< The reference type
using const_reference = void; ///< The const reference type
container_type& container;
explicit front_insert_iterator(container_type& container)
: container(container) {}
front_insert_iterator& operator=(const typename container_type::value_type& value) {
container.push_front(value);
return *this;
}
front_insert_iterator& operator=(typename container_type::value_type&& value) {
container.push_front(std::move(value));
return *this;
}
front_insert_iterator& operator*() {
return *this;
}
front_insert_iterator& operator++() {
return *this;
}
front_insert_iterator& operator++(int) {
return *this;
}
};
template <typename Container>
std::back_insert_iterator<Container> back_inserter(Container& c) {
return std::back_insert_iterator<Container>(c);
}
template <typename Container>
std::front_insert_iterator<Container> front_inserter(Container& c) {
return std::front_insert_iterator<Container>(c);
}
} //end of namespace std
#endif
|
// 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 "quic/core/quic_connection_id_manager.h"
#include <cstdio>
#include "quic/core/quic_clock.h"
#include "quic/core/quic_connection_id.h"
#include "quic/core/quic_error_codes.h"
#include "quic/core/quic_utils.h"
namespace quic {
QuicConnectionIdData::QuicConnectionIdData(
const QuicConnectionId& connection_id,
uint64_t sequence_number,
const StatelessResetToken& stateless_reset_token)
: connection_id(connection_id),
sequence_number(sequence_number),
stateless_reset_token(stateless_reset_token) {}
namespace {
class RetirePeerIssuedConnectionIdAlarm : public QuicAlarm::Delegate {
public:
explicit RetirePeerIssuedConnectionIdAlarm(
QuicConnectionIdManagerVisitorInterface* visitor)
: visitor_(visitor) {}
RetirePeerIssuedConnectionIdAlarm(const RetirePeerIssuedConnectionIdAlarm&) =
delete;
RetirePeerIssuedConnectionIdAlarm& operator=(
const RetirePeerIssuedConnectionIdAlarm&) = delete;
void OnAlarm() override { visitor_->OnPeerIssuedConnectionIdRetired(); }
private:
QuicConnectionIdManagerVisitorInterface* visitor_;
};
std::vector<QuicConnectionIdData>::const_iterator FindConnectionIdData(
const std::vector<QuicConnectionIdData>& cid_data_vector,
const QuicConnectionId& cid) {
return std::find_if(cid_data_vector.begin(), cid_data_vector.end(),
[&cid](const QuicConnectionIdData& cid_data) {
return cid == cid_data.connection_id;
});
}
std::vector<QuicConnectionIdData>::iterator FindConnectionIdData(
std::vector<QuicConnectionIdData>* cid_data_vector,
const QuicConnectionId& cid) {
return std::find_if(cid_data_vector->begin(), cid_data_vector->end(),
[&cid](const QuicConnectionIdData& cid_data) {
return cid == cid_data.connection_id;
});
}
} // namespace
QuicPeerIssuedConnectionIdManager::QuicPeerIssuedConnectionIdManager(
size_t active_connection_id_limit,
const QuicConnectionId& initial_peer_issued_connection_id,
const QuicClock* clock,
QuicAlarmFactory* alarm_factory,
QuicConnectionIdManagerVisitorInterface* visitor)
: active_connection_id_limit_(active_connection_id_limit),
clock_(clock),
retire_connection_id_alarm_(alarm_factory->CreateAlarm(
new RetirePeerIssuedConnectionIdAlarm(visitor))) {
QUICHE_DCHECK_GE(active_connection_id_limit_, 2u);
QUICHE_DCHECK(!initial_peer_issued_connection_id.IsEmpty());
active_connection_id_data_.emplace_back<const QuicConnectionId&, uint64_t,
const StatelessResetToken&>(
initial_peer_issued_connection_id,
/*sequence_number=*/0u, {});
recent_new_connection_id_sequence_numbers_.Add(0u, 1u);
}
QuicPeerIssuedConnectionIdManager::~QuicPeerIssuedConnectionIdManager() {
retire_connection_id_alarm_->Cancel();
}
bool QuicPeerIssuedConnectionIdManager::IsConnectionIdNew(
const QuicNewConnectionIdFrame& frame) {
auto is_old_connection_id = [&frame](const QuicConnectionIdData& cid_data) {
return cid_data.connection_id == frame.connection_id;
};
if (std::any_of(active_connection_id_data_.begin(),
active_connection_id_data_.end(), is_old_connection_id)) {
return false;
}
if (std::any_of(unused_connection_id_data_.begin(),
unused_connection_id_data_.end(), is_old_connection_id)) {
return false;
}
if (std::any_of(to_be_retired_connection_id_data_.begin(),
to_be_retired_connection_id_data_.end(),
is_old_connection_id)) {
return false;
}
return true;
}
void QuicPeerIssuedConnectionIdManager::PrepareToRetireConnectionIdPriorTo(
uint64_t retire_prior_to,
std::vector<QuicConnectionIdData>* cid_data_vector) {
auto it2 = cid_data_vector->begin();
for (auto it = cid_data_vector->begin(); it != cid_data_vector->end(); ++it) {
if (it->sequence_number >= retire_prior_to) {
*it2++ = *it;
} else {
to_be_retired_connection_id_data_.push_back(*it);
if (!retire_connection_id_alarm_->IsSet()) {
retire_connection_id_alarm_->Set(clock_->ApproximateNow());
}
}
}
cid_data_vector->erase(it2, cid_data_vector->end());
}
QuicErrorCode QuicPeerIssuedConnectionIdManager::OnNewConnectionIdFrame(
const QuicNewConnectionIdFrame& frame,
std::string* error_detail) {
if (recent_new_connection_id_sequence_numbers_.Contains(
frame.sequence_number)) {
// This frame has a recently seen sequence number. Ignore.
return QUIC_NO_ERROR;
}
if (!IsConnectionIdNew(frame)) {
*error_detail =
"Received a NEW_CONNECTION_ID frame that reuses a previously seen Id.";
return IETF_QUIC_PROTOCOL_VIOLATION;
}
recent_new_connection_id_sequence_numbers_.AddOptimizedForAppend(
frame.sequence_number, frame.sequence_number + 1);
if (recent_new_connection_id_sequence_numbers_.Size() >
kMaxNumConnectionIdSequenceNumberIntervals) {
*error_detail =
"Too many disjoint connection Id sequence number intervals.";
return IETF_QUIC_PROTOCOL_VIOLATION;
}
// QuicFramer::ProcessNewConnectionIdFrame guarantees that
// frame.sequence_number >= frame.retire_prior_to, and hence there is no need
// to check that.
if (frame.sequence_number < max_new_connection_id_frame_retire_prior_to_) {
// Later frames have asked for retirement of the current frame.
to_be_retired_connection_id_data_.emplace_back(frame.connection_id,
frame.sequence_number,
frame.stateless_reset_token);
if (!retire_connection_id_alarm_->IsSet()) {
retire_connection_id_alarm_->Set(clock_->ApproximateNow());
}
return QUIC_NO_ERROR;
}
if (frame.retire_prior_to > max_new_connection_id_frame_retire_prior_to_) {
max_new_connection_id_frame_retire_prior_to_ = frame.retire_prior_to;
PrepareToRetireConnectionIdPriorTo(frame.retire_prior_to,
&active_connection_id_data_);
PrepareToRetireConnectionIdPriorTo(frame.retire_prior_to,
&unused_connection_id_data_);
}
if (active_connection_id_data_.size() + unused_connection_id_data_.size() >=
active_connection_id_limit_) {
*error_detail = "Peer provides more connection IDs than the limit.";
return QUIC_CONNECTION_ID_LIMIT_ERROR;
}
unused_connection_id_data_.emplace_back(
frame.connection_id, frame.sequence_number, frame.stateless_reset_token);
return QUIC_NO_ERROR;
}
const QuicConnectionIdData*
QuicPeerIssuedConnectionIdManager::ConsumeOneUnusedConnectionId() {
if (unused_connection_id_data_.empty()) {
return nullptr;
}
active_connection_id_data_.push_back(unused_connection_id_data_.back());
unused_connection_id_data_.pop_back();
return &active_connection_id_data_.back();
}
void QuicPeerIssuedConnectionIdManager::PrepareToRetireActiveConnectionId(
const QuicConnectionId& cid) {
auto it = FindConnectionIdData(active_connection_id_data_, cid);
if (it == active_connection_id_data_.end()) {
// The cid has already been retired.
return;
}
to_be_retired_connection_id_data_.push_back(*it);
active_connection_id_data_.erase(it);
if (!retire_connection_id_alarm_->IsSet()) {
retire_connection_id_alarm_->Set(clock_->ApproximateNow());
}
}
void QuicPeerIssuedConnectionIdManager::MaybeRetireUnusedConnectionIds(
const std::vector<QuicConnectionId>& active_connection_ids_on_path) {
std::vector<QuicConnectionId> cids_to_retire;
for (const auto& cid_data : active_connection_id_data_) {
if (std::find(active_connection_ids_on_path.begin(),
active_connection_ids_on_path.end(),
cid_data.connection_id) ==
active_connection_ids_on_path.end()) {
cids_to_retire.push_back(cid_data.connection_id);
}
}
for (const auto& cid : cids_to_retire) {
PrepareToRetireActiveConnectionId(cid);
}
}
bool QuicPeerIssuedConnectionIdManager::IsConnectionIdActive(
const QuicConnectionId& cid) const {
return FindConnectionIdData(active_connection_id_data_, cid) !=
active_connection_id_data_.end();
}
std::vector<uint64_t> QuicPeerIssuedConnectionIdManager::
ConsumeToBeRetiredConnectionIdSequenceNumbers() {
std::vector<uint64_t> result;
for (auto const& cid_data : to_be_retired_connection_id_data_) {
result.push_back(cid_data.sequence_number);
}
to_be_retired_connection_id_data_.clear();
return result;
}
void QuicPeerIssuedConnectionIdManager::ReplaceConnectionId(
const QuicConnectionId& old_connection_id,
const QuicConnectionId& new_connection_id) {
auto it1 =
FindConnectionIdData(&active_connection_id_data_, old_connection_id);
if (it1 != active_connection_id_data_.end()) {
it1->connection_id = new_connection_id;
return;
}
auto it2 = FindConnectionIdData(&to_be_retired_connection_id_data_,
old_connection_id);
if (it2 != to_be_retired_connection_id_data_.end()) {
it2->connection_id = new_connection_id;
}
}
namespace {
class RetireSelfIssuedConnectionIdAlarmDelegate : public QuicAlarm::Delegate {
public:
explicit RetireSelfIssuedConnectionIdAlarmDelegate(
QuicSelfIssuedConnectionIdManager* connection_id_manager)
: connection_id_manager_(connection_id_manager) {}
RetireSelfIssuedConnectionIdAlarmDelegate(
const RetireSelfIssuedConnectionIdAlarmDelegate&) = delete;
RetireSelfIssuedConnectionIdAlarmDelegate& operator=(
const RetireSelfIssuedConnectionIdAlarmDelegate&) = delete;
void OnAlarm() override { connection_id_manager_->RetireConnectionId(); }
private:
QuicSelfIssuedConnectionIdManager* connection_id_manager_;
};
} // namespace
QuicSelfIssuedConnectionIdManager::QuicSelfIssuedConnectionIdManager(
size_t active_connection_id_limit,
const QuicConnectionId& initial_connection_id,
const QuicClock* clock,
QuicAlarmFactory* alarm_factory,
QuicConnectionIdManagerVisitorInterface* visitor)
: active_connection_id_limit_(active_connection_id_limit),
clock_(clock),
visitor_(visitor),
retire_connection_id_alarm_(alarm_factory->CreateAlarm(
new RetireSelfIssuedConnectionIdAlarmDelegate(this))),
last_connection_id_(initial_connection_id),
next_connection_id_sequence_number_(1u),
last_connection_id_consumed_by_self_sequence_number_(0u) {
active_connection_ids_.emplace_back(initial_connection_id, 0u);
}
QuicSelfIssuedConnectionIdManager::~QuicSelfIssuedConnectionIdManager() {
retire_connection_id_alarm_->Cancel();
}
QuicConnectionId QuicSelfIssuedConnectionIdManager::GenerateNewConnectionId(
const QuicConnectionId& old_connection_id) const {
return QuicUtils::CreateReplacementConnectionId(old_connection_id);
}
QuicNewConnectionIdFrame
QuicSelfIssuedConnectionIdManager::IssueNewConnectionId() {
QuicNewConnectionIdFrame frame;
frame.connection_id = GenerateNewConnectionId(last_connection_id_);
frame.sequence_number = next_connection_id_sequence_number_++;
frame.stateless_reset_token =
QuicUtils::GenerateStatelessResetToken(frame.connection_id);
visitor_->OnNewConnectionIdIssued(frame.connection_id);
active_connection_ids_.emplace_back(frame.connection_id,
frame.sequence_number);
frame.retire_prior_to = active_connection_ids_.front().second;
last_connection_id_ = frame.connection_id;
return frame;
}
QuicNewConnectionIdFrame
QuicSelfIssuedConnectionIdManager::IssueNewConnectionIdForPreferredAddress() {
QuicNewConnectionIdFrame frame = IssueNewConnectionId();
QUICHE_DCHECK_EQ(frame.sequence_number, 1u);
return frame;
}
QuicErrorCode QuicSelfIssuedConnectionIdManager::OnRetireConnectionIdFrame(
const QuicRetireConnectionIdFrame& frame,
QuicTime::Delta pto_delay,
std::string* error_detail) {
QUICHE_DCHECK(!active_connection_ids_.empty());
if (frame.sequence_number > active_connection_ids_.back().second) {
*error_detail = "To be retired connecton ID is never issued.";
return IETF_QUIC_PROTOCOL_VIOLATION;
}
auto it =
std::find_if(active_connection_ids_.begin(), active_connection_ids_.end(),
[&frame](const std::pair<QuicConnectionId, uint64_t>& p) {
return p.second == frame.sequence_number;
});
// The corresponding connection ID has been retired. Ignore.
if (it == active_connection_ids_.end()) {
return QUIC_NO_ERROR;
}
if (to_be_retired_connection_ids_.size() + active_connection_ids_.size() >=
kMaxNumConnectonIdsInUse) {
// Close connection if the number of connection IDs in use will exeed the
// limit, i.e., peer retires connection ID too fast.
*error_detail = "There are too many connection IDs in use.";
return QUIC_TOO_MANY_CONNECTION_ID_WAITING_TO_RETIRE;
}
QuicTime retirement_time = clock_->ApproximateNow() + 3 * pto_delay;
if (!to_be_retired_connection_ids_.empty()) {
retirement_time =
std::max(retirement_time, to_be_retired_connection_ids_.back().second);
}
to_be_retired_connection_ids_.emplace_back(it->first, retirement_time);
if (!retire_connection_id_alarm_->IsSet()) {
retire_connection_id_alarm_->Set(retirement_time);
}
active_connection_ids_.erase(it);
MaybeSendNewConnectionIds();
return QUIC_NO_ERROR;
}
std::vector<QuicConnectionId>
QuicSelfIssuedConnectionIdManager::GetUnretiredConnectionIds() const {
std::vector<QuicConnectionId> unretired_ids;
for (const auto& cid_pair : to_be_retired_connection_ids_) {
unretired_ids.push_back(cid_pair.first);
}
for (const auto& cid_pair : active_connection_ids_) {
unretired_ids.push_back(cid_pair.first);
}
return unretired_ids;
}
void QuicSelfIssuedConnectionIdManager::RetireConnectionId() {
if (to_be_retired_connection_ids_.empty()) {
QUIC_BUG(quic_bug_12420_1)
<< "retire_connection_id_alarm fired but there is no connection ID "
"to be retired.";
return;
}
QuicTime now = clock_->ApproximateNow();
auto it = to_be_retired_connection_ids_.begin();
do {
visitor_->OnSelfIssuedConnectionIdRetired(it->first);
++it;
} while (it != to_be_retired_connection_ids_.end() && it->second <= now);
to_be_retired_connection_ids_.erase(to_be_retired_connection_ids_.begin(),
it);
// Set the alarm again if there is another connection ID to be removed.
if (!to_be_retired_connection_ids_.empty()) {
retire_connection_id_alarm_->Set(
to_be_retired_connection_ids_.front().second);
}
}
void QuicSelfIssuedConnectionIdManager::MaybeSendNewConnectionIds() {
while (active_connection_ids_.size() < active_connection_id_limit_) {
QuicNewConnectionIdFrame frame = IssueNewConnectionId();
if (!visitor_->SendNewConnectionId(frame)) {
break;
}
}
}
bool QuicSelfIssuedConnectionIdManager::HasConnectionIdToConsume() const {
for (const auto& active_cid_data : active_connection_ids_) {
if (active_cid_data.second >
last_connection_id_consumed_by_self_sequence_number_) {
return true;
}
}
return false;
}
absl::optional<QuicConnectionId>
QuicSelfIssuedConnectionIdManager::ConsumeOneConnectionId() {
for (const auto& active_cid_data : active_connection_ids_) {
if (active_cid_data.second >
last_connection_id_consumed_by_self_sequence_number_) {
// Since connection IDs in active_connection_ids_ has monotonically
// increasing sequence numbers, the returned connection ID has the
// smallest sequence number among all unconsumed active connection IDs.
last_connection_id_consumed_by_self_sequence_number_ =
active_cid_data.second;
return active_cid_data.first;
}
}
return absl::nullopt;
}
bool QuicSelfIssuedConnectionIdManager::IsConnectionIdInUse(
const QuicConnectionId& cid) const {
for (const auto& active_cid_data : active_connection_ids_) {
if (active_cid_data.first == cid) {
return true;
}
}
for (const auto& to_be_retired_cid_data : to_be_retired_connection_ids_) {
if (to_be_retired_cid_data.first == cid) {
return true;
}
}
return false;
}
} // namespace quic
|
#include "Player.h"
#include "Game.h"
#include"Sencer.h"
#include"ParticleEmitter.h"
#include"Cameraman.h"
#include"ObjectDelayCreater.h"
Framework::Player::Player(std::shared_ptr<Transform> shp_arg_transform, std::shared_ptr<GameObjectManager> shp_arg_gameObjectManager) :GameObject(shp_arg_transform, shp_arg_gameObjectManager)
{
velocity = Vector2(0.0f, 0.0f);
phisicsForce = Vector2(0,0);
tag = ObjectTag::player;
for (int i = 0; i < HISTORY_COUNT; i++)
{
MoveHistory moveH;
moveH.position = transform->GetPosition();
deq_moveHistory.push_front( moveH);
deq_shotHistory.push_front(false);
}
//shp_gameObjectManager = shp_arg_gameObjectManager->GetThis<Transform>();
//shp_gameObjectManager = ObjectFactory::Create<GameObjectManager>();
}
Framework::Player::~Player() {
}
void Framework::Player::Hit(std::shared_ptr<GameObject> other)
{
}
void Framework::Player::PreInitialize()
{
shp_texture = ObjectFactory::Create<Resource_Texture>("robo.png", transform, false, false);
shp_sound_damage = ObjectFactory::Create<Resource_Sound>("Damage.wav", DX_PLAYTYPE_BACK, true);
shp_sound_jump = ObjectFactory::Create<Resource_Sound>("Jump.wav", DX_PLAYTYPE_BACK, true);
shp_sound_shoot = ObjectFactory::Create<Resource_Sound>("Shoot.wav", DX_PLAYTYPE_BACK, true);
shp_sound_throw = ObjectFactory::Create<Resource_Sound>("Throw.wav", DX_PLAYTYPE_BACK, true);
shp_sound_landing = ObjectFactory::Create<Resource_Sound>("Landing.wav", DX_PLAYTYPE_BACK, true);
shp_collisionRect = ObjectFactory::Create<Collision2D_Rectangle>(std::make_shared<Rectangle>(32, 32, transform->GetPosition().GetVector2(), Rectangle::GetRectangleOuterCircleRadius(32, 32)), GetThis<GameObject>());
shp_cursol = ObjectFactory::Create<Cursol>(ObjectFactory::Create<Transform>(transform->GetPosition()),transform,manager);
manager->AddObject_Init(shp_cursol);
AddChildObject(shp_cursol);
}
void Framework::Player::SetSpawnPoint(Vector3 arg_pos)
{
for (auto itr = vec_childs.begin(); itr != vec_childs.end(); itr++) {
(*itr)->transform->localPosition = arg_pos;
}
deq_moveHistory.clear();
deq_shotHistory.clear();
for (int i = 0; i < HISTORY_COUNT; i++)
{
MoveHistory moveH;
moveH.position = transform->GetPosition();
deq_moveHistory.push_front(moveH);
deq_shotHistory.push_front(false);
}
}
void Framework::Player::Initialize()
{
for (int i = 0; i <
Game::GetInstance()->GetSceneManager()->GetGameMaster()->GetPlayerChildsCount(); i++) {
AddPlayerChild();
}
AddPlayerChild();
AddPlayerChild();
AddPlayerChild();
auto camera = manager->SerchGameObject(ObjectTag::camera);
if (camera) {
camera->GetThis<Cameraman_Chase>()->SetTarget((*vec_childs.begin())->transform);
}
(*vec_childs.begin())->SetTop();
}
bool Framework::Player::OnUpdate() {
if (vec_childs.size() == 0) {
SetIsDead(true);
}
Throw();
return true;
}
bool Framework::Player::Release()
{
vec_childs.clear();
//shp_collisionRect->Releace();
//shp_collisionRect = nullptr;
shp_cursol = nullptr;
shp_texture = nullptr;
shp_sound_damage = nullptr;
shp_sound_jump = nullptr;
shp_sound_shoot = nullptr;
shp_sound_throw = nullptr;
shp_sound_landing = nullptr;
Game::GetInstance()->GetGameTime()->SlowMotion(0.5f,30);
manager->AddObject(ObjectFactory::Create<ObjectDelayCreater<Player>>(60,ObjectFactory::Create<Transform>(
Game::GetInstance()->GetSceneManager()->GetGameMaster()->GetRespawnPoint()
), manager
));
Game::GetInstance()->GetSceneManager()->GetGameMaster()->SetPlayerChildsCount(vec_childs.size());
return true;
}
void Framework::Player::DeletePlayer(int num)
{
auto itr = vec_childs.begin() + num;
RemoveChildObject(*itr);
vec_childs.erase(itr);
for (int i = 0; i < vec_childs.size(); i ++) {
vec_childs.at(i)->SetNum(i);
}
}
void Framework::Player::AddPlayerChild()
{
//manager->SerchGameObject(ObjectTag::map)->GetThis<Map>()->ChangeGlid(2, 19,26);
if (vec_childs.size() >Game::GetInstance()->GetSceneManager()->GetGameMaster()->GetChildsMax()) {
return;
}
auto childTransform = ObjectFactory::Create<Transform>(transform->GetPosition() );
auto child = ObjectFactory::Create<Child>( GetThis<Player>(), childTransform, manager);
child->SetNum(vec_childs.size());
AddChildObject(child->GetThis<GameObject>());
vec_childs.push_back(child->GetThis<Child>());
manager->AddObject(child);
}
void Framework::Player::UpdateMovingHistory(MoveHistory & arg_playerMoving)
{
deq_moveHistory.push_front(arg_playerMoving);
deq_moveHistory.pop_back();
}
void Framework::Player::UpdateShotHistory(bool arg_shotFlg)
{
deq_shotHistory.push_front(arg_shotFlg);
deq_shotHistory.pop_back();
}
void Framework::Player::BlockRelease()
{
if (shp_throwChild == nullptr) {
return;
}
RemoveChildObject(shp_throwChild);
shp_throwChild->Throw(shp_cursol->GetWorldTransform());
vec_childs.erase(vec_childs.begin() + 1);
for (int i = 0; i < vec_childs.size(); i++) {
vec_childs.at(i)->SetNum(i);
}
shp_throwChild = nullptr;
}
void Framework::Player::OnChangeScene()
{
for (auto itr = vec_childs.begin(); itr != vec_childs.end(); itr++) {
(*itr)->ReSetMapYMax();
}
}
Framework::MoveHistory Framework::Player::GetMovingFromHystory(int num)
{
return deq_moveHistory.at(num);
}
bool Framework::Player::GetShotHystory(int num)
{
return deq_shotHistory.at(num);
}
bool Framework::Player::Move() {
return true;
}
bool Framework::Player::Throw() {
if (vec_childs.size() == 0) {
return true;
}
befRTrigger = currentRTrigger;
currentRTrigger = Input::GetRightTrigger() > 0.5f;
if ((!befRTrigger&¤tRTrigger) && vec_childs.size() >= 2) {
shp_throwChild = *(vec_childs.begin() + 1);
shp_throwChild->SetStandby();
}
else
if ((befRTrigger&&!currentRTrigger) && vec_childs.size() >= 2) {
if (shp_throwChild == nullptr) {
return true;
}
RemoveChildObject(shp_throwChild);
shp_throwChild->Throw(shp_cursol->GetWorldTransform());
vec_childs.erase(vec_childs.begin() + 1);
for (int i = 0; i < vec_childs.size(); i++) {
vec_childs.at(i)->SetNum(i);
}
shp_throwChild = nullptr;
}
return true;
}
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Runtime.ConstrainedExecution.CriticalFinalizerObject
#include "System/Runtime/ConstrainedExecution/CriticalFinalizerObject.hpp"
// Including type: System.IDisposable
#include "System/IDisposable.hpp"
// Including type: System.IntPtr
#include "System/IntPtr.hpp"
// Including type: System.Int32
#include "System/Int32.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Type namespace: System.Runtime.InteropServices
namespace System::Runtime::InteropServices {
// Size: 0x1E
#pragma pack(push, 1)
// WARNING Layout: Sequential may not be correctly taken into account!
// Autogenerated type: System.Runtime.InteropServices.SafeHandle
class SafeHandle : public System::Runtime::ConstrainedExecution::CriticalFinalizerObject/*, public System::IDisposable*/ {
public:
// protected System.IntPtr handle
// Size: 0x8
// Offset: 0x10
System::IntPtr handle;
// Field size check
static_assert(sizeof(System::IntPtr) == 0x8);
// private System.Int32 _state
// Size: 0x4
// Offset: 0x18
int state;
// Field size check
static_assert(sizeof(int) == 0x4);
// private System.Boolean _ownsHandle
// Size: 0x1
// Offset: 0x1C
bool ownsHandle;
// Field size check
static_assert(sizeof(bool) == 0x1);
// private System.Boolean _fullyInitialized
// Size: 0x1
// Offset: 0x1D
bool fullyInitialized;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Creating value type constructor for type: SafeHandle
SafeHandle(System::IntPtr handle_ = {}, int state_ = {}, bool ownsHandle_ = {}, bool fullyInitialized_ = {}) noexcept : handle{handle_}, state{state_}, ownsHandle{ownsHandle_}, fullyInitialized{fullyInitialized_} {}
// Creating interface conversion operator: operator System::IDisposable
operator System::IDisposable() noexcept {
return *reinterpret_cast<System::IDisposable*>(this);
}
// static field const value: static private System.Int32 RefCount_Mask
static constexpr const int RefCount_Mask = 2147483644;
// Get static field: static private System.Int32 RefCount_Mask
static int _get_RefCount_Mask();
// Set static field: static private System.Int32 RefCount_Mask
static void _set_RefCount_Mask(int value);
// static field const value: static private System.Int32 RefCount_One
static constexpr const int RefCount_One = 4;
// Get static field: static private System.Int32 RefCount_One
static int _get_RefCount_One();
// Set static field: static private System.Int32 RefCount_One
static void _set_RefCount_One(int value);
// protected System.Void .ctor(System.IntPtr invalidHandleValue, System.Boolean ownsHandle)
// Offset: 0x1404850
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static SafeHandle* New_ctor(System::IntPtr invalidHandleValue, bool ownsHandle) {
static auto ___internal__logger = ::Logger::get().WithContext("System::Runtime::InteropServices::SafeHandle::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<SafeHandle*, creationType>(invalidHandleValue, ownsHandle)));
}
// protected System.Void SetHandle(System.IntPtr handle)
// Offset: 0x140496C
void SetHandle(System::IntPtr handle);
// public System.IntPtr DangerousGetHandle()
// Offset: 0x1404974
System::IntPtr DangerousGetHandle();
// public System.Boolean get_IsClosed()
// Offset: 0x140497C
bool get_IsClosed();
// public System.Boolean get_IsInvalid()
// Offset: 0xFFFFFFFF
bool get_IsInvalid();
// public System.Void Close()
// Offset: 0x1404988
void Close();
// public System.Void Dispose()
// Offset: 0x1404998
void Dispose();
// protected System.Void Dispose(System.Boolean disposing)
// Offset: 0x14049A8
void Dispose(bool disposing);
// protected System.Boolean ReleaseHandle()
// Offset: 0xFFFFFFFF
bool ReleaseHandle();
// public System.Void SetHandleAsInvalid()
// Offset: 0x1404A84
void SetHandleAsInvalid();
// public System.Void DangerousAddRef(ref System.Boolean success)
// Offset: 0x14046E4
void DangerousAddRef(bool& success);
// public System.Void DangerousRelease()
// Offset: 0x1404848
void DangerousRelease();
// private System.Void InternalDispose()
// Offset: 0x14049C4
void InternalDispose();
// private System.Void InternalFinalize()
// Offset: 0x1404A70
void InternalFinalize();
// private System.Void DangerousReleaseInternal(System.Boolean dispose)
// Offset: 0x1404B18
void DangerousReleaseInternal(bool dispose);
// protected override System.Void Finalize()
// Offset: 0x14048F8
// Implemented from: System.Runtime.ConstrainedExecution.CriticalFinalizerObject
// Base method: System.Void CriticalFinalizerObject::Finalize()
void Finalize();
}; // System.Runtime.InteropServices.SafeHandle
#pragma pack(pop)
static check_size<sizeof(SafeHandle), 29 + sizeof(bool)> __System_Runtime_InteropServices_SafeHandleSizeCheck;
static_assert(sizeof(SafeHandle) == 0x1E);
}
DEFINE_IL2CPP_ARG_TYPE(System::Runtime::InteropServices::SafeHandle*, "System.Runtime.InteropServices", "SafeHandle");
|
// Copyright (c) 2006-2018 Maxim Khizhinsky
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
#include "test_set_nogc.h"
#include <cds/container/lazy_list_nogc.h>
#include <cds/container/michael_set_nogc.h>
namespace {
namespace cc = cds::container;
typedef cds::gc::nogc gc_type;
class MichaelLazySet_NoGC : public cds_test::container_set_nogc
{
protected:
typedef cds_test::container_set_nogc base_class;
//void SetUp()
//{}
//void TearDown()
//{}
};
TEST_F( MichaelLazySet_NoGC, compare )
{
typedef cc::LazyList< gc_type, int_item,
typename cc::lazy_list::make_traits<
cds::opt::compare< cmp >
>::type
> list_type;
typedef cc::MichaelHashSet< gc_type, list_type,
typename cc::michael_set::make_traits<
cds::opt::hash< hash_int >
>::type
> set_type;
set_type s( kSize, 2 );
test( s );
}
TEST_F( MichaelLazySet_NoGC, less )
{
typedef cc::LazyList< gc_type, int_item,
typename cc::lazy_list::make_traits<
cds::opt::less< base_class::less >
>::type
> list_type;
typedef cc::MichaelHashSet< gc_type, list_type,
typename cc::michael_set::make_traits<
cds::opt::hash< hash_int >
>::type
> set_type;
set_type s( kSize, 2 );
test( s );
}
TEST_F( MichaelLazySet_NoGC, cmpmix )
{
struct list_traits : public cc::lazy_list::traits
{
typedef base_class::less less;
typedef cmp compare;
};
typedef cc::LazyList< gc_type, int_item, list_traits > list_type;
typedef cc::MichaelHashSet< gc_type, list_type,
typename cc::michael_set::make_traits<
cds::opt::hash< hash_int >
>::type
> set_type;
set_type s( kSize, 2 );
test( s );
}
TEST_F( MichaelLazySet_NoGC, item_counting )
{
struct list_traits : public cc::lazy_list::traits
{
typedef cmp compare;
};
typedef cc::LazyList< gc_type, int_item, list_traits > list_type;
struct set_traits: public cc::michael_set::traits
{
typedef hash_int hash;
typedef simple_item_counter item_counter;
};
typedef cc::MichaelHashSet< gc_type, list_type, set_traits >set_type;
set_type s( kSize, 3 );
test( s );
}
TEST_F( MichaelLazySet_NoGC, backoff )
{
struct list_traits : public cc::lazy_list::traits
{
typedef cmp compare;
typedef cds::backoff::make_exponential_t<cds::backoff::pause, cds::backoff::yield> back_off;
};
typedef cc::LazyList< gc_type, int_item, list_traits > list_type;
struct set_traits : public cc::michael_set::traits
{
typedef hash_int hash;
typedef cds::atomicity::item_counter item_counter;
};
typedef cc::MichaelHashSet< gc_type, list_type, set_traits >set_type;
set_type s( kSize, 4 );
test( s );
}
TEST_F( MichaelLazySet_NoGC, seq_cst )
{
struct list_traits : public cc::lazy_list::traits
{
typedef base_class::less less;
typedef cds::backoff::pause back_off;
typedef cds::opt::v::sequential_consistent memory_model;
};
typedef cc::LazyList< gc_type, int_item, list_traits > list_type;
struct set_traits : public cc::michael_set::traits
{
typedef hash_int hash;
typedef cds::atomicity::item_counter item_counter;
};
typedef cc::MichaelHashSet< gc_type, list_type, set_traits >set_type;
set_type s( kSize, 4 );
test( s );
}
TEST_F( MichaelLazySet_NoGC, mutex )
{
struct list_traits : public cc::lazy_list::traits
{
typedef base_class::less less;
typedef cds::backoff::pause back_off;
typedef std::mutex lock_type;
};
typedef cc::LazyList< gc_type, int_item, list_traits > list_type;
struct set_traits : public cc::michael_set::traits
{
typedef hash_int hash;
typedef cds::atomicity::item_counter item_counter;
};
typedef cc::MichaelHashSet< gc_type, list_type, set_traits >set_type;
set_type s( kSize, 4 );
test( s );
}
TEST_F( MichaelLazySet_NoGC, stat )
{
struct list_traits: public cc::lazy_list::traits
{
typedef base_class::less less;
typedef cds::backoff::pause back_off;
typedef cc::lazy_list::stat<> stat;
};
typedef cc::LazyList< gc_type, int_item, list_traits > list_type;
struct set_traits: public cc::michael_set::traits
{
typedef hash_int hash;
typedef cds::atomicity::item_counter item_counter;
};
typedef cc::MichaelHashSet< gc_type, list_type, set_traits >set_type;
set_type s( kSize, 4 );
test( s );
EXPECT_GE( s.statistics().m_nInsertSuccess, 0u );
}
TEST_F( MichaelLazySet_NoGC, wrapped_stat )
{
struct list_traits: public cc::lazy_list::traits
{
typedef base_class::less less;
typedef cds::backoff::pause back_off;
typedef cc::lazy_list::wrapped_stat<> stat;
};
typedef cc::LazyList< gc_type, int_item, list_traits > list_type;
struct set_traits: public cc::michael_set::traits
{
typedef hash_int hash;
typedef cds::atomicity::item_counter item_counter;
};
typedef cc::MichaelHashSet< gc_type, list_type, set_traits >set_type;
set_type s( kSize, 4 );
test( s );
EXPECT_GE( s.statistics().m_nInsertSuccess, 0u );
}
} // namespace
|
#include "Simplify.h"
#include "Core.h"
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <iostream>
#include <stack>
struct Q_result {
Vec<double, 3> position_;
double cost_;
};
Q_result Q_calculate(std::vector<Vertex> &vs, std::size_t index1,
std::size_t index2);
bool isreverse(std::vector<Vertex> &vs, std::size_t index,
Vec<double, 3> new_position);
Simplify::Simplify(std::vector<Vertex> &vs, std::list<Face> &fs,
double threshold, bool isverbose, bool isjudgereverse)
: vertexs_(vs), faces_(fs), threshold2_(threshold * threshold),
facenum_(fs.size()), isverbose_(isverbose),
isjudgereverse_(isjudgereverse) {
using std::size_t;
if (isverbose_) {
std::cout << "build start" << std::endl;
}
size_t v_number = vertexs_.size();
for (Face &f : fs) {
f.set_parameter(vs);
for (int i = 0; i < 3; ++i) {
vs[f.vertex_[i]].ma_.add(f.paramater_);
}
}
if (isverbose_) {
std::cout << "calculating paramater finish" << std::endl;
}
for (size_t i = 0; i < v_number; ++i) {
if (threshold2_ == 0)
for (size_t const &j : vs[i].neibor_) {
if (j < i)
continue;
heap_.push_back(Edge(i, j));
Edge &new_pair = heap_.back();
Q_result result = Q_calculate(vs, i, j);
new_pair.cost_ = result.cost_;
if (isjudgereverse_ && (isreverse(vs, i, result.position_) ||
isreverse(vs, j, result.position_)))
new_pair.cost_ += 100;
new_pair.position_ = result.position_;
}
else
for (size_t j = i + 1; j < v_number; ++j) {
bool isneibor = vs[i].search_neiborhood(j);
if (isneibor) {
heap_.push_back(Edge(i, j));
} else {
if (Vec<double, 3>(vs[i] - vs[j]).norm2() < threshold2_) {
heap_.push_back(Edge(i, j));
} else {
continue;
}
}
Edge &new_pair = heap_.back();
Q_result result = Q_calculate(vs, i, j);
new_pair.cost_ = result.cost_;
new_pair.position_ = result.position_;
}
}
std::make_heap(heap_.begin(), heap_.end());
if (isverbose_) {
std::cout << "build finish" << std::endl;
std::cout << "total " << vertexs_.size() << " vertexs" << std::endl;
std::cout << "total " << heap_.size() << " pairs" << std::endl;
std::cout << "total " << faces_.size() << " faces" << std::endl;
}
for (std::size_t i = 0; i < heap_.size(); ++i) {
vs[heap_[i].pair_.first].pair_location_.insert(i);
vs[heap_[i].pair_.second].pair_location_.insert(i);
}
}
void Simplify::swap_pairs(std::size_t index1, std::size_t index2) {
bool iscontained[4] = {false, false, false, false};
if (vertexs_[heap_[index1].pair_.first].pair_location_.erase(index1))
iscontained[0] = true;
if (vertexs_[heap_[index1].pair_.second].pair_location_.erase(index1))
iscontained[1] = true;
if (vertexs_[heap_[index2].pair_.first].pair_location_.erase(index2))
iscontained[2] = true;
if (vertexs_[heap_[index2].pair_.second].pair_location_.erase(index2))
iscontained[3] = true;
std::swap(heap_[index1], heap_[index2]);
if (iscontained[2])
vertexs_[heap_[index1].pair_.first].pair_location_.insert(index1);
if (iscontained[3])
vertexs_[heap_[index1].pair_.second].pair_location_.insert(index1);
if (iscontained[0])
vertexs_[heap_[index2].pair_.first].pair_location_.insert(index2);
if (iscontained[1])
vertexs_[heap_[index2].pair_.second].pair_location_.insert(index2);
}
void Simplify::downflow(std::size_t index) {
if (heap_[index].isdeleted_) {
swap_pairs(index, heap_.size() - 1);
heap_.pop_back();
downflow(index);
}
if ((index << 1) + 2 > heap_.size()) {
heap_[index].ischanged_ = false;
return;
}
std::size_t largest = index, left = (index << 1) + 1,
right = (index << 1) + 2;
if (heap_[left].ischanged_) {
heap_[left].ischanged_ = false;
downflow(left);
}
if (heap_[right].ischanged_) {
heap_[right].ischanged_ = false;
downflow(right);
}
if (heap_[largest] < heap_[left])
largest = left;
if (right != heap_.size() && heap_[largest] < heap_[right])
largest = right;
if (largest != index) {
swap_pairs(largest, index);
downflow(largest);
}
}
void Simplify::remove() {
downflow(0);
std::size_t fin = heap_.front().pair_.first, sin = heap_.front().pair_.second;
Vertex &fir = vertexs_[heap_.front().pair_.first],
&sec = vertexs_[heap_.front().pair_.second];
fir = heap_[0].position_;
// fir.ma_ = Q_Matrix();
fir.ma_ = fir.ma_ + sec.ma_;
sec.isdeleted_ = true;
sec.index_ = fir.index_;
for (Face *const &f : sec.face_in_neibor_) {
if (!f->isdeleted_) {
for (int i = 0; i < 3; ++i) {
if (f->vertex_[i] == fin) {
f->isdeleted_ = true;
facenum_--;
break;
} else if (f->vertex_[i] == sin) {
f->vertex_[i] = fin;
}
}
if (!f->isdeleted_) {
fir.face_in_neibor_.insert(f);
}
}
}
sec.face_in_neibor_.clear();
// for (Face *const &f : fir.face_in_neibor_) {
// if (!f->isdeleted_) {
// f->set_parameter(vertexs_);
// fir.ma_.add(f->paramater_);
// }
// }
fir.pair_location_.erase(0);
sec.pair_location_.erase(0);
for (std::size_t const &s : sec.pair_location_) {
if (heap_[s].pair_.first == sin)
heap_[s].pair_.first = fin;
if (heap_[s].pair_.second == sin)
heap_[s].pair_.second = fin;
bool isduplicate = false;
for (std::size_t const &c : fir.pair_location_) {
if (heap_[s] == heap_[c]) {
heap_[s].ischanged_ = true;
heap_[s].isdeleted_ = true;
isduplicate = true;
break;
}
}
if (!isduplicate)
fir.pair_location_.insert(s);
}
for (std::size_t const &s : fir.pair_location_) {
Q_result out =
Q_calculate(vertexs_, heap_[s].pair_.first, heap_[s].pair_.second);
// if (isverbose_ && out.cost_ < heap_[s].cost_)
// std::cout << "cost reduced ";
heap_[s].cost_ = out.cost_;
if (isjudgereverse_ &&
(isreverse(vertexs_, heap_[s].pair_.first, out.position_) ||
isreverse(vertexs_, heap_[s].pair_.second, out.position_)))
heap_[s].cost_ += 100;
heap_[s].position_ = out.position_;
heap_[s].ischanged_ = true;
}
heap_[0].ischanged_ = true;
heap_[0].isdeleted_ = true;
}
void Simplify::simplify(std::size_t aim) {
while (facenum_ > aim)
remove();
if (isverbose_) {
std::cout << facenum_ << " faces remained" << std::endl;
}
}
Q_result Q_calculate(std::vector<Vertex> &vs, std::size_t index1,
std::size_t index2) {
Q_Matrix Q = vs[index1].ma_ + vs[index2].ma_;
Q_result out;
try {
out.position_ = Q.max_point();
out.cost_ = Q.cal_norm(out.position_);
} catch (std::domain_error) {
double cost[3];
cost[0] = Q.cal_norm(vs[index1]);
cost[1] = Q.cal_norm(vs[index2]);
cost[2] = Q.cal_norm(0.5 * (vs[index1] + vs[index2]));
int index = 0;
double min_cost = cost[index];
for (int i = 1; i < 3; ++i)
if (cost[i] < min_cost) {
min_cost = cost[i];
index = i;
}
switch (index) {
case 0:
out.position_ = vs[index1];
break;
case 1:
out.position_ = vs[index2];
break;
case 2:
out.position_ = 0.5 * (vs[index1] + vs[index2]);
break;
}
out.cost_ = min_cost;
}
return out;
}
bool isreverse(std::vector<Vertex> &vs, std::size_t index,
Vec<double, 3> new_position) {
for (Face *const &f : vs[index].face_in_neibor_) {
if (!f->isdeleted_) {
Vec<double, 3> old_direct;
Vec<double, 3> new_direct;
for (int i = 0; i < 3; ++i) {
old_direct[i] = f->paramater_[i];
}
Vec<double, 3> new_vertex[3];
for (int i = 0; i < 3; ++i) {
if (f->vertex_[i] == index) {
new_vertex[i] = new_position;
} else
new_vertex[i] = vs[f->vertex_[i]];
}
new_direct = cross(Vec<double, 3>(new_vertex[1] - new_vertex[0]),
Vec<double, 3>(new_vertex[2] - new_vertex[1]));
if (inner(old_direct, new_direct) < 0)
return true;
}
}
return false;
}
|
#pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/DynArray.hpp>
#include <RED4ext/Handle.hpp>
#include <RED4ext/Scripting/Natives/Generated/scn/IInterruptManager_Operation.hpp>
namespace RED4ext
{
namespace scn { struct IReturnCondition; }
namespace scn {
struct OverrideReturnConditions_Operation : scn::IInterruptManager_Operation
{
static constexpr const char* NAME = "scnOverrideReturnConditions_Operation";
static constexpr const char* ALIAS = NAME;
DynArray<Handle<scn::IReturnCondition>> returnConditions; // 30
};
RED4EXT_ASSERT_SIZE(OverrideReturnConditions_Operation, 0x40);
} // namespace scn
} // namespace RED4ext
|
/*
* Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <iostream>
#include <stdlib.h>
#include <dali-toolkit-test-suite-utils.h>
#include <dali-toolkit/dali-toolkit.h>
#include <dali/devel-api/actors/actor-devel.h>
#include <dali-toolkit/devel-api/visuals/visual-properties-devel.h>
#include <dali-toolkit/public-api/transition/transition-set.h>
#include <dali-toolkit/public-api/transition/transition-base.h>
#include <dali-toolkit/public-api/transition/fade-transition.h>
using namespace Dali;
using namespace Dali::Toolkit;
// Functor to test whether a Finish signal is emitted
struct TransitionFinishCheck
{
TransitionFinishCheck(bool& signalReceived)
: mSignalReceived(signalReceived)
{
}
void operator()(TransitionSet& transitionSet)
{
mSignalReceived = true;
}
void Reset()
{
mSignalReceived = false;
}
void CheckSignalReceived()
{
if(!mSignalReceived)
{
tet_printf("Expected Finish signal was not received\n");
tet_result(TET_FAIL);
}
else
{
tet_result(TET_PASS);
}
}
void CheckSignalNotReceived()
{
if(mSignalReceived)
{
tet_printf("Unexpected Finish signal was received\n");
tet_result(TET_FAIL);
}
else
{
tet_result(TET_PASS);
}
}
bool& mSignalReceived; // owned by individual tests
};
int UtcDaliFadeTransitionSetGetProperty(void)
{
ToolkitTestApplication application;
tet_infoline("UtcDaliFadeTransitionSetGetProperty");
Control control = Control::New();
FadeTransition fade = FadeTransition::New(control, 0.5, TimePeriod(-0.5f, -0.5f));
TimePeriod timePeriod = fade.GetTimePeriod();
DALI_TEST_EQUALS(0.0f, timePeriod.delaySeconds, TEST_LOCATION);
DALI_TEST_EQUALS(0.0f, timePeriod.durationSeconds, TEST_LOCATION);
END_TEST;
}
int UtcDaliFadeTransitionWithOffScene(void)
{
ToolkitTestApplication application;
tet_infoline("UtcDaliFadeTransitionWithOffScene");
Control control = Control::New();
control.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT);
control.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
control.SetProperty(Actor::Property::POSITION, Vector3(100, 200, 0));
control.SetProperty(Actor::Property::SIZE, Vector3(150, 150, 0));
control.SetProperty(Actor::Property::OPACITY, 1.0f);
Property::Map controlProperty;
controlProperty.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR);
controlProperty.Insert(Toolkit::ColorVisual::Property::MIX_COLOR, Vector4(1.0f, 0.0f, 0.0f, 1.0f));
control.SetProperty(Toolkit::Control::Property::BACKGROUND, controlProperty);
application.SendNotification();
application.Render(20);
DALI_TEST_EQUALS(1.0f, control.GetCurrentProperty<float>(Actor::Property::OPACITY), TEST_LOCATION);
FadeTransition fade = FadeTransition::New(control, 0.5, TimePeriod(0.5f));
fade.SetAppearingTransition(false); // set fade out
TransitionSet transitionSet = TransitionSet::New();
transitionSet.AddTransition(fade);
transitionSet.Play();
bool signalReceived(false);
TransitionFinishCheck finishCheck(signalReceived);
transitionSet.FinishedSignal().Connect(&application, finishCheck);
application.SendNotification();
application.Render(400);
// We didn't expect the animation to finish yet
application.SendNotification();
finishCheck.CheckSignalNotReceived();
DALI_TEST_EQUALS(1.0f, control.GetCurrentProperty<float>(Actor::Property::OPACITY), TEST_LOCATION);
application.SendNotification();
application.Render(200);
// We did expect the animation to finish
application.SendNotification();
finishCheck.CheckSignalReceived();
application.SendNotification();
application.Render(20);
DALI_TEST_EQUALS(1.0f, control.GetCurrentProperty<float>(Actor::Property::OPACITY), TEST_LOCATION);
END_TEST;
}
int UtcDaliFadeTransitionDisappearing(void)
{
ToolkitTestApplication application;
tet_infoline("UtcDaliFadeTransitionOut");
Control control = Control::New();
control.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT);
control.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
control.SetProperty(Actor::Property::POSITION, Vector3(100, 200, 0));
control.SetProperty(Actor::Property::SIZE, Vector3(150, 150, 0));
control.SetProperty(Actor::Property::OPACITY, 1.0f);
Property::Map controlProperty;
controlProperty.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR);
controlProperty.Insert(Toolkit::ColorVisual::Property::MIX_COLOR, Vector4(1.0f, 0.0f, 0.0f, 1.0f));
control.SetProperty(Toolkit::Control::Property::BACKGROUND, controlProperty);
application.GetScene().Add(control);
application.SendNotification();
application.Render(20);
DALI_TEST_EQUALS(1.0f, control.GetCurrentProperty<float>(Actor::Property::OPACITY), TEST_LOCATION);
FadeTransition fade = FadeTransition::New(control, 0.5, TimePeriod(0.5f));
fade.SetAppearingTransition(false); // set fade out
TransitionSet transitionSet = TransitionSet::New();
transitionSet.AddTransition(fade);
transitionSet.Play();
bool signalReceived(false);
TransitionFinishCheck finishCheck(signalReceived);
transitionSet.FinishedSignal().Connect(&application, finishCheck);
application.SendNotification();
application.Render(400);
// We didn't expect the animation to finish yet
application.SendNotification();
finishCheck.CheckSignalNotReceived();
float currentOpacity = control.GetCurrentProperty<float>(Actor::Property::OPACITY);
DALI_TEST_CHECK(currentOpacity <= 0.7 && currentOpacity >= 0.5);
application.SendNotification();
application.Render(200);
// We did expect the animation to finish
application.SendNotification();
finishCheck.CheckSignalReceived();
application.SendNotification();
application.Render(20);
// Property is reset after animation.
DALI_TEST_EQUALS(1.0f, control.GetCurrentProperty<float>(Actor::Property::OPACITY), TEST_LOCATION);
END_TEST;
}
int UtcDaliFadeTransitionAppearing(void)
{
ToolkitTestApplication application;
tet_infoline("UtcDaliFadeTransitionIn");
Control control = Control::New();
control.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT);
control.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
control.SetProperty(Actor::Property::POSITION, Vector3(100, 200, 0));
control.SetProperty(Actor::Property::SIZE, Vector3(150, 150, 0));
control.SetProperty(Actor::Property::OPACITY, 1.0f);
Property::Map controlProperty;
controlProperty.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR);
controlProperty.Insert(Toolkit::ColorVisual::Property::MIX_COLOR, Vector4(1.0f, 0.0f, 0.0f, 1.0f));
control.SetProperty(Toolkit::Control::Property::BACKGROUND, controlProperty);
application.GetScene().Add(control);
application.SendNotification();
application.Render(20);
DALI_TEST_EQUALS(1.0f, control.GetCurrentProperty<float>(Actor::Property::OPACITY), TEST_LOCATION);
FadeTransition fade = FadeTransition::New(control, 0.5, TimePeriod(0.5f));
fade.SetAppearingTransition(true); // set fade in
TransitionSet transitionSet = TransitionSet::New();
transitionSet.AddTransition(fade);
transitionSet.Play();
bool signalReceived(false);
TransitionFinishCheck finishCheck(signalReceived);
transitionSet.FinishedSignal().Connect(&application, finishCheck);
application.SendNotification();
application.Render(400);
// We didn't expect the animation to finish yet
application.SendNotification();
finishCheck.CheckSignalNotReceived();
float currentOpacity = control.GetCurrentProperty<float>(Actor::Property::OPACITY);
DALI_TEST_CHECK(currentOpacity <= 1.0 && currentOpacity >= 0.8);
application.SendNotification();
application.Render(200);
// We did expect the animation to finish
application.SendNotification();
finishCheck.CheckSignalReceived();
application.SendNotification();
application.Render(20);
DALI_TEST_EQUALS(1.0f, control.GetCurrentProperty<float>(Actor::Property::OPACITY), TEST_LOCATION);
END_TEST;
}
int UtcDaliFadeTransitionAppearingWithDelay(void)
{
ToolkitTestApplication application;
tet_infoline("UtcDaliFadeTransitionIn");
Control control = Control::New();
control.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT);
control.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
control.SetProperty(Actor::Property::POSITION, Vector3(100, 200, 0));
control.SetProperty(Actor::Property::SIZE, Vector3(150, 150, 0));
control.SetProperty(Actor::Property::OPACITY, 1.0f);
Property::Map controlProperty;
controlProperty.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR);
controlProperty.Insert(Toolkit::ColorVisual::Property::MIX_COLOR, Vector4(1.0f, 0.0f, 0.0f, 1.0f));
control.SetProperty(Toolkit::Control::Property::BACKGROUND, controlProperty);
application.GetScene().Add(control);
application.SendNotification();
application.Render(20);
DALI_TEST_EQUALS(1.0f, control.GetCurrentProperty<float>(Actor::Property::OPACITY), TEST_LOCATION);
FadeTransition fade = FadeTransition::New(control, 0.5, TimePeriod(0.5f, 0.5f));
fade.SetAppearingTransition(true); // set fade in
TransitionSet transitionSet = TransitionSet::New();
transitionSet.AddTransition(fade);
transitionSet.Play();
bool signalReceived(false);
TransitionFinishCheck finishCheck(signalReceived);
transitionSet.FinishedSignal().Connect(&application, finishCheck);
application.SendNotification();
application.Render(400);
// We didn't expect the animation to finish yet
application.SendNotification();
finishCheck.CheckSignalNotReceived();
float currentOpacity = control.GetCurrentProperty<float>(Actor::Property::OPACITY);
DALI_TEST_CHECK(currentOpacity <= 0.01f);
application.SendNotification();
application.Render(500);
// We didn't expect the animation to finish yet
application.SendNotification();
finishCheck.CheckSignalNotReceived();
currentOpacity = control.GetCurrentProperty<float>(Actor::Property::OPACITY);
DALI_TEST_CHECK(currentOpacity <= 1.0 && currentOpacity >= 0.8);
application.SendNotification();
application.Render(200);
// We did expect the animation to finish
application.SendNotification();
finishCheck.CheckSignalReceived();
application.SendNotification();
application.Render(20);
DALI_TEST_EQUALS(1.0f, control.GetCurrentProperty<float>(Actor::Property::OPACITY), TEST_LOCATION);
END_TEST;
}
|
#include<iostream>
using namespace std;
class LTMatrix{
int size;
int *arr;
public:
LTMatrix(int s = 0){
if(s < 0)
throw "Invalid Size";
size = s;
arr = new int[size * (size + 1) / 2]{0};
}
void set(int i, int j, int value){
if(j > i){
if(value != 0)
throw "Invalid value for given indices";
else
return;
}
if(i < 1 || j < 1 || i > size || j > size)
throw "Invalid Indices for Lower Triangular Matrix";
arr[(i * (i - 1) / 2) + (j - 1)] = value;
}
int get(int i, int j){
if(i < 1 || j < 1 || i > size || j > size)
throw "Invalid Indices for Lower Triangular Matrix";
if (j > i)
return 0;
return arr[(i * (i - 1) / 2) + (j - 1)];
}
void print(){
for(int i = 1; i <= size; i++){
for(int j = 1; j <= size; j++){
if(j > i){
cout << 0 << " ";
continue;
}
cout << get(i, j) << " ";
}
cout << "\n";
}
}
~LTMatrix(){
delete arr;
}
};
int main(){
int n;
try{
cout << "Enter size of the Lower triangular matrix: ";
cin >> n;
LTMatrix ltm(n);
ltm.print();
cout << endl;
ltm.set(1, 1, 10);
ltm.set(2, 1, 30);
ltm.print();
cout << endl;
ltm.set(1, 0, 20);
ltm.set(1, 2, 0);
cout << "[1, 1]: " << ltm.get(1, 1) << "\n";
cout << "[1, 2]: " << ltm.get(1 ,2) << "\n";
}
catch(const char* s){
cout << s << endl;
}
return 0;
}
|
// 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 <openssl/ecdsa.h>
#include <openssl/rand.h>
#include <openssl/obj_mac.h>
#include "key.h"
// anonymous namespace with local implementation code (OpenSSL interaction)
namespace {
// Generate a private key from just the secret parameter
int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
{
int ok = 0;
BN_CTX *ctx = NULL;
EC_POINT *pub_key = NULL;
if (!eckey) return 0;
const EC_GROUP *group = EC_KEY_get0_group(eckey);
if ((ctx = BN_CTX_new()) == NULL)
goto err;
pub_key = EC_POINT_new(group);
if (pub_key == NULL)
goto err;
if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
goto err;
EC_KEY_set_private_key(eckey,priv_key);
EC_KEY_set_public_key(eckey,pub_key);
ok = 1;
err:
if (pub_key)
EC_POINT_free(pub_key);
if (ctx != NULL)
BN_CTX_free(ctx);
return(ok);
}
// Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
// recid selects which key is recovered
// if check is non-zero, additional checks are performed
int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
{
if (!eckey) return 0;
int ret = 0;
BN_CTX *ctx = NULL;
BIGNUM *x = NULL;
BIGNUM *e = NULL;
BIGNUM *order = NULL;
BIGNUM *sor = NULL;
BIGNUM *eor = NULL;
BIGNUM *field = NULL;
EC_POINT *R = NULL;
EC_POINT *O = NULL;
EC_POINT *Q = NULL;
BIGNUM *rr = NULL;
BIGNUM *zero = NULL;
int n = 0;
int i = recid / 2;
const EC_GROUP *group = EC_KEY_get0_group(eckey);
if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
BN_CTX_start(ctx);
order = BN_CTX_get(ctx);
if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
x = BN_CTX_get(ctx);
if (!BN_copy(x, order)) { ret=-1; goto err; }
if (!BN_mul_word(x, i)) { ret=-1; goto err; }
if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }
field = BN_CTX_get(ctx);
if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
if (check)
{
if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
}
if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
n = EC_GROUP_get_degree(group);
e = BN_CTX_get(ctx);
if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
zero = BN_CTX_get(ctx);
if (!BN_zero(zero)) { ret=-1; goto err; }
if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
rr = BN_CTX_get(ctx);
if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }
sor = BN_CTX_get(ctx);
if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }
eor = BN_CTX_get(ctx);
if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
ret = 1;
err:
if (ctx) {
BN_CTX_end(ctx);
BN_CTX_free(ctx);
}
if (R != NULL) EC_POINT_free(R);
if (O != NULL) EC_POINT_free(O);
if (Q != NULL) EC_POINT_free(Q);
return ret;
}
// RAII Wrapper around OpenSSL's EC_KEY
class CECKey {
private:
EC_KEY *pkey;
public:
CECKey() {
pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
assert(pkey != NULL);
}
~CECKey() {
EC_KEY_free(pkey);
}
void GetSecretBytes(unsigned char vch[32]) const {
const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
assert(bn);
int nBytes = BN_num_bytes(bn);
int n=BN_bn2bin(bn,&vch[32 - nBytes]);
assert(n == nBytes);
memset(vch, 0, 32 - nBytes);
}
void SetSecretBytes(const unsigned char vch[32]) {
BIGNUM bn;
BN_init(&bn);
assert(BN_bin2bn(vch, 32, &bn));
assert(EC_KEY_regenerate_key(pkey, &bn));
BN_clear_free(&bn);
}
void GetPrivKey(CPrivKey &privkey, bool fCompressed) {
EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
int nSize = i2d_ECPrivateKey(pkey, NULL);
assert(nSize);
privkey.resize(nSize);
unsigned char* pbegin = &privkey[0];
int nSize2 = i2d_ECPrivateKey(pkey, &pbegin);
assert(nSize == nSize2);
}
bool SetPrivKey(const CPrivKey &privkey) {
const unsigned char* pbegin = &privkey[0];
if (d2i_ECPrivateKey(&pkey, &pbegin, privkey.size())) {
// d2i_ECPrivateKey returns true if parsing succeeds.
// This doesn't necessarily mean the key is valid.
if (EC_KEY_check_key(pkey))
return true;
}
return false;
}
void GetPubKey(CPubKey &pubkey, bool fCompressed) {
EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
int nSize = i2o_ECPublicKey(pkey, NULL);
assert(nSize);
assert(nSize <= 65);
unsigned char c[65];
unsigned char *pbegin = c;
int nSize2 = i2o_ECPublicKey(pkey, &pbegin);
assert(nSize == nSize2);
pubkey.Set(&c[0], &c[nSize]);
}
bool SetPubKey(const CPubKey &pubkey) {
const unsigned char* pbegin = pubkey.begin();
return o2i_ECPublicKey(&pkey, &pbegin, pubkey.size());
}
bool Sign(const uint256 &hash, std::vector<unsigned char>& vchSig) {
unsigned int nSize = ECDSA_size(pkey);
vchSig.resize(nSize); // Make sure it is big enough
assert(ECDSA_sign(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], &nSize, pkey));
vchSig.resize(nSize); // Shrink to fit actual size
return true;
}
bool Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) {
// -1 = error, 0 = bad sig, 1 = good
if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1)
return false;
return true;
}
bool SignCompact(const uint256 &hash, unsigned char *p64, int &rec) {
bool fOk = false;
ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
if (sig==NULL)
return false;
memset(p64, 0, 64);
int nBitsR = BN_num_bits(sig->r);
int nBitsS = BN_num_bits(sig->s);
if (nBitsR <= 256 && nBitsS <= 256) {
CPubKey pubkey;
GetPubKey(pubkey, true);
for (int i=0; i<4; i++) {
CECKey keyRec;
if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1) {
CPubKey pubkeyRec;
keyRec.GetPubKey(pubkeyRec, true);
if (pubkeyRec == pubkey) {
rec = i;
fOk = true;
break;
}
}
}
assert(fOk);
BN_bn2bin(sig->r,&p64[32-(nBitsR+7)/8]);
BN_bn2bin(sig->s,&p64[64-(nBitsS+7)/8]);
}
ECDSA_SIG_free(sig);
return fOk;
}
// reconstruct public key from a compact signature
// This is only slightly more CPU intensive than just verifying it.
// If this function succeeds, the recovered public key is guaranteed to be valid
// (the signature is a valid signature of the given data for that key)
bool Recover(const uint256 &hash, const unsigned char *p64, int rec)
{
if (rec<0 || rec>=3)
return false;
ECDSA_SIG *sig = ECDSA_SIG_new();
BN_bin2bn(&p64[0], 32, sig->r);
BN_bin2bn(&p64[32], 32, sig->s);
bool ret = ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), rec, 0) == 1;
ECDSA_SIG_free(sig);
return ret;
}
};
}; // end of anonymous namespace
bool CKey::Check(const unsigned char *vch) {
// Do not convert to OpenSSL's data structures for range-checking keys,
// it's easy enough to do directly.
static const unsigned char vchMax[32] = {
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE,
0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,
0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x40
};
bool fIsZero = true;
for (int i=0; i<32 && fIsZero; i++)
if (vch[i] != 0)
fIsZero = false;
if (fIsZero)
return false;
for (int i=0; i<32; i++) {
if (vch[i] < vchMax[i])
return true;
if (vch[i] > vchMax[i])
return false;
}
return true;
}
void CKey::MakeNewKey(bool fCompressedIn) {
do {
RAND_bytes(vch, sizeof(vch));
} while (!Check(vch));
fValid = true;
fCompressed = fCompressedIn;
}
bool CKey::SetPrivKey(const CPrivKey &privkey, bool fCompressedIn) {
CECKey key;
if (!key.SetPrivKey(privkey))
return false;
key.GetSecretBytes(vch);
fCompressed = fCompressedIn;
fValid = true;
return true;
}
CPrivKey CKey::GetPrivKey() const {
assert(fValid);
CECKey key;
key.SetSecretBytes(vch);
CPrivKey privkey;
key.GetPrivKey(privkey, fCompressed);
return privkey;
}
CPubKey CKey::GetPubKey() const {
assert(fValid);
CECKey key;
key.SetSecretBytes(vch);
CPubKey pubkey;
key.GetPubKey(pubkey, fCompressed);
return pubkey;
}
bool CKey::Sign(const uint256 &hash, std::vector<unsigned char>& vchSig) const {
if (!fValid)
return false;
CECKey key;
key.SetSecretBytes(vch);
return key.Sign(hash, vchSig);
}
bool CKey::SignCompact(const uint256 &hash, std::vector<unsigned char>& vchSig) const {
if (!fValid)
return false;
CECKey key;
key.SetSecretBytes(vch);
vchSig.resize(65);
int rec = -1;
if (!key.SignCompact(hash, &vchSig[1], rec))
return false;
assert(rec != -1);
vchSig[0] = 27 + rec + (fCompressed ? 4 : 0);
return true;
}
bool CPubKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) const {
if (!IsValid())
return false;
CECKey key;
if (!key.SetPubKey(*this))
return false;
if (!key.Verify(hash, vchSig))
return false;
return true;
}
bool CPubKey::RecoverCompact(const uint256 &hash, const std::vector<unsigned char>& vchSig) {
if (vchSig.size() != 65)
return false;
CECKey key;
if (!key.Recover(hash, &vchSig[1], (vchSig[0] - 27) & ~4))
return false;
key.GetPubKey(*this, (vchSig[0] - 27) & 4);
return true;
}
bool CPubKey::VerifyCompact(const uint256 &hash, const std::vector<unsigned char>& vchSig) const {
if (!IsValid())
return false;
if (vchSig.size() != 65)
return false;
CECKey key;
if (!key.Recover(hash, &vchSig[1], (vchSig[0] - 27) & ~4))
return false;
CPubKey pubkeyRec;
key.GetPubKey(pubkeyRec, IsCompressed());
if (*this != pubkeyRec)
return false;
return true;
}
bool CPubKey::IsFullyValid() const {
if (!IsValid())
return false;
CECKey key;
if (!key.SetPubKey(*this))
return false;
return true;
}
bool CPubKey::Decompress() {
if (!IsValid())
return false;
CECKey key;
if (!key.SetPubKey(*this))
return false;
key.GetPubKey(*this, false);
return true;
}
|
/************************** TRICK HEADER **********************************************************
LIBRARY DEPENDENCY:
((TsApproximation.o))
***************************************************************************************************/
#include <cfloat>
#include "QuadraticFit.hh"
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Default constructs this Quadratic curve fit model.
////////////////////////////////////////////////////////////////////////////////////////////////////
QuadraticFit::QuadraticFit()
:
TsApproximation(),
mA(0.0),
mB(0.0),
mC(0.0)
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] a (--) First coefficient for curve fit model.
/// @param[in] b (--) Second coefficient for curve fit model.
/// @param[in] c (--) Third coefficient for curve fit model.
/// @param[in] minX (--) Curve fit model valid range lower limit for first variable.
/// @param[in] maxX (--) Curve fit model valid range upper limit for first variable.
/// @param[in] name (--) name for the instance.
///
/// @details Constructs this Quadratic curve fit model taking coefficient and range arguments.
////////////////////////////////////////////////////////////////////////////////////////////////////
QuadraticFit::QuadraticFit(const double a, const double b, const double c,
const double minX, const double maxX,
const std::string &name)
:
TsApproximation(),
mA(a),
mB(b),
mC(c)
{
init(a, b, c, minX, maxX, name);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Default destructs this Quadratic curve fit model.
////////////////////////////////////////////////////////////////////////////////////////////////////
QuadraticFit::~QuadraticFit()
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] a (--) First coefficient for curve fit model.
/// @param[in] b (--) Second coefficient for curve fit model.
/// @param[in] c (--) Third coefficient for curve fit model.
/// @param[in] minX (--) Curve fit model valid range lower limit for first variable.
/// @param[in] maxX (--) Curve fit model valid range upper limit for first variable.
/// @param[in] name (--) name for the instance.
///
/// @details Initializes this Quadratic curve fit model taking coefficient, range and
/// name arguments
////////////////////////////////////////////////////////////////////////////////////////////////////
void QuadraticFit::init(const double a, const double b, const double c,
const double minX, const double maxX,
const std::string &name)
{
/// - Initialize the parent
TsApproximation::init(minX, maxX, -FLT_EPSILON, +FLT_EPSILON, name);
/// - Initialize the coefficients.
mA = a;
mB = b;
mC = c;
}
|
// Copyright 2010-2014 UT-Battelle, LLC. See LICENSE.txt for more information.
#include "eavlPoint3.h"
ostream &operator<<(ostream& out, const eavlPoint3 &r)
{
out << "<" << r.x << "," << r.y << "," << r.z << ">";
return out;
}
|
#include "editaddressdialog.h"
#include "ui_editaddressdialog.h"
#include "addresstablemodel.h"
#include "guiutil.h"
#include <QDataWidgetMapper>
#include <QMessageBox>
EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0)
{
ui->setupUi(this);
GUIUtil::setupAddressWidget(ui->addressEdit, this);
switch(mode)
{
case NewReceivingAddress:
setWindowTitle(tr("New receiving address"));
ui->addressEdit->setEnabled(false);
break;
case NewSendingAddress:
setWindowTitle(tr("New sending address"));
break;
case EditReceivingAddress:
setWindowTitle(tr("Edit receiving address"));
ui->addressEdit->setEnabled(false);
break;
case EditSendingAddress:
setWindowTitle(tr("Edit sending address"));
break;
}
mapper = new QDataWidgetMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
}
EditAddressDialog::~EditAddressDialog()
{
delete ui;
}
void EditAddressDialog::setModel(AddressTableModel *model)
{
this->model = model;
if(!model)
return;
mapper->setModel(model);
mapper->addMapping(ui->labelEdit, AddressTableModel::Label);
mapper->addMapping(ui->addressEdit, AddressTableModel::Address);
}
void EditAddressDialog::loadRow(int row)
{
mapper->setCurrentIndex(row);
}
bool EditAddressDialog::saveCurrentRow()
{
if(!model)
return false;
switch(mode)
{
case NewReceivingAddress:
case NewSendingAddress:
address = model->addRow(
mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive,
ui->labelEdit->text(),
ui->addressEdit->text());
break;
case EditReceivingAddress:
case EditSendingAddress:
if(mapper->submit())
{
address = ui->addressEdit->text();
}
break;
}
return !address.isEmpty();
}
void EditAddressDialog::accept()
{
if(!model)
return;
if(!saveCurrentRow())
{
switch(model->getEditStatus())
{
case AddressTableModel::OK:
// Failed with unknown reason. Just reject.
break;
case AddressTableModel::NO_CHANGES:
// No changes were made during edit operation. Just reject.
break;
case AddressTableModel::INVALID_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is not a valid FitCoin address.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::DUPLICATE_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::WALLET_UNLOCK_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("Could not unlock wallet."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::KEY_GENERATION_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("New key generation failed."),
QMessageBox::Ok, QMessageBox::Ok);
break;
}
return;
}
QDialog::accept();
}
QString EditAddressDialog::getAddress() const
{
return address;
}
void EditAddressDialog::setAddress(const QString &address)
{
this->address = address;
ui->addressEdit->setText(address);
}
|
/*************************************************************************/
/* global_defaults.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2017 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 "global_defaults.h"
#include "global_config.h"
void register_android_global_defaults() {
/* GLOBAL_DEF("rasterizer.Android/use_fragment_lighting",false);
GLOBAL_DEF("rasterizer.Android/fp16_framebuffer",false);
GLOBAL_DEF("display.Android/driver","GLES2");
//GLOBAL_DEF("rasterizer.Android/trilinear_mipmap_filter",false);
GlobalConfig::get_singleton()->set_custom_property_info("display.Android/driver",PropertyInfo(Variant::STRING,"display.Android/driver",PROPERTY_HINT_ENUM,"GLES2"));
*/
}
|
/*
* Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include "MoveTool.h"
#include "Image.h"
#include "ImageEditor.h"
#include "Layer.h"
#include <LibGUI/Action.h>
#include <LibGUI/Menu.h>
#include <LibGUI/Window.h>
#include <LibGfx/Bitmap.h>
namespace PixelPaint {
MoveTool::MoveTool()
{
}
MoveTool::~MoveTool()
{
}
void MoveTool::on_mousedown(Layer& layer, GUI::MouseEvent& event, GUI::MouseEvent& image_event)
{
if (event.button() != GUI::MouseButton::Left)
return;
if (!layer.rect().contains(event.position()))
return;
m_layer_being_moved = layer;
m_event_origin = image_event.position();
m_layer_origin = layer.location();
m_editor->window()->set_cursor(Gfx::StandardCursor::Move);
}
void MoveTool::on_mousemove(Layer&, GUI::MouseEvent&, GUI::MouseEvent& image_event)
{
if (!m_layer_being_moved)
return;
auto delta = image_event.position() - m_event_origin;
m_layer_being_moved->set_location(m_layer_origin.translated(delta));
m_editor->layers_did_change();
}
void MoveTool::on_mouseup(Layer&, GUI::MouseEvent& event, GUI::MouseEvent&)
{
if (event.button() != GUI::MouseButton::Left)
return;
m_layer_being_moved = nullptr;
m_editor->window()->set_cursor(Gfx::StandardCursor::None);
m_editor->did_complete_action();
}
void MoveTool::on_keydown(GUI::KeyEvent& event)
{
if (event.modifiers() != 0)
return;
auto* layer = m_editor->active_layer();
if (!layer)
return;
auto new_location = layer->location();
switch (event.key()) {
case Key_Up:
new_location.move_by(0, -1);
break;
case Key_Down:
new_location.move_by(0, 1);
break;
case Key_Left:
new_location.move_by(-1, 0);
break;
case Key_Right:
new_location.move_by(1, 0);
break;
default:
return;
}
layer->set_location(new_location);
m_editor->layers_did_change();
}
void MoveTool::on_context_menu(Layer& layer, GUI::ContextMenuEvent& event)
{
if (!m_context_menu) {
m_context_menu = GUI::Menu::construct();
m_context_menu->add_action(GUI::CommonActions::make_move_to_front_action(
[this](auto&) {
m_editor->image()->move_layer_to_front(*m_context_menu_layer);
m_editor->layers_did_change();
},
m_editor));
m_context_menu->add_action(GUI::CommonActions::make_move_to_back_action(
[this](auto&) {
m_editor->image()->move_layer_to_back(*m_context_menu_layer);
m_editor->layers_did_change();
},
m_editor));
m_context_menu->add_separator();
m_context_menu->add_action(GUI::Action::create(
"&Delete Layer", Gfx::Bitmap::load_from_file("/res/icons/16x16/delete.png"), [this](auto&) {
m_editor->image()->remove_layer(*m_context_menu_layer);
// FIXME: This should not be done imperatively here. Perhaps a Image::Client interface that ImageEditor can implement?
if (m_editor->active_layer() == m_context_menu_layer)
m_editor->set_active_layer(nullptr);
m_editor->layers_did_change();
},
m_editor));
}
m_context_menu_layer = layer;
m_context_menu->popup(event.screen_position());
}
}
|
/**
* @file
* @brief Monster spell casting.
**/
#include "AppHdr.h"
#include "mon-cast.h"
#include <algorithm>
#include <cmath>
#include <functional>
#include <unordered_set>
#include "act-iter.h"
#include "areas.h"
#include "bloodspatter.h"
#include "branch.h"
#include "cleansing-flame-source-type.h"
#include "cloud.h"
#include "colour.h"
#include "coordit.h"
#include "database.h"
#include "delay.h"
#include "directn.h"
#include "english.h"
#include "env.h"
#include "evoke.h"
#include "exclude.h"
#include "fight.h"
#include "fprop.h"
#include "god-passive.h"
#include "items.h"
#include "level-state-type.h"
#include "libutil.h"
#include "losglobal.h"
#include "mapmark.h"
#include "message.h"
#include "misc.h"
#include "mon-act.h"
#include "mon-behv.h"
#include "mon-book.h"
#include "mon-clone.h"
#include "mon-death.h"
#include "mon-gear.h"
#include "mon-pathfind.h"
#include "mon-pick.h"
#include "mon-place.h"
#include "mon-project.h"
#include "mon-speak.h"
#include "mon-tentacle.h"
#include "mutation.h"
#include "player-stats.h"
#include "random.h"
#include "religion.h"
#include "shout.h"
#include "showsymb.h"
#include "spl-clouds.h"
#include "spl-damage.h"
#include "spl-goditem.h"
#include "spl-monench.h"
#include "spl-selfench.h"
#include "spl-summoning.h"
#include "spl-transloc.h"
#include "spl-util.h"
#include "spl-zap.h" // spell_to_zap
#include "state.h"
#include "stepdown.h"
#include "stringutil.h"
#include "target.h"
#include "teleport.h"
#include "terrain.h"
#ifdef USE_TILE
#include "tiledef-dngn.h"
#endif
#include "timed-effects.h"
#include "traps.h"
#include "travel.h"
#include "unwind.h"
#include "view.h"
#include "viewchar.h"
#include "xom.h"
static bool _valid_mon_spells[NUM_SPELLS];
static const string MIRROR_RECAST_KEY = "mirror_recast_time";
static god_type _find_god(const monster &mons, mon_spell_slot_flags flags);
static monster* _get_allied_target(const monster &caster, bolt &tracer);
static void _fire_simple_beam(monster &caster, mon_spell_slot, bolt &beam);
static void _fire_direct_explosion(monster &caster, mon_spell_slot, bolt &beam);
static int _mons_mesmerise(monster* mons, bool actual = true);
static int _mons_cause_fear(monster* mons, bool actual = true);
static int _mons_mass_confuse(monster* mons, bool actual = true);
static coord_def _mons_fragment_target(const monster &mons);
static coord_def _mons_conjure_flame_pos(const monster &mon);
static coord_def _mons_awaken_earth_target(const monster& mon);
static void _maybe_throw_ally(const monster &mons);
static void _siren_sing(monster* mons, bool avatar);
static void _doom_howl(monster &mon);
static void _mons_awaken_earth(monster &mon, const coord_def &target);
static bool _ms_waste_of_time(monster* mon, mon_spell_slot slot);
static string _god_name(god_type god);
static bool _mons_can_bind_soul(monster* binder, monster* bound);
static coord_def _mons_ghostly_sacrifice_target(const monster &caster,
bolt tracer);
static function<void(bolt&, const monster&, int)>
_selfench_beam_setup(beam_type flavour);
static function<void(bolt&, const monster&, int)>
_zap_setup(spell_type spell);
static function<void(bolt&, const monster&, int)>
_buff_beam_setup(beam_type flavour);
static function<void(bolt&, const monster&, int)>
_target_beam_setup(function<coord_def(const monster&)> targeter);
static void _setup_minor_healing(bolt &beam, const monster &caster,
int = -1);
static void _setup_heal_other(bolt &beam, const monster &caster, int = -1);
static bool _foe_should_res_negative_energy(const actor* foe);
static bool _caster_sees_foe(const monster &caster);
static bool _foe_can_sleep(const monster &caster);
static bool _foe_not_teleporting(const monster &caster);
static bool _foe_not_mr_vulnerable(const monster &caster);
static bool _should_still_winds(const monster &caster);
static void _mons_vampiric_drain(monster &mons, mon_spell_slot, bolt&);
static void _cast_cantrip(monster &mons, mon_spell_slot, bolt&);
static void _cast_injury_mirror(monster &mons, mon_spell_slot, bolt&);
static void _cast_smiting(monster &mons, mon_spell_slot slot, bolt&);
static void _cast_resonance_strike(monster &mons, mon_spell_slot, bolt&);
static void _cast_flay(monster &caster, mon_spell_slot, bolt&);
static void _cast_still_winds(monster &caster, mon_spell_slot, bolt&);
static void _mons_summon_elemental(monster &caster, mon_spell_slot, bolt&);
static bool _los_spell_worthwhile(const monster &caster, spell_type spell);
static void _setup_fake_beam(bolt& beam, const monster&, int = -1);
static void _branch_summon(monster &caster, mon_spell_slot slot, bolt&);
static void _branch_summon_helper(monster* mons, spell_type spell_cast);
static bool _prepare_ghostly_sacrifice(monster &caster, bolt &beam);
static void _setup_ghostly_beam(bolt &beam, int power, int dice);
static void _setup_ghostly_sacrifice_beam(bolt& beam, const monster& caster,
int power);
static function<bool(const monster&)> _setup_hex_check(spell_type spell);
static bool _worth_hexing(const monster &caster, spell_type spell);
static bool _torment_vulnerable(actor* victim);
static function<bool(const monster&)> _should_selfench(enchant_type ench);
static void _cast_grasping_roots(monster &caster, mon_spell_slot, bolt&);
enum spell_logic_flag
{
MSPELL_NO_AUTO_NOISE = 1 << 0, ///< silent, or noise generated specially
};
DEF_BITFIELD(spell_logic_flags, spell_logic_flag);
constexpr spell_logic_flags MSPELL_LOGIC_NONE{};
struct mons_spell_logic
{
/// Can casting this spell right now accomplish anything useful?
function<bool(const monster&)> worthwhile;
/// Actually cast the given spell.
function<void(monster&, mon_spell_slot, bolt&)> cast;
/// Setup a targeting/effect beam for the given spell, if applicable.
function<void(bolt&, const monster&, int)> setup_beam;
/// What special behaviors does this spell have for monsters?
spell_logic_flags flags;
/// How much 'power' is this spell cast with per caster HD? If 0, ignore
int power_hd_factor;
};
static bool _always_worthwhile(const monster &caster) { return true; }
static bool _caster_has_foe(const monster &caster) { return caster.foe != 0; }
static mons_spell_logic _conjuration_logic(spell_type spell);
static mons_spell_logic _hex_logic(spell_type spell,
function<bool(const monster&)> extra_logic
= nullptr,
int power_hd_factor = 0);
/// How do monsters go about casting spells?
static const map<spell_type, mons_spell_logic> spell_to_logic = {
{ SPELL_MIGHT, {
_should_selfench(ENCH_MIGHT),
_fire_simple_beam,
_selfench_beam_setup(BEAM_MIGHT),
} },
{ SPELL_INVISIBILITY, {
_should_selfench(ENCH_INVIS),
_fire_simple_beam,
_selfench_beam_setup(BEAM_INVISIBILITY),
} },
{ SPELL_HASTE, {
_should_selfench(ENCH_HASTE),
_fire_simple_beam,
_selfench_beam_setup(BEAM_HASTE),
} },
{ SPELL_MINOR_HEALING, {
[](const monster &caster) {
return caster.hit_points <= caster.max_hit_points / 2;
},
_fire_simple_beam,
_setup_minor_healing,
} },
{ SPELL_TELEPORT_SELF, {
[](const monster &caster)
{
// Monsters aren't smart enough to know when to cancel teleport.
return !caster.has_ench(ENCH_TP) && !caster.no_tele(true, false);
},
_fire_simple_beam,
_selfench_beam_setup(BEAM_TELEPORT),
} },
{ SPELL_SLUG_DART, _conjuration_logic(SPELL_SLUG_DART) },
{ SPELL_VAMPIRIC_DRAINING, {
[](const monster &caster)
{
const actor* foe = caster.get_foe();
// always cast at < 1/3rd hp, never at > 2/3rd hp
const bool low_hp = x_chance_in_y(caster.max_hit_points * 2 / 3
- caster.hit_points,
caster.max_hit_points / 3);
return foe
&& adjacent(caster.pos(), foe->pos())
&& !_foe_should_res_negative_energy(foe)
&& low_hp;
},
_mons_vampiric_drain,
nullptr,
MSPELL_NO_AUTO_NOISE,
} },
{ SPELL_CANTRIP, {
[](const monster &caster) { return caster.get_foe(); },
_cast_cantrip,
nullptr,
MSPELL_NO_AUTO_NOISE,
} },
{ SPELL_INJURY_MIRROR, {
[](const monster &caster) {
return !caster.has_ench(ENCH_MIRROR_DAMAGE)
&& (!caster.props.exists(MIRROR_RECAST_KEY)
|| you.elapsed_time >=
caster.props[MIRROR_RECAST_KEY].get_int());
},
_cast_injury_mirror,
nullptr,
MSPELL_NO_AUTO_NOISE,
} },
{ SPELL_DRAIN_LIFE, {
[](const monster &caster) {
return _los_spell_worthwhile(caster, SPELL_DRAIN_LIFE)
&& (!caster.friendly()
|| !you.visible_to(&caster)
|| player_prot_life(false) >= 3);
},
[](monster &caster, mon_spell_slot slot, bolt&) {
const int splpow = mons_spellpower(caster, slot.spell);
int damage = 0;
fire_los_attack_spell(slot.spell, splpow, &caster, nullptr, false,
&damage);
if (damage > 0 && caster.heal(damage))
simple_monster_message(caster, " is healed.");
},
nullptr,
MSPELL_NO_AUTO_NOISE,
1,
} },
{ SPELL_OZOCUBUS_REFRIGERATION, {
[](const monster &caster) {
return _los_spell_worthwhile(caster, SPELL_OZOCUBUS_REFRIGERATION)
&& (!caster.friendly() || !you.visible_to(&caster));
},
[](monster &caster, mon_spell_slot slot, bolt&) {
const int splpow = mons_spellpower(caster, slot.spell);
fire_los_attack_spell(slot.spell, splpow, &caster, nullptr, false);
},
nullptr,
MSPELL_LOGIC_NONE,
5,
} },
{ SPELL_TROGS_HAND, {
[](const monster &caster) {
return !caster.has_ench(ENCH_RAISED_MR)
&& !caster.has_ench(ENCH_REGENERATION);
},
[](monster &caster, mon_spell_slot, bolt&) {
const string god = apostrophise(god_name(caster.god));
const string msg = make_stringf(" invokes %s protection!",
god.c_str());
simple_monster_message(caster, msg.c_str(), MSGCH_MONSTER_SPELL);
// Not spell_hd(spell_cast); this is an invocation
const int dur = BASELINE_DELAY
* min(5 + roll_dice(2, (caster.get_hit_dice() * 10) / 3 + 1),
100);
caster.add_ench(mon_enchant(ENCH_RAISED_MR, 0, &caster, dur));
caster.add_ench(mon_enchant(ENCH_REGENERATION, 0, &caster, dur));
dprf("Trog's Hand cast (dur: %d aut)", dur);
},
nullptr,
MSPELL_NO_AUTO_NOISE,
} },
{ SPELL_LEDAS_LIQUEFACTION, {
[](const monster &caster) {
return caster.stand_on_solid_ground() && !liquefied(caster.pos());
},
[](monster &caster, mon_spell_slot, bolt&) {
if (you.can_see(caster))
{
mprf("%s liquefies the ground around %s!",
caster.name(DESC_THE).c_str(),
caster.pronoun(PRONOUN_REFLEXIVE).c_str());
flash_view_delay(UA_MONSTER, BROWN, 80);
}
caster.add_ench(ENCH_LIQUEFYING);
invalidate_agrid(true);
},
nullptr,
MSPELL_NO_AUTO_NOISE,
} },
{ SPELL_FORCEFUL_INVITATION, {
_always_worthwhile,
_branch_summon,
nullptr,
MSPELL_NO_AUTO_NOISE,
} },
{ SPELL_PLANEREND, {
_always_worthwhile,
_branch_summon,
nullptr,
MSPELL_NO_AUTO_NOISE,
} },
{ SPELL_STILL_WINDS, { _should_still_winds, _cast_still_winds } },
{ SPELL_SMITING, { _caster_has_foe, _cast_smiting, } },
{ SPELL_RESONANCE_STRIKE, { _caster_has_foe, _cast_resonance_strike, } },
{ SPELL_FLAY, {
[](const monster &caster) {
const actor* foe = caster.get_foe(); // XXX: check vis?
return foe && (foe->holiness() & MH_NATURAL);
},
_cast_flay,
} },
{ SPELL_PARALYSIS_GAZE, {
_caster_sees_foe,
[](monster &caster, mon_spell_slot, bolt&) {
caster.get_foe()->paralyse(&caster, 2 + random2(3));
},
} },
{ SPELL_DRAINING_GAZE, {
_caster_sees_foe,
[](monster &caster, mon_spell_slot slot, bolt&) {
enchant_actor_with_flavour(caster.get_foe(), &caster,
BEAM_DRAIN_MAGIC,
mons_spellpower(caster, slot.spell));
},
} },
{ SPELL_WATER_ELEMENTALS, { _always_worthwhile, _mons_summon_elemental } },
{ SPELL_EARTH_ELEMENTALS, { _always_worthwhile, _mons_summon_elemental } },
{ SPELL_AIR_ELEMENTALS, { _always_worthwhile, _mons_summon_elemental } },
{ SPELL_FIRE_ELEMENTALS, { _always_worthwhile, _mons_summon_elemental } },
#if TAG_MAJOR_VERSION == 34
{ SPELL_IRON_ELEMENTALS, { _always_worthwhile, _mons_summon_elemental } },
#endif
{ SPELL_HASTE_OTHER, {
_always_worthwhile,
_fire_simple_beam,
_buff_beam_setup(BEAM_HASTE)
} },
{ SPELL_MIGHT_OTHER, {
_always_worthwhile,
_fire_simple_beam,
_buff_beam_setup(BEAM_MIGHT)
} },
{ SPELL_INVISIBILITY_OTHER, {
_always_worthwhile,
_fire_simple_beam,
_buff_beam_setup(BEAM_INVISIBILITY)
} },
{ SPELL_HEAL_OTHER, {
_always_worthwhile,
_fire_simple_beam,
_setup_heal_other,
} },
{ SPELL_LRD, {
_always_worthwhile,
[](monster &caster, mon_spell_slot slot, bolt& pbolt) {
const int splpow = mons_spellpower(caster, slot.spell);
cast_fragmentation(splpow, &caster, pbolt.target, false);
},
_target_beam_setup(_mons_fragment_target),
MSPELL_LOGIC_NONE, 6
} },
{ SPELL_CONJURE_FLAME, {
[](const monster &caster) {
return !(env.level_state & LSTATE_STILL_WINDS);
},
[](monster &caster, mon_spell_slot slot, bolt& pbolt) {
const int splpow = mons_spellpower(caster, slot.spell);
if ((!in_bounds(pbolt.target)
|| conjure_flame(&caster, splpow, pbolt.target, false)
!= SPRET_SUCCESS)
&& you.can_see(caster))
{
canned_msg(MSG_NOTHING_HAPPENS);
}
},
_target_beam_setup(_mons_conjure_flame_pos),
MSPELL_LOGIC_NONE, 6
} },
{ SPELL_AWAKEN_EARTH, {
_always_worthwhile,
[](monster &caster, mon_spell_slot, bolt& pbolt) {
_mons_awaken_earth(caster, pbolt.target);
},
_target_beam_setup(_mons_awaken_earth_target),
} },
{ SPELL_GHOSTLY_SACRIFICE, {
_always_worthwhile,
[](monster &caster, mon_spell_slot slot, bolt& pbolt) {
if (_prepare_ghostly_sacrifice(caster, pbolt))
_fire_direct_explosion(caster, slot, pbolt);
else if (you.can_see(caster))
canned_msg(MSG_NOTHING_HAPPENS);
},
_setup_ghostly_sacrifice_beam,
} },
{ SPELL_SLOW, _hex_logic(SPELL_SLOW) },
{ SPELL_CONFUSE, _hex_logic(SPELL_CONFUSE) },
{ SPELL_BANISHMENT, _hex_logic(SPELL_BANISHMENT) },
{ SPELL_PARALYSE, _hex_logic(SPELL_PARALYSE) },
{ SPELL_PETRIFY, _hex_logic(SPELL_PETRIFY) },
{ SPELL_PAIN, _hex_logic(SPELL_PAIN, [](const monster& caster) {
return _torment_vulnerable(caster.get_foe());
}) },
{ SPELL_DISINTEGRATE, _hex_logic(SPELL_DISINTEGRATE) },
{ SPELL_CORONA, _hex_logic(SPELL_CORONA, [](const monster& caster) {
return !caster.get_foe()->backlit();
}) },
{ SPELL_POLYMORPH, _hex_logic(SPELL_POLYMORPH, [](const monster& caster) {
return !caster.friendly(); // too dangerous to let allies use
}) },
{ SPELL_SLEEP, _hex_logic(SPELL_SLEEP, _foe_can_sleep, 6) },
{ SPELL_HIBERNATION, _hex_logic(SPELL_HIBERNATION, _foe_can_sleep) },
{ SPELL_TELEPORT_OTHER, _hex_logic(SPELL_TELEPORT_OTHER,
_foe_not_teleporting) },
{ SPELL_DIMENSION_ANCHOR, _hex_logic(SPELL_DIMENSION_ANCHOR, nullptr, 6)},
{ SPELL_AGONY, _hex_logic(SPELL_AGONY, [](const monster &caster) {
return _torment_vulnerable(caster.get_foe());
}, 6)
},
{ SPELL_STRIP_RESISTANCE,
_hex_logic(SPELL_STRIP_RESISTANCE, _foe_not_mr_vulnerable, 6)
},
{ SPELL_SENTINEL_MARK, _hex_logic(SPELL_SENTINEL_MARK, nullptr, 16) },
{ SPELL_SAP_MAGIC, {
_always_worthwhile, _fire_simple_beam, _zap_setup(SPELL_SAP_MAGIC),
MSPELL_LOGIC_NONE, 10,
} },
{ SPELL_DRAIN_MAGIC, _hex_logic(SPELL_DRAIN_MAGIC, nullptr, 6) },
{ SPELL_VIRULENCE, _hex_logic(SPELL_VIRULENCE, [](const monster &caster) {
return caster.get_foe()->res_poison(false) < 3;
}, 6) },
{ SPELL_RING_OF_THUNDER, { _should_selfench(ENCH_RING_OF_THUNDER),
[](monster &caster, mon_spell_slot, bolt&) {
caster.add_ench(ENCH_RING_OF_THUNDER);
} } },
{ SPELL_GRASPING_ROOTS, {
[](const monster &caster)
{
const actor* foe = caster.get_foe();
return foe && caster.can_constrict(foe, false);
}, _cast_grasping_roots, } },
};
/// Is the 'monster' actually a proxy for the player?
static bool _caster_is_player_shadow(const monster &mons)
{
return mons.type == MONS_PLAYER_SHADOW;
}
/// Create the appropriate casting logic for a simple conjuration.
static mons_spell_logic _conjuration_logic(spell_type spell)
{
return { _always_worthwhile, _fire_simple_beam, _zap_setup(spell), };
}
/**
* Create the appropriate casting logic for a simple mr-checking hex.
*
* @param spell The hex in question; e.g. SPELL_CORONA.
* @param extra_logic An additional pre-casting condition, beyond the
* normal hex logic.
* @param power_hd_factor If nonzero, how much spellpower the spell has per
* caster HD.
*/
static mons_spell_logic _hex_logic(spell_type spell,
function<bool(const monster&)> extra_logic,
int power_hd_factor)
{
function<bool(const monster&)> worthwhile = nullptr;
if (!extra_logic)
worthwhile = _setup_hex_check(spell);
else
{
worthwhile = [spell, extra_logic](const monster& caster) {
return _worth_hexing(caster, spell) && extra_logic(caster);
};
}
return { worthwhile, _fire_simple_beam, _zap_setup(spell),
MSPELL_LOGIC_NONE, power_hd_factor * ENCH_POW_FACTOR };
}
/**
* Take the given beam and fire it, handling screen-refresh issues in the
* process.
*
* @param caster The monster casting the spell that produced the beam.
* @param pbolt A pre-setup & aimed spell beam. (For e.g. FIREBALL.)
*/
static void _fire_simple_beam(monster &caster, mon_spell_slot, bolt &pbolt)
{
// If a monster just came into view and immediately cast a spell,
// we need to refresh the screen before drawing the beam.
viewwindow();
pbolt.fire();
}
/**
* Take the given explosion and fire it, handling screen-refresh issues in the
* process.
*
* @param caster The monster casting the spell that produced the beam.
* @param pbolt A pre-setup & aimed spell beam. (For e.g. FIRE_STORM.)
*/
static void _fire_direct_explosion(monster &caster, mon_spell_slot, bolt &pbolt)
{
// If a monster just came into view and immediately cast a spell,
// we need to refresh the screen before drawing the beam.
viewwindow();
const actor* foe = caster.get_foe();
const bool need_more = foe && (foe->is_player()
|| you.see_cell(foe->pos()));
pbolt.in_explosion_phase = false;
pbolt.refine_for_explosion();
pbolt.explode(need_more);
}
static bool _caster_sees_foe(const monster &caster)
{
const actor* foe = caster.get_foe();
return foe && caster.can_see(*foe);
}
static bool _foe_can_sleep(const monster &caster)
{
const actor* foe = caster.get_foe();
return foe && foe->can_sleep();
}
static bool _foe_not_teleporting(const monster &caster)
{
const actor* foe = caster.get_foe();
ASSERT(foe);
if (foe->is_player())
return !you.duration[DUR_TELEPORT];
return !foe->as_monster()->has_ench(ENCH_TP);
}
static bool _foe_not_mr_vulnerable(const monster &caster)
{
const actor* foe = caster.get_foe();
ASSERT(foe);
if (foe->is_player())
return !you.duration[DUR_LOWERED_MR];
return !foe->as_monster()->has_ench(ENCH_LOWERED_MR);
}
/**
* Build a function to set up a beam to buff the caster.
*
* @param flavour The flavour to buff a caster with.
* @return A function that sets up a beam to buff its caster with
* the given flavour.
*/
static function<void(bolt&, const monster&, int)>
_selfench_beam_setup(beam_type flavour)
{
return [flavour](bolt &beam, const monster &caster, int)
{
beam.flavour = flavour;
if (!_caster_is_player_shadow(caster))
beam.target = caster.pos();
};
}
/**
* Build a function that tests whether it's worth casting a buff spell that
* applies the given enchantment to the caster.
*/
static function<bool(const monster&)> _should_selfench(enchant_type ench)
{
return [ench](const monster &caster)
{
// keep non-summoned pals with haste from spamming constantly
if (caster.friendly() && !caster.get_foe() && !caster.is_summoned())
return false;
return !caster.has_ench(ench);
};
}
/**
* Build a function that sets up and targets a buffing beam at one of the
* caster's allies. If the function fails to find an ally, the beam will be
* targeted at an out-of-bounds tile to signal failure.
*
* @param flavour The flavour to buff an ally with.
* @return A function that sets up a single-target buff beam.
*/
static function<void(bolt&, const monster&, int)>
_buff_beam_setup(beam_type flavour)
{
return [flavour](bolt &beam, const monster &caster, int)
{
beam.flavour = flavour;
const monster* target = _get_allied_target(caster, beam);
beam.target = target ? target->pos() : coord_def(GXM+1, GYM+1);
};
}
/**
* Build a function to set up a beam with spl-to-zap.
*
* @param spell The spell for which beams will be set up.
* @return A function that sets up a beam to zap the given spell.
*/
static function<void(bolt&, const monster&, int)> _zap_setup(spell_type spell)
{
return [spell](bolt &beam, const monster &, int power)
{
zappy(spell_to_zap(spell), power, true, beam);
};
}
static void _setup_healing_beam(bolt &beam, const monster &caster)
{
beam.damage = dice_def(2, caster.spell_hd(SPELL_MINOR_HEALING) / 2);
beam.flavour = BEAM_HEALING;
}
static void _setup_minor_healing(bolt &beam, const monster &caster, int)
{
_setup_healing_beam(beam, caster);
if (!_caster_is_player_shadow(caster))
beam.target = caster.pos();
}
static void _setup_heal_other(bolt &beam, const monster &caster, int)
{
_setup_healing_beam(beam, caster);
const monster* target = _get_allied_target(caster, beam);
beam.target = target ? target->pos() : coord_def(GXM+1, GYM+1);
}
/**
* Build a function that sets up a fake beam for targeting special spells.
*
* @param targeter A function that finds a target for the given spell.
* Expected to return an out-of-bounds coord on failure.
* @return A function that initializes a fake targetting beam.
*/
static function<void(bolt&, const monster&, int)>
_target_beam_setup(function<coord_def(const monster&)> targeter)
{
return [targeter](bolt& beam, const monster& caster, int)
{
_setup_fake_beam(beam, caster);
// Your shadow keeps your targetting.
if (_caster_is_player_shadow(caster))
return;
beam.target = targeter(caster);
beam.aimed_at_spot = true; // to get noise to work properly
};
}
/// Returns true if a message referring to the player's legs makes sense.
static bool _legs_msg_applicable()
{
return you.species != SP_NAGA && !you.fishtail;
}
// Monster spell of uselessness, just prints a message.
// This spell exists so that some monsters with really strong
// spells (ie orc priest) can be toned down a bit. -- bwr
static void _cast_cantrip(monster &mons, mon_spell_slot slot, bolt& pbolt)
{
// only messaging; don't bother if you can't see anything anyway.
if (!you.see_cell(mons.pos()))
return;
const bool friendly = mons.friendly();
const bool buff_only = !friendly && is_sanctuary(you.pos());
const msg_channel_type channel = (friendly) ? MSGCH_FRIEND_ENCHANT
: MSGCH_MONSTER_ENCHANT;
if (mons.type != MONS_GASTRONOK)
{
const char* msgs[] =
{
" casts a cantrip, but nothing happens.",
" begins to cast a cantrip, but forgets the words!",
" miscasts a cantrip.",
" looks braver for a moment.",
" looks encouraged for a moment.",
" looks satisfied for a moment.",
};
simple_monster_message(mons, RANDOM_ELEMENT(msgs), channel);
return;
}
bool has_mon_foe = !invalid_monster_index(mons.foe);
if (buff_only
|| crawl_state.game_is_arena() && !has_mon_foe
|| friendly && !has_mon_foe
|| coinflip())
{
string slugform = getSpeakString("gastronok_self_buff");
if (!slugform.empty())
{
slugform = replace_all(slugform, "@The_monster@",
mons.name(DESC_THE));
mprf(channel, "%s", slugform.c_str());
}
}
else if (!friendly && !has_mon_foe)
{
mons_cast_noise(&mons, pbolt, slot.spell, slot.flags);
// "Enchant" the player.
const string slugform = getSpeakString("gastronok_debuff");
if (!slugform.empty()
&& (slugform.find("legs") == string::npos
|| _legs_msg_applicable()))
{
mpr(slugform);
}
}
else
{
// "Enchant" another monster.
string slugform = getSpeakString("gastronok_other_buff");
if (!slugform.empty())
{
slugform = replace_all(slugform, "@The_monster@",
mons.get_foe()->name(DESC_THE));
mprf(channel, "%s", slugform.c_str());
}
}
}
static void _cast_injury_mirror(monster &mons, mon_spell_slot slot, bolt&)
{
const string msg
= make_stringf(" offers %s to %s, and fills with unholy energy.",
mons.pronoun(PRONOUN_REFLEXIVE).c_str(),
god_name(mons.god).c_str());
simple_monster_message(mons, msg.c_str(), MSGCH_MONSTER_SPELL);
mons.add_ench(mon_enchant(ENCH_MIRROR_DAMAGE, 0, &mons,
random_range(7, 9) * BASELINE_DELAY));
mons.props[MIRROR_RECAST_KEY].get_int()
= you.elapsed_time + 150 + random2(60);
}
static void _cast_smiting(monster &caster, mon_spell_slot slot, bolt&)
{
const god_type god = _find_god(caster, slot.flags);
actor* foe = caster.get_foe();
ASSERT(foe);
if (foe->is_player())
mprf("%s smites you!", _god_name(god).c_str());
else
simple_monster_message(*foe->as_monster(), " is smitten.");
foe->hurt(&caster, 7 + random2avg(11, 2), BEAM_MISSILE, KILLED_BY_BEAM,
"", "by divine providence");
}
static void _cast_grasping_roots(monster &caster, mon_spell_slot, bolt&)
{
actor* foe = caster.get_foe();
ASSERT(foe);
const int turns = 4 + random2avg(div_rand_round(
mons_spellpower(caster, SPELL_GRASPING_ROOTS), 10), 2);
dprf("Grasping roots turns: %d", turns);
mpr("Roots burst forth from the earth!");
if (foe->is_player())
{
you.increase_duration(DUR_GRASPING_ROOTS, turns);
caster.start_constricting(you);
mprf(MSGCH_WARN, "The grasping roots grab you!");
}
else
{
caster.add_ench(mon_enchant(ENCH_GRASPING_ROOTS, 0, foe,
turns * BASELINE_DELAY));
}
}
/// Is the given full-LOS attack spell worth casting for the given monster?
static bool _los_spell_worthwhile(const monster &mons, spell_type spell)
{
return trace_los_attack_spell(spell, mons_spellpower(mons, spell), &mons)
== SPRET_SUCCESS;
}
/// Set up a fake beam, for noise-generating purposes (?)
static void _setup_fake_beam(bolt& beam, const monster&, int)
{
beam.flavour = BEAM_DEVASTATION;
beam.pierce = true;
// Doesn't take distance into account, but this is just a tracer so
// we'll ignore that. We need some damage on the tracer so the monster
// doesn't think the spell is useless against other monsters.
beam.damage = CONVENIENT_NONZERO_DAMAGE;
beam.range = LOS_RADIUS;
}
/**
* Create a summoned monster.
*
* @param summoner The monster doing the summoning.
* @param mtyp The type of monster to summon.
* @param dur The duration for which the monster should last.
* Not in aut or turns; nonlinear. Sorry!
* @param slot The spell & slot flags.
* @return The summoned creature, if any.
*/
static monster* _summon(const monster &summoner, monster_type mtyp, int dur,
mon_spell_slot slot)
{
const god_type god = _find_god(summoner, slot.flags);
return create_monster(
mgen_data(mtyp, SAME_ATTITUDE((&summoner)), summoner.pos(),
summoner.foe)
.set_summoned(&summoner, dur, slot.spell, god));
}
void init_mons_spells()
{
monster fake_mon;
fake_mon.type = MONS_BLACK_DRACONIAN;
fake_mon.hit_points = 1;
fake_mon.mid = MID_NOBODY; // used indirectly, through _mon_special_name
bolt pbolt;
for (int i = 0; i < NUM_SPELLS; i++)
{
spell_type spell = (spell_type) i;
_valid_mon_spells[i] = false;
if (!is_valid_spell(spell))
continue;
if (
#if TAG_MAJOR_VERSION == 34
spell == SPELL_MELEE ||
#endif
setup_mons_cast(&fake_mon, pbolt, spell, true))
{
_valid_mon_spells[i] = true;
}
}
}
bool is_valid_mon_spell(spell_type spell)
{
if (spell < 0 || spell >= NUM_SPELLS)
return false;
return _valid_mon_spells[spell];
}
/// Is the current spell being cast via player wizmode &z by a dummy mons?
static bool _is_wiz_cast()
{
#ifdef WIZARD
// iffy logic but might be right enough
return crawl_state.prev_cmd == CMD_WIZARD;
#else
return false;
#endif
}
static bool _flavour_benefits_monster(beam_type flavour, monster& monster)
{
switch (flavour)
{
case BEAM_HASTE:
return !monster.has_ench(ENCH_HASTE);
case BEAM_MIGHT:
return !monster.has_ench(ENCH_MIGHT);
case BEAM_INVISIBILITY:
return !monster.has_ench(ENCH_INVIS);
case BEAM_HEALING:
return monster.hit_points != monster.max_hit_points;
case BEAM_AGILITY:
return !monster.has_ench(ENCH_AGILE);
case BEAM_RESISTANCE:
return !monster.has_ench(ENCH_RESISTANCE);
default:
return false;
}
}
/**
* Will the given monster consider buffing the given target? (Are they close
* enough in type, genus, attitude, etc?)
*
* @param caster The monster casting a targeted buff spell.
* @param targ The monster to be buffed.
* @return Whether the monsters are similar enough.
*/
static bool _monster_will_buff(const monster &caster, const monster &targ)
{
if (mons_is_firewood(targ))
return false;
if (!mons_aligned(&targ, &caster))
return false;
// don't buff only temporarily-aligned pals (charmed, hexed)
if (!mons_atts_aligned(caster.temp_attitude(), targ.real_attitude()))
return false;
if (caster.type == MONS_IRONBRAND_CONVOKER || mons_enslaved_soul(caster))
return true; // will buff any ally
if (targ.is_holy() && caster.is_holy())
return true;
const monster_type caster_genus = mons_genus(caster.type);
return mons_genus(targ.type) == caster_genus
|| mons_genus(targ.base_monster) == caster_genus;
}
/// Find an allied monster to cast a beneficial beam spell at.
static monster* _get_allied_target(const monster &caster, bolt &tracer)
{
monster* selected_target = nullptr;
int min_distance = tracer.range;
for (monster_near_iterator targ(&caster, LOS_NO_TRANS); targ; ++targ)
{
if (*targ == &caster
|| !_monster_will_buff(caster, **targ)
|| !_flavour_benefits_monster(tracer.flavour, **targ))
{
continue;
}
// prefer the closest ally we can find (why?)
const int targ_distance = grid_distance(targ->pos(), caster.pos());
if (targ_distance < min_distance)
{
// Make sure we won't hit someone other than we're aiming at.
tracer.target = targ->pos();
fire_tracer(&caster, tracer);
if (!mons_should_fire(tracer)
|| tracer.path_taken.back() != tracer.target)
{
continue;
}
min_distance = targ_distance;
selected_target = *targ;
}
}
return selected_target;
}
// Find an ally of the target to cast a hex at.
// Note that this deliberately does not target the player.
static bool _set_hex_target(monster* caster, bolt& pbolt)
{
monster* selected_target = nullptr;
int min_distance = INT_MAX;
if (!caster->get_foe())
return false;
const actor *foe = caster->get_foe();
for (monster_near_iterator targ(caster, LOS_NO_TRANS); targ; ++targ)
{
if (*targ == caster)
continue;
const int targ_distance = grid_distance(targ->pos(), foe->pos());
bool got_target = false;
if (mons_aligned(*targ, foe)
&& !targ->has_ench(ENCH_CHARM)
&& !targ->has_ench(ENCH_HEXED)
&& !mons_is_firewood(**targ)
&& !_flavour_benefits_monster(pbolt.flavour, **targ))
{
got_target = true;
}
if (got_target && targ_distance < min_distance
&& targ_distance < pbolt.range)
{
// Make sure we won't hit an invalid target with this aim.
pbolt.target = targ->pos();
fire_tracer(caster, pbolt);
if (!mons_should_fire(pbolt)
|| pbolt.path_taken.back() != pbolt.target)
{
continue;
}
min_distance = targ_distance;
selected_target = *targ;
}
}
if (selected_target)
{
pbolt.target = selected_target->pos();
return true;
}
// Didn't find a target.
return false;
}
/**
* What value do monsters multiply their hd with to get spellpower, for the
* given spell?
*
* XXX: everything except SPELL_CONFUSION_GAZE could be trivially exported to
* data.
*
* @param spell The spell in question.
* @param random Whether to randomize powers for weird spells.
* If false, the average value is used.
* @return A multiplier to HD for spellpower.
* Value may exceed 200.
*/
static int _mons_power_hd_factor(spell_type spell, bool random)
{
const mons_spell_logic* logic = map_find(spell_to_logic, spell);
if (logic && logic->power_hd_factor)
return logic->power_hd_factor;
switch (spell)
{
case SPELL_CONFUSION_GAZE:
if (random)
return 5 * (2 + random2(3)) * ENCH_POW_FACTOR;
return 5 * (2 + 1) * ENCH_POW_FACTOR;
case SPELL_CAUSE_FEAR:
return 18 * ENCH_POW_FACTOR;
case SPELL_MESMERISE:
return 10 * ENCH_POW_FACTOR;
case SPELL_SIREN_SONG:
return 9 * ENCH_POW_FACTOR;
case SPELL_MASS_CONFUSION:
return 8 * ENCH_POW_FACTOR;
case SPELL_ABJURATION:
return 20;
case SPELL_OLGREBS_TOXIC_RADIANCE:
return 8;
case SPELL_MONSTROUS_MENAGERIE:
case SPELL_BATTLESPHERE:
case SPELL_SPECTRAL_WEAPON:
case SPELL_IGNITE_POISON:
case SPELL_IOOD:
return 6;
case SPELL_SUMMON_DRAGON:
case SPELL_SUMMON_HYDRA:
return 5;
case SPELL_CHAIN_LIGHTNING:
case SPELL_CHAIN_OF_CHAOS:
return 4;
default:
return 12;
}
}
/**
* What spellpower does a monster with the given spell_hd cast the given spell
* at?
*
* @param spell The spell in question.
* @param hd The spell_hd of the given monster.
* @param random Whether to randomize powers for weird spells.
* If false, the average value is used.
* @return A spellpower value for the spell.
*/
int mons_power_for_hd(spell_type spell, int hd, bool random)
{
const int power = hd * _mons_power_hd_factor(spell, random);
if (spell == SPELL_PAIN)
return max(50 * ENCH_POW_FACTOR, power);
return power;
}
/**
* What power does the given monster cast the given spell with?
*
* @param spell The spell in question.
* @param mons The monster in question.
* @return A spellpower value for the spell.
* May vary from call to call for certain weird spells.
*/
int mons_spellpower(const monster &mons, spell_type spell)
{
return mons_power_for_hd(spell, mons.spell_hd(spell));
}
/**
* What power does the given monster cast the given enchantment with?
*
* @param spell The spell in question.
* @param mons The monster in question.
* @param cap The maximum power of the spell.
* @return A spellpower value for the spell, with ENCH_POW_FACTOR
* removed & capped at maximum spellpower.
*/
static int _ench_power(spell_type spell, const monster &mons)
{
const int cap = 200;
return min(cap, mons_spellpower(mons, spell) / ENCH_POW_FACTOR);
}
static int _mons_spell_range(const monster &mons, spell_type spell)
{
return mons_spell_range_for_hd(spell, mons.spell_hd());
}
/**
* How much range does a monster of the given spell HD have with the given
* spell?
*
* @param spell The spell in question.
* @param hd The monster's effective HD for spellcasting purposes.
* @return -1 if the spell has an undefined range; else its range.
*/
int mons_spell_range_for_hd(spell_type spell, int hd)
{
switch (spell)
{
case SPELL_FLAME_TONGUE:
// HD:1 monsters would get range 2, HD:2 -- 3, other 4, let's
// use the mighty Throw Flame for big ranges.
return min(2, hd);
default:
break;
}
const int power = mons_power_for_hd(spell, hd);
return spell_range(spell, power, false);
}
/**
* What god is responsible for a spell cast by the given monster with the
* given flags?
*
* Relevant for Smite messages & summons, sometimes.
*
* @param mons The monster casting the spell.
* @param flags The slot flags;
* e.g. MON_SPELL_NATURAL | MON_SPELL_NO_SILENT.
* @return The god that is responsible for the spell.
*/
static god_type _find_god(const monster &mons, mon_spell_slot_flags flags)
{
// Permanent wizard summons of Yred should have the same god even
// though they aren't priests. This is so that e.g. the zombies of
// Yred's enslaved souls will properly turn on you if you abandon
// Yred.
if (mons.god == GOD_YREDELEMNUL)
return mons.god;
// If this is a wizard spell, summons won't necessarily have the
// same god. But intrinsic/priestly summons should.
return flags & MON_SPELL_WIZARD ? GOD_NO_GOD : mons.god;
}
static spell_type _random_bolt_spell()
{
return random_choose(SPELL_VENOM_BOLT,
SPELL_BOLT_OF_DRAINING,
SPELL_BOLT_OF_FIRE,
SPELL_LIGHTNING_BOLT,
SPELL_QUICKSILVER_BOLT,
SPELL_CORROSIVE_BOLT);
}
static spell_type _major_destruction_spell()
{
return random_choose(SPELL_BOLT_OF_FIRE,
SPELL_FIREBALL,
SPELL_LIGHTNING_BOLT,
SPELL_STICKY_FLAME,
SPELL_IRON_SHOT,
SPELL_BOLT_OF_DRAINING,
SPELL_ORB_OF_ELECTRICITY);
}
static spell_type _legendary_destruction_spell()
{
return random_choose_weighted(25, SPELL_FIREBALL,
20, SPELL_ICEBLAST,
15, SPELL_GHOSTLY_FIREBALL);
}
// TODO: documentme
// NOTE: usually doesn't set target, but if set, should take precedence
bolt mons_spell_beam(const monster* mons, spell_type spell_cast, int power,
bool check_validity)
{
ASSERT(power > 0);
bolt beam;
// Initialise to some bogus values so we can catch problems.
beam.name = "****";
beam.colour = 255;
beam.hit = -1;
beam.damage = dice_def(1, 0);
beam.ench_power = max(1, power / ENCH_POW_FACTOR); // U G H
beam.glyph = 0;
beam.flavour = BEAM_NONE;
beam.thrower = KILL_MISC;
beam.pierce = false;
beam.is_explosion = false;
beam.attitude = mons_attitude(*mons);
beam.range = _mons_spell_range(*mons, spell_cast);
spell_type real_spell = spell_cast;
if (spell_cast == SPELL_RANDOM_BOLT)
real_spell = _random_bolt_spell();
else if (spell_cast == SPELL_MAJOR_DESTRUCTION)
real_spell = _major_destruction_spell();
else if (spell_cast == SPELL_LEGENDARY_DESTRUCTION)
{
// ones with ranges too small are fixed in setup_mons_cast
real_spell = _legendary_destruction_spell();
}
else if (spell_is_soh_breath(spell_cast))
{
// this will be fixed up later in mons_cast
// XXX: is this necessary?
real_spell = SPELL_FIRE_BREATH;
}
beam.glyph = dchar_glyph(DCHAR_FIRED_ZAP); // default
beam.thrower = KILL_MON_MISSILE;
beam.origin_spell = real_spell;
beam.source_id = mons->mid;
beam.source_name = mons->name(DESC_A, true);
const mons_spell_logic* logic = map_find(spell_to_logic, spell_cast);
if (logic && logic->setup_beam)
logic->setup_beam(beam, *mons, power);
// FIXME: more of these should use the zap_data[] struct from beam.cc!
switch (real_spell)
{
case SPELL_ORB_OF_ELECTRICITY:
beam.foe_ratio = random_range(40, 55); // ...
// fallthrough to other zaps
case SPELL_MAGIC_DART:
case SPELL_THROW_FLAME:
case SPELL_THROW_FROST:
case SPELL_FLAME_TONGUE:
case SPELL_VENOM_BOLT:
case SPELL_POISON_ARROW:
case SPELL_BOLT_OF_MAGMA:
case SPELL_BOLT_OF_FIRE:
case SPELL_BOLT_OF_COLD:
case SPELL_THROW_ICICLE:
case SPELL_SHOCK:
case SPELL_LIGHTNING_BOLT:
case SPELL_FIREBALL:
case SPELL_ICEBLAST:
case SPELL_LEHUDIBS_CRYSTAL_SPEAR:
case SPELL_BOLT_OF_DRAINING:
case SPELL_ISKENDERUNS_MYSTIC_BLAST:
case SPELL_STICKY_FLAME:
case SPELL_STICKY_FLAME_RANGE:
case SPELL_STING:
case SPELL_IRON_SHOT:
case SPELL_STONE_ARROW:
case SPELL_FORCE_LANCE:
case SPELL_CORROSIVE_BOLT:
case SPELL_HIBERNATION:
case SPELL_SLEEP:
case SPELL_DIG:
case SPELL_ENSLAVEMENT:
case SPELL_QUICKSILVER_BOLT:
case SPELL_PRIMAL_WAVE:
case SPELL_BLINKBOLT:
case SPELL_STEAM_BALL:
case SPELL_TELEPORT_OTHER:
case SPELL_SANDBLAST:
case SPELL_HARPOON_SHOT:
zappy(spell_to_zap(real_spell), power, true, beam);
break;
case SPELL_DAZZLING_SPRAY: // special-cased because of a spl-zap hack...
zappy(ZAP_DAZZLING_SPRAY, power, true, beam);
break;
case SPELL_FREEZING_CLOUD: // battlesphere special-case
zappy(ZAP_FREEZING_BLAST, power, true, beam);
break;
case SPELL_DISPEL_UNDEAD:
beam.flavour = BEAM_DISPEL_UNDEAD;
beam.damage = dice_def(3, min(6 + power / 10, 40));
break;
case SPELL_MALMUTATE:
beam.flavour = BEAM_MALMUTATE;
break;
case SPELL_FIRE_STORM:
setup_fire_storm(mons, power / 2, beam);
beam.foe_ratio = random_range(40, 55);
break;
case SPELL_CALL_DOWN_DAMNATION:
beam.aux_source = "damnation";
beam.name = "damnation";
beam.ex_size = 1;
beam.flavour = BEAM_DAMNATION;
beam.is_explosion = true;
beam.colour = LIGHTRED;
beam.aux_source.clear();
beam.is_tracer = false;
beam.hit = 20;
beam.damage = dice_def(3, 15);
break;
case SPELL_NOXIOUS_CLOUD:
beam.name = "noxious blast";
beam.damage = dice_def(1, 0);
beam.colour = GREEN;
beam.flavour = BEAM_MEPHITIC;
beam.hit = 18 + power / 25;
beam.pierce = true;
break;
case SPELL_POISONOUS_CLOUD:
beam.name = "blast of poison";
beam.damage = dice_def(3, 3 + power / 25);
beam.colour = LIGHTGREEN;
beam.flavour = BEAM_POISON;
beam.hit = 18 + power / 25;
beam.pierce = true;
break;
case SPELL_ENERGY_BOLT: // eye of devastation
beam.colour = YELLOW;
beam.name = "bolt of energy";
beam.short_name = "energy";
beam.damage = dice_def(3, 20);
beam.hit = 15 + power / 30;
beam.flavour = BEAM_DEVASTATION; // DEVASTATION is BEAM_MMISSILE
beam.pierce = true; // (except bloodier)
break;
case SPELL_SPIT_POISON:
beam.colour = GREEN;
beam.name = "splash of poison";
beam.damage = dice_def(1, 4 + power / 10);
beam.hit = 16 + power / 20;
beam.flavour = BEAM_POISON;
break;
case SPELL_SPIT_ACID:
beam.colour = YELLOW;
beam.name = "splash of acid";
beam.damage = dice_def(3, 7);
// Natural ability, so don't use spell_hd here
beam.hit = 20 + (3 * mons->get_hit_dice());
beam.flavour = BEAM_ACID;
break;
case SPELL_ACID_SPLASH: // yellow draconian
beam.colour = YELLOW;
beam.name = "glob of acid";
beam.damage = dice_def(3, 7);
// Natural ability, so don't use spell_hd here
beam.hit = 20 + (3 * mons->get_hit_dice());
beam.flavour = BEAM_ACID;
break;
case SPELL_MEPHITIC_CLOUD:
beam.name = "stinking cloud";
beam.damage = dice_def(1, 0);
beam.colour = GREEN;
beam.flavour = BEAM_MEPHITIC;
beam.hit = 14 + power / 30;
beam.is_explosion = true;
break;
case SPELL_MIASMA_BREATH: // death drake
beam.name = "foul vapour";
beam.damage = dice_def(3, 5 + power / 24);
beam.colour = DARKGREY;
beam.flavour = BEAM_MIASMA;
beam.hit = 17 + power / 20;
beam.pierce = true;
break;
case SPELL_HURL_DAMNATION: // fiend's damnation
beam.name = "damnation";
beam.aux_source = "damnation";
beam.colour = LIGHTRED;
beam.damage = dice_def(3, 20);
beam.hit = 24;
beam.flavour = BEAM_DAMNATION;
beam.pierce = true; // needed?
beam.is_explosion = true;
break;
case SPELL_METAL_SPLINTERS:
beam.name = "spray of metal splinters";
beam.short_name = "metal splinters";
beam.damage = dice_def(3, 20 + power / 20);
beam.colour = CYAN;
beam.flavour = BEAM_FRAG;
beam.hit = 19 + power / 30;
beam.pierce = true;
break;
case SPELL_BLINK_OTHER:
beam.flavour = BEAM_BLINK;
break;
case SPELL_BLINK_OTHER_CLOSE:
beam.flavour = BEAM_BLINK_CLOSE;
break;
case SPELL_FIRE_BREATH:
case SPELL_SEARING_BREATH:
beam.name = "blast of flame";
beam.aux_source = "blast of fiery breath";
beam.short_name = "flames";
beam.damage = dice_def(3, (mons->get_hit_dice() * 2));
beam.colour = RED;
beam.hit = 30;
beam.flavour = BEAM_FIRE;
beam.pierce = true;
if (real_spell == SPELL_SEARING_BREATH)
{
beam.name = "searing blast";
beam.aux_source = "blast of searing breath";
if (mons->type != MONS_XTAHUA)
beam.damage.size = 65 * beam.damage.size / 100;
}
break;
case SPELL_CHAOS_BREATH:
beam.name = "blast of chaos";
beam.aux_source = "blast of chaotic breath";
beam.damage = dice_def(1, 3 * mons->get_hit_dice() / 2);
beam.colour = ETC_RANDOM;
beam.hit = 30;
beam.flavour = BEAM_CHAOS;
beam.pierce = true;
break;
case SPELL_CHILLING_BREATH:
case SPELL_COLD_BREATH:
beam.name = "blast of cold";
beam.aux_source = "blast of icy breath";
beam.short_name = "frost";
beam.damage = dice_def(3, (mons->get_hit_dice() * 2));
beam.colour = WHITE;
beam.hit = 30;
beam.flavour = BEAM_COLD;
beam.pierce = true;
if (real_spell == SPELL_CHILLING_BREATH)
{
beam.name = "chilling blast";
beam.aux_source = "blast of chilling breath";
beam.short_name = "frost";
beam.damage.size = 65 * beam.damage.size / 100;
}
break;
case SPELL_HOLY_BREATH:
beam.name = "blast of cleansing flame";
beam.damage = dice_def(3, mons->get_hit_dice());
beam.colour = ETC_HOLY;
beam.flavour = BEAM_HOLY;
beam.hit = 18 + power / 25;
beam.pierce = true;
break;
case SPELL_PORKALATOR:
beam.name = "porkalator";
beam.glyph = 0;
beam.flavour = BEAM_PORKALATOR;
beam.thrower = KILL_MON_MISSILE;
break;
case SPELL_IOOD: // tracer only
case SPELL_PORTAL_PROJECTILE: // for noise generation purposes
case SPELL_GLACIATE: // ditto
case SPELL_CLOUD_CONE: // ditto
case SPELL_SCATTERSHOT: // ditto
_setup_fake_beam(beam, *mons);
break;
case SPELL_PETRIFYING_CLOUD:
beam.name = "blast of calcifying dust";
beam.colour = WHITE;
beam.damage = dice_def(2, 6);
beam.hit = AUTOMATIC_HIT;
beam.flavour = BEAM_PETRIFYING_CLOUD;
beam.foe_ratio = 30;
beam.pierce = true;
break;
#if TAG_MAJOR_VERSION == 34
case SPELL_HOLY_LIGHT:
case SPELL_SILVER_BLAST:
beam.name = "beam of golden light";
beam.damage = dice_def(3, 8 + power / 11);
beam.colour = ETC_HOLY;
beam.flavour = BEAM_HOLY;
beam.hit = 17 + power / 25;
beam.pierce = true;
break;
#endif
case SPELL_ENSNARE:
beam.name = "stream of webbing";
beam.colour = WHITE;
beam.glyph = dchar_glyph(DCHAR_FIRED_MISSILE);
beam.flavour = BEAM_ENSNARE;
beam.hit = 22 + power / 20;
break;
case SPELL_SPECTRAL_CLOUD:
beam.name = "spectral mist";
beam.damage = dice_def(0, 1);
beam.colour = CYAN;
beam.flavour = BEAM_MMISSILE;
beam.hit = AUTOMATIC_HIT;
beam.pierce = true;
break;
case SPELL_GHOSTLY_FIREBALL:
_setup_ghostly_beam(beam, power, 3);
break;
case SPELL_DIMENSION_ANCHOR:
beam.flavour = BEAM_DIMENSION_ANCHOR;
break;
case SPELL_THORN_VOLLEY:
beam.colour = BROWN;
beam.name = "volley of thorns";
beam.damage = dice_def(3, 5 + (power / 13));
beam.hit = 20 + power / 15;
beam.flavour = BEAM_MMISSILE;
break;
// XXX: This seems needed to give proper spellcasting messages, even though
// damage is done via another means
case SPELL_FREEZE:
beam.flavour = BEAM_COLD;
break;
case SPELL_MALIGN_OFFERING:
beam.flavour = BEAM_MALIGN_OFFERING;
beam.damage = dice_def(2, 7 + (power / 13));
break;
case SPELL_FLASH_FREEZE:
beam.name = "flash freeze";
beam.damage = dice_def(3, 7 + (power / 12));
beam.colour = WHITE;
beam.flavour = BEAM_ICE;
beam.hit = 5 + power / 3;
break;
case SPELL_SHADOW_BOLT:
beam.name = "shadow bolt";
beam.pierce = true;
// deliberate fall-through
case SPELL_SHADOW_SHARD:
if (real_spell == SPELL_SHADOW_SHARD)
beam.name = "shadow shard";
beam.damage = dice_def(3, 8 + power / 11);
beam.colour = MAGENTA;
beam.flavour = BEAM_MMISSILE;
beam.hit = 17 + power / 25;
break;
case SPELL_CRYSTAL_BOLT:
beam.name = "crystal bolt";
beam.damage = dice_def(3, 8 + power / 11);
beam.colour = GREEN;
beam.flavour = BEAM_CRYSTAL;
beam.hit = 17 + power / 25;
beam.pierce = true;
break;
case SPELL_SPIT_LAVA:
beam.name = "glob of lava";
beam.damage = dice_def(3, 10);
beam.hit = 20;
beam.colour = RED;
beam.glyph = dchar_glyph(DCHAR_FIRED_ZAP);
beam.flavour = BEAM_LAVA;
break;
case SPELL_ELECTRICAL_BOLT:
beam.name = "bolt of electricity";
beam.damage = dice_def(3, 3 + mons->get_hit_dice());
beam.hit = 35;
beam.colour = LIGHTCYAN;
beam.glyph = dchar_glyph(DCHAR_FIRED_ZAP);
beam.flavour = BEAM_ELECTRICITY;
beam.pierce = true;
break;
case SPELL_FLAMING_CLOUD:
beam.name = "blast of flame";
beam.aux_source = "blast of fiery breath";
beam.short_name = "flames";
beam.damage = dice_def(1, 3 * mons->get_hit_dice() / 2);
beam.colour = RED;
beam.hit = 30;
beam.flavour = BEAM_FIRE;
beam.pierce = true;
break;
case SPELL_THROW_BARBS:
beam.name = "volley of spikes";
beam.aux_source = "volley of spikes";
beam.hit_verb = "skewers";
beam.hit = 27;
beam.damage = dice_def(2, 13);
beam.glyph = dchar_glyph(DCHAR_FIRED_MISSILE);
beam.colour = LIGHTGREY;
beam.flavour = BEAM_MISSILE;
break;
case SPELL_DEATH_RATTLE:
beam.name = "vile air";
beam.colour = DARKGREY;
beam.damage = dice_def(2, 4);
beam.hit = AUTOMATIC_HIT;
beam.flavour = BEAM_DEATH_RATTLE;
beam.foe_ratio = 30;
beam.pierce = true;
break;
// Special behavior handled in _mons_upheaval
// Hack so beam.cc allows us to correctly use that function
case SPELL_UPHEAVAL:
beam.flavour = BEAM_RANDOM;
beam.damage = dice_def(3, 24);
beam.hit = AUTOMATIC_HIT;
beam.glyph = dchar_glyph(DCHAR_EXPLOSION);
beam.ex_size = 2;
break;
default:
if (logic && logic->setup_beam) // already setup
break;
if (check_validity)
{
beam.flavour = NUM_BEAMS;
return beam;
}
if (!is_valid_spell(real_spell))
{
die("Invalid spell #%d cast by %s", (int) real_spell,
mons->name(DESC_PLAIN, true).c_str());
}
die("Unknown monster spell '%s' cast by %s",
spell_title(real_spell),
mons->name(DESC_PLAIN, true).c_str());
}
if (beam.is_enchantment())
{
beam.hit = AUTOMATIC_HIT;
beam.glyph = 0;
beam.name = "";
}
return beam;
}
// Set up bolt structure for monster spell casting.
bool setup_mons_cast(const monster* mons, bolt &pbolt, spell_type spell_cast,
bool check_validity)
{
// always set these -- used by things other than fire_beam()
pbolt.source_id = mons->mid;
// Convenience for the hapless innocent who assumes that this
// damn function does all possible setup. [ds]
if (pbolt.target.origin())
pbolt.target = mons->target;
// Set bolt type and range.
if (spell_is_direct_explosion(spell_cast))
{
pbolt.range = 0;
pbolt.glyph = 0;
}
// The below are no-ops since they don't involve fire_tracer or beams.
switch (spell_cast)
{
case SPELL_STICKS_TO_SNAKES:
case SPELL_SUMMON_SMALL_MAMMAL:
case SPELL_VAMPIRIC_DRAINING:
case SPELL_MAJOR_HEALING:
#if TAG_MAJOR_VERSION == 34
case SPELL_VAMPIRE_SUMMON:
#endif
case SPELL_SHADOW_CREATURES: // summon anything appropriate for level
#if TAG_MAJOR_VERSION == 34
case SPELL_FAKE_RAKSHASA_SUMMON:
#endif
case SPELL_FAKE_MARA_SUMMON:
case SPELL_SUMMON_ILLUSION:
case SPELL_SUMMON_DEMON:
case SPELL_MONSTROUS_MENAGERIE:
#if TAG_MAJOR_VERSION == 34
case SPELL_ANIMATE_DEAD:
#endif
case SPELL_TWISTED_RESURRECTION:
#if TAG_MAJOR_VERSION == 34
case SPELL_CIGOTUVIS_EMBRACE:
case SPELL_SIMULACRUM:
#endif
case SPELL_CALL_IMP:
case SPELL_SUMMON_MINOR_DEMON:
#if TAG_MAJOR_VERSION == 34
case SPELL_SUMMON_SCORPIONS:
case SPELL_SUMMON_SWARM:
#endif
case SPELL_SUMMON_UFETUBUS:
case SPELL_SUMMON_HELL_BEAST: // Geryon
case SPELL_SUMMON_UNDEAD:
case SPELL_SUMMON_ICE_BEAST:
case SPELL_SUMMON_MUSHROOMS:
case SPELL_CONJURE_BALL_LIGHTNING:
case SPELL_SUMMON_DRAKES:
case SPELL_SUMMON_HORRIBLE_THINGS:
case SPELL_MALIGN_GATEWAY:
case SPELL_SYMBOL_OF_TORMENT:
case SPELL_CAUSE_FEAR:
case SPELL_MESMERISE:
case SPELL_SUMMON_GREATER_DEMON:
case SPELL_BROTHERS_IN_ARMS:
case SPELL_BERSERKER_RAGE:
case SPELL_SPRINT:
#if TAG_MAJOR_VERSION == 34
case SPELL_SWIFTNESS:
case SPELL_STONESKIN:
case SPELL_SUMMON_ELEMENTAL:
#endif
case SPELL_CREATE_TENTACLES:
case SPELL_BLINK:
case SPELL_CONTROLLED_BLINK:
case SPELL_BLINK_RANGE:
case SPELL_BLINK_AWAY:
case SPELL_BLINK_CLOSE:
case SPELL_TOMB_OF_DOROKLOHE:
case SPELL_CHAIN_LIGHTNING: // the only user is reckless
case SPELL_SUMMON_EYEBALLS:
case SPELL_SUMMON_BUTTERFLIES:
#if TAG_MAJOR_VERSION == 34
case SPELL_MISLEAD:
#endif
case SPELL_CALL_TIDE:
case SPELL_INK_CLOUD:
case SPELL_SILENCE:
case SPELL_AWAKEN_FOREST:
case SPELL_DRUIDS_CALL:
case SPELL_SUMMON_HOLIES:
case SPELL_REGENERATION:
case SPELL_CORPSE_ROT:
case SPELL_SUMMON_DRAGON:
case SPELL_SUMMON_HYDRA:
case SPELL_FIRE_SUMMON:
#if TAG_MAJOR_VERSION == 34
case SPELL_DEATHS_DOOR:
#endif
case SPELL_OZOCUBUS_ARMOUR:
case SPELL_OLGREBS_TOXIC_RADIANCE:
case SPELL_SHATTER:
#if TAG_MAJOR_VERSION == 34
case SPELL_FRENZY:
case SPELL_SUMMON_TWISTER:
#endif
case SPELL_BATTLESPHERE:
case SPELL_SPECTRAL_WEAPON:
case SPELL_WORD_OF_RECALL:
case SPELL_INJURY_BOND:
case SPELL_CALL_LOST_SOUL:
case SPELL_BLINK_ALLIES_ENCIRCLE:
case SPELL_MASS_CONFUSION:
case SPELL_ENGLACIATION:
#if TAG_MAJOR_VERSION == 34
case SPELL_SHAFT_SELF:
#endif
case SPELL_AWAKEN_VINES:
#if TAG_MAJOR_VERSION == 34
case SPELL_CONTROL_WINDS:
#endif
case SPELL_WALL_OF_BRAMBLES:
#if TAG_MAJOR_VERSION == 34
case SPELL_HASTE_PLANTS:
#endif
case SPELL_WIND_BLAST:
case SPELL_SUMMON_VERMIN:
case SPELL_TORNADO:
case SPELL_VORTEX:
case SPELL_DISCHARGE:
case SPELL_IGNITE_POISON:
#if TAG_MAJOR_VERSION == 34
case SPELL_EPHEMERAL_INFUSION:
#endif
case SPELL_BLACK_MARK:
#if TAG_MAJOR_VERSION == 34
case SPELL_GRAND_AVATAR:
case SPELL_REARRANGE_PIECES:
#endif
case SPELL_BLINK_ALLIES_AWAY:
case SPELL_SHROUD_OF_GOLUBRIA:
case SPELL_PHANTOM_MIRROR:
case SPELL_SUMMON_MANA_VIPER:
case SPELL_SUMMON_EMPEROR_SCORPIONS:
case SPELL_BATTLECRY:
case SPELL_WARNING_CRY:
case SPELL_SEAL_DOORS:
case SPELL_BERSERK_OTHER:
case SPELL_SPELLFORGED_SERVITOR:
case SPELL_THROW:
case SPELL_THROW_ALLY:
case SPELL_CORRUPTING_PULSE:
case SPELL_SIREN_SONG:
case SPELL_AVATAR_SONG:
case SPELL_REPEL_MISSILES:
case SPELL_DEFLECT_MISSILES:
case SPELL_SUMMON_SCARABS:
#if TAG_MAJOR_VERSION == 34
case SPELL_HUNTING_CRY:
case SPELL_CONDENSATION_SHIELD:
case SPELL_CONTROL_UNDEAD:
#endif
case SPELL_CLEANSING_FLAME:
case SPELL_DRAINING_GAZE:
case SPELL_CONFUSION_GAZE:
case SPELL_HAUNT:
case SPELL_SUMMON_SPECTRAL_ORCS:
case SPELL_BRAIN_FEED:
case SPELL_HOLY_FLAMES:
case SPELL_CALL_OF_CHAOS:
case SPELL_AIRSTRIKE:
case SPELL_WATERSTRIKE:
#if TAG_MAJOR_VERSION == 34
case SPELL_CHANT_FIRE_STORM:
#endif
case SPELL_GRAVITAS:
case SPELL_ENTROPIC_WEAVE:
case SPELL_SUMMON_EXECUTIONERS:
case SPELL_DOOM_HOWL:
case SPELL_AURA_OF_BRILLIANCE:
case SPELL_GREATER_SERVANT_MAKHLEB:
case SPELL_BIND_SOULS:
case SPELL_DREAM_DUST:
pbolt.range = 0;
pbolt.glyph = 0;
return true;
default:
{
const mons_spell_logic* logic = map_find(spell_to_logic, spell_cast);
if (logic && logic->setup_beam == nullptr)
{
pbolt.range = 0;
pbolt.glyph = 0;
return true;
}
if (check_validity)
{
bolt beam = mons_spell_beam(mons, spell_cast, 1, true);
return beam.flavour != NUM_BEAMS;
}
break;
}
}
const int power = mons_spellpower(*mons, spell_cast);
bolt theBeam = mons_spell_beam(mons, spell_cast, power);
bolt_parent_init(theBeam, pbolt);
if (!theBeam.target.origin())
pbolt.target = theBeam.target;
pbolt.source = mons->pos();
pbolt.is_tracer = false;
if (!pbolt.is_enchantment())
pbolt.aux_source = pbolt.name;
else
pbolt.aux_source.clear();
return true;
}
/// Can 'binder' bind 'bound's soul with BIND_SOUL?
static bool _mons_can_bind_soul(monster* binder, monster* bound)
{
return bound->holiness() & MH_NATURAL
&& mons_can_be_zombified(*bound)
&& !bound->has_ench(ENCH_BOUND_SOUL)
&& mons_aligned(binder, bound);
}
// Function should return false if friendlies shouldn't animate any dead.
// Currently, this only happens if the player is in the middle of butchering
// a corpse (infuriating), or if they are less than satiated. Only applies
// to friendly corpse animators. {due}
static bool _animate_dead_okay(spell_type spell)
{
// It's always okay in the arena.
if (crawl_state.game_is_arena())
return true;
if (you_are_delayed() && current_delay()->is_butcher()
|| is_vampire_feeding()
|| you.hunger_state < HS_SATIATED
&& you.get_base_mutation_level(MUT_HERBIVOROUS) == 0
|| god_hates_spell(spell, you.religion)
|| will_have_passive(passive_t::convert_orcs))
{
return false;
}
return true;
}
// Returns true if the spell is something you wouldn't want done if
// you had a friendly target... only returns a meaningful value for
// non-beam spells.
static bool _ms_direct_nasty(spell_type monspell)
{
return !(get_spell_flags(monspell) & SPFLAG_UTILITY
|| spell_typematch(monspell, SPTYP_SUMMONING));
}
// Checks if the foe *appears* to be immune to negative energy. We
// can't just use foe->res_negative_energy(), because that'll mean
// monsters will just "know" whether a player is fully life-protected.
static bool _foe_should_res_negative_energy(const actor* foe)
{
if (foe->is_player())
{
switch (you.undead_state())
{
case US_ALIVE:
// Demonspawn are not demons, and statue form grants only
// partial resistance.
return false;
case US_SEMI_UNDEAD:
// Non-bloodless vampires do not appear immune.
return you.hunger_state <= HS_STARVING;
default:
return true;
}
}
return !(foe->holiness() & MH_NATURAL);
}
static bool _valid_blink_ally(const monster* caster, const monster* target)
{
return mons_aligned(caster, target) && caster != target
&& !target->no_tele(true, false, true);
}
static bool _valid_encircle_ally(const monster* caster, const monster* target,
const coord_def foepos)
{
return _valid_blink_ally(caster, target)
&& target->pos().distance_from(foepos) > 1;
}
static bool _valid_blink_away_ally(const monster* caster, const monster* target,
const coord_def foepos)
{
return _valid_blink_ally(caster, target)
&& target->pos().distance_from(foepos) < 3;
}
static bool _valid_druids_call_target(const monster* caller, const monster* callee)
{
return mons_aligned(caller, callee) && mons_is_beast(callee->type)
&& callee->get_experience_level() <= 20
&& !callee->is_shapeshifter()
&& !caller->see_cell(callee->pos())
&& mons_habitat(*callee) != HT_WATER
&& mons_habitat(*callee) != HT_LAVA
&& !callee->is_travelling();
}
static bool _mirrorable(const monster* agent, const monster* mon)
{
return mon != agent
&& mons_aligned(mon, agent)
&& !mon->is_stationary()
&& !mon->is_summoned()
&& !mons_is_conjured(mon->type)
&& !mons_is_unique(mon->type);
}
static bool _valid_aura_of_brilliance_ally(const monster* caster,
const monster* target)
{
return mons_aligned(caster, target) && caster != target
&& target->is_actual_spellcaster();
}
/**
* Print the message that the player sees after a battlecry goes off.
*
* @param chief The monster letting out the battlecry.
* @param seen_affected The affected monsters that are visible to the
* player.
*/
static void _print_battlecry_announcement(const monster& chief,
vector<monster*> &seen_affected)
{
// Disabling detailed frenzy announcement because it's so spammy.
const msg_channel_type channel = chief.friendly() ? MSGCH_MONSTER_ENCHANT
: MSGCH_FRIEND_ENCHANT;
if (seen_affected.size() == 1)
{
mprf(channel, "%s goes into a battle-frenzy!",
seen_affected[0]->name(DESC_THE).c_str());
return;
}
// refer to the group by the most specific name possible. If they're all
// one monster type; use that name; otherwise, use the genus name (since
// we restrict this by genus).
// Note: If we stop restricting by genus, use "foo's allies" instead.
monster_type first_type = seen_affected[0]->type;
const bool generic = any_of(
begin(seen_affected), end(seen_affected),
[=](const monster *m)
{ return m->type != first_type; });
monster_type group_type = generic ? mons_genus(chief.type) : first_type;
const string ally_desc
= pluralise_monster(mons_type_name(group_type, DESC_PLAIN));
mprf(channel, "%s %s go into a battle-frenzy!",
chief.friendly() ? "Your" : "The", ally_desc.c_str());
}
/**
* Let loose a mighty battlecry, inspiring & strengthening nearby foes!
*
* @param chief The monster letting out the battlecry.
* @param check_only Whether to perform a 'dry run', only checking whether
* any monsters are potentially affected.
* @return Whether any monsters are (or would be) affected.
*/
static bool _battle_cry(const monster& chief, bool check_only = false)
{
const actor *foe = chief.get_foe();
// Only let loose a battlecry if you have a valid target.
if (!foe
|| foe->is_player() && chief.friendly()
|| !chief.see_cell_no_trans(foe->pos()))
{
return false;
}
// Don't try to make noise when silent.
if (chief.is_silenced())
return false;
int affected = 0;
vector<monster* > seen_affected;
for (monster_near_iterator mi(chief.pos(), LOS_NO_TRANS); mi; ++mi)
{
const monster *mons = *mi;
// can't buff yourself
if (mons == &chief)
continue;
// only buff allies
if (!mons_aligned(&chief, mons))
continue;
// no buffing confused/paralysed mons
if (mons->berserk_or_insane()
|| mons->confused()
|| mons->cannot_move())
{
continue;
}
// already buffed
if (mons->has_ench(ENCH_MIGHT))
continue;
// invalid battlecry target (wrong genus)
if (mons_genus(mons->type) != mons_genus(chief.type))
continue;
if (check_only)
return true; // just need to check
const int dur = random_range(12, 20) * speed_to_duration(mi->speed);
mi->add_ench(mon_enchant(ENCH_MIGHT, 1, &chief, dur));
affected++;
if (you.can_see(**mi))
seen_affected.push_back(*mi);
if (mi->asleep())
behaviour_event(*mi, ME_DISTURB, 0, chief.pos());
}
if (affected == 0)
return false;
// The yell happens whether you happen to see it or not.
noisy(LOS_DEFAULT_RANGE, chief.pos(), chief.mid);
if (!seen_affected.empty())
_print_battlecry_announcement(chief, seen_affected);
return true;
}
/**
* Call upon the powers of chaos, applying mostly positive effects to nearby
* allies!
*
* @param mons The monster carrying out the call of chaos.
* @param check_only Whether to perform a 'dry run', only checking whether
* any monsters are potentially affected.
* @return Whether any monsters are (or would be) affected.
*/
static bool _mons_call_of_chaos(const monster& mon, bool check_only = false)
{
const actor *foe = mon.get_foe();
if (!foe
|| foe->is_player() && mon.friendly()
|| !mon.see_cell_no_trans(foe->pos()))
{
return false;
}
int affected = 0;
vector<monster* > seen_affected;
for (monster_near_iterator mi(mon.pos(), LOS_NO_TRANS); mi; ++mi)
{
const monster *mons = *mi;
// can't buff yourself
if (mons == &mon)
continue;
// only buff allies
if (!mons_aligned(&mon, mons))
continue;
if (mons_is_firewood(*mons))
continue;
if (check_only)
return true; // just need to check
if (mi->asleep())
behaviour_event(*mi, ME_DISTURB, 0, mon.pos());
beam_type flavour = random_choose_weighted(150, BEAM_HASTE,
150, BEAM_MIGHT,
150, BEAM_BERSERK,
150, BEAM_AGILITY,
150, BEAM_RESISTANCE,
150, BEAM_BLINK_CLOSE,
15, BEAM_BLINK,
15, BEAM_SLOW,
15, BEAM_VULNERABILITY,
15, BEAM_MALMUTATE,
15, BEAM_POLYMORPH,
15, BEAM_INNER_FLAME);
enchant_actor_with_flavour(*mi,
flavour == BEAM_BLINK_CLOSE
? foe
: &mon,
flavour);
affected++;
if (you.can_see(**mi))
seen_affected.push_back(*mi);
}
if (affected == 0)
return false;
return true;
}
static void _set_door(set<coord_def> door, dungeon_feature_type feat)
{
for (const auto &dc : door)
{
grd(dc) = feat;
set_terrain_changed(dc);
}
}
static int _tension_door_closed(set<coord_def> door,
dungeon_feature_type old_feat)
{
// this unwind is a bit heavy, but because out-of-los clouds dissipate
// instantly, they can be wiped out by these door tests.
unwind_var<map<coord_def, cloud_struct>> cloud_state(env.cloud);
_set_door(door, DNGN_CLOSED_DOOR);
const int new_tension = get_tension(GOD_NO_GOD);
_set_door(door, old_feat);
return new_tension;
}
/**
* Can any actors and items be pushed out of a doorway? An actor can be pushed
* for purposes of this check if there is a habitable target location and the
* actor is either the player or non-hostile. Items can be moved if there is
* any free space.
*
* @param door the door position
*
* @return true if any actors and items can be pushed out of the door.
*/
static bool _can_force_door_shut(const coord_def& door)
{
if (grd(door) != DNGN_OPEN_DOOR)
return false;
set<coord_def> all_door;
find_connected_identical(door, all_door);
auto veto_spots = vector<coord_def>(all_door.begin(), all_door.end());
auto door_spots = veto_spots;
for (const auto &dc : all_door)
{
// Only attempt to push players and non-hostile monsters out of
// doorways
actor* act = actor_at(dc);
if (act)
{
if (act->is_player()
|| act->is_monster()
&& act->as_monster()->attitude != ATT_HOSTILE)
{
vector<coord_def> targets = get_push_spaces(dc, true, &veto_spots);
if (targets.empty())
return false;
veto_spots.push_back(targets.front());
}
else
return false;
}
// If there are items in the way, see if there's room to push them
// out of the way. Having push space for an actor doesn't guarantee
// push space for items (e.g. with a flying actor over lava).
if (igrd(dc) != NON_ITEM)
{
if (!has_push_spaces(dc, false, &door_spots))
return false;
}
}
// Didn't find any actors or items we couldn't displace
return true;
}
/**
* Get push spaces for an actor that maximize tension. If there are any push
* spaces at all, this function is guaranteed to return something.
*
* @param pos the position of the actor
* @param excluded a set of pre-excluded spots
*
* @return a vector of coordinates, empty if there are no push spaces at all.
*/
static vector<coord_def> _get_push_spaces_max_tension(const coord_def& pos,
const vector<coord_def>* excluded)
{
vector<coord_def> possible_spaces = get_push_spaces(pos, true, excluded);
if (possible_spaces.empty())
return possible_spaces;
vector<coord_def> best;
int max_tension = -1;
actor *act = actor_at(pos);
ASSERT(act);
for (auto c : possible_spaces)
{
set<coord_def> all_door;
find_connected_identical(pos, all_door);
dungeon_feature_type old_feat = grd(pos);
act->move_to_pos(c);
int new_tension = _tension_door_closed(all_door, old_feat);
act->move_to_pos(pos);
if (new_tension == max_tension)
best.push_back(c);
else if (new_tension > max_tension)
{
max_tension = new_tension;
best.clear();
best.push_back(c);
}
}
return best;
}
/**
* Would forcing a door shut (possibly pushing the player) lower tension too
* much?
*
* @param door the door to check
*
* @return true iff forcing the door shut won't lower tension by more than 1/3.
*/
static bool _should_force_door_shut(const coord_def& door)
{
if (grd(door) != DNGN_OPEN_DOOR)
return false;
dungeon_feature_type old_feat = grd(door);
set<coord_def> all_door;
find_connected_identical(door, all_door);
auto veto_spots = vector<coord_def>(all_door.begin(), all_door.end());
bool player_in_door = false;
for (const auto &dc : all_door)
{
if (you.pos() == dc)
{
player_in_door = true;
break;
}
}
const int cur_tension = get_tension(GOD_NO_GOD);
coord_def oldpos = you.pos();
if (player_in_door)
{
coord_def newpos =
_get_push_spaces_max_tension(you.pos(), &veto_spots).front();
you.move_to_pos(newpos);
}
const int new_tension = _tension_door_closed(all_door, old_feat);
if (player_in_door)
you.move_to_pos(oldpos);
// If closing the door would reduce player tension by too much, probably
// it is scarier for the player to leave it open and thus it should be left
// open
// Currently won't allow tension to be lowered by more than 33%
return ((cur_tension - new_tension) * 3) <= cur_tension;
}
static bool _seal_doors_and_stairs(const monster* warden,
bool check_only = false)
{
ASSERT(warden);
int num_closed = 0;
int seal_duration = 80 + random2(80);
bool player_pushed = false;
bool had_effect = false;
// Friendly wardens are already excluded by _ms_waste_of_time()
if (!warden->can_see(you) || warden->foe != MHITYOU)
return false;
// Greedy iteration through doors/stairs that you can see.
for (radius_iterator ri(you.pos(), LOS_RADIUS, C_SQUARE);
ri; ++ri)
{
if (grd(*ri) == DNGN_OPEN_DOOR)
{
if (!_can_force_door_shut(*ri))
continue;
// If it's scarier to leave this door open, do so
if (!_should_force_door_shut(*ri))
continue;
if (check_only)
return true;
set<coord_def> all_door;
find_connected_identical(*ri, all_door);
auto veto_spots = vector<coord_def>(all_door.begin(), all_door.end());
auto door_spots = veto_spots;
for (const auto &dc : all_door)
{
// If there are things in the way, push them aside
// This is only reached for the player or non-hostile actors
actor* act = actor_at(dc);
if (act)
{
vector<coord_def> targets =
_get_push_spaces_max_tension(dc, &veto_spots);
// at this point, _can_force_door_shut should have
// indicated that the door can be shut.
ASSERTM(!targets.empty(), "No push space from (%d,%d)",
dc.x, dc.y);
coord_def newpos = targets.front();
actor_at(dc)->move_to_pos(newpos);
if (act->is_player())
{
stop_delay(true);
player_pushed = true;
}
veto_spots.push_back(newpos);
}
push_items_from(dc, &door_spots);
}
// Close the door
bool seen = false;
vector<coord_def> excludes;
for (const auto &dc : all_door)
{
grd(dc) = DNGN_CLOSED_DOOR;
set_terrain_changed(dc);
dungeon_events.fire_position_event(DET_DOOR_CLOSED, dc);
if (is_excluded(dc))
excludes.push_back(dc);
if (you.see_cell(dc))
seen = true;
had_effect = true;
}
if (seen)
{
for (const auto &dc : all_door)
{
if (env.map_knowledge(dc).seen())
{
env.map_knowledge(dc).set_feature(DNGN_CLOSED_DOOR);
#ifdef USE_TILE
env.tile_bk_bg(dc) = TILE_DNGN_CLOSED_DOOR;
#endif
}
}
update_exclusion_los(excludes);
++num_closed;
}
}
// Try to seal the door
if (grd(*ri) == DNGN_CLOSED_DOOR || grd(*ri) == DNGN_RUNED_DOOR)
{
if (check_only)
return true;
set<coord_def> all_door;
find_connected_identical(*ri, all_door);
for (const auto &dc : all_door)
{
temp_change_terrain(dc, DNGN_SEALED_DOOR, seal_duration,
TERRAIN_CHANGE_DOOR_SEAL, warden);
had_effect = true;
}
}
else if (feat_is_travelable_stair(grd(*ri)))
{
if (check_only)
return true;
dungeon_feature_type stype;
if (feat_stair_direction(grd(*ri)) == CMD_GO_UPSTAIRS)
stype = DNGN_SEALED_STAIRS_UP;
else
stype = DNGN_SEALED_STAIRS_DOWN;
temp_change_terrain(*ri, stype, seal_duration,
TERRAIN_CHANGE_DOOR_SEAL, warden);
had_effect = true;
}
}
if (had_effect)
{
ASSERT(!check_only);
mprf(MSGCH_MONSTER_SPELL, "%s activates a sealing rune.",
(warden->visible_to(&you) ? warden->name(DESC_THE, true).c_str()
: "Someone"));
if (num_closed > 1)
mpr("The doors slam shut!");
else if (num_closed == 1)
mpr("A door slams shut!");
if (player_pushed)
mpr("You are pushed out of the doorway!");
return true;
}
return false;
}
/// Should the given monster cast Still Winds?
static bool _should_still_winds(const monster &caster)
{
// if it's already running, don't start it again.
if (env.level_state & LSTATE_STILL_WINDS)
return false;
// just gonna annoy the player most of the time. don't try to be clever
if (caster.wont_attack())
return false;
for (radius_iterator ri(caster.pos(), LOS_NO_TRANS); ri; ++ri)
{
const cloud_struct *cloud = cloud_at(*ri);
if (!cloud)
continue;
// clouds the player might hide in are worrying.
if (grid_distance(*ri, you.pos()) <= 3 // decent margin
&& is_opaque_cloud(cloud->type)
&& actor_cloud_immune(you, *cloud))
{
return true;
}
// so are hazardous clouds on allies.
const monster* mon = monster_at(*ri);
if (mon && !actor_cloud_immune(*mon, *cloud))
return true;
}
// let's give a pass otherwise.
return false;
}
/// Cast the spell Still Winds, disabling clouds across the level temporarily.
static void _cast_still_winds(monster &caster, mon_spell_slot, bolt&)
{
ASSERT(!(env.level_state & LSTATE_STILL_WINDS));
caster.add_ench(ENCH_STILL_WINDS);
}
static bool _make_monster_angry(const monster* mon, monster* targ, bool actual)
{
ASSERT(mon); // XXX: change to const monster &mon
ASSERT(targ); // XXX: change to monster &targ
if (mon->friendly() != targ->friendly())
return false;
// targ is guaranteed to have a foe (needs_berserk checks this).
// Now targ needs to be closer to *its* foe than mon is (otherwise
// mon might be in the way).
coord_def victim;
if (targ->foe == MHITYOU)
victim = you.pos();
else if (targ->foe != MHITNOT)
{
const monster* vmons = &menv[targ->foe];
if (!vmons->alive())
return false;
victim = vmons->pos();
}
else
{
// Should be impossible. needs_berserk should find this case.
die("angered by no foe");
}
// If mon may be blocking targ from its victim, don't try.
if (victim.distance_from(targ->pos()) > victim.distance_from(mon->pos()))
return false;
if (!actual)
return true;
if (you.can_see(*mon))
{
if (mon->type == MONS_QUEEN_BEE && (targ->type == MONS_KILLER_BEE ||
targ->type == MONS_MELIAI))
{
mprf("%s calls on %s to defend %s!",
mon->name(DESC_THE).c_str(),
targ->name(DESC_THE).c_str(),
mon->pronoun(PRONOUN_OBJECTIVE).c_str());
}
else
mprf("%s goads %s on!", mon->name(DESC_THE).c_str(),
targ->name(DESC_THE).c_str());
}
targ->go_berserk(false);
return true;
}
static bool _incite_monsters(const monster* mon, bool actual)
{
if (is_sanctuary(you.pos()) || is_sanctuary(mon->pos()))
return false;
// Only things both in LOS of the inciter and within radius 3.
const int radius = 3;
int goaded = 0;
for (monster_near_iterator mi(mon->pos(), LOS_NO_TRANS); mi; ++mi)
{
// XXX: Ugly hack to skip the spellcaster rules for meliai.
if (*mi == mon || !mi->needs_berserk(mon->type != MONS_QUEEN_BEE))
continue;
if (is_sanctuary(mi->pos()))
continue;
// Cannot goad other moths of wrath!
if (mon->type == MONS_MOTH_OF_WRATH
&& mi->type == MONS_MOTH_OF_WRATH
// Queen bees can only incite bees.
|| mon->type == MONS_QUEEN_BEE
&& mi->type != MONS_KILLER_BEE &&
mi->type != MONS_MELIAI)
{
continue;
}
if (grid_distance(mon->pos(), mi->pos()) > radius)
continue;
const bool worked = _make_monster_angry(mon, *mi, actual);
if (worked && (!actual || !one_chance_in(3 * ++goaded)))
return true;
}
return goaded > 0;
}
// Spells for a quick get-away.
// Currently only used to get out of a net.
static bool _ms_quick_get_away(spell_type monspell)
{
switch (monspell)
{
case SPELL_TELEPORT_SELF:
case SPELL_BLINK:
return true;
default:
return false;
}
}
// Is it worth bothering to invoke recall? (Currently defined by there being at
// least 3 things we could actually recall, and then with a probability inversely
// proportional to how many HD of allies are current nearby)
static bool _should_recall(monster* caller)
{
ASSERT(caller); // XXX: change to monster &caller
// It's a long recitation - if we're winded, we can't use it.
if (caller->has_ench(ENCH_BREATH_WEAPON))
return false;
int num = 0;
for (monster_iterator mi; mi; ++mi)
{
if (mons_is_recallable(caller, **mi)
&& !caller->see_cell_no_trans((*mi)->pos()))
{
++num;
}
}
// Since there are reinforcements we could recall, do we think we need them?
if (num > 2)
{
int ally_hd = 0;
for (monster_near_iterator mi(caller->pos(), LOS_NO_TRANS); mi; ++mi)
{
if (*mi != caller && caller->can_see(**mi)
&& mons_aligned(caller, *mi)
&& !mons_is_firewood(**mi))
{
ally_hd += mi->get_experience_level();
}
}
return 25 + roll_dice(2, 22) > ally_hd;
}
else
return false;
}
/**
* Recall a bunch of monsters!
*
* @param mons[in] the monster doing the recall
* @param recall_target the max number of monsters to recall.
* @returns whether anything was recalled.
*/
bool mons_word_of_recall(monster* mons, int recall_target)
{
unsigned short num_recalled = 0;
vector<monster* > mon_list;
// Build the list of recallable monsters and randomize
for (monster_iterator mi; mi; ++mi)
{
// Don't recall ourselves
if (*mi == mons)
continue;
if (!mons_is_recallable(mons, **mi))
continue;
// Don't recall things that are already close to us
if ((mons && mons->see_cell_no_trans((*mi)->pos()))
|| (!mons && you.see_cell_no_trans((*mi)->pos())))
{
continue;
}
mon_list.push_back(*mi);
}
shuffle_array(mon_list);
const coord_def target = (mons) ? mons->pos() : you.pos();
const unsigned short foe = (mons) ? mons->foe : MHITYOU;
// Now actually recall things
for (monster *mon : mon_list)
{
coord_def empty;
if (find_habitable_spot_near(target, mons_base_type(*mon),
3, false, empty)
&& mon->move_to_pos(empty))
{
mon->behaviour = BEH_SEEK;
mon->foe = foe;
++num_recalled;
simple_monster_message(*mon, " is recalled.");
}
// Can only recall a couple things at once
if (num_recalled == recall_target)
break;
}
return num_recalled;
}
static bool _valid_vine_spot(coord_def p)
{
if (actor_at(p) || !monster_habitable_grid(MONS_PLANT, grd(p)))
return false;
int num_trees = 0;
bool valid_trees = false;
for (adjacent_iterator ai(p); ai; ++ai)
{
if (feat_is_tree(grd(*ai)))
{
// Make sure this spot is not on a diagonal to its only adjacent
// tree (so that the vines can pull back against the tree properly)
if (num_trees || !((*ai-p).sgn().x != 0 && (*ai-p).sgn().y != 0))
{
valid_trees = true;
break;
}
else
++num_trees;
}
}
if (!valid_trees)
return false;
// Now the connectivity check
return !plant_forbidden_at(p, true);
}
static bool _awaken_vines(monster* mon, bool test_only = false)
{
if (_is_wiz_cast())
{
mprf("Sorry, this spell isn't supported for dummies!"); //mons dummy
return false;
}
vector<coord_def> spots;
for (radius_iterator ri(mon->pos(), LOS_NO_TRANS); ri; ++ri)
{
if (_valid_vine_spot(*ri))
spots.push_back(*ri);
}
shuffle_array(spots);
actor* foe = mon->get_foe();
ASSERT(foe);
int num_vines = 1 + random2(3);
if (mon->props.exists("vines_awakened"))
num_vines = min(num_vines, 3 - mon->props["vines_awakened"].get_int());
bool seen = false;
for (coord_def spot : spots)
{
// Don't place vines where they can't see our target
if (!cell_see_cell(spot, foe->pos(), LOS_NO_TRANS))
continue;
// Don't place a vine too near to another existing one
bool too_close = false;
for (distance_iterator di(spot, false, true, 3); di; ++di)
{
monster* m = monster_at(*di);
if (m && m->type == MONS_SNAPLASHER_VINE)
{
too_close = true;
break;
}
}
if (too_close)
continue;
// We've found at least one valid spot, so the spell should be castable
if (test_only)
return true;
// Actually place the vine and update properties
if (monster* vine = create_monster(
mgen_data(MONS_SNAPLASHER_VINE, SAME_ATTITUDE(mon), spot, mon->foe,
MG_FORCE_PLACE)
.set_summoned(mon, 0, SPELL_AWAKEN_VINES, mon->god)))
{
vine->props["vine_awakener"].get_int() = mon->mid;
mon->props["vines_awakened"].get_int()++;
mon->add_ench(mon_enchant(ENCH_AWAKEN_VINES, 1, nullptr, 200));
--num_vines;
if (you.can_see(*vine))
seen = true;
}
// We've finished placing all our vines
if (num_vines == 0)
break;
}
if (test_only)
return false;
else
{
if (seen)
mpr("Vines fly forth from the trees!");
return true;
}
}
static bool _place_druids_call_beast(const monster* druid, monster* beast,
const actor* target)
{
for (int t = 0; t < 20; ++t)
{
// Attempt to find some random spot out of the target's los to place
// the beast (but not too far away).
coord_def area = clamp_in_bounds(target->pos() + coord_def(random_range(-11, 11),
random_range(-11, 11)));
if (cell_see_cell(target->pos(), area, LOS_DEFAULT))
continue;
coord_def base_spot;
int tries = 0;
while (tries < 10 && base_spot.origin())
{
find_habitable_spot_near(area, mons_base_type(*beast), 3, false, base_spot);
if (cell_see_cell(target->pos(), base_spot, LOS_DEFAULT))
base_spot.reset();
++tries;
}
if (base_spot.origin())
continue;
beast->move_to_pos(base_spot);
// Wake the beast up and calculate a path to the druid's target.
// (Note that both BEH_WANDER and MTRAV_PATROL are necessary for it
// to follow the given path and also not randomly wander off instead)
beast->behaviour = BEH_WANDER;
beast->foe = druid->foe;
monster_pathfind mp;
if (mp.init_pathfind(beast, target->pos()))
{
beast->travel_path = mp.calc_waypoints();
if (!beast->travel_path.empty())
{
beast->target = beast->travel_path[0];
beast->travel_target = MTRAV_PATROL;
}
}
// Assign blame (for statistical purposes, mostly)
mons_add_blame(beast, "called by " + druid->name(DESC_A, true));
return true;
}
return false;
}
static void _cast_druids_call(const monster* mon)
{
vector<monster*> mon_list;
for (monster_iterator mi; mi; ++mi)
{
if (_valid_druids_call_target(mon, *mi))
mon_list.push_back(*mi);
}
shuffle_array(mon_list);
const actor* target = mon->get_foe();
const int num = min((int)mon_list.size(),
mon->get_experience_level() > 10 ? random_range(2, 3)
: random_range(1, 2));
for (int i = 0; i < num; ++i)
_place_druids_call_beast(mon, mon_list[i], target);
}
static double _angle_between(coord_def origin, coord_def p1, coord_def p2)
{
double ang0 = atan2(p1.x - origin.x, p1.y - origin.y);
double ang = atan2(p2.x - origin.x, p2.y - origin.y);
return min(fabs(ang - ang0), fabs(ang - ang0 + 2 * PI));
}
// Does there already appear to be a bramble wall in this direction?
// We approximate this by seeing if there are at least two briar patches in
// a ray between us and our target, which turns out to be a pretty decent
// metric in practice.
static bool _already_bramble_wall(const monster* mons, coord_def targ)
{
bolt tracer;
tracer.source = mons->pos();
tracer.target = targ;
tracer.range = 12;
tracer.is_tracer = true;
tracer.pierce = true;
tracer.fire();
int briar_count = 0;
bool targ_reached = false;
for (coord_def p : tracer.path_taken)
{
if (!targ_reached && p == targ)
targ_reached = true;
else if (!targ_reached)
continue;
if (monster_at(p) && monster_at(p)->type == MONS_BRIAR_PATCH)
++briar_count;
}
return briar_count > 1;
}
static bool _wall_of_brambles(monster* mons)
{
mgen_data briar_mg = mgen_data(MONS_BRIAR_PATCH, SAME_ATTITUDE(mons),
coord_def(-1, -1), MHITNOT, MG_FORCE_PLACE);
briar_mg.set_summoned(mons, 0, 0);
// We want to raise a defensive wall if we think our foe is moving to attack
// us, and otherwise raise a wall further away to block off their escape.
// (Each wall type uses different parameters)
bool defensive = mons->props["foe_approaching"].get_bool();
coord_def aim_pos = you.pos();
coord_def targ_pos = mons->pos();
// A defensive wall cannot provide any cover if our target is already
// adjacent, so don't bother creating one.
if (defensive && mons->pos().distance_from(aim_pos) == 1)
return false;
// Don't raise a non-defensive wall if it looks like there's an existing one
// in the same direction already (this looks rather silly to see walls
// springing up in the distance behind already-closed paths, and probably
// is more likely to aid the player than the monster)
if (!defensive)
{
if (_already_bramble_wall(mons, aim_pos))
return false;
}
// Select a random radius for the circle used draw an arc from (affects
// both shape and distance of the resulting wall)
int rad = (defensive ? random_range(3, 5)
: min(11, mons->pos().distance_from(you.pos()) + 6));
// Adjust the center of the circle used to draw the arc of the wall if
// we're raising one defensively, based on both its radius and foe distance.
// (The idea is the ensure that our foe will end up on the other side of it
// without always raising the wall in exactly the same shape and position)
if (defensive)
{
coord_def adjust = (targ_pos - aim_pos).sgn();
targ_pos += adjust;
if (rad == 5)
targ_pos += adjust;
if (mons->pos().distance_from(aim_pos) == 2)
targ_pos += adjust;
}
// XXX: There is almost certainly a better way to calculate the points
// along the desired arcs, though this code produces the proper look.
vector<coord_def> points;
for (distance_iterator di(targ_pos, false, false, rad); di; ++di)
{
if (di.radius() == rad || di.radius() == rad - 1)
{
if (!actor_at(*di) && !cell_is_solid(*di))
{
if (defensive && _angle_between(targ_pos, aim_pos, *di) <= PI/4.0
|| (!defensive
&& _angle_between(targ_pos, aim_pos, *di) <= PI/(4.2 + rad/6.0)))
{
points.push_back(*di);
}
}
}
}
bool seen = false;
for (coord_def point : points)
{
briar_mg.pos = point;
monster* briar = create_monster(briar_mg, false);
if (briar)
{
briar->add_ench(mon_enchant(ENCH_SHORT_LIVED, 1, nullptr, 80 + random2(100)));
if (you.can_see(*briar))
seen = true;
}
}
if (seen)
mpr("Thorny briars emerge from the ground!");
return true;
}
/**
* Make the given monster cast the spell "Corrupting Pulse", corrupting
* (temporarily malmutating) all creatures in LOS.
*
* @param mons The monster in question.
*/
static void _corrupting_pulse(monster *mons)
{
if (cell_see_cell(you.pos(), mons->pos(), LOS_DEFAULT))
{
targeter_los hitfunc(mons, LOS_SOLID);
flash_view_delay(UA_MONSTER, MAGENTA, 300, &hitfunc);
if (!is_sanctuary(you.pos())
&& cell_see_cell(you.pos(), mons->pos(), LOS_SOLID))
{
int num_mutations = one_chance_in(4) ? 2 : 1;
for (int i = 0; i < num_mutations; ++i)
temp_mutate(RANDOM_CORRUPT_MUTATION, "wretched star");
}
}
for (radius_iterator ri(mons->pos(), LOS_RADIUS, C_SQUARE); ri; ++ri)
{
monster *m = monster_at(*ri);
if (m && cell_see_cell(mons->pos(), *ri, LOS_SOLID_SEE)
&& !mons_aligned(mons, m))
{
m->corrupt();
}
}
}
// Returns the clone just created (null otherwise)
monster* cast_phantom_mirror(monster* mons, monster* targ, int hp_perc, int summ_type)
{
// Create clone.
monster *mirror = clone_mons(targ, true);
// Abort if we failed to place the monster for some reason.
if (!mirror)
return nullptr;
// Unentangle the real monster.
if (mons->is_constricted())
mons->stop_being_constricted();
mons_clear_trapping_net(mons);
// Don't leak the real one with the targeting interface.
if (you.prev_targ == mons->mindex())
{
you.prev_targ = MHITNOT;
crawl_state.cancel_cmd_repeat();
}
mons->reset_client_id();
mirror->mark_summoned(5, true, summ_type);
mirror->add_ench(ENCH_PHANTOM_MIRROR);
mirror->summoner = mons->mid;
mirror->hit_points = mirror->hit_points * 100 / hp_perc;
mirror->max_hit_points = mirror->max_hit_points * 100 / hp_perc;
// Sometimes swap the two monsters, so as to disguise the original and the
// copy.
if (coinflip())
targ->swap_with(mirror);
return mirror;
}
static bool _trace_los(monster* agent, bool (*vulnerable)(actor*))
{
bolt tracer;
tracer.foe_ratio = 0;
for (actor_near_iterator ai(agent, LOS_NO_TRANS); ai; ++ai)
{
if (agent == *ai || !vulnerable(*ai))
continue;
if (mons_aligned(agent, *ai))
{
tracer.friend_info.count++;
tracer.friend_info.power +=
ai->is_player() ? you.experience_level
: ai->as_monster()->get_experience_level();
}
else
{
tracer.foe_info.count++;
tracer.foe_info.power +=
ai->is_player() ? you.experience_level
: ai->as_monster()->get_experience_level();
}
}
return mons_should_fire(tracer);
}
static bool _tornado_vulnerable(actor* victim)
{
return !victim->res_tornado();
}
static bool _torment_vulnerable(actor* victim)
{
if (victim->is_player())
return !player_res_torment(false);
return !victim->res_torment();
}
static bool _elec_vulnerable(actor* victim)
{
return victim->res_elec() < 3;
}
static bool _mutation_vulnerable(actor* victim)
{
return victim->can_mutate();
}
static void _cast_black_mark(monster* agent)
{
for (actor_near_iterator ai(agent, LOS_NO_TRANS); ai; ++ai)
{
if (ai->is_player() || !mons_aligned(*ai, agent))
continue;
monster* mon = ai->as_monster();
if (!mon->has_ench(ENCH_BLACK_MARK)
&& mons_has_attacks(*mon))
{
mon->add_ench(ENCH_BLACK_MARK);
simple_monster_message(*mon, " begins absorbing vital energies!");
}
}
}
void aura_of_brilliance(monster* agent)
{
bool did_something = false;
for (actor_near_iterator ai(agent, LOS_NO_TRANS); ai; ++ai)
{
if (ai->is_player() || !mons_aligned(*ai, agent))
continue;
monster* mon = ai->as_monster();
if (_valid_aura_of_brilliance_ally(agent, mon))
{
if (!mon->has_ench(ENCH_EMPOWERED_SPELLS) && you.can_see(*mon))
{
mprf("%s is empowered by %s aura!",
mon->name(DESC_THE).c_str(),
apostrophise(agent->name(DESC_THE)).c_str());
}
mon_enchant ench = mon->get_ench(ENCH_EMPOWERED_SPELLS);
if (ench.ench != ENCH_NONE)
{
ench.duration = 2 * BASELINE_DELAY;
mon->update_ench(ench);
}
else
{
mon->add_ench(mon_enchant(ENCH_EMPOWERED_SPELLS, 1,
agent, 2 * BASELINE_DELAY));
}
did_something = true;
}
}
if (!did_something)
agent->del_ench(ENCH_BRILLIANCE_AURA);
}
static bool _glaciate_tracer(monster *caster, int pow, coord_def aim)
{
targeter_cone hitfunc(caster, spell_range(SPELL_GLACIATE, pow));
hitfunc.set_aim(aim);
mon_attitude_type castatt = caster->temp_attitude();
int friendly = 0, enemy = 0;
for (const auto &entry : hitfunc.zapped)
{
if (entry.second <= 0)
continue;
const actor *victim = actor_at(entry.first);
if (!victim)
continue;
if (mons_atts_aligned(castatt, victim->temp_attitude()))
{
if (victim->is_player() && !(caster->holiness() & MH_DEMONIC))
return false; // never glaciate the player! except demons
friendly += victim->get_experience_level();
}
else
enemy += victim->get_experience_level();
}
return enemy > friendly;
}
bool mons_should_cloud_cone(monster* agent, int power, const coord_def pos)
{
targeter_shotgun hitfunc(agent, CLOUD_CONE_BEAM_COUNT,
spell_range(SPELL_CLOUD_CONE, power));
hitfunc.set_aim(pos);
bolt tracer;
tracer.foe_ratio = 80;
tracer.source_id = agent->mid;
tracer.target = pos;
for (actor_near_iterator ai(agent, LOS_NO_TRANS); ai; ++ai)
{
if (hitfunc.is_affected(ai->pos()) == AFF_NO)
continue;
if (mons_aligned(agent, *ai))
{
tracer.friend_info.count++;
tracer.friend_info.power += ai->get_experience_level();
}
else
{
tracer.foe_info.count++;
tracer.foe_info.power += ai->get_experience_level();
}
}
return mons_should_fire(tracer);
}
static bool _spray_tracer(monster *caster, int pow, bolt parent_beam, spell_type spell)
{
vector<bolt> beams = get_spray_rays(caster, parent_beam.target,
spell_range(spell, pow), 3);
if (beams.size() == 0)
return false;
bolt beam;
for (bolt &child : beams)
{
bolt_parent_init(parent_beam, child);
fire_tracer(caster, child);
beam.friend_info += child.friend_info;
beam.foe_info += child.foe_info;
}
return mons_should_fire(beam);
}
/**
* Pick a target for conjuring a flame.
*
* @param[in] mon The monster casting this.
* @param[in] foe The victim whose movement we are trying to impede.
* @return A position for conjuring a cloud.
*/
static coord_def _mons_conjure_flame_pos(const monster &mons)
{
const monster *mon = &mons; // TODO: rewriteme
actor* foe = mon->get_foe();
// Don't bother if our target is sufficiently fire-resistant,
// or doesn't exist.
if (!foe || foe->res_fire() >= 3)
return coord_def(GXM+1, GYM+1);
const coord_def foe_pos = foe->pos();
const coord_def a = foe_pos - mon->pos();
vector<coord_def> targets;
const int range = _mons_spell_range(*mon, SPELL_CONJURE_FLAME);
for (distance_iterator di(mon->pos(), true, true, range); di; ++di)
{
// Our target needs to be in LOS, and we can't have a creature or
// cloud there. Technically we can target flame clouds, but that's
// usually not very constructive where monsters are concerned.
if (!cell_see_cell(mon->pos(), *di, LOS_SOLID)
|| cell_is_solid(*di)
|| (actor_at(*di) && mon->can_see(*actor_at(*di))))
{
continue;
}
if (cloud_at(*di))
continue;
// Conjure flames *behind* the target; blocking the target from
// accessing us just lets them run away, which is bad if our target
// is usually the player.
coord_def b = *di - foe_pos;
int dot = (a.x * b.x + a.y * b.y);
if (dot < 0)
continue;
// Try to block off a hallway.
int floor_count = 0;
for (adjacent_iterator ai(*di); ai; ++ai)
{
if (feat_is_traversable(grd(*ai))
&& is_damaging_cloud(cloud_type_at(*ai)))
{
floor_count++;
}
}
if (floor_count != 2)
continue;
targets.push_back(*di);
}
// If we found something, pick a square at random to block.
const int count = targets.size();
if (!count)
return coord_def(GXM+1, GYM+1);
return targets[random2(count)];
}
/**
* Is this a feature that we can Awaken?
*
* @param feat The feature type.
* @returns If the feature is a valid feature that we can Awaken Earth on.
*/
static bool _feat_is_awakenable(dungeon_feature_type feat)
{
return feat == DNGN_ROCK_WALL || feat == DNGN_CLEAR_ROCK_WALL;
}
/**
* Pick a target for Awaken Earth.
*
* @param mon The monster casting
* @return The target square - out of bounds if no target was found.
*/
static coord_def _mons_awaken_earth_target(const monster &mon)
{
coord_def pos = mon.target;
// First up, see if we can see our target, and if they're in a good spot
// to pick on them. If so, do that.
if (in_bounds(pos) && mon.see_cell(pos)
&& count_neighbours_with_func(pos, &_feat_is_awakenable) > 0)
{
return pos;
}
// Either we can't see our target, or they're not adjacent to walls.
// Step back towards the caster from the target, and see if we can find
// a better wall for this.
const coord_def start_pos = mon.pos();
ray_def ray;
fallback_ray(pos, start_pos, ray); // straight line from them to mon
unordered_set<coord_def> candidates;
// Candidates: everything on or adjacent to a straight line to the target.
// Strongly prefer cells where we can get lots of elementals.
while (in_bounds(pos) && pos != start_pos)
{
for (adjacent_iterator ai(pos, false); ai; ++ai)
if (mon.see_cell(pos))
candidates.insert(*ai);
ray.advance();
pos = ray.pos();
}
vector<coord_weight> targets;
for (coord_def candidate : candidates)
{
int neighbours = count_neighbours_with_func(candidate,
&_feat_is_awakenable);
// We can target solid cells, which themselves will awaken, so count
// those as well.
if (_feat_is_awakenable(grd(candidate)))
neighbours++;
if (neighbours > 0)
targets.emplace_back(candidate, neighbours * neighbours);
}
coord_def* choice = random_choose_weighted(targets);
return choice ? *choice : coord_def(GXM+1, GYM+1);
}
/**
* Get the fraction of damage done by the given beam that's to enemies,
* multiplied by the given scale.
*/
static int _get_dam_fraction(const bolt &tracer, int scale)
{
if (!tracer.foe_info.power)
return 0;
return tracer.foe_info.power * scale
/ (tracer.foe_info.power + tracer.friend_info.power);
}
/**
* Pick a target for Ghostly Sacrifice.
*
* @param caster The monster casting the spell.
* TODO: constify (requires mon_spell_beam param const
* @return The target square, or an out of bounds coord if none was found.
*/
static coord_def _mons_ghostly_sacrifice_target(const monster &caster,
bolt tracer)
{
const int dam_scale = 1000;
int best_dam_fraction = dam_scale / 2;
coord_def best_target = coord_def(GXM+1, GYM+1); // initially out of bounds
tracer.ex_size = 1;
for (monster_near_iterator mi(&caster, LOS_NO_TRANS); mi; ++mi)
{
if (*mi == &caster)
continue; // don't blow yourself up!
if (!mons_aligned(&caster, *mi))
continue; // can only blow up allies ;)
tracer.target = mi->pos();
fire_tracer(&caster, tracer, true, true);
if (mons_is_threatening(**mi)) // only care about sacrificing real mons
tracer.friend_info.power += mi->get_experience_level() * 2;
const int dam_fraction = _get_dam_fraction(tracer, dam_scale);
dprf("if sacrificing %s (at %d,%d): ratio %d/%d",
mi->name(DESC_A, true).c_str(),
best_target.x, best_target.y, dam_fraction, dam_scale);
if (dam_fraction > best_dam_fraction)
{
best_target = mi->pos();
best_dam_fraction = dam_fraction;
dprf("setting best target");
}
}
return best_target;
}
/// Everything short of the actual explosion. Returns whether to explode.
static bool _prepare_ghostly_sacrifice(monster &caster, bolt &beam)
{
if (!in_bounds(beam.target))
return false; // assert?
monster* victim = monster_at(beam.target);
if (!victim)
return false; // assert?
if (you.see_cell(victim->pos()))
{
mprf("%s animating energy erupts into ghostly fire!",
apostrophise(victim->name(DESC_THE)).c_str());
}
monster_die(*victim, &caster, true);
return true;
}
/// Setup a negative energy explosion.
static void _setup_ghostly_beam(bolt &beam, int power, int dice)
{
beam.colour = CYAN;
beam.name = "ghostly fireball";
beam.damage = dice_def(dice, 6 + power / 13);
beam.hit = 40;
beam.flavour = BEAM_NEG;
beam.is_explosion = true;
}
/// Setup and target a ghostly sacrifice explosion.
static void _setup_ghostly_sacrifice_beam(bolt& beam, const monster& caster,
int power)
{
_setup_ghostly_beam(beam, power, 5);
// Future-proofing: your shadow keeps your targetting.
if (_caster_is_player_shadow(caster))
return;
beam.target = _mons_ghostly_sacrifice_target(caster, beam);
beam.aimed_at_spot = true; // to get noise to work properly
}
static function<bool(const monster&)> _setup_hex_check(spell_type spell)
{
return [spell](const monster& caster) {
return _worth_hexing(caster, spell);
};
}
/**
* Does the given monster think it's worth casting the given hex at its current
* target?
*
* XXX: very strongly consider removing this logic!
*
* @param caster The monster casting the hex.
* @param spell The spell to cast; e.g. SPELL_DIMENSIONAL_ANCHOR.
* @return Whether the monster thinks it's worth trying to beat the
* defender's magic resistance.
*/
static bool _worth_hexing(const monster &caster, spell_type spell)
{
const actor* foe = caster.get_foe();
if (!foe)
return false; // simplifies later checks
// Occasionally we don't estimate... just fire and see.
if (one_chance_in(5))
return true;
// Only intelligent monsters estimate.
if (mons_intel(caster) < I_HUMAN)
return true;
// Simulate Strip Resistance's 1/3 chance of ignoring MR
if (spell == SPELL_STRIP_RESISTANCE && one_chance_in(3))
return true;
// We'll estimate the target's resistance to magic, by first getting
// the actual value and then randomising it.
const int est_magic_resist = foe->res_magic() + random2(60) - 30; // +-30
const int power = ench_power_stepdown(mons_spellpower(caster, spell));
// Determine the amount of chance allowed by the benefit from
// the spell. The estimated difficulty is the probability
// of rolling over 100 + diff on 2d100. -- bwr
int diff = (spell == SPELL_PAIN
|| spell == SPELL_SLOW
|| spell == SPELL_CONFUSE) ? 0 : 50;
return est_magic_resist - power <= diff;
}
bool scattershot_tracer(monster *caster, int pow, coord_def aim)
{
targeter_shotgun hitfunc(caster, shotgun_beam_count(pow),
spell_range(SPELL_SCATTERSHOT, pow));
hitfunc.set_aim(aim);
mon_attitude_type castatt = caster->temp_attitude();
int friendly = 0, enemy = 0;
for (const auto &entry : hitfunc.zapped)
{
if (entry.second <= 0)
continue;
const actor *victim = actor_at(entry.first);
if (!victim)
continue;
if (mons_atts_aligned(castatt, victim->temp_attitude()))
friendly += victim->get_experience_level();
else
enemy += victim->get_experience_level();
}
return enemy > friendly;
}
/** Chooses a matching spell from this spell list, based on frequency.
*
* @param[in] spells the monster spell list to search
* @param[in] flag what SPFLAG_ the spell should match
* @return The spell chosen, or a slot containing SPELL_NO_SPELL and
* MON_SPELL_NO_FLAGS if no spell was chosen.
*/
static mon_spell_slot _pick_spell_from_list(const monster_spells &spells,
int flag)
{
spell_type spell_cast = SPELL_NO_SPELL;
mon_spell_slot_flags slot_flags = MON_SPELL_NO_FLAGS;
int weight = 0;
for (const mon_spell_slot &slot : spells)
{
int flags = get_spell_flags(slot.spell);
if (!(flags & flag))
continue;
weight += slot.freq;
if (x_chance_in_y(slot.freq, weight))
{
spell_cast = slot.spell;
slot_flags = slot.flags;
}
}
return { spell_cast, 0, slot_flags };
}
/**
* Are we a short distance from our target?
*
* @param mons The monster checking distance from its target.
* @return true if we have a target and are within LOS_DEFAULT_RANGE / 2 of that
* target, or false otherwise.
*/
static bool _short_target_range(const monster *mons)
{
return mons->get_foe()
&& mons->pos().distance_from(mons->get_foe()->pos())
< LOS_DEFAULT_RANGE / 2;
}
/**
* Are we a long distance from our target?
*
* @param mons The monster checking distance from its target.
* @return true if we have a target and are outside LOS_DEFAULT_RANGE / 2 of
* that target, or false otherwise.
*/
static bool _long_target_range(const monster *mons)
{
return mons->get_foe()
&& mons->pos().distance_from(mons->get_foe()->pos())
> LOS_DEFAULT_RANGE / 2;
}
/// Does the given monster think it's in an emergency situation?
static bool _mons_in_emergency(const monster &mons)
{
return mons.hit_points < mons.max_hit_points / 3;
}
/**
* Choose a spell for the given monster to consider casting.
*
* @param mons The monster considering casting a spell/
* @param hspell_pass The set of spells to choose from.
* @param prefer_selfench Whether to prefer self-enchantment spells, which
* are more likely to be castable.
* @return A spell to cast, or { SPELL_NO_SPELL }.
*/
static mon_spell_slot _find_spell_prospect(const monster &mons,
const monster_spells &hspell_pass,
bool prefer_selfench)
{
// Setup spell.
// If we didn't find a spell on the first pass, try a
// self-enchantment.
if (prefer_selfench)
return _pick_spell_from_list(hspell_pass, SPFLAG_SELFENCH);
// Monsters that are fleeing or pacified and leaving the
// level will always try to choose an emergency spell.
if (mons_is_fleeing(mons) || mons.pacified())
{
const mon_spell_slot spell = _pick_spell_from_list(hspell_pass,
SPFLAG_EMERGENCY);
// Pacified monsters leaving the level will only
// try and cast escape spells.
if (spell.spell != SPELL_NO_SPELL
&& mons.pacified()
&& !testbits(get_spell_flags(spell.spell), SPFLAG_ESCAPE))
{
return { SPELL_NO_SPELL, 0, MON_SPELL_NO_FLAGS };
}
return spell;
}
unsigned what = random2(200);
unsigned int i = 0;
for (; i < hspell_pass.size(); i++)
{
if ((hspell_pass[i].flags & MON_SPELL_EMERGENCY
&& !_mons_in_emergency(mons))
|| (hspell_pass[i].flags & MON_SPELL_SHORT_RANGE
&& !_short_target_range(&mons))
|| (hspell_pass[i].flags & MON_SPELL_LONG_RANGE
&& !_long_target_range(&mons)))
{
continue;
}
if (hspell_pass[i].freq >= what)
break;
what -= hspell_pass[i].freq;
}
// If we roll above the weight of the spell list,
// don't cast a spell at all.
if (i == hspell_pass.size())
return { SPELL_NO_SPELL, 0, MON_SPELL_NO_FLAGS };
return hspell_pass[i];
}
/**
* Would it be a good idea for the given monster to cast the given spell?
*
* @param mons The monster casting the spell.
* @param spell The spell in question; e.g. SPELL_FIREBALL.
* @param beem A beam with the spell loaded into it; used as a tracer.
* @param ignore_good_idea Whether to be almost completely indiscriminate
* with beam spells. XXX: refactor this out?
*/
static bool _should_cast_spell(const monster &mons, spell_type spell,
bolt &beem, bool ignore_good_idea)
{
// beam-type spells requiring tracers
if (get_spell_flags(spell) & SPFLAG_NEEDS_TRACER)
{
const bool explode = spell_is_direct_explosion(spell);
fire_tracer(&mons, beem, explode);
// Good idea?
return mons_should_fire(beem, ignore_good_idea);
}
// All direct-effect/summoning/self-enchantments/etc.
const actor *foe = mons.get_foe();
if (_ms_direct_nasty(spell)
&& mons_aligned(&mons, (mons.foe == MHITYOU) ?
&you : foe)) // foe=get_foe() is nullptr for friendlies
{ // targeting you, which is bad here.
return false;
}
if (mons.foe == MHITYOU || mons.foe == MHITNOT)
{
// XXX: Note the crude hack so that monsters can
// use ME_ALERT to target (we should really have
// a measure of time instead of peeking to see
// if the player is still there). -- bwr
return you.visible_to(&mons)
|| mons.target == you.pos() && coinflip();
}
ASSERT(foe);
if (!mons.can_see(*foe))
return false;
return true;
}
/// How does Ru describe stopping the given monster casting a spell?
static string _ru_spell_stop_desc(monster &mons)
{
if (mons.is_actual_spellcaster())
return "cast a spell";
if (mons.is_priest())
return "pray";
return "attack";
}
/// What spells can the given monster currently use?
static monster_spells _find_usable_spells(monster &mons)
{
// TODO: make mons param const (requires waste_of_time param to be const)
monster_spells hspell_pass(mons.spells);
if (mons.is_silenced() || mons.is_shapeshifter())
{
erase_if(hspell_pass, [](const mon_spell_slot &t) {
return t.flags & MON_SPELL_SILENCE_MASK;
});
}
// Remove currently useless spells.
erase_if(hspell_pass, [&](const mon_spell_slot &t) {
return _ms_waste_of_time(&mons, t)
// Should monster not have selected dig by now,
// it never will.
|| t.spell == SPELL_DIG;
});
return hspell_pass;
}
/**
* For the given spell and monster, try to find a target for the spell, and
* and then see if it's a good idea to actually cast the spell at that target.
* Return whether we succeeded in both.
*
* @param mons The monster casting the spell. XXX: should be const
* @param beem[in,out] A targeting beam. Has a very few params already set.
* (from setup_targetting_beam())
* @param spell The spell to be targetted and cast.
* @param ignore_good_idea Whether to ignore most targeting constraints (ru)
*/
static bool _target_and_justify_spell(monster &mons,
bolt &beem,
spell_type spell,
bool ignore_good_idea)
{
// Setup the spell.
setup_mons_cast(&mons, beem, spell);
switch (spell)
{
case SPELL_ENSLAVEMENT:
// Try to find an ally of the player to hex if we are
// hexing the player.
if (mons.foe == MHITYOU && !_set_hex_target(&mons, beem))
return false;
break;
case SPELL_DAZZLING_SPRAY:
if (!mons.get_foe()
|| !_spray_tracer(&mons, mons_spellpower(mons, spell),
beem, spell))
{
return false;
}
break;
default:
break;
}
// special beam targeting sets the beam's target to an out-of-bounds coord
// if no valid target was found.
const mons_spell_logic* logic = map_find(spell_to_logic, spell);
if (logic && logic->setup_beam && !in_bounds(beem.target))
return false;
// Don't knockback something we're trying to constrict.
const actor *victim = actor_at(beem.target);
if (victim &&
beem.can_knockback(*victim)
&& mons.is_constricting()
&& mons.constricting->count(victim->mid))
{
return false;
}
return _should_cast_spell(mons, spell, beem, ignore_good_idea);
}
/**
* Let a monster choose a spell to cast; may be SPELL_NO_SPELL.
*
* @param mons The monster doing the casting, potentially.
* TODO: should be const (requires _ms_low_hitpoint_cast
param to be const)
* @param orig_beem[in,out] A beam. Has a very few params already set.
* (from setup_targetting_beam())
* TODO: split out targeting into another func
* @param hspell_pass A list of valid spells to consider casting.
* @param ignore_good_idea Whether to be almost completely indiscriminate
* with beam spells. XXX: refactor this out?
* @return A spell to cast, or SPELL_NO_SPELL.
*/
static mon_spell_slot _choose_spell_to_cast(monster &mons,
bolt &beem,
const monster_spells &hspell_pass,
bool ignore_good_idea)
{
// Monsters caught in a net try to get away.
// This is only urgent if enemies are around.
if (mon_enemies_around(&mons) && mons.caught() && one_chance_in(15))
for (const mon_spell_slot &slot : hspell_pass)
if (_ms_quick_get_away(slot.spell))
return slot;
bolt orig_beem = beem;
// Promote the casting of useful spells for low-HP monsters.
// (kraken should always cast their escape spell of inky).
if (_mons_in_emergency(mons)
&& one_chance_in(mons.type == MONS_KRAKEN ? 4 : 8))
{
// Note: There should always be at least some chance we don't
// get here... even if the monster is on its last HP. That
// way we don't have to worry about monsters infinitely casting
// Healing on themselves (e.g. orc high priests).
int found_spell = 0;
mon_spell_slot chosen_slot = { SPELL_NO_SPELL, 0, MON_SPELL_NO_FLAGS };
for (const mon_spell_slot &slot : hspell_pass)
{
bolt targ_beam = orig_beem;
if (_target_and_justify_spell(mons, targ_beam, slot.spell,
ignore_good_idea)
&& one_chance_in(++found_spell))
{
chosen_slot = slot;
beem = targ_beam;
}
}
if (chosen_slot.spell != SPELL_NO_SPELL)
return chosen_slot;
}
// If nothing found by now, safe friendlies and good
// neutrals will rarely cast.
if (mons.wont_attack() && !mon_enemies_around(&mons) && !one_chance_in(10))
return { SPELL_NO_SPELL, 0, MON_SPELL_NO_FLAGS };
bool reroll = mons.has_ench(ENCH_EMPOWERED_SPELLS);
for (int attempt = 0; attempt < 2; attempt++)
{
const bool prefer_selfench = attempt > 0 && coinflip();
mon_spell_slot chosen_slot
= _find_spell_prospect(mons, hspell_pass, prefer_selfench);
// aura of brilliance gives monsters a bonus cast chance.
if (chosen_slot.spell == SPELL_NO_SPELL && reroll)
{
chosen_slot = _find_spell_prospect(mons, hspell_pass,
prefer_selfench);
reroll = false;
}
// if we didn't roll a spell, don't make another attempt; bail.
// (only give multiple attempts for targetting issues.)
if (chosen_slot.spell == SPELL_NO_SPELL)
return chosen_slot;
// reset the beam
beem = orig_beem;
if (_target_and_justify_spell(mons, beem, chosen_slot.spell,
ignore_good_idea))
{
ASSERT(chosen_slot.spell != SPELL_NO_SPELL);
return chosen_slot;
}
}
return { SPELL_NO_SPELL, 0, MON_SPELL_NO_FLAGS };
}
/**
* Give a monster a chance to cast a spell.
*
* @param mons the monster that might cast.
* @param return whether a spell was cast.
*/
bool handle_mon_spell(monster* mons)
{
ASSERT(mons);
if (is_sanctuary(mons->pos()) && !mons->wont_attack())
return false;
// Yes, there is a logic to this ordering {dlb}:
// .. berserk check is necessary for out-of-sequence actions like emergency
// slot spells {blue}
if (mons->asleep()
|| mons->submerged()
|| mons->berserk_or_insane()
|| mons_is_confused(*mons, false)
|| !mons->has_spells())
{
return false;
}
const monster_spells hspell_pass = _find_usable_spells(*mons);
// If no useful spells... cast no spell.
if (!hspell_pass.size())
return false;
bolt beem = setup_targetting_beam(*mons);
bool ignore_good_idea = false;
if (does_ru_wanna_redirect(mons))
{
ru_interference interference = get_ru_attack_interference_level();
if (interference == DO_BLOCK_ATTACK)
{
const string message
= make_stringf(" begins to %s, but is stunned by your will!",
_ru_spell_stop_desc(*mons).c_str());
simple_monster_message(*mons, message.c_str(), MSGCH_GOD);
mons->lose_energy(EUT_SPELL);
return true;
}
if (interference == DO_REDIRECT_ATTACK)
{
int pfound = 0;
for (radius_iterator ri(you.pos(),
LOS_DEFAULT); ri; ++ri)
{
monster* new_target = monster_at(*ri);
if (new_target == nullptr
|| mons_is_projectile(new_target->type)
|| mons_is_firewood(*new_target)
|| new_target->friendly())
{
continue;
}
ASSERT(new_target);
if (one_chance_in(++pfound))
{
mons->target = new_target->pos();
mons->foe = new_target->mindex();
beem.target = mons->target;
ignore_good_idea = true;
}
}
if (ignore_good_idea)
{
mprf(MSGCH_GOD, "You redirect %s's attack!",
mons->name(DESC_THE).c_str());
}
}
}
const mon_spell_slot spell_slot
= _choose_spell_to_cast(*mons, beem, hspell_pass, ignore_good_idea);
const spell_type spell_cast = spell_slot.spell;
const mon_spell_slot_flags flags = spell_slot.flags;
// Should the monster *still* not have a spell, well, too bad {dlb}:
if (spell_cast == SPELL_NO_SPELL)
return false;
// Check for antimagic if casting a spell spell.
if (mons->has_ench(ENCH_ANTIMAGIC) && flags & MON_SPELL_ANTIMAGIC_MASK
&& !x_chance_in_y(4 * BASELINE_DELAY,
4 * BASELINE_DELAY
+ mons->get_ench(ENCH_ANTIMAGIC).duration))
{
// This may be a bad idea -- if we decide monsters shouldn't
// lose a turn like players do not, please make this just return.
simple_monster_message(*mons, " falters for a moment.");
mons->lose_energy(EUT_SPELL);
return true;
}
// Dragons now have a time-out on their breath weapons, draconians too!
if (flags & MON_SPELL_BREATH)
setup_breath_timeout(mons);
// FINALLY! determine primary spell effects {dlb}:
if (spell_cast == SPELL_BLINK || spell_cast == SPELL_CONTROLLED_BLINK)
{
// Why only cast blink if nearby? {dlb}
if (mons->can_see(you))
{
mons_cast_noise(mons, beem, spell_cast, flags);
monster_blink(mons);
}
else
return false;
}
else if (spell_cast == SPELL_BLINK_RANGE)
blink_range(mons);
else if (spell_cast == SPELL_BLINK_AWAY)
blink_away(mons, true);
else if (spell_cast == SPELL_BLINK_CLOSE)
blink_close(mons);
else
{
const bool battlesphere = mons->props.exists("battlesphere");
if (!(get_spell_flags(spell_cast) & SPFLAG_UTILITY))
make_mons_stop_fleeing(mons);
if (battlesphere)
aim_battlesphere(mons, spell_cast, beem.ench_power, beem);
const bool was_visible = you.can_see(*mons);
mons_cast(mons, beem, spell_cast, flags);
if ((was_visible || you.can_see(*mons)) && mons->alive())
mons->note_spell_cast(spell_cast);
if (battlesphere)
trigger_battlesphere(mons, beem);
if (flags & MON_SPELL_WIZARD && mons->has_ench(ENCH_SAP_MAGIC))
{
mons->add_ench(mon_enchant(ENCH_ANTIMAGIC, 0,
mons->get_ench(ENCH_SAP_MAGIC).agent(),
6 * BASELINE_DELAY));
}
// Wellsprings "cast" from their own hp.
if (spell_cast == SPELL_PRIMAL_WAVE
&& mons->type == MONS_ELEMENTAL_WELLSPRING)
{
mons->hurt(mons, 5 + random2(15));
if (mons->alive())
_summon(*mons, MONS_WATER_ELEMENTAL, 3, spell_slot);
}
}
// Reflection, fireballs, wellspring self-damage, etc.
if (!mons->alive())
return true;
if (!(flags & MON_SPELL_INSTANT))
{
mons->lose_energy(EUT_SPELL);
return true;
}
return false; // to let them do something else
}
static int _monster_abjure_target(monster* target, int pow, bool actual)
{
int duration;
if (!target->is_summoned(&duration))
return 0;
pow = max(20, fuzz_value(pow, 40, 25));
if (!actual)
return pow > 40 || pow >= duration;
// TSO and Trog's abjuration protection.
bool shielded = false;
if (have_passive(passive_t::abjuration_protection_hd))
{
pow = pow * (30 - target->get_hit_dice()) / 30;
if (pow < duration)
{
simple_god_message(" protects your fellow warrior from evil "
"magic!");
shielded = true;
}
}
else if (have_passive(passive_t::abjuration_protection))
{
pow = pow / 2;
if (pow < duration)
{
simple_god_message(" shields your ally from puny magic!");
shielded = true;
}
}
else if (is_sanctuary(target->pos()))
{
pow = 0;
mprf(MSGCH_GOD, "Zin's power protects your fellow warrior from evil magic!");
shielded = true;
}
dprf("Abj: dur: %d, pow: %d, ndur: %d", duration, pow, duration - pow);
mon_enchant abj = target->get_ench(ENCH_ABJ);
if (!target->lose_ench_duration(abj, pow))
{
if (!shielded)
simple_monster_message(*target, " shudders.");
return 1;
}
return 0;
}
static int _monster_abjuration(const monster* caster, bool actual)
{
int maffected = 0;
if (actual)
mpr("Send 'em back where they came from!");
const int pow = mons_spellpower(*caster, SPELL_ABJURATION);
for (monster_near_iterator mi(caster->pos(), LOS_NO_TRANS); mi; ++mi)
{
if (!mons_aligned(caster, *mi))
maffected += _monster_abjure_target(*mi, pow, actual);
}
return maffected;
}
static bool _mons_will_abjure(monster* mons, spell_type spell)
{
if (get_spell_flags(spell) & SPFLAG_MONS_ABJURE
&& _monster_abjuration(mons, false) > 0
&& one_chance_in(3))
{
return true;
}
return false;
}
static void _haunt_fixup(monster* summon, coord_def pos)
{
actor* victim = actor_at(pos);
if (victim && victim != summon)
{
summon->add_ench(mon_enchant(ENCH_HAUNTING, 1, victim,
INFINITE_DURATION));
summon->foe = victim->mindex();
}
}
static monster_type _pick_horrible_thing()
{
return one_chance_in(4) ? MONS_TENTACLED_MONSTROSITY
: MONS_ABOMINATION_LARGE;
}
static monster_type _pick_undead_summon()
{
static monster_type undead[] =
{
MONS_NECROPHAGE, MONS_JIANGSHI, MONS_HUNGRY_GHOST, MONS_FLAYED_GHOST,
MONS_ZOMBIE, MONS_SKELETON, MONS_SIMULACRUM, MONS_SPECTRAL_THING,
MONS_FLYING_SKULL, MONS_MUMMY, MONS_VAMPIRE, MONS_WIGHT, MONS_WRAITH,
MONS_SHADOW_WRAITH, MONS_FREEZING_WRAITH, MONS_PHANTASMAL_WARRIOR, MONS_SHADOW
};
return RANDOM_ELEMENT(undead);
}
static monster_type _pick_vermin()
{
return random_choose_weighted(8, MONS_HELL_RAT,
5, MONS_REDBACK,
2, MONS_TARANTELLA,
2, MONS_JUMPING_SPIDER,
3, MONS_DEMONIC_CRAWLER);
}
static monster_type _pick_drake()
{
return random_choose_weighted(5, MONS_SWAMP_DRAKE,
5, MONS_KOMODO_DRAGON,
5, MONS_WIND_DRAKE,
6, MONS_RIME_DRAKE,
6, MONS_DEATH_DRAKE,
3, MONS_LINDWURM);
}
static void _do_high_level_summon(monster* mons, spell_type spell_cast,
monster_type (*mpicker)(), int nsummons,
god_type god, const coord_def *target = nullptr,
void (*post_hook)(monster*, coord_def)
= nullptr)
{
const int duration = min(2 + mons->spell_hd(spell_cast) / 5, 6);
for (int i = 0; i < nsummons; ++i)
{
monster_type which_mons = mpicker();
if (which_mons == MONS_NO_MONSTER)
continue;
monster* summon = create_monster(
mgen_data(which_mons, SAME_ATTITUDE(mons),
target ? *target : mons->pos(), mons->foe)
.set_summoned(mons, duration, spell_cast, god));
if (summon && post_hook)
post_hook(summon, target ? *target : mons->pos());
}
}
static void _mons_summon_elemental(monster &mons, mon_spell_slot slot, bolt&)
{
static const map<spell_type, monster_type> elemental_types = {
{ SPELL_WATER_ELEMENTALS, MONS_WATER_ELEMENTAL },
{ SPELL_FIRE_ELEMENTALS, MONS_FIRE_ELEMENTAL },
{ SPELL_EARTH_ELEMENTALS, MONS_EARTH_ELEMENTAL },
{ SPELL_AIR_ELEMENTALS, MONS_AIR_ELEMENTAL },
#if TAG_MAJOR_VERSION == 34
{ SPELL_IRON_ELEMENTALS, MONS_IRON_ELEMENTAL },
#endif
};
const monster_type* mtyp = map_find(elemental_types, slot.spell);
ASSERT(mtyp);
const int spell_hd = mons.spell_hd(slot.spell);
const int count = 1 + (spell_hd > 15) + random2(spell_hd / 7 + 1);
for (int i = 0; i < count; i++)
_summon(mons, *mtyp, 3, slot);
}
static void _mons_cast_haunt(monster* mons)
{
ASSERT(mons->get_foe());
const coord_def fpos = mons->get_foe()->pos();
_do_high_level_summon(mons, SPELL_HAUNT, pick_random_wraith,
random_range(2, 3), GOD_NO_GOD, &fpos, _haunt_fixup);
}
static void _mons_cast_summon_illusion(monster* mons, spell_type spell)
{
actor *foe = mons->get_foe();
if (!foe || !actor_is_illusion_cloneable(foe))
return;
mons_summon_illusion_from(mons, foe, spell);
}
static void _mons_cast_spectral_orcs(monster* mons)
{
ASSERT(mons->get_foe());
const coord_def fpos = mons->get_foe()->pos();
const int abj = 3;
for (int i = random2(3) + 1; i > 0; --i)
{
monster_type mon = MONS_ORC;
if (coinflip())
mon = MONS_ORC_WARRIOR;
else if (one_chance_in(3))
mon = MONS_ORC_KNIGHT;
else if (one_chance_in(10))
mon = MONS_ORC_WARLORD;
// Use the original monster type as the zombified type here, to
// get the proper stats from it.
if (monster *orc = create_monster(
mgen_data(MONS_SPECTRAL_THING, SAME_ATTITUDE(mons), fpos,
mons->foe)
.set_summoned(mons, abj, SPELL_SUMMON_SPECTRAL_ORCS, mons->god)
.set_base(mon)))
{
// set which base type this orc is pretending to be for gear
// purposes
if (mon != MONS_ORC)
{
orc->mname = mons_type_name(mon, DESC_PLAIN);
orc->flags |= MF_NAME_REPLACE | MF_NAME_DESCRIPTOR;
}
// give gear using the base type
const int lvl = env.absdepth0;
give_specific_item(orc, make_mons_weapon(orc->base_monster, lvl));
give_specific_item(orc, make_mons_armour(orc->base_monster, lvl));
// XXX: and a shield, for warlords...? (wasn't included before)
// set gear as summoned
orc->mark_summoned(abj, true, SPELL_SUMMON_SPECTRAL_ORCS);
}
}
}
static void _mons_vampiric_drain(monster &mons, mon_spell_slot slot, bolt&)
{
actor *target = mons.get_foe();
if (!target)
return;
if (grid_distance(mons.pos(), target->pos()) > 1)
return;
const int pow = mons_spellpower(mons, slot.spell);
int hp_cost = 3 + random2avg(9, 2) + 1 + random2(pow) / 7;
hp_cost = min(hp_cost, target->stat_hp());
hp_cost = min(hp_cost, mons.max_hit_points - mons.hit_points);
hp_cost = resist_adjust_damage(target, BEAM_NEG, hp_cost);
if (!hp_cost)
{
simple_monster_message(mons,
" is infused with unholy energy, but nothing happens.",
MSGCH_MONSTER_SPELL);
return;
}
dprf("vamp draining: %d damage, %d healing", hp_cost, hp_cost/2);
if (you.can_see(mons))
{
simple_monster_message(mons,
" is infused with unholy energy.",
MSGCH_MONSTER_SPELL);
}
else
mpr("Unholy energy fills the air.");
if (target->is_player())
{
ouch(hp_cost, KILLED_BY_BEAM, mons.mid, "by vampiric draining");
if (mons.heal(hp_cost * 2 / 3))
{
simple_monster_message(mons,
" draws life force from you and is healed!");
}
}
else
{
monster* mtarget = target->as_monster();
const string targname = mtarget->name(DESC_THE);
mtarget->hurt(&mons, hp_cost);
if (mtarget->is_summoned())
{
simple_monster_message(mons,
make_stringf(" draws life force from %s!",
targname.c_str()).c_str());
}
else if (mons.heal(hp_cost * 2 / 3))
{
simple_monster_message(mons,
make_stringf(" draws life force from %s and is healed!",
targname.c_str()).c_str());
}
if (mtarget->alive())
print_wounds(*mtarget);
}
}
static bool _mons_cast_freeze(monster* mons)
{
actor *target = mons->get_foe();
if (!target)
return false;
if (grid_distance(mons->pos(), target->pos()) > 1)
return false;
const int pow = mons_spellpower(*mons, SPELL_FREEZE);
const int base_damage = roll_dice(1, 3 + pow / 6);
int damage = 0;
if (target->is_player())
damage = resist_adjust_damage(&you, BEAM_COLD, base_damage);
else
{
bolt beam;
beam.flavour = BEAM_COLD;
damage = mons_adjust_flavoured(target->as_monster(), beam, base_damage);
}
if (you.can_see(*target))
{
mprf("%s %s frozen.", target->name(DESC_THE).c_str(),
target->conj_verb("are").c_str());
}
target->hurt(mons, damage, BEAM_COLD, KILLED_BY_BEAM, "", "by Freeze");
if (target->alive())
{
target->expose_to_element(BEAM_COLD, damage);
if (target->is_monster() && target->res_cold() <= 0)
{
const int stun = (1 - target->res_cold())
* random2(min(7, 2 + pow/24));
target->as_monster()->speed_increment -= stun;
}
}
return true;
}
void setup_breath_timeout(monster* mons)
{
if (mons->has_ench(ENCH_BREATH_WEAPON))
return;
int timeout = roll_dice(1, 5);
dprf("breath timeout: %d", timeout);
mon_enchant breath_timeout = mon_enchant(ENCH_BREATH_WEAPON, 1, mons, timeout*10);
mons->add_ench(breath_timeout);
}
/**
* Maybe mesmerise the player.
*
* This function decides whether or not it is possible for the player to become
* mesmerised by mons. It will return a variety of values depending on whether
* or not this can succeed or has succeeded; finally, it will add mons to the
* player's list of beholders.
*
* @param mons The monster doing the mesmerisation.
* @param actual Whether or not we are actually casting the spell. If false,
* no messages are emitted.
* @return 0 if the player could be mesmerised but wasn't, 1 if the
* player was mesmerised, -1 if the player couldn't be
* mesmerised.
**/
static int _mons_mesmerise(monster* mons, bool actual)
{
ASSERT(mons); // XXX: change to monster &mons
bool already_mesmerised = you.beheld_by(*mons);
if (!you.visible_to(mons) // Don't mesmerise while invisible.
|| (!you.can_see(*mons) // Or if we are, and you're aren't
&& !already_mesmerised) // already mesmerised by us.
|| !player_can_hear(mons->pos()) // Or if you're silenced, or we are.
|| you.berserk() // Or if you're berserk.
|| mons->has_ench(ENCH_CONFUSION) // Or we're confused,
|| mons_is_fleeing(*mons) // fleeing,
|| mons->pacified() // pacified,
|| mons->friendly()) // or friendly!
{
return -1;
}
if (actual)
{
if (!already_mesmerised)
{
simple_monster_message(*mons, " attempts to bespell you!");
flash_view(UA_MONSTER, LIGHTMAGENTA);
}
else
{
mprf("%s draws you further into %s thrall.",
mons->name(DESC_THE).c_str(),
mons->pronoun(PRONOUN_POSSESSIVE).c_str());
}
}
const int pow = _ench_power(SPELL_MESMERISE, *mons);
const int res_magic = you.check_res_magic(pow);
// Don't mesmerise if you pass an MR check or have clarity.
// If you're already mesmerised, you cannot resist further.
if ((res_magic > 0 || you.clarity()
|| you.duration[DUR_MESMERISE_IMMUNE]) && !already_mesmerised)
{
if (actual)
{
if (you.clarity())
canned_msg(MSG_YOU_UNAFFECTED);
else if (you.duration[DUR_MESMERISE_IMMUNE] && !already_mesmerised)
canned_msg(MSG_YOU_RESIST);
else
mprf("You%s", you.resist_margin_phrase(res_magic).c_str());
}
return 0;
}
you.add_beholder(*mons);
return 1;
}
// Check whether targets might be scared.
// Returns 0, if targets can be scared but the attempt failed or wasn't made.
// Returns 1, if targets are scared.
// Returns -1, if targets can never be scared.
static int _mons_cause_fear(monster* mons, bool actual)
{
if (actual)
{
if (you.can_see(*mons))
simple_monster_message(*mons, " radiates an aura of fear!");
else if (you.see_cell(mons->pos()))
mpr("An aura of fear fills the air!");
}
int retval = -1;
const int pow = _ench_power(SPELL_CAUSE_FEAR, *mons);
if (mons->see_cell_no_trans(you.pos())
&& mons->can_see(you)
&& !mons->wont_attack()
&& !you.afraid_of(mons))
{
if (!(you.holiness() & MH_NATURAL))
{
if (actual)
canned_msg(MSG_YOU_UNAFFECTED);
}
else if (!actual)
retval = 0;
else
{
const int res_margin = you.check_res_magic(pow);
if (you.clarity())
canned_msg(MSG_YOU_UNAFFECTED);
else if (res_margin > 0)
mprf("You%s", you.resist_margin_phrase(res_margin).c_str());
else if (you.add_fearmonger(mons))
{
retval = 1;
you.increase_duration(DUR_AFRAID, 10 + random2avg(pow / 10, 4));
if (!mons->has_ench(ENCH_FEAR_INSPIRING))
mons->add_ench(ENCH_FEAR_INSPIRING);
}
}
}
for (monster_near_iterator mi(mons->pos(), LOS_NO_TRANS); mi; ++mi)
{
if (*mi == mons)
continue;
// Magic-immune, unnatural and "firewood" monsters are
// immune to being scared. Same-aligned monsters are
// never affected, even though they aren't immune.
// Will not further scare a monster that is already afraid.
if (mons_immune_magic(**mi)
|| !(mi->holiness() & MH_NATURAL)
|| mons_is_firewood(**mi)
|| mons_atts_aligned(mi->attitude, mons->attitude)
|| mi->has_ench(ENCH_FEAR))
{
continue;
}
retval = max(retval, 0);
if (!actual)
continue;
// It's possible to scare this monster. If its magic
// resistance fails, do so.
int res_margin = mi->check_res_magic(pow);
if (res_margin > 0)
{
simple_monster_message(**mi,
mi->resist_margin_phrase(res_margin).c_str());
continue;
}
if (mi->add_ench(mon_enchant(ENCH_FEAR, 0, mons)))
{
retval = 1;
if (you.can_see(**mi))
simple_monster_message(**mi, " looks frightened!");
behaviour_event(*mi, ME_SCARE, mons);
if (!mons->has_ench(ENCH_FEAR_INSPIRING))
mons->add_ench(ENCH_FEAR_INSPIRING);
}
}
if (actual && retval == 1 && you.see_cell(mons->pos()))
flash_view_delay(UA_MONSTER, DARKGREY, 300);
return retval;
}
static int _mons_mass_confuse(monster* mons, bool actual)
{
int retval = -1;
const int pow = _ench_power(SPELL_MASS_CONFUSION, *mons);
if (mons->see_cell_no_trans(you.pos())
&& mons->can_see(you)
&& !mons->wont_attack())
{
retval = 0;
if (actual)
{
const int res_magic = you.check_res_magic(pow);
if (res_magic > 0)
mprf("You%s", you.resist_margin_phrase(res_magic).c_str());
else
{
you.confuse(mons, 5 + random2(3));
retval = 1;
}
}
}
for (monster_near_iterator mi(mons->pos(), LOS_NO_TRANS); mi; ++mi)
{
if (*mi == mons)
continue;
if (mons_immune_magic(**mi)
|| mons_is_firewood(**mi)
|| mons_atts_aligned(mi->attitude, mons->attitude)
|| mons->has_ench(ENCH_HEXED))
{
continue;
}
retval = max(retval, 0);
int res_margin = mi->check_res_magic(pow);
if (res_margin > 0)
{
if (actual)
{
simple_monster_message(**mi,
mi->resist_margin_phrase(res_margin).c_str());
}
continue;
}
if (actual)
{
retval = 1;
mi->confuse(mons, 5 + random2(3));
}
}
return retval;
}
static coord_def _mons_fragment_target(const monster &mon)
{
coord_def target(GXM+1, GYM+1);
const monster *mons = &mon; // TODO: rewriteme
const int pow = mons_spellpower(*mons, SPELL_LRD);
// Shadow casting should try to affect the same tile as the player.
if (mons_is_player_shadow(*mons))
{
bool temp;
bolt beam;
if (!setup_fragmentation_beam(beam, pow, mons, mons->target, true,
nullptr, temp))
{
return target;
}
return mons->target;
}
const int range = _mons_spell_range(*mons, SPELL_LRD);
int maxpower = 0;
for (distance_iterator di(mons->pos(), true, true, range); di; ++di)
{
bool temp;
if (!cell_see_cell(mons->pos(), *di, LOS_SOLID))
continue;
bolt beam;
if (!setup_fragmentation_beam(beam, pow, mons, *di, true, nullptr,
temp))
{
continue;
}
beam.range = range;
fire_tracer(mons, beam, true);
if (!mons_should_fire(beam))
continue;
if (beam.foe_info.count > 0
&& beam.foe_info.power > maxpower)
{
maxpower = beam.foe_info.power;
target = *di;
}
}
return target;
}
static void _blink_allies_encircle(const monster* mon)
{
vector<monster*> allies;
const coord_def foepos = mon->get_foe()->pos();
for (monster_near_iterator mi(mon, LOS_NO_TRANS); mi; ++mi)
{
if (_valid_encircle_ally(mon, *mi, foepos))
allies.push_back(*mi);
}
shuffle_array(allies);
int count = max(1, mon->spell_hd(SPELL_BLINK_ALLIES_ENCIRCLE) / 8
+ random2(mon->spell_hd(SPELL_BLINK_ALLIES_ENCIRCLE) / 4));
for (monster *ally : allies)
{
coord_def empty;
if (find_habitable_spot_near(foepos, mons_base_type(*ally), 1, false, empty))
{
if (ally->blink_to(empty))
{
// XXX: This seems an awkward way to give a message for something
// blinking from out of sight into sight. Probably could use a
// more general solution.
if (!(ally->flags & MF_WAS_IN_VIEW)
&& ally->flags & MF_SEEN)
{
simple_monster_message(*ally, " blinks into view!");
}
ally->behaviour = BEH_SEEK;
ally->foe = mon->foe;
count--;
}
}
}
}
static void _blink_allies_away(const monster* mon)
{
vector<monster*> allies;
const coord_def foepos = mon->get_foe()->pos();
for (monster_near_iterator mi(mon, LOS_NO_TRANS); mi; ++mi)
{
if (_valid_blink_away_ally(mon, *mi, foepos))
allies.push_back(*mi);
}
shuffle_array(allies);
int count = max(1, mon->spell_hd(SPELL_BLINK_ALLIES_AWAY) / 8
+ random2(mon->spell_hd(SPELL_BLINK_ALLIES_AWAY) / 4));
for (unsigned int i = 0; i < allies.size() && count; ++i)
{
if (blink_away(allies[i], &you, false))
count--;
}
}
struct branch_summon_pair
{
branch_type origin;
const pop_entry *pop;
};
static const pop_entry _invitation_lair[] =
{ // Lair enemies
{ 1, 1, 60, FLAT, MONS_BLINK_FROG },
{ 1, 1, 40, FLAT, MONS_DREAM_SHEEP },
{ 1, 1, 20, FLAT, MONS_SPINY_FROG },
{ 0,0,0,FLAT,MONS_0 }
};
static const pop_entry _invitation_snake[] =
{ // Snake enemies
{ 1, 1, 80, FLAT, MONS_NAGA },
{ 1, 1, 40, FLAT, MONS_BLACK_MAMBA },
{ 1, 1, 20, FLAT, MONS_MANA_VIPER },
{ 0,0,0,FLAT,MONS_0 }
};
static const pop_entry _invitation_spider[] =
{ // Spider enemies
{ 1, 1, 60, FLAT, MONS_TARANTELLA },
{ 1, 1, 80, FLAT, MONS_JUMPING_SPIDER },
{ 1, 1, 20, FLAT, MONS_ORB_SPIDER },
{ 0,0,0,FLAT,MONS_0 }
};
static const pop_entry _invitation_swamp[] =
{ // Swamp enemies
{ 1, 1, 80, FLAT, MONS_VAMPIRE_MOSQUITO },
{ 1, 1, 60, FLAT, MONS_INSUBSTANTIAL_WISP },
{ 1, 1, 40, FLAT, MONS_SWAMP_DRAKE },
{ 0,0,0,FLAT,MONS_0 }
};
static const pop_entry _invitation_shoals[] =
{ // Swamp enemies
{ 1, 1, 60, FLAT, MONS_MERFOLK_SIREN },
{ 1, 1, 40, FLAT, MONS_MANTICORE },
{ 1, 1, 20, FLAT, MONS_WIND_DRAKE },
{ 0,0,0,FLAT,MONS_0 }
};
static const pop_entry _invitation_orc[] =
{ // Orc enemies
{ 1, 1, 80, FLAT, MONS_ORC_PRIEST },
{ 1, 1, 40, FLAT, MONS_WARG },
{ 1, 1, 20, FLAT, MONS_TROLL },
{ 0,0,0,FLAT,MONS_0 }
};
static const pop_entry _invitation_elf[] =
{ // Elf enemies
{ 1, 1, 100, FLAT, MONS_DEEP_ELF_MAGE },
{ 1, 1, 40, FLAT, MONS_DEEP_ELF_KNIGHT },
{ 1, 1, 40, FLAT, MONS_DEEP_ELF_ARCHER },
{ 0,0,0,FLAT,MONS_0 }
};
static const pop_entry _invitation_vaults[] =
{ // Vaults enemies
{ 1, 1, 60, FLAT, MONS_YAKTAUR },
{ 1, 1, 40, FLAT, MONS_IRONHEART_PRESERVER },
{ 1, 1, 20, FLAT, MONS_VAULT_SENTINEL },
{ 0,0,0,FLAT,MONS_0 }
};
static const pop_entry _invitation_crypt[] =
{ // Crypt enemies
{ 1, 1, 80, FLAT, MONS_WRAITH },
{ 1, 1, 60, FLAT, MONS_SHADOW },
{ 1, 1, 20, FLAT, MONS_NECROMANCER },
{ 0,0,0,FLAT,MONS_0 }
};
static branch_summon_pair _invitation_summons[] =
{
{ BRANCH_LAIR, _invitation_lair },
{ BRANCH_SNAKE, _invitation_snake },
{ BRANCH_SPIDER, _invitation_spider },
{ BRANCH_SWAMP, _invitation_swamp },
{ BRANCH_SHOALS, _invitation_shoals },
{ BRANCH_ORC, _invitation_orc },
{ BRANCH_ELF, _invitation_elf },
{ BRANCH_VAULTS, _invitation_vaults },
{ BRANCH_CRYPT, _invitation_crypt }
};
static const pop_entry _planerend_snake[] =
{ // Snake enemies
{ 1, 1, 40, FLAT, MONS_ANACONDA },
{ 1, 1, 100, FLAT, MONS_GUARDIAN_SERPENT },
{ 1, 1, 100, FLAT, MONS_NAGARAJA },
{ 0,0,0,FLAT,MONS_0 }
};
static const pop_entry _planerend_spider[] =
{ // Spider enemies
{ 1, 1, 100, FLAT, MONS_EMPEROR_SCORPION },
{ 1, 1, 80, FLAT, MONS_TORPOR_SNAIL },
{ 1, 1, 100, FLAT, MONS_GHOST_MOTH },
{ 0,0,0,FLAT,MONS_0 }
};
static const pop_entry _planerend_swamp[] =
{ // Swamp enemies
{ 1, 1, 100, FLAT, MONS_SWAMP_DRAGON },
{ 1, 1, 80, FLAT, MONS_SHAMBLING_MANGROVE },
{ 1, 1, 40, FLAT, MONS_THORN_HUNTER },
{ 0,0,0,FLAT,MONS_0 }
};
static const pop_entry _planerend_shoals[] =
{ // Shoals enemies
{ 1, 1, 80, FLAT, MONS_ALLIGATOR_SNAPPING_TURTLE },
{ 1, 1, 40, FLAT, MONS_WATER_NYMPH },
{ 1, 1, 100, FLAT, MONS_MERFOLK_JAVELINEER },
{ 0,0,0,FLAT,MONS_0 }
};
static const pop_entry _planerend_slime[] =
{ // Slime enemies
{ 1, 1, 80, FLAT, MONS_SLIME_CREATURE }, // changed to titanic below
{ 1, 1, 100, FLAT, MONS_AZURE_JELLY },
{ 1, 1, 100, FLAT, MONS_ACID_BLOB },
{ 0,0,0,FLAT,MONS_0 }
};
static const pop_entry _planerend_elf[] =
{ // Elf enemies
{ 1, 1, 100, FLAT, MONS_DEEP_ELF_SORCERER },
{ 1, 1, 100, FLAT, MONS_DEEP_ELF_HIGH_PRIEST },
{ 1, 1, 60, FLAT, MONS_DEEP_ELF_BLADEMASTER },
{ 0,0,0,FLAT,MONS_0 }
};
static const pop_entry _planerend_vaults[] =
{ // Vaults enemies
{ 1, 1, 80, FLAT, MONS_VAULT_SENTINEL },
{ 1, 1, 40, FLAT, MONS_IRONBRAND_CONVOKER },
{ 1, 1, 100, FLAT, MONS_WAR_GARGOYLE },
{ 0,0,0,FLAT,MONS_0 }
};
static const pop_entry _planerend_crypt[] =
{ // Crypt enemies
{ 1, 1, 100, FLAT, MONS_VAMPIRE_KNIGHT },
{ 1, 1, 100, FLAT, MONS_FLAYED_GHOST },
{ 1, 1, 80, FLAT, MONS_REVENANT },
{ 0,0,0,FLAT,MONS_0 }
};
static const pop_entry _planerend_tomb[] =
{ // Tomb enemies
{ 1, 1, 60, FLAT, MONS_ANCIENT_CHAMPION },
{ 1, 1, 100, FLAT, MONS_SPHINX },
{ 1, 1, 100, FLAT, MONS_MUMMY_PRIEST },
{ 0,0,0,FLAT,MONS_0 }
};
static const pop_entry _planerend_abyss[] =
{ // Abyss enemies
{ 1, 1, 80, FLAT, MONS_APOCALYPSE_CRAB },
{ 1, 1, 100, FLAT, MONS_STARCURSED_MASS },
{ 1, 1, 40, FLAT, MONS_WRETCHED_STAR },
{ 0,0,0,FLAT,MONS_0 }
};
static const pop_entry _planerend_zot[] =
{ // Zot enemies
{ 1, 1, 40, FLAT, MONS_DRACONIAN_STORMCALLER },
{ 1, 1, 100, FLAT, MONS_GOLDEN_DRAGON },
{ 1, 1, 80, FLAT, MONS_MOTH_OF_WRATH },
{ 0,0,0,FLAT,MONS_0 }
};
static branch_summon_pair _planerend_summons[] =
{
{ BRANCH_SNAKE, _planerend_snake },
{ BRANCH_SPIDER, _planerend_spider },
{ BRANCH_SWAMP, _planerend_swamp },
{ BRANCH_SHOALS, _planerend_shoals },
{ BRANCH_SLIME, _planerend_slime },
{ BRANCH_ELF, _planerend_elf },
{ BRANCH_VAULTS, _planerend_vaults },
{ BRANCH_CRYPT, _planerend_crypt },
{ BRANCH_TOMB, _planerend_tomb },
{ BRANCH_ABYSS, _planerend_abyss },
{ BRANCH_ZOT, _planerend_zot }
};
static void _branch_summon(monster &mons, mon_spell_slot slot, bolt&)
{
_branch_summon_helper(&mons, slot.spell);
}
static void _branch_summon_helper(monster* mons, spell_type spell_cast)
{
// TODO: rewrite me! (should use maps, vectors, const monster&...)
branch_summon_pair *summon_list;
size_t list_size;
int which_branch;
static const string INVITATION_KEY = "invitation_branch";
switch (spell_cast)
{
case SPELL_FORCEFUL_INVITATION:
summon_list = _invitation_summons;
list_size = ARRAYSZ(_invitation_summons);
if (!mons->props.exists(INVITATION_KEY))
mons->props[INVITATION_KEY].get_byte() = random2(list_size);
which_branch = mons->props[INVITATION_KEY].get_byte();
break;
case SPELL_PLANEREND:
summon_list = _planerend_summons;
list_size = ARRAYSZ(_planerend_summons);
which_branch = random2(list_size);
break;
default:
die("Unsupported branch summon spell %s!",
spell_title(spell_cast));
}
const int num_summons = random_range(1, 3);
if (you.see_cell(mons->pos()))
{
string msg = getSpeakString("branch summon cast prefix");
if (!msg.empty())
{
msg = replace_all(msg, "@The_monster@", mons->name(DESC_THE));
msg += " ";
msg += branches[summon_list[which_branch].origin].longname;
msg += "!";
mprf(mons->wont_attack() ? MSGCH_FRIEND_ENCHANT
: MSGCH_MONSTER_ENCHANT,
"%s", msg.c_str());
}
}
for (int i = 0; i < num_summons; i++)
{
monster_type type = pick_monster_from(summon_list[which_branch].pop, 1);
if (type == MONS_NO_MONSTER)
continue;
mgen_data mg(type, SAME_ATTITUDE(mons), mons->pos(), mons->foe);
mg.set_summoned(mons, 1, spell_cast);
if (type == MONS_SLIME_CREATURE)
mg.props[MGEN_BLOB_SIZE] = 5;
create_monster(mg);
}
}
static void _cast_flay(monster &caster, mon_spell_slot, bolt&)
{
actor* defender = caster.get_foe();
ASSERT(defender);
int damage_taken = 0;
if (defender->is_player())
{
damage_taken = (6 + (you.hp * 18 / you.hp_max)) * you.hp_max / 100;
damage_taken = min(damage_taken,
max(0, you.hp - 25 - random2(15)));
}
else
{
monster* mon = defender->as_monster();
damage_taken = (6 + (mon->hit_points * 18 / mon->max_hit_points))
* mon->max_hit_points / 100;
damage_taken = min(damage_taken,
max(0, mon->hit_points - 25 - random2(15)));
}
flay(caster, *defender, damage_taken);
}
/**
* Attempt to flay the given target, dealing 'temporary' damage that heals when
* a flayed ghost nearby dies.
*
* @param caster The flayed ghost doing the flaying. (Mostly irrelevant.)
* @param defender The thing being flayed.
* @param damage How much flaying damage to do.
*/
void flay(const monster &caster, actor &defender, int damage)
{
if (damage < 10)
return;
bool was_flayed = false;
if (defender.is_player())
{
if (you.duration[DUR_FLAYED])
was_flayed = true;
you.duration[DUR_FLAYED] = max(you.duration[DUR_FLAYED],
55 + random2(66));
}
else
{
monster* mon = defender.as_monster();
const int added_dur = 30 + random2(50);
if (mon->has_ench(ENCH_FLAYED))
{
was_flayed = true;
mon_enchant flayed = mon->get_ench(ENCH_FLAYED);
flayed.duration = min(flayed.duration + added_dur, 150);
mon->update_ench(flayed);
}
else
{
mon_enchant flayed(ENCH_FLAYED, 1, &caster, added_dur);
mon->add_ench(flayed);
}
}
if (you.can_see(defender))
{
if (was_flayed)
{
mprf("Terrible wounds spread across more of %s body!",
defender.name(DESC_ITS).c_str());
}
else
{
mprf("Terrible wounds open up all over %s body!",
defender.name(DESC_ITS).c_str());
}
}
// Due to Deep Dwarf damage shaving, the player may take less than the intended
// amount of damage. Keep track of the actual amount of damage done by comparing
// hp before and after the player is hurt; use this as the actual value for
// flay damage to prevent the player from regaining extra hp when it wears off
const int orig_hp = defender.stat_hp();
defender.hurt(&caster, damage, BEAM_NONE,
KILLED_BY_MONSTER, "", "flay_damage", true);
defender.props["flay_damage"].get_int() += orig_hp - defender.stat_hp();
vector<coord_def> old_blood;
CrawlVector &new_blood = defender.props["flay_blood"].get_vector();
// Find current blood spatters
for (radius_iterator ri(defender.pos(), LOS_SOLID); ri; ++ri)
{
if (env.pgrid(*ri) & FPROP_BLOODY)
old_blood.push_back(*ri);
}
blood_spray(defender.pos(), defender.type, 20);
// Compute and store new blood spatters
unsigned int i = 0;
for (radius_iterator ri(defender.pos(), LOS_SOLID); ri; ++ri)
{
if (env.pgrid(*ri) & FPROP_BLOODY)
{
if (i < old_blood.size() && old_blood[i] == *ri)
++i;
else
new_blood.push_back(*ri);
}
}
}
/// What nonliving creatures are adjacent to the given location?
static vector<const actor*> _find_nearby_constructs(const monster &caster,
coord_def pos)
{
vector<const actor*> nearby_constructs;
for (adjacent_iterator ai(pos); ai; ++ai)
{
const actor* act = actor_at(*ai);
if (act && act->holiness() & MH_NONLIVING && mons_aligned(&caster, act))
nearby_constructs.push_back(act);
}
return nearby_constructs;
}
/// How many nonliving creatures are adjacent to the given location?
static int _count_nearby_constructs(const monster &caster, coord_def pos)
{
return _find_nearby_constructs(caster, pos).size();
}
/// What's a good description of nonliving creatures adjacent to the given point?
static string _describe_nearby_constructs(const monster &caster, coord_def pos)
{
const vector<const actor*> nearby_constructs
= _find_nearby_constructs(caster, pos);
if (!nearby_constructs.size())
return "";
const string name = nearby_constructs.back()->name(DESC_THE);
if (nearby_constructs.size() == 1)
return make_stringf(" and %s", name.c_str());
for (auto act : nearby_constructs)
if (act->name(DESC_THE) != name)
return " and the adjacent constructs";
return make_stringf(" and %s", pluralise_monster(name).c_str());
}
/// Cast Resonance Strike, blasting the caster's target with smitey damage.
static void _cast_resonance_strike(monster &caster, mon_spell_slot, bolt&)
{
actor* target = caster.get_foe();
if (!target)
return;
const int constructs = _count_nearby_constructs(caster, target->pos());
// base damage 3d(spell hd) (probably 3d12)
// + 1 die for every 2 adjacent constructs (so at 4 constructs, 5dhd)
dice_def dice = resonance_strike_base_damage(caster);
dice.num += div_rand_round(constructs, 2);
const int dam = target->apply_ac(dice.roll());
const string constructs_desc
= _describe_nearby_constructs(caster, target->pos());
if (you.see_cell(target->pos()))
{
mprf("A blast of power from the earth%s strikes %s!",
constructs_desc.c_str(),
target->name(DESC_THE).c_str());
}
target->hurt(&caster, dam, BEAM_MISSILE, KILLED_BY_BEAM,
"", "by a resonance strike");
}
static bool _spell_charged(monster *mons)
{
mon_enchant ench = mons->get_ench(ENCH_SPELL_CHARGED);
if (ench.ench == ENCH_NONE || ench.degree < max_mons_charge(mons->type))
{
if (ench.ench == ENCH_NONE)
{
mons->add_ench(mon_enchant(ENCH_SPELL_CHARGED, 1, mons,
INFINITE_DURATION));
}
else
{
ench.degree++;
mons->update_ench(ench);
}
if (!you.can_see(*mons))
return false;
string msg =
getSpeakString(make_stringf("%s charge",
mons->name(DESC_PLAIN, true).c_str())
.c_str());
if (!msg.empty())
{
msg = do_mon_str_replacements(msg, *mons);
mprf(mons->wont_attack() ? MSGCH_FRIEND_ENCHANT
: MSGCH_MONSTER_ENCHANT, "%s", msg.c_str());
}
return false;
}
mons->del_ench(ENCH_SPELL_CHARGED);
return true;
}
/// How much damage does the given monster do when casting Waterstrike?
dice_def waterstrike_damage(const monster &mons)
{
return dice_def(3, 7 + mons.spell_hd(SPELL_WATERSTRIKE));
}
/**
* How much damage does the given monster do when casting Resonance Strike,
* assuming no allied constructs are boosting damage?
*/
dice_def resonance_strike_base_damage(const monster &mons)
{
return dice_def(3, mons.spell_hd(SPELL_RESONANCE_STRIKE));
}
static const int MIN_DREAM_SUCCESS_POWER = 25;
static void _sheep_message(int num_sheep, int sleep_pow, actor& foe)
{
string message;
// Determine messaging based on sleep strength.
if (sleep_pow >= 125)
message = "You are overwhelmed by glittering dream dust!";
else if (sleep_pow >= 75)
message = "The dream sheep are wreathed in dream dust.";
else if (sleep_pow >= MIN_DREAM_SUCCESS_POWER)
{
message = make_stringf("The dream sheep shake%s wool and sparkle%s.",
num_sheep == 1 ? "s its" : " their",
num_sheep == 1 ? "s": "");
}
else // if sleep fails
{
message = make_stringf("The dream sheep ruffle%s wool and motes of "
"dream dust sparkle, to no effect.",
num_sheep == 1 ? "s its" : " their");
}
// Messaging for non-player targets
if (!foe.is_player() && you.see_cell(foe.pos()))
{
const char* pluralize = num_sheep == 1 ? "s": "";
const string foe_name = foe.name(DESC_THE);
if (sleep_pow)
{
mprf(foe.as_monster()->friendly() ? MSGCH_FRIEND_SPELL
: MSGCH_MONSTER_SPELL,
"As the sheep sparkle%s and sway%s, %s falls asleep.",
pluralize,
pluralize,
foe_name.c_str());
}
else // if dust strength failure for non-player
{
mprf(foe.as_monster()->friendly() ? MSGCH_FRIEND_SPELL
: MSGCH_MONSTER_SPELL,
"The dream sheep attempt%s to lull %s to sleep.",
pluralize,
foe_name.c_str());
mprf("%s is unaffected.", foe_name.c_str());
}
}
else if (foe.is_player())
{
mprf(MSGCH_MONSTER_SPELL, "%s%s", message.c_str(),
sleep_pow ? " You feel drowsy..." : "");
}
}
static void _dream_sheep_sleep(monster& mons, actor& foe)
{
// Shepherd the dream sheep.
int num_sheep = 0;
for (monster_near_iterator mi(foe.pos(), LOS_NO_TRANS); mi; ++mi)
if (mi->type == MONS_DREAM_SHEEP)
num_sheep++;
// The correlation between amount of sheep and duration of
// sleep is randomised, but bounds are 5 to 20 turns of sleep.
// More dream sheep are both more likely to succeed and to have a
// stronger effect. Too-weak attempts get blanked.
// Special note: a single sheep has a 1 in 25 chance to succeed.
int sleep_pow = min(150, random2(num_sheep * 25) + 1);
if (sleep_pow < MIN_DREAM_SUCCESS_POWER)
sleep_pow = 0;
// Communicate with the player.
_sheep_message(num_sheep, sleep_pow, foe);
// Put the player to sleep.
if (sleep_pow)
foe.put_to_sleep(&mons, sleep_pow, false);
}
// Draconian stormcaller upheaval. Simplified compared to the player version.
// Noisy! Causes terrain changes. Destroys doors/walls.
// TODO: Could use further simplification.
static void _mons_upheaval(monster& mons, actor& foe)
{
bolt beam;
beam.source_id = mons.mid;
beam.source_name = mons.name(DESC_THE).c_str();
beam.thrower = KILL_MON_MISSILE;
beam.range = LOS_RADIUS;
beam.damage = dice_def(3, 24);
beam.foe_ratio = random_range(20, 30);
beam.hit = AUTOMATIC_HIT;
beam.glyph = dchar_glyph(DCHAR_EXPLOSION);
beam.loudness = 10;
#ifdef USE_TILE
beam.tile_beam = -1;
#endif
beam.draw_delay = 0;
beam.target = mons.target;
string message = "";
switch (random2(4))
{
case 0:
beam.name = "blast of magma";
beam.flavour = BEAM_LAVA;
beam.colour = RED;
beam.hit_verb = "engulfs";
message = "Magma suddenly erupts from the ground!";
break;
case 1:
beam.name = "blast of ice";
beam.flavour = BEAM_ICE;
beam.colour = WHITE;
message = "A blizzard blasts the area with ice!";
break;
case 2:
beam.name = "cutting wind";
beam.flavour = BEAM_AIR;
beam.colour = LIGHTGRAY;
message = "A storm cloud blasts the area with cutting wind!";
break;
case 3:
beam.name = "blast of rubble";
beam.flavour = BEAM_FRAG;
beam.colour = BROWN;
message = "The ground shakes violently, spewing rubble!";
break;
default:
break;
}
vector<coord_def> affected;
affected.push_back(beam.target);
const int radius = 2;
for (radius_iterator ri(beam.target, radius, C_SQUARE, LOS_SOLID, true);
ri; ++ri)
{
if (!in_bounds(*ri) || cell_is_solid(*ri))
continue;
bool splash = true;
bool adj = adjacent(beam.target, *ri);
if (!adj)
splash = false;
if (adj || splash)
{
if (beam.flavour == BEAM_FRAG || !cell_is_solid(*ri))
affected.push_back(*ri);
}
}
for (coord_def pos : affected)
{
beam.draw(pos);
scaled_delay(25);
}
for (coord_def pos : affected)
{
beam.source = pos;
beam.target = pos;
beam.fire();
switch (beam.flavour)
{
case BEAM_LAVA:
if (grd(pos) == DNGN_FLOOR && !actor_at(pos) && coinflip())
{
temp_change_terrain(
pos, DNGN_LAVA,
random2(14) * BASELINE_DELAY,
TERRAIN_CHANGE_FLOOD);
}
break;
case BEAM_AIR:
if (!cell_is_solid(pos) && !cloud_at(pos) && coinflip())
place_cloud(CLOUD_STORM, pos, random2(7), &mons);
break;
case BEAM_FRAG:
if (((grd(pos) == DNGN_ROCK_WALL
|| grd(pos) == DNGN_CLEAR_ROCK_WALL
|| grd(pos) == DNGN_SLIMY_WALL)
&& x_chance_in_y(1, 4)
|| grd(pos) == DNGN_CLOSED_DOOR
|| grd(pos) == DNGN_RUNED_DOOR
|| grd(pos) == DNGN_OPEN_DOOR
|| grd(pos) == DNGN_SEALED_DOOR
|| grd(pos) == DNGN_GRATE))
{
noisy(30, pos);
destroy_wall(pos);
}
break;
default:
break;
}
}
}
static void _mons_tornado(monster *mons, bool is_vortex = false)
{
const int dur = is_vortex ? 30 : 60;
const string desc = is_vortex ? "vortex" : "great vortex";
const string prop = is_vortex ? "vortex_since" : "tornado_since";
const enchant_type ench = is_vortex ? ENCH_VORTEX : ENCH_TORNADO;
if (you.can_see(*mons))
{
bool flying = mons->airborne();
mprf("A %s of raging winds appears %s%s%s!",
desc.c_str(),
flying ? "around " : "and lifts ",
mons->name(DESC_THE).c_str(),
flying ? "" : " up!");
}
else if (you.see_cell(mons->pos()))
mprf("A %s of raging winds appears out of thin air!", desc.c_str());
mons->props[prop.c_str()].get_int() = you.elapsed_time;
mon_enchant me(ench, 0, mons, dur);
mons->add_ench(me);
if (mons->has_ench(ENCH_FLIGHT))
{
mon_enchant me2 = mons->get_ench(ENCH_FLIGHT);
me2.duration = me.duration;
mons->update_ench(me2);
}
else
mons->add_ench(mon_enchant(ENCH_FLIGHT, 0, mons, dur));
}
/**
* Make this monster cast a spell
*
* @param mons The monster casting
* @param pbolt The beam, possibly containing pre-done setup, to use
* for the spell. Not a reference because this function
shouldn't affect the original copy.
* @param spell_cast The spell to be cast.
* @param slot_flags The spell slot flags in mons->spells (is it an
* invocation, natural, shouty, etc.?)
* @param do_noise Whether to make noise (including casting messages).
*/
void mons_cast(monster* mons, bolt pbolt, spell_type spell_cast,
mon_spell_slot_flags slot_flags, bool do_noise)
{
// check sputtercast state for e.g. orb spiders. assumption: all
// sputtercasting monsters have one charge status and use it for all of
// their spells.
if (max_mons_charge(mons->type) > 0 && !_spell_charged(mons))
return;
if (spell_is_soh_breath(spell_cast))
{
const vector<spell_type> *breaths = soh_breath_spells(spell_cast);
ASSERT(breaths);
ASSERT(mons->heads() == (int)breaths->size());
for (spell_type head_spell : *breaths)
{
if (!mons->get_foe())
return;
setup_mons_cast(mons, pbolt, head_spell);
mons_cast(mons, pbolt, head_spell, slot_flags, do_noise);
}
return;
}
if (spell_cast == SPELL_LEGENDARY_DESTRUCTION)
{
if (do_noise)
{
mons_cast_noise(mons, pbolt, SPELL_LEGENDARY_DESTRUCTION,
slot_flags);
}
setup_mons_cast(mons, pbolt, SPELL_LEGENDARY_DESTRUCTION);
mons_cast(mons, pbolt, _legendary_destruction_spell(), slot_flags,
false);
if (!mons->get_foe())
return;
setup_mons_cast(mons, pbolt, SPELL_LEGENDARY_DESTRUCTION);
mons_cast(mons, pbolt, _legendary_destruction_spell(), slot_flags,
false);
return;
}
// Always do setup. It might be done already, but it doesn't hurt
// to do it again (cheap).
setup_mons_cast(mons, pbolt, spell_cast);
// single calculation permissible {dlb}
const unsigned int flags = get_spell_flags(spell_cast);
actor* const foe = mons->get_foe();
const mons_spell_logic* logic = map_find(spell_to_logic, spell_cast);
const mon_spell_slot slot = {spell_cast, 0, slot_flags};
int sumcount = 0;
int sumcount2;
int duration = 0;
dprf("Mon #%d casts %s (#%d)",
mons->mindex(), spell_title(spell_cast), spell_cast);
ASSERT(!(flags & SPFLAG_TESTING));
// Targeted spells need a valid target.
// Wizard-mode cast monster spells may target the boundary (shift-dir).
ASSERT(map_bounds(pbolt.target) || !(flags & SPFLAG_TARGETING_MASK));
// Maybe cast abjuration instead of certain summoning spells.
if (mons->can_see(you) && _mons_will_abjure(mons, spell_cast))
{
if (do_noise)
{
pbolt.range = 0;
pbolt.glyph = 0;
mons_cast_noise(mons, pbolt, SPELL_ABJURATION, MON_SPELL_NO_FLAGS);
}
_monster_abjuration(mons, true);
return;
}
if (spell_cast == SPELL_PORTAL_PROJECTILE
|| logic && (logic->flags & MSPELL_NO_AUTO_NOISE))
{
do_noise = false; // Spell itself does the messaging.
}
if (do_noise)
mons_cast_noise(mons, pbolt, spell_cast, slot_flags);
if (logic && logic->cast)
{
logic->cast(*mons, slot, pbolt);
return;
}
const god_type god = _find_god(*mons, slot_flags);
const int splpow = mons_spellpower(*mons, spell_cast);
switch (spell_cast)
{
default:
break;
case SPELL_WATERSTRIKE:
{
if (you.can_see(*foe))
{
if (foe->airborne())
mprf("The water rises up and strikes %s!", foe->name(DESC_THE).c_str());
else
mprf("The water swirls and strikes %s!", foe->name(DESC_THE).c_str());
}
pbolt.flavour = BEAM_WATER;
int damage_taken = waterstrike_damage(*mons).roll();
damage_taken = foe->beam_resists(pbolt, damage_taken, false);
damage_taken = foe->apply_ac(damage_taken);
foe->hurt(mons, damage_taken, BEAM_MISSILE, KILLED_BY_BEAM,
"", "by the raging water");
return;
}
case SPELL_AIRSTRIKE:
{
// Damage averages 14 for 5HD, 18 for 10HD, 28 for 20HD, +50% if flying.
if (foe->is_player())
{
if (you.airborne())
mpr("The air twists around and violently strikes you in flight!");
else
mpr("The air twists around and strikes you!");
}
else
{
simple_monster_message(*foe->as_monster(),
" is struck by the twisting air!");
}
pbolt.flavour = BEAM_AIR;
int damage_taken = 10 + 2 * mons->get_hit_dice();
damage_taken = foe->beam_resists(pbolt, damage_taken, false);
// Previous method of damage calculation (in line with player
// airstrike) had absurd variance.
damage_taken = foe->apply_ac(random2avg(damage_taken, 3));
foe->hurt(mons, damage_taken, BEAM_MISSILE, KILLED_BY_BEAM,
"", "by the air");
return;
}
case SPELL_HOLY_FLAMES:
holy_flames(mons, foe);
return;
case SPELL_BRAIN_FEED:
if (one_chance_in(3)
&& lose_stat(STAT_INT, 1 + random2(3)))
{
mpr("Something feeds on your intellect!");
xom_is_stimulated(50);
}
else
mpr("Something tries to feed on your intellect!");
return;
case SPELL_SUMMON_SPECTRAL_ORCS:
if (foe->is_player())
mpr("Orcish apparitions take form around you.");
else
simple_monster_message(*foe->as_monster(), " is surrounded by Orcish apparitions.");
_mons_cast_spectral_orcs(mons);
return;
case SPELL_HAUNT:
if (foe->is_player())
mpr("You feel haunted.");
else
mpr("You sense an evil presence.");
_mons_cast_haunt(mons);
return;
// SPELL_SLEEP_GAZE ;)
case SPELL_DREAM_DUST:
_dream_sheep_sleep(*mons, *foe);
return;
case SPELL_CONFUSION_GAZE:
{
const int res_margin = foe->check_res_magic(splpow / ENCH_POW_FACTOR);
if (res_margin > 0)
{
if (you.can_see(*foe))
{
mprf("%s%s",
foe->name(DESC_THE).c_str(),
foe->resist_margin_phrase(res_margin).c_str());
}
return;
}
foe->confuse(mons, 5 + random2(3));
return;
}
case SPELL_MAJOR_HEALING:
if (mons->heal(50 + random2avg(mons->spell_hd(spell_cast) * 10, 2)))
simple_monster_message(*mons, " is healed.");
return;
case SPELL_BERSERKER_RAGE:
mons->props.erase("brothers_count");
mons->go_berserk(true);
return;
#if TAG_MAJOR_VERSION == 34
// Replaced with monster-specific version.
case SPELL_SWIFTNESS:
#endif
case SPELL_SPRINT:
mons->add_ench(ENCH_SWIFT);
simple_monster_message(*mons, " puts on a burst of speed!");
return;
case SPELL_SILENCE:
mons->add_ench(ENCH_SILENCE);
invalidate_agrid(true);
simple_monster_message(*mons, "'s surroundings become eerily quiet.");
return;
case SPELL_CALL_TIDE:
if (player_in_branch(BRANCH_SHOALS))
{
const int tide_duration = BASELINE_DELAY
* random_range(80, 200, 2);
mons->add_ench(mon_enchant(ENCH_TIDE, 0, mons,
tide_duration));
mons->props[TIDE_CALL_TURN].get_int() = you.num_turns;
if (simple_monster_message(*
mons,
" sings a water chant to call the tide!"))
{
flash_view_delay(UA_MONSTER, ETC_WATER, 300);
}
}
return;
case SPELL_INK_CLOUD:
if (!feat_is_watery(grd(mons->pos())))
return;
big_cloud(CLOUD_INK, mons, mons->pos(), 30, 30);
simple_monster_message(*
mons,
" squirts a massive cloud of ink into the water!");
return;
#if TAG_MAJOR_VERSION == 34
case SPELL_VAMPIRE_SUMMON:
#endif
case SPELL_SUMMON_SMALL_MAMMAL:
sumcount2 = 1 + random2(3);
for (sumcount = 0; sumcount < sumcount2; ++sumcount)
{
monster_type rats[] = { MONS_QUOKKA, MONS_RIVER_RAT, MONS_RAT };
const monster_type mon = (one_chance_in(3) ? MONS_BAT
: RANDOM_ELEMENT(rats));
create_monster(
mgen_data(mon, SAME_ATTITUDE(mons), mons->pos(), mons->foe)
.set_summoned(mons, 5, spell_cast, god));
}
return;
case SPELL_STICKS_TO_SNAKES:
{
const int pow = (mons->spell_hd(spell_cast) * 15) / 10;
int cnt = 1 + random2(1 + pow / 4);
monster_type sum;
for (int i = 0; i < cnt; i++)
{
if (random2(mons->spell_hd(spell_cast)) > 27
|| one_chance_in(5 - min(4, div_rand_round(pow * 2, 25))))
{
sum = x_chance_in_y(pow / 3, 100) ? MONS_WATER_MOCCASIN
: MONS_ADDER;
}
else
sum = MONS_BALL_PYTHON;
if (create_monster(
mgen_data(sum, SAME_ATTITUDE(mons), mons->pos(), mons->foe)
.set_summoned(mons, 5, spell_cast, god)))
{
i++;
}
}
return;
}
case SPELL_SHADOW_CREATURES: // summon anything appropriate for level
{
level_id place = level_id::current();
sumcount2 = 1 + random2(mons->spell_hd(spell_cast) / 5 + 1);
for (sumcount = 0; sumcount < sumcount2; ++sumcount)
{
create_monster(
mgen_data(RANDOM_MOBILE_MONSTER, SAME_ATTITUDE(mons),
mons->pos(), mons->foe)
.set_summoned(mons, 5, spell_cast, god)
.set_place(place));
}
return;
}
case SPELL_SUMMON_ILLUSION:
_mons_cast_summon_illusion(mons, spell_cast);
return;
case SPELL_CREATE_TENTACLES:
mons_create_tentacles(mons);
return;
case SPELL_FAKE_MARA_SUMMON:
// We only want there to be two fakes, which, plus Mara, means
// a total of three Maras; if we already have two, give up, otherwise
// we want to summon either one more or two more.
sumcount2 = 2 - count_summons(mons, SPELL_FAKE_MARA_SUMMON);
if (sumcount2 <= 0)
return;
for (sumcount = 0; sumcount < sumcount2; sumcount++)
cast_phantom_mirror(mons, mons, 50, SPELL_FAKE_MARA_SUMMON);
if (you.can_see(*mons))
{
mprf("%s shimmers and seems to become %s!", mons->name(DESC_THE).c_str(),
sumcount2 == 1 ? "two"
: "three");
}
return;
case SPELL_SUMMON_DEMON: // class 3-4 demons
// if you change this, please update art-func.h:_DEMON_AXE_melee_effects
sumcount2 = 1 + random2(mons->spell_hd(spell_cast) / 10 + 1);
duration = min(2 + mons->spell_hd(spell_cast) / 10, 6);
for (sumcount = 0; sumcount < sumcount2; sumcount++)
{
create_monster(
mgen_data(summon_any_demon(RANDOM_DEMON_COMMON, true),
SAME_ATTITUDE(mons), mons->pos(), mons->foe)
.set_summoned(mons, duration, spell_cast, god));
}
return;
case SPELL_MONSTROUS_MENAGERIE:
cast_monstrous_menagerie(mons, splpow, mons->god);
return;
case SPELL_TWISTED_RESURRECTION:
// Double efficiency compared to maxed out player spell: one
// elf corpse gives 4.5 HD.
twisted_resurrection(mons, 500, SAME_ATTITUDE(mons),
mons->foe, god);
return;
case SPELL_CALL_IMP:
duration = min(2 + mons->spell_hd(spell_cast) / 5, 6);
create_monster(
mgen_data(random_choose_weighted(
1, MONS_IRON_IMP,
2, MONS_SHADOW_IMP,
2, MONS_WHITE_IMP,
4, MONS_CRIMSON_IMP),
SAME_ATTITUDE(mons), mons->pos(), mons->foe)
.set_summoned(mons, duration, spell_cast, god));
return;
case SPELL_SUMMON_MINOR_DEMON: // class 5 demons
sumcount2 = 1 + random2(3);
duration = min(2 + mons->spell_hd(spell_cast) / 5, 6);
for (sumcount = 0; sumcount < sumcount2; ++sumcount)
{
create_monster(
mgen_data(summon_any_demon(RANDOM_DEMON_LESSER, true),
SAME_ATTITUDE(mons), mons->pos(), mons->foe)
.set_summoned(mons, duration, spell_cast, god));
}
return;
case SPELL_SUMMON_UFETUBUS:
sumcount2 = 2 + random2(2);
duration = min(2 + mons->spell_hd(spell_cast) / 5, 6);
for (sumcount = 0; sumcount < sumcount2; ++sumcount)
{
create_monster(
mgen_data(MONS_UFETUBUS, SAME_ATTITUDE(mons), mons->pos(),
mons->foe)
.set_summoned(mons, duration, spell_cast, god));
}
return;
case SPELL_SUMMON_HELL_BEAST: // Geryon
create_monster(
mgen_data(MONS_HELL_BEAST, SAME_ATTITUDE(mons), mons->pos(),
mons->foe).set_summoned(mons, 4, spell_cast, god));
return;
case SPELL_SUMMON_ICE_BEAST:
_summon(*mons, MONS_ICE_BEAST, 5, slot);
return;
case SPELL_SUMMON_MUSHROOMS: // Summon a ring of icky crawling fungi.
sumcount2 = 2 + random2(mons->spell_hd(spell_cast) / 4 + 1);
duration = min(2 + mons->spell_hd(spell_cast) / 5, 6);
for (int i = 0; i < sumcount2; ++i)
{
// Attempt to place adjacent to target first, and only at a wider
// radius if no adjacent spots can be found
coord_def empty;
find_habitable_spot_near(mons->get_foe()->pos(),
MONS_WANDERING_MUSHROOM, 1, false, empty);
if (empty.origin())
{
find_habitable_spot_near(mons->get_foe()->pos(),
MONS_WANDERING_MUSHROOM, 2, false, empty);
}
// Can't find any room, so stop trying
if (empty.origin())
return;
create_monster(
mgen_data(one_chance_in(3) ? MONS_DEATHCAP
: MONS_WANDERING_MUSHROOM,
SAME_ATTITUDE(mons), empty, mons->foe, MG_FORCE_PLACE)
.set_summoned(mons, duration, spell_cast, god));
}
return;
case SPELL_SUMMON_HORRIBLE_THINGS:
_do_high_level_summon(mons, spell_cast, _pick_horrible_thing,
random_range(3, 5), god);
return;
case SPELL_MALIGN_GATEWAY:
if (!can_cast_malign_gateway())
{
dprf("ERROR: %s can't cast malign gateway, but is casting anyway! "
"Counted %d gateways.", mons->name(DESC_THE).c_str(),
count_malign_gateways());
}
cast_malign_gateway(mons, 200);
return;
case SPELL_CONJURE_BALL_LIGHTNING:
{
const int n = min(8, 2 + random2avg(mons->spell_hd(spell_cast) / 4, 2));
for (int i = 0; i < n; ++i)
{
if (monster *ball = create_monster(
mgen_data(MONS_BALL_LIGHTNING, SAME_ATTITUDE(mons),
mons->pos(), mons->foe)
.set_summoned(mons, 0, spell_cast, god)))
{
ball->add_ench(ENCH_SHORT_LIVED);
}
}
return;
}
#if TAG_MAJOR_VERSION == 34
case SPELL_CONTROL_UNDEAD:
#endif
case SPELL_SUMMON_UNDEAD:
_do_high_level_summon(mons, spell_cast, _pick_undead_summon,
2 + random2(mons->spell_hd(spell_cast) / 5 + 1),
god);
return;
case SPELL_BROTHERS_IN_ARMS:
{
// Invocation; don't use spell_hd
const int power = (mons->get_hit_dice() * 20)
+ random2(mons->get_hit_dice() * 5)
- random2(mons->get_hit_dice() * 5);
monster_type to_summon;
if (mons->type == MONS_SPRIGGAN_BERSERKER)
{
monster_type berserkers[] = { MONS_POLAR_BEAR, MONS_ELEPHANT,
MONS_DEATH_YAK };
to_summon = RANDOM_ELEMENT(berserkers);
}
else
{
monster_type berserkers[] = { MONS_BLACK_BEAR, MONS_OGRE, MONS_TROLL,
MONS_TWO_HEADED_OGRE, MONS_DEEP_TROLL };
to_summon = RANDOM_ELEMENT(berserkers);
}
summon_berserker(power, mons, to_summon);
mons->props["brothers_count"].get_int()++;
return;
}
case SPELL_SYMBOL_OF_TORMENT:
torment(mons, TORMENT_SPELL, mons->pos());
return;
case SPELL_MESMERISE:
_mons_mesmerise(mons);
return;
case SPELL_CAUSE_FEAR:
_mons_cause_fear(mons);
return;
case SPELL_OLGREBS_TOXIC_RADIANCE:
cast_toxic_radiance(mons, splpow);
return;
case SPELL_SHATTER:
mons_shatter(mons);
return;
case SPELL_CORPSE_ROT:
corpse_rot(mons);
return;
case SPELL_SUMMON_GREATER_DEMON:
duration = min(2 + mons->spell_hd(spell_cast) / 10, 6);
create_monster(
mgen_data(summon_any_demon(RANDOM_DEMON_GREATER, true),
SAME_ATTITUDE(mons), mons->pos(), mons->foe)
.set_summoned(mons, duration, spell_cast, god));
return;
// Journey -- Added in Summon Lizards
case SPELL_SUMMON_DRAKES:
sumcount2 = 1 + random2(mons->spell_hd(spell_cast) / 5 + 1);
duration = min(2 + mons->spell_hd(spell_cast) / 10, 6);
{
vector<monster_type> monsters;
for (sumcount = 0; sumcount < sumcount2; ++sumcount)
{
monster_type mon = _pick_drake();
monsters.push_back(mon);
}
for (monster_type type : monsters)
{
create_monster(
mgen_data(type, SAME_ATTITUDE(mons), mons->pos(),
mons->foe)
.set_summoned(mons, duration, spell_cast, god));
}
}
return;
case SPELL_DRUIDS_CALL:
_cast_druids_call(mons);
return;
case SPELL_BATTLESPHERE:
cast_battlesphere(mons, min(splpow, 200), mons->god, false);
return;
case SPELL_SPECTRAL_WEAPON:
cast_spectral_weapon(mons, min(splpow, 200), mons->god, false);
return;
case SPELL_TORNADO:
{
_mons_tornado(mons);
return;
}
case SPELL_VORTEX:
{
_mons_tornado(mons, true);
return;
}
case SPELL_SUMMON_HOLIES: // Holy monsters.
sumcount2 = 1 + random2(2)
+ random2(mons->spell_hd(spell_cast) / 4 + 1);
duration = min(2 + mons->spell_hd(spell_cast) / 5, 6);
for (int i = 0; i < sumcount2; ++i)
{
create_monster(
mgen_data(random_choose_weighted(
100, MONS_ANGEL, 80, MONS_CHERUB,
50, MONS_DAEVA, 1, MONS_OPHAN),
SAME_ATTITUDE(mons), mons->pos(), mons->foe)
.set_summoned(mons, duration, spell_cast, god));
}
return;
case SPELL_BLINK_OTHER:
{
// Allow the caster to comment on moving the foe.
string msg = getSpeakString(mons->name(DESC_PLAIN) + " blink_other");
if (!msg.empty() && msg != "__NONE")
{
mons_speaks_msg(mons, msg, MSGCH_TALK,
silenced(you.pos()) || silenced(mons->pos()));
}
break;
}
case SPELL_BLINK_OTHER_CLOSE:
{
// Allow the caster to comment on moving the foe.
string msg = getSpeakString(mons->name(DESC_PLAIN)
+ " blink_other_close");
if (!msg.empty() && msg != "__NONE")
{
mons_speaks_msg(mons, msg, MSGCH_TALK,
silenced(you.pos()) || silenced(mons->pos()));
}
break;
}
case SPELL_TOMB_OF_DOROKLOHE:
{
sumcount = 0;
const int hp_lost = mons->max_hit_points - mons->hit_points;
if (!hp_lost)
sumcount++;
static const set<dungeon_feature_type> safe_tiles =
{
DNGN_SHALLOW_WATER, DNGN_FLOOR, DNGN_OPEN_DOOR,
};
for (adjacent_iterator ai(mons->pos()); ai; ++ai)
{
const actor* act = actor_at(*ai);
// We can blink away the crowd, but only our allies.
if (act
&& (act->is_player()
|| (act->is_monster()
&& act->as_monster()->attitude != mons->attitude)))
{
sumcount++;
}
// Make sure we have a legitimate tile.
if (!safe_tiles.count(grd(*ai)) && !feat_is_trap(grd(*ai))
&& feat_is_reachable_past(grd(*ai)))
{
sumcount++;
}
}
if (sumcount)
{
mons->blink();
return;
}
sumcount = 0;
for (adjacent_iterator ai(mons->pos()); ai; ++ai)
{
if (monster_at(*ai))
{
monster_at(*ai)->blink();
if (monster_at(*ai))
{
monster_at(*ai)->teleport(true);
if (monster_at(*ai))
continue;
}
}
// Make sure we have a legitimate tile.
if (safe_tiles.count(grd(*ai)) || feat_is_trap(grd(*ai)))
{
// All items are moved inside.
if (igrd(*ai) != NON_ITEM)
move_items(*ai, mons->pos());
// All clouds are destroyed.
delete_cloud(*ai);
// All traps are destroyed.
if (trap_def *ptrap = trap_at(*ai))
ptrap->destroy();
// Actually place the wall.
temp_change_terrain(*ai, DNGN_ROCK_WALL, INFINITE_DURATION,
TERRAIN_CHANGE_TOMB, mons);
sumcount++;
}
}
if (sumcount)
{
mpr("Walls emerge from the floor!");
// XXX: Assume that the entombed monster can regenerate.
// Also, base the regeneration rate on HD to avoid
// randomness.
const int tomb_duration = BASELINE_DELAY
* hp_lost * max(1, mons->spell_hd(spell_cast) / 3);
int mon_index = mons->mindex();
env.markers.add(new map_tomb_marker(mons->pos(),
tomb_duration,
mon_index,
mon_index));
env.markers.clear_need_activate(); // doesn't need activation
}
return;
}
case SPELL_CHAIN_LIGHTNING:
cast_chain_spell(spell_cast, splpow, mons);
return;
case SPELL_SUMMON_EYEBALLS:
sumcount2 = 1 + random2(mons->spell_hd(spell_cast) / 7 + 1);
duration = min(2 + mons->spell_hd(spell_cast) / 10, 6);
for (sumcount = 0; sumcount < sumcount2; sumcount++)
{
const monster_type mon = random_choose_weighted(
100, MONS_FLOATING_EYE,
80, MONS_EYE_OF_DRAINING,
60, MONS_GOLDEN_EYE,
40, MONS_SHINING_EYE,
20, MONS_GREAT_ORB_OF_EYES,
10, MONS_EYE_OF_DEVASTATION);
create_monster(
mgen_data(mon, SAME_ATTITUDE(mons), mons->pos(), mons->foe)
.set_summoned(mons, duration, spell_cast, god));
}
return;
case SPELL_SUMMON_BUTTERFLIES:
duration = min(2 + mons->spell_hd(spell_cast) / 5, 6);
for (int i = 0; i < 10; ++i)
{
create_monster(
mgen_data(MONS_BUTTERFLY, SAME_ATTITUDE(mons),
mons->pos(), mons->foe)
.set_summoned(mons, duration, spell_cast, god));
}
return;
case SPELL_IOOD:
cast_iood(mons, 6 * mons->spell_hd(spell_cast), &pbolt);
return;
case SPELL_AWAKEN_FOREST:
if (!mons->friendly() && have_passive(passive_t::friendly_plants))
{
if (you.can_see(*mons))
{
mprf("%s commands the forest to attack, but nothing happens.",
mons->name(DESC_THE).c_str());
}
return;
}
duration = 50 + random2(mons->spell_hd(spell_cast) * 20);
mons->add_ench(mon_enchant(ENCH_AWAKEN_FOREST, 0, mons, duration));
// Actually, it's a boolean marker... save for a sanity check.
env.forest_awoken_until = you.elapsed_time + duration;
// You may be unable to see the monster, but notice an affected tree.
forest_message(mons->pos(), "The forest starts to sway and rumble!");
return;
case SPELL_SUMMON_DRAGON:
cast_summon_dragon(mons, splpow, god);
return;
case SPELL_SUMMON_HYDRA:
cast_summon_hydra(mons, splpow, god);
return;
case SPELL_FIRE_SUMMON:
sumcount2 = 1 + random2(mons->spell_hd(spell_cast) / 5 + 1);
duration = min(2 + mons->spell_hd(spell_cast) / 10, 6);
for (sumcount = 0; sumcount < sumcount2; sumcount++)
{
const monster_type mon = random_choose_weighted(
3, MONS_EFREET,
3, MONS_SUN_DEMON,
3, MONS_BALRUG,
2, MONS_HELLION,
1, MONS_BRIMSTONE_FIEND);
create_monster(
mgen_data(mon, SAME_ATTITUDE(mons), mons->pos(), mons->foe)
.set_summoned(mons, duration, spell_cast, god));
}
return;
case SPELL_REGENERATION:
{
simple_monster_message(*mons,
"'s wounds begin to heal before your eyes!");
const int dur = BASELINE_DELAY
* min(5 + roll_dice(2, (mons->spell_hd(spell_cast) * 10) / 3 + 1), 100);
mons->add_ench(mon_enchant(ENCH_REGENERATION, 0, mons, dur));
return;
}
case SPELL_OZOCUBUS_ARMOUR:
{
if (you.can_see(*mons))
{
mprf("A film of ice covers %s body!",
apostrophise(mons->name(DESC_THE)).c_str());
}
const int power = (mons->spell_hd(spell_cast) * 15) / 10;
mons->add_ench(mon_enchant(ENCH_OZOCUBUS_ARMOUR,
20 + random2(power) + random2(power),
mons));
return;
}
case SPELL_WORD_OF_RECALL:
{
mon_enchant chant_timer = mon_enchant(ENCH_WORD_OF_RECALL, 1, mons, 30);
mons->add_ench(chant_timer);
mons->speed_increment -= 30;
return;
}
case SPELL_INJURY_BOND:
{
simple_monster_message(*mons,
make_stringf(" begins to accept %s allies' injuries.",
mons->pronoun(PRONOUN_POSSESSIVE).c_str()).c_str());
// FIXME: allies preservers vs the player
for (monster_near_iterator mi(mons, LOS_NO_TRANS); mi; ++mi)
{
if (mons_aligned(mons, *mi) && !mi->has_ench(ENCH_CHARM)
&& !mi->has_ench(ENCH_HEXED) && *mi != mons)
{
mon_enchant bond = mon_enchant(ENCH_INJURY_BOND, 1, mons,
40 + random2(80));
mi->add_ench(bond);
}
}
return;
}
case SPELL_CALL_LOST_SOUL:
create_monster(mgen_data(MONS_LOST_SOUL, SAME_ATTITUDE(mons),
mons->pos(), mons->foe)
.set_summoned(mons, 2, spell_cast, god));
return;
case SPELL_BLINK_ALLIES_ENCIRCLE:
_blink_allies_encircle(mons);
return;
case SPELL_MASS_CONFUSION:
_mons_mass_confuse(mons);
return;
case SPELL_ENGLACIATION:
if (you.can_see(*mons))
simple_monster_message(*mons, " radiates an aura of cold.");
else if (mons->see_cell_no_trans(you.pos()))
mpr("A wave of cold passes over you.");
apply_area_visible([splpow, mons] (coord_def where) {
return englaciate(where, min(splpow, 200), mons);
}, mons->pos());
return;
case SPELL_AWAKEN_VINES:
_awaken_vines(mons);
return;
case SPELL_WALL_OF_BRAMBLES:
// If we can't cast this for some reason (can be expensive to determine
// at every call to _ms_waste_of_time), refund the energy for it so that
// the caster can do something else
if (!_wall_of_brambles(mons))
{
mons->speed_increment +=
get_monster_data(mons->type)->energy_usage.spell;
}
return;
case SPELL_WIND_BLAST:
{
// Wind blast is stopped by FFT_SOLID features.
if (foe && cell_see_cell(mons->pos(), foe->pos(), LOS_SOLID))
wind_blast(mons, splpow, foe->pos());
return;
}
case SPELL_FREEZE:
_mons_cast_freeze(mons);
return;
case SPELL_SUMMON_VERMIN:
_do_high_level_summon(mons, spell_cast, _pick_vermin,
one_chance_in(4) ? 3 : 2 , god);
return;
case SPELL_DISCHARGE:
cast_discharge(min(200, splpow), *mons);
return;
case SPELL_PORTAL_PROJECTILE:
{
// Swap weapons if necessary so that that happens before the spell
// casting message.
item_def *launcher = nullptr;
mons_usable_missile(mons, &launcher);
const item_def *weapon = mons->mslot_item(MSLOT_WEAPON);
if (launcher && launcher != weapon)
mons->swap_weapons();
mons_cast_noise(mons, pbolt, spell_cast, slot_flags);
handle_throw(mons, pbolt, true, false);
return;
}
case SPELL_IGNITE_POISON:
cast_ignite_poison(mons, splpow, false);
return;
case SPELL_BLACK_MARK:
_cast_black_mark(mons);
return;
#if TAG_MAJOR_VERSION == 34
case SPELL_REARRANGE_PIECES:
{
bool did_message = false;
vector<actor* > victims;
for (actor_near_iterator ai(mons, LOS_NO_TRANS); ai; ++ai)
victims.push_back(*ai);
shuffle_array(victims);
for (auto it = victims.begin(); it != victims.end(); it++)
{
actor* victim1 = *it;
it++;
if (it == victims.end())
break;
actor* victim2 = *it;
if (victim1->is_player())
swap_with_monster(victim2->as_monster());
else if (victim2->is_player())
swap_with_monster(victim1->as_monster());
else
{
if (!did_message
&& (you.can_see(*victim1)
|| you.can_see(*victim2)))
{
mpr("Some monsters swap places.");
did_message = true;
}
swap_monsters(victim1->as_monster(), victim2->as_monster());
}
}
return;
}
#endif
case SPELL_BLINK_ALLIES_AWAY:
_blink_allies_away(mons);
return;
case SPELL_SHROUD_OF_GOLUBRIA:
if (you.can_see(*mons))
{
mprf("Space distorts along a thin shroud covering %s %s.",
apostrophise(mons->name(DESC_THE)).c_str(),
mons->is_insubstantial() ? "form" : "body");
}
mons->add_ench(mon_enchant(ENCH_SHROUD));
return;
case SPELL_DAZZLING_SPRAY:
{
vector<bolt> beams = get_spray_rays(mons, pbolt.target, pbolt.range, 3,
ZAP_DAZZLING_SPRAY);
for (bolt &child : beams)
{
bolt_parent_init(pbolt, child);
child.fire();
}
return;
}
case SPELL_GLACIATE:
{
ASSERT(foe);
cast_glaciate(mons, splpow, foe->pos());
return;
}
case SPELL_CLOUD_CONE:
{
ASSERT(mons->get_foe());
cast_cloud_cone(mons, splpow, mons->get_foe()->pos());
return;
}
case SPELL_PHANTOM_MIRROR:
{
// Find appropriate ally to clone.
vector<monster*> targets;
for (monster_near_iterator mi(mons); mi; ++mi)
{
if (_mirrorable(mons, *mi))
targets.push_back(*mi);
}
// If we've found something, mirror it.
if (targets.size())
{
monster* targ = targets[random2(targets.size())];
if (cast_phantom_mirror(mons, targ))
simple_monster_message(*targ, " shimmers and seems to become two!");
}
return;
}
case SPELL_SUMMON_MANA_VIPER:
{
const int num_vipers = 1 + random2(mons->spell_hd(spell_cast) / 5 + 1);
for (int i = 0; i < num_vipers; ++i)
_summon(*mons, MONS_MANA_VIPER, 2, slot);
return;
}
case SPELL_SUMMON_EMPEROR_SCORPIONS:
{
const int num_scorps = 1 + random2(mons->spell_hd(spell_cast) / 5 + 1);
for (int i = 0; i < num_scorps; ++i)
_summon(*mons, MONS_EMPEROR_SCORPION, 5, slot);
return;
}
case SPELL_BATTLECRY:
_battle_cry(*mons);
return;
case SPELL_WARNING_CRY:
return; // the entire point is the noise, handled elsewhere
case SPELL_SEAL_DOORS:
_seal_doors_and_stairs(mons);
return;
case SPELL_BERSERK_OTHER:
_incite_monsters(mons, true);
return;
case SPELL_SPELLFORGED_SERVITOR:
{
monster* servitor = _summon(*mons, MONS_SPELLFORGED_SERVITOR, 4, slot);
if (servitor)
init_servitor(servitor, mons);
else if (you.can_see(*mons))
canned_msg(MSG_NOTHING_HAPPENS);
return;
}
case SPELL_CORRUPTING_PULSE:
_corrupting_pulse(mons);
return;
case SPELL_THROW_ALLY:
_maybe_throw_ally(*mons);
return;
case SPELL_SIREN_SONG:
_siren_sing(mons, false);
return;
case SPELL_AVATAR_SONG:
_siren_sing(mons, true);
return;
case SPELL_REPEL_MISSILES:
simple_monster_message(*mons, " begins repelling missiles!");
mons->add_ench(mon_enchant(ENCH_REPEL_MISSILES));
return;
case SPELL_DEFLECT_MISSILES:
simple_monster_message(*mons, " begins deflecting missiles!");
mons->add_ench(mon_enchant(ENCH_DEFLECT_MISSILES));
return;
case SPELL_SUMMON_SCARABS:
{
const int num_scarabs = 1 + random2(mons->spell_hd(spell_cast) / 5 + 1);
for (int i = 0; i < num_scarabs; ++i)
_summon(*mons, MONS_DEATH_SCARAB, 2, slot);
return;
}
case SPELL_SCATTERSHOT:
{
ASSERT(foe);
cast_scattershot(mons, splpow, foe->pos());
return;
}
case SPELL_CLEANSING_FLAME:
simple_monster_message(*mons, " channels a blast of cleansing flame!");
cleansing_flame(5 + (5 * mons->spell_hd(spell_cast) / 12),
CLEANSING_FLAME_SPELL, mons->pos(), mons);
return;
case SPELL_GRAVITAS:
fatal_attraction(foe->pos(), mons, splpow);
return;
case SPELL_ENTROPIC_WEAVE:
foe->corrode_equipment("the entropic weave");
return;
case SPELL_SUMMON_EXECUTIONERS:
{
const int num_exec = 1 + random2(mons->spell_hd(spell_cast) / 5 + 1);
duration = min(2 + mons->spell_hd(spell_cast) / 10, 6);
for (int i = 0; i < num_exec; ++i)
_summon(*mons, MONS_EXECUTIONER, duration, slot);
return;
}
case SPELL_DOOM_HOWL:
_doom_howl(*mons);
break;
case SPELL_CALL_OF_CHAOS:
_mons_call_of_chaos(*mons);
return;
case SPELL_AURA_OF_BRILLIANCE:
simple_monster_message(*mons, " begins emitting a brilliant aura!");
mons->add_ench(ENCH_BRILLIANCE_AURA);
aura_of_brilliance(mons);
return;
case SPELL_BIND_SOULS:
simple_monster_message(*mons, " binds the souls of nearby monsters.");
for (monster_near_iterator mi(mons, LOS_NO_TRANS); mi; ++mi)
{
if (*mi == mons)
continue;
if (_mons_can_bind_soul(mons, *mi))
{
mi->add_ench(
mon_enchant(ENCH_BOUND_SOUL, 0, mons,
random_range(10, 30) * BASELINE_DELAY));
}
}
return;
case SPELL_GREATER_SERVANT_MAKHLEB:
{
const monster_type servants[] = { MONS_EXECUTIONER, MONS_GREEN_DEATH,
MONS_BLIZZARD_DEMON, MONS_BALRUG,
MONS_CACODEMON };
_summon(*mons, RANDOM_ELEMENT(servants), 5, slot);
return;
}
case SPELL_UPHEAVAL:
_mons_upheaval(*mons, *foe);
return;
}
if (spell_is_direct_explosion(spell_cast))
_fire_direct_explosion(*mons, slot, pbolt);
else
_fire_simple_beam(*mons, slot, pbolt);
}
static int _noise_level(const monster* mons, spell_type spell,
bool silent, mon_spell_slot_flags slot_flags)
{
const unsigned int flags = get_spell_flags(spell);
int noise;
if (silent
|| (slot_flags & MON_SPELL_INNATE_MASK
&& !(slot_flags & MON_SPELL_NOISY)
&& !(flags & SPFLAG_NOISY)))
{
noise = 0;
}
else if (mons_genus(mons->type) == MONS_DRAGON)
noise = get_shout_noise_level(S_LOUD_ROAR);
else
noise = spell_noise(spell);
return noise;
}
static void _speech_keys(vector<string>& key_list,
const monster* mons, const bolt& pbolt,
spell_type spell, mon_spell_slot_flags slot_flags,
bool targeted)
{
const string cast_str = " cast";
// Can't use copy-initialization 'wizard = slot_flags & ...' here,
// because the bitfield-to-bool conversion is not implicit.
const bool wizard {slot_flags & MON_SPELL_WIZARD};
const bool priest {slot_flags & MON_SPELL_PRIEST};
const bool natural {slot_flags & MON_SPELL_NATURAL};
const bool magical {slot_flags & MON_SPELL_MAGICAL};
const mon_body_shape shape = get_mon_shape(*mons);
const string spell_name = spell_title(spell);
const bool real_spell = priest || wizard;
// Before just using generic per-spell and per-monster casts, try
// per-monster, per-spell, with the monster type name, then the
// species name, then the genus name, then wizard/priest/magical/natural.
// We don't include "real" or "gestures" here since that can be
// be determined from the monster type; or "targeted" since that
// can be determined from the spell.
key_list.push_back(spell_name + " "
+ mons_type_name(mons->type, DESC_PLAIN) + cast_str);
key_list.push_back(spell_name + " "
+ mons_type_name(mons_species(mons->type), DESC_PLAIN)
+ cast_str);
key_list.push_back(spell_name + " "
+ mons_type_name(mons_genus(mons->type), DESC_PLAIN)
+ cast_str);
if (wizard)
{
key_list.push_back(make_stringf("%s %swizard%s",
spell_name.c_str(),
mon_shape_is_humanoid(shape) ? ""
: "non-humanoid ",
cast_str.c_str()));
}
else if (priest)
key_list.push_back(spell_name + " priest" + cast_str);
else if (magical)
key_list.push_back(spell_name + " magical" + cast_str);
else if (natural)
key_list.push_back(spell_name + " natural" + cast_str);
// Now try just the spell's name.
if (mon_shape_is_humanoid(shape))
{
if (real_spell)
key_list.push_back(spell_name + cast_str + " real");
if (mons_intel(*mons) >= I_HUMAN)
key_list.push_back(spell_name + cast_str + " gestures");
}
key_list.push_back(spell_name + cast_str);
// Only postfix "targeted" after this point.
const unsigned int num_spell_keys = key_list.size();
// Next the monster type name, then species name, then genus name.
key_list.push_back(mons_type_name(mons->type, DESC_PLAIN) + cast_str);
key_list.push_back(mons_type_name(mons_species(mons->type), DESC_PLAIN)
+ cast_str);
key_list.push_back(mons_type_name(mons_genus(mons->type), DESC_PLAIN)
+ cast_str);
// Last, generic wizard, priest or magical.
if (wizard)
{
key_list.push_back(make_stringf("%swizard%s",
mon_shape_is_humanoid(shape) ? ""
: "non-humanoid ",
cast_str.c_str()));
}
else if (priest)
key_list.push_back("priest" + cast_str);
else if (magical)
key_list.push_back("magical" + cast_str);
if (targeted)
{
// For targeted spells, try with the targeted suffix first.
for (unsigned int i = key_list.size() - 1; i >= num_spell_keys; i--)
{
string str = key_list[i] + " targeted";
key_list.insert(key_list.begin() + i, str);
}
// Generic beam messages.
if (pbolt.visible())
{
key_list.push_back(pbolt.get_short_name() + " beam " + cast_str);
key_list.emplace_back("beam catchall cast");
}
}
}
static string _speech_message(const vector<string>& key_list,
bool silent, bool unseen)
{
string prefix;
if (silent)
prefix = "silent ";
else if (unseen)
prefix = "unseen ";
string msg;
for (const string &key : key_list)
{
#ifdef DEBUG_MONSPEAK
dprf(DIAG_SPEECH, "monster casting lookup: %s%s",
prefix.c_str(), key.c_str());
#endif
msg = getSpeakString(prefix + key);
if (msg == "__NONE")
{
msg = "";
break;
}
else if (!msg.empty())
break;
// If we got no message and we're using the silent prefix, then
// try again without the prefix.
if (prefix != "silent ")
continue;
msg = getSpeakString(key);
if (msg == "__NONE")
{
msg = "";
break;
}
else if (!msg.empty())
break;
}
return msg;
}
static void _speech_fill_target(string& targ_prep, string& target,
const monster* mons, const bolt& pbolt,
bool gestured)
{
targ_prep = "at";
target = "nothing";
bolt tracer = pbolt;
// For a targeted but rangeless spell make the range positive so that
// fire_tracer() will fill out path_taken.
if (pbolt.range == 0 && pbolt.target != mons->pos())
tracer.range = ENV_SHOW_DIAMETER;
fire_tracer(mons, tracer);
if (pbolt.target == you.pos())
target = "you";
else if (pbolt.target == mons->pos())
target = mons->pronoun(PRONOUN_REFLEXIVE);
// Monsters should only use targeted spells while foe == MHITNOT
// if they're targeting themselves.
else if (mons->foe == MHITNOT && !mons_is_confused(*mons, true))
target = "NONEXISTENT FOE";
else if (!invalid_monster_index(mons->foe)
&& menv[mons->foe].type == MONS_NO_MONSTER)
{
target = "DEAD FOE";
}
else if (in_bounds(pbolt.target) && you.see_cell(pbolt.target))
{
if (const monster* mtarg = monster_at(pbolt.target))
{
if (you.can_see(*mtarg))
target = mtarg->name(DESC_THE);
}
}
const bool visible_path = pbolt.visible() || gestured;
// Monster might be aiming past the real target, or maybe some fuzz has
// been applied because the target is invisible.
if (target == "nothing")
{
if (pbolt.aimed_at_spot || pbolt.origin_spell == SPELL_DIG)
{
int count = 0;
for (adjacent_iterator ai(pbolt.target); ai; ++ai)
{
const actor* act = actor_at(*ai);
if (act && act != mons && you.can_see(*act))
{
targ_prep = "next to";
if (act->is_player() || one_chance_in(++count))
target = act->name(DESC_THE);
if (act->is_player())
break;
}
}
if (targ_prep == "at")
{
if (grd(pbolt.target) != DNGN_FLOOR)
{
target = feature_description(grd(pbolt.target),
NUM_TRAPS, "", DESC_THE,
false);
}
else
target = "thin air";
}
return;
}
bool mons_targ_aligned = false;
for (const coord_def pos : tracer.path_taken)
{
if (pos == mons->pos())
continue;
const monster* m = monster_at(pos);
if (pos == you.pos())
{
// Be egotistical and assume that the monster is aiming at
// the player, rather than the player being in the path of
// a beam aimed at an ally.
if (!mons->wont_attack())
{
targ_prep = "at";
target = "you";
break;
}
// If the ally is confused or aiming at an invisible enemy,
// with the player in the path, act like it's targeted at
// the player if there isn't any visible target earlier
// in the path.
else if (target == "nothing")
{
targ_prep = "at";
target = "you";
mons_targ_aligned = true;
}
}
else if (visible_path && m && you.can_see(*m))
{
bool is_aligned = mons_aligned(m, mons);
string name = m->name(DESC_THE);
if (target == "nothing")
{
mons_targ_aligned = is_aligned;
target = name;
}
// If the first target was aligned with the beam source then
// the first subsequent non-aligned monster in the path will
// take it's place.
else if (mons_targ_aligned && !is_aligned)
{
mons_targ_aligned = false;
target = name;
}
targ_prep = "at";
}
else if (visible_path && target == "nothing")
{
int count = 0;
for (adjacent_iterator ai(pbolt.target); ai; ++ai)
{
const actor* act = monster_at(*ai);
if (act && act != mons && you.can_see(*act))
{
targ_prep = "past";
if (act->is_player()
|| one_chance_in(++count))
{
target = act->name(DESC_THE);
}
if (act->is_player())
break;
}
}
}
} // for (const coord_def pos : path)
} // if (target == "nothing" && targeted)
const actor* foe = mons->get_foe();
// If we still can't find what appears to be the target, and the
// monster isn't just throwing the spell in a random direction,
// we should be able to tell what the monster was aiming for if
// we can see the monster's foe and the beam (or the beam path
// implied by gesturing). But only if the beam didn't actually hit
// anything (but if it did hit something, why didn't that monster
// show up in the beam's path?)
if (target == "nothing"
&& (tracer.foe_info.count + tracer.friend_info.count) == 0
&& foe != nullptr
&& you.can_see(*foe)
&& !mons->confused()
&& visible_path)
{
target = foe->name(DESC_THE);
targ_prep = (pbolt.aimed_at_spot ? "next to" : "past");
}
// If the monster gestures to create an invisible beam then
// assume that anything close to the beam is the intended target.
// Also, if the monster gestures to create a visible beam but it
// misses still say that the monster gestured "at" the target,
// rather than "past".
if (gestured || target == "nothing")
targ_prep = "at";
// "throws whatever at something" is better than "at nothing"
if (target == "nothing")
target = "something";
}
void mons_cast_noise(monster* mons, const bolt &pbolt,
spell_type spell_cast, mon_spell_slot_flags slot_flags)
{
bool force_silent = false;
if (mons->type == MONS_SHADOW_DRAGON)
// Draining breath is silent.
force_silent = true;
const bool unseen = !you.can_see(*mons);
const bool silent = silenced(mons->pos()) || force_silent;
if (unseen && silent)
return;
int noise = _noise_level(mons, spell_cast, silent, slot_flags);
const unsigned int spell_flags = get_spell_flags(spell_cast);
const bool targeted = (spell_flags & SPFLAG_TARGETING_MASK)
&& (pbolt.target != mons->pos()
|| pbolt.visible());
vector<string> key_list;
_speech_keys(key_list, mons, pbolt, spell_cast, slot_flags, targeted);
string msg = _speech_message(key_list, silent, unseen);
if (msg.empty())
{
if (silent)
return;
noisy(noise, mons->pos(), mons->mid);
return;
}
// FIXME: we should not need to look at the message text.
const bool gestured = msg.find("Gesture") != string::npos
|| msg.find(" gesture") != string::npos
|| msg.find("Point") != string::npos
|| msg.find(" point") != string::npos;
string targ_prep = "at";
string target = "NO_TARGET";
if (targeted)
_speech_fill_target(targ_prep, target, mons, pbolt, gestured);
msg = replace_all(msg, "@at@", targ_prep);
msg = replace_all(msg, "@target@", target);
string beam_name;
if (!targeted)
beam_name = "NON TARGETED BEAM";
else if (pbolt.name.empty())
beam_name = "INVALID BEAM";
else
beam_name = pbolt.get_short_name();
msg = replace_all(msg, "@beam@", beam_name);
const msg_channel_type chan =
(unseen ? MSGCH_SOUND :
mons->friendly() ? MSGCH_FRIEND_SPELL
: MSGCH_MONSTER_SPELL);
if (silent || noise == 0)
mons_speaks_msg(mons, msg, chan, true);
else if (noisy(noise, mons->pos(), mons->mid) || !unseen)
{
// noisy() returns true if the player heard the noise.
mons_speaks_msg(mons, msg, chan);
}
}
static const int MIN_THROW_DIST = 2;
static bool _valid_throw_dest(const actor &thrower, const actor &victim,
const coord_def pos)
{
return thrower.pos().distance_from(pos) >= MIN_THROW_DIST
&& !actor_at(pos)
&& victim.is_habitable(pos)
&& thrower.see_cell(pos);
}
/**
* Choose a landing site for a monster that is throwing someone.
*
* @param thrower The monster performing the toss.
* @param victim The actor being thrown.
* @param rater A function that takes thrower, victim, and an arbitrary
* coord_def and determines how good the throw is; a higher
* number is better.
* @return The coord_def of one of the best (as determined by rater)
* possible landing sites for a toss.
* If no valid site is found, returns the origin (0,0).
*/
static coord_def _choose_throwing_target(const monster &thrower,
const actor &victim,
function<int (const monster&, const actor&,
coord_def)> rater)
{
int best_site_score = -1;
vector<coord_def> best_sites;
for (distance_iterator di(thrower.pos(), true, true, LOS_RADIUS); di; ++di)
{
ray_def ray;
// Unusable landing sites.
if (!_valid_throw_dest(thrower, victim, *di)
|| !find_ray(thrower.pos(), *di, ray, opc_solid_see))
{
continue;
}
const int site_score = rater(thrower, victim, *di);
if (site_score > best_site_score)
{
best_site_score = site_score;
best_sites.clear();
}
if (site_score == best_site_score)
best_sites.push_back(*di);
}
// No valid landing site found.
if (!best_sites.size())
return coord_def(0,0);
const coord_def best_site = best_sites[random2(best_sites.size())];
return best_site;
}
static bool _will_throw_ally(const monster& thrower, const monster& throwee)
{
switch (thrower.type)
{
case MONS_ROBIN:
return throwee.mons_species() == MONS_GOBLIN;
case MONS_POLYPHEMUS:
return mons_genus(throwee.type) == MONS_YAK;
case MONS_IRON_GIANT:
return !mons_is_conjured(throwee.type);
default:
return false;
}
}
static monster* _find_ally_to_throw(const monster &mons)
{
const actor *foe = mons.get_foe();
if (!foe)
return nullptr;
int furthest_dist = -1;
monster* best = nullptr;
for (fair_adjacent_iterator ai(mons.pos(), true); ai; ++ai)
{
monster* throwee = monster_at(*ai);
if (!throwee || !throwee->alive() || !mons_aligned(&mons, throwee)
|| !_will_throw_ally(mons, *throwee))
{
continue;
}
// Don't try to throw anything constricted.
if (throwee->is_constricted())
continue;
// otherwise throw whoever's furthest from our target.
const int dist = grid_distance(throwee->pos(), foe->pos());
if (dist > furthest_dist)
{
best = throwee;
furthest_dist = dist;
}
}
if (best != nullptr)
dprf("found a monster to toss");
else
dprf("couldn't find anyone to toss");
return best;
}
/**
* Toss an ally at the monster's foe, landing them in the given square after
* maybe dealing a pittance of damage.
*
* XXX: some duplication with tentacle toss code
*
* @param thrower The monster doing the throwing.
* @param throwee The monster being tossed.
* @param chosen_dest The location of the square throwee should land on.
*/
static void _throw_ally_to(const monster &thrower, monster &throwee,
const coord_def chosen_dest)
{
ASSERT_IN_BOUNDS(chosen_dest);
ASSERT(!throwee.is_constricted());
actor* foe = thrower.get_foe();
ASSERT(foe);
const coord_def old_pos = throwee.pos();
const bool thrower_seen = you.can_see(thrower);
const bool throwee_was_seen = you.can_see(throwee);
const bool throwee_will_be_seen = throwee.visible_to(&you)
&& you.see_cell(chosen_dest);
const bool throwee_seen = throwee_was_seen || throwee_will_be_seen;
if (!(throwee.flags & MF_WAS_IN_VIEW))
throwee.seen_context = SC_THROWN_IN;
if (thrower_seen || throwee_seen)
{
const string destination = you.can_see(*foe) ?
make_stringf("at %s",
foe->name(DESC_THE).c_str()) :
"out of sight";
mprf("%s throws %s %s!",
(thrower_seen ? thrower.name(DESC_THE).c_str() : "Something"),
(throwee_seen ? throwee.name(DESC_THE, true).c_str() : "something"),
destination.c_str());
bolt beam;
beam.range = INFINITE_DISTANCE;
beam.hit = AUTOMATIC_HIT;
beam.flavour = BEAM_VISUAL;
beam.source = thrower.pos();
beam.target = chosen_dest;
beam.glyph = mons_char(throwee.type);
const monster_info mi(&throwee);
beam.colour = mi.colour();
beam.draw_delay = 30; // Make beam animation somewhat slower than normal.
beam.aimed_at_spot = true;
beam.fire();
}
throwee.move_to_pos(chosen_dest);
throwee.apply_location_effects(old_pos);
throwee.check_redraw(old_pos);
const string killed_by = make_stringf("Hit by %s thrown by %s",
throwee.name(DESC_A, true).c_str(),
thrower.name(DESC_PLAIN, true).c_str());
const int dam = foe->apply_ac(random2(thrower.get_hit_dice() * 2));
foe->hurt(&thrower, dam, BEAM_NONE, KILLED_BY_BEAM, "", killed_by, true);
// wake sleepy goblins
behaviour_event(&throwee, ME_DISTURB, &thrower, throwee.pos());
}
static int _throw_ally_site_score(const monster& thrower, const actor& throwee,
coord_def pos)
{
const actor *foe = thrower.get_foe();
if (!foe || !adjacent(foe->pos(), pos))
return -2;
return grid_distance(thrower.pos(), pos);
}
static void _maybe_throw_ally(const monster &mons)
{
monster* throwee = _find_ally_to_throw(mons);
if (!throwee)
return;
const coord_def toss_target =
_choose_throwing_target(mons, *static_cast<actor*>(throwee),
_throw_ally_site_score);
if (toss_target.origin())
return;
_throw_ally_to(mons, *throwee, toss_target);
}
/**
* Check if a siren or merfolk avatar should sing its song.
*
* @param mons The singing monster.
* @param avatar Whether to use the more powerful "avatar song".
* @return Whether the song should be sung.
*/
static bool _should_siren_sing(monster* mons, bool avatar)
{
// Don't behold observer in the arena.
if (crawl_state.game_is_arena())
return false;
// Don't behold player already half down or up the stairs.
if (player_stair_delay())
{
dprf("Taking stairs, don't mesmerise.");
return false;
}
// Won't sing if either of you silenced, or it's friendly,
// confused, fleeing, or leaving the level.
if (mons->has_ench(ENCH_CONFUSION)
|| mons_is_fleeing(*mons)
|| mons->pacified()
|| mons->friendly()
|| !player_can_hear(mons->pos()))
{
return false;
}
// Don't even try on berserkers. Sirens know their limits.
// (merfolk avatars should still sing since their song has other effects)
if (!avatar && you.berserk())
return false;
// If the mer is trying to mesmerise you anew, only sing half as often.
if (!you.beheld_by(*mons) && mons->foe == MHITYOU && you.can_see(*mons)
&& coinflip())
{
return false;
}
// We can do it!
return true;
}
/**
* Have a monster attempt to cast Doom Howl.
*
* @param mon The howling monster.
*/
static void _doom_howl(monster &mon)
{
mprf("%s unleashes a %s howl, and it begins to echo in your mind!",
mon.name(DESC_THE).c_str(),
silenced(mon.pos()) ? "silent" : "terrible");
you.duration[DUR_DOOM_HOWL] = random_range(120, 180);
mon.props[DOOM_HOUND_HOWLED_KEY] = true;
}
/**
* Have a monster cast Awaken Earth.
*
* @param mon The monster casting the spell.
* @param target The target cell.
*/
static void _mons_awaken_earth(monster &mon, const coord_def &target)
{
if (!in_bounds(target))
{
if (you.can_see(mon))
canned_msg(MSG_NOTHING_HAPPENS);
return;
}
bool seen = false;
int count = 0;
const int max = 1 + (mon.spell_hd(SPELL_AWAKEN_EARTH) > 15)
+ random2(mon.spell_hd(SPELL_AWAKEN_EARTH) / 7 + 1);
for (fair_adjacent_iterator ai(target, false); ai; ++ai)
{
if (!_feat_is_awakenable(grd(*ai))
|| env.markers.property_at(*ai, MAT_ANY, "veto_dig")
== "veto")
{
continue;
}
destroy_wall(*ai);
if (you.see_cell(*ai))
seen = true;
if (create_monster(mgen_data(
MONS_EARTH_ELEMENTAL, SAME_ATTITUDE((&mon)), *ai, mon.foe)
.set_summoned(&mon, 2, SPELL_AWAKEN_EARTH, mon.god)))
{
count++;
}
if (count >= max)
break;
}
if (seen)
{
noisy(20, target);
mprf("Some walls %s!",
count > 0 ? "begin to move on their own"
: "crumble away");
}
else
noisy(20, target, "You hear rumbling.");
if (!seen && !count && you.can_see(mon))
canned_msg(MSG_NOTHING_HAPPENS);
}
/**
* Have a siren or merfolk avatar attempt to mesmerize the player.
*
* @param mons The singing monster.
* @param avatar Whether to use the more powerful "avatar song".
*/
static void _siren_sing(monster* mons, bool avatar)
{
const msg_channel_type spl = (mons->friendly() ? MSGCH_FRIEND_SPELL
: MSGCH_MONSTER_SPELL);
const bool already_mesmerised = you.beheld_by(*mons);
noisy(LOS_DEFAULT_RANGE, mons->pos(), mons->mid);
if (avatar && !mons->has_ench(ENCH_MERFOLK_AVATAR_SONG))
mons->add_ench(mon_enchant(ENCH_MERFOLK_AVATAR_SONG, 0, mons, 70));
if (you.can_see(*mons))
{
const char * const song_adj = already_mesmerised ? "its luring"
: "a haunting";
const string song_desc = make_stringf(" chants %s song.", song_adj);
simple_monster_message(*mons, song_desc.c_str(), spl);
}
else
{
mprf(MSGCH_SOUND, "You hear %s.",
already_mesmerised ? "a luring song" :
coinflip() ? "a haunting song"
: "an eerie melody");
// If you're already mesmerised by an invisible siren, it
// can still prolong the enchantment.
if (!already_mesmerised)
return;
}
// power is the same for siren & avatar song, so just use siren
const int pow = _ench_power(SPELL_SIREN_SONG, *mons);
const int res_magic = you.check_res_magic(pow);
// Once mesmerised by a particular monster, you cannot resist anymore.
if (you.duration[DUR_MESMERISE_IMMUNE]
|| !already_mesmerised
&& (res_magic > 0 || you.clarity()))
{
if (you.clarity())
canned_msg(MSG_YOU_UNAFFECTED);
else if (you.duration[DUR_MESMERISE_IMMUNE] && !already_mesmerised)
canned_msg(MSG_YOU_RESIST);
else
mprf("You%s", you.resist_margin_phrase(res_magic).c_str());
return;
}
you.add_beholder(*mons);
}
// Checks to see if a particular spell is worth casting in the first place.
static bool _ms_waste_of_time(monster* mon, mon_spell_slot slot)
{
spell_type monspell = slot.spell;
actor *foe = mon->get_foe();
const bool friendly = mon->friendly();
// Keep friendly summoners from spamming summons constantly.
if (friendly && !foe && spell_typematch(monspell, SPTYP_SUMMONING))
return true;
// Don't try to cast spells at players who are stepped from time.
if (foe && foe->is_player() && you.duration[DUR_TIME_STEP])
return true;
if (!mon->wont_attack())
{
if (spell_harms_area(monspell) && env.sanctuary_time > 0)
return true;
if (spell_harms_target(monspell) && is_sanctuary(mon->target))
return true;
}
if (slot.flags & MON_SPELL_BREATH && mon->has_ench(ENCH_BREATH_WEAPON))
return true;
// Don't bother casting a summon spell if we're already at its cap
if (summons_are_capped(monspell)
&& count_summons(mon, monspell) >= summons_limit(monspell))
{
return true;
}
const mons_spell_logic* logic = map_find(spell_to_logic, monspell);
if (logic && logic->worthwhile)
return !logic->worthwhile(*mon);
const bool no_clouds = env.level_state & LSTATE_STILL_WINDS;
// Eventually, we'll probably want to be able to have monsters
// learn which of their elemental bolts were resisted and have those
// handled here as well. - bwr
switch (monspell)
{
case SPELL_CALL_TIDE:
return !player_in_branch(BRANCH_SHOALS)
|| mon->has_ench(ENCH_TIDE)
|| !foe
|| (grd(mon->pos()) == DNGN_DEEP_WATER
&& grd(foe->pos()) == DNGN_DEEP_WATER);
case SPELL_BRAIN_FEED:
return !foe || !foe->is_player();
case SPELL_BOLT_OF_DRAINING:
case SPELL_MALIGN_OFFERING:
case SPELL_GHOSTLY_FIREBALL:
return !foe || _foe_should_res_negative_energy(foe);
case SPELL_DEATH_RATTLE:
case SPELL_MIASMA_BREATH:
return !foe || foe->res_rotting() || no_clouds;
case SPELL_DISPEL_UNDEAD:
// [ds] How is dispel undead intended to interact with vampires?
// Currently if the vampire's undead state returns MH_UNDEAD it
// affects the player.
return !foe || !(foe->holiness() & MH_UNDEAD);
case SPELL_BERSERKER_RAGE:
return !mon->needs_berserk(false);
#if TAG_MAJOR_VERSION == 34
case SPELL_SWIFTNESS:
#endif
case SPELL_SPRINT:
return mon->has_ench(ENCH_SWIFT);
case SPELL_REGENERATION:
return mon->has_ench(ENCH_REGENERATION);
case SPELL_MAJOR_HEALING:
return mon->hit_points > mon->max_hit_points / 2;
case SPELL_BLINK_CLOSE:
if (!foe || adjacent(mon->pos(), foe->pos()))
return true;
// intentional fall-through
case SPELL_BLINK:
case SPELL_CONTROLLED_BLINK:
case SPELL_BLINK_RANGE:
case SPELL_BLINK_AWAY:
// Prefer to keep a tornado going rather than blink.
return mon->no_tele(true, false)
|| mon->has_ench(ENCH_TORNADO)
|| mon->has_ench(ENCH_VORTEX);
case SPELL_BLINK_OTHER:
case SPELL_BLINK_OTHER_CLOSE:
return !foe
|| foe->is_monster()
&& foe->as_monster()->has_ench(ENCH_DIMENSION_ANCHOR)
|| foe->is_player()
&& you.duration[DUR_DIMENSION_ANCHOR];
case SPELL_DREAM_DUST:
return !_foe_can_sleep(*mon);
// Mara shouldn't cast player ghost if he can't see the player
case SPELL_SUMMON_ILLUSION:
return !foe
|| !mon->see_cell_no_trans(foe->pos())
|| !mon->can_see(*foe)
|| !actor_is_illusion_cloneable(foe);
case SPELL_AWAKEN_FOREST:
return mon->has_ench(ENCH_AWAKEN_FOREST)
|| env.forest_awoken_until > you.elapsed_time
|| !forest_near_enemy(mon);
case SPELL_OZOCUBUS_ARMOUR:
return mon->is_insubstantial() || mon->has_ench(ENCH_OZOCUBUS_ARMOUR);
case SPELL_BATTLESPHERE:
return find_battlesphere(mon);
case SPELL_SPECTRAL_WEAPON:
return find_spectral_weapon(mon)
|| !weapon_can_be_spectral(mon->weapon())
|| !foe
// Don't cast unless the caster is at or close to melee range for
// its target. Casting spectral weapon at distance is bad since it
// generally helps the caster's target maintain distance, also
// letting the target exploit the spectral's damage sharing.
|| grid_distance(mon->pos(), foe->pos()) > 2;
case SPELL_INJURY_BOND:
for (monster_iterator mi; mi; ++mi)
{
if (mons_aligned(mon, *mi) && !mi->has_ench(ENCH_CHARM)
&& !mi->has_ench(ENCH_HEXED)
&& *mi != mon && mon->see_cell_no_trans(mi->pos())
&& !mi->has_ench(ENCH_INJURY_BOND))
{
return false; // We found at least one target; that's enough.
}
}
return true;
case SPELL_BLINK_ALLIES_ENCIRCLE:
if (!foe || !mon->see_cell_no_trans(foe->pos()) || !mon->can_see(*foe))
return true;
for (monster_near_iterator mi(mon, LOS_NO_TRANS); mi; ++mi)
if (_valid_encircle_ally(mon, *mi, foe->pos()))
return false; // We found at least one valid ally; that's enough.
return true;
case SPELL_AWAKEN_VINES:
return !foe
|| mon->has_ench(ENCH_AWAKEN_VINES)
&& mon->props["vines_awakened"].get_int() >= 3
|| !_awaken_vines(mon, true);
case SPELL_WATERSTRIKE:
return !foe || !feat_is_watery(grd(foe->pos()));
// Don't use unless our foe is close to us and there are no allies already
// between the two of us
case SPELL_WIND_BLAST:
if (foe && foe->pos().distance_from(mon->pos()) < 4)
{
bolt tracer;
tracer.target = foe->pos();
tracer.range = LOS_RADIUS;
tracer.hit = AUTOMATIC_HIT;
fire_tracer(mon, tracer);
actor* act = actor_at(tracer.path_taken.back());
if (act && mons_aligned(mon, act))
return true;
else
return false;
}
else
return true;
case SPELL_BROTHERS_IN_ARMS:
return mon->props.exists("brothers_count")
&& mon->props["brothers_count"].get_int() >= 2;
case SPELL_HAUNT:
case SPELL_SUMMON_SPECTRAL_ORCS:
case SPELL_SUMMON_MUSHROOMS:
case SPELL_ENTROPIC_WEAVE:
case SPELL_AIRSTRIKE:
return !foe;
case SPELL_HOLY_FLAMES:
return !foe || no_clouds;
case SPELL_FREEZE:
return !foe || !adjacent(mon->pos(), foe->pos());
case SPELL_DRUIDS_CALL:
// Don't cast unless there's at least one valid target
for (monster_iterator mi; mi; ++mi)
if (_valid_druids_call_target(mon, *mi))
return false;
return true;
// Don't spam mesmerisation if you're already mesmerised
case SPELL_MESMERISE:
return you.beheld_by(*mon) && coinflip();
case SPELL_DISCHARGE:
// TODO: possibly check for friendlies nearby?
// Perhaps it will be used recklessly like chain lightning...
return !foe || !adjacent(foe->pos(), mon->pos());
case SPELL_PORTAL_PROJECTILE:
{
bolt beam;
beam.source = mon->pos();
beam.target = mon->target;
beam.source_id = mon->mid;
return !handle_throw(mon, beam, true, true);
}
case SPELL_FLASH_FREEZE:
return !foe
|| foe->is_player() && you.duration[DUR_FROZEN]
|| foe->is_monster()
&& foe->as_monster()->has_ench(ENCH_FROZEN);
case SPELL_LEGENDARY_DESTRUCTION:
return !foe;
case SPELL_BLACK_MARK:
return mon->has_ench(ENCH_BLACK_MARK);
case SPELL_BLINK_ALLIES_AWAY:
if (!foe || !mon->see_cell_no_trans(foe->pos()) && !mon->can_see(*foe))
return true;
for (monster_near_iterator mi(mon, LOS_NO_TRANS); mi; ++mi)
if (_valid_blink_away_ally(mon, *mi, foe->pos()))
return false;
return true;
case SPELL_SHROUD_OF_GOLUBRIA:
return mon->has_ench(ENCH_SHROUD);
// Don't let clones duplicate anything, to prevent exponential explosion
case SPELL_FAKE_MARA_SUMMON:
return mon->has_ench(ENCH_PHANTOM_MIRROR);
case SPELL_PHANTOM_MIRROR:
if (!mon->has_ench(ENCH_PHANTOM_MIRROR))
{
for (monster_near_iterator mi(mon); mi; ++mi)
{
// A single valid target is enough.
if (_mirrorable(mon, *mi))
return false;
}
}
return true;
case SPELL_THROW_BARBS:
case SPELL_HARPOON_SHOT:
// Don't fire barbs in melee range.
return !foe || adjacent(mon->pos(), foe->pos());
case SPELL_BATTLECRY:
return !_battle_cry(*mon, true);
case SPELL_WARNING_CRY:
return friendly;
case SPELL_CONJURE_BALL_LIGHTNING:
return friendly
&& (you.res_elec() <= 0 || you.hp <= 50)
&& !(mon->holiness() & MH_DEMONIC); // rude demons
case SPELL_SEAL_DOORS:
return friendly || !_seal_doors_and_stairs(mon, true);
case SPELL_TWISTED_RESURRECTION:
if (friendly && !_animate_dead_okay(monspell))
return true;
if (mon->is_summoned())
return true;
return !twisted_resurrection(mon, 500, SAME_ATTITUDE(mon), mon->foe,
mon->god, false);
//XXX: unify with the other SPELL_FOO_OTHER spells?
case SPELL_BERSERK_OTHER:
return !_incite_monsters(mon, false);
case SPELL_CAUSE_FEAR:
return _mons_cause_fear(mon, false) < 0;
case SPELL_MASS_CONFUSION:
return _mons_mass_confuse(mon, false) < 0;
case SPELL_THROW_ALLY:
return !_find_ally_to_throw(*mon);
case SPELL_CREATE_TENTACLES:
return !mons_available_tentacles(mon);
case SPELL_WORD_OF_RECALL:
return !_should_recall(mon);
case SPELL_SHATTER:
return friendly || !mons_shatter(mon, false);
case SPELL_SYMBOL_OF_TORMENT:
return !_trace_los(mon, _torment_vulnerable)
|| you.visible_to(mon)
&& friendly
&& !player_res_torment(false)
&& !player_kiku_res_torment();
case SPELL_CHAIN_LIGHTNING:
return !_trace_los(mon, _elec_vulnerable)
|| you.visible_to(mon) && friendly; // don't zap player
case SPELL_CORRUPTING_PULSE:
return !_trace_los(mon, _mutation_vulnerable)
|| you.visible_to(mon)
&& friendly;
case SPELL_TORNADO:
return mon->has_ench(ENCH_TORNADO)
|| mon->has_ench(ENCH_TORNADO_COOLDOWN)
|| !_trace_los(mon, _tornado_vulnerable)
|| you.visible_to(mon) && friendly // don't cast near the player
&& !(mon->holiness() & MH_DEMONIC); // demons are rude
case SPELL_VORTEX:
return mon->has_ench(ENCH_VORTEX)
|| mon->has_ench(ENCH_VORTEX_COOLDOWN)
|| !_trace_los(mon, _tornado_vulnerable)
|| you.visible_to(mon) && friendly
&& !(mon->holiness() & MH_DEMONIC);
case SPELL_ENGLACIATION:
return !foe
|| !mon->see_cell_no_trans(foe->pos())
|| foe->res_cold() > 0;
case SPELL_OLGREBS_TOXIC_RADIANCE:
return mon->has_ench(ENCH_TOXIC_RADIANCE)
|| cast_toxic_radiance(mon, 100, false, true) != SPRET_SUCCESS;
case SPELL_IGNITE_POISON:
return cast_ignite_poison(mon, 0, false, true) != SPRET_SUCCESS;
case SPELL_GLACIATE:
return !foe
|| !_glaciate_tracer(mon, mons_spellpower(*mon, monspell),
foe->pos());
case SPELL_CLOUD_CONE:
return !foe || no_clouds
|| !mons_should_cloud_cone(mon, mons_spellpower(*mon, monspell),
foe->pos());
case SPELL_MALIGN_GATEWAY:
return !can_cast_malign_gateway();
case SPELL_SIREN_SONG:
return !_should_siren_sing(mon, false);
case SPELL_AVATAR_SONG:
return !_should_siren_sing(mon, true);
case SPELL_REPEL_MISSILES:
return mon->has_ench(ENCH_REPEL_MISSILES);
case SPELL_DEFLECT_MISSILES:
return mon->has_ench(ENCH_DEFLECT_MISSILES);
case SPELL_CONFUSION_GAZE:
return !foe || !mon->can_see(*foe);
case SPELL_SCATTERSHOT:
return !foe
|| !scattershot_tracer(mon, mons_spellpower(*mon, monspell),
foe->pos());
case SPELL_CLEANSING_FLAME:
{
bolt tracer;
setup_cleansing_flame_beam(tracer,
5 + (7 * mon->spell_hd(monspell)) / 12,
CLEANSING_FLAME_SPELL, mon->pos(), mon);
fire_tracer(mon, tracer, true);
return !mons_should_fire(tracer);
}
case SPELL_GRAVITAS:
if (!foe)
return true;
for (actor_near_iterator ai(foe->pos(), LOS_SOLID); ai; ++ai)
if (*ai != mon && *ai != foe && !ai->is_stationary()
&& mon->can_see(**ai))
{
return false;
}
return true;
case SPELL_DOOM_HOWL:
return !foe || !foe->is_player() || you.duration[DUR_DOOM_HOWL]
|| mon->props[DOOM_HOUND_HOWLED_KEY]
|| mon->is_summoned();
case SPELL_CALL_OF_CHAOS:
return !_mons_call_of_chaos(*mon, true);
case SPELL_AURA_OF_BRILLIANCE:
if (mon->has_ench(ENCH_BRILLIANCE_AURA) || !foe || !mon->can_see(*foe))
return true;
for (monster_near_iterator mi(mon, LOS_NO_TRANS); mi; ++mi)
if (_valid_aura_of_brilliance_ally(mon, *mi))
return false;
return true;
case SPELL_BIND_SOULS:
for (monster_near_iterator mi(mon, LOS_NO_TRANS); mi; ++mi)
if (_mons_can_bind_soul(mon, *mi))
return false;
return true;
case SPELL_CORPSE_ROT:
case SPELL_POISONOUS_CLOUD:
case SPELL_FREEZING_CLOUD:
case SPELL_MEPHITIC_CLOUD:
case SPELL_NOXIOUS_CLOUD:
case SPELL_SPECTRAL_CLOUD:
case SPELL_FLAMING_CLOUD:
case SPELL_CHAOS_BREATH:
return no_clouds;
#if TAG_MAJOR_VERSION == 34
case SPELL_SUMMON_TWISTER:
case SPELL_SHAFT_SELF:
case SPELL_MISLEAD:
case SPELL_SUMMON_SCORPIONS:
case SPELL_SUMMON_SWARM:
case SPELL_SUMMON_ELEMENTAL:
case SPELL_EPHEMERAL_INFUSION:
case SPELL_SINGULARITY:
case SPELL_GRAND_AVATAR:
case SPELL_INNER_FLAME:
case SPELL_ANIMATE_DEAD:
case SPELL_SIMULACRUM:
case SPELL_CHANT_FIRE_STORM:
case SPELL_IGNITE_POISON_SINGLE:
case SPELL_CONDENSATION_SHIELD:
case SPELL_STONESKIN:
case SPELL_HUNTING_CRY:
case SPELL_CONTROL_WINDS:
case SPELL_DEATHS_DOOR:
case SPELL_FULMINANT_PRISM:
case SPELL_CONTROL_UNDEAD:
#endif
case SPELL_NO_SPELL:
return true;
default:
return false;
}
}
static string _god_name(god_type god)
{
return god_has_name(god) ? god_name(god) : "Something";
}
|
/* Copyright 2007-2015 QReal Research Group
*
* 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 "kitBase/devicesConfigurationProvider.h"
using namespace kitBase;
using namespace robotModel;
DevicesConfigurationProvider::DevicesConfigurationProvider(const QString &name)
: mName(name)
{
}
DevicesConfigurationProvider::~DevicesConfigurationProvider()
{
disconnectDevicesConfigurationProvider();
mConnectedProviders.clear();
}
void DevicesConfigurationProvider::connectDevicesConfigurationProvider(
DevicesConfigurationProvider * const otherProvider)
{
if (!otherProvider) {
return;
}
if (!mConnectedProviders.contains(otherProvider)) {
mConnectedProviders << otherProvider;
otherProvider->connectDevicesConfigurationProvider(this);
}
// Copying unknown devices configuration from connected provider.
for (const QString &robotModel : otherProvider->configuredModels()) {
for (const kitBase::robotModel::PortInfo &port : otherProvider->configuredPorts(robotModel)) {
if (!mCurrentConfiguration.contains(robotModel) || !mCurrentConfiguration[robotModel].contains(port)) {
mCurrentConfiguration[robotModel][port] = otherProvider->currentConfiguration(robotModel, port);
}
}
}
}
void DevicesConfigurationProvider::disconnectDevicesConfigurationProvider(
DevicesConfigurationProvider * const provider)
{
if (!provider) {
return;
}
mConnectedProviders.removeOne(provider);
}
void DevicesConfigurationProvider::disconnectDevicesConfigurationProvider()
{
for (DevicesConfigurationProvider *provider : mConnectedProviders) {
provider->disconnectDevicesConfigurationProvider(this);
}
}
void DevicesConfigurationProvider::deviceConfigurationChanged(const QString &robotModel
, const PortInfo &port, const DeviceInfo &device, Reason reason)
{
if (mCurrentConfiguration[robotModel][port] != device) {
mCurrentConfiguration[robotModel][port] = device;
for (DevicesConfigurationProvider * const provider : mConnectedProviders) {
// Broadcast change.
provider->deviceConfigurationChanged(robotModel, port, device, reason);
// Allow connected providers to react on configuration change.
provider->onDeviceConfigurationChanged(robotModel, port, device, reason);
}
}
}
void DevicesConfigurationProvider::onDeviceConfigurationChanged(const QString &robotModel
, const PortInfo &port, const DeviceInfo &sensor, Reason reason)
{
Q_UNUSED(robotModel)
Q_UNUSED(port);
Q_UNUSED(sensor);
Q_UNUSED(reason);
}
void DevicesConfigurationProvider::clearConfiguration(Reason reason)
{
for (const QString &robotModel : mCurrentConfiguration.keys()) {
for (const PortInfo &port : mCurrentConfiguration[robotModel].keys()) {
deviceConfigurationChanged(robotModel, port, DeviceInfo(), reason);
}
}
}
QStringList DevicesConfigurationProvider::configuredModels() const
{
return mCurrentConfiguration.keys();
}
QList<robotModel::PortInfo> DevicesConfigurationProvider::configuredPorts(const QString &modelName) const
{
if (!mCurrentConfiguration.contains(modelName)) {
return {};
}
return mCurrentConfiguration[modelName].keys();
}
robotModel::DeviceInfo DevicesConfigurationProvider::currentConfiguration(const QString &modelName
, const robotModel::PortInfo &port) const
{
if (!mCurrentConfiguration.contains(modelName) || !mCurrentConfiguration[modelName].contains(port)) {
return robotModel::DeviceInfo();
}
return mCurrentConfiguration[modelName][port];
}
|
// Copyright (c) 2009 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/in_process_webkit/indexed_db_key_utility_client.h"
#include <vector>
#include "chrome/browser/browser_process.h"
#include "chrome/common/indexed_db_key.h"
#include "chrome/common/serialized_script_value.h"
IndexedDBKeyUtilityClient::IndexedDBKeyUtilityClient()
: waitable_event_(false, false),
state_(STATE_UNINITIALIZED),
utility_process_host_(NULL) {
}
IndexedDBKeyUtilityClient::~IndexedDBKeyUtilityClient() {
DCHECK(state_ == STATE_UNINITIALIZED || state_ == STATE_SHUTDOWN);
DCHECK(!utility_process_host_);
DCHECK(!client_.get());
}
void IndexedDBKeyUtilityClient::StartUtilityProcess() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));
DCHECK(state_ == STATE_UNINITIALIZED);
GetRDHAndStartUtilityProcess();
bool ret = waitable_event_.Wait();
DCHECK(ret && state_ == STATE_INITIALIZED);
}
void IndexedDBKeyUtilityClient::EndUtilityProcess() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));
DCHECK(state_ == STATE_INITIALIZED);
EndUtilityProcessInternal();
bool ret = waitable_event_.Wait();
DCHECK(ret && state_ == STATE_SHUTDOWN);
}
void IndexedDBKeyUtilityClient::CreateIDBKeysFromSerializedValuesAndKeyPath(
const std::vector<SerializedScriptValue>& values,
const string16& key_path,
std::vector<IndexedDBKey>* keys) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));
DCHECK(state_ == STATE_INITIALIZED);
state_ = STATE_CREATING_KEYS;
CallStartIDBKeyFromValueAndKeyPathFromIOThread(values, key_path);
bool ret = waitable_event_.Wait();
DCHECK(ret && state_ == STATE_INITIALIZED);
*keys = keys_;
}
void IndexedDBKeyUtilityClient::GetRDHAndStartUtilityProcess() {
// In order to start the UtilityProcess, we need to grab
// a pointer to the ResourceDispatcherHost. This can only
// be done on the UI thread. See the comment at the top of
// browser_process.h
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
NewRunnableMethod(
this,
&IndexedDBKeyUtilityClient::GetRDHAndStartUtilityProcess));
return;
}
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
StartUtilityProcessInternal(g_browser_process->resource_dispatcher_host());
}
void IndexedDBKeyUtilityClient::StartUtilityProcessInternal(
ResourceDispatcherHost* rdh) {
DCHECK(rdh);
// The ResourceDispatcherHost can only be used on the IO thread.
if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
NewRunnableMethod(
this,
&IndexedDBKeyUtilityClient::StartUtilityProcessInternal,
rdh));
return;
}
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
DCHECK(state_ == STATE_UNINITIALIZED);
client_ = new IndexedDBKeyUtilityClient::Client(this);
utility_process_host_ = new UtilityProcessHost(
rdh, client_.get(), BrowserThread::IO);
utility_process_host_->StartBatchMode();
state_ = STATE_INITIALIZED;
waitable_event_.Signal();
}
void IndexedDBKeyUtilityClient::EndUtilityProcessInternal() {
if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
NewRunnableMethod(
this,
&IndexedDBKeyUtilityClient::EndUtilityProcessInternal));
return;
}
utility_process_host_->EndBatchMode();
utility_process_host_ = NULL;
client_ = NULL;
state_ = STATE_SHUTDOWN;
waitable_event_.Signal();
}
void IndexedDBKeyUtilityClient::CallStartIDBKeyFromValueAndKeyPathFromIOThread(
const std::vector<SerializedScriptValue>& values,
const string16& key_path) {
if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
NewRunnableMethod(this,
&IndexedDBKeyUtilityClient::
CallStartIDBKeyFromValueAndKeyPathFromIOThread,
values, key_path));
return;
}
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
utility_process_host_->StartIDBKeysFromValuesAndKeyPath(
0, values, key_path);
}
void IndexedDBKeyUtilityClient::SetKeys(const std::vector<IndexedDBKey>& keys) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
keys_ = keys;
}
void IndexedDBKeyUtilityClient::FinishCreatingKeys() {
DCHECK(state_ == STATE_CREATING_KEYS);
state_ = STATE_INITIALIZED;
waitable_event_.Signal();
}
IndexedDBKeyUtilityClient::Client::Client(IndexedDBKeyUtilityClient* parent)
: parent_(parent) {
}
void IndexedDBKeyUtilityClient::Client::OnProcessCrashed(int exit_code) {
if (parent_->state_ == STATE_CREATING_KEYS)
parent_->FinishCreatingKeys();
}
void IndexedDBKeyUtilityClient::Client::OnIDBKeysFromValuesAndKeyPathSucceeded(
int id, const std::vector<IndexedDBKey>& keys) {
parent_->SetKeys(keys);
parent_->FinishCreatingKeys();
}
void IndexedDBKeyUtilityClient::Client::OnIDBKeysFromValuesAndKeyPathFailed(
int id) {
parent_->FinishCreatingKeys();
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkSTLReader.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkSTLReader.h"
#include "vtkByteSwap.h"
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkErrorCode.h"
#include "vtkFloatArray.h"
#include "vtkIncrementalPointLocator.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkMergePoints.h"
#include "vtkObjectFactory.h"
#include "vtkPolyData.h"
#include "vtkSmartPointer.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include <algorithm>
#include <ctype.h>
#include <stdexcept>
#include <string>
#include <vtksys/SystemTools.hxx>
vtkStandardNewMacro(vtkSTLReader);
#define VTK_ASCII 0
#define VTK_BINARY 1
vtkCxxSetObjectMacro(vtkSTLReader, Locator, vtkIncrementalPointLocator);
//------------------------------------------------------------------------------
// Construct object with merging set to true.
vtkSTLReader::vtkSTLReader()
{
this->FileName = NULL;
this->Merging = 1;
this->ScalarTags = 0;
this->Locator = NULL;
this->SetNumberOfInputPorts(0);
}
//------------------------------------------------------------------------------
vtkSTLReader::~vtkSTLReader()
{
this->SetFileName(0);
this->SetLocator(0);
}
//------------------------------------------------------------------------------
// Overload standard modified time function. If locator is modified,
// then this object is modified as well.
unsigned long vtkSTLReader::GetMTime()
{
unsigned long mTime1 = this->Superclass::GetMTime();
if (this->Locator)
{
unsigned long mTime2 = this->Locator->GetMTime();
mTime1 = std::max(mTime1, mTime2);
}
return mTime1;
}
//------------------------------------------------------------------------------
int vtkSTLReader::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **vtkNotUsed(inputVector),
vtkInformationVector *outputVector)
{
vtkInformation *outInfo = outputVector->GetInformationObject(0);
vtkPolyData *output = vtkPolyData::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
// All of the data in the first piece.
if (outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) > 0)
{
return 0;
}
if (!this->FileName || *this->FileName == 0)
{
vtkErrorMacro(<<"A FileName must be specified.");
this->SetErrorCode(vtkErrorCode::NoFileNameError);
return 0;
}
// Initialize
FILE *fp = fopen(this->FileName, "r");
if (fp == NULL)
{
vtkErrorMacro(<< "File " << this->FileName << " not found");
this->SetErrorCode(vtkErrorCode::CannotOpenFileError);
return 0;
}
vtkPoints *newPts = vtkPoints::New();
vtkCellArray *newPolys = vtkCellArray::New();
vtkFloatArray *newScalars = 0;
// Depending upon file type, read differently
if (this->GetSTLFileType(this->FileName) == VTK_ASCII)
{
newPts->Allocate(5000);
newPolys->Allocate(10000);
if (this->ScalarTags)
{
newScalars = vtkFloatArray::New();
newScalars->Allocate(5000);
}
if (!this->ReadASCIISTL(fp, newPts, newPolys, newScalars))
{
fclose(fp);
return 0;
}
}
else
{
// Close file and reopen in binary mode.
fclose(fp);
fp = fopen(this->FileName, "rb");
if (fp == NULL)
{
vtkErrorMacro(<< "File " << this->FileName << " not found");
this->SetErrorCode(vtkErrorCode::CannotOpenFileError);
return 0;
}
if (!this->ReadBinarySTL(fp, newPts, newPolys))
{
fclose(fp);
return 0;
}
}
vtkDebugMacro(<< "Read: "
<< newPts->GetNumberOfPoints() << " points, "
<< newPolys->GetNumberOfCells() << " triangles");
fclose(fp);
// If merging is on, create hash table and merge points/triangles.
vtkPoints *mergedPts = newPts;
vtkCellArray *mergedPolys = newPolys;
vtkFloatArray *mergedScalars = newScalars;
if (this->Merging)
{
mergedPts = vtkPoints::New();
mergedPts->Allocate(newPts->GetNumberOfPoints() /2);
mergedPolys = vtkCellArray::New();
mergedPolys->Allocate(newPolys->GetSize());
if (newScalars)
{
mergedScalars = vtkFloatArray::New();
mergedScalars->Allocate(newPolys->GetSize());
}
vtkSmartPointer<vtkIncrementalPointLocator> locator = this->Locator;
if (this->Locator == NULL)
{
locator.TakeReference(this->NewDefaultLocator());
}
locator->InitPointInsertion(mergedPts, newPts->GetBounds());
int nextCell = 0;
vtkIdType *pts = 0;
vtkIdType npts;
for (newPolys->InitTraversal(); newPolys->GetNextCell(npts, pts);)
{
vtkIdType nodes[3];
for (int i = 0; i < 3; i++)
{
double x[3];
newPts->GetPoint(pts[i], x);
locator->InsertUniquePoint(x, nodes[i]);
}
if (nodes[0] != nodes[1] &&
nodes[0] != nodes[2] &&
nodes[1] != nodes[2])
{
mergedPolys->InsertNextCell(3, nodes);
if (newScalars)
{
mergedScalars->InsertNextValue(newScalars->GetValue(nextCell));
}
}
nextCell++;
}
newPts->Delete();
newPolys->Delete();
if (newScalars)
{
newScalars->Delete();
}
vtkDebugMacro(<< "Merged to: "
<< mergedPts->GetNumberOfPoints() << " points, "
<< mergedPolys->GetNumberOfCells() << " triangles");
}
output->SetPoints(mergedPts);
mergedPts->Delete();
output->SetPolys(mergedPolys);
mergedPolys->Delete();
if (mergedScalars)
{
mergedScalars->SetName("STLSolidLabeling");
output->GetCellData()->SetScalars(mergedScalars);
mergedScalars->Delete();
}
if (this->Locator)
{
this->Locator->Initialize(); //free storage
}
output->Squeeze();
return 1;
}
//------------------------------------------------------------------------------
bool vtkSTLReader::ReadBinarySTL(FILE *fp, vtkPoints *newPts,
vtkCellArray *newPolys)
{
typedef struct { float n[3], v1[3], v2[3], v3[3]; } facet_t;
vtkDebugMacro(<< "Reading BINARY STL file");
// File is read to obtain raw information as well as bounding box
//
char header[81];
if (fread(header, 1, 80, fp) != 80)
{
vtkErrorMacro("STLReader error reading file: " << this->FileName
<< " Premature EOF while reading header.");
return false;
}
unsigned long ulint;
if (fread(&ulint, 1, 4, fp) != 4)
{
vtkErrorMacro("STLReader error reading file: " << this->FileName
<< " Premature EOF while reading header.");
return false;
}
vtkByteSwap::Swap4LE(&ulint);
// Many .stl files contain bogus count. Hence we will ignore and read
// until end of file.
//
int numTris = static_cast<int>(ulint);
if (numTris <= 0)
{
vtkDebugMacro(<< "Bad binary count: attempting to correct("
<< numTris << ")");
}
// Verify the numTris with the length of the file
unsigned long ulFileLength = vtksys::SystemTools::FileLength(this->FileName);
ulFileLength -= (80 + 4); // 80 byte - header, 4 byte - tringle count
ulFileLength /= 50; // 50 byte - twelve 32-bit-floating point numbers + 2 byte for attribute byte count
if (numTris < static_cast<int>(ulFileLength))
{
numTris = static_cast<int>(ulFileLength);
}
// now we can allocate the memory we need for this STL file
newPts->Allocate(numTris * 3);
newPolys->Allocate(numTris);
facet_t facet;
for (int i = 0; fread(&facet, 48, 1, fp) > 0; i++)
{
unsigned short ibuff2;
if (fread(&ibuff2, 2, 1, fp) != 1) //read extra junk
{
vtkErrorMacro("STLReader error reading file: " << this->FileName
<< " Premature EOF while reading extra junk.");
return false;
}
vtkByteSwap::Swap4LE(facet.n);
vtkByteSwap::Swap4LE(facet.n+1);
vtkByteSwap::Swap4LE(facet.n+2);
vtkByteSwap::Swap4LE(facet.v1);
vtkByteSwap::Swap4LE(facet.v1+1);
vtkByteSwap::Swap4LE(facet.v1+2);
vtkByteSwap::Swap4LE(facet.v2);
vtkByteSwap::Swap4LE(facet.v2+1);
vtkByteSwap::Swap4LE(facet.v2+2);
vtkByteSwap::Swap4LE(facet.v3);
vtkByteSwap::Swap4LE(facet.v3+1);
vtkByteSwap::Swap4LE(facet.v3+2);
vtkIdType pts[3];
pts[0] = newPts->InsertNextPoint(facet.v1);
pts[1] = newPts->InsertNextPoint(facet.v2);
pts[2] = newPts->InsertNextPoint(facet.v3);
newPolys->InsertNextCell(3, pts);
if ((i % 5000) == 0 && i != 0)
{
vtkDebugMacro(<< "triangle# " << i);
this->UpdateProgress(static_cast<double>(i) / numTris);
}
}
return true;
}
//------------------------------------------------------------------------------
bool vtkSTLReader::ReadASCIISTL(FILE *fp, vtkPoints *newPts,
vtkCellArray *newPolys, vtkFloatArray *scalars)
{
vtkDebugMacro(<< "Reading ASCII STL file");
// Ingest header and junk to get to first vertex
char line[256];
if (!fgets(line, 255, fp))
{
vtkErrorMacro("STLReader error reading file: " << this->FileName
<< " Premature EOF while reading header at line 0.");
return false;
}
int lineCount = 1;
int done = (fgets(line, 255, fp) == 0);
float x[3];
lineCount++;
if (!strcmp(line, "COLOR") || !strcmp(line, "color"))
{
// if there is a color field, skip it
done = (fgets(line, 255, fp) == 0);
lineCount++;
}
try
{
int currentSolid = 0;
// Go into loop, reading facet normal and vertices
while (!done)
{
if (!fgets(line, 255, fp))
{
throw std::runtime_error("unable to read outer loop.");
}
lineCount++;
if (fscanf(fp, "%*s %f %f %f\n", x, x+1, x+2) != 3)
{
throw std::runtime_error("unable to read point.");
}
lineCount++;
vtkIdType pts[3];
pts[0] = newPts->InsertNextPoint(x);
if (fscanf(fp, "%*s %f %f %f\n", x, x+1, x+2) != 3)
{
throw std::runtime_error("unable to read point.");
}
lineCount++;
pts[1] = newPts->InsertNextPoint(x);
if (fscanf(fp, "%*s %f %f %f\n", x, x+1, x+2) != 3)
{
throw std::runtime_error("unable to read reading point.");
}
lineCount++;
pts[2] = newPts->InsertNextPoint(x);
if (!fgets(line, 255, fp)) // end loop
{
throw std::runtime_error("unable to read end loop.");
}
lineCount++;
if (!fgets(line, 255, fp)) // end facet
{
throw std::runtime_error("unable to read end facet.");
}
lineCount++;
newPolys->InsertNextCell(3, pts);
if (scalars)
{
scalars->InsertNextValue(currentSolid);
}
if ((newPolys->GetNumberOfCells() % 5000) == 0)
{
this->UpdateProgress((newPolys->GetNumberOfCells()%50000) / 50000.0);
}
done = (fscanf(fp,"%s", line) == EOF);
if (!strcmp(line, "ENDSOLID") || !strcmp(line, "endsolid"))
{
currentSolid++;
if (!fgets(line, 255, fp))
{
throw std::runtime_error("unable to read end solid.");
}
done = feof(fp);
while (!strstr(line, "SOLID") && !strstr(line, "solid") && !done)
{
if (!fgets(line, 255, fp))
{
// if fgets() returns an error, it may be due to the fact that the EOF
// is reached(BUG #13101) hence we test again.
done = feof(fp);
if (!done)
{
throw std::runtime_error("unable to read solid.");
}
}
lineCount++;
done = feof(fp);
}
done = (fscanf(fp,"%s", line)==EOF);
if (!strstr(line, "COLOR") || !strstr(line, "color"))
{
done = (fgets(line, 255, fp) == 0);
lineCount++;
done = done || (fscanf(fp,"%s", line)==EOF);
}
}
if (!done)
{
done = (fgets(line, 255, fp) == 0);
lineCount++;
}
}
}
catch (const std::runtime_error &e)
{
vtkErrorMacro("STLReader: error while reading file " <<
this->FileName << " at line " << lineCount << ": " << e.what());
return false;
}
return true;
}
//------------------------------------------------------------------------------
int vtkSTLReader::GetSTLFileType(const char *filename)
{
vtksys::SystemTools::FileTypeEnum ft =
vtksys::SystemTools::DetectFileType(filename);
switch (ft)
{
case vtksys::SystemTools::FileTypeBinary:
return VTK_BINARY;
case vtksys::SystemTools::FileTypeText:
return VTK_ASCII;
case vtksys::SystemTools::FileTypeUnknown:
vtkWarningMacro("File type not recognized attempting binary");
return VTK_BINARY;
default:
vtkErrorMacro("Case not handled, file type is " << static_cast<int>(ft));
return VTK_BINARY; // should not happen
}
}
//------------------------------------------------------------------------------
// Specify a spatial locator for merging points. By
// default an instance of vtkMergePoints is used.
vtkIncrementalPointLocator* vtkSTLReader::NewDefaultLocator()
{
return vtkMergePoints::New();
}
//------------------------------------------------------------------------------
void vtkSTLReader::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "File Name: "
<<(this->FileName ? this->FileName : "(none)") << "\n";
os << indent << "Merging: " <<(this->Merging ? "On\n" : "Off\n");
os << indent << "ScalarTags: " <<(this->ScalarTags ? "On\n" : "Off\n");
os << indent << "Locator: ";
if (this->Locator)
{
this->Locator->PrintSelf(os << endl, indent.GetNextIndent());
}
else
{
os << "(none)\n";
}
}
|
//===--------- dppl_sycl_queue_manager.cpp - dpctl-C_API --*-- C++ ---*---===//
//
// Data Parallel Control Library (dpCtl)
//
// Copyright 2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file implements the data types and functions declared in
/// dppl_sycl_queue_manager.h.
///
//===----------------------------------------------------------------------===//
#include "dppl_sycl_queue_manager.h"
#include "Support/CBindingWrapping.h"
#include <string>
#include <vector>
#include <CL/sycl.hpp> /* SYCL headers */
using namespace cl::sycl;
/*------------------------------- Private helpers ----------------------------*/
// Anonymous namespace for private helpers
namespace
{
// Create wrappers for C Binding types (see CBindingWrapping.h).
DEFINE_SIMPLE_CONVERSION_FUNCTIONS(queue, DPPLSyclQueueRef)
/*!
* @brief A helper class to support the DPPLSyclQueuemanager.
*
* The QMgrHelper is needed so that sycl headers are not exposed at the
* top-level DPPL API.
*
*/
class QMgrHelper
{
public:
using QVec = vector_class<queue>;
static QVec* init_queues (backend BE, info::device_type DTy)
{
QVec *queues = new QVec();
auto Platforms = platform::get_platforms();
for (auto &p : Platforms) {
if (p.is_host()) continue;
auto be = p.get_backend();
auto Devices = p.get_devices();
if (Devices.size() == 1) {
auto d = Devices[0];
auto devty = d.get_info<info::device::device_type>();
if(devty == DTy && be == BE) {
auto Ctx = context(d);
queues->emplace_back(Ctx, d);
break;
}
}
else {
vector_class<device> SelectedDevices;
for(auto &d : Devices) {
auto devty = d.get_info<info::device::device_type>();
if(devty == DTy && be == BE) {
SelectedDevices.push_back(d);
// Workaround for situations when in some environments
// get_devices() returns each device TWICE. Then it fails in call
// for context constructor with all doubled devices.
// So use only one first device.
break;
}
}
if (SelectedDevices.size() > 0) {
auto Ctx = context(SelectedDevices);
auto d = SelectedDevices[0];
queues->emplace_back(Ctx, d);
}
}
}
return queues;
}
static QVec* init_active_queues ()
{
QVec *active_queues;
try {
auto def_device = std::move(default_selector().select_device());
auto BE = def_device.get_platform().get_backend();
auto DevTy = def_device.get_info<info::device::device_type>();
// \todo : We need to have a better way to match the default device
// to what SYCL returns based on the same scoring logic. Just
// storing the first device is not correct when we will have
// multiple devices of same type.
if(BE == backend::opencl &&
DevTy == info::device_type::cpu) {
active_queues = new QVec({get_opencl_cpu_queues()[0]});
}
else if(BE == backend::opencl &&
DevTy == info::device_type::gpu) {
active_queues = new QVec({get_opencl_gpu_queues()[0]});
}
else if(BE == backend::level_zero &&
DevTy == info::device_type::gpu) {
active_queues = new QVec({get_level0_gpu_queues()[0]});
}
else {
active_queues = new QVec();
}
}
catch (runtime_error &re) {
// \todo Handle the error
active_queues = new QVec();
}
return active_queues;
}
static QVec& get_opencl_cpu_queues ()
{
static QVec* queues = init_queues(backend::opencl,
info::device_type::cpu);
return *queues;
}
static QVec& get_opencl_gpu_queues ()
{
static QVec* queues = init_queues(backend::opencl,
info::device_type::gpu);
return *queues;
}
static QVec get_level0_gpu_queues ()
{
static QVec* queues = init_queues(backend::level_zero,
info::device_type::gpu);
return *queues;
}
static QVec& get_active_queues ()
{
thread_local static QVec *active_queues = init_active_queues();
return *active_queues;
}
static __dppl_give DPPLSyclQueueRef
getQueue (DPPLSyclBackendType BETy,
DPPLSyclDeviceType DeviceTy,
size_t DNum);
static __dppl_give DPPLSyclQueueRef
getCurrentQueue ();
static bool isCurrentQueue (__dppl_keep const DPPLSyclQueueRef QRef);
static __dppl_give DPPLSyclQueueRef
setAsDefaultQueue (DPPLSyclBackendType BETy,
DPPLSyclDeviceType DeviceTy,
size_t DNum);
static __dppl_give DPPLSyclQueueRef
pushSyclQueue (DPPLSyclBackendType BETy,
DPPLSyclDeviceType DeviceTy,
size_t DNum);
static void
popSyclQueue ();
};
/*!
* Allocates a new copy of the present top of stack queue, which can be the
* default queue and returns to caller. The caller owns the pointer and is
* responsible for deallocating it. The helper function DPPLQueue_Delete should
* be used for that purpose.
*/
DPPLSyclQueueRef QMgrHelper::getCurrentQueue ()
{
auto &activated_q = get_active_queues();
if(activated_q.empty()) {
// \todo handle error
std::cerr << "No currently active queues.\n";
return nullptr;
}
auto last = activated_q.size() - 1;
return wrap(new queue(activated_q[last]));
}
/*!
* Allocates a sycl::queue by copying from the cached {cpu|gpu}_queues vector
* and returns it to the caller. The caller owns the pointer and is responsible
* for deallocating it. The helper function DPPLQueue_Delete should
* be used for that purpose.
*/
__dppl_give DPPLSyclQueueRef
QMgrHelper::getQueue (DPPLSyclBackendType BETy,
DPPLSyclDeviceType DeviceTy,
size_t DNum)
{
queue *QRef = nullptr;
switch (BETy|DeviceTy)
{
case DPPLSyclBackendType::DPPL_OPENCL | DPPLSyclDeviceType::DPPL_CPU:
{
auto cpuQs = get_opencl_cpu_queues();
if (DNum >= cpuQs.size()) {
// \todo handle error
std::cerr << "OpenCL CPU device " << DNum
<< " not found on system.\n";
return nullptr;
}
QRef = new queue(cpuQs[DNum]);
break;
}
case DPPLSyclBackendType::DPPL_OPENCL | DPPLSyclDeviceType::DPPL_GPU:
{
auto gpuQs = get_opencl_gpu_queues();
if (DNum >= gpuQs.size()) {
// \todo handle error
std::cerr << "OpenCL GPU device " << DNum
<< " not found on system.\n";
return nullptr;
}
QRef = new queue(gpuQs[DNum]);
break;
}
case DPPLSyclBackendType::DPPL_LEVEL_ZERO | DPPLSyclDeviceType::DPPL_GPU:
{
auto l0GpuQs = get_level0_gpu_queues();
if (DNum >= l0GpuQs.size()) {
// \todo handle error
std::cerr << "Level-0 GPU device " << DNum
<< " not found on system.\n";
return nullptr;
}
QRef = new queue(l0GpuQs[DNum]);
break;
}
default:
std::cerr << "Unsupported device type.\n";
return nullptr;
}
return wrap(QRef);
}
/*!
* Compares the context and device of the current queue to the context and
* device of the queue passed as input. Return true if both queues have the
* same context and device.
*/
bool QMgrHelper::isCurrentQueue (__dppl_keep const DPPLSyclQueueRef QRef)
{
auto &activated_q = get_active_queues();
if(activated_q.empty()) {
// \todo handle error
std::cerr << "No currently active queues.\n";
return false;
}
auto last = activated_q.size() - 1;
auto currQ = activated_q[last];
return (*unwrap(QRef) == currQ);
}
/*!
* Changes the first entry into the stack, i.e., the default queue to a new
* sycl::queue corresponding to the device type and device number.
*/
__dppl_give DPPLSyclQueueRef
QMgrHelper::setAsDefaultQueue (DPPLSyclBackendType BETy,
DPPLSyclDeviceType DeviceTy,
size_t DNum)
{
queue *QRef = nullptr;
auto &activeQ = get_active_queues();
if(activeQ.empty()) {
std::cerr << "active queue vector is corrupted.\n";
return nullptr;
}
switch (BETy|DeviceTy)
{
case DPPLSyclBackendType::DPPL_OPENCL | DPPLSyclDeviceType::DPPL_CPU:
{
auto oclcpu_q = get_opencl_cpu_queues();
if (DNum >= oclcpu_q.size()) {
// \todo handle error
std::cerr << "OpenCL CPU device " << DNum
<< " not found on system\n.";
return nullptr;
}
activeQ[0] = oclcpu_q[DNum];
break;
}
case DPPLSyclBackendType::DPPL_OPENCL | DPPLSyclDeviceType::DPPL_GPU:
{
auto oclgpu_q = get_opencl_gpu_queues();
if (DNum >= oclgpu_q.size()) {
// \todo handle error
std::cerr << "OpenCL GPU device " << DNum
<< " not found on system\n.";
return nullptr;
}
activeQ[0] = oclgpu_q[DNum];
break;
}
case DPPLSyclBackendType::DPPL_LEVEL_ZERO | DPPLSyclDeviceType::DPPL_GPU:
{
auto l0gpu_q = get_level0_gpu_queues();
if (DNum >= l0gpu_q.size()) {
// \todo handle error
std::cerr << "Level-0 GPU device " << DNum
<< " not found on system\n.";
return nullptr;
}
activeQ[0] = l0gpu_q[DNum];
break;
}
default:
{
std::cerr << "Unsupported device type.\n";
return nullptr;
}
}
QRef = new queue(activeQ[0]);
return wrap(QRef);
}
/*!
* Allocates a new sycl::queue by copying from the cached {cpu|gpu}_queues
* vector. The pointer returned is now owned by the caller and must be properly
* cleaned up. The helper function DPPLDeleteSyclQueue() can be used is for that
* purpose.
*/
__dppl_give DPPLSyclQueueRef
QMgrHelper::pushSyclQueue (DPPLSyclBackendType BETy,
DPPLSyclDeviceType DeviceTy,
size_t DNum)
{
queue *QRef = nullptr;
auto &activeQ = get_active_queues();
if(activeQ.empty()) {
std::cerr << "Why is there no previous global context?\n";
return nullptr;
}
switch (BETy|DeviceTy)
{
case DPPLSyclBackendType::DPPL_OPENCL | DPPLSyclDeviceType::DPPL_CPU:
{
if (DNum >= get_opencl_cpu_queues().size()) {
// \todo handle error
std::cerr << "OpenCL CPU device " << DNum
<< " not found on system\n.";
return nullptr;
}
activeQ.emplace_back(get_opencl_cpu_queues()[DNum]);
QRef = new queue(activeQ[activeQ.size()-1]);
break;
}
case DPPLSyclBackendType::DPPL_OPENCL | DPPLSyclDeviceType::DPPL_GPU:
{
if (DNum >= get_opencl_gpu_queues().size()) {
// \todo handle error
std::cerr << "OpenCL GPU device " << DNum
<< " not found on system\n.";
return nullptr;
}
activeQ.emplace_back(get_opencl_gpu_queues()[DNum]);
QRef = new queue(activeQ[get_active_queues().size()-1]);
break;
}
case DPPLSyclBackendType::DPPL_LEVEL_ZERO | DPPLSyclDeviceType::DPPL_GPU:
{
if (DNum >= get_level0_gpu_queues().size()) {
// \todo handle error
std::cerr << "Level-0 GPU device " << DNum
<< " not found on system\n.";
return nullptr;
}
activeQ.emplace_back(get_level0_gpu_queues()[DNum]);
QRef = new queue(activeQ[get_active_queues().size()-1]);
break;
}
default:
{
std::cerr << "Unsupported device type.\n";
return nullptr;
}
}
return wrap(QRef);
}
/*!
* If there were any sycl::queue that were activated and added to the stack of
* activated queues then the top of the stack entry is popped. Note that since
* the same std::vector is used to keep track of the activated queues and the
* global queue a popSyclQueue call can never make the stack empty. Even
* after all activated queues are popped, the global queue is still available as
* the first element added to the stack.
*/
void
QMgrHelper::popSyclQueue ()
{
// The first queue which is the "default" queue can not be removed.
if(get_active_queues().size() <= 1 ) {
std::cerr << "No active contexts.\n";
return;
}
get_active_queues().pop_back();
}
} /* end of anonymous namespace */
//----------------------------- Public API -----------------------------------//
/*!
* Returns inside the number of activated queues not including the global queue
* (QMgrHelper::active_queues[0]).
*/
size_t DPPLQueueMgr_GetNumActivatedQueues ()
{
if (QMgrHelper::get_active_queues().empty()) {
// \todo handle error
std::cerr << "No active contexts.\n";
return 0;
}
return QMgrHelper::get_active_queues().size() - 1;
}
/*!
* Returns the number of available queues for a specific backend and device
* type combination.
*/
size_t DPPLQueueMgr_GetNumQueues (DPPLSyclBackendType BETy,
DPPLSyclDeviceType DeviceTy)
{
switch (BETy|DeviceTy)
{
case DPPLSyclBackendType::DPPL_OPENCL | DPPLSyclDeviceType::DPPL_CPU:
{
return QMgrHelper::get_opencl_cpu_queues().size();
}
case DPPLSyclBackendType::DPPL_OPENCL | DPPLSyclDeviceType::DPPL_GPU:
{
return QMgrHelper::get_opencl_gpu_queues().size();
}
case DPPLSyclBackendType::DPPL_LEVEL_ZERO | DPPLSyclDeviceType::DPPL_GPU:
{
return QMgrHelper::get_level0_gpu_queues().size();
}
default:
{
// \todo handle error
std::cerr << "Unsupported device type.\n";
return 0;
}
}
}
/*!
* \see QMgrHelper::getCurrentQueue()
*/
DPPLSyclQueueRef DPPLQueueMgr_GetCurrentQueue ()
{
return QMgrHelper::getCurrentQueue();
}
/*!
* Returns a copy of a sycl::queue corresponding to the specified device type
* and device number. A runtime_error gets thrown if no such device exists.
*/
DPPLSyclQueueRef DPPLQueueMgr_GetQueue (DPPLSyclBackendType BETy,
DPPLSyclDeviceType DeviceTy,
size_t DNum)
{
return QMgrHelper::getQueue(BETy, DeviceTy, DNum);
}
/*!
* */
bool DPPLQueueMgr_IsCurrentQueue (__dppl_keep const DPPLSyclQueueRef QRef)
{
return QMgrHelper::isCurrentQueue(QRef);
}
/*!
* The function sets the global queue, i.e., the sycl::queue object at
* QMgrHelper::active_queues[0] vector to the sycl::queue corresponding to the
* specified device type and id. If not queue was found for the backend and
* device, Null is returned.
*/
__dppl_give DPPLSyclQueueRef
DPPLQueueMgr_SetAsDefaultQueue (DPPLSyclBackendType BETy,
DPPLSyclDeviceType DeviceTy,
size_t DNum)
{
return QMgrHelper::setAsDefaultQueue(BETy, DeviceTy, DNum);
}
/*!
* \see QMgrHelper::pushSyclQueue()
*/
__dppl_give DPPLSyclQueueRef
DPPLQueueMgr_PushQueue (DPPLSyclBackendType BETy,
DPPLSyclDeviceType DeviceTy,
size_t DNum)
{
return QMgrHelper::pushSyclQueue(BETy, DeviceTy, DNum);
}
/*!
* \see QMgrHelper::popSyclQueue()
*/
void DPPLQueueMgr_PopQueue ()
{
QMgrHelper::popSyclQueue();
}
|
#pragma once
#include <chrono>
#include <queue>
#include "LogFilter.hpp"
#include "data.hpp"
#include "util/global_const.hpp"
namespace taraxa::net::rpc::eth {
using namespace chrono;
// TODO taraxa simple exception
DEV_SIMPLE_EXCEPTION(WatchLimitExceeded);
enum WatchType {
new_blocks,
new_transactions,
logs,
// do not touch
COUNT,
};
struct WatchGroupConfig {
uint64_t max_watches = 0;
chrono::seconds idle_timeout{5 * 60};
};
using WatchesConfig = array<WatchGroupConfig, WatchType::COUNT>;
using WatchID = uint64_t;
GLOBAL_CONST(WatchType, watch_id_type_mask_bits);
struct placeholder_t {};
template <WatchType type_, typename InputType_, typename OutputType_ = placeholder_t, typename Params = placeholder_t>
class WatchGroup {
public:
static constexpr auto type = type_;
using InputType = InputType_;
using OutputType = conditional_t<is_same_v<OutputType_, placeholder_t>, InputType, OutputType_>;
using time_point = high_resolution_clock::time_point;
using Updater = function<void(Params const&, //
InputType const&, //
function<void(OutputType const&)> const& /*do_update*/)>;
struct Watch {
Params params;
time_point last_touched{};
vector<OutputType> updates{};
};
private:
WatchGroupConfig cfg_;
Updater updater_;
mutable unordered_map<WatchID, Watch> watches_;
mutable shared_mutex watches_mu_;
mutable WatchID watch_id_seq_ = 0;
public:
explicit WatchGroup(WatchesConfig const& cfg = {}, Updater&& updater = {})
: cfg_(cfg[type]), updater_(move(updater)) {
assert(cfg_.idle_timeout.count() != 0);
if constexpr (is_same_v<InputType, OutputType>) {
if (!updater) {
updater = [](auto const&, auto const& input, auto const& do_update) { do_update(input); };
}
}
}
WatchID install_watch(Params&& params = {}) const {
unique_lock l(watches_mu_);
if (cfg_.max_watches && watches_.size() == cfg_.max_watches) {
throw WatchLimitExceeded();
}
auto id = ((++watch_id_seq_) << watch_id_type_mask_bits()) + type;
watches_.insert_or_assign(id, Watch{move(params), high_resolution_clock::now()});
return id;
}
bool uninstall_watch(WatchID watch_id) const {
unique_lock l(watches_mu_);
return watches_.erase(watch_id);
}
void uninstall_stale_watches() const {
unique_lock l(watches_mu_);
bool did_uninstall = false;
for (auto& [id, watch] : watches_) {
if (cfg_.idle_timeout <= duration_cast<seconds>(high_resolution_clock::now() - watch.last_touched)) {
watches_.erase(id);
did_uninstall = true;
}
}
if (auto num_buckets = watches_.bucket_count(); did_uninstall && (1 << 10) < num_buckets) {
if (size_t desired_num_buckets = 1 << uint(ceil(log2(watches_.size()))); desired_num_buckets != num_buckets) {
watches_.rehash(desired_num_buckets);
}
}
}
optional<Params> get_watch_params(WatchID watch_id) const {
shared_lock l(watches_mu_);
if (auto entry = watches_.find(watch_id); entry != watches_.end()) {
return entry->second.params;
}
return {};
}
void process_update(InputType const& obj_in) const {
shared_lock l(watches_mu_);
for (auto& entry : watches_) {
auto& watch = entry.second;
updater_(watch.params, obj_in, [&](auto const& obj_out) { watch.updates.push_back(obj_out); });
}
}
auto poll(WatchID watch_id) const {
vector<OutputType> ret;
shared_lock l(watches_mu_);
if (auto entry = watches_.find(watch_id); entry != watches_.end()) {
auto& watch = entry->second;
swap(ret, watch.updates);
watch.last_touched = high_resolution_clock::now();
}
return ret;
}
};
class Watches {
public:
WatchesConfig const cfg_;
WatchGroup<WatchType::new_blocks, h256> const new_blocks_{cfg_};
WatchGroup<WatchType::new_transactions, h256> const new_transactions_{cfg_};
WatchGroup<WatchType::logs, //
pair<ExtendedTransactionLocation const&, TransactionReceipt const&>, LocalisedLogEntry, LogFilter> const
logs_{
cfg_,
[](auto const& log_filter, auto const& input, auto const& do_update) {
auto const& [trx_loc, receipt] = input;
log_filter.match_one(trx_loc, receipt, do_update);
},
};
template <typename Visitor>
auto visit(WatchType type, Visitor&& visitor) {
switch (type) {
case WatchType::new_blocks:
return visitor(&new_blocks_);
case WatchType::new_transactions:
return visitor(&new_transactions_);
case WatchType::logs:
return visitor(&logs_);
default:
assert(false);
}
}
private:
condition_variable watch_cleaner_wait_cv_;
thread watch_cleaner_;
atomic<bool> destructor_called_ = false;
public:
Watches(WatchesConfig const& _cfg);
~Watches();
template <typename Visitor>
auto visit_by_id(WatchID watch_id, Visitor&& visitor) {
if (auto type = WatchType(watch_id & ((1 << watch_id_type_mask_bits()) - 1)); type < COUNT) {
return visit(type, forward<Visitor>(visitor));
}
return visitor(decltype (&new_blocks_)(nullptr));
}
};
} // namespace taraxa::net::rpc::eth
|
/*
* Copyright 2007 Sandia Corporation.
* Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
* license for use of this work by or on behalf of the
* U.S. Government. Redistribution and use in source and binary forms, with
* or without modification, are permitted provided that this Notice and any
* statement of authorship are reproduced on all copies.
*/
// QT includes
#include <QApplication>
#include <QSurfaceFormat>
#include "QVTKOpenGLWidget.h"
#include "CustomLinkView.h"
extern int qInitResources_icons();
int main( int argc, char** argv )
{
// needed to ensure appropriate OpenGL context is created for VTK rendering.
QSurfaceFormat::setDefaultFormat(QVTKOpenGLWidget::defaultFormat());
// QT Stuff
QApplication app( argc, argv );
QApplication::setStyle("fusion");
qInitResources_icons();
CustomLinkView myCustomLinkView;
myCustomLinkView.show();
return app.exec();
}
|
/*************************************************************************/
/* rasterizer_scene_rd.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 "rasterizer_scene_rd.h"
#include "core/os/os.h"
#include "core/project_settings.h"
#include "rasterizer_rd.h"
#include "servers/rendering/rendering_server_raster.h"
uint64_t RasterizerSceneRD::auto_exposure_counter = 2;
void get_vogel_disk(float *r_kernel, int p_sample_count) {
const float golden_angle = 2.4;
for (int i = 0; i < p_sample_count; i++) {
float r = Math::sqrt(float(i) + 0.5) / Math::sqrt(float(p_sample_count));
float theta = float(i) * golden_angle;
r_kernel[i * 4] = Math::cos(theta) * r;
r_kernel[i * 4 + 1] = Math::sin(theta) * r;
}
}
void RasterizerSceneRD::_clear_reflection_data(ReflectionData &rd) {
rd.layers.clear();
rd.radiance_base_cubemap = RID();
if (rd.downsampled_radiance_cubemap.is_valid()) {
RD::get_singleton()->free(rd.downsampled_radiance_cubemap);
}
rd.downsampled_radiance_cubemap = RID();
rd.downsampled_layer.mipmaps.clear();
rd.coefficient_buffer = RID();
}
void RasterizerSceneRD::_update_reflection_data(ReflectionData &rd, int p_size, int p_mipmaps, bool p_use_array, RID p_base_cube, int p_base_layer, bool p_low_quality) {
//recreate radiance and all data
int mipmaps = p_mipmaps;
uint32_t w = p_size, h = p_size;
if (p_use_array) {
int layers = p_low_quality ? 8 : roughness_layers;
for (int i = 0; i < layers; i++) {
ReflectionData::Layer layer;
uint32_t mmw = w;
uint32_t mmh = h;
layer.mipmaps.resize(mipmaps);
layer.views.resize(mipmaps);
for (int j = 0; j < mipmaps; j++) {
ReflectionData::Layer::Mipmap &mm = layer.mipmaps.write[j];
mm.size.width = mmw;
mm.size.height = mmh;
for (int k = 0; k < 6; k++) {
mm.views[k] = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), p_base_cube, p_base_layer + i * 6 + k, j);
Vector<RID> fbtex;
fbtex.push_back(mm.views[k]);
mm.framebuffers[k] = RD::get_singleton()->framebuffer_create(fbtex);
}
layer.views.write[j] = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), p_base_cube, p_base_layer + i * 6, j, RD::TEXTURE_SLICE_CUBEMAP);
mmw = MAX(1, mmw >> 1);
mmh = MAX(1, mmh >> 1);
}
rd.layers.push_back(layer);
}
} else {
mipmaps = p_low_quality ? 8 : mipmaps;
//regular cubemap, lower quality (aliasing, less memory)
ReflectionData::Layer layer;
uint32_t mmw = w;
uint32_t mmh = h;
layer.mipmaps.resize(mipmaps);
layer.views.resize(mipmaps);
for (int j = 0; j < mipmaps; j++) {
ReflectionData::Layer::Mipmap &mm = layer.mipmaps.write[j];
mm.size.width = mmw;
mm.size.height = mmh;
for (int k = 0; k < 6; k++) {
mm.views[k] = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), p_base_cube, p_base_layer + k, j);
Vector<RID> fbtex;
fbtex.push_back(mm.views[k]);
mm.framebuffers[k] = RD::get_singleton()->framebuffer_create(fbtex);
}
layer.views.write[j] = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), p_base_cube, p_base_layer, j, RD::TEXTURE_SLICE_CUBEMAP);
mmw = MAX(1, mmw >> 1);
mmh = MAX(1, mmh >> 1);
}
rd.layers.push_back(layer);
}
rd.radiance_base_cubemap = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), p_base_cube, p_base_layer, 0, RD::TEXTURE_SLICE_CUBEMAP);
RD::TextureFormat tf;
tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
tf.width = 64; // Always 64x64
tf.height = 64;
tf.type = RD::TEXTURE_TYPE_CUBE;
tf.array_layers = 6;
tf.mipmaps = 7;
tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
rd.downsampled_radiance_cubemap = RD::get_singleton()->texture_create(tf, RD::TextureView());
{
uint32_t mmw = 64;
uint32_t mmh = 64;
rd.downsampled_layer.mipmaps.resize(7);
for (int j = 0; j < rd.downsampled_layer.mipmaps.size(); j++) {
ReflectionData::DownsampleLayer::Mipmap &mm = rd.downsampled_layer.mipmaps.write[j];
mm.size.width = mmw;
mm.size.height = mmh;
mm.view = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), rd.downsampled_radiance_cubemap, 0, j, RD::TEXTURE_SLICE_CUBEMAP);
mmw = MAX(1, mmw >> 1);
mmh = MAX(1, mmh >> 1);
}
}
}
void RasterizerSceneRD::_create_reflection_fast_filter(ReflectionData &rd, bool p_use_arrays) {
storage->get_effects()->cubemap_downsample(rd.radiance_base_cubemap, rd.downsampled_layer.mipmaps[0].view, rd.downsampled_layer.mipmaps[0].size);
for (int i = 1; i < rd.downsampled_layer.mipmaps.size(); i++) {
storage->get_effects()->cubemap_downsample(rd.downsampled_layer.mipmaps[i - 1].view, rd.downsampled_layer.mipmaps[i].view, rd.downsampled_layer.mipmaps[i].size);
}
Vector<RID> views;
if (p_use_arrays) {
for (int i = 1; i < rd.layers.size(); i++) {
views.push_back(rd.layers[i].views[0]);
}
} else {
for (int i = 1; i < rd.layers[0].views.size(); i++) {
views.push_back(rd.layers[0].views[i]);
}
}
storage->get_effects()->cubemap_filter(rd.downsampled_radiance_cubemap, views, p_use_arrays);
}
void RasterizerSceneRD::_create_reflection_importance_sample(ReflectionData &rd, bool p_use_arrays, int p_cube_side, int p_base_layer) {
if (p_use_arrays) {
//render directly to the layers
storage->get_effects()->cubemap_roughness(rd.radiance_base_cubemap, rd.layers[p_base_layer].views[0], p_cube_side, sky_ggx_samples_quality, float(p_base_layer) / (rd.layers.size() - 1.0), rd.layers[p_base_layer].mipmaps[0].size.x);
} else {
storage->get_effects()->cubemap_roughness(rd.layers[0].views[p_base_layer - 1], rd.layers[0].views[p_base_layer], p_cube_side, sky_ggx_samples_quality, float(p_base_layer) / (rd.layers[0].mipmaps.size() - 1.0), rd.layers[0].mipmaps[p_base_layer].size.x);
}
}
void RasterizerSceneRD::_update_reflection_mipmaps(ReflectionData &rd, int p_start, int p_end) {
for (int i = p_start; i < p_end; i++) {
for (int j = 0; j < rd.layers[i].mipmaps.size() - 1; j++) {
for (int k = 0; k < 6; k++) {
RID view = rd.layers[i].mipmaps[j].views[k];
RID texture = rd.layers[i].mipmaps[j + 1].views[k];
Size2i size = rd.layers[i].mipmaps[j + 1].size;
storage->get_effects()->make_mipmap(view, texture, size);
}
}
}
}
void RasterizerSceneRD::_sdfgi_erase(RenderBuffers *rb) {
for (uint32_t i = 0; i < rb->sdfgi->cascades.size(); i++) {
const SDFGI::Cascade &c = rb->sdfgi->cascades[i];
RD::get_singleton()->free(c.light_data);
RD::get_singleton()->free(c.light_aniso_0_tex);
RD::get_singleton()->free(c.light_aniso_1_tex);
RD::get_singleton()->free(c.sdf_tex);
RD::get_singleton()->free(c.solid_cell_dispatch_buffer);
RD::get_singleton()->free(c.solid_cell_buffer);
RD::get_singleton()->free(c.lightprobe_history_tex);
RD::get_singleton()->free(c.lightprobe_average_tex);
RD::get_singleton()->free(c.lights_buffer);
}
RD::get_singleton()->free(rb->sdfgi->render_albedo);
RD::get_singleton()->free(rb->sdfgi->render_emission);
RD::get_singleton()->free(rb->sdfgi->render_emission_aniso);
RD::get_singleton()->free(rb->sdfgi->render_sdf[0]);
RD::get_singleton()->free(rb->sdfgi->render_sdf[1]);
RD::get_singleton()->free(rb->sdfgi->render_sdf_half[0]);
RD::get_singleton()->free(rb->sdfgi->render_sdf_half[1]);
for (int i = 0; i < 8; i++) {
RD::get_singleton()->free(rb->sdfgi->render_occlusion[i]);
}
RD::get_singleton()->free(rb->sdfgi->render_geom_facing);
RD::get_singleton()->free(rb->sdfgi->lightprobe_data);
RD::get_singleton()->free(rb->sdfgi->lightprobe_history_scroll);
RD::get_singleton()->free(rb->sdfgi->occlusion_data);
RD::get_singleton()->free(rb->sdfgi->ambient_texture);
RD::get_singleton()->free(rb->sdfgi->cascades_ubo);
memdelete(rb->sdfgi);
rb->sdfgi = nullptr;
}
const Vector3i RasterizerSceneRD::SDFGI::Cascade::DIRTY_ALL = Vector3i(0x7FFFFFFF, 0x7FFFFFFF, 0x7FFFFFFF);
void RasterizerSceneRD::sdfgi_update(RID p_render_buffers, RID p_environment, const Vector3 &p_world_position) {
Environment *env = environment_owner.getornull(p_environment);
RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
bool needs_sdfgi = env && env->sdfgi_enabled;
if (!needs_sdfgi) {
if (rb->sdfgi != nullptr) {
//erase it
_sdfgi_erase(rb);
_render_buffers_uniform_set_changed(p_render_buffers);
}
return;
}
static const uint32_t history_frames_to_converge[RS::ENV_SDFGI_CONVERGE_MAX] = { 5, 10, 15, 20, 25, 30 };
uint32_t requested_history_size = history_frames_to_converge[sdfgi_frames_to_converge];
if (rb->sdfgi && (rb->sdfgi->cascade_mode != env->sdfgi_cascades || rb->sdfgi->min_cell_size != env->sdfgi_min_cell_size || requested_history_size != rb->sdfgi->history_size || rb->sdfgi->uses_occlusion != env->sdfgi_use_occlusion || rb->sdfgi->y_scale_mode != env->sdfgi_y_scale)) {
//configuration changed, erase
_sdfgi_erase(rb);
}
SDFGI *sdfgi = rb->sdfgi;
if (sdfgi == nullptr) {
//re-create
rb->sdfgi = memnew(SDFGI);
sdfgi = rb->sdfgi;
sdfgi->cascade_mode = env->sdfgi_cascades;
sdfgi->min_cell_size = env->sdfgi_min_cell_size;
sdfgi->uses_occlusion = env->sdfgi_use_occlusion;
sdfgi->y_scale_mode = env->sdfgi_y_scale;
static const float y_scale[3] = { 1.0, 1.5, 2.0 };
sdfgi->y_mult = y_scale[sdfgi->y_scale_mode];
static const int cascasde_size[3] = { 4, 6, 8 };
sdfgi->cascades.resize(cascasde_size[sdfgi->cascade_mode]);
sdfgi->probe_axis_count = SDFGI::PROBE_DIVISOR + 1;
sdfgi->solid_cell_ratio = sdfgi_solid_cell_ratio;
sdfgi->solid_cell_count = uint32_t(float(sdfgi->cascade_size * sdfgi->cascade_size * sdfgi->cascade_size) * sdfgi->solid_cell_ratio);
float base_cell_size = sdfgi->min_cell_size;
RD::TextureFormat tf_sdf;
tf_sdf.format = RD::DATA_FORMAT_R8_UNORM;
tf_sdf.width = sdfgi->cascade_size; // Always 64x64
tf_sdf.height = sdfgi->cascade_size;
tf_sdf.depth = sdfgi->cascade_size;
tf_sdf.type = RD::TEXTURE_TYPE_3D;
tf_sdf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_CAN_COPY_TO_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT;
{
RD::TextureFormat tf_render = tf_sdf;
tf_render.format = RD::DATA_FORMAT_R16_UINT;
sdfgi->render_albedo = RD::get_singleton()->texture_create(tf_render, RD::TextureView());
tf_render.format = RD::DATA_FORMAT_R32_UINT;
sdfgi->render_emission = RD::get_singleton()->texture_create(tf_render, RD::TextureView());
sdfgi->render_emission_aniso = RD::get_singleton()->texture_create(tf_render, RD::TextureView());
tf_render.format = RD::DATA_FORMAT_R8_UNORM; //at least its easy to visualize
for (int i = 0; i < 8; i++) {
sdfgi->render_occlusion[i] = RD::get_singleton()->texture_create(tf_render, RD::TextureView());
}
tf_render.format = RD::DATA_FORMAT_R32_UINT;
sdfgi->render_geom_facing = RD::get_singleton()->texture_create(tf_render, RD::TextureView());
tf_render.format = RD::DATA_FORMAT_R8G8B8A8_UINT;
sdfgi->render_sdf[0] = RD::get_singleton()->texture_create(tf_render, RD::TextureView());
sdfgi->render_sdf[1] = RD::get_singleton()->texture_create(tf_render, RD::TextureView());
tf_render.width /= 2;
tf_render.height /= 2;
tf_render.depth /= 2;
sdfgi->render_sdf_half[0] = RD::get_singleton()->texture_create(tf_render, RD::TextureView());
sdfgi->render_sdf_half[1] = RD::get_singleton()->texture_create(tf_render, RD::TextureView());
}
RD::TextureFormat tf_occlusion = tf_sdf;
tf_occlusion.format = RD::DATA_FORMAT_R16_UINT;
tf_occlusion.shareable_formats.push_back(RD::DATA_FORMAT_R16_UINT);
tf_occlusion.shareable_formats.push_back(RD::DATA_FORMAT_R4G4B4A4_UNORM_PACK16);
tf_occlusion.depth *= sdfgi->cascades.size(); //use depth for occlusion slices
tf_occlusion.width *= 2; //use width for the other half
RD::TextureFormat tf_light = tf_sdf;
tf_light.format = RD::DATA_FORMAT_R32_UINT;
tf_light.shareable_formats.push_back(RD::DATA_FORMAT_R32_UINT);
tf_light.shareable_formats.push_back(RD::DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32);
RD::TextureFormat tf_aniso0 = tf_sdf;
tf_aniso0.format = RD::DATA_FORMAT_R8G8B8A8_UNORM;
RD::TextureFormat tf_aniso1 = tf_sdf;
tf_aniso1.format = RD::DATA_FORMAT_R8G8_UNORM;
int passes = nearest_shift(sdfgi->cascade_size) - 1;
//store lightprobe SH
RD::TextureFormat tf_probes;
tf_probes.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
tf_probes.width = sdfgi->probe_axis_count * sdfgi->probe_axis_count;
tf_probes.height = sdfgi->probe_axis_count * SDFGI::SH_SIZE;
tf_probes.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_CAN_COPY_TO_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT;
tf_probes.type = RD::TEXTURE_TYPE_2D_ARRAY;
sdfgi->history_size = requested_history_size;
RD::TextureFormat tf_probe_history = tf_probes;
tf_probe_history.format = RD::DATA_FORMAT_R16G16B16A16_SINT; //signed integer because SH are signed
tf_probe_history.array_layers = sdfgi->history_size;
RD::TextureFormat tf_probe_average = tf_probes;
tf_probe_average.format = RD::DATA_FORMAT_R32G32B32A32_SINT; //signed integer because SH are signed
tf_probe_average.type = RD::TEXTURE_TYPE_2D_ARRAY;
tf_probe_average.array_layers = 1;
sdfgi->lightprobe_history_scroll = RD::get_singleton()->texture_create(tf_probe_history, RD::TextureView());
sdfgi->lightprobe_average_scroll = RD::get_singleton()->texture_create(tf_probe_average, RD::TextureView());
{
//octahedral lightprobes
RD::TextureFormat tf_octprobes = tf_probes;
tf_octprobes.array_layers = sdfgi->cascades.size() * 2;
tf_octprobes.format = RD::DATA_FORMAT_R32_UINT; //pack well with RGBE
tf_octprobes.width = sdfgi->probe_axis_count * sdfgi->probe_axis_count * (SDFGI::LIGHTPROBE_OCT_SIZE + 2);
tf_octprobes.height = sdfgi->probe_axis_count * (SDFGI::LIGHTPROBE_OCT_SIZE + 2);
tf_octprobes.shareable_formats.push_back(RD::DATA_FORMAT_R32_UINT);
tf_octprobes.shareable_formats.push_back(RD::DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32);
//lightprobe texture is an octahedral texture
sdfgi->lightprobe_data = RD::get_singleton()->texture_create(tf_octprobes, RD::TextureView());
RD::TextureView tv;
tv.format_override = RD::DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32;
sdfgi->lightprobe_texture = RD::get_singleton()->texture_create_shared(tv, sdfgi->lightprobe_data);
//texture handling ambient data, to integrate with volumetric foc
RD::TextureFormat tf_ambient = tf_probes;
tf_ambient.array_layers = sdfgi->cascades.size();
tf_ambient.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT; //pack well with RGBE
tf_ambient.width = sdfgi->probe_axis_count * sdfgi->probe_axis_count;
tf_ambient.height = sdfgi->probe_axis_count;
tf_ambient.type = RD::TEXTURE_TYPE_2D_ARRAY;
//lightprobe texture is an octahedral texture
sdfgi->ambient_texture = RD::get_singleton()->texture_create(tf_ambient, RD::TextureView());
}
sdfgi->cascades_ubo = RD::get_singleton()->uniform_buffer_create(sizeof(SDFGI::Cascade::UBO) * SDFGI::MAX_CASCADES);
sdfgi->occlusion_data = RD::get_singleton()->texture_create(tf_occlusion, RD::TextureView());
{
RD::TextureView tv;
tv.format_override = RD::DATA_FORMAT_R4G4B4A4_UNORM_PACK16;
sdfgi->occlusion_texture = RD::get_singleton()->texture_create_shared(tv, sdfgi->occlusion_data);
}
for (uint32_t i = 0; i < sdfgi->cascades.size(); i++) {
SDFGI::Cascade &cascade = sdfgi->cascades[i];
/* 3D Textures */
cascade.sdf_tex = RD::get_singleton()->texture_create(tf_sdf, RD::TextureView());
cascade.light_data = RD::get_singleton()->texture_create(tf_light, RD::TextureView());
cascade.light_aniso_0_tex = RD::get_singleton()->texture_create(tf_aniso0, RD::TextureView());
cascade.light_aniso_1_tex = RD::get_singleton()->texture_create(tf_aniso1, RD::TextureView());
{
RD::TextureView tv;
tv.format_override = RD::DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32;
cascade.light_tex = RD::get_singleton()->texture_create_shared(tv, cascade.light_data);
RD::get_singleton()->texture_clear(cascade.light_tex, Color(0, 0, 0, 0), 0, 1, 0, 1);
RD::get_singleton()->texture_clear(cascade.light_aniso_0_tex, Color(0, 0, 0, 0), 0, 1, 0, 1);
RD::get_singleton()->texture_clear(cascade.light_aniso_1_tex, Color(0, 0, 0, 0), 0, 1, 0, 1);
}
cascade.cell_size = base_cell_size;
Vector3 world_position = p_world_position;
world_position.y *= sdfgi->y_mult;
int32_t probe_cells = sdfgi->cascade_size / SDFGI::PROBE_DIVISOR;
Vector3 probe_size = Vector3(1, 1, 1) * cascade.cell_size * probe_cells;
Vector3i probe_pos = Vector3i((world_position / probe_size + Vector3(0.5, 0.5, 0.5)).floor());
cascade.position = probe_pos * probe_cells;
cascade.dirty_regions = SDFGI::Cascade::DIRTY_ALL;
base_cell_size *= 2.0;
/* Probe History */
cascade.lightprobe_history_tex = RD::get_singleton()->texture_create(tf_probe_history, RD::TextureView());
RD::get_singleton()->texture_clear(cascade.lightprobe_history_tex, Color(0, 0, 0, 0), 0, 1, 0, tf_probe_history.array_layers); //needs to be cleared for average to work
cascade.lightprobe_average_tex = RD::get_singleton()->texture_create(tf_probe_average, RD::TextureView());
RD::get_singleton()->texture_clear(cascade.lightprobe_average_tex, Color(0, 0, 0, 0), 0, 1, 0, 1); //needs to be cleared for average to work
/* Buffers */
cascade.solid_cell_buffer = RD::get_singleton()->storage_buffer_create(sizeof(SDFGI::Cascade::SolidCell) * sdfgi->solid_cell_count);
cascade.solid_cell_dispatch_buffer = RD::get_singleton()->storage_buffer_create(sizeof(uint32_t) * 4, Vector<uint8_t>(), RD::STORAGE_BUFFER_USAGE_DISPATCH_INDIRECT);
cascade.lights_buffer = RD::get_singleton()->storage_buffer_create(sizeof(SDGIShader::Light) * MAX(SDFGI::MAX_STATIC_LIGHTS, SDFGI::MAX_DYNAMIC_LIGHTS));
{
Vector<RD::Uniform> uniforms;
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 1;
u.ids.push_back(sdfgi->render_sdf[(passes & 1) ? 1 : 0]); //if passes are even, we read from buffer 0, else we read from buffer 1
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 2;
u.ids.push_back(sdfgi->render_albedo);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 3;
for (int j = 0; j < 8; j++) {
u.ids.push_back(sdfgi->render_occlusion[j]);
}
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 4;
u.ids.push_back(sdfgi->render_emission);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 5;
u.ids.push_back(sdfgi->render_emission_aniso);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 6;
u.ids.push_back(sdfgi->render_geom_facing);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 7;
u.ids.push_back(cascade.sdf_tex);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 8;
u.ids.push_back(sdfgi->occlusion_data);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
u.binding = 10;
u.ids.push_back(cascade.solid_cell_dispatch_buffer);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
u.binding = 11;
u.ids.push_back(cascade.solid_cell_buffer);
uniforms.push_back(u);
}
cascade.sdf_store_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_STORE), 0);
}
{
Vector<RD::Uniform> uniforms;
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 1;
u.ids.push_back(sdfgi->render_albedo);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 2;
u.ids.push_back(sdfgi->render_geom_facing);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 3;
u.ids.push_back(sdfgi->render_emission);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 4;
u.ids.push_back(sdfgi->render_emission_aniso);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
u.binding = 5;
u.ids.push_back(cascade.solid_cell_dispatch_buffer);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
u.binding = 6;
u.ids.push_back(cascade.solid_cell_buffer);
uniforms.push_back(u);
}
cascade.scroll_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_SCROLL), 0);
}
{
Vector<RD::Uniform> uniforms;
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 1;
for (int j = 0; j < 8; j++) {
u.ids.push_back(sdfgi->render_occlusion[j]);
}
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 2;
u.ids.push_back(sdfgi->occlusion_data);
uniforms.push_back(u);
}
cascade.scroll_occlusion_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_SCROLL_OCCLUSION), 0);
}
}
//direct light
for (uint32_t i = 0; i < sdfgi->cascades.size(); i++) {
SDFGI::Cascade &cascade = sdfgi->cascades[i];
Vector<RD::Uniform> uniforms;
{
RD::Uniform u;
u.binding = 1;
u.type = RD::UNIFORM_TYPE_TEXTURE;
for (uint32_t j = 0; j < SDFGI::MAX_CASCADES; j++) {
if (j < rb->sdfgi->cascades.size()) {
u.ids.push_back(rb->sdfgi->cascades[j].sdf_tex);
} else {
u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
}
}
uniforms.push_back(u);
}
{
RD::Uniform u;
u.binding = 2;
u.type = RD::UNIFORM_TYPE_SAMPLER;
u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
uniforms.push_back(u);
}
{
RD::Uniform u;
u.binding = 3;
u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
u.ids.push_back(cascade.solid_cell_dispatch_buffer);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.binding = 4;
u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
u.ids.push_back(cascade.solid_cell_buffer);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.binding = 5;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.ids.push_back(cascade.light_data);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.binding = 6;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.ids.push_back(cascade.light_aniso_0_tex);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.binding = 7;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.ids.push_back(cascade.light_aniso_1_tex);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.binding = 8;
u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
u.ids.push_back(rb->sdfgi->cascades_ubo);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.binding = 9;
u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
u.ids.push_back(cascade.lights_buffer);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.binding = 10;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.ids.push_back(rb->sdfgi->lightprobe_texture);
uniforms.push_back(u);
}
cascade.sdf_direct_light_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.direct_light.version_get_shader(sdfgi_shader.direct_light_shader, 0), 0);
}
//preprocess initialize uniform set
{
Vector<RD::Uniform> uniforms;
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 1;
u.ids.push_back(sdfgi->render_albedo);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 2;
u.ids.push_back(sdfgi->render_sdf[0]);
uniforms.push_back(u);
}
sdfgi->sdf_initialize_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_JUMP_FLOOD_INITIALIZE), 0);
}
{
Vector<RD::Uniform> uniforms;
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 1;
u.ids.push_back(sdfgi->render_albedo);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 2;
u.ids.push_back(sdfgi->render_sdf_half[0]);
uniforms.push_back(u);
}
sdfgi->sdf_initialize_half_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_JUMP_FLOOD_INITIALIZE_HALF), 0);
}
//jump flood uniform set
{
Vector<RD::Uniform> uniforms;
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 1;
u.ids.push_back(sdfgi->render_sdf[0]);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 2;
u.ids.push_back(sdfgi->render_sdf[1]);
uniforms.push_back(u);
}
sdfgi->jump_flood_uniform_set[0] = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_JUMP_FLOOD), 0);
SWAP(uniforms.write[0].ids.write[0], uniforms.write[1].ids.write[0]);
sdfgi->jump_flood_uniform_set[1] = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_JUMP_FLOOD), 0);
}
//jump flood half uniform set
{
Vector<RD::Uniform> uniforms;
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 1;
u.ids.push_back(sdfgi->render_sdf_half[0]);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 2;
u.ids.push_back(sdfgi->render_sdf_half[1]);
uniforms.push_back(u);
}
sdfgi->jump_flood_half_uniform_set[0] = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_JUMP_FLOOD), 0);
SWAP(uniforms.write[0].ids.write[0], uniforms.write[1].ids.write[0]);
sdfgi->jump_flood_half_uniform_set[1] = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_JUMP_FLOOD), 0);
}
//upscale half size sdf
{
Vector<RD::Uniform> uniforms;
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 1;
u.ids.push_back(sdfgi->render_albedo);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 2;
u.ids.push_back(sdfgi->render_sdf_half[(passes & 1) ? 0 : 1]); //reverse pass order because half size
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 3;
u.ids.push_back(sdfgi->render_sdf[(passes & 1) ? 0 : 1]); //reverse pass order because it needs an extra JFA pass
uniforms.push_back(u);
}
sdfgi->upscale_jfa_uniform_set_index = (passes & 1) ? 0 : 1;
sdfgi->sdf_upscale_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_JUMP_FLOOD_UPSCALE), 0);
}
//occlusion uniform set
{
Vector<RD::Uniform> uniforms;
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 1;
u.ids.push_back(sdfgi->render_albedo);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 2;
for (int i = 0; i < 8; i++) {
u.ids.push_back(sdfgi->render_occlusion[i]);
}
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 3;
u.ids.push_back(sdfgi->render_geom_facing);
uniforms.push_back(u);
}
sdfgi->occlusion_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_OCCLUSION), 0);
}
for (uint32_t i = 0; i < sdfgi->cascades.size(); i++) {
//integrate uniform
Vector<RD::Uniform> uniforms;
{
RD::Uniform u;
u.binding = 1;
u.type = RD::UNIFORM_TYPE_TEXTURE;
for (uint32_t j = 0; j < SDFGI::MAX_CASCADES; j++) {
if (j < sdfgi->cascades.size()) {
u.ids.push_back(sdfgi->cascades[j].sdf_tex);
} else {
u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
}
}
uniforms.push_back(u);
}
{
RD::Uniform u;
u.binding = 2;
u.type = RD::UNIFORM_TYPE_TEXTURE;
for (uint32_t j = 0; j < SDFGI::MAX_CASCADES; j++) {
if (j < sdfgi->cascades.size()) {
u.ids.push_back(sdfgi->cascades[j].light_tex);
} else {
u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
}
}
uniforms.push_back(u);
}
{
RD::Uniform u;
u.binding = 3;
u.type = RD::UNIFORM_TYPE_TEXTURE;
for (uint32_t j = 0; j < SDFGI::MAX_CASCADES; j++) {
if (j < sdfgi->cascades.size()) {
u.ids.push_back(sdfgi->cascades[j].light_aniso_0_tex);
} else {
u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
}
}
uniforms.push_back(u);
}
{
RD::Uniform u;
u.binding = 4;
u.type = RD::UNIFORM_TYPE_TEXTURE;
for (uint32_t j = 0; j < SDFGI::MAX_CASCADES; j++) {
if (j < sdfgi->cascades.size()) {
u.ids.push_back(sdfgi->cascades[j].light_aniso_1_tex);
} else {
u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
}
}
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_SAMPLER;
u.binding = 6;
u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
u.binding = 7;
u.ids.push_back(sdfgi->cascades_ubo);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 8;
u.ids.push_back(sdfgi->lightprobe_data);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 9;
u.ids.push_back(sdfgi->cascades[i].lightprobe_history_tex);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 10;
u.ids.push_back(sdfgi->cascades[i].lightprobe_average_tex);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 11;
u.ids.push_back(sdfgi->lightprobe_history_scroll);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 12;
u.ids.push_back(sdfgi->lightprobe_average_scroll);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 13;
RID parent_average;
if (i < sdfgi->cascades.size() - 1) {
parent_average = sdfgi->cascades[i + 1].lightprobe_average_tex;
} else {
parent_average = sdfgi->cascades[i - 1].lightprobe_average_tex; //to use something, but it won't be used
}
u.ids.push_back(parent_average);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 14;
u.ids.push_back(sdfgi->ambient_texture);
uniforms.push_back(u);
}
sdfgi->cascades[i].integrate_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.integrate.version_get_shader(sdfgi_shader.integrate_shader, 0), 0);
}
sdfgi->uses_multibounce = env->sdfgi_use_multibounce;
sdfgi->energy = env->sdfgi_energy;
sdfgi->normal_bias = env->sdfgi_normal_bias;
sdfgi->probe_bias = env->sdfgi_probe_bias;
sdfgi->reads_sky = env->sdfgi_read_sky_light;
_render_buffers_uniform_set_changed(p_render_buffers);
return; //done. all levels will need to be rendered which its going to take a bit
}
//check for updates
sdfgi->uses_multibounce = env->sdfgi_use_multibounce;
sdfgi->energy = env->sdfgi_energy;
sdfgi->normal_bias = env->sdfgi_normal_bias;
sdfgi->probe_bias = env->sdfgi_probe_bias;
sdfgi->reads_sky = env->sdfgi_read_sky_light;
int32_t drag_margin = (sdfgi->cascade_size / SDFGI::PROBE_DIVISOR) / 2;
for (uint32_t i = 0; i < sdfgi->cascades.size(); i++) {
SDFGI::Cascade &cascade = sdfgi->cascades[i];
cascade.dirty_regions = Vector3i();
Vector3 probe_half_size = Vector3(1, 1, 1) * cascade.cell_size * float(sdfgi->cascade_size / SDFGI::PROBE_DIVISOR) * 0.5;
probe_half_size = Vector3(0, 0, 0);
Vector3 world_position = p_world_position;
world_position.y *= sdfgi->y_mult;
Vector3i pos_in_cascade = Vector3i((world_position + probe_half_size) / cascade.cell_size);
for (int j = 0; j < 3; j++) {
if (pos_in_cascade[j] < cascade.position[j]) {
while (pos_in_cascade[j] < (cascade.position[j] - drag_margin)) {
cascade.position[j] -= drag_margin * 2;
cascade.dirty_regions[j] += drag_margin * 2;
}
} else if (pos_in_cascade[j] > cascade.position[j]) {
while (pos_in_cascade[j] > (cascade.position[j] + drag_margin)) {
cascade.position[j] += drag_margin * 2;
cascade.dirty_regions[j] -= drag_margin * 2;
}
}
if (cascade.dirty_regions[j] == 0) {
continue; // not dirty
} else if (uint32_t(ABS(cascade.dirty_regions[j])) >= sdfgi->cascade_size) {
//moved too much, just redraw everything (make all dirty)
cascade.dirty_regions = SDFGI::Cascade::DIRTY_ALL;
break;
}
}
if (cascade.dirty_regions != Vector3i() && cascade.dirty_regions != SDFGI::Cascade::DIRTY_ALL) {
//see how much the total dirty volume represents from the total volume
uint32_t total_volume = sdfgi->cascade_size * sdfgi->cascade_size * sdfgi->cascade_size;
uint32_t safe_volume = 1;
for (int j = 0; j < 3; j++) {
safe_volume *= sdfgi->cascade_size - ABS(cascade.dirty_regions[j]);
}
uint32_t dirty_volume = total_volume - safe_volume;
if (dirty_volume > (safe_volume / 2)) {
//more than half the volume is dirty, make all dirty so its only rendered once
cascade.dirty_regions = SDFGI::Cascade::DIRTY_ALL;
}
}
}
}
int RasterizerSceneRD::sdfgi_get_pending_region_count(RID p_render_buffers) const {
RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND_V(rb == nullptr, 0);
if (rb->sdfgi == nullptr) {
return 0;
}
int dirty_count = 0;
for (uint32_t i = 0; i < rb->sdfgi->cascades.size(); i++) {
const SDFGI::Cascade &c = rb->sdfgi->cascades[i];
if (c.dirty_regions == SDFGI::Cascade::DIRTY_ALL) {
dirty_count++;
} else {
for (int j = 0; j < 3; j++) {
if (c.dirty_regions[j] != 0) {
dirty_count++;
}
}
}
}
return dirty_count;
}
int RasterizerSceneRD::_sdfgi_get_pending_region_data(RID p_render_buffers, int p_region, Vector3i &r_local_offset, Vector3i &r_local_size, AABB &r_bounds) const {
RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND_V(rb == nullptr, -1);
ERR_FAIL_COND_V(rb->sdfgi == nullptr, -1);
int dirty_count = 0;
for (uint32_t i = 0; i < rb->sdfgi->cascades.size(); i++) {
const SDFGI::Cascade &c = rb->sdfgi->cascades[i];
if (c.dirty_regions == SDFGI::Cascade::DIRTY_ALL) {
if (dirty_count == p_region) {
r_local_offset = Vector3i();
r_local_size = Vector3i(1, 1, 1) * rb->sdfgi->cascade_size;
r_bounds.position = Vector3((Vector3i(1, 1, 1) * -int32_t(rb->sdfgi->cascade_size >> 1) + c.position)) * c.cell_size * Vector3(1, 1.0 / rb->sdfgi->y_mult, 1);
r_bounds.size = Vector3(r_local_size) * c.cell_size * Vector3(1, 1.0 / rb->sdfgi->y_mult, 1);
return i;
}
dirty_count++;
} else {
for (int j = 0; j < 3; j++) {
if (c.dirty_regions[j] != 0) {
if (dirty_count == p_region) {
Vector3i from = Vector3i(0, 0, 0);
Vector3i to = Vector3i(1, 1, 1) * rb->sdfgi->cascade_size;
if (c.dirty_regions[j] > 0) {
//fill from the beginning
to[j] = c.dirty_regions[j];
} else {
//fill from the end
from[j] = to[j] + c.dirty_regions[j];
}
for (int k = 0; k < j; k++) {
// "chip" away previous regions to avoid re-voxelizing the same thing
if (c.dirty_regions[k] > 0) {
from[k] += c.dirty_regions[k];
} else if (c.dirty_regions[k] < 0) {
to[k] += c.dirty_regions[k];
}
}
r_local_offset = from;
r_local_size = to - from;
r_bounds.position = Vector3(from + Vector3i(1, 1, 1) * -int32_t(rb->sdfgi->cascade_size >> 1) + c.position) * c.cell_size * Vector3(1, 1.0 / rb->sdfgi->y_mult, 1);
r_bounds.size = Vector3(r_local_size) * c.cell_size * Vector3(1, 1.0 / rb->sdfgi->y_mult, 1);
return i;
}
dirty_count++;
}
}
}
}
return -1;
}
AABB RasterizerSceneRD::sdfgi_get_pending_region_bounds(RID p_render_buffers, int p_region) const {
AABB bounds;
Vector3i from;
Vector3i size;
int c = _sdfgi_get_pending_region_data(p_render_buffers, p_region, from, size, bounds);
ERR_FAIL_COND_V(c == -1, AABB());
return bounds;
}
uint32_t RasterizerSceneRD::sdfgi_get_pending_region_cascade(RID p_render_buffers, int p_region) const {
AABB bounds;
Vector3i from;
Vector3i size;
return _sdfgi_get_pending_region_data(p_render_buffers, p_region, from, size, bounds);
}
void RasterizerSceneRD::_sdfgi_update_cascades(RID p_render_buffers) {
RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND(rb == nullptr);
if (rb->sdfgi == nullptr) {
return;
}
//update cascades
SDFGI::Cascade::UBO cascade_data[SDFGI::MAX_CASCADES];
int32_t probe_divisor = rb->sdfgi->cascade_size / SDFGI::PROBE_DIVISOR;
for (uint32_t i = 0; i < rb->sdfgi->cascades.size(); i++) {
Vector3 pos = Vector3((Vector3i(1, 1, 1) * -int32_t(rb->sdfgi->cascade_size >> 1) + rb->sdfgi->cascades[i].position)) * rb->sdfgi->cascades[i].cell_size;
cascade_data[i].offset[0] = pos.x;
cascade_data[i].offset[1] = pos.y;
cascade_data[i].offset[2] = pos.z;
cascade_data[i].to_cell = 1.0 / rb->sdfgi->cascades[i].cell_size;
cascade_data[i].probe_offset[0] = rb->sdfgi->cascades[i].position.x / probe_divisor;
cascade_data[i].probe_offset[1] = rb->sdfgi->cascades[i].position.y / probe_divisor;
cascade_data[i].probe_offset[2] = rb->sdfgi->cascades[i].position.z / probe_divisor;
cascade_data[i].pad = 0;
}
RD::get_singleton()->buffer_update(rb->sdfgi->cascades_ubo, 0, sizeof(SDFGI::Cascade::UBO) * SDFGI::MAX_CASCADES, cascade_data, true);
}
void RasterizerSceneRD::sdfgi_update_probes(RID p_render_buffers, RID p_environment, const RID *p_directional_light_instances, uint32_t p_directional_light_count, const RID *p_positional_light_instances, uint32_t p_positional_light_count) {
RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND(rb == nullptr);
if (rb->sdfgi == nullptr) {
return;
}
Environment *env = environment_owner.getornull(p_environment);
RENDER_TIMESTAMP(">SDFGI Update Probes");
/* Update Cascades UBO */
_sdfgi_update_cascades(p_render_buffers);
/* Update Dynamic Lights Buffer */
RENDER_TIMESTAMP("Update Lights");
/* Update dynamic lights */
{
int32_t cascade_light_count[SDFGI::MAX_CASCADES];
for (uint32_t i = 0; i < rb->sdfgi->cascades.size(); i++) {
SDFGI::Cascade &cascade = rb->sdfgi->cascades[i];
SDGIShader::Light lights[SDFGI::MAX_DYNAMIC_LIGHTS];
uint32_t idx = 0;
for (uint32_t j = 0; j < p_directional_light_count; j++) {
if (idx == SDFGI::MAX_DYNAMIC_LIGHTS) {
break;
}
LightInstance *li = light_instance_owner.getornull(p_directional_light_instances[j]);
ERR_CONTINUE(!li);
Vector3 dir = -li->transform.basis.get_axis(Vector3::AXIS_Z);
dir.y *= rb->sdfgi->y_mult;
dir.normalize();
lights[idx].direction[0] = dir.x;
lights[idx].direction[1] = dir.y;
lights[idx].direction[2] = dir.z;
Color color = storage->light_get_color(li->light);
color = color.to_linear();
lights[idx].color[0] = color.r;
lights[idx].color[1] = color.g;
lights[idx].color[2] = color.b;
lights[idx].type = RS::LIGHT_DIRECTIONAL;
lights[idx].energy = storage->light_get_param(li->light, RS::LIGHT_PARAM_ENERGY);
lights[idx].has_shadow = storage->light_has_shadow(li->light);
idx++;
}
AABB cascade_aabb;
cascade_aabb.position = Vector3((Vector3i(1, 1, 1) * -int32_t(rb->sdfgi->cascade_size >> 1) + cascade.position)) * cascade.cell_size;
cascade_aabb.size = Vector3(1, 1, 1) * rb->sdfgi->cascade_size * cascade.cell_size;
for (uint32_t j = 0; j < p_positional_light_count; j++) {
if (idx == SDFGI::MAX_DYNAMIC_LIGHTS) {
break;
}
LightInstance *li = light_instance_owner.getornull(p_positional_light_instances[j]);
ERR_CONTINUE(!li);
uint32_t max_sdfgi_cascade = storage->light_get_max_sdfgi_cascade(li->light);
if (i > max_sdfgi_cascade) {
continue;
}
if (!cascade_aabb.intersects(li->aabb)) {
continue;
}
Vector3 dir = -li->transform.basis.get_axis(Vector3::AXIS_Z);
//faster to not do this here
//dir.y *= rb->sdfgi->y_mult;
//dir.normalize();
lights[idx].direction[0] = dir.x;
lights[idx].direction[1] = dir.y;
lights[idx].direction[2] = dir.z;
Vector3 pos = li->transform.origin;
pos.y *= rb->sdfgi->y_mult;
lights[idx].position[0] = pos.x;
lights[idx].position[1] = pos.y;
lights[idx].position[2] = pos.z;
Color color = storage->light_get_color(li->light);
color = color.to_linear();
lights[idx].color[0] = color.r;
lights[idx].color[1] = color.g;
lights[idx].color[2] = color.b;
lights[idx].type = storage->light_get_type(li->light);
lights[idx].energy = storage->light_get_param(li->light, RS::LIGHT_PARAM_ENERGY);
lights[idx].has_shadow = storage->light_has_shadow(li->light);
lights[idx].attenuation = storage->light_get_param(li->light, RS::LIGHT_PARAM_ATTENUATION);
lights[idx].radius = storage->light_get_param(li->light, RS::LIGHT_PARAM_RANGE);
lights[idx].spot_angle = Math::deg2rad(storage->light_get_param(li->light, RS::LIGHT_PARAM_SPOT_ANGLE));
lights[idx].spot_attenuation = storage->light_get_param(li->light, RS::LIGHT_PARAM_SPOT_ATTENUATION);
idx++;
}
if (idx > 0) {
RD::get_singleton()->buffer_update(cascade.lights_buffer, 0, idx * sizeof(SDGIShader::Light), lights, true);
}
cascade_light_count[i] = idx;
}
RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.direct_light_pipeline[SDGIShader::DIRECT_LIGHT_MODE_DYNAMIC]);
SDGIShader::DirectLightPushConstant push_constant;
push_constant.grid_size[0] = rb->sdfgi->cascade_size;
push_constant.grid_size[1] = rb->sdfgi->cascade_size;
push_constant.grid_size[2] = rb->sdfgi->cascade_size;
push_constant.max_cascades = rb->sdfgi->cascades.size();
push_constant.probe_axis_size = rb->sdfgi->probe_axis_count;
push_constant.multibounce = rb->sdfgi->uses_multibounce;
push_constant.y_mult = rb->sdfgi->y_mult;
push_constant.process_offset = 0;
push_constant.process_increment = 1;
for (uint32_t i = 0; i < rb->sdfgi->cascades.size(); i++) {
SDFGI::Cascade &cascade = rb->sdfgi->cascades[i];
push_constant.light_count = cascade_light_count[i];
push_constant.cascade = i;
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, cascade.sdf_direct_light_uniform_set, 0);
RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::DirectLightPushConstant));
RD::get_singleton()->compute_list_dispatch_indirect(compute_list, cascade.solid_cell_dispatch_buffer, 0);
}
RD::get_singleton()->compute_list_end();
}
RENDER_TIMESTAMP("Raytrace");
SDGIShader::IntegratePushConstant push_constant;
push_constant.grid_size[1] = rb->sdfgi->cascade_size;
push_constant.grid_size[2] = rb->sdfgi->cascade_size;
push_constant.grid_size[0] = rb->sdfgi->cascade_size;
push_constant.max_cascades = rb->sdfgi->cascades.size();
push_constant.probe_axis_size = rb->sdfgi->probe_axis_count;
push_constant.history_index = rb->sdfgi->render_pass % rb->sdfgi->history_size;
push_constant.history_size = rb->sdfgi->history_size;
static const uint32_t ray_count[RS::ENV_SDFGI_RAY_COUNT_MAX] = { 8, 16, 32, 64, 96, 128 };
push_constant.ray_count = ray_count[sdfgi_ray_count];
push_constant.ray_bias = rb->sdfgi->probe_bias;
push_constant.image_size[0] = rb->sdfgi->probe_axis_count * rb->sdfgi->probe_axis_count;
push_constant.image_size[1] = rb->sdfgi->probe_axis_count;
push_constant.store_ambient_texture = env->volumetric_fog_enabled;
RID sky_uniform_set = sdfgi_shader.integrate_default_sky_uniform_set;
push_constant.sky_mode = SDGIShader::IntegratePushConstant::SKY_MODE_DISABLED;
push_constant.y_mult = rb->sdfgi->y_mult;
if (rb->sdfgi->reads_sky && env) {
push_constant.sky_energy = env->bg_energy;
if (env->background == RS::ENV_BG_CLEAR_COLOR) {
push_constant.sky_mode = SDGIShader::IntegratePushConstant::SKY_MODE_COLOR;
Color c = storage->get_default_clear_color().to_linear();
push_constant.sky_color[0] = c.r;
push_constant.sky_color[1] = c.g;
push_constant.sky_color[2] = c.b;
} else if (env->background == RS::ENV_BG_COLOR) {
push_constant.sky_mode = SDGIShader::IntegratePushConstant::SKY_MODE_COLOR;
Color c = env->bg_color;
push_constant.sky_color[0] = c.r;
push_constant.sky_color[1] = c.g;
push_constant.sky_color[2] = c.b;
} else if (env->background == RS::ENV_BG_SKY) {
Sky *sky = sky_owner.getornull(env->sky);
if (sky && sky->radiance.is_valid()) {
if (sky->sdfgi_integrate_sky_uniform_set.is_null() || !RD::get_singleton()->uniform_set_is_valid(sky->sdfgi_integrate_sky_uniform_set)) {
Vector<RD::Uniform> uniforms;
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 0;
u.ids.push_back(sky->radiance);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_SAMPLER;
u.binding = 1;
u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
uniforms.push_back(u);
}
sky->sdfgi_integrate_sky_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.integrate.version_get_shader(sdfgi_shader.integrate_shader, 0), 1);
}
sky_uniform_set = sky->sdfgi_integrate_sky_uniform_set;
push_constant.sky_mode = SDGIShader::IntegratePushConstant::SKY_MODE_SKY;
}
}
}
rb->sdfgi->render_pass++;
RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.integrate_pipeline[SDGIShader::INTEGRATE_MODE_PROCESS]);
int32_t probe_divisor = rb->sdfgi->cascade_size / SDFGI::PROBE_DIVISOR;
for (uint32_t i = 0; i < rb->sdfgi->cascades.size(); i++) {
push_constant.cascade = i;
push_constant.world_offset[0] = rb->sdfgi->cascades[i].position.x / probe_divisor;
push_constant.world_offset[1] = rb->sdfgi->cascades[i].position.y / probe_divisor;
push_constant.world_offset[2] = rb->sdfgi->cascades[i].position.z / probe_divisor;
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->cascades[i].integrate_uniform_set, 0);
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, sky_uniform_set, 1);
RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::IntegratePushConstant));
RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->probe_axis_count * rb->sdfgi->probe_axis_count, rb->sdfgi->probe_axis_count, 1, 8, 8, 1);
}
RD::get_singleton()->compute_list_add_barrier(compute_list); //wait until done
// Then store values into the lightprobe texture. Separating these steps has a small performance hit, but it allows for multiple bounces
RENDER_TIMESTAMP("Average Probes");
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.integrate_pipeline[SDGIShader::INTEGRATE_MODE_STORE]);
//convert to octahedral to store
push_constant.image_size[0] *= SDFGI::LIGHTPROBE_OCT_SIZE;
push_constant.image_size[1] *= SDFGI::LIGHTPROBE_OCT_SIZE;
for (uint32_t i = 0; i < rb->sdfgi->cascades.size(); i++) {
push_constant.cascade = i;
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->cascades[i].integrate_uniform_set, 0);
RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::IntegratePushConstant));
RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->probe_axis_count * rb->sdfgi->probe_axis_count * SDFGI::LIGHTPROBE_OCT_SIZE, rb->sdfgi->probe_axis_count * SDFGI::LIGHTPROBE_OCT_SIZE, 1, 8, 8, 1);
}
RD::get_singleton()->compute_list_end();
RENDER_TIMESTAMP("<SDFGI Update Probes");
}
void RasterizerSceneRD::_setup_giprobes(RID p_render_buffers, const Transform &p_transform, RID *p_gi_probe_cull_result, int p_gi_probe_cull_count, uint32_t &r_gi_probes_used) {
r_gi_probes_used = 0;
RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND(rb == nullptr);
RID gi_probe_buffer = render_buffers_get_gi_probe_buffer(p_render_buffers);
GI::GIProbeData gi_probe_data[RenderBuffers::MAX_GIPROBES];
bool giprobes_changed = false;
Transform to_camera;
to_camera.origin = p_transform.origin; //only translation, make local
for (int i = 0; i < RenderBuffers::MAX_GIPROBES; i++) {
RID texture;
if (i < p_gi_probe_cull_count) {
GIProbeInstance *gipi = gi_probe_instance_owner.getornull(p_gi_probe_cull_result[i]);
if (gipi) {
texture = gipi->texture;
GI::GIProbeData &gipd = gi_probe_data[i];
RID base_probe = gipi->probe;
Transform to_cell = storage->gi_probe_get_to_cell_xform(gipi->probe) * gipi->transform.affine_inverse() * to_camera;
gipd.xform[0] = to_cell.basis.elements[0][0];
gipd.xform[1] = to_cell.basis.elements[1][0];
gipd.xform[2] = to_cell.basis.elements[2][0];
gipd.xform[3] = 0;
gipd.xform[4] = to_cell.basis.elements[0][1];
gipd.xform[5] = to_cell.basis.elements[1][1];
gipd.xform[6] = to_cell.basis.elements[2][1];
gipd.xform[7] = 0;
gipd.xform[8] = to_cell.basis.elements[0][2];
gipd.xform[9] = to_cell.basis.elements[1][2];
gipd.xform[10] = to_cell.basis.elements[2][2];
gipd.xform[11] = 0;
gipd.xform[12] = to_cell.origin.x;
gipd.xform[13] = to_cell.origin.y;
gipd.xform[14] = to_cell.origin.z;
gipd.xform[15] = 1;
Vector3 bounds = storage->gi_probe_get_octree_size(base_probe);
gipd.bounds[0] = bounds.x;
gipd.bounds[1] = bounds.y;
gipd.bounds[2] = bounds.z;
gipd.dynamic_range = storage->gi_probe_get_dynamic_range(base_probe) * storage->gi_probe_get_energy(base_probe);
gipd.bias = storage->gi_probe_get_bias(base_probe);
gipd.normal_bias = storage->gi_probe_get_normal_bias(base_probe);
gipd.blend_ambient = !storage->gi_probe_is_interior(base_probe);
gipd.anisotropy_strength = 0;
gipd.ao = storage->gi_probe_get_ao(base_probe);
gipd.ao_size = Math::pow(storage->gi_probe_get_ao_size(base_probe), 4.0f);
gipd.mipmaps = gipi->mipmaps.size();
}
r_gi_probes_used++;
}
if (texture == RID()) {
texture = storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE);
}
if (texture != rb->giprobe_textures[i]) {
giprobes_changed = true;
rb->giprobe_textures[i] = texture;
}
}
if (giprobes_changed) {
RD::get_singleton()->free(rb->gi_uniform_set);
rb->gi_uniform_set = RID();
if (rb->volumetric_fog) {
if (RD::get_singleton()->uniform_set_is_valid(rb->volumetric_fog->uniform_set)) {
RD::get_singleton()->free(rb->volumetric_fog->uniform_set);
RD::get_singleton()->free(rb->volumetric_fog->uniform_set2);
}
rb->volumetric_fog->uniform_set = RID();
rb->volumetric_fog->uniform_set2 = RID();
}
}
if (p_gi_probe_cull_count > 0) {
RD::get_singleton()->buffer_update(gi_probe_buffer, 0, sizeof(GI::GIProbeData) * MIN(RenderBuffers::MAX_GIPROBES, p_gi_probe_cull_count), gi_probe_data, true);
}
}
void RasterizerSceneRD::_process_gi(RID p_render_buffers, RID p_normal_roughness_buffer, RID p_ambient_buffer, RID p_reflection_buffer, RID p_gi_probe_buffer, RID p_environment, const CameraMatrix &p_projection, const Transform &p_transform, RID *p_gi_probe_cull_result, int p_gi_probe_cull_count) {
RENDER_TIMESTAMP("Render GI");
RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND(rb == nullptr);
Environment *env = environment_owner.getornull(p_environment);
GI::PushConstant push_constant;
push_constant.screen_size[0] = rb->width;
push_constant.screen_size[1] = rb->height;
push_constant.z_near = p_projection.get_z_near();
push_constant.z_far = p_projection.get_z_far();
push_constant.orthogonal = p_projection.is_orthogonal();
push_constant.proj_info[0] = -2.0f / (rb->width * p_projection.matrix[0][0]);
push_constant.proj_info[1] = -2.0f / (rb->height * p_projection.matrix[1][1]);
push_constant.proj_info[2] = (1.0f - p_projection.matrix[0][2]) / p_projection.matrix[0][0];
push_constant.proj_info[3] = (1.0f + p_projection.matrix[1][2]) / p_projection.matrix[1][1];
push_constant.max_giprobes = MIN(RenderBuffers::MAX_GIPROBES, p_gi_probe_cull_count);
push_constant.high_quality_vct = gi_probe_quality == RS::GI_PROBE_QUALITY_HIGH;
push_constant.use_sdfgi = rb->sdfgi != nullptr;
if (env) {
push_constant.ao_color[0] = env->ao_color.r;
push_constant.ao_color[1] = env->ao_color.g;
push_constant.ao_color[2] = env->ao_color.b;
} else {
push_constant.ao_color[0] = 0;
push_constant.ao_color[1] = 0;
push_constant.ao_color[2] = 0;
}
push_constant.cam_rotation[0] = p_transform.basis[0][0];
push_constant.cam_rotation[1] = p_transform.basis[1][0];
push_constant.cam_rotation[2] = p_transform.basis[2][0];
push_constant.cam_rotation[3] = 0;
push_constant.cam_rotation[4] = p_transform.basis[0][1];
push_constant.cam_rotation[5] = p_transform.basis[1][1];
push_constant.cam_rotation[6] = p_transform.basis[2][1];
push_constant.cam_rotation[7] = 0;
push_constant.cam_rotation[8] = p_transform.basis[0][2];
push_constant.cam_rotation[9] = p_transform.basis[1][2];
push_constant.cam_rotation[10] = p_transform.basis[2][2];
push_constant.cam_rotation[11] = 0;
if (rb->sdfgi) {
GI::SDFGIData sdfgi_data;
sdfgi_data.grid_size[0] = rb->sdfgi->cascade_size;
sdfgi_data.grid_size[1] = rb->sdfgi->cascade_size;
sdfgi_data.grid_size[2] = rb->sdfgi->cascade_size;
sdfgi_data.max_cascades = rb->sdfgi->cascades.size();
sdfgi_data.probe_axis_size = rb->sdfgi->probe_axis_count;
sdfgi_data.cascade_probe_size[0] = sdfgi_data.probe_axis_size - 1; //float version for performance
sdfgi_data.cascade_probe_size[1] = sdfgi_data.probe_axis_size - 1;
sdfgi_data.cascade_probe_size[2] = sdfgi_data.probe_axis_size - 1;
float csize = rb->sdfgi->cascade_size;
sdfgi_data.probe_to_uvw = 1.0 / float(sdfgi_data.cascade_probe_size[0]);
sdfgi_data.use_occlusion = rb->sdfgi->uses_occlusion;
//sdfgi_data.energy = rb->sdfgi->energy;
sdfgi_data.y_mult = rb->sdfgi->y_mult;
float cascade_voxel_size = (csize / sdfgi_data.cascade_probe_size[0]);
float occlusion_clamp = (cascade_voxel_size - 0.5) / cascade_voxel_size;
sdfgi_data.occlusion_clamp[0] = occlusion_clamp;
sdfgi_data.occlusion_clamp[1] = occlusion_clamp;
sdfgi_data.occlusion_clamp[2] = occlusion_clamp;
sdfgi_data.normal_bias = (rb->sdfgi->normal_bias / csize) * sdfgi_data.cascade_probe_size[0];
//vec2 tex_pixel_size = 1.0 / vec2(ivec2( (OCT_SIZE+2) * params.probe_axis_size * params.probe_axis_size, (OCT_SIZE+2) * params.probe_axis_size ) );
//vec3 probe_uv_offset = (ivec3(OCT_SIZE+2,OCT_SIZE+2,(OCT_SIZE+2) * params.probe_axis_size)) * tex_pixel_size.xyx;
uint32_t oct_size = SDFGI::LIGHTPROBE_OCT_SIZE;
sdfgi_data.lightprobe_tex_pixel_size[0] = 1.0 / ((oct_size + 2) * sdfgi_data.probe_axis_size * sdfgi_data.probe_axis_size);
sdfgi_data.lightprobe_tex_pixel_size[1] = 1.0 / ((oct_size + 2) * sdfgi_data.probe_axis_size);
sdfgi_data.lightprobe_tex_pixel_size[2] = 1.0;
sdfgi_data.energy = rb->sdfgi->energy;
sdfgi_data.lightprobe_uv_offset[0] = float(oct_size + 2) * sdfgi_data.lightprobe_tex_pixel_size[0];
sdfgi_data.lightprobe_uv_offset[1] = float(oct_size + 2) * sdfgi_data.lightprobe_tex_pixel_size[1];
sdfgi_data.lightprobe_uv_offset[2] = float((oct_size + 2) * sdfgi_data.probe_axis_size) * sdfgi_data.lightprobe_tex_pixel_size[0];
sdfgi_data.occlusion_renormalize[0] = 0.5;
sdfgi_data.occlusion_renormalize[1] = 1.0;
sdfgi_data.occlusion_renormalize[2] = 1.0 / float(sdfgi_data.max_cascades);
int32_t probe_divisor = rb->sdfgi->cascade_size / SDFGI::PROBE_DIVISOR;
for (uint32_t i = 0; i < sdfgi_data.max_cascades; i++) {
GI::SDFGIData::ProbeCascadeData &c = sdfgi_data.cascades[i];
Vector3 pos = Vector3((Vector3i(1, 1, 1) * -int32_t(rb->sdfgi->cascade_size >> 1) + rb->sdfgi->cascades[i].position)) * rb->sdfgi->cascades[i].cell_size;
Vector3 cam_origin = p_transform.origin;
cam_origin.y *= rb->sdfgi->y_mult;
pos -= cam_origin; //make pos local to camera, to reduce numerical error
c.position[0] = pos.x;
c.position[1] = pos.y;
c.position[2] = pos.z;
c.to_probe = 1.0 / (float(rb->sdfgi->cascade_size) * rb->sdfgi->cascades[i].cell_size / float(rb->sdfgi->probe_axis_count - 1));
Vector3i probe_ofs = rb->sdfgi->cascades[i].position / probe_divisor;
c.probe_world_offset[0] = probe_ofs.x;
c.probe_world_offset[1] = probe_ofs.y;
c.probe_world_offset[2] = probe_ofs.z;
c.to_cell = 1.0 / rb->sdfgi->cascades[i].cell_size;
}
RD::get_singleton()->buffer_update(gi.sdfgi_ubo, 0, sizeof(GI::SDFGIData), &sdfgi_data, true);
}
if (rb->gi_uniform_set.is_null() || !RD::get_singleton()->uniform_set_is_valid(rb->gi_uniform_set)) {
Vector<RD::Uniform> uniforms;
{
RD::Uniform u;
u.binding = 1;
u.type = RD::UNIFORM_TYPE_TEXTURE;
for (uint32_t j = 0; j < SDFGI::MAX_CASCADES; j++) {
if (rb->sdfgi && j < rb->sdfgi->cascades.size()) {
u.ids.push_back(rb->sdfgi->cascades[j].sdf_tex);
} else {
u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
}
}
uniforms.push_back(u);
}
{
RD::Uniform u;
u.binding = 2;
u.type = RD::UNIFORM_TYPE_TEXTURE;
for (uint32_t j = 0; j < SDFGI::MAX_CASCADES; j++) {
if (rb->sdfgi && j < rb->sdfgi->cascades.size()) {
u.ids.push_back(rb->sdfgi->cascades[j].light_tex);
} else {
u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
}
}
uniforms.push_back(u);
}
{
RD::Uniform u;
u.binding = 3;
u.type = RD::UNIFORM_TYPE_TEXTURE;
for (uint32_t j = 0; j < SDFGI::MAX_CASCADES; j++) {
if (rb->sdfgi && j < rb->sdfgi->cascades.size()) {
u.ids.push_back(rb->sdfgi->cascades[j].light_aniso_0_tex);
} else {
u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
}
}
uniforms.push_back(u);
}
{
RD::Uniform u;
u.binding = 4;
u.type = RD::UNIFORM_TYPE_TEXTURE;
for (uint32_t j = 0; j < SDFGI::MAX_CASCADES; j++) {
if (rb->sdfgi && j < rb->sdfgi->cascades.size()) {
u.ids.push_back(rb->sdfgi->cascades[j].light_aniso_1_tex);
} else {
u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
}
}
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 5;
if (rb->sdfgi) {
u.ids.push_back(rb->sdfgi->occlusion_texture);
} else {
u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
}
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_SAMPLER;
u.binding = 6;
u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_SAMPLER;
u.binding = 7;
u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 9;
u.ids.push_back(p_ambient_buffer);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 10;
u.ids.push_back(p_reflection_buffer);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 11;
if (rb->sdfgi) {
u.ids.push_back(rb->sdfgi->lightprobe_texture);
} else {
u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_2D_ARRAY_WHITE));
}
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 12;
u.ids.push_back(rb->depth_texture);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 13;
u.ids.push_back(p_normal_roughness_buffer);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 14;
RID buffer = p_gi_probe_buffer.is_valid() ? p_gi_probe_buffer : storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_BLACK);
u.ids.push_back(buffer);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
u.binding = 15;
u.ids.push_back(gi.sdfgi_ubo);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
u.binding = 16;
u.ids.push_back(rb->giprobe_buffer);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 17;
for (int i = 0; i < RenderBuffers::MAX_GIPROBES; i++) {
u.ids.push_back(rb->giprobe_textures[i]);
}
uniforms.push_back(u);
}
rb->gi_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, gi.shader.version_get_shader(gi.shader_version, 0), 0);
}
RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, gi.pipelines[0]);
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->gi_uniform_set, 0);
RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(GI::PushConstant));
RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->width, rb->height, 1, 8, 8, 1);
RD::get_singleton()->compute_list_end();
}
RID RasterizerSceneRD::sky_create() {
return sky_owner.make_rid(Sky());
}
void RasterizerSceneRD::_sky_invalidate(Sky *p_sky) {
if (!p_sky->dirty) {
p_sky->dirty = true;
p_sky->dirty_list = dirty_sky_list;
dirty_sky_list = p_sky;
}
}
void RasterizerSceneRD::sky_set_radiance_size(RID p_sky, int p_radiance_size) {
Sky *sky = sky_owner.getornull(p_sky);
ERR_FAIL_COND(!sky);
ERR_FAIL_COND(p_radiance_size < 32 || p_radiance_size > 2048);
if (sky->radiance_size == p_radiance_size) {
return;
}
sky->radiance_size = p_radiance_size;
if (sky->mode == RS::SKY_MODE_REALTIME && sky->radiance_size != 256) {
WARN_PRINT("Realtime Skies can only use a radiance size of 256. Radiance size will be set to 256 internally.");
sky->radiance_size = 256;
}
_sky_invalidate(sky);
if (sky->radiance.is_valid()) {
RD::get_singleton()->free(sky->radiance);
sky->radiance = RID();
}
_clear_reflection_data(sky->reflection);
}
void RasterizerSceneRD::sky_set_mode(RID p_sky, RS::SkyMode p_mode) {
Sky *sky = sky_owner.getornull(p_sky);
ERR_FAIL_COND(!sky);
if (sky->mode == p_mode) {
return;
}
sky->mode = p_mode;
if (sky->mode == RS::SKY_MODE_REALTIME && sky->radiance_size != 256) {
WARN_PRINT("Realtime Skies can only use a radiance size of 256. Radiance size will be set to 256 internally.");
sky_set_radiance_size(p_sky, 256);
}
_sky_invalidate(sky);
if (sky->radiance.is_valid()) {
RD::get_singleton()->free(sky->radiance);
sky->radiance = RID();
}
_clear_reflection_data(sky->reflection);
}
void RasterizerSceneRD::sky_set_material(RID p_sky, RID p_material) {
Sky *sky = sky_owner.getornull(p_sky);
ERR_FAIL_COND(!sky);
sky->material = p_material;
_sky_invalidate(sky);
}
Ref<Image> RasterizerSceneRD::sky_bake_panorama(RID p_sky, float p_energy, bool p_bake_irradiance, const Size2i &p_size) {
Sky *sky = sky_owner.getornull(p_sky);
ERR_FAIL_COND_V(!sky, Ref<Image>());
_update_dirty_skys();
if (sky->radiance.is_valid()) {
RD::TextureFormat tf;
tf.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;
tf.width = p_size.width;
tf.height = p_size.height;
tf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT;
RID rad_tex = RD::get_singleton()->texture_create(tf, RD::TextureView());
storage->get_effects()->copy_cubemap_to_panorama(sky->radiance, rad_tex, p_size, p_bake_irradiance ? roughness_layers : 0, sky->reflection.layers.size() > 1);
Vector<uint8_t> data = RD::get_singleton()->texture_get_data(rad_tex, 0);
RD::get_singleton()->free(rad_tex);
Ref<Image> img;
img.instance();
img->create(p_size.width, p_size.height, false, Image::FORMAT_RGBAF, data);
for (int i = 0; i < p_size.width; i++) {
for (int j = 0; j < p_size.height; j++) {
Color c = img->get_pixel(i, j);
c.r *= p_energy;
c.g *= p_energy;
c.b *= p_energy;
img->set_pixel(i, j, c);
}
}
return img;
}
return Ref<Image>();
}
void RasterizerSceneRD::_update_dirty_skys() {
Sky *sky = dirty_sky_list;
while (sky) {
bool texture_set_dirty = false;
//update sky configuration if texture is missing
if (sky->radiance.is_null()) {
int mipmaps = Image::get_image_required_mipmaps(sky->radiance_size, sky->radiance_size, Image::FORMAT_RGBAH) + 1;
uint32_t w = sky->radiance_size, h = sky->radiance_size;
int layers = roughness_layers;
if (sky->mode == RS::SKY_MODE_REALTIME) {
layers = 8;
if (roughness_layers != 8) {
WARN_PRINT("When using REALTIME skies, roughness_layers should be set to 8 in the project settings for best quality reflections");
}
}
if (sky_use_cubemap_array) {
//array (higher quality, 6 times more memory)
RD::TextureFormat tf;
tf.array_layers = layers * 6;
tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
tf.type = RD::TEXTURE_TYPE_CUBE_ARRAY;
tf.mipmaps = mipmaps;
tf.width = w;
tf.height = h;
tf.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
sky->radiance = RD::get_singleton()->texture_create(tf, RD::TextureView());
_update_reflection_data(sky->reflection, sky->radiance_size, mipmaps, true, sky->radiance, 0, sky->mode == RS::SKY_MODE_REALTIME);
} else {
//regular cubemap, lower quality (aliasing, less memory)
RD::TextureFormat tf;
tf.array_layers = 6;
tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
tf.type = RD::TEXTURE_TYPE_CUBE;
tf.mipmaps = MIN(mipmaps, layers);
tf.width = w;
tf.height = h;
tf.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
sky->radiance = RD::get_singleton()->texture_create(tf, RD::TextureView());
_update_reflection_data(sky->reflection, sky->radiance_size, MIN(mipmaps, layers), false, sky->radiance, 0, sky->mode == RS::SKY_MODE_REALTIME);
}
texture_set_dirty = true;
}
// Create subpass buffers if they haven't been created already
if (sky->half_res_pass.is_null() && !RD::get_singleton()->texture_is_valid(sky->half_res_pass) && sky->screen_size.x >= 4 && sky->screen_size.y >= 4) {
RD::TextureFormat tformat;
tformat.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
tformat.width = sky->screen_size.x / 2;
tformat.height = sky->screen_size.y / 2;
tformat.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
tformat.type = RD::TEXTURE_TYPE_2D;
sky->half_res_pass = RD::get_singleton()->texture_create(tformat, RD::TextureView());
Vector<RID> texs;
texs.push_back(sky->half_res_pass);
sky->half_res_framebuffer = RD::get_singleton()->framebuffer_create(texs);
texture_set_dirty = true;
}
if (sky->quarter_res_pass.is_null() && !RD::get_singleton()->texture_is_valid(sky->quarter_res_pass) && sky->screen_size.x >= 4 && sky->screen_size.y >= 4) {
RD::TextureFormat tformat;
tformat.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
tformat.width = sky->screen_size.x / 4;
tformat.height = sky->screen_size.y / 4;
tformat.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
tformat.type = RD::TEXTURE_TYPE_2D;
sky->quarter_res_pass = RD::get_singleton()->texture_create(tformat, RD::TextureView());
Vector<RID> texs;
texs.push_back(sky->quarter_res_pass);
sky->quarter_res_framebuffer = RD::get_singleton()->framebuffer_create(texs);
texture_set_dirty = true;
}
if (texture_set_dirty) {
for (int i = 0; i < SKY_TEXTURE_SET_MAX; i++) {
if (sky->texture_uniform_sets[i].is_valid() && RD::get_singleton()->uniform_set_is_valid(sky->texture_uniform_sets[i])) {
RD::get_singleton()->free(sky->texture_uniform_sets[i]);
sky->texture_uniform_sets[i] = RID();
}
}
}
sky->reflection.dirty = true;
sky->processing_layer = 0;
Sky *next = sky->dirty_list;
sky->dirty_list = nullptr;
sky->dirty = false;
sky = next;
}
dirty_sky_list = nullptr;
}
RID RasterizerSceneRD::sky_get_radiance_texture_rd(RID p_sky) const {
Sky *sky = sky_owner.getornull(p_sky);
ERR_FAIL_COND_V(!sky, RID());
return sky->radiance;
}
RID RasterizerSceneRD::sky_get_radiance_uniform_set_rd(RID p_sky, RID p_shader, int p_set) const {
Sky *sky = sky_owner.getornull(p_sky);
ERR_FAIL_COND_V(!sky, RID());
if (sky->uniform_set.is_null() || !RD::get_singleton()->uniform_set_is_valid(sky->uniform_set)) {
sky->uniform_set = RID();
if (sky->radiance.is_valid()) {
Vector<RD::Uniform> uniforms;
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 0;
u.ids.push_back(sky->radiance);
uniforms.push_back(u);
}
sky->uniform_set = RD::get_singleton()->uniform_set_create(uniforms, p_shader, p_set);
}
}
return sky->uniform_set;
}
RID RasterizerSceneRD::_get_sky_textures(Sky *p_sky, SkyTextureSetVersion p_version) {
if (p_sky->texture_uniform_sets[p_version].is_valid() && RD::get_singleton()->uniform_set_is_valid(p_sky->texture_uniform_sets[p_version])) {
return p_sky->texture_uniform_sets[p_version];
}
Vector<RD::Uniform> uniforms;
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 0;
if (p_sky->radiance.is_valid() && p_version <= SKY_TEXTURE_SET_QUARTER_RES) {
u.ids.push_back(p_sky->radiance);
} else {
u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_CUBEMAP_BLACK));
}
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 1; // half res
if (p_sky->half_res_pass.is_valid() && p_version != SKY_TEXTURE_SET_HALF_RES && p_version != SKY_TEXTURE_SET_CUBEMAP_HALF_RES) {
if (p_version >= SKY_TEXTURE_SET_CUBEMAP) {
u.ids.push_back(p_sky->reflection.layers[0].views[1]);
} else {
u.ids.push_back(p_sky->half_res_pass);
}
} else {
if (p_version < SKY_TEXTURE_SET_CUBEMAP) {
u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_WHITE));
} else {
u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_CUBEMAP_BLACK));
}
}
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 2; // quarter res
if (p_sky->quarter_res_pass.is_valid() && p_version != SKY_TEXTURE_SET_QUARTER_RES && p_version != SKY_TEXTURE_SET_CUBEMAP_QUARTER_RES) {
if (p_version >= SKY_TEXTURE_SET_CUBEMAP) {
u.ids.push_back(p_sky->reflection.layers[0].views[2]);
} else {
u.ids.push_back(p_sky->quarter_res_pass);
}
} else {
if (p_version < SKY_TEXTURE_SET_CUBEMAP) {
u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_WHITE));
} else {
u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_CUBEMAP_BLACK));
}
}
uniforms.push_back(u);
}
p_sky->texture_uniform_sets[p_version] = RD::get_singleton()->uniform_set_create(uniforms, sky_shader.default_shader_rd, SKY_SET_TEXTURES);
return p_sky->texture_uniform_sets[p_version];
}
RID RasterizerSceneRD::sky_get_material(RID p_sky) const {
Sky *sky = sky_owner.getornull(p_sky);
ERR_FAIL_COND_V(!sky, RID());
return sky->material;
}
void RasterizerSceneRD::_draw_sky(bool p_can_continue_color, bool p_can_continue_depth, RID p_fb, RID p_environment, const CameraMatrix &p_projection, const Transform &p_transform) {
ERR_FAIL_COND(!is_environment(p_environment));
SkyMaterialData *material = nullptr;
Sky *sky = sky_owner.getornull(environment_get_sky(p_environment));
RID sky_material;
RS::EnvironmentBG background = environment_get_background(p_environment);
if (!(background == RS::ENV_BG_CLEAR_COLOR || background == RS::ENV_BG_COLOR) || sky) {
ERR_FAIL_COND(!sky);
sky_material = sky_get_material(environment_get_sky(p_environment));
if (sky_material.is_valid()) {
material = (SkyMaterialData *)storage->material_get_data(sky_material, RasterizerStorageRD::SHADER_TYPE_SKY);
if (!material || !material->shader_data->valid) {
material = nullptr;
}
}
if (!material) {
sky_material = sky_shader.default_material;
material = (SkyMaterialData *)storage->material_get_data(sky_material, RasterizerStorageRD::SHADER_TYPE_SKY);
}
}
if (background == RS::ENV_BG_CLEAR_COLOR || background == RS::ENV_BG_COLOR) {
sky_material = sky_scene_state.fog_material;
material = (SkyMaterialData *)storage->material_get_data(sky_material, RasterizerStorageRD::SHADER_TYPE_SKY);
}
ERR_FAIL_COND(!material);
SkyShaderData *shader_data = material->shader_data;
ERR_FAIL_COND(!shader_data);
Basis sky_transform = environment_get_sky_orientation(p_environment);
sky_transform.invert();
float multiplier = environment_get_bg_energy(p_environment);
float custom_fov = environment_get_sky_custom_fov(p_environment);
// Camera
CameraMatrix camera;
if (custom_fov) {
float near_plane = p_projection.get_z_near();
float far_plane = p_projection.get_z_far();
float aspect = p_projection.get_aspect();
camera.set_perspective(custom_fov, aspect, near_plane, far_plane);
} else {
camera = p_projection;
}
sky_transform = p_transform.basis * sky_transform;
if (shader_data->uses_quarter_res) {
RenderPipelineVertexFormatCacheRD *pipeline = &shader_data->pipelines[SKY_VERSION_QUARTER_RES];
RID texture_uniform_set = _get_sky_textures(sky, SKY_TEXTURE_SET_QUARTER_RES);
Vector<Color> clear_colors;
clear_colors.push_back(Color(0.0, 0.0, 0.0));
RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(sky->quarter_res_framebuffer, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_DISCARD, clear_colors);
storage->get_effects()->render_sky(draw_list, time, sky->quarter_res_framebuffer, sky_scene_state.uniform_set, sky_scene_state.fog_uniform_set, pipeline, material->uniform_set, texture_uniform_set, camera, sky_transform, multiplier, p_transform.origin);
RD::get_singleton()->draw_list_end();
}
if (shader_data->uses_half_res) {
RenderPipelineVertexFormatCacheRD *pipeline = &shader_data->pipelines[SKY_VERSION_HALF_RES];
RID texture_uniform_set = _get_sky_textures(sky, SKY_TEXTURE_SET_HALF_RES);
Vector<Color> clear_colors;
clear_colors.push_back(Color(0.0, 0.0, 0.0));
RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(sky->half_res_framebuffer, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_DISCARD, clear_colors);
storage->get_effects()->render_sky(draw_list, time, sky->half_res_framebuffer, sky_scene_state.uniform_set, sky_scene_state.fog_uniform_set, pipeline, material->uniform_set, texture_uniform_set, camera, sky_transform, multiplier, p_transform.origin);
RD::get_singleton()->draw_list_end();
}
RenderPipelineVertexFormatCacheRD *pipeline = &shader_data->pipelines[SKY_VERSION_BACKGROUND];
RID texture_uniform_set;
if (sky) {
texture_uniform_set = _get_sky_textures(sky, SKY_TEXTURE_SET_BACKGROUND);
} else {
texture_uniform_set = sky_scene_state.fog_only_texture_uniform_set;
}
RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(p_fb, RD::INITIAL_ACTION_CONTINUE, p_can_continue_color ? RD::FINAL_ACTION_CONTINUE : RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_CONTINUE, p_can_continue_depth ? RD::FINAL_ACTION_CONTINUE : RD::FINAL_ACTION_READ);
storage->get_effects()->render_sky(draw_list, time, p_fb, sky_scene_state.uniform_set, sky_scene_state.fog_uniform_set, pipeline, material->uniform_set, texture_uniform_set, camera, sky_transform, multiplier, p_transform.origin);
RD::get_singleton()->draw_list_end();
}
void RasterizerSceneRD::_setup_sky(RID p_environment, RID p_render_buffers, const CameraMatrix &p_projection, const Transform &p_transform, const Size2i p_screen_size) {
ERR_FAIL_COND(!is_environment(p_environment));
SkyMaterialData *material = nullptr;
Sky *sky = sky_owner.getornull(environment_get_sky(p_environment));
RID sky_material;
SkyShaderData *shader_data = nullptr;
RS::EnvironmentBG background = environment_get_background(p_environment);
if (!(background == RS::ENV_BG_CLEAR_COLOR || background == RS::ENV_BG_COLOR) || sky) {
ERR_FAIL_COND(!sky);
sky_material = sky_get_material(environment_get_sky(p_environment));
if (sky_material.is_valid()) {
material = (SkyMaterialData *)storage->material_get_data(sky_material, RasterizerStorageRD::SHADER_TYPE_SKY);
if (!material || !material->shader_data->valid) {
material = nullptr;
}
}
if (!material) {
sky_material = sky_shader.default_material;
material = (SkyMaterialData *)storage->material_get_data(sky_material, RasterizerStorageRD::SHADER_TYPE_SKY);
}
ERR_FAIL_COND(!material);
shader_data = material->shader_data;
ERR_FAIL_COND(!shader_data);
}
if (sky) {
// Invalidate supbass buffers if screen size changes
if (sky->screen_size != p_screen_size) {
sky->screen_size = p_screen_size;
sky->screen_size.x = sky->screen_size.x < 4 ? 4 : sky->screen_size.x;
sky->screen_size.y = sky->screen_size.y < 4 ? 4 : sky->screen_size.y;
if (shader_data->uses_half_res) {
if (sky->half_res_pass.is_valid()) {
RD::get_singleton()->free(sky->half_res_pass);
sky->half_res_pass = RID();
}
_sky_invalidate(sky);
}
if (shader_data->uses_quarter_res) {
if (sky->quarter_res_pass.is_valid()) {
RD::get_singleton()->free(sky->quarter_res_pass);
sky->quarter_res_pass = RID();
}
_sky_invalidate(sky);
}
}
// Create new subpass buffers if necessary
if ((shader_data->uses_half_res && sky->half_res_pass.is_null()) ||
(shader_data->uses_quarter_res && sky->quarter_res_pass.is_null()) ||
sky->radiance.is_null()) {
_sky_invalidate(sky);
_update_dirty_skys();
}
if (shader_data->uses_time && time - sky->prev_time > 0.00001) {
sky->prev_time = time;
sky->reflection.dirty = true;
RenderingServerRaster::redraw_request();
}
if (material != sky->prev_material) {
sky->prev_material = material;
sky->reflection.dirty = true;
}
if (material->uniform_set_updated) {
material->uniform_set_updated = false;
sky->reflection.dirty = true;
}
if (!p_transform.origin.is_equal_approx(sky->prev_position) && shader_data->uses_position) {
sky->prev_position = p_transform.origin;
sky->reflection.dirty = true;
}
if (shader_data->uses_light) {
// Check whether the directional_light_buffer changes
bool light_data_dirty = false;
if (sky_scene_state.ubo.directional_light_count != sky_scene_state.last_frame_directional_light_count) {
light_data_dirty = true;
for (uint32_t i = sky_scene_state.ubo.directional_light_count; i < sky_scene_state.max_directional_lights; i++) {
sky_scene_state.directional_lights[i].enabled = false;
}
}
if (!light_data_dirty) {
for (uint32_t i = 0; i < sky_scene_state.ubo.directional_light_count; i++) {
if (sky_scene_state.directional_lights[i].direction[0] != sky_scene_state.last_frame_directional_lights[i].direction[0] ||
sky_scene_state.directional_lights[i].direction[1] != sky_scene_state.last_frame_directional_lights[i].direction[1] ||
sky_scene_state.directional_lights[i].direction[2] != sky_scene_state.last_frame_directional_lights[i].direction[2] ||
sky_scene_state.directional_lights[i].energy != sky_scene_state.last_frame_directional_lights[i].energy ||
sky_scene_state.directional_lights[i].color[0] != sky_scene_state.last_frame_directional_lights[i].color[0] ||
sky_scene_state.directional_lights[i].color[1] != sky_scene_state.last_frame_directional_lights[i].color[1] ||
sky_scene_state.directional_lights[i].color[2] != sky_scene_state.last_frame_directional_lights[i].color[2] ||
sky_scene_state.directional_lights[i].enabled != sky_scene_state.last_frame_directional_lights[i].enabled ||
sky_scene_state.directional_lights[i].size != sky_scene_state.last_frame_directional_lights[i].size) {
light_data_dirty = true;
break;
}
}
}
if (light_data_dirty) {
RD::get_singleton()->buffer_update(sky_scene_state.directional_light_buffer, 0, sizeof(SkyDirectionalLightData) * sky_scene_state.max_directional_lights, sky_scene_state.directional_lights, true);
RasterizerSceneRD::SkyDirectionalLightData *temp = sky_scene_state.last_frame_directional_lights;
sky_scene_state.last_frame_directional_lights = sky_scene_state.directional_lights;
sky_scene_state.directional_lights = temp;
sky_scene_state.last_frame_directional_light_count = sky_scene_state.ubo.directional_light_count;
sky->reflection.dirty = true;
}
}
}
//setup fog variables
sky_scene_state.ubo.volumetric_fog_enabled = false;
if (p_render_buffers.is_valid()) {
if (render_buffers_has_volumetric_fog(p_render_buffers)) {
sky_scene_state.ubo.volumetric_fog_enabled = true;
float fog_end = render_buffers_get_volumetric_fog_end(p_render_buffers);
if (fog_end > 0.0) {
sky_scene_state.ubo.volumetric_fog_inv_length = 1.0 / fog_end;
} else {
sky_scene_state.ubo.volumetric_fog_inv_length = 1.0;
}
float fog_detail_spread = render_buffers_get_volumetric_fog_detail_spread(p_render_buffers); //reverse lookup
if (fog_detail_spread > 0.0) {
sky_scene_state.ubo.volumetric_fog_detail_spread = 1.0 / fog_detail_spread;
} else {
sky_scene_state.ubo.volumetric_fog_detail_spread = 1.0;
}
}
RID fog_uniform_set = render_buffers_get_volumetric_fog_sky_uniform_set(p_render_buffers);
if (fog_uniform_set != RID()) {
sky_scene_state.fog_uniform_set = fog_uniform_set;
} else {
sky_scene_state.fog_uniform_set = sky_scene_state.default_fog_uniform_set;
}
}
sky_scene_state.ubo.z_far = p_projection.get_z_far();
sky_scene_state.ubo.fog_enabled = environment_is_fog_enabled(p_environment);
sky_scene_state.ubo.fog_density = environment_get_fog_density(p_environment);
sky_scene_state.ubo.fog_aerial_perspective = environment_get_fog_aerial_perspective(p_environment);
Color fog_color = environment_get_fog_light_color(p_environment).to_linear();
float fog_energy = environment_get_fog_light_energy(p_environment);
sky_scene_state.ubo.fog_light_color[0] = fog_color.r * fog_energy;
sky_scene_state.ubo.fog_light_color[1] = fog_color.g * fog_energy;
sky_scene_state.ubo.fog_light_color[2] = fog_color.b * fog_energy;
sky_scene_state.ubo.fog_sun_scatter = environment_get_fog_sun_scatter(p_environment);
RD::get_singleton()->buffer_update(sky_scene_state.uniform_buffer, 0, sizeof(SkySceneState::UBO), &sky_scene_state.ubo, true);
}
void RasterizerSceneRD::_update_sky(RID p_environment, const CameraMatrix &p_projection, const Transform &p_transform) {
ERR_FAIL_COND(!is_environment(p_environment));
Sky *sky = sky_owner.getornull(environment_get_sky(p_environment));
ERR_FAIL_COND(!sky);
RID sky_material = sky_get_material(environment_get_sky(p_environment));
SkyMaterialData *material = nullptr;
if (sky_material.is_valid()) {
material = (SkyMaterialData *)storage->material_get_data(sky_material, RasterizerStorageRD::SHADER_TYPE_SKY);
if (!material || !material->shader_data->valid) {
material = nullptr;
}
}
if (!material) {
sky_material = sky_shader.default_material;
material = (SkyMaterialData *)storage->material_get_data(sky_material, RasterizerStorageRD::SHADER_TYPE_SKY);
}
ERR_FAIL_COND(!material);
SkyShaderData *shader_data = material->shader_data;
ERR_FAIL_COND(!shader_data);
float multiplier = environment_get_bg_energy(p_environment);
bool update_single_frame = sky->mode == RS::SKY_MODE_REALTIME || sky->mode == RS::SKY_MODE_QUALITY;
RS::SkyMode sky_mode = sky->mode;
if (sky_mode == RS::SKY_MODE_AUTOMATIC) {
if (shader_data->uses_time || shader_data->uses_position) {
update_single_frame = true;
sky_mode = RS::SKY_MODE_REALTIME;
} else if (shader_data->uses_light || shader_data->ubo_size > 0) {
update_single_frame = false;
sky_mode = RS::SKY_MODE_INCREMENTAL;
} else {
update_single_frame = true;
sky_mode = RS::SKY_MODE_QUALITY;
}
}
if (sky->processing_layer == 0 && sky_mode == RS::SKY_MODE_INCREMENTAL) {
// On the first frame after creating sky, rebuild in single frame
update_single_frame = true;
sky_mode = RS::SKY_MODE_QUALITY;
}
int max_processing_layer = sky_use_cubemap_array ? sky->reflection.layers.size() : sky->reflection.layers[0].mipmaps.size();
// Update radiance cubemap
if (sky->reflection.dirty && (sky->processing_layer >= max_processing_layer || update_single_frame)) {
static const Vector3 view_normals[6] = {
Vector3(+1, 0, 0),
Vector3(-1, 0, 0),
Vector3(0, +1, 0),
Vector3(0, -1, 0),
Vector3(0, 0, +1),
Vector3(0, 0, -1)
};
static const Vector3 view_up[6] = {
Vector3(0, -1, 0),
Vector3(0, -1, 0),
Vector3(0, 0, +1),
Vector3(0, 0, -1),
Vector3(0, -1, 0),
Vector3(0, -1, 0)
};
CameraMatrix cm;
cm.set_perspective(90, 1, 0.01, 10.0);
CameraMatrix correction;
correction.set_depth_correction(true);
cm = correction * cm;
if (shader_data->uses_quarter_res) {
RenderPipelineVertexFormatCacheRD *pipeline = &shader_data->pipelines[SKY_VERSION_CUBEMAP_QUARTER_RES];
Vector<Color> clear_colors;
clear_colors.push_back(Color(0.0, 0.0, 0.0));
RD::DrawListID cubemap_draw_list;
for (int i = 0; i < 6; i++) {
Transform local_view;
local_view.set_look_at(Vector3(0, 0, 0), view_normals[i], view_up[i]);
RID texture_uniform_set = _get_sky_textures(sky, SKY_TEXTURE_SET_CUBEMAP_QUARTER_RES);
cubemap_draw_list = RD::get_singleton()->draw_list_begin(sky->reflection.layers[0].mipmaps[2].framebuffers[i], RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_DISCARD);
storage->get_effects()->render_sky(cubemap_draw_list, time, sky->reflection.layers[0].mipmaps[2].framebuffers[i], sky_scene_state.uniform_set, sky_scene_state.fog_uniform_set, pipeline, material->uniform_set, texture_uniform_set, cm, local_view.basis, multiplier, p_transform.origin);
RD::get_singleton()->draw_list_end();
}
}
if (shader_data->uses_half_res) {
RenderPipelineVertexFormatCacheRD *pipeline = &shader_data->pipelines[SKY_VERSION_CUBEMAP_HALF_RES];
Vector<Color> clear_colors;
clear_colors.push_back(Color(0.0, 0.0, 0.0));
RD::DrawListID cubemap_draw_list;
for (int i = 0; i < 6; i++) {
Transform local_view;
local_view.set_look_at(Vector3(0, 0, 0), view_normals[i], view_up[i]);
RID texture_uniform_set = _get_sky_textures(sky, SKY_TEXTURE_SET_CUBEMAP_HALF_RES);
cubemap_draw_list = RD::get_singleton()->draw_list_begin(sky->reflection.layers[0].mipmaps[1].framebuffers[i], RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_DISCARD);
storage->get_effects()->render_sky(cubemap_draw_list, time, sky->reflection.layers[0].mipmaps[1].framebuffers[i], sky_scene_state.uniform_set, sky_scene_state.fog_uniform_set, pipeline, material->uniform_set, texture_uniform_set, cm, local_view.basis, multiplier, p_transform.origin);
RD::get_singleton()->draw_list_end();
}
}
RD::DrawListID cubemap_draw_list;
RenderPipelineVertexFormatCacheRD *pipeline = &shader_data->pipelines[SKY_VERSION_CUBEMAP];
for (int i = 0; i < 6; i++) {
Transform local_view;
local_view.set_look_at(Vector3(0, 0, 0), view_normals[i], view_up[i]);
RID texture_uniform_set = _get_sky_textures(sky, SKY_TEXTURE_SET_CUBEMAP);
cubemap_draw_list = RD::get_singleton()->draw_list_begin(sky->reflection.layers[0].mipmaps[0].framebuffers[i], RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_DISCARD);
storage->get_effects()->render_sky(cubemap_draw_list, time, sky->reflection.layers[0].mipmaps[0].framebuffers[i], sky_scene_state.uniform_set, sky_scene_state.fog_uniform_set, pipeline, material->uniform_set, texture_uniform_set, cm, local_view.basis, multiplier, p_transform.origin);
RD::get_singleton()->draw_list_end();
}
if (sky_mode == RS::SKY_MODE_REALTIME) {
_create_reflection_fast_filter(sky->reflection, sky_use_cubemap_array);
if (sky_use_cubemap_array) {
_update_reflection_mipmaps(sky->reflection, 0, sky->reflection.layers.size());
}
} else {
if (update_single_frame) {
for (int i = 1; i < max_processing_layer; i++) {
_create_reflection_importance_sample(sky->reflection, sky_use_cubemap_array, 10, i);
}
if (sky_use_cubemap_array) {
_update_reflection_mipmaps(sky->reflection, 0, sky->reflection.layers.size());
}
} else {
if (sky_use_cubemap_array) {
// Multi-Frame so just update the first array level
_update_reflection_mipmaps(sky->reflection, 0, 1);
}
}
sky->processing_layer = 1;
}
sky->reflection.dirty = false;
} else {
if (sky_mode == RS::SKY_MODE_INCREMENTAL && sky->processing_layer < max_processing_layer) {
_create_reflection_importance_sample(sky->reflection, sky_use_cubemap_array, 10, sky->processing_layer);
if (sky_use_cubemap_array) {
_update_reflection_mipmaps(sky->reflection, sky->processing_layer, sky->processing_layer + 1);
}
sky->processing_layer++;
}
}
}
/* SKY SHADER */
void RasterizerSceneRD::SkyShaderData::set_code(const String &p_code) {
//compile
code = p_code;
valid = false;
ubo_size = 0;
uniforms.clear();
if (code == String()) {
return; //just invalid, but no error
}
ShaderCompilerRD::GeneratedCode gen_code;
ShaderCompilerRD::IdentifierActions actions;
uses_time = false;
uses_half_res = false;
uses_quarter_res = false;
uses_position = false;
uses_light = false;
actions.render_mode_flags["use_half_res_pass"] = &uses_half_res;
actions.render_mode_flags["use_quarter_res_pass"] = &uses_quarter_res;
actions.usage_flag_pointers["TIME"] = &uses_time;
actions.usage_flag_pointers["POSITION"] = &uses_position;
actions.usage_flag_pointers["LIGHT0_ENABLED"] = &uses_light;
actions.usage_flag_pointers["LIGHT0_ENERGY"] = &uses_light;
actions.usage_flag_pointers["LIGHT0_DIRECTION"] = &uses_light;
actions.usage_flag_pointers["LIGHT0_COLOR"] = &uses_light;
actions.usage_flag_pointers["LIGHT0_SIZE"] = &uses_light;
actions.usage_flag_pointers["LIGHT1_ENABLED"] = &uses_light;
actions.usage_flag_pointers["LIGHT1_ENERGY"] = &uses_light;
actions.usage_flag_pointers["LIGHT1_DIRECTION"] = &uses_light;
actions.usage_flag_pointers["LIGHT1_COLOR"] = &uses_light;
actions.usage_flag_pointers["LIGHT1_SIZE"] = &uses_light;
actions.usage_flag_pointers["LIGHT2_ENABLED"] = &uses_light;
actions.usage_flag_pointers["LIGHT2_ENERGY"] = &uses_light;
actions.usage_flag_pointers["LIGHT2_DIRECTION"] = &uses_light;
actions.usage_flag_pointers["LIGHT2_COLOR"] = &uses_light;
actions.usage_flag_pointers["LIGHT2_SIZE"] = &uses_light;
actions.usage_flag_pointers["LIGHT3_ENABLED"] = &uses_light;
actions.usage_flag_pointers["LIGHT3_ENERGY"] = &uses_light;
actions.usage_flag_pointers["LIGHT3_DIRECTION"] = &uses_light;
actions.usage_flag_pointers["LIGHT3_COLOR"] = &uses_light;
actions.usage_flag_pointers["LIGHT3_SIZE"] = &uses_light;
actions.uniforms = &uniforms;
RasterizerSceneRD *scene_singleton = (RasterizerSceneRD *)RasterizerSceneRD::singleton;
Error err = scene_singleton->sky_shader.compiler.compile(RS::SHADER_SKY, code, &actions, path, gen_code);
ERR_FAIL_COND(err != OK);
if (version.is_null()) {
version = scene_singleton->sky_shader.shader.version_create();
}
#if 0
print_line("**compiling shader:");
print_line("**defines:\n");
for (int i = 0; i < gen_code.defines.size(); i++) {
print_line(gen_code.defines[i]);
}
print_line("\n**uniforms:\n" + gen_code.uniforms);
// print_line("\n**vertex_globals:\n" + gen_code.vertex_global);
// print_line("\n**vertex_code:\n" + gen_code.vertex);
print_line("\n**fragment_globals:\n" + gen_code.fragment_global);
print_line("\n**fragment_code:\n" + gen_code.fragment);
print_line("\n**light_code:\n" + gen_code.light);
#endif
scene_singleton->sky_shader.shader.version_set_code(version, gen_code.uniforms, gen_code.vertex_global, gen_code.vertex, gen_code.fragment_global, gen_code.light, gen_code.fragment, gen_code.defines);
ERR_FAIL_COND(!scene_singleton->sky_shader.shader.version_is_valid(version));
ubo_size = gen_code.uniform_total_size;
ubo_offsets = gen_code.uniform_offsets;
texture_uniforms = gen_code.texture_uniforms;
//update pipelines
for (int i = 0; i < SKY_VERSION_MAX; i++) {
RD::PipelineDepthStencilState depth_stencil_state;
depth_stencil_state.enable_depth_test = true;
depth_stencil_state.depth_compare_operator = RD::COMPARE_OP_LESS_OR_EQUAL;
RID shader_variant = scene_singleton->sky_shader.shader.version_get_shader(version, i);
pipelines[i].setup(shader_variant, RD::RENDER_PRIMITIVE_TRIANGLES, RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), depth_stencil_state, RD::PipelineColorBlendState::create_disabled(), 0);
}
valid = true;
}
void RasterizerSceneRD::SkyShaderData::set_default_texture_param(const StringName &p_name, RID p_texture) {
if (!p_texture.is_valid()) {
default_texture_params.erase(p_name);
} else {
default_texture_params[p_name] = p_texture;
}
}
void RasterizerSceneRD::SkyShaderData::get_param_list(List<PropertyInfo> *p_param_list) const {
Map<int, StringName> order;
for (Map<StringName, ShaderLanguage::ShaderNode::Uniform>::Element *E = uniforms.front(); E; E = E->next()) {
if (E->get().scope == ShaderLanguage::ShaderNode::Uniform::SCOPE_GLOBAL || E->get().scope == ShaderLanguage::ShaderNode::Uniform::SCOPE_INSTANCE) {
continue;
}
if (E->get().texture_order >= 0) {
order[E->get().texture_order + 100000] = E->key();
} else {
order[E->get().order] = E->key();
}
}
for (Map<int, StringName>::Element *E = order.front(); E; E = E->next()) {
PropertyInfo pi = ShaderLanguage::uniform_to_property_info(uniforms[E->get()]);
pi.name = E->get();
p_param_list->push_back(pi);
}
}
void RasterizerSceneRD::SkyShaderData::get_instance_param_list(List<RasterizerStorage::InstanceShaderParam> *p_param_list) const {
for (Map<StringName, ShaderLanguage::ShaderNode::Uniform>::Element *E = uniforms.front(); E; E = E->next()) {
if (E->get().scope != ShaderLanguage::ShaderNode::Uniform::SCOPE_INSTANCE) {
continue;
}
RasterizerStorage::InstanceShaderParam p;
p.info = ShaderLanguage::uniform_to_property_info(E->get());
p.info.name = E->key(); //supply name
p.index = E->get().instance_index;
p.default_value = ShaderLanguage::constant_value_to_variant(E->get().default_value, E->get().type, E->get().hint);
p_param_list->push_back(p);
}
}
bool RasterizerSceneRD::SkyShaderData::is_param_texture(const StringName &p_param) const {
if (!uniforms.has(p_param)) {
return false;
}
return uniforms[p_param].texture_order >= 0;
}
bool RasterizerSceneRD::SkyShaderData::is_animated() const {
return false;
}
bool RasterizerSceneRD::SkyShaderData::casts_shadows() const {
return false;
}
Variant RasterizerSceneRD::SkyShaderData::get_default_parameter(const StringName &p_parameter) const {
if (uniforms.has(p_parameter)) {
ShaderLanguage::ShaderNode::Uniform uniform = uniforms[p_parameter];
Vector<ShaderLanguage::ConstantNode::Value> default_value = uniform.default_value;
return ShaderLanguage::constant_value_to_variant(default_value, uniform.type, uniform.hint);
}
return Variant();
}
RasterizerSceneRD::SkyShaderData::SkyShaderData() {
valid = false;
}
RasterizerSceneRD::SkyShaderData::~SkyShaderData() {
RasterizerSceneRD *scene_singleton = (RasterizerSceneRD *)RasterizerSceneRD::singleton;
ERR_FAIL_COND(!scene_singleton);
//pipeline variants will clear themselves if shader is gone
if (version.is_valid()) {
scene_singleton->sky_shader.shader.version_free(version);
}
}
RasterizerStorageRD::ShaderData *RasterizerSceneRD::_create_sky_shader_func() {
SkyShaderData *shader_data = memnew(SkyShaderData);
return shader_data;
}
void RasterizerSceneRD::SkyMaterialData::update_parameters(const Map<StringName, Variant> &p_parameters, bool p_uniform_dirty, bool p_textures_dirty) {
RasterizerSceneRD *scene_singleton = (RasterizerSceneRD *)RasterizerSceneRD::singleton;
uniform_set_updated = true;
if ((uint32_t)ubo_data.size() != shader_data->ubo_size) {
p_uniform_dirty = true;
if (uniform_buffer.is_valid()) {
RD::get_singleton()->free(uniform_buffer);
uniform_buffer = RID();
}
ubo_data.resize(shader_data->ubo_size);
if (ubo_data.size()) {
uniform_buffer = RD::get_singleton()->uniform_buffer_create(ubo_data.size());
memset(ubo_data.ptrw(), 0, ubo_data.size()); //clear
}
//clear previous uniform set
if (uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(uniform_set)) {
RD::get_singleton()->free(uniform_set);
uniform_set = RID();
}
}
//check whether buffer changed
if (p_uniform_dirty && ubo_data.size()) {
update_uniform_buffer(shader_data->uniforms, shader_data->ubo_offsets.ptr(), p_parameters, ubo_data.ptrw(), ubo_data.size(), false);
RD::get_singleton()->buffer_update(uniform_buffer, 0, ubo_data.size(), ubo_data.ptrw());
}
uint32_t tex_uniform_count = shader_data->texture_uniforms.size();
if ((uint32_t)texture_cache.size() != tex_uniform_count) {
texture_cache.resize(tex_uniform_count);
p_textures_dirty = true;
//clear previous uniform set
if (uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(uniform_set)) {
RD::get_singleton()->free(uniform_set);
uniform_set = RID();
}
}
if (p_textures_dirty && tex_uniform_count) {
update_textures(p_parameters, shader_data->default_texture_params, shader_data->texture_uniforms, texture_cache.ptrw(), true);
}
if (shader_data->ubo_size == 0 && shader_data->texture_uniforms.size() == 0) {
// This material does not require an uniform set, so don't create it.
return;
}
if (!p_textures_dirty && uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(uniform_set)) {
//no reason to update uniform set, only UBO (or nothing) was needed to update
return;
}
Vector<RD::Uniform> uniforms;
{
if (shader_data->ubo_size) {
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
u.binding = 0;
u.ids.push_back(uniform_buffer);
uniforms.push_back(u);
}
const RID *textures = texture_cache.ptrw();
for (uint32_t i = 0; i < tex_uniform_count; i++) {
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 1 + i;
u.ids.push_back(textures[i]);
uniforms.push_back(u);
}
}
uniform_set = RD::get_singleton()->uniform_set_create(uniforms, scene_singleton->sky_shader.shader.version_get_shader(shader_data->version, 0), SKY_SET_MATERIAL);
}
RasterizerSceneRD::SkyMaterialData::~SkyMaterialData() {
if (uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(uniform_set)) {
RD::get_singleton()->free(uniform_set);
}
if (uniform_buffer.is_valid()) {
RD::get_singleton()->free(uniform_buffer);
}
}
RasterizerStorageRD::MaterialData *RasterizerSceneRD::_create_sky_material_func(SkyShaderData *p_shader) {
SkyMaterialData *material_data = memnew(SkyMaterialData);
material_data->shader_data = p_shader;
material_data->last_frame = false;
//update will happen later anyway so do nothing.
return material_data;
}
RID RasterizerSceneRD::environment_create() {
return environment_owner.make_rid(Environment());
}
void RasterizerSceneRD::environment_set_background(RID p_env, RS::EnvironmentBG p_bg) {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND(!env);
env->background = p_bg;
}
void RasterizerSceneRD::environment_set_sky(RID p_env, RID p_sky) {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND(!env);
env->sky = p_sky;
}
void RasterizerSceneRD::environment_set_sky_custom_fov(RID p_env, float p_scale) {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND(!env);
env->sky_custom_fov = p_scale;
}
void RasterizerSceneRD::environment_set_sky_orientation(RID p_env, const Basis &p_orientation) {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND(!env);
env->sky_orientation = p_orientation;
}
void RasterizerSceneRD::environment_set_bg_color(RID p_env, const Color &p_color) {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND(!env);
env->bg_color = p_color;
}
void RasterizerSceneRD::environment_set_bg_energy(RID p_env, float p_energy) {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND(!env);
env->bg_energy = p_energy;
}
void RasterizerSceneRD::environment_set_canvas_max_layer(RID p_env, int p_max_layer) {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND(!env);
env->canvas_max_layer = p_max_layer;
}
void RasterizerSceneRD::environment_set_ambient_light(RID p_env, const Color &p_color, RS::EnvironmentAmbientSource p_ambient, float p_energy, float p_sky_contribution, RS::EnvironmentReflectionSource p_reflection_source, const Color &p_ao_color) {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND(!env);
env->ambient_light = p_color;
env->ambient_source = p_ambient;
env->ambient_light_energy = p_energy;
env->ambient_sky_contribution = p_sky_contribution;
env->reflection_source = p_reflection_source;
env->ao_color = p_ao_color;
}
RS::EnvironmentBG RasterizerSceneRD::environment_get_background(RID p_env) const {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND_V(!env, RS::ENV_BG_MAX);
return env->background;
}
RID RasterizerSceneRD::environment_get_sky(RID p_env) const {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND_V(!env, RID());
return env->sky;
}
float RasterizerSceneRD::environment_get_sky_custom_fov(RID p_env) const {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND_V(!env, 0);
return env->sky_custom_fov;
}
Basis RasterizerSceneRD::environment_get_sky_orientation(RID p_env) const {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND_V(!env, Basis());
return env->sky_orientation;
}
Color RasterizerSceneRD::environment_get_bg_color(RID p_env) const {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND_V(!env, Color());
return env->bg_color;
}
float RasterizerSceneRD::environment_get_bg_energy(RID p_env) const {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND_V(!env, 0);
return env->bg_energy;
}
int RasterizerSceneRD::environment_get_canvas_max_layer(RID p_env) const {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND_V(!env, 0);
return env->canvas_max_layer;
}
Color RasterizerSceneRD::environment_get_ambient_light_color(RID p_env) const {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND_V(!env, Color());
return env->ambient_light;
}
RS::EnvironmentAmbientSource RasterizerSceneRD::environment_get_ambient_source(RID p_env) const {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND_V(!env, RS::ENV_AMBIENT_SOURCE_BG);
return env->ambient_source;
}
float RasterizerSceneRD::environment_get_ambient_light_energy(RID p_env) const {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND_V(!env, 0);
return env->ambient_light_energy;
}
float RasterizerSceneRD::environment_get_ambient_sky_contribution(RID p_env) const {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND_V(!env, 0);
return env->ambient_sky_contribution;
}
RS::EnvironmentReflectionSource RasterizerSceneRD::environment_get_reflection_source(RID p_env) const {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND_V(!env, RS::ENV_REFLECTION_SOURCE_DISABLED);
return env->reflection_source;
}
Color RasterizerSceneRD::environment_get_ao_color(RID p_env) const {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND_V(!env, Color());
return env->ao_color;
}
void RasterizerSceneRD::environment_set_tonemap(RID p_env, RS::EnvironmentToneMapper p_tone_mapper, float p_exposure, float p_white, bool p_auto_exposure, float p_min_luminance, float p_max_luminance, float p_auto_exp_speed, float p_auto_exp_scale) {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND(!env);
env->exposure = p_exposure;
env->tone_mapper = p_tone_mapper;
if (!env->auto_exposure && p_auto_exposure) {
env->auto_exposure_version = ++auto_exposure_counter;
}
env->auto_exposure = p_auto_exposure;
env->white = p_white;
env->min_luminance = p_min_luminance;
env->max_luminance = p_max_luminance;
env->auto_exp_speed = p_auto_exp_speed;
env->auto_exp_scale = p_auto_exp_scale;
}
void RasterizerSceneRD::environment_set_glow(RID p_env, bool p_enable, Vector<float> p_levels, float p_intensity, float p_strength, float p_mix, float p_bloom_threshold, RS::EnvironmentGlowBlendMode p_blend_mode, float p_hdr_bleed_threshold, float p_hdr_bleed_scale, float p_hdr_luminance_cap) {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND(!env);
ERR_FAIL_COND_MSG(p_levels.size() != 7, "Size of array of glow levels must be 7");
env->glow_enabled = p_enable;
env->glow_levels = p_levels;
env->glow_intensity = p_intensity;
env->glow_strength = p_strength;
env->glow_mix = p_mix;
env->glow_bloom = p_bloom_threshold;
env->glow_blend_mode = p_blend_mode;
env->glow_hdr_bleed_threshold = p_hdr_bleed_threshold;
env->glow_hdr_bleed_scale = p_hdr_bleed_scale;
env->glow_hdr_luminance_cap = p_hdr_luminance_cap;
}
void RasterizerSceneRD::environment_glow_set_use_bicubic_upscale(bool p_enable) {
glow_bicubic_upscale = p_enable;
}
void RasterizerSceneRD::environment_glow_set_use_high_quality(bool p_enable) {
glow_high_quality = p_enable;
}
void RasterizerSceneRD::environment_set_sdfgi(RID p_env, bool p_enable, RS::EnvironmentSDFGICascades p_cascades, float p_min_cell_size, RS::EnvironmentSDFGIYScale p_y_scale, bool p_use_occlusion, bool p_use_multibounce, bool p_read_sky, float p_energy, float p_normal_bias, float p_probe_bias) {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND(!env);
env->sdfgi_enabled = p_enable;
env->sdfgi_cascades = p_cascades;
env->sdfgi_min_cell_size = p_min_cell_size;
env->sdfgi_use_occlusion = p_use_occlusion;
env->sdfgi_use_multibounce = p_use_multibounce;
env->sdfgi_read_sky_light = p_read_sky;
env->sdfgi_energy = p_energy;
env->sdfgi_normal_bias = p_normal_bias;
env->sdfgi_probe_bias = p_probe_bias;
env->sdfgi_y_scale = p_y_scale;
}
void RasterizerSceneRD::environment_set_fog(RID p_env, bool p_enable, const Color &p_light_color, float p_light_energy, float p_sun_scatter, float p_density, float p_height, float p_height_density, float p_fog_aerial_perspective) {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND(!env);
env->fog_enabled = p_enable;
env->fog_light_color = p_light_color;
env->fog_light_energy = p_light_energy;
env->fog_sun_scatter = p_sun_scatter;
env->fog_density = p_density;
env->fog_height = p_height;
env->fog_height_density = p_height_density;
env->fog_aerial_perspective = p_fog_aerial_perspective;
}
bool RasterizerSceneRD::environment_is_fog_enabled(RID p_env) const {
const Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND_V(!env, false);
return env->fog_enabled;
}
Color RasterizerSceneRD::environment_get_fog_light_color(RID p_env) const {
const Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND_V(!env, Color());
return env->fog_light_color;
}
float RasterizerSceneRD::environment_get_fog_light_energy(RID p_env) const {
const Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND_V(!env, 0);
return env->fog_light_energy;
}
float RasterizerSceneRD::environment_get_fog_sun_scatter(RID p_env) const {
const Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND_V(!env, 0);
return env->fog_sun_scatter;
}
float RasterizerSceneRD::environment_get_fog_density(RID p_env) const {
const Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND_V(!env, 0);
return env->fog_density;
}
float RasterizerSceneRD::environment_get_fog_height(RID p_env) const {
const Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND_V(!env, 0);
return env->fog_height;
}
float RasterizerSceneRD::environment_get_fog_height_density(RID p_env) const {
const Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND_V(!env, 0);
return env->fog_height_density;
}
float RasterizerSceneRD::environment_get_fog_aerial_perspective(RID p_env) const {
const Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND_V(!env, 0);
return env->fog_aerial_perspective;
}
void RasterizerSceneRD::environment_set_volumetric_fog(RID p_env, bool p_enable, float p_density, const Color &p_light, float p_light_energy, float p_length, float p_detail_spread, float p_gi_inject, RenderingServer::EnvVolumetricFogShadowFilter p_shadow_filter) {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND(!env);
env->volumetric_fog_enabled = p_enable;
env->volumetric_fog_density = p_density;
env->volumetric_fog_light = p_light;
env->volumetric_fog_light_energy = p_light_energy;
env->volumetric_fog_length = p_length;
env->volumetric_fog_detail_spread = p_detail_spread;
env->volumetric_fog_shadow_filter = p_shadow_filter;
env->volumetric_fog_gi_inject = p_gi_inject;
}
void RasterizerSceneRD::environment_set_volumetric_fog_volume_size(int p_size, int p_depth) {
volumetric_fog_size = p_size;
volumetric_fog_depth = p_depth;
}
void RasterizerSceneRD::environment_set_volumetric_fog_filter_active(bool p_enable) {
volumetric_fog_filter_active = p_enable;
}
void RasterizerSceneRD::environment_set_volumetric_fog_directional_shadow_shrink_size(int p_shrink_size) {
p_shrink_size = nearest_power_of_2_templated(p_shrink_size);
if (volumetric_fog_directional_shadow_shrink == (uint32_t)p_shrink_size) {
return;
}
_clear_shadow_shrink_stages(directional_shadow.shrink_stages);
}
void RasterizerSceneRD::environment_set_volumetric_fog_positional_shadow_shrink_size(int p_shrink_size) {
p_shrink_size = nearest_power_of_2_templated(p_shrink_size);
if (volumetric_fog_positional_shadow_shrink == (uint32_t)p_shrink_size) {
return;
}
for (uint32_t i = 0; i < shadow_atlas_owner.get_rid_count(); i++) {
ShadowAtlas *sa = shadow_atlas_owner.get_ptr_by_index(i);
_clear_shadow_shrink_stages(sa->shrink_stages);
}
}
void RasterizerSceneRD::environment_set_sdfgi_ray_count(RS::EnvironmentSDFGIRayCount p_ray_count) {
sdfgi_ray_count = p_ray_count;
}
void RasterizerSceneRD::environment_set_sdfgi_frames_to_converge(RS::EnvironmentSDFGIFramesToConverge p_frames) {
sdfgi_frames_to_converge = p_frames;
}
void RasterizerSceneRD::environment_set_ssr(RID p_env, bool p_enable, int p_max_steps, float p_fade_int, float p_fade_out, float p_depth_tolerance) {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND(!env);
env->ssr_enabled = p_enable;
env->ssr_max_steps = p_max_steps;
env->ssr_fade_in = p_fade_int;
env->ssr_fade_out = p_fade_out;
env->ssr_depth_tolerance = p_depth_tolerance;
}
void RasterizerSceneRD::environment_set_ssr_roughness_quality(RS::EnvironmentSSRRoughnessQuality p_quality) {
ssr_roughness_quality = p_quality;
}
RS::EnvironmentSSRRoughnessQuality RasterizerSceneRD::environment_get_ssr_roughness_quality() const {
return ssr_roughness_quality;
}
void RasterizerSceneRD::environment_set_ssao(RID p_env, bool p_enable, float p_radius, float p_intensity, float p_bias, float p_light_affect, float p_ao_channel_affect, RS::EnvironmentSSAOBlur p_blur, float p_bilateral_sharpness) {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND(!env);
env->ssao_enabled = p_enable;
env->ssao_radius = p_radius;
env->ssao_intensity = p_intensity;
env->ssao_bias = p_bias;
env->ssao_direct_light_affect = p_light_affect;
env->ssao_ao_channel_affect = p_ao_channel_affect;
env->ssao_blur = p_blur;
}
void RasterizerSceneRD::environment_set_ssao_quality(RS::EnvironmentSSAOQuality p_quality, bool p_half_size) {
ssao_quality = p_quality;
ssao_half_size = p_half_size;
}
bool RasterizerSceneRD::environment_is_ssao_enabled(RID p_env) const {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND_V(!env, false);
return env->ssao_enabled;
}
float RasterizerSceneRD::environment_get_ssao_ao_affect(RID p_env) const {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND_V(!env, false);
return env->ssao_ao_channel_affect;
}
float RasterizerSceneRD::environment_get_ssao_light_affect(RID p_env) const {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND_V(!env, false);
return env->ssao_direct_light_affect;
}
bool RasterizerSceneRD::environment_is_ssr_enabled(RID p_env) const {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND_V(!env, false);
return env->ssr_enabled;
}
bool RasterizerSceneRD::environment_is_sdfgi_enabled(RID p_env) const {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND_V(!env, false);
return env->sdfgi_enabled;
}
bool RasterizerSceneRD::is_environment(RID p_env) const {
return environment_owner.owns(p_env);
}
Ref<Image> RasterizerSceneRD::environment_bake_panorama(RID p_env, bool p_bake_irradiance, const Size2i &p_size) {
Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND_V(!env, Ref<Image>());
if (env->background == RS::ENV_BG_CAMERA_FEED || env->background == RS::ENV_BG_CANVAS || env->background == RS::ENV_BG_KEEP) {
return Ref<Image>(); //nothing to bake
}
if (env->background == RS::ENV_BG_CLEAR_COLOR || env->background == RS::ENV_BG_COLOR) {
Color color;
if (env->background == RS::ENV_BG_CLEAR_COLOR) {
color = storage->get_default_clear_color();
} else {
color = env->bg_color;
}
color.r *= env->bg_energy;
color.g *= env->bg_energy;
color.b *= env->bg_energy;
Ref<Image> ret;
ret.instance();
ret->create(p_size.width, p_size.height, false, Image::FORMAT_RGBAF);
for (int i = 0; i < p_size.width; i++) {
for (int j = 0; j < p_size.height; j++) {
ret->set_pixel(i, j, color);
}
}
return ret;
}
if (env->background == RS::ENV_BG_SKY && env->sky.is_valid()) {
return sky_bake_panorama(env->sky, env->bg_energy, p_bake_irradiance, p_size);
}
return Ref<Image>();
}
////////////////////////////////////////////////////////////
RID RasterizerSceneRD::reflection_atlas_create() {
ReflectionAtlas ra;
ra.count = GLOBAL_GET("rendering/quality/reflection_atlas/reflection_count");
ra.size = GLOBAL_GET("rendering/quality/reflection_atlas/reflection_size");
return reflection_atlas_owner.make_rid(ra);
}
void RasterizerSceneRD::reflection_atlas_set_size(RID p_ref_atlas, int p_reflection_size, int p_reflection_count) {
ReflectionAtlas *ra = reflection_atlas_owner.getornull(p_ref_atlas);
ERR_FAIL_COND(!ra);
if (ra->size == p_reflection_size && ra->count == p_reflection_count) {
return; //no changes
}
ra->size = p_reflection_size;
ra->count = p_reflection_count;
if (ra->reflection.is_valid()) {
//clear and invalidate everything
RD::get_singleton()->free(ra->reflection);
ra->reflection = RID();
RD::get_singleton()->free(ra->depth_buffer);
ra->depth_buffer = RID();
for (int i = 0; i < ra->reflections.size(); i++) {
_clear_reflection_data(ra->reflections.write[i].data);
if (ra->reflections[i].owner.is_null()) {
continue;
}
reflection_probe_release_atlas_index(ra->reflections[i].owner);
//rp->atlasindex clear
}
ra->reflections.clear();
}
}
////////////////////////
RID RasterizerSceneRD::reflection_probe_instance_create(RID p_probe) {
ReflectionProbeInstance rpi;
rpi.probe = p_probe;
return reflection_probe_instance_owner.make_rid(rpi);
}
void RasterizerSceneRD::reflection_probe_instance_set_transform(RID p_instance, const Transform &p_transform) {
ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
ERR_FAIL_COND(!rpi);
rpi->transform = p_transform;
rpi->dirty = true;
}
void RasterizerSceneRD::reflection_probe_release_atlas_index(RID p_instance) {
ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
ERR_FAIL_COND(!rpi);
if (rpi->atlas.is_null()) {
return; //nothing to release
}
ReflectionAtlas *atlas = reflection_atlas_owner.getornull(rpi->atlas);
ERR_FAIL_COND(!atlas);
ERR_FAIL_INDEX(rpi->atlas_index, atlas->reflections.size());
atlas->reflections.write[rpi->atlas_index].owner = RID();
rpi->atlas_index = -1;
rpi->atlas = RID();
}
bool RasterizerSceneRD::reflection_probe_instance_needs_redraw(RID p_instance) {
ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
ERR_FAIL_COND_V(!rpi, false);
if (rpi->rendering) {
return false;
}
if (rpi->dirty) {
return true;
}
if (storage->reflection_probe_get_update_mode(rpi->probe) == RS::REFLECTION_PROBE_UPDATE_ALWAYS) {
return true;
}
return rpi->atlas_index == -1;
}
bool RasterizerSceneRD::reflection_probe_instance_has_reflection(RID p_instance) {
ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
ERR_FAIL_COND_V(!rpi, false);
return rpi->atlas.is_valid();
}
bool RasterizerSceneRD::reflection_probe_instance_begin_render(RID p_instance, RID p_reflection_atlas) {
ReflectionAtlas *atlas = reflection_atlas_owner.getornull(p_reflection_atlas);
ERR_FAIL_COND_V(!atlas, false);
ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
ERR_FAIL_COND_V(!rpi, false);
if (storage->reflection_probe_get_update_mode(rpi->probe) == RS::REFLECTION_PROBE_UPDATE_ALWAYS && atlas->reflection.is_valid() && atlas->size != 256) {
WARN_PRINT("ReflectionProbes set to UPDATE_ALWAYS must have an atlas size of 256. Please update the atlas size in the ProjectSettings.");
reflection_atlas_set_size(p_reflection_atlas, 256, atlas->count);
}
if (storage->reflection_probe_get_update_mode(rpi->probe) == RS::REFLECTION_PROBE_UPDATE_ALWAYS && atlas->reflection.is_valid() && atlas->reflections[0].data.layers[0].mipmaps.size() != 8) {
// Invalidate reflection atlas, need to regenerate
RD::get_singleton()->free(atlas->reflection);
atlas->reflection = RID();
for (int i = 0; i < atlas->reflections.size(); i++) {
if (atlas->reflections[i].owner.is_null()) {
continue;
}
reflection_probe_release_atlas_index(atlas->reflections[i].owner);
}
atlas->reflections.clear();
}
if (atlas->reflection.is_null()) {
int mipmaps = MIN(roughness_layers, Image::get_image_required_mipmaps(atlas->size, atlas->size, Image::FORMAT_RGBAH) + 1);
mipmaps = storage->reflection_probe_get_update_mode(rpi->probe) == RS::REFLECTION_PROBE_UPDATE_ALWAYS ? 8 : mipmaps; // always use 8 mipmaps with real time filtering
{
//reflection atlas was unused, create:
RD::TextureFormat tf;
tf.array_layers = 6 * atlas->count;
tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
tf.type = RD::TEXTURE_TYPE_CUBE_ARRAY;
tf.mipmaps = mipmaps;
tf.width = atlas->size;
tf.height = atlas->size;
tf.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
atlas->reflection = RD::get_singleton()->texture_create(tf, RD::TextureView());
}
{
RD::TextureFormat tf;
tf.format = RD::get_singleton()->texture_is_format_supported_for_usage(RD::DATA_FORMAT_D32_SFLOAT, RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) ? RD::DATA_FORMAT_D32_SFLOAT : RD::DATA_FORMAT_X8_D24_UNORM_PACK32;
tf.width = atlas->size;
tf.height = atlas->size;
tf.usage_bits = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT;
atlas->depth_buffer = RD::get_singleton()->texture_create(tf, RD::TextureView());
}
atlas->reflections.resize(atlas->count);
for (int i = 0; i < atlas->count; i++) {
_update_reflection_data(atlas->reflections.write[i].data, atlas->size, mipmaps, false, atlas->reflection, i * 6, storage->reflection_probe_get_update_mode(rpi->probe) == RS::REFLECTION_PROBE_UPDATE_ALWAYS);
for (int j = 0; j < 6; j++) {
Vector<RID> fb;
fb.push_back(atlas->reflections.write[i].data.layers[0].mipmaps[0].views[j]);
fb.push_back(atlas->depth_buffer);
atlas->reflections.write[i].fbs[j] = RD::get_singleton()->framebuffer_create(fb);
}
}
Vector<RID> fb;
fb.push_back(atlas->depth_buffer);
atlas->depth_fb = RD::get_singleton()->framebuffer_create(fb);
}
if (rpi->atlas_index == -1) {
for (int i = 0; i < atlas->reflections.size(); i++) {
if (atlas->reflections[i].owner.is_null()) {
rpi->atlas_index = i;
break;
}
}
//find the one used last
if (rpi->atlas_index == -1) {
//everything is in use, find the one least used via LRU
uint64_t pass_min = 0;
for (int i = 0; i < atlas->reflections.size(); i++) {
ReflectionProbeInstance *rpi2 = reflection_probe_instance_owner.getornull(atlas->reflections[i].owner);
if (rpi2->last_pass < pass_min) {
pass_min = rpi2->last_pass;
rpi->atlas_index = i;
}
}
}
}
rpi->atlas = p_reflection_atlas;
rpi->rendering = true;
rpi->dirty = false;
rpi->processing_layer = 1;
rpi->processing_side = 0;
return true;
}
bool RasterizerSceneRD::reflection_probe_instance_postprocess_step(RID p_instance) {
ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
ERR_FAIL_COND_V(!rpi, false);
ERR_FAIL_COND_V(!rpi->rendering, false);
ERR_FAIL_COND_V(rpi->atlas.is_null(), false);
ReflectionAtlas *atlas = reflection_atlas_owner.getornull(rpi->atlas);
if (!atlas || rpi->atlas_index == -1) {
//does not belong to an atlas anymore, cancel (was removed from atlas or atlas changed while rendering)
rpi->rendering = false;
return false;
}
if (storage->reflection_probe_get_update_mode(rpi->probe) == RS::REFLECTION_PROBE_UPDATE_ALWAYS) {
// Using real time reflections, all roughness is done in one step
_create_reflection_fast_filter(atlas->reflections.write[rpi->atlas_index].data, false);
rpi->rendering = false;
rpi->processing_side = 0;
rpi->processing_layer = 1;
return true;
}
if (rpi->processing_layer > 1) {
_create_reflection_importance_sample(atlas->reflections.write[rpi->atlas_index].data, false, 10, rpi->processing_layer);
rpi->processing_layer++;
if (rpi->processing_layer == atlas->reflections[rpi->atlas_index].data.layers[0].mipmaps.size()) {
rpi->rendering = false;
rpi->processing_side = 0;
rpi->processing_layer = 1;
return true;
}
return false;
} else {
_create_reflection_importance_sample(atlas->reflections.write[rpi->atlas_index].data, false, rpi->processing_side, rpi->processing_layer);
}
rpi->processing_side++;
if (rpi->processing_side == 6) {
rpi->processing_side = 0;
rpi->processing_layer++;
}
return false;
}
uint32_t RasterizerSceneRD::reflection_probe_instance_get_resolution(RID p_instance) {
ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
ERR_FAIL_COND_V(!rpi, 0);
ReflectionAtlas *atlas = reflection_atlas_owner.getornull(rpi->atlas);
ERR_FAIL_COND_V(!atlas, 0);
return atlas->size;
}
RID RasterizerSceneRD::reflection_probe_instance_get_framebuffer(RID p_instance, int p_index) {
ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
ERR_FAIL_COND_V(!rpi, RID());
ERR_FAIL_INDEX_V(p_index, 6, RID());
ReflectionAtlas *atlas = reflection_atlas_owner.getornull(rpi->atlas);
ERR_FAIL_COND_V(!atlas, RID());
return atlas->reflections[rpi->atlas_index].fbs[p_index];
}
RID RasterizerSceneRD::reflection_probe_instance_get_depth_framebuffer(RID p_instance, int p_index) {
ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
ERR_FAIL_COND_V(!rpi, RID());
ERR_FAIL_INDEX_V(p_index, 6, RID());
ReflectionAtlas *atlas = reflection_atlas_owner.getornull(rpi->atlas);
ERR_FAIL_COND_V(!atlas, RID());
return atlas->depth_fb;
}
///////////////////////////////////////////////////////////
RID RasterizerSceneRD::shadow_atlas_create() {
return shadow_atlas_owner.make_rid(ShadowAtlas());
}
void RasterizerSceneRD::shadow_atlas_set_size(RID p_atlas, int p_size) {
ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_atlas);
ERR_FAIL_COND(!shadow_atlas);
ERR_FAIL_COND(p_size < 0);
p_size = next_power_of_2(p_size);
if (p_size == shadow_atlas->size) {
return;
}
// erasing atlas
if (shadow_atlas->depth.is_valid()) {
RD::get_singleton()->free(shadow_atlas->depth);
shadow_atlas->depth = RID();
_clear_shadow_shrink_stages(shadow_atlas->shrink_stages);
}
for (int i = 0; i < 4; i++) {
//clear subdivisions
shadow_atlas->quadrants[i].shadows.resize(0);
shadow_atlas->quadrants[i].shadows.resize(1 << shadow_atlas->quadrants[i].subdivision);
}
//erase shadow atlas reference from lights
for (Map<RID, uint32_t>::Element *E = shadow_atlas->shadow_owners.front(); E; E = E->next()) {
LightInstance *li = light_instance_owner.getornull(E->key());
ERR_CONTINUE(!li);
li->shadow_atlases.erase(p_atlas);
}
//clear owners
shadow_atlas->shadow_owners.clear();
shadow_atlas->size = p_size;
if (shadow_atlas->size) {
RD::TextureFormat tf;
tf.format = RD::DATA_FORMAT_R32_SFLOAT;
tf.width = shadow_atlas->size;
tf.height = shadow_atlas->size;
tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
shadow_atlas->depth = RD::get_singleton()->texture_create(tf, RD::TextureView());
}
}
void RasterizerSceneRD::shadow_atlas_set_quadrant_subdivision(RID p_atlas, int p_quadrant, int p_subdivision) {
ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_atlas);
ERR_FAIL_COND(!shadow_atlas);
ERR_FAIL_INDEX(p_quadrant, 4);
ERR_FAIL_INDEX(p_subdivision, 16384);
uint32_t subdiv = next_power_of_2(p_subdivision);
if (subdiv & 0xaaaaaaaa) { //sqrt(subdiv) must be integer
subdiv <<= 1;
}
subdiv = int(Math::sqrt((float)subdiv));
//obtain the number that will be x*x
if (shadow_atlas->quadrants[p_quadrant].subdivision == subdiv) {
return;
}
//erase all data from quadrant
for (int i = 0; i < shadow_atlas->quadrants[p_quadrant].shadows.size(); i++) {
if (shadow_atlas->quadrants[p_quadrant].shadows[i].owner.is_valid()) {
shadow_atlas->shadow_owners.erase(shadow_atlas->quadrants[p_quadrant].shadows[i].owner);
LightInstance *li = light_instance_owner.getornull(shadow_atlas->quadrants[p_quadrant].shadows[i].owner);
ERR_CONTINUE(!li);
li->shadow_atlases.erase(p_atlas);
}
}
shadow_atlas->quadrants[p_quadrant].shadows.resize(0);
shadow_atlas->quadrants[p_quadrant].shadows.resize(subdiv * subdiv);
shadow_atlas->quadrants[p_quadrant].subdivision = subdiv;
//cache the smallest subdiv (for faster allocation in light update)
shadow_atlas->smallest_subdiv = 1 << 30;
for (int i = 0; i < 4; i++) {
if (shadow_atlas->quadrants[i].subdivision) {
shadow_atlas->smallest_subdiv = MIN(shadow_atlas->smallest_subdiv, shadow_atlas->quadrants[i].subdivision);
}
}
if (shadow_atlas->smallest_subdiv == 1 << 30) {
shadow_atlas->smallest_subdiv = 0;
}
//resort the size orders, simple bublesort for 4 elements..
int swaps = 0;
do {
swaps = 0;
for (int i = 0; i < 3; i++) {
if (shadow_atlas->quadrants[shadow_atlas->size_order[i]].subdivision < shadow_atlas->quadrants[shadow_atlas->size_order[i + 1]].subdivision) {
SWAP(shadow_atlas->size_order[i], shadow_atlas->size_order[i + 1]);
swaps++;
}
}
} while (swaps > 0);
}
bool RasterizerSceneRD::_shadow_atlas_find_shadow(ShadowAtlas *shadow_atlas, int *p_in_quadrants, int p_quadrant_count, int p_current_subdiv, uint64_t p_tick, int &r_quadrant, int &r_shadow) {
for (int i = p_quadrant_count - 1; i >= 0; i--) {
int qidx = p_in_quadrants[i];
if (shadow_atlas->quadrants[qidx].subdivision == (uint32_t)p_current_subdiv) {
return false;
}
//look for an empty space
int sc = shadow_atlas->quadrants[qidx].shadows.size();
ShadowAtlas::Quadrant::Shadow *sarr = shadow_atlas->quadrants[qidx].shadows.ptrw();
int found_free_idx = -1; //found a free one
int found_used_idx = -1; //found existing one, must steal it
uint64_t min_pass = 0; // pass of the existing one, try to use the least recently used one (LRU fashion)
for (int j = 0; j < sc; j++) {
if (!sarr[j].owner.is_valid()) {
found_free_idx = j;
break;
}
LightInstance *sli = light_instance_owner.getornull(sarr[j].owner);
ERR_CONTINUE(!sli);
if (sli->last_scene_pass != scene_pass) {
//was just allocated, don't kill it so soon, wait a bit..
if (p_tick - sarr[j].alloc_tick < shadow_atlas_realloc_tolerance_msec) {
continue;
}
if (found_used_idx == -1 || sli->last_scene_pass < min_pass) {
found_used_idx = j;
min_pass = sli->last_scene_pass;
}
}
}
if (found_free_idx == -1 && found_used_idx == -1) {
continue; //nothing found
}
if (found_free_idx == -1 && found_used_idx != -1) {
found_free_idx = found_used_idx;
}
r_quadrant = qidx;
r_shadow = found_free_idx;
return true;
}
return false;
}
bool RasterizerSceneRD::shadow_atlas_update_light(RID p_atlas, RID p_light_intance, float p_coverage, uint64_t p_light_version) {
ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_atlas);
ERR_FAIL_COND_V(!shadow_atlas, false);
LightInstance *li = light_instance_owner.getornull(p_light_intance);
ERR_FAIL_COND_V(!li, false);
if (shadow_atlas->size == 0 || shadow_atlas->smallest_subdiv == 0) {
return false;
}
uint32_t quad_size = shadow_atlas->size >> 1;
int desired_fit = MIN(quad_size / shadow_atlas->smallest_subdiv, next_power_of_2(quad_size * p_coverage));
int valid_quadrants[4];
int valid_quadrant_count = 0;
int best_size = -1; //best size found
int best_subdiv = -1; //subdiv for the best size
//find the quadrants this fits into, and the best possible size it can fit into
for (int i = 0; i < 4; i++) {
int q = shadow_atlas->size_order[i];
int sd = shadow_atlas->quadrants[q].subdivision;
if (sd == 0) {
continue; //unused
}
int max_fit = quad_size / sd;
if (best_size != -1 && max_fit > best_size) {
break; //too large
}
valid_quadrants[valid_quadrant_count++] = q;
best_subdiv = sd;
if (max_fit >= desired_fit) {
best_size = max_fit;
}
}
ERR_FAIL_COND_V(valid_quadrant_count == 0, false);
uint64_t tick = OS::get_singleton()->get_ticks_msec();
//see if it already exists
if (shadow_atlas->shadow_owners.has(p_light_intance)) {
//it does!
uint32_t key = shadow_atlas->shadow_owners[p_light_intance];
uint32_t q = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x3;
uint32_t s = key & ShadowAtlas::SHADOW_INDEX_MASK;
bool should_realloc = shadow_atlas->quadrants[q].subdivision != (uint32_t)best_subdiv && (shadow_atlas->quadrants[q].shadows[s].alloc_tick - tick > shadow_atlas_realloc_tolerance_msec);
bool should_redraw = shadow_atlas->quadrants[q].shadows[s].version != p_light_version;
if (!should_realloc) {
shadow_atlas->quadrants[q].shadows.write[s].version = p_light_version;
//already existing, see if it should redraw or it's just OK
return should_redraw;
}
int new_quadrant, new_shadow;
//find a better place
if (_shadow_atlas_find_shadow(shadow_atlas, valid_quadrants, valid_quadrant_count, shadow_atlas->quadrants[q].subdivision, tick, new_quadrant, new_shadow)) {
//found a better place!
ShadowAtlas::Quadrant::Shadow *sh = &shadow_atlas->quadrants[new_quadrant].shadows.write[new_shadow];
if (sh->owner.is_valid()) {
//is taken, but is invalid, erasing it
shadow_atlas->shadow_owners.erase(sh->owner);
LightInstance *sli = light_instance_owner.getornull(sh->owner);
sli->shadow_atlases.erase(p_atlas);
}
//erase previous
shadow_atlas->quadrants[q].shadows.write[s].version = 0;
shadow_atlas->quadrants[q].shadows.write[s].owner = RID();
sh->owner = p_light_intance;
sh->alloc_tick = tick;
sh->version = p_light_version;
li->shadow_atlases.insert(p_atlas);
//make new key
key = new_quadrant << ShadowAtlas::QUADRANT_SHIFT;
key |= new_shadow;
//update it in map
shadow_atlas->shadow_owners[p_light_intance] = key;
//make it dirty, as it should redraw anyway
return true;
}
//no better place for this shadow found, keep current
//already existing, see if it should redraw or it's just OK
shadow_atlas->quadrants[q].shadows.write[s].version = p_light_version;
return should_redraw;
}
int new_quadrant, new_shadow;
//find a better place
if (_shadow_atlas_find_shadow(shadow_atlas, valid_quadrants, valid_quadrant_count, -1, tick, new_quadrant, new_shadow)) {
//found a better place!
ShadowAtlas::Quadrant::Shadow *sh = &shadow_atlas->quadrants[new_quadrant].shadows.write[new_shadow];
if (sh->owner.is_valid()) {
//is taken, but is invalid, erasing it
shadow_atlas->shadow_owners.erase(sh->owner);
LightInstance *sli = light_instance_owner.getornull(sh->owner);
sli->shadow_atlases.erase(p_atlas);
}
sh->owner = p_light_intance;
sh->alloc_tick = tick;
sh->version = p_light_version;
li->shadow_atlases.insert(p_atlas);
//make new key
uint32_t key = new_quadrant << ShadowAtlas::QUADRANT_SHIFT;
key |= new_shadow;
//update it in map
shadow_atlas->shadow_owners[p_light_intance] = key;
//make it dirty, as it should redraw anyway
return true;
}
//no place to allocate this light, apologies
return false;
}
void RasterizerSceneRD::directional_shadow_atlas_set_size(int p_size) {
p_size = nearest_power_of_2_templated(p_size);
if (directional_shadow.size == p_size) {
return;
}
directional_shadow.size = p_size;
if (directional_shadow.depth.is_valid()) {
RD::get_singleton()->free(directional_shadow.depth);
_clear_shadow_shrink_stages(directional_shadow.shrink_stages);
directional_shadow.depth = RID();
}
if (p_size > 0) {
RD::TextureFormat tf;
tf.format = RD::DATA_FORMAT_R32_SFLOAT;
tf.width = p_size;
tf.height = p_size;
tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
directional_shadow.depth = RD::get_singleton()->texture_create(tf, RD::TextureView());
}
_base_uniforms_changed();
}
void RasterizerSceneRD::set_directional_shadow_count(int p_count) {
directional_shadow.light_count = p_count;
directional_shadow.current_light = 0;
}
static Rect2i _get_directional_shadow_rect(int p_size, int p_shadow_count, int p_shadow_index) {
int split_h = 1;
int split_v = 1;
while (split_h * split_v < p_shadow_count) {
if (split_h == split_v) {
split_h <<= 1;
} else {
split_v <<= 1;
}
}
Rect2i rect(0, 0, p_size, p_size);
rect.size.width /= split_h;
rect.size.height /= split_v;
rect.position.x = rect.size.width * (p_shadow_index % split_h);
rect.position.y = rect.size.height * (p_shadow_index / split_h);
return rect;
}
int RasterizerSceneRD::get_directional_light_shadow_size(RID p_light_intance) {
ERR_FAIL_COND_V(directional_shadow.light_count == 0, 0);
Rect2i r = _get_directional_shadow_rect(directional_shadow.size, directional_shadow.light_count, 0);
LightInstance *light_instance = light_instance_owner.getornull(p_light_intance);
ERR_FAIL_COND_V(!light_instance, 0);
switch (storage->light_directional_get_shadow_mode(light_instance->light)) {
case RS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL:
break; //none
case RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS:
r.size.height /= 2;
break;
case RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS:
r.size /= 2;
break;
}
return MAX(r.size.width, r.size.height);
}
//////////////////////////////////////////////////
RID RasterizerSceneRD::camera_effects_create() {
return camera_effects_owner.make_rid(CameraEffects());
}
void RasterizerSceneRD::camera_effects_set_dof_blur_quality(RS::DOFBlurQuality p_quality, bool p_use_jitter) {
dof_blur_quality = p_quality;
dof_blur_use_jitter = p_use_jitter;
}
void RasterizerSceneRD::camera_effects_set_dof_blur_bokeh_shape(RS::DOFBokehShape p_shape) {
dof_blur_bokeh_shape = p_shape;
}
void RasterizerSceneRD::camera_effects_set_dof_blur(RID p_camera_effects, bool p_far_enable, float p_far_distance, float p_far_transition, bool p_near_enable, float p_near_distance, float p_near_transition, float p_amount) {
CameraEffects *camfx = camera_effects_owner.getornull(p_camera_effects);
ERR_FAIL_COND(!camfx);
camfx->dof_blur_far_enabled = p_far_enable;
camfx->dof_blur_far_distance = p_far_distance;
camfx->dof_blur_far_transition = p_far_transition;
camfx->dof_blur_near_enabled = p_near_enable;
camfx->dof_blur_near_distance = p_near_distance;
camfx->dof_blur_near_transition = p_near_transition;
camfx->dof_blur_amount = p_amount;
}
void RasterizerSceneRD::camera_effects_set_custom_exposure(RID p_camera_effects, bool p_enable, float p_exposure) {
CameraEffects *camfx = camera_effects_owner.getornull(p_camera_effects);
ERR_FAIL_COND(!camfx);
camfx->override_exposure_enabled = p_enable;
camfx->override_exposure = p_exposure;
}
RID RasterizerSceneRD::light_instance_create(RID p_light) {
RID li = light_instance_owner.make_rid(LightInstance());
LightInstance *light_instance = light_instance_owner.getornull(li);
light_instance->self = li;
light_instance->light = p_light;
light_instance->light_type = storage->light_get_type(p_light);
return li;
}
void RasterizerSceneRD::light_instance_set_transform(RID p_light_instance, const Transform &p_transform) {
LightInstance *light_instance = light_instance_owner.getornull(p_light_instance);
ERR_FAIL_COND(!light_instance);
light_instance->transform = p_transform;
}
void RasterizerSceneRD::light_instance_set_aabb(RID p_light_instance, const AABB &p_aabb) {
LightInstance *light_instance = light_instance_owner.getornull(p_light_instance);
ERR_FAIL_COND(!light_instance);
light_instance->aabb = p_aabb;
}
void RasterizerSceneRD::light_instance_set_shadow_transform(RID p_light_instance, const CameraMatrix &p_projection, const Transform &p_transform, float p_far, float p_split, int p_pass, float p_shadow_texel_size, float p_bias_scale, float p_range_begin, const Vector2 &p_uv_scale) {
LightInstance *light_instance = light_instance_owner.getornull(p_light_instance);
ERR_FAIL_COND(!light_instance);
if (storage->light_get_type(light_instance->light) != RS::LIGHT_DIRECTIONAL) {
p_pass = 0;
}
ERR_FAIL_INDEX(p_pass, 4);
light_instance->shadow_transform[p_pass].camera = p_projection;
light_instance->shadow_transform[p_pass].transform = p_transform;
light_instance->shadow_transform[p_pass].farplane = p_far;
light_instance->shadow_transform[p_pass].split = p_split;
light_instance->shadow_transform[p_pass].bias_scale = p_bias_scale;
light_instance->shadow_transform[p_pass].range_begin = p_range_begin;
light_instance->shadow_transform[p_pass].shadow_texel_size = p_shadow_texel_size;
light_instance->shadow_transform[p_pass].uv_scale = p_uv_scale;
}
void RasterizerSceneRD::light_instance_mark_visible(RID p_light_instance) {
LightInstance *light_instance = light_instance_owner.getornull(p_light_instance);
ERR_FAIL_COND(!light_instance);
light_instance->last_scene_pass = scene_pass;
}
RasterizerSceneRD::ShadowCubemap *RasterizerSceneRD::_get_shadow_cubemap(int p_size) {
if (!shadow_cubemaps.has(p_size)) {
ShadowCubemap sc;
{
RD::TextureFormat tf;
tf.format = RD::get_singleton()->texture_is_format_supported_for_usage(RD::DATA_FORMAT_D32_SFLOAT, RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) ? RD::DATA_FORMAT_D32_SFLOAT : RD::DATA_FORMAT_X8_D24_UNORM_PACK32;
tf.width = p_size;
tf.height = p_size;
tf.type = RD::TEXTURE_TYPE_CUBE;
tf.array_layers = 6;
tf.usage_bits = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT;
sc.cubemap = RD::get_singleton()->texture_create(tf, RD::TextureView());
}
for (int i = 0; i < 6; i++) {
RID side_texture = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), sc.cubemap, i, 0);
Vector<RID> fbtex;
fbtex.push_back(side_texture);
sc.side_fb[i] = RD::get_singleton()->framebuffer_create(fbtex);
}
shadow_cubemaps[p_size] = sc;
}
return &shadow_cubemaps[p_size];
}
RasterizerSceneRD::ShadowMap *RasterizerSceneRD::_get_shadow_map(const Size2i &p_size) {
if (!shadow_maps.has(p_size)) {
ShadowMap sm;
{
RD::TextureFormat tf;
tf.format = RD::get_singleton()->texture_is_format_supported_for_usage(RD::DATA_FORMAT_D32_SFLOAT, RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) ? RD::DATA_FORMAT_D32_SFLOAT : RD::DATA_FORMAT_X8_D24_UNORM_PACK32;
tf.width = p_size.width;
tf.height = p_size.height;
tf.usage_bits = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT;
sm.depth = RD::get_singleton()->texture_create(tf, RD::TextureView());
}
Vector<RID> fbtex;
fbtex.push_back(sm.depth);
sm.fb = RD::get_singleton()->framebuffer_create(fbtex);
shadow_maps[p_size] = sm;
}
return &shadow_maps[p_size];
}
//////////////////////////
RID RasterizerSceneRD::decal_instance_create(RID p_decal) {
DecalInstance di;
di.decal = p_decal;
return decal_instance_owner.make_rid(di);
}
void RasterizerSceneRD::decal_instance_set_transform(RID p_decal, const Transform &p_transform) {
DecalInstance *di = decal_instance_owner.getornull(p_decal);
ERR_FAIL_COND(!di);
di->transform = p_transform;
}
/////////////////////////////////
RID RasterizerSceneRD::gi_probe_instance_create(RID p_base) {
GIProbeInstance gi_probe;
gi_probe.probe = p_base;
RID rid = gi_probe_instance_owner.make_rid(gi_probe);
return rid;
}
void RasterizerSceneRD::gi_probe_instance_set_transform_to_data(RID p_probe, const Transform &p_xform) {
GIProbeInstance *gi_probe = gi_probe_instance_owner.getornull(p_probe);
ERR_FAIL_COND(!gi_probe);
gi_probe->transform = p_xform;
}
bool RasterizerSceneRD::gi_probe_needs_update(RID p_probe) const {
GIProbeInstance *gi_probe = gi_probe_instance_owner.getornull(p_probe);
ERR_FAIL_COND_V(!gi_probe, false);
//return true;
return gi_probe->last_probe_version != storage->gi_probe_get_version(gi_probe->probe);
}
void RasterizerSceneRD::gi_probe_update(RID p_probe, bool p_update_light_instances, const Vector<RID> &p_light_instances, int p_dynamic_object_count, InstanceBase **p_dynamic_objects) {
GIProbeInstance *gi_probe = gi_probe_instance_owner.getornull(p_probe);
ERR_FAIL_COND(!gi_probe);
uint32_t data_version = storage->gi_probe_get_data_version(gi_probe->probe);
// (RE)CREATE IF NEEDED
if (gi_probe->last_probe_data_version != data_version) {
//need to re-create everything
if (gi_probe->texture.is_valid()) {
RD::get_singleton()->free(gi_probe->texture);
RD::get_singleton()->free(gi_probe->write_buffer);
gi_probe->mipmaps.clear();
}
for (int i = 0; i < gi_probe->dynamic_maps.size(); i++) {
RD::get_singleton()->free(gi_probe->dynamic_maps[i].texture);
RD::get_singleton()->free(gi_probe->dynamic_maps[i].depth);
}
gi_probe->dynamic_maps.clear();
Vector3i octree_size = storage->gi_probe_get_octree_size(gi_probe->probe);
if (octree_size != Vector3i()) {
//can create a 3D texture
Vector<int> levels = storage->gi_probe_get_level_counts(gi_probe->probe);
RD::TextureFormat tf;
tf.format = RD::DATA_FORMAT_R8G8B8A8_UNORM;
tf.width = octree_size.x;
tf.height = octree_size.y;
tf.depth = octree_size.z;
tf.type = RD::TEXTURE_TYPE_3D;
tf.mipmaps = levels.size();
tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_CAN_COPY_TO_BIT;
gi_probe->texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
RD::get_singleton()->texture_clear(gi_probe->texture, Color(0, 0, 0, 0), 0, levels.size(), 0, 1, false);
{
int total_elements = 0;
for (int i = 0; i < levels.size(); i++) {
total_elements += levels[i];
}
gi_probe->write_buffer = RD::get_singleton()->storage_buffer_create(total_elements * 16);
}
for (int i = 0; i < levels.size(); i++) {
GIProbeInstance::Mipmap mipmap;
mipmap.texture = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), gi_probe->texture, 0, i, RD::TEXTURE_SLICE_3D);
mipmap.level = levels.size() - i - 1;
mipmap.cell_offset = 0;
for (uint32_t j = 0; j < mipmap.level; j++) {
mipmap.cell_offset += levels[j];
}
mipmap.cell_count = levels[mipmap.level];
Vector<RD::Uniform> uniforms;
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
u.binding = 1;
u.ids.push_back(storage->gi_probe_get_octree_buffer(gi_probe->probe));
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
u.binding = 2;
u.ids.push_back(storage->gi_probe_get_data_buffer(gi_probe->probe));
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
u.binding = 4;
u.ids.push_back(gi_probe->write_buffer);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 9;
u.ids.push_back(storage->gi_probe_get_sdf_texture(gi_probe->probe));
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_SAMPLER;
u.binding = 10;
u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
uniforms.push_back(u);
}
{
Vector<RD::Uniform> copy_uniforms = uniforms;
if (i == 0) {
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
u.binding = 3;
u.ids.push_back(gi_probe_lights_uniform);
copy_uniforms.push_back(u);
}
mipmap.uniform_set = RD::get_singleton()->uniform_set_create(copy_uniforms, giprobe_lighting_shader_version_shaders[GI_PROBE_SHADER_VERSION_COMPUTE_LIGHT], 0);
copy_uniforms = uniforms; //restore
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 5;
u.ids.push_back(gi_probe->texture);
copy_uniforms.push_back(u);
}
mipmap.second_bounce_uniform_set = RD::get_singleton()->uniform_set_create(copy_uniforms, giprobe_lighting_shader_version_shaders[GI_PROBE_SHADER_VERSION_COMPUTE_SECOND_BOUNCE], 0);
} else {
mipmap.uniform_set = RD::get_singleton()->uniform_set_create(copy_uniforms, giprobe_lighting_shader_version_shaders[GI_PROBE_SHADER_VERSION_COMPUTE_MIPMAP], 0);
}
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 5;
u.ids.push_back(mipmap.texture);
uniforms.push_back(u);
}
mipmap.write_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, giprobe_lighting_shader_version_shaders[GI_PROBE_SHADER_VERSION_WRITE_TEXTURE], 0);
gi_probe->mipmaps.push_back(mipmap);
}
{
uint32_t dynamic_map_size = MAX(MAX(octree_size.x, octree_size.y), octree_size.z);
uint32_t oversample = nearest_power_of_2_templated(4);
int mipmap_index = 0;
while (mipmap_index < gi_probe->mipmaps.size()) {
GIProbeInstance::DynamicMap dmap;
if (oversample > 0) {
dmap.size = dynamic_map_size * (1 << oversample);
dmap.mipmap = -1;
oversample--;
} else {
dmap.size = dynamic_map_size >> mipmap_index;
dmap.mipmap = mipmap_index;
mipmap_index++;
}
RD::TextureFormat dtf;
dtf.width = dmap.size;
dtf.height = dmap.size;
dtf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
dtf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT;
if (gi_probe->dynamic_maps.size() == 0) {
dtf.usage_bits |= RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
}
dmap.texture = RD::get_singleton()->texture_create(dtf, RD::TextureView());
if (gi_probe->dynamic_maps.size() == 0) {
//render depth for first one
dtf.format = RD::get_singleton()->texture_is_format_supported_for_usage(RD::DATA_FORMAT_D32_SFLOAT, RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) ? RD::DATA_FORMAT_D32_SFLOAT : RD::DATA_FORMAT_X8_D24_UNORM_PACK32;
dtf.usage_bits = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
dmap.fb_depth = RD::get_singleton()->texture_create(dtf, RD::TextureView());
}
//just use depth as-is
dtf.format = RD::DATA_FORMAT_R32_SFLOAT;
dtf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
dmap.depth = RD::get_singleton()->texture_create(dtf, RD::TextureView());
if (gi_probe->dynamic_maps.size() == 0) {
dtf.format = RD::DATA_FORMAT_R8G8B8A8_UNORM;
dtf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
dmap.albedo = RD::get_singleton()->texture_create(dtf, RD::TextureView());
dmap.normal = RD::get_singleton()->texture_create(dtf, RD::TextureView());
dmap.orm = RD::get_singleton()->texture_create(dtf, RD::TextureView());
Vector<RID> fb;
fb.push_back(dmap.albedo);
fb.push_back(dmap.normal);
fb.push_back(dmap.orm);
fb.push_back(dmap.texture); //emission
fb.push_back(dmap.depth);
fb.push_back(dmap.fb_depth);
dmap.fb = RD::get_singleton()->framebuffer_create(fb);
{
Vector<RD::Uniform> uniforms;
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
u.binding = 3;
u.ids.push_back(gi_probe_lights_uniform);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 5;
u.ids.push_back(dmap.albedo);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 6;
u.ids.push_back(dmap.normal);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 7;
u.ids.push_back(dmap.orm);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 8;
u.ids.push_back(dmap.fb_depth);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 9;
u.ids.push_back(storage->gi_probe_get_sdf_texture(gi_probe->probe));
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_SAMPLER;
u.binding = 10;
u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 11;
u.ids.push_back(dmap.texture);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 12;
u.ids.push_back(dmap.depth);
uniforms.push_back(u);
}
dmap.uniform_set = RD::get_singleton()->uniform_set_create(uniforms, giprobe_lighting_shader_version_shaders[GI_PROBE_SHADER_VERSION_DYNAMIC_OBJECT_LIGHTING], 0);
}
} else {
bool plot = dmap.mipmap >= 0;
bool write = dmap.mipmap < (gi_probe->mipmaps.size() - 1);
Vector<RD::Uniform> uniforms;
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 5;
u.ids.push_back(gi_probe->dynamic_maps[gi_probe->dynamic_maps.size() - 1].texture);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 6;
u.ids.push_back(gi_probe->dynamic_maps[gi_probe->dynamic_maps.size() - 1].depth);
uniforms.push_back(u);
}
if (write) {
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 7;
u.ids.push_back(dmap.texture);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 8;
u.ids.push_back(dmap.depth);
uniforms.push_back(u);
}
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 9;
u.ids.push_back(storage->gi_probe_get_sdf_texture(gi_probe->probe));
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_SAMPLER;
u.binding = 10;
u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
uniforms.push_back(u);
}
if (plot) {
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 11;
u.ids.push_back(gi_probe->mipmaps[dmap.mipmap].texture);
uniforms.push_back(u);
}
}
dmap.uniform_set = RD::get_singleton()->uniform_set_create(uniforms, giprobe_lighting_shader_version_shaders[(write && plot) ? GI_PROBE_SHADER_VERSION_DYNAMIC_SHRINK_WRITE_PLOT : write ? GI_PROBE_SHADER_VERSION_DYNAMIC_SHRINK_WRITE : GI_PROBE_SHADER_VERSION_DYNAMIC_SHRINK_PLOT], 0);
}
gi_probe->dynamic_maps.push_back(dmap);
}
}
}
gi_probe->last_probe_data_version = data_version;
p_update_light_instances = true; //just in case
_base_uniforms_changed();
}
// UDPDATE TIME
if (gi_probe->has_dynamic_object_data) {
//if it has dynamic object data, it needs to be cleared
RD::get_singleton()->texture_clear(gi_probe->texture, Color(0, 0, 0, 0), 0, gi_probe->mipmaps.size(), 0, 1, true);
}
uint32_t light_count = 0;
if (p_update_light_instances || p_dynamic_object_count > 0) {
light_count = MIN(gi_probe_max_lights, (uint32_t)p_light_instances.size());
{
Transform to_cell = storage->gi_probe_get_to_cell_xform(gi_probe->probe);
Transform to_probe_xform = (gi_probe->transform * to_cell.affine_inverse()).affine_inverse();
//update lights
for (uint32_t i = 0; i < light_count; i++) {
GIProbeLight &l = gi_probe_lights[i];
RID light_instance = p_light_instances[i];
RID light = light_instance_get_base_light(light_instance);
l.type = storage->light_get_type(light);
l.attenuation = storage->light_get_param(light, RS::LIGHT_PARAM_ATTENUATION);
l.energy = storage->light_get_param(light, RS::LIGHT_PARAM_ENERGY) * storage->light_get_param(light, RS::LIGHT_PARAM_INDIRECT_ENERGY);
l.radius = to_cell.basis.xform(Vector3(storage->light_get_param(light, RS::LIGHT_PARAM_RANGE), 0, 0)).length();
Color color = storage->light_get_color(light).to_linear();
l.color[0] = color.r;
l.color[1] = color.g;
l.color[2] = color.b;
l.spot_angle_radians = Math::deg2rad(storage->light_get_param(light, RS::LIGHT_PARAM_SPOT_ANGLE));
l.spot_attenuation = storage->light_get_param(light, RS::LIGHT_PARAM_SPOT_ATTENUATION);
Transform xform = light_instance_get_base_transform(light_instance);
Vector3 pos = to_probe_xform.xform(xform.origin);
Vector3 dir = to_probe_xform.basis.xform(-xform.basis.get_axis(2)).normalized();
l.position[0] = pos.x;
l.position[1] = pos.y;
l.position[2] = pos.z;
l.direction[0] = dir.x;
l.direction[1] = dir.y;
l.direction[2] = dir.z;
l.has_shadow = storage->light_has_shadow(light);
}
RD::get_singleton()->buffer_update(gi_probe_lights_uniform, 0, sizeof(GIProbeLight) * light_count, gi_probe_lights, true);
}
}
if (gi_probe->has_dynamic_object_data || p_update_light_instances || p_dynamic_object_count) {
// PROCESS MIPMAPS
if (gi_probe->mipmaps.size()) {
//can update mipmaps
Vector3i probe_size = storage->gi_probe_get_octree_size(gi_probe->probe);
GIProbePushConstant push_constant;
push_constant.limits[0] = probe_size.x;
push_constant.limits[1] = probe_size.y;
push_constant.limits[2] = probe_size.z;
push_constant.stack_size = gi_probe->mipmaps.size();
push_constant.emission_scale = 1.0;
push_constant.propagation = storage->gi_probe_get_propagation(gi_probe->probe);
push_constant.dynamic_range = storage->gi_probe_get_dynamic_range(gi_probe->probe);
push_constant.light_count = light_count;
push_constant.aniso_strength = 0;
/* print_line("probe update to version " + itos(gi_probe->last_probe_version));
print_line("propagation " + rtos(push_constant.propagation));
print_line("dynrange " + rtos(push_constant.dynamic_range));
*/
RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
int passes;
if (p_update_light_instances) {
passes = storage->gi_probe_is_using_two_bounces(gi_probe->probe) ? 2 : 1;
} else {
passes = 1; //only re-blitting is necessary
}
int wg_size = 64;
int wg_limit_x = RD::get_singleton()->limit_get(RD::LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_X);
for (int pass = 0; pass < passes; pass++) {
if (p_update_light_instances) {
for (int i = 0; i < gi_probe->mipmaps.size(); i++) {
if (i == 0) {
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, giprobe_lighting_shader_version_pipelines[pass == 0 ? GI_PROBE_SHADER_VERSION_COMPUTE_LIGHT : GI_PROBE_SHADER_VERSION_COMPUTE_SECOND_BOUNCE]);
} else if (i == 1) {
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, giprobe_lighting_shader_version_pipelines[GI_PROBE_SHADER_VERSION_COMPUTE_MIPMAP]);
}
if (pass == 1 || i > 0) {
RD::get_singleton()->compute_list_add_barrier(compute_list); //wait til previous step is done
}
if (pass == 0 || i > 0) {
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, gi_probe->mipmaps[i].uniform_set, 0);
} else {
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, gi_probe->mipmaps[i].second_bounce_uniform_set, 0);
}
push_constant.cell_offset = gi_probe->mipmaps[i].cell_offset;
push_constant.cell_count = gi_probe->mipmaps[i].cell_count;
int wg_todo = (gi_probe->mipmaps[i].cell_count - 1) / wg_size + 1;
while (wg_todo) {
int wg_count = MIN(wg_todo, wg_limit_x);
RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(GIProbePushConstant));
RD::get_singleton()->compute_list_dispatch(compute_list, wg_count, 1, 1);
wg_todo -= wg_count;
push_constant.cell_offset += wg_count * wg_size;
}
}
RD::get_singleton()->compute_list_add_barrier(compute_list); //wait til previous step is done
}
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, giprobe_lighting_shader_version_pipelines[GI_PROBE_SHADER_VERSION_WRITE_TEXTURE]);
for (int i = 0; i < gi_probe->mipmaps.size(); i++) {
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, gi_probe->mipmaps[i].write_uniform_set, 0);
push_constant.cell_offset = gi_probe->mipmaps[i].cell_offset;
push_constant.cell_count = gi_probe->mipmaps[i].cell_count;
int wg_todo = (gi_probe->mipmaps[i].cell_count - 1) / wg_size + 1;
while (wg_todo) {
int wg_count = MIN(wg_todo, wg_limit_x);
RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(GIProbePushConstant));
RD::get_singleton()->compute_list_dispatch(compute_list, wg_count, 1, 1);
wg_todo -= wg_count;
push_constant.cell_offset += wg_count * wg_size;
}
}
}
RD::get_singleton()->compute_list_end();
}
}
gi_probe->has_dynamic_object_data = false; //clear until dynamic object data is used again
if (p_dynamic_object_count && gi_probe->dynamic_maps.size()) {
Vector3i octree_size = storage->gi_probe_get_octree_size(gi_probe->probe);
int multiplier = gi_probe->dynamic_maps[0].size / MAX(MAX(octree_size.x, octree_size.y), octree_size.z);
Transform oversample_scale;
oversample_scale.basis.scale(Vector3(multiplier, multiplier, multiplier));
Transform to_cell = oversample_scale * storage->gi_probe_get_to_cell_xform(gi_probe->probe);
Transform to_world_xform = gi_probe->transform * to_cell.affine_inverse();
Transform to_probe_xform = to_world_xform.affine_inverse();
AABB probe_aabb(Vector3(), octree_size);
//this could probably be better parallelized in compute..
for (int i = 0; i < p_dynamic_object_count; i++) {
InstanceBase *instance = p_dynamic_objects[i];
//not used, so clear
instance->depth_layer = 0;
instance->depth = 0;
//transform aabb to giprobe
AABB aabb = (to_probe_xform * instance->transform).xform(instance->aabb);
//this needs to wrap to grid resolution to avoid jitter
//also extend margin a bit just in case
Vector3i begin = aabb.position - Vector3i(1, 1, 1);
Vector3i end = aabb.position + aabb.size + Vector3i(1, 1, 1);
for (int j = 0; j < 3; j++) {
if ((end[j] - begin[j]) & 1) {
end[j]++; //for half extents split, it needs to be even
}
begin[j] = MAX(begin[j], 0);
end[j] = MIN(end[j], octree_size[j] * multiplier);
}
//aabb = aabb.intersection(probe_aabb); //intersect
aabb.position = begin;
aabb.size = end - begin;
//print_line("aabb: " + aabb);
for (int j = 0; j < 6; j++) {
//if (j != 0 && j != 3) {
// continue;
//}
static const Vector3 render_z[6] = {
Vector3(1, 0, 0),
Vector3(0, 1, 0),
Vector3(0, 0, 1),
Vector3(-1, 0, 0),
Vector3(0, -1, 0),
Vector3(0, 0, -1),
};
static const Vector3 render_up[6] = {
Vector3(0, 1, 0),
Vector3(0, 0, 1),
Vector3(0, 1, 0),
Vector3(0, 1, 0),
Vector3(0, 0, 1),
Vector3(0, 1, 0),
};
Vector3 render_dir = render_z[j];
Vector3 up_dir = render_up[j];
Vector3 center = aabb.position + aabb.size * 0.5;
Transform xform;
xform.set_look_at(center - aabb.size * 0.5 * render_dir, center, up_dir);
Vector3 x_dir = xform.basis.get_axis(0).abs();
int x_axis = int(Vector3(0, 1, 2).dot(x_dir));
Vector3 y_dir = xform.basis.get_axis(1).abs();
int y_axis = int(Vector3(0, 1, 2).dot(y_dir));
Vector3 z_dir = -xform.basis.get_axis(2);
int z_axis = int(Vector3(0, 1, 2).dot(z_dir.abs()));
Rect2i rect(aabb.position[x_axis], aabb.position[y_axis], aabb.size[x_axis], aabb.size[y_axis]);
bool x_flip = bool(Vector3(1, 1, 1).dot(xform.basis.get_axis(0)) < 0);
bool y_flip = bool(Vector3(1, 1, 1).dot(xform.basis.get_axis(1)) < 0);
bool z_flip = bool(Vector3(1, 1, 1).dot(xform.basis.get_axis(2)) > 0);
CameraMatrix cm;
cm.set_orthogonal(-rect.size.width / 2, rect.size.width / 2, -rect.size.height / 2, rect.size.height / 2, 0.0001, aabb.size[z_axis]);
_render_material(to_world_xform * xform, cm, true, &instance, 1, gi_probe->dynamic_maps[0].fb, Rect2i(Vector2i(), rect.size));
GIProbeDynamicPushConstant push_constant;
zeromem(&push_constant, sizeof(GIProbeDynamicPushConstant));
push_constant.limits[0] = octree_size.x;
push_constant.limits[1] = octree_size.y;
push_constant.limits[2] = octree_size.z;
push_constant.light_count = p_light_instances.size();
push_constant.x_dir[0] = x_dir[0];
push_constant.x_dir[1] = x_dir[1];
push_constant.x_dir[2] = x_dir[2];
push_constant.y_dir[0] = y_dir[0];
push_constant.y_dir[1] = y_dir[1];
push_constant.y_dir[2] = y_dir[2];
push_constant.z_dir[0] = z_dir[0];
push_constant.z_dir[1] = z_dir[1];
push_constant.z_dir[2] = z_dir[2];
push_constant.z_base = xform.origin[z_axis];
push_constant.z_sign = (z_flip ? -1.0 : 1.0);
push_constant.pos_multiplier = float(1.0) / multiplier;
push_constant.dynamic_range = storage->gi_probe_get_dynamic_range(gi_probe->probe);
push_constant.flip_x = x_flip;
push_constant.flip_y = y_flip;
push_constant.rect_pos[0] = rect.position[0];
push_constant.rect_pos[1] = rect.position[1];
push_constant.rect_size[0] = rect.size[0];
push_constant.rect_size[1] = rect.size[1];
push_constant.prev_rect_ofs[0] = 0;
push_constant.prev_rect_ofs[1] = 0;
push_constant.prev_rect_size[0] = 0;
push_constant.prev_rect_size[1] = 0;
push_constant.on_mipmap = false;
push_constant.propagation = storage->gi_probe_get_propagation(gi_probe->probe);
push_constant.pad[0] = 0;
push_constant.pad[1] = 0;
push_constant.pad[2] = 0;
//process lighting
RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, giprobe_lighting_shader_version_pipelines[GI_PROBE_SHADER_VERSION_DYNAMIC_OBJECT_LIGHTING]);
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, gi_probe->dynamic_maps[0].uniform_set, 0);
RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(GIProbeDynamicPushConstant));
RD::get_singleton()->compute_list_dispatch(compute_list, (rect.size.x - 1) / 8 + 1, (rect.size.y - 1) / 8 + 1, 1);
//print_line("rect: " + itos(i) + ": " + rect);
for (int k = 1; k < gi_probe->dynamic_maps.size(); k++) {
// enlarge the rect if needed so all pixels fit when downscaled,
// this ensures downsampling is smooth and optimal because no pixels are left behind
//x
if (rect.position.x & 1) {
rect.size.x++;
push_constant.prev_rect_ofs[0] = 1; //this is used to ensure reading is also optimal
} else {
push_constant.prev_rect_ofs[0] = 0;
}
if (rect.size.x & 1) {
rect.size.x++;
}
rect.position.x >>= 1;
rect.size.x = MAX(1, rect.size.x >> 1);
//y
if (rect.position.y & 1) {
rect.size.y++;
push_constant.prev_rect_ofs[1] = 1;
} else {
push_constant.prev_rect_ofs[1] = 0;
}
if (rect.size.y & 1) {
rect.size.y++;
}
rect.position.y >>= 1;
rect.size.y = MAX(1, rect.size.y >> 1);
//shrink limits to ensure plot does not go outside map
if (gi_probe->dynamic_maps[k].mipmap > 0) {
for (int l = 0; l < 3; l++) {
push_constant.limits[l] = MAX(1, push_constant.limits[l] >> 1);
}
}
//print_line("rect: " + itos(i) + ": " + rect);
push_constant.rect_pos[0] = rect.position[0];
push_constant.rect_pos[1] = rect.position[1];
push_constant.prev_rect_size[0] = push_constant.rect_size[0];
push_constant.prev_rect_size[1] = push_constant.rect_size[1];
push_constant.rect_size[0] = rect.size[0];
push_constant.rect_size[1] = rect.size[1];
push_constant.on_mipmap = gi_probe->dynamic_maps[k].mipmap > 0;
RD::get_singleton()->compute_list_add_barrier(compute_list);
if (gi_probe->dynamic_maps[k].mipmap < 0) {
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, giprobe_lighting_shader_version_pipelines[GI_PROBE_SHADER_VERSION_DYNAMIC_SHRINK_WRITE]);
} else if (k < gi_probe->dynamic_maps.size() - 1) {
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, giprobe_lighting_shader_version_pipelines[GI_PROBE_SHADER_VERSION_DYNAMIC_SHRINK_WRITE_PLOT]);
} else {
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, giprobe_lighting_shader_version_pipelines[GI_PROBE_SHADER_VERSION_DYNAMIC_SHRINK_PLOT]);
}
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, gi_probe->dynamic_maps[k].uniform_set, 0);
RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(GIProbeDynamicPushConstant));
RD::get_singleton()->compute_list_dispatch(compute_list, (rect.size.x - 1) / 8 + 1, (rect.size.y - 1) / 8 + 1, 1);
}
RD::get_singleton()->compute_list_end();
}
}
gi_probe->has_dynamic_object_data = true; //clear until dynamic object data is used again
}
gi_probe->last_probe_version = storage->gi_probe_get_version(gi_probe->probe);
}
void RasterizerSceneRD::_debug_giprobe(RID p_gi_probe, RD::DrawListID p_draw_list, RID p_framebuffer, const CameraMatrix &p_camera_with_transform, bool p_lighting, bool p_emission, float p_alpha) {
GIProbeInstance *gi_probe = gi_probe_instance_owner.getornull(p_gi_probe);
ERR_FAIL_COND(!gi_probe);
if (gi_probe->mipmaps.size() == 0) {
return;
}
CameraMatrix transform = (p_camera_with_transform * CameraMatrix(gi_probe->transform)) * CameraMatrix(storage->gi_probe_get_to_cell_xform(gi_probe->probe).affine_inverse());
int level = 0;
Vector3i octree_size = storage->gi_probe_get_octree_size(gi_probe->probe);
GIProbeDebugPushConstant push_constant;
push_constant.alpha = p_alpha;
push_constant.dynamic_range = storage->gi_probe_get_dynamic_range(gi_probe->probe);
push_constant.cell_offset = gi_probe->mipmaps[level].cell_offset;
push_constant.level = level;
push_constant.bounds[0] = octree_size.x >> level;
push_constant.bounds[1] = octree_size.y >> level;
push_constant.bounds[2] = octree_size.z >> level;
push_constant.pad = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
push_constant.projection[i * 4 + j] = transform.matrix[i][j];
}
}
if (giprobe_debug_uniform_set.is_valid()) {
RD::get_singleton()->free(giprobe_debug_uniform_set);
}
Vector<RD::Uniform> uniforms;
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
u.binding = 1;
u.ids.push_back(storage->gi_probe_get_data_buffer(gi_probe->probe));
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 2;
u.ids.push_back(gi_probe->texture);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_SAMPLER;
u.binding = 3;
u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
uniforms.push_back(u);
}
int cell_count;
if (!p_emission && p_lighting && gi_probe->has_dynamic_object_data) {
cell_count = push_constant.bounds[0] * push_constant.bounds[1] * push_constant.bounds[2];
} else {
cell_count = gi_probe->mipmaps[level].cell_count;
}
giprobe_debug_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, giprobe_debug_shader_version_shaders[0], 0);
RD::get_singleton()->draw_list_bind_render_pipeline(p_draw_list, giprobe_debug_shader_version_pipelines[p_emission ? GI_PROBE_DEBUG_EMISSION : p_lighting ? (gi_probe->has_dynamic_object_data ? GI_PROBE_DEBUG_LIGHT_FULL : GI_PROBE_DEBUG_LIGHT) : GI_PROBE_DEBUG_COLOR].get_render_pipeline(RD::INVALID_ID, RD::get_singleton()->framebuffer_get_format(p_framebuffer)));
RD::get_singleton()->draw_list_bind_uniform_set(p_draw_list, giprobe_debug_uniform_set, 0);
RD::get_singleton()->draw_list_set_push_constant(p_draw_list, &push_constant, sizeof(GIProbeDebugPushConstant));
RD::get_singleton()->draw_list_draw(p_draw_list, false, cell_count, 36);
}
void RasterizerSceneRD::_debug_sdfgi_probes(RID p_render_buffers, RD::DrawListID p_draw_list, RID p_framebuffer, const CameraMatrix &p_camera_with_transform) {
RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND(!rb);
if (!rb->sdfgi) {
return; //nothing to debug
}
SDGIShader::DebugProbesPushConstant push_constant;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
push_constant.projection[i * 4 + j] = p_camera_with_transform.matrix[i][j];
}
}
//gen spheres from strips
uint32_t band_points = 16;
push_constant.band_power = 4;
push_constant.sections_in_band = ((band_points / 2) - 1);
push_constant.band_mask = band_points - 2;
push_constant.section_arc = (Math_PI * 2.0) / float(push_constant.sections_in_band);
push_constant.y_mult = rb->sdfgi->y_mult;
uint32_t total_points = push_constant.sections_in_band * band_points;
uint32_t total_probes = rb->sdfgi->probe_axis_count * rb->sdfgi->probe_axis_count * rb->sdfgi->probe_axis_count;
push_constant.grid_size[0] = rb->sdfgi->cascade_size;
push_constant.grid_size[1] = rb->sdfgi->cascade_size;
push_constant.grid_size[2] = rb->sdfgi->cascade_size;
push_constant.cascade = 0;
push_constant.probe_axis_size = rb->sdfgi->probe_axis_count;
if (!rb->sdfgi->debug_probes_uniform_set.is_valid() || !RD::get_singleton()->uniform_set_is_valid(rb->sdfgi->debug_probes_uniform_set)) {
Vector<RD::Uniform> uniforms;
{
RD::Uniform u;
u.binding = 1;
u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
u.ids.push_back(rb->sdfgi->cascades_ubo);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.binding = 2;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.ids.push_back(rb->sdfgi->lightprobe_texture);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.binding = 3;
u.type = RD::UNIFORM_TYPE_SAMPLER;
u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
uniforms.push_back(u);
}
{
RD::Uniform u;
u.binding = 4;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.ids.push_back(rb->sdfgi->occlusion_texture);
uniforms.push_back(u);
}
rb->sdfgi->debug_probes_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.debug_probes.version_get_shader(sdfgi_shader.debug_probes_shader, 0), 0);
}
RD::get_singleton()->draw_list_bind_render_pipeline(p_draw_list, sdfgi_shader.debug_probes_pipeline[SDGIShader::PROBE_DEBUG_PROBES].get_render_pipeline(RD::INVALID_FORMAT_ID, RD::get_singleton()->framebuffer_get_format(p_framebuffer)));
RD::get_singleton()->draw_list_bind_uniform_set(p_draw_list, rb->sdfgi->debug_probes_uniform_set, 0);
RD::get_singleton()->draw_list_set_push_constant(p_draw_list, &push_constant, sizeof(SDGIShader::DebugProbesPushConstant));
RD::get_singleton()->draw_list_draw(p_draw_list, false, total_probes, total_points);
if (sdfgi_debug_probe_dir != Vector3()) {
print_line("CLICK DEBUG ME?");
uint32_t cascade = 0;
Vector3 offset = Vector3((Vector3i(1, 1, 1) * -int32_t(rb->sdfgi->cascade_size >> 1) + rb->sdfgi->cascades[cascade].position)) * rb->sdfgi->cascades[cascade].cell_size * Vector3(1.0, 1.0 / rb->sdfgi->y_mult, 1.0);
Vector3 probe_size = rb->sdfgi->cascades[cascade].cell_size * (rb->sdfgi->cascade_size / SDFGI::PROBE_DIVISOR) * Vector3(1.0, 1.0 / rb->sdfgi->y_mult, 1.0);
Vector3 ray_from = sdfgi_debug_probe_pos;
Vector3 ray_to = sdfgi_debug_probe_pos + sdfgi_debug_probe_dir * rb->sdfgi->cascades[cascade].cell_size * Math::sqrt(3.0) * rb->sdfgi->cascade_size;
float sphere_radius = 0.2;
float closest_dist = 1e20;
sdfgi_debug_probe_enabled = false;
Vector3i probe_from = rb->sdfgi->cascades[cascade].position / (rb->sdfgi->cascade_size / SDFGI::PROBE_DIVISOR);
for (int i = 0; i < (SDFGI::PROBE_DIVISOR + 1); i++) {
for (int j = 0; j < (SDFGI::PROBE_DIVISOR + 1); j++) {
for (int k = 0; k < (SDFGI::PROBE_DIVISOR + 1); k++) {
Vector3 pos = offset + probe_size * Vector3(i, j, k);
Vector3 res;
if (Geometry3D::segment_intersects_sphere(ray_from, ray_to, pos, sphere_radius, &res)) {
float d = ray_from.distance_to(res);
if (d < closest_dist) {
closest_dist = d;
sdfgi_debug_probe_enabled = true;
sdfgi_debug_probe_index = probe_from + Vector3i(i, j, k);
}
}
}
}
}
if (sdfgi_debug_probe_enabled) {
print_line("found: " + sdfgi_debug_probe_index);
} else {
print_line("no found");
}
sdfgi_debug_probe_dir = Vector3();
}
if (sdfgi_debug_probe_enabled) {
uint32_t cascade = 0;
uint32_t probe_cells = (rb->sdfgi->cascade_size / SDFGI::PROBE_DIVISOR);
Vector3i probe_from = rb->sdfgi->cascades[cascade].position / probe_cells;
Vector3i ofs = sdfgi_debug_probe_index - probe_from;
if (ofs.x < 0 || ofs.y < 0 || ofs.z < 0) {
return;
}
if (ofs.x > SDFGI::PROBE_DIVISOR || ofs.y > SDFGI::PROBE_DIVISOR || ofs.z > SDFGI::PROBE_DIVISOR) {
return;
}
uint32_t mult = (SDFGI::PROBE_DIVISOR + 1);
uint32_t index = ofs.z * mult * mult + ofs.y * mult + ofs.x;
push_constant.probe_debug_index = index;
uint32_t cell_count = probe_cells * 2 * probe_cells * 2 * probe_cells * 2;
RD::get_singleton()->draw_list_bind_render_pipeline(p_draw_list, sdfgi_shader.debug_probes_pipeline[SDGIShader::PROBE_DEBUG_VISIBILITY].get_render_pipeline(RD::INVALID_FORMAT_ID, RD::get_singleton()->framebuffer_get_format(p_framebuffer)));
RD::get_singleton()->draw_list_bind_uniform_set(p_draw_list, rb->sdfgi->debug_probes_uniform_set, 0);
RD::get_singleton()->draw_list_set_push_constant(p_draw_list, &push_constant, sizeof(SDGIShader::DebugProbesPushConstant));
RD::get_singleton()->draw_list_draw(p_draw_list, false, cell_count, total_points);
}
}
////////////////////////////////
RID RasterizerSceneRD::render_buffers_create() {
RenderBuffers rb;
rb.data = _create_render_buffer_data();
return render_buffers_owner.make_rid(rb);
}
void RasterizerSceneRD::_allocate_blur_textures(RenderBuffers *rb) {
ERR_FAIL_COND(!rb->blur[0].texture.is_null());
uint32_t mipmaps_required = Image::get_image_required_mipmaps(rb->width, rb->height, Image::FORMAT_RGBAH);
RD::TextureFormat tf;
tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
tf.width = rb->width;
tf.height = rb->height;
tf.type = RD::TEXTURE_TYPE_2D;
tf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_COPY_TO_BIT;
tf.mipmaps = mipmaps_required;
rb->blur[0].texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
//the second one is smaller (only used for separatable part of blur)
tf.width >>= 1;
tf.height >>= 1;
tf.mipmaps--;
rb->blur[1].texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
int base_width = rb->width;
int base_height = rb->height;
for (uint32_t i = 0; i < mipmaps_required; i++) {
RenderBuffers::Blur::Mipmap mm;
mm.texture = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), rb->blur[0].texture, 0, i);
mm.width = base_width;
mm.height = base_height;
rb->blur[0].mipmaps.push_back(mm);
if (i > 0) {
mm.texture = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), rb->blur[1].texture, 0, i - 1);
rb->blur[1].mipmaps.push_back(mm);
}
base_width = MAX(1, base_width >> 1);
base_height = MAX(1, base_height >> 1);
}
}
void RasterizerSceneRD::_allocate_luminance_textures(RenderBuffers *rb) {
ERR_FAIL_COND(!rb->luminance.current.is_null());
int w = rb->width;
int h = rb->height;
while (true) {
w = MAX(w / 8, 1);
h = MAX(h / 8, 1);
RD::TextureFormat tf;
tf.format = RD::DATA_FORMAT_R32_SFLOAT;
tf.width = w;
tf.height = h;
tf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT;
bool final = w == 1 && h == 1;
if (final) {
tf.usage_bits |= RD::TEXTURE_USAGE_SAMPLING_BIT;
}
RID texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
rb->luminance.reduce.push_back(texture);
if (final) {
rb->luminance.current = RD::get_singleton()->texture_create(tf, RD::TextureView());
break;
}
}
}
void RasterizerSceneRD::_free_render_buffer_data(RenderBuffers *rb) {
if (rb->texture.is_valid()) {
RD::get_singleton()->free(rb->texture);
rb->texture = RID();
}
if (rb->depth_texture.is_valid()) {
RD::get_singleton()->free(rb->depth_texture);
rb->depth_texture = RID();
}
for (int i = 0; i < 2; i++) {
if (rb->blur[i].texture.is_valid()) {
RD::get_singleton()->free(rb->blur[i].texture);
rb->blur[i].texture = RID();
rb->blur[i].mipmaps.clear();
}
}
for (int i = 0; i < rb->luminance.reduce.size(); i++) {
RD::get_singleton()->free(rb->luminance.reduce[i]);
}
for (int i = 0; i < rb->luminance.reduce.size(); i++) {
RD::get_singleton()->free(rb->luminance.reduce[i]);
}
rb->luminance.reduce.clear();
if (rb->luminance.current.is_valid()) {
RD::get_singleton()->free(rb->luminance.current);
rb->luminance.current = RID();
}
if (rb->ssao.ao[0].is_valid()) {
RD::get_singleton()->free(rb->ssao.depth);
RD::get_singleton()->free(rb->ssao.ao[0]);
if (rb->ssao.ao[1].is_valid()) {
RD::get_singleton()->free(rb->ssao.ao[1]);
}
if (rb->ssao.ao_full.is_valid()) {
RD::get_singleton()->free(rb->ssao.ao_full);
}
rb->ssao.depth = RID();
rb->ssao.ao[0] = RID();
rb->ssao.ao[1] = RID();
rb->ssao.ao_full = RID();
rb->ssao.depth_slices.clear();
}
if (rb->ssr.blur_radius[0].is_valid()) {
RD::get_singleton()->free(rb->ssr.blur_radius[0]);
RD::get_singleton()->free(rb->ssr.blur_radius[1]);
rb->ssr.blur_radius[0] = RID();
rb->ssr.blur_radius[1] = RID();
}
if (rb->ssr.depth_scaled.is_valid()) {
RD::get_singleton()->free(rb->ssr.depth_scaled);
rb->ssr.depth_scaled = RID();
RD::get_singleton()->free(rb->ssr.normal_scaled);
rb->ssr.normal_scaled = RID();
}
}
void RasterizerSceneRD::_process_sss(RID p_render_buffers, const CameraMatrix &p_camera) {
RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND(!rb);
bool can_use_effects = rb->width >= 8 && rb->height >= 8;
if (!can_use_effects) {
//just copy
return;
}
if (rb->blur[0].texture.is_null()) {
_allocate_blur_textures(rb);
_render_buffers_uniform_set_changed(p_render_buffers);
}
storage->get_effects()->sub_surface_scattering(rb->texture, rb->blur[0].mipmaps[0].texture, rb->depth_texture, p_camera, Size2i(rb->width, rb->height), sss_scale, sss_depth_scale, sss_quality);
}
void RasterizerSceneRD::_process_ssr(RID p_render_buffers, RID p_dest_framebuffer, RID p_normal_buffer, RID p_specular_buffer, RID p_metallic, const Color &p_metallic_mask, RID p_environment, const CameraMatrix &p_projection, bool p_use_additive) {
RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND(!rb);
bool can_use_effects = rb->width >= 8 && rb->height >= 8;
if (!can_use_effects) {
//just copy
storage->get_effects()->merge_specular(p_dest_framebuffer, p_specular_buffer, p_use_additive ? RID() : rb->texture, RID());
return;
}
Environment *env = environment_owner.getornull(p_environment);
ERR_FAIL_COND(!env);
ERR_FAIL_COND(!env->ssr_enabled);
if (rb->ssr.depth_scaled.is_null()) {
RD::TextureFormat tf;
tf.format = RD::DATA_FORMAT_R32_SFLOAT;
tf.width = rb->width / 2;
tf.height = rb->height / 2;
tf.type = RD::TEXTURE_TYPE_2D;
tf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT;
rb->ssr.depth_scaled = RD::get_singleton()->texture_create(tf, RD::TextureView());
tf.format = RD::DATA_FORMAT_R8G8B8A8_UNORM;
rb->ssr.normal_scaled = RD::get_singleton()->texture_create(tf, RD::TextureView());
}
if (ssr_roughness_quality != RS::ENV_SSR_ROUGNESS_QUALITY_DISABLED && !rb->ssr.blur_radius[0].is_valid()) {
RD::TextureFormat tf;
tf.format = RD::DATA_FORMAT_R8_UNORM;
tf.width = rb->width / 2;
tf.height = rb->height / 2;
tf.type = RD::TEXTURE_TYPE_2D;
tf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT;
rb->ssr.blur_radius[0] = RD::get_singleton()->texture_create(tf, RD::TextureView());
rb->ssr.blur_radius[1] = RD::get_singleton()->texture_create(tf, RD::TextureView());
}
if (rb->blur[0].texture.is_null()) {
_allocate_blur_textures(rb);
_render_buffers_uniform_set_changed(p_render_buffers);
}
storage->get_effects()->screen_space_reflection(rb->texture, p_normal_buffer, ssr_roughness_quality, rb->ssr.blur_radius[0], rb->ssr.blur_radius[1], p_metallic, p_metallic_mask, rb->depth_texture, rb->ssr.depth_scaled, rb->ssr.normal_scaled, rb->blur[0].mipmaps[1].texture, rb->blur[1].mipmaps[0].texture, Size2i(rb->width / 2, rb->height / 2), env->ssr_max_steps, env->ssr_fade_in, env->ssr_fade_out, env->ssr_depth_tolerance, p_projection);
storage->get_effects()->merge_specular(p_dest_framebuffer, p_specular_buffer, p_use_additive ? RID() : rb->texture, rb->blur[0].mipmaps[1].texture);
}
void RasterizerSceneRD::_process_ssao(RID p_render_buffers, RID p_environment, RID p_normal_buffer, const CameraMatrix &p_projection) {
RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND(!rb);
Environment *env = environment_owner.getornull(p_environment);
ERR_FAIL_COND(!env);
RENDER_TIMESTAMP("Process SSAO");
if (rb->ssao.ao[0].is_valid() && rb->ssao.ao_full.is_valid() != ssao_half_size) {
RD::get_singleton()->free(rb->ssao.depth);
RD::get_singleton()->free(rb->ssao.ao[0]);
if (rb->ssao.ao[1].is_valid()) {
RD::get_singleton()->free(rb->ssao.ao[1]);
}
if (rb->ssao.ao_full.is_valid()) {
RD::get_singleton()->free(rb->ssao.ao_full);
}
rb->ssao.depth = RID();
rb->ssao.ao[0] = RID();
rb->ssao.ao[1] = RID();
rb->ssao.ao_full = RID();
rb->ssao.depth_slices.clear();
}
if (!rb->ssao.ao[0].is_valid()) {
//allocate depth slices
{
RD::TextureFormat tf;
tf.format = RD::DATA_FORMAT_R32_SFLOAT;
tf.width = rb->width / 2;
tf.height = rb->height / 2;
tf.mipmaps = Image::get_image_required_mipmaps(tf.width, tf.height, Image::FORMAT_RF) + 1;
tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
rb->ssao.depth = RD::get_singleton()->texture_create(tf, RD::TextureView());
for (uint32_t i = 0; i < tf.mipmaps; i++) {
RID slice = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), rb->ssao.depth, 0, i);
rb->ssao.depth_slices.push_back(slice);
}
}
{
RD::TextureFormat tf;
tf.format = RD::DATA_FORMAT_R8_UNORM;
tf.width = ssao_half_size ? rb->width / 2 : rb->width;
tf.height = ssao_half_size ? rb->height / 2 : rb->height;
tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
rb->ssao.ao[0] = RD::get_singleton()->texture_create(tf, RD::TextureView());
rb->ssao.ao[1] = RD::get_singleton()->texture_create(tf, RD::TextureView());
}
if (ssao_half_size) {
//upsample texture
RD::TextureFormat tf;
tf.format = RD::DATA_FORMAT_R8_UNORM;
tf.width = rb->width;
tf.height = rb->height;
tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
rb->ssao.ao_full = RD::get_singleton()->texture_create(tf, RD::TextureView());
}
_render_buffers_uniform_set_changed(p_render_buffers);
}
storage->get_effects()->generate_ssao(rb->depth_texture, p_normal_buffer, Size2i(rb->width, rb->height), rb->ssao.depth, rb->ssao.depth_slices, rb->ssao.ao[0], rb->ssao.ao_full.is_valid(), rb->ssao.ao[1], rb->ssao.ao_full, env->ssao_intensity, env->ssao_radius, env->ssao_bias, p_projection, ssao_quality, env->ssao_blur, env->ssao_blur_edge_sharpness);
}
void RasterizerSceneRD::_render_buffers_post_process_and_tonemap(RID p_render_buffers, RID p_environment, RID p_camera_effects, const CameraMatrix &p_projection) {
RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND(!rb);
Environment *env = environment_owner.getornull(p_environment);
//glow (if enabled)
CameraEffects *camfx = camera_effects_owner.getornull(p_camera_effects);
bool can_use_effects = rb->width >= 8 && rb->height >= 8;
if (can_use_effects && camfx && (camfx->dof_blur_near_enabled || camfx->dof_blur_far_enabled) && camfx->dof_blur_amount > 0.0) {
if (rb->blur[0].texture.is_null()) {
_allocate_blur_textures(rb);
_render_buffers_uniform_set_changed(p_render_buffers);
}
float bokeh_size = camfx->dof_blur_amount * 64.0;
storage->get_effects()->bokeh_dof(rb->texture, rb->depth_texture, Size2i(rb->width, rb->height), rb->blur[0].mipmaps[0].texture, rb->blur[1].mipmaps[0].texture, rb->blur[0].mipmaps[1].texture, camfx->dof_blur_far_enabled, camfx->dof_blur_far_distance, camfx->dof_blur_far_transition, camfx->dof_blur_near_enabled, camfx->dof_blur_near_distance, camfx->dof_blur_near_transition, bokeh_size, dof_blur_bokeh_shape, dof_blur_quality, dof_blur_use_jitter, p_projection.get_z_near(), p_projection.get_z_far(), p_projection.is_orthogonal());
}
if (can_use_effects && env && env->auto_exposure) {
if (rb->luminance.current.is_null()) {
_allocate_luminance_textures(rb);
_render_buffers_uniform_set_changed(p_render_buffers);
}
bool set_immediate = env->auto_exposure_version != rb->auto_exposure_version;
rb->auto_exposure_version = env->auto_exposure_version;
double step = env->auto_exp_speed * time_step;
storage->get_effects()->luminance_reduction(rb->texture, Size2i(rb->width, rb->height), rb->luminance.reduce, rb->luminance.current, env->min_luminance, env->max_luminance, step, set_immediate);
//swap final reduce with prev luminance
SWAP(rb->luminance.current, rb->luminance.reduce.write[rb->luminance.reduce.size() - 1]);
RenderingServerRaster::redraw_request(); //redraw all the time if auto exposure rendering is on
}
int max_glow_level = -1;
if (can_use_effects && env && env->glow_enabled) {
/* see that blur textures are allocated */
if (rb->blur[1].texture.is_null()) {
_allocate_blur_textures(rb);
_render_buffers_uniform_set_changed(p_render_buffers);
}
for (int i = 0; i < RS::MAX_GLOW_LEVELS; i++) {
if (env->glow_levels[i] > 0.0) {
if (i >= rb->blur[1].mipmaps.size()) {
max_glow_level = rb->blur[1].mipmaps.size() - 1;
} else {
max_glow_level = i;
}
}
}
for (int i = 0; i < (max_glow_level + 1); i++) {
int vp_w = rb->blur[1].mipmaps[i].width;
int vp_h = rb->blur[1].mipmaps[i].height;
if (i == 0) {
RID luminance_texture;
if (env->auto_exposure && rb->luminance.current.is_valid()) {
luminance_texture = rb->luminance.current;
}
storage->get_effects()->gaussian_glow(rb->texture, rb->blur[1].mipmaps[i].texture, Size2i(vp_w, vp_h), env->glow_strength, glow_high_quality, true, env->glow_hdr_luminance_cap, env->exposure, env->glow_bloom, env->glow_hdr_bleed_threshold, env->glow_hdr_bleed_scale, luminance_texture, env->auto_exp_scale);
} else {
storage->get_effects()->gaussian_glow(rb->blur[1].mipmaps[i - 1].texture, rb->blur[1].mipmaps[i].texture, Size2i(vp_w, vp_h), env->glow_strength, glow_high_quality);
}
}
}
{
//tonemap
RasterizerEffectsRD::TonemapSettings tonemap;
tonemap.color_correction_texture = storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE);
if (can_use_effects && env && env->auto_exposure && rb->luminance.current.is_valid()) {
tonemap.use_auto_exposure = true;
tonemap.exposure_texture = rb->luminance.current;
tonemap.auto_exposure_grey = env->auto_exp_scale;
} else {
tonemap.exposure_texture = storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_WHITE);
}
if (can_use_effects && env && env->glow_enabled) {
tonemap.use_glow = true;
tonemap.glow_mode = RasterizerEffectsRD::TonemapSettings::GlowMode(env->glow_blend_mode);
tonemap.glow_intensity = env->glow_blend_mode == RS::ENV_GLOW_BLEND_MODE_MIX ? env->glow_mix : env->glow_intensity;
for (int i = 0; i < RS::MAX_GLOW_LEVELS; i++) {
tonemap.glow_levels[i] = env->glow_levels[i];
}
tonemap.glow_texture_size.x = rb->blur[1].mipmaps[0].width;
tonemap.glow_texture_size.y = rb->blur[1].mipmaps[0].height;
tonemap.glow_use_bicubic_upscale = glow_bicubic_upscale;
tonemap.glow_texture = rb->blur[1].texture;
} else {
tonemap.glow_texture = storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_BLACK);
}
if (rb->screen_space_aa == RS::VIEWPORT_SCREEN_SPACE_AA_FXAA) {
tonemap.use_fxaa = true;
}
tonemap.use_debanding = rb->use_debanding;
tonemap.texture_size = Vector2i(rb->width, rb->height);
if (env) {
tonemap.tonemap_mode = env->tone_mapper;
tonemap.white = env->white;
tonemap.exposure = env->exposure;
}
storage->get_effects()->tonemapper(rb->texture, storage->render_target_get_rd_framebuffer(rb->render_target), tonemap);
}
storage->render_target_disable_clear_request(rb->render_target);
}
void RasterizerSceneRD::_render_buffers_debug_draw(RID p_render_buffers, RID p_shadow_atlas) {
RasterizerEffectsRD *effects = storage->get_effects();
RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND(!rb);
if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_SHADOW_ATLAS) {
if (p_shadow_atlas.is_valid()) {
RID shadow_atlas_texture = shadow_atlas_get_texture(p_shadow_atlas);
Size2 rtsize = storage->render_target_get_size(rb->render_target);
effects->copy_to_fb_rect(shadow_atlas_texture, storage->render_target_get_rd_framebuffer(rb->render_target), Rect2i(Vector2(), rtsize / 2), false, true);
}
}
if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_DIRECTIONAL_SHADOW_ATLAS) {
if (directional_shadow_get_texture().is_valid()) {
RID shadow_atlas_texture = directional_shadow_get_texture();
Size2 rtsize = storage->render_target_get_size(rb->render_target);
effects->copy_to_fb_rect(shadow_atlas_texture, storage->render_target_get_rd_framebuffer(rb->render_target), Rect2i(Vector2(), rtsize / 2), false, true);
}
}
if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_DECAL_ATLAS) {
RID decal_atlas = storage->decal_atlas_get_texture();
if (decal_atlas.is_valid()) {
Size2 rtsize = storage->render_target_get_size(rb->render_target);
effects->copy_to_fb_rect(decal_atlas, storage->render_target_get_rd_framebuffer(rb->render_target), Rect2i(Vector2(), rtsize / 2), false, false, true);
}
}
if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_SCENE_LUMINANCE) {
if (rb->luminance.current.is_valid()) {
Size2 rtsize = storage->render_target_get_size(rb->render_target);
effects->copy_to_fb_rect(rb->luminance.current, storage->render_target_get_rd_framebuffer(rb->render_target), Rect2(Vector2(), rtsize / 8), false, true);
}
}
if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_SSAO && rb->ssao.ao[0].is_valid()) {
Size2 rtsize = storage->render_target_get_size(rb->render_target);
RID ao_buf = rb->ssao.ao_full.is_valid() ? rb->ssao.ao_full : rb->ssao.ao[0];
effects->copy_to_fb_rect(ao_buf, storage->render_target_get_rd_framebuffer(rb->render_target), Rect2(Vector2(), rtsize), false, true);
}
if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_NORMAL_BUFFER && _render_buffers_get_normal_texture(p_render_buffers).is_valid()) {
Size2 rtsize = storage->render_target_get_size(rb->render_target);
effects->copy_to_fb_rect(_render_buffers_get_normal_texture(p_render_buffers), storage->render_target_get_rd_framebuffer(rb->render_target), Rect2(Vector2(), rtsize), false, false);
}
if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_GI_BUFFER && _render_buffers_get_ambient_texture(p_render_buffers).is_valid()) {
Size2 rtsize = storage->render_target_get_size(rb->render_target);
RID ambient_texture = _render_buffers_get_ambient_texture(p_render_buffers);
RID reflection_texture = _render_buffers_get_reflection_texture(p_render_buffers);
effects->copy_to_fb_rect(ambient_texture, storage->render_target_get_rd_framebuffer(rb->render_target), Rect2(Vector2(), rtsize), false, false, false, true, reflection_texture);
}
}
void RasterizerSceneRD::_sdfgi_debug_draw(RID p_render_buffers, const CameraMatrix &p_projection, const Transform &p_transform) {
RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND(!rb);
if (!rb->sdfgi) {
return; //eh
}
if (!rb->sdfgi->debug_uniform_set.is_valid() || !RD::get_singleton()->uniform_set_is_valid(rb->sdfgi->debug_uniform_set)) {
Vector<RD::Uniform> uniforms;
{
RD::Uniform u;
u.binding = 1;
u.type = RD::UNIFORM_TYPE_TEXTURE;
for (uint32_t i = 0; i < SDFGI::MAX_CASCADES; i++) {
if (i < rb->sdfgi->cascades.size()) {
u.ids.push_back(rb->sdfgi->cascades[i].sdf_tex);
} else {
u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
}
}
uniforms.push_back(u);
}
{
RD::Uniform u;
u.binding = 2;
u.type = RD::UNIFORM_TYPE_TEXTURE;
for (uint32_t i = 0; i < SDFGI::MAX_CASCADES; i++) {
if (i < rb->sdfgi->cascades.size()) {
u.ids.push_back(rb->sdfgi->cascades[i].light_tex);
} else {
u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
}
}
uniforms.push_back(u);
}
{
RD::Uniform u;
u.binding = 3;
u.type = RD::UNIFORM_TYPE_TEXTURE;
for (uint32_t i = 0; i < SDFGI::MAX_CASCADES; i++) {
if (i < rb->sdfgi->cascades.size()) {
u.ids.push_back(rb->sdfgi->cascades[i].light_aniso_0_tex);
} else {
u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
}
}
uniforms.push_back(u);
}
{
RD::Uniform u;
u.binding = 4;
u.type = RD::UNIFORM_TYPE_TEXTURE;
for (uint32_t i = 0; i < SDFGI::MAX_CASCADES; i++) {
if (i < rb->sdfgi->cascades.size()) {
u.ids.push_back(rb->sdfgi->cascades[i].light_aniso_1_tex);
} else {
u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
}
}
uniforms.push_back(u);
}
{
RD::Uniform u;
u.binding = 5;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.ids.push_back(rb->sdfgi->occlusion_texture);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.binding = 8;
u.type = RD::UNIFORM_TYPE_SAMPLER;
u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
uniforms.push_back(u);
}
{
RD::Uniform u;
u.binding = 9;
u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
u.ids.push_back(rb->sdfgi->cascades_ubo);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.binding = 10;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.ids.push_back(rb->texture);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.binding = 11;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.ids.push_back(rb->sdfgi->lightprobe_texture);
uniforms.push_back(u);
}
rb->sdfgi->debug_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.debug_shader_version, 0);
}
RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.debug_pipeline);
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->debug_uniform_set, 0);
SDGIShader::DebugPushConstant push_constant;
push_constant.grid_size[0] = rb->sdfgi->cascade_size;
push_constant.grid_size[1] = rb->sdfgi->cascade_size;
push_constant.grid_size[2] = rb->sdfgi->cascade_size;
push_constant.max_cascades = rb->sdfgi->cascades.size();
push_constant.screen_size[0] = rb->width;
push_constant.screen_size[1] = rb->height;
push_constant.probe_axis_size = rb->sdfgi->probe_axis_count;
push_constant.use_occlusion = rb->sdfgi->uses_occlusion;
push_constant.y_mult = rb->sdfgi->y_mult;
Vector2 vp_half = p_projection.get_viewport_half_extents();
push_constant.cam_extent[0] = vp_half.x;
push_constant.cam_extent[1] = vp_half.y;
push_constant.cam_extent[2] = -p_projection.get_z_near();
push_constant.cam_transform[0] = p_transform.basis.elements[0][0];
push_constant.cam_transform[1] = p_transform.basis.elements[1][0];
push_constant.cam_transform[2] = p_transform.basis.elements[2][0];
push_constant.cam_transform[3] = 0;
push_constant.cam_transform[4] = p_transform.basis.elements[0][1];
push_constant.cam_transform[5] = p_transform.basis.elements[1][1];
push_constant.cam_transform[6] = p_transform.basis.elements[2][1];
push_constant.cam_transform[7] = 0;
push_constant.cam_transform[8] = p_transform.basis.elements[0][2];
push_constant.cam_transform[9] = p_transform.basis.elements[1][2];
push_constant.cam_transform[10] = p_transform.basis.elements[2][2];
push_constant.cam_transform[11] = 0;
push_constant.cam_transform[12] = p_transform.origin.x;
push_constant.cam_transform[13] = p_transform.origin.y;
push_constant.cam_transform[14] = p_transform.origin.z;
push_constant.cam_transform[15] = 1;
RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::DebugPushConstant));
RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->width, rb->height, 1, 8, 8, 1);
RD::get_singleton()->compute_list_end();
Size2 rtsize = storage->render_target_get_size(rb->render_target);
storage->get_effects()->copy_to_fb_rect(rb->texture, storage->render_target_get_rd_framebuffer(rb->render_target), Rect2(Vector2(), rtsize), true);
}
RID RasterizerSceneRD::render_buffers_get_back_buffer_texture(RID p_render_buffers) {
RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND_V(!rb, RID());
if (!rb->blur[0].texture.is_valid()) {
return RID(); //not valid at the moment
}
return rb->blur[0].texture;
}
RID RasterizerSceneRD::render_buffers_get_ao_texture(RID p_render_buffers) {
RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND_V(!rb, RID());
return rb->ssao.ao_full.is_valid() ? rb->ssao.ao_full : rb->ssao.ao[0];
}
RID RasterizerSceneRD::render_buffers_get_gi_probe_buffer(RID p_render_buffers) {
RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND_V(!rb, RID());
if (rb->giprobe_buffer.is_null()) {
rb->giprobe_buffer = RD::get_singleton()->uniform_buffer_create(sizeof(GI::GIProbeData) * RenderBuffers::MAX_GIPROBES);
}
return rb->giprobe_buffer;
}
RID RasterizerSceneRD::render_buffers_get_default_gi_probe_buffer() {
return default_giprobe_buffer;
}
uint32_t RasterizerSceneRD::render_buffers_get_sdfgi_cascade_count(RID p_render_buffers) const {
const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND_V(!rb, 0);
ERR_FAIL_COND_V(!rb->sdfgi, 0);
return rb->sdfgi->cascades.size();
}
bool RasterizerSceneRD::render_buffers_is_sdfgi_enabled(RID p_render_buffers) const {
const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND_V(!rb, false);
return rb->sdfgi != nullptr;
}
RID RasterizerSceneRD::render_buffers_get_sdfgi_irradiance_probes(RID p_render_buffers) const {
const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND_V(!rb, RID());
ERR_FAIL_COND_V(!rb->sdfgi, RID());
return rb->sdfgi->lightprobe_texture;
}
Vector3 RasterizerSceneRD::render_buffers_get_sdfgi_cascade_offset(RID p_render_buffers, uint32_t p_cascade) const {
const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND_V(!rb, Vector3());
ERR_FAIL_COND_V(!rb->sdfgi, Vector3());
ERR_FAIL_UNSIGNED_INDEX_V(p_cascade, rb->sdfgi->cascades.size(), Vector3());
return Vector3((Vector3i(1, 1, 1) * -int32_t(rb->sdfgi->cascade_size >> 1) + rb->sdfgi->cascades[p_cascade].position)) * rb->sdfgi->cascades[p_cascade].cell_size;
}
Vector3i RasterizerSceneRD::render_buffers_get_sdfgi_cascade_probe_offset(RID p_render_buffers, uint32_t p_cascade) const {
const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND_V(!rb, Vector3i());
ERR_FAIL_COND_V(!rb->sdfgi, Vector3i());
ERR_FAIL_UNSIGNED_INDEX_V(p_cascade, rb->sdfgi->cascades.size(), Vector3i());
int32_t probe_divisor = rb->sdfgi->cascade_size / SDFGI::PROBE_DIVISOR;
return rb->sdfgi->cascades[p_cascade].position / probe_divisor;
}
float RasterizerSceneRD::render_buffers_get_sdfgi_normal_bias(RID p_render_buffers) const {
const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND_V(!rb, 0);
ERR_FAIL_COND_V(!rb->sdfgi, 0);
return rb->sdfgi->normal_bias;
}
float RasterizerSceneRD::render_buffers_get_sdfgi_cascade_probe_size(RID p_render_buffers, uint32_t p_cascade) const {
const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND_V(!rb, 0);
ERR_FAIL_COND_V(!rb->sdfgi, 0);
ERR_FAIL_UNSIGNED_INDEX_V(p_cascade, rb->sdfgi->cascades.size(), 0);
return float(rb->sdfgi->cascade_size) * rb->sdfgi->cascades[p_cascade].cell_size / float(rb->sdfgi->probe_axis_count - 1);
}
uint32_t RasterizerSceneRD::render_buffers_get_sdfgi_cascade_probe_count(RID p_render_buffers) const {
const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND_V(!rb, 0);
ERR_FAIL_COND_V(!rb->sdfgi, 0);
return rb->sdfgi->probe_axis_count;
}
uint32_t RasterizerSceneRD::render_buffers_get_sdfgi_cascade_size(RID p_render_buffers) const {
const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND_V(!rb, 0);
ERR_FAIL_COND_V(!rb->sdfgi, 0);
return rb->sdfgi->cascade_size;
}
bool RasterizerSceneRD::render_buffers_is_sdfgi_using_occlusion(RID p_render_buffers) const {
const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND_V(!rb, false);
ERR_FAIL_COND_V(!rb->sdfgi, false);
return rb->sdfgi->uses_occlusion;
}
float RasterizerSceneRD::render_buffers_get_sdfgi_energy(RID p_render_buffers) const {
const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND_V(!rb, 0);
ERR_FAIL_COND_V(!rb->sdfgi, false);
return rb->sdfgi->energy;
}
RID RasterizerSceneRD::render_buffers_get_sdfgi_occlusion_texture(RID p_render_buffers) const {
const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND_V(!rb, RID());
ERR_FAIL_COND_V(!rb->sdfgi, RID());
return rb->sdfgi->occlusion_texture;
}
bool RasterizerSceneRD::render_buffers_has_volumetric_fog(RID p_render_buffers) const {
const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND_V(!rb, false);
return rb->volumetric_fog != nullptr;
}
RID RasterizerSceneRD::render_buffers_get_volumetric_fog_texture(RID p_render_buffers) {
const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND_V(!rb || !rb->volumetric_fog, RID());
return rb->volumetric_fog->fog_map;
}
RID RasterizerSceneRD::render_buffers_get_volumetric_fog_sky_uniform_set(RID p_render_buffers) {
const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND_V(!rb, RID());
if (!rb->volumetric_fog) {
return RID();
}
return rb->volumetric_fog->sky_uniform_set;
}
float RasterizerSceneRD::render_buffers_get_volumetric_fog_end(RID p_render_buffers) {
const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND_V(!rb || !rb->volumetric_fog, 0);
return rb->volumetric_fog->length;
}
float RasterizerSceneRD::render_buffers_get_volumetric_fog_detail_spread(RID p_render_buffers) {
const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND_V(!rb || !rb->volumetric_fog, 0);
return rb->volumetric_fog->spread;
}
void RasterizerSceneRD::render_buffers_configure(RID p_render_buffers, RID p_render_target, int p_width, int p_height, RS::ViewportMSAA p_msaa, RenderingServer::ViewportScreenSpaceAA p_screen_space_aa, bool p_use_debanding) {
RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
rb->width = p_width;
rb->height = p_height;
rb->render_target = p_render_target;
rb->msaa = p_msaa;
rb->screen_space_aa = p_screen_space_aa;
rb->use_debanding = p_use_debanding;
_free_render_buffer_data(rb);
{
RD::TextureFormat tf;
tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
tf.width = rb->width;
tf.height = rb->height;
tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
if (rb->msaa != RS::VIEWPORT_MSAA_DISABLED) {
tf.usage_bits |= RD::TEXTURE_USAGE_CAN_COPY_TO_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
} else {
tf.usage_bits |= RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
}
rb->texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
}
{
RD::TextureFormat tf;
if (rb->msaa == RS::VIEWPORT_MSAA_DISABLED) {
tf.format = RD::get_singleton()->texture_is_format_supported_for_usage(RD::DATA_FORMAT_D24_UNORM_S8_UINT, RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) ? RD::DATA_FORMAT_D24_UNORM_S8_UINT : RD::DATA_FORMAT_D32_SFLOAT_S8_UINT;
} else {
tf.format = RD::DATA_FORMAT_R32_SFLOAT;
}
tf.width = p_width;
tf.height = p_height;
tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT;
if (rb->msaa != RS::VIEWPORT_MSAA_DISABLED) {
tf.usage_bits |= RD::TEXTURE_USAGE_CAN_COPY_TO_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
} else {
tf.usage_bits |= RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
}
rb->depth_texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
}
rb->data->configure(rb->texture, rb->depth_texture, p_width, p_height, p_msaa);
_render_buffers_uniform_set_changed(p_render_buffers);
}
void RasterizerSceneRD::sub_surface_scattering_set_quality(RS::SubSurfaceScatteringQuality p_quality) {
sss_quality = p_quality;
}
RS::SubSurfaceScatteringQuality RasterizerSceneRD::sub_surface_scattering_get_quality() const {
return sss_quality;
}
void RasterizerSceneRD::sub_surface_scattering_set_scale(float p_scale, float p_depth_scale) {
sss_scale = p_scale;
sss_depth_scale = p_depth_scale;
}
void RasterizerSceneRD::shadows_quality_set(RS::ShadowQuality p_quality) {
ERR_FAIL_INDEX_MSG(p_quality, RS::SHADOW_QUALITY_MAX, "Shadow quality too high, please see RenderingServer's ShadowQuality enum");
if (shadows_quality != p_quality) {
shadows_quality = p_quality;
switch (shadows_quality) {
case RS::SHADOW_QUALITY_HARD: {
penumbra_shadow_samples = 4;
soft_shadow_samples = 1;
shadows_quality_radius = 1.0;
} break;
case RS::SHADOW_QUALITY_SOFT_LOW: {
penumbra_shadow_samples = 8;
soft_shadow_samples = 4;
shadows_quality_radius = 2.0;
} break;
case RS::SHADOW_QUALITY_SOFT_MEDIUM: {
penumbra_shadow_samples = 12;
soft_shadow_samples = 8;
shadows_quality_radius = 2.0;
} break;
case RS::SHADOW_QUALITY_SOFT_HIGH: {
penumbra_shadow_samples = 24;
soft_shadow_samples = 16;
shadows_quality_radius = 3.0;
} break;
case RS::SHADOW_QUALITY_SOFT_ULTRA: {
penumbra_shadow_samples = 32;
soft_shadow_samples = 32;
shadows_quality_radius = 4.0;
} break;
case RS::SHADOW_QUALITY_MAX:
break;
}
get_vogel_disk(penumbra_shadow_kernel, penumbra_shadow_samples);
get_vogel_disk(soft_shadow_kernel, soft_shadow_samples);
}
}
void RasterizerSceneRD::directional_shadow_quality_set(RS::ShadowQuality p_quality) {
ERR_FAIL_INDEX_MSG(p_quality, RS::SHADOW_QUALITY_MAX, "Shadow quality too high, please see RenderingServer's ShadowQuality enum");
if (directional_shadow_quality != p_quality) {
directional_shadow_quality = p_quality;
switch (directional_shadow_quality) {
case RS::SHADOW_QUALITY_HARD: {
directional_penumbra_shadow_samples = 4;
directional_soft_shadow_samples = 1;
directional_shadow_quality_radius = 1.0;
} break;
case RS::SHADOW_QUALITY_SOFT_LOW: {
directional_penumbra_shadow_samples = 8;
directional_soft_shadow_samples = 4;
directional_shadow_quality_radius = 2.0;
} break;
case RS::SHADOW_QUALITY_SOFT_MEDIUM: {
directional_penumbra_shadow_samples = 12;
directional_soft_shadow_samples = 8;
directional_shadow_quality_radius = 2.0;
} break;
case RS::SHADOW_QUALITY_SOFT_HIGH: {
directional_penumbra_shadow_samples = 24;
directional_soft_shadow_samples = 16;
directional_shadow_quality_radius = 3.0;
} break;
case RS::SHADOW_QUALITY_SOFT_ULTRA: {
directional_penumbra_shadow_samples = 32;
directional_soft_shadow_samples = 32;
directional_shadow_quality_radius = 4.0;
} break;
case RS::SHADOW_QUALITY_MAX:
break;
}
get_vogel_disk(directional_penumbra_shadow_kernel, directional_penumbra_shadow_samples);
get_vogel_disk(directional_soft_shadow_kernel, directional_soft_shadow_samples);
}
}
int RasterizerSceneRD::get_roughness_layers() const {
return roughness_layers;
}
bool RasterizerSceneRD::is_using_radiance_cubemap_array() const {
return sky_use_cubemap_array;
}
RasterizerSceneRD::RenderBufferData *RasterizerSceneRD::render_buffers_get_data(RID p_render_buffers) {
RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND_V(!rb, nullptr);
return rb->data;
}
void RasterizerSceneRD::_setup_reflections(RID *p_reflection_probe_cull_result, int p_reflection_probe_cull_count, const Transform &p_camera_inverse_transform, RID p_environment) {
for (int i = 0; i < p_reflection_probe_cull_count; i++) {
RID rpi = p_reflection_probe_cull_result[i];
if (i >= (int)cluster.max_reflections) {
reflection_probe_instance_set_render_index(rpi, 0); //invalid, but something needs to be set
continue;
}
reflection_probe_instance_set_render_index(rpi, i);
RID base_probe = reflection_probe_instance_get_probe(rpi);
Cluster::ReflectionData &reflection_ubo = cluster.reflections[i];
Vector3 extents = storage->reflection_probe_get_extents(base_probe);
reflection_ubo.box_extents[0] = extents.x;
reflection_ubo.box_extents[1] = extents.y;
reflection_ubo.box_extents[2] = extents.z;
reflection_ubo.index = reflection_probe_instance_get_atlas_index(rpi);
Vector3 origin_offset = storage->reflection_probe_get_origin_offset(base_probe);
reflection_ubo.box_offset[0] = origin_offset.x;
reflection_ubo.box_offset[1] = origin_offset.y;
reflection_ubo.box_offset[2] = origin_offset.z;
reflection_ubo.mask = storage->reflection_probe_get_cull_mask(base_probe);
float intensity = storage->reflection_probe_get_intensity(base_probe);
bool interior = storage->reflection_probe_is_interior(base_probe);
bool box_projection = storage->reflection_probe_is_box_projection(base_probe);
reflection_ubo.params[0] = intensity;
reflection_ubo.params[1] = 0;
reflection_ubo.params[2] = interior ? 1.0 : 0.0;
reflection_ubo.params[3] = box_projection ? 1.0 : 0.0;
Color ambient_linear = storage->reflection_probe_get_ambient_color(base_probe).to_linear();
float interior_ambient_energy = storage->reflection_probe_get_ambient_color_energy(base_probe);
uint32_t ambient_mode = storage->reflection_probe_get_ambient_mode(base_probe);
reflection_ubo.ambient[0] = ambient_linear.r * interior_ambient_energy;
reflection_ubo.ambient[1] = ambient_linear.g * interior_ambient_energy;
reflection_ubo.ambient[2] = ambient_linear.b * interior_ambient_energy;
reflection_ubo.ambient_mode = ambient_mode;
Transform transform = reflection_probe_instance_get_transform(rpi);
Transform proj = (p_camera_inverse_transform * transform).inverse();
RasterizerStorageRD::store_transform(proj, reflection_ubo.local_matrix);
cluster.builder.add_reflection_probe(transform, extents);
reflection_probe_instance_set_render_pass(rpi, RSG::rasterizer->get_frame_number());
}
if (p_reflection_probe_cull_count) {
RD::get_singleton()->buffer_update(cluster.reflection_buffer, 0, MIN(cluster.max_reflections, (unsigned int)p_reflection_probe_cull_count) * sizeof(ReflectionData), cluster.reflections, true);
}
}
void RasterizerSceneRD::_setup_lights(RID *p_light_cull_result, int p_light_cull_count, const Transform &p_camera_inverse_transform, RID p_shadow_atlas, bool p_using_shadows, uint32_t &r_directional_light_count, uint32_t &r_positional_light_count) {
uint32_t light_count = 0;
r_directional_light_count = 0;
r_positional_light_count = 0;
sky_scene_state.ubo.directional_light_count = 0;
for (int i = 0; i < p_light_cull_count; i++) {
RID li = p_light_cull_result[i];
RID base = light_instance_get_base_light(li);
ERR_CONTINUE(base.is_null());
RS::LightType type = storage->light_get_type(base);
switch (type) {
case RS::LIGHT_DIRECTIONAL: {
if (r_directional_light_count >= cluster.max_directional_lights) {
continue;
}
Cluster::DirectionalLightData &light_data = cluster.directional_lights[r_directional_light_count];
Transform light_transform = light_instance_get_base_transform(li);
Vector3 direction = p_camera_inverse_transform.basis.xform(light_transform.basis.xform(Vector3(0, 0, 1))).normalized();
light_data.direction[0] = direction.x;
light_data.direction[1] = direction.y;
light_data.direction[2] = direction.z;
float sign = storage->light_is_negative(base) ? -1 : 1;
light_data.energy = sign * storage->light_get_param(base, RS::LIGHT_PARAM_ENERGY) * Math_PI;
Color linear_col = storage->light_get_color(base).to_linear();
light_data.color[0] = linear_col.r;
light_data.color[1] = linear_col.g;
light_data.color[2] = linear_col.b;
light_data.specular = storage->light_get_param(base, RS::LIGHT_PARAM_SPECULAR);
light_data.mask = storage->light_get_cull_mask(base);
float size = storage->light_get_param(base, RS::LIGHT_PARAM_SIZE);
light_data.size = 1.0 - Math::cos(Math::deg2rad(size)); //angle to cosine offset
Color shadow_col = storage->light_get_shadow_color(base).to_linear();
if (get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_PSSM_SPLITS) {
light_data.shadow_color1[0] = 1.0;
light_data.shadow_color1[1] = 0.0;
light_data.shadow_color1[2] = 0.0;
light_data.shadow_color1[3] = 1.0;
light_data.shadow_color2[0] = 0.0;
light_data.shadow_color2[1] = 1.0;
light_data.shadow_color2[2] = 0.0;
light_data.shadow_color2[3] = 1.0;
light_data.shadow_color3[0] = 0.0;
light_data.shadow_color3[1] = 0.0;
light_data.shadow_color3[2] = 1.0;
light_data.shadow_color3[3] = 1.0;
light_data.shadow_color4[0] = 1.0;
light_data.shadow_color4[1] = 1.0;
light_data.shadow_color4[2] = 0.0;
light_data.shadow_color4[3] = 1.0;
} else {
light_data.shadow_color1[0] = shadow_col.r;
light_data.shadow_color1[1] = shadow_col.g;
light_data.shadow_color1[2] = shadow_col.b;
light_data.shadow_color1[3] = 1.0;
light_data.shadow_color2[0] = shadow_col.r;
light_data.shadow_color2[1] = shadow_col.g;
light_data.shadow_color2[2] = shadow_col.b;
light_data.shadow_color2[3] = 1.0;
light_data.shadow_color3[0] = shadow_col.r;
light_data.shadow_color3[1] = shadow_col.g;
light_data.shadow_color3[2] = shadow_col.b;
light_data.shadow_color3[3] = 1.0;
light_data.shadow_color4[0] = shadow_col.r;
light_data.shadow_color4[1] = shadow_col.g;
light_data.shadow_color4[2] = shadow_col.b;
light_data.shadow_color4[3] = 1.0;
}
light_data.shadow_enabled = p_using_shadows && storage->light_has_shadow(base);
float angular_diameter = storage->light_get_param(base, RS::LIGHT_PARAM_SIZE);
if (angular_diameter > 0.0) {
// I know tan(0) is 0, but let's not risk it with numerical precision.
// technically this will keep expanding until reaching the sun, but all we care
// is expand until we reach the radius of the near plane (there can't be more occluders than that)
angular_diameter = Math::tan(Math::deg2rad(angular_diameter));
} else {
angular_diameter = 0.0;
}
if (light_data.shadow_enabled) {
RS::LightDirectionalShadowMode smode = storage->light_directional_get_shadow_mode(base);
int limit = smode == RS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL ? 0 : (smode == RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS ? 1 : 3);
light_data.blend_splits = storage->light_directional_get_blend_splits(base);
for (int j = 0; j < 4; j++) {
Rect2 atlas_rect = light_instance_get_directional_shadow_atlas_rect(li, j);
CameraMatrix matrix = light_instance_get_shadow_camera(li, j);
float split = light_instance_get_directional_shadow_split(li, MIN(limit, j));
CameraMatrix bias;
bias.set_light_bias();
CameraMatrix rectm;
rectm.set_light_atlas_rect(atlas_rect);
Transform modelview = (p_camera_inverse_transform * light_instance_get_shadow_transform(li, j)).inverse();
CameraMatrix shadow_mtx = rectm * bias * matrix * modelview;
light_data.shadow_split_offsets[j] = split;
float bias_scale = light_instance_get_shadow_bias_scale(li, j);
light_data.shadow_bias[j] = storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_BIAS) * bias_scale;
light_data.shadow_normal_bias[j] = storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_NORMAL_BIAS) * light_instance_get_directional_shadow_texel_size(li, j);
light_data.shadow_transmittance_bias[j] = storage->light_get_transmittance_bias(base) * bias_scale;
light_data.shadow_z_range[j] = light_instance_get_shadow_range(li, j);
light_data.shadow_range_begin[j] = light_instance_get_shadow_range_begin(li, j);
RasterizerStorageRD::store_camera(shadow_mtx, light_data.shadow_matrices[j]);
Vector2 uv_scale = light_instance_get_shadow_uv_scale(li, j);
uv_scale *= atlas_rect.size; //adapt to atlas size
switch (j) {
case 0: {
light_data.uv_scale1[0] = uv_scale.x;
light_data.uv_scale1[1] = uv_scale.y;
} break;
case 1: {
light_data.uv_scale2[0] = uv_scale.x;
light_data.uv_scale2[1] = uv_scale.y;
} break;
case 2: {
light_data.uv_scale3[0] = uv_scale.x;
light_data.uv_scale3[1] = uv_scale.y;
} break;
case 3: {
light_data.uv_scale4[0] = uv_scale.x;
light_data.uv_scale4[1] = uv_scale.y;
} break;
}
}
float fade_start = storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_FADE_START);
light_data.fade_from = -light_data.shadow_split_offsets[3] * MIN(fade_start, 0.999); //using 1.0 would break smoothstep
light_data.fade_to = -light_data.shadow_split_offsets[3];
light_data.shadow_volumetric_fog_fade = 1.0 / storage->light_get_shadow_volumetric_fog_fade(base);
light_data.soft_shadow_scale = storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_BLUR);
light_data.softshadow_angle = angular_diameter;
if (angular_diameter <= 0.0) {
light_data.soft_shadow_scale *= directional_shadow_quality_radius_get(); // Only use quality radius for PCF
}
}
// Copy to SkyDirectionalLightData
if (r_directional_light_count < sky_scene_state.max_directional_lights) {
SkyDirectionalLightData &sky_light_data = sky_scene_state.directional_lights[r_directional_light_count];
Vector3 world_direction = light_transform.basis.xform(Vector3(0, 0, 1)).normalized();
sky_light_data.direction[0] = world_direction.x;
sky_light_data.direction[1] = world_direction.y;
sky_light_data.direction[2] = -world_direction.z;
sky_light_data.energy = light_data.energy / Math_PI;
sky_light_data.color[0] = light_data.color[0];
sky_light_data.color[1] = light_data.color[1];
sky_light_data.color[2] = light_data.color[2];
sky_light_data.enabled = true;
sky_light_data.size = angular_diameter;
sky_scene_state.ubo.directional_light_count++;
}
r_directional_light_count++;
} break;
case RS::LIGHT_SPOT:
case RS::LIGHT_OMNI: {
if (light_count >= cluster.max_lights) {
continue;
}
Transform light_transform = light_instance_get_base_transform(li);
Cluster::LightData &light_data = cluster.lights[light_count];
cluster.lights_instances[light_count] = li;
float sign = storage->light_is_negative(base) ? -1 : 1;
Color linear_col = storage->light_get_color(base).to_linear();
light_data.attenuation_energy[0] = Math::make_half_float(storage->light_get_param(base, RS::LIGHT_PARAM_ATTENUATION));
light_data.attenuation_energy[1] = Math::make_half_float(sign * storage->light_get_param(base, RS::LIGHT_PARAM_ENERGY) * Math_PI);
light_data.color_specular[0] = MIN(uint32_t(linear_col.r * 255), 255);
light_data.color_specular[1] = MIN(uint32_t(linear_col.g * 255), 255);
light_data.color_specular[2] = MIN(uint32_t(linear_col.b * 255), 255);
light_data.color_specular[3] = MIN(uint32_t(storage->light_get_param(base, RS::LIGHT_PARAM_SPECULAR) * 255), 255);
float radius = MAX(0.001, storage->light_get_param(base, RS::LIGHT_PARAM_RANGE));
light_data.inv_radius = 1.0 / radius;
Vector3 pos = p_camera_inverse_transform.xform(light_transform.origin);
light_data.position[0] = pos.x;
light_data.position[1] = pos.y;
light_data.position[2] = pos.z;
Vector3 direction = p_camera_inverse_transform.basis.xform(light_transform.basis.xform(Vector3(0, 0, -1))).normalized();
light_data.direction[0] = direction.x;
light_data.direction[1] = direction.y;
light_data.direction[2] = direction.z;
float size = storage->light_get_param(base, RS::LIGHT_PARAM_SIZE);
light_data.size = size;
light_data.cone_attenuation_angle[0] = Math::make_half_float(storage->light_get_param(base, RS::LIGHT_PARAM_SPOT_ATTENUATION));
float spot_angle = storage->light_get_param(base, RS::LIGHT_PARAM_SPOT_ANGLE);
light_data.cone_attenuation_angle[1] = Math::make_half_float(Math::cos(Math::deg2rad(spot_angle)));
light_data.mask = storage->light_get_cull_mask(base);
light_data.atlas_rect[0] = 0;
light_data.atlas_rect[1] = 0;
light_data.atlas_rect[2] = 0;
light_data.atlas_rect[3] = 0;
RID projector = storage->light_get_projector(base);
if (projector.is_valid()) {
Rect2 rect = storage->decal_atlas_get_texture_rect(projector);
if (type == RS::LIGHT_SPOT) {
light_data.projector_rect[0] = rect.position.x;
light_data.projector_rect[1] = rect.position.y + rect.size.height; //flip because shadow is flipped
light_data.projector_rect[2] = rect.size.width;
light_data.projector_rect[3] = -rect.size.height;
} else {
light_data.projector_rect[0] = rect.position.x;
light_data.projector_rect[1] = rect.position.y;
light_data.projector_rect[2] = rect.size.width;
light_data.projector_rect[3] = rect.size.height * 0.5; //used by dp, so needs to be half
}
} else {
light_data.projector_rect[0] = 0;
light_data.projector_rect[1] = 0;
light_data.projector_rect[2] = 0;
light_data.projector_rect[3] = 0;
}
if (p_using_shadows && p_shadow_atlas.is_valid() && shadow_atlas_owns_light_instance(p_shadow_atlas, li)) {
// fill in the shadow information
Color shadow_color = storage->light_get_shadow_color(base);
light_data.shadow_color_enabled[0] = MIN(uint32_t(shadow_color.r * 255), 255);
light_data.shadow_color_enabled[1] = MIN(uint32_t(shadow_color.g * 255), 255);
light_data.shadow_color_enabled[2] = MIN(uint32_t(shadow_color.b * 255), 255);
light_data.shadow_color_enabled[3] = 255;
if (type == RS::LIGHT_SPOT) {
light_data.shadow_bias = (storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_BIAS) * radius / 10.0);
float shadow_texel_size = Math::tan(Math::deg2rad(spot_angle)) * radius * 2.0;
shadow_texel_size *= light_instance_get_shadow_texel_size(li, p_shadow_atlas);
light_data.shadow_normal_bias = storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_NORMAL_BIAS) * shadow_texel_size;
} else { //omni
light_data.shadow_bias = storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_BIAS) * radius / 10.0;
float shadow_texel_size = light_instance_get_shadow_texel_size(li, p_shadow_atlas);
light_data.shadow_normal_bias = storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_NORMAL_BIAS) * shadow_texel_size * 2.0; // applied in -1 .. 1 space
}
light_data.transmittance_bias = storage->light_get_transmittance_bias(base);
Rect2 rect = light_instance_get_shadow_atlas_rect(li, p_shadow_atlas);
light_data.atlas_rect[0] = rect.position.x;
light_data.atlas_rect[1] = rect.position.y;
light_data.atlas_rect[2] = rect.size.width;
light_data.atlas_rect[3] = rect.size.height;
light_data.soft_shadow_scale = storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_BLUR);
light_data.shadow_volumetric_fog_fade = 1.0 / storage->light_get_shadow_volumetric_fog_fade(base);
if (type == RS::LIGHT_OMNI) {
light_data.atlas_rect[3] *= 0.5; //one paraboloid on top of another
Transform proj = (p_camera_inverse_transform * light_transform).inverse();
RasterizerStorageRD::store_transform(proj, light_data.shadow_matrix);
if (size > 0.0) {
light_data.soft_shadow_size = size;
} else {
light_data.soft_shadow_size = 0.0;
light_data.soft_shadow_scale *= shadows_quality_radius_get(); // Only use quality radius for PCF
}
} else if (type == RS::LIGHT_SPOT) {
Transform modelview = (p_camera_inverse_transform * light_transform).inverse();
CameraMatrix bias;
bias.set_light_bias();
CameraMatrix shadow_mtx = bias * light_instance_get_shadow_camera(li, 0) * modelview;
RasterizerStorageRD::store_camera(shadow_mtx, light_data.shadow_matrix);
if (size > 0.0) {
CameraMatrix cm = light_instance_get_shadow_camera(li, 0);
float half_np = cm.get_z_near() * Math::tan(Math::deg2rad(spot_angle));
light_data.soft_shadow_size = (size * 0.5 / radius) / (half_np / cm.get_z_near()) * rect.size.width;
} else {
light_data.soft_shadow_size = 0.0;
light_data.soft_shadow_scale *= shadows_quality_radius_get(); // Only use quality radius for PCF
}
}
} else {
light_data.shadow_color_enabled[3] = 0;
}
light_instance_set_index(li, light_count);
cluster.builder.add_light(type == RS::LIGHT_SPOT ? LightClusterBuilder::LIGHT_TYPE_SPOT : LightClusterBuilder::LIGHT_TYPE_OMNI, light_transform, radius, spot_angle);
light_count++;
r_positional_light_count++;
} break;
}
light_instance_set_render_pass(li, RSG::rasterizer->get_frame_number());
//update UBO for forward rendering, blit to texture for clustered
}
if (light_count) {
RD::get_singleton()->buffer_update(cluster.light_buffer, 0, sizeof(Cluster::LightData) * light_count, cluster.lights, true);
}
if (r_directional_light_count) {
RD::get_singleton()->buffer_update(cluster.directional_light_buffer, 0, sizeof(Cluster::DirectionalLightData) * r_directional_light_count, cluster.directional_lights, true);
}
}
void RasterizerSceneRD::_setup_decals(const RID *p_decal_instances, int p_decal_count, const Transform &p_camera_inverse_xform) {
Transform uv_xform;
uv_xform.basis.scale(Vector3(2.0, 1.0, 2.0));
uv_xform.origin = Vector3(-1.0, 0.0, -1.0);
p_decal_count = MIN((uint32_t)p_decal_count, cluster.max_decals);
int idx = 0;
for (int i = 0; i < p_decal_count; i++) {
RID di = p_decal_instances[i];
RID decal = decal_instance_get_base(di);
Transform xform = decal_instance_get_transform(di);
float fade = 1.0;
if (storage->decal_is_distance_fade_enabled(decal)) {
real_t distance = -p_camera_inverse_xform.xform(xform.origin).z;
float fade_begin = storage->decal_get_distance_fade_begin(decal);
float fade_length = storage->decal_get_distance_fade_length(decal);
if (distance > fade_begin) {
if (distance > fade_begin + fade_length) {
continue; // do not use this decal, its invisible
}
fade = 1.0 - (distance - fade_begin) / fade_length;
}
}
Cluster::DecalData &dd = cluster.decals[idx];
Vector3 decal_extents = storage->decal_get_extents(decal);
Transform scale_xform;
scale_xform.basis.scale(Vector3(decal_extents.x, decal_extents.y, decal_extents.z));
Transform to_decal_xform = (p_camera_inverse_xform * decal_instance_get_transform(di) * scale_xform * uv_xform).affine_inverse();
RasterizerStorageRD::store_transform(to_decal_xform, dd.xform);
Vector3 normal = xform.basis.get_axis(Vector3::AXIS_Y).normalized();
normal = p_camera_inverse_xform.basis.xform(normal); //camera is normalized, so fine
dd.normal[0] = normal.x;
dd.normal[1] = normal.y;
dd.normal[2] = normal.z;
dd.normal_fade = storage->decal_get_normal_fade(decal);
RID albedo_tex = storage->decal_get_texture(decal, RS::DECAL_TEXTURE_ALBEDO);
RID emission_tex = storage->decal_get_texture(decal, RS::DECAL_TEXTURE_EMISSION);
if (albedo_tex.is_valid()) {
Rect2 rect = storage->decal_atlas_get_texture_rect(albedo_tex);
dd.albedo_rect[0] = rect.position.x;
dd.albedo_rect[1] = rect.position.y;
dd.albedo_rect[2] = rect.size.x;
dd.albedo_rect[3] = rect.size.y;
} else {
if (!emission_tex.is_valid()) {
continue; //no albedo, no emission, no decal.
}
dd.albedo_rect[0] = 0;
dd.albedo_rect[1] = 0;
dd.albedo_rect[2] = 0;
dd.albedo_rect[3] = 0;
}
RID normal_tex = storage->decal_get_texture(decal, RS::DECAL_TEXTURE_NORMAL);
if (normal_tex.is_valid()) {
Rect2 rect = storage->decal_atlas_get_texture_rect(normal_tex);
dd.normal_rect[0] = rect.position.x;
dd.normal_rect[1] = rect.position.y;
dd.normal_rect[2] = rect.size.x;
dd.normal_rect[3] = rect.size.y;
Basis normal_xform = p_camera_inverse_xform.basis * xform.basis.orthonormalized();
RasterizerStorageRD::store_basis_3x4(normal_xform, dd.normal_xform);
} else {
dd.normal_rect[0] = 0;
dd.normal_rect[1] = 0;
dd.normal_rect[2] = 0;
dd.normal_rect[3] = 0;
}
RID orm_tex = storage->decal_get_texture(decal, RS::DECAL_TEXTURE_ORM);
if (orm_tex.is_valid()) {
Rect2 rect = storage->decal_atlas_get_texture_rect(orm_tex);
dd.orm_rect[0] = rect.position.x;
dd.orm_rect[1] = rect.position.y;
dd.orm_rect[2] = rect.size.x;
dd.orm_rect[3] = rect.size.y;
} else {
dd.orm_rect[0] = 0;
dd.orm_rect[1] = 0;
dd.orm_rect[2] = 0;
dd.orm_rect[3] = 0;
}
if (emission_tex.is_valid()) {
Rect2 rect = storage->decal_atlas_get_texture_rect(emission_tex);
dd.emission_rect[0] = rect.position.x;
dd.emission_rect[1] = rect.position.y;
dd.emission_rect[2] = rect.size.x;
dd.emission_rect[3] = rect.size.y;
} else {
dd.emission_rect[0] = 0;
dd.emission_rect[1] = 0;
dd.emission_rect[2] = 0;
dd.emission_rect[3] = 0;
}
Color modulate = storage->decal_get_modulate(decal);
dd.modulate[0] = modulate.r;
dd.modulate[1] = modulate.g;
dd.modulate[2] = modulate.b;
dd.modulate[3] = modulate.a * fade;
dd.emission_energy = storage->decal_get_emission_energy(decal) * fade;
dd.albedo_mix = storage->decal_get_albedo_mix(decal);
dd.mask = storage->decal_get_cull_mask(decal);
dd.upper_fade = storage->decal_get_upper_fade(decal);
dd.lower_fade = storage->decal_get_lower_fade(decal);
cluster.builder.add_decal(xform, decal_extents);
idx++;
}
if (idx > 0) {
RD::get_singleton()->buffer_update(cluster.decal_buffer, 0, sizeof(Cluster::DecalData) * idx, cluster.decals, true);
}
}
void RasterizerSceneRD::_volumetric_fog_erase(RenderBuffers *rb) {
ERR_FAIL_COND(!rb->volumetric_fog);
RD::get_singleton()->free(rb->volumetric_fog->light_density_map);
RD::get_singleton()->free(rb->volumetric_fog->fog_map);
if (rb->volumetric_fog->uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(rb->volumetric_fog->uniform_set)) {
RD::get_singleton()->free(rb->volumetric_fog->uniform_set);
}
if (rb->volumetric_fog->uniform_set2.is_valid() && RD::get_singleton()->uniform_set_is_valid(rb->volumetric_fog->uniform_set2)) {
RD::get_singleton()->free(rb->volumetric_fog->uniform_set2);
}
if (rb->volumetric_fog->sdfgi_uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(rb->volumetric_fog->sdfgi_uniform_set)) {
RD::get_singleton()->free(rb->volumetric_fog->sdfgi_uniform_set);
}
if (rb->volumetric_fog->sky_uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(rb->volumetric_fog->sky_uniform_set)) {
RD::get_singleton()->free(rb->volumetric_fog->sky_uniform_set);
}
memdelete(rb->volumetric_fog);
rb->volumetric_fog = nullptr;
}
void RasterizerSceneRD::_allocate_shadow_shrink_stages(RID p_base, int p_base_size, Vector<ShadowShrinkStage> &shrink_stages, uint32_t p_target_size) {
//create fog mipmaps
uint32_t fog_texture_size = p_target_size;
uint32_t base_texture_size = p_base_size;
ShadowShrinkStage first;
first.size = base_texture_size;
first.texture = p_base;
shrink_stages.push_back(first); //put depth first in case we dont find smaller ones
while (fog_texture_size < base_texture_size) {
base_texture_size = MAX(base_texture_size / 8, fog_texture_size);
ShadowShrinkStage s;
s.size = base_texture_size;
RD::TextureFormat tf;
tf.format = RD::DATA_FORMAT_R32_SFLOAT;
tf.width = base_texture_size;
tf.height = base_texture_size;
tf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT;
if (base_texture_size == fog_texture_size) {
s.filter_texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
tf.usage_bits |= RD::TEXTURE_USAGE_SAMPLING_BIT;
}
s.texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
shrink_stages.push_back(s);
}
}
void RasterizerSceneRD::_clear_shadow_shrink_stages(Vector<ShadowShrinkStage> &shrink_stages) {
for (int i = 1; i < shrink_stages.size(); i++) {
RD::get_singleton()->free(shrink_stages[i].texture);
if (shrink_stages[i].filter_texture.is_valid()) {
RD::get_singleton()->free(shrink_stages[i].filter_texture);
}
}
shrink_stages.clear();
}
void RasterizerSceneRD::_update_volumetric_fog(RID p_render_buffers, RID p_environment, const CameraMatrix &p_cam_projection, const Transform &p_cam_transform, RID p_shadow_atlas, int p_directional_light_count, bool p_use_directional_shadows, int p_positional_light_count, int p_gi_probe_count) {
RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND(!rb);
Environment *env = environment_owner.getornull(p_environment);
float ratio = float(rb->width) / float((rb->width + rb->height) / 2);
uint32_t target_width = uint32_t(float(volumetric_fog_size) * ratio);
uint32_t target_height = uint32_t(float(volumetric_fog_size) / ratio);
if (rb->volumetric_fog) {
//validate
if (!env || !env->volumetric_fog_enabled || rb->volumetric_fog->width != target_width || rb->volumetric_fog->height != target_height || rb->volumetric_fog->depth != volumetric_fog_depth) {
_volumetric_fog_erase(rb);
_render_buffers_uniform_set_changed(p_render_buffers);
}
}
if (!env || !env->volumetric_fog_enabled) {
//no reason to enable or update, bye
return;
}
if (env && env->volumetric_fog_enabled && !rb->volumetric_fog) {
//required volumetric fog but not existing, create
rb->volumetric_fog = memnew(VolumetricFog);
rb->volumetric_fog->width = target_width;
rb->volumetric_fog->height = target_height;
rb->volumetric_fog->depth = volumetric_fog_depth;
RD::TextureFormat tf;
tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
tf.width = target_width;
tf.height = target_height;
tf.depth = volumetric_fog_depth;
tf.type = RD::TEXTURE_TYPE_3D;
tf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT;
rb->volumetric_fog->light_density_map = RD::get_singleton()->texture_create(tf, RD::TextureView());
tf.usage_bits |= RD::TEXTURE_USAGE_SAMPLING_BIT;
rb->volumetric_fog->fog_map = RD::get_singleton()->texture_create(tf, RD::TextureView());
_render_buffers_uniform_set_changed(p_render_buffers);
Vector<RD::Uniform> uniforms;
{
RD::Uniform u;
u.binding = 0;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.ids.push_back(rb->volumetric_fog->fog_map);
uniforms.push_back(u);
}
rb->volumetric_fog->sky_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sky_shader.default_shader_rd, SKY_SET_FOG);
}
//update directional shadow
if (p_use_directional_shadows) {
if (directional_shadow.shrink_stages.empty()) {
if (rb->volumetric_fog->uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(rb->volumetric_fog->uniform_set)) {
//invalidate uniform set, we will need a new one
RD::get_singleton()->free(rb->volumetric_fog->uniform_set);
rb->volumetric_fog->uniform_set = RID();
}
_allocate_shadow_shrink_stages(directional_shadow.depth, directional_shadow.size, directional_shadow.shrink_stages, volumetric_fog_directional_shadow_shrink);
}
if (directional_shadow.shrink_stages.size() > 1) {
RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
for (int i = 1; i < directional_shadow.shrink_stages.size(); i++) {
int32_t src_size = directional_shadow.shrink_stages[i - 1].size;
int32_t dst_size = directional_shadow.shrink_stages[i].size;
Rect2i r(0, 0, src_size, src_size);
int32_t shrink_limit = 8 / (src_size / dst_size);
storage->get_effects()->reduce_shadow(directional_shadow.shrink_stages[i - 1].texture, directional_shadow.shrink_stages[i].texture, Size2i(src_size, src_size), r, shrink_limit, compute_list);
RD::get_singleton()->compute_list_add_barrier(compute_list);
if (env->volumetric_fog_shadow_filter != RS::ENV_VOLUMETRIC_FOG_SHADOW_FILTER_DISABLED && directional_shadow.shrink_stages[i].filter_texture.is_valid()) {
Rect2i rf(0, 0, dst_size, dst_size);
storage->get_effects()->filter_shadow(directional_shadow.shrink_stages[i].texture, directional_shadow.shrink_stages[i].filter_texture, Size2i(dst_size, dst_size), rf, env->volumetric_fog_shadow_filter, compute_list);
}
}
RD::get_singleton()->compute_list_end();
}
}
ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_shadow_atlas);
if (shadow_atlas) {
//shrink shadows that need to be shrunk
bool force_shrink_shadows = false;
if (shadow_atlas->shrink_stages.empty()) {
if (rb->volumetric_fog->uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(rb->volumetric_fog->uniform_set)) {
//invalidate uniform set, we will need a new one
RD::get_singleton()->free(rb->volumetric_fog->uniform_set);
rb->volumetric_fog->uniform_set = RID();
}
_allocate_shadow_shrink_stages(shadow_atlas->depth, shadow_atlas->size, shadow_atlas->shrink_stages, volumetric_fog_positional_shadow_shrink);
force_shrink_shadows = true;
}
if (rb->volumetric_fog->last_shadow_filter != env->volumetric_fog_shadow_filter) {
//if shadow filter changed, invalidate caches
rb->volumetric_fog->last_shadow_filter = env->volumetric_fog_shadow_filter;
force_shrink_shadows = true;
}
cluster.lights_shadow_rect_cache_count = 0;
for (int i = 0; i < p_positional_light_count; i++) {
if (cluster.lights[i].shadow_color_enabled[3] > 127) {
RID li = cluster.lights_instances[i];
ERR_CONTINUE(!shadow_atlas->shadow_owners.has(li));
uint32_t key = shadow_atlas->shadow_owners[li];
uint32_t quadrant = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x3;
uint32_t shadow = key & ShadowAtlas::SHADOW_INDEX_MASK;
ERR_CONTINUE((int)shadow >= shadow_atlas->quadrants[quadrant].shadows.size());
ShadowAtlas::Quadrant::Shadow &s = shadow_atlas->quadrants[quadrant].shadows.write[shadow];
if (!force_shrink_shadows && s.fog_version == s.version) {
continue; //do not update, no need
}
s.fog_version = s.version;
uint32_t quadrant_size = shadow_atlas->size >> 1;
Rect2i atlas_rect;
atlas_rect.position.x = (quadrant & 1) * quadrant_size;
atlas_rect.position.y = (quadrant >> 1) * quadrant_size;
uint32_t shadow_size = (quadrant_size / shadow_atlas->quadrants[quadrant].subdivision);
atlas_rect.position.x += (shadow % shadow_atlas->quadrants[quadrant].subdivision) * shadow_size;
atlas_rect.position.y += (shadow / shadow_atlas->quadrants[quadrant].subdivision) * shadow_size;
atlas_rect.size.x = shadow_size;
atlas_rect.size.y = shadow_size;
cluster.lights_shadow_rect_cache[cluster.lights_shadow_rect_cache_count] = atlas_rect;
cluster.lights_shadow_rect_cache_count++;
if (cluster.lights_shadow_rect_cache_count == cluster.max_lights) {
break; //light limit reached
}
}
}
if (cluster.lights_shadow_rect_cache_count > 0) {
//there are shadows to be shrunk, try to do them in parallel
RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
for (int i = 1; i < shadow_atlas->shrink_stages.size(); i++) {
int32_t base_size = shadow_atlas->shrink_stages[0].size;
int32_t src_size = shadow_atlas->shrink_stages[i - 1].size;
int32_t dst_size = shadow_atlas->shrink_stages[i].size;
uint32_t rect_divisor = base_size / src_size;
int32_t shrink_limit = 8 / (src_size / dst_size);
//shrink in parallel for more performance
for (uint32_t j = 0; j < cluster.lights_shadow_rect_cache_count; j++) {
Rect2i src_rect = cluster.lights_shadow_rect_cache[j];
src_rect.position /= rect_divisor;
src_rect.size /= rect_divisor;
storage->get_effects()->reduce_shadow(shadow_atlas->shrink_stages[i - 1].texture, shadow_atlas->shrink_stages[i].texture, Size2i(src_size, src_size), src_rect, shrink_limit, compute_list);
}
RD::get_singleton()->compute_list_add_barrier(compute_list);
if (env->volumetric_fog_shadow_filter != RS::ENV_VOLUMETRIC_FOG_SHADOW_FILTER_DISABLED && shadow_atlas->shrink_stages[i].filter_texture.is_valid()) {
uint32_t filter_divisor = base_size / dst_size;
//filter in parallel for more performance
for (uint32_t j = 0; j < cluster.lights_shadow_rect_cache_count; j++) {
Rect2i dst_rect = cluster.lights_shadow_rect_cache[j];
dst_rect.position /= filter_divisor;
dst_rect.size /= filter_divisor;
storage->get_effects()->filter_shadow(shadow_atlas->shrink_stages[i].texture, shadow_atlas->shrink_stages[i].filter_texture, Size2i(dst_size, dst_size), dst_rect, env->volumetric_fog_shadow_filter, compute_list, true, false);
}
RD::get_singleton()->compute_list_add_barrier(compute_list);
for (uint32_t j = 0; j < cluster.lights_shadow_rect_cache_count; j++) {
Rect2i dst_rect = cluster.lights_shadow_rect_cache[j];
dst_rect.position /= filter_divisor;
dst_rect.size /= filter_divisor;
storage->get_effects()->filter_shadow(shadow_atlas->shrink_stages[i].texture, shadow_atlas->shrink_stages[i].filter_texture, Size2i(dst_size, dst_size), dst_rect, env->volumetric_fog_shadow_filter, compute_list, false, true);
}
}
}
RD::get_singleton()->compute_list_end();
}
}
//update volumetric fog
if (rb->volumetric_fog->uniform_set.is_null() || !RD::get_singleton()->uniform_set_is_valid(rb->volumetric_fog->uniform_set)) {
//re create uniform set if needed
Vector<RD::Uniform> uniforms;
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 1;
if (shadow_atlas == nullptr || shadow_atlas->shrink_stages.size() == 0) {
u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_BLACK));
} else {
u.ids.push_back(shadow_atlas->shrink_stages[shadow_atlas->shrink_stages.size() - 1].texture);
}
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 2;
if (directional_shadow.shrink_stages.size() == 0) {
u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_BLACK));
} else {
u.ids.push_back(directional_shadow.shrink_stages[directional_shadow.shrink_stages.size() - 1].texture);
}
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
u.binding = 3;
u.ids.push_back(get_positional_light_buffer());
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
u.binding = 4;
u.ids.push_back(get_directional_light_buffer());
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 5;
u.ids.push_back(get_cluster_builder_texture());
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
u.binding = 6;
u.ids.push_back(get_cluster_builder_indices_buffer());
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_SAMPLER;
u.binding = 7;
u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 8;
u.ids.push_back(rb->volumetric_fog->light_density_map);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_IMAGE;
u.binding = 9;
u.ids.push_back(rb->volumetric_fog->fog_map);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_SAMPLER;
u.binding = 10;
u.ids.push_back(shadow_sampler);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
u.binding = 11;
u.ids.push_back(render_buffers_get_gi_probe_buffer(p_render_buffers));
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 12;
for (int i = 0; i < RenderBuffers::MAX_GIPROBES; i++) {
u.ids.push_back(rb->giprobe_textures[i]);
}
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_SAMPLER;
u.binding = 13;
u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
uniforms.push_back(u);
}
rb->volumetric_fog->uniform_set = RD::get_singleton()->uniform_set_create(uniforms, volumetric_fog.shader.version_get_shader(volumetric_fog.shader_version, 0), 0);
SWAP(uniforms.write[7].ids.write[0], uniforms.write[8].ids.write[0]);
rb->volumetric_fog->uniform_set2 = RD::get_singleton()->uniform_set_create(uniforms, volumetric_fog.shader.version_get_shader(volumetric_fog.shader_version, 0), 0);
}
bool using_sdfgi = env->volumetric_fog_gi_inject > 0.0001 && env->sdfgi_enabled && (rb->sdfgi != nullptr);
if (using_sdfgi) {
if (rb->volumetric_fog->sdfgi_uniform_set.is_null() || !RD::get_singleton()->uniform_set_is_valid(rb->volumetric_fog->sdfgi_uniform_set)) {
Vector<RD::Uniform> uniforms;
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
u.binding = 0;
u.ids.push_back(gi.sdfgi_ubo);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 1;
u.ids.push_back(rb->sdfgi->ambient_texture);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 2;
u.ids.push_back(rb->sdfgi->occlusion_texture);
uniforms.push_back(u);
}
rb->volumetric_fog->sdfgi_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, volumetric_fog.shader.version_get_shader(volumetric_fog.shader_version, VOLUMETRIC_FOG_SHADER_DENSITY_WITH_SDFGI), 1);
}
}
rb->volumetric_fog->length = env->volumetric_fog_length;
rb->volumetric_fog->spread = env->volumetric_fog_detail_spread;
VolumetricFogShader::PushConstant push_constant;
Vector2 frustum_near_size = p_cam_projection.get_viewport_half_extents();
Vector2 frustum_far_size = p_cam_projection.get_far_plane_half_extents();
float z_near = p_cam_projection.get_z_near();
float z_far = p_cam_projection.get_z_far();
float fog_end = env->volumetric_fog_length;
Vector2 fog_far_size = frustum_near_size.lerp(frustum_far_size, (fog_end - z_near) / (z_far - z_near));
Vector2 fog_near_size;
if (p_cam_projection.is_orthogonal()) {
fog_near_size = fog_far_size;
} else {
fog_near_size = Vector2();
}
push_constant.fog_frustum_size_begin[0] = fog_near_size.x;
push_constant.fog_frustum_size_begin[1] = fog_near_size.y;
push_constant.fog_frustum_size_end[0] = fog_far_size.x;
push_constant.fog_frustum_size_end[1] = fog_far_size.y;
push_constant.z_near = z_near;
push_constant.z_far = z_far;
push_constant.fog_frustum_end = fog_end;
push_constant.fog_volume_size[0] = rb->volumetric_fog->width;
push_constant.fog_volume_size[1] = rb->volumetric_fog->height;
push_constant.fog_volume_size[2] = rb->volumetric_fog->depth;
push_constant.directional_light_count = p_directional_light_count;
Color light = env->volumetric_fog_light.to_linear();
push_constant.light_energy[0] = light.r * env->volumetric_fog_light_energy;
push_constant.light_energy[1] = light.g * env->volumetric_fog_light_energy;
push_constant.light_energy[2] = light.b * env->volumetric_fog_light_energy;
push_constant.base_density = env->volumetric_fog_density;
push_constant.detail_spread = env->volumetric_fog_detail_spread;
push_constant.gi_inject = env->volumetric_fog_gi_inject;
push_constant.cam_rotation[0] = p_cam_transform.basis[0][0];
push_constant.cam_rotation[1] = p_cam_transform.basis[1][0];
push_constant.cam_rotation[2] = p_cam_transform.basis[2][0];
push_constant.cam_rotation[3] = 0;
push_constant.cam_rotation[4] = p_cam_transform.basis[0][1];
push_constant.cam_rotation[5] = p_cam_transform.basis[1][1];
push_constant.cam_rotation[6] = p_cam_transform.basis[2][1];
push_constant.cam_rotation[7] = 0;
push_constant.cam_rotation[8] = p_cam_transform.basis[0][2];
push_constant.cam_rotation[9] = p_cam_transform.basis[1][2];
push_constant.cam_rotation[10] = p_cam_transform.basis[2][2];
push_constant.cam_rotation[11] = 0;
push_constant.filter_axis = 0;
push_constant.max_gi_probes = env->volumetric_fog_gi_inject > 0.001 ? p_gi_probe_count : 0;
/* Vector2 dssize = directional_shadow_get_size();
push_constant.directional_shadow_pixel_size[0] = 1.0 / dssize.x;
push_constant.directional_shadow_pixel_size[1] = 1.0 / dssize.y;
*/
RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
bool use_filter = volumetric_fog_filter_active;
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, volumetric_fog.pipelines[using_sdfgi ? VOLUMETRIC_FOG_SHADER_DENSITY_WITH_SDFGI : VOLUMETRIC_FOG_SHADER_DENSITY]);
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->volumetric_fog->uniform_set, 0);
if (using_sdfgi) {
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->volumetric_fog->sdfgi_uniform_set, 1);
}
RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(VolumetricFogShader::PushConstant));
RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->volumetric_fog->width, rb->volumetric_fog->height, rb->volumetric_fog->depth, 4, 4, 4);
RD::get_singleton()->compute_list_add_barrier(compute_list);
if (use_filter) {
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, volumetric_fog.pipelines[VOLUMETRIC_FOG_SHADER_FILTER]);
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->volumetric_fog->uniform_set, 0);
RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(VolumetricFogShader::PushConstant));
RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->volumetric_fog->width, rb->volumetric_fog->height, rb->volumetric_fog->depth, 8, 8, 1);
RD::get_singleton()->compute_list_add_barrier(compute_list);
push_constant.filter_axis = 1;
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->volumetric_fog->uniform_set2, 0);
RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(VolumetricFogShader::PushConstant));
RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->volumetric_fog->width, rb->volumetric_fog->height, rb->volumetric_fog->depth, 8, 8, 1);
RD::get_singleton()->compute_list_add_barrier(compute_list);
}
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, volumetric_fog.pipelines[VOLUMETRIC_FOG_SHADER_FOG]);
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->volumetric_fog->uniform_set, 0);
RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(VolumetricFogShader::PushConstant));
RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->volumetric_fog->width, rb->volumetric_fog->height, 1, 8, 8, 1);
RD::get_singleton()->compute_list_end();
}
void RasterizerSceneRD::render_scene(RID p_render_buffers, const Transform &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, InstanceBase **p_cull_result, int p_cull_count, RID *p_light_cull_result, int p_light_cull_count, RID *p_reflection_probe_cull_result, int p_reflection_probe_cull_count, RID *p_gi_probe_cull_result, int p_gi_probe_cull_count, RID *p_decal_cull_result, int p_decal_cull_count, InstanceBase **p_lightmap_cull_result, int p_lightmap_cull_count, RID p_environment, RID p_camera_effects, RID p_shadow_atlas, RID p_reflection_atlas, RID p_reflection_probe, int p_reflection_probe_pass) {
Color clear_color;
if (p_render_buffers.is_valid()) {
RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND(!rb);
clear_color = storage->render_target_get_clear_request_color(rb->render_target);
} else {
clear_color = storage->get_default_clear_color();
}
//assign render indices to giprobes
for (int i = 0; i < p_gi_probe_cull_count; i++) {
GIProbeInstance *giprobe_inst = gi_probe_instance_owner.getornull(p_gi_probe_cull_result[i]);
if (giprobe_inst) {
giprobe_inst->render_index = i;
}
}
if (get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_UNSHADED) {
p_light_cull_count = 0;
p_reflection_probe_cull_count = 0;
p_gi_probe_cull_count = 0;
}
cluster.builder.begin(p_cam_transform.affine_inverse(), p_cam_projection); //prepare cluster
bool using_shadows = true;
if (p_reflection_probe.is_valid()) {
if (!storage->reflection_probe_renders_shadows(reflection_probe_instance_get_probe(p_reflection_probe))) {
using_shadows = false;
}
} else {
//do not render reflections when rendering a reflection probe
_setup_reflections(p_reflection_probe_cull_result, p_reflection_probe_cull_count, p_cam_transform.affine_inverse(), p_environment);
}
uint32_t directional_light_count = 0;
uint32_t positional_light_count = 0;
_setup_lights(p_light_cull_result, p_light_cull_count, p_cam_transform.affine_inverse(), p_shadow_atlas, using_shadows, directional_light_count, positional_light_count);
_setup_decals(p_decal_cull_result, p_decal_cull_count, p_cam_transform.affine_inverse());
cluster.builder.bake_cluster(); //bake to cluster
uint32_t gi_probe_count = 0;
_setup_giprobes(p_render_buffers, p_cam_transform, p_gi_probe_cull_result, p_gi_probe_cull_count, gi_probe_count);
if (p_render_buffers.is_valid()) {
bool directional_shadows = false;
for (uint32_t i = 0; i < directional_light_count; i++) {
if (cluster.directional_lights[i].shadow_enabled) {
directional_shadows = true;
break;
}
}
_update_volumetric_fog(p_render_buffers, p_environment, p_cam_projection, p_cam_transform, p_shadow_atlas, directional_light_count, directional_shadows, positional_light_count, gi_probe_count);
}
_render_scene(p_render_buffers, p_cam_transform, p_cam_projection, p_cam_ortogonal, p_cull_result, p_cull_count, directional_light_count, p_gi_probe_cull_result, p_gi_probe_cull_count, p_lightmap_cull_result, p_lightmap_cull_count, p_environment, p_camera_effects, p_shadow_atlas, p_reflection_atlas, p_reflection_probe, p_reflection_probe_pass, clear_color);
if (p_render_buffers.is_valid()) {
RENDER_TIMESTAMP("Tonemap");
_render_buffers_post_process_and_tonemap(p_render_buffers, p_environment, p_camera_effects, p_cam_projection);
_render_buffers_debug_draw(p_render_buffers, p_shadow_atlas);
if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_SDFGI) {
_sdfgi_debug_draw(p_render_buffers, p_cam_projection, p_cam_transform);
}
}
}
void RasterizerSceneRD::render_shadow(RID p_light, RID p_shadow_atlas, int p_pass, InstanceBase **p_cull_result, int p_cull_count) {
LightInstance *light_instance = light_instance_owner.getornull(p_light);
ERR_FAIL_COND(!light_instance);
Rect2i atlas_rect;
RID atlas_texture;
bool using_dual_paraboloid = false;
bool using_dual_paraboloid_flip = false;
float znear = 0;
float zfar = 0;
RID render_fb;
RID render_texture;
float bias = 0;
float normal_bias = 0;
bool use_pancake = false;
bool use_linear_depth = false;
bool render_cubemap = false;
bool finalize_cubemap = false;
CameraMatrix light_projection;
Transform light_transform;
if (storage->light_get_type(light_instance->light) == RS::LIGHT_DIRECTIONAL) {
//set pssm stuff
if (light_instance->last_scene_shadow_pass != scene_pass) {
light_instance->directional_rect = _get_directional_shadow_rect(directional_shadow.size, directional_shadow.light_count, directional_shadow.current_light);
directional_shadow.current_light++;
light_instance->last_scene_shadow_pass = scene_pass;
}
use_pancake = storage->light_get_param(light_instance->light, RS::LIGHT_PARAM_SHADOW_PANCAKE_SIZE) > 0;
light_projection = light_instance->shadow_transform[p_pass].camera;
light_transform = light_instance->shadow_transform[p_pass].transform;
atlas_rect.position.x = light_instance->directional_rect.position.x;
atlas_rect.position.y = light_instance->directional_rect.position.y;
atlas_rect.size.width = light_instance->directional_rect.size.x;
atlas_rect.size.height = light_instance->directional_rect.size.y;
if (storage->light_directional_get_shadow_mode(light_instance->light) == RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS) {
atlas_rect.size.width /= 2;
atlas_rect.size.height /= 2;
if (p_pass == 1) {
atlas_rect.position.x += atlas_rect.size.width;
} else if (p_pass == 2) {
atlas_rect.position.y += atlas_rect.size.height;
} else if (p_pass == 3) {
atlas_rect.position.x += atlas_rect.size.width;
atlas_rect.position.y += atlas_rect.size.height;
}
} else if (storage->light_directional_get_shadow_mode(light_instance->light) == RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS) {
atlas_rect.size.height /= 2;
if (p_pass == 0) {
} else {
atlas_rect.position.y += atlas_rect.size.height;
}
}
light_instance->shadow_transform[p_pass].atlas_rect = atlas_rect;
light_instance->shadow_transform[p_pass].atlas_rect.position /= directional_shadow.size;
light_instance->shadow_transform[p_pass].atlas_rect.size /= directional_shadow.size;
float bias_mult = light_instance->shadow_transform[p_pass].bias_scale;
zfar = storage->light_get_param(light_instance->light, RS::LIGHT_PARAM_RANGE);
bias = storage->light_get_param(light_instance->light, RS::LIGHT_PARAM_SHADOW_BIAS) * bias_mult;
normal_bias = storage->light_get_param(light_instance->light, RS::LIGHT_PARAM_SHADOW_NORMAL_BIAS) * bias_mult;
ShadowMap *shadow_map = _get_shadow_map(atlas_rect.size);
render_fb = shadow_map->fb;
render_texture = shadow_map->depth;
atlas_texture = directional_shadow.depth;
} else {
//set from shadow atlas
ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_shadow_atlas);
ERR_FAIL_COND(!shadow_atlas);
ERR_FAIL_COND(!shadow_atlas->shadow_owners.has(p_light));
uint32_t key = shadow_atlas->shadow_owners[p_light];
uint32_t quadrant = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x3;
uint32_t shadow = key & ShadowAtlas::SHADOW_INDEX_MASK;
ERR_FAIL_INDEX((int)shadow, shadow_atlas->quadrants[quadrant].shadows.size());
uint32_t quadrant_size = shadow_atlas->size >> 1;
atlas_rect.position.x = (quadrant & 1) * quadrant_size;
atlas_rect.position.y = (quadrant >> 1) * quadrant_size;
uint32_t shadow_size = (quadrant_size / shadow_atlas->quadrants[quadrant].subdivision);
atlas_rect.position.x += (shadow % shadow_atlas->quadrants[quadrant].subdivision) * shadow_size;
atlas_rect.position.y += (shadow / shadow_atlas->quadrants[quadrant].subdivision) * shadow_size;
atlas_rect.size.width = shadow_size;
atlas_rect.size.height = shadow_size;
atlas_texture = shadow_atlas->depth;
zfar = storage->light_get_param(light_instance->light, RS::LIGHT_PARAM_RANGE);
bias = storage->light_get_param(light_instance->light, RS::LIGHT_PARAM_SHADOW_BIAS);
normal_bias = storage->light_get_param(light_instance->light, RS::LIGHT_PARAM_SHADOW_NORMAL_BIAS);
if (storage->light_get_type(light_instance->light) == RS::LIGHT_OMNI) {
if (storage->light_omni_get_shadow_mode(light_instance->light) == RS::LIGHT_OMNI_SHADOW_CUBE) {
ShadowCubemap *cubemap = _get_shadow_cubemap(shadow_size / 2);
render_fb = cubemap->side_fb[p_pass];
render_texture = cubemap->cubemap;
light_projection = light_instance->shadow_transform[0].camera;
light_transform = light_instance->shadow_transform[0].transform;
render_cubemap = true;
finalize_cubemap = p_pass == 5;
} else {
light_projection = light_instance->shadow_transform[0].camera;
light_transform = light_instance->shadow_transform[0].transform;
atlas_rect.size.height /= 2;
atlas_rect.position.y += p_pass * atlas_rect.size.height;
using_dual_paraboloid = true;
using_dual_paraboloid_flip = p_pass == 1;
ShadowMap *shadow_map = _get_shadow_map(atlas_rect.size);
render_fb = shadow_map->fb;
render_texture = shadow_map->depth;
}
} else if (storage->light_get_type(light_instance->light) == RS::LIGHT_SPOT) {
light_projection = light_instance->shadow_transform[0].camera;
light_transform = light_instance->shadow_transform[0].transform;
ShadowMap *shadow_map = _get_shadow_map(atlas_rect.size);
render_fb = shadow_map->fb;
render_texture = shadow_map->depth;
znear = light_instance->shadow_transform[0].camera.get_z_near();
use_linear_depth = true;
}
}
if (render_cubemap) {
//rendering to cubemap
_render_shadow(render_fb, p_cull_result, p_cull_count, light_projection, light_transform, zfar, 0, 0, false, false, use_pancake);
if (finalize_cubemap) {
//reblit
atlas_rect.size.height /= 2;
storage->get_effects()->copy_cubemap_to_dp(render_texture, atlas_texture, atlas_rect, light_projection.get_z_near(), light_projection.get_z_far(), 0.0, false);
atlas_rect.position.y += atlas_rect.size.height;
storage->get_effects()->copy_cubemap_to_dp(render_texture, atlas_texture, atlas_rect, light_projection.get_z_near(), light_projection.get_z_far(), 0.0, true);
}
} else {
//render shadow
_render_shadow(render_fb, p_cull_result, p_cull_count, light_projection, light_transform, zfar, bias, normal_bias, using_dual_paraboloid, using_dual_paraboloid_flip, use_pancake);
//copy to atlas
if (use_linear_depth) {
storage->get_effects()->copy_depth_to_rect_and_linearize(render_texture, atlas_texture, atlas_rect, true, znear, zfar);
} else {
storage->get_effects()->copy_depth_to_rect(render_texture, atlas_texture, atlas_rect, true);
}
//does not work from depth to color
//RD::get_singleton()->texture_copy(render_texture, atlas_texture, Vector3(0, 0, 0), Vector3(atlas_rect.position.x, atlas_rect.position.y, 0), Vector3(atlas_rect.size.x, atlas_rect.size.y, 1), 0, 0, 0, 0, true);
}
}
void RasterizerSceneRD::render_material(const Transform &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, InstanceBase **p_cull_result, int p_cull_count, RID p_framebuffer, const Rect2i &p_region) {
_render_material(p_cam_transform, p_cam_projection, p_cam_ortogonal, p_cull_result, p_cull_count, p_framebuffer, p_region);
}
void RasterizerSceneRD::render_sdfgi(RID p_render_buffers, int p_region, InstanceBase **p_cull_result, int p_cull_count) {
//print_line("rendering region " + itos(p_region));
RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND(!rb);
ERR_FAIL_COND(!rb->sdfgi);
AABB bounds;
Vector3i from;
Vector3i size;
int cascade_prev = _sdfgi_get_pending_region_data(p_render_buffers, p_region - 1, from, size, bounds);
int cascade_next = _sdfgi_get_pending_region_data(p_render_buffers, p_region + 1, from, size, bounds);
int cascade = _sdfgi_get_pending_region_data(p_render_buffers, p_region, from, size, bounds);
ERR_FAIL_COND(cascade < 0);
if (cascade_prev != cascade) {
//initialize render
RD::get_singleton()->texture_clear(rb->sdfgi->render_albedo, Color(0, 0, 0, 0), 0, 1, 0, 1, true);
RD::get_singleton()->texture_clear(rb->sdfgi->render_emission, Color(0, 0, 0, 0), 0, 1, 0, 1, true);
RD::get_singleton()->texture_clear(rb->sdfgi->render_emission_aniso, Color(0, 0, 0, 0), 0, 1, 0, 1, true);
RD::get_singleton()->texture_clear(rb->sdfgi->render_geom_facing, Color(0, 0, 0, 0), 0, 1, 0, 1, true);
}
//print_line("rendering cascade " + itos(p_region) + " objects: " + itos(p_cull_count) + " bounds: " + bounds + " from: " + from + " size: " + size + " cell size: " + rtos(rb->sdfgi->cascades[cascade].cell_size));
_render_sdfgi(p_render_buffers, from, size, bounds, p_cull_result, p_cull_count, rb->sdfgi->render_albedo, rb->sdfgi->render_emission, rb->sdfgi->render_emission_aniso, rb->sdfgi->render_geom_facing);
if (cascade_next != cascade) {
RENDER_TIMESTAMP(">SDFGI Update SDF");
//done rendering! must update SDF
//clear dispatch indirect data
SDGIShader::PreprocessPushConstant push_constant;
zeromem(&push_constant, sizeof(SDGIShader::PreprocessPushConstant));
RENDER_TIMESTAMP("Scroll SDF");
//scroll
if (rb->sdfgi->cascades[cascade].dirty_regions != SDFGI::Cascade::DIRTY_ALL) {
//for scroll
Vector3i dirty = rb->sdfgi->cascades[cascade].dirty_regions;
push_constant.scroll[0] = dirty.x;
push_constant.scroll[1] = dirty.y;
push_constant.scroll[2] = dirty.z;
} else {
//for no scroll
push_constant.scroll[0] = 0;
push_constant.scroll[1] = 0;
push_constant.scroll[2] = 0;
}
push_constant.grid_size = rb->sdfgi->cascade_size;
push_constant.cascade = cascade;
if (rb->sdfgi->cascades[cascade].dirty_regions != SDFGI::Cascade::DIRTY_ALL) {
RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
//must pre scroll existing data because not all is dirty
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_SCROLL]);
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->cascades[cascade].scroll_uniform_set, 0);
RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
RD::get_singleton()->compute_list_dispatch_indirect(compute_list, rb->sdfgi->cascades[cascade].solid_cell_dispatch_buffer, 0);
// no barrier do all together
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_SCROLL_OCCLUSION]);
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->cascades[cascade].scroll_occlusion_uniform_set, 0);
Vector3i dirty = rb->sdfgi->cascades[cascade].dirty_regions;
Vector3i groups;
groups.x = rb->sdfgi->cascade_size - ABS(dirty.x);
groups.y = rb->sdfgi->cascade_size - ABS(dirty.y);
groups.z = rb->sdfgi->cascade_size - ABS(dirty.z);
RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
RD::get_singleton()->compute_list_dispatch_threads(compute_list, groups.x, groups.y, groups.z, 4, 4, 4);
//no barrier, continue together
{
//scroll probes and their history also
SDGIShader::IntegratePushConstant ipush_constant;
ipush_constant.grid_size[1] = rb->sdfgi->cascade_size;
ipush_constant.grid_size[2] = rb->sdfgi->cascade_size;
ipush_constant.grid_size[0] = rb->sdfgi->cascade_size;
ipush_constant.max_cascades = rb->sdfgi->cascades.size();
ipush_constant.probe_axis_size = rb->sdfgi->probe_axis_count;
ipush_constant.history_index = 0;
ipush_constant.history_size = rb->sdfgi->history_size;
ipush_constant.ray_count = 0;
ipush_constant.ray_bias = 0;
ipush_constant.sky_mode = 0;
ipush_constant.sky_energy = 0;
ipush_constant.sky_color[0] = 0;
ipush_constant.sky_color[1] = 0;
ipush_constant.sky_color[2] = 0;
ipush_constant.y_mult = rb->sdfgi->y_mult;
ipush_constant.store_ambient_texture = false;
ipush_constant.image_size[0] = rb->sdfgi->probe_axis_count * rb->sdfgi->probe_axis_count;
ipush_constant.image_size[1] = rb->sdfgi->probe_axis_count;
ipush_constant.image_size[1] = rb->sdfgi->probe_axis_count;
int32_t probe_divisor = rb->sdfgi->cascade_size / SDFGI::PROBE_DIVISOR;
ipush_constant.cascade = cascade;
ipush_constant.world_offset[0] = rb->sdfgi->cascades[cascade].position.x / probe_divisor;
ipush_constant.world_offset[1] = rb->sdfgi->cascades[cascade].position.y / probe_divisor;
ipush_constant.world_offset[2] = rb->sdfgi->cascades[cascade].position.z / probe_divisor;
ipush_constant.scroll[0] = dirty.x / probe_divisor;
ipush_constant.scroll[1] = dirty.y / probe_divisor;
ipush_constant.scroll[2] = dirty.z / probe_divisor;
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.integrate_pipeline[SDGIShader::INTEGRATE_MODE_SCROLL]);
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->cascades[cascade].integrate_uniform_set, 0);
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, sdfgi_shader.integrate_default_sky_uniform_set, 1);
RD::get_singleton()->compute_list_set_push_constant(compute_list, &ipush_constant, sizeof(SDGIShader::IntegratePushConstant));
RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->probe_axis_count * rb->sdfgi->probe_axis_count, rb->sdfgi->probe_axis_count, 1, 8, 8, 1);
RD::get_singleton()->compute_list_add_barrier(compute_list);
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.integrate_pipeline[SDGIShader::INTEGRATE_MODE_SCROLL_STORE]);
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->cascades[cascade].integrate_uniform_set, 0);
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, sdfgi_shader.integrate_default_sky_uniform_set, 1);
RD::get_singleton()->compute_list_set_push_constant(compute_list, &ipush_constant, sizeof(SDGIShader::IntegratePushConstant));
RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->probe_axis_count * rb->sdfgi->probe_axis_count, rb->sdfgi->probe_axis_count, 1, 8, 8, 1);
}
//ok finally barrier
RD::get_singleton()->compute_list_end();
}
//clear dispatch indirect data
uint32_t dispatch_indirct_data[4] = { 0, 0, 0, 0 };
RD::get_singleton()->buffer_update(rb->sdfgi->cascades[cascade].solid_cell_dispatch_buffer, 0, sizeof(uint32_t) * 4, dispatch_indirct_data, true);
RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
bool half_size = true; //much faster, very little difference
static const int optimized_jf_group_size = 8;
if (half_size) {
push_constant.grid_size >>= 1;
uint32_t cascade_half_size = rb->sdfgi->cascade_size >> 1;
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_JUMP_FLOOD_INITIALIZE_HALF]);
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->sdf_initialize_half_uniform_set, 0);
RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
RD::get_singleton()->compute_list_dispatch_threads(compute_list, cascade_half_size, cascade_half_size, cascade_half_size, 4, 4, 4);
RD::get_singleton()->compute_list_add_barrier(compute_list);
//must start with regular jumpflood
push_constant.half_size = true;
{
RENDER_TIMESTAMP("SDFGI Jump Flood (Half Size)");
uint32_t s = cascade_half_size;
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_JUMP_FLOOD]);
int jf_us = 0;
//start with regular jump flood for very coarse reads, as this is impossible to optimize
while (s > 1) {
s /= 2;
push_constant.step_size = s;
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->jump_flood_half_uniform_set[jf_us], 0);
RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
RD::get_singleton()->compute_list_dispatch_threads(compute_list, cascade_half_size, cascade_half_size, cascade_half_size, 4, 4, 4);
RD::get_singleton()->compute_list_add_barrier(compute_list);
jf_us = jf_us == 0 ? 1 : 0;
if (cascade_half_size / (s / 2) >= optimized_jf_group_size) {
break;
}
}
RENDER_TIMESTAMP("SDFGI Jump Flood Optimized (Half Size)");
//continue with optimized jump flood for smaller reads
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_JUMP_FLOOD_OPTIMIZED]);
while (s > 1) {
s /= 2;
push_constant.step_size = s;
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->jump_flood_half_uniform_set[jf_us], 0);
RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
RD::get_singleton()->compute_list_dispatch_threads(compute_list, cascade_half_size, cascade_half_size, cascade_half_size, optimized_jf_group_size, optimized_jf_group_size, optimized_jf_group_size);
RD::get_singleton()->compute_list_add_barrier(compute_list);
jf_us = jf_us == 0 ? 1 : 0;
}
}
// restore grid size for last passes
push_constant.grid_size = rb->sdfgi->cascade_size;
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_JUMP_FLOOD_UPSCALE]);
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->sdf_upscale_uniform_set, 0);
RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, 4, 4, 4);
RD::get_singleton()->compute_list_add_barrier(compute_list);
//run one pass of fullsize jumpflood to fix up half size arctifacts
push_constant.half_size = false;
push_constant.step_size = 1;
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_JUMP_FLOOD_OPTIMIZED]);
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->jump_flood_uniform_set[rb->sdfgi->upscale_jfa_uniform_set_index], 0);
RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, optimized_jf_group_size, optimized_jf_group_size, optimized_jf_group_size);
RD::get_singleton()->compute_list_add_barrier(compute_list);
} else {
//full size jumpflood
RENDER_TIMESTAMP("SDFGI Jump Flood");
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_JUMP_FLOOD_INITIALIZE]);
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->sdf_initialize_uniform_set, 0);
RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, 4, 4, 4);
RD::get_singleton()->compute_list_add_barrier(compute_list);
push_constant.half_size = false;
{
uint32_t s = rb->sdfgi->cascade_size;
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_JUMP_FLOOD]);
int jf_us = 0;
//start with regular jump flood for very coarse reads, as this is impossible to optimize
while (s > 1) {
s /= 2;
push_constant.step_size = s;
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->jump_flood_uniform_set[jf_us], 0);
RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, 4, 4, 4);
RD::get_singleton()->compute_list_add_barrier(compute_list);
jf_us = jf_us == 0 ? 1 : 0;
if (rb->sdfgi->cascade_size / (s / 2) >= optimized_jf_group_size) {
break;
}
}
RENDER_TIMESTAMP("SDFGI Jump Flood Optimized");
//continue with optimized jump flood for smaller reads
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_JUMP_FLOOD_OPTIMIZED]);
while (s > 1) {
s /= 2;
push_constant.step_size = s;
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->jump_flood_uniform_set[jf_us], 0);
RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, optimized_jf_group_size, optimized_jf_group_size, optimized_jf_group_size);
RD::get_singleton()->compute_list_add_barrier(compute_list);
jf_us = jf_us == 0 ? 1 : 0;
}
}
}
RENDER_TIMESTAMP("SDFGI Occlusion");
// occlusion
{
uint32_t probe_size = rb->sdfgi->cascade_size / SDFGI::PROBE_DIVISOR;
Vector3i probe_global_pos = rb->sdfgi->cascades[cascade].position / probe_size;
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_OCCLUSION]);
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->occlusion_uniform_set, 0);
for (int i = 0; i < 8; i++) {
//dispatch all at once for performance
Vector3i offset(i & 1, (i >> 1) & 1, (i >> 2) & 1);
if ((probe_global_pos.x & 1) != 0) {
offset.x = (offset.x + 1) & 1;
}
if ((probe_global_pos.y & 1) != 0) {
offset.y = (offset.y + 1) & 1;
}
if ((probe_global_pos.z & 1) != 0) {
offset.z = (offset.z + 1) & 1;
}
push_constant.probe_offset[0] = offset.x;
push_constant.probe_offset[1] = offset.y;
push_constant.probe_offset[2] = offset.z;
push_constant.occlusion_index = i;
RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
Vector3i groups = Vector3i(probe_size + 1, probe_size + 1, probe_size + 1) - offset; //if offset, it's one less probe per axis to compute
RD::get_singleton()->compute_list_dispatch(compute_list, groups.x, groups.y, groups.z);
}
RD::get_singleton()->compute_list_add_barrier(compute_list);
}
RENDER_TIMESTAMP("SDFGI Store");
// store
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_STORE]);
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->cascades[cascade].sdf_store_uniform_set, 0);
RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, 4, 4, 4);
RD::get_singleton()->compute_list_end();
//clear these textures, as they will have previous garbage on next draw
RD::get_singleton()->texture_clear(rb->sdfgi->cascades[cascade].light_tex, Color(0, 0, 0, 0), 0, 1, 0, 1, true);
RD::get_singleton()->texture_clear(rb->sdfgi->cascades[cascade].light_aniso_0_tex, Color(0, 0, 0, 0), 0, 1, 0, 1, true);
RD::get_singleton()->texture_clear(rb->sdfgi->cascades[cascade].light_aniso_1_tex, Color(0, 0, 0, 0), 0, 1, 0, 1, true);
#if 0
Vector<uint8_t> data = RD::get_singleton()->texture_get_data(rb->sdfgi->cascades[cascade].sdf, 0);
Ref<Image> img;
img.instance();
for (uint32_t i = 0; i < rb->sdfgi->cascade_size; i++) {
Vector<uint8_t> subarr = data.subarray(128 * 128 * i, 128 * 128 * (i + 1) - 1);
img->create(rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, false, Image::FORMAT_L8, subarr);
img->save_png("res://cascade_sdf_" + itos(cascade) + "_" + itos(i) + ".png");
}
//finalize render and update sdf
#endif
#if 0
Vector<uint8_t> data = RD::get_singleton()->texture_get_data(rb->sdfgi->render_albedo, 0);
Ref<Image> img;
img.instance();
for (uint32_t i = 0; i < rb->sdfgi->cascade_size; i++) {
Vector<uint8_t> subarr = data.subarray(128 * 128 * i * 2, 128 * 128 * (i + 1) * 2 - 1);
img->create(rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, false, Image::FORMAT_RGB565, subarr);
img->convert(Image::FORMAT_RGBA8);
img->save_png("res://cascade_" + itos(cascade) + "_" + itos(i) + ".png");
}
//finalize render and update sdf
#endif
RENDER_TIMESTAMP("<SDFGI Update SDF");
}
}
void RasterizerSceneRD::render_particle_collider_heightfield(RID p_collider, const Transform &p_transform, InstanceBase **p_cull_result, int p_cull_count) {
ERR_FAIL_COND(!storage->particles_collision_is_heightfield(p_collider));
Vector3 extents = storage->particles_collision_get_extents(p_collider) * p_transform.basis.get_scale();
CameraMatrix cm;
cm.set_orthogonal(-extents.x, extents.x, -extents.z, extents.z, 0, extents.y * 2.0);
Vector3 cam_pos = p_transform.origin;
cam_pos.y += extents.y;
Transform cam_xform;
cam_xform.set_look_at(cam_pos, cam_pos - p_transform.basis.get_axis(Vector3::AXIS_Y), -p_transform.basis.get_axis(Vector3::AXIS_Z).normalized());
RID fb = storage->particles_collision_get_heightfield_framebuffer(p_collider);
_render_particle_collider_heightfield(fb, cam_xform, cm, p_cull_result, p_cull_count);
}
void RasterizerSceneRD::render_sdfgi_static_lights(RID p_render_buffers, uint32_t p_cascade_count, const uint32_t *p_cascade_indices, const RID **p_positional_light_cull_result, const uint32_t *p_positional_light_cull_count) {
RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
ERR_FAIL_COND(!rb);
ERR_FAIL_COND(!rb->sdfgi);
ERR_FAIL_COND(p_positional_light_cull_count == 0);
_sdfgi_update_cascades(p_render_buffers); //need cascades updated for this
RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.direct_light_pipeline[SDGIShader::DIRECT_LIGHT_MODE_STATIC]);
SDGIShader::DirectLightPushConstant dl_push_constant;
dl_push_constant.grid_size[0] = rb->sdfgi->cascade_size;
dl_push_constant.grid_size[1] = rb->sdfgi->cascade_size;
dl_push_constant.grid_size[2] = rb->sdfgi->cascade_size;
dl_push_constant.max_cascades = rb->sdfgi->cascades.size();
dl_push_constant.probe_axis_size = rb->sdfgi->probe_axis_count;
dl_push_constant.multibounce = false; // this is static light, do not multibounce yet
dl_push_constant.y_mult = rb->sdfgi->y_mult;
//all must be processed
dl_push_constant.process_offset = 0;
dl_push_constant.process_increment = 1;
SDGIShader::Light lights[SDFGI::MAX_STATIC_LIGHTS];
for (uint32_t i = 0; i < p_cascade_count; i++) {
ERR_CONTINUE(p_cascade_indices[i] >= rb->sdfgi->cascades.size());
SDFGI::Cascade &cc = rb->sdfgi->cascades[p_cascade_indices[i]];
{ //fill light buffer
AABB cascade_aabb;
cascade_aabb.position = Vector3((Vector3i(1, 1, 1) * -int32_t(rb->sdfgi->cascade_size >> 1) + cc.position)) * cc.cell_size;
cascade_aabb.size = Vector3(1, 1, 1) * rb->sdfgi->cascade_size * cc.cell_size;
int idx = 0;
for (uint32_t j = 0; j < p_positional_light_cull_count[i]; j++) {
if (idx == SDFGI::MAX_STATIC_LIGHTS) {
break;
}
LightInstance *li = light_instance_owner.getornull(p_positional_light_cull_result[i][j]);
ERR_CONTINUE(!li);
uint32_t max_sdfgi_cascade = storage->light_get_max_sdfgi_cascade(li->light);
if (p_cascade_indices[i] > max_sdfgi_cascade) {
continue;
}
if (!cascade_aabb.intersects(li->aabb)) {
continue;
}
lights[idx].type = storage->light_get_type(li->light);
Vector3 dir = -li->transform.basis.get_axis(Vector3::AXIS_Z);
if (lights[idx].type == RS::LIGHT_DIRECTIONAL) {
dir.y *= rb->sdfgi->y_mult; //only makes sense for directional
dir.normalize();
}
lights[idx].direction[0] = dir.x;
lights[idx].direction[1] = dir.y;
lights[idx].direction[2] = dir.z;
Vector3 pos = li->transform.origin;
pos.y *= rb->sdfgi->y_mult;
lights[idx].position[0] = pos.x;
lights[idx].position[1] = pos.y;
lights[idx].position[2] = pos.z;
Color color = storage->light_get_color(li->light);
color = color.to_linear();
lights[idx].color[0] = color.r;
lights[idx].color[1] = color.g;
lights[idx].color[2] = color.b;
lights[idx].energy = storage->light_get_param(li->light, RS::LIGHT_PARAM_ENERGY);
lights[idx].has_shadow = storage->light_has_shadow(li->light);
lights[idx].attenuation = storage->light_get_param(li->light, RS::LIGHT_PARAM_ATTENUATION);
lights[idx].radius = storage->light_get_param(li->light, RS::LIGHT_PARAM_RANGE);
lights[idx].spot_angle = Math::deg2rad(storage->light_get_param(li->light, RS::LIGHT_PARAM_SPOT_ANGLE));
lights[idx].spot_attenuation = storage->light_get_param(li->light, RS::LIGHT_PARAM_SPOT_ATTENUATION);
idx++;
}
if (idx > 0) {
RD::get_singleton()->buffer_update(cc.lights_buffer, 0, idx * sizeof(SDGIShader::Light), lights, true);
}
dl_push_constant.light_count = idx;
}
dl_push_constant.cascade = p_cascade_indices[i];
if (dl_push_constant.light_count > 0) {
RD::get_singleton()->compute_list_bind_uniform_set(compute_list, cc.sdf_direct_light_uniform_set, 0);
RD::get_singleton()->compute_list_set_push_constant(compute_list, &dl_push_constant, sizeof(SDGIShader::DirectLightPushConstant));
RD::get_singleton()->compute_list_dispatch_indirect(compute_list, cc.solid_cell_dispatch_buffer, 0);
}
}
RD::get_singleton()->compute_list_end();
}
bool RasterizerSceneRD::free(RID p_rid) {
if (render_buffers_owner.owns(p_rid)) {
RenderBuffers *rb = render_buffers_owner.getornull(p_rid);
_free_render_buffer_data(rb);
memdelete(rb->data);
if (rb->sdfgi) {
_sdfgi_erase(rb);
}
if (rb->volumetric_fog) {
_volumetric_fog_erase(rb);
}
render_buffers_owner.free(p_rid);
} else if (environment_owner.owns(p_rid)) {
//not much to delete, just free it
environment_owner.free(p_rid);
} else if (camera_effects_owner.owns(p_rid)) {
//not much to delete, just free it
camera_effects_owner.free(p_rid);
} else if (reflection_atlas_owner.owns(p_rid)) {
reflection_atlas_set_size(p_rid, 0, 0);
reflection_atlas_owner.free(p_rid);
} else if (reflection_probe_instance_owner.owns(p_rid)) {
//not much to delete, just free it
//ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_rid);
reflection_probe_release_atlas_index(p_rid);
reflection_probe_instance_owner.free(p_rid);
} else if (decal_instance_owner.owns(p_rid)) {
decal_instance_owner.free(p_rid);
} else if (gi_probe_instance_owner.owns(p_rid)) {
GIProbeInstance *gi_probe = gi_probe_instance_owner.getornull(p_rid);
if (gi_probe->texture.is_valid()) {
RD::get_singleton()->free(gi_probe->texture);
RD::get_singleton()->free(gi_probe->write_buffer);
}
for (int i = 0; i < gi_probe->dynamic_maps.size(); i++) {
RD::get_singleton()->free(gi_probe->dynamic_maps[i].texture);
RD::get_singleton()->free(gi_probe->dynamic_maps[i].depth);
}
gi_probe_instance_owner.free(p_rid);
} else if (sky_owner.owns(p_rid)) {
_update_dirty_skys();
Sky *sky = sky_owner.getornull(p_rid);
if (sky->radiance.is_valid()) {
RD::get_singleton()->free(sky->radiance);
sky->radiance = RID();
}
_clear_reflection_data(sky->reflection);
if (sky->uniform_buffer.is_valid()) {
RD::get_singleton()->free(sky->uniform_buffer);
sky->uniform_buffer = RID();
}
if (sky->half_res_pass.is_valid()) {
RD::get_singleton()->free(sky->half_res_pass);
sky->half_res_pass = RID();
}
if (sky->quarter_res_pass.is_valid()) {
RD::get_singleton()->free(sky->quarter_res_pass);
sky->quarter_res_pass = RID();
}
if (sky->material.is_valid()) {
storage->free(sky->material);
}
sky_owner.free(p_rid);
} else if (light_instance_owner.owns(p_rid)) {
LightInstance *light_instance = light_instance_owner.getornull(p_rid);
//remove from shadow atlases..
for (Set<RID>::Element *E = light_instance->shadow_atlases.front(); E; E = E->next()) {
ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(E->get());
ERR_CONTINUE(!shadow_atlas->shadow_owners.has(p_rid));
uint32_t key = shadow_atlas->shadow_owners[p_rid];
uint32_t q = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x3;
uint32_t s = key & ShadowAtlas::SHADOW_INDEX_MASK;
shadow_atlas->quadrants[q].shadows.write[s].owner = RID();
shadow_atlas->shadow_owners.erase(p_rid);
}
light_instance_owner.free(p_rid);
} else if (shadow_atlas_owner.owns(p_rid)) {
shadow_atlas_set_size(p_rid, 0);
shadow_atlas_owner.free(p_rid);
} else {
return false;
}
return true;
}
void RasterizerSceneRD::set_debug_draw_mode(RS::ViewportDebugDraw p_debug_draw) {
debug_draw = p_debug_draw;
}
void RasterizerSceneRD::update() {
_update_dirty_skys();
}
void RasterizerSceneRD::set_time(double p_time, double p_step) {
time = p_time;
time_step = p_step;
}
void RasterizerSceneRD::screen_space_roughness_limiter_set_active(bool p_enable, float p_amount, float p_limit) {
screen_space_roughness_limiter = p_enable;
screen_space_roughness_limiter_amount = p_amount;
screen_space_roughness_limiter_limit = p_limit;
}
bool RasterizerSceneRD::screen_space_roughness_limiter_is_active() const {
return screen_space_roughness_limiter;
}
float RasterizerSceneRD::screen_space_roughness_limiter_get_amount() const {
return screen_space_roughness_limiter_amount;
}
float RasterizerSceneRD::screen_space_roughness_limiter_get_limit() const {
return screen_space_roughness_limiter_limit;
}
TypedArray<Image> RasterizerSceneRD::bake_render_uv2(RID p_base, const Vector<RID> &p_material_overrides, const Size2i &p_image_size) {
RD::TextureFormat tf;
tf.format = RD::DATA_FORMAT_R8G8B8A8_UNORM;
tf.width = p_image_size.width; // Always 64x64
tf.height = p_image_size.height;
tf.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT;
RID albedo_alpha_tex = RD::get_singleton()->texture_create(tf, RD::TextureView());
RID normal_tex = RD::get_singleton()->texture_create(tf, RD::TextureView());
RID orm_tex = RD::get_singleton()->texture_create(tf, RD::TextureView());
tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
RID emission_tex = RD::get_singleton()->texture_create(tf, RD::TextureView());
tf.format = RD::DATA_FORMAT_R32_SFLOAT;
RID depth_write_tex = RD::get_singleton()->texture_create(tf, RD::TextureView());
tf.usage_bits = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT;
tf.format = RD::get_singleton()->texture_is_format_supported_for_usage(RD::DATA_FORMAT_D32_SFLOAT, RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) ? RD::DATA_FORMAT_D32_SFLOAT : RD::DATA_FORMAT_X8_D24_UNORM_PACK32;
RID depth_tex = RD::get_singleton()->texture_create(tf, RD::TextureView());
Vector<RID> fb_tex;
fb_tex.push_back(albedo_alpha_tex);
fb_tex.push_back(normal_tex);
fb_tex.push_back(orm_tex);
fb_tex.push_back(emission_tex);
fb_tex.push_back(depth_write_tex);
fb_tex.push_back(depth_tex);
RID fb = RD::get_singleton()->framebuffer_create(fb_tex);
//RID sampled_light;
InstanceBase ins;
ins.base_type = RSG::storage->get_base_type(p_base);
ins.base = p_base;
ins.materials.resize(RSG::storage->mesh_get_surface_count(p_base));
for (int i = 0; i < ins.materials.size(); i++) {
if (i < p_material_overrides.size()) {
ins.materials.write[i] = p_material_overrides[i];
}
}
InstanceBase *cull = &ins;
_render_uv2(&cull, 1, fb, Rect2i(0, 0, p_image_size.width, p_image_size.height));
TypedArray<Image> ret;
{
PackedByteArray data = RD::get_singleton()->texture_get_data(albedo_alpha_tex, 0);
Ref<Image> img;
img.instance();
img->create(p_image_size.width, p_image_size.height, false, Image::FORMAT_RGBA8, data);
RD::get_singleton()->free(albedo_alpha_tex);
ret.push_back(img);
}
{
PackedByteArray data = RD::get_singleton()->texture_get_data(normal_tex, 0);
Ref<Image> img;
img.instance();
img->create(p_image_size.width, p_image_size.height, false, Image::FORMAT_RGBA8, data);
RD::get_singleton()->free(normal_tex);
ret.push_back(img);
}
{
PackedByteArray data = RD::get_singleton()->texture_get_data(orm_tex, 0);
Ref<Image> img;
img.instance();
img->create(p_image_size.width, p_image_size.height, false, Image::FORMAT_RGBA8, data);
RD::get_singleton()->free(orm_tex);
ret.push_back(img);
}
{
PackedByteArray data = RD::get_singleton()->texture_get_data(emission_tex, 0);
Ref<Image> img;
img.instance();
img->create(p_image_size.width, p_image_size.height, false, Image::FORMAT_RGBAH, data);
RD::get_singleton()->free(emission_tex);
ret.push_back(img);
}
RD::get_singleton()->free(depth_write_tex);
RD::get_singleton()->free(depth_tex);
return ret;
}
void RasterizerSceneRD::sdfgi_set_debug_probe_select(const Vector3 &p_position, const Vector3 &p_dir) {
sdfgi_debug_probe_pos = p_position;
sdfgi_debug_probe_dir = p_dir;
}
RasterizerSceneRD *RasterizerSceneRD::singleton = nullptr;
RID RasterizerSceneRD::get_cluster_builder_texture() {
return cluster.builder.get_cluster_texture();
}
RID RasterizerSceneRD::get_cluster_builder_indices_buffer() {
return cluster.builder.get_cluster_indices_buffer();
}
RID RasterizerSceneRD::get_reflection_probe_buffer() {
return cluster.reflection_buffer;
}
RID RasterizerSceneRD::get_positional_light_buffer() {
return cluster.light_buffer;
}
RID RasterizerSceneRD::get_directional_light_buffer() {
return cluster.directional_light_buffer;
}
RID RasterizerSceneRD::get_decal_buffer() {
return cluster.decal_buffer;
}
int RasterizerSceneRD::get_max_directional_lights() const {
return cluster.max_directional_lights;
}
RasterizerSceneRD::RasterizerSceneRD(RasterizerStorageRD *p_storage) {
storage = p_storage;
singleton = this;
roughness_layers = GLOBAL_GET("rendering/quality/reflections/roughness_layers");
sky_ggx_samples_quality = GLOBAL_GET("rendering/quality/reflections/ggx_samples");
sky_use_cubemap_array = GLOBAL_GET("rendering/quality/reflections/texture_array_reflections");
// sky_use_cubemap_array = false;
//uint32_t textures_per_stage = RD::get_singleton()->limit_get(RD::LIMIT_MAX_TEXTURES_PER_SHADER_STAGE);
{
//kinda complicated to compute the amount of slots, we try to use as many as we can
gi_probe_max_lights = 32;
gi_probe_lights = memnew_arr(GIProbeLight, gi_probe_max_lights);
gi_probe_lights_uniform = RD::get_singleton()->uniform_buffer_create(gi_probe_max_lights * sizeof(GIProbeLight));
gi_probe_quality = RS::GIProbeQuality(CLAMP(int(GLOBAL_GET("rendering/quality/gi_probes/quality")), 0, 1));
String defines = "\n#define MAX_LIGHTS " + itos(gi_probe_max_lights) + "\n";
Vector<String> versions;
versions.push_back("\n#define MODE_COMPUTE_LIGHT\n");
versions.push_back("\n#define MODE_SECOND_BOUNCE\n");
versions.push_back("\n#define MODE_UPDATE_MIPMAPS\n");
versions.push_back("\n#define MODE_WRITE_TEXTURE\n");
versions.push_back("\n#define MODE_DYNAMIC\n#define MODE_DYNAMIC_LIGHTING\n");
versions.push_back("\n#define MODE_DYNAMIC\n#define MODE_DYNAMIC_SHRINK\n#define MODE_DYNAMIC_SHRINK_WRITE\n");
versions.push_back("\n#define MODE_DYNAMIC\n#define MODE_DYNAMIC_SHRINK\n#define MODE_DYNAMIC_SHRINK_PLOT\n");
versions.push_back("\n#define MODE_DYNAMIC\n#define MODE_DYNAMIC_SHRINK\n#define MODE_DYNAMIC_SHRINK_PLOT\n#define MODE_DYNAMIC_SHRINK_WRITE\n");
giprobe_shader.initialize(versions, defines);
giprobe_lighting_shader_version = giprobe_shader.version_create();
for (int i = 0; i < GI_PROBE_SHADER_VERSION_MAX; i++) {
giprobe_lighting_shader_version_shaders[i] = giprobe_shader.version_get_shader(giprobe_lighting_shader_version, i);
giprobe_lighting_shader_version_pipelines[i] = RD::get_singleton()->compute_pipeline_create(giprobe_lighting_shader_version_shaders[i]);
}
}
{
String defines;
Vector<String> versions;
versions.push_back("\n#define MODE_DEBUG_COLOR\n");
versions.push_back("\n#define MODE_DEBUG_LIGHT\n");
versions.push_back("\n#define MODE_DEBUG_EMISSION\n");
versions.push_back("\n#define MODE_DEBUG_LIGHT\n#define MODE_DEBUG_LIGHT_FULL\n");
giprobe_debug_shader.initialize(versions, defines);
giprobe_debug_shader_version = giprobe_debug_shader.version_create();
for (int i = 0; i < GI_PROBE_DEBUG_MAX; i++) {
giprobe_debug_shader_version_shaders[i] = giprobe_debug_shader.version_get_shader(giprobe_debug_shader_version, i);
RD::PipelineRasterizationState rs;
rs.cull_mode = RD::POLYGON_CULL_FRONT;
RD::PipelineDepthStencilState ds;
ds.enable_depth_test = true;
ds.enable_depth_write = true;
ds.depth_compare_operator = RD::COMPARE_OP_LESS_OR_EQUAL;
giprobe_debug_shader_version_pipelines[i].setup(giprobe_debug_shader_version_shaders[i], RD::RENDER_PRIMITIVE_TRIANGLES, rs, RD::PipelineMultisampleState(), ds, RD::PipelineColorBlendState::create_disabled(), 0);
}
}
/* SKY SHADER */
{
// Start with the directional lights for the sky
sky_scene_state.max_directional_lights = 4;
uint32_t directional_light_buffer_size = sky_scene_state.max_directional_lights * sizeof(SkyDirectionalLightData);
sky_scene_state.directional_lights = memnew_arr(SkyDirectionalLightData, sky_scene_state.max_directional_lights);
sky_scene_state.last_frame_directional_lights = memnew_arr(SkyDirectionalLightData, sky_scene_state.max_directional_lights);
sky_scene_state.last_frame_directional_light_count = sky_scene_state.max_directional_lights + 1;
sky_scene_state.directional_light_buffer = RD::get_singleton()->uniform_buffer_create(directional_light_buffer_size);
String defines = "\n#define MAX_DIRECTIONAL_LIGHT_DATA_STRUCTS " + itos(sky_scene_state.max_directional_lights) + "\n";
// Initialize sky
Vector<String> sky_modes;
sky_modes.push_back(""); // Full size
sky_modes.push_back("\n#define USE_HALF_RES_PASS\n"); // Half Res
sky_modes.push_back("\n#define USE_QUARTER_RES_PASS\n"); // Quarter res
sky_modes.push_back("\n#define USE_CUBEMAP_PASS\n"); // Cubemap
sky_modes.push_back("\n#define USE_CUBEMAP_PASS\n#define USE_HALF_RES_PASS\n"); // Half Res Cubemap
sky_modes.push_back("\n#define USE_CUBEMAP_PASS\n#define USE_QUARTER_RES_PASS\n"); // Quarter res Cubemap
sky_shader.shader.initialize(sky_modes, defines);
}
// register our shader funds
storage->shader_set_data_request_function(RasterizerStorageRD::SHADER_TYPE_SKY, _create_sky_shader_funcs);
storage->material_set_data_request_function(RasterizerStorageRD::SHADER_TYPE_SKY, _create_sky_material_funcs);
{
ShaderCompilerRD::DefaultIdentifierActions actions;
actions.renames["COLOR"] = "color";
actions.renames["ALPHA"] = "alpha";
actions.renames["EYEDIR"] = "cube_normal";
actions.renames["POSITION"] = "params.position_multiplier.xyz";
actions.renames["SKY_COORDS"] = "panorama_coords";
actions.renames["SCREEN_UV"] = "uv";
actions.renames["TIME"] = "params.time";
actions.renames["HALF_RES_COLOR"] = "half_res_color";
actions.renames["QUARTER_RES_COLOR"] = "quarter_res_color";
actions.renames["RADIANCE"] = "radiance";
actions.renames["FOG"] = "custom_fog";
actions.renames["LIGHT0_ENABLED"] = "directional_lights.data[0].enabled";
actions.renames["LIGHT0_DIRECTION"] = "directional_lights.data[0].direction_energy.xyz";
actions.renames["LIGHT0_ENERGY"] = "directional_lights.data[0].direction_energy.w";
actions.renames["LIGHT0_COLOR"] = "directional_lights.data[0].color_size.xyz";
actions.renames["LIGHT0_SIZE"] = "directional_lights.data[0].color_size.w";
actions.renames["LIGHT1_ENABLED"] = "directional_lights.data[1].enabled";
actions.renames["LIGHT1_DIRECTION"] = "directional_lights.data[1].direction_energy.xyz";
actions.renames["LIGHT1_ENERGY"] = "directional_lights.data[1].direction_energy.w";
actions.renames["LIGHT1_COLOR"] = "directional_lights.data[1].color_size.xyz";
actions.renames["LIGHT1_SIZE"] = "directional_lights.data[1].color_size.w";
actions.renames["LIGHT2_ENABLED"] = "directional_lights.data[2].enabled";
actions.renames["LIGHT2_DIRECTION"] = "directional_lights.data[2].direction_energy.xyz";
actions.renames["LIGHT2_ENERGY"] = "directional_lights.data[2].direction_energy.w";
actions.renames["LIGHT2_COLOR"] = "directional_lights.data[2].color_size.xyz";
actions.renames["LIGHT2_SIZE"] = "directional_lights.data[2].color_size.w";
actions.renames["LIGHT3_ENABLED"] = "directional_lights.data[3].enabled";
actions.renames["LIGHT3_DIRECTION"] = "directional_lights.data[3].direction_energy.xyz";
actions.renames["LIGHT3_ENERGY"] = "directional_lights.data[3].direction_energy.w";
actions.renames["LIGHT3_COLOR"] = "directional_lights.data[3].color_size.xyz";
actions.renames["LIGHT3_SIZE"] = "directional_lights.data[3].color_size.w";
actions.renames["AT_CUBEMAP_PASS"] = "AT_CUBEMAP_PASS";
actions.renames["AT_HALF_RES_PASS"] = "AT_HALF_RES_PASS";
actions.renames["AT_QUARTER_RES_PASS"] = "AT_QUARTER_RES_PASS";
actions.custom_samplers["RADIANCE"] = "material_samplers[3]";
actions.usage_defines["HALF_RES_COLOR"] = "\n#define USES_HALF_RES_COLOR\n";
actions.usage_defines["QUARTER_RES_COLOR"] = "\n#define USES_QUARTER_RES_COLOR\n";
actions.render_mode_defines["disable_fog"] = "#define DISABLE_FOG\n";
actions.sampler_array_name = "material_samplers";
actions.base_texture_binding_index = 1;
actions.texture_layout_set = 1;
actions.base_uniform_string = "material.";
actions.base_varying_index = 10;
actions.default_filter = ShaderLanguage::FILTER_LINEAR_MIPMAP;
actions.default_repeat = ShaderLanguage::REPEAT_ENABLE;
actions.global_buffer_array_variable = "global_variables.data";
sky_shader.compiler.initialize(actions);
}
{
// default material and shader for sky shader
sky_shader.default_shader = storage->shader_create();
storage->shader_set_code(sky_shader.default_shader, "shader_type sky; void fragment() { COLOR = vec3(0.0); } \n");
sky_shader.default_material = storage->material_create();
storage->material_set_shader(sky_shader.default_material, sky_shader.default_shader);
SkyMaterialData *md = (SkyMaterialData *)storage->material_get_data(sky_shader.default_material, RasterizerStorageRD::SHADER_TYPE_SKY);
sky_shader.default_shader_rd = sky_shader.shader.version_get_shader(md->shader_data->version, SKY_VERSION_BACKGROUND);
sky_scene_state.uniform_buffer = RD::get_singleton()->uniform_buffer_create(sizeof(SkySceneState::UBO));
Vector<RD::Uniform> uniforms;
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_SAMPLER;
u.binding = 0;
u.ids.resize(12);
RID *ids_ptr = u.ids.ptrw();
ids_ptr[0] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
ids_ptr[1] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
ids_ptr[2] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
ids_ptr[3] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
ids_ptr[4] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS_ANISOTROPIC, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
ids_ptr[5] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS_ANISOTROPIC, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
ids_ptr[6] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
ids_ptr[7] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
ids_ptr[8] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
ids_ptr[9] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
ids_ptr[10] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS_ANISOTROPIC, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
ids_ptr[11] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS_ANISOTROPIC, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
u.binding = 1;
u.ids.push_back(storage->global_variables_get_storage_buffer());
uniforms.push_back(u);
}
{
RD::Uniform u;
u.binding = 2;
u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
u.ids.push_back(sky_scene_state.uniform_buffer);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.binding = 3;
u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
u.ids.push_back(sky_scene_state.directional_light_buffer);
uniforms.push_back(u);
}
sky_scene_state.uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sky_shader.default_shader_rd, SKY_SET_UNIFORMS);
}
{
Vector<RD::Uniform> uniforms;
{
RD::Uniform u;
u.binding = 0;
u.type = RD::UNIFORM_TYPE_TEXTURE;
RID vfog = storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE);
u.ids.push_back(vfog);
uniforms.push_back(u);
}
sky_scene_state.default_fog_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sky_shader.default_shader_rd, SKY_SET_FOG);
}
{
// Need defaults for using fog with clear color
sky_scene_state.fog_shader = storage->shader_create();
storage->shader_set_code(sky_scene_state.fog_shader, "shader_type sky; uniform vec4 clear_color; void fragment() { COLOR = clear_color.rgb; } \n");
sky_scene_state.fog_material = storage->material_create();
storage->material_set_shader(sky_scene_state.fog_material, sky_scene_state.fog_shader);
Vector<RD::Uniform> uniforms;
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 0;
u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_CUBEMAP_BLACK));
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 1;
u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_WHITE));
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 2;
u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_WHITE));
uniforms.push_back(u);
}
sky_scene_state.fog_only_texture_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sky_shader.default_shader_rd, SKY_SET_TEXTURES);
}
{
Vector<String> preprocess_modes;
preprocess_modes.push_back("\n#define MODE_SCROLL\n");
preprocess_modes.push_back("\n#define MODE_SCROLL_OCCLUSION\n");
preprocess_modes.push_back("\n#define MODE_INITIALIZE_JUMP_FLOOD\n");
preprocess_modes.push_back("\n#define MODE_INITIALIZE_JUMP_FLOOD_HALF\n");
preprocess_modes.push_back("\n#define MODE_JUMPFLOOD\n");
preprocess_modes.push_back("\n#define MODE_JUMPFLOOD_OPTIMIZED\n");
preprocess_modes.push_back("\n#define MODE_UPSCALE_JUMP_FLOOD\n");
preprocess_modes.push_back("\n#define MODE_OCCLUSION\n");
preprocess_modes.push_back("\n#define MODE_STORE\n");
String defines = "\n#define OCCLUSION_SIZE " + itos(SDFGI::CASCADE_SIZE / SDFGI::PROBE_DIVISOR) + "\n";
sdfgi_shader.preprocess.initialize(preprocess_modes, defines);
sdfgi_shader.preprocess_shader = sdfgi_shader.preprocess.version_create();
for (int i = 0; i < SDGIShader::PRE_PROCESS_MAX; i++) {
sdfgi_shader.preprocess_pipeline[i] = RD::get_singleton()->compute_pipeline_create(sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, i));
}
}
{
//calculate tables
String defines = "\n#define OCT_SIZE " + itos(SDFGI::LIGHTPROBE_OCT_SIZE) + "\n";
Vector<String> direct_light_modes;
direct_light_modes.push_back("\n#define MODE_PROCESS_STATIC\n");
direct_light_modes.push_back("\n#define MODE_PROCESS_DYNAMIC\n");
sdfgi_shader.direct_light.initialize(direct_light_modes, defines);
sdfgi_shader.direct_light_shader = sdfgi_shader.direct_light.version_create();
for (int i = 0; i < SDGIShader::DIRECT_LIGHT_MODE_MAX; i++) {
sdfgi_shader.direct_light_pipeline[i] = RD::get_singleton()->compute_pipeline_create(sdfgi_shader.direct_light.version_get_shader(sdfgi_shader.direct_light_shader, i));
}
}
{
//calculate tables
String defines = "\n#define OCT_SIZE " + itos(SDFGI::LIGHTPROBE_OCT_SIZE) + "\n";
defines += "\n#define SH_SIZE " + itos(SDFGI::SH_SIZE) + "\n";
Vector<String> integrate_modes;
integrate_modes.push_back("\n#define MODE_PROCESS\n");
integrate_modes.push_back("\n#define MODE_STORE\n");
integrate_modes.push_back("\n#define MODE_SCROLL\n");
integrate_modes.push_back("\n#define MODE_SCROLL_STORE\n");
sdfgi_shader.integrate.initialize(integrate_modes, defines);
sdfgi_shader.integrate_shader = sdfgi_shader.integrate.version_create();
for (int i = 0; i < SDGIShader::INTEGRATE_MODE_MAX; i++) {
sdfgi_shader.integrate_pipeline[i] = RD::get_singleton()->compute_pipeline_create(sdfgi_shader.integrate.version_get_shader(sdfgi_shader.integrate_shader, i));
}
{
Vector<RD::Uniform> uniforms;
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 0;
u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_SAMPLER;
u.binding = 1;
u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
uniforms.push_back(u);
}
sdfgi_shader.integrate_default_sky_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.integrate.version_get_shader(sdfgi_shader.integrate_shader, 0), 1);
}
}
{
//calculate tables
String defines = "\n#define SDFGI_OCT_SIZE " + itos(SDFGI::LIGHTPROBE_OCT_SIZE) + "\n";
Vector<String> gi_modes;
gi_modes.push_back("");
gi.shader.initialize(gi_modes, defines);
gi.shader_version = gi.shader.version_create();
for (int i = 0; i < GI::MODE_MAX; i++) {
gi.pipelines[i] = RD::get_singleton()->compute_pipeline_create(gi.shader.version_get_shader(gi.shader_version, i));
}
gi.sdfgi_ubo = RD::get_singleton()->uniform_buffer_create(sizeof(GI::SDFGIData));
}
{
String defines = "\n#define OCT_SIZE " + itos(SDFGI::LIGHTPROBE_OCT_SIZE) + "\n";
Vector<String> debug_modes;
debug_modes.push_back("");
sdfgi_shader.debug.initialize(debug_modes, defines);
sdfgi_shader.debug_shader = sdfgi_shader.debug.version_create();
sdfgi_shader.debug_shader_version = sdfgi_shader.debug.version_get_shader(sdfgi_shader.debug_shader, 0);
sdfgi_shader.debug_pipeline = RD::get_singleton()->compute_pipeline_create(sdfgi_shader.debug_shader_version);
}
{
String defines = "\n#define OCT_SIZE " + itos(SDFGI::LIGHTPROBE_OCT_SIZE) + "\n";
Vector<String> versions;
versions.push_back("\n#define MODE_PROBES\n");
versions.push_back("\n#define MODE_VISIBILITY\n");
sdfgi_shader.debug_probes.initialize(versions, defines);
sdfgi_shader.debug_probes_shader = sdfgi_shader.debug_probes.version_create();
{
RD::PipelineRasterizationState rs;
rs.cull_mode = RD::POLYGON_CULL_DISABLED;
RD::PipelineDepthStencilState ds;
ds.enable_depth_test = true;
ds.enable_depth_write = true;
ds.depth_compare_operator = RD::COMPARE_OP_LESS_OR_EQUAL;
for (int i = 0; i < SDGIShader::PROBE_DEBUG_MAX; i++) {
RID debug_probes_shader_version = sdfgi_shader.debug_probes.version_get_shader(sdfgi_shader.debug_probes_shader, i);
sdfgi_shader.debug_probes_pipeline[i].setup(debug_probes_shader_version, RD::RENDER_PRIMITIVE_TRIANGLE_STRIPS, rs, RD::PipelineMultisampleState(), ds, RD::PipelineColorBlendState::create_disabled(), 0);
}
}
}
//cluster setup
uint32_t uniform_max_size = RD::get_singleton()->limit_get(RD::LIMIT_MAX_UNIFORM_BUFFER_SIZE);
{ //reflections
uint32_t reflection_buffer_size;
if (uniform_max_size < 65536) {
//Yes, you guessed right, ARM again
reflection_buffer_size = uniform_max_size;
} else {
reflection_buffer_size = 65536;
}
cluster.max_reflections = reflection_buffer_size / sizeof(Cluster::ReflectionData);
cluster.reflections = memnew_arr(Cluster::ReflectionData, cluster.max_reflections);
cluster.reflection_buffer = RD::get_singleton()->storage_buffer_create(reflection_buffer_size);
}
{ //lights
cluster.max_lights = MIN(1024 * 1024, uniform_max_size) / sizeof(Cluster::LightData); //1mb of lights
uint32_t light_buffer_size = cluster.max_lights * sizeof(Cluster::LightData);
cluster.lights = memnew_arr(Cluster::LightData, cluster.max_lights);
cluster.light_buffer = RD::get_singleton()->storage_buffer_create(light_buffer_size);
//defines += "\n#define MAX_LIGHT_DATA_STRUCTS " + itos(cluster.max_lights) + "\n";
cluster.lights_instances = memnew_arr(RID, cluster.max_lights);
cluster.lights_shadow_rect_cache = memnew_arr(Rect2i, cluster.max_lights);
cluster.max_directional_lights = 8;
uint32_t directional_light_buffer_size = cluster.max_directional_lights * sizeof(Cluster::DirectionalLightData);
cluster.directional_lights = memnew_arr(Cluster::DirectionalLightData, cluster.max_directional_lights);
cluster.directional_light_buffer = RD::get_singleton()->uniform_buffer_create(directional_light_buffer_size);
}
{ //decals
cluster.max_decals = MIN(1024 * 1024, uniform_max_size) / sizeof(Cluster::DecalData); //1mb of decals
uint32_t decal_buffer_size = cluster.max_decals * sizeof(Cluster::DecalData);
cluster.decals = memnew_arr(Cluster::DecalData, cluster.max_decals);
cluster.decal_buffer = RD::get_singleton()->storage_buffer_create(decal_buffer_size);
}
cluster.builder.setup(16, 8, 24);
{
String defines = "\n#define MAX_DIRECTIONAL_LIGHT_DATA_STRUCTS " + itos(cluster.max_directional_lights) + "\n";
Vector<String> volumetric_fog_modes;
volumetric_fog_modes.push_back("\n#define MODE_DENSITY\n");
volumetric_fog_modes.push_back("\n#define MODE_DENSITY\n#define ENABLE_SDFGI\n");
volumetric_fog_modes.push_back("\n#define MODE_FILTER\n");
volumetric_fog_modes.push_back("\n#define MODE_FOG\n");
volumetric_fog.shader.initialize(volumetric_fog_modes, defines);
volumetric_fog.shader_version = volumetric_fog.shader.version_create();
for (int i = 0; i < VOLUMETRIC_FOG_SHADER_MAX; i++) {
volumetric_fog.pipelines[i] = RD::get_singleton()->compute_pipeline_create(volumetric_fog.shader.version_get_shader(volumetric_fog.shader_version, i));
}
}
default_giprobe_buffer = RD::get_singleton()->uniform_buffer_create(sizeof(GI::GIProbeData) * RenderBuffers::MAX_GIPROBES);
{
RD::SamplerState sampler;
sampler.mag_filter = RD::SAMPLER_FILTER_LINEAR;
sampler.min_filter = RD::SAMPLER_FILTER_LINEAR;
sampler.enable_compare = true;
sampler.compare_op = RD::COMPARE_OP_LESS;
shadow_sampler = RD::get_singleton()->sampler_create(sampler);
}
camera_effects_set_dof_blur_bokeh_shape(RS::DOFBokehShape(int(GLOBAL_GET("rendering/quality/depth_of_field/depth_of_field_bokeh_shape"))));
camera_effects_set_dof_blur_quality(RS::DOFBlurQuality(int(GLOBAL_GET("rendering/quality/depth_of_field/depth_of_field_bokeh_quality"))), GLOBAL_GET("rendering/quality/depth_of_field/depth_of_field_use_jitter"));
environment_set_ssao_quality(RS::EnvironmentSSAOQuality(int(GLOBAL_GET("rendering/quality/ssao/quality"))), GLOBAL_GET("rendering/quality/ssao/half_size"));
screen_space_roughness_limiter = GLOBAL_GET("rendering/quality/screen_filters/screen_space_roughness_limiter_enabled");
screen_space_roughness_limiter_amount = GLOBAL_GET("rendering/quality/screen_filters/screen_space_roughness_limiter_amount");
screen_space_roughness_limiter_limit = GLOBAL_GET("rendering/quality/screen_filters/screen_space_roughness_limiter_limit");
glow_bicubic_upscale = int(GLOBAL_GET("rendering/quality/glow/upscale_mode")) > 0;
glow_high_quality = GLOBAL_GET("rendering/quality/glow/use_high_quality");
ssr_roughness_quality = RS::EnvironmentSSRRoughnessQuality(int(GLOBAL_GET("rendering/quality/screen_space_reflection/roughness_quality")));
sss_quality = RS::SubSurfaceScatteringQuality(int(GLOBAL_GET("rendering/quality/subsurface_scattering/subsurface_scattering_quality")));
sss_scale = GLOBAL_GET("rendering/quality/subsurface_scattering/subsurface_scattering_scale");
sss_depth_scale = GLOBAL_GET("rendering/quality/subsurface_scattering/subsurface_scattering_depth_scale");
directional_penumbra_shadow_kernel = memnew_arr(float, 128);
directional_soft_shadow_kernel = memnew_arr(float, 128);
penumbra_shadow_kernel = memnew_arr(float, 128);
soft_shadow_kernel = memnew_arr(float, 128);
shadows_quality_set(RS::ShadowQuality(int(GLOBAL_GET("rendering/quality/shadows/soft_shadow_quality"))));
directional_shadow_quality_set(RS::ShadowQuality(int(GLOBAL_GET("rendering/quality/directional_shadow/soft_shadow_quality"))));
environment_set_volumetric_fog_volume_size(GLOBAL_GET("rendering/volumetric_fog/volume_size"), GLOBAL_GET("rendering/volumetric_fog/volume_depth"));
environment_set_volumetric_fog_filter_active(GLOBAL_GET("rendering/volumetric_fog/use_filter"));
environment_set_volumetric_fog_directional_shadow_shrink_size(GLOBAL_GET("rendering/volumetric_fog/directional_shadow_shrink"));
environment_set_volumetric_fog_positional_shadow_shrink_size(GLOBAL_GET("rendering/volumetric_fog/positional_shadow_shrink"));
}
RasterizerSceneRD::~RasterizerSceneRD() {
for (Map<Vector2i, ShadowMap>::Element *E = shadow_maps.front(); E; E = E->next()) {
RD::get_singleton()->free(E->get().depth);
}
for (Map<int, ShadowCubemap>::Element *E = shadow_cubemaps.front(); E; E = E->next()) {
RD::get_singleton()->free(E->get().cubemap);
}
if (sky_scene_state.uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(sky_scene_state.uniform_set)) {
RD::get_singleton()->free(sky_scene_state.uniform_set);
}
RD::get_singleton()->free(default_giprobe_buffer);
RD::get_singleton()->free(gi_probe_lights_uniform);
RD::get_singleton()->free(gi.sdfgi_ubo);
giprobe_debug_shader.version_free(giprobe_debug_shader_version);
giprobe_shader.version_free(giprobe_lighting_shader_version);
gi.shader.version_free(gi.shader_version);
sdfgi_shader.debug_probes.version_free(sdfgi_shader.debug_probes_shader);
sdfgi_shader.debug.version_free(sdfgi_shader.debug_shader);
sdfgi_shader.direct_light.version_free(sdfgi_shader.direct_light_shader);
sdfgi_shader.integrate.version_free(sdfgi_shader.integrate_shader);
sdfgi_shader.preprocess.version_free(sdfgi_shader.preprocess_shader);
volumetric_fog.shader.version_free(volumetric_fog.shader_version);
memdelete_arr(gi_probe_lights);
SkyMaterialData *md = (SkyMaterialData *)storage->material_get_data(sky_shader.default_material, RasterizerStorageRD::SHADER_TYPE_SKY);
sky_shader.shader.version_free(md->shader_data->version);
RD::get_singleton()->free(sky_scene_state.directional_light_buffer);
RD::get_singleton()->free(sky_scene_state.uniform_buffer);
memdelete_arr(sky_scene_state.directional_lights);
memdelete_arr(sky_scene_state.last_frame_directional_lights);
storage->free(sky_shader.default_shader);
storage->free(sky_shader.default_material);
storage->free(sky_scene_state.fog_shader);
storage->free(sky_scene_state.fog_material);
memdelete_arr(directional_penumbra_shadow_kernel);
memdelete_arr(directional_soft_shadow_kernel);
memdelete_arr(penumbra_shadow_kernel);
memdelete_arr(soft_shadow_kernel);
{
RD::get_singleton()->free(cluster.directional_light_buffer);
RD::get_singleton()->free(cluster.light_buffer);
RD::get_singleton()->free(cluster.reflection_buffer);
RD::get_singleton()->free(cluster.decal_buffer);
memdelete_arr(cluster.directional_lights);
memdelete_arr(cluster.lights);
memdelete_arr(cluster.lights_shadow_rect_cache);
memdelete_arr(cluster.lights_instances);
memdelete_arr(cluster.reflections);
memdelete_arr(cluster.decals);
}
RD::get_singleton()->free(shadow_sampler);
directional_shadow_atlas_set_size(0);
}
|
// Copyright 2014 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 "device/battery/battery_status_manager_linux.h"
#include <stddef.h>
#include <stdint.h>
#include <memory>
#include "base/macros.h"
#include "base/metrics/histogram.h"
#include "base/threading/thread.h"
#include "base/values.h"
#include "dbus/bus.h"
#include "dbus/message.h"
#include "dbus/object_path.h"
#include "dbus/object_proxy.h"
#include "dbus/property.h"
#include "dbus/values_util.h"
#include "device/battery/battery_status_manager.h"
namespace device {
namespace {
const char kUPowerServiceName[] = "org.freedesktop.UPower";
const char kUPowerDeviceName[] = "org.freedesktop.UPower.Device";
const char kUPowerPath[] = "/org/freedesktop/UPower";
const char kUPowerDeviceSignalChanged[] = "Changed";
const char kUPowerEnumerateDevices[] = "EnumerateDevices";
const char kBatteryNotifierThreadName[] = "BatteryStatusNotifier";
// UPowerDeviceType reflects the possible UPower.Device.Type values,
// see upower.freedesktop.org/docs/Device.html#Device:Type.
enum UPowerDeviceType {
UPOWER_DEVICE_TYPE_UNKNOWN = 0,
UPOWER_DEVICE_TYPE_LINE_POWER = 1,
UPOWER_DEVICE_TYPE_BATTERY = 2,
UPOWER_DEVICE_TYPE_UPS = 3,
UPOWER_DEVICE_TYPE_MONITOR = 4,
UPOWER_DEVICE_TYPE_MOUSE = 5,
UPOWER_DEVICE_TYPE_KEYBOARD = 6,
UPOWER_DEVICE_TYPE_PDA = 7,
UPOWER_DEVICE_TYPE_PHONE = 8,
};
typedef std::vector<dbus::ObjectPath> PathsVector;
double GetPropertyAsDouble(const base::DictionaryValue& dictionary,
const std::string& property_name,
double default_value) {
double value = default_value;
return dictionary.GetDouble(property_name, &value) ? value : default_value;
}
bool GetPropertyAsBoolean(const base::DictionaryValue& dictionary,
const std::string& property_name,
bool default_value) {
bool value = default_value;
return dictionary.GetBoolean(property_name, &value) ? value : default_value;
}
std::unique_ptr<base::DictionaryValue> GetPropertiesAsDictionary(
dbus::ObjectProxy* proxy) {
dbus::MethodCall method_call(dbus::kPropertiesInterface,
dbus::kPropertiesGetAll);
dbus::MessageWriter builder(&method_call);
builder.AppendString(kUPowerDeviceName);
std::unique_ptr<dbus::Response> response(proxy->CallMethodAndBlock(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT));
if (response) {
dbus::MessageReader reader(response.get());
std::unique_ptr<base::Value> value(dbus::PopDataAsValue(&reader));
base::DictionaryValue* dictionary_value = NULL;
if (value && value->GetAsDictionary(&dictionary_value)) {
ignore_result(value.release());
return std::unique_ptr<base::DictionaryValue>(dictionary_value);
}
}
return std::unique_ptr<base::DictionaryValue>();
}
std::unique_ptr<PathsVector> GetPowerSourcesPaths(dbus::ObjectProxy* proxy) {
std::unique_ptr<PathsVector> paths(new PathsVector());
if (!proxy)
return paths;
dbus::MethodCall method_call(kUPowerServiceName, kUPowerEnumerateDevices);
std::unique_ptr<dbus::Response> response(proxy->CallMethodAndBlock(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT));
if (response) {
dbus::MessageReader reader(response.get());
reader.PopArrayOfObjectPaths(paths.get());
}
return paths;
}
void UpdateNumberBatteriesHistogram(int count) {
UMA_HISTOGRAM_CUSTOM_COUNTS(
"BatteryStatus.NumberBatteriesLinux", count, 1, 5, 6);
}
// Class that represents a dedicated thread which communicates with DBus to
// obtain battery information and receives battery change notifications.
class BatteryStatusNotificationThread : public base::Thread {
public:
BatteryStatusNotificationThread(
const BatteryStatusService::BatteryUpdateCallback& callback)
: base::Thread(kBatteryNotifierThreadName),
callback_(callback),
battery_proxy_(NULL) {}
~BatteryStatusNotificationThread() override {
// Make sure to shutdown the dbus connection if it is still open in the very
// end. It needs to happen on the BatteryStatusNotificationThread.
message_loop()->PostTask(
FROM_HERE,
base::Bind(&BatteryStatusNotificationThread::ShutdownDBusConnection,
base::Unretained(this)));
// Drain the message queue of the BatteryStatusNotificationThread and stop.
Stop();
}
void StartListening() {
DCHECK(OnWatcherThread());
if (system_bus_.get())
return;
InitDBus();
dbus::ObjectProxy* power_proxy =
system_bus_->GetObjectProxy(kUPowerServiceName,
dbus::ObjectPath(kUPowerPath));
std::unique_ptr<PathsVector> device_paths =
GetPowerSourcesPaths(power_proxy);
int num_batteries = 0;
for (size_t i = 0; i < device_paths->size(); ++i) {
const dbus::ObjectPath& device_path = device_paths->at(i);
dbus::ObjectProxy* device_proxy = system_bus_->GetObjectProxy(
kUPowerServiceName, device_path);
std::unique_ptr<base::DictionaryValue> dictionary =
GetPropertiesAsDictionary(device_proxy);
if (!dictionary)
continue;
bool is_present = GetPropertyAsBoolean(*dictionary, "IsPresent", false);
uint32_t type = static_cast<uint32_t>(
GetPropertyAsDouble(*dictionary, "Type", UPOWER_DEVICE_TYPE_UNKNOWN));
if (!is_present || type != UPOWER_DEVICE_TYPE_BATTERY) {
system_bus_->RemoveObjectProxy(kUPowerServiceName,
device_path,
base::Bind(&base::DoNothing));
continue;
}
if (battery_proxy_) {
// TODO(timvolodine): add support for multiple batteries. Currently we
// only collect information from the first battery we encounter
// (crbug.com/400780).
LOG(WARNING) << "multiple batteries found, "
<< "using status data of the first battery only.";
} else {
battery_proxy_ = device_proxy;
}
num_batteries++;
}
UpdateNumberBatteriesHistogram(num_batteries);
if (!battery_proxy_) {
callback_.Run(BatteryStatus());
return;
}
battery_proxy_->ConnectToSignal(
kUPowerDeviceName,
kUPowerDeviceSignalChanged,
base::Bind(&BatteryStatusNotificationThread::BatteryChanged,
base::Unretained(this)),
base::Bind(&BatteryStatusNotificationThread::OnSignalConnected,
base::Unretained(this)));
}
void StopListening() {
DCHECK(OnWatcherThread());
ShutdownDBusConnection();
}
private:
bool OnWatcherThread() {
return task_runner()->BelongsToCurrentThread();
}
void InitDBus() {
DCHECK(OnWatcherThread());
dbus::Bus::Options options;
options.bus_type = dbus::Bus::SYSTEM;
options.connection_type = dbus::Bus::PRIVATE;
system_bus_ = new dbus::Bus(options);
}
void ShutdownDBusConnection() {
DCHECK(OnWatcherThread());
if (!system_bus_.get())
return;
// Shutdown DBus connection later because there may be pending tasks on
// this thread.
message_loop()->PostTask(FROM_HERE,
base::Bind(&dbus::Bus::ShutdownAndBlock,
system_bus_));
system_bus_ = NULL;
battery_proxy_ = NULL;
}
void OnSignalConnected(const std::string& interface_name,
const std::string& signal_name,
bool success) {
DCHECK(OnWatcherThread());
if (interface_name != kUPowerDeviceName ||
signal_name != kUPowerDeviceSignalChanged) {
return;
}
if (!system_bus_.get())
return;
if (success) {
BatteryChanged(NULL);
} else {
// Failed to register for "Changed" signal, execute callback with the
// default values.
callback_.Run(BatteryStatus());
}
}
void BatteryChanged(dbus::Signal* signal /* unsused */) {
DCHECK(OnWatcherThread());
if (!system_bus_.get())
return;
std::unique_ptr<base::DictionaryValue> dictionary =
GetPropertiesAsDictionary(battery_proxy_);
if (dictionary)
callback_.Run(ComputeWebBatteryStatus(*dictionary));
else
callback_.Run(BatteryStatus());
}
BatteryStatusService::BatteryUpdateCallback callback_;
scoped_refptr<dbus::Bus> system_bus_;
dbus::ObjectProxy* battery_proxy_; // owned by the bus
DISALLOW_COPY_AND_ASSIGN(BatteryStatusNotificationThread);
};
// Creates a notification thread and delegates Start/Stop calls to it.
class BatteryStatusManagerLinux : public BatteryStatusManager {
public:
explicit BatteryStatusManagerLinux(
const BatteryStatusService::BatteryUpdateCallback& callback)
: callback_(callback) {}
~BatteryStatusManagerLinux() override {}
private:
// BatteryStatusManager:
bool StartListeningBatteryChange() override {
if (!StartNotifierThreadIfNecessary())
return false;
notifier_thread_->message_loop()->PostTask(
FROM_HERE,
base::Bind(&BatteryStatusNotificationThread::StartListening,
base::Unretained(notifier_thread_.get())));
return true;
}
void StopListeningBatteryChange() override {
if (!notifier_thread_)
return;
notifier_thread_->message_loop()->PostTask(
FROM_HERE,
base::Bind(&BatteryStatusNotificationThread::StopListening,
base::Unretained(notifier_thread_.get())));
}
// Starts the notifier thread if not already started and returns true on
// success.
bool StartNotifierThreadIfNecessary() {
if (notifier_thread_)
return true;
base::Thread::Options thread_options(base::MessageLoop::TYPE_IO, 0);
notifier_thread_.reset(new BatteryStatusNotificationThread(callback_));
if (!notifier_thread_->StartWithOptions(thread_options)) {
notifier_thread_.reset();
LOG(ERROR) << "Could not start the " << kBatteryNotifierThreadName
<< " thread";
return false;
}
return true;
}
BatteryStatusService::BatteryUpdateCallback callback_;
std::unique_ptr<BatteryStatusNotificationThread> notifier_thread_;
DISALLOW_COPY_AND_ASSIGN(BatteryStatusManagerLinux);
};
} // namespace
BatteryStatus ComputeWebBatteryStatus(const base::DictionaryValue& dictionary) {
BatteryStatus status;
if (!dictionary.HasKey("State"))
return status;
uint32_t state = static_cast<uint32_t>(
GetPropertyAsDouble(dictionary, "State", UPOWER_DEVICE_STATE_UNKNOWN));
status.charging = state != UPOWER_DEVICE_STATE_DISCHARGING &&
state != UPOWER_DEVICE_STATE_EMPTY;
double percentage = GetPropertyAsDouble(dictionary, "Percentage", 100);
// Convert percentage to a value between 0 and 1 with 2 digits of precision.
// This is to bring it in line with other platforms like Mac and Android where
// we report level with 1% granularity. It also serves the purpose of reducing
// the possibility of fingerprinting and triggers less level change events on
// the blink side.
// TODO(timvolodine): consider moving this rounding to the blink side.
status.level = round(percentage) / 100.f;
switch (state) {
case UPOWER_DEVICE_STATE_CHARGING : {
double time_to_full = GetPropertyAsDouble(dictionary, "TimeToFull", 0);
status.charging_time =
(time_to_full > 0) ? time_to_full
: std::numeric_limits<double>::infinity();
break;
}
case UPOWER_DEVICE_STATE_DISCHARGING : {
double time_to_empty = GetPropertyAsDouble(dictionary, "TimeToEmpty", 0);
// Set dischargingTime if it's available. Otherwise leave the default
// value which is +infinity.
if (time_to_empty > 0)
status.discharging_time = time_to_empty;
status.charging_time = std::numeric_limits<double>::infinity();
break;
}
case UPOWER_DEVICE_STATE_FULL : {
break;
}
default: {
status.charging_time = std::numeric_limits<double>::infinity();
}
}
return status;
}
// static
std::unique_ptr<BatteryStatusManager> BatteryStatusManager::Create(
const BatteryStatusService::BatteryUpdateCallback& callback) {
return std::unique_ptr<BatteryStatusManager>(
new BatteryStatusManagerLinux(callback));
}
} // namespace device
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.