text
stringlengths
5
1.04M
// Copyright (c) 2009-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chain.h> #include <key_io.h> #include <rpc/server.h> #include <validation.h> #include <script/script.h> #include <script/standard.h> #include <sync.h> #include <util.h> #include <utiltime.h> #include <wallet/wallet.h> #include <merkleblock.h> #include <core_io.h> #include <wallet/rpcwallet.h> #include <fstream> #include <stdint.h> #include <boost/algorithm/string.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <univalue.h> int64_t static DecodeDumpTime(const std::string &str) { static const boost::posix_time::ptime epoch = boost::posix_time::from_time_t(0); static const std::locale loc(std::locale::classic(), new boost::posix_time::time_input_facet("%Y-%m-%dT%H:%M:%SZ")); std::istringstream iss(str); iss.imbue(loc); boost::posix_time::ptime ptime(boost::date_time::not_a_date_time); iss >> ptime; if (ptime.is_not_a_date_time()) return 0; return (ptime - epoch).total_seconds(); } std::string static EncodeDumpString(const std::string &str) { std::stringstream ret; for (unsigned char c : str) { if (c <= 32 || c >= 128 || c == '%') { ret << '%' << HexStr(&c, &c + 1); } else { ret << c; } } return ret.str(); } static std::string DecodeDumpString(const std::string &str) { std::stringstream ret; for (unsigned int pos = 0; pos < str.length(); pos++) { unsigned char c = str[pos]; if (c == '%' && pos+2 < str.length()) { c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) | ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15)); pos += 2; } ret << c; } return ret.str(); } static bool GetWalletAddressesForKey(CWallet * const pwallet, const CKeyID &keyid, std::string &strAddr, std::string &strLabel) { bool fLabelFound = false; CKey key; pwallet->GetKey(keyid, key); for (const auto& dest : GetAllDestinationsForKey(key.GetPubKey())) { if (pwallet->mapAddressBook.count(dest)) { if (!strAddr.empty()) { strAddr += ","; } strAddr += EncodeDestination(dest); strLabel = EncodeDumpString(pwallet->mapAddressBook[dest].name); fLabelFound = true; } } if (!fLabelFound) { strAddr = EncodeDestination(GetDestinationForKey(key.GetPubKey(), pwallet->m_default_address_type)); } return fLabelFound; } static const int64_t TIMESTAMP_MIN = 0; static void RescanWallet(CWallet& wallet, const WalletRescanReserver& reserver, int64_t time_begin = TIMESTAMP_MIN, bool update = true) { int64_t scanned_time = wallet.RescanFromTime(time_begin, reserver, update); if (wallet.IsAbortingRescan()) { throw JSONRPCError(RPC_MISC_ERROR, "Rescan aborted by user."); } else if (scanned_time > time_begin) { throw JSONRPCError(RPC_WALLET_ERROR, "Rescan was unable to fully rescan the blockchain. Some transactions may be missing."); } } UniValue importprivkey(const JSONRPCRequest& request) { std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request); CWallet* const pwallet = wallet.get(); if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) { return NullUniValue; } if (request.fHelp || request.params.size() < 1 || request.params.size() > 3) throw std::runtime_error( "importprivkey \"privkey\" ( \"label\" ) ( rescan )\n" "\nAdds a private key (as returned by dumpprivkey) to your wallet. Requires a new wallet backup.\n" "Hint: use importmulti to import more than one private key.\n" "\nArguments:\n" "1. \"privkey\" (string, required) The private key (see dumpprivkey)\n" "2. \"label\" (string, optional, default=\"\") An optional label\n" "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n" "\nNote: This call can take over an hour to complete if rescan is true, during that time, other rpc calls\n" "may report that the imported key exists but related transactions are still missing, leading to temporarily incorrect/bogus balances and unspent outputs until rescan completes.\n" "\nExamples:\n" "\nDump a private key\n" + HelpExampleCli("dumpprivkey", "\"myaddress\"") + "\nImport the private key with rescan\n" + HelpExampleCli("importprivkey", "\"mykey\"") + "\nImport using a label and without rescan\n" + HelpExampleCli("importprivkey", "\"mykey\" \"testing\" false") + "\nImport using default blank label and without rescan\n" + HelpExampleCli("importprivkey", "\"mykey\" \"\" false") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("importprivkey", "\"mykey\", \"testing\", false") ); WalletRescanReserver reserver(pwallet); bool fRescan = true; { LOCK2(cs_main, pwallet->cs_wallet); EnsureWalletIsUnlocked(pwallet); std::string strSecret = request.params[0].get_str(); std::string strLabel = ""; if (!request.params[1].isNull()) strLabel = request.params[1].get_str(); // Whether to perform rescan after import if (!request.params[2].isNull()) fRescan = request.params[2].get_bool(); if (fRescan && fPruneMode) throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled in pruned mode"); if (fRescan && !reserver.reserve()) { throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait."); } CKey key = DecodeSecret(strSecret); if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding"); CPubKey pubkey = key.GetPubKey(); assert(key.VerifyPubKey(pubkey)); CKeyID vchAddress = pubkey.GetID(); { pwallet->MarkDirty(); // We don't know which corresponding address will be used; label them all for (const auto& dest : GetAllDestinationsForKey(pubkey)) { pwallet->SetAddressBook(dest, strLabel, "receive"); } // Don't throw error in case a key is already there if (pwallet->HaveKey(vchAddress)) { return NullUniValue; } // whenever a key is imported, we need to scan the whole chain pwallet->UpdateTimeFirstKey(1); pwallet->mapKeyMetadata[vchAddress].nCreateTime = 1; if (!pwallet->AddKeyPubKey(key, pubkey)) { throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); } pwallet->LearnAllRelatedScripts(pubkey); } } if (fRescan) { RescanWallet(*pwallet, reserver); } return NullUniValue; } UniValue abortrescan(const JSONRPCRequest& request) { std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request); CWallet* const pwallet = wallet.get(); if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) { return NullUniValue; } if (request.fHelp || request.params.size() > 0) throw std::runtime_error( "abortrescan\n" "\nStops current wallet rescan triggered by an RPC call, e.g. by an importprivkey call.\n" "\nExamples:\n" "\nImport a private key\n" + HelpExampleCli("importprivkey", "\"mykey\"") + "\nAbort the running wallet rescan\n" + HelpExampleCli("abortrescan", "") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("abortrescan", "") ); if (!pwallet->IsScanning() || pwallet->IsAbortingRescan()) return false; pwallet->AbortRescan(); return true; } static void ImportAddress(CWallet*, const CTxDestination& dest, const std::string& strLabel); static void ImportScript(CWallet* const pwallet, const CScript& script, const std::string& strLabel, bool isRedeemScript) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) { if (!isRedeemScript && ::IsMine(*pwallet, script) == ISMINE_SPENDABLE) { throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script"); } pwallet->MarkDirty(); if (!pwallet->HaveWatchOnly(script) && !pwallet->AddWatchOnly(script, 0 /* nCreateTime */)) { throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet"); } if (isRedeemScript) { const CScriptID id(script); if (!pwallet->HaveCScript(id) && !pwallet->AddCScript(script)) { throw JSONRPCError(RPC_WALLET_ERROR, "Error adding p2sh redeemScript to wallet"); } ImportAddress(pwallet, id, strLabel); } else { CTxDestination destination; if (ExtractDestination(script, destination)) { pwallet->SetAddressBook(destination, strLabel, "receive"); } } } static void ImportAddress(CWallet* const pwallet, const CTxDestination& dest, const std::string& strLabel) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) { CScript script = GetScriptForDestination(dest); ImportScript(pwallet, script, strLabel, false); // add to address book or update label if (IsValidDestination(dest)) pwallet->SetAddressBook(dest, strLabel, "receive"); } UniValue importaddress(const JSONRPCRequest& request) { std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request); CWallet* const pwallet = wallet.get(); if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) { return NullUniValue; } if (request.fHelp || request.params.size() < 1 || request.params.size() > 4) throw std::runtime_error( "importaddress \"address\" ( \"label\" rescan p2sh )\n" "\nAdds an address or script (in hex) that can be watched as if it were in your wallet but cannot be used to spend. Requires a new wallet backup.\n" "\nArguments:\n" "1. \"address\" (string, required) The Spore address (or hex-encoded script)\n" "2. \"label\" (string, optional, default=\"\") An optional label\n" "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n" "4. p2sh (boolean, optional, default=false) Add the P2SH version of the script as well\n" "\nNote: This call can take over an hour to complete if rescan is true, during that time, other rpc calls\n" "may report that the imported address exists but related transactions are still missing, leading to temporarily incorrect/bogus balances and unspent outputs until rescan completes.\n" "If you have the full public key, you should call importpubkey instead of this.\n" "\nNote: If you import a non-standard raw script in hex form, outputs sending to it will be treated\n" "as change, and not show up in many RPCs.\n" "\nExamples:\n" "\nImport an address with rescan\n" + HelpExampleCli("importaddress", "\"myaddress\"") + "\nImport using a label without rescan\n" + HelpExampleCli("importaddress", "\"myaddress\" \"testing\" false") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("importaddress", "\"myaddress\", \"testing\", false") ); std::string strLabel; if (!request.params[1].isNull()) strLabel = request.params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (!request.params[2].isNull()) fRescan = request.params[2].get_bool(); if (fRescan && fPruneMode) throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled in pruned mode"); WalletRescanReserver reserver(pwallet); if (fRescan && !reserver.reserve()) { throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait."); } // Whether to import a p2sh version, too bool fP2SH = false; if (!request.params[3].isNull()) fP2SH = request.params[3].get_bool(); { LOCK2(cs_main, pwallet->cs_wallet); CTxDestination dest = DecodeDestination(request.params[0].get_str()); if (IsValidDestination(dest)) { if (fP2SH) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Cannot use the p2sh flag with an address - use a script instead"); } ImportAddress(pwallet, dest, strLabel); } else if (IsHex(request.params[0].get_str())) { std::vector<unsigned char> data(ParseHex(request.params[0].get_str())); ImportScript(pwallet, CScript(data.begin(), data.end()), strLabel, fP2SH); } else { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Spore address or script"); } } if (fRescan) { RescanWallet(*pwallet, reserver); pwallet->ReacceptWalletTransactions(); } return NullUniValue; } UniValue importprunedfunds(const JSONRPCRequest& request) { std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request); CWallet* const pwallet = wallet.get(); if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) { return NullUniValue; } if (request.fHelp || request.params.size() != 2) throw std::runtime_error( "importprunedfunds\n" "\nImports funds without rescan. Corresponding address or script must previously be included in wallet. Aimed towards pruned wallets. The end-user is responsible to import additional transactions that subsequently spend the imported outputs or rescan after the point in the blockchain the transaction is included.\n" "\nArguments:\n" "1. \"rawtransaction\" (string, required) A raw transaction in hex funding an already-existing address in wallet\n" "2. \"txoutproof\" (string, required) The hex output from gettxoutproof that contains the transaction\n" ); CMutableTransaction tx; if (!DecodeHexTx(tx, request.params[0].get_str())) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); uint256 hashTx = tx.GetHash(); CWalletTx wtx(pwallet, MakeTransactionRef(std::move(tx))); CDataStream ssMB(ParseHexV(request.params[1], "proof"), SER_NETWORK, PROTOCOL_VERSION); CMerkleBlock merkleBlock; ssMB >> merkleBlock; //Search partial merkle tree in proof for our transaction and index in valid block std::vector<uint256> vMatch; std::vector<unsigned int> vIndex; unsigned int txnIndex = 0; if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) == merkleBlock.header.hashMerkleRoot) { LOCK(cs_main); const CBlockIndex* pindex = LookupBlockIndex(merkleBlock.header.GetHash()); if (!pindex || !chainActive.Contains(pindex)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain"); } std::vector<uint256>::const_iterator it; if ((it = std::find(vMatch.begin(), vMatch.end(), hashTx))==vMatch.end()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction given doesn't exist in proof"); } txnIndex = vIndex[it - vMatch.begin()]; } else { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Something wrong with merkleblock"); } wtx.nIndex = txnIndex; wtx.hashBlock = merkleBlock.header.GetHash(); LOCK2(cs_main, pwallet->cs_wallet); if (pwallet->IsMine(*wtx.tx)) { pwallet->AddToWallet(wtx, false); return NullUniValue; } throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No addresses in wallet correspond to included transaction"); } UniValue removeprunedfunds(const JSONRPCRequest& request) { std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request); CWallet* const pwallet = wallet.get(); if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) { return NullUniValue; } if (request.fHelp || request.params.size() != 1) throw std::runtime_error( "removeprunedfunds \"txid\"\n" "\nDeletes the specified transaction from the wallet. Meant for use with pruned wallets and as a companion to importprunedfunds. This will affect wallet balances.\n" "\nArguments:\n" "1. \"txid\" (string, required) The hex-encoded id of the transaction you are deleting\n" "\nExamples:\n" + HelpExampleCli("removeprunedfunds", "\"c54357a1ff9f4e792198e75c01fc633acc6d093abd67ec1849596637c3457bf2\"") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("removeprunedfunds", "\"c54357a1ff9f4e792198e75c01fc633acc6d093abd67ec1849596637c3457bf2\"") ); LOCK2(cs_main, pwallet->cs_wallet); uint256 hash; hash.SetHex(request.params[0].get_str()); std::vector<uint256> vHash; vHash.push_back(hash); std::vector<uint256> vHashOut; if (pwallet->ZapSelectTx(vHash, vHashOut) != DBErrors::LOAD_OK) { throw JSONRPCError(RPC_WALLET_ERROR, "Could not properly delete the transaction."); } if(vHashOut.empty()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Transaction does not exist in wallet."); } return NullUniValue; } UniValue importpubkey(const JSONRPCRequest& request) { std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request); CWallet* const pwallet = wallet.get(); if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) { return NullUniValue; } if (request.fHelp || request.params.size() < 1 || request.params.size() > 3) throw std::runtime_error( "importpubkey \"pubkey\" ( \"label\" rescan )\n" "\nAdds a public key (in hex) that can be watched as if it were in your wallet but cannot be used to spend. Requires a new wallet backup.\n" "\nArguments:\n" "1. \"pubkey\" (string, required) The hex-encoded public key\n" "2. \"label\" (string, optional, default=\"\") An optional label\n" "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n" "\nNote: This call can take over an hour to complete if rescan is true, during that time, other rpc calls\n" "may report that the imported pubkey exists but related transactions are still missing, leading to temporarily incorrect/bogus balances and unspent outputs until rescan completes.\n" "\nExamples:\n" "\nImport a public key with rescan\n" + HelpExampleCli("importpubkey", "\"mypubkey\"") + "\nImport using a label without rescan\n" + HelpExampleCli("importpubkey", "\"mypubkey\" \"testing\" false") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("importpubkey", "\"mypubkey\", \"testing\", false") ); std::string strLabel; if (!request.params[1].isNull()) strLabel = request.params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (!request.params[2].isNull()) fRescan = request.params[2].get_bool(); if (fRescan && fPruneMode) throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled in pruned mode"); WalletRescanReserver reserver(pwallet); if (fRescan && !reserver.reserve()) { throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait."); } if (!IsHex(request.params[0].get_str())) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey must be a hex string"); std::vector<unsigned char> data(ParseHex(request.params[0].get_str())); CPubKey pubKey(data.begin(), data.end()); if (!pubKey.IsFullyValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey is not a valid public key"); { LOCK2(cs_main, pwallet->cs_wallet); for (const auto& dest : GetAllDestinationsForKey(pubKey)) { ImportAddress(pwallet, dest, strLabel); } ImportScript(pwallet, GetScriptForRawPubKey(pubKey), strLabel, false); pwallet->LearnAllRelatedScripts(pubKey); } if (fRescan) { RescanWallet(*pwallet, reserver); pwallet->ReacceptWalletTransactions(); } return NullUniValue; } UniValue importwallet(const JSONRPCRequest& request) { std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request); CWallet* const pwallet = wallet.get(); if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) { return NullUniValue; } if (request.fHelp || request.params.size() != 1) throw std::runtime_error( "importwallet \"filename\"\n" "\nImports keys from a wallet dump file (see dumpwallet). Requires a new wallet backup to include imported keys.\n" "\nArguments:\n" "1. \"filename\" (string, required) The wallet file\n" "\nExamples:\n" "\nDump the wallet\n" + HelpExampleCli("dumpwallet", "\"test\"") + "\nImport the wallet\n" + HelpExampleCli("importwallet", "\"test\"") + "\nImport using the json rpc call\n" + HelpExampleRpc("importwallet", "\"test\"") ); if (fPruneMode) throw JSONRPCError(RPC_WALLET_ERROR, "Importing wallets is disabled in pruned mode"); WalletRescanReserver reserver(pwallet); if (!reserver.reserve()) { throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait."); } int64_t nTimeBegin = 0; bool fGood = true; { LOCK2(cs_main, pwallet->cs_wallet); EnsureWalletIsUnlocked(pwallet); std::ifstream file; file.open(request.params[0].get_str().c_str(), std::ios::in | std::ios::ate); if (!file.is_open()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); } nTimeBegin = chainActive.Tip()->GetBlockTime(); int64_t nFilesize = std::max((int64_t)1, (int64_t)file.tellg()); file.seekg(0, file.beg); // Use uiInterface.ShowProgress instead of pwallet.ShowProgress because pwallet.ShowProgress has a cancel button tied to AbortRescan which // we don't want for this progress bar showing the import progress. uiInterface.ShowProgress does not have a cancel button. uiInterface.ShowProgress(strprintf("%s " + _("Importing..."), pwallet->GetDisplayName()), 0, false); // show progress dialog in GUI while (file.good()) { uiInterface.ShowProgress("", std::max(1, std::min(99, (int)(((double)file.tellg() / (double)nFilesize) * 100))), false); std::string line; std::getline(file, line); if (line.empty() || line[0] == '#') continue; std::vector<std::string> vstr; boost::split(vstr, line, boost::is_any_of(" ")); if (vstr.size() < 2) continue; CKey key = DecodeSecret(vstr[0]); if (key.IsValid()) { CPubKey pubkey = key.GetPubKey(); assert(key.VerifyPubKey(pubkey)); CKeyID keyid = pubkey.GetID(); if (pwallet->HaveKey(keyid)) { pwallet->WalletLogPrintf("Skipping import of %s (key already present)\n", EncodeDestination(keyid)); continue; } int64_t nTime = DecodeDumpTime(vstr[1]); std::string strLabel; bool fLabel = true; for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) { if (vstr[nStr].front() == '#') break; if (vstr[nStr] == "change=1") fLabel = false; if (vstr[nStr] == "reserve=1") fLabel = false; if (vstr[nStr].substr(0,6) == "label=") { strLabel = DecodeDumpString(vstr[nStr].substr(6)); fLabel = true; } } pwallet->WalletLogPrintf("Importing %s...\n", EncodeDestination(keyid)); if (!pwallet->AddKeyPubKey(key, pubkey)) { fGood = false; continue; } pwallet->mapKeyMetadata[keyid].nCreateTime = nTime; if (fLabel) pwallet->SetAddressBook(keyid, strLabel, "receive"); nTimeBegin = std::min(nTimeBegin, nTime); } else if(IsHex(vstr[0])) { std::vector<unsigned char> vData(ParseHex(vstr[0])); CScript script = CScript(vData.begin(), vData.end()); CScriptID id(script); if (pwallet->HaveCScript(id)) { pwallet->WalletLogPrintf("Skipping import of %s (script already present)\n", vstr[0]); continue; } if(!pwallet->AddCScript(script)) { pwallet->WalletLogPrintf("Error importing script %s\n", vstr[0]); fGood = false; continue; } int64_t birth_time = DecodeDumpTime(vstr[1]); if (birth_time > 0) { pwallet->m_script_metadata[id].nCreateTime = birth_time; nTimeBegin = std::min(nTimeBegin, birth_time); } } } file.close(); uiInterface.ShowProgress("", 100, false); // hide progress dialog in GUI pwallet->UpdateTimeFirstKey(nTimeBegin); } uiInterface.ShowProgress("", 100, false); // hide progress dialog in GUI RescanWallet(*pwallet, reserver, nTimeBegin, false /* update */); pwallet->MarkDirty(); if (!fGood) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys/scripts to wallet"); return NullUniValue; } UniValue dumpprivkey(const JSONRPCRequest& request) { std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request); CWallet* const pwallet = wallet.get(); if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) { return NullUniValue; } if (request.fHelp || request.params.size() != 1) throw std::runtime_error( "dumpprivkey \"address\"\n" "\nReveals the private key corresponding to 'address'.\n" "Then the importprivkey can be used with this output\n" "\nArguments:\n" "1. \"address\" (string, required) The spore address for the private key\n" "\nResult:\n" "\"key\" (string) The private key\n" "\nExamples:\n" + HelpExampleCli("dumpprivkey", "\"myaddress\"") + HelpExampleCli("importprivkey", "\"mykey\"") + HelpExampleRpc("dumpprivkey", "\"myaddress\"") ); LOCK2(cs_main, pwallet->cs_wallet); EnsureWalletIsUnlocked(pwallet); std::string strAddress = request.params[0].get_str(); CTxDestination dest = DecodeDestination(strAddress); if (!IsValidDestination(dest)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Spore address"); } auto keyid = GetKeyForDestination(*pwallet, dest); if (keyid.IsNull()) { throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); } CKey vchSecret; if (!pwallet->GetKey(keyid, vchSecret)) { throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); } return EncodeSecret(vchSecret); } UniValue dumpwallet(const JSONRPCRequest& request) { std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request); CWallet* const pwallet = wallet.get(); if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) { return NullUniValue; } if (request.fHelp || request.params.size() != 1) throw std::runtime_error( "dumpwallet \"filename\"\n" "\nDumps all wallet keys in a human-readable format to a server-side file. This does not allow overwriting existing files.\n" "Imported scripts are included in the dumpfile, but corresponding BIP173 addresses, etc. may not be added automatically by importwallet.\n" "Note that if your wallet contains keys which are not derived from your HD seed (e.g. imported keys), these are not covered by\n" "only backing up the seed itself, and must be backed up too (e.g. ensure you back up the whole dumpfile).\n" "\nArguments:\n" "1. \"filename\" (string, required) The filename with path (either absolute or relative to spored)\n" "\nResult:\n" "{ (json object)\n" " \"filename\" : { (string) The filename with full absolute path\n" "}\n" "\nExamples:\n" + HelpExampleCli("dumpwallet", "\"test\"") + HelpExampleRpc("dumpwallet", "\"test\"") ); LOCK2(cs_main, pwallet->cs_wallet); EnsureWalletIsUnlocked(pwallet); boost::filesystem::path filepath = request.params[0].get_str(); filepath = boost::filesystem::absolute(filepath); /* Prevent arbitrary files from being overwritten. There have been reports * that users have overwritten wallet files this way: * https://github.com/bitcoin/bitcoin/issues/9934 * It may also avoid other security issues. */ if (boost::filesystem::exists(filepath)) { throw JSONRPCError(RPC_INVALID_PARAMETER, filepath.string() + " already exists. If you are sure this is what you want, move it out of the way first"); } std::ofstream file; file.open(filepath.string().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); std::map<CTxDestination, int64_t> mapKeyBirth; const std::map<CKeyID, int64_t>& mapKeyPool = pwallet->GetAllReserveKeys(); pwallet->GetKeyBirthTimes(mapKeyBirth); std::set<CScriptID> scripts = pwallet->GetCScripts(); // TODO: include scripts in GetKeyBirthTimes() output instead of separate // sort time/key pairs std::vector<std::pair<int64_t, CKeyID> > vKeyBirth; for (const auto& entry : mapKeyBirth) { if (const CKeyID* keyID = boost::get<CKeyID>(&entry.first)) { // set and test vKeyBirth.push_back(std::make_pair(entry.second, *keyID)); } } mapKeyBirth.clear(); std::sort(vKeyBirth.begin(), vKeyBirth.end()); // produce output file << strprintf("# Wallet dump created by Spore %s\n", CLIENT_BUILD); file << strprintf("# * Created on %s\n", FormatISO8601DateTime(GetTime())); file << strprintf("# * Best block at time of backup was %i (%s),\n", chainActive.Height(), chainActive.Tip()->GetBlockHash().ToString()); file << strprintf("# mined on %s\n", FormatISO8601DateTime(chainActive.Tip()->GetBlockTime())); file << "\n"; // add the base58check encoded extended master if the wallet uses HD CKeyID seed_id = pwallet->GetHDChain().seed_id; if (!seed_id.IsNull()) { CKey seed; if (pwallet->GetKey(seed_id, seed)) { CExtKey masterKey; masterKey.SetSeed(seed.begin(), seed.size()); file << "# extended private masterkey: " << EncodeExtKey(masterKey) << "\n\n"; } } for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) { const CKeyID &keyid = it->second; std::string strTime = FormatISO8601DateTime(it->first); std::string strAddr; std::string strLabel; CKey key; if (pwallet->GetKey(keyid, key)) { file << strprintf("%s %s ", EncodeSecret(key), strTime); if (GetWalletAddressesForKey(pwallet, keyid, strAddr, strLabel)) { file << strprintf("label=%s", strLabel); } else if (keyid == seed_id) { file << "hdseed=1"; } else if (mapKeyPool.count(keyid)) { file << "reserve=1"; } else if (pwallet->mapKeyMetadata[keyid].hdKeypath == "s") { file << "inactivehdseed=1"; } else { file << "change=1"; } file << strprintf(" # addr=%s%s\n", strAddr, (pwallet->mapKeyMetadata[keyid].hdKeypath.size() > 0 ? " hdkeypath="+pwallet->mapKeyMetadata[keyid].hdKeypath : "")); } } file << "\n"; for (const CScriptID &scriptid : scripts) { CScript script; std::string create_time = "0"; std::string address = EncodeDestination(scriptid); // get birth times for scripts with metadata auto it = pwallet->m_script_metadata.find(scriptid); if (it != pwallet->m_script_metadata.end()) { create_time = FormatISO8601DateTime(it->second.nCreateTime); } if(pwallet->GetCScript(scriptid, script)) { file << strprintf("%s %s script=1", HexStr(script.begin(), script.end()), create_time); file << strprintf(" # addr=%s\n", address); } } file << "\n"; file << "# End of dump\n"; file.close(); UniValue reply(UniValue::VOBJ); reply.pushKV("filename", filepath.string()); return reply; } static UniValue ProcessImport(CWallet * const pwallet, const UniValue& data, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) { try { bool success = false; // Required fields. const UniValue& scriptPubKey = data["scriptPubKey"]; // Should have script or JSON with "address". if (!(scriptPubKey.getType() == UniValue::VOBJ && scriptPubKey.exists("address")) && !(scriptPubKey.getType() == UniValue::VSTR)) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid scriptPubKey"); } // Optional fields. const std::string& strRedeemScript = data.exists("redeemscript") ? data["redeemscript"].get_str() : ""; const UniValue& pubKeys = data.exists("pubkeys") ? data["pubkeys"].get_array() : UniValue(); const UniValue& keys = data.exists("keys") ? data["keys"].get_array() : UniValue(); const bool internal = data.exists("internal") ? data["internal"].get_bool() : false; const bool watchOnly = data.exists("watchonly") ? data["watchonly"].get_bool() : false; const std::string& label = data.exists("label") && !internal ? data["label"].get_str() : ""; bool isScript = scriptPubKey.getType() == UniValue::VSTR; bool isP2SH = strRedeemScript.length() > 0; const std::string& output = isScript ? scriptPubKey.get_str() : scriptPubKey["address"].get_str(); // Parse the output. CScript script; CTxDestination dest; if (!isScript) { dest = DecodeDestination(output); if (!IsValidDestination(dest)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address"); } script = GetScriptForDestination(dest); } else { if (!IsHex(output)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid scriptPubKey"); } std::vector<unsigned char> vData(ParseHex(output)); script = CScript(vData.begin(), vData.end()); } // Watchonly and private keys if (watchOnly && keys.size()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Incompatibility found between watchonly and keys"); } // Internal + Label if (internal && data.exists("label")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Incompatibility found between internal and label"); } // Not having Internal + Script if (!internal && isScript) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Internal must be set for hex scriptPubKey"); } // Keys / PubKeys size check. if (!isP2SH && (keys.size() > 1 || pubKeys.size() > 1)) { // Address / scriptPubKey throw JSONRPCError(RPC_INVALID_PARAMETER, "More than private key given for one address"); } // Invalid P2SH redeemScript if (isP2SH && !IsHex(strRedeemScript)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid redeem script"); } // Process. // // P2SH if (isP2SH) { // Import redeem script. std::vector<unsigned char> vData(ParseHex(strRedeemScript)); CScript redeemScript = CScript(vData.begin(), vData.end()); // Invalid P2SH address if (!script.IsPayToScriptHash()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid P2SH address / script"); } pwallet->MarkDirty(); if (!pwallet->AddWatchOnly(redeemScript, timestamp)) { throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet"); } CScriptID redeem_id(redeemScript); if (!pwallet->HaveCScript(redeem_id) && !pwallet->AddCScript(redeemScript)) { throw JSONRPCError(RPC_WALLET_ERROR, "Error adding p2sh redeemScript to wallet"); } CScript redeemDestination = GetScriptForDestination(redeem_id); if (::IsMine(*pwallet, redeemDestination) == ISMINE_SPENDABLE) { throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script"); } pwallet->MarkDirty(); if (!pwallet->AddWatchOnly(redeemDestination, timestamp)) { throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet"); } // add to address book or update label if (IsValidDestination(dest)) { pwallet->SetAddressBook(dest, label, "receive"); } // Import private keys. if (keys.size()) { for (size_t i = 0; i < keys.size(); i++) { const std::string& privkey = keys[i].get_str(); CKey key = DecodeSecret(privkey); if (!key.IsValid()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding"); } CPubKey pubkey = key.GetPubKey(); assert(key.VerifyPubKey(pubkey)); CKeyID vchAddress = pubkey.GetID(); pwallet->MarkDirty(); pwallet->SetAddressBook(vchAddress, label, "receive"); if (pwallet->HaveKey(vchAddress)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Already have this key"); } pwallet->mapKeyMetadata[vchAddress].nCreateTime = timestamp; if (!pwallet->AddKeyPubKey(key, pubkey)) { throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); } pwallet->UpdateTimeFirstKey(timestamp); } } success = true; } else { // Import public keys. if (pubKeys.size() && keys.size() == 0) { const std::string& strPubKey = pubKeys[0].get_str(); if (!IsHex(strPubKey)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey must be a hex string"); } std::vector<unsigned char> vData(ParseHex(strPubKey)); CPubKey pubKey(vData.begin(), vData.end()); if (!pubKey.IsFullyValid()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey is not a valid public key"); } CTxDestination pubkey_dest = pubKey.GetID(); // Consistency check. if (!isScript && !(pubkey_dest == dest)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Consistency check failed"); } // Consistency check. if (isScript) { CTxDestination destination; if (ExtractDestination(script, destination)) { if (!(destination == pubkey_dest)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Consistency check failed"); } } } CScript pubKeyScript = GetScriptForDestination(pubkey_dest); if (::IsMine(*pwallet, pubKeyScript) == ISMINE_SPENDABLE) { throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script"); } pwallet->MarkDirty(); if (!pwallet->AddWatchOnly(pubKeyScript, timestamp)) { throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet"); } // add to address book or update label if (IsValidDestination(pubkey_dest)) { pwallet->SetAddressBook(pubkey_dest, label, "receive"); } // TODO Is this necessary? CScript scriptRawPubKey = GetScriptForRawPubKey(pubKey); if (::IsMine(*pwallet, scriptRawPubKey) == ISMINE_SPENDABLE) { throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script"); } pwallet->MarkDirty(); if (!pwallet->AddWatchOnly(scriptRawPubKey, timestamp)) { throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet"); } success = true; } // Import private keys. if (keys.size()) { const std::string& strPrivkey = keys[0].get_str(); // Checks. CKey key = DecodeSecret(strPrivkey); if (!key.IsValid()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding"); } CPubKey pubKey = key.GetPubKey(); assert(key.VerifyPubKey(pubKey)); CTxDestination pubkey_dest = pubKey.GetID(); // Consistency check. if (!isScript && !(pubkey_dest == dest)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Consistency check failed"); } // Consistency check. if (isScript) { CTxDestination destination; if (ExtractDestination(script, destination)) { if (!(destination == pubkey_dest)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Consistency check failed"); } } } CKeyID vchAddress = pubKey.GetID(); pwallet->MarkDirty(); pwallet->SetAddressBook(vchAddress, label, "receive"); if (pwallet->HaveKey(vchAddress)) { throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script"); } pwallet->mapKeyMetadata[vchAddress].nCreateTime = timestamp; if (!pwallet->AddKeyPubKey(key, pubKey)) { throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); } pwallet->UpdateTimeFirstKey(timestamp); success = true; } // Import scriptPubKey only. if (pubKeys.size() == 0 && keys.size() == 0) { if (::IsMine(*pwallet, script) == ISMINE_SPENDABLE) { throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script"); } pwallet->MarkDirty(); if (!pwallet->AddWatchOnly(script, timestamp)) { throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet"); } if (scriptPubKey.getType() == UniValue::VOBJ) { // add to address book or update label if (IsValidDestination(dest)) { pwallet->SetAddressBook(dest, label, "receive"); } } success = true; } } UniValue result = UniValue(UniValue::VOBJ); result.pushKV("success", UniValue(success)); return result; } catch (const UniValue& e) { UniValue result = UniValue(UniValue::VOBJ); result.pushKV("success", UniValue(false)); result.pushKV("error", e); return result; } catch (...) { UniValue result = UniValue(UniValue::VOBJ); result.pushKV("success", UniValue(false)); result.pushKV("error", JSONRPCError(RPC_MISC_ERROR, "Missing required fields")); return result; } } static int64_t GetImportTimestamp(const UniValue& data, int64_t now) { if (data.exists("timestamp")) { const UniValue& timestamp = data["timestamp"]; if (timestamp.isNum()) { return timestamp.get_int64(); } else if (timestamp.isStr() && timestamp.get_str() == "now") { return now; } throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Expected number or \"now\" timestamp value for key. got type %s", uvTypeName(timestamp.type()))); } throw JSONRPCError(RPC_TYPE_ERROR, "Missing required timestamp field for key"); } UniValue importmulti(const JSONRPCRequest& mainRequest) { std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(mainRequest); CWallet* const pwallet = wallet.get(); if (!EnsureWalletIsAvailable(pwallet, mainRequest.fHelp)) { return NullUniValue; } // clang-format off if (mainRequest.fHelp || mainRequest.params.size() < 1 || mainRequest.params.size() > 2) throw std::runtime_error( "importmulti \"requests\" ( \"options\" )\n\n" "Import addresses/scripts (with private or public keys, redeem script (P2SH)), rescanning all addresses in one-shot-only (rescan can be disabled via options). Requires a new wallet backup.\n\n" "Arguments:\n" "1. requests (array, required) Data to be imported\n" " [ (array of json objects)\n" " {\n" " \"scriptPubKey\": \"<script>\" | { \"address\":\"<address>\" }, (string / json, required) Type of scriptPubKey (string for script, json for address)\n" " \"timestamp\": timestamp | \"now\" , (integer / string, required) Creation time of the key in seconds since epoch (Jan 1 1970 GMT),\n" " or the string \"now\" to substitute the current synced blockchain time. The timestamp of the oldest\n" " key will determine how far back blockchain rescans need to begin for missing wallet transactions.\n" " \"now\" can be specified to bypass scanning, for keys which are known to never have been used, and\n" " 0 can be specified to scan the entire blockchain. Blocks up to 2 hours before the earliest key\n" " creation time of all keys being imported by the importmulti call will be scanned.\n" " \"redeemscript\": \"<script>\" , (string, optional) Allowed only if the scriptPubKey is a P2SH address or a P2SH scriptPubKey\n" " \"pubkeys\": [\"<pubKey>\", ... ] , (array, optional) Array of strings giving pubkeys that must occur in the output or redeemscript\n" " \"keys\": [\"<key>\", ... ] , (array, optional) Array of strings giving private keys whose corresponding public keys must occur in the output or redeemscript\n" " \"internal\": <true> , (boolean, optional, default: false) Stating whether matching outputs should be treated as not incoming payments\n" " \"watchonly\": <true> , (boolean, optional, default: false) Stating whether matching outputs should be considered watched even when they're not spendable, only allowed if keys are empty\n" " \"label\": <label> , (string, optional, default: '') Label to assign to the address (aka account name, for now), only allowed with internal=false\n" " }\n" " ,...\n" " ]\n" "2. options (json, optional)\n" " {\n" " \"rescan\": <false>, (boolean, optional, default: true) Stating if should rescan the blockchain after all imports\n" " }\n" "\nNote: This call can take over an hour to complete if rescan is true, during that time, other rpc calls\n" "may report that the imported keys, addresses or scripts exists but related transactions are still missing.\n" "\nExamples:\n" + HelpExampleCli("importmulti", "'[{ \"scriptPubKey\": { \"address\": \"<my address>\" }, \"timestamp\":1455191478 }, " "{ \"scriptPubKey\": { \"address\": \"<my 2nd address>\" }, \"label\": \"example 2\", \"timestamp\": 1455191480 }]'") + HelpExampleCli("importmulti", "'[{ \"scriptPubKey\": { \"address\": \"<my address>\" }, \"timestamp\":1455191478 }]' '{ \"rescan\": false}'") + "\nResponse is an array with the same size as the input that has the execution result :\n" " [{ \"success\": true } , { \"success\": false, \"error\": { \"code\": -1, \"message\": \"Internal Server Error\"} }, ... ]\n"); // clang-format on RPCTypeCheck(mainRequest.params, {UniValue::VARR, UniValue::VOBJ}); const UniValue& requests = mainRequest.params[0]; //Default options bool fRescan = true; if (!mainRequest.params[1].isNull()) { const UniValue& options = mainRequest.params[1]; if (options.exists("rescan")) { fRescan = options["rescan"].get_bool(); } } WalletRescanReserver reserver(pwallet); if (fRescan && !reserver.reserve()) { throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait."); } int64_t now = 0; bool fRunScan = false; int64_t nLowestTimestamp = 0; UniValue response(UniValue::VARR); { LOCK2(cs_main, pwallet->cs_wallet); EnsureWalletIsUnlocked(pwallet); // Verify all timestamps are present before importing any keys. now = chainActive.Tip() ? chainActive.Tip()->GetMedianTimePast() : 0; for (const UniValue& data : requests.getValues()) { GetImportTimestamp(data, now); } const int64_t minimumTimestamp = 1; if (fRescan && chainActive.Tip()) { nLowestTimestamp = chainActive.Tip()->GetBlockTime(); } else { fRescan = false; } for (const UniValue& data : requests.getValues()) { const int64_t timestamp = std::max(GetImportTimestamp(data, now), minimumTimestamp); const UniValue result = ProcessImport(pwallet, data, timestamp); response.push_back(result); if (!fRescan) { continue; } // If at least one request was successful then allow rescan. if (result["success"].get_bool()) { fRunScan = true; } // Get the lowest timestamp. if (timestamp < nLowestTimestamp) { nLowestTimestamp = timestamp; } } } if (fRescan && fRunScan && requests.size()) { int64_t scannedTime = pwallet->RescanFromTime(nLowestTimestamp, reserver, true /* update */); pwallet->ReacceptWalletTransactions(); if (pwallet->IsAbortingRescan()) { throw JSONRPCError(RPC_MISC_ERROR, "Rescan aborted by user."); } if (scannedTime > nLowestTimestamp) { std::vector<UniValue> results = response.getValues(); response.clear(); response.setArray(); size_t i = 0; for (const UniValue& request : requests.getValues()) { // If key creation date is within the successfully scanned // range, or if the import result already has an error set, let // the result stand unmodified. Otherwise replace the result // with an error message. if (scannedTime <= GetImportTimestamp(request, now) || results.at(i).exists("error")) { response.push_back(results.at(i)); } else { UniValue result = UniValue(UniValue::VOBJ); result.pushKV("success", UniValue(false)); result.pushKV( "error", JSONRPCError( RPC_MISC_ERROR, strprintf("Rescan failed for key with creation timestamp %d. There was an error reading a " "block from time %d, which is after or within %d seconds of key creation, and " "could contain transactions pertaining to the key. As a result, transactions " "and coins using this key may not appear in the wallet. This error could be " "caused by pruning or data corruption (see spored log for details) and could " "be dealt with by downloading and rescanning the relevant blocks (see -reindex " "and -rescan options).", GetImportTimestamp(request, now), scannedTime - TIMESTAMP_WINDOW - 1, TIMESTAMP_WINDOW))); response.push_back(std::move(result)); } ++i; } } } return response; }
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/gaap/v20180529/model/ModifyCertificateAttributesRequest.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using namespace TencentCloud::Gaap::V20180529::Model; using namespace std; ModifyCertificateAttributesRequest::ModifyCertificateAttributesRequest() : m_certificateIdHasBeenSet(false), m_certificateAliasHasBeenSet(false) { } string ModifyCertificateAttributesRequest::ToJsonString() const { rapidjson::Document d; d.SetObject(); rapidjson::Document::AllocatorType& allocator = d.GetAllocator(); if (m_certificateIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "CertificateId"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_certificateId.c_str(), allocator).Move(), allocator); } if (m_certificateAliasHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "CertificateAlias"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_certificateAlias.c_str(), allocator).Move(), allocator); } rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); } string ModifyCertificateAttributesRequest::GetCertificateId() const { return m_certificateId; } void ModifyCertificateAttributesRequest::SetCertificateId(const string& _certificateId) { m_certificateId = _certificateId; m_certificateIdHasBeenSet = true; } bool ModifyCertificateAttributesRequest::CertificateIdHasBeenSet() const { return m_certificateIdHasBeenSet; } string ModifyCertificateAttributesRequest::GetCertificateAlias() const { return m_certificateAlias; } void ModifyCertificateAttributesRequest::SetCertificateAlias(const string& _certificateAlias) { m_certificateAlias = _certificateAlias; m_certificateAliasHasBeenSet = true; } bool ModifyCertificateAttributesRequest::CertificateAliasHasBeenSet() const { return m_certificateAliasHasBeenSet; }
#include <algorithm> #include <set> #include <stdlib.h> #include <iostream> #include "common/params.h" #include "common/swaglog.h" #include "wifiManager.h" /** * We are using a NetworkManager DBUS API : https://developer.gnome.org/NetworkManager/1.26/spec.html * */ // https://developer.gnome.org/NetworkManager/1.26/nm-dbus-types.html#NM80211ApFlags const int NM_802_11_AP_FLAGS_PRIVACY = 0x00000001; // https://developer.gnome.org/NetworkManager/1.26/nm-dbus-types.html#NM80211ApSecurityFlags const int NM_802_11_AP_SEC_PAIR_WEP40 = 0x00000001; const int NM_802_11_AP_SEC_PAIR_WEP104 = 0x00000002; const int NM_802_11_AP_SEC_GROUP_WEP40 = 0x00000010; const int NM_802_11_AP_SEC_GROUP_WEP104 = 0x00000020; const int NM_802_11_AP_SEC_KEY_MGMT_PSK = 0x00000100; const int NM_802_11_AP_SEC_KEY_MGMT_802_1X = 0x00000200; const QString nm_path = "/org/freedesktop/NetworkManager"; const QString nm_settings_path = "/org/freedesktop/NetworkManager/Settings"; const QString nm_iface = "org.freedesktop.NetworkManager"; const QString props_iface = "org.freedesktop.DBus.Properties"; const QString nm_settings_iface = "org.freedesktop.NetworkManager.Settings"; const QString nm_settings_conn_iface = "org.freedesktop.NetworkManager.Settings.Connection"; const QString device_iface = "org.freedesktop.NetworkManager.Device"; const QString wireless_device_iface = "org.freedesktop.NetworkManager.Device.Wireless"; const QString ap_iface = "org.freedesktop.NetworkManager.AccessPoint"; const QString connection_iface = "org.freedesktop.NetworkManager.Connection.Active"; const QString ipv4config_iface = "org.freedesktop.NetworkManager.IP4Config"; const QString nm_service = "org.freedesktop.NetworkManager"; const int state_connected = 100; const int state_need_auth = 60; const int reason_wrong_password = 8; const int dbus_timeout = 100; template <typename T> T get_response(QDBusMessage response) { QVariant first = response.arguments().at(0); QDBusVariant dbvFirst = first.value<QDBusVariant>(); QVariant vFirst = dbvFirst.variant(); if (vFirst.canConvert<T>()) { return vFirst.value<T>(); } else { LOGE("Variant unpacking failure"); return T(); } } bool compare_by_strength(const Network &a, const Network &b) { if (a.connected == ConnectedType::CONNECTED) return true; if (b.connected == ConnectedType::CONNECTED) return false; if (a.connected == ConnectedType::CONNECTING) return true; if (b.connected == ConnectedType::CONNECTING) return false; return a.strength > b.strength; } WifiManager::WifiManager(QWidget* parent) { qDBusRegisterMetaType<Connection>(); qDBusRegisterMetaType<IpConfig>(); connecting_to_network = ""; adapter = get_adapter(); bool has_adapter = adapter != ""; if (!has_adapter){ throw std::runtime_error("Error connecting to NetworkManager"); } QDBusInterface nm(nm_service, adapter, device_iface, bus); bus.connect(nm_service, adapter, device_iface, "StateChanged", this, SLOT(change(unsigned int, unsigned int, unsigned int))); QDBusInterface device_props(nm_service, adapter, props_iface, bus); device_props.setTimeout(dbus_timeout); QDBusMessage response = device_props.call("Get", device_iface, "State"); raw_adapter_state = get_response<uint>(response); change(raw_adapter_state, 0, 0); // Set tethering ssid as "weedle" + first 4 characters of a dongle id tethering_ssid = "weedle"; std::string bytes = Params().get("DongleId"); if (bytes.length() >= 4) { tethering_ssid+="-"+QString::fromStdString(bytes.substr(0,4)); } // Create dbus interface for tethering button. This populates the introspection cache, // making sure all future creations are non-blocking // https://bugreports.qt.io/browse/QTBUG-14485 QDBusInterface(nm_service, nm_settings_path, nm_settings_iface, bus); } void WifiManager::refreshNetworks() { seen_networks.clear(); seen_ssids.clear(); ipv4_address = get_ipv4_address(); for (Network &network : get_networks()) { if (seen_ssids.count(network.ssid)) { continue; } seen_ssids.push_back(network.ssid); seen_networks.push_back(network); } } QString WifiManager::get_ipv4_address(){ if (raw_adapter_state != state_connected){ return ""; } QVector<QDBusObjectPath> conns = get_active_connections(); for (auto &p : conns){ QString active_connection = p.path(); QDBusInterface nm(nm_service, active_connection, props_iface, bus); nm.setTimeout(dbus_timeout); QDBusObjectPath pth = get_response<QDBusObjectPath>(nm.call("Get", connection_iface, "Ip4Config")); QString ip4config = pth.path(); QString type = get_response<QString>(nm.call("Get", connection_iface, "Type")); if (type == "802-11-wireless") { QDBusInterface nm2(nm_service, ip4config, props_iface, bus); nm2.setTimeout(dbus_timeout); const QDBusArgument &arr = get_response<QDBusArgument>(nm2.call("Get", ipv4config_iface, "AddressData")); QMap<QString, QVariant> pth2; arr.beginArray(); while (!arr.atEnd()){ arr >> pth2; QString ipv4 = pth2.value("address").value<QString>(); arr.endArray(); return ipv4; } arr.endArray(); } } return ""; } QList<Network> WifiManager::get_networks() { QList<Network> r; QDBusInterface nm(nm_service, adapter, wireless_device_iface, bus); nm.setTimeout(dbus_timeout); QDBusMessage response = nm.call("GetAllAccessPoints"); QVariant first = response.arguments().at(0); QString active_ap = get_active_ap(); const QDBusArgument &args = first.value<QDBusArgument>(); args.beginArray(); while (!args.atEnd()) { QDBusObjectPath path; args >> path; QByteArray ssid = get_property(path.path(), "Ssid"); unsigned int strength = get_ap_strength(path.path()); SecurityType security = getSecurityType(path.path()); ConnectedType ctype; if (path.path() != active_ap) { ctype = ConnectedType::DISCONNECTED; } else { if (ssid == connecting_to_network) { ctype = ConnectedType::CONNECTING; } else { ctype = ConnectedType::CONNECTED; } } Network network = {path.path(), ssid, strength, ctype, security}; if (ssid.length()) { r.push_back(network); } } args.endArray(); std::sort(r.begin(), r.end(), compare_by_strength); return r; } SecurityType WifiManager::getSecurityType(QString path) { int sflag = get_property(path, "Flags").toInt(); int wpaflag = get_property(path, "WpaFlags").toInt(); int rsnflag = get_property(path, "RsnFlags").toInt(); int wpa_props = wpaflag | rsnflag; // obtained by looking at flags of networks in the office as reported by an Android phone const int supports_wpa = NM_802_11_AP_SEC_PAIR_WEP40 | NM_802_11_AP_SEC_PAIR_WEP104 | NM_802_11_AP_SEC_GROUP_WEP40 | NM_802_11_AP_SEC_GROUP_WEP104 | NM_802_11_AP_SEC_KEY_MGMT_PSK; if (sflag == 0) { return SecurityType::OPEN; } else if ((sflag & NM_802_11_AP_FLAGS_PRIVACY) && (wpa_props & supports_wpa) && !(wpa_props & NM_802_11_AP_SEC_KEY_MGMT_802_1X)) { return SecurityType::WPA; } else { return SecurityType::UNSUPPORTED; } } void WifiManager::connect(Network n) { return connect(n, "", ""); } void WifiManager::connect(Network n, QString password) { return connect(n, "", password); } void WifiManager::connect(Network n, QString username, QString password) { connecting_to_network = n.ssid; // disconnect(); clear_connections(n.ssid); //Clear all connections that may already exist to the network we are connecting connect(n.ssid, username, password, n.security_type); } void WifiManager::connect(QByteArray ssid, QString username, QString password, SecurityType security_type) { Connection connection; connection["connection"]["type"] = "802-11-wireless"; connection["connection"]["uuid"] = QUuid::createUuid().toString().remove('{').remove('}'); connection["connection"]["id"] = "openpilot connection "+QString::fromStdString(ssid.toStdString()); connection["connection"]["autoconnect-retries"] = 0; connection["802-11-wireless"]["ssid"] = ssid; connection["802-11-wireless"]["mode"] = "infrastructure"; if (security_type == SecurityType::WPA) { connection["802-11-wireless-security"]["key-mgmt"] = "wpa-psk"; connection["802-11-wireless-security"]["auth-alg"] = "open"; connection["802-11-wireless-security"]["psk"] = password; } connection["ipv4"]["method"] = "auto"; connection["ipv6"]["method"] = "ignore"; QDBusInterface nm_settings(nm_service, nm_settings_path, nm_settings_iface, bus); nm_settings.setTimeout(dbus_timeout); nm_settings.call("AddConnection", QVariant::fromValue(connection)); activate_wifi_connection(QString(ssid)); } void WifiManager::deactivate_connections(QString ssid) { for (QDBusObjectPath active_connection_raw : get_active_connections()) { QString active_connection = active_connection_raw.path(); QDBusInterface nm(nm_service, active_connection, props_iface, bus); nm.setTimeout(dbus_timeout); QDBusObjectPath pth = get_response<QDBusObjectPath>(nm.call("Get", connection_iface, "SpecificObject")); if (pth.path() != "" && pth.path() != "/") { QString Ssid = get_property(pth.path(), "Ssid"); if (Ssid == ssid) { QDBusInterface nm2(nm_service, nm_path, nm_iface, bus); nm2.setTimeout(dbus_timeout); nm2.call("DeactivateConnection", QVariant::fromValue(active_connection_raw));// TODO change to disconnect } } } } QVector<QDBusObjectPath> WifiManager::get_active_connections() { QDBusInterface nm(nm_service, nm_path, props_iface, bus); nm.setTimeout(dbus_timeout); QDBusMessage response = nm.call("Get", nm_iface, "ActiveConnections"); const QDBusArgument &arr = get_response<QDBusArgument>(response); QVector<QDBusObjectPath> conns; QDBusObjectPath path; arr.beginArray(); while (!arr.atEnd()) { arr >> path; conns.push_back(path); } arr.endArray(); return conns; } void WifiManager::clear_connections(QString ssid) { for(QDBusObjectPath path : list_connections()){ QDBusInterface nm2(nm_service, path.path(), nm_settings_conn_iface, bus); nm2.setTimeout(dbus_timeout); QDBusMessage response = nm2.call("GetSettings"); const QDBusArgument &dbusArg = response.arguments().at(0).value<QDBusArgument>(); QMap<QString, QMap<QString,QVariant>> map; dbusArg >> map; for (auto &inner : map) { for (auto &val : inner) { QString key = inner.key(val); if (key == "ssid") { if (val == ssid) { nm2.call("Delete"); } } } } } } void WifiManager::request_scan() { QDBusInterface nm(nm_service, adapter, wireless_device_iface, bus); nm.setTimeout(dbus_timeout); nm.call("RequestScan", QVariantMap()); } uint WifiManager::get_wifi_device_state() { QDBusInterface device_props(nm_service, adapter, props_iface, bus); device_props.setTimeout(dbus_timeout); QDBusMessage response = device_props.call("Get", device_iface, "State"); uint resp = get_response<uint>(response); return resp; } QString WifiManager::get_active_ap() { QDBusInterface device_props(nm_service, adapter, props_iface, bus); device_props.setTimeout(dbus_timeout); QDBusMessage response = device_props.call("Get", wireless_device_iface, "ActiveAccessPoint"); QDBusObjectPath r = get_response<QDBusObjectPath>(response); return r.path(); } QByteArray WifiManager::get_property(QString network_path ,QString property) { QDBusInterface device_props(nm_service, network_path, props_iface, bus); device_props.setTimeout(dbus_timeout); QDBusMessage response = device_props.call("Get", ap_iface, property); return get_response<QByteArray>(response); } unsigned int WifiManager::get_ap_strength(QString network_path) { QDBusInterface device_props(nm_service, network_path, props_iface, bus); device_props.setTimeout(dbus_timeout); QDBusMessage response = device_props.call("Get", ap_iface, "Strength"); return get_response<unsigned int>(response); } QString WifiManager::get_adapter() { QDBusInterface nm(nm_service, nm_path, nm_iface, bus); nm.setTimeout(dbus_timeout); QDBusMessage response = nm.call("GetDevices"); QVariant first = response.arguments().at(0); QString adapter_path = ""; const QDBusArgument &args = first.value<QDBusArgument>(); args.beginArray(); while (!args.atEnd()) { QDBusObjectPath path; args >> path; // Get device type QDBusInterface device_props(nm_service, path.path(), props_iface, bus); device_props.setTimeout(dbus_timeout); QDBusMessage response = device_props.call("Get", device_iface, "DeviceType"); uint device_type = get_response<uint>(response); if (device_type == 2) { // Wireless adapter_path = path.path(); break; } } args.endArray(); return adapter_path; } void WifiManager::change(unsigned int new_state, unsigned int previous_state, unsigned int change_reason) { raw_adapter_state = new_state; if (new_state == state_need_auth && change_reason == reason_wrong_password) { emit wrongPassword(connecting_to_network); } else if (new_state == state_connected) { emit successfulConnection(connecting_to_network); connecting_to_network = ""; } } void WifiManager::disconnect() { QString active_ap = get_active_ap(); if (active_ap != "" && active_ap != "/") { deactivate_connections(get_property(active_ap, "Ssid")); } } QVector<QDBusObjectPath> WifiManager::list_connections(){ QVector<QDBusObjectPath> connections; QDBusInterface nm(nm_service, nm_settings_path, nm_settings_iface, bus); nm.setTimeout(dbus_timeout); QDBusMessage response = nm.call("ListConnections"); QVariant first = response.arguments().at(0); const QDBusArgument &args = first.value<QDBusArgument>(); args.beginArray(); while (!args.atEnd()) { QDBusObjectPath path; args >> path; connections.push_back(path); } return connections; } bool WifiManager::activate_wifi_connection(QString ssid){ QString devicePath = get_adapter(); for(QDBusObjectPath path : list_connections()){ QDBusInterface nm2(nm_service, path.path(), nm_settings_conn_iface, bus); nm2.setTimeout(dbus_timeout); QDBusMessage response = nm2.call("GetSettings"); const QDBusArgument &dbusArg = response.arguments().at(0).value<QDBusArgument>(); QMap<QString, QMap<QString,QVariant>> map; dbusArg >> map; for (auto &inner : map) { for (auto &val : inner) { QString key = inner.key(val); if (key == "ssid") { if (val == ssid) { QDBusInterface nm3(nm_service, nm_path, nm_iface, bus); nm3.setTimeout(dbus_timeout); nm3.call("ActivateConnection", QVariant::fromValue(path), QVariant::fromValue(QDBusObjectPath(devicePath)), QVariant::fromValue(QDBusObjectPath("/"))); return true; } } } } } return false; } //Functions for tethering bool WifiManager::activate_tethering_connection(){ QString devicePath = get_adapter(); for(QDBusObjectPath path : list_connections()){ QDBusInterface nm2(nm_service, path.path(), nm_settings_conn_iface, bus); nm2.setTimeout(dbus_timeout); QDBusMessage response = nm2.call("GetSettings"); const QDBusArgument &dbusArg = response.arguments().at(0).value<QDBusArgument>(); QMap<QString, QMap<QString,QVariant>> map; dbusArg >> map; for (auto &inner : map) { for (auto &val : inner) { QString key = inner.key(val); if (key == "ssid") { if (val == tethering_ssid.toUtf8()) { QDBusInterface nm3(nm_service, nm_path, nm_iface, bus); nm3.setTimeout(dbus_timeout); nm3.call("ActivateConnection", QVariant::fromValue(path), QVariant::fromValue(QDBusObjectPath(devicePath)), QVariant::fromValue(QDBusObjectPath("/"))); return true; } } } } } return false; } void WifiManager::addTetheringConnection(){ Connection connection; connection["connection"]["id"] = "Hotspot"; connection["connection"]["uuid"] = QUuid::createUuid().toString().remove('{').remove('}'); connection["connection"]["type"] = "802-11-wireless"; connection["connection"]["interface-name"] = "wlan0"; connection["connection"]["autoconnect"] = false; connection["802-11-wireless"]["band"] = "bg"; connection["802-11-wireless"]["mode"] = "ap"; connection["802-11-wireless"]["ssid"] = tethering_ssid.toUtf8(); connection["802-11-wireless-security"]["group"] = QStringList("ccmp"); connection["802-11-wireless-security"]["key-mgmt"] = "wpa-psk"; connection["802-11-wireless-security"]["pairwise"] = QStringList("ccmp"); connection["802-11-wireless-security"]["proto"] = QStringList("rsn"); connection["802-11-wireless-security"]["psk"] = tetheringPassword; connection["ipv4"]["method"] = "shared"; QMap<QString,QVariant> address; address["address"] = "192.168.43.1"; address["prefix"] = 24u; connection["ipv4"]["address-data"] = QVariant::fromValue(IpConfig() << address); connection["ipv4"]["gateway"] = "192.168.43.1"; connection["ipv6"]["method"] = "ignore"; QDBusInterface nm_settings(nm_service, nm_settings_path, nm_settings_iface, bus); nm_settings.setTimeout(dbus_timeout); nm_settings.call("AddConnection", QVariant::fromValue(connection)); } void WifiManager::enableTethering() { if(activate_tethering_connection()){ return; } addTetheringConnection(); activate_tethering_connection(); } void WifiManager::disableTethering() { deactivate_connections(tethering_ssid.toUtf8()); } bool WifiManager::tetheringEnabled() { QString active_ap = get_active_ap(); return get_property(active_ap, "Ssid") == tethering_ssid; } void WifiManager::changeTetheringPassword(QString newPassword){ tetheringPassword = newPassword; clear_connections(tethering_ssid.toUtf8()); addTetheringConnection(); }
//Copyupper 2021 Adam G. Smith // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http ://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. #ifndef ANVIL_COMPUTE_VECTOR_HPP #define ANVIL_COMPUTE_VECTOR_HPP #include "anvil/core/Keywords.hpp" #include "anvil/core/Assert.hpp" #if ANVIL_CPU_ARCHITECTURE == ANVIL_CPU_X86 || ANVIL_CPU_ARCHITECTURE == ANVIL_CPU_X86_64 #include <intrin.h> #endif namespace anvil { namespace detail { template<class T, size_t SIZE> struct BasicVector; template<class T, size_t SIZE> struct VectorTypeSelector { typedef BasicVector<T, SIZE> type; }; template<class T> struct VectorTypeSelector<T, 0u> { typedef T type; }; template<class T> struct VectorTypeSelector<T, 1u> { typedef T type; }; template<class T, size_t SIZE> struct UnoptimisedNativeType { T data[SIZE]; }; template<class T, size_t SIZE> struct NativeVectorSelector { typedef UnoptimisedNativeType<T, SIZE> type; }; #if ANVIL_CPU_ARCHITECTURE == ANVIL_CPU_X86 || ANVIL_CPU_ARCHITECTURE == ANVIL_CPU_X86_64 template<> struct NativeVectorSelector<float, 4u> { typedef __m128 type; }; template<> struct NativeVectorSelector<double, 2u> { typedef __m128d type; }; template<> struct NativeVectorSelector<uint8_t, 16u> { typedef __m128i type; }; template<> struct NativeVectorSelector<uint16_t, 8u> { typedef __m128i type; }; template<> struct NativeVectorSelector<uint32_t, 4u> { typedef __m128i type; }; template<> struct NativeVectorSelector<uint64_t, 2u> { typedef __m128i type; }; template<> struct NativeVectorSelector<int8_t, 16u> { typedef __m128i type; }; template<> struct NativeVectorSelector<int16_t, 8u> { typedef __m128i type; }; template<> struct NativeVectorSelector<int32_t, 4u> { typedef __m128i type; }; template<> struct NativeVectorSelector<int64_t, 2u> { typedef __m128i type; }; template<> struct NativeVectorSelector<float, 8u> { typedef __m256 type; }; template<> struct NativeVectorSelector<double, 4u> { typedef __m256d type; }; template<> struct NativeVectorSelector<uint8_t, 32u> { typedef __m256i type; }; template<> struct NativeVectorSelector<uint16_t, 16u> { typedef __m256i type; }; template<> struct NativeVectorSelector<uint32_t, 8u> { typedef __m256i type; }; template<> struct NativeVectorSelector<uint64_t, 4u> { typedef __m256i type; }; template<> struct NativeVectorSelector<int8_t, 32u> { typedef __m256i type; }; template<> struct NativeVectorSelector<int16_t, 16u> { typedef __m256i type; }; template<> struct NativeVectorSelector<int32_t, 8u> { typedef __m256i type; }; template<> struct NativeVectorSelector<int64_t, 4u> { typedef __m256i type; }; template<> struct NativeVectorSelector<float, 16u> { typedef __m512 type; }; template<> struct NativeVectorSelector<double, 8u> { typedef __m512d type; }; template<> struct NativeVectorSelector<uint8_t, 64u> { typedef __m512i type; }; template<> struct NativeVectorSelector<uint16_t, 32u> { typedef __m512i type; }; template<> struct NativeVectorSelector<uint32_t, 16u> { typedef __m512i type; }; template<> struct NativeVectorSelector<uint64_t, 8u> { typedef __m512i type; }; template<> struct NativeVectorSelector<int8_t, 64u> { typedef __m512i type; }; template<> struct NativeVectorSelector<int16_t, 32u> { typedef __m512i type; }; template<> struct NativeVectorSelector<int32_t, 16u> { typedef __m512i type; }; template<> struct NativeVectorSelector<int64_t, 8u> { typedef __m512i type; }; #endif } template<class T, size_t SIZE> using Vector = typename detail::VectorTypeSelector<T, SIZE>::type; namespace detail { #pragma pack(push, 1) template<class T, size_t SIZE> struct BasicVector { typedef T type; enum { size = SIZE, upper_size = SIZE / 2, lower_size = size - upper_size }; typedef Vector<T, lower_size> lower_t; typedef Vector<T, upper_size> upper_t; typedef typename detail::NativeVectorSelector<type, size>::type native_t; union { struct { lower_t lower_half; upper_t upper_half; }; native_t native; T data[size]; }; BasicVector() = default; ~BasicVector() = default; BasicVector(const Vector<T, lower_size>& a, const Vector<T, upper_size>& b) : lower_half(a), upper_half(b) {} template<size_t S1, size_t S2> BasicVector(const Vector<T,S1>& a, const Vector<T, S2>& b) { static_assert((S1 + S2) == size, "anvil::BasicVector : Vector sizes must add upp"); SetSubVector<S1>(a, 0u); SetSubVector<S2>(b, S1); } template<size_t S1, size_t S2, size_t S3> BasicVector(const Vector<T, S1>& a, const Vector<T, S2>& b, const Vector<T, S3>& c) { static_assert((S1 + S2 + S3) == size, "anvil::BasicVector : Vector sizes must add upp"); SetSubVector<S1>(a, 0u); SetSubVector<S2>(b, S1); SetSubVector<S3>(c, S1 + S2); } template<size_t S1, size_t S2, size_t S3, size_t S4> BasicVector(const Vector<T, S1>& a, const Vector<T, S2>& b, const Vector<T, S3>& c, const Vector<T, S4>& d) { static_assert((S1 + S2 + S3 + S4) == size, "anvil::BasicVector : Vector sizes must add upp"); SetSubVector<S1>(a, 0u); SetSubVector<S2>(b, S1); SetSubVector<S3>(c, S1 + S2); SetSubVector<S4>(c, S1 + S2 + S3); } template<size_t S1, size_t S2, size_t S3, size_t S4, size_t S5> BasicVector(const Vector<T, S1>& a, const Vector<T, S2>& b, const Vector<T, S3>& c, const Vector<T, S4>& d, const Vector<T, S5>& e) { static_assert((S1 + S2 + S3 + S4 + S5) == size, "anvil::BasicVector : Vector sizes must add upp"); SetSubVector<S1>(a, 0u); SetSubVector<S2>(b, S1); SetSubVector<S3>(c, S1 + S2); SetSubVector<S4>(d, S1 + S2 + S3); SetSubVector<S5>(e, S1 + S2 + S3 + S4); } template<size_t S1, size_t S2, size_t S3, size_t S4, size_t S5, size_t S6> BasicVector(const Vector<T, S1>& a, const Vector<T, S2>& b, const Vector<T, S3>& c, const Vector<T, S4>& d, const Vector<T, S5>& e, const Vector<T, S6>& f) { static_assert((S1 + S2 + S3 + S4 + S5 + S6) == size, "anvil::BasicVector : Vector sizes must add upp"); SetSubVector<S1>(a, 0u); SetSubVector<S2>(b, S1); SetSubVector<S3>(c, S1 + S2); SetSubVector<S4>(d, S1 + S2 + S3); SetSubVector<S5>(e, S1 + S2 + S3 + S4); SetSubVector<S6>(f, S1 + S2 + S3 + S4 + S5); } template<size_t S1, size_t S2, size_t S3, size_t S4, size_t S5, size_t S6, size_t S7> BasicVector(const Vector<T, S1>& a, const Vector<T, S2>& b, const Vector<T, S3>& c, const Vector<T, S4>& d, const Vector<T, S5>& e, const Vector<T, S6>& f, const Vector<T, S7>& g) { static_assert((S1 + S2 + S3 + S4 + S5 + S6 + S7) == size, "anvil::BasicVector : Vector sizes must add upp"); SetSubVector<S1>(a, 0u); SetSubVector<S2>(b, S1); SetSubVector<S3>(c, S1 + S2); SetSubVector<S4>(d, S1 + S2 + S3); SetSubVector<S5>(e, S1 + S2 + S3 + S4); SetSubVector<S6>(f, S1 + S2 + S3 + S4 + S5); SetSubVector<S7>(g, S1 + S2 + S3 + S4 + S5 + S6); } template<size_t S1, size_t S2, size_t S3, size_t S4, size_t S5, size_t S6, size_t S7, size_t S8> BasicVector(const Vector<T, S1>& a, const Vector<T, S2>& b, const Vector<T, S3>& c, const Vector<T, S4>& d, const Vector<T, S5>& e, const Vector<T, S6>& f, const Vector<T, S7>& g, const Vector<T, S8>& h) { static_assert((S1 + S2 + S3 + S4 + S5 + S6 + S7 + S8) == size, "anvil::BasicVector : Vector sizes must add upp"); SetSubVector<S1>(a, 0u); SetSubVector<S2>(b, S1); SetSubVector<S3>(c, S1 + S2); SetSubVector<S4>(d, S1 + S2 + S3); SetSubVector<S5>(e, S1 + S2 + S3 + S4); SetSubVector<S6>(f, S1 + S2 + S3 + S4 + S5); SetSubVector<S7>(g, S1 + S2 + S3 + S4 + S5 + S6); SetSubVector<S8>(h, S1 + S2 + S3 + S4 + S5 + S6 + S7); } ANVIL_STRONG_INLINE T& operator[](const size_t i) throw() { return data[i]; } ANVIL_STRONG_INLINE T operator[](const size_t i) const throw() { return data[i]; } template<size_t SIZE2> ANVIL_STRONG_INLINE Vector<type, SIZE2>& GetSubVector(size_t offset) throw() { ANVIL_ASSUME(SIZE2 + offset <= size); return *reinterpret_cast<Vector<type, SIZE2>*>(data + offset); } template<size_t SIZE2> ANVIL_STRONG_INLINE const Vector<type, SIZE2>& GetSubVector(size_t offset) const throw() { ANVIL_ASSUME(SIZE2 + offset <= size); return *reinterpret_cast<const Vector<type, SIZE2>*>(data + offset); } template<size_t SIZE2> ANVIL_STRONG_INLINE void SetSubVector(const Vector<type, SIZE2>& x, size_t offset) { ANVIL_ASSUME(SIZE2 + offset <= size); Vector<type, SIZE2>& dst = GetSubVector(offset); dst = x; } ANVIL_STRONG_INLINE Vector<T, size>& operator+=(const Vector<T, size>& other) throw() { return *this = *this + other; } ANVIL_STRONG_INLINE Vector<T, size>& operator-=(const Vector<T, size>& other) throw() { return *this = *this - other; } ANVIL_STRONG_INLINE Vector<T, size>& operator*=(const Vector<T, size>& other) throw() { return *this = *this * other; } ANVIL_STRONG_INLINE Vector<T, size>& operator/=(const Vector<T, size>& other) throw() { return *this = *this / other; } ANVIL_STRONG_INLINE Vector<T, size>& operator&=(const Vector<T, size>& other) throw() { return *this = *this & other; } ANVIL_STRONG_INLINE Vector<T, size>& operator|=(const Vector<T, size>& other) throw() { return *this = *this | other; } ANVIL_STRONG_INLINE Vector<T, size>& operator^=(const Vector<T, size>& other) throw() { return *this = *this ^ other; } }; #pragma pack(pop) } // Check that the union inside of BasicVector is the correct size static_assert(sizeof(Vector<float32_t, 4u>) == sizeof(float32_t) * 4u, "Size of anvil::Vector<float32_t, 4u> is different than expected"); //static_assert(sizeof(Vector<float32_t, 7u>) == sizeof(float32_t) * 7u, "Size of anvil::Vector<float32_t, 7u> is different than expected"); static_assert(sizeof(Vector<float32_t, 8u>) == sizeof(float32_t) * 8u, "Size of anvil::Vector<float32_t, 8u> is different than expected"); static_assert(sizeof(Vector<float32_t, 16u>) == sizeof(float32_t) * 16u, "Size of anvil::Vector<float32_t, 16u> is different than expected"); } #endif
#include "chunk_renderer.h" #include "world/block_data.h" #include "world/chunk.h" #include "chunk_mesh.h" // clang-format off // uses a direction index to index CUBE_VERTICES constexpr uint32_t CUBE_INDICES[] = { 6, 7, 4, 5, // north 3, 2, 1, 0, // south 2, 6, 5, 1, // east 7, 3, 0, 4, // west 2, 3, 7, 6, // top 0, 1, 5, 4, // bottom }; constexpr glm::vec3 CUBE_VERTICES[] = { { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f }, { 1.0f, 1.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f }, { 1.0f, 0.0f, 1.0f }, { 1.0f, 1.0f, 1.0f }, { 0.0f, 1.0f, 1.0f } }; constexpr glm::vec2 CUBE_UVS[] = { { 0.0f, 0.0f }, { 1.0f, 0.0f }, { 1.0f, 1.0f }, { 0.0f, 1.0f } }; // clang-format on ChunkMesh::ChunkMesh(ChunkRenderer* chunkRenderer) : m_vertexBuffer(MAX_VERTICES * sizeof(Vertex)), m_chunkRenderer(chunkRenderer) { BufferElement layout[] = { { GL_FLOAT, 3 }, { GL_FLOAT, 2 } }; m_vertexArray.addVertexBuffer(m_vertexBuffer, layout, 2); m_indexBuffer.setIndices(m_chunkRenderer->getMeshIndices(), MAX_INDICES_COUNT); m_vertexArray.setIndexBuffer(m_indexBuffer); m_vertexBufferBase = new Vertex[MAX_VERTICES]; } void ChunkMesh::regenerateMesh(const Chunk& chunk) { m_indicesCount = 0; m_vertexBufferPtr = m_vertexBufferBase; m_chunkPos = chunk.getChunkPos(); for (int x = 0; x < CHUNK_SIZE; x++) { for (int y = 0; y < CHUNK_SIZE; y++) { for (int z = 0; z < CHUNK_SIZE; z++) { glm::ivec3 blockPos = { x, y, z }; blockid_t id = chunk.getBlock(blockPos); const BlockData& data = BlockDatabase::getBlockData(id); if (id == 0) continue; for (int dirIndex = 0; dirIndex < 6; dirIndex++) { Direction direction = static_cast<Direction>(dirIndex); const glm::ivec3& dirVec = DIRECTION_TO_VECTOR[direction]; glm::ivec3 neighbourPos = blockPos + dirVec; if (chunk.getBlock(neighbourPos) == 0) { FaceParams params(blockPos, direction); m_chunkRenderer->getTexture().getSubTextureUVs( data.texture, &params.uvMin, &params.uvMax); addFace(params); } } } } } if (m_indicesCount == 0) return; uint32_t size = static_cast<uint32_t>( reinterpret_cast<uint8_t*>(m_vertexBufferPtr) - reinterpret_cast<uint8_t*>(m_vertexBufferBase)); m_vertexBuffer.setDynamicData(m_vertexBufferBase, size); } void ChunkMesh::addFace(const FaceParams& params) { // gen vertices for (uint8_t i = 0; i < 4; i++) { const glm::ivec3& vertex = CUBE_VERTICES[CUBE_INDICES[(params.direction * 4) + i]]; m_vertexBufferPtr->position = vertex + params.blockPos; m_vertexBufferPtr->texCoord.x = CUBE_UVS[i].x ? params.uvMax.x : params.uvMin.x; m_vertexBufferPtr->texCoord.y = CUBE_UVS[i].y ? params.uvMax.y : params.uvMin.y; m_vertexBufferPtr++; } m_indicesCount += 6; } void ChunkMesh::render() { if (m_indicesCount == 0) return; m_vertexArray.bind(); m_vertexArray.draw(m_indicesCount); }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "ppl/kernel/riscv/common/internal_include.h" #include <string.h> namespace ppl { namespace kernel { namespace riscv { template <typename srcT, typename dstT> ppl::common::RetCode cast_kernel(const ppl::nn::TensorShape* src_shape, const ppl::nn::TensorShape* dst_shape, const srcT* src, dstT* dst) { const bool out_bool = dst_shape->GetDataType() == ppl::common::DATATYPE_BOOL; const uint64_t length = src_shape->GetElementsIncludingPadding(); if (out_bool) { for (uint64_t i = 0; i < length; i++) { dst[i] = src[i] != 0 ? 1 : 0; } } else { for (uint64_t i = 0; i < length; i++) { dst[i] = src[i]; } } return ppl::common::RC_SUCCESS; } ppl::common::RetCode cast(const ppl::nn::TensorShape* src_shape, const ppl::nn::TensorShape* dst_shape, const void* src, void* dst) { #define MAKE_CAST_TYPE(idt, odt) (((uint32_t)idt << 16) | (uint32_t)odt) auto idt = src_shape->GetDataType(); auto odt = dst_shape->GetDataType(); if (idt == odt) { memcpy(dst, src, dst_shape->GetBytesIncludingPadding()); return ppl::common::RC_SUCCESS; } switch (MAKE_CAST_TYPE(idt, odt)) { case MAKE_CAST_TYPE(ppl::common::DATATYPE_FLOAT32, ppl::common::DATATYPE_INT64): return cast_kernel<float, int64_t>(src_shape, dst_shape, (float*)src, (int64_t*)dst); case MAKE_CAST_TYPE(ppl::common::DATATYPE_FLOAT32, ppl::common::DATATYPE_BOOL): return cast_kernel<float, uint8_t>(src_shape, dst_shape, (float*)src, (uint8_t*)dst); case MAKE_CAST_TYPE(ppl::common::DATATYPE_INT64, ppl::common::DATATYPE_FLOAT32): return cast_kernel<int64_t, float>(src_shape, dst_shape, (int64_t*)src, (float*)dst); case MAKE_CAST_TYPE(ppl::common::DATATYPE_INT64, ppl::common::DATATYPE_BOOL): return cast_kernel<int64_t, uint8_t>(src_shape, dst_shape, (int64_t*)src, (uint8_t*)dst); case MAKE_CAST_TYPE(ppl::common::DATATYPE_BOOL, ppl::common::DATATYPE_FLOAT32): return cast_kernel<uint8_t, float>(src_shape, dst_shape, (uint8_t*)src, (float*)dst); case MAKE_CAST_TYPE(ppl::common::DATATYPE_BOOL, ppl::common::DATATYPE_INT64): return cast_kernel<uint8_t, int64_t>(src_shape, dst_shape, (uint8_t*)src, (int64_t*)dst); case MAKE_CAST_TYPE(ppl::common::DATATYPE_FLOAT32, ppl::common::DATATYPE_FLOAT64): return cast_kernel<float, double>(src_shape, dst_shape, (float*)src, (double*)dst); case MAKE_CAST_TYPE(ppl::common::DATATYPE_FLOAT64, ppl::common::DATATYPE_FLOAT32): return cast_kernel<double, float>(src_shape, dst_shape, (double*)src, (float*)dst); default: return ppl::common::RC_UNSUPPORTED; } return ppl::common::RC_UNSUPPORTED; } }}}; // namespace ppl::kernel::riscv
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/Scripting/Natives/Generated/game/IGameSystem.hpp> namespace RED4ext { namespace game { struct IVisionModeSystem : game::IGameSystem { static constexpr const char* NAME = "gameIVisionModeSystem"; static constexpr const char* ALIAS = NAME; }; RED4EXT_ASSERT_SIZE(IVisionModeSystem, 0x48); } // namespace game } // namespace RED4ext
// Author: btjanaka (Bryon Tjanaka) // Problem: (HackerRank) climbing-the-leaderboard // Title: Climbing the Leaderboard // Link: https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem // Idea: // Difficulty: medium // Tags: implementation #include <bits/stdc++.h> #define GET(x) scanf("%d", &x) #define GED(x) scanf("%lf", &x) using namespace std; typedef long long ll; typedef pair<int, int> ii; typedef vector<int> vi; int main() { int n, m, x; vector<ii> board; // input GET(n); for (int i = 0; i < n; ++i) { GET(x); x = -x; int rank; if (i == 0) { rank = 1; } else { if (x == board.back().first) { rank = board.back().second; } else { rank = board.back().second + 1; } } board.push_back({x, rank}); } // output GET(m); int alice; for (int i = 0; i < m; ++i) { GET(alice); auto it = lower_bound(board.begin(), board.end(), make_pair(-alice, 100), [](const ii& a, const ii& b) { return a.first < b.first; }); if (it == board.end()) { printf("%d\n", board.back().second + 1); } else { printf("%d\n", it->second); } } return 0; }
// // Copyright (C) 2001-2021 Greg Landrum and other RDKit contributors // // @@ All Rights Reserved @@ // This file is part of the RDKit. // The contents are covered by the terms of the BSD license // which is included in the file license.txt, found at the root // of the RDKit source tree. // #include <cmath> #include "ROMol.h" #include "Atom.h" #include "PeriodicTable.h" #include "SanitException.h" #include "QueryOps.h" #include "MonomerInfo.h" #include <RDGeneral/Invariant.h> #include <RDGeneral/RDLog.h> #include <RDGeneral/types.h> #include <RDGeneral/Dict.h> namespace RDKit { // Determine whether or not a molecule is to the left of Carbon bool isEarlyAtom(int atomicNum) { if (atomicNum <= 1) { return false; } switch (PeriodicTable::getTable()->getNouterElecs(atomicNum)) { case 1: case 2: case 3: return true; case 4: // we make an arbitrary decision that Ge, Sn, and Pb // are treated like early elements (part of github #2606) return atomicNum > 14; case 5: // we make an arbitrary decision that Sb and Bi // are treated like early elements (part of github #2775) return atomicNum > 33; case 6: case 7: case 8: return false; default: return false; } } Atom::Atom() : RDProps() { d_atomicNum = 0; initAtom(); } Atom::Atom(unsigned int num) : RDProps() { d_atomicNum = num; initAtom(); }; Atom::Atom(const std::string &what) : RDProps() { d_atomicNum = PeriodicTable::getTable()->getAtomicNumber(what); initAtom(); }; void Atom::initFromOther(const Atom &other) { RDProps::operator=(other); // NOTE: we do *not* copy ownership! dp_mol = nullptr; d_atomicNum = other.d_atomicNum; d_index = 0; d_formalCharge = other.d_formalCharge; df_noImplicit = other.df_noImplicit; df_isAromatic = other.df_isAromatic; d_numExplicitHs = other.d_numExplicitHs; d_numRadicalElectrons = other.d_numRadicalElectrons; d_isotope = other.d_isotope; // d_pos = other.d_pos; d_chiralTag = other.d_chiralTag; d_hybrid = other.d_hybrid; d_implicitValence = other.d_implicitValence; d_explicitValence = other.d_explicitValence; if (other.dp_monomerInfo) { dp_monomerInfo = other.dp_monomerInfo->copy(); } else { dp_monomerInfo = nullptr; } } Atom::Atom(const Atom &other) : RDProps() { initFromOther(other); } Atom &Atom::operator=(const Atom &other) { if (this == &other) { return *this; } initFromOther(other); return *this; } void Atom::initAtom() { df_isAromatic = false; df_noImplicit = false; d_numExplicitHs = 0; d_numRadicalElectrons = 0; d_formalCharge = 0; d_index = 0; d_isotope = 0; d_chiralTag = CHI_UNSPECIFIED; d_hybrid = UNSPECIFIED; dp_mol = nullptr; dp_monomerInfo = nullptr; d_implicitValence = -1; d_explicitValence = -1; } Atom::~Atom() { if (dp_monomerInfo) { delete dp_monomerInfo; } } Atom *Atom::copy() const { auto *res = new Atom(*this); return res; } void Atom::setOwningMol(ROMol *other) { // NOTE: this operation does not update the topology of the owning // molecule (i.e. this atom is not added to the graph). Only // molecules can add atoms to themselves. dp_mol = other; } std::string Atom::getSymbol() const { std::string res; // handle dummies differently: if (d_atomicNum != 0 || !getPropIfPresent<std::string>(common_properties::dummyLabel, res)) { res = PeriodicTable::getTable()->getElementSymbol(d_atomicNum); } return res; } unsigned int Atom::getDegree() const { PRECONDITION(dp_mol, "degree not defined for atoms not associated with molecules"); return getOwningMol().getAtomDegree(this); } unsigned int Atom::getTotalDegree() const { PRECONDITION(dp_mol, "degree not defined for atoms not associated with molecules"); unsigned int res = this->getTotalNumHs(false) + this->getDegree(); return res; } // // If includeNeighbors is set, we'll loop over our neighbors // and include any of them that are Hs in the count here // unsigned int Atom::getTotalNumHs(bool includeNeighbors) const { PRECONDITION(dp_mol, "valence not defined for atoms not associated with molecules") int res = getNumExplicitHs() + getNumImplicitHs(); if (includeNeighbors) { ROMol::ADJ_ITER begin, end; const ROMol *parent = &getOwningMol(); boost::tie(begin, end) = parent->getAtomNeighbors(this); while (begin != end) { const Atom *at = parent->getAtomWithIdx(*begin); if (at->getAtomicNum() == 1) { res++; } ++begin; } } return res; } unsigned int Atom::getNumImplicitHs() const { if (df_noImplicit) { return 0; } PRECONDITION(d_implicitValence > -1, "getNumImplicitHs() called without preceding call to " "calcImplicitValence()"); return getImplicitValence(); } int Atom::getExplicitValence() const { PRECONDITION(dp_mol, "valence not defined for atoms not associated with molecules"); PRECONDITION( d_explicitValence > -1, "getExplicitValence() called without call to calcExplicitValence()"); return d_explicitValence; } unsigned int Atom::getTotalValence() const { PRECONDITION(dp_mol, "valence not defined for atoms not associated with molecules"); return getExplicitValence() + getImplicitValence(); } int Atom::calcExplicitValence(bool strict) { PRECONDITION(dp_mol, "valence not defined for atoms not associated with molecules"); unsigned int res; // FIX: contributions of bonds to valence are being done at best // approximately double accum = 0; for (const auto &nbri : boost::make_iterator_range(getOwningMol().getAtomBonds(this))) { const auto bnd = getOwningMol()[nbri]; accum += bnd->getValenceContrib(this); } accum += getNumExplicitHs(); // check accum is greater than the default valence unsigned int dv = PeriodicTable::getTable()->getDefaultValence(d_atomicNum); int chr = getFormalCharge(); if (isEarlyAtom(d_atomicNum)) { chr *= -1; // <- the usual correction for early atoms } // special case for carbon - see GitHub #539 if (d_atomicNum == 6 && chr > 0) { chr = -chr; } if (accum > (dv + chr) && this->getIsAromatic()) { // this needs some explanation : if the atom is aromatic and // accum > (dv + chr) we assume that no hydrogen can be added // to this atom. We set x = (v + chr) such that x is the // closest possible integer to "accum" but less than // "accum". // // "v" here is one of the allowed valences. For example: // sulfur here : O=c1ccs(=O)cc1 // nitrogen here : c1cccn1C int pval = dv + chr; const INT_VECT &valens = PeriodicTable::getTable()->getValenceList(d_atomicNum); for (auto vi = valens.begin(); vi != valens.end() && *vi != -1; ++vi) { int val = (*vi) + chr; if (val > accum) { break; } else { pval = val; } } // if we're within 1.5 of the allowed valence, go ahead and take it. // this reflects things like the N in c1cccn1C, which starts with // accum of 4, but which can be kekulized to C1=CC=CN1C, where // the valence is 3 or the bridging N in c1ccn2cncc2c1, which starts // with a valence of 4.5, but can be happily kekulized down to a valence // of 3 if (accum - pval <= 1.5) { accum = pval; } } // despite promising to not to blame it on him - this a trick Greg // came up with: if we have a bond order sum of x.5 (i.e. 1.5, 2.5 // etc) we would like it to round to the higher integer value -- // 2.5 to 3 instead of 2 -- so we will add 0.1 to accum. // this plays a role in the number of hydrogen that are implicitly // added. This will only happen when the accum is a non-integer // value and less than the default valence (otherwise the above if // statement should have caught it). An example of where this can // happen is the following smiles: // C1ccccC1 // Daylight accepts this smiles and we should be able to Kekulize // correctly. accum += 0.1; res = static_cast<int>(std::round(accum)); if (strict) { int effectiveValence; if (PeriodicTable::getTable()->getNouterElecs(d_atomicNum) >= 4) { effectiveValence = res - getFormalCharge(); } else { // for boron and co, we move to the right in the PT, so adding // extra valences means adding negative charge effectiveValence = res + getFormalCharge(); } const INT_VECT &valens = PeriodicTable::getTable()->getValenceList(d_atomicNum); int maxValence = *(valens.rbegin()); // maxValence == -1 signifies that we'll take anything at the high end if (maxValence > 0 && effectiveValence > maxValence) { // the explicit valence is greater than any // allowed valence for the atoms - raise an error std::ostringstream errout; errout << "Explicit valence for atom # " << getIdx() << " " << PeriodicTable::getTable()->getElementSymbol(d_atomicNum) << ", " << effectiveValence << ", is greater than permitted"; std::string msg = errout.str(); BOOST_LOG(rdErrorLog) << msg << std::endl; throw AtomValenceException(msg, getIdx()); } } d_explicitValence = res; return res; } int Atom::getImplicitValence() const { PRECONDITION(dp_mol, "valence not defined for atoms not associated with molecules"); if (df_noImplicit) { return 0; } return d_implicitValence; } // NOTE: this uses the explicitValence, so it will call // calcExplictValence() if it hasn't already been called int Atom::calcImplicitValence(bool strict) { PRECONDITION(dp_mol, "valence not defined for atoms not associated with molecules"); if (df_noImplicit) { return 0; } if (d_explicitValence == -1) { this->calcExplicitValence(strict); } // special cases if (d_atomicNum == 0) { d_implicitValence = 0; return 0; } for (const auto &nbri : boost::make_iterator_range(getOwningMol().getAtomBonds(this))) { const auto bnd = getOwningMol()[nbri]; if (QueryOps::hasComplexBondTypeQuery(*bnd)) { d_implicitValence = 0; return 0; } } if (d_explicitValence == 0 && d_atomicNum == 1 && d_numRadicalElectrons == 0) { if (d_formalCharge == 1 || d_formalCharge == -1) { d_implicitValence = 0; return 0; } else if (d_formalCharge == 0) { d_implicitValence = 1; return 1; } else { if (strict) { std::ostringstream errout; errout << "Unreasonable formal charge on hydrogen # " << getIdx() << "."; std::string msg = errout.str(); BOOST_LOG(rdErrorLog) << msg << std::endl; throw AtomValenceException(msg, getIdx()); } else { d_implicitValence = 0; return 0; } } } // this is basically the difference between the allowed valence of // the atom and the explicit valence already specified - tells how // many Hs to add // int res; // The d-block and f-block of the periodic table (i.e. transition metals, // lanthanoids and actinoids) have no default valence. int dv = PeriodicTable::getTable()->getDefaultValence(d_atomicNum); if (dv == -1) { d_implicitValence = 0; return 0; } // here is how we are going to deal with the possibility of // multiple valences // - check the explicit valence "ev" // - if it is already equal to one of the allowed valences for the // atom return 0 // - otherwise take return difference between next larger allowed // valence and "ev" // if "ev" is greater than all allowed valences for the atom raise an // exception // finally aromatic cases are dealt with differently - these atoms are allowed // only default valences const INT_VECT &valens = PeriodicTable::getTable()->getValenceList(d_atomicNum); int explicitPlusRadV = getExplicitValence() + getNumRadicalElectrons(); int chg = getFormalCharge(); // NOTE: this is here to take care of the difference in element on // the right side of the carbon vs left side of carbon // For elements on the right side of the periodic table // (electronegative elements): // NHYD = V - SBO + CHG // For elements on the left side of the periodic table // (electropositive elements): // NHYD = V - SBO - CHG // This reflects that hydrogen adds to, for example, O as H+ while // it adds to Na as H-. // V = valence // SBO = Sum of bond orders // CHG = Formal charge // It seems reasonable that the line is drawn at Carbon (in Group // IV), but we must assume on which side of the line C // falls... an assumption which will not always be correct. For // example: // - Electropositive Carbon: a C with three singly-bonded // neighbors (DV = 4, SBO = 3, CHG = 1) and a positive charge (a // 'stable' carbocation) should not have any hydrogens added. // - Electronegative Carbon: C in isonitrile, R[N+]#[C-] (DV = 4, SBO = 3, // CHG = -1), also should not have any hydrogens added. // Because isonitrile seems more relevant to pharma problems, we'll be // making the second assumption: *Carbon is electronegative*. // // So assuming you read all the above stuff - you know why we are // changing signs for "chg" here if (isEarlyAtom(d_atomicNum)) { chg *= -1; } // special case for carbon - see GitHub #539 if (d_atomicNum == 6 && chg > 0) { chg = -chg; } // if we have an aromatic case treat it differently if (getIsAromatic()) { if (explicitPlusRadV <= (static_cast<int>(dv) + chg)) { res = dv + chg - explicitPlusRadV; } else { // As we assume when finding the explicitPlusRadValence if we are // aromatic we should not be adding any hydrogen and already // be at an accepted valence state, // FIX: this is just ERROR checking and probably moot - the // explicitPlusRadValence function called above should assure us that // we satisfy one of the accepted valence states for the // atom. The only diff I can think of is in the way we handle // formal charge here vs the explicit valence function. bool satis = false; for (auto vi = valens.begin(); vi != valens.end() && *vi > 0; ++vi) { if (explicitPlusRadV == ((*vi) + chg)) { satis = true; break; } } if (strict && !satis) { std::ostringstream errout; errout << "Explicit valence for aromatic atom # " << getIdx() << " not equal to any accepted valence\n"; std::string msg = errout.str(); BOOST_LOG(rdErrorLog) << msg << std::endl; throw AtomValenceException(msg, getIdx()); } res = 0; } } else { // non-aromatic case we are allowed to have non default valences // and be able to add hydrogens res = -1; for (auto vi = valens.begin(); vi != valens.end() && *vi >= 0; ++vi) { int tot = (*vi) + chg; if (explicitPlusRadV <= tot) { res = tot - explicitPlusRadV; break; } } if (res < 0) { if (strict) { // this means that the explicit valence is greater than any // allowed valence for the atoms - raise an error std::ostringstream errout; errout << "Explicit valence for atom # " << getIdx() << " " << PeriodicTable::getTable()->getElementSymbol(d_atomicNum) << " greater than permitted"; std::string msg = errout.str(); BOOST_LOG(rdErrorLog) << msg << std::endl; throw AtomValenceException(msg, getIdx()); } else { res = 0; } } } d_implicitValence = res; return res; } void Atom::setIsotope(unsigned int what) { d_isotope = what; } double Atom::getMass() const { if (d_isotope) { double res = PeriodicTable::getTable()->getMassForIsotope(d_atomicNum, d_isotope); if (d_atomicNum != 0 && res == 0.0) { res = d_isotope; } return res; } else { return PeriodicTable::getTable()->getAtomicWeight(d_atomicNum); } } void Atom::setQuery(Atom::QUERYATOM_QUERY *) { // Atoms don't have complex queries so this has to fail PRECONDITION(0, "plain atoms have no Query"); } Atom::QUERYATOM_QUERY *Atom::getQuery() const { return nullptr; }; void Atom::expandQuery(Atom::QUERYATOM_QUERY *, Queries::CompositeQueryType, bool) { PRECONDITION(0, "plain atoms have no Query"); } bool Atom::Match(Atom const *what) const { PRECONDITION(what, "bad query atom"); bool res = getAtomicNum() == what->getAtomicNum(); // special dummy--dummy match case: // [*] matches [*],[1*],[2*],etc. // [1*] only matches [*] and [1*] if (res) { if (this->dp_mol && what->dp_mol && this->getOwningMol().getRingInfo()->isInitialized() && what->getOwningMol().getRingInfo()->isInitialized() && this->getOwningMol().getRingInfo()->numAtomRings(d_index) > what->getOwningMol().getRingInfo()->numAtomRings(what->d_index)) { res = false; } else if (!this->getAtomicNum()) { // this is the new behavior, based on the isotopes: int tgt = this->getIsotope(); int test = what->getIsotope(); if (tgt && test && tgt != test) { res = false; } } else { // standard atom-atom match: The general rule here is that if this atom // has a property that // deviates from the default, then the other atom should match that value. if ((this->getFormalCharge() && this->getFormalCharge() != what->getFormalCharge()) || (this->getIsotope() && this->getIsotope() != what->getIsotope()) || (this->getNumRadicalElectrons() && this->getNumRadicalElectrons() != what->getNumRadicalElectrons())) { res = false; } } } return res; } void Atom::updatePropertyCache(bool strict) { calcExplicitValence(strict); calcImplicitValence(strict); } bool Atom::needsUpdatePropertyCache() const { if (this->d_explicitValence >= 0 && (this->df_noImplicit || this->d_implicitValence >= 0)) { return false; } return true; } // returns the number of swaps required to convert the ordering // of the probe list to match the order of our incoming bonds: // // e.g. if our incoming bond order is: [0,1,2,3]: // getPerturbationOrder([1,0,2,3]) = 1 // getPerturbationOrder([1,2,3,0]) = 3 // getPerturbationOrder([1,2,0,3]) = 2 int Atom::getPerturbationOrder(const INT_LIST &probe) const { PRECONDITION( dp_mol, "perturbation order not defined for atoms not associated with molecules") INT_LIST ref; ROMol::OEDGE_ITER beg, end; boost::tie(beg, end) = getOwningMol().getAtomBonds(this); while (beg != end) { ref.push_back(getOwningMol()[*beg]->getIdx()); ++beg; } int nSwaps = static_cast<int>(countSwapsToInterconvert(probe, ref)); return nSwaps; } void Atom::invertChirality() { switch (getChiralTag()) { case CHI_TETRAHEDRAL_CW: setChiralTag(CHI_TETRAHEDRAL_CCW); break; case CHI_TETRAHEDRAL_CCW: setChiralTag(CHI_TETRAHEDRAL_CW); break; case CHI_OTHER: case CHI_UNSPECIFIED: break; } } void setAtomRLabel(Atom *atm, int rlabel) { PRECONDITION(atm, "bad atom"); // rlabel ==> n2 => 0..99 PRECONDITION(rlabel >= 0 && rlabel < 100, "rlabel out of range for MDL files"); if (rlabel) { atm->setProp(common_properties::_MolFileRLabel, static_cast<unsigned int>(rlabel)); } else if (atm->hasProp(common_properties::_MolFileRLabel)) { atm->clearProp(common_properties::_MolFileRLabel); } } //! Gets the atom's RLabel int getAtomRLabel(const Atom *atom) { PRECONDITION(atom, "bad atom"); unsigned int rlabel = 0; atom->getPropIfPresent(common_properties::_MolFileRLabel, rlabel); return static_cast<int>(rlabel); } void setAtomAlias(Atom *atom, const std::string &alias) { PRECONDITION(atom, "bad atom"); if (alias != "") { atom->setProp(common_properties::molFileAlias, alias); } else if (atom->hasProp(common_properties::molFileAlias)) { atom->clearProp(common_properties::molFileAlias); } } std::string getAtomAlias(const Atom *atom) { PRECONDITION(atom, "bad atom"); std::string alias; atom->getPropIfPresent(common_properties::molFileAlias, alias); return alias; } void setAtomValue(Atom *atom, const std::string &value) { PRECONDITION(atom, "bad atom"); if (value != "") { atom->setProp(common_properties::molFileValue, value); } else if (atom->hasProp(common_properties::molFileValue)) { atom->clearProp(common_properties::molFileValue); } } std::string getAtomValue(const Atom *atom) { PRECONDITION(atom, "bad atom"); std::string value; atom->getPropIfPresent(common_properties::molFileValue, value); return value; } void setSupplementalSmilesLabel(Atom *atom, const std::string &label) { PRECONDITION(atom, "bad atom"); if (label != "") { atom->setProp(common_properties::_supplementalSmilesLabel, label); } else if (atom->hasProp(common_properties::_supplementalSmilesLabel)) { atom->clearProp(common_properties::_supplementalSmilesLabel); } } std::string getSupplementalSmilesLabel(const Atom *atom) { PRECONDITION(atom, "bad atom"); std::string label; atom->getPropIfPresent(common_properties::_supplementalSmilesLabel, label); return label; } } // namespace RDKit std::ostream &operator<<(std::ostream &target, const RDKit::Atom &at) { target << at.getIdx() << " " << at.getAtomicNum() << " " << at.getSymbol(); target << " chg: " << at.getFormalCharge(); target << " deg: " << at.getDegree(); target << " exp: "; try { int explicitValence = at.getExplicitValence(); target << explicitValence; } catch (...) { target << "N/A"; } target << " imp: "; try { int implicitValence = at.getImplicitValence(); target << implicitValence; } catch (...) { target << "N/A"; } target << " hyb: " << at.getHybridization(); target << " arom?: " << at.getIsAromatic(); target << " chi: " << at.getChiralTag(); if (at.getNumRadicalElectrons()) { target << " rad: " << at.getNumRadicalElectrons(); } if (at.getIsotope()) { target << " iso: " << at.getIsotope(); } if (at.getAtomMapNum()) { target << " mapno: " << at.getAtomMapNum(); } return target; };
// -*- C++ -*- // // Package: CSCTFConfigTestAnalyzer // Class: CSCTFConfigTestAnalyzer // // system include files #include <iostream> #include <memory> // user include files #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "CondFormats/L1TObjects/interface/L1TriggerKey.h" #include "CondFormats/L1TObjects/interface/L1TriggerKeyList.h" #include "CondFormats/DataRecord/interface/L1TriggerKeyRcd.h" #include "CondFormats/DataRecord/interface/L1TriggerKeyListRcd.h" #include "CondTools/L1Trigger/interface/Exception.h" // // class decleration // class CSCTFConfigTestAnalyzer : public edm::EDAnalyzer { public: explicit CSCTFConfigTestAnalyzer(const edm::ParameterSet&); ~CSCTFConfigTestAnalyzer() override; private: void beginJob() override ; void analyze(const edm::Event&, const edm::EventSetup&) override; void endJob() override ; // ----------member data --------------------------- }; // // constants, enums and typedefs // // // static data member definitions // // // constructors and destructor // CSCTFConfigTestAnalyzer::CSCTFConfigTestAnalyzer(const edm::ParameterSet& iConfig) { //now do what ever initialization is needed } CSCTFConfigTestAnalyzer::~CSCTFConfigTestAnalyzer() { // do anything here that needs to be done at desctruction time // (e.g. close files, deallocate resources etc.) } // // member functions // // ------------ method called to for each event ------------ void CSCTFConfigTestAnalyzer::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { using namespace edm; ESHandle< L1TriggerKeyList > pList ; iSetup.get< L1TriggerKeyListRcd >().get( pList ) ; std::cout << "Found " << pList->tscKeyToTokenMap().size() << " TSC keys:" << std::endl ; L1TriggerKeyList::KeyToToken::const_iterator iTSCKey = pList->tscKeyToTokenMap().begin() ; L1TriggerKeyList::KeyToToken::const_iterator eTSCKey = pList->tscKeyToTokenMap().end() ; for( ; iTSCKey != eTSCKey ; ++iTSCKey ) { std::cout << iTSCKey->first << " " << iTSCKey->second << std::endl ; } std::cout << std::endl ; L1TriggerKeyList::RecordToKeyToToken::const_iterator iRec = pList->recordTypeToKeyToTokenMap().begin() ; L1TriggerKeyList::RecordToKeyToToken::const_iterator eRec = pList->recordTypeToKeyToTokenMap().end() ; for( ; iRec != eRec ; ++iRec ) { const L1TriggerKeyList::KeyToToken& keyTokenMap = iRec->second ; std::cout << "For record@type " << iRec->first << ", found " << keyTokenMap.size() << " keys:" << std::endl ; L1TriggerKeyList::KeyToToken::const_iterator iKey = keyTokenMap.begin(); L1TriggerKeyList::KeyToToken::const_iterator eKey = keyTokenMap.end() ; for( ; iKey != eKey ; ++iKey ) { std::cout << iKey->first << " " << iKey->second << std::endl ; } std::cout << std::endl ; } try { ESHandle< L1TriggerKey > pKey ; iSetup.get< L1TriggerKeyRcd >().get( pKey ) ; // std::cout << "Current TSC key = " << pKey->getTSCKey() << std::endl ; std::cout << "Current TSC key = " << pKey->tscKey() << std::endl ; std::cout << "Current subsystem keys:" << std::endl ; std::cout << "CSCTF " << pKey->subsystemKey( L1TriggerKey::kCSCTF ) << std::endl ; std::cout << "DTTF " << pKey->subsystemKey( L1TriggerKey::kDTTF ) << std::endl ; std::cout << "RPC " << pKey->subsystemKey( L1TriggerKey::kRPC ) << std::endl ; std::cout << "GMT " << pKey->subsystemKey( L1TriggerKey::kGMT ) << std::endl ; std::cout << "RCT " << pKey->subsystemKey( L1TriggerKey::kRCT ) << std::endl ; std::cout << "GCT " << pKey->subsystemKey( L1TriggerKey::kGCT ) << std::endl ; std::cout << "TSP0 " << pKey->subsystemKey( L1TriggerKey::kTSP0 ) << std::endl ; const L1TriggerKey::RecordToKey& recKeyMap = pKey->recordToKeyMap() ; L1TriggerKey::RecordToKey::const_iterator iRec = recKeyMap.begin() ; L1TriggerKey::RecordToKey::const_iterator eRec = recKeyMap.end() ; for( ; iRec != eRec ; ++iRec ) { std::cout << iRec->first << " " << iRec->second << std::endl ; } } catch( cms::Exception& ex ) { std::cout << "No L1TriggerKey found." << std::endl ; } } // ------------ method called once each job just before starting event loop ------------ void CSCTFConfigTestAnalyzer::beginJob() { } // ------------ method called once each job just after ending the event loop ------------ void CSCTFConfigTestAnalyzer::endJob() { } //define this as a plug-in DEFINE_FWK_MODULE(CSCTFConfigTestAnalyzer);
/* * 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 <cudf/partitioning.hpp> #include <cudf/join.hpp> #include <cudf/io/csv.hpp> #include <gcylon/gtable.hpp> #include <gcylon/gtable_api.hpp> #include <gcylon/net/cudf_net_ops.hpp> #include <cylon/util/macros.hpp> #include <cylon/net/mpi/mpi_operations.hpp> #include <cylon/repartition.hpp> #include <gcylon/utils/util.hpp> #include <cudf/concatenate.hpp> #include <cudf/copying.hpp> namespace gcylon { cylon::Status Shuffle(const cudf::table_view &input_tv, const std::vector<int> &columns_to_hash, const std::shared_ptr<cylon::CylonContext> &ctx, std::unique_ptr<cudf::table> &table_out) { std::pair<std::unique_ptr<cudf::table>, std::vector<cudf::size_type>> partitioned = cudf::hash_partition(input_tv, columns_to_hash, ctx->GetWorldSize()); partitioned.second.push_back(input_tv.num_rows()); RETURN_CYLON_STATUS_IF_FAILED( gcylon::net::AllToAll(partitioned.first->view(), partitioned.second, ctx, table_out)); return cylon::Status::OK(); } cylon::Status Repartition(const cudf::table_view &input_tv, const std::shared_ptr<cylon::CylonContext> &ctx, std::unique_ptr<cudf::table> &table_out, const std::vector<int32_t> &rows_per_worker){ std::vector<int32_t> current_row_counts; RETURN_CYLON_STATUS_IF_FAILED( RowCountsAllTables(input_tv.num_rows(), ctx, current_row_counts)); std::vector<int32_t> rows_to_all; if (rows_per_worker.empty()) { auto evenly_dist_rows = cylon::DivideRowsEvenly(current_row_counts); rows_to_all = cylon::RowIndicesToAll(ctx->GetRank(), current_row_counts, evenly_dist_rows); } else { auto sum_of_current_rows = std::accumulate(current_row_counts.begin(), current_row_counts.end(), 0); auto sum_of_target_rows = std::accumulate(rows_per_worker.begin(), rows_per_worker.end(), 0); if (sum_of_current_rows != sum_of_target_rows) { return cylon::Status(cylon::Code::ValueError, "Sum of target partitions does not match the sum of current partitions."); } rows_to_all = cylon::RowIndicesToAll(ctx->GetRank(), current_row_counts, rows_per_worker); } RETURN_CYLON_STATUS_IF_FAILED( gcylon::net::AllToAll(input_tv, rows_to_all, ctx, table_out)); return cylon::Status::OK(); } cylon::Status Gather(const cudf::table_view &input_tv, const std::shared_ptr<cylon::CylonContext> &ctx, std::unique_ptr<cudf::table> &table_out, int gather_root) { std::vector<std::unique_ptr<cudf::table>> gathered_tables; RETURN_CYLON_STATUS_IF_FAILED( gcylon::net::Gather(input_tv, gather_root, true, ctx, gathered_tables)); if (gather_root == ctx->GetRank()) { auto init_tvs = tablesToViews(gathered_tables); table_out = cudf::concatenate(init_tvs); } else { table_out = cudf::empty_like(input_tv); } return cylon::Status::OK(); } cylon::Status Broadcast(const cudf::table_view &input_tv, int root, const std::shared_ptr<cylon::CylonContext> &ctx, std::unique_ptr<cudf::table> &table_out) { RETURN_CYLON_STATUS_IF_FAILED( gcylon::net::Bcast(input_tv, root, ctx, table_out)); if (root == ctx->GetRank()) { table_out = std::make_unique<cudf::table>(input_tv); } return cylon::Status::OK(); } cylon::Status AllGather(const cudf::table_view &input_tv, const std::shared_ptr<cylon::CylonContext> &ctx, std::unique_ptr<cudf::table> &table_out) { std::vector<std::unique_ptr<cudf::table>> gathered_tables; RETURN_CYLON_STATUS_IF_FAILED( gcylon::net::AllGather(input_tv, ctx, gathered_tables)); auto init_tvs = tablesToViews(gathered_tables); table_out = cudf::concatenate(init_tvs); return cylon::Status::OK(); } cylon::Status Shuffle(std::shared_ptr<GTable> &input_table, const std::vector<int> &columns_to_hash, std::shared_ptr<GTable> &output_table) { std::unique_ptr<cudf::table> table_out; auto ctx = input_table->GetContext(); RETURN_CYLON_STATUS_IF_FAILED( Shuffle(input_table->GetCudfTable()->view(), columns_to_hash, ctx, table_out)); RETURN_CYLON_STATUS_IF_FAILED( GTable::FromCudfTable(ctx, table_out, output_table)); // set metadata for the shuffled table output_table->SetCudfMetadata(input_table->GetCudfMetadata()); return cylon::Status::OK(); } cylon::Status joinTables(const cudf::table_view &left, const cudf::table_view &right, const cylon::join::config::JoinConfig &join_config, std::shared_ptr<cylon::CylonContext> ctx, std::unique_ptr<cudf::table> &table_out) { if (join_config.GetAlgorithm() == cylon::join::config::JoinAlgorithm::SORT) { return cylon::Status(cylon::Code::NotImplemented, "SORT join is not supported on GPUs yet."); } if (join_config.GetType() == cylon::join::config::JoinType::INNER) { table_out = cudf::inner_join(left, right, join_config.GetLeftColumnIdx(), join_config.GetRightColumnIdx()); } else if (join_config.GetType() == cylon::join::config::JoinType::LEFT) { table_out = cudf::left_join(left, right, join_config.GetLeftColumnIdx(), join_config.GetRightColumnIdx()); } else if (join_config.GetType() == cylon::join::config::JoinType::RIGHT) { table_out = cudf::left_join(right, left, join_config.GetRightColumnIdx(), join_config.GetLeftColumnIdx()); } else if (join_config.GetType() == cylon::join::config::JoinType::FULL_OUTER) { table_out = cudf::full_join(left, right, join_config.GetLeftColumnIdx(), join_config.GetRightColumnIdx()); } return cylon::Status::OK(); } cylon::Status joinTables(std::shared_ptr<GTable> &left, std::shared_ptr<GTable> &right, const cylon::join::config::JoinConfig &join_config, std::shared_ptr<GTable> &joined_table) { if (left == nullptr) { return cylon::Status(cylon::Code::KeyError, "Couldn't find the left table"); } else if (right == nullptr) { return cylon::Status(cylon::Code::KeyError, "Couldn't find the right table"); } if (join_config.GetAlgorithm() == cylon::join::config::JoinAlgorithm::SORT) { return cylon::Status(cylon::Code::NotImplemented, "SORT join is not supported on GPUs yet."); } std::shared_ptr<cylon::CylonContext> ctx = left->GetContext(); std::unique_ptr<cudf::table> joined; RETURN_CYLON_STATUS_IF_FAILED(joinTables(left->GetCudfTable()->view(), right->GetCudfTable()->view(), join_config, ctx, joined)); RETURN_CYLON_STATUS_IF_FAILED( GTable::FromCudfTable(ctx, joined, joined_table)); // set metadata for the joined table joined_table->SetCudfMetadata(left->GetCudfMetadata()); return cylon::Status::OK(); } /** * Similar to local join, but performs the join in a distributed fashion * works on tale_view objects * @param left_table * @param right_table * @param join_config * @param ctx * @param table_out * @return */ cylon::Status DistributedJoin(const cudf::table_view &left_table, const cudf::table_view &right_table, const cylon::join::config::JoinConfig &join_config, const std::shared_ptr<cylon::CylonContext> &ctx, std::unique_ptr<cudf::table> &table_out) { if (ctx->GetWorldSize() == 1) { // perform single join return joinTables(left_table, right_table, join_config, ctx, table_out); } std::unique_ptr<cudf::table> left_shuffled_table, right_shuffled_table; RETURN_CYLON_STATUS_IF_FAILED( Shuffle(left_table, join_config.GetLeftColumnIdx(), ctx, left_shuffled_table)); RETURN_CYLON_STATUS_IF_FAILED( Shuffle(right_table, join_config.GetRightColumnIdx(), ctx, right_shuffled_table)); RETURN_CYLON_STATUS_IF_FAILED( joinTables(left_shuffled_table->view(), right_shuffled_table->view(), join_config, ctx, table_out)); return cylon::Status::OK(); } /** * Similar to local join, but performs the join in a distributed fashion * works on GTable objects * @param left * @param right * @param join_config * @param output * @return */ cylon::Status DistributedJoin(std::shared_ptr<GTable> &left, std::shared_ptr<GTable> &right, const cylon::join::config::JoinConfig &join_config, std::shared_ptr<GTable> &output) { std::shared_ptr<cylon::CylonContext> ctx = left->GetContext(); if (ctx->GetWorldSize() == 1) { // perform single join return joinTables(left, right, join_config, output); } std::shared_ptr<GTable> left_shuffled_table, right_shuffled_table; RETURN_CYLON_STATUS_IF_FAILED( Shuffle(left, join_config.GetLeftColumnIdx(), left_shuffled_table)); RETURN_CYLON_STATUS_IF_FAILED( Shuffle(right, join_config.GetRightColumnIdx(), right_shuffled_table)); RETURN_CYLON_STATUS_IF_FAILED( joinTables(left_shuffled_table, right_shuffled_table, join_config, output)); return cylon::Status::OK(); } /** * write GTable to file * @param table * @param output_file * @return */ cylon::Status WriteToCsv(std::shared_ptr<GTable> &table, std::string output_file) { cudf::io::sink_info sink_info(output_file); cudf::io::csv_writer_options options = cudf::io::csv_writer_options::builder(sink_info, table->GetCudfTable()->view()) .metadata(&(table->GetCudfMetadata())) .include_header(true); cudf::io::write_csv(options); return cylon::Status::OK(); } /** * get table sizes from all workers * each worker size in the table_sizes[rank] * @param num_rows size of the table at the current worker * @param ctx * @param all_num_rows all tables sizes from all workers * @return */ cylon::Status RowCountsAllTables(int32_t num_rows, const std::shared_ptr<cylon::CylonContext> &ctx, std::vector<int32_t> &all_num_rows) { std::vector<int32_t> send_data(1, num_rows); return cylon::mpi::AllGather(send_data, ctx->GetWorldSize(), all_num_rows); } }// end of namespace gcylon
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <utility> #include "base/gtest_prod_util.h" #include "base/macros.h" #include "chrome/browser/background/background_mode_manager.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/profiles/profile_manager.h" class TestBackgroundModeManager : public BackgroundModeManager { public: TestBackgroundModeManager(const base::CommandLine& command_line, ProfileAttributesStorage* profile_storage) : BackgroundModeManager(command_line, profile_storage), showed_background_app_installed_notification_for_test_(false) {} ~TestBackgroundModeManager() override {} void DisplayClientInstalledNotification(const base::string16& name) override { showed_background_app_installed_notification_for_test_ = true; } bool showed_background_app_installed_notification_for_test() { return showed_background_app_installed_notification_for_test_; } void set_showed_background_app_installed_notification_for_test( bool showed) { showed_background_app_installed_notification_for_test_ = showed; } private: // Tracks if we have shown a "Background App Installed" notification to the // user. Used for unit tests only. bool showed_background_app_installed_notification_for_test_; FRIEND_TEST_ALL_PREFIXES(BackgroundAppBrowserTest, ReloadBackgroundApp); DISALLOW_COPY_AND_ASSIGN(TestBackgroundModeManager); }; class BackgroundAppBrowserTest: public ExtensionBrowserTest {}; // Tests that if we reload a background app, we don't get a popup bubble // telling us that a new background app has been installed. IN_PROC_BROWSER_TEST_F(BackgroundAppBrowserTest, ReloadBackgroundApp) { // Pass this in to the browser test. std::unique_ptr<BackgroundModeManager> test_background_mode_manager( new TestBackgroundModeManager(*base::CommandLine::ForCurrentProcess(), &(g_browser_process->profile_manager() ->GetProfileAttributesStorage()))); g_browser_process->set_background_mode_manager_for_test( std::move(test_background_mode_manager)); TestBackgroundModeManager* manager = reinterpret_cast<TestBackgroundModeManager*>( g_browser_process->background_mode_manager()); // Load our background extension ASSERT_FALSE( manager->showed_background_app_installed_notification_for_test()); const extensions::Extension* extension = LoadExtension( test_data_dir_.AppendASCII("background_app")); ASSERT_FALSE(extension == NULL); // Set the test flag to not shown. manager->set_showed_background_app_installed_notification_for_test(false); // Reload our background extension ReloadExtension(extension->id()); // Ensure that we did not see a "Background extension loaded" dialog. EXPECT_FALSE( manager->showed_background_app_installed_notification_for_test()); }
#include "MultipleSelectionWidget.h" #include <QGridLayout> #include <QFileDialog> #include "MLIException.h" #include "CaseCreator/CaseContent/CaseContent.h" MultipleSelectionWidgetBase::MultipleSelectionWidgetBase(QWidget *parent, Qt::WindowFlags flags) : QWidget(parent, flags) { pSelectorLayout = new QVBoxLayout(); pSelectorLayout->setContentsMargins(0, 0, 0, 0); setLayout(pSelectorLayout); } QStringList MultipleSelectionWidgetBase::GetSelections() { QStringList selections; for (MultipleSelectionSelectorWidgetSlots *pSelector : selectorList) { selections.append(pSelector->GetString()); } return selections; } void MultipleSelectionWidgetBase::SetSelections(const QStringList &stringList) { for (MultipleSelectionSelectorWidgetSlots *pSelector : selectorList) { pSelectorLayout->removeWidget(pSelector); delete pSelector; } selectorList.clear(); for (QString string : stringList) { MultipleSelectionSelectorWidgetSlots *pSelector = CreateSelector(); pSelector->SetToString(string); pSelectorLayout->addWidget(pSelector); selectorList.append(pSelector); } UpdateSelectorSingletonness(); } void MultipleSelectionWidgetBase::SelectorStringSelected(MultipleSelectionSelectorWidgetSlots *pSender, const QString &string) { for (int i = 0; i < selectorList.size(); i++) { if (selectorList[i] == pSender) { emit StringChanged(i, string); break; } } } void MultipleSelectionWidgetBase::SelectorAddRequested(MultipleSelectionSelectorWidgetSlots *pSender) { for (int i = 0; i < selectorList.size(); i++) { if (selectorList[i] == pSender) { MultipleSelectionSelectorWidgetSlots *pSelector = CreateSelector(); pSelectorLayout->insertWidget(i + 1, pSelector); selectorList.insert(i + 1, pSelector); emit StringAdded(i + 1, pSelector->GetString()); break; } } UpdateSelectorSingletonness(); } void MultipleSelectionWidgetBase::SelectorDeleteRequested(MultipleSelectionSelectorWidgetSlots *pSender) { if (selectorList.size() < 2) { throw new MLIException("Should never be able to remove a selector when there's fewer than two."); } for (int i = 0; i < selectorList.size(); i++) { if (selectorList[i] == pSender) { pSelectorLayout->removeWidget(pSender); selectorList.removeAt(i); emit StringRemoved(i); break; } } UpdateSelectorSingletonness(); } void MultipleSelectionWidgetBase::UpdateSelectorSingletonness() { for (MultipleSelectionSelectorWidgetSlots *pSelector : selectorList) { pSelector->SetIsSingleton(selectorList.size() == 1); } } MultipleSelectionSelectorWidget::MultipleSelectionSelectorWidget(QWidget *parent, Qt::WindowFlags flags) : MultipleSelectionSelectorWidgetSlots(parent, flags) { } void MultipleSelectionSelectorWidget::Initialize() { QGridLayout *pLayout = new QGridLayout(); pLayout->setColumnStretch(0, 1); pLayout->setColumnStretch(1, 0); pLayout->setColumnStretch(2, 0); pLayout->addWidget(CreateSelector(), 0, 0); QPushButton *pAddButton = new QPushButton(); pAddButton->setText("+"); QObject::connect(pAddButton, SIGNAL(clicked()), this, SLOT(AddButtonClicked())); pLayout->addWidget(pAddButton, 0, 1); pDeleteButton = new QPushButton(); pDeleteButton->setText("x"); pLayout->addWidget(pDeleteButton, 0, 2); QObject::connect(pDeleteButton, SIGNAL(clicked()), this, SLOT(DeleteButtonClicked())); pLayout->setContentsMargins(0, 0, 0, 0); setLayout(pLayout); } void MultipleSelectionSelectorWidget::SetIsSingleton(bool isSingleton) { if (isSingleton) { pDeleteButton->hide(); pDeleteButton->setEnabled(false); } else { pDeleteButton->show(); pDeleteButton->setEnabled(true); } } void MultipleSelectionSelectorWidget::StringSelectedImpl(const QString &string) { emit StringSelected(this, string); } void MultipleSelectionSelectorWidget::AddButtonClickedImpl() { emit AddRequested(this); } void MultipleSelectionSelectorWidget::DeleteButtonClickedImpl() { emit DeleteRequested(this); } QString FilePathMultipleSelectionSelectorWidget::GetString() { return filePath; } void FilePathMultipleSelectionSelectorWidget::SetToString(const QString &string) { filePath = string; pFilePathLabel->SetText(string); } QWidget * FilePathMultipleSelectionSelectorWidget::CreateSelector() { QWidget *pSelectorWidget = new QWidget(); QGridLayout *pSelectorLayout = new QGridLayout(); pSelectorLayout->setColumnStretch(0, 0); pSelectorLayout->setColumnStretch(1, 1); pSelectFilePathButton = new QPushButton(); pSelectFilePathButton->setText("Select file path..."); pSelectorLayout->addWidget(pSelectFilePathButton, 0, 0); pFilePathLabel = new SizeAwareElidingLabel(Qt::ElideLeft); pSelectorLayout->addWidget(pFilePathLabel, 0, 1); pSelectorWidget->setLayout(pSelectorLayout); QObject::connect(pSelectFilePathButton, SIGNAL(clicked()), this, SLOT(SelectFilePathButtonClicked())); return pSelectorWidget; } void FilePathMultipleSelectionSelectorWidget::SelectFilePathButtonClicked() { QString filePath = QFileDialog::getOpenFileName(this, tr("Select image file"), QString(), tr("PNG images (*.png)")); if (filePath.length() > 0) { SetToString(filePath); emit StringSelected(filePath); } }
/* _______________________________________________________________________ DAKOTA: Design Analysis Kit for Optimization and Terascale Applications Copyright 2014 Sandia Corporation. This software is distributed under the GNU Lesser General Public License. For more information, see the README file in the top Dakota directory. _______________________________________________________________________ */ //- Class: SharedResponseData //- Description: Class implementation //- Owner: Mike Eldred // #define REFCOUNT_DEBUG 1 // #define SERIALIZE_DEBUG 1 #include "SharedResponseData.hpp" #include "ProblemDescDB.hpp" #include "DakotaActiveSet.hpp" #include "dakota_data_util.hpp" #include <boost/archive/binary_oarchive.hpp> #include <boost/archive/binary_iarchive.hpp> #include <boost/serialization/export.hpp> #include <boost/serialization/vector.hpp> #include <boost/serialization/shared_ptr.hpp> static const char rcsId[]="@(#) $Id: SharedResponseData.cpp 6886 2010-08-02 19:13:01Z mseldre $"; BOOST_CLASS_EXPORT(Dakota::SharedResponseDataRep) BOOST_CLASS_EXPORT(Dakota::SharedResponseData) namespace Dakota { SharedResponseDataRep:: SharedResponseDataRep(const ProblemDescDB& problem_db): responseType(BASE_RESPONSE), // overridden in derived class ctors primaryFnType(GENERIC_FNS), responsesId(problem_db.get_string("responses.id")), functionLabels(problem_db.get_sa("responses.labels")), simulationVariance(problem_db.get_rv("responses.simulation_variance")) { // scalar response data types: size_t num_scalar_resp_fns = problem_db.get_sizet("responses.num_scalar_responses"); numScalarResponses = (num_scalar_resp_fns) ? num_scalar_resp_fns : problem_db.get_sizet( "responses.num_scalar_nonlinear_inequality_constraints") + problem_db.get_sizet( "responses.num_scalar_nonlinear_equality_constraints") + std::max(problem_db.get_sizet("responses.num_scalar_objectives"), problem_db.get_sizet("responses.num_scalar_calibration_terms")); // field response data types: size_t num_field_resp_fns = problem_db.get_sizet("responses.num_field_responses"), num_field_responses = (num_field_resp_fns) ? num_field_resp_fns : problem_db.get_sizet( "responses.num_field_nonlinear_inequality_constraints") + problem_db.get_sizet( "responses.num_field_nonlinear_equality_constraints") + std::max(problem_db.get_sizet("responses.num_field_objectives"), problem_db.get_sizet("responses.num_field_calibration_terms")); // aggregate response data types: size_t num_total_resp_fns = problem_db.get_sizet("responses.num_response_functions"), num_total_responses = (num_total_resp_fns) ? num_total_resp_fns : problem_db.get_sizet("responses.num_nonlinear_inequality_constraints") + problem_db.get_sizet("responses.num_nonlinear_equality_constraints") + std::max(problem_db.get_sizet("responses.num_objective_functions"), problem_db.get_sizet("responses.num_calibration_terms")); // update primary response type based on specification if (problem_db.get_sizet("responses.num_objective_functions") > 0) primaryFnType = OBJECTIVE_FNS; else if (problem_db.get_sizet("responses.num_calibration_terms") > 0) primaryFnType = CALIB_TERMS; if (num_field_responses) { // require scalar spec and enforce total = scalar + field if (num_field_responses + numScalarResponses != num_total_responses) { Cerr << "Error: number of scalar (" << numScalarResponses << ") and field (" << num_field_responses << ") response functions must sum to total number (" << num_total_responses << ") of response functions." << std::endl; abort_handler(-1); } // extract the fieldLabels from the functionLabels (one per field group) copy_data_partial(functionLabels, numScalarResponses, num_field_responses, fieldLabels); // unroll field response groups to create individual function labels fieldRespGroupLengths = problem_db.get_iv("responses.lengths"); if (num_field_responses != fieldRespGroupLengths.length()) { Cerr << "Error: For each field response, you must specify " << "the length of that field. The number of elements " << "in the 'lengths' vector must " << "equal the number of field responses." << std::endl; abort_handler(-1); } build_field_labels(); } else if (numScalarResponses) { // validate scalar spec versus total spec if (numScalarResponses != num_total_responses) { Cerr << "Error: number of scalar (" << numScalarResponses << ") and field (0) response functions must sum to total number (" << num_total_responses << ") of response functions." << std::endl; abort_handler(-1); } } else if (num_total_responses) { // interpret total spec as scalar spec (backwards compatibility) numScalarResponses = num_total_responses; } else Cerr << "Warning: total number of response functions is zero. This is " << "admissible in rare cases (e.g., nested overlays)." << std::endl; if ( simulationVariance.length() != 0 && simulationVariance.length() != 1 && simulationVariance.length() != num_total_responses) { Cerr << "Error: simulation_variance must have length equal to 1 or " << "the total number of calibration terms." << std::endl; abort_handler(-1); } #ifdef REFCOUNT_DEBUG Cout << "SharedResponseDataRep::SharedResponseDataRep(problem_db) " << "called to build body object." << std::endl; #endif } SharedResponseDataRep::SharedResponseDataRep(const ActiveSet& set): responseType(BASE_RESPONSE), // overridden in derived class ctors primaryFnType(GENERIC_FNS), responsesId("NO_SPECIFICATION"), numScalarResponses(set.request_vector().size()) { // Build a default functionLabels array (currently only used for // bestResponse by NPSOLOptimizer's user-defined functions option). functionLabels.resize(numScalarResponses); build_labels(functionLabels, "f"); #ifdef REFCOUNT_DEBUG Cout << "SharedResponseDataRep::SharedResponseDataRep() called to build " << "empty body object." << std::endl; #endif } /** Deep copies are used when recasting changes the nature of a Response set. */ void SharedResponseDataRep::copy_rep(SharedResponseDataRep* srd_rep) { responseType = srd_rep->responseType; primaryFnType = srd_rep->primaryFnType; responsesId = srd_rep->responsesId; functionLabels = srd_rep->functionLabels; fieldLabels = srd_rep->fieldLabels; numScalarResponses = srd_rep->numScalarResponses; fieldRespGroupLengths = srd_rep->fieldRespGroupLengths; numCoordsPerField = srd_rep->numCoordsPerField; simulationVariance = srd_rep->simulationVariance; } template<class Archive> void SharedResponseDataRep::serialize(Archive& ar, const unsigned int version) { ar & responseType; ar & primaryFnType; ar & responsesId; // TODO: archive unrolled minimal labels if possible ar & functionLabels; ar & fieldLabels; ar & numScalarResponses; ar & fieldRespGroupLengths; ar & numCoordsPerField; #ifdef SERIALIZE_DEBUG Cout << "Serializing SharedResponseDataRep:\n" << responseType << '\n' << responsesId << '\n' << functionLabels << numScalarResponses << fieldRespGroupLengths << std::endl; #endif } bool SharedResponseDataRep::operator==(const SharedResponseDataRep& other) { return (responseType == other.responseType && primaryFnType == other.primaryFnType && responsesId == other.responsesId && functionLabels == other.functionLabels && fieldLabels == other.fieldLabels && numScalarResponses == other.numScalarResponses && fieldRespGroupLengths == other.fieldRespGroupLengths && numCoordsPerField == other.numCoordsPerField); } void SharedResponseDataRep::build_field_labels() { size_t unroll_fns = numScalarResponses + fieldRespGroupLengths.normOne(); if (functionLabels.size() != unroll_fns) functionLabels.resize(unroll_fns); // unique label for each QoI // append _<field_entry_num> to the base label size_t unrolled_index = numScalarResponses; for (size_t i=0; i<fieldRespGroupLengths.length(); ++i) for (size_t j=0; j<fieldRespGroupLengths[i]; ++j) build_label(functionLabels[unrolled_index++], fieldLabels[i], j+1, "_"); } /** Deep copies are used when recasting changes the nature of a Response set. */ SharedResponseData SharedResponseData::copy() const { // the handle class instantiates a new handle and a new body and copies // current attributes into the new body #ifdef REFCOUNT_DEBUG Cout << "SharedResponseData::copy() called to generate a deep copy with no " << "representation sharing.\n"; Cout << " srdRep use_count before = " << srdRep.use_count() << std::endl; #endif SharedResponseData srd; // new handle: srdRep=NULL if (srdRep) { srd.srdRep.reset(new SharedResponseDataRep()); srd.srdRep->copy_rep(srdRep.get()); } #ifdef REFCOUNT_DEBUG Cout << " srdRep use_count after = " << srdRep.use_count() << '\n'; Cout << " new srd use_count after = " << srd.srdRep.use_count() << std::endl; #endif return srd; } void SharedResponseData::reshape(size_t num_fns) { if (num_functions() != num_fns) { // separate sharing if needed //if (srdRep->referenceCount > 1) { // shared rep: separate #ifdef REFCOUNT_DEBUG Cout << "SharedResponseData::reshape() called.\n" << " srdRep use_count before = " << srdRep.use_count() << std::endl; #endif boost::shared_ptr<SharedResponseDataRep> old_rep = srdRep; srdRep.reset(new SharedResponseDataRep()); // create new srdRep srdRep->copy_rep(old_rep.get()); // copy old data to new #ifdef REFCOUNT_DEBUG Cout << " srdRep use_count after = " << srdRep.use_count() << '\n' << " old_rep use_count after = " << old_rep.use_count() << std::endl; #endif //} // reshape function labels srdRep->functionLabels.resize(num_fns); build_labels(srdRep->functionLabels, "f"); // update scalar counts (update of field counts requires addtnl data) srdRep->numScalarResponses = num_fns - num_field_functions(); } } // TODO: unify with reshape void SharedResponseData::field_lengths(const IntVector& field_lens) { // no change in number of scalar functions // when the field lengths change, need a new rep if (field_lengths() != field_lens) { boost::shared_ptr<SharedResponseDataRep> old_rep = srdRep; srdRep.reset(new SharedResponseDataRep()); // create new srdRep srdRep->copy_rep(old_rep.get()); // copy old data to new // update the field lengths srdRep->fieldRespGroupLengths = field_lens; // reshape function labels, using updated num_functions() srdRep->functionLabels.resize(num_functions()); if (field_lens.length() != srdRep->fieldLabels.size()) { // can't use existing field labels (could happen in testing); use generic build_labels(srdRep->functionLabels, "f"); // update the fieldLabels copy_data_partial(srdRep->functionLabels, num_scalar_responses(), num_field_response_groups(), srdRep->fieldLabels); } else { // no change in number of fields; use existing labels for build srdRep->build_field_labels(); } } } void SharedResponseData::field_group_labels(const StringArray& field_labels) { if (field_labels.size() != num_field_response_groups()) { Cerr << "\nError: Attempt to set " << field_labels.size() << " labels on Response with " << num_field_response_groups() << " fields." << std::endl; abort_handler(-1); } srdRep->fieldLabels = field_labels; // rebuild unrolled functionLabels for field values (no size change) srdRep->build_field_labels(); } void SharedResponseData::primary_fn_type(short type) { // when the primary type changes, need a new rep if (srdRep->primaryFnType != type) { boost::shared_ptr<SharedResponseDataRep> old_rep = srdRep; srdRep.reset(new SharedResponseDataRep()); // create new srdRep srdRep->copy_rep(old_rep.get()); // copy old data to new srdRep->primaryFnType = type; } } bool SharedResponseData::operator==(const SharedResponseData& other) { // test pointer equality // return(srdRep->get() == other.srdRep->get()); // test data equality return(*srdRep == *other.srdRep); } template<class Archive> void SharedResponseData::serialize(Archive& ar, const unsigned int version) { #ifdef REFCOUNT_DEBUG Cout << "SRD serializing with pointer " << srdRep.get() << '\n' << " srdRep use_count before = " << srdRep.use_count() << std::endl; #endif // load will default construct and load through the pointer ar & srdRep; #ifdef REFCOUNT_DEBUG Cout << " srdRep pointer after = " << srdRep.get() << std::endl; Cout << " srdRep use_count after = " << srdRep.use_count() << std::endl; #endif } long SharedResponseData::reference_count() const { return srdRep.use_count(); } // explicit instantions needed due to serialization through pointer, // which won't instantate the above template? template void SharedResponseData::serialize<boost::archive::binary_iarchive> (boost::archive::binary_iarchive& ar, const unsigned int version); template void SharedResponseData::serialize<boost::archive::binary_oarchive> (boost::archive::binary_oarchive& ar, const unsigned int version); } // namespace Dakota
Array3d v(2,3,4); cout << v.square() << endl;
/* Copyright 2020 The OneFlow 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 "oneflow/core/eager/transport_blob_instruction_type.h" #include "oneflow/core/vm/instruction_operand.msg.h" #include "oneflow/core/vm/object_wrapper.h" #include "oneflow/core/object_msg/flat_msg_view.h" #include "oneflow/core/eager/eager_blob_object.h" #include "oneflow/core/common/maybe.h" #include "oneflow/core/control/ctrl_client.h" namespace oneflow { namespace eager { namespace { // clang-format off FLAT_MSG_VIEW_BEGIN(SendBlobInstruction); FLAT_MSG_VIEW_DEFINE_PATTERN(vm::SymbolOperand, dst_parallel_desc); FLAT_MSG_VIEW_DEFINE_PATTERN(vm::ConstOperand, src_blob); FLAT_MSG_VIEW_DEFINE_PATTERN(vm::OperandSeparator, header_token_sep); FLAT_MSG_VIEW_DEFINE_REPEATED_PATTERN(uint64_t, header_token); FLAT_MSG_VIEW_DEFINE_PATTERN(vm::OperandSeparator, body_token_sep); FLAT_MSG_VIEW_DEFINE_REPEATED_PATTERN(uint64_t, body_token); FLAT_MSG_VIEW_END(SendBlobInstruction); FLAT_MSG_VIEW_BEGIN(ReceiveBlobInstruction); FLAT_MSG_VIEW_DEFINE_PATTERN(vm::SymbolOperand, src_parallel_desc); FLAT_MSG_VIEW_DEFINE_PATTERN(vm::Mut2Operand, dst_blob); FLAT_MSG_VIEW_DEFINE_PATTERN(vm::OperandSeparator, header_token_sep); FLAT_MSG_VIEW_DEFINE_REPEATED_PATTERN(uint64_t, header_token); FLAT_MSG_VIEW_DEFINE_PATTERN(vm::OperandSeparator, body_token_sep); FLAT_MSG_VIEW_DEFINE_REPEATED_PATTERN(uint64_t, body_token); FLAT_MSG_VIEW_END(ReceiveBlobInstruction); // clang-format on } // namespace void SendBlobInstructionType::Compute(vm::Instruction* instruction) const { CHECK_OK(Send(instruction)); } void ReceiveBlobInstructionType::Compute(vm::Instruction* instruction) const { CHECK_OK(Receive(instruction)); } Maybe<void> SendBlobInstructionType::Send(vm::Instruction* instruction) const { FlatMsgView<SendBlobInstruction> args(instruction->instr_msg().operand()); CHECK_EQ_OR_RETURN(args->body_token_size(), args->header_token_size()); std::function<void()> Callback; { char* data_ptr = instruction->mut_status_buffer()->mut_buffer()->mut_data(); RefCntType* ref_cnt = reinterpret_cast<RefCntType*>(data_ptr); // reference for blob header and blob body *ref_cnt = 2; // `ref_cnt` is safe to be captured before `Callback` finished. Callback = [ref_cnt] { CHECK_GE(--*ref_cnt, 0); }; } const auto* src_parallel_desc = instruction->parallel_desc().get(); int64_t parallel_id = 0; { CHECK_NOTNULL_OR_RETURN(src_parallel_desc) << Error::RwMutexedObjectNotFoundError(); CHECK_EQ_OR_RETURN(src_parallel_desc->parallel_num(), args->body_token_size()); int64_t machine_id = instruction->stream().machine_id(); int64_t device_id = instruction->stream().device_id(); parallel_id = JUST(src_parallel_desc->ParallelId4MachineDeviceId(machine_id, device_id)); } int64_t dst_machine_id = 0; { const auto* parallel_desc_operand = instruction->operand_type(args->dst_parallel_desc()); CHECK_NOTNULL_OR_RETURN(parallel_desc_operand); const auto& dst_parallel_desc = JUST(parallel_desc_operand->Get<vm::ObjectWrapper<ParallelDesc>>()).Get(); CHECK_EQ_OR_RETURN(dst_parallel_desc.device_type(), src_parallel_desc->device_type()); CHECK_EQ_OR_RETURN(dst_parallel_desc.parallel_num(), src_parallel_desc->parallel_num()); dst_machine_id = JUST(dst_parallel_desc.MachineId4ParallelId(parallel_id)); } const char* header_mem_ptr = nullptr; std::size_t header_size = 0; const char* body_mem_ptr = nullptr; std::size_t body_size = 0; { const auto* src_blob_operand = instruction->operand_type(args->src_blob()); CHECK_NOTNULL_OR_RETURN(src_blob_operand) << Error::RwMutexedObjectNotFoundError(); const auto& blob = JUST(src_blob_operand->template Get<BlobObject>()).blob(); header_mem_ptr = blob.header_ptr(); header_size = blob.blob_desc().ByteSizeOfBlobHeader(); body_mem_ptr = blob.dptr<char>(); // get actual byte size of blob body body_size = blob.ByteSizeOfBlobBody(); } JUST( Send(dst_machine_id, args->header_token(parallel_id), header_mem_ptr, header_size, Callback)); JUST(Send(dst_machine_id, args->body_token(parallel_id), body_mem_ptr, body_size, Callback)); return Maybe<void>::Ok(); } Maybe<void> ReceiveBlobInstructionType::Receive(vm::Instruction* instruction) const { FlatMsgView<ReceiveBlobInstruction> args(instruction->instr_msg().operand()); CHECK_EQ_OR_RETURN(args->body_token_size(), args->header_token_size()); std::function<void()> Callback; { char* data_ptr = instruction->mut_status_buffer()->mut_buffer()->mut_data(); RefCntType* ref_cnt = reinterpret_cast<RefCntType*>(data_ptr); // reference for blob header and blob body *ref_cnt = 2; // `ref_cnt` is safe to be captured before `Callback` finished. Callback = [ref_cnt] { CHECK_GE(--*ref_cnt, 0); }; } const auto* dst_parallel_desc = instruction->parallel_desc().get(); int64_t parallel_id = 0; { CHECK_NOTNULL_OR_RETURN(dst_parallel_desc) << Error::RwMutexedObjectNotFoundError(); CHECK_EQ_OR_RETURN(dst_parallel_desc->parallel_num(), args->body_token_size()); int64_t machine_id = instruction->stream().machine_id(); int64_t device_id = instruction->stream().device_id(); parallel_id = JUST(dst_parallel_desc->ParallelId4MachineDeviceId(machine_id, device_id)); } int64_t src_machine_id = 0; { const auto* parallel_desc_operand = instruction->operand_type(args->src_parallel_desc()); CHECK_NOTNULL_OR_RETURN(parallel_desc_operand); const auto& src_parallel_desc = JUST(parallel_desc_operand->Get<vm::ObjectWrapper<ParallelDesc>>()).Get(); CHECK_EQ_OR_RETURN(src_parallel_desc.device_type(), dst_parallel_desc->device_type()); CHECK_EQ_OR_RETURN(src_parallel_desc.parallel_num(), dst_parallel_desc->parallel_num()); src_machine_id = JUST(src_parallel_desc.MachineId4ParallelId(parallel_id)); } char* header_mem_ptr = nullptr; std::size_t header_size = 0; char* body_mem_ptr = nullptr; std::size_t body_size = 0; { auto* dst_blob_operand = instruction->mut_operand_type(args->dst_blob()); CHECK_NOTNULL_OR_RETURN(dst_blob_operand) << Error::RwMutexedObjectNotFoundError(); auto* blob = JUST(dst_blob_operand->template Mut<BlobObject>())->mut_blob(); header_mem_ptr = blob->mut_header_ptr(); header_size = blob->blob_desc().ByteSizeOfBlobHeader(); body_mem_ptr = blob->mut_dptr<char>(); // get capacity byte size of blob body body_size = blob->blob_desc().ByteSizeOfBlobBody(); } JUST(Receive(src_machine_id, args->header_token(parallel_id), header_mem_ptr, header_size, Callback)); JUST(Receive(src_machine_id, args->body_token(parallel_id), body_mem_ptr, body_size, Callback)); return Maybe<void>::Ok(); } Maybe<void> SendBlobInstructionType::Send(int64_t dst_machine_id, uint64_t token, const char* mem_ptr, std::size_t size, const std::function<void()>& Callback) const { // TODO(lixinqi) : Change to Global<Transport> solution Global<CtrlClient>::Get()->PushKV(std::to_string(token), [&](std::string* str) { str->assign(mem_ptr, size); }); Callback(); return Maybe<void>::Ok(); } Maybe<void> ReceiveBlobInstructionType::Receive(int64_t src_machine_id, uint64_t token, char* mem_ptr, std::size_t size, const std::function<void()>& Callback) const { // TODO(lixinqi) : Change to Global<Transport> solution Global<CtrlClient>::Get()->PullKV(std::to_string(token), [&](const std::string& str) { CHECK_LE(str.size(), size); std::memcpy(mem_ptr, str.data(), str.size()); }); Callback(); return Maybe<void>::Ok(); } COMMAND(vm::RegisterInstructionType<SendBlobInstructionType>("SendBlob")); COMMAND(vm::RegisterInstructionType<ReceiveBlobInstructionType>("ReceiveBlob")); } // namespace eager } // namespace oneflow
/** * @file ub_tree_split.hpp * @author Mikhail Lozhnikov * * Definition of UBTreeSplit, a class that splits the space according * to the median address of points contained in the node. */ #ifndef MLPACK_CORE_TREE_BINARY_SPACE_TREE_UB_TREE_SPLIT_HPP #define MLPACK_CORE_TREE_BINARY_SPACE_TREE_UB_TREE_SPLIT_HPP #include <mlpack/core.hpp> #include "../address.hpp" namespace mlpack { namespace tree /** Trees and tree-building procedures. */ { /** * Split a node into two parts according to the median address of points * contained in the node. The class reorders the dataset such that points * with lower addresses belong to the left subtree and points with high * addresses belong to the right subtree. */ template<typename BoundType, typename MatType = arma::mat> class UBTreeSplit { public: //! The type of an address element. typedef typename std::conditional<sizeof(typename MatType::elem_type) * CHAR_BIT <= 32, uint32_t, uint64_t>::type AddressElemType; //! An information about the partition. struct SplitInfo { //! This vector contains addresses of all points in the dataset. std::vector<std::pair<arma::Col<AddressElemType>, size_t>>* addresses; }; /** * Split the node according to the median address of points contained in the * node. * * @param bound The bound used for this node. * @param data The dataset used by the binary space tree. * @param begin Index of the starting point in the dataset that belongs to * this node. * @param count Number of points in this node. * @param splitInfo An information about the split (not used here). */ bool SplitNode(BoundType& bound, MatType& data, const size_t begin, const size_t count, SplitInfo& splitInfo); /** * Rearrange the dataset according to the addresses. * * @param data The dataset used by the binary space tree. * @param begin Index of the starting point in the dataset that belongs to * this node. * @param count Number of points in this node. * @param splitInfo The information about the split. */ static size_t PerformSplit(MatType& data, const size_t begin, const size_t count, const SplitInfo& splitInfo); /** * Rearrange the dataset according to the addresses and return the list * of changed indices. * * @param data The dataset used by the binary space tree. * @param begin Index of the starting point in the dataset that belongs to * this node. * @param count Number of points in this node. * @param splitInfo The information about the split. * @param oldFromNew Vector which will be filled with the old positions for * each new point. */ static size_t PerformSplit(MatType& data, const size_t begin, const size_t count, const SplitInfo& splitInfo, std::vector<size_t>& oldFromNew); private: //! This vector contains addresses of all points in the dataset. std::vector<std::pair<arma::Col<AddressElemType>, size_t>> addresses; /** * Calculate addresses for all points in the dataset. * * @param data The dataset used by the binary space tree. */ void InitializeAddresses(const MatType& data); //! A comparator for sorting addresses. static bool ComparePair( const std::pair<arma::Col<AddressElemType>, size_t>& p1, const std::pair<arma::Col<AddressElemType>, size_t>& p2) { return bound::addr::CompareAddresses(p1.first, p2.first) < 0; } }; } // namespace tree } // namespace mlpack // Include implementation. #include "ub_tree_split_impl.hpp" #endif
/// /// \author Adam Wegrzynek <adam.wegrzynek@cern.ch> /// #include "InfluxDBFactory.h" #include <functional> #include <string> #include <memory> #include <map> #include "UriParser.h" #include "HTTP.h" #include "InfluxDBException.h" #ifdef INFLUXDB_WITH_BOOST #include "UDP.h" #include "UnixSocket.h" #endif namespace influxdb { #ifdef INFLUXDB_WITH_BOOST std::unique_ptr<Transport> withUdpTransport(const http::url& uri) { return std::make_unique<transports::UDP>(uri.host, uri.port); } std::unique_ptr<Transport> withUnixSocketTransport(const http::url& uri) { return std::make_unique<transports::UnixSocket>(uri.path); } #else std::unique_ptr<Transport> withUdpTransport(const http::url& /*uri*/) { throw InfluxDBException("InfluxDBFactory", "UDP transport requires Boost"); } std::unique_ptr<Transport> withUnixSocketTransport(const http::url& /*uri*/) { throw InfluxDBException("InfluxDBFactory", "Unix socket transport requires Boost"); } #endif std::unique_ptr<Transport> withHttpTransport(const http::url& uri) { auto transport = std::make_unique<transports::HTTP>(uri.url); if (!uri.user.empty()) { transport->enableBasicAuth(uri.user + ":" + uri.password); } if (uri.protocol == "https") { transport->enableSsl(); } return transport; } std::unique_ptr<Transport> InfluxDBFactory::GetTransport(std::string url) { static const std::map<std::string, std::function<std::unique_ptr<Transport>(const http::url&)>> map = { {"udp", withUdpTransport}, {"http", withHttpTransport}, {"https", withHttpTransport}, {"unix", withUnixSocketTransport}, }; http::url parsedUrl = http::ParseHttpUrl(url); if (parsedUrl.protocol.empty()) { throw InfluxDBException("InfluxDBFactory::GetTransport", "Ill-formed URI"); } auto iterator = map.find(parsedUrl.protocol); if (iterator == map.end()) { throw InfluxDBException("InfluxDBFactory::GetTransport", "Unrecognized backend " + parsedUrl.protocol); } return iterator->second(parsedUrl); } std::unique_ptr<InfluxDB> InfluxDBFactory::Get(std::string url) { return std::make_unique<InfluxDB>(InfluxDBFactory::GetTransport(url)); } } // namespace influxdb
#include <iostream> #include <string> #include "../include/Level.h" #include "../include/CustomNode.h" using namespace irr; Level::Level() { std::cout << "Level constructor called"; //The dimensions of the level LEVEL_WIDTH = 160; LEVEL_LENGTH = 160; //Tile constants TILE_WIDTH = 10; TILE_LENGTH = 10; TOTAL_TILES = 256; TILE_SPRITES = 12; //Fills all spaces with air, to avoid null pointer catastrophes for(int i=0; i<10; i++) { for(int t=0; t<256; t++) { tiles[i][t] = new Tile( 0, 0, 0, AIR ); } } } void Level::LoadLevel(int iny, std::string filename) { std::cout<< "Loading level..."; int x = 0, z = 0; int y = iny*TILE_LENGTH; std::ifstream lvl(filename.c_str()); if(!lvl) { std::cout << "Level loading failed."; } for( int t = 0; t < TOTAL_TILES; t++ ) { int tileType = -1; lvl >> tileType; if( lvl.fail() == true ) { std::cout << "Level reading failed."; lvl.close(); } //If the number is a valid tile number if( ( tileType >= 0 ) && ( tileType < TILE_SPRITES ) ) { tiles[iny][ t ] = new Tile( x, y, z, tileType ); } //If we don't recognize the tile type else { lvl.close(); } //Move to next tile spot x += TILE_WIDTH; //If we've gone too far if( x >= LEVEL_WIDTH ) { //Move back x = 0; //Move to the next row z += TILE_LENGTH; } } lvl.close(); } scene::SMesh* Level::CustomMesh(video::SColor incolor, SHAPE shape) { scene::SMesh * mesh = new scene::SMesh(); if (shape==CUBE) { float cubeSize = 1.f; //f32 cubeSize = 10.f; video::SColor cubeColour = incolor; scene::SMeshBuffer * buffer = new scene::SMeshBuffer(); u16 u[36] = { 0,2,1, 0,3,2, 1,5,4, 1,2,5, 4,6,7, 4,5,6, 7,3,0, 7,6,3, 9,5,2, 9,8,5, 0,11,10, 0,10,7 }; buffer->Indices.set_used(36); for (s32 i=0; i<36; ++i) buffer->Indices[i] = u[i]; buffer->Vertices.set_used(12); buffer->Vertices[0] = video::S3DVertex(0,0,0, -10,-10,-10, cubeColour, 0, 1); buffer->Vertices[1] = video::S3DVertex(10,0,0, 10,-10,-10, cubeColour, 1, 1); buffer->Vertices[2] = video::S3DVertex(10,10,0, 10, 10,-10, cubeColour, 1, 0); buffer->Vertices[3] = video::S3DVertex(0,10,0, -10, 10,-10, cubeColour, 0, 0); buffer->Vertices[4] = video::S3DVertex(10,0,10, 10,-10, 10, cubeColour, 0, 1); buffer->Vertices[5] = video::S3DVertex(10,10,10, 10, 10, 10, cubeColour, 0, 0); buffer->Vertices[6] = video::S3DVertex(0,10,10, -10, 10, 10, cubeColour, 1, 0); buffer->Vertices[7] = video::S3DVertex(0,0,10, -10,-10, 10, cubeColour, 1, 1); buffer->Vertices[8] = video::S3DVertex(0,10,10, -10, 10, 10, cubeColour, 0, 1); buffer->Vertices[9] = video::S3DVertex(0,10,0, -10, 10,-10, cubeColour, 1, 1); buffer->Vertices[10] = video::S3DVertex(10,0,10, 10,-10, 10, cubeColour, 1, 0); buffer->Vertices[11] = video::S3DVertex(10,0,0, 10,-10,-10, cubeColour, 0, 0); buffer->BoundingBox.reset(0,0,0); for (int i=0; i<12; ++i) { buffer->Vertices[i].Pos -= core::vector3df(0.5f, 0.5f, 0.5f); buffer->Vertices[i].Pos *= cubeSize; buffer->BoundingBox.addInternalPoint(buffer->Vertices[i].Pos); } mesh->addMeshBuffer(buffer); return mesh; } } void Level::DrawLevel(irr::IrrlichtDevice* device) { std::cout << "\nDrawing level"; irr::scene::ISceneManager* smgr = device->getSceneManager(); irr::scene::ISceneNode* tilenode; float tilescale = 1.f; for (int y=0; y<10; y++) { for(int t=0; t<256; t++) { //tilenode = smgr->addCubeSceneNode(10.f); video::SColor tilecolor(0,0,0,0); switch (tiles[y][t]->type) { case TILE_FLOOR: tilecolor = video::SColor(255,90,90,90); tilescale = 1.f; break; case TILE_RED: tilecolor = video::SColor(255,255,0,0); tilescale = 1.f; break; case TILE_WALL: tilecolor = video::SColor(255,200,200,200); tilescale = 1.f; break; case TILE_RAMP_TOP: case TILE_RAMP_RIGHT: case TILE_RAMP_BOTTOM: case TILE_RAMP_LEFT: case AIR: tilenode->setVisible(false); tilescale = 1.f; break; default: break; } tilenode = smgr->addMeshSceneNode(CustomMesh(tilecolor, CUBE)); //tilenode = smgr->addCubeSceneNode(10.f); tilenode->setPosition(tiles[y][t]->position); tilenode->setMaterialFlag(irr::video::EMF_LIGHTING, true); tilenode->getMaterial(0).Shininess = 0.0f; std::cout <<"\ndrawing tile"<<t+1; } } } Level::~Level() { //dtor }
// Copyright 2018 The SwiftShader 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 "VkSurfaceKHR.hpp" #include "Vulkan/VkDestroy.h" #include <algorithm> namespace { static const VkSurfaceFormatKHR surfaceFormats[] = { {VK_FORMAT_B8G8R8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR}, {VK_FORMAT_B8G8R8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR}, }; static const VkPresentModeKHR presentModes[] = { VK_PRESENT_MODE_FIFO_KHR, }; } namespace vk { VkResult PresentImage::allocateImage(VkDevice device, const VkImageCreateInfo& createInfo) { VkImage* vkImagePtr = reinterpret_cast<VkImage*>(allocate(sizeof(VkImage), REQUIRED_MEMORY_ALIGNMENT, DEVICE_MEMORY)); if(!vkImagePtr) { return VK_ERROR_OUT_OF_DEVICE_MEMORY; } VkResult status = vkCreateImage(device, &createInfo, nullptr, vkImagePtr); if(status != VK_SUCCESS) { deallocate(vkImagePtr, DEVICE_MEMORY); return status; } image = Cast(*vkImagePtr); deallocate(vkImagePtr, DEVICE_MEMORY); return status; } VkResult PresentImage::allocateAndBindImageMemory(VkDevice device, const VkMemoryAllocateInfo& allocateInfo) { ASSERT(image); VkDeviceMemory* vkDeviceMemoryPtr = reinterpret_cast<VkDeviceMemory*>( allocate(sizeof(VkDeviceMemory), REQUIRED_MEMORY_ALIGNMENT, DEVICE_MEMORY)); if(!vkDeviceMemoryPtr) { return VK_ERROR_OUT_OF_DEVICE_MEMORY; } VkResult status = vkAllocateMemory(device, &allocateInfo, nullptr, vkDeviceMemoryPtr); if(status != VK_SUCCESS) { deallocate(vkDeviceMemoryPtr, DEVICE_MEMORY); return status; } imageMemory = Cast(*vkDeviceMemoryPtr); vkBindImageMemory(device, *image, *vkDeviceMemoryPtr, 0); imageStatus = AVAILABLE; deallocate(vkDeviceMemoryPtr, DEVICE_MEMORY); return status; } void PresentImage::clear() { if(imageMemory) { vk::destroy(static_cast<VkDeviceMemory>(*imageMemory), nullptr); imageMemory = nullptr; } if(image) { vk::destroy(static_cast<VkImage>(*image), nullptr); image = nullptr; } imageStatus = NONEXISTENT; } VkImage PresentImage::asVkImage() const { return image ? static_cast<VkImage>(*image) : VkImage({ VK_NULL_HANDLE }); } void SurfaceKHR::getSurfaceCapabilities(VkSurfaceCapabilitiesKHR *pSurfaceCapabilities) const { pSurfaceCapabilities->minImageCount = 1; pSurfaceCapabilities->maxImageCount = 0; pSurfaceCapabilities->maxImageArrayLayers = 1; pSurfaceCapabilities->supportedTransforms = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; pSurfaceCapabilities->currentTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; pSurfaceCapabilities->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; pSurfaceCapabilities->supportedUsageFlags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; } uint32_t SurfaceKHR::getSurfaceFormatsCount() const { return static_cast<uint32_t>(sizeof(surfaceFormats) / sizeof(surfaceFormats[0])); } VkResult SurfaceKHR::getSurfaceFormats(uint32_t *pSurfaceFormatCount, VkSurfaceFormatKHR *pSurfaceFormats) const { uint32_t count = getSurfaceFormatsCount(); uint32_t i; for(i = 0; i < std::min(*pSurfaceFormatCount, count); i++) { pSurfaceFormats[i] = surfaceFormats[i]; } *pSurfaceFormatCount = i; if(*pSurfaceFormatCount < count) { return VK_INCOMPLETE; } return VK_SUCCESS; } uint32_t SurfaceKHR::getPresentModeCount() const { return static_cast<uint32_t>(sizeof(presentModes) / sizeof(presentModes[0])); } VkResult SurfaceKHR::getPresentModes(uint32_t *pPresentModeCount, VkPresentModeKHR *pPresentModes) const { uint32_t count = getPresentModeCount(); uint32_t i; for(i = 0; i < std::min(*pPresentModeCount, count); i++) { pPresentModes[i] = presentModes[i]; } *pPresentModeCount = i; if(*pPresentModeCount < count) { return VK_INCOMPLETE; } return VK_SUCCESS; } void SurfaceKHR::associateSwapchain(SwapchainKHR* swapchain) { associatedSwapchain = swapchain; } void SurfaceKHR::disassociateSwapchain() { associatedSwapchain = nullptr; } bool SurfaceKHR::hasAssociatedSwapchain() { return (associatedSwapchain != nullptr); } }
#include <ToolsFoundationPCH.h> #include <Foundation/IO/MemoryStream.h> #include <Foundation/Serialization/DdlSerializer.h> #include <ToolsFoundation/Command/TreeCommands.h> #include <ToolsFoundation/Document/PrefabUtils.h> #include <ToolsFoundation/Object/DocumentObjectManager.h> #include <ToolsFoundation/Reflection/PhantomRttiManager.h> #include <ToolsFoundation/Serialization/DocumentObjectConverter.h> // clang-format off EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezAddObjectCommand, 1, ezRTTIDefaultAllocator<ezAddObjectCommand>) { EZ_BEGIN_PROPERTIES { EZ_ACCESSOR_PROPERTY("Type", GetType, SetType), EZ_MEMBER_PROPERTY("ParentGuid", m_Parent), EZ_MEMBER_PROPERTY("ParentProperty", m_sParentProperty), EZ_MEMBER_PROPERTY("Index", m_Index), EZ_MEMBER_PROPERTY("NewGuid", m_NewObjectGuid), } EZ_END_PROPERTIES; } EZ_END_DYNAMIC_REFLECTED_TYPE; EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezPasteObjectsCommand, 1, ezRTTIDefaultAllocator<ezPasteObjectsCommand>) { EZ_BEGIN_PROPERTIES { EZ_MEMBER_PROPERTY("ParentGuid", m_Parent), EZ_MEMBER_PROPERTY("TextGraph", m_sGraphTextFormat), EZ_MEMBER_PROPERTY("Mime", m_sMimeType), } EZ_END_PROPERTIES; } EZ_END_DYNAMIC_REFLECTED_TYPE; EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezInstantiatePrefabCommand, 1, ezRTTIDefaultAllocator<ezInstantiatePrefabCommand>) { EZ_BEGIN_PROPERTIES { EZ_MEMBER_PROPERTY("ParentGuid", m_Parent), EZ_MEMBER_PROPERTY("CreateFromPrefab", m_CreateFromPrefab), EZ_MEMBER_PROPERTY("BaseGraph", m_sBasePrefabGraph), EZ_MEMBER_PROPERTY("ObjectGraph", m_sObjectGraph), EZ_MEMBER_PROPERTY("RemapGuid", m_RemapGuid), EZ_MEMBER_PROPERTY("CreatedObjects", m_CreatedRootObject), EZ_MEMBER_PROPERTY("AllowPickedPos", m_bAllowPickedPosition), EZ_MEMBER_PROPERTY("Index", m_Index), } EZ_END_PROPERTIES; } EZ_END_DYNAMIC_REFLECTED_TYPE; EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezUnlinkPrefabCommand, 1, ezRTTIDefaultAllocator<ezUnlinkPrefabCommand>) { EZ_BEGIN_PROPERTIES { EZ_MEMBER_PROPERTY("Object", m_Object), } EZ_END_PROPERTIES; } EZ_END_DYNAMIC_REFLECTED_TYPE; EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezRemoveObjectCommand, 1, ezRTTIDefaultAllocator<ezRemoveObjectCommand>) { EZ_BEGIN_PROPERTIES { EZ_MEMBER_PROPERTY("ObjectGuid", m_Object), } EZ_END_PROPERTIES; } EZ_END_DYNAMIC_REFLECTED_TYPE; EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezMoveObjectCommand, 1, ezRTTIDefaultAllocator<ezMoveObjectCommand>) { EZ_BEGIN_PROPERTIES { EZ_MEMBER_PROPERTY("ObjectGuid", m_Object), EZ_MEMBER_PROPERTY("NewParentGuid", m_NewParent), EZ_MEMBER_PROPERTY("ParentProperty", m_sParentProperty), EZ_MEMBER_PROPERTY("Index", m_Index), } EZ_END_PROPERTIES; } EZ_END_DYNAMIC_REFLECTED_TYPE; EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezSetObjectPropertyCommand, 1, ezRTTIDefaultAllocator<ezSetObjectPropertyCommand>) { EZ_BEGIN_PROPERTIES { EZ_MEMBER_PROPERTY("ObjectGuid", m_Object), EZ_MEMBER_PROPERTY("NewValue", m_NewValue), EZ_MEMBER_PROPERTY("Index", m_Index), EZ_MEMBER_PROPERTY("Property", m_sProperty), } EZ_END_PROPERTIES; } EZ_END_DYNAMIC_REFLECTED_TYPE; EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezResizeAndSetObjectPropertyCommand, 1, ezRTTIDefaultAllocator<ezResizeAndSetObjectPropertyCommand>) { EZ_BEGIN_PROPERTIES { EZ_MEMBER_PROPERTY("ObjectGuid", m_Object), EZ_MEMBER_PROPERTY("NewValue", m_NewValue), EZ_MEMBER_PROPERTY("Index", m_Index), EZ_MEMBER_PROPERTY("Property", m_sProperty), } EZ_END_PROPERTIES; } EZ_END_DYNAMIC_REFLECTED_TYPE; EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezInsertObjectPropertyCommand, 1, ezRTTIDefaultAllocator<ezInsertObjectPropertyCommand>) { EZ_BEGIN_PROPERTIES { EZ_MEMBER_PROPERTY("ObjectGuid", m_Object), EZ_MEMBER_PROPERTY("NewValue", m_NewValue), EZ_MEMBER_PROPERTY("Index", m_Index), EZ_MEMBER_PROPERTY("Property", m_sProperty), } EZ_END_PROPERTIES; } EZ_END_DYNAMIC_REFLECTED_TYPE; EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezRemoveObjectPropertyCommand, 1, ezRTTIDefaultAllocator<ezRemoveObjectPropertyCommand>) { EZ_BEGIN_PROPERTIES { EZ_MEMBER_PROPERTY("ObjectGuid", m_Object), EZ_MEMBER_PROPERTY("Index", m_Index), EZ_MEMBER_PROPERTY("Property", m_sProperty), } EZ_END_PROPERTIES; } EZ_END_DYNAMIC_REFLECTED_TYPE; EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezMoveObjectPropertyCommand, 1, ezRTTIDefaultAllocator<ezMoveObjectPropertyCommand>) { EZ_BEGIN_PROPERTIES { EZ_MEMBER_PROPERTY("ObjectGuid", m_Object), EZ_MEMBER_PROPERTY("OldIndex", m_OldIndex), EZ_MEMBER_PROPERTY("NewIndex", m_NewIndex), EZ_MEMBER_PROPERTY("Property", m_sProperty), } EZ_END_PROPERTIES; } EZ_END_DYNAMIC_REFLECTED_TYPE; // clang-format on //////////////////////////////////////////////////////////////////////// // ezAddObjectCommand //////////////////////////////////////////////////////////////////////// ezAddObjectCommand::ezAddObjectCommand() : m_pType(nullptr) , m_pObject(nullptr) { } const char* ezAddObjectCommand::GetType() const { if (m_pType == nullptr) return ""; return m_pType->GetTypeName(); } void ezAddObjectCommand::SetType(const char* szType) { m_pType = ezRTTI::FindTypeByName(szType); } ezStatus ezAddObjectCommand::DoInternal(bool bRedo) { ezDocument* pDocument = GetDocument(); if (!bRedo) { if (!m_NewObjectGuid.IsValid()) m_NewObjectGuid.CreateNewUuid(); } ezDocumentObject* pParent = nullptr; if (m_Parent.IsValid()) { pParent = pDocument->GetObjectManager()->GetObject(m_Parent); if (pParent == nullptr) return ezStatus("Add Object: The given parent does not exist!"); } EZ_SUCCEED_OR_RETURN(pDocument->GetObjectManager()->CanAdd(m_pType, pParent, m_sParentProperty, m_Index)); if (!bRedo) { m_pObject = pDocument->GetObjectManager()->CreateObject(m_pType, m_NewObjectGuid); } pDocument->GetObjectManager()->AddObject(m_pObject, pParent, m_sParentProperty, m_Index); return ezStatus(EZ_SUCCESS); } ezStatus ezAddObjectCommand::UndoInternal(bool bFireEvents) { EZ_ASSERT_DEV(bFireEvents, "This command does not support temporary commands"); ezDocument* pDocument = GetDocument(); EZ_SUCCEED_OR_RETURN(pDocument->GetObjectManager()->CanRemove(m_pObject)); pDocument->GetObjectManager()->RemoveObject(m_pObject); return ezStatus(EZ_SUCCESS); } void ezAddObjectCommand::CleanupInternal(CommandState state) { if (state == CommandState::WasUndone) { GetDocument()->GetObjectManager()->DestroyObject(m_pObject); m_pObject = nullptr; } } //////////////////////////////////////////////////////////////////////// // ezPasteObjectsCommand //////////////////////////////////////////////////////////////////////// ezPasteObjectsCommand::ezPasteObjectsCommand() {} ezStatus ezPasteObjectsCommand::DoInternal(bool bRedo) { ezDocument* pDocument = GetDocument(); ezDocumentObject* pParent = nullptr; if (m_Parent.IsValid()) { pParent = pDocument->GetObjectManager()->GetObject(m_Parent); if (pParent == nullptr) return ezStatus("Paste Objects: The given parent does not exist!"); } if (!bRedo) { ezAbstractObjectGraph graph; { // Deserialize ezRawMemoryStreamReader memoryReader(m_sGraphTextFormat.GetData(), m_sGraphTextFormat.GetElementCount()); ezAbstractGraphDdlSerializer::Read(memoryReader, &graph); } // Remap ezUuid seed; seed.CreateNewUuid(); graph.ReMapNodeGuids(seed); ezDocumentObjectConverterReader reader(&graph, pDocument->GetObjectManager(), ezDocumentObjectConverterReader::Mode::CreateOnly); ezHybridArray<ezDocument::PasteInfo, 16> ToBePasted; auto& nodes = graph.GetAllNodes(); for (auto it = nodes.GetIterator(); it.IsValid(); ++it) { auto* pNode = it.Value(); if (ezStringUtils::IsEqual(pNode->GetNodeName(), "root")) { auto* pNewObject = reader.CreateObjectFromNode(pNode); if (pNewObject) { reader.ApplyPropertiesToObject(pNode, pNewObject); auto& ref = ToBePasted.ExpandAndGetRef(); ref.m_pObject = pNewObject; ref.m_pParent = pParent; } } } if (pDocument->Paste(ToBePasted, graph, true, m_sMimeType)) { for (const auto& item : ToBePasted) { auto& po = m_PastedObjects.ExpandAndGetRef(); po.m_pObject = item.m_pObject; po.m_pParent = item.m_pParent; po.m_Index = item.m_pObject->GetPropertyIndex(); po.m_sParentProperty = item.m_pObject->GetParentProperty(); } } else { for (const auto& item : ToBePasted) { pDocument->GetObjectManager()->DestroyObject(item.m_pObject); } } if (m_PastedObjects.IsEmpty()) return ezStatus("Paste Objects: nothing was pasted!"); } else { // Re-add at recorded place. for (auto& po : m_PastedObjects) { pDocument->GetObjectManager()->AddObject(po.m_pObject, po.m_pParent, po.m_sParentProperty, po.m_Index); } } return ezStatus(EZ_SUCCESS); } ezStatus ezPasteObjectsCommand::UndoInternal(bool bFireEvents) { EZ_ASSERT_DEV(bFireEvents, "This command does not support temporary commands"); ezDocument* pDocument = GetDocument(); for (auto& po : m_PastedObjects) { EZ_SUCCEED_OR_RETURN(pDocument->GetObjectManager()->CanRemove(po.m_pObject)); pDocument->GetObjectManager()->RemoveObject(po.m_pObject); } return ezStatus(EZ_SUCCESS); } void ezPasteObjectsCommand::CleanupInternal(CommandState state) { if (state == CommandState::WasUndone) { for (auto& po : m_PastedObjects) { GetDocument()->GetObjectManager()->DestroyObject(po.m_pObject); } m_PastedObjects.Clear(); } } //////////////////////////////////////////////////////////////////////// // ezInstantiatePrefabCommand //////////////////////////////////////////////////////////////////////// ezInstantiatePrefabCommand::ezInstantiatePrefabCommand() { m_bAllowPickedPosition = true; } ezStatus ezInstantiatePrefabCommand::DoInternal(bool bRedo) { ezDocument* pDocument = GetDocument(); ezDocumentObject* pParent = nullptr; if (m_Parent.IsValid()) { pParent = pDocument->GetObjectManager()->GetObject(m_Parent); if (pParent == nullptr) return ezStatus("Instantiate Prefab: The given parent does not exist!"); } if (!bRedo) { // TODO: this is hard-coded, it only works for scene documents ! const ezRTTI* pRootObjectType = ezRTTI::FindTypeByName("ezGameObject"); const char* szParentProperty = "Children"; ezDocumentObject* pRootObject = nullptr; ezHybridArray<ezDocument::PasteInfo, 16> ToBePasted; ezAbstractObjectGraph graph; // create root object { EZ_SUCCEED_OR_RETURN(pDocument->GetObjectManager()->CanAdd(pRootObjectType, pParent, szParentProperty, m_Index)); // use the same GUID for the root object ID as the remap GUID, this way the object ID is deterministic and reproducible m_CreatedRootObject = m_RemapGuid; pRootObject = pDocument->GetObjectManager()->CreateObject(pRootObjectType, m_CreatedRootObject); auto& ref = ToBePasted.ExpandAndGetRef(); ref.m_pObject = pRootObject; ref.m_pParent = pParent; ref.m_Index = m_Index; } // update meta data // this is read when Paste is executed, to determine a good node name { // if prefabs are not allowed in this document, just create this as a regular object, with no link to the prefab template if (pDocument->ArePrefabsAllowed()) { auto pMeta = pDocument->m_DocumentObjectMetaData.BeginModifyMetaData(m_CreatedRootObject); pMeta->m_CreateFromPrefab = m_CreateFromPrefab; pMeta->m_PrefabSeedGuid = m_RemapGuid; pMeta->m_sBasePrefab = m_sBasePrefabGraph; pDocument->m_DocumentObjectMetaData.EndModifyMetaData(ezDocumentObjectMetaData::PrefabFlag); } else { pDocument->ShowDocumentStatus("Nested prefabs are not allowed. Instantiated object will not be linked to prefab template."); } } if (pDocument->Paste(ToBePasted, graph, m_bAllowPickedPosition, "application/ezEditor.ezAbstractGraph")) { for (const auto& item : ToBePasted) { auto& po = m_PastedObjects.ExpandAndGetRef(); po.m_pObject = item.m_pObject; po.m_pParent = item.m_pParent; po.m_Index = item.m_pObject->GetPropertyIndex(); po.m_sParentProperty = item.m_pObject->GetParentProperty(); } } else { for (const auto& item : ToBePasted) { pDocument->GetObjectManager()->DestroyObject(item.m_pObject); } ToBePasted.Clear(); } if (m_PastedObjects.IsEmpty()) return ezStatus("Paste Objects: nothing was pasted!"); if (!m_sObjectGraph.IsEmpty()) ezPrefabUtils::LoadGraph(graph, m_sObjectGraph); else ezPrefabUtils::LoadGraph(graph, m_sBasePrefabGraph); graph.ReMapNodeGuids(m_RemapGuid); // a prefab can have multiple top level nodes ezHybridArray<ezAbstractObjectNode*, 4> rootNodes; ezPrefabUtils::GetRootNodes(graph, rootNodes); for (auto* pPrefabRoot : rootNodes) { ezDocumentObjectConverterReader reader(&graph, pDocument->GetObjectManager(), ezDocumentObjectConverterReader::Mode::CreateOnly); if (auto* pNewObject = reader.CreateObjectFromNode(pPrefabRoot)) { reader.ApplyPropertiesToObject(pPrefabRoot, pNewObject); // attach all prefab nodes to the main group node pDocument->GetObjectManager()->AddObject(pNewObject, pRootObject, szParentProperty, -1); } } } else { // Re-add at recorded place. for (auto& po : m_PastedObjects) { pDocument->GetObjectManager()->AddObject(po.m_pObject, po.m_pParent, po.m_sParentProperty, po.m_Index); } } return ezStatus(EZ_SUCCESS); } ezStatus ezInstantiatePrefabCommand::UndoInternal(bool bFireEvents) { EZ_ASSERT_DEV(bFireEvents, "This command does not support temporary commands"); ezDocument* pDocument = GetDocument(); for (auto& po : m_PastedObjects) { EZ_SUCCEED_OR_RETURN(pDocument->GetObjectManager()->CanRemove(po.m_pObject)); pDocument->GetObjectManager()->RemoveObject(po.m_pObject); } return ezStatus(EZ_SUCCESS); } void ezInstantiatePrefabCommand::CleanupInternal(CommandState state) { if (state == CommandState::WasUndone) { for (auto& po : m_PastedObjects) { GetDocument()->GetObjectManager()->DestroyObject(po.m_pObject); } m_PastedObjects.Clear(); } } ////////////////////////////////////////////////////////////////////////// // ezUnlinkPrefabCommand ////////////////////////////////////////////////////////////////////////// ezStatus ezUnlinkPrefabCommand::DoInternal(bool bRedo) { ezDocument* pDocument = GetDocument(); ezDocumentObject* pObject = pDocument->GetObjectManager()->GetObject(m_Object); if (pObject == nullptr) return ezStatus("Unlink Prefab: The given object does not exist!"); // store previous values if (!bRedo) { auto pMeta = pDocument->m_DocumentObjectMetaData.BeginReadMetaData(m_Object); m_OldCreateFromPrefab = pMeta->m_CreateFromPrefab; m_OldRemapGuid = pMeta->m_PrefabSeedGuid; m_sOldGraphTextFormat = pMeta->m_sBasePrefab; pDocument->m_DocumentObjectMetaData.EndReadMetaData(); } // unlink { auto pMeta = pDocument->m_DocumentObjectMetaData.BeginModifyMetaData(m_Object); pMeta->m_CreateFromPrefab = ezUuid(); pMeta->m_PrefabSeedGuid = ezUuid(); pMeta->m_sBasePrefab.Clear(); pDocument->m_DocumentObjectMetaData.EndModifyMetaData(ezDocumentObjectMetaData::PrefabFlag); } return ezStatus(EZ_SUCCESS); } ezStatus ezUnlinkPrefabCommand::UndoInternal(bool bFireEvents) { ezDocument* pDocument = GetDocument(); ezDocumentObject* pObject = pDocument->GetObjectManager()->GetObject(m_Object); if (pObject == nullptr) return ezStatus("Unlink Prefab: The given object does not exist!"); // restore link { auto pMeta = pDocument->m_DocumentObjectMetaData.BeginModifyMetaData(m_Object); pMeta->m_CreateFromPrefab = m_OldCreateFromPrefab; pMeta->m_PrefabSeedGuid = m_OldRemapGuid; pMeta->m_sBasePrefab = m_sOldGraphTextFormat; pDocument->m_DocumentObjectMetaData.EndModifyMetaData(ezDocumentObjectMetaData::PrefabFlag); } return ezStatus(EZ_SUCCESS); } //////////////////////////////////////////////////////////////////////// // ezRemoveObjectCommand //////////////////////////////////////////////////////////////////////// ezRemoveObjectCommand::ezRemoveObjectCommand() : m_pParent(nullptr) , m_pObject(nullptr) { } ezStatus ezRemoveObjectCommand::DoInternal(bool bRedo) { ezDocument* pDocument = GetDocument(); if (!bRedo) { if (m_Object.IsValid()) { m_pObject = pDocument->GetObjectManager()->GetObject(m_Object); if (m_pObject == nullptr) return ezStatus("Remove Object: The given object does not exist!"); } else return ezStatus("Remove Object: The given object does not exist!"); EZ_SUCCEED_OR_RETURN(pDocument->GetObjectManager()->CanRemove(m_pObject)); m_pParent = const_cast<ezDocumentObject*>(m_pObject->GetParent()); m_sParentProperty = m_pObject->GetParentProperty(); const ezIReflectedTypeAccessor& accessor = m_pObject->GetParent()->GetTypeAccessor(); m_Index = accessor.GetPropertyChildIndex(m_pObject->GetParentProperty(), m_pObject->GetGuid()); } pDocument->GetObjectManager()->RemoveObject(m_pObject); return ezStatus(EZ_SUCCESS); } ezStatus ezRemoveObjectCommand::UndoInternal(bool bFireEvents) { EZ_ASSERT_DEV(bFireEvents, "This command does not support temporary commands"); ezDocument* pDocument = GetDocument(); EZ_SUCCEED_OR_RETURN( pDocument->GetObjectManager()->CanAdd(m_pObject->GetTypeAccessor().GetType(), m_pParent, m_sParentProperty, m_Index)); pDocument->GetObjectManager()->AddObject(m_pObject, m_pParent, m_sParentProperty, m_Index); return ezStatus(EZ_SUCCESS); } void ezRemoveObjectCommand::CleanupInternal(CommandState state) { if (state == CommandState::WasDone) { GetDocument()->GetObjectManager()->DestroyObject(m_pObject); m_pObject = nullptr; } } //////////////////////////////////////////////////////////////////////// // ezMoveObjectCommand //////////////////////////////////////////////////////////////////////// ezMoveObjectCommand::ezMoveObjectCommand() { m_pObject = nullptr; m_pOldParent = nullptr; m_pNewParent = nullptr; } ezStatus ezMoveObjectCommand::DoInternal(bool bRedo) { ezDocument* pDocument = GetDocument(); if (!bRedo) { { m_pObject = pDocument->GetObjectManager()->GetObject(m_Object); if (m_pObject == nullptr) return ezStatus("Move Object: The given object does not exist!"); } if (m_NewParent.IsValid()) { m_pNewParent = pDocument->GetObjectManager()->GetObject(m_NewParent); if (m_pNewParent == nullptr) return ezStatus("Move Object: The new parent does not exist!"); } m_pOldParent = const_cast<ezDocumentObject*>(m_pObject->GetParent()); m_sOldParentProperty = m_pObject->GetParentProperty(); const ezIReflectedTypeAccessor& accessor = m_pOldParent->GetTypeAccessor(); m_OldIndex = accessor.GetPropertyChildIndex(m_pObject->GetParentProperty(), m_pObject->GetGuid()); EZ_SUCCEED_OR_RETURN(pDocument->GetObjectManager()->CanMove(m_pObject, m_pNewParent, m_sParentProperty, m_Index)); } pDocument->GetObjectManager()->MoveObject(m_pObject, m_pNewParent, m_sParentProperty, m_Index); return ezStatus(EZ_SUCCESS); } ezStatus ezMoveObjectCommand::UndoInternal(bool bFireEvents) { EZ_ASSERT_DEV(bFireEvents, "This command does not support temporary commands"); ezDocument* pDocument = GetDocument(); ezVariant FinalOldPosition = m_OldIndex; if (m_Index.CanConvertTo<ezInt32>() && m_pOldParent == m_pNewParent) { // If we are moving an object downwards, we must move by more than 1 (+1 would be behind the same object, which is still the same // position) so an object must always be moved by at least +2 moving UP can be done by -1, so when we undo that, we must ensure to move // +2 ezInt32 iNew = m_Index.ConvertTo<ezInt32>(); ezInt32 iOld = m_OldIndex.ConvertTo<ezInt32>(); if (iNew < iOld) { FinalOldPosition = iOld + 1; } } EZ_SUCCEED_OR_RETURN(pDocument->GetObjectManager()->CanMove(m_pObject, m_pOldParent, m_sOldParentProperty, FinalOldPosition)); pDocument->GetObjectManager()->MoveObject(m_pObject, m_pOldParent, m_sOldParentProperty, FinalOldPosition); return ezStatus(EZ_SUCCESS); } //////////////////////////////////////////////////////////////////////// // ezSetObjectPropertyCommand //////////////////////////////////////////////////////////////////////// ezSetObjectPropertyCommand::ezSetObjectPropertyCommand() { m_pObject = nullptr; } ezStatus ezSetObjectPropertyCommand::DoInternal(bool bRedo) { ezDocument* pDocument = GetDocument(); if (!bRedo) { if (m_Object.IsValid()) { m_pObject = pDocument->GetObjectManager()->GetObject(m_Object); if (m_pObject == nullptr) return ezStatus("Set Property: The given object does not exist!"); } else return ezStatus("Set Property: The given object does not exist!"); ezIReflectedTypeAccessor& accessor0 = m_pObject->GetTypeAccessor(); ezStatus res; m_OldValue = accessor0.GetValue(m_sProperty, m_Index, &res); if (res.Failed()) return res; ezAbstractProperty* pProp = accessor0.GetType()->FindPropertyByName(m_sProperty); if (pProp == nullptr) return ezStatus(ezFmt("Set Property: The property '{0}' does not exist", m_sProperty)); if (pProp->GetFlags().IsSet(ezPropertyFlags::PointerOwner)) { return ezStatus(ezFmt("Set Property: The property '{0}' is a PointerOwner, use ezAddObjectCommand instead", m_sProperty)); } } return pDocument->GetObjectManager()->SetValue(m_pObject, m_sProperty, m_NewValue, m_Index); } ezStatus ezSetObjectPropertyCommand::UndoInternal(bool bFireEvents) { if (bFireEvents) { return GetDocument()->GetObjectManager()->SetValue(m_pObject, m_sProperty, m_OldValue, m_Index); } else { ezIReflectedTypeAccessor& accessor = m_pObject->GetTypeAccessor(); if (!accessor.SetValue(m_sProperty, m_OldValue, m_Index)) { return ezStatus(ezFmt("Set Property: The property '{0}' does not exist", m_sProperty)); } } return ezStatus(EZ_SUCCESS); } //////////////////////////////////////////////////////////////////////// // ezSetObjectPropertyCommand //////////////////////////////////////////////////////////////////////// ezResizeAndSetObjectPropertyCommand::ezResizeAndSetObjectPropertyCommand() { m_pObject = nullptr; } ezStatus ezResizeAndSetObjectPropertyCommand::DoInternal(bool bRedo) { ezDocument* pDocument = GetDocument(); if (!bRedo) { if (m_Object.IsValid()) { m_pObject = pDocument->GetObjectManager()->GetObject(m_Object); if (m_pObject == nullptr) return ezStatus("Set Property: The given object does not exist!"); } else return ezStatus("Set Property: The given object does not exist!"); const ezInt32 uiIndex = m_Index.ConvertTo<ezInt32>(); ezIReflectedTypeAccessor& accessor0 = m_pObject->GetTypeAccessor(); const ezInt32 iCount = accessor0.GetCount(m_sProperty); for (ezInt32 i = iCount; i <= uiIndex; ++i) { ezInsertObjectPropertyCommand ins; ins.m_Object = m_Object; ins.m_sProperty = m_sProperty; ins.m_Index = i; ins.m_NewValue = ezReflectionUtils::GetDefaultVariantFromType(m_NewValue.GetType()); AddSubCommand(ins); } ezSetObjectPropertyCommand set; set.m_sProperty = m_sProperty; set.m_Index = m_Index; set.m_NewValue = m_NewValue; set.m_Object = m_Object; AddSubCommand(set); } return ezStatus(EZ_SUCCESS); } //////////////////////////////////////////////////////////////////////// // ezInsertObjectPropertyCommand //////////////////////////////////////////////////////////////////////// ezInsertObjectPropertyCommand::ezInsertObjectPropertyCommand() { m_pObject = nullptr; } ezStatus ezInsertObjectPropertyCommand::DoInternal(bool bRedo) { ezDocument* pDocument = GetDocument(); if (!bRedo) { if (m_Object.IsValid()) { m_pObject = pDocument->GetObjectManager()->GetObject(m_Object); if (m_pObject == nullptr) return ezStatus("Insert Property: The given object does not exist!"); } else return ezStatus("Insert Property: The given object does not exist!"); if (m_Index.CanConvertTo<ezInt32>() && m_Index.ConvertTo<ezInt32>() == -1) { ezIReflectedTypeAccessor& accessor = m_pObject->GetTypeAccessor(); m_Index = accessor.GetCount(m_sProperty.GetData()); } } return pDocument->GetObjectManager()->InsertValue(m_pObject, m_sProperty, m_NewValue, m_Index); } ezStatus ezInsertObjectPropertyCommand::UndoInternal(bool bFireEvents) { if (bFireEvents) { return GetDocument()->GetObjectManager()->RemoveValue(m_pObject, m_sProperty, m_Index); } else { ezIReflectedTypeAccessor& accessor = m_pObject->GetTypeAccessor(); if (!accessor.RemoveValue(m_sProperty, m_Index)) { return ezStatus(ezFmt("Insert Property: The property '{0}' does not exist", m_sProperty)); } } return ezStatus(EZ_SUCCESS); } //////////////////////////////////////////////////////////////////////// // ezRemoveObjectPropertyCommand //////////////////////////////////////////////////////////////////////// ezRemoveObjectPropertyCommand::ezRemoveObjectPropertyCommand() { m_pObject = nullptr; } ezStatus ezRemoveObjectPropertyCommand::DoInternal(bool bRedo) { ezDocument* pDocument = GetDocument(); if (!bRedo) { if (m_Object.IsValid()) { m_pObject = pDocument->GetObjectManager()->GetObject(m_Object); if (m_pObject == nullptr) return ezStatus("Remove Property: The given object does not exist!"); ezStatus res; m_OldValue = m_pObject->GetTypeAccessor().GetValue(m_sProperty, m_Index, &res); if (res.Failed()) return res; } else return ezStatus("Remove Property: The given object does not exist!"); } return pDocument->GetObjectManager()->RemoveValue(m_pObject, m_sProperty, m_Index); } ezStatus ezRemoveObjectPropertyCommand::UndoInternal(bool bFireEvents) { if (bFireEvents) { return GetDocument()->GetObjectManager()->InsertValue(m_pObject, m_sProperty, m_OldValue, m_Index); } else { ezIReflectedTypeAccessor& accessor = m_pObject->GetTypeAccessor(); if (!accessor.InsertValue(m_sProperty, m_Index, m_OldValue)) { return ezStatus(ezFmt("Remove Property: Undo failed! The index '{0}' in property '{1}' does not exist", m_Index.ConvertTo<ezString>(), m_sProperty)); } } return ezStatus(EZ_SUCCESS); } //////////////////////////////////////////////////////////////////////// // ezMoveObjectPropertyCommand //////////////////////////////////////////////////////////////////////// ezMoveObjectPropertyCommand::ezMoveObjectPropertyCommand() { m_pObject = nullptr; } ezStatus ezMoveObjectPropertyCommand::DoInternal(bool bRedo) { ezDocument* pDocument = GetDocument(); if (!bRedo) { m_pObject = pDocument->GetObjectManager()->GetObject(m_Object); if (m_pObject == nullptr) return ezStatus("Move Property: The given object does not exist."); } return GetDocument()->GetObjectManager()->MoveValue(m_pObject, m_sProperty, m_OldIndex, m_NewIndex); } ezStatus ezMoveObjectPropertyCommand::UndoInternal(bool bFireEvents) { EZ_ASSERT_DEV(bFireEvents, "This command does not support temporary commands"); ezVariant FinalOldPosition = m_OldIndex; ezVariant FinalNewPosition = m_NewIndex; if (m_OldIndex.CanConvertTo<ezInt32>()) { // If we are moving an object downwards, we must move by more than 1 (+1 would be behind the same object, which is still the same // position) so an object must always be moved by at least +2 moving UP can be done by -1, so when we undo that, we must ensure to move // +2 ezInt32 iNew = m_NewIndex.ConvertTo<ezInt32>(); ezInt32 iOld = m_OldIndex.ConvertTo<ezInt32>(); if (iNew < iOld) { FinalOldPosition = iOld + 1; } // The new position is relative to the original array, so we need to substract one to account for // the removal of the same element at the lower index. if (iNew > iOld) { FinalNewPosition = iNew - 1; } } return GetDocument()->GetObjectManager()->MoveValue(m_pObject, m_sProperty, FinalOldPosition, FinalNewPosition); }
// // Copyright 2021 Splunk Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include <scheduling/interval_scheduler.h> #include <util/log.h> #include <utility> #include <cassert> namespace scheduling { IntervalScheduler::IntervalScheduler(uv_loop_t &loop, JobType job): job_(std::move(job)), timer_(loop, std::bind(&IntervalScheduler::callback, this)) {} bool IntervalScheduler::defer(TimerPeriod timeout) { return start(timeout, TimerPeriod::zero()); } bool IntervalScheduler::start(TimerPeriod timeout, TimerPeriod interval) { reset_backoff(); interval_ = interval; if (auto result = timer_.defer(timeout); !result) { LOG::error("unable to start interval scheduler: {}", result.error()); return false; } return started_ = true; } bool IntervalScheduler::start(TimerPeriod timeout) { return start(timeout, timeout); } bool IntervalScheduler::restart() { if (auto result = timer_.restart(); !result) { LOG::error("unable to restart interval scheduler: {}", result.error()); return false; } return started_ = true; } bool IntervalScheduler::stop() { if (!started_) { return true; } if (auto result = timer_.stop(); !result) { LOG::error("unable to stop interval scheduler: {}", result.error()); return false; } started_ = false; return true; } void IntervalScheduler::callback() { switch (job_()) { case JobFollowUp::ok: { if (backoff_count_) { reset_backoff(); } if (interval_ != TimerPeriod::zero()) { timer_.defer(interval_); } break; } case JobFollowUp::stop: { stop(); break; } case JobFollowUp::backoff: { ++backoff_count_; backoff_ratio_ *= BACKOFF_RATIO; auto const interval = interval_ * backoff_ratio_; timer_.defer(interval); break; } default: assert(false); break; } } void IntervalScheduler::reset_backoff() { backoff_count_ = 0; backoff_ratio_ = 1; } } // namespace scheduling
/* @copyright Louis Dionne 2015 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #define BOOST_HANA_TEST_COMPARABLE_ORDERABLE_MCD #include "main.hpp"
#include <vector> #include <string> #include <iostream> #include "Week03_Task04_responses.h" using namespace std; ostream& operator << (ostream& os, const BusesForStopResponse& r) { if (r.buses.empty()) { os << "No stop";// << endl; } else { for (const string& bus : r.buses) { os << bus << " "; } os << endl; } return os; } ostream& operator << (ostream& os, const StopsForBusResponse& r) { if (r.stops.empty()) { cout << "No bus";// << endl; } else { for (const auto& stop : r.stops) { cout << "Stop " << stop.first << ": "; if (stop.second.size() == 0) { cout << "no interchange"; } else { for (const string& bus : stop.second) { cout << bus << " "; } } cout << endl; } } return os; } ostream& operator << (ostream& os, const AllBusesResponse& r) { if (r.buses.empty()) { cout << "No buses";// << endl; } else { for (const auto& bus : r.buses) { cout << "Bus " << bus.first << ": "; for (const string& stop : bus.second) { cout << stop << " "; } cout << endl; } } return os; }
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/vm/native.h" #include "hphp/runtime/base/req-ptr.h" #include "hphp/runtime/base/type-variant.h" #include "hphp/runtime/vm/func-emitter.h" #include "hphp/runtime/vm/runtime.h" #include "hphp/runtime/vm/unit.h" #include "hphp/runtime/ext_zend_compat/hhvm/zend-wrap-func.h" namespace HPHP { namespace Native { ////////////////////////////////////////////////////////////////////////////// BuiltinFunctionMap s_builtinFunctions; ConstantMap s_constant_map; ClassConstantMapMap s_class_constant_map; static size_t numGPRegArgs() { #ifdef __aarch64__ return 8; // r0-r7 #elif defined(__powerpc64__) return 31; #else // amd64 return 6; // rdi, rsi, rdx, rcx, r8, r9 #endif } // Note: This number should generally not be modified // as it depends on the CPU's ABI. // If an update is needed, however, update and run // make_native-func-caller.php as well const size_t kNumSIMDRegs = 8; ///////////////////////////////////////////////////////////////////////////// #include "hphp/runtime/vm/native-func-caller.h" static void nativeArgHelper(const Func* func, int i, const MaybeDataType& type, TypedValue& arg, int64_t* GP_args, int& GP_count) { auto val = arg.m_data.num; if (!type) { if (func->byRef(i)) { if (arg.m_type != KindOfRef) { // For OutputArgs, if the param is not a KindOfRef, // we give it a nullptr val = 0; } } else { GP_args[GP_count++] = val; assert((GP_count + 1) < kMaxBuiltinArgs); val = arg.m_type; } } GP_args[GP_count++] = val; } /* Shuffle args into two vectors. * * SIMD_args contains at most 8 elements for the first 8 double args in the * call which will end up in xmm0-xmm7 (or v0-v7) * * GP_args contains all remaining args optionally with padding to ensure the * GP regs only contain integer arguments (when there are less than * numGPRegArgs INT args) */ static void populateArgs(const Func* func, TypedValue* args, const int numArgs, int64_t* GP_args, int& GP_count, double* SIMD_args, int& SIMD_count) { auto numGP = numGPRegArgs(); int64_t tmp[kMaxBuiltinArgs]; int ntmp = 0; for (size_t i = 0; i < numArgs; ++i) { const auto& pi = func->params()[i]; MaybeDataType type = pi.builtinType; if (type == KindOfDouble) { if (SIMD_count < kNumSIMDRegs) { SIMD_args[SIMD_count++] = args[-i].m_data.dbl; #if defined(__powerpc64__) // According with ABI, the GP index must be incremented after // a floating point function argument if (GP_count < numGP) GP_args[GP_count++] = 0; #endif } else if (GP_count < numGP) { // We have enough double args to hit the stack // but we haven't finished filling the GP regs yet. // Stack these in tmp (autoboxed to int64_t) // until we fill the GP regs, or we run out of args // (in which case we'll pad them). tmp[ntmp++] = args[-i].m_data.num; } else { // Additional SIMD args wind up on the stack // and can autobox with integer types GP_args[GP_count++] = args[-i].m_data.num; } } else { assert((GP_count + 1) < kMaxBuiltinArgs); if (pi.nativeArg) { nativeArgHelper(func, i, type, args[-i], GP_args, GP_count); } else if (!type) { GP_args[GP_count++] = (int64_t)(args - i); } else if (isBuiltinByRef(type)) { GP_args[GP_count++] = (int64_t)&args[-i].m_data; } else { GP_args[GP_count++] = args[-i].m_data.num; } if ((GP_count == numGP) && ntmp) { // GP regs are now full, bring tmp back to fill the initial stack assert((GP_count + ntmp) <= kMaxBuiltinArgs); memcpy(GP_args + GP_count, tmp, ntmp * sizeof(int64_t)); GP_count += ntmp; ntmp = 0; } } } if (ntmp) { assert((GP_count + ntmp) <= kMaxBuiltinArgs); // We had more than kNumSIMDRegs doubles, // but less than numGPRegArgs INTs. // Push out the count and leave garbage behind. if (GP_count < numGP) { GP_count = numGP; } memcpy(GP_args + GP_count, tmp, ntmp * sizeof(int64_t)); GP_count += ntmp; } } /* A much simpler version of the above specialized for GP-arg-only methods */ static void populateArgsNoDoubles(const Func* func, TypedValue* args, int numArgs, int64_t* GP_args, int& GP_count) { assert(numArgs >= 0); for (int i = 0; i < numArgs; ++i) { auto const& pi = func->params()[i]; auto dt = pi.builtinType; assert(dt != KindOfDouble); if (pi.nativeArg) { nativeArgHelper(func, i, dt, args[-i], GP_args, GP_count); } else if (!dt) { GP_args[GP_count++] = (int64_t)(args - i); } else if (isBuiltinByRef(dt)) { GP_args[GP_count++] = (int64_t)&(args[-i].m_data); } else { GP_args[GP_count++] = args[-i].m_data.num; } } } template<bool usesDoubles> void callFunc(const Func* func, void *ctx, TypedValue *args, int32_t numNonDefault, TypedValue& ret) { int64_t GP_args[kMaxBuiltinArgs]; double SIMD_args[kNumSIMDRegs]; int GP_count = 0, SIMD_count = 0; auto const numArgs = func->numParams(); auto retType = func->hniReturnType(); if (ctx) { GP_args[GP_count++] = (int64_t)ctx; } if (func->attrs() & AttrNumArgs) { GP_args[GP_count++] = (int64_t)numNonDefault; } if (usesDoubles) { populateArgs(func, args, numArgs, GP_args, GP_count, SIMD_args, SIMD_count); } else { populateArgsNoDoubles(func, args, numArgs, GP_args, GP_count); } BuiltinFunction f = func->nativeFuncPtr(); if (!retType) { // A folly::none return signifies Variant. if (func->isReturnByValue()) { ret = callFuncTVImpl(f, GP_args, GP_count, SIMD_args, SIMD_count); } else { new (&ret) Variant(callFuncIndirectImpl<Variant>(f, GP_args, GP_count, SIMD_args, SIMD_count)); if (ret.m_type == KindOfUninit) { ret.m_type = KindOfNull; } } return; } ret.m_type = *retType; switch (*retType) { case KindOfNull: case KindOfBoolean: ret.m_data.num = callFuncInt64Impl(f, GP_args, GP_count, SIMD_args, SIMD_count) & 1; return; case KindOfInt64: ret.m_data.num = callFuncInt64Impl(f, GP_args, GP_count, SIMD_args, SIMD_count); return; case KindOfDouble: ret.m_data.dbl = callFuncDoubleImpl(f, GP_args, GP_count, SIMD_args, SIMD_count); return; case KindOfPersistentString: case KindOfString: case KindOfPersistentVec: case KindOfVec: case KindOfPersistentDict: case KindOfDict: case KindOfPersistentKeyset: case KindOfKeyset: case KindOfPersistentArray: case KindOfArray: case KindOfObject: case KindOfResource: case KindOfRef: { assert(isBuiltinByRef(ret.m_type)); if (func->isReturnByValue()) { auto val = callFuncInt64Impl(f, GP_args, GP_count, SIMD_args, SIMD_count); ret.m_data.num = val; } else { using T = req::ptr<StringData>; new (&ret.m_data) T(callFuncIndirectImpl<T>(f, GP_args, GP_count, SIMD_args, SIMD_count)); } if (ret.m_data.num == 0) { ret.m_type = KindOfNull; } return; } case KindOfUninit: break; } not_reached(); } ////////////////////////////////////////////////////////////////////////////// #define COERCE_OR_CAST(kind, warn_kind) \ if (paramCoerceMode) { \ if (!tvCoerceParamTo##kind##InPlace(&args[-i])) { \ raise_param_type_warning( \ func->displayName()->data(), \ i+1, \ KindOf##warn_kind, \ args[-i].m_type \ ); \ return false; \ } \ } else { \ tvCastTo##kind##InPlace(&args[-i]); \ } #define CASE(kind) \ case KindOf##kind: \ COERCE_OR_CAST(kind, kind) \ break; /* end of case */ bool coerceFCallArgs(TypedValue* args, int32_t numArgs, int32_t numNonDefault, const Func* func, bool useStrictTypes) { assert(numArgs == func->numParams()); bool paramCoerceMode = func->isParamCoerceMode(); for (int32_t i = 0; (i < numNonDefault) && (i < numArgs); i++) { const Func::ParamInfo& pi = func->params()[i]; auto tc = pi.typeConstraint; auto targetType = pi.builtinType; if (tc.isNullable() && !func->byRef(i)) { if (isNullType(args[-i].m_type)) { // No need to coerce when passed a null for a nullable type continue; } // Arg isn't null, so treat it like the underlying type for coersion // purposes. The ABI-passed type will still be mixed/Variant. targetType = tc.underlyingDataType(); } // Skip tvCoerceParamTo*() call if we're already the right type, or if its a // Variant. if (!targetType || equivDataTypes(args[-i].m_type, *targetType)) continue; if (RuntimeOption::PHP7_ScalarTypes && useStrictTypes) { tc.verifyParam(&args[-i], func, i, true); return true; } switch (*targetType) { CASE(Boolean) CASE(Int64) CASE(Double) CASE(String) CASE(Vec) CASE(Dict) CASE(Keyset) CASE(Array) CASE(Resource) case KindOfObject: { if (pi.hasDefaultValue()) { COERCE_OR_CAST(NullableObject, Object); } else { COERCE_OR_CAST(Object, Object); } break; } case KindOfUninit: case KindOfNull: case KindOfPersistentString: case KindOfPersistentVec: case KindOfPersistentDict: case KindOfPersistentKeyset: case KindOfPersistentArray: case KindOfRef: not_reached(); } } return true; } #undef CASE #undef COERCE_OR_CAST static inline int32_t minNumArgs(ActRec* ar) { auto func = ar->m_func; auto numArgs = func->numNonVariadicParams(); int32_t num = numArgs; const Func::ParamInfoVec& paramInfo = func->params(); while (num && (paramInfo[num-1].funcletOff != InvalidAbsoluteOffset)) { --num; } return num; } const StringData* getInvokeName(ActRec* ar) { if (ar->magicDispatch()) { return ar->getInvName(); } return ar->func()->fullDisplayName(); } bool nativeWrapperCheckArgs(ActRec* ar) { auto func = ar->m_func; auto numArgs = func->numNonVariadicParams(); auto numNonDefault = ar->numArgs(); if (numNonDefault < numArgs) { const Func::ParamInfoVec& paramInfo = func->params(); for (auto i = numNonDefault; i < numArgs; ++i) { if (InvalidAbsoluteOffset == paramInfo[i].funcletOff) { // There's at least one non-default param which wasn't passed throw_wrong_arguments_nr(getInvokeName(ar)->data(), numNonDefault, minNumArgs(ar), numArgs, 1); return false; } } } else if (numNonDefault > numArgs && !func->hasVariadicCaptureParam()) { // Too many arguments passed, raise a warning ourselves this time throw_wrong_arguments_nr(getInvokeName(ar)->data(), numNonDefault, minNumArgs(ar), numArgs, 1); return false; } // Looks good return true; } template<bool usesDoubles> TypedValue* functionWrapper(ActRec* ar) { assert(ar); auto func = ar->m_func; auto numArgs = func->numParams(); auto numNonDefault = ar->numArgs(); auto strict = !ar->useWeakTypes(); TypedValue* args = ((TypedValue*)ar) - 1; TypedValue rv; rv.m_type = KindOfNull; if (((numNonDefault == numArgs) || (nativeWrapperCheckArgs(ar))) && (coerceFCallArgs(args, numArgs, numNonDefault, func, strict))) { callFunc<usesDoubles>(func, nullptr, args, numNonDefault, rv); } else if (func->attrs() & AttrParamCoerceModeFalse) { rv.m_type = KindOfBoolean; rv.m_data.num = 0; } assert(rv.m_type != KindOfUninit); frame_free_locals_no_this_inl(ar, func->numLocals(), &rv); tvCopy(rv, *ar->retSlot()); return ar->retSlot(); } template<bool usesDoubles> TypedValue* methodWrapper(ActRec* ar) { assert(ar); auto func = ar->m_func; auto numArgs = func->numParams(); auto numNonDefault = ar->numArgs(); bool isStatic = func->isStatic(); auto strict = !ar->useWeakTypes(); TypedValue* args = ((TypedValue*)ar) - 1; TypedValue rv; rv.m_type = KindOfNull; if (((numNonDefault == numArgs) || (nativeWrapperCheckArgs(ar))) && (coerceFCallArgs(args, numArgs, numNonDefault, func, strict))) { // Prepend a context arg for methods // Class when it's being called statically Foo::bar() // Object when it's being called on an instance $foo->bar() void* ctx; // ObjectData* or Class* if (ar->hasThis()) { if (isStatic) { throw_instance_method_fatal(getInvokeName(ar)->data()); } ctx = ar->getThis(); } else { if (!isStatic) { throw_instance_method_fatal(getInvokeName(ar)->data()); } ctx = ar->getClass(); } callFunc<usesDoubles>(func, ctx, args, numNonDefault, rv); } else if (func->attrs() & AttrParamCoerceModeFalse) { rv.m_type = KindOfBoolean; rv.m_data.num = 0; } assert(rv.m_type != KindOfUninit); if (isStatic) { frame_free_locals_no_this_inl(ar, func->numLocals(), &rv); } else { frame_free_locals_inl(ar, func->numLocals(), &rv); } tvCopy(rv, *ar->retSlot()); return ar->retSlot(); } TypedValue* unimplementedWrapper(ActRec* ar) { auto func = ar->m_func; auto cls = func->cls(); if (cls) { raise_error("Call to unimplemented native method %s::%s()", cls->name()->data(), func->name()->data()); tvWriteNull(ar->retSlot()); if (func->isStatic()) { frame_free_locals_no_this_inl(ar, func->numParams(), ar->retSlot()); } else { frame_free_locals_inl(ar, func->numParams(), ar->retSlot()); } } else { raise_error("Call to unimplemented native function %s()", func->displayName()->data()); tvWriteNull(ar->retSlot()); frame_free_locals_no_this_inl(ar, func->numParams(), ar->retSlot()); } return ar->retSlot(); } void getFunctionPointers(const BuiltinFunctionInfo& info, int nativeAttrs, BuiltinFunction& bif, BuiltinFunction& nif) { nif = info.ptr; if (!nif) { bif = unimplementedWrapper; return; } if (nativeAttrs & AttrZendCompat) { bif = zend_wrap_func; return; } if (nativeAttrs & AttrActRec) { bif = nif; nif = nullptr; return; } bool usesDoubles = false; for (auto const argType : info.sig.args) { if (argType == NativeSig::Type::Double) { usesDoubles = true; break; } } bool isMethod = info.sig.args.size() && ((info.sig.args[0] == NativeSig::Type::This) || (info.sig.args[0] == NativeSig::Type::Class)); if (isMethod) { if (usesDoubles) { bif = methodWrapper<true>; } else { bif = methodWrapper<false>; } } else { if (usesDoubles) { bif = functionWrapper<true>; } else { bif = functionWrapper<false>; } } } ////////////////////////////////////////////////////////////////////////////// static bool tcCheckNative(const TypeConstraint& tc, const NativeSig::Type ty) { using T = NativeSig::Type; if (tc.isDict() || tc.isVec() || tc.isKeyset()) { return ty == T::Array || ty == T::ArrayArg; } if (!tc.hasConstraint() || tc.isNullable() || tc.isCallable() || tc.isArrayKey() || tc.isNumber()) { return ty == T::Mixed || ty == T::MixedTV; } if (!tc.underlyingDataType()) { return false; } switch (*tc.underlyingDataType()) { case KindOfDouble: return ty == T::Double; case KindOfBoolean: return ty == T::Bool; case KindOfObject: return ty == T::Object || ty == T::ObjectArg; case KindOfPersistentString: case KindOfString: return ty == T::String || ty == T::StringArg; case KindOfPersistentVec: case KindOfVec: return ty == T::Array || ty == T::ArrayArg; case KindOfPersistentDict: case KindOfDict: return ty == T::Array || ty == T::ArrayArg; case KindOfPersistentKeyset: case KindOfKeyset: return ty == T::Array || ty == T::ArrayArg; case KindOfPersistentArray: case KindOfArray: return ty == T::Array || ty == T::ArrayArg; case KindOfResource: return ty == T::Resource || ty == T::ResourceArg; case KindOfUninit: case KindOfNull: return ty == T::Void; case KindOfRef: return ty == T::Mixed || ty == T::OutputArg; case KindOfInt64: return ty == T::Int64 || ty == T::Int32; } not_reached(); } const char* kInvalidReturnTypeMessage = "Invalid return type detected"; const char* kInvalidArgTypeMessage = "Invalid argument type detected"; const char* kInvalidArgCountMessage = "Invalid argument count detected"; const char* kInvalidNumArgsMessage = "\"NumArgs\" builtins must take an int64_t as their first declared argument"; const char* kNeedStaticContextMessage = "Static class functions must take a Class* as their first argument"; const char* kNeedObjectContextMessage = "Instance methods must take an ObjectData* as their first argument"; const char* kInvalidZendFuncMessage = "PHP5 compatibility layer functions must be registered using " "registerBuiltinZendFunction"; const char* kInvalidActRecFuncMessage = "Functions declared as ActRec must return a TypedValue* and take an ActRec* " "as their sole argument"; const char* checkTypeFunc(const NativeSig& sig, const TypeConstraint& retType, const Func* func) { using T = NativeSig::Type; if (sig.ret == T::Zend) { return sig.args.empty() ? nullptr : kInvalidZendFuncMessage; } if (!func->nativeFuncPtr()) { return sig.ret == T::ARReturn && sig.args.size() == 1 && sig.args[0] == T::VarArgs ? nullptr : kInvalidActRecFuncMessage; } if (!tcCheckNative(retType, sig.ret)) return kInvalidReturnTypeMessage; auto argIt = sig.args.begin(); auto endIt = sig.args.end(); if (func->preClass()) { // called from the verifier so m_cls is not set yet if (argIt == endIt) return kInvalidArgCountMessage; auto const ctxTy = *argIt++; if (func->attrs() & HPHP::AttrStatic) { if (ctxTy != T::Class) return kNeedStaticContextMessage; } else { if (ctxTy != T::This) return kNeedObjectContextMessage; } } if (func->attrs() & AttrNumArgs) { if (*argIt++ != T::Int64) return kInvalidNumArgsMessage; } int index = 0; for (auto const& pInfo : func->params()) { if (argIt == endIt) return kInvalidArgCountMessage; auto const argTy = *argIt++; if (func->byRef(index++)) { if (argTy != T::MixedRef && argTy != T::OutputArg) { return kInvalidArgTypeMessage; } continue; } if (pInfo.variadic) { if (argTy != T::Array) return kInvalidArgTypeMessage; continue; } if (!tcCheckNative(pInfo.typeConstraint, argTy)) { return kInvalidArgTypeMessage; } } return argIt == endIt ? nullptr : kInvalidArgCountMessage; } static std::string nativeTypeString(NativeSig::Type ty) { using T = NativeSig::Type; switch (ty) { case T::Int32: case T::Int64: return "int"; case T::Double: return "double"; case T::Bool: return "bool"; case T::Object: return "object"; case T::String: return "string"; case T::Array: return "array"; case T::Resource: return "resource"; case T::ObjectArg: return "object"; case T::StringArg: return "string"; case T::ArrayArg: return "array"; case T::ResourceArg:return "resource"; case T::OutputArg: return "mixed&"; case T::Mixed: return "mixed"; case T::MixedTV: return "mixed"; case T::ARReturn: return "[TypedValue*]"; case T::MixedRef: return "mixed&"; case T::VarArgs: return "..."; case T::This: return "this"; case T::Class: return "class"; case T::Void: return "void"; case T::Zend: return "[zend]"; } not_reached(); } std::string NativeSig::toString(const char* classname, const char* fname) const { using T = NativeSig::Type; auto str = folly::to<std::string>(nativeTypeString(ret), " "); auto argIt = args.begin(); auto endIt = args.end(); if (argIt != endIt) { if (classname) str += classname; if (*argIt == T::This) { str += "->"; ++argIt; } else if (*argIt == T::Class) { str += "::"; ++argIt; } } str += folly::to<std::string>(fname, "(", argIt != endIt ? nativeTypeString(*argIt++) : "void"); for (;argIt != endIt; ++argIt) { str += folly::to<std::string>(", ", nativeTypeString(*argIt)); } str += ")"; return str; } ///////////////////////////////////////////////////////////////////////////// bool registerConstant(const StringData* cnsName, NativeConstantCallback callback) { if (!Unit::defSystemConstantCallback(cnsName, callback)) { return false; } TypedValue tv; tv.m_type = KindOfUninit; tv.m_data.pref = reinterpret_cast<RefData*>(callback); s_constant_map[cnsName] = tv; return true; } ////////////////////////////////////////////////////////////////////////////// }} // namespace HPHP::Native
#include "ITG3200.h" Serial pc(USBTX, USBRX); ITG3200 gyro(p9, p10); int main() { pc.printf("Now starting ITG-3200 test...\n"); //Set highest bandwidth. gyro.setLpBandwidth(LPFBW_42HZ); while (1) { //Arbitrary wait for printf clarity. wait(0.1); pc.printf("%i, %i, %i\n", gyro.getGyroX(), gyro.getGyroY(), gyro.getGyroZ()); } }
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/system/audio/unified_volume_view.h" #include <cmath> #include <memory> #include <utility> #include "ash/public/cpp/ash_features.h" #include "ash/public/cpp/ash_pref_names.h" #include "ash/resources/vector_icons/vector_icons.h" #include "ash/session/session_controller_impl.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" #include "ash/style/ash_color_provider.h" #include "ash/system/tray/tray_popup_utils.h" #include "base/bind.h" #include "base/i18n/rtl.h" #include "base/stl_util.h" #include "components/live_caption/pref_names.h" #include "components/prefs/pref_service.h" #include "components/vector_icons/vector_icons.h" #include "media/base/media_switches.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/canvas.h" #include "ui/gfx/image/image_skia_operations.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/gfx/vector_icon_utils.h" #include "ui/views/animation/flood_fill_ink_drop_ripple.h" #include "ui/views/animation/ink_drop_highlight.h" #include "ui/views/animation/ink_drop_impl.h" #include "ui/views/animation/ink_drop_mask.h" #include "ui/views/background.h" #include "ui/views/controls/button/image_button_factory.h" #include "ui/views/controls/highlight_path_generator.h" #include "ui/views/controls/image_view.h" #include "ui/views/layout/box_layout.h" namespace ash { namespace { // References to the icons that correspond to different volume levels. const gfx::VectorIcon* const kVolumeLevelIcons[] = { &kUnifiedMenuVolumeLowIcon, // Low volume. &kUnifiedMenuVolumeMediumIcon, // Medium volume. &kUnifiedMenuVolumeHighIcon, // High volume. &kUnifiedMenuVolumeHighIcon, // Full volume. }; // The maximum index of kVolumeLevelIcons. constexpr int kVolumeLevels = base::size(kVolumeLevelIcons) - 1; // Get vector icon reference that corresponds to the given volume level. |level| // is between 0.0 to 1.0. const gfx::VectorIcon& GetVolumeIconForLevel(float level) { int index = static_cast<int>(std::ceil(level * kVolumeLevels)); if (index < 0) index = 0; else if (index > kVolumeLevels) index = kVolumeLevels; return *kVolumeLevelIcons[index]; } // A template class for the UnifiedVolumeView buttons, used by the More and // Live Caption buttons. |T| must be a subtype of |views::Button|. template <typename T> class UnifiedVolumeViewButton : public T { public: static_assert(std::is_base_of<views::Button, T>::value, "T must be a subtype of views::Button"); // A constructor that forwards |args| to |T|'s constructor, so |args| are the // exact same as required by |T|'s constructor. It sets up the ink drop on the // view. template <typename... Args> explicit UnifiedVolumeViewButton(Args... args) : T(std::forward<Args>(args)...) { TrayPopupUtils::ConfigureTrayPopupButton(this); views::InstallRoundRectHighlightPathGenerator(this, gfx::Insets(), kTrayItemCornerRadius); T::SetBackground(views::CreateRoundedRectBackground(GetBackgroundColor(), kTrayItemCornerRadius)); } ~UnifiedVolumeViewButton() override = default; void OnThemeChanged() override { T::OnThemeChanged(); auto* color_provider = AshColorProvider::Get(); T::focus_ring()->SetColor(color_provider->GetControlsLayerColor( AshColorProvider::ControlsLayerType::kFocusRingColor)); T::background()->SetNativeControlColor(GetBackgroundColor()); } SkColor GetIconColor() { return AshColorProvider::Get()->GetContentLayerColor( AshColorProvider::ContentLayerType::kButtonIconColor); } SkColor GetBackgroundColor() { return AshColorProvider::Get()->GetControlsLayerColor( AshColorProvider::ControlsLayerType::kControlBackgroundColorInactive); } }; class LiveCaptionButton : public UnifiedVolumeViewButton<views::ToggleImageButton> { public: explicit LiveCaptionButton(PressedCallback callback) : UnifiedVolumeViewButton(std::move(callback)) { DCHECK_EQ(GetDefaultSizeOfVectorIcon(vector_icons::kLiveCaptionOffIcon), GetDefaultSizeOfVectorIcon(vector_icons::kLiveCaptionOnIcon)); int icon_size = GetDefaultSizeOfVectorIcon(vector_icons::kLiveCaptionOnIcon); SetBorder( views::CreateEmptyBorder(gfx::Insets((kTrayItemSize - icon_size) / 2))); SetImageHorizontalAlignment(ALIGN_CENTER); SetImageVerticalAlignment(ALIGN_MIDDLE); SetTooltipText(l10n_util::GetStringFUTF16( IDS_ASH_STATUS_TRAY_LIVE_CAPTION_TOGGLE_TOOLTIP, l10n_util::GetStringUTF16( IDS_ASH_STATUS_TRAY_LIVE_CAPTION_DISABLED_STATE_TOOLTIP))); SetToggledTooltipText(l10n_util::GetStringFUTF16( IDS_ASH_STATUS_TRAY_LIVE_CAPTION_TOGGLE_TOOLTIP, l10n_util::GetStringUTF16( IDS_ASH_STATUS_TRAY_LIVE_CAPTION_ENABLED_STATE_TOOLTIP))); SetToggledBackground(views::CreateRoundedRectBackground( GetToggledBackgroundColor(), kTrayItemCornerRadius)); } ~LiveCaptionButton() override = default; const char* GetClassName() const override { return "LiveCaptionButton"; } void OnThemeChanged() override { UnifiedVolumeViewButton::OnThemeChanged(); const int icon_size = GetDefaultSizeOfVectorIcon(vector_icons::kLiveCaptionOnIcon); views::SetImageFromVectorIconWithColor( this, vector_icons::kLiveCaptionOffIcon, icon_size, GetIconColor()); views::SetToggledImageFromVectorIconWithColor( this, vector_icons::kLiveCaptionOnIcon, icon_size, GetToggledIconColor(), GetToggledIconColor()); GetToggledBackground()->SetNativeControlColor(GetToggledBackgroundColor()); } SkColor GetToggledIconColor() { return AshColorProvider::Get()->GetContentLayerColor( AshColorProvider::ContentLayerType::kButtonIconColorPrimary); } SkColor GetToggledBackgroundColor() { return AshColorProvider::Get()->GetControlsLayerColor( AshColorProvider::ControlsLayerType::kControlBackgroundColorActive); } private: DISALLOW_COPY_AND_ASSIGN(LiveCaptionButton); }; class MoreButton : public UnifiedVolumeViewButton<views::Button> { public: explicit MoreButton(PressedCallback callback) : UnifiedVolumeViewButton(std::move(callback)) { SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kHorizontal, gfx::Insets((kTrayItemSize - GetDefaultSizeOfVectorIcon(kUnifiedMenuExpandIcon)) / 2), 2)); more_image_ = AddChildView(std::make_unique<views::ImageView>()); more_image_->SetCanProcessEventsWithinSubtree(false); SetTooltipText(l10n_util::GetStringUTF16(IDS_ASH_STATUS_TRAY_AUDIO)); } ~MoreButton() override = default; const char* GetClassName() const override { return "MoreButton"; } void OnThemeChanged() override { UnifiedVolumeViewButton::OnThemeChanged(); const SkColor icon_color = GetIconColor(); DCHECK(more_image_); auto icon_rotation = base::i18n::IsRTL() ? SkBitmapOperations::ROTATION_270_CW : SkBitmapOperations::ROTATION_90_CW; more_image_->SetImage(gfx::ImageSkiaOperations::CreateRotatedImage( CreateVectorIcon(kUnifiedMenuExpandIcon, icon_color), icon_rotation)); } private: views::ImageView* more_image_ = nullptr; DISALLOW_COPY_AND_ASSIGN(MoreButton); }; } // namespace UnifiedVolumeView::UnifiedVolumeView( UnifiedVolumeSliderController* controller, UnifiedVolumeSliderController::Delegate* delegate, bool in_bubble) : UnifiedSliderView(base::BindRepeating( &UnifiedVolumeSliderController::SliderButtonPressed, base::Unretained(controller)), controller, kSystemMenuVolumeHighIcon, IDS_ASH_STATUS_TRAY_VOLUME_SLIDER_LABEL), in_bubble_(in_bubble), live_caption_button_(new LiveCaptionButton( base::BindRepeating(&UnifiedVolumeView::OnLiveCaptionButtonPressed, base::Unretained(this)))), more_button_(new MoreButton( base::BindRepeating(&UnifiedVolumeSliderController::Delegate:: OnAudioSettingsButtonClicked, base::Unretained(delegate)))) { CrasAudioHandler::Get()->AddAudioObserver(this); AddChildViewAt(live_caption_button_, 0); AddChildView(more_button_); Update(false /* by_user */); } UnifiedVolumeView::~UnifiedVolumeView() { CrasAudioHandler::Get()->RemoveAudioObserver(this); } const char* UnifiedVolumeView::GetClassName() const { return "UnifiedVolumeView"; } void UnifiedVolumeView::Update(bool by_user) { bool is_muted = CrasAudioHandler::Get()->IsOutputMuted(); float level = CrasAudioHandler::Get()->GetOutputVolumePercent() / 100.f; // To indicate that the volume is muted, set the volume slider to the minimal // visual style. slider()->SetRenderingStyle( is_muted ? views::Slider::RenderingStyle::kMinimalStyle : views::Slider::RenderingStyle::kDefaultStyle); slider()->SetEnabled(!CrasAudioHandler::Get()->IsOutputMutedByPolicy()); // The button should be gray when muted and colored otherwise. button()->SetToggled(!is_muted); button()->SetVectorIcon(is_muted ? kUnifiedMenuVolumeMuteIcon : GetVolumeIconForLevel(level)); std::u16string state_tooltip_text = l10n_util::GetStringUTF16( is_muted ? IDS_ASH_STATUS_TRAY_VOLUME_STATE_MUTED : IDS_ASH_STATUS_TRAY_VOLUME_STATE_ON); button()->SetTooltipText(l10n_util::GetStringFUTF16( IDS_ASH_STATUS_TRAY_VOLUME, state_tooltip_text)); live_caption_button_->SetVisible( in_bubble_ && base::FeatureList::IsEnabled(media::kLiveCaptionSystemWideOnChromeOS)); live_caption_button_->SetToggled( Shell::Get()->session_controller()->GetActivePrefService()->GetBoolean( ::prefs::kLiveCaptionEnabled)); // Slider's value is in finer granularity than audio volume level(0.01), // there will be a small discrepancy between slider's value and volume level // on audio side. To avoid the jittering in slider UI, use the slider's // current value. if (level != 1.0 && std::abs(level - slider()->GetValue()) < kAudioSliderIgnoreUpdateThreshold) { level = slider()->GetValue(); } // Note: even if the value does not change, we still need to call this // function to enable accessibility events (crbug.com/1013251). SetSliderValue(level, by_user); } void UnifiedVolumeView::OnOutputNodeVolumeChanged(uint64_t node_id, int volume) { Update(true /* by_user */); } void UnifiedVolumeView::OnOutputMuteChanged(bool mute_on) { Update(true /* by_user */); } void UnifiedVolumeView::OnAudioNodesChanged() { Update(true /* by_user */); } void UnifiedVolumeView::OnActiveOutputNodeChanged() { Update(true /* by_user */); } void UnifiedVolumeView::OnActiveInputNodeChanged() { Update(true /* by_user */); } void UnifiedVolumeView::ChildVisibilityChanged(views::View* child) { Layout(); } void UnifiedVolumeView::OnLiveCaptionButtonPressed() { PrefService* prefs = Shell::Get()->session_controller()->GetActivePrefService(); bool enabled = !prefs->GetBoolean(::prefs::kLiveCaptionEnabled); prefs->SetBoolean(::prefs::kLiveCaptionEnabled, enabled); live_caption_button_->SetToggled(enabled); } } // namespace ash
/* * File: OutputSection.cpp * * Copyright (c) Freescale Semiconductor, Inc. All rights reserved. * See included license file for license details. */ #include "OutputSection.h"
/* * This file is part of the Marmalade SDK Code Samples. * * (C) 2001-2012 Marmalade. All Rights Reserved. * * This source code is intended only as a supplement to the Marmalade SDK. * * THIS CODE AND INFORMATION ARE 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. */ /* * Sound description. */ #include "IwSoundSpec.h" #include "IwResManager.h" #include "s3eSound.h" #include "IwSound.h" #include "IwSoundData.h" #include "IwSoundGroup.h" #include "IwSoundInst.h" #include "IwSoundParams.h" #include "IwSoundPCM.h" #include "IwSoundADPCM.h" #include "IwDebug.h" #include "IwRandom.h" // Forward Declarations //----------------------------------------------------------------------------- // CIwSoundSpec callbacks //----------------------------------------------------------------------------- int _IwSoundSpec_EndSampleCB(s3eSoundEndSampleInfo* esInfo, void* userData) { IW_CALLSTACK("_IwSoundSpec_EndSampleCB") if (esInfo->m_RepsRemaining) return 1; // End sound CIwSoundInst* pInst = (CIwSoundInst*)userData; pInst->m_Flags |= CIwSoundInst::COMPLETE_F; return 0; } //----------------------------------------------------------------------------- // CIwSoundSpec //----------------------------------------------------------------------------- IW_CLASS_FACTORY(CIwSoundSpec); IW_MANAGED_IMPLEMENT(CIwSoundSpec) CIwSoundSpec::CIwSoundSpec() { IW_CALLSTACK("CIwSoundSpec::CIwSoundSpec") m_Data = NULL; m_VolMin = IW_GEOM_ONE; m_VolMax = IW_GEOM_ONE; m_PanMin = 0; m_PanMax = 0; m_PitchMin = IW_GEOM_ONE; m_PitchMax = IW_GEOM_ONE; m_Group = NULL; m_Flags = 0; } //----------------------------------------------------------------------------- CIwSoundSpec::~CIwSoundSpec() { IW_CALLSTACK("CIwSoundSpec::~CIwSoundSpec"); if (IwGetSoundManager()) IwGetSoundManager()->StopSoundSpec(this); } //----------------------------------------------------------------------------- void CIwSoundSpec::Serialise() { IW_CALLSTACK("CIwSoundSpec::Serialise") CIwManaged::Serialise(); IwSerialiseUInt16(m_Flags); IwSerialiseInt16(m_VolMin); IwSerialiseInt16(m_VolMax); IwSerialiseInt16(m_PanMin); IwSerialiseInt16(m_PanMax); IwSerialiseInt16(m_PitchMin); IwSerialiseInt16(m_PitchMax); // To be resolved: IwSerialiseManagedHash(&m_Data); IwSerialiseManagedHash(&m_Group); } //----------------------------------------------------------------------------- void CIwSoundSpec::Resolve() { IW_CALLSTACK("CIwSoundSpec::Resolve") CIwManaged::Resolve(); IwResolveManagedHash(&m_Data, IW_SOUND_RESTYPE_DATA); IwResolveManagedHash(&m_Group, IW_SOUND_RESTYPE_GROUP); } //----------------------------------------------------------------------------- CIwSoundInst* CIwSoundSpec::Play(const CIwSoundParams* pParams) { IW_CALLSTACK("CIwSoundSpec::Play") // Get free inst - Fail if not available CIwSoundInst* pInst = IwGetSoundManager()->GetFreeInst(); if (!pInst) return NULL; // Fail if no free channel int32 chanID = IwGetSoundManager()->GetFreeChannel(pInst, m_Data->m_Format); if (chanID < 0) { IwGetSoundManager()->SetFreeInst(pInst); return NULL; } IwTrace(SOUND, ("Playing %s %p", DebugGetName(), m_Data->m_Samples)); // Get specified or identity modifying params if (!pParams) pParams = IwGetSoundManager()->GetParamsIdentity(); // Get specified or identity group CIwSoundGroup* pGroup = NULL; if (m_Group) { pGroup = m_Group; if (pGroup->GetMaxPolyphony()) { if (pGroup->GetMaxPolyphony() == pGroup->GetCurrPolyphony()) { // ! I have changed the default behaviour here from killing // ! the oldest instance to just preventing any new sounds // ! being played. This is because there are multithreading // ! issues to consider, which aren't trivial. The current // ! KillOldestInst isn't strictly correct, as the polyphony // ! gets decremented twice - once in our thread, once in // ! the sound thread. Also, because of the delayed stop, // ! if many instances are fired off at once, the fixed // ! buffer can overflow if (pGroup->GetFlags() & CIwSoundGroup::KILL_OLDEST_F) { // Kill oldest instance pGroup->KillOldestInst(true); } else { // Sorry, we're at our limit IwGetSoundManager()->SetFreeInst(pInst); return NULL; } } } // Increase curr polyphony pGroup->m_CurrPolyphony++; } else { pGroup = (CIwSoundGroup*)IwGetSoundManager()->GetGroupIdentity(); } pInst->m_Count = 0; // Get vol/pan/pitch to store with inst iwsfixed vol = (m_VolMin == m_VolMax) ? m_VolMin : (iwsfixed)IwRandMinMax(m_VolMin, m_VolMax); iwsfixed pan = (m_PanMin == m_PanMax) ? m_PanMin : (iwsfixed)IwRandMinMax(m_PanMin, m_PanMax); iwsfixed pitch = (m_PitchMin == m_PitchMax) ? m_PitchMin : (iwsfixed)IwRandMinMax(m_PitchMin, m_PitchMax); // Write to inst pInst->m_Spec = this; pInst->m_Vol = (iwsfixed)IW_FIXED_MUL(vol, pParams->m_Vol); pInst->m_Pan = (iwsfixed)MAX(-IW_GEOM_ONE, MIN(IW_GEOM_ONE, pan + pParams->m_Pan)); pInst->m_Pitch = (iwsfixed)IW_FIXED_MUL(pitch, pParams->m_Pitch); pInst->m_ChanID = (uint16)chanID; pInst->m_EndSampleCB = NULL; // Get final vol/pan/pitch vol = (iwsfixed)IW_FIXED_MUL(pInst->m_Vol, IW_FIXED_MUL(IwGetSoundManager()->GetMasterVol(), pGroup->m_Vol)); pan = (iwsfixed)MAX(-IW_GEOM_ONE, MIN(IW_GEOM_ONE, pan + IwGetSoundManager()->GetMasterPan() + pGroup->m_Pan)); pitch = (iwsfixed)IW_FIXED_MUL(pitch, IW_FIXED_MUL(IwGetSoundManager()->GetMasterPitch(), pGroup->m_Pitch)); bool looped = IsLooped(); if (IwGetSoundManager()->IsActive() == false) return pInst; s3eSoundChannelRegister(chanID, S3E_CHANNEL_END_SAMPLE, (s3eCallback)_IwSoundSpec_EndSampleCB, pInst); // Set volume // s3eSoundChannelSetInt(chanID, S3E_CHANNEL_VOLUME, vol << 4); // PROPOSED FIX TO #379 s3eSoundChannelSetInt(chanID, S3E_CHANNEL_VOLUME, MIN(S3E_SOUND_MAX_VOLUME, vol >> 4)); // convert from .12 to .8 format // TODO: SET PAN // Set pitch int32 pp = IW_FIXED_MUL(pitch, pInst->GetSpec()->GetData()->m_RecPitch); s3eSoundChannelSetInt(chanID, S3E_CHANNEL_RATE, pp); // Play sound according to sample formatzzscz switch (m_Data->m_Format) { case PCM_8BIT_MONO: { CIwArray<int8> samples; m_Data->GetData(samples); s3eSoundChannelPlay(chanID, (int16*) samples.begin(), (int16*) samples.end()-(int16*)samples.begin(), (looped ? -1 : 1), 0); } break; case PCM_16BIT_MONO: { // Get an array containing the data CIwArray<int16> samples; m_Data->GetData(samples); s3eSoundChannelPlay(chanID, (int16*)samples.begin(), (int16*)samples.end()-(int16*)samples.begin(), (looped ? -1 : 1), 0); } break; case ADPCM_MONO: { CIwArray<int16> samples; m_Data->GetData(samples); s3eSoundChannelSetInt(chanID, S3E_CHANNEL_USERVAR, (intptr_t)m_Data); s3eSoundChannelPlay(chanID, (int16*)samples.begin(), (int16*)samples.end()-(int16*)samples.begin(), (looped ? -1 : 1), 0); } break; } // Set callbacks return pInst; } //----------------------------------------------------------------------------- bool CIwSoundSpec::ParseAttribute(CIwTextParserITX* pParser, const char* pAttrName) { IW_CALLSTACK("CIwSoundSpec::ParseAttribute") #ifndef IW_DEBUG IwAssertMsg(SOUND, false, ("Project not built with IW_DEBUG")); return false; #else if (!strcmp(pAttrName, "data")) { // Locate CIwSoundData resource char line[80]; pParser->ReadString(line, 80); m_Data = (CIwSoundData*)IwGetResManager()->GetResNamed(line, IW_SOUND_RESTYPE_DATA); IwAssertMsg(SOUND, m_Data, ("Could not find CIwSoundData named %s", line)); } else if (!strcmp(pAttrName, "vol")) { iwfixed v; pParser->ReadFixed(&v); m_VolMin = m_VolMax = (iwsfixed)v; } else if (!strcmp(pAttrName, "volMin")) { iwfixed v; pParser->ReadFixed(&v); m_VolMin = (iwsfixed)v; } else if (!strcmp(pAttrName, "volMax")) { iwfixed v; pParser->ReadFixed(&v); m_VolMax = (iwsfixed)v; } else if (!strcmp(pAttrName, "pitch")) { iwfixed v; pParser->ReadFixed(&v); m_PitchMin = m_PitchMax = (iwsfixed)v; } else if (!strcmp(pAttrName, "pitchMin")) { iwfixed v; pParser->ReadFixed(&v); m_PitchMin = (iwsfixed)v; } else if (!strcmp(pAttrName, "pitchMax")) { iwfixed v; pParser->ReadFixed(&v); m_PitchMax = (iwsfixed)v; } else if (!strcmp(pAttrName, "loop")) { bool b; pParser->ReadBool(&b); if (b == true) m_Flags |= LOOPED_F; else m_Flags &= ~LOOPED_F; } else if (!strcmp(pAttrName, "group")) { // Locate CIwSoundGroup resource char line[80]; pParser->ReadString(line, 80); CIwSoundGroup* pGroup = IwSafeCast<CIwSoundGroup*> (IwGetResManager()->GetResNamed(line, IW_SOUND_RESTYPE_GROUP)); IwAssertMsgTrap(SOUND, pGroup, ("Could not find CIwSoundGroup named %s", line), return true); SetGroup(pGroup); } else return CIwManaged::ParseAttribute(pParser, pAttrName); #endif return true; } //----------------------------------------------------------------------------- void CIwSoundSpec::ParseClose(CIwTextParserITX* pParser) { IW_CALLSTACK("CIwSoundSpec::ParseClose") #ifndef IW_DEBUG IwAssertMsg(SOUND, false, ("Project not built with IW_DEBUG")); #else // There must be a current resource group IwAssertMsgTrap(SOUND, IwGetResManager()->GetCurrentGroup(), ("No current resource group - don't know what to do with created object"), return); // Add to current resource group IwGetResManager()->GetCurrentGroup()->AddRes(IW_SOUND_RESTYPE_SPEC, this); #endif } //----------------------------------------------------------------------------- void CIwSoundSpec::Trace() { // Output header info #ifdef IW_DEBUG IwTrace(SOUND, ("\"%s\"", DebugGetName())); #endif IwTrace(SOUND, ("Hash: %u Vol: %d->%d Pitch: %d->%d Pan: %d->%d", m_Hash, m_VolMin, m_VolMax, m_PitchMin, m_PitchMax, m_PanMin, m_PanMax)); // Output an ascii graph representing the sample const int32 cColumns = 80; // Width of graph const int32 cRows = 32; // Height of graph // Symbols used to draw the graph - Should look something like this: // .:'| // |||| // -------- // |||| // ':!| // This gives us four units per row of the graph. const char cSymbolsPos[] = { ' ', '.', ':', '\'', '|' }; const char cSymbolsNeg[] = { '|', '!', ':', '\'', ' ' }; char lineBuffer[cColumns + 1]; // Allow space for terminator uint32 sampleSize = m_Data->m_SampleCount; int16 heightUnit; // Sample value represented by each quarter row. CIwArray<int16> samples16; CIwArray<int8> samples8; switch (m_Data->m_Format) { case PCM_8BIT_MONO: heightUnit = 0x100 / (cRows * 4); m_Data->GetData(samples8); IwTrace(SOUND, ("Format: PCM 8-bit mono")); break; case PCM_16BIT_MONO: heightUnit = 0x10000 / (cRows * 4); m_Data->GetData(samples16); IwTrace(SOUND, ("Format: PCM 16-bit mono")); break; default: // Unsupported format IwTrace(SOUND, ("Format: Unsupported")); return; } // Draw the graph for (int32 y = cRows / 2 - 1; y >= (-cRows / 2); y--) // Counting cRows { int16 sampleMin = (int16)(y * 4); const char* symbols = (y >= 0) ? cSymbolsPos : cSymbolsNeg; int32 x = 0; for (x = 0; x < cColumns; x++) { int16 sampleUnits; if (m_Data->m_Format == PCM_16BIT_MONO) sampleUnits = samples16[(x * sampleSize) / cColumns] / heightUnit; else sampleUnits = samples8[(x * sampleSize) / cColumns] / heightUnit; int16 remainder = sampleUnits - sampleMin; if (sampleMin >= sampleUnits) remainder = 0; else if (remainder > 4) remainder = 4; lineBuffer[x] = symbols[remainder]; } // Start and terminate string and output lineBuffer[x] = '\0'; #ifdef IW_USE_TRACING int16 axisVal = (y >= 0) ? (sampleMin + 4) * heightUnit : sampleMin * heightUnit; IwTrace(SOUND, ("%6d %s", axisVal, lineBuffer)); #endif if (y == 0) { // axis line memset(lineBuffer, '-', cColumns); lineBuffer[0] = '0'; lineBuffer[cColumns] = '\0'; IwTrace(SOUND, ("%6d %s", 0, lineBuffer)); } } }
// Copyright 2018 Roie R. Black #include <iostream> #include <string> #include "ALU.h" #include "alu_ops.h" // constructor ALU::ALU(std::string n):Component(n) { this->add_in_pin("IN1"); this->add_in_pin("IN2"); this->add_in_pin("AOP"); this->add_out_pin("RES8"); this->add_out_pin("RES16"); val = 0; } // TICK: perform component processing void ALU::tick(int ctrl) { Pin *in1pin = this->get_in_pin("IN1"); Pin *in2pin = this->get_in_pin("IN2"); Pin *out1pin = this->get_out_pin("RES8"); Pin *out2pin = this->get_out_pin("RES16"); uint16_t ival1, ival2, aop, oval; try { ival1 = in1pin->get_val(); ival2 = in2pin->get_val(); aop = ctrl; } catch (std::exception & e) { std::cout << "ALU pins not configured: " << e.what() << std::endl; } switch (aop) { case ADD: oval = ival1 + ival2; break; case SUB: oval = ival1 - ival2; break; case COM: oval = ~ival1; break; case AND: oval = ival1 & ival2; break; case OR: oval = ival1 | ival2; break; case EOR: oval = ival1 ^ ival2; break; } try { std::cout << "ALU: " << oval << std::endl; out1pin->set_val(oval); } catch(std::exception e) { std::cout << "ALU out pin not configured" << e.what() << std::endl; } }
#include "editor_scene_importer_gltf.h" #include "io/json.h" #include "math_defs.h" #include "os/file_access.h" #include "os/os.h" #include "scene/3d/camera.h" #include "scene/3d/mesh_instance.h" #include "scene/animation/animation_player.h" #include "scene/resources/surface_tool.h" #include "thirdparty/misc/base64.h" uint32_t EditorSceneImporterGLTF::get_import_flags() const { return IMPORT_SCENE | IMPORT_ANIMATION; } void EditorSceneImporterGLTF::get_extensions(List<String> *r_extensions) const { r_extensions->push_back("gltf"); r_extensions->push_back("glb"); } Error EditorSceneImporterGLTF::_parse_json(const String &p_path, GLTFState &state) { Error err; FileAccessRef f = FileAccess::open(p_path, FileAccess::READ, &err); if (!f) { return err; } Vector<uint8_t> array; array.resize(f->get_len()); f->get_buffer(array.ptrw(), array.size()); String text; text.parse_utf8((const char *)array.ptr(), array.size()); String err_txt; int err_line; Variant v; err = JSON::parse(text, v, err_txt, err_line); if (err != OK) { _err_print_error("", p_path.utf8().get_data(), err_line, err_txt.utf8().get_data(), ERR_HANDLER_SCRIPT); return err; } state.json = v; return OK; } Error EditorSceneImporterGLTF::_parse_glb(const String &p_path, GLTFState &state) { Error err; FileAccessRef f = FileAccess::open(p_path, FileAccess::READ, &err); if (!f) { return err; } uint32_t magic = f->get_32(); ERR_FAIL_COND_V(magic != 0x46546C67, ERR_FILE_UNRECOGNIZED); //glTF f->get_32(); // version f->get_32(); // length uint32_t chunk_length = f->get_32(); uint32_t chunk_type = f->get_32(); ERR_FAIL_COND_V(chunk_type != 0x4E4F534A, ERR_PARSE_ERROR); //JSON Vector<uint8_t> json_data; json_data.resize(chunk_length); uint32_t len = f->get_buffer(json_data.ptrw(), chunk_length); ERR_FAIL_COND_V(len != chunk_length, ERR_FILE_CORRUPT); String text; text.parse_utf8((const char *)json_data.ptr(), json_data.size()); String err_txt; int err_line; Variant v; err = JSON::parse(text, v, err_txt, err_line); if (err != OK) { _err_print_error("", p_path.utf8().get_data(), err_line, err_txt.utf8().get_data(), ERR_HANDLER_SCRIPT); return err; } state.json = v; //data? chunk_length = f->get_32(); chunk_type = f->get_32(); if (f->eof_reached()) { return OK; //all good } ERR_FAIL_COND_V(chunk_type != 0x004E4942, ERR_PARSE_ERROR); //BIN state.glb_data.resize(chunk_length); len = f->get_buffer(state.glb_data.ptrw(), chunk_length); ERR_FAIL_COND_V(len != chunk_length, ERR_FILE_CORRUPT); return OK; } static Vector3 _arr_to_vec3(const Array &p_array) { ERR_FAIL_COND_V(p_array.size() != 3, Vector3()); return Vector3(p_array[0], p_array[1], p_array[2]); } static Quat _arr_to_quat(const Array &p_array) { ERR_FAIL_COND_V(p_array.size() != 4, Quat()); return Quat(p_array[0], p_array[1], p_array[2], p_array[3]); } static Transform _arr_to_xform(const Array &p_array) { ERR_FAIL_COND_V(p_array.size() != 16, Transform()); Transform xform; xform.basis.set_axis(Vector3::AXIS_X, Vector3(p_array[0], p_array[1], p_array[2])); xform.basis.set_axis(Vector3::AXIS_Y, Vector3(p_array[4], p_array[5], p_array[6])); xform.basis.set_axis(Vector3::AXIS_Z, Vector3(p_array[8], p_array[9], p_array[10])); xform.set_origin(Vector3(p_array[12], p_array[13], p_array[14])); return xform; } String EditorSceneImporterGLTF::_gen_unique_name(GLTFState &state, const String &p_name) { int index = 1; String name; while (true) { name = p_name; if (index > 1) { name += " " + itos(index); } if (!state.unique_names.has(name)) { break; } index++; } state.unique_names.insert(name); return name; } Error EditorSceneImporterGLTF::_parse_scenes(GLTFState &state) { ERR_FAIL_COND_V(!state.json.has("scenes"), ERR_FILE_CORRUPT); Array scenes = state.json["scenes"]; for (int i = 0; i < 1; i++) { //only first scene is imported Dictionary s = scenes[i]; ERR_FAIL_COND_V(!s.has("nodes"), ERR_UNAVAILABLE); Array nodes = s["nodes"]; for (int j = 0; j < nodes.size(); j++) { state.root_nodes.push_back(nodes[j]); } if (s.has("name")) { state.scene_name = s["name"]; } } return OK; } Error EditorSceneImporterGLTF::_parse_nodes(GLTFState &state) { ERR_FAIL_COND_V(!state.json.has("nodes"), ERR_FILE_CORRUPT); Array nodes = state.json["nodes"]; for (int i = 0; i < nodes.size(); i++) { GLTFNode *node = memnew(GLTFNode); Dictionary n = nodes[i]; print_line("node " + itos(i) + ": " + String(Variant(n))); if (n.has("name")) { node->name = n["name"]; } if (n.has("camera")) { node->camera = n["camera"]; } if (n.has("mesh")) { node->mesh = n["mesh"]; } if (n.has("skin")) { node->skin = n["skin"]; if (!state.skin_users.has(node->skin)) { state.skin_users[node->skin] = Vector<int>(); } state.skin_users[node->skin].push_back(i); } if (n.has("matrix")) { node->xform = _arr_to_xform(n["matrix"]); } else { if (n.has("translation")) { node->translation = _arr_to_vec3(n["translation"]); } if (n.has("rotation")) { node->rotation = _arr_to_quat(n["rotation"]); } if (n.has("scale")) { node->scale = _arr_to_vec3(n["scale"]); } node->xform.basis = Basis(node->rotation); node->xform.basis.scale(node->scale); node->xform.origin = node->translation; } if (n.has("children")) { Array children = n["children"]; for (int i = 0; i < children.size(); i++) { node->children.push_back(children[i]); } } state.nodes.push_back(node); } //build the hierarchy for (int i = 0; i < state.nodes.size(); i++) { for (int j = 0; j < state.nodes[i]->children.size(); j++) { int child = state.nodes[i]->children[j]; ERR_FAIL_INDEX_V(child, state.nodes.size(), ERR_FILE_CORRUPT); ERR_CONTINUE(state.nodes[child]->parent != -1); //node already has a parent, wtf. state.nodes[child]->parent = i; } } return OK; } static Vector<uint8_t> _parse_base64_uri(const String &uri) { int start = uri.find(","); ERR_FAIL_COND_V(start == -1, Vector<uint8_t>()); CharString substr = uri.right(start + 1).ascii(); int strlen = substr.length(); Vector<uint8_t> buf; buf.resize(strlen / 4 * 3 + 1 + 1); int len = base64_decode((char *)buf.ptr(), (char *)substr.get_data(), strlen); buf.resize(len); return buf; } Error EditorSceneImporterGLTF::_parse_buffers(GLTFState &state, const String &p_base_path) { if (!state.json.has("buffers")) return OK; Array buffers = state.json["buffers"]; for (int i = 0; i < buffers.size(); i++) { if (i == 0 && state.glb_data.size()) { state.buffers.push_back(state.glb_data); } else { Dictionary buffer = buffers[i]; if (buffer.has("uri")) { Vector<uint8_t> buffer_data; String uri = buffer["uri"]; if (uri.findn("data:application/octet-stream;base64") == 0) { //embedded data buffer_data = _parse_base64_uri(uri); } else { uri = p_base_path.plus_file(uri).replace("\\", "/"); //fix for windows buffer_data = FileAccess::get_file_as_array(uri); ERR_FAIL_COND_V(buffer.size() == 0, ERR_PARSE_ERROR); } ERR_FAIL_COND_V(!buffer.has("byteLength"), ERR_PARSE_ERROR); int byteLength = buffer["byteLength"]; ERR_FAIL_COND_V(byteLength < buffer_data.size(), ERR_PARSE_ERROR); state.buffers.push_back(buffer_data); } } } print_line("total buffers: " + itos(state.buffers.size())); return OK; } Error EditorSceneImporterGLTF::_parse_buffer_views(GLTFState &state) { ERR_FAIL_COND_V(!state.json.has("bufferViews"), ERR_FILE_CORRUPT); Array buffers = state.json["bufferViews"]; for (int i = 0; i < buffers.size(); i++) { Dictionary d = buffers[i]; GLTFBufferView buffer_view; ERR_FAIL_COND_V(!d.has("buffer"), ERR_PARSE_ERROR); buffer_view.buffer = d["buffer"]; ERR_FAIL_COND_V(!d.has("byteLength"), ERR_PARSE_ERROR); buffer_view.byte_length = d["byteLength"]; if (d.has("byteOffset")) { buffer_view.byte_offset = d["byteOffset"]; } if (d.has("byteStride")) { buffer_view.byte_stride = d["byteStride"]; } if (d.has("target")) { int target = d["target"]; buffer_view.indices = target == ELEMENT_ARRAY_BUFFER; } state.buffer_views.push_back(buffer_view); } print_line("total buffer views: " + itos(state.buffer_views.size())); return OK; } EditorSceneImporterGLTF::GLTFType EditorSceneImporterGLTF::_get_type_from_str(const String &p_string) { if (p_string == "SCALAR") return TYPE_SCALAR; if (p_string == "VEC2") return TYPE_VEC2; if (p_string == "VEC3") return TYPE_VEC3; if (p_string == "VEC4") return TYPE_VEC4; if (p_string == "MAT2") return TYPE_MAT2; if (p_string == "MAT3") return TYPE_MAT3; if (p_string == "MAT4") return TYPE_MAT4; ERR_FAIL_V(TYPE_SCALAR); } Error EditorSceneImporterGLTF::_parse_accessors(GLTFState &state) { ERR_FAIL_COND_V(!state.json.has("accessors"), ERR_FILE_CORRUPT); Array accessors = state.json["accessors"]; for (int i = 0; i < accessors.size(); i++) { Dictionary d = accessors[i]; GLTFAccessor accessor; ERR_FAIL_COND_V(!d.has("componentType"), ERR_PARSE_ERROR); accessor.component_type = d["componentType"]; ERR_FAIL_COND_V(!d.has("count"), ERR_PARSE_ERROR); accessor.count = d["count"]; ERR_FAIL_COND_V(!d.has("type"), ERR_PARSE_ERROR); accessor.type = _get_type_from_str(d["type"]); if (d.has("bufferView")) { accessor.buffer_view = d["bufferView"]; //optional because it may be sparse... } if (d.has("byteOffset")) { accessor.byte_offset = d["byteOffset"]; } if (d.has("max")) { accessor.max = d["max"]; } if (d.has("min")) { accessor.min = d["min"]; } if (d.has("sparse")) { //eeh.. Dictionary s = d["sparse"]; ERR_FAIL_COND_V(!d.has("count"), ERR_PARSE_ERROR); accessor.sparse_count = d["count"]; ERR_FAIL_COND_V(!d.has("indices"), ERR_PARSE_ERROR); Dictionary si = d["indices"]; ERR_FAIL_COND_V(!si.has("bufferView"), ERR_PARSE_ERROR); accessor.sparse_indices_buffer_view = si["bufferView"]; ERR_FAIL_COND_V(!si.has("componentType"), ERR_PARSE_ERROR); accessor.sparse_indices_component_type = si["componentType"]; if (si.has("byteOffset")) { accessor.sparse_indices_byte_offset = si["byteOffset"]; } ERR_FAIL_COND_V(!d.has("values"), ERR_PARSE_ERROR); Dictionary sv = d["values"]; ERR_FAIL_COND_V(!sv.has("bufferView"), ERR_PARSE_ERROR); accessor.sparse_values_buffer_view = sv["bufferView"]; if (sv.has("byteOffset")) { accessor.sparse_values_byte_offset = sv["byteOffset"]; } } state.accessors.push_back(accessor); } print_line("total accessors: " + itos(state.accessors.size())); return OK; } String EditorSceneImporterGLTF::_get_component_type_name(uint32_t p_component) { switch (p_component) { case COMPONENT_TYPE_BYTE: return "Byte"; case COMPONENT_TYPE_UNSIGNED_BYTE: return "UByte"; case COMPONENT_TYPE_SHORT: return "Short"; case COMPONENT_TYPE_UNSIGNED_SHORT: return "UShort"; case COMPONENT_TYPE_INT: return "Int"; case COMPONENT_TYPE_FLOAT: return "Float"; } return "<Error>"; } String EditorSceneImporterGLTF::_get_type_name(GLTFType p_component) { static const char *names[] = { "float", "vec2", "vec3", "vec4", "mat2", "mat3", "mat4" }; return names[p_component]; } Error EditorSceneImporterGLTF::_decode_buffer_view(GLTFState &state, int p_buffer_view, double *dst, int skip_every, int skip_bytes, int element_size, int count, GLTFType type, int component_count, int component_type, int component_size, bool normalized, int byte_offset, bool for_vertex) { const GLTFBufferView &bv = state.buffer_views[p_buffer_view]; int stride = bv.byte_stride ? bv.byte_stride : element_size; if (for_vertex && stride % 4) { stride += 4 - (stride % 4); //according to spec must be multiple of 4 } ERR_FAIL_INDEX_V(bv.buffer, state.buffers.size(), ERR_PARSE_ERROR); uint32_t offset = bv.byte_offset + byte_offset; Vector<uint8_t> buffer = state.buffers[bv.buffer]; //copy on write, so no performance hit const uint8_t *bufptr = buffer.ptr(); //use to debug //print_line("type " + _get_type_name(type) + " component type: " + _get_component_type_name(component_type) + " stride: " + itos(stride) + " amount " + itos(count)); print_line("accessor offset" + itos(byte_offset) + " view offset: " + itos(bv.byte_offset) + " total buffer len: " + itos(buffer.size()) + " view len " + itos(bv.byte_length)); int buffer_end = (stride * (count - 1)) + element_size; ERR_FAIL_COND_V(buffer_end > bv.byte_length, ERR_PARSE_ERROR); ERR_FAIL_COND_V((int)(offset + buffer_end) > buffer.size(), ERR_PARSE_ERROR); //fill everything as doubles for (int i = 0; i < count; i++) { const uint8_t *src = &bufptr[offset + i * stride]; for (int j = 0; j < component_count; j++) { if (skip_every && j > 0 && (j % skip_every) == 0) { src += skip_bytes; } double d = 0; switch (component_type) { case COMPONENT_TYPE_BYTE: { int8_t b = int8_t(*src); if (normalized) { d = (double(b) / 128.0); } else { d = double(b); } } break; case COMPONENT_TYPE_UNSIGNED_BYTE: { uint8_t b = *src; if (normalized) { d = (double(b) / 255.0); } else { d = double(b); } } break; case COMPONENT_TYPE_SHORT: { int16_t s = *(int16_t *)src; if (normalized) { d = (double(s) / 32768.0); } else { d = double(s); } } break; case COMPONENT_TYPE_UNSIGNED_SHORT: { uint16_t s = *(uint16_t *)src; if (normalized) { d = (double(s) / 65535.0); } else { d = double(s); } } break; case COMPONENT_TYPE_INT: { d = *(int *)src; } break; case COMPONENT_TYPE_FLOAT: { d = *(float *)src; } break; } *dst++ = d; src += component_size; } } return OK; } int EditorSceneImporterGLTF::_get_component_type_size(int component_type) { switch (component_type) { case COMPONENT_TYPE_BYTE: return 1; break; case COMPONENT_TYPE_UNSIGNED_BYTE: return 1; break; case COMPONENT_TYPE_SHORT: return 2; break; case COMPONENT_TYPE_UNSIGNED_SHORT: return 2; break; case COMPONENT_TYPE_INT: return 4; break; case COMPONENT_TYPE_FLOAT: return 4; break; default: { ERR_FAIL_V(0); } } return 0; } Vector<double> EditorSceneImporterGLTF::_decode_accessor(GLTFState &state, int p_accessor, bool p_for_vertex) { //spec, for reference: //https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment ERR_FAIL_INDEX_V(p_accessor, state.accessors.size(), Vector<double>()); const GLTFAccessor &a = state.accessors[p_accessor]; int component_count_for_type[7] = { 1, 2, 3, 4, 4, 9, 16 }; int component_count = component_count_for_type[a.type]; int component_size = _get_component_type_size(a.component_type); ERR_FAIL_COND_V(component_size == 0, Vector<double>()); int element_size = component_count * component_size; int skip_every = 0; int skip_bytes = 0; //special case of alignments, as described in spec switch (a.component_type) { case COMPONENT_TYPE_BYTE: case COMPONENT_TYPE_UNSIGNED_BYTE: { if (a.type == TYPE_MAT2) { skip_every = 2; skip_bytes = 2; element_size = 8; //override for this case } if (a.type == TYPE_MAT3) { skip_every = 3; skip_bytes = 1; element_size = 12; //override for this case } } break; case COMPONENT_TYPE_SHORT: case COMPONENT_TYPE_UNSIGNED_SHORT: { if (a.type == TYPE_MAT3) { skip_every = 6; skip_bytes = 4; element_size = 16; //override for this case } } break; default: {} } Vector<double> dst_buffer; dst_buffer.resize(component_count * a.count); double *dst = dst_buffer.ptrw(); if (a.buffer_view >= 0) { ERR_FAIL_INDEX_V(a.buffer_view, state.buffer_views.size(), Vector<double>()); Error err = _decode_buffer_view(state, a.buffer_view, dst, skip_every, skip_bytes, element_size, a.count, a.type, component_count, a.component_type, component_size, a.normalized, a.byte_offset, p_for_vertex); if (err != OK) return Vector<double>(); } else { //fill with zeros, as bufferview is not defined. for (int i = 0; i < (a.count * component_count); i++) { dst_buffer[i] = 0; } } if (a.sparse_count > 0) { // I could not find any file using this, so this code is so far untested Vector<double> indices; indices.resize(a.sparse_count); int indices_component_size = _get_component_type_size(a.sparse_indices_component_type); Error err = _decode_buffer_view(state, a.sparse_indices_buffer_view, indices.ptrw(), 0, 0, indices_component_size, a.sparse_count, TYPE_SCALAR, 1, a.sparse_indices_component_type, indices_component_size, false, a.sparse_indices_byte_offset, false); if (err != OK) return Vector<double>(); Vector<double> data; data.resize(component_count * a.sparse_count); err = _decode_buffer_view(state, a.sparse_values_buffer_view, data.ptrw(), skip_every, skip_bytes, element_size, a.sparse_count, a.type, component_count, a.component_type, component_size, a.normalized, a.sparse_values_byte_offset, p_for_vertex); if (err != OK) return Vector<double>(); for (int i = 0; i < indices.size(); i++) { int write_offset = int(indices[i]) * component_count; for (int j = 0; j < component_count; j++) { dst[write_offset + j] = data[i * component_count + j]; } } } return dst_buffer; } PoolVector<int> EditorSceneImporterGLTF::_decode_accessor_as_ints(GLTFState &state, int p_accessor, bool p_for_vertex) { Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex); PoolVector<int> ret; if (attribs.size() == 0) return ret; const double *attribs_ptr = attribs.ptr(); int ret_size = attribs.size(); ret.resize(ret_size); { PoolVector<int>::Write w = ret.write(); for (int i = 0; i < ret_size; i++) { w[i] = int(attribs_ptr[i]); } } return ret; } PoolVector<float> EditorSceneImporterGLTF::_decode_accessor_as_floats(GLTFState &state, int p_accessor, bool p_for_vertex) { Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex); PoolVector<float> ret; if (attribs.size() == 0) return ret; const double *attribs_ptr = attribs.ptr(); int ret_size = attribs.size(); ret.resize(ret_size); { PoolVector<float>::Write w = ret.write(); for (int i = 0; i < ret_size; i++) { w[i] = float(attribs_ptr[i]); } } return ret; } PoolVector<Vector2> EditorSceneImporterGLTF::_decode_accessor_as_vec2(GLTFState &state, int p_accessor, bool p_for_vertex) { Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex); PoolVector<Vector2> ret; if (attribs.size() == 0) return ret; ERR_FAIL_COND_V(attribs.size() % 2 != 0, ret); const double *attribs_ptr = attribs.ptr(); int ret_size = attribs.size() / 2; ret.resize(ret_size); { PoolVector<Vector2>::Write w = ret.write(); for (int i = 0; i < ret_size; i++) { w[i] = Vector2(attribs_ptr[i * 2 + 0], attribs_ptr[i * 2 + 1]); } } return ret; } PoolVector<Vector3> EditorSceneImporterGLTF::_decode_accessor_as_vec3(GLTFState &state, int p_accessor, bool p_for_vertex) { Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex); PoolVector<Vector3> ret; if (attribs.size() == 0) return ret; ERR_FAIL_COND_V(attribs.size() % 3 != 0, ret); const double *attribs_ptr = attribs.ptr(); int ret_size = attribs.size() / 3; ret.resize(ret_size); { PoolVector<Vector3>::Write w = ret.write(); for (int i = 0; i < ret_size; i++) { w[i] = Vector3(attribs_ptr[i * 3 + 0], attribs_ptr[i * 3 + 1], attribs_ptr[i * 3 + 2]); } } return ret; } PoolVector<Color> EditorSceneImporterGLTF::_decode_accessor_as_color(GLTFState &state, int p_accessor, bool p_for_vertex) { Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex); PoolVector<Color> ret; if (attribs.size() == 0) return ret; ERR_FAIL_COND_V(attribs.size() % 4 != 0, ret); const double *attribs_ptr = attribs.ptr(); int ret_size = attribs.size() / 4; ret.resize(ret_size); { PoolVector<Color>::Write w = ret.write(); for (int i = 0; i < ret_size; i++) { w[i] = Color(attribs_ptr[i * 4 + 0], attribs_ptr[i * 4 + 1], attribs_ptr[i * 4 + 2], attribs_ptr[i * 4 + 3]); } } return ret; } Vector<Quat> EditorSceneImporterGLTF::_decode_accessor_as_quat(GLTFState &state, int p_accessor, bool p_for_vertex) { Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex); Vector<Quat> ret; if (attribs.size() == 0) return ret; ERR_FAIL_COND_V(attribs.size() % 4 != 0, ret); const double *attribs_ptr = attribs.ptr(); int ret_size = attribs.size() / 4; ret.resize(ret_size); { for (int i = 0; i < ret_size; i++) { ret[i] = Quat(attribs_ptr[i * 4 + 0], attribs_ptr[i * 4 + 1], attribs_ptr[i * 4 + 2], attribs_ptr[i * 4 + 3]); } } return ret; } Vector<Transform2D> EditorSceneImporterGLTF::_decode_accessor_as_xform2d(GLTFState &state, int p_accessor, bool p_for_vertex) { Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex); Vector<Transform2D> ret; if (attribs.size() == 0) return ret; ERR_FAIL_COND_V(attribs.size() % 4 != 0, ret); ret.resize(attribs.size() / 4); for (int i = 0; i < ret.size(); i++) { ret[i][0] = Vector2(attribs[i * 4 + 0], attribs[i * 4 + 1]); ret[i][1] = Vector2(attribs[i * 4 + 2], attribs[i * 4 + 3]); } return ret; } Vector<Basis> EditorSceneImporterGLTF::_decode_accessor_as_basis(GLTFState &state, int p_accessor, bool p_for_vertex) { Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex); Vector<Basis> ret; if (attribs.size() == 0) return ret; ERR_FAIL_COND_V(attribs.size() % 9 != 0, ret); ret.resize(attribs.size() / 9); for (int i = 0; i < ret.size(); i++) { ret[i].set_axis(0, Vector3(attribs[i * 9 + 0], attribs[i * 9 + 1], attribs[i * 9 + 2])); ret[i].set_axis(1, Vector3(attribs[i * 9 + 3], attribs[i * 9 + 4], attribs[i * 9 + 5])); ret[i].set_axis(2, Vector3(attribs[i * 9 + 6], attribs[i * 9 + 7], attribs[i * 9 + 8])); } return ret; } Vector<Transform> EditorSceneImporterGLTF::_decode_accessor_as_xform(GLTFState &state, int p_accessor, bool p_for_vertex) { Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex); Vector<Transform> ret; if (attribs.size() == 0) return ret; ERR_FAIL_COND_V(attribs.size() % 16 != 0, ret); ret.resize(attribs.size() / 16); for (int i = 0; i < ret.size(); i++) { ret[i].basis.set_axis(0, Vector3(attribs[i * 16 + 0], attribs[i * 16 + 1], attribs[i * 16 + 2])); ret[i].basis.set_axis(1, Vector3(attribs[i * 16 + 4], attribs[i * 16 + 5], attribs[i * 16 + 6])); ret[i].basis.set_axis(2, Vector3(attribs[i * 16 + 8], attribs[i * 16 + 9], attribs[i * 16 + 10])); ret[i].set_origin(Vector3(attribs[i * 16 + 12], attribs[i * 16 + 13], attribs[i * 16 + 14])); } return ret; } Error EditorSceneImporterGLTF::_parse_meshes(GLTFState &state) { if (!state.json.has("meshes")) return OK; Array meshes = state.json["meshes"]; for (int i = 0; i < meshes.size(); i++) { print_line("on mesh: " + itos(i)); Dictionary d = meshes[i]; GLTFMesh mesh; mesh.mesh.instance(); ERR_FAIL_COND_V(!d.has("primitives"), ERR_PARSE_ERROR); Array primitives = d["primitives"]; for (int j = 0; j < primitives.size(); j++) { Dictionary p = primitives[j]; Array array; array.resize(Mesh::ARRAY_MAX); ERR_FAIL_COND_V(!p.has("attributes"), ERR_PARSE_ERROR); Dictionary a = p["attributes"]; Mesh::PrimitiveType primitive = Mesh::PRIMITIVE_TRIANGLES; if (p.has("mode")) { int mode = p["mode"]; ERR_FAIL_INDEX_V(mode, 7, ERR_FILE_CORRUPT); static const Mesh::PrimitiveType primitives[7] = { Mesh::PRIMITIVE_POINTS, Mesh::PRIMITIVE_LINES, Mesh::PRIMITIVE_LINE_LOOP, Mesh::PRIMITIVE_LINE_STRIP, Mesh::PRIMITIVE_TRIANGLES, Mesh::PRIMITIVE_TRIANGLE_STRIP, Mesh::PRIMITIVE_TRIANGLE_FAN, }; primitive = primitives[mode]; } if (a.has("POSITION")) { array[Mesh::ARRAY_VERTEX] = _decode_accessor_as_vec3(state, a["POSITION"], true); } if (a.has("NORMAL")) { array[Mesh::ARRAY_NORMAL] = _decode_accessor_as_vec3(state, a["NORMAL"], true); } if (a.has("TANGENT")) { array[Mesh::ARRAY_TANGENT] = _decode_accessor_as_floats(state, a["TANGENT"], true); } if (a.has("TEXCOORD_0")) { array[Mesh::ARRAY_TEX_UV] = _decode_accessor_as_vec2(state, a["TEXCOORD_0"], true); } if (a.has("TEXCOORD_1")) { array[Mesh::ARRAY_TEX_UV2] = _decode_accessor_as_vec2(state, a["TEXCOORD_1"], true); } if (a.has("COLOR_0")) { array[Mesh::ARRAY_COLOR] = _decode_accessor_as_color(state, a["COLOR_0"], true); } if (a.has("JOINTS_0")) { array[Mesh::ARRAY_BONES] = _decode_accessor_as_ints(state, a["JOINTS_0"], true); } if (a.has("WEIGHTS_0")) { PoolVector<float> weights = _decode_accessor_as_floats(state, a["WEIGHTS_0"], true); { //gltf does not seem to normalize the weights for some reason.. int wc = weights.size(); PoolVector<float>::Write w = weights.write(); for (int i = 0; i < wc; i += 4) { float total = 0.0; total += w[i + 0]; total += w[i + 1]; total += w[i + 2]; total += w[i + 3]; if (total > 0.0) { w[i + 0] /= total; w[i + 1] /= total; w[i + 2] /= total; w[i + 3] /= total; } } } array[Mesh::ARRAY_WEIGHTS] = weights; } if (p.has("indices")) { PoolVector<int> indices = _decode_accessor_as_ints(state, p["indices"], false); if (primitive == Mesh::PRIMITIVE_TRIANGLES) { //swap around indices, convert ccw to cw for front face int is = indices.size(); PoolVector<int>::Write w = indices.write(); for (int i = 0; i < is; i += 3) { SWAP(w[i + 1], w[i + 2]); } } array[Mesh::ARRAY_INDEX] = indices; } else if (primitive == Mesh::PRIMITIVE_TRIANGLES) { //generate indices because they need to be swapped for CW/CCW PoolVector<Vector3> vertices = array[Mesh::ARRAY_VERTEX]; ERR_FAIL_COND_V(vertices.size() == 0, ERR_PARSE_ERROR); PoolVector<int> indices; int vs = vertices.size(); indices.resize(vs); { PoolVector<int>::Write w = indices.write(); for (int i = 0; i < vs; i += 3) { w[i] = i; w[i + 1] = i + 2; w[i + 2] = i + 1; } } array[Mesh::ARRAY_INDEX] = indices; } bool generated_tangents = false; Variant erased_indices; if (primitive == Mesh::PRIMITIVE_TRIANGLES && !a.has("TANGENT") && a.has("TEXCOORD_0") && a.has("NORMAL")) { //must generate mikktspace tangents.. ergh.. Ref<SurfaceTool> st; st.instance(); st->create_from_triangle_arrays(array); if (p.has("targets")) { //morph targets should not be reindexed, as array size might differ //removing indices is the best bet here st->deindex(); erased_indices = a[Mesh::ARRAY_INDEX]; a[Mesh::ARRAY_INDEX] = Variant(); } st->generate_tangents(); array = st->commit_to_arrays(); generated_tangents = true; } Array morphs; //blend shapes if (p.has("targets")) { print_line("has targets!"); Array targets = p["targets"]; if (j == 0) { for (int k = 0; k < targets.size(); k++) { mesh.mesh->add_blend_shape(String("morph_") + itos(k)); } } for (int k = 0; k < targets.size(); k++) { Dictionary t = targets[k]; Array array_copy; array_copy.resize(Mesh::ARRAY_MAX); for (int l = 0; l < Mesh::ARRAY_MAX; l++) { array_copy[l] = array[l]; } array_copy[Mesh::ARRAY_INDEX] = Variant(); if (t.has("POSITION")) { array_copy[Mesh::ARRAY_VERTEX] = _decode_accessor_as_vec3(state, t["POSITION"], true); } if (t.has("NORMAL")) { array_copy[Mesh::ARRAY_NORMAL] = _decode_accessor_as_vec3(state, t["NORMAL"], true); } if (t.has("TANGENT")) { PoolVector<Vector3> tangents_v3 = _decode_accessor_as_vec3(state, t["TANGENT"], true); PoolVector<float> tangents_v4; PoolVector<float> src_tangents = array[Mesh::ARRAY_TANGENT]; ERR_FAIL_COND_V(src_tangents.size() == 0, ERR_PARSE_ERROR); { int size4 = src_tangents.size(); tangents_v4.resize(size4); PoolVector<float>::Write w4 = tangents_v4.write(); PoolVector<Vector3>::Read r3 = tangents_v3.read(); PoolVector<float>::Read r4 = src_tangents.read(); for (int l = 0; l < size4 / 4; l++) { w4[l * 4 + 0] = r3[l].x; w4[l * 4 + 1] = r3[l].y; w4[l * 4 + 2] = r3[l].z; w4[l * 4 + 3] = r4[l * 4 + 3]; //copy flip value } } array_copy[Mesh::ARRAY_TANGENT] = tangents_v4; } if (generated_tangents) { Ref<SurfaceTool> st; st.instance(); array_copy[Mesh::ARRAY_INDEX] = erased_indices; //needed for tangent generation, erased by deindex st->create_from_triangle_arrays(array_copy); st->deindex(); st->generate_tangents(); array_copy = st->commit_to_arrays(); } morphs.push_back(array_copy); } } //just add it mesh.mesh->add_surface_from_arrays(primitive, array, morphs); if (p.has("material")) { int material = p["material"]; ERR_FAIL_INDEX_V(material, state.materials.size(), ERR_FILE_CORRUPT); Ref<Material> mat = state.materials[material]; mesh.mesh->surface_set_material(mesh.mesh->get_surface_count() - 1, mat); } } if (d.has("weights")) { Array weights = d["weights"]; ERR_FAIL_COND_V(mesh.mesh->get_blend_shape_count() != weights.size(), ERR_PARSE_ERROR); mesh.blend_weights.resize(weights.size()); for (int j = 0; j < weights.size(); j++) { mesh.blend_weights[j] = weights[j]; } } state.meshes.push_back(mesh); } print_line("total meshes: " + itos(state.meshes.size())); return OK; } Error EditorSceneImporterGLTF::_parse_images(GLTFState &state, const String &p_base_path) { if (!state.json.has("images")) return OK; Array images = state.json["images"]; for (int i = 0; i < images.size(); i++) { Dictionary d = images[i]; String mimetype; if (d.has("mimeType")) { mimetype = d["mimeType"]; } Vector<uint8_t> data; const uint8_t *data_ptr = NULL; int data_size = 0; if (d.has("uri")) { String uri = d["uri"]; if (uri.findn("data:application/octet-stream;base64") == 0) { //embedded data data = _parse_base64_uri(uri); data_ptr = data.ptr(); data_size = data.size(); } else { uri = p_base_path.plus_file(uri).replace("\\", "/"); //fix for windows Ref<Texture> texture = ResourceLoader::load(uri); state.images.push_back(texture); continue; } } if (d.has("bufferView")) { int bvi = d["bufferView"]; ERR_FAIL_INDEX_V(bvi, state.buffer_views.size(), ERR_PARAMETER_RANGE_ERROR); GLTFBufferView &bv = state.buffer_views[bvi]; int bi = bv.buffer; ERR_FAIL_INDEX_V(bi, state.buffers.size(), ERR_PARAMETER_RANGE_ERROR); ERR_FAIL_COND_V(bv.byte_offset + bv.byte_length > state.buffers[bi].size(), ERR_FILE_CORRUPT); data_ptr = &state.buffers[bi][bv.byte_offset]; data_size = bv.byte_length; } ERR_FAIL_COND_V(mimetype == "", ERR_FILE_CORRUPT); if (mimetype.findn("png") != -1) { //is a png Ref<Image> img = Image::_png_mem_loader_func(data_ptr, data_size); ERR_FAIL_COND_V(img.is_null(), ERR_FILE_CORRUPT); Ref<ImageTexture> t; t.instance(); t->create_from_image(img); state.images.push_back(t); continue; } if (mimetype.findn("jpg") != -1) { //is a jpg Ref<Image> img = Image::_jpg_mem_loader_func(data_ptr, data_size); ERR_FAIL_COND_V(img.is_null(), ERR_FILE_CORRUPT); Ref<ImageTexture> t; t.instance(); t->create_from_image(img); state.images.push_back(t); continue; } ERR_FAIL_V(ERR_FILE_CORRUPT); } print_line("total images: " + itos(state.images.size())); return OK; } Error EditorSceneImporterGLTF::_parse_textures(GLTFState &state) { if (!state.json.has("textures")) return OK; Array textures = state.json["textures"]; for (int i = 0; i < textures.size(); i++) { Dictionary d = textures[i]; ERR_FAIL_COND_V(!d.has("source"), ERR_PARSE_ERROR); GLTFTexture t; t.src_image = d["source"]; state.textures.push_back(t); } return OK; } Ref<Texture> EditorSceneImporterGLTF::_get_texture(GLTFState &state, int p_texture) { ERR_FAIL_INDEX_V(p_texture, state.textures.size(), Ref<Texture>()); int image = state.textures[p_texture].src_image; ERR_FAIL_INDEX_V(image, state.images.size(), Ref<Texture>()); return state.images[image]; } Error EditorSceneImporterGLTF::_parse_materials(GLTFState &state) { if (!state.json.has("materials")) return OK; Array materials = state.json["materials"]; for (int i = 0; i < materials.size(); i++) { Dictionary d = materials[i]; Ref<SpatialMaterial> material; material.instance(); if (d.has("name")) { material->set_name(d["name"]); } if (d.has("pbrMetallicRoughness")) { Dictionary mr = d["pbrMetallicRoughness"]; if (mr.has("baseColorFactor")) { Array arr = mr["baseColorFactor"]; ERR_FAIL_COND_V(arr.size() != 4, ERR_PARSE_ERROR); Color c = Color(arr[0], arr[1], arr[2], arr[3]).to_srgb(); material->set_albedo(c); } if (mr.has("baseColorTexture")) { Dictionary bct = mr["baseColorTexture"]; if (bct.has("index")) { material->set_texture(SpatialMaterial::TEXTURE_ALBEDO, _get_texture(state, bct["index"])); } if (!mr.has("baseColorFactor")) { material->set_albedo(Color(1, 1, 1)); } } if (mr.has("metallicFactor")) { material->set_metallic(mr["metallicFactor"]); } if (mr.has("roughnessFactor")) { material->set_roughness(mr["roughnessFactor"]); } if (mr.has("metallicRoughnessTexture")) { Dictionary bct = mr["metallicRoughnessTexture"]; if (bct.has("index")) { Ref<Texture> t = _get_texture(state, bct["index"]); material->set_texture(SpatialMaterial::TEXTURE_METALLIC, t); material->set_metallic_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_BLUE); material->set_texture(SpatialMaterial::TEXTURE_ROUGHNESS, t); material->set_roughness_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_GREEN); if (!mr.has("metallicFactor")) { material->set_metallic(1); } if (!mr.has("roughnessFactor")) { material->set_roughness(1); } } } } if (d.has("normalTexture")) { Dictionary bct = d["normalTexture"]; if (bct.has("index")) { material->set_texture(SpatialMaterial::TEXTURE_NORMAL, _get_texture(state, bct["index"])); material->set_feature(SpatialMaterial::FEATURE_NORMAL_MAPPING, true); } if (bct.has("scale")) { material->set_normal_scale(bct["scale"]); } } if (d.has("occlusionTexture")) { Dictionary bct = d["occlusionTexture"]; if (bct.has("index")) { material->set_texture(SpatialMaterial::TEXTURE_AMBIENT_OCCLUSION, _get_texture(state, bct["index"])); material->set_ao_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_RED); material->set_feature(SpatialMaterial::FEATURE_AMBIENT_OCCLUSION, true); } } if (d.has("emissiveFactor")) { Array arr = d["emissiveFactor"]; ERR_FAIL_COND_V(arr.size() != 3, ERR_PARSE_ERROR); Color c = Color(arr[0], arr[1], arr[2]).to_srgb(); material->set_feature(SpatialMaterial::FEATURE_EMISSION, true); material->set_emission(c); } if (d.has("emissiveTexture")) { Dictionary bct = d["emissiveTexture"]; if (bct.has("index")) { material->set_texture(SpatialMaterial::TEXTURE_EMISSION, _get_texture(state, bct["index"])); material->set_feature(SpatialMaterial::FEATURE_EMISSION, true); material->set_emission(Color(0, 0, 0)); } } if (d.has("doubleSided")) { bool ds = d["doubleSided"]; if (ds) { material->set_cull_mode(SpatialMaterial::CULL_DISABLED); } } if (d.has("alphaMode")) { String am = d["alphaMode"]; if (am != "OPAQUE") { material->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true); } } state.materials.push_back(material); } print_line("total materials: " + itos(state.materials.size())); return OK; } Error EditorSceneImporterGLTF::_parse_skins(GLTFState &state) { if (!state.json.has("skins")) return OK; Array skins = state.json["skins"]; for (int i = 0; i < skins.size(); i++) { Dictionary d = skins[i]; GLTFSkin skin; ERR_FAIL_COND_V(!d.has("joints"), ERR_PARSE_ERROR); Array joints = d["joints"]; Vector<Transform> bind_matrices; if (d.has("inverseBindMatrices")) { bind_matrices = _decode_accessor_as_xform(state, d["inverseBindMatrices"], false); ERR_FAIL_COND_V(bind_matrices.size() != joints.size(), ERR_PARSE_ERROR); } for (int j = 0; j < joints.size(); j++) { int index = joints[j]; ERR_FAIL_INDEX_V(index, state.nodes.size(), ERR_PARSE_ERROR); state.nodes[index]->joint_skin = state.skins.size(); state.nodes[index]->joint_bone = j; GLTFSkin::Bone bone; bone.node = index; if (bind_matrices.size()) { bone.inverse_bind = bind_matrices[j]; } skin.bones.push_back(bone); } print_line("skin has skeleton? " + itos(d.has("skeleton"))); if (d.has("skeleton")) { int skeleton = d["skeleton"]; ERR_FAIL_INDEX_V(skeleton, state.nodes.size(), ERR_PARSE_ERROR); state.nodes[skeleton]->skeleton_skin = state.skins.size(); print_line("setting skeleton skin to" + itos(skeleton)); skin.skeleton = skeleton; } if (d.has("name")) { skin.name = d["name"]; } //locate the right place to put a Skeleton node if (state.skin_users.has(i)) { Vector<int> users = state.skin_users[i]; int skin_node = -1; for (int j = 0; j < users.size(); j++) { int user = state.nodes[users[j]]->parent; //always go from parent if (j == 0) { skin_node = user; } else if (skin_node != -1) { bool found = false; while (skin_node >= 0) { int cuser = user; while (cuser != -1) { if (cuser == skin_node) { found = true; break; } cuser = state.nodes[skin_node]->parent; } if (found) break; skin_node = state.nodes[skin_node]->parent; } if (!found) { skin_node = -1; //just leave where it is } //find a common parent } } if (skin_node != -1) { for (int j = 0; j < users.size(); j++) { state.nodes[users[j]]->child_of_skeleton = i; } state.nodes[skin_node]->skeleton_children.push_back(i); } } state.skins.push_back(skin); } print_line("total skins: " + itos(state.skins.size())); //now return OK; } Error EditorSceneImporterGLTF::_parse_cameras(GLTFState &state) { if (!state.json.has("cameras")) return OK; Array cameras = state.json["cameras"]; for (int i = 0; i < cameras.size(); i++) { Dictionary d = cameras[i]; GLTFCamera camera; ERR_FAIL_COND_V(!d.has("type"), ERR_PARSE_ERROR); String type = d["type"]; if (type == "orthographic") { camera.perspective = false; if (d.has("orthographic")) { Dictionary og = d["orthographic"]; camera.fov_size = og["ymag"]; camera.zfar = og["zfar"]; camera.znear = og["znear"]; } else { camera.fov_size = 10; } } else if (type == "perspective") { camera.perspective = true; if (d.has("perspective")) { Dictionary ppt = d["perspective"]; // GLTF spec is in radians, Godot's camera is in degrees. camera.fov_size = (double)ppt["yfov"] * 180.0 / Math_PI; camera.zfar = ppt["zfar"]; camera.znear = ppt["znear"]; } else { camera.fov_size = 10; } } else { ERR_EXPLAIN("Camera should be in 'orthographic' or 'perspective'"); ERR_FAIL_V(ERR_PARSE_ERROR); } state.cameras.push_back(camera); } print_line("total cameras: " + itos(state.cameras.size())); return OK; } Error EditorSceneImporterGLTF::_parse_animations(GLTFState &state) { if (!state.json.has("animations")) return OK; Array animations = state.json["animations"]; for (int i = 0; i < animations.size(); i++) { Dictionary d = animations[i]; GLTFAnimation animation; if (!d.has("channels") || !d.has("samplers")) continue; Array channels = d["channels"]; Array samplers = d["samplers"]; if (d.has("name")) { animation.name = d["name"]; } for (int j = 0; j < channels.size(); j++) { Dictionary c = channels[j]; if (!c.has("target")) continue; Dictionary t = c["target"]; if (!t.has("node") || !t.has("path")) { continue; } ERR_FAIL_COND_V(!c.has("sampler"), ERR_PARSE_ERROR); int sampler = c["sampler"]; ERR_FAIL_INDEX_V(sampler, samplers.size(), ERR_PARSE_ERROR); int node = t["node"]; String path = t["path"]; ERR_FAIL_INDEX_V(node, state.nodes.size(), ERR_PARSE_ERROR); GLTFAnimation::Track *track = NULL; if (!animation.tracks.has(node)) { animation.tracks[node] = GLTFAnimation::Track(); } track = &animation.tracks[node]; Dictionary s = samplers[sampler]; ERR_FAIL_COND_V(!s.has("input"), ERR_PARSE_ERROR); ERR_FAIL_COND_V(!s.has("output"), ERR_PARSE_ERROR); int input = s["input"]; int output = s["output"]; GLTFAnimation::Interpolation interp = GLTFAnimation::INTERP_LINEAR; if (s.has("interpolation")) { String in = s["interpolation"]; if (in == "STEP") { interp = GLTFAnimation::INTERP_STEP; } else if (in == "LINEAR") { interp = GLTFAnimation::INTERP_LINEAR; } else if (in == "CATMULLROMSPLINE") { interp = GLTFAnimation::INTERP_CATMULLROMSPLINE; } else if (in == "CUBICSPLINE") { interp = GLTFAnimation::INTERP_CUBIC_SPLINE; } } print_line("path: " + path); PoolVector<float> times = _decode_accessor_as_floats(state, input, false); if (path == "translation") { PoolVector<Vector3> translations = _decode_accessor_as_vec3(state, output, false); track->translation_track.interpolation = interp; track->translation_track.times = Variant(times); //convert via variant track->translation_track.values = Variant(translations); //convert via variant } else if (path == "rotation") { Vector<Quat> rotations = _decode_accessor_as_quat(state, output, false); track->rotation_track.interpolation = interp; track->rotation_track.times = Variant(times); //convert via variant track->rotation_track.values = rotations; //convert via variant } else if (path == "scale") { PoolVector<Vector3> scales = _decode_accessor_as_vec3(state, output, false); track->scale_track.interpolation = interp; track->scale_track.times = Variant(times); //convert via variant track->scale_track.values = Variant(scales); //convert via variant } else if (path == "weights") { PoolVector<float> weights = _decode_accessor_as_floats(state, output, false); ERR_FAIL_INDEX_V(state.nodes[node]->mesh, state.meshes.size(), ERR_PARSE_ERROR); GLTFMesh *mesh = &state.meshes[state.nodes[node]->mesh]; ERR_FAIL_COND_V(mesh->blend_weights.size() == 0, ERR_PARSE_ERROR); int wc = mesh->blend_weights.size(); track->weight_tracks.resize(wc); int wlen = weights.size() / wc; PoolVector<float>::Read r = weights.read(); for (int k = 0; k < wc; k++) { //separate tracks, having them together is not such a good idea GLTFAnimation::Channel<float> cf; cf.interpolation = interp; cf.times = Variant(times); Vector<float> wdata; wdata.resize(wlen); for (int l = 0; l < wlen; l++) { wdata[l] = r[l * wc + k]; } cf.values = wdata; track->weight_tracks[k] = cf; } } else { WARN_PRINTS("Invalid path: " + path); } } state.animations.push_back(animation); } print_line("total animations: " + itos(state.animations.size())); return OK; } void EditorSceneImporterGLTF::_assign_scene_names(GLTFState &state) { for (int i = 0; i < state.nodes.size(); i++) { GLTFNode *n = state.nodes[i]; if (n->name == "") { if (n->mesh >= 0) { n->name = "Mesh"; } else if (n->joint_skin >= 0) { n->name = "Bone"; } else { n->name = "Node"; } } n->name = _gen_unique_name(state, n->name); } } void EditorSceneImporterGLTF::_generate_node(GLTFState &state, int p_node, Node *p_parent, Node *p_owner, Vector<Skeleton *> &skeletons) { ERR_FAIL_INDEX(p_node, state.nodes.size()); GLTFNode *n = state.nodes[p_node]; Spatial *node; if (n->mesh >= 0) { ERR_FAIL_INDEX(n->mesh, state.meshes.size()); MeshInstance *mi = memnew(MeshInstance); const GLTFMesh &mesh = state.meshes[n->mesh]; mi->set_mesh(mesh.mesh); for (int i = 0; i < mesh.blend_weights.size(); i++) { mi->set("blend_shapes/" + mesh.mesh->get_blend_shape_name(i), mesh.blend_weights[i]); } node = mi; } else if (n->camera >= 0) { ERR_FAIL_INDEX(n->camera, state.cameras.size()); Camera *camera = memnew(Camera); const GLTFCamera &c = state.cameras[n->camera]; if (c.perspective) { camera->set_perspective(c.fov_size, c.znear, c.znear); } else { camera->set_orthogonal(c.fov_size, c.znear, c.znear); } node = camera; } else { node = memnew(Spatial); } node->set_name(n->name); if (n->child_of_skeleton >= 0) { //move skeleton around and place it on node, as the node _is_ a skeleton. Skeleton *s = skeletons[n->child_of_skeleton]; p_parent = s; } p_parent->add_child(node); node->set_owner(p_owner); node->set_transform(n->xform); n->godot_node = node; for (int i = 0; i < n->skeleton_children.size(); i++) { Skeleton *s = skeletons[n->skeleton_children[i]]; s->get_parent()->remove_child(s); node->add_child(s); s->set_owner(p_owner); } for (int i = 0; i < n->children.size(); i++) { if (state.nodes[n->children[i]]->joint_skin >= 0) { _generate_bone(state, n->children[i], skeletons, -1); } else { _generate_node(state, n->children[i], node, p_owner, skeletons); } } } void EditorSceneImporterGLTF::_generate_bone(GLTFState &state, int p_node, Vector<Skeleton *> &skeletons, int p_parent_bone) { ERR_FAIL_INDEX(p_node, state.nodes.size()); GLTFNode *n = state.nodes[p_node]; ERR_FAIL_COND(n->joint_skin < 0); int bone_index = skeletons[n->joint_skin]->get_bone_count(); skeletons[n->joint_skin]->add_bone(n->name); if (p_parent_bone >= 0) { skeletons[n->joint_skin]->set_bone_parent(bone_index, p_parent_bone); } skeletons[n->joint_skin]->set_bone_rest(bone_index, state.skins[n->joint_skin].bones[n->joint_bone].inverse_bind.affine_inverse()); n->godot_node = skeletons[n->joint_skin]; n->godot_bone_index = bone_index; for (int i = 0; i < n->children.size(); i++) { ERR_CONTINUE(state.nodes[n->children[i]]->joint_skin < 0); _generate_bone(state, n->children[i], skeletons, bone_index); } } template <class T> struct EditorSceneImporterGLTFInterpolate { T lerp(const T &a, const T &b, float c) const { return a + (b - a) * c; } T catmull_rom(const T &p0, const T &p1, const T &p2, const T &p3, float t) { float t2 = t * t; float t3 = t2 * t; return 0.5f * ((2.0f * p1) + (-p0 + p2) * t + (2.0f * p0 - 5.0f * p1 + 4 * p2 - p3) * t2 + (-p0 + 3.0f * p1 - 3.0f * p2 + p3) * t3); } T bezier(T start, T control_1, T control_2, T end, float t) { /* Formula from Wikipedia article on Bezier curves. */ real_t omt = (1.0 - t); real_t omt2 = omt * omt; real_t omt3 = omt2 * omt; real_t t2 = t * t; real_t t3 = t2 * t; return start * omt3 + control_1 * omt2 * t * 3.0 + control_2 * omt * t2 * 3.0 + end * t3; } }; //thank you for existing, partial specialization template <> struct EditorSceneImporterGLTFInterpolate<Quat> { Quat lerp(const Quat &a, const Quat &b, float c) const { return a.slerp(b, c); } Quat catmull_rom(const Quat &p0, const Quat &p1, const Quat &p2, const Quat &p3, float c) { return p1.slerp(p2, c); } Quat bezier(Quat start, Quat control_1, Quat control_2, Quat end, float t) { return start.slerp(end, t); } }; template <class T> T EditorSceneImporterGLTF::_interpolate_track(const Vector<float> &p_times, const Vector<T> &p_values, float p_time, GLTFAnimation::Interpolation p_interp) { //could use binary search, worth it? int idx = -1; for (int i = 0; i < p_times.size(); i++) { if (p_times[i] > p_time) break; idx++; } EditorSceneImporterGLTFInterpolate<T> interp; switch (p_interp) { case GLTFAnimation::INTERP_LINEAR: { if (idx == -1) { return p_values[0]; } else if (idx >= p_times.size() - 1) { return p_values[p_times.size() - 1]; } float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]); return interp.lerp(p_values[idx], p_values[idx + 1], c); } break; case GLTFAnimation::INTERP_STEP: { if (idx == -1) { return p_values[0]; } else if (idx >= p_times.size() - 1) { return p_values[p_times.size() - 1]; } return p_values[idx]; } break; case GLTFAnimation::INTERP_CATMULLROMSPLINE: { if (idx == -1) { return p_values[1]; } else if (idx >= p_times.size() - 1) { return p_values[1 + p_times.size() - 1]; } float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]); return interp.catmull_rom(p_values[idx - 1], p_values[idx], p_values[idx + 1], p_values[idx + 3], c); } break; case GLTFAnimation::INTERP_CUBIC_SPLINE: { if (idx == -1) { return p_values[1]; } else if (idx >= p_times.size() - 1) { return p_values[(p_times.size() - 1) * 3 + 1]; } float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]); T from = p_values[idx * 3 + 1]; T c1 = from + p_values[idx * 3 + 0]; T to = p_values[idx * 3 + 3]; T c2 = to + p_values[idx * 3 + 2]; return interp.bezier(from, c1, c2, to, c); } break; } ERR_FAIL_V(p_values[0]); } void EditorSceneImporterGLTF::_import_animation(GLTFState &state, AnimationPlayer *ap, int index, int bake_fps, Vector<Skeleton *> skeletons) { const GLTFAnimation &anim = state.animations[index]; String name = anim.name; if (name == "") { name = _gen_unique_name(state, "Animation"); } Ref<Animation> animation; animation.instance(); animation->set_name(name); for (Map<int, GLTFAnimation::Track>::Element *E = anim.tracks.front(); E; E = E->next()) { const GLTFAnimation::Track &track = E->get(); //need to find the path NodePath node_path; GLTFNode *node = state.nodes[E->key()]; ERR_CONTINUE(!node->godot_node); if (node->godot_bone_index >= 0) { Skeleton *sk = (Skeleton *)node->godot_node; String path = ap->get_parent()->get_path_to(sk); String bone = sk->get_bone_name(node->godot_bone_index); node_path = path + ":" + bone; } else { node_path = ap->get_parent()->get_path_to(node->godot_node); } float length = 0; for (int i = 0; i < track.rotation_track.times.size(); i++) { length = MAX(length, track.rotation_track.times[i]); } for (int i = 0; i < track.translation_track.times.size(); i++) { length = MAX(length, track.translation_track.times[i]); } for (int i = 0; i < track.scale_track.times.size(); i++) { length = MAX(length, track.scale_track.times[i]); } for (int i = 0; i < track.weight_tracks.size(); i++) { for (int j = 0; j < track.weight_tracks[i].times.size(); j++) { length = MAX(length, track.weight_tracks[i].times[j]); } } animation->set_length(length); if (track.rotation_track.values.size() || track.translation_track.values.size() || track.scale_track.values.size()) { //make transform track int track_idx = animation->get_track_count(); animation->add_track(Animation::TYPE_TRANSFORM); animation->track_set_path(track_idx, node_path); //first determine animation length float increment = 1.0 / float(bake_fps); float time = 0.0; Vector3 base_pos; Quat base_rot; Vector3 base_scale = Vector3(1, 1, 1); if (!track.rotation_track.values.size()) { base_rot = state.nodes[E->key()]->rotation; } if (!track.translation_track.values.size()) { base_pos = state.nodes[E->key()]->translation; } if (!track.scale_track.values.size()) { base_scale = state.nodes[E->key()]->scale; } bool last = false; while (true) { Vector3 pos = base_pos; Quat rot = base_rot; Vector3 scale = base_scale; if (track.translation_track.times.size()) { pos = _interpolate_track<Vector3>(track.translation_track.times, track.translation_track.values, time, track.translation_track.interpolation); } if (track.rotation_track.times.size()) { rot = _interpolate_track<Quat>(track.rotation_track.times, track.rotation_track.values, time, track.rotation_track.interpolation); } if (track.scale_track.times.size()) { scale = _interpolate_track<Vector3>(track.scale_track.times, track.scale_track.values, time, track.scale_track.interpolation); } if (node->godot_bone_index >= 0) { Transform xform; xform.basis = Basis(rot); xform.basis.scale(scale); xform.origin = pos; Skeleton *skeleton = skeletons[node->joint_skin]; int bone = node->godot_bone_index; xform = skeleton->get_bone_rest(bone).affine_inverse() * xform; rot = xform.basis; rot.normalize(); scale = xform.basis.get_scale(); pos = xform.origin; } animation->transform_track_insert_key(track_idx, time, pos, rot, scale); if (last) { break; } time += increment; if (time >= length) { last = true; time = length; } } } for (int i = 0; i < track.weight_tracks.size(); i++) { ERR_CONTINUE(node->mesh < 0 || node->mesh >= state.meshes.size()); const GLTFMesh &mesh = state.meshes[node->mesh]; String prop = "blend_shapes/" + mesh.mesh->get_blend_shape_name(i); node_path = String(node_path) + ":" + prop; int track_idx = animation->get_track_count(); animation->add_track(Animation::TYPE_VALUE); animation->track_set_path(track_idx, node_path); if (track.weight_tracks[i].interpolation <= GLTFAnimation::INTERP_STEP) { animation->track_set_interpolation_type(track_idx, track.weight_tracks[i].interpolation == GLTFAnimation::INTERP_STEP ? Animation::INTERPOLATION_NEAREST : Animation::INTERPOLATION_NEAREST); for (int j = 0; j < track.weight_tracks[i].times.size(); j++) { float t = track.weight_tracks[i].times[j]; float w = track.weight_tracks[i].values[j]; animation->track_insert_key(track_idx, t, w); } } else { //must bake, apologies. float increment = 1.0 / float(bake_fps); float time = 0.0; bool last = false; while (true) { _interpolate_track<float>(track.weight_tracks[i].times, track.weight_tracks[i].values, time, track.weight_tracks[i].interpolation); if (last) { break; } time += increment; if (time >= length) { last = true; time = length; } } } } } ap->add_animation(name, animation); } Spatial *EditorSceneImporterGLTF::_generate_scene(GLTFState &state, int p_bake_fps) { Spatial *root = memnew(Spatial); root->set_name(state.scene_name); //generate skeletons Vector<Skeleton *> skeletons; for (int i = 0; i < state.skins.size(); i++) { Skeleton *s = memnew(Skeleton); String name = state.skins[i].name; if (name == "") { name = _gen_unique_name(state, "Skeleton"); } s->set_name(name); root->add_child(s); s->set_owner(root); skeletons.push_back(s); } for (int i = 0; i < state.root_nodes.size(); i++) { if (state.nodes[state.root_nodes[i]]->joint_skin >= 0) { _generate_bone(state, state.root_nodes[i], skeletons, -1); } else { _generate_node(state, state.root_nodes[i], root, root, skeletons); } } for (int i = 0; i < skeletons.size(); i++) { skeletons[i]->localize_rests(); } if (state.animations.size()) { AnimationPlayer *ap = memnew(AnimationPlayer); ap->set_name("AnimationPlayer"); root->add_child(ap); ap->set_owner(root); for (int i = 0; i < state.animations.size(); i++) { _import_animation(state, ap, i, p_bake_fps, skeletons); } } return root; } Node *EditorSceneImporterGLTF::import_scene(const String &p_path, uint32_t p_flags, int p_bake_fps, List<String> *r_missing_deps, Error *r_err) { GLTFState state; if (p_path.to_lower().ends_with("glb")) { //binary file //text file Error err = _parse_glb(p_path, state); if (err) return NULL; } else { //text file Error err = _parse_json(p_path, state); if (err) return NULL; } ERR_FAIL_COND_V(!state.json.has("asset"), NULL); Dictionary asset = state.json["asset"]; ERR_FAIL_COND_V(!asset.has("version"), NULL); String version = asset["version"]; state.major_version = version.get_slice(".", 0).to_int(); state.minor_version = version.get_slice(".", 1).to_int(); /* STEP 0 PARSE SCENE */ Error err = _parse_scenes(state); if (err != OK) return NULL; /* STEP 1 PARSE NODES */ err = _parse_nodes(state); if (err != OK) return NULL; /* STEP 2 PARSE BUFFERS */ err = _parse_buffers(state, p_path.get_base_dir()); if (err != OK) return NULL; /* STEP 3 PARSE BUFFER VIEWS */ err = _parse_buffer_views(state); if (err != OK) return NULL; /* STEP 4 PARSE ACCESSORS */ err = _parse_accessors(state); if (err != OK) return NULL; /* STEP 5 PARSE IMAGES */ err = _parse_images(state, p_path.get_base_dir()); if (err != OK) return NULL; /* STEP 6 PARSE TEXTURES */ err = _parse_textures(state); if (err != OK) return NULL; /* STEP 7 PARSE TEXTURES */ err = _parse_materials(state); if (err != OK) return NULL; /* STEP 8 PARSE MESHES (we have enough info now) */ err = _parse_meshes(state); if (err != OK) return NULL; /* STEP 9 PARSE SKINS */ err = _parse_skins(state); if (err != OK) return NULL; /* STEP 10 PARSE CAMERAS */ err = _parse_cameras(state); if (err != OK) return NULL; /* STEP 11 PARSE ANIMATIONS */ err = _parse_animations(state); if (err != OK) return NULL; /* STEP 12 ASSIGN SCENE NAMES */ _assign_scene_names(state); /* STEP 13 MAKE SCENE! */ Spatial *scene = _generate_scene(state, p_bake_fps); return scene; } Ref<Animation> EditorSceneImporterGLTF::import_animation(const String &p_path, uint32_t p_flags) { return Ref<Animation>(); } EditorSceneImporterGLTF::EditorSceneImporterGLTF() { }
#include <ftdi.h> #include "ftdi_context_wrapper.h" #include <node.h> #include <node_buffer.h> #include <node_object_wrap.h> #include <v8.h> using namespace v8; void create_context(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); FtdiContextWrapper::NewInstance(args); } void ftdi_usb_open_desc(const v8::FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); FtdiContextWrapper* ctx = node::ObjectWrap::Unwrap<FtdiContextWrapper>( args[0]->ToObject()); int vendor = args[1]->NumberValue(); int product = args[2]->NumberValue(); char *description = NULL; char *serial = NULL; String::Utf8Value d(args[3]->ToString()); if (args[3]->IsString()) { description = *d; } String::Utf8Value s(args[4]->ToString()); if (args[4]->IsString()) { serial = *s; } int ret = ftdi_usb_open_desc(&ctx->_ftdic, vendor, product, description, serial); args.GetReturnValue().Set(ret); } void ftdi_set_bitmode(const v8::FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); FtdiContextWrapper* ctx = node::ObjectWrap::Unwrap<FtdiContextWrapper>( args[0]->ToObject()); int mask = args[1]->NumberValue(); int mode = args[2]->NumberValue(); int ret = ftdi_set_bitmode(&ctx->_ftdic, mask, mode); args.GetReturnValue().Set(ret); } void ftdi_set_baudrate(const v8::FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); FtdiContextWrapper* ctx = node::ObjectWrap::Unwrap<FtdiContextWrapper>( args[0]->ToObject()); int baudrate = args[1]->NumberValue(); int ret = ftdi_set_baudrate(&ctx->_ftdic, baudrate); args.GetReturnValue().Set(ret); } void ftdi_get_error_string(const v8::FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); FtdiContextWrapper* ctx = node::ObjectWrap::Unwrap<FtdiContextWrapper>( args[0]->ToObject()); const char* ret = ftdi_get_error_string(&ctx->_ftdic); args.GetReturnValue().Set(String::NewFromUtf8(isolate, ret)); } void ftdi_read_data(const v8::FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); FtdiContextWrapper* ctx = node::ObjectWrap::Unwrap<FtdiContextWrapper>( args[0]->ToObject()); unsigned char* buf = (unsigned char*) node::Buffer::Data(args[1]); size_t len = node::Buffer::Length(args[1]); int size = (int) len; int ret = ftdi_read_data(&ctx->_ftdic, buf, size); args.GetReturnValue().Set(ret); } void ftdi_write_data(const v8::FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); FtdiContextWrapper* ctx = node::ObjectWrap::Unwrap<FtdiContextWrapper>( args[0]->ToObject()); unsigned char* buf = (unsigned char*) node::Buffer::Data(args[1]); int size = args[2]->NumberValue(); int ret = ftdi_write_data(&ctx->_ftdic, buf, size); args.GetReturnValue().Set(ret); } void ftdi_usb_purge_tx_buffer(const v8::FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); FtdiContextWrapper* ctx = node::ObjectWrap::Unwrap<FtdiContextWrapper>( args[0]->ToObject()); int ret = ftdi_usb_purge_tx_buffer(&ctx->_ftdic); args.GetReturnValue().Set(ret); } void InitAll(Handle<Object> exports) { FtdiContextWrapper::Init(exports); NODE_SET_METHOD(exports, "create_context", create_context); NODE_SET_METHOD(exports, "ftdi_usb_open_desc", ftdi_usb_open_desc); NODE_SET_METHOD(exports, "ftdi_set_bitmode", ftdi_set_bitmode); NODE_SET_METHOD(exports, "ftdi_set_baudrate", ftdi_set_baudrate); NODE_SET_METHOD(exports, "ftdi_get_error_string", ftdi_get_error_string); NODE_SET_METHOD(exports, "ftdi_read_data", ftdi_read_data); NODE_SET_METHOD(exports, "ftdi_write_data", ftdi_write_data); NODE_SET_METHOD(exports, "ftdi_usb_purge_tx_buffer", ftdi_usb_purge_tx_buffer); } NODE_MODULE(libftdi, InitAll)
#include "transactionrecord.h" #include "wallet.h" #include "base58.h" /* Return positive answer if transaction should be shown in list. */ bool TransactionRecord::showTransaction(const CWalletTx &wtx) { if (wtx.IsCoinBase()) { // Ensures we show generated coins / mined transactions at depth 1 if (!wtx.IsInMainChain()) { return false; } } return true; } /* * Decompose CWallet transaction to model transaction records. */ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx) { QList<TransactionRecord> parts; int64 nTime = wtx.GetTxTime(); int64 nCredit = wtx.GetCredit(true); int64 nDebit = wtx.GetDebit(); int64 nNet = nCredit - nDebit; uint256 hash = wtx.GetHash(); std::map<std::string, std::string> mapValue = wtx.mapValue; if (nNet > 0 || wtx.IsCoinBase()) { // // Credit // BOOST_FOREACH(const CTxOut& txout, wtx.vout) { if(wallet->IsMine(txout)) { TransactionRecord sub(hash, nTime); CTxDestination address; sub.idx = parts.size(); // sequence number sub.credit = txout.nValue; if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*wallet, address)) { // Received by BITDOOK Address sub.type = TransactionRecord::RecvWithAddress; sub.address = CBitcoinAddress(address).ToString(); } else { // Received by IP connection (deprecated features), or a multisignature or other non-simple transaction sub.type = TransactionRecord::RecvFromOther; sub.address = mapValue["from"]; } if (wtx.IsCoinBase()) { // Generated sub.type = TransactionRecord::Generated; } parts.append(sub); } } } else { bool fAllFromMe = true; BOOST_FOREACH(const CTxIn& txin, wtx.vin) fAllFromMe = fAllFromMe && wallet->IsMine(txin); bool fAllToMe = true; BOOST_FOREACH(const CTxOut& txout, wtx.vout) fAllToMe = fAllToMe && wallet->IsMine(txout); if (fAllFromMe && fAllToMe) { // Payment to self int64 nChange = wtx.GetChange(); parts.append(TransactionRecord(hash, nTime, TransactionRecord::SendToSelf, "", -(nDebit - nChange), nCredit - nChange)); } else if (fAllFromMe) { // // Debit // int64 nTxFee = nDebit - GetValueOut(wtx); for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++) { const CTxOut& txout = wtx.vout[nOut]; TransactionRecord sub(hash, nTime); sub.idx = parts.size(); if(wallet->IsMine(txout)) { // Ignore parts sent to self, as this is usually the change // from a transaction sent back to our own address. continue; } CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address)) { // Sent to BITDOOK Address sub.type = TransactionRecord::SendToAddress; sub.address = CBitcoinAddress(address).ToString(); } else { // Sent to IP, or other non-address transaction like OP_EVAL sub.type = TransactionRecord::SendToOther; sub.address = mapValue["to"]; } int64 nValue = txout.nValue; /* Add fee to first output */ if (nTxFee > 0) { nValue += nTxFee; nTxFee = 0; } sub.debit = -nValue; parts.append(sub); } } else { // // Mixed debit transaction, can't break down payees // parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, "", nNet, 0)); } } return parts; } void TransactionRecord::updateStatus(const CWalletTx &wtx) { // Determine transaction status // Find the block the tx is in CBlockIndex* pindex = NULL; std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(wtx.hashBlock); if (mi != mapBlockIndex.end()) pindex = (*mi).second; // Sort order, unrecorded transactions sort to the top status.sortKey = strprintf("%010d-%01d-%010u-%03d", (pindex ? pindex->nHeight : std::numeric_limits<int>::max()), (wtx.IsCoinBase() ? 1 : 0), wtx.nTimeReceived, idx); status.confirmed = wtx.IsConfirmed(); status.depth = wtx.GetDepthInMainChain(); status.cur_num_blocks = nBestHeight; if (!IsFinalTx(wtx)) { if (wtx.nLockTime < LOCKTIME_THRESHOLD) { status.status = TransactionStatus::OpenUntilBlock; status.open_for = wtx.nLockTime - nBestHeight + 1; } else { status.status = TransactionStatus::OpenUntilDate; status.open_for = wtx.nLockTime; } } else { if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0) { status.status = TransactionStatus::Offline; } else if (status.depth < NumConfirmations) { status.status = TransactionStatus::Unconfirmed; } else { status.status = TransactionStatus::HaveConfirmations; } } // For generated transactions, determine maturity if(type == TransactionRecord::Generated) { int64 nCredit = wtx.GetCredit(true); if (nCredit == 0) { status.maturity = TransactionStatus::Immature; if (wtx.IsInMainChain()) { status.matures_in = wtx.GetBlocksToMaturity(); // Check if the block was requested by anyone if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0) status.maturity = TransactionStatus::MaturesWarning; } else { status.maturity = TransactionStatus::NotAccepted; } } else { status.maturity = TransactionStatus::Mature; } } } bool TransactionRecord::statusUpdateNeeded() { return status.cur_num_blocks != nBestHeight; } std::string TransactionRecord::getTxID() { return hash.ToString() + strprintf("-%03d", idx); }
#include<cstdio> #include<algorithm> struct Snowflake{ int armLen[6]; }; const int HASH_MAX=1000000,EMPTY=-1; int hash(const Snowflake& snowflake){ int sum=0; for(int armIndex=0;armIndex<6;armIndex++) sum+=snowflake.armLen[armIndex]; return sum%HASH_MAX; } bool equals(const Snowflake& left,const Snowflake& right){ for(int shift=0;shift<6;shift++){ int same=true; for(int armIndex=0;armIndex<6;armIndex++) if(left.armLen[armIndex]!=right.armLen[(armIndex+shift)%6]) same=false; if(same) return true; same=true; for(int armIndex=0;armIndex<6;armIndex++) if(left.armLen[armIndex]!=right.armLen[(5-armIndex+shift)%6]) same=false; if(same) return true; } return false; } bool twinsExist(int existIndex,int newIndex,Snowflake snowflakes[],int next[]){ if(equals(snowflakes[existIndex],snowflakes[newIndex])) return true; if(next[existIndex]==EMPTY){ next[existIndex]=newIndex; return false; } return twinsExist(next[existIndex],newIndex,snowflakes,next); } int main(){ int snowflakeNum; scanf("%d",&snowflakeNum); Snowflake *snowflakes=new Snowflake[snowflakeNum]; int *hashTable=new int[HASH_MAX]; std::fill(hashTable,hashTable+HASH_MAX,EMPTY); int *next=new int[snowflakeNum]; std::fill(next,next+snowflakeNum,EMPTY); bool twinFound=false; for(int snowflakeIndex=0;snowflakeIndex<snowflakeNum;snowflakeIndex++){ for(int armIndex=0;armIndex<6;armIndex++) scanf("%d",snowflakes[snowflakeIndex].armLen+armIndex); if(twinFound) continue; int hashCode=hash(snowflakes[snowflakeIndex]); if(hashTable[hashCode]==EMPTY) hashTable[hashCode]=snowflakeIndex; else twinFound=twinsExist(hashTable[hashCode],snowflakeIndex,snowflakes,next); } if(twinFound) printf("Twin snowflakes found.\n"); else printf("No two snowflakes are alike.\n"); delete[] next; delete[] hashTable; delete[] snowflakes; return 0; }
/****************************************************************************//* * Copyright (C) 2021 Marek M. Cel * * 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 <gui/DialogMass.h> #include <ui_DialogMass.h> #include <gui/Aircrafts.h> //////////////////////////////////////////////////////////////////////////////// DialogMass::DialogMass( QWidget *parent ) : QDialog ( parent ), _ui ( new Ui::DialogMass ), _type ( -1 ), _pilot_1 ( 0.0 ), _pilot_2 ( 0.0 ), _fuel_tank_1 ( 0.0 ), _fuel_tank_2 ( 0.0 ), _fuel_tank_3 ( 0.0 ), _fuel_tank_4 ( 0.0 ), _fuel_tank_5 ( 0.0 ), _fuel_tank_6 ( 0.0 ), _fuel_tank_7 ( 0.0 ), _fuel_tank_8 ( 0.0 ), _cabin ( 0.0 ), _trunk ( 0.0 ), _slung ( 0.0 ) { _ui->setupUi( this ); _ui->spinBoxTotal->setHighlightColor( QColor( 0xff, 0x0, 0x0 ) ); _ui->spinBoxTotal->setToggleOnDblClick( false ); settingsRead(); } //////////////////////////////////////////////////////////////////////////////// DialogMass::~DialogMass() { settingsSave(); DELPTR( _ui ); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::readData() { _ui->spinBoxPilot_1->setValue( _ui->comboBoxPilot_1->convert( _pilot_1 ) ); _ui->spinBoxPilot_2->setValue( _ui->comboBoxPilot_2->convert( _pilot_2 ) ); _ui->spinBoxFuelTank_1->setValue( _ui->comboBoxFuelTank_1->convert( _fuel_tank_1 ) ); _ui->spinBoxFuelTank_2->setValue( _ui->comboBoxFuelTank_2->convert( _fuel_tank_2 ) ); _ui->spinBoxFuelTank_3->setValue( _ui->comboBoxFuelTank_3->convert( _fuel_tank_3 ) ); _ui->spinBoxFuelTank_4->setValue( _ui->comboBoxFuelTank_4->convert( _fuel_tank_4 ) ); _ui->spinBoxFuelTank_5->setValue( _ui->comboBoxFuelTank_5->convert( _fuel_tank_5 ) ); _ui->spinBoxFuelTank_6->setValue( _ui->comboBoxFuelTank_6->convert( _fuel_tank_6 ) ); _ui->spinBoxFuelTank_7->setValue( _ui->comboBoxFuelTank_7->convert( _fuel_tank_7 ) ); _ui->spinBoxFuelTank_8->setValue( _ui->comboBoxFuelTank_8->convert( _fuel_tank_8 ) ); _ui->spinBoxCabin->setValue( _ui->comboBoxCabin->convert( _cabin ) ); _ui->spinBoxTrunk->setValue( _ui->comboBoxTrunk->convert( _trunk ) ); _ui->spinBoxSlung->setValue( _ui->comboBoxSlung->convert( _slung ) ); updateResults(); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::saveData() { _pilot_1 = _ui->comboBoxPilot_1->invert( _ui->spinBoxPilot_1->value() ); _pilot_2 = _ui->comboBoxPilot_2->invert( _ui->spinBoxPilot_2->value() ); _fuel_tank_1 = _ui->comboBoxFuelTank_1->invert( _ui->spinBoxFuelTank_1->value() ); _fuel_tank_2 = _ui->comboBoxFuelTank_2->invert( _ui->spinBoxFuelTank_2->value() ); _fuel_tank_3 = _ui->comboBoxFuelTank_3->invert( _ui->spinBoxFuelTank_3->value() ); _fuel_tank_4 = _ui->comboBoxFuelTank_4->invert( _ui->spinBoxFuelTank_4->value() ); _fuel_tank_5 = _ui->comboBoxFuelTank_5->invert( _ui->spinBoxFuelTank_5->value() ); _fuel_tank_6 = _ui->comboBoxFuelTank_6->invert( _ui->spinBoxFuelTank_6->value() ); _fuel_tank_7 = _ui->comboBoxFuelTank_7->invert( _ui->spinBoxFuelTank_7->value() ); _fuel_tank_8 = _ui->comboBoxFuelTank_8->invert( _ui->spinBoxFuelTank_8->value() ); _cabin = _ui->comboBoxCabin->invert( _ui->spinBoxCabin->value() ); _trunk = _ui->comboBoxTrunk->invert( _ui->spinBoxTrunk->value() ); _slung = _ui->comboBoxSlung->invert( _ui->spinBoxSlung->value() ); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::setAircraftType( int type ) { Aircrafts::Masses masses = Aircrafts::instance()->getAircraft( type ).masses; if ( _type != type ) { _type = type; _pilot_1 = masses.pilot_1.def; _pilot_2 = masses.pilot_2.def; _fuel_tank_1 = masses.fuel_tank_1.def; _fuel_tank_2 = masses.fuel_tank_2.def; _fuel_tank_3 = masses.fuel_tank_3.def; _fuel_tank_4 = masses.fuel_tank_4.def; _fuel_tank_5 = masses.fuel_tank_5.def; _fuel_tank_6 = masses.fuel_tank_6.def; _fuel_tank_7 = masses.fuel_tank_7.def; _fuel_tank_8 = masses.fuel_tank_8.def; _cabin = masses.cabin.def; _trunk = masses.trunk.def; _slung = masses.slung.def; } _ui->spinBoxPilot_1->setMaximum( _ui->comboBoxPilot_1->convert( masses.pilot_1.max ) ); _ui->spinBoxPilot_2->setMaximum( _ui->comboBoxPilot_2->convert( masses.pilot_2.max ) ); _ui->spinBoxFuelTank_1->setMaximum( _ui->comboBoxFuelTank_1->convert( masses.fuel_tank_1.max ) ); _ui->spinBoxFuelTank_2->setMaximum( _ui->comboBoxFuelTank_2->convert( masses.fuel_tank_2.max ) ); _ui->spinBoxFuelTank_3->setMaximum( _ui->comboBoxFuelTank_3->convert( masses.fuel_tank_3.max ) ); _ui->spinBoxFuelTank_4->setMaximum( _ui->comboBoxFuelTank_4->convert( masses.fuel_tank_4.max ) ); _ui->spinBoxFuelTank_5->setMaximum( _ui->comboBoxFuelTank_5->convert( masses.fuel_tank_5.max ) ); _ui->spinBoxFuelTank_6->setMaximum( _ui->comboBoxFuelTank_6->convert( masses.fuel_tank_6.max ) ); _ui->spinBoxFuelTank_7->setMaximum( _ui->comboBoxFuelTank_7->convert( masses.fuel_tank_7.max ) ); _ui->spinBoxFuelTank_8->setMaximum( _ui->comboBoxFuelTank_8->convert( masses.fuel_tank_8.max ) ); _ui->spinBoxCabin->setMaximum( _ui->comboBoxCabin->convert( masses.cabin.max ) ); _ui->spinBoxTrunk->setMaximum( _ui->comboBoxTrunk->convert( masses.trunk.max ) ); _ui->spinBoxSlung->setMaximum( _ui->comboBoxTrunk->convert( masses.slung.max ) ); _ui->labelPilot_1->setVisible( masses.pilot_1.enabled ); _ui->labelPilot_2->setVisible( masses.pilot_2.enabled ); _ui->labelFuelTank_1->setVisible( masses.fuel_tank_1.enabled ); _ui->labelFuelTank_2->setVisible( masses.fuel_tank_2.enabled ); _ui->labelFuelTank_3->setVisible( masses.fuel_tank_3.enabled ); _ui->labelFuelTank_4->setVisible( masses.fuel_tank_4.enabled ); _ui->labelFuelTank_5->setVisible( masses.fuel_tank_5.enabled ); _ui->labelFuelTank_6->setVisible( masses.fuel_tank_6.enabled ); _ui->labelFuelTank_7->setVisible( masses.fuel_tank_7.enabled ); _ui->labelFuelTank_8->setVisible( masses.fuel_tank_8.enabled ); _ui->labelCabin->setVisible( masses.cabin.enabled ); _ui->labelTrunk->setVisible( masses.trunk.enabled ); _ui->labelSlung->setVisible( masses.slung.enabled ); _ui->labelPilot_1->setText( masses.pilot_1.name + ":" ); _ui->labelPilot_2->setText( masses.pilot_2.name + ":" ); _ui->labelFuelTank_1->setText( masses.fuel_tank_1.name + ":" ); _ui->labelFuelTank_2->setText( masses.fuel_tank_2.name + ":" ); _ui->labelFuelTank_3->setText( masses.fuel_tank_3.name + ":" ); _ui->labelFuelTank_4->setText( masses.fuel_tank_4.name + ":" ); _ui->labelFuelTank_5->setText( masses.fuel_tank_5.name + ":" ); _ui->labelFuelTank_6->setText( masses.fuel_tank_6.name + ":" ); _ui->labelFuelTank_7->setText( masses.fuel_tank_7.name + ":" ); _ui->labelFuelTank_8->setText( masses.fuel_tank_8.name + ":" ); _ui->labelCabin->setText( masses.cabin.name + ":" ); _ui->labelTrunk->setText( masses.trunk.name + ":" ); _ui->labelSlung->setText( masses.slung.name + ":" ); _ui->spinBoxPilot_1->setVisible( masses.pilot_1.enabled ); _ui->spinBoxPilot_2->setVisible( masses.pilot_2.enabled ); _ui->spinBoxFuelTank_1->setVisible( masses.fuel_tank_1.enabled ); _ui->spinBoxFuelTank_2->setVisible( masses.fuel_tank_2.enabled ); _ui->spinBoxFuelTank_3->setVisible( masses.fuel_tank_3.enabled ); _ui->spinBoxFuelTank_4->setVisible( masses.fuel_tank_4.enabled ); _ui->spinBoxFuelTank_5->setVisible( masses.fuel_tank_5.enabled ); _ui->spinBoxFuelTank_6->setVisible( masses.fuel_tank_6.enabled ); _ui->spinBoxFuelTank_7->setVisible( masses.fuel_tank_7.enabled ); _ui->spinBoxFuelTank_8->setVisible( masses.fuel_tank_8.enabled ); _ui->spinBoxCabin->setVisible( masses.cabin.enabled ); _ui->spinBoxTrunk->setVisible( masses.trunk.enabled ); _ui->spinBoxSlung->setVisible( masses.slung.enabled ); _ui->comboBoxPilot_1->setVisible( masses.pilot_1.enabled ); _ui->comboBoxPilot_2->setVisible( masses.pilot_2.enabled ); _ui->comboBoxFuelTank_1->setVisible( masses.fuel_tank_1.enabled ); _ui->comboBoxFuelTank_2->setVisible( masses.fuel_tank_2.enabled ); _ui->comboBoxFuelTank_3->setVisible( masses.fuel_tank_3.enabled ); _ui->comboBoxFuelTank_4->setVisible( masses.fuel_tank_4.enabled ); _ui->comboBoxFuelTank_5->setVisible( masses.fuel_tank_5.enabled ); _ui->comboBoxFuelTank_6->setVisible( masses.fuel_tank_6.enabled ); _ui->comboBoxFuelTank_7->setVisible( masses.fuel_tank_7.enabled ); _ui->comboBoxFuelTank_8->setVisible( masses.fuel_tank_8.enabled ); _ui->comboBoxCabin->setVisible( masses.cabin.enabled ); _ui->comboBoxTrunk->setVisible( masses.trunk.enabled ); _ui->comboBoxSlung->setVisible( masses.slung.enabled ); readData(); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::settingsRead() { QSettings settings( SIM_ORG_NAME, SIM_APP_NAME ); settings.beginGroup( "dialog_mass" ); restoreGeometry( settings.value( "geometry" ).toByteArray() ); _type = settings.value( "aircraft_type", -1 ).toInt(); settingsRead_UnitCombos( settings ); // before mass data !!! settingsRead_MassData( settings ); settings.endGroup(); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::settingsRead_MassData( QSettings &settings ) { settings.beginGroup( "mass_data" ); _pilot_1 = settings.value( "pilot_1", 0.0 ).toDouble(); _pilot_2 = settings.value( "pilot_2", 0.0 ).toDouble(); _fuel_tank_1 = settings.value( "fuel_tank_1", 0.0 ).toDouble(); _fuel_tank_2 = settings.value( "fuel_tank_2", 0.0 ).toDouble(); _fuel_tank_3 = settings.value( "fuel_tank_3", 0.0 ).toDouble(); _fuel_tank_4 = settings.value( "fuel_tank_4", 0.0 ).toDouble(); _fuel_tank_5 = settings.value( "fuel_tank_5", 0.0 ).toDouble(); _fuel_tank_6 = settings.value( "fuel_tank_6", 0.0 ).toDouble(); _fuel_tank_7 = settings.value( "fuel_tank_7", 0.0 ).toDouble(); _fuel_tank_8 = settings.value( "fuel_tank_8", 0.0 ).toDouble(); _cabin = settings.value( "cabin", 0.0 ).toDouble(); _trunk = settings.value( "trunk", 0.0 ).toDouble(); _slung = settings.value( "slung", 0.0 ).toDouble(); settings.endGroup(); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::settingsRead_UnitCombos( QSettings &settings ) { settings.beginGroup( "unit_combos" ); _ui->comboBoxPilot_1->setCurrentIndex( settings.value( "pilot_1", 0 ).toInt() ); _ui->comboBoxPilot_2->setCurrentIndex( settings.value( "pilot_2", 0 ).toInt() ); _ui->comboBoxFuelTank_1->setCurrentIndex( settings.value( "fuel_tank_1", 0 ).toInt() ); _ui->comboBoxFuelTank_2->setCurrentIndex( settings.value( "fuel_tank_2", 0 ).toInt() ); _ui->comboBoxFuelTank_3->setCurrentIndex( settings.value( "fuel_tank_3", 0 ).toInt() ); _ui->comboBoxFuelTank_4->setCurrentIndex( settings.value( "fuel_tank_4", 0 ).toInt() ); _ui->comboBoxFuelTank_5->setCurrentIndex( settings.value( "fuel_tank_5", 0 ).toInt() ); _ui->comboBoxFuelTank_6->setCurrentIndex( settings.value( "fuel_tank_6", 0 ).toInt() ); _ui->comboBoxFuelTank_7->setCurrentIndex( settings.value( "fuel_tank_7", 0 ).toInt() ); _ui->comboBoxFuelTank_8->setCurrentIndex( settings.value( "fuel_tank_8", 0 ).toInt() ); _ui->comboBoxCabin->setCurrentIndex( settings.value( "cabin", 0 ).toInt() ); _ui->comboBoxTrunk->setCurrentIndex( settings.value( "trunk", 0 ).toInt() ); _ui->comboBoxSlung->setCurrentIndex( settings.value( "slung", 0 ).toInt() ); settings.endGroup(); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::settingsSave() { QSettings settings( SIM_ORG_NAME, SIM_APP_NAME ); settings.beginGroup( "dialog_mass" ); settings.setValue( "geometry" , saveGeometry() ); settings.setValue( "aircraft_type", _type ); settingsSave_MassData( settings ); settingsSave_UnitCombos( settings ); settings.endGroup(); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::settingsSave_MassData( QSettings &settings ) { settings.beginGroup( "mass_data" ); settings.setValue( "pilot_1", _pilot_1 ); settings.setValue( "pilot_2", _pilot_2 ); settings.setValue( "fuel_tank_1", _fuel_tank_1 ); settings.setValue( "fuel_tank_2", _fuel_tank_2 ); settings.setValue( "fuel_tank_3", _fuel_tank_3 ); settings.setValue( "fuel_tank_4", _fuel_tank_4 ); settings.setValue( "fuel_tank_5", _fuel_tank_5 ); settings.setValue( "fuel_tank_6", _fuel_tank_6 ); settings.setValue( "fuel_tank_7", _fuel_tank_7 ); settings.setValue( "fuel_tank_8", _fuel_tank_8 ); settings.setValue( "cabin", _cabin ); settings.setValue( "trunk", _trunk ); settings.setValue( "slung", _slung ); settings.endGroup(); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::settingsSave_UnitCombos( QSettings &settings ) { settings.beginGroup( "unit_combos" ); settings.setValue( "pilot_1", _ui->comboBoxPilot_1->currentIndex() ); settings.setValue( "pilot_2", _ui->comboBoxPilot_2->currentIndex() ); settings.setValue( "fuel_tank_1", _ui->comboBoxFuelTank_1->currentIndex() ); settings.setValue( "fuel_tank_2", _ui->comboBoxFuelTank_2->currentIndex() ); settings.setValue( "fuel_tank_3", _ui->comboBoxFuelTank_3->currentIndex() ); settings.setValue( "fuel_tank_4", _ui->comboBoxFuelTank_4->currentIndex() ); settings.setValue( "fuel_tank_5", _ui->comboBoxFuelTank_5->currentIndex() ); settings.setValue( "fuel_tank_6", _ui->comboBoxFuelTank_6->currentIndex() ); settings.setValue( "fuel_tank_7", _ui->comboBoxFuelTank_7->currentIndex() ); settings.setValue( "fuel_tank_8", _ui->comboBoxFuelTank_8->currentIndex() ); settings.setValue( "cabin", _ui->comboBoxCabin->currentIndex() ); settings.setValue( "trunk", _ui->comboBoxTrunk->currentIndex() ); settings.setValue( "slung", _ui->comboBoxSlung->currentIndex() ); settings.endGroup(); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::updateResults() { Aircrafts::Masses masses = Aircrafts::instance()->getAircraft( _type ).masses; double m_e = masses.empty; double mtow = masses.mtow; _ui->spinBoxMTOW->setValue( _ui->comboBoxMTOW->convert( mtow ) ); _ui->spinBoxTotal->setHighlighted( false ); if ( m_e > 0.0 ) { double m_t = m_e; if ( masses.pilot_1 .enabled ) m_t += _ui->comboBoxPilot_1 ->invert( _ui->spinBoxPilot_1 ->value() ); if ( masses.pilot_2 .enabled ) m_t += _ui->comboBoxPilot_2 ->invert( _ui->spinBoxPilot_2 ->value() ); if ( masses.fuel_tank_1 .enabled ) m_t += _ui->comboBoxFuelTank_1 ->invert( _ui->spinBoxFuelTank_1 ->value() ); if ( masses.fuel_tank_2 .enabled ) m_t += _ui->comboBoxFuelTank_2 ->invert( _ui->spinBoxFuelTank_2 ->value() ); if ( masses.fuel_tank_3 .enabled ) m_t += _ui->comboBoxFuelTank_3 ->invert( _ui->spinBoxFuelTank_3 ->value() ); if ( masses.fuel_tank_4 .enabled ) m_t += _ui->comboBoxFuelTank_4 ->invert( _ui->spinBoxFuelTank_4 ->value() ); if ( masses.fuel_tank_5 .enabled ) m_t += _ui->comboBoxFuelTank_5 ->invert( _ui->spinBoxFuelTank_5 ->value() ); if ( masses.fuel_tank_6 .enabled ) m_t += _ui->comboBoxFuelTank_6 ->invert( _ui->spinBoxFuelTank_6 ->value() ); if ( masses.fuel_tank_7 .enabled ) m_t += _ui->comboBoxFuelTank_7 ->invert( _ui->spinBoxFuelTank_7 ->value() ); if ( masses.fuel_tank_8 .enabled ) m_t += _ui->comboBoxFuelTank_8 ->invert( _ui->spinBoxFuelTank_8 ->value() ); if ( masses.cabin .enabled ) m_t += _ui->comboBoxCabin ->invert( _ui->spinBoxCabin ->value() ); if ( masses.trunk .enabled ) m_t += _ui->comboBoxTrunk ->invert( _ui->spinBoxTrunk ->value() ); if ( masses.slung .enabled ) m_t += _ui->comboBoxSlung ->invert( _ui->spinBoxSlung ->value() ); _ui->spinBoxTotal->setValue( _ui->comboBoxTotal->convert( m_t ) ); _ui->spinBoxTotal->setHighlighted( m_t > mtow ); } else { _ui->spinBoxTotal->setValue( 0.0 ); } } //////////////////////////////////////////////////////////////////////////////// void DialogMass::on_comboBoxPilot_1_currentIndexChanged( int ) { double mass_kg = _ui->comboBoxPilot_1->invertPrev( _ui->spinBoxPilot_1->value() ); Aircrafts::Masses::Mass mass = Aircrafts::instance()->getAircraft( _type ).masses.pilot_1; _ui->spinBoxPilot_1->setMaximum( _ui->comboBoxPilot_1->convert( mass.max ) ); _ui->spinBoxPilot_1->setValue( _ui->comboBoxPilot_1->convert( mass_kg ) ); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::on_comboBoxPilot_2_currentIndexChanged( int ) { double mass_kg = _ui->comboBoxPilot_1->invertPrev( _ui->spinBoxPilot_2->value() ); Aircrafts::Masses::Mass mass = Aircrafts::instance()->getAircraft( _type ).masses.pilot_2; _ui->spinBoxPilot_2->setMaximum( _ui->comboBoxPilot_2->convert( mass.max ) ); _ui->spinBoxPilot_2->setValue( _ui->comboBoxPilot_2->convert( mass_kg ) ); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::on_comboBoxFuelTank_1_currentIndexChanged( int ) { double mass_kg = _ui->comboBoxFuelTank_1->invertPrev( _ui->spinBoxFuelTank_1->value() ); Aircrafts::Masses::Mass mass = Aircrafts::instance()->getAircraft( _type ).masses.fuel_tank_1; _ui->spinBoxFuelTank_1->setMaximum( _ui->comboBoxFuelTank_1->convert( mass.max ) ); _ui->spinBoxFuelTank_1->setValue( _ui->comboBoxFuelTank_1->convert( mass_kg ) ); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::on_comboBoxFuelTank_2_currentIndexChanged( int ) { double mass_kg = _ui->comboBoxFuelTank_2->invertPrev( _ui->spinBoxFuelTank_2->value() ); Aircrafts::Masses::Mass mass = Aircrafts::instance()->getAircraft( _type ).masses.fuel_tank_2; _ui->spinBoxFuelTank_2->setMaximum( _ui->comboBoxFuelTank_2->convert( mass.max ) ); _ui->spinBoxFuelTank_2->setValue( _ui->comboBoxFuelTank_2->convert( mass_kg ) ); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::on_comboBoxFuelTank_3_currentIndexChanged( int ) { double mass_kg = _ui->comboBoxFuelTank_3->invertPrev( _ui->spinBoxFuelTank_3->value() ); Aircrafts::Masses::Mass mass = Aircrafts::instance()->getAircraft( _type ).masses.fuel_tank_3; _ui->spinBoxFuelTank_3->setMaximum( _ui->comboBoxFuelTank_3->convert( mass.max ) ); _ui->spinBoxFuelTank_3->setValue( _ui->comboBoxFuelTank_3->convert( mass_kg ) ); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::on_comboBoxFuelTank_4_currentIndexChanged( int ) { double mass_kg = _ui->comboBoxFuelTank_4->invertPrev( _ui->spinBoxFuelTank_4->value() ); Aircrafts::Masses::Mass mass = Aircrafts::instance()->getAircraft( _type ).masses.fuel_tank_4; _ui->spinBoxFuelTank_4->setMaximum( _ui->comboBoxFuelTank_4->convert( mass.max ) ); _ui->spinBoxFuelTank_4->setValue( _ui->comboBoxFuelTank_4->convert( mass_kg ) ); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::on_comboBoxFuelTank_5_currentIndexChanged( int ) { double mass_kg = _ui->comboBoxFuelTank_5->invertPrev( _ui->spinBoxFuelTank_5->value() ); Aircrafts::Masses::Mass mass = Aircrafts::instance()->getAircraft( _type ).masses.fuel_tank_5; _ui->spinBoxFuelTank_5->setMaximum( _ui->comboBoxFuelTank_5->convert( mass.max ) ); _ui->spinBoxFuelTank_5->setValue( _ui->comboBoxFuelTank_5->convert( mass_kg ) ); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::on_comboBoxFuelTank_6_currentIndexChanged( int ) { double mass_kg = _ui->comboBoxFuelTank_6->invertPrev( _ui->spinBoxFuelTank_6->value() ); Aircrafts::Masses::Mass mass = Aircrafts::instance()->getAircraft( _type ).masses.fuel_tank_6; _ui->spinBoxFuelTank_6->setMaximum( _ui->comboBoxFuelTank_6->convert( mass.max ) ); _ui->spinBoxFuelTank_6->setValue( _ui->comboBoxFuelTank_6->convert( mass_kg ) ); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::on_comboBoxFuelTank_7_currentIndexChanged( int ) { double mass_kg = _ui->comboBoxFuelTank_7->invertPrev( _ui->spinBoxFuelTank_7->value() ); Aircrafts::Masses::Mass mass = Aircrafts::instance()->getAircraft( _type ).masses.fuel_tank_7; _ui->spinBoxFuelTank_7->setMaximum( _ui->comboBoxFuelTank_7->convert( mass.max ) ); _ui->spinBoxFuelTank_7->setValue( _ui->comboBoxFuelTank_7->convert( mass_kg ) ); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::on_comboBoxFuelTank_8_currentIndexChanged( int ) { double mass_kg = _ui->comboBoxFuelTank_8->invertPrev( _ui->spinBoxFuelTank_8->value() ); Aircrafts::Masses::Mass mass = Aircrafts::instance()->getAircraft( _type ).masses.fuel_tank_8; _ui->spinBoxFuelTank_8->setMaximum( _ui->comboBoxFuelTank_8->convert( mass.max ) ); _ui->spinBoxFuelTank_8->setValue( _ui->comboBoxFuelTank_8->convert( mass_kg ) ); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::on_comboBoxCabin_currentIndexChanged( int ) { double mass_kg = _ui->comboBoxCabin->invertPrev( _ui->spinBoxCabin->value() ); Aircrafts::Masses::Mass mass = Aircrafts::instance()->getAircraft( _type ).masses.cabin; _ui->spinBoxCabin->setMaximum( _ui->comboBoxCabin->convert( mass.max ) ); _ui->spinBoxCabin->setValue( _ui->comboBoxCabin->convert( mass_kg ) ); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::on_comboBoxTrunk_currentIndexChanged( int ) { double mass_kg = _ui->comboBoxTrunk->invertPrev( _ui->spinBoxTrunk->value() ); Aircrafts::Masses::Mass mass = Aircrafts::instance()->getAircraft( _type ).masses.trunk; _ui->spinBoxTrunk->setMaximum( _ui->comboBoxTrunk->convert( mass.max ) ); _ui->spinBoxTrunk->setValue( _ui->comboBoxTrunk->convert( mass_kg ) ); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::on_comboBoxSlung_currentIndexChanged( int ) { double mass_kg = _ui->comboBoxSlung->invertPrev( _ui->spinBoxSlung->value() ); Aircrafts::Masses::Mass mass = Aircrafts::instance()->getAircraft( _type ).masses.slung; _ui->spinBoxSlung->setMaximum( _ui->comboBoxSlung->convert( mass.max ) ); _ui->spinBoxSlung->setValue( _ui->comboBoxSlung->convert( mass_kg ) ); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::on_spinBoxPilot_1_valueChanged( double /*arg1*/ ) { updateResults(); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::on_spinBoxPilot_2_valueChanged( double /*arg1*/ ) { updateResults(); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::on_spinBoxFuelTank_1_valueChanged( double /*arg1*/ ) { updateResults(); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::on_spinBoxFuelTank_2_valueChanged( double /*arg1*/ ) { updateResults(); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::on_spinBoxFuelTank_3_valueChanged( double /*arg1*/ ) { updateResults(); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::on_spinBoxFuelTank_4_valueChanged( double /*arg1*/ ) { updateResults(); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::on_spinBoxFuelTank_5_valueChanged( double /*arg1*/ ) { updateResults(); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::on_spinBoxFuelTank_6_valueChanged( double /*arg1*/ ) { updateResults(); } void DialogMass::on_spinBoxFuelTank_7_valueChanged( double /*arg1*/ ) { updateResults(); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::on_spinBoxFuelTank_8_valueChanged( double /*arg1*/ ) { updateResults(); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::on_spinBoxCabin_valueChanged( double /*arg1*/ ) { updateResults(); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::on_spinBoxTrunk_valueChanged( double /*arg1*/ ) { updateResults(); } //////////////////////////////////////////////////////////////////////////////// void DialogMass::on_spinBoxSlung_valueChanged( double /*arg1*/ ) { updateResults(); }
#include <iostream> #include <bits/stdc++.h> using namespace std; int main() { int dragons; //total dragons int punched; //k dragon got punched with frying pan int tail; //l dragon got his tail shut to balcony door int paws;// m dragon got his paws trampled with sharp heels int mom;//n dragon got threatened by calling his mom int start=1; cin>>punched>>tail>>paws>>mom>>dragons; int damaged[dragons]; int punched1=punched;// to have the original value after punched's value has changed int tail1=tail;// to have the original value after tail's value has changed int paws1=paws;// to have the original value after paws' value has changed int mom1=mom;// to have the original value after mom's value has changed int counter=dragons;//to count how many the damaged dragons int count=0; for(int i=0;i<dragons;i++) { damaged[i]={start}; start++; } for(int i=0;i<dragons;i++) { if(damaged[i]==punched) { punched=punched1+punched; count++; } if(damaged[i]==tail) { tail= tail+tail1; count++; } if(damaged[i]==paws) { paws= paws+paws1; count++; } if(damaged[i]==mom) { mom= mom+mom1; count++; } if(count==0) { counter--; } count=0; } cout<<counter; }
//-------------------------------------------------------- // OpenNero : IrrFactory // irrilicht factory //-------------------------------------------------------- #include "core/Common.h" #include <irrlicht.h> #include "game/objects/PropertyMap.h" // keep TinyXml from complaining #include "core/Common.h" #include "core/IrrSerialize.h" #include "game/factories/IrrFactory.h" #include "game/factories/SimFactory.h" #include "game/Kernel.h" #include "render/Shader.h" #include "core/LogConnections.h" #include "core/Log.h" namespace OpenNero { namespace { /// Scalable axes with R,G,B for X,Y,Z respectively class AxesSceneNode : public scene::ISceneNode { scene::SMeshBuffer ZMeshBuffer; scene::SMeshBuffer YMeshBuffer; scene::SMeshBuffer XMeshBuffer; video::SColor ZColor; video::SColor YColor; video::SColor XColor; public: AxesSceneNode(scene::ISceneNode* parent, scene::ISceneManager* mgr, s32 id); virtual ~AxesSceneNode() {} virtual void OnRegisterSceneNode(); virtual void render(); void setAxesCoordinates(); virtual const core::aabbox3d<f32>& getBoundingBox() const { return ZMeshBuffer.BoundingBox; } void setAxesScale(f32 scale); }; } /// CTOR IrrFactory::IrrFactory( const IrrHandles& irr ) : mIrr(irr) {} /// DTOR IrrFactory::~IrrFactory() {} /** * Load an Irrlicht model file * @param modelFile the file to load from * @return a ptr to the IAnimatedMesh class */ IAnimatedMesh* IrrFactory::LoadAniMesh( const std::string& modelFile ) { return mIrr.getSceneManager()->getMesh( SimFactory::TransformPath(modelFile).c_str() ); } /** * Load an Irrlicht texture file * @param textureFile the file to load from * @return a void ptr to the ITexture class */ ITexture* IrrFactory::LoadTexture( const std::string& textureFile ) { // load the texture ITexture* tex = mIrr.getVideoDriver()->getTexture( SimFactory::TransformPath(textureFile).c_str() ); if( tex ) { LOG_D_MSG( "factory_resource_log", "Loaded texture " << textureFile ); } return tex; } IAnimatedMeshSceneNode* IrrFactory::addAnimatedMeshSceneNode( IAnimatedMesh* mesh ) { Assert( mesh ); return mIrr.getSceneManager()->addAnimatedMeshSceneNode( mesh ); } ISceneNode* IrrFactory::addAxes() { AxesSceneNode* scene = new AxesSceneNode(mIrr.getSceneManager()->getRootSceneNode(), mIrr.getSceneManager(), -1); Assert(scene); scene->setAxesScale(10); scene->setScale(vector3df(5,5,5)); return scene; } ITerrainSceneNode* IrrFactory::addTerrainSceneNode( const std::string& heightmap ) { return mIrr.getSceneManager()->addTerrainSceneNode( SimFactory::TransformPath(heightmap).c_str() ); } IParticleSystemSceneNode* IrrFactory::addParticleSystemNode( const std::string& particleSystemFile ) { PropertyMap propMap; if( propMap.constructPropertyMap( SimFactory::TransformPath(particleSystemFile) ) ) { // default values const vector3df pos( 0, 0, 0 ); const vector3df rot( 0, 0, 0 ); const vector3df scale( 1, 1, 1 ); // create the particle system node IParticleSystemSceneNode* pSystem = mIrr.getSceneManager()->addParticleSystemSceneNode( false, 0, -1, pos, rot, scale ); Assert( pSystem ); // read some custom properties bool globalMovement = true; dimension2df particleSize( 5.0f, 5.0f ); propMap.getValue( globalMovement, "ParticleSystem.System.GlobalMovement" ); propMap.getValue( particleSize, "ParticleSystem.System.ParticleSize" ); pSystem->setParticlesAreGlobal(globalMovement); pSystem->setParticleSize(particleSize); /// ---- load the effectors ---- // get the gravity properties if( propMap.hasSection( "ParticleSystem.Gravity" ) ) { vector3df gravDir( 0, -1, 0 ); uint32_t affectorTimeMS(1000); // try to read params propMap.getValue( gravDir, "ParticleSystem.Gravity.Direction" ); propMap.getValue( affectorTimeMS, "ParticleSystem.Gravity.AffectorTimeMS" ); gravDir = ConvertNeroToIrrlichtPosition(gravDir); IParticleAffector* pGravity = pSystem->createGravityAffector( gravDir, affectorTimeMS ); Assert( pGravity ); pSystem->addAffector( pGravity ); pGravity->drop(); } // get the fade properties if( propMap.hasSection( "ParticleSystem.Fade" ) ) { SColor targetColor(0,0,0,0); uint32_t affectorTimeMS(1000); // try to read params propMap.getValue( targetColor, "ParticleSystem.Fade.TargetColor" ); propMap.getValue( affectorTimeMS, "ParticleSystem.Fade.AffectorTimeMS" ); IParticleAffector* pFade = pSystem->createFadeOutParticleAffector( targetColor, affectorTimeMS ); Assert( pFade ); pSystem->addAffector( pFade ); pFade->drop(); } // ---- load the emitters ---- // --- NOTE: WE ONLY DO BOX EMITTERS --- if( propMap.hasSection( "ParticleSystem.Emitter" ) ) { // default params aabbox3df box(-10, 28,-10, 10, 30, 10); vector3df dir( 0, .03f, 0 ); uint32_t minParticlesPerSecond = 5; uint32_t maxParticlesPerSecond = 10; SColor minStartColor( 255, 0, 0, 0 ); SColor maxStartColor( 255, 255, 255, 255 ); uint32_t lifeTimeMin = 2000; uint32_t lifeTimeMax = 4000; int32_t maxAngleDegrees = 0; // try to read custom params propMap.getValue( box, "ParticleSystem.Emitter.Box" ); propMap.getValue( dir, "ParticleSystem.Emitter.Direction" ); propMap.getValue( minParticlesPerSecond, "ParticleSystem.Emitter.MinParticlesPerSecond" ); propMap.getValue( maxParticlesPerSecond, "ParticleSystem.Emitter.MaxParticlesPerSecond" ); propMap.getValue( minStartColor, "ParticleSystem.Emitter.MinStartColor" ); propMap.getValue( maxStartColor, "ParticleSystem.Emitter.MaxStartColor" ); propMap.getValue( lifeTimeMin, "ParticleSystem.Emitter.LifetimeMin" ); propMap.getValue( lifeTimeMax, "ParticleSystem.Emitter.LifetimeMax" ); propMap.getValue( maxAngleDegrees, "ParticleSystem.Emitter.MaxAngleDegrees" ); // do coordinate system transformations dir = ConvertNeroToIrrlichtPosition(dir); // create the emitter IParticleEmitter* emit = pSystem->createBoxEmitter ( box, dir, minParticlesPerSecond, maxParticlesPerSecond, minStartColor, maxStartColor, lifeTimeMin, lifeTimeMax, maxAngleDegrees ); Assert( emit ); pSystem->setEmitter( emit ); emit->drop(); } else { LOG_F_WARNING( "render", "No emitter in particle system file - " << particleSystemFile ); } return pSystem; } return NULL; } ITextSceneNode* IrrFactory::addTextSceneNode(const std::string& text, const SColor& color, const Vector3f pos, ISceneNode* parent) { ITextSceneNode* node = mIrr.getSceneManager()->addTextSceneNode(mIrr.getGuiEnv()->getFont( "common/data/gui/fonthaettenschweiler.bmp" ), L"TEST", color, parent, pos, 1); Assert(node); return node; } /** * Load a glsl shader into the cache. * @param vertFile the file containing the vertex program * @param fragFile the file containing the fragment program * @return-1 if failed, otherwise the index of the irrlicht material */ int32_t IrrFactory::LoadGlslShader( const std::string& vertFile, const std::string& fragFile ) { // combine the names to do lookup std::string lookupName = vertFile+fragFile; // do we already have this cache? ShaderMap::iterator itr = mShaderCache.find(lookupName); if( itr != mShaderCache.end() ) { return itr->second; } // create the callback (dont delete, irrlicht will manage it for us) ShaderCallback* cb = new ShaderCallback(mIrr); // convert the files to mod paths std::string modVertFile = SimFactory::TransformPath(vertFile); std::string modFragFile = SimFactory::TransformPath(fragFile); // attempt to create the shader int32_t shader = createGlslShader( mIrr, cb, modVertFile, "main", modFragFile, "main", EMT_SOLID ); // if the load succeeded, cache it for future calls if( shader >= 0 ) { mShaderCache[lookupName] = shader; } return shader; } void IrrFactory::addSphere( F32 radius, const vector3df& position, const vector3df& rotation, const vector3df& scale) { mIrr.getSceneManager()->addSphereSceneNode( radius, // size of the sphere 16, // poly-count mIrr.getSceneManager()->getRootSceneNode(), // parent node -1, // id position, rotation, scale); // pose } namespace { AxesSceneNode::AxesSceneNode(scene::ISceneNode* parent, scene::ISceneManager* mgr, s32 id): ISceneNode(parent, mgr, id) { #ifdef _DEBUG setDebugName("AxesSceneNode"); #endif u16 u[36] = { 0,2,1, 0,3,2, 1,5,4, 1,2,5, 4,6,7, 4,5,6, 7,3,0, 7,6,3, 3,5,2, 3,6,5, 0,1,4, 0,4,7,}; ZMeshBuffer.Indices.set_used(36); YMeshBuffer.Indices.set_used(36); XMeshBuffer.Indices.set_used(36); // Color Settings // jsheblak - note i fiddle with these to meet our OpenNero->Irrlicht coordinate frame conversion expectations XColor = video::SColor(255,255,0,0); YColor = video::SColor(255,0,0,255); ZColor = video::SColor(255,0,255,0); for (s32 i=0; i<36; ++i) { ZMeshBuffer.Indices[i] = u[i]; YMeshBuffer.Indices[i] = u[i]; XMeshBuffer.Indices[i] = u[i]; } // Default Position, Rotation and Scale this->setPosition(core::vector3df(0,0,0)); this->setRotation(core::vector3df(0,0,0)); this->setScale(core::vector3df(1,1,1)); // Axes Box Coordinates Settings setAxesCoordinates(); } void AxesSceneNode::OnRegisterSceneNode() { if (IsVisible) { SceneManager->registerNodeForRendering(this); ISceneNode::OnRegisterSceneNode(); } } void AxesSceneNode::render() { video::IVideoDriver* driver = SceneManager->getVideoDriver(); driver->setMaterial(ZMeshBuffer.Material); driver->setTransform(video::ETS_WORLD, AbsoluteTransformation); driver->drawMeshBuffer(&ZMeshBuffer); driver->setMaterial(YMeshBuffer.Material); driver->setTransform(video::ETS_WORLD, AbsoluteTransformation); driver->drawMeshBuffer(&YMeshBuffer); driver->setMaterial(XMeshBuffer.Material); driver->setTransform(video::ETS_WORLD, AbsoluteTransformation); driver->drawMeshBuffer(&XMeshBuffer); } void AxesSceneNode::setAxesCoordinates() { ZMeshBuffer.Vertices.set_used(8); ZMeshBuffer.Material.Wireframe = false; ZMeshBuffer.Material.Lighting = false; ZMeshBuffer.Vertices[0] = video::S3DVertex(-0.25,-0.25,0, -1,-1,-1, ZColor, 0, 1); ZMeshBuffer.Vertices[1] = video::S3DVertex(0.25,-0.25,0, 1,-1,-1, ZColor, 1, 1); ZMeshBuffer.Vertices[2] = video::S3DVertex(0.25,0.25,0, 1, 1,-1, ZColor, 1, 0); ZMeshBuffer.Vertices[3] = video::S3DVertex(-0.25,0.25,0, -1, 1,-1, ZColor, 0, 0); ZMeshBuffer.Vertices[4] = video::S3DVertex(0.25,-0.25,25, 1,-1, 1, ZColor, 0, 1); ZMeshBuffer.Vertices[5] = video::S3DVertex(0.25,0.25,25, 1, 1, 1, ZColor, 0, 0); ZMeshBuffer.Vertices[6] = video::S3DVertex(-0.25,0.25,25, -1, 1, 1, ZColor, 1, 0); ZMeshBuffer.Vertices[7] = video::S3DVertex(-0.25,-0.25,25, -1,-1, 1, ZColor, 1, 1); ZMeshBuffer.BoundingBox.reset(0,0,0); YMeshBuffer.Vertices.set_used(8); YMeshBuffer.Material.Wireframe = false; YMeshBuffer.Material.Lighting = false; YMeshBuffer.Vertices[0] = video::S3DVertex(-0.25,0,0.25, -1,-1,-1, YColor, 0, 1); YMeshBuffer.Vertices[1] = video::S3DVertex(0.25,0,0.25, 1,-1,-1, YColor, 1, 1); YMeshBuffer.Vertices[2] = video::S3DVertex(0.25,0,-0.25, 1, 1,-1, YColor, 1, 0); YMeshBuffer.Vertices[3] = video::S3DVertex(-0.25,0,-0.25, -1, 1,-1, YColor, 0, 0); YMeshBuffer.Vertices[4] = video::S3DVertex(0.25,25,0.25, 1,-1, 1, YColor, 0, 1); YMeshBuffer.Vertices[5] = video::S3DVertex(0.25,25,-0.25, 1, 1, 1, YColor, 0, 0); YMeshBuffer.Vertices[6] = video::S3DVertex(-0.25,25,-0.25, -1, 1, 1, YColor, 1, 0); YMeshBuffer.Vertices[7] = video::S3DVertex(-0.25,25,0.25, -1,-1, 1, YColor, 1, 1); YMeshBuffer.BoundingBox.reset(0,0,0); XMeshBuffer.Vertices.set_used(8); XMeshBuffer.Material.Wireframe = false; XMeshBuffer.Material.Lighting = false; XMeshBuffer.Vertices[0] = video::S3DVertex(0,-0.25,0.25, -1,-1,-1, XColor, 0, 1); XMeshBuffer.Vertices[1] = video::S3DVertex(0,-0.25,-0.25, 1,-1,-1, XColor, 1, 1); XMeshBuffer.Vertices[2] = video::S3DVertex(0,0.25,-0.25, 1, 1,-1, XColor, 1, 0); XMeshBuffer.Vertices[3] = video::S3DVertex(0,0.25,0.25, -1, 1,-1, XColor, 0, 0); XMeshBuffer.Vertices[4] = video::S3DVertex(25,-0.25,-0.25, 1,-1, 1, XColor, 0, 1); XMeshBuffer.Vertices[5] = video::S3DVertex(25,0.25,-0.25, 1, 1, 1, XColor, 0, 0); XMeshBuffer.Vertices[6] = video::S3DVertex(25,0.25,0.25, -1, 1, 1, XColor, 1, 0); XMeshBuffer.Vertices[7] = video::S3DVertex(25,-0.25,0.25, -1,-1, 1, XColor, 1, 1); XMeshBuffer.BoundingBox.reset(0,0,0); } void AxesSceneNode::setAxesScale(f32 scale) { ZMeshBuffer.Vertices.set_used(8); ZMeshBuffer.Material.Wireframe = false; ZMeshBuffer.Material.Lighting = false; ZMeshBuffer.Vertices[0] = video::S3DVertex(-0.25,-0.25,0, -1,-1,-1, ZColor, 0, 1); ZMeshBuffer.Vertices[1] = video::S3DVertex(0.25,-0.25,0, 1,-1,-1, ZColor, 1, 1); ZMeshBuffer.Vertices[2] = video::S3DVertex(0.25,0.25,0, 1, 1,-1, ZColor, 1, 0); ZMeshBuffer.Vertices[3] = video::S3DVertex(-0.25,0.25,0, -1, 1,-1, ZColor, 0, 0); ZMeshBuffer.Vertices[4] = video::S3DVertex(0.25,-0.25,scale, 1,-1, 1, ZColor, 0, 1); ZMeshBuffer.Vertices[5] = video::S3DVertex(0.25,0.25,scale, 1, 1, 1, ZColor, 0, 0); ZMeshBuffer.Vertices[6] = video::S3DVertex(-0.25,0.25,scale, -1, 1, 1, ZColor, 1, 0); ZMeshBuffer.Vertices[7] = video::S3DVertex(-0.25,-0.25,scale, -1,-1, 1, ZColor, 1, 1); ZMeshBuffer.BoundingBox.reset(0,0,0); YMeshBuffer.Vertices.set_used(8); YMeshBuffer.Material.Wireframe = false; YMeshBuffer.Material.Lighting = false; YMeshBuffer.Vertices[0] = video::S3DVertex(-0.25,0,0.25, -1,-1,-1, YColor, 0, 1); YMeshBuffer.Vertices[1] = video::S3DVertex(0.25,0,0.25, 1,-1,-1, YColor, 1, 1); YMeshBuffer.Vertices[2] = video::S3DVertex(0.25,0,-0.25, 1, 1,-1, YColor, 1, 0); YMeshBuffer.Vertices[3] = video::S3DVertex(-0.25,0,-0.25, -1, 1,-1, YColor, 0, 0); YMeshBuffer.Vertices[4] = video::S3DVertex(0.25,scale,0.25, 1,-1, 1, YColor, 0, 1); YMeshBuffer.Vertices[5] = video::S3DVertex(0.25,scale,-0.25, 1, 1, 1, YColor, 0, 0); YMeshBuffer.Vertices[6] = video::S3DVertex(-0.25,scale,-0.25, -1, 1, 1, YColor, 1, 0); YMeshBuffer.Vertices[7] = video::S3DVertex(-0.25,scale,0.25, -1,-1, 1, YColor, 1, 1); YMeshBuffer.BoundingBox.reset(0,0,0); XMeshBuffer.Vertices.set_used(8); XMeshBuffer.Material.Wireframe = false; XMeshBuffer.Material.Lighting = false; XMeshBuffer.Vertices[0] = video::S3DVertex(0,-0.25,0.25, -1,-1,-1, XColor, 0, 1); XMeshBuffer.Vertices[1] = video::S3DVertex(0,-0.25,-0.25, 1,-1,-1, XColor, 1, 1); XMeshBuffer.Vertices[2] = video::S3DVertex(0,0.25,-0.25, 1, 1,-1, XColor, 1, 0); XMeshBuffer.Vertices[3] = video::S3DVertex(0,0.25,0.25, -1, 1,-1, XColor, 0, 0); XMeshBuffer.Vertices[4] = video::S3DVertex(scale,-0.25,-0.25, 1,-1, 1, XColor, 0, 1); XMeshBuffer.Vertices[5] = video::S3DVertex(scale,0.25,-0.25, 1, 1, 1, XColor, 0, 0); XMeshBuffer.Vertices[6] = video::S3DVertex(scale,0.25,0.25, -1, 1, 1, XColor, 1, 0); XMeshBuffer.Vertices[7] = video::S3DVertex(scale,-0.25,0.25, -1,-1, 1, XColor, 1, 1); XMeshBuffer.BoundingBox.reset(0,0,0); } }; } ;//end OpenNero
// Copyright (c) 2011-2015 The Newcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "arith_uint256.h" #include "uint256.h" #include "version.h" #include "test/test_newcoin.h" #include <boost/test/unit_test.hpp> #include <stdint.h> #include <sstream> #include <iomanip> #include <limits> #include <cmath> #include <string> #include <stdio.h> BOOST_FIXTURE_TEST_SUITE(uint256_tests, BasicTestingSetup) const unsigned char R1Array[] = "\x9c\x52\x4a\xdb\xcf\x56\x11\x12\x2b\x29\x12\x5e\x5d\x35\xd2\xd2" "\x22\x81\xaa\xb5\x33\xf0\x08\x32\xd5\x56\xb1\xf9\xea\xe5\x1d\x7d"; const char R1ArrayHex[] = "7D1DE5EAF9B156D53208F033B5AA8122D2d2355d5e12292b121156cfdb4a529c"; const uint256 R1L = uint256(std::vector<unsigned char>(R1Array,R1Array+32)); const uint160 R1S = uint160(std::vector<unsigned char>(R1Array,R1Array+20)); const unsigned char R2Array[] = "\x70\x32\x1d\x7c\x47\xa5\x6b\x40\x26\x7e\x0a\xc3\xa6\x9c\xb6\xbf" "\x13\x30\x47\xa3\x19\x2d\xda\x71\x49\x13\x72\xf0\xb4\xca\x81\xd7"; const uint256 R2L = uint256(std::vector<unsigned char>(R2Array,R2Array+32)); const uint160 R2S = uint160(std::vector<unsigned char>(R2Array,R2Array+20)); const unsigned char ZeroArray[] = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"; const uint256 ZeroL = uint256(std::vector<unsigned char>(ZeroArray,ZeroArray+32)); const uint160 ZeroS = uint160(std::vector<unsigned char>(ZeroArray,ZeroArray+20)); const unsigned char OneArray[] = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"; const uint256 OneL = uint256(std::vector<unsigned char>(OneArray,OneArray+32)); const uint160 OneS = uint160(std::vector<unsigned char>(OneArray,OneArray+20)); const unsigned char MaxArray[] = "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff"; const uint256 MaxL = uint256(std::vector<unsigned char>(MaxArray,MaxArray+32)); const uint160 MaxS = uint160(std::vector<unsigned char>(MaxArray,MaxArray+20)); std::string ArrayToString(const unsigned char A[], unsigned int width) { std::stringstream Stream; Stream << std::hex; for (unsigned int i = 0; i < width; ++i) { Stream<<std::setw(2)<<std::setfill('0')<<(unsigned int)A[width-i-1]; } return Stream.str(); } inline uint160 uint160S(const char *str) { uint160 rv; rv.SetHex(str); return rv; } inline uint160 uint160S(const std::string& str) { uint160 rv; rv.SetHex(str); return rv; } BOOST_AUTO_TEST_CASE( basics ) // constructors, equality, inequality { BOOST_CHECK(1 == 0+1); // constructor uint256(vector<char>): BOOST_CHECK(R1L.ToString() == ArrayToString(R1Array,32)); BOOST_CHECK(R1S.ToString() == ArrayToString(R1Array,20)); BOOST_CHECK(R2L.ToString() == ArrayToString(R2Array,32)); BOOST_CHECK(R2S.ToString() == ArrayToString(R2Array,20)); BOOST_CHECK(ZeroL.ToString() == ArrayToString(ZeroArray,32)); BOOST_CHECK(ZeroS.ToString() == ArrayToString(ZeroArray,20)); BOOST_CHECK(OneL.ToString() == ArrayToString(OneArray,32)); BOOST_CHECK(OneS.ToString() == ArrayToString(OneArray,20)); BOOST_CHECK(MaxL.ToString() == ArrayToString(MaxArray,32)); BOOST_CHECK(MaxS.ToString() == ArrayToString(MaxArray,20)); BOOST_CHECK(OneL.ToString() != ArrayToString(ZeroArray,32)); BOOST_CHECK(OneS.ToString() != ArrayToString(ZeroArray,20)); // == and != BOOST_CHECK(R1L != R2L && R1S != R2S); BOOST_CHECK(ZeroL != OneL && ZeroS != OneS); BOOST_CHECK(OneL != ZeroL && OneS != ZeroS); BOOST_CHECK(MaxL != ZeroL && MaxS != ZeroS); // String Constructor and Copy Constructor BOOST_CHECK(uint256S("0x"+R1L.ToString()) == R1L); BOOST_CHECK(uint256S("0x"+R2L.ToString()) == R2L); BOOST_CHECK(uint256S("0x"+ZeroL.ToString()) == ZeroL); BOOST_CHECK(uint256S("0x"+OneL.ToString()) == OneL); BOOST_CHECK(uint256S("0x"+MaxL.ToString()) == MaxL); BOOST_CHECK(uint256S(R1L.ToString()) == R1L); BOOST_CHECK(uint256S(" 0x"+R1L.ToString()+" ") == R1L); BOOST_CHECK(uint256S("") == ZeroL); BOOST_CHECK(R1L == uint256S(R1ArrayHex)); BOOST_CHECK(uint256(R1L) == R1L); BOOST_CHECK(uint256(ZeroL) == ZeroL); BOOST_CHECK(uint256(OneL) == OneL); BOOST_CHECK(uint160S("0x"+R1S.ToString()) == R1S); BOOST_CHECK(uint160S("0x"+R2S.ToString()) == R2S); BOOST_CHECK(uint160S("0x"+ZeroS.ToString()) == ZeroS); BOOST_CHECK(uint160S("0x"+OneS.ToString()) == OneS); BOOST_CHECK(uint160S("0x"+MaxS.ToString()) == MaxS); BOOST_CHECK(uint160S(R1S.ToString()) == R1S); BOOST_CHECK(uint160S(" 0x"+R1S.ToString()+" ") == R1S); BOOST_CHECK(uint160S("") == ZeroS); BOOST_CHECK(R1S == uint160S(R1ArrayHex)); BOOST_CHECK(uint160(R1S) == R1S); BOOST_CHECK(uint160(ZeroS) == ZeroS); BOOST_CHECK(uint160(OneS) == OneS); } BOOST_AUTO_TEST_CASE( comparison ) // <= >= < > { uint256 LastL; for (int i = 255; i >= 0; --i) { uint256 TmpL; *(TmpL.begin() + (i>>3)) |= 1<<(7-(i&7)); BOOST_CHECK( LastL < TmpL ); LastL = TmpL; } BOOST_CHECK( ZeroL < R1L ); BOOST_CHECK( R2L < R1L ); BOOST_CHECK( ZeroL < OneL ); BOOST_CHECK( OneL < MaxL ); BOOST_CHECK( R1L < MaxL ); BOOST_CHECK( R2L < MaxL ); uint160 LastS; for (int i = 159; i >= 0; --i) { uint160 TmpS; *(TmpS.begin() + (i>>3)) |= 1<<(7-(i&7)); BOOST_CHECK( LastS < TmpS ); LastS = TmpS; } BOOST_CHECK( ZeroS < R1S ); BOOST_CHECK( R2S < R1S ); BOOST_CHECK( ZeroS < OneS ); BOOST_CHECK( OneS < MaxS ); BOOST_CHECK( R1S < MaxS ); BOOST_CHECK( R2S < MaxS ); } BOOST_AUTO_TEST_CASE( methods ) // GetHex SetHex begin() end() size() GetLow64 GetSerializeSize, Serialize, Unserialize { BOOST_CHECK(R1L.GetHex() == R1L.ToString()); BOOST_CHECK(R2L.GetHex() == R2L.ToString()); BOOST_CHECK(OneL.GetHex() == OneL.ToString()); BOOST_CHECK(MaxL.GetHex() == MaxL.ToString()); uint256 TmpL(R1L); BOOST_CHECK(TmpL == R1L); TmpL.SetHex(R2L.ToString()); BOOST_CHECK(TmpL == R2L); TmpL.SetHex(ZeroL.ToString()); BOOST_CHECK(TmpL == uint256()); TmpL.SetHex(R1L.ToString()); BOOST_CHECK(memcmp(R1L.begin(), R1Array, 32)==0); BOOST_CHECK(memcmp(TmpL.begin(), R1Array, 32)==0); BOOST_CHECK(memcmp(R2L.begin(), R2Array, 32)==0); BOOST_CHECK(memcmp(ZeroL.begin(), ZeroArray, 32)==0); BOOST_CHECK(memcmp(OneL.begin(), OneArray, 32)==0); BOOST_CHECK(R1L.size() == sizeof(R1L)); BOOST_CHECK(sizeof(R1L) == 32); BOOST_CHECK(R1L.size() == 32); BOOST_CHECK(R2L.size() == 32); BOOST_CHECK(ZeroL.size() == 32); BOOST_CHECK(MaxL.size() == 32); BOOST_CHECK(R1L.begin() + 32 == R1L.end()); BOOST_CHECK(R2L.begin() + 32 == R2L.end()); BOOST_CHECK(OneL.begin() + 32 == OneL.end()); BOOST_CHECK(MaxL.begin() + 32 == MaxL.end()); BOOST_CHECK(TmpL.begin() + 32 == TmpL.end()); BOOST_CHECK(R1L.GetSerializeSize(0,PROTOCOL_VERSION) == 32); BOOST_CHECK(ZeroL.GetSerializeSize(0,PROTOCOL_VERSION) == 32); std::stringstream ss; R1L.Serialize(ss,0,PROTOCOL_VERSION); BOOST_CHECK(ss.str() == std::string(R1Array,R1Array+32)); TmpL.Unserialize(ss,0,PROTOCOL_VERSION); BOOST_CHECK(R1L == TmpL); ss.str(""); ZeroL.Serialize(ss,0,PROTOCOL_VERSION); BOOST_CHECK(ss.str() == std::string(ZeroArray,ZeroArray+32)); TmpL.Unserialize(ss,0,PROTOCOL_VERSION); BOOST_CHECK(ZeroL == TmpL); ss.str(""); MaxL.Serialize(ss,0,PROTOCOL_VERSION); BOOST_CHECK(ss.str() == std::string(MaxArray,MaxArray+32)); TmpL.Unserialize(ss,0,PROTOCOL_VERSION); BOOST_CHECK(MaxL == TmpL); ss.str(""); BOOST_CHECK(R1S.GetHex() == R1S.ToString()); BOOST_CHECK(R2S.GetHex() == R2S.ToString()); BOOST_CHECK(OneS.GetHex() == OneS.ToString()); BOOST_CHECK(MaxS.GetHex() == MaxS.ToString()); uint160 TmpS(R1S); BOOST_CHECK(TmpS == R1S); TmpS.SetHex(R2S.ToString()); BOOST_CHECK(TmpS == R2S); TmpS.SetHex(ZeroS.ToString()); BOOST_CHECK(TmpS == uint160()); TmpS.SetHex(R1S.ToString()); BOOST_CHECK(memcmp(R1S.begin(), R1Array, 20)==0); BOOST_CHECK(memcmp(TmpS.begin(), R1Array, 20)==0); BOOST_CHECK(memcmp(R2S.begin(), R2Array, 20)==0); BOOST_CHECK(memcmp(ZeroS.begin(), ZeroArray, 20)==0); BOOST_CHECK(memcmp(OneS.begin(), OneArray, 20)==0); BOOST_CHECK(R1S.size() == sizeof(R1S)); BOOST_CHECK(sizeof(R1S) == 20); BOOST_CHECK(R1S.size() == 20); BOOST_CHECK(R2S.size() == 20); BOOST_CHECK(ZeroS.size() == 20); BOOST_CHECK(MaxS.size() == 20); BOOST_CHECK(R1S.begin() + 20 == R1S.end()); BOOST_CHECK(R2S.begin() + 20 == R2S.end()); BOOST_CHECK(OneS.begin() + 20 == OneS.end()); BOOST_CHECK(MaxS.begin() + 20 == MaxS.end()); BOOST_CHECK(TmpS.begin() + 20 == TmpS.end()); BOOST_CHECK(R1S.GetSerializeSize(0,PROTOCOL_VERSION) == 20); BOOST_CHECK(ZeroS.GetSerializeSize(0,PROTOCOL_VERSION) == 20); R1S.Serialize(ss,0,PROTOCOL_VERSION); BOOST_CHECK(ss.str() == std::string(R1Array,R1Array+20)); TmpS.Unserialize(ss,0,PROTOCOL_VERSION); BOOST_CHECK(R1S == TmpS); ss.str(""); ZeroS.Serialize(ss,0,PROTOCOL_VERSION); BOOST_CHECK(ss.str() == std::string(ZeroArray,ZeroArray+20)); TmpS.Unserialize(ss,0,PROTOCOL_VERSION); BOOST_CHECK(ZeroS == TmpS); ss.str(""); MaxS.Serialize(ss,0,PROTOCOL_VERSION); BOOST_CHECK(ss.str() == std::string(MaxArray,MaxArray+20)); TmpS.Unserialize(ss,0,PROTOCOL_VERSION); BOOST_CHECK(MaxS == TmpS); ss.str(""); } BOOST_AUTO_TEST_CASE( conversion ) { BOOST_CHECK(ArithToUint256(UintToArith256(ZeroL)) == ZeroL); BOOST_CHECK(ArithToUint256(UintToArith256(OneL)) == OneL); BOOST_CHECK(ArithToUint256(UintToArith256(R1L)) == R1L); BOOST_CHECK(ArithToUint256(UintToArith256(R2L)) == R2L); BOOST_CHECK(UintToArith256(ZeroL) == 0); BOOST_CHECK(UintToArith256(OneL) == 1); BOOST_CHECK(ArithToUint256(0) == ZeroL); BOOST_CHECK(ArithToUint256(1) == OneL); BOOST_CHECK(arith_uint256(R1L.GetHex()) == UintToArith256(R1L)); BOOST_CHECK(arith_uint256(R2L.GetHex()) == UintToArith256(R2L)); BOOST_CHECK(R1L.GetHex() == UintToArith256(R1L).GetHex()); BOOST_CHECK(R2L.GetHex() == UintToArith256(R2L).GetHex()); } BOOST_AUTO_TEST_SUITE_END()
/* * Copyright (C) 2019 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "runtime/execution_environment/execution_environment.h" #include "runtime/memory_manager/os_agnostic_memory_manager.h" #include "runtime/os_interface/linux/drm_memory_manager.h" #include "runtime/os_interface/linux/os_interface.h" #include "runtime/os_interface/os_interface.h" #include "unit_tests/libult/create_command_stream.h" namespace NEO { bool overrideMemoryManagerCreation = true; std::unique_ptr<MemoryManager> MemoryManager::createMemoryManager(ExecutionEnvironment &executionEnvironment) { if (overrideMemoryManagerCreation) { return std::make_unique<OsAgnosticMemoryManager>(executionEnvironment); } return std::make_unique<DrmMemoryManager>(gemCloseWorkerMode::gemCloseWorkerInactive, DebugManager.flags.EnableForcePin.get(), true, executionEnvironment); } } // namespace NEO
/**************************************************************************** * * Copyright (c) 2012-2015 PX4 Development Team. 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 PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file fmu.cpp * * Driver/configurator for the PX4 FMU multi-purpose port on v1 and v2 boards. */ #include <px4_config.h> #include <sys/types.h> #include <stdint.h> #include <stdbool.h> #include <stdlib.h> #include <semaphore.h> #include <string.h> #include <fcntl.h> #include <poll.h> #include <errno.h> #include <stdio.h> #include <math.h> #include <unistd.h> #include <nuttx/arch.h> #include <drivers/device/device.h> #include <drivers/device/i2c.h> #include <drivers/drv_pwm_output.h> #include <drivers/drv_gpio.h> #include <drivers/drv_hrt.h> #include <board_config.h> #include <systemlib/systemlib.h> #include <systemlib/err.h> #include <systemlib/mixer/mixer.h> #include <systemlib/pwm_limit/pwm_limit.h> #include <systemlib/board_serial.h> #include <systemlib/param/param.h> #include <drivers/drv_mixer.h> #include <drivers/drv_rc_input.h> #include <uORB/topics/actuator_controls.h> #include <uORB/topics/actuator_controls_0.h> #include <uORB/topics/actuator_controls_1.h> #include <uORB/topics/actuator_controls_2.h> #include <uORB/topics/actuator_controls_3.h> #include <uORB/topics/actuator_outputs.h> #include <uORB/topics/actuator_armed.h> #include <uORB/topics/parameter_update.h> #ifdef HRT_PPM_CHANNEL # include <systemlib/ppm_decode.h> #endif /* * This is the analog to FMU_INPUT_DROP_LIMIT_US on the IO side */ #define CONTROL_INPUT_DROP_LIMIT_MS 20 #define NAN_VALUE (0.0f/0.0f) class PX4FMU : public device::CDev { public: enum Mode { MODE_NONE, MODE_2PWM, MODE_4PWM, MODE_6PWM, MODE_8PWM, }; PX4FMU(); virtual ~PX4FMU(); virtual int ioctl(file *filp, int cmd, unsigned long arg); virtual ssize_t write(file *filp, const char *buffer, size_t len); virtual int init(); int set_mode(Mode mode); int set_pwm_alt_rate(unsigned rate); int set_pwm_alt_channels(uint32_t channels); int set_i2c_bus_clock(unsigned bus, unsigned clock_hz); private: #if defined(CONFIG_ARCH_BOARD_PX4FMU_V1) static const unsigned _max_actuators = 4; #endif #if defined(CONFIG_ARCH_BOARD_PX4FMU_V2) static const unsigned _max_actuators = 6; #endif #if defined(CONFIG_ARCH_BOARD_AEROCORE) static const unsigned _max_actuators = 8; #endif Mode _mode; unsigned _pwm_default_rate; unsigned _pwm_alt_rate; uint32_t _pwm_alt_rate_channels; unsigned _current_update_rate; int _task; int _armed_sub; int _param_sub; orb_advert_t _outputs_pub; unsigned _num_outputs; int _class_instance; volatile bool _task_should_exit; bool _servo_armed; bool _pwm_on; MixerGroup *_mixers; uint32_t _groups_required; uint32_t _groups_subscribed; int _control_subs[actuator_controls_s::NUM_ACTUATOR_CONTROL_GROUPS]; actuator_controls_s _controls[actuator_controls_s::NUM_ACTUATOR_CONTROL_GROUPS]; orb_id_t _control_topics[actuator_controls_s::NUM_ACTUATOR_CONTROL_GROUPS]; int _actuator_output_topic_instance; pollfd _poll_fds[actuator_controls_s::NUM_ACTUATOR_CONTROL_GROUPS]; unsigned _poll_fds_num; static pwm_limit_t _pwm_limit; static actuator_armed_s _armed; uint16_t _failsafe_pwm[_max_actuators]; uint16_t _disarmed_pwm[_max_actuators]; uint16_t _min_pwm[_max_actuators]; uint16_t _max_pwm[_max_actuators]; uint16_t _reverse_pwm_mask; unsigned _num_failsafe_set; unsigned _num_disarmed_set; static bool arm_nothrottle() { return (_armed.ready_to_arm && !_armed.armed); } static void task_main_trampoline(int argc, char *argv[]); void task_main(); static int control_callback(uintptr_t handle, uint8_t control_group, uint8_t control_index, float &input); void subscribe(); int set_pwm_rate(unsigned rate_map, unsigned default_rate, unsigned alt_rate); int pwm_ioctl(file *filp, int cmd, unsigned long arg); void update_pwm_rev_mask(); struct GPIOConfig { uint32_t input; uint32_t output; uint32_t alt; }; static const GPIOConfig _gpio_tab[]; static const unsigned _ngpio; void gpio_reset(void); void sensor_reset(int ms); void peripheral_reset(int ms); void gpio_set_function(uint32_t gpios, int function); void gpio_write(uint32_t gpios, int function); uint32_t gpio_read(void); int gpio_ioctl(file *filp, int cmd, unsigned long arg); /* do not allow to copy due to ptr data members */ PX4FMU(const PX4FMU&); PX4FMU operator=(const PX4FMU&); }; const PX4FMU::GPIOConfig PX4FMU::_gpio_tab[] = { #if defined(CONFIG_ARCH_BOARD_PX4FMU_V1) {GPIO_GPIO0_INPUT, GPIO_GPIO0_OUTPUT, 0}, {GPIO_GPIO1_INPUT, GPIO_GPIO1_OUTPUT, 0}, {GPIO_GPIO2_INPUT, GPIO_GPIO2_OUTPUT, GPIO_USART2_CTS_1}, {GPIO_GPIO3_INPUT, GPIO_GPIO3_OUTPUT, GPIO_USART2_RTS_1}, {GPIO_GPIO4_INPUT, GPIO_GPIO4_OUTPUT, GPIO_USART2_TX_1}, {GPIO_GPIO5_INPUT, GPIO_GPIO5_OUTPUT, GPIO_USART2_RX_1}, {GPIO_GPIO6_INPUT, GPIO_GPIO6_OUTPUT, GPIO_CAN2_TX_2}, {GPIO_GPIO7_INPUT, GPIO_GPIO7_OUTPUT, GPIO_CAN2_RX_2}, #endif #if defined(CONFIG_ARCH_BOARD_PX4FMU_V2) {GPIO_GPIO0_INPUT, GPIO_GPIO0_OUTPUT, 0}, {GPIO_GPIO1_INPUT, GPIO_GPIO1_OUTPUT, 0}, {GPIO_GPIO2_INPUT, GPIO_GPIO2_OUTPUT, 0}, {GPIO_GPIO3_INPUT, GPIO_GPIO3_OUTPUT, 0}, {GPIO_GPIO4_INPUT, GPIO_GPIO4_OUTPUT, 0}, {GPIO_GPIO5_INPUT, GPIO_GPIO5_OUTPUT, 0}, {0, GPIO_VDD_5V_PERIPH_EN, 0}, {0, GPIO_VDD_3V3_SENSORS_EN, 0}, {GPIO_VDD_BRICK_VALID, 0, 0}, {GPIO_VDD_SERVO_VALID, 0, 0}, {GPIO_VDD_5V_HIPOWER_OC, 0, 0}, {GPIO_VDD_5V_PERIPH_OC, 0, 0}, #endif #if defined(CONFIG_ARCH_BOARD_AEROCORE) /* AeroCore breaks out User GPIOs on J11 */ {GPIO_GPIO0_INPUT, GPIO_GPIO0_OUTPUT, 0}, {GPIO_GPIO1_INPUT, GPIO_GPIO1_OUTPUT, 0}, {GPIO_GPIO3_INPUT, GPIO_GPIO3_OUTPUT, 0}, {GPIO_GPIO4_INPUT, GPIO_GPIO4_OUTPUT, 0}, {GPIO_GPIO5_INPUT, GPIO_GPIO5_OUTPUT, 0}, {GPIO_GPIO6_INPUT, GPIO_GPIO6_OUTPUT, 0}, {GPIO_GPIO7_INPUT, GPIO_GPIO7_OUTPUT, 0}, {GPIO_GPIO8_INPUT, GPIO_GPIO8_OUTPUT, 0}, {GPIO_GPIO9_INPUT, GPIO_GPIO9_OUTPUT, 0}, {GPIO_GPIO10_INPUT, GPIO_GPIO10_OUTPUT, 0}, {GPIO_GPIO11_INPUT, GPIO_GPIO11_OUTPUT, 0}, #endif }; const unsigned PX4FMU::_ngpio = sizeof(PX4FMU::_gpio_tab) / sizeof(PX4FMU::_gpio_tab[0]); pwm_limit_t PX4FMU::_pwm_limit; actuator_armed_s PX4FMU::_armed = {}; namespace { PX4FMU *g_fmu; } // namespace PX4FMU::PX4FMU() : CDev("fmuservo", PX4FMU_DEVICE_PATH), _mode(MODE_NONE), _pwm_default_rate(50), _pwm_alt_rate(50), _pwm_alt_rate_channels(0), _current_update_rate(0), _task(-1), _armed_sub(-1), _param_sub(-1), _outputs_pub(nullptr), _num_outputs(0), _class_instance(0), _task_should_exit(false), _servo_armed(false), _pwm_on(false), _mixers(nullptr), _groups_required(0), _groups_subscribed(0), _control_subs{-1}, _actuator_output_topic_instance(-1), _poll_fds_num(0), _failsafe_pwm{0}, _disarmed_pwm{0}, _reverse_pwm_mask(0), _num_failsafe_set(0), _num_disarmed_set(0) { for (unsigned i = 0; i < _max_actuators; i++) { _min_pwm[i] = PWM_DEFAULT_MIN; _max_pwm[i] = PWM_DEFAULT_MAX; } _control_topics[0] = ORB_ID(actuator_controls_0); _control_topics[1] = ORB_ID(actuator_controls_1); _control_topics[2] = ORB_ID(actuator_controls_2); _control_topics[3] = ORB_ID(actuator_controls_3); memset(_controls, 0, sizeof(_controls)); memset(_poll_fds, 0, sizeof(_poll_fds)); _debug_enabled = true; } PX4FMU::~PX4FMU() { if (_task != -1) { /* tell the task we want it to go away */ _task_should_exit = true; unsigned i = 10; do { /* wait 50ms - it should wake every 100ms or so worst-case */ usleep(50000); /* if we have given up, kill it */ if (--i == 0) { task_delete(_task); break; } } while (_task != -1); } /* clean up the alternate device node */ unregister_class_devname(PWM_OUTPUT_BASE_DEVICE_PATH, _class_instance); g_fmu = nullptr; } int PX4FMU::init() { int ret; ASSERT(_task == -1); /* do regular cdev init */ ret = CDev::init(); if (ret != OK) return ret; /* try to claim the generic PWM output device node as well - it's OK if we fail at this */ _class_instance = register_class_devname(PWM_OUTPUT_BASE_DEVICE_PATH); if (_class_instance == CLASS_DEVICE_PRIMARY) { log("default PWM output device"); } else if (_class_instance < 0) { log("FAILED registering class device"); } /* reset GPIOs */ gpio_reset(); /* start the IO interface task */ _task = px4_task_spawn_cmd("fmuservo", SCHED_DEFAULT, SCHED_PRIORITY_DEFAULT, 1600, (main_t)&PX4FMU::task_main_trampoline, nullptr); if (_task < 0) { debug("task start failed: %d", errno); return -errno; } return OK; } void PX4FMU::task_main_trampoline(int argc, char *argv[]) { g_fmu->task_main(); } int PX4FMU::set_mode(Mode mode) { /* * Configure for PWM output. * * Note that regardless of the configured mode, the task is always * listening and mixing; the mode just selects which of the channels * are presented on the output pins. */ switch (mode) { case MODE_2PWM: // v1 multi-port with flow control lines as PWM debug("MODE_2PWM"); /* default output rates */ _pwm_default_rate = 50; _pwm_alt_rate = 50; _pwm_alt_rate_channels = 0; /* XXX magic numbers */ up_pwm_servo_init(0x3); set_pwm_rate(_pwm_alt_rate_channels, _pwm_default_rate, _pwm_alt_rate); break; case MODE_4PWM: // v1 multi-port as 4 PWM outs debug("MODE_4PWM"); /* default output rates */ _pwm_default_rate = 50; _pwm_alt_rate = 50; _pwm_alt_rate_channels = 0; /* XXX magic numbers */ up_pwm_servo_init(0xf); set_pwm_rate(_pwm_alt_rate_channels, _pwm_default_rate, _pwm_alt_rate); break; case MODE_6PWM: // v2 PWMs as 6 PWM outs debug("MODE_6PWM"); /* default output rates */ _pwm_default_rate = 50; _pwm_alt_rate = 50; _pwm_alt_rate_channels = 0; /* XXX magic numbers */ up_pwm_servo_init(0x3f); set_pwm_rate(_pwm_alt_rate_channels, _pwm_default_rate, _pwm_alt_rate); break; #ifdef CONFIG_ARCH_BOARD_AEROCORE case MODE_8PWM: // AeroCore PWMs as 8 PWM outs debug("MODE_8PWM"); /* default output rates */ _pwm_default_rate = 50; _pwm_alt_rate = 50; _pwm_alt_rate_channels = 0; /* XXX magic numbers */ up_pwm_servo_init(0xff); set_pwm_rate(_pwm_alt_rate_channels, _pwm_default_rate, _pwm_alt_rate); break; #endif case MODE_NONE: debug("MODE_NONE"); _pwm_default_rate = 10; /* artificially reduced output rate */ _pwm_alt_rate = 10; _pwm_alt_rate_channels = 0; /* disable servo outputs - no need to set rates */ up_pwm_servo_deinit(); break; default: return -EINVAL; } _mode = mode; return OK; } int PX4FMU::set_pwm_rate(uint32_t rate_map, unsigned default_rate, unsigned alt_rate) { debug("set_pwm_rate %x %u %u", rate_map, default_rate, alt_rate); for (unsigned pass = 0; pass < 2; pass++) { for (unsigned group = 0; group < _max_actuators; group++) { // get the channel mask for this rate group uint32_t mask = up_pwm_servo_get_rate_group(group); if (mask == 0) continue; // all channels in the group must be either default or alt-rate uint32_t alt = rate_map & mask; if (pass == 0) { // preflight if ((alt != 0) && (alt != mask)) { warn("rate group %u mask %x bad overlap %x", group, mask, alt); // not a legal map, bail return -EINVAL; } } else { // set it - errors here are unexpected if (alt != 0) { if (up_pwm_servo_set_rate_group_update(group, _pwm_alt_rate) != OK) { warn("rate group set alt failed"); return -EINVAL; } } else { if (up_pwm_servo_set_rate_group_update(group, _pwm_default_rate) != OK) { warn("rate group set default failed"); return -EINVAL; } } } } } _pwm_alt_rate_channels = rate_map; _pwm_default_rate = default_rate; _pwm_alt_rate = alt_rate; return OK; } int PX4FMU::set_pwm_alt_rate(unsigned rate) { return set_pwm_rate(_pwm_alt_rate_channels, _pwm_default_rate, rate); } int PX4FMU::set_pwm_alt_channels(uint32_t channels) { return set_pwm_rate(channels, _pwm_default_rate, _pwm_alt_rate); } int PX4FMU::set_i2c_bus_clock(unsigned bus, unsigned clock_hz) { return device::I2C::set_bus_clock(bus, clock_hz); } void PX4FMU::subscribe() { /* subscribe/unsubscribe to required actuator control groups */ uint32_t sub_groups = _groups_required & ~_groups_subscribed; uint32_t unsub_groups = _groups_subscribed & ~_groups_required; _poll_fds_num = 0; for (unsigned i = 0; i < actuator_controls_s::NUM_ACTUATOR_CONTROL_GROUPS; i++) { if (sub_groups & (1 << i)) { warnx("subscribe to actuator_controls_%d", i); _control_subs[i] = orb_subscribe(_control_topics[i]); } if (unsub_groups & (1 << i)) { warnx("unsubscribe from actuator_controls_%d", i); ::close(_control_subs[i]); _control_subs[i] = -1; } if (_control_subs[i] > 0) { _poll_fds[_poll_fds_num].fd = _control_subs[i]; _poll_fds[_poll_fds_num].events = POLLIN; _poll_fds_num++; } } } void PX4FMU::update_pwm_rev_mask() { _reverse_pwm_mask = 0; for (unsigned i = 0; i < _max_actuators; i++) { char pname[16]; int32_t ival; /* fill the channel reverse mask from parameters */ sprintf(pname, "PWM_AUX_REV%d", i + 1); param_t param_h = param_find(pname); if (param_h != PARAM_INVALID) { param_get(param_h, &ival); _reverse_pwm_mask |= ((int16_t)(ival != 0)) << i; } } } void PX4FMU::task_main() { /* force a reset of the update rate */ _current_update_rate = 0; _armed_sub = orb_subscribe(ORB_ID(actuator_armed)); _param_sub = orb_subscribe(ORB_ID(parameter_update)); /* advertise the mixed control outputs */ actuator_outputs_s outputs; memset(&outputs, 0, sizeof(outputs)); #ifdef HRT_PPM_CHANNEL // rc input, published to ORB struct rc_input_values rc_in; orb_advert_t to_input_rc = 0; memset(&rc_in, 0, sizeof(rc_in)); rc_in.input_source = RC_INPUT_SOURCE_PX4FMU_PPM; #endif /* initialize PWM limit lib */ pwm_limit_init(&_pwm_limit); update_pwm_rev_mask(); /* loop until killed */ while (!_task_should_exit) { if (_groups_subscribed != _groups_required) { subscribe(); _groups_subscribed = _groups_required; /* force setting update rate */ _current_update_rate = 0; } /* * Adjust actuator topic update rate to keep up with * the highest servo update rate configured. * * We always mix at max rate; some channels may update slower. */ unsigned max_rate = (_pwm_default_rate > _pwm_alt_rate) ? _pwm_default_rate : _pwm_alt_rate; if (_current_update_rate != max_rate) { _current_update_rate = max_rate; int update_rate_in_ms = int(1000 / _current_update_rate); /* reject faster than 500 Hz updates */ if (update_rate_in_ms < 2) { update_rate_in_ms = 2; } /* reject slower than 10 Hz updates */ if (update_rate_in_ms > 100) { update_rate_in_ms = 100; } debug("adjusted actuator update interval to %ums", update_rate_in_ms); for (unsigned i = 0; i < actuator_controls_s::NUM_ACTUATOR_CONTROL_GROUPS; i++) { if (_control_subs[i] > 0) { orb_set_interval(_control_subs[i], update_rate_in_ms); } } // set to current max rate, even if we are actually checking slower/faster _current_update_rate = max_rate; } /* sleep waiting for data, stopping to check for PPM * input at 50Hz */ int ret = ::poll(_poll_fds, _poll_fds_num, CONTROL_INPUT_DROP_LIMIT_MS); /* this would be bad... */ if (ret < 0) { log("poll error %d", errno); continue; } else if (ret == 0) { /* timeout: no control data, switch to failsafe values */ // warnx("no PWM: failsafe"); } else { /* get controls for required topics */ unsigned poll_id = 0; for (unsigned i = 0; i < actuator_controls_s::NUM_ACTUATOR_CONTROL_GROUPS; i++) { if (_control_subs[i] > 0) { if (_poll_fds[poll_id].revents & POLLIN) { orb_copy(_control_topics[i], _control_subs[i], &_controls[i]); } poll_id++; } } /* can we mix? */ if (_mixers != nullptr) { unsigned num_outputs; switch (_mode) { case MODE_2PWM: num_outputs = 2; break; case MODE_4PWM: num_outputs = 4; break; case MODE_6PWM: num_outputs = 6; break; case MODE_8PWM: num_outputs = 8; break; default: num_outputs = 0; break; } /* do mixing */ outputs.noutputs = _mixers->mix(&outputs.output[0], num_outputs, NULL); outputs.timestamp = hrt_absolute_time(); /* disable unused ports by setting their output to NaN */ for (unsigned i = 0; i < num_outputs; i++) { if (i >= outputs.noutputs) { outputs.output[i] = NAN_VALUE; } } uint16_t pwm_limited[num_outputs]; /* the PWM limit call takes care of out of band errors, NaN and constrains */ pwm_limit_calc(_servo_armed, arm_nothrottle(), num_outputs, _reverse_pwm_mask, _disarmed_pwm, _min_pwm, _max_pwm, outputs.output, pwm_limited, &_pwm_limit); /* output to the servos */ for (unsigned i = 0; i < num_outputs; i++) { up_pwm_servo_set(i, pwm_limited[i]); } /* publish mixed control outputs */ if (_outputs_pub != nullptr) { _outputs_pub = orb_advertise_multi(ORB_ID(actuator_outputs), &outputs, &_actuator_output_topic_instance, ORB_PRIO_DEFAULT); } else { orb_publish(ORB_ID(actuator_outputs), _outputs_pub, &outputs); } } } /* check arming state */ bool updated = false; orb_check(_armed_sub, &updated); if (updated) { orb_copy(ORB_ID(actuator_armed), _armed_sub, &_armed); /* update the armed status and check that we're not locked down */ bool set_armed = (_armed.armed || _armed.ready_to_arm) && !_armed.lockdown; if (_servo_armed != set_armed) { _servo_armed = set_armed; } /* update PWM status if armed or if disarmed PWM values are set */ bool pwm_on = (set_armed || _num_disarmed_set > 0); if (_pwm_on != pwm_on) { _pwm_on = pwm_on; up_pwm_servo_arm(pwm_on); } } orb_check(_param_sub, &updated); if (updated) { parameter_update_s pupdate; orb_copy(ORB_ID(parameter_update), _param_sub, &pupdate); update_pwm_rev_mask(); } #ifdef HRT_PPM_CHANNEL // see if we have new PPM input data if (ppm_last_valid_decode != rc_in.timestamp_last_signal) { // we have a new PPM frame. Publish it. rc_in.channel_count = ppm_decoded_channels; if (rc_in.channel_count > RC_INPUT_MAX_CHANNELS) { rc_in.channel_count = RC_INPUT_MAX_CHANNELS; } for (uint8_t i = 0; i < rc_in.channel_count; i++) { rc_in.values[i] = ppm_buffer[i]; } rc_in.timestamp_publication = ppm_last_valid_decode; rc_in.timestamp_last_signal = ppm_last_valid_decode; rc_in.rc_ppm_frame_length = ppm_frame_length; rc_in.rssi = RC_INPUT_RSSI_MAX; rc_in.rc_failsafe = false; rc_in.rc_lost = false; rc_in.rc_lost_frame_count = 0; rc_in.rc_total_frame_count = 0; /* lazily advertise on first publication */ if (to_input_rc == 0) { to_input_rc = orb_advertise(ORB_ID(input_rc), &rc_in); } else { orb_publish(ORB_ID(input_rc), to_input_rc, &rc_in); } } #endif } for (unsigned i = 0; i < actuator_controls_s::NUM_ACTUATOR_CONTROL_GROUPS; i++) { if (_control_subs[i] > 0) { ::close(_control_subs[i]); _control_subs[i] = -1; } } ::close(_armed_sub); ::close(_param_sub); /* make sure servos are off */ up_pwm_servo_deinit(); log("stopping"); /* note - someone else is responsible for restoring the GPIO config */ /* tell the dtor that we are exiting */ _task = -1; _exit(0); } int PX4FMU::control_callback(uintptr_t handle, uint8_t control_group, uint8_t control_index, float &input) { const actuator_controls_s *controls = (actuator_controls_s *)handle; input = controls[control_group].control[control_index]; /* limit control input */ if (input > 1.0f) { input = 1.0f; } else if (input < -1.0f) { input = -1.0f; } /* motor spinup phase - lock throttle to zero */ if (_pwm_limit.state == PWM_LIMIT_STATE_RAMP) { if (control_group == actuator_controls_s::GROUP_INDEX_ATTITUDE && control_index == actuator_controls_s::INDEX_THROTTLE) { /* limit the throttle output to zero during motor spinup, * as the motors cannot follow any demand yet */ input = 0.0f; } } /* throttle not arming - mark throttle input as invalid */ if (arm_nothrottle()) { if (control_group == actuator_controls_s::GROUP_INDEX_ATTITUDE && control_index == actuator_controls_s::INDEX_THROTTLE) { /* set the throttle to an invalid value */ input = NAN_VALUE; } } return 0; } int PX4FMU::ioctl(file *filp, int cmd, unsigned long arg) { int ret; /* try it as a GPIO ioctl first */ ret = gpio_ioctl(filp, cmd, arg); if (ret != -ENOTTY) { return ret; } /* if we are in valid PWM mode, try it as a PWM ioctl as well */ switch (_mode) { case MODE_2PWM: case MODE_4PWM: case MODE_6PWM: #ifdef CONFIG_ARCH_BOARD_AEROCORE case MODE_8PWM: #endif ret = pwm_ioctl(filp, cmd, arg); break; default: debug("not in a PWM mode"); break; } /* if nobody wants it, let CDev have it */ if (ret == -ENOTTY) { ret = CDev::ioctl(filp, cmd, arg); } return ret; } int PX4FMU::pwm_ioctl(file *filp, int cmd, unsigned long arg) { int ret = OK; lock(); switch (cmd) { case PWM_SERVO_ARM: up_pwm_servo_arm(true); break; case PWM_SERVO_SET_ARM_OK: case PWM_SERVO_CLEAR_ARM_OK: case PWM_SERVO_SET_FORCE_SAFETY_OFF: case PWM_SERVO_SET_FORCE_SAFETY_ON: // these are no-ops, as no safety switch break; case PWM_SERVO_DISARM: up_pwm_servo_arm(false); break; case PWM_SERVO_GET_DEFAULT_UPDATE_RATE: *(uint32_t *)arg = _pwm_default_rate; break; case PWM_SERVO_SET_UPDATE_RATE: ret = set_pwm_rate(_pwm_alt_rate_channels, _pwm_default_rate, arg); break; case PWM_SERVO_GET_UPDATE_RATE: *(uint32_t *)arg = _pwm_alt_rate; break; case PWM_SERVO_SET_SELECT_UPDATE_RATE: ret = set_pwm_rate(arg, _pwm_default_rate, _pwm_alt_rate); break; case PWM_SERVO_GET_SELECT_UPDATE_RATE: *(uint32_t *)arg = _pwm_alt_rate_channels; break; case PWM_SERVO_SET_FAILSAFE_PWM: { struct pwm_output_values *pwm = (struct pwm_output_values *)arg; /* discard if too many values are sent */ if (pwm->channel_count > _max_actuators) { ret = -EINVAL; break; } for (unsigned i = 0; i < pwm->channel_count; i++) { if (pwm->values[i] == 0) { /* ignore 0 */ } else if (pwm->values[i] > PWM_HIGHEST_MAX) { _failsafe_pwm[i] = PWM_HIGHEST_MAX; } else if (pwm->values[i] < PWM_LOWEST_MIN) { _failsafe_pwm[i] = PWM_LOWEST_MIN; } else { _failsafe_pwm[i] = pwm->values[i]; } } /* * update the counter * this is needed to decide if disarmed PWM output should be turned on or not */ _num_failsafe_set = 0; for (unsigned i = 0; i < _max_actuators; i++) { if (_failsafe_pwm[i] > 0) _num_failsafe_set++; } break; } case PWM_SERVO_GET_FAILSAFE_PWM: { struct pwm_output_values *pwm = (struct pwm_output_values *)arg; for (unsigned i = 0; i < _max_actuators; i++) { pwm->values[i] = _failsafe_pwm[i]; } pwm->channel_count = _max_actuators; break; } case PWM_SERVO_SET_DISARMED_PWM: { struct pwm_output_values *pwm = (struct pwm_output_values *)arg; /* discard if too many values are sent */ if (pwm->channel_count > _max_actuators) { ret = -EINVAL; break; } for (unsigned i = 0; i < pwm->channel_count; i++) { if (pwm->values[i] == 0) { /* ignore 0 */ } else if (pwm->values[i] > PWM_HIGHEST_MAX) { _disarmed_pwm[i] = PWM_HIGHEST_MAX; } else if (pwm->values[i] < PWM_LOWEST_MIN) { _disarmed_pwm[i] = PWM_LOWEST_MIN; } else { _disarmed_pwm[i] = pwm->values[i]; } } /* * update the counter * this is needed to decide if disarmed PWM output should be turned on or not */ _num_disarmed_set = 0; for (unsigned i = 0; i < _max_actuators; i++) { if (_disarmed_pwm[i] > 0) _num_disarmed_set++; } break; } case PWM_SERVO_GET_DISARMED_PWM: { struct pwm_output_values *pwm = (struct pwm_output_values *)arg; for (unsigned i = 0; i < _max_actuators; i++) { pwm->values[i] = _disarmed_pwm[i]; } pwm->channel_count = _max_actuators; break; } case PWM_SERVO_SET_MIN_PWM: { struct pwm_output_values *pwm = (struct pwm_output_values *)arg; /* discard if too many values are sent */ if (pwm->channel_count > _max_actuators) { ret = -EINVAL; break; } for (unsigned i = 0; i < pwm->channel_count; i++) { if (pwm->values[i] == 0) { /* ignore 0 */ } else if (pwm->values[i] > PWM_HIGHEST_MIN) { _min_pwm[i] = PWM_HIGHEST_MIN; } else if (pwm->values[i] < PWM_LOWEST_MIN) { _min_pwm[i] = PWM_LOWEST_MIN; } else { _min_pwm[i] = pwm->values[i]; } } break; } case PWM_SERVO_GET_MIN_PWM: { struct pwm_output_values *pwm = (struct pwm_output_values *)arg; for (unsigned i = 0; i < _max_actuators; i++) { pwm->values[i] = _min_pwm[i]; } pwm->channel_count = _max_actuators; arg = (unsigned long)&pwm; break; } case PWM_SERVO_SET_MAX_PWM: { struct pwm_output_values *pwm = (struct pwm_output_values *)arg; /* discard if too many values are sent */ if (pwm->channel_count > _max_actuators) { ret = -EINVAL; break; } for (unsigned i = 0; i < pwm->channel_count; i++) { if (pwm->values[i] == 0) { /* ignore 0 */ } else if (pwm->values[i] < PWM_LOWEST_MAX) { _max_pwm[i] = PWM_LOWEST_MAX; } else if (pwm->values[i] > PWM_HIGHEST_MAX) { _max_pwm[i] = PWM_HIGHEST_MAX; } else { _max_pwm[i] = pwm->values[i]; } } break; } case PWM_SERVO_GET_MAX_PWM: { struct pwm_output_values *pwm = (struct pwm_output_values *)arg; for (unsigned i = 0; i < _max_actuators; i++) { pwm->values[i] = _max_pwm[i]; } pwm->channel_count = _max_actuators; arg = (unsigned long)&pwm; break; } #ifdef CONFIG_ARCH_BOARD_AEROCORE case PWM_SERVO_SET(7): case PWM_SERVO_SET(6): if (_mode < MODE_8PWM) { ret = -EINVAL; break; } #endif case PWM_SERVO_SET(5): case PWM_SERVO_SET(4): if (_mode < MODE_6PWM) { ret = -EINVAL; break; } /* FALLTHROUGH */ case PWM_SERVO_SET(3): case PWM_SERVO_SET(2): if (_mode < MODE_4PWM) { ret = -EINVAL; break; } /* FALLTHROUGH */ case PWM_SERVO_SET(1): case PWM_SERVO_SET(0): if (arg <= 2100) { up_pwm_servo_set(cmd - PWM_SERVO_SET(0), arg); } else { ret = -EINVAL; } break; #ifdef CONFIG_ARCH_BOARD_AEROCORE case PWM_SERVO_GET(7): case PWM_SERVO_GET(6): if (_mode < MODE_8PWM) { ret = -EINVAL; break; } #endif case PWM_SERVO_GET(5): case PWM_SERVO_GET(4): if (_mode < MODE_6PWM) { ret = -EINVAL; break; } /* FALLTHROUGH */ case PWM_SERVO_GET(3): case PWM_SERVO_GET(2): if (_mode < MODE_4PWM) { ret = -EINVAL; break; } /* FALLTHROUGH */ case PWM_SERVO_GET(1): case PWM_SERVO_GET(0): *(servo_position_t *)arg = up_pwm_servo_get(cmd - PWM_SERVO_GET(0)); break; case PWM_SERVO_GET_RATEGROUP(0): case PWM_SERVO_GET_RATEGROUP(1): case PWM_SERVO_GET_RATEGROUP(2): case PWM_SERVO_GET_RATEGROUP(3): case PWM_SERVO_GET_RATEGROUP(4): case PWM_SERVO_GET_RATEGROUP(5): #ifdef CONFIG_ARCH_BOARD_AEROCORE case PWM_SERVO_GET_RATEGROUP(6): case PWM_SERVO_GET_RATEGROUP(7): #endif *(uint32_t *)arg = up_pwm_servo_get_rate_group(cmd - PWM_SERVO_GET_RATEGROUP(0)); break; case PWM_SERVO_GET_COUNT: case MIXERIOCGETOUTPUTCOUNT: switch (_mode) { #ifdef CONFIG_ARCH_BOARD_AEROCORE case MODE_8PWM: *(unsigned *)arg = 8; break; #endif case MODE_6PWM: *(unsigned *)arg = 6; break; case MODE_4PWM: *(unsigned *)arg = 4; break; case MODE_2PWM: *(unsigned *)arg = 2; break; default: ret = -EINVAL; break; } break; case PWM_SERVO_SET_COUNT: { /* change the number of outputs that are enabled for * PWM. This is used to change the split between GPIO * and PWM under control of the flight config * parameters. Note that this does not allow for * changing a set of pins to be used for serial on * FMUv1 */ switch (arg) { case 0: set_mode(MODE_NONE); break; case 2: set_mode(MODE_2PWM); break; case 4: set_mode(MODE_4PWM); break; #if defined(CONFIG_ARCH_BOARD_PX4FMU_V2) case 6: set_mode(MODE_6PWM); break; #endif #if defined(CONFIG_ARCH_BOARD_AEROCORE) case 8: set_mode(MODE_8PWM); break; #endif default: ret = -EINVAL; break; } break; } case MIXERIOCRESET: if (_mixers != nullptr) { delete _mixers; _mixers = nullptr; _groups_required = 0; } break; case MIXERIOCADDSIMPLE: { mixer_simple_s *mixinfo = (mixer_simple_s *)arg; SimpleMixer *mixer = new SimpleMixer(control_callback, (uintptr_t)_controls, mixinfo); if (mixer->check()) { delete mixer; _groups_required = 0; ret = -EINVAL; } else { if (_mixers == nullptr) _mixers = new MixerGroup(control_callback, (uintptr_t)_controls); _mixers->add_mixer(mixer); _mixers->groups_required(_groups_required); } break; } case MIXERIOCLOADBUF: { const char *buf = (const char *)arg; unsigned buflen = strnlen(buf, 1024); if (_mixers == nullptr) _mixers = new MixerGroup(control_callback, (uintptr_t)_controls); if (_mixers == nullptr) { _groups_required = 0; ret = -ENOMEM; } else { ret = _mixers->load_from_buf(buf, buflen); if (ret != 0) { debug("mixer load failed with %d", ret); delete _mixers; _mixers = nullptr; _groups_required = 0; ret = -EINVAL; } else { _mixers->groups_required(_groups_required); } } break; } default: ret = -ENOTTY; break; } unlock(); return ret; } /* this implements PWM output via a write() method, for compatibility with px4io */ ssize_t PX4FMU::write(file *filp, const char *buffer, size_t len) { unsigned count = len / 2; uint16_t values[6]; #ifdef CONFIG_ARCH_BOARD_AEROCORE if (count > 8) { // we have at most 8 outputs count = 8; } #else if (count > 6) { // we have at most 6 outputs count = 6; } #endif // allow for misaligned values memcpy(values, buffer, count * 2); for (uint8_t i = 0; i < count; i++) { if (values[i] != PWM_IGNORE_THIS_CHANNEL) { up_pwm_servo_set(i, values[i]); } } return count * 2; } void PX4FMU::sensor_reset(int ms) { #if defined(CONFIG_ARCH_BOARD_PX4FMU_V2) if (ms < 1) { ms = 1; } /* disable SPI bus */ stm32_configgpio(GPIO_SPI_CS_GYRO_OFF); stm32_configgpio(GPIO_SPI_CS_ACCEL_MAG_OFF); stm32_configgpio(GPIO_SPI_CS_BARO_OFF); stm32_configgpio(GPIO_SPI_CS_MPU_OFF); stm32_gpiowrite(GPIO_SPI_CS_GYRO_OFF, 0); stm32_gpiowrite(GPIO_SPI_CS_ACCEL_MAG_OFF, 0); stm32_gpiowrite(GPIO_SPI_CS_BARO_OFF, 0); stm32_gpiowrite(GPIO_SPI_CS_MPU_OFF, 0); stm32_configgpio(GPIO_SPI1_SCK_OFF); stm32_configgpio(GPIO_SPI1_MISO_OFF); stm32_configgpio(GPIO_SPI1_MOSI_OFF); stm32_gpiowrite(GPIO_SPI1_SCK_OFF, 0); stm32_gpiowrite(GPIO_SPI1_MISO_OFF, 0); stm32_gpiowrite(GPIO_SPI1_MOSI_OFF, 0); stm32_configgpio(GPIO_GYRO_DRDY_OFF); stm32_configgpio(GPIO_MAG_DRDY_OFF); stm32_configgpio(GPIO_ACCEL_DRDY_OFF); stm32_configgpio(GPIO_EXTI_MPU_DRDY_OFF); stm32_gpiowrite(GPIO_GYRO_DRDY_OFF, 0); stm32_gpiowrite(GPIO_MAG_DRDY_OFF, 0); stm32_gpiowrite(GPIO_ACCEL_DRDY_OFF, 0); stm32_gpiowrite(GPIO_EXTI_MPU_DRDY_OFF, 0); /* set the sensor rail off */ stm32_configgpio(GPIO_VDD_3V3_SENSORS_EN); stm32_gpiowrite(GPIO_VDD_3V3_SENSORS_EN, 0); /* wait for the sensor rail to reach GND */ usleep(ms * 1000); warnx("reset done, %d ms", ms); /* re-enable power */ /* switch the sensor rail back on */ stm32_gpiowrite(GPIO_VDD_3V3_SENSORS_EN, 1); /* wait a bit before starting SPI, different times didn't influence results */ usleep(100); /* reconfigure the SPI pins */ #ifdef CONFIG_STM32_SPI1 stm32_configgpio(GPIO_SPI_CS_GYRO); stm32_configgpio(GPIO_SPI_CS_ACCEL_MAG); stm32_configgpio(GPIO_SPI_CS_BARO); stm32_configgpio(GPIO_SPI_CS_MPU); /* De-activate all peripherals, * required for some peripheral * state machines */ stm32_gpiowrite(GPIO_SPI_CS_GYRO, 1); stm32_gpiowrite(GPIO_SPI_CS_ACCEL_MAG, 1); stm32_gpiowrite(GPIO_SPI_CS_BARO, 1); stm32_gpiowrite(GPIO_SPI_CS_MPU, 1); // // XXX bring up the EXTI pins again // stm32_configgpio(GPIO_GYRO_DRDY); // stm32_configgpio(GPIO_MAG_DRDY); // stm32_configgpio(GPIO_ACCEL_DRDY); // stm32_configgpio(GPIO_EXTI_MPU_DRDY); #endif #endif } void PX4FMU::peripheral_reset(int ms) { #if defined(CONFIG_ARCH_BOARD_PX4FMU_V2) if (ms < 1) { ms = 10; } /* set the peripheral rails off */ stm32_configgpio(GPIO_VDD_5V_PERIPH_EN); stm32_gpiowrite(GPIO_VDD_5V_PERIPH_EN, 1); /* wait for the peripheral rail to reach GND */ usleep(ms * 1000); warnx("reset done, %d ms", ms); /* re-enable power */ /* switch the peripheral rail back on */ stm32_gpiowrite(GPIO_VDD_5V_PERIPH_EN, 0); #endif } void PX4FMU::gpio_reset(void) { /* * Setup default GPIO config - all pins as GPIOs, input if * possible otherwise output if possible. */ for (unsigned i = 0; i < _ngpio; i++) { if (_gpio_tab[i].input != 0) { stm32_configgpio(_gpio_tab[i].input); } else if (_gpio_tab[i].output != 0) { stm32_configgpio(_gpio_tab[i].output); } } #if defined(CONFIG_ARCH_BOARD_PX4FMU_V1) /* if we have a GPIO direction control, set it to zero (input) */ stm32_gpiowrite(GPIO_GPIO_DIR, 0); stm32_configgpio(GPIO_GPIO_DIR); #endif } void PX4FMU::gpio_set_function(uint32_t gpios, int function) { #if defined(CONFIG_ARCH_BOARD_PX4FMU_V1) /* * GPIOs 0 and 1 must have the same direction as they are buffered * by a shared 2-port driver. Any attempt to set either sets both. */ if (gpios & 3) { gpios |= 3; /* flip the buffer to output mode if required */ if (GPIO_SET_OUTPUT == function) stm32_gpiowrite(GPIO_GPIO_DIR, 1); } #endif /* configure selected GPIOs as required */ for (unsigned i = 0; i < _ngpio; i++) { if (gpios & (1 << i)) { switch (function) { case GPIO_SET_INPUT: stm32_configgpio(_gpio_tab[i].input); break; case GPIO_SET_OUTPUT: stm32_configgpio(_gpio_tab[i].output); break; case GPIO_SET_ALT_1: if (_gpio_tab[i].alt != 0) stm32_configgpio(_gpio_tab[i].alt); break; } } } #if defined(CONFIG_ARCH_BOARD_PX4FMU_V1) /* flip buffer to input mode if required */ if ((GPIO_SET_INPUT == function) && (gpios & 3)) stm32_gpiowrite(GPIO_GPIO_DIR, 0); #endif } void PX4FMU::gpio_write(uint32_t gpios, int function) { int value = (function == GPIO_SET) ? 1 : 0; for (unsigned i = 0; i < _ngpio; i++) if (gpios & (1 << i)) stm32_gpiowrite(_gpio_tab[i].output, value); } uint32_t PX4FMU::gpio_read(void) { uint32_t bits = 0; for (unsigned i = 0; i < _ngpio; i++) if (stm32_gpioread(_gpio_tab[i].input)) bits |= (1 << i); return bits; } int PX4FMU::gpio_ioctl(struct file *filp, int cmd, unsigned long arg) { int ret = OK; lock(); switch (cmd) { case GPIO_RESET: gpio_reset(); break; case GPIO_SENSOR_RAIL_RESET: sensor_reset(arg); break; case GPIO_PERIPHERAL_RAIL_RESET: peripheral_reset(arg); break; case GPIO_SET_OUTPUT: case GPIO_SET_INPUT: case GPIO_SET_ALT_1: gpio_set_function(arg, cmd); break; case GPIO_SET_ALT_2: case GPIO_SET_ALT_3: case GPIO_SET_ALT_4: ret = -EINVAL; break; case GPIO_SET: case GPIO_CLEAR: gpio_write(arg, cmd); break; case GPIO_GET: *(uint32_t *)arg = gpio_read(); break; default: ret = -ENOTTY; } unlock(); return ret; } namespace { enum PortMode { PORT_MODE_UNSET = 0, PORT_FULL_GPIO, PORT_FULL_SERIAL, PORT_FULL_PWM, PORT_GPIO_AND_SERIAL, PORT_PWM_AND_SERIAL, PORT_PWM_AND_GPIO, PORT_PWM4, }; PortMode g_port_mode; int fmu_new_mode(PortMode new_mode) { uint32_t gpio_bits; PX4FMU::Mode servo_mode; /* reset to all-inputs */ g_fmu->ioctl(0, GPIO_RESET, 0); gpio_bits = 0; servo_mode = PX4FMU::MODE_NONE; switch (new_mode) { case PORT_FULL_GPIO: case PORT_MODE_UNSET: /* nothing more to do here */ break; case PORT_FULL_PWM: #if defined(CONFIG_ARCH_BOARD_PX4FMU_V1) /* select 4-pin PWM mode */ servo_mode = PX4FMU::MODE_4PWM; #endif #if defined(CONFIG_ARCH_BOARD_PX4FMU_V2) servo_mode = PX4FMU::MODE_6PWM; #endif #if defined(CONFIG_ARCH_BOARD_AEROCORE) servo_mode = PX4FMU::MODE_8PWM; #endif break; #if defined(CONFIG_ARCH_BOARD_PX4FMU_V2) case PORT_PWM4: /* select 4-pin PWM mode */ servo_mode = PX4FMU::MODE_4PWM; break; #endif /* mixed modes supported on v1 board only */ #if defined(CONFIG_ARCH_BOARD_PX4FMU_V1) case PORT_FULL_SERIAL: /* set all multi-GPIOs to serial mode */ gpio_bits = GPIO_MULTI_1 | GPIO_MULTI_2 | GPIO_MULTI_3 | GPIO_MULTI_4; break; case PORT_GPIO_AND_SERIAL: /* set RX/TX multi-GPIOs to serial mode */ gpio_bits = GPIO_MULTI_3 | GPIO_MULTI_4; break; case PORT_PWM_AND_SERIAL: /* select 2-pin PWM mode */ servo_mode = PX4FMU::MODE_2PWM; /* set RX/TX multi-GPIOs to serial mode */ gpio_bits = GPIO_MULTI_3 | GPIO_MULTI_4; break; case PORT_PWM_AND_GPIO: /* select 2-pin PWM mode */ servo_mode = PX4FMU::MODE_2PWM; break; #endif default: return -1; } /* adjust GPIO config for serial mode(s) */ if (gpio_bits != 0) g_fmu->ioctl(0, GPIO_SET_ALT_1, gpio_bits); /* (re)set the PWM output mode */ g_fmu->set_mode(servo_mode); return OK; } int fmu_new_i2c_speed(unsigned bus, unsigned clock_hz) { return g_fmu->set_i2c_bus_clock(bus, clock_hz); } int fmu_start(void) { int ret = OK; if (g_fmu == nullptr) { g_fmu = new PX4FMU; if (g_fmu == nullptr) { ret = -ENOMEM; } else { ret = g_fmu->init(); if (ret != OK) { delete g_fmu; g_fmu = nullptr; } } } return ret; } int fmu_stop(void) { int ret = OK; if (g_fmu != nullptr) { delete g_fmu; g_fmu = nullptr; } return ret; } void sensor_reset(int ms) { int fd; fd = open(PX4FMU_DEVICE_PATH, O_RDWR); if (fd < 0) { errx(1, "open fail"); } if (ioctl(fd, GPIO_SENSOR_RAIL_RESET, ms) < 0) { warnx("sensor rail reset failed"); } close(fd); } void peripheral_reset(int ms) { int fd; fd = open(PX4FMU_DEVICE_PATH, O_RDWR); if (fd < 0) { errx(1, "open fail"); } if (ioctl(fd, GPIO_PERIPHERAL_RAIL_RESET, ms) < 0) { warnx("peripheral rail reset failed"); } close(fd); } void test(void) { int fd; unsigned servo_count = 0; unsigned pwm_value = 1000; int direction = 1; int ret; fd = open(PX4FMU_DEVICE_PATH, O_RDWR); if (fd < 0) errx(1, "open fail"); if (ioctl(fd, PWM_SERVO_ARM, 0) < 0) err(1, "servo arm failed"); if (ioctl(fd, PWM_SERVO_GET_COUNT, (unsigned long)&servo_count) != 0) { err(1, "Unable to get servo count\n"); } warnx("Testing %u servos", (unsigned)servo_count); struct pollfd fds; fds.fd = 0; /* stdin */ fds.events = POLLIN; warnx("Press CTRL-C or 'c' to abort."); for (;;) { /* sweep all servos between 1000..2000 */ servo_position_t servos[servo_count]; for (unsigned i = 0; i < servo_count; i++) servos[i] = pwm_value; if (direction == 1) { // use ioctl interface for one direction for (unsigned i = 0; i < servo_count; i++) { if (ioctl(fd, PWM_SERVO_SET(i), servos[i]) < 0) { err(1, "servo %u set failed", i); } } } else { // and use write interface for the other direction ret = write(fd, servos, sizeof(servos)); if (ret != (int)sizeof(servos)) err(1, "error writing PWM servo data, wrote %u got %d", sizeof(servos), ret); } if (direction > 0) { if (pwm_value < 2000) { pwm_value++; } else { direction = -1; } } else { if (pwm_value > 1000) { pwm_value--; } else { direction = 1; } } /* readback servo values */ for (unsigned i = 0; i < servo_count; i++) { servo_position_t value; if (ioctl(fd, PWM_SERVO_GET(i), (unsigned long)&value)) err(1, "error reading PWM servo %d", i); if (value != servos[i]) errx(1, "servo %d readback error, got %u expected %u", i, value, servos[i]); } /* Check if user wants to quit */ char c; ret = poll(&fds, 1, 0); if (ret > 0) { read(0, &c, 1); if (c == 0x03 || c == 0x63 || c == 'q') { warnx("User abort\n"); break; } } } close(fd); exit(0); } void fake(int argc, char *argv[]) { if (argc < 5) errx(1, "fmu fake <roll> <pitch> <yaw> <thrust> (values -100 .. 100)"); actuator_controls_s ac; ac.control[0] = strtol(argv[1], 0, 0) / 100.0f; ac.control[1] = strtol(argv[2], 0, 0) / 100.0f; ac.control[2] = strtol(argv[3], 0, 0) / 100.0f; ac.control[3] = strtol(argv[4], 0, 0) / 100.0f; orb_advert_t handle = orb_advertise(ORB_ID_VEHICLE_ATTITUDE_CONTROLS, &ac); if (handle == nullptr) errx(1, "advertise failed"); actuator_armed_s aa; aa.armed = true; aa.lockdown = false; handle = orb_advertise(ORB_ID(actuator_armed), &aa); if (handle == nullptr) errx(1, "advertise failed 2"); exit(0); } } // namespace extern "C" __EXPORT int fmu_main(int argc, char *argv[]); int fmu_main(int argc, char *argv[]) { PortMode new_mode = PORT_MODE_UNSET; const char *verb = argv[1]; if (!strcmp(verb, "stop")) { fmu_stop(); errx(0, "FMU driver stopped"); } if (!strcmp(verb, "id")) { uint8_t id[12]; (void)get_board_serial(id); errx(0, "Board serial:\n %02X%02X%02X%02X %02X%02X%02X%02X %02X%02X%02X%02X", (unsigned)id[0], (unsigned)id[1], (unsigned)id[2], (unsigned)id[3], (unsigned)id[4], (unsigned)id[5], (unsigned)id[6], (unsigned)id[7], (unsigned)id[8], (unsigned)id[9], (unsigned)id[10], (unsigned)id[11]); } if (fmu_start() != OK) errx(1, "failed to start the FMU driver"); /* * Mode switches. */ if (!strcmp(verb, "mode_gpio")) { new_mode = PORT_FULL_GPIO; } else if (!strcmp(verb, "mode_pwm")) { new_mode = PORT_FULL_PWM; #if defined(CONFIG_ARCH_BOARD_PX4FMU_V2) } else if (!strcmp(verb, "mode_pwm4")) { new_mode = PORT_PWM4; #endif #if defined(CONFIG_ARCH_BOARD_PX4FMU_V1) } else if (!strcmp(verb, "mode_serial")) { new_mode = PORT_FULL_SERIAL; } else if (!strcmp(verb, "mode_gpio_serial")) { new_mode = PORT_GPIO_AND_SERIAL; } else if (!strcmp(verb, "mode_pwm_serial")) { new_mode = PORT_PWM_AND_SERIAL; } else if (!strcmp(verb, "mode_pwm_gpio")) { new_mode = PORT_PWM_AND_GPIO; #endif } /* was a new mode set? */ if (new_mode != PORT_MODE_UNSET) { /* yes but it's the same mode */ if (new_mode == g_port_mode) return OK; /* switch modes */ int ret = fmu_new_mode(new_mode); exit(ret == OK ? 0 : 1); } if (!strcmp(verb, "test")) test(); if (!strcmp(verb, "fake")) fake(argc - 1, argv + 1); if (!strcmp(verb, "sensor_reset")) { if (argc > 2) { int reset_time = strtol(argv[2], 0, 0); sensor_reset(reset_time); } else { sensor_reset(0); warnx("resettet default time"); } exit(0); } if (!strcmp(verb, "peripheral_reset")) { if (argc > 2) { int reset_time = strtol(argv[2], 0, 0); peripheral_reset(reset_time); } else { peripheral_reset(0); warnx("resettet default time"); } exit(0); } if (!strcmp(verb, "i2c")) { if (argc > 3) { int bus = strtol(argv[2], 0, 0); int clock_hz = strtol(argv[3], 0, 0); int ret = fmu_new_i2c_speed(bus, clock_hz); if (ret) { errx(ret, "setting I2C clock failed"); } exit(0); } else { warnx("i2c cmd args: <bus id> <clock Hz>"); } } fprintf(stderr, "FMU: unrecognised command %s, try:\n", verb); #if defined(CONFIG_ARCH_BOARD_PX4FMU_V1) fprintf(stderr, " mode_gpio, mode_serial, mode_pwm, mode_gpio_serial, mode_pwm_serial, mode_pwm_gpio, test, fake, sensor_reset, id\n"); #elif defined(CONFIG_ARCH_BOARD_PX4FMU_V2) || defined(CONFIG_ARCH_BOARD_AEROCORE) fprintf(stderr, " mode_gpio, mode_pwm, test, sensor_reset [milliseconds], i2c <bus> <hz>\n"); #endif exit(1); }
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/captcha/v20190722/model/CaptchaOperDataTryTimesDistributeUnit.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Captcha::V20190722::Model; using namespace std; CaptchaOperDataTryTimesDistributeUnit::CaptchaOperDataTryTimesDistributeUnit() : m_tryCountHasBeenSet(false), m_userCountHasBeenSet(false) { } CoreInternalOutcome CaptchaOperDataTryTimesDistributeUnit::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("TryCount") && !value["TryCount"].IsNull()) { if (!value["TryCount"].IsInt64()) { return CoreInternalOutcome(Error("response `CaptchaOperDataTryTimesDistributeUnit.TryCount` IsInt64=false incorrectly").SetRequestId(requestId)); } m_tryCount = value["TryCount"].GetInt64(); m_tryCountHasBeenSet = true; } if (value.HasMember("UserCount") && !value["UserCount"].IsNull()) { if (!value["UserCount"].IsInt64()) { return CoreInternalOutcome(Error("response `CaptchaOperDataTryTimesDistributeUnit.UserCount` IsInt64=false incorrectly").SetRequestId(requestId)); } m_userCount = value["UserCount"].GetInt64(); m_userCountHasBeenSet = true; } return CoreInternalOutcome(true); } void CaptchaOperDataTryTimesDistributeUnit::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_tryCountHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "TryCount"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_tryCount, allocator); } if (m_userCountHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "UserCount"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_userCount, allocator); } } int64_t CaptchaOperDataTryTimesDistributeUnit::GetTryCount() const { return m_tryCount; } void CaptchaOperDataTryTimesDistributeUnit::SetTryCount(const int64_t& _tryCount) { m_tryCount = _tryCount; m_tryCountHasBeenSet = true; } bool CaptchaOperDataTryTimesDistributeUnit::TryCountHasBeenSet() const { return m_tryCountHasBeenSet; } int64_t CaptchaOperDataTryTimesDistributeUnit::GetUserCount() const { return m_userCount; } void CaptchaOperDataTryTimesDistributeUnit::SetUserCount(const int64_t& _userCount) { m_userCount = _userCount; m_userCountHasBeenSet = true; } bool CaptchaOperDataTryTimesDistributeUnit::UserCountHasBeenSet() const { return m_userCountHasBeenSet; }
/* IZ3D_FILE: $Id$ * * Project : iZ3D Stereo Driver * Copyright (C) iZ3D Inc. 2002 - 2010 * * $Author$ * $Revision$ * $Date$ * $LastChangedBy$ * $URL$ */ #include "stdafx.h" #include "Output_dx10.h" using namespace DX10Output; #include "Shaders_dx10/shaderFullScreenQuadVS.h" #include "Shaders_dx10/shaderHorizontalSideBySide.h" #include "Shaders_dx10/shaderVerticalSideBySide.h" OUTPUT_API void* CALLBACK CreateOutputDX10( DWORD nMode_, DWORD nSpanMode_ ) { return new SideBySideOutput( nMode_, nSpanMode_ ); } SideBySideOutput::SideBySideOutput( DWORD nMode_, DWORD nSpanMode_ ) : PostprocessedOutput( nMode_, nSpanMode_ ) { if ( nMode_ != 2 ) m_OutputMode &= 1; else { m_bCrosseyed = true; m_OutputMode = 0; } m_SigVS.NumInputSignatureEntries = 1; m_SigVS.NumOutputSignatureEntries = 2; m_SigVS.pInputSignature = &m_SigEntryVS[ 0 ]; m_SigEntryVS[ 0 ].SystemValue = D3D10_SB_NAME_VERTEX_ID; m_SigEntryVS[ 0 ].Register = 0; m_SigEntryVS[ 0 ].Mask = 1; m_SigVS.pOutputSignature = &m_SigEntryVS[ m_SigVS.NumInputSignatureEntries ]; m_SigEntryVS[ 1 ].SystemValue = D3D10_SB_NAME_UNDEFINED; m_SigEntryVS[ 1 ].Register = 0; m_SigEntryVS[ 1 ].Mask = 0x03; m_SigEntryVS[ 2 ].SystemValue = D3D10_SB_NAME_POSITION; m_SigEntryVS[ 2 ].Register = 1; m_SigEntryVS[ 2 ].Mask = 0x0F; m_SigPS.NumInputSignatureEntries = 1; m_SigPS.NumOutputSignatureEntries = 1; m_SigPS.pInputSignature = &m_SigEntryPS[ 0 ]; m_SigEntryPS[ 0 ].SystemValue = D3D10_SB_NAME_UNDEFINED; m_SigEntryPS[ 0 ].Register = 0; m_SigEntryPS[ 0 ].Mask = D3D10_SB_COMPONENT_MASK_X | D3D10_SB_COMPONENT_MASK_Y; m_SigPS.pOutputSignature = &m_SigEntryPS[ m_SigPS.NumInputSignatureEntries ]; m_SigEntryPS[ 1 ].SystemValue = D3D10_SB_NAME_UNDEFINED; m_SigEntryPS[ 1 ].Register = 0; m_SigEntryPS[ 1 ].Mask = D3D10_SB_COMPONENT_MASK_X | D3D10_SB_COMPONENT_MASK_Y | D3D10_SB_COMPONENT_MASK_Z | D3D10_SB_COMPONENT_MASK_W; m_hSamplerState.pDrvPrivate = NULL; } SideBySideOutput::~SideBySideOutput() { } void SideBySideOutput::InitializeResources( D3DDeviceWrapper* pD3DWrapper_ ) { D3D10DDI_DEVICEFUNCS& GET_ORIG = pD3DWrapper_->OriginalDeviceFuncs; D3D10DDI_HDEVICE hDevice = pD3DWrapper_->hDevice; CONST UINT* pCode = NULL; /************************************************************************/ // begin create shaders ParseShaderBlob( g_shaderFullScreenQuadVS, sizeof( g_shaderFullScreenQuadVS ), &pCode ); SIZE_T nSize = GET_ORIG.pfnCalcPrivateShaderSize( hDevice, pCode, &m_SigVS ); NEW_HANDLE( m_hVSShader, nSize ); D3D10DDI_HRTSHADER hRTShader = { NULL }; GET_ORIG.pfnCreateVertexShader( hDevice, pCode, m_hVSShader, hRTShader, &m_SigVS ); pCode = NULL; if( m_OutputMode == 0 ) { ParseShaderBlob( g_shaderHorizontalSideBySide, sizeof( g_shaderHorizontalSideBySide ), &pCode ); } else { ParseShaderBlob( g_shaderVerticalSideBySide, sizeof( g_shaderVerticalSideBySide ), &pCode ); } nSize = GET_ORIG.pfnCalcPrivateShaderSize( hDevice, pCode, &m_SigPS ); NEW_HANDLE( m_hPSShader, nSize ); GET_ORIG.pfnCreatePixelShader( hDevice, pCode, m_hPSShader, hRTShader, &m_SigPS ); // end create shaders /************************************************************************/ // begin create sampler state D3D10_DDI_SAMPLER_DESC samplerDesc; D3D10DDI_HRTSAMPLER hRTSampler = { NULL }; ZeroMemory( &samplerDesc, sizeof( D3D10_DDI_SAMPLER_DESC ) ); samplerDesc.Filter = D3D10_DDI_FILTER_MIN_MAG_MIP_LINEAR; samplerDesc.AddressU = D3D10_DDI_TEXTURE_ADDRESS_BORDER; samplerDesc.AddressV = D3D10_DDI_TEXTURE_ADDRESS_BORDER; samplerDesc.AddressW = D3D10_DDI_TEXTURE_ADDRESS_BORDER; samplerDesc.MipLODBias = 0.0f; samplerDesc.MaxAnisotropy = 1; samplerDesc.ComparisonFunc = D3D10_DDI_COMPARISON_NEVER; samplerDesc.BorderColor[ 0 ] = 0.0f; samplerDesc.BorderColor[ 1 ] = 0.0f; samplerDesc.BorderColor[ 2 ] = 0.0f; samplerDesc.BorderColor[ 3 ] = 0.0f; samplerDesc.MinLOD = 0.0f; samplerDesc.MaxLOD = FLT_MAX; nSize = GET_ORIG.pfnCalcPrivateSamplerSize( hDevice, &samplerDesc ); NEW_HANDLE( m_hSamplerState, nSize ); GET_ORIG.pfnCreateSampler( hDevice, &samplerDesc, m_hSamplerState, hRTSampler ); // end create sampler state /************************************************************************/ } void SideBySideOutput::SetStates( D3DDeviceWrapper* pDevice_, D3DSwapChain* pSwapChain_ ) { D3D10DDI_DEVICEFUNCS& GET_ORIG = pDevice_->OriginalDeviceFuncs; D3D10DDI_HDEVICE hDevice = pDevice_->hDevice; GET_ORIG.pfnPsSetSamplers( hDevice, 0, 1, &m_hSamplerState ); } void SideBySideOutput::ClearResources( D3DDeviceWrapper* pD3DWrapper_ ) { D3D10DDI_DEVICEFUNCS& GET_ORIG = pD3DWrapper_->OriginalDeviceFuncs; D3D10DDI_HDEVICE hDevice = pD3DWrapper_->hDevice; GET_ORIG.pfnDestroyShader( hDevice, m_hVSShader ); DELETE_HANDLE( m_hVSShader ); GET_ORIG.pfnDestroyShader( hDevice, m_hPSShader ); DELETE_HANDLE( m_hPSShader ); GET_ORIG.pfnDestroySampler( hDevice, m_hSamplerState ); DELETE_HANDLE( m_hSamplerState ); }
#include <fcgi_stdio.h> #include <string> #include <stdlib.h> #include <openframe/openframe.h> #include "App.h" #include "DBI.h" #include "config.h" #include "openapi.h" #include "openapiCommands.h" namespace openapi { const char *App::kPidFile = "openapi.pid"; App::App(const std::string &prompt, const std::string &config) : super(prompt, config) { _dbi_w = NULL; _dbi_r = NULL; _numRequests = 0; _stats = NULL; _debug = false; _env["QUERY_STRING"] = "request.query.string"; _env["REQUEST_METHOD"] = "request.method"; _env["CONTENT_TYPE"] = "request.content.type"; _env["CONTENT_LENGTH"] = "request.content.length"; _env["SCRIPT_NAME"] = "request.script.name"; _env["REQUEST_URI"] = "request.uri"; _env["DOCUMENT_URI"] = "request.document.uri"; _env["DOCUMENT_ROOT"] = "request.document.root"; _env["SERVER_PROTOCOL"] = "request.server.protocol"; _env["GATEWAY_INTERFACE"] = "request.gateway.interface"; _env["SERVER_SOFTWARE"] = "request.server.software"; _env["REMOTE_ADDR"] = "request.remote.addr"; _env["REMOTE_PORT"] = "request.remote.port"; _env["SERVER_ADDR"] = "request.server.addr"; _env["SERVER_PORT"] = "request.server.port"; _env["SERVER_NAME"] = "request.server.name"; } // App::App App::~App() { } // App:~App bool App::onRun() { while(FCGI_Accept() >= 0 && !is_done() ) { _accept(); } // while return true; } // App::onRun void App::onInitializeCommands() { } void App::onInitializeSystem() { const char *opts[] = { "openapi.syslog.perror", "openapi.syslog.console", "openapi.syslog.pid", NULL }; const int optmask[] = { SyslogController::SYSCLOG_PERROR, SyslogController::SYSCLOG_CONS, SyslogController::SYSCLOG_PID, 0 }; try { SyslogController::logOptionType mask = 0; for(size_t i=0; opts[i] != NULL; i++) mask |= optmask[i]; _syslog = new SyslogController(cfg->get_string("openapi.syslog.ident", "openapi"), mask, cfg->get_string("openapi.syslog.facility", "local0")); _syslog->setlogmask(cfg->get_int("openapi.syslog.level", 6)); } // try catch(std::bad_alloc xa) { assert(false); } // catch } // App::onInitializeSystem void App::onInitializeConfig() { } void App::onInitializeDatabase() { try { _dbi_r = new DBI(new App_Log(""), SQL_READ_DB, SQL_READ_HOST, SQL_READ_USER, SQL_READ_PASS); _dbi_w = new DBI(new App_Log(""), SQL_WRITE_DB, SQL_WRITE_HOST, SQL_WRITE_USER, SQL_WRITE_PASS); } // try catch(std::bad_alloc xa) { assert(false); } // catch } // App::onInitializeDatabase void App::onInitializeModules() { } void App::onInitializeThreads() { std::string source = app->cfg->get_string("app.stompstats.source", "/topic/stats.openstomp"); std::string instance = app->cfg->get_string("app.stompstats.instance", "prod"); time_t update_interval = app->cfg->get_int("app.stompstats.interval", 300); std::string hosts = app->cfg->get_string("app.stompstats.hosts", "localhost:61613"); std::string login = app->cfg->get_string("app.stompstats.login", "openstomp-stompstats"); std::string passcode = app->cfg->get_string("app.stats.passcode", "openstomp-stompstats"); int maxqueue = app->cfg->get_int("app.stompstats.maxqueue", 100); /* _stats = new stomp::StompStats(source, instance, update_interval, maxqueue, hosts, login, passcode); // _stats->elogger(&elog, "app"); _stats->start(); */ } // App::onInitializeThreads void App::onDeinitializeCommands() { } void App::onDeinitializeSystem() { } void App::onDeinitializeDatabase() { if (_dbi_r) delete _dbi_r; if (_dbi_w) delete _dbi_w; } // App::onDeinitializeDatabase void App::onDeinitializeThreads() { if (_stats) delete _stats; } // App::onDeinitializeThreads void App::onDeinitializeModules() { } void App::_accept() { envMapType::iterator ptr; openframe::Packet packet; openframe::Stopwatch sw; _numRequests++; sw.Start(); FCGI_printf("Content-type: text/plain\r\n\r\n"); for(ptr = _env.begin(); ptr != _env.end(); ptr++) { char *env = getenv(ptr->first.c_str()); if (env == NULL) { _infof("ERROR: Missing %s", ptr->first.c_str()); return; } // if packet.addString(ptr->second, env); } // for _infof("Accepted request %d from %s", _numRequests, packet.getString("request.remote.addr").c_str()); if (is_debug()) { std::list<string> slist; packet.showStringTree("root", 0, "# ", slist); FCGI_printf("# root\n"); while(!slist.empty()) { FCGI_printf("%s\n", slist.front().c_str()); slist.pop_front(); } // while } // if openframe::Url u(packet.getString("request.query.string")); _infof("%s requested %s", packet.getString("request.remote.addr").c_str(), packet.getString("request.uri").c_str()); if (is_debug() ) { openframe::Url::varMapType::iterator uptr; openframe::Result res("key,value"); for(uptr = u.begin(); uptr != u.end(); uptr++) { openframe::Serialize s; s.add(uptr->first); s.add(uptr->second); openframe::Row row(s.compile()); res.add(row); } // for openframe::Result::print(res, 80, sw.Time()); } // if packet.addVariable("url", &u); packet.addVariable("log", _logger); if (!u.exists("c")) { FCGI_printf("Command not found.\n"); return; } // if // initialize variables openframe::StringToken parseCommand = u["c"]; unsigned int nodeLevel = 0; int returnResult = time(NULL); // find the command openframe::Command *tCommand = command()->findCommand("FCGI", parseCommand, nodeLevel, NULL); double total = 0.0; if (tCommand != NULL) { packet.setSource("FCGI"); packet.setArguments(parseCommand.getRange(nodeLevel, parseCommand.size())); packet.setPath(tCommand->getPath()); sw.Start(); returnResult = tCommand->getCommandHandler()->Execute(&packet); total = sw.Time(); } // if switch(returnResult) { case CMDERR_SUCCESS: // _fcgif("# Total %0.5fs", total); break; case CMDERR_SYNTAX: std::cout << "Syntax Error: " << tCommand->getSyntax() << std::endl; std::cout << "Type /HELP for a list of available commands." << std::endl; break; case CMDERR_ACCESS: break; default: std::cout << "Invalid Command: " << u["c"] << std::endl; std::cout << "Type /HELP for a list of available commands." << std::endl; break; } // switch } // App::_accept void App::rcvSighup() { // LOG(LogNotice, << "### SIGHUP Received" << std::endl); // elogger()->hup(); } // App::rcvSighup void App::rcvSigusr1() { // LOG(LogNotice, << "### SIGHUS1 Received" << std::endl); } // App::Sigusr1 void App::rcvSigusr2() { // LOG(LogNotice, << "### SIGUSR2 Received" << std::endl); } // App::Sigusr2 void App::rcvSigint() { // LOG(LogNotice, << "### SIGINT Received" << std::endl); set_done(true); } // App::rcvSigint void App::rcvSigpipe() { // LOG(LogNotice, << "### SIGPIPE Received" << std::endl); } // App::rcvSigpipe } // openapi
// HtmlResourceReader.cpp #include <QResource> #include <QTextStream> #include "HtmlResourceReader.h" /* explicit HtmlResourceReader::HtmlResourceReader(QObject* p = nullptr); ----- This connects the textChange signals in the subsidiary Utf8ResourceReader objects to the appropriate private slots. */ HtmlResourceReader::HtmlResourceReader(QObject* p): QObject(p) { connect(&m_default, &Utf8ResourceReader::textChanged, this, &HtmlResourceReader::setDefaultText); connect(&m_html, &Utf8ResourceReader::textChanged, this, &HtmlResourceReader::setHtmlText); connect(&m_style, &Utf8ResourceReader::textChanged, this, &HtmlResourceReader::setStyleText); } /* bool HtmlResourceReader::resourceExists(QString url); ---------------------- This returns true if there is a resource called url. */ bool HtmlResourceReader::resourceExists(QString url) { return QResource(url).isValid(); } /* void HtmlResourceReader::setDefaultText(QString const& text); -------------- This private slot is connected to the textChanged signal of m_default. If the text of m_html is empty, this recomputes m_text. */ void HtmlResourceReader::setDefaultText(QString const&) { if (!m_html.getText().size()) textSet(); } /* void HtmlResourceReader::setDefaultUrl(QString const& url); ---------------- This sets the url property of m_default to url. */ void HtmlResourceReader::setDefaultUrl(QString const& url) { m_default.setUrl(url); } /* void HtmlResourceReader::setHtmlText(QString const& text); ----------------- This private slot is connected to the textChanged signal of m_html. It recomputes m_text. */ void HtmlResourceReader::setHtmlText(QString const&) { textSet(); } /* void HtmlResourceReader::setHtmlUrl(QString const& url); ------------------- This sets the url property of m_html to url. */ void HtmlResourceReader::setHtmlUrl(QString const& url) { m_html.setUrl(url); } /* void HtmlResourceReader::setStyleText(QString const& text); ---------------- This private slot is connected to the textChanged signal of m_style. It recomputes m_text. */ void HtmlResourceReader::setStyleText(QString const&) { textSet(); } /* void HtmlResourceReader::setStyleUrl(QString const& url); ------------------ This sets the url property of m_style to url. */ void HtmlResourceReader::setStyleUrl(QString const& url) { m_style.setUrl(url); } /* QString& HtmlResourceReader::textSet(); ------------------------------------ This private function sets m_text to m_style concatenated with m_html, or with m_default if m_html is empty, and emits the textChanged signal if it actually changes. */ QString& HtmlResourceReader::textSet() { QString s, t; // Extract base name from URL into t. int i = m_html.getUrl().lastIndexOf('/') + 1; int j = m_html.getUrl().indexOf('.', i); if (j < 0) j = m_html.getUrl().size(); t = m_html.getUrl().mid(i, j - i); // If there is no HTML... if (!m_html.getText().size()) { // Copy default HTML, replace "$URL$" with missing URL. s = m_default.getText(); s.replace(QStringLiteral(u"$URL$"), m_html.getUrl()); } // If HTML found, use it. else s = m_html.getText(); // Scan HTML for <title> element, use instead of URL base name if found. i = s.indexOf(QStringLiteral(u"<title>")); if (i >= 0) { i += 7; int j = s.indexOf(QStringLiteral(u"</title>"), i); if (j > i) { j -= i; if (j <= 30) t = s.mid(i, j).trimmed(); } } // Set title, signal change. if (m_title != t) emit titleChanged(m_title = t); // Set m_text to style plus HTML, signal change. s = "<style>\n" + m_style.getText() + "</style>\n" + s; if (m_text != s) emit textChanged(m_text = s); // Return text. return m_text; }
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #include "cbase.h" #include <vgui_controls/AnimationController.h> #include "tf_hud_freezepanel.h" #include "clientmode_shared.h" #include "tf_hud_robot_destruction_status.h" #include "tf_logic_player_destruction.h" #include "c_tf_objective_resource.h" #include "c_func_capture_zone.h" #define ATTACK_BLINK_TIME 2.f using namespace vgui; extern ConVar tf_rd_min_points_to_steal; extern ConVar tf_rd_steal_rate; extern ConVar tf_rd_points_per_steal; extern ConVar tf_rd_points_approach_interval; extern ConVar tf_rd_points_per_approach; //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CTFHudRobotDestruction_StateImage::CTFHudRobotDestruction_StateImage( Panel *parent, const char *name, const char *pszResFile ) : vgui::EditablePanel( parent, name ) , m_pImage( NULL ) , m_pRobotImage( NULL ) , m_pszResFile( pszResFile ) { m_pImage = new ImagePanel( this, "Image" ); m_pRobotImage = new ImagePanel( this, "RobotImage" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFHudRobotDestruction_StateImage::ApplySchemeSettings( IScheme *pScheme ) { BaseClass::ApplySchemeSettings( pScheme ); LoadControlSettings( m_pszResFile ); ImagePanel* pGlow = dynamic_cast<ImagePanel*>( FindChildByName( "GlowImage", true ) ); if ( pGlow ) { pGlow->SetAlpha( 0 ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFHudRobotDestruction_StateImage::ApplySettings( KeyValues *inResourceData ) { BaseClass::ApplySettings( inResourceData ); int nTeam = TF_TEAM_RED; const CTFHudRobotDestruction_RobotIndicator *pRobotImageParent = dynamic_cast< const CTFHudRobotDestruction_RobotIndicator* >( GetParent()->GetParent() ); if ( pRobotImageParent ) { nTeam = pRobotImageParent->GetTeamNumber(); } const char *pszKeyName = nTeam == TF_TEAM_RED ? "redimage" : "blueimage"; const char *pszImageName = inResourceData->GetString( pszKeyName ); if ( pszImageName && pszImageName[0] ) { m_pImage->SetImage( pszImageName ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CTFHudRobotDestruction_DeadImage::CTFHudRobotDestruction_DeadImage( Panel *parent, const char *name, const char *pszResFile ) : CTFHudRobotDestruction_StateImage( parent, name, pszResFile ) , m_pRespawnProgressBar( NULL ) { m_pRespawnProgressBar = new CTFProgressBar( this, "RespawnProgressBar" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFHudRobotDestruction_DeadImage::SetProgress( float flProgress ) { m_pRespawnProgressBar->SetPercentage( flProgress ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CTFHudRobotDestruction_ActiveImage::CTFHudRobotDestruction_ActiveImage( Panel *parent, const char *name, const char *pszResFile ) : CTFHudRobotDestruction_StateImage( parent, name, pszResFile ) {} //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFHudRobotDestruction_ActiveImage::ApplySettings( KeyValues *inResourceData ) { BaseClass::ApplySettings( inResourceData ); const CTFHudRobotDestruction_RobotIndicator *pRobotImageParent = dynamic_cast< const CTFHudRobotDestruction_RobotIndicator* >( GetParent()->GetParent() ); if ( pRobotImageParent && pRobotImageParent->GetGroup() ) { m_pRobotImage->SetImage( pRobotImageParent->GetGroup()->GetHUDIcon() ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CTFHudRobotDestruction_RobotIndicator::CTFHudRobotDestruction_RobotIndicator( vgui::Panel *pParent, const char *pszName, CTFRobotDestruction_RobotGroup *pGroup ) : EditablePanel( pParent, pszName ) , m_hGroup( pGroup ) , m_pNextRobotIndicator( NULL ) , m_pPrevRobotIndicator( NULL ) { Assert( pGroup ); m_pSwoop = new CControlPointIconSwoop( this, "Swoop" ); m_pSwoop->SetVisible( false ); m_pRobotStateContainer = new EditablePanel( this, "RobotStateContainer" ); m_pDeadPanel = new CTFHudRobotDestruction_DeadImage( m_pRobotStateContainer, "DeadState", "resource/UI/TFHudRobotDestruction_DeadState.res" ); m_pActivePanel = new CTFHudRobotDestruction_ActiveImage( m_pRobotStateContainer, "ActiveState", "resource/UI/TFHudRobotDestruction_ActiveState.res" ); m_pShieldedPanel = new CTFHudRobotDestruction_StateImage( m_pRobotStateContainer, "ShieldedState", "resource/UI/TFHudRobotDestruction_ShieldedState.res" ); m_flHealthPercentage = 0.f; m_eState = ROBOT_STATE_DEAD; vgui::ivgui()->AddTickSignal( GetVPanel(), 0 ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFHudRobotDestruction_RobotIndicator::ApplySchemeSettings( vgui::IScheme *pScheme ) { BaseClass::ApplySchemeSettings( pScheme ); LoadControlSettings( "resource/UI/TFHudRobotDestruction_RobotIndicator.res" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFHudRobotDestruction_RobotIndicator::PerformLayout() { BaseClass::PerformLayout(); m_pSwoop->SetBounds( 0, 0, GetWide(), GetTall() ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFHudRobotDestruction_RobotIndicator::ApplySettings( KeyValues *inResourceData ) { BaseClass::ApplySettings( inResourceData ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFHudRobotDestruction_RobotIndicator::OnTick() { if ( !m_hGroup ) { SetVisible( false ); vgui::ivgui()->RemoveTickSignal( GetVPanel() ); } UpdateState(); DoUnderAttackBlink(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFHudRobotDestruction_RobotIndicator::DoUnderAttackBlink() { if ( !m_hGroup.Get() ) return; if ( gpGlobals->curtime < ( m_hGroup->GetLastAttackedTime() + ATTACK_BLINK_TIME ) && ( GetLocalPlayerTeam() == m_hGroup->GetTeamNumber() ) ) { // Pulse red ImagePanel* pGlow = dynamic_cast<ImagePanel*>( FindChildByName( "GlowImage", true ) ); if ( pGlow ) { float flAlpha = fabs(sin( gpGlobals->curtime * 10.f )) * 255; pGlow->SetAlpha( flAlpha ); } } else { // Stop pulsing, stop ticking ImagePanel* pGlow = dynamic_cast<ImagePanel*>( FindChildByName( "GlowImage", true ) ); if ( pGlow ) { pGlow->SetAlpha( 0 ); } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CTFHudRobotDestruction_RobotIndicator::GetGroupNumber() const { Assert( m_hGroup ); if ( !m_hGroup ) { return 0; } return m_hGroup->GetGroupNumber(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CTFHudRobotDestruction_RobotIndicator::GetTeamNumber() const { Assert( m_hGroup ); if ( !m_hGroup ) { return 0; } return m_hGroup->GetTeamNumber(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFHudRobotDestruction_RobotIndicator::UpdateState() { // Don't do anything if there's no group if ( !m_hGroup.Get() ) return; eRobotUIState eState = (eRobotUIState)m_hGroup->GetState(); // Get the time float flStartTime = m_hGroup->GetRespawnStartTime(); float flEndTime = m_hGroup->GetRespawnEndTime(); // Show how much time is remaining m_pDeadPanel->SetDialogVariable( "time", CFmtStr( "%0.0f", Max( 0.f, flEndTime - gpGlobals->curtime ) ) ); // Figure out what percentage we're at float flDuration = flEndTime - flStartTime; float flProgress = gpGlobals->curtime - flStartTime; m_pDeadPanel->SetProgress( flProgress / flDuration ); bool bStateVisibility[ NUM_ROBOT_STATES ]; memset( bStateVisibility, false, sizeof( bStateVisibility ) ); bool bDraw = eState != ROBOT_STATE_INACIVE; if ( bDraw ) { m_pRobotStateContainer->SetVisible( true ); bStateVisibility[ eState ] = true; } else { m_pRobotStateContainer->SetVisible( false ); } m_eState = eState; bool bShowDead = m_eState == ROBOT_STATE_DEAD; m_pActivePanel->SetImageVisible( !bShowDead ); m_pDeadPanel->SetVisible( bStateVisibility[ ROBOT_STATE_DEAD ] || bShowDead ); m_pActivePanel->SetVisible( bStateVisibility[ ROBOT_STATE_ACTIVE ] ); m_pShieldedPanel->SetVisible( bStateVisibility[ ROBOT_STATE_SHIELDED ] ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CTFHUDRobotDestruction::CTFHUDRobotDestruction( Panel *parent, const char *name ) : EditablePanel( parent, name ) , m_bPlayingRD( false ) { m_pPlayingTo = NULL; m_pRobotIndicatorKVs = NULL; m_pCarriedContainer = new EditablePanel( this, "CarriedContainer" ); m_pCarriedImage = new ImagePanel( m_pCarriedContainer, "CarriedImage" ); m_pCarriedFlagProgressBar = new CProgressPanel( m_pCarriedContainer, "CarriedProgressBar" ); m_pScoreContainer = new EditablePanel( this, "ScoreContainer" ); m_pBlueStolenContainer = new EditablePanel( m_pScoreContainer, "BlueStolenContainer" ); m_pBlueDroppedPanel = new EditablePanel( m_pBlueStolenContainer, "DroppedIntelContainer" ); m_pRedStolenContainer = new EditablePanel( m_pScoreContainer, "RedStolenContainer" ); m_pRedDroppedPanel = new EditablePanel( m_pRedStolenContainer, "DroppedIntelContainer" ); m_pBlueScoreValueContainer = new EditablePanel( m_pScoreContainer, "BlueScoreValueContainer" ); m_pRedScoreValueContainer = new EditablePanel( m_pScoreContainer, "RedScoreValueContainer" ); m_pProgressBarsContainer = new EditablePanel( m_pScoreContainer, "ProgressBarContainer" ); m_pBlueVictoryPanel = new EditablePanel( m_pProgressBarsContainer, "BlueVictoryContainer" ); m_pBlueProgressBar = new CProgressPanel( m_pProgressBarsContainer, "BlueProgressBarFill" ); m_pBlueProgressBarEscrow = new CProgressPanel( m_pProgressBarsContainer, "BlueProgressBarEscrow" ); m_pRedVictoryPanel = new EditablePanel( m_pProgressBarsContainer, "RedVictoryContainer" ); m_pRedProgressBar = new CProgressPanel( m_pProgressBarsContainer, "RedProgressBarFill" ); m_pRedProgressBarEscrow = new CProgressPanel( m_pProgressBarsContainer, "RedProgressBarEscrow" ); m_pCountdownContainer = NULL; m_pTeamLeaderImage = NULL; vgui::ivgui()->AddTickSignal( GetVPanel(), 50 ); ListenForGameEvent( "rd_rules_state_changed" ); ListenForGameEvent( "flagstatus_update" ); ListenForGameEvent( "rd_team_points_changed" ); ListenForGameEvent( "teamplay_round_start" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CTFHUDRobotDestruction::~CTFHUDRobotDestruction() { if ( m_pRobotIndicatorKVs ) { m_pRobotIndicatorKVs->deleteThis(); m_pRobotIndicatorKVs = NULL; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CTFHUDRobotDestruction::IsVisible( void ) { if( IsTakingAFreezecamScreenshot() ) return false; return BaseClass::IsVisible(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFHUDRobotDestruction::ApplySettings( KeyValues *inResourceData ) { BaseClass::ApplySettings( inResourceData ); KeyValues *pItemKV = inResourceData->FindKey( "robot_kv" ); if ( pItemKV ) { if ( m_pRobotIndicatorKVs ) { m_pRobotIndicatorKVs->deleteThis(); } m_pRobotIndicatorKVs = new KeyValues( "robot_kv" ); pItemKV->CopySubkeys( m_pRobotIndicatorKVs ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int SortRobotVec( CTFHudRobotDestruction_RobotIndicator * const *p1, CTFHudRobotDestruction_RobotIndicator * const *p2 ) { return (*p2)->GetGroupNumber() - (*p1)->GetGroupNumber(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFHUDRobotDestruction::ApplySchemeSettings( IScheme *pScheme ) { BaseClass::ApplySchemeSettings( pScheme ); CTFRobotDestructionLogic* pRoboLogic = CTFRobotDestructionLogic::GetRobotDestructionLogic(); if ( !pRoboLogic ) return; // load control settings... LoadControlSettings( pRoboLogic->GetResFile() ); // Clear out any old robot panels and bars m_vecRedRobots.PurgeAndDeleteElements(); m_vecBlueRobots.PurgeAndDeleteElements(); CUtlVector< CTFRobotDestruction_RobotGroup * > vecSeenGroups; // Go through all the groups in the map, and create a UI element for each one for ( int i=0; i<IRobotDestructionGroupAutoList::AutoList().Count(); ++i ) { CTFRobotDestruction_RobotGroup *pGroup = static_cast< CTFRobotDestruction_RobotGroup* >( IRobotDestructionGroupAutoList::AutoList()[i] ); if ( pGroup->IsDormant() ) continue; if ( vecSeenGroups.Find( pGroup ) != vecSeenGroups.InvalidIndex() ) { Assert( 0 ); DevMsg( "[RD HUD]: %p seen multiple times!\n", pGroup); continue; } vecSeenGroups.AddToTail( pGroup ); RobotVector_t &robotVec = pGroup->GetTeamNumber() == TF_TEAM_RED ? m_vecRedRobots : m_vecBlueRobots; const char* pszPanelName = pGroup->GetTeamNumber() == TF_TEAM_RED ? "red" : "blue"; robotVec[ robotVec.AddToTail() ] = new CTFHudRobotDestruction_RobotIndicator( this, CFmtStr( "%s_group_%d", pszPanelName, robotVec.Count() ), pGroup ); } // Sort them from lowest group to highest group m_vecRedRobots.Sort( &SortRobotVec ); m_vecBlueRobots.Sort( &SortRobotVec ); m_pCarriedContainer->SetVisible( false ); m_pCountdownContainer = dynamic_cast<EditablePanel*>( FindChildByName( "CountdownContainer" ) ); m_pTeamLeaderImage = dynamic_cast<CTFImagePanel*>( m_pCarriedContainer->FindChildByName( "TeamLeaderImage" ) ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFHUDRobotDestruction::PerformLayout() { BaseClass::PerformLayout(); // Sort them from lowest group to highest group m_vecRedRobots.Sort( &SortRobotVec ); m_vecBlueRobots.Sort( &SortRobotVec ); PerformRobotLayout( m_vecRedRobots, TF_TEAM_RED ); PerformRobotLayout( m_vecBlueRobots, TF_TEAM_BLUE ); int nXPos, nYPos; m_pProgressBarsContainer->GetPos( nXPos, nYPos ); // Store the edges of the score container m_nStealLeftEdge = nXPos + m_nStealLeftEdgeOffset - ( m_pRedStolenContainer->GetWide() / 2.f ); m_nStealRightEdge = nXPos + m_pProgressBarsContainer->GetWide() - m_nStealRightEdgeOffset + ( m_pRedStolenContainer->GetWide() / 2.f ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFHUDRobotDestruction::PerformRobotLayout( RobotVector_t& vecRobots, int nTeam ) { int nParentX = 0, nParentY = 0, nParentWide = 0, nParentTall = 0; GetBounds( nParentX, nParentY, nParentWide, nParentTall ); bool bIsRed = nTeam == TF_TEAM_RED; const int nCenterX = nParentX + ( nParentWide * 0.5f ); int nActiveIndex = 0; const int nXOffset = m_iRobotXOffset; const int nYOffest = nParentTall - m_iRobotYOffset; const int nXStep = m_iRobotXStep; const int nYStep = m_iRobotYStep; Panel *pPrevPanel = NULL; // Position the robot panels, spanning out from the bottom center FOR_EACH_VEC_BACK( vecRobots, i ) { CTFHudRobotDestruction_RobotIndicator* pRobot = vecRobots[i]; if ( pRobot ) { pRobot->ApplySettings( m_pRobotIndicatorKVs ); pRobot->UpdateState(); pRobot->SetZPos( vecRobots.Count() - i ); CTFHudRobotDestruction_RobotIndicator *pPrevRobot = dynamic_cast< CTFHudRobotDestruction_RobotIndicator * >( pPrevPanel ); if ( pPrevRobot ) { pRobot->SetPrevRobotIndicator( pPrevRobot ); pPrevRobot->SetNextRobotIndicator( pRobot ); } int nWide = pRobot->GetWide(); // The starting offset int nStartPos = ( ( nXOffset ) + ( nWide * 0.5f ) ) * (bIsRed ? 1 : -1); // The offset between each position int nOffset = bIsRed ? nXStep : -nXStep; int nXPos = nCenterX + nStartPos + ( nOffset * nActiveIndex ) - ( nWide * 0.5 ); pRobot->SetPos( nXPos, nYOffest - pRobot->GetTall() - ( nYStep * i ) ); pRobot->InvalidateLayout( true, true ); // If the state is anything but ROBOT_STATE_INACTIVE, then it's an active panel if ( pRobot->GetState() != ROBOT_STATE_INACIVE ) { pPrevPanel = pRobot; ++nActiveIndex; } } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFHUDRobotDestruction::Reset() { g_pClientMode->GetViewportAnimationController()->StartAnimationSequence( "FlagOutlineHide" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFHUDRobotDestruction::SetPlayingToLabelVisible( bool bVisible ) { if ( m_pPlayingTo && m_pPlayingToBG ) { if ( m_pPlayingTo->IsVisible() != bVisible ) { m_pPlayingTo->SetVisible( bVisible ); } if ( m_pPlayingToBG->IsVisible() != bVisible ) { m_pPlayingToBG->SetVisible( bVisible ); } } } #ifdef STAGING_ONLY ConVar rd_hud_test_bars( "rd_hud_test_bars", 0 ); #endif //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFHUDRobotDestruction::OnTick() { CTFRobotDestructionLogic* pRoboLogic = CTFRobotDestructionLogic::GetRobotDestructionLogic(); bool bPlayindRD = ( pRoboLogic != NULL ); if ( m_bPlayingRD != bPlayindRD ) { if ( bPlayindRD ) { InvalidateLayout( true, true ); } m_bPlayingRD = bPlayindRD; } if ( !pRoboLogic ) return; m_pRedScoreValueContainer->SetDialogVariable( "score", pRoboLogic->GetScore( TF_TEAM_RED ) ); m_pBlueScoreValueContainer->SetDialogVariable( "score", pRoboLogic->GetScore( TF_TEAM_BLUE ) ); #ifdef STAGING_ONLY if ( rd_hud_test_bars.GetBool() ) { float flProgress = (sin( gpGlobals->curtime ) * 0.5f) + 0.5f; m_pBlueProgressBar->SetProgress( flProgress, true ); m_pRedProgressBar->SetProgress( flProgress, true ); m_pBlueProgressBarEscrow->SetProgress( 0.f, true ); m_pRedProgressBarEscrow->SetProgress( 0.f, true ); m_pRedScoreValueContainer->SetDialogVariable( "score", flProgress ); m_pBlueScoreValueContainer->SetDialogVariable( "score", flProgress ); } else #endif { int nBlueEscrow = 0, nRedEscrow = 0; if ( pRoboLogic->GetType() == CTFRobotDestructionLogic::TYPE_PLAYER_DESTRUCTION ) { for ( int i=0; i<ICaptureFlagAutoList::AutoList().Count(); ++i ) { CCaptureFlag *pFlag = static_cast< CCaptureFlag* >( ICaptureFlagAutoList::AutoList()[i] ); if ( pFlag->IsStolen() && pFlag->GetPrevOwner() ) { int &nFriendScore = pFlag->GetPrevOwner()->GetTeamNumber() == TF_TEAM_RED ? nRedEscrow : nBlueEscrow; nFriendScore += pFlag->GetPointValue(); m_pRedDroppedPanel->SetAlpha( 255 ); } } if ( m_pProgressBarsContainer ) { m_pProgressBarsContainer->SetDialogVariable( "red_escrow", nRedEscrow ); m_pProgressBarsContainer->SetDialogVariable( "blue_escrow", nBlueEscrow ); } // update the team leader image if ( m_pTeamLeaderImage ) { bool bLocalplayerIsLeader = false; if ( CTFPlayer::GetLocalTFPlayer() && ( CTFPlayer::GetLocalTFPlayer()->GetTeamNumber() > LAST_SHARED_TEAM ) ) { if ( CTFPlayer::GetLocalTFPlayer() == pRoboLogic->GetTeamLeader( GetLocalPlayerTeam() ) ) { bLocalplayerIsLeader = true; } } if ( m_pTeamLeaderImage->IsVisible() != bLocalplayerIsLeader ) { m_pTeamLeaderImage->SetVisible( bLocalplayerIsLeader ); } } // update the countdowns if they exist if ( m_pCountdownContainer ) { float flTimeRemaining = pRoboLogic->GetCountdownEndTime() - gpGlobals->curtime; if ( flTimeRemaining > -1 ) { if ( !m_pCountdownContainer->IsVisible() ) { m_pCountdownContainer->SetVisible( true ); } ImagePanel* pCountdownImage = dynamic_cast<ImagePanel*>( m_pCountdownContainer->FindChildByName( "CountdownImage", true ) ); if ( pCountdownImage ) { bool bVisible = true; if ( pRoboLogic->IsUsingCustomCountdownImage() ) { const char *pszImage = pRoboLogic->GetCountdownImage(); if ( pszImage && pszImage[0] ) { pCountdownImage->SetImage( pszImage ); } else { bVisible = false; } } if ( pCountdownImage->IsVisible() != bVisible ) { pCountdownImage->SetVisible( bVisible ); } } CExLabel* pCountdownTime = dynamic_cast<CExLabel*>( m_pCountdownContainer->FindChildByName( "CountdownTime", true ) ); CExLabel* pCountdownTimeShadow = dynamic_cast<CExLabel*>( m_pCountdownContainer->FindChildByName( "CountdownTimeShadow", true ) ); if ( pCountdownTime ) { if ( !pCountdownTime->IsVisible() ) { pCountdownTime->SetVisible( true ); } } if ( pCountdownTimeShadow ) { if ( !pCountdownTimeShadow->IsVisible() ) { pCountdownTimeShadow->SetVisible( true ); } } int nCountdownTime = (int)flTimeRemaining; m_pCountdownContainer->SetDialogVariable( "countdowntime", ( nCountdownTime < 0 ) ? 0 : nCountdownTime ); } else { if ( m_pCountdownContainer->IsVisible() ) { m_pCountdownContainer->SetVisible( false ); } } } } else { // Find the flags if we dont have them yet if ( !m_hRedFlag || !m_hBlueFlag ) { for ( int i=0; i<ICaptureFlagAutoList::AutoList().Count(); ++i ) { CCaptureFlag *pFlag = static_cast< CCaptureFlag* >( ICaptureFlagAutoList::AutoList()[i] ); if ( pFlag->GetTeamNumber() == TF_TEAM_BLUE ) { m_hBlueFlag = pFlag; } else { m_hRedFlag = pFlag; } } if ( pRoboLogic->GetType() == CTFRobotDestructionLogic::TYPE_ROBOT_DESTRUCTION ) { Assert( m_hBlueFlag ); Assert( m_hRedFlag ); } } // A held flag counts towards the stealing team's escrow. // A dropped flag counts towards the original team's escrow. if ( m_hRedFlag && m_hBlueFlag ) { if ( m_hRedFlag->IsDropped() ) { nRedEscrow += m_hRedFlag->GetPointValue(); if ( m_hRedFlag->GetReturnProgress() > 0.8f ) { // Blink when we're close to returning int nAlpha = int( gpGlobals->curtime * 10 ) % 10 < 5 ? 255 : 0; m_pRedDroppedPanel->SetAlpha( nAlpha ); } } else { nBlueEscrow += m_hRedFlag->GetPointValue(); m_pRedDroppedPanel->SetAlpha( 255 ); } if ( m_hBlueFlag->IsDropped() ) { nBlueEscrow += m_hBlueFlag->GetPointValue(); if ( m_hBlueFlag->GetReturnProgress() > 0.8f ) { // Blink when we're close to returning int nAlpha = int( gpGlobals->curtime * 10 ) % 10 < 5 ? 255 : 0; m_pBlueDroppedPanel->SetAlpha( nAlpha ); } } else { nRedEscrow += m_hBlueFlag->GetPointValue(); m_pBlueDroppedPanel->SetAlpha( 255 ); } } } const float flFinaleTime = pRoboLogic->GetFinaleLength(); // Get red finale progress. We hide the big scores and show the finale countdown if at max score. float flFinaleProgress = clamp( pRoboLogic->GetFinaleWinTime( TF_TEAM_RED ) - gpGlobals->curtime, 0.f, pRoboLogic->GetFinaleLength() ); m_pRedVictoryPanel->SetVisible( flFinaleProgress < flFinaleTime ); m_pRedScoreValueContainer->SetVisible( flFinaleProgress >= flFinaleTime ); if ( flFinaleProgress < flFinaleTime ) { m_pRedVictoryPanel->SetDialogVariable( "victorytime", (int)flFinaleProgress ); } // Get blue finale progress. We hide the big scores and show the finale countdown if at max score. flFinaleProgress = clamp( pRoboLogic->GetFinaleWinTime( TF_TEAM_BLUE ) - gpGlobals->curtime, 0.f, pRoboLogic->GetFinaleLength() ); m_pBlueVictoryPanel->SetVisible( flFinaleProgress < flFinaleTime ); m_pBlueScoreValueContainer->SetVisible( flFinaleProgress >= flFinaleTime ); if ( flFinaleProgress < flFinaleTime ) { m_pBlueVictoryPanel->SetDialogVariable( "victorytime", (int)flFinaleProgress ); } const float flMaxPoints = pRoboLogic->GetMaxPoints(); int nTargetPoints = pRoboLogic->GetTargetScore( TF_TEAM_BLUE ); m_pBlueProgressBar->SetProgress( nTargetPoints / flMaxPoints ); m_pBlueProgressBarEscrow->SetProgress( ( nTargetPoints + nBlueEscrow ) / flMaxPoints ); nTargetPoints = pRoboLogic->GetTargetScore( TF_TEAM_RED ); m_pRedProgressBar->SetProgress( nTargetPoints / flMaxPoints ); m_pRedProgressBarEscrow->SetProgress( ( nTargetPoints + nRedEscrow ) / flMaxPoints ); } SetPlayingToLabelVisible( true ); SetDialogVariable( "rounds", pRoboLogic->GetMaxPoints() ); // HACK! Fix the events UpdateCarriedFlagStatus( NULL, NULL ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFHUDRobotDestruction::PaintBackground() { UpdateStolenPoints( TF_TEAM_RED, m_pRedStolenContainer ); UpdateStolenPoints( TF_TEAM_BLUE, m_pBlueStolenContainer ); BaseClass::PaintBackground(); } void CTFHUDRobotDestruction::PaintPDPlayerScore( const CTFPlayer* pPlayer ) { if ( !pPlayer ) return; // Don't draw the number for ourselves if ( pPlayer == C_BasePlayer::GetLocalPlayer() ) return; Vector vecPos = pPlayer->GetAbsOrigin(); vecPos.z += VEC_HULL_MAX_SCALED( pPlayer ).z + 20; int iX, iY; Vector vecWorld( vecPos.x, vecPos.y, vecPos.z ); if ( GetVectorInHudSpace( vecWorld, iX, iY ) ) { int iCurrentLeadingPoint = 0; if ( pPlayer->HasItem() ) { CCaptureFlag *pFlag = dynamic_cast<CCaptureFlag*>( pPlayer->GetItem() ); if ( pFlag ) { iCurrentLeadingPoint = pFlag->GetPointValue(); } } wchar_t wszScore[3]; V_snwprintf( wszScore, ARRAYSIZE( wszScore ), L"%d", iCurrentLeadingPoint ); const int nWidth = V_wcslen( wszScore ) * 15; // draw the name vgui::surface()->DrawSetTextFont( m_hPDPlayerScoreFont ); vgui::surface()->DrawSetTextPos( iX - ( nWidth / 2 ), iY ); vgui::surface()->DrawSetTextColor( m_TextColor ); vgui::surface()->DrawPrintText( wszScore, wcslen( wszScore ), vgui::FONT_DRAW_NONADDITIVE ); } } void CTFHUDRobotDestruction::Paint() { CTFRobotDestructionLogic* pRoboLogic = CTFRobotDestructionLogic::GetRobotDestructionLogic(); if ( pRoboLogic && pRoboLogic->GetType() == CTFRobotDestructionLogic::TYPE_PLAYER_DESTRUCTION ) { CTFPlayerDestructionLogic* pPDLogic = static_cast< CTFPlayerDestructionLogic* >( pRoboLogic ); PaintPDPlayerScore( pPDLogic->GetRedTeamLeader() ); PaintPDPlayerScore( pPDLogic->GetBlueTeamLeader() ); } BaseClass::Paint(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFHUDRobotDestruction::UpdateStolenPoints( int nTeam, EditablePanel* pContainer ) { CTFRobotDestructionLogic* pRoboLogic = CTFRobotDestructionLogic::GetRobotDestructionLogic(); if ( pRoboLogic ) { int nStolenPoints = 0; // Get the stolen score for this team CCaptureFlag* pTheirFlag = nTeam == TF_TEAM_RED ? m_hRedFlag : m_hBlueFlag; if ( pTheirFlag ) { nStolenPoints = pTheirFlag->GetPointValue(); } // Show the stolen panels if the stolen score is anything pContainer->SetVisible( nStolenPoints > 0 ); pContainer->SetDialogVariable( "intelvalue", nStolenPoints ); } // Find our stolen flag CCaptureFlag *pStolenFlag = nTeam == TF_TEAM_RED ? m_hRedFlag : m_hBlueFlag; if ( pStolenFlag && pStolenFlag->IsHome() ) { pStolenFlag = NULL; } C_CaptureZone *pStartCaptureZone = NULL, *pEndCaptureZone = NULL; // Go through all the capture zones and find ours and theirs for ( int i = 0; i<ICaptureZoneAutoList::AutoList().Count(); i++ ) { C_CaptureZone *pCaptureZone = static_cast< C_CaptureZone* >( ICaptureZoneAutoList::AutoList()[i] ); if ( !pCaptureZone->IsDormant() && !pCaptureZone->IsDisabled() ) { if ( pCaptureZone->GetTeamNumber() == nTeam ) { pStartCaptureZone = pCaptureZone; } else { pEndCaptureZone = pCaptureZone; } } } if ( pStolenFlag && pStartCaptureZone && pEndCaptureZone ) { // Use the player's pos if the flag is being carried Vector vecFlagPos = pStolenFlag->GetMoveParent() ? pStolenFlag->GetMoveParent()->GetAbsOrigin() : pStolenFlag->GetAbsOrigin(); // Get the distance of the flag between the cap points const float flTotalDist = ( pEndCaptureZone->WorldSpaceCenter() - pStartCaptureZone->WorldSpaceCenter() ).Length() - pEndCaptureZone->BoundingRadius() - pStartCaptureZone->BoundingRadius(); const float flFlagDist = ( pEndCaptureZone->WorldSpaceCenter() - vecFlagPos ).Length() - pEndCaptureZone->BoundingRadius(); const float flLerp = clamp( flFlagDist / flTotalDist, 0.f, 1.f ); // Flip for blue team const float flProgress = nTeam == TF_TEAM_BLUE ? ( 1.f - flLerp ) : flLerp; // Calc position int nWide = pContainer->GetWide(); const int nXpos = ( ( m_nStealRightEdge - ( m_nStealLeftEdge + nWide ) ) * flProgress ) + m_nStealLeftEdge; // Move the panel! int nDummy, nYpos; pContainer->GetPos( nDummy, nYpos ); pContainer->SetPos( nXpos, nYpos ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFHUDRobotDestruction::UpdateCarriedFlagStatus( C_BasePlayer *pNewOwner /*= NULL*/, C_BaseEntity *pFlagEntity /*= NULL*/ ) { C_TFPlayer *pLocalPlayer = ToTFPlayer( C_BasePlayer::GetLocalPlayer() ); // If this is about the other team, we dont care if ( pNewOwner && pNewOwner->GetTeamNumber() != pLocalPlayer->GetTeamNumber() ) { return; } // are we carrying a flag? CCaptureFlag *pPlayerFlag = NULL; if ( pLocalPlayer && pLocalPlayer->HasItem() && pLocalPlayer->GetItem()->GetItemID() == TF_ITEM_CAPTURE_FLAG ) { if ( !pNewOwner || pNewOwner == pLocalPlayer ) { pPlayerFlag = dynamic_cast< CCaptureFlag* >( pLocalPlayer->GetItem() ); } } if ( !pPlayerFlag && pLocalPlayer && pLocalPlayer == pNewOwner ) { pPlayerFlag = dynamic_cast< CCaptureFlag* >( pFlagEntity ); } if ( pPlayerFlag && !pPlayerFlag->IsMarkedForDeletion() && !pPlayerFlag->IsDormant() ) { m_pCarriedContainer->SetVisible( true ); m_pCarriedContainer->SetDialogVariable( "flagvalue", pPlayerFlag->GetPointValue() ); // make sure the panels are on, set the initial alpha values, // set the color of the flag we're carrying, and start the animations if ( m_pCarriedImage && !m_pCarriedImage->IsVisible() ) { int nTeam; if ( pPlayerFlag->GetType() == TF_FLAGTYPE_ATTACK_DEFEND || pPlayerFlag->GetType() == TF_FLAGTYPE_TERRITORY_CONTROL || pPlayerFlag->GetType() == TF_FLAGTYPE_INVADE || pPlayerFlag->GetType() == TF_FLAGTYPE_RESOURCE_CONTROL ) { nTeam = ( ( GetLocalPlayerTeam() == TF_TEAM_BLUE ) ? ( TF_TEAM_BLUE ) : ( TF_TEAM_RED ) ); } else { // normal CTF behavior (carrying the enemy flag) nTeam = ( ( GetLocalPlayerTeam() == TF_TEAM_RED ) ? ( TF_TEAM_BLUE ) : ( TF_TEAM_RED ) ); } m_pCarriedImage->SetVisible( true ); m_pCarriedFlagProgressBar->SetProgress( 0.f, true ); // Slam to 0 instantly m_pCarriedFlagProgressBar->SetColor( pLocalPlayer->GetTeamNumber() == TF_TEAM_RED ? m_ColorRed : m_ColorBlue ); } CTFRobotDestructionLogic* pRoboLogic = CTFRobotDestructionLogic::GetRobotDestructionLogic(); if ( pRoboLogic ) { int nMinToSteal = tf_rd_min_points_to_steal.GetInt(); // Current progress float flProgress = float( pPlayerFlag->GetPointValue() ) / float( pRoboLogic->GetMaxPoints() ); // What percentage needs to map to the dotted line const float flProgressAtDottedLine = float( nMinToSteal ) / float( pRoboLogic->GetMaxPoints() ); // This is where in the texture the dotted line is const float flWhereTheDottedLineIs = 0.25f; // We want the progress bar range from [0, The dotted line] map to the progress value [0, Min to steal] if ( flProgress <= flProgressAtDottedLine ) { flProgress = RemapValClamped( flProgress, 0.f, flProgressAtDottedLine, 0.f, flWhereTheDottedLineIs ); } else // Make the progress bar range from (The dotted line, 1] map to the progress value(Min to steal, 1] { flProgress = RemapValClamped( flProgress, flProgressAtDottedLine, 1.f, flWhereTheDottedLineIs, 1.f ); } m_pCarriedFlagProgressBar->SetProgress( flProgress ); } } else if ( m_pCarriedImage && m_pCarriedImage->IsVisible() ) { m_pCarriedContainer->SetVisible( false ); m_pCarriedImage->SetVisible( false ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFHUDRobotDestruction::UpdateRobotElements() { m_vecRedRobots.PurgeAndDeleteElements(); m_vecBlueRobots.PurgeAndDeleteElements(); InvalidateLayout( false, true ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFHUDRobotDestruction::UpdateStolenFlagStatus( int nTeam, C_BaseEntity *pFlag ) { CCaptureFlag *pPlayerFlag = dynamic_cast< CCaptureFlag* >( pFlag ); if ( pPlayerFlag ) { EditablePanel *pStolenContainer = nTeam == TF_TEAM_RED ? m_pRedStolenContainer : m_pBlueStolenContainer; Panel* pCarriedImage = pStolenContainer->FindChildByName( "IntelImage" ); Panel* pDownImage = pStolenContainer->FindChildByName( "DroppedIntelContainer" ); Assert( pCarriedImage && pDownImage ); if ( !pCarriedImage || !pDownImage ) return; // Toggle the carried or dropped images bool bIsDropped = pPlayerFlag->IsDropped(); pCarriedImage->SetVisible( !bIsDropped ); pDownImage->SetVisible( bIsDropped ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFHUDRobotDestruction::FireGameEvent( IGameEvent * pEvent ) { CTFRobotDestructionLogic* pRoboLogic = CTFRobotDestructionLogic::GetRobotDestructionLogic(); if ( !pRoboLogic ) return; const char *pszEventName = pEvent->GetName(); if ( FStrEq( "rd_rules_state_changed", pszEventName ) ) { UpdateRobotElements(); } else if ( FStrEq( pszEventName, "flagstatus_update" ) ) { int nVictimID = pEvent->GetInt( "userid" ); C_BasePlayer *pNewOwner = USERID2PLAYER( nVictimID ); int nFlagEntIndex = pEvent->GetInt( "entindex" ); C_BaseEntity *pFlagEntity = ClientEntityList().GetEnt( nFlagEntIndex ); if ( pFlagEntity ) { UpdateCarriedFlagStatus( pNewOwner, pFlagEntity ); UpdateStolenFlagStatus( pFlagEntity->GetTeamNumber(), pFlagEntity ); } } else if ( FStrEq( pszEventName, "rd_team_points_changed" ) ) { // Extract data int nTeam = pEvent->GetInt( "team" ); int nPoints = pEvent->GetInt( "points" ); RDScoreMethod_t eMethod = RDScoreMethod_t( pEvent->GetInt( "method" ) ); // Figure out which panel and which anim Panel *pPanel = nTeam == TF_TEAM_RED ? m_pRedScoreValueContainer : m_pBlueScoreValueContainer; bool bPositive = ( nTeam == GetLocalPlayerTeam() && nPoints > 0 ) || ( nTeam != GetLocalPlayerTeam() && nPoints < 0 ); const char *pszAnimName = bPositive ? "RDPositiveScorePulse" : "RDNegativeScorePulse"; g_pClientMode->GetViewportAnimationController()->StartAnimationSequence( pPanel, pszAnimName ); // Make the progress bar blink CProgressPanel *pProgressBar = nTeam == TF_TEAM_RED ? m_pRedProgressBar : m_pBlueProgressBar; pProgressBar->Blink(); if ( eMethod == SCORE_REACTOR_STEAL ) { // Make the OTHER team's escrow progress bar blink CProgressPanel *pEscrowBar = nTeam != TF_TEAM_RED ? m_pRedProgressBarEscrow : m_pBlueProgressBarEscrow; pEscrowBar->Blink(); } } else if ( FStrEq( pszEventName, "teamplay_round_start" ) ) { // Recalculate the progress speed float flApproachSpeed = ( tf_rd_points_per_approach.GetInt() / tf_rd_points_approach_interval.GetFloat() ) / pRoboLogic->GetMaxPoints(); m_pBlueProgressBar->SetApproachSpeed( flApproachSpeed ); m_pBlueProgressBarEscrow->SetApproachSpeed( flApproachSpeed ); m_pRedProgressBar->SetApproachSpeed( flApproachSpeed ); m_pRedProgressBarEscrow->SetApproachSpeed( flApproachSpeed ); } } CTFHUDRobotDestruction::CProgressPanel::CProgressPanel( vgui::Panel *parent, const char *name ) : BaseClass( parent, name ) , m_nXOrg( 0 ) , m_nYOrg( 0 ) , m_nWideOrg( 0 ) , m_nTallOrg( 0 ) , m_flLastScoreTime( 0.f ) , m_flEndProgress( 0.f ) , m_flCurrentProgress( 0.f ) , m_flLastTick( 0.f ) { ListenForGameEvent( "teamplay_round_start" ); } void CTFHUDRobotDestruction::CProgressPanel::CaptureBounds() { GetBounds( m_nXOrg, m_nYOrg, m_nWideOrg, m_nTallOrg ); if ( GetImage() ) { GetImage()->SetSize( m_nWideOrg, m_nTallOrg ); } } void CTFHUDRobotDestruction::CProgressPanel::SetProgress( float flProgress, bool bInstant /*= false*/ ) { if ( bInstant ) { m_flEndProgress = m_flCurrentProgress = flProgress; CalculateSize(); } else { // Start ticking if the progress is different if ( m_flEndProgress != flProgress ) { vgui::ivgui()->AddTickSignal( GetVPanel(), 0 ); m_flLastTick = gpGlobals->curtime; } // Set end target m_flEndProgress = flProgress; } } void CTFHUDRobotDestruction::CProgressPanel::OnTick() { float flDelta = gpGlobals->curtime - m_flLastTick; m_flLastTick = gpGlobals->curtime; // Approach the target progress amount m_flCurrentProgress = Approach( m_flEndProgress, m_flCurrentProgress, flDelta * m_flApproachSpeed ); // Stop ticking if we've met our progress if ( m_flCurrentProgress == m_flEndProgress ) { vgui::ivgui()->RemoveTickSignal( GetVPanel() ); } CalculateSize(); } void CTFHUDRobotDestruction::CProgressPanel::PaintBackground() { // Resize internal image in here. The other bars use this image too, so we have to move // it right before we paint or else it will be out of position. IImage *pImage = GetImage(); if ( pImage ) { pImage->SetPos( m_bLeftToRight ? -m_nLeftOffset : -m_flXpos, m_nYOrg ); pImage->SetSize( m_nWideOrg, m_nTallOrg ); } // Find out blink lerp time const float flBlinkPeriod = 0.25f; bool bPastBlink = gpGlobals->curtime > ( m_flLastScoreTime + flBlinkPeriod ); // Blink if it's blink time, or else pulse if within threshold, else just be the standard color float flLerp = bPastBlink ? ( m_flCurrentProgress >= m_flBlinkThreshold ? ( ( sin( gpGlobals->curtime * m_flBlinkRate ) * 0.5f ) + 0.5f ) : 1.f ) : ( (gpGlobals->curtime - m_flLastScoreTime) / flBlinkPeriod ); flLerp = clamp( flLerp, 0.f, 1.f ); const float flInverseLerp = 1.f - flLerp; // Get out lerped color Color drawColor( flInverseLerp * m_BrightColor.r() + flLerp * m_StandardColor.r(), flInverseLerp * m_BrightColor.g() + flLerp * m_StandardColor.g(), flInverseLerp * m_BrightColor.b() + flLerp * m_StandardColor.b(), 255 ); // Change color in base class (it uses it in PaintBackground) SetDrawColor( drawColor ); BaseClass::PaintBackground(); } void CTFHUDRobotDestruction::CProgressPanel::ApplySettings( KeyValues *inResourceData ) { BaseClass::ApplySettings( inResourceData ); int nXpos, nYpos; GetPos( nXpos, nYpos ); SetPos( nXpos + m_nLeftOffset, nYpos ); CaptureBounds(); CalculateSize(); } void CTFHUDRobotDestruction::CProgressPanel::Blink() { m_flLastScoreTime = gpGlobals->curtime; } void CTFHUDRobotDestruction::CProgressPanel::FireGameEvent( IGameEvent * pEvent ) { const char *pszEventName = pEvent->GetName(); if ( FStrEq( pszEventName, "teamplay_round_start" ) ) { // We need to reset the timers here in case we changelevel'd m_flCurrentProgress = 0.f; m_flEndProgress = 0.f; // Resize CalculateSize(); } } void CTFHUDRobotDestruction::CProgressPanel::CalculateSize() { // Find xpos int nProgressWidth = m_nWideOrg - m_nRightOffset - m_nLeftOffset; m_flXpos = m_bLeftToRight ? m_nXOrg : ( 1.f - m_flCurrentProgress) * nProgressWidth + m_nXOrg; // Find width m_flWidth = m_flCurrentProgress * nProgressWidth; // Resize SetBounds( m_flXpos, m_nYOrg, m_flWidth, m_nTallOrg ); }
//////////////////////////////////////////////////////////////////////////// // Module : script_game_object_script3.cpp // Created : 17.11.2004 // Modified : 17.11.2004 // Author : Dmitriy Iassenev // Description : Script game object class script export //////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "script_game_object.h" #include "ai_space.h" #include "script_engine.h" #include "cover_evaluators.h" #include "cover_point.h" #include "cover_manager.h" #include "ai/stalker/ai_stalker.h" #include "stalker_animation_manager.h" #include "stalker_planner.h" #include "weapon.h" #include "inventory.h" #include "customzone.h" #include "patrol_path_manager.h" #include "object_handler_planner.h" #include "object_handler_space.h" #include "memory_manager.h" #include "visual_memory_manager.h" #include "sound_memory_manager.h" #include "hit_memory_manager.h" #include "sight_manager.h" #include "stalker_movement_manager_smart_cover.h" #include "movement_manager_space.h" #include "detail_path_manager_space.h" #include "level_debug.h" #include "ai/monsters/BaseMonster/base_monster.h" #include "trade_parameters.h" #include "script_ini_file.h" #include "sound_player.h" #include "stalker_decision_space.h" #include "space_restriction_manager.h" namespace MemorySpace { struct CVisibleObject; struct CSoundObject; struct CHitObject; }; const CCoverPoint *CScriptGameObject::best_cover (const Fvector &position, const Fvector &enemy_position, float radius, float min_enemy_distance, float max_enemy_distance) { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CGameObject : cannot access class member best_cover!"); return (0); } stalker->m_ce_best->setup(enemy_position,min_enemy_distance,max_enemy_distance,0.f); const CCoverPoint *point = ai().cover_manager().best_cover(position,radius,*stalker->m_ce_best); return (point); } const CCoverPoint *CScriptGameObject::safe_cover (const Fvector &position, float radius, float min_distance) { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CGameObject : cannot access class member best_cover!"); return (0); } stalker->m_ce_safe->setup(min_distance); const CCoverPoint *point = ai().cover_manager().best_cover(position,radius,*stalker->m_ce_safe); return (point); } const xr_vector<MemorySpace::CVisibleObject> &CScriptGameObject::memory_visible_objects () const { CCustomMonster *monster = smart_cast<CCustomMonster*>(&object()); if (!monster) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CGameObject : cannot access class member memory_visible_objects!"); NODEFAULT; } return (monster->memory().visual().objects()); } const xr_vector<MemorySpace::CSoundObject> &CScriptGameObject::memory_sound_objects () const { CCustomMonster *monster = smart_cast<CCustomMonster*>(&object()); if (!monster) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CGameObject : cannot access class member memory_sound_objects!"); NODEFAULT; } return (monster->memory().sound().objects()); } const xr_vector<MemorySpace::CHitObject> &CScriptGameObject::memory_hit_objects () const { CCustomMonster *monster = smart_cast<CCustomMonster*>(&object()); if (!monster) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CGameObject : cannot access class member memory_hit_objects!"); NODEFAULT; } return (monster->memory().hit().objects()); } void CScriptGameObject::ChangeTeam(u8 team, u8 squad, u8 group) { CCustomMonster *custom_monster = smart_cast<CCustomMonster*>(&object()); if (!custom_monster) ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CCustomMonster: cannot access class member ChangeTeam!"); else custom_monster->ChangeTeam(team,squad,group); } void CScriptGameObject::SetVisualMemoryEnabled (bool enabled) { CCustomMonster *custom_monster = smart_cast<CCustomMonster*>(&object()); if (!custom_monster) ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CCustomMonster: cannot access class member ChangeTeam!"); else custom_monster->memory().visual().enable(enabled); } CScriptGameObject *CScriptGameObject::GetEnemy() const { CCustomMonster *l_tpCustomMonster = smart_cast<CCustomMonster*>(&object()); if (l_tpCustomMonster && l_tpCustomMonster->g_Alive() ) { if (l_tpCustomMonster->GetCurrentEnemy() && !l_tpCustomMonster->GetCurrentEnemy()->getDestroy()) return (l_tpCustomMonster->GetCurrentEnemy()->lua_game_object()); else return (0); } else { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CScriptGameObject : cannot access class member GetEnemy!"); return (0); } } CScriptGameObject *CScriptGameObject::GetCorpse() const { CCustomMonster *l_tpCustomMonster = smart_cast<CCustomMonster*>(&object()); if (l_tpCustomMonster) if (l_tpCustomMonster->GetCurrentCorpse() && !l_tpCustomMonster->GetCurrentCorpse()->getDestroy()) return (l_tpCustomMonster->GetCurrentCorpse()->lua_game_object()); else return (0); else { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CScriptGameObject : cannot access class member GetCorpse!"); return (0); } } bool CScriptGameObject::CheckTypeVisibility(const char *section_name) { CCustomMonster *l_tpCustomMonster = smart_cast<CCustomMonster*>(&object()); if (l_tpCustomMonster) return (l_tpCustomMonster->CheckTypeVisibility(section_name)); else { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CScriptGameObject : cannot access class member CheckTypeVisibility!"); return (false); } } CScriptGameObject *CScriptGameObject::GetCurrentWeapon() const { CAI_Stalker *l_tpStalker = smart_cast<CAI_Stalker*>(&object()); if (!l_tpStalker) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member GetCurrentWeapon!"); return (0); } CGameObject *current_weapon = l_tpStalker->GetCurrentWeapon(); return (current_weapon ? current_weapon->lua_game_object() : 0); } void CScriptGameObject::deadbody_closed(bool status) { CInventoryOwner *inventoryOwner = smart_cast<CInventoryOwner*>(&object()); if (!inventoryOwner) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CInventoryOwner : cannot access class member deadbody_closed!"); return; } inventoryOwner->deadbody_closed(status); } bool CScriptGameObject::deadbody_closed_status() { CInventoryOwner *inventoryOwner = smart_cast<CInventoryOwner*>(&object()); if (!inventoryOwner) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CInventoryOwner : cannot access class member deadbody_closed_status!"); return (0); } return inventoryOwner->deadbody_closed_status(); } void CScriptGameObject::can_select_weapon(bool status) { CAI_Stalker* stalker = smart_cast<CAI_Stalker*>(&object()); if(!stalker) { ai().script_engine().script_log(ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member can_select_weapon!"); return; } stalker->can_select_weapon(status); } bool CScriptGameObject::can_select_weapon() const { CAI_Stalker* stalker = smart_cast<CAI_Stalker*>(&object()); if(!stalker) { ai().script_engine().script_log(ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member can_select_weapon!"); return(0); } return stalker->can_select_weapon(); } void CScriptGameObject::deadbody_can_take(bool status) { CInventoryOwner *inventoryOwner = smart_cast<CInventoryOwner*>(&object()); if (!inventoryOwner) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CInventoryOwner : cannot access class member deadbody_can_take!"); return; } inventoryOwner->deadbody_can_take(status); } bool CScriptGameObject::deadbody_can_take_status() { CInventoryOwner *inventoryOwner = smart_cast<CInventoryOwner*>(&object()); if (!inventoryOwner) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CInventoryOwner : cannot access class member deadbody_can_take_status!"); return (0); } return inventoryOwner->deadbody_can_take_status(); } #include "CustomOutfit.h" CScriptGameObject *CScriptGameObject::GetCurrentOutfit() const { CInventoryOwner *inventoryOwner = smart_cast<CInventoryOwner*>(&object()); if (!inventoryOwner) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CInventoryOwner : cannot access class member GetCurrentOutfit!"); return (0); } CGameObject *current_equipment = inventoryOwner->GetOutfit(); return (current_equipment ? current_equipment->lua_game_object() : 0); } float CScriptGameObject::GetCurrentOutfitProtection(int hit_type) { CInventoryOwner *inventoryOwner = smart_cast<CInventoryOwner*>(&object()); if (!inventoryOwner) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CInventoryOwner : cannot access class member GetCurrentOutfitProtection!"); return (0); } CGameObject *current_equipment = inventoryOwner->GetOutfit(); CCustomOutfit* o = smart_cast<CCustomOutfit*>(current_equipment); if(!o) return 0.0f; return o->GetDefHitTypeProtection(ALife::EHitType(hit_type)); } CScriptGameObject *CScriptGameObject::GetFood() const { CAI_Stalker *l_tpStalker = smart_cast<CAI_Stalker*>(&object()); if (!l_tpStalker) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member GetFood!"); return (0); } CGameObject *food = l_tpStalker->GetFood() ? &l_tpStalker->GetFood()->object() : 0; return (food ? food->lua_game_object() : 0); } CScriptGameObject *CScriptGameObject::GetMedikit() const { CAI_Stalker *l_tpStalker = smart_cast<CAI_Stalker*>(&object()); if (!l_tpStalker) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member GetCurrentWeapon!"); return (0); } CGameObject *medikit = l_tpStalker->GetMedikit() ? &l_tpStalker->GetMedikit()->object() : 0; return (medikit ? medikit->lua_game_object() : 0); } LPCSTR CScriptGameObject::GetPatrolPathName() { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) { CScriptEntity *script_monster = smart_cast<CScriptEntity*>(&object()); if (!script_monster) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CGameObject : cannot access class member GetPatrolPathName!"); return (""); } else return (script_monster->GetPatrolPathName()); } else return (*stalker->movement().patrol().path_name()); } void CScriptGameObject::add_animation (LPCSTR animation, bool hand_usage, bool use_movement_controller) { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CGameObject : cannot access class member add_animation!"); return; } if (stalker->movement().current_params().cover()) { ai().script_engine().script_log(eLuaMessageTypeError,"Cannot add animation [%s]: object [%s] is in smart_cover!", animation, stalker->cName().c_str()); } if (stalker->animation().global_selector()) { ai().script_engine().script_log( eLuaMessageTypeError, "Cannot add animation [%s]: global selector is set for object [%s], in_smart_cover returned [%s]!", animation, stalker->cName().c_str(), in_smart_cover() ? "true" : "false" ); return; } stalker->animation().add_script_animation(animation,hand_usage,use_movement_controller); } void CScriptGameObject::add_animation (LPCSTR animation, bool hand_usage, Fvector position, Fvector rotation, bool local_animation) { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CGameObject : cannot access class member add_animation!"); return; } if (stalker->movement().current_params().cover()) { ai().script_engine().script_log(eLuaMessageTypeError,"Cannot add animation [%s]: object [%s] is in smart_cover!", animation, stalker->cName().c_str()); } if (stalker->animation().global_selector()) { ai().script_engine().script_log( eLuaMessageTypeError, "Cannot add animation [%s]: global selector is set for object [%s], in_smart_cover returned [%s]!", animation, stalker->cName().c_str(), in_smart_cover() ? "true" : "false" ); return; } stalker->animation().add_script_animation( animation, hand_usage, position, rotation, local_animation); } void CScriptGameObject::clear_animations () { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CGameObject : cannot access class member clear_animations!"); return; } stalker->animation().clear_script_animations(); } int CScriptGameObject::animation_count () const { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CGameObject : cannot access class member clear_animations!"); return (-1); } return ((int)stalker->animation().script_animations().size()); } Flags32 CScriptGameObject::get_actor_relation_flags () const { CAI_Stalker* stalker = smart_cast<CAI_Stalker*>(&object()); THROW(stalker); return stalker->m_actor_relation_flags; } void CScriptGameObject::set_actor_relation_flags (Flags32 flags) { CAI_Stalker* stalker = smart_cast<CAI_Stalker*>(&object()); THROW(stalker); stalker->m_actor_relation_flags = flags; } void CScriptGameObject::set_patrol_path (LPCSTR path_name, const PatrolPathManager::EPatrolStartType patrol_start_type, const PatrolPathManager::EPatrolRouteType patrol_route_type, bool random) { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member movement!"); else stalker->movement().patrol().set_path (path_name,patrol_start_type,patrol_route_type,random); } void CScriptGameObject::inactualize_patrol_path () { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member movement!"); else stalker->movement().patrol().make_inactual(); } void CScriptGameObject::set_dest_level_vertex_id(u32 level_vertex_id) { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member set_dest_level_vertex_id!"); else { if (!ai().level_graph().valid_vertex_id(level_vertex_id)) { #ifdef DEBUG ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : invalid vertex id being setup by action %s!",stalker->brain().CStalkerPlanner::current_action().m_action_name); #endif return; } if (!stalker->movement().restrictions().accessible(level_vertex_id)) { ai().script_engine().script_log ( ScriptStorage::eLuaMessageTypeError, "! you are trying to setup destination for the stalker %s, which is not accessible by its restrictors in[%s] out[%s]", stalker->cName().c_str(), Level().space_restriction_manager().in_restrictions (stalker->ID()).c_str(), Level().space_restriction_manager().out_restrictions(stalker->ID()).c_str() ); return; } stalker->movement().set_level_dest_vertex (level_vertex_id); } } void CScriptGameObject::set_dest_game_vertex_id( GameGraph::_GRAPH_ID game_vertex_id) { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member set_dest_game_vertex_id!"); else { if (!ai().game_graph().valid_vertex_id(game_vertex_id)) { #ifdef DEBUG ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : invalid vertex id being setup by action %s!",stalker->brain().CStalkerPlanner::current_action().m_action_name); #endif return; } stalker->movement().set_game_dest_vertex(game_vertex_id); } } void CScriptGameObject::set_movement_selection_type(ESelectionType selection_type){ CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member set_movement_selection_type!"); stalker->movement().game_selector().set_selection_type (selection_type); } CHARACTER_RANK_VALUE CScriptGameObject::GetRank () { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member GetRank!"); return (CHARACTER_RANK_VALUE(0)); } else return (stalker->Rank()); } void CScriptGameObject::set_desired_position () { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member movement!"); else stalker->movement().set_desired_position (0); } void CScriptGameObject::set_desired_position (const Fvector *desired_position) { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member movement!"); else { THROW2 (desired_position || stalker->movement().restrictions().accessible(*desired_position),*stalker->cName()); stalker->movement().set_desired_position (desired_position); } } void CScriptGameObject::set_desired_direction () { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member movement!"); else stalker->movement().set_desired_direction (0); } void CScriptGameObject::set_desired_direction (const Fvector *desired_direction) { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member movement!"); else { if (fsimilar(desired_direction->magnitude(), 0.f)) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : [%s] set_desired_direction - you passed zero direction!", stalker->cName().c_str()); //ai().script_engine().print_stack(); } else { if (!fsimilar(desired_direction->magnitude(), 1.f)) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : [%s] set_desired_direction - you passed non-normalized direction!", stalker->cName().c_str()); //ai().script_engine().print_stack(); } } Fvector direction = *desired_direction; direction.normalize_safe (); stalker->movement().set_desired_direction (&direction); } } void CScriptGameObject::set_body_state (EBodyState body_state) { THROW ((body_state == eBodyStateStand) || (body_state == eBodyStateCrouch)); CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member movement!"); else stalker->movement().set_body_state (body_state); } void CScriptGameObject::set_movement_type (EMovementType movement_type) { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member movement!"); else stalker->movement().set_movement_type (movement_type); } void CScriptGameObject::set_mental_state (EMentalState mental_state) { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member movement!"); else { #if 0//def DEBUG if (mental_state != eMentalStateDanger) { if (stalker->brain().initialized()) { if (stalker->brain().current_action_id() == StalkerDecisionSpace::eWorldOperatorCombatPlanner) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : set_mental_state is used during universal combat!, object[%s]", stalker->cName().c_str()); // return; } } } #endif // DEBUG stalker->movement().set_mental_state (mental_state); } } void CScriptGameObject::set_path_type (MovementManager::EPathType path_type) { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member movement!"); else stalker->movement().set_path_type (path_type); } void CScriptGameObject::set_detail_path_type (DetailPathManager::EDetailPathType detail_path_type) { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member movement!"); else stalker->movement().set_detail_path_type (detail_path_type); } MonsterSpace::EBodyState CScriptGameObject::body_state () const { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member body_state!"); return (MonsterSpace::eBodyStateStand); } return (stalker->movement().body_state()); } MonsterSpace::EBodyState CScriptGameObject::target_body_state () const { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member body_state!"); return (MonsterSpace::eBodyStateStand); } return (stalker->movement().target_body_state()); } MonsterSpace::EMovementType CScriptGameObject::movement_type () const { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member movement_type!"); return (MonsterSpace::eMovementTypeStand); } return (stalker->movement().movement_type()); } MonsterSpace::EMovementType CScriptGameObject::target_movement_type () const { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member target_movement_type!"); return (MonsterSpace::eMovementTypeStand); } return (stalker->movement().target_movement_type()); } MonsterSpace::EMentalState CScriptGameObject::mental_state () const { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member mental_state!"); return (MonsterSpace::eMentalStateDanger); } return (stalker->movement().mental_state()); } MonsterSpace::EMentalState CScriptGameObject::target_mental_state () const { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member mental_state!"); return (MonsterSpace::eMentalStateDanger); } return (stalker->movement().target_mental_state()); } MovementManager::EPathType CScriptGameObject::path_type () const { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member path_type!"); return (MovementManager::ePathTypeNoPath); } return (stalker->movement().path_type()); } DetailPathManager::EDetailPathType CScriptGameObject::detail_path_type () const { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member detail_path_type!"); return (DetailPathManager::eDetailPathTypeSmooth); } return (DetailPathManager::eDetailPathTypeSmooth); } void CScriptGameObject::set_sight (SightManager::ESightType sight_type, Fvector *vector3d, u32 dwLookOverDelay) { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CSightManager : cannot access class member set_sight!"); else { if ( (sight_type == SightManager::eSightTypeDirection) && vector3d && (_abs(vector3d->magnitude() - 1.f) > .01f) ) { VERIFY2 ( false, make_string("non-normalized direction passed [%f][%f][%f]", VPUSH(*vector3d)) ); vector3d->normalize ( ); } stalker->sight().setup (sight_type,vector3d); } } void CScriptGameObject::set_sight (SightManager::ESightType sight_type, bool torso_look, bool path) { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CSightManager : cannot access class member set_sight!"); else stalker->sight().setup (sight_type,torso_look,path); } void CScriptGameObject::set_sight (SightManager::ESightType sight_type, Fvector &vector3d, bool torso_look = false) { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CSightManager : cannot access class member set_sight!"); else { if ( (sight_type == SightManager::eSightTypeDirection) && (_abs(vector3d.magnitude() - 1.f) > .01f) ) { VERIFY2 ( false, make_string("non-normalized direction passed [%f][%f][%f]", VPUSH(vector3d)) ); vector3d.normalize ( ); } stalker->sight().setup (sight_type,vector3d,torso_look); } } void CScriptGameObject::set_sight (SightManager::ESightType sight_type, Fvector *vector3d) { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CSightManager : cannot access class member set_sight!"); else { if ( (sight_type == SightManager::eSightTypeDirection) && vector3d && (_abs(vector3d->magnitude() - 1.f) > .01f) ) { VERIFY2 ( false, make_string("non-normalized direction passed [%f][%f][%f]", VPUSH(*vector3d)) ); vector3d->normalize ( ); } stalker->sight().setup (sight_type,vector3d); } } void CScriptGameObject::set_sight (CScriptGameObject *object_to_look) { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CSightManager : cannot access class member set_sight!"); else stalker->sight().setup (&object_to_look->object()); } void CScriptGameObject::set_sight (CScriptGameObject *object_to_look, bool torso_look) { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CSightManager : cannot access class member set_sight!"); else stalker->sight().setup (&object_to_look->object(),torso_look); } void CScriptGameObject::set_sight (CScriptGameObject *object_to_look, bool torso_look, bool fire_object) { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CSightManager : cannot access class member set_sight!"); else stalker->sight().setup (&object_to_look->object(),torso_look,fire_object); } void CScriptGameObject::set_sight (CScriptGameObject *object_to_look, bool torso_look, bool fire_object, bool no_pitch) { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CSightManager : cannot access class member set_sight!"); else stalker->sight().setup (CSightAction(&object_to_look->object(),torso_look,fire_object,no_pitch)); } void CScriptGameObject::set_sight (const CMemoryInfo *memory_object, bool torso_look) { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CSightManager : cannot access class member set_sight!"); else stalker->sight().setup (memory_object,torso_look); } // CAI_Stalker ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// u32 CScriptGameObject::GetInventoryObjectCount() const { CInventoryOwner *l_tpInventoryOwner = smart_cast<CInventoryOwner*>(&object()); if (l_tpInventoryOwner) return (l_tpInventoryOwner->inventory().dwfGetObjectCount()); else { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CScriptGameObject : cannot access class member obj_count!"); return (0); } } CScriptGameObject *CScriptGameObject::GetActiveItem() { CInventoryOwner *l_tpInventoryOwner = smart_cast<CInventoryOwner*>(&object()); if (l_tpInventoryOwner) if (l_tpInventoryOwner->inventory().ActiveItem()) return (l_tpInventoryOwner->inventory().ActiveItem()->object().lua_game_object()); else return (0); else { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CScriptGameObject : cannot access class member activge_item!"); return (0); } } CScriptGameObject *CScriptGameObject::GetObjectByName (LPCSTR caObjectName) const { CInventoryOwner *l_tpInventoryOwner = smart_cast<CInventoryOwner*>(&object()); if (l_tpInventoryOwner) { CInventoryItem *l_tpInventoryItem = l_tpInventoryOwner->inventory().GetItemFromInventory(caObjectName); CGameObject *l_tpGameObject = smart_cast<CGameObject*>(l_tpInventoryItem); if (!l_tpGameObject) return (0); else return (l_tpGameObject->lua_game_object()); } else { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CScriptGameObject : cannot access class member object!"); return (0); } } CScriptGameObject *CScriptGameObject::GetObjectByIndex (int iIndex) const { CInventoryOwner *l_tpInventoryOwner = smart_cast<CInventoryOwner*>(&object()); if (l_tpInventoryOwner) { CInventoryItem *l_tpInventoryItem = l_tpInventoryOwner->inventory().tpfGetObjectByIndex(iIndex); CGameObject *l_tpGameObject = smart_cast<CGameObject*>(l_tpInventoryItem); if (!l_tpGameObject) return (0); else return (l_tpGameObject->lua_game_object()); } else { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CScriptGameObject : cannot access class member object!"); return (0); } } void CScriptGameObject::EnableAnomaly() { CCustomZone *zone = smart_cast<CCustomZone*>(&object()); THROW(zone); zone->ZoneEnable(); } void CScriptGameObject::DisableAnomaly() { CCustomZone *zone = smart_cast<CCustomZone*>(&object()); THROW(zone); zone->ZoneDisable(); } float CScriptGameObject::GetAnomalyPower() { CCustomZone *zone = smart_cast<CCustomZone*>(&object()); THROW(zone); return zone->GetMaxPower(); } void CScriptGameObject::SetAnomalyPower(float p) { CCustomZone *zone = smart_cast<CCustomZone*>(&object()); THROW(zone); zone->SetMaxPower(p); } bool CScriptGameObject::weapon_strapped () const { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CScriptGameObject : cannot access class member weapon_strapped!"); return (false); } bool const result = stalker->weapon_strapped(); // Msg ( "[%6d][%s] weapon_strapped = %s", Device.dwTimeGlobal, stalker->cName().c_str(), result ? "true" : "false" ); return (result); } bool CScriptGameObject::weapon_unstrapped () const { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CScriptGameObject : cannot access class member weapon_unstrapped!"); return (false); } bool const result = stalker->weapon_unstrapped(); // Msg ( "[%6d][%s] weapon_unstrapped = %s", Device.dwTimeGlobal, stalker->cName().c_str(), result ? "true" : "false" ); return (result); } bool CScriptGameObject::path_completed () const { CCustomMonster *monster = smart_cast<CCustomMonster*>(&object()); if (!monster) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CScriptGameObject : cannot access class member path_completed!"); return (false); } return (monster->movement().path_completed()); } void CScriptGameObject::patrol_path_make_inactual () { CCustomMonster *monster = smart_cast<CCustomMonster*>(&object()); if (!monster) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CScriptGameObject : cannot access class member patrol_path_make_inactual!"); return; } monster->movement().patrol().make_inactual(); } Fvector CScriptGameObject::head_orientation () const { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&object()); if (!stalker) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CScriptGameObject : cannot access class member head_orientation!"); return (Fvector().set(flt_max,flt_max,flt_max)); } const SRotation &r = stalker->movement().head_orientation().current; return (Fvector().setHP(-r.yaw,-r.pitch)); } void CScriptGameObject::info_add(LPCSTR text) { #ifdef DEBUG DBG().object_info(&object(),this).add_item (text, D3DCOLOR_XRGB(255,0,0), 0); #endif } void CScriptGameObject::info_clear() { #ifdef DEBUG DBG().object_info(&object(),this).clear (); #endif } void CScriptGameObject::jump(const Fvector &position, float factor) { CBaseMonster *monster = smart_cast<CBaseMonster*>(&object()); if (!monster) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CScriptGameObject : cannot process jump for not a monster!"); return; } monster->jump(position, factor); } void CScriptGameObject::make_object_visible_somewhen (CScriptGameObject *object) { CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(&this->object()); if (!stalker) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member make_object_visible_somewhen!"); return; } CEntityAlive *entity_alive = smart_cast<CEntityAlive*>(&object->object()); if (!entity_alive) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CEntityAlive : cannot access class member make_object_visible_somewhen!"); return; } stalker->memory().make_object_visible_somewhen (entity_alive); } void CScriptGameObject::sell_condition (CScriptIniFile *ini_file, LPCSTR section) { CInventoryOwner *inventory_owner = smart_cast<CInventoryOwner*>(&object()); if (!inventory_owner) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CInventoryOwner : cannot access class member sell_condition!"); return; } inventory_owner->trade_parameters().process (CTradeParameters::action_sell(0),*ini_file,section); } void CScriptGameObject::sell_condition (float friend_factor, float enemy_factor) { CInventoryOwner *inventory_owner = smart_cast<CInventoryOwner*>(&object()); if (!inventory_owner) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CInventoryOwner : cannot access class member sell_condition!"); return; } inventory_owner->trade_parameters().default_factors ( CTradeParameters::action_sell(0), CTradeFactors( friend_factor, enemy_factor ) ); } void CScriptGameObject::buy_condition (CScriptIniFile *ini_file, LPCSTR section) { CInventoryOwner *inventory_owner = smart_cast<CInventoryOwner*>(&object()); if (!inventory_owner) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CInventoryOwner : cannot access class member buy_condition!"); return; } inventory_owner->trade_parameters().process (CTradeParameters::action_buy(0),*ini_file,section); } void CScriptGameObject::buy_condition (float friend_factor, float enemy_factor) { CInventoryOwner *inventory_owner = smart_cast<CInventoryOwner*>(&object()); if (!inventory_owner) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CInventoryOwner : cannot access class member buy_condition!"); return; } inventory_owner->trade_parameters().default_factors ( CTradeParameters::action_buy(0), CTradeFactors( friend_factor, enemy_factor ) ); } void CScriptGameObject::show_condition (CScriptIniFile *ini_file, LPCSTR section) { CInventoryOwner *inventory_owner = smart_cast<CInventoryOwner*>(&object()); if (!inventory_owner) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CInventoryOwner : cannot access class member show_condition!"); return; } inventory_owner->trade_parameters().process ( CTradeParameters::action_show(0), *ini_file, section ); } void CScriptGameObject::buy_supplies (CScriptIniFile *ini_file, LPCSTR section) { CInventoryOwner *inventory_owner = smart_cast<CInventoryOwner*>(&object()); if (!inventory_owner) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CInventoryOwner : cannot access class member buy_condition!"); return; } inventory_owner->buy_supplies( *ini_file, section ); } void CScriptGameObject::buy_item_condition_factor(float factor) { CInventoryOwner *inventory_owner = smart_cast<CInventoryOwner*>(&object()); if (!inventory_owner) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CInventoryOwner : cannot access class member buy_item_condition_factor!"); return; } inventory_owner->trade_parameters().buy_item_condition_factor = factor; } void sell_condition (CScriptIniFile *ini_file, LPCSTR section) { default_trade_parameters().process (CTradeParameters::action_sell(0),*ini_file,section); } void sell_condition (float friend_factor, float enemy_factor) { default_trade_parameters().default_factors ( CTradeParameters::action_sell(0), CTradeFactors( friend_factor, enemy_factor ) ); } void buy_condition (CScriptIniFile *ini_file, LPCSTR section) { default_trade_parameters().process (CTradeParameters::action_buy(0),*ini_file,section); } void buy_condition (float friend_factor, float enemy_factor) { default_trade_parameters().default_factors ( CTradeParameters::action_buy(0), CTradeFactors( friend_factor, enemy_factor ) ); } void show_condition (CScriptIniFile *ini_file, LPCSTR section) { default_trade_parameters().process (CTradeParameters::action_show(0),*ini_file,section); } LPCSTR CScriptGameObject::sound_prefix () const { CCustomMonster *custom_monster = smart_cast<CCustomMonster*>(&object()); if (!custom_monster) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CCustomMonster : cannot access class member sound_prefix!"); return (0); } return (*custom_monster->sound().sound_prefix()); } void CScriptGameObject::sound_prefix (LPCSTR sound_prefix) { CCustomMonster *custom_monster = smart_cast<CCustomMonster*>(&object()); if (!custom_monster) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CCustomMonster : cannot access class member sound_prefix!"); return; } custom_monster->sound().sound_prefix (sound_prefix); } bool CScriptGameObject::is_weapon_going_to_be_strapped ( CScriptGameObject const* object ) const { if ( !object ) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CGameObject : cannot access class member is_weapon_going_to_be_strapped (object passed is null)!"); return false; } CAI_Stalker const *stalker = smart_cast<CAI_Stalker const*>( &this->object() ); if (!stalker) { ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CGameObject : cannot access class member is_weapon_going_to_be_strapped!"); return false; } return stalker->is_weapon_going_to_be_strapped ( &object->object() ); }
/********************************************************************** * * This source code is part of the Tree-based Network Optimizer (TORO) * * TORO Copyright (c) 2007 Giorgio Grisetti, Cyrill Stachniss, * Slawomir Grzonka, and Wolfram Burgard * * TORO is licences under the Common Creative License, * Attribution-NonCommercial-ShareAlike 3.0 * * You are free: * - to Share - to copy, distribute and transmit the work * - to Remix - to adapt the work * * Under the following conditions: * * - Attribution. You must attribute the work in the manner specified * by the author or licensor (but not in any way that suggests that * they endorse you or your use of the work). * * - Noncommercial. You may not use this work for commercial purposes. * * - Share Alike. If you alter, transform, or build upon this work, * you may distribute the resulting work only under the same or * similar license to this one. * * Any of the above conditions can be waived if you get permission * from the copyright holder. Nothing in this license impairs or * restricts the author's moral rights. * * TORO 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. **********************************************************************/ /** \file treeoptimizer3.cpp * * \brief Defines the core optimizer class for 3D graphs which is a * subclass of TreePoseGraph3 * **/ #include "treeoptimizer3.hh" #include <fstream> #include <sstream> #include <string> using namespace std; namespace AISNavigation { //#define DEBUG(i) if (verboseLevel>i) cerr TreeOptimizer3::TreeOptimizer3(){ restartOnDivergence=false; sortedEdges=0; mpl=-1; edgeCompareMode=EVComparator<Edge*>::CompareLevel; } TreeOptimizer3::~TreeOptimizer3(){ } void TreeOptimizer3::initializeTreeParameters(){ ParameterPropagator pp; treeDepthVisit(pp,root); } void TreeOptimizer3::iterate(TreePoseGraph3::EdgeSet* eset, bool noPreconditioner){ TreePoseGraph3::EdgeSet* temp=sortedEdges; if (eset){ sortedEdges=eset; } if (noPreconditioner) propagateErrors(false); else { if (iteration==1) computePreconditioner(); propagateErrors(true); } sortedEdges=temp; onRestartBegin(); if (restartOnDivergence){ double mte, ate; double mre, are; error(&mre, &mte, &are, &ate); maxTranslationalErrors.push_back(mte); maxRotationalErrors.push_back(mre); int interval=3; if ((int)maxRotationalErrors.size()>=interval){ uint s=(uint)maxRotationalErrors.size(); double re0 = maxRotationalErrors[s-interval]; double re1 = maxRotationalErrors[s-1]; if ((re1-re0)>are || sqrt(re1)>0.99*M_PI){ double rg=rotGain; if (sqrt(re1)>M_PI/4){ cerr << "RESTART!!!!! : Angular wraparound may be occourring" << endl; cerr << " err=" << re0 << " -> " << re1 << endl; cerr << "Restarting optimization and reducing the rotation factor" << endl; cerr << rg << " -> "; initializeOnTree(); initializeTreeParameters(); initializeOptimization(); error(&mre, &mte); maxTranslationalErrors.push_back(mte); maxRotationalErrors.push_back(mre); rg*=0.1; rotGain=rg; cerr << rotGain << endl; } else { cerr << "decreasing angular gain" << rotGain*0.1 << endl; rotGain*=0.1; } } } } onRestartDone(); } void TreeOptimizer3::recomputeTransformations(Vertex*v, Vertex* top){ if (v==top) return; recomputeTransformations(v->parent, top); v->transformation=v->parent->transformation*v->parameters; } void TreeOptimizer3::recomputeParameters(Vertex*v, Vertex* top){ while (v!=top){ v->parameters=v->parent->transformation.inv()*v->transformation; v=v->parent; } } TreeOptimizer3::Transformation TreeOptimizer3::getPose(Vertex*v, Vertex* top){ Transformation t(0.,0.,0.,0.,0.,0.); if (v==top) return v->transformation; while (v!=top){ t=v->parameters*t; v=v->parent; } return top->transformation*t; } TreeOptimizer3::Rotation TreeOptimizer3::getRotation(Vertex*v, Vertex* top){ Rotation r(0.,0.,0.); if (v==top) return v->transformation.rotation(); while (v!=top){ r=v->parameters.rotation()*r; v=v->parent; } return top->transformation.rotation()*r; } double TreeOptimizer3::error(const Edge* e) const{ const Vertex* v1=e->v1; const Vertex* v2=e->v2; Transformation et=e->transformation; Transformation t1=v1->transformation; Transformation t2=v2->transformation; Transformation t12=(t1*et)*t2.inv(); Pose p12=t12.toPoseType(); Pose ps=e->informationMatrix*p12; double err=p12*ps; //DEBUG(100) << "e(" << v1->id << "," << v2->id << ")" << err << endl; return err; } double TreeOptimizer3::traslationalError(const Edge* e) const{ const Vertex* v1=e->v1; const Vertex* v2=e->v2; Transformation et=e->transformation; Transformation t1=v1->transformation; Transformation t2=v2->transformation; Translation t12=(t2.inv()*(t1*et)).translation(); return t12*t12;; } double TreeOptimizer3::rotationalError(const Edge* e) const{ const Vertex* v1=e->v1; const Vertex* v2=e->v2; Rotation er=e->transformation.rotation(); Rotation r1=v1->transformation.rotation(); Rotation r2=v2->transformation.rotation(); Rotation r12=r2.inverse()*(r1*er); double r=r12.angle(); return r*r; } double TreeOptimizer3::loopError(const Edge* e) const{ double err=0; const Vertex* v=e->v1; while (v!=e->top){ err+=error(v->parentEdge); v=v->parent; } v=e->v2; while (v==e->top){ err+=error(v->parentEdge); v=v->parent; } if (e->v2->parentEdge!=e && e->v1->parentEdge!=e) err+=error(e); return err; } double TreeOptimizer3::loopRotationalError(const Edge* e) const{ double err=0; const Vertex* v=e->v1; while (v!=e->top){ err+=rotationalError(v->parentEdge); v=v->parent; } v=e->v2; while (v!=e->top){ err+=rotationalError(v->parentEdge); v=v->parent; } if (e->v2->parentEdge!=e && e->v1->parentEdge!=e) err+=rotationalError(e); return err; } double TreeOptimizer3::error(double* mre, double* mte, double* are, double* ate, TreePoseGraph3::EdgeSet* eset) const{ double globalRotError=0.; double maxRotError=0; double globalTrasError=0.; double maxTrasError=0; int c=0; if (! eset){ for (TreePoseGraph3::EdgeMap::const_iterator it=edges.begin(); it!=edges.end(); it++){ double re=rotationalError(it->second); globalRotError+=re; maxRotError=maxRotError>re?maxRotError:re; double te=traslationalError(it->second); globalTrasError+=te; maxTrasError=maxTrasError>te?maxTrasError:te; c++; } } else { for (TreePoseGraph3::EdgeSet::const_iterator it=eset->begin(); it!=eset->end(); it++){ const TreePoseGraph3::Edge* edge=*it; double re=rotationalError(edge); globalRotError+=re; maxRotError=maxRotError>re?maxRotError:re; double te=traslationalError(edge); globalTrasError+=te; maxTrasError=maxTrasError>te?maxTrasError:te; c++; } } if (mte) *mte=maxTrasError; if (mre) *mre=maxRotError; if (ate) *ate=globalTrasError/c; if (are) *are=globalRotError/c; return globalRotError+globalTrasError; } void TreeOptimizer3::initializeOptimization(EdgeCompareMode mode){ edgeCompareMode=mode; // compute the size of the preconditioning matrix int sz=maxIndex()+1; //DEBUG(1) << "Size= " << sz << endl; M.resize(sz); //DEBUG(1) << "allocating M(" << sz << ")" << endl; iteration=1; // sorting edges if (sortedEdges!=0){ delete sortedEdges; sortedEdges=0; } sortedEdges=sortEdges(); mpl=maxPathLength(); rotGain=1.; trasGain=1.; } void TreeOptimizer3::initializeOnlineIterations(){ int sz=maxIndex()+1; //DEBUG(1) << "Size= " << sz << endl; M.resize(sz); //DEBUG(1) << "allocating M(" << sz << ")" << endl; iteration=1; maxRotationalErrors.clear(); maxTranslationalErrors.clear(); rotGain=1.; trasGain=1.; } void TreeOptimizer3::initializeOnlineOptimization(EdgeCompareMode mode){ edgeCompareMode=mode; // compute the size of the preconditioning matrix clear(); Vertex* v0=addVertex(0,Pose(0,0,0,0,0,0)); root=v0; v0->parameters=Transformation(v0->pose); v0->parentEdge=0; v0->parent=0; v0->level=0; v0->transformation=Transformation(TreePoseGraph3::Pose(0,0,0,0,0,0)); } void TreeOptimizer3::onStepStart(Edge* e){ //DEBUG(5) << "entering edge" << e << endl; } void TreeOptimizer3::onStepFinished(Edge* e){ //DEBUG(5) << "exiting edge" << e << endl; } void TreeOptimizer3::onIterationStart(int iteration){ //DEBUG(5) << "entering iteration " << iteration << endl; } void TreeOptimizer3::onIterationFinished(int iteration){ //DEBUG(5) << "exiting iteration " << iteration << endl; } void TreeOptimizer3::onRestartBegin(){} void TreeOptimizer3::onRestartDone(){} bool TreeOptimizer3::isDone(){ return false; } }; //namespace AISNavigation
/* * Created by Phil on 22/10/2010. * Copyright 2010 Two Blue Cubes Ltd * * 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 TWOBLUECUBES_CATCH_HPP_INCLUDED #define TWOBLUECUBES_CATCH_HPP_INCLUDED #include "internal/catch_suppress_warnings.h" #ifdef CATCH_CONFIG_MAIN # define CATCH_CONFIG_RUNNER #endif #ifdef CATCH_CONFIG_RUNNER # ifndef CLARA_CONFIG_MAIN # define CLARA_CONFIG_MAIN_NOT_DEFINED # define CLARA_CONFIG_MAIN # endif #endif #include "internal/catch_notimplemented_exception.h" #include "internal/catch_context.h" #include "internal/catch_test_registry.hpp" #include "internal/catch_capture.hpp" #include "internal/catch_section.h" #include "internal/catch_generators.hpp" #include "internal/catch_interfaces_exception.h" #include "internal/catch_approx.hpp" #include "internal/catch_matchers.hpp" #include "internal/catch_compiler_capabilities.h" #include "internal/catch_interfaces_tag_alias_registry.h" // These files are included here so the single_include script doesn't put them // in the conditionally compiled sections #include "internal/catch_test_case_info.h" #include "internal/catch_interfaces_runner.h" #ifdef __OBJC__ #include "internal/catch_objc.hpp" #endif #ifdef CATCH_CONFIG_RUNNER #include "internal/catch_impl.hpp" #endif #ifdef CATCH_CONFIG_MAIN #include "internal/catch_default_main.hpp" #endif #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED # undef CLARA_CONFIG_MAIN #endif ////// // If this config identifier is defined then all CATCH macros are prefixed with CATCH_ #ifdef CATCH_CONFIG_PREFIX_ALL #define CATCH_REQUIRE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal, "CATCH_REQUIRE" ) #define CATCH_REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, "CATCH_REQUIRE_FALSE" ) #define CATCH_REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_THROWS" ) #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_THROWS_AS" ) #define CATCH_REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_NOTHROW" ) #define CATCH_CHECK( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK" ) #define CATCH_CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, "CATCH_CHECK_FALSE" ) #define CATCH_CHECKED_IF( expr ) INTERNAL_CATCH_IF( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECKED_IF" ) #define CATCH_CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECKED_ELSE" ) #define CATCH_CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, "CATCH_CHECK_NOFAIL" ) #define CATCH_CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THROWS" ) #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THROWS_AS" ) #define CATCH_CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_NOTHROW" ) #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THAT" ) #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_THAT" ) #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( msg, "CATCH_INFO" ) #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, "CATCH_WARN", msg ) #define CATCH_SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( msg, "CATCH_INFO" ) #define CATCH_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CATCH_CAPTURE" ) #define CATCH_SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CATCH_CAPTURE" ) #ifdef CATCH_CONFIG_VARIADIC_MACROS #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "CATCH_FAIL", __VA_ARGS__ ) #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "CATCH_SUCCEED", __VA_ARGS__ ) #else #define CATCH_TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description ) #define CATCH_TEST_CASE_METHOD( className, name, description ) INTERNAL_CATCH_TEST_CASE_METHOD( className, name, description ) #define CATCH_METHOD_AS_TEST_CASE( method, name, description ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, name, description ) #define CATCH_SECTION( name, description ) INTERNAL_CATCH_SECTION( name, description ) #define CATCH_FAIL( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "CATCH_FAIL", msg ) #define CATCH_SUCCEED( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "CATCH_SUCCEED", msg ) #endif #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE( "", "" ) #define CATCH_REGISTER_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) #define CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) #define CATCH_GENERATE( expr) INTERNAL_CATCH_GENERATE( expr ) // "BDD-style" convenience wrappers #ifdef CATCH_CONFIG_VARIADIC_MACROS #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ ) #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) #else #define CATCH_SCENARIO( name, tags ) CATCH_TEST_CASE( "Scenario: " name, tags ) #define CATCH_SCENARIO_METHOD( className, name, tags ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " name, tags ) #endif #define CATCH_GIVEN( desc ) CATCH_SECTION( "Given: " desc, "" ) #define CATCH_WHEN( desc ) CATCH_SECTION( " When: " desc, "" ) #define CATCH_AND_WHEN( desc ) CATCH_SECTION( " And: " desc, "" ) #define CATCH_THEN( desc ) CATCH_SECTION( " Then: " desc, "" ) #define CATCH_AND_THEN( desc ) CATCH_SECTION( " And: " desc, "" ) // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required #else #define REQUIRE( expr ) INTERNAL_CATCH_TEST( (expr), Catch::ResultDisposition::Normal, "REQUIRE" ) #define REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, "REQUIRE_FALSE" ) #define REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::Normal, "REQUIRE_THROWS" ) #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::Normal, "REQUIRE_THROWS_AS" ) #define REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::Normal, "REQUIRE_NOTHROW" ) #define CHECK( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECK" ) #define CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, "CHECK_FALSE" ) #define CHECKED_IF( expr ) INTERNAL_CATCH_IF( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECKED_IF" ) #define CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECKED_ELSE" ) #define CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, "CHECK_NOFAIL" ) #define CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECK_THROWS" ) #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::ContinueOnFailure, "CHECK_THROWS_AS" ) #define CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECK_NOTHROW" ) #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::ContinueOnFailure, "CHECK_THAT" ) #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::Normal, "REQUIRE_THAT" ) #define INFO( msg ) INTERNAL_CATCH_INFO( msg, "INFO" ) #define WARN( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, "WARN", msg ) #define SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( msg, "INFO" ) #define CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CAPTURE" ) #define SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CAPTURE" ) #ifdef CATCH_CONFIG_VARIADIC_MACROS #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) #define FAIL( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "FAIL", __VA_ARGS__ ) #define SUCCEED( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "SUCCEED", __VA_ARGS__ ) #else #define TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description ) #define TEST_CASE_METHOD( className, name, description ) INTERNAL_CATCH_TEST_CASE_METHOD( className, name, description ) #define METHOD_AS_TEST_CASE( method, name, description ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, name, description ) #define SECTION( name, description ) INTERNAL_CATCH_SECTION( name, description ) #define FAIL( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "FAIL", msg ) #define SUCCEED( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "SUCCEED", msg ) #endif #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE( "", "" ) #define REGISTER_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) #define REGISTER_LEGACY_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) #define GENERATE( expr) INTERNAL_CATCH_GENERATE( expr ) #endif #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) // "BDD-style" convenience wrappers #ifdef CATCH_CONFIG_VARIADIC_MACROS #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ ) #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) #else #define SCENARIO( name, tags ) TEST_CASE( "Scenario: " name, tags ) #define SCENARIO_METHOD( className, name, tags ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " name, tags ) #endif #define GIVEN( desc ) SECTION( " Given: " desc, "" ) #define WHEN( desc ) SECTION( " When: " desc, "" ) #define AND_WHEN( desc ) SECTION( "And when: " desc, "" ) #define THEN( desc ) SECTION( " Then: " desc, "" ) #define AND_THEN( desc ) SECTION( " And: " desc, "" ) using Catch::Detail::Approx; #include "internal/catch_reenable_warnings.h" #endif // TWOBLUECUBES_CATCH_HPP_INCLUDED
#include <dae.h> #include <dae/daeDom.h> #include <1.5/dom/domFx_samplerRECT.h> #include <dae/daeMetaCMPolicy.h> #include <dae/daeMetaSequence.h> #include <dae/daeMetaChoice.h> #include <dae/daeMetaGroup.h> #include <dae/daeMetaAny.h> #include <dae/daeMetaElementAttribute.h> namespace ColladaDOM150 { daeElementRef domFx_samplerRECT::create(DAE& dae) { domFx_samplerRECTRef ref = new domFx_samplerRECT(dae); return ref; } daeMetaElement * domFx_samplerRECT::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "fx_samplerRECT" ); meta->registerClass(domFx_samplerRECT::create); daeMetaCMPolicy *cm = NULL; daeMetaElementAttribute *mea = NULL; cm = new daeMetaSequence( meta, cm, 0, 1, 1 ); cm = new daeMetaSequence( meta, cm, 0, 1, 1 ); mea = new daeMetaElementAttribute( meta, cm, 0, 0, 1 ); mea->setName( "instance_image" ); mea->setOffset( daeOffsetOf(domFx_samplerRECT,elemInstance_image) ); mea->setElementType( domInstance_image::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 1, 1, 1 ); mea->setName( "fx_sampler_states" ); mea->setOffset( daeOffsetOf(domFx_samplerRECT,elemFx_sampler_states) ); mea->setElementType( domFx_sampler_states::registerElement(dae) ); cm->appendChild( new daeMetaGroup( mea, meta, cm, 1, 1, 1 ) ); cm->setMaxOrdinal( 1 ); cm->getParent()->appendChild( cm ); cm = cm->getParent(); cm->setMaxOrdinal( 1 ); meta->setCMRoot( cm ); meta->setElementSize(sizeof(domFx_samplerRECT)); meta->validate(); return meta; } } // ColladaDOM150
/** ******************************************************************************* * Copyright (C) 1996-2006, International Business Machines Corporation and * * others. All Rights Reserved. * ******************************************************************************* * * ******************************************************************************* */ /* * @(#) icujniinterface.c 1.2 00/10/11 * * (C) Copyright IBM Corp. 2000 - All Rights Reserved * A JNI wrapper to ICU native converter Interface * @author: Ram Viswanadha */ #include "JNIHelp.h" #include "AndroidSystemNatives.h" #include "unicode/utypes.h" /* Basic ICU data types */ #include "unicode/ucnv.h" /* C Converter API */ #include "unicode/ustring.h" /* some more string functions*/ #include "unicode/ucnv_cb.h" /* for callback functions */ #include "unicode/uset.h" /* for contains function */ #include "ErrorCode.h" #include <stdlib.h> #include <string.h> #define com_ibm_icu4jni_converters_NativeConverter_STOP_CALLBACK 0L #define com_ibm_icu4jni_converters_NativeConverter_SKIP_CALLBACK 1L #define com_ibm_icu4jni_converters_NativeConverter_SUBSTITUTE_CALLBACK 2L // BEGIN android-removed // #define UTF_16BE "UTF-16BE" // #define UTF_16 "UTF-16" // END android-removed /* Prototype of callback for substituting user settable sub chars */ static void JNI_TO_U_CALLBACK_SUBSTITUTE (const void *,UConverterToUnicodeArgs *,const char* ,int32_t ,UConverterCallbackReason ,UErrorCode * ); /** * Opens the ICU converter * @param env environment handle for JNI * @param jClass handle for the class * @param handle buffer to recieve ICU's converter address * @param converterName name of the ICU converter */ static jlong openConverter (JNIEnv *env, jclass jClass, jstring converterName) { UConverter* conv=NULL; UErrorCode errorCode = U_ZERO_ERROR; const char* cnvName= (const char*) env->GetStringUTFChars(converterName,NULL); if(cnvName) { int count = env->GetStringUTFLength(converterName); conv = ucnv_open(cnvName,&errorCode); } env->ReleaseStringUTFChars(converterName,cnvName); if (icu4jni_error(env, errorCode) != FALSE) { return 0; } return (jlong) conv; } /** * Closes the ICU converter * @param env environment handle for JNI * @param jClass handle for the class * @param handle address of ICU converter */ static void closeConverter (JNIEnv *env, jclass jClass, jlong handle) { UConverter* cnv = (UConverter*)(long)handle; if(cnv) { // BEGIN android-added // Free up any contexts created in setCallback[Encode|Decode]() UConverterToUCallback toAction; UConverterFromUCallback fromAction; void* context1 = NULL; void* context2 = NULL; // TODO: ICU API bug? // The documentation clearly states that the caller owns the returned // pointers: http://icu-project.org/apiref/icu4c/ucnv_8h.html ucnv_getToUCallBack(cnv, &toAction, const_cast<const void**>(&context1)); ucnv_getFromUCallBack(cnv, &fromAction, const_cast<const void**>(&context2)); // END android-added ucnv_close(cnv); // BEGIN android-added if (context1 != NULL) { free(context1); } if (context2 != NULL) { free(context2); } // END android-added } } /** * Sets the substution mode for from Unicode conversion. Currently only * two modes are supported: substitute or report * @param env environment handle for JNI * @param jClass handle for the class * @param handle address of ICU converter * @param mode the mode to set */ static jint setSubstitutionModeCharToByte (JNIEnv *env, jclass jClass, jlong handle, jboolean mode) { UConverter* conv = (UConverter*)(long)handle; UErrorCode errorCode =U_ZERO_ERROR; if(conv) { UConverterFromUCallback fromUOldAction ; void* fromUOldContext; void* fromUNewContext=NULL; if(mode) { ucnv_setFromUCallBack(conv, UCNV_FROM_U_CALLBACK_SUBSTITUTE, fromUNewContext, &fromUOldAction, (const void**)&fromUOldContext, &errorCode); } else{ ucnv_setFromUCallBack(conv, UCNV_FROM_U_CALLBACK_STOP, fromUNewContext, &fromUOldAction, (const void**)&fromUOldContext, &errorCode); } return errorCode; } errorCode = U_ILLEGAL_ARGUMENT_ERROR; return errorCode; } /** * Sets the substution mode for to Unicode conversion. Currently only * two modes are supported: substitute or report * @param env environment handle for JNI * @param jClass handle for the class * @param handle address of ICU converter * @param mode the mode to set */ static jint setSubstitutionModeByteToChar (JNIEnv *env, jclass jClass, jlong handle, jboolean mode) { UConverter* conv = (UConverter*)handle; UErrorCode errorCode =U_ZERO_ERROR; if(conv) { UConverterToUCallback toUOldAction ; void* toUOldContext; void* toUNewContext=NULL; if(mode) { ucnv_setToUCallBack(conv, UCNV_TO_U_CALLBACK_SUBSTITUTE, toUNewContext, &toUOldAction, (const void**)&toUOldContext, &errorCode); } else{ ucnv_setToUCallBack(conv, UCNV_TO_U_CALLBACK_STOP, toUNewContext, &toUOldAction, (const void**)&toUOldContext, &errorCode); } return errorCode; } errorCode = U_ILLEGAL_ARGUMENT_ERROR; return errorCode; } /** * Converts a buffer of Unicode code units to target encoding * @param env environment handle for JNI * @param jClass handle for the class * @param handle address of ICU converter * @param source buffer of Unicode chars to convert * @param sourceEnd limit of the source buffer * @param target buffer to recieve the converted bytes * @param targetEnd the limit of the target buffer * @param data buffer to recieve state of the current conversion * @param flush boolean that specifies end of source input */ static jint convertCharToByte(JNIEnv *env, jclass jClass, jlong handle, jcharArray source, jint sourceEnd, jbyteArray target, jint targetEnd, jintArray data, jboolean flush) { UErrorCode errorCode =U_ZERO_ERROR; UConverter* cnv = (UConverter*)handle; if(cnv) { jint* myData = (jint*) env->GetPrimitiveArrayCritical(data,NULL); if(myData) { jint* sourceOffset = &myData[0]; jint* targetOffset = &myData[1]; const jchar* uSource =(jchar*) env->GetPrimitiveArrayCritical(source, NULL); if(uSource) { jbyte* uTarget=(jbyte*) env->GetPrimitiveArrayCritical(target,NULL); if(uTarget) { const jchar* mySource = uSource+ *sourceOffset; const UChar* mySourceLimit= uSource+sourceEnd; char* cTarget = reinterpret_cast<char*>(uTarget+ *targetOffset); const char* cTargetLimit = reinterpret_cast<const char*>(uTarget+targetEnd); ucnv_fromUnicode( cnv , &cTarget, cTargetLimit,&mySource, mySourceLimit,NULL,(UBool) flush, &errorCode); *sourceOffset = (jint) (mySource - uSource)-*sourceOffset; *targetOffset = (jint) ((jbyte*)cTarget - uTarget)- *targetOffset; if(U_FAILURE(errorCode)) { env->ReleasePrimitiveArrayCritical(target,uTarget,0); env->ReleasePrimitiveArrayCritical(source,(jchar*)uSource,0); env->ReleasePrimitiveArrayCritical(data,(jint*)myData,0); return errorCode; } }else{ errorCode = U_ILLEGAL_ARGUMENT_ERROR; } env->ReleasePrimitiveArrayCritical(target,uTarget,0); }else{ errorCode = U_ILLEGAL_ARGUMENT_ERROR; } env->ReleasePrimitiveArrayCritical(source,(jchar*)uSource,0); }else{ errorCode = U_ILLEGAL_ARGUMENT_ERROR; } env->ReleasePrimitiveArrayCritical(data,(jint*)myData,0); return errorCode; } errorCode = U_ILLEGAL_ARGUMENT_ERROR; return errorCode; } static jint encode(JNIEnv *env, jclass jClass, jlong handle, jcharArray source, jint sourceEnd, jbyteArray target, jint targetEnd, jintArray data, jboolean flush) { UErrorCode ec = UErrorCode(convertCharToByte(env, jClass,handle,source,sourceEnd, target,targetEnd,data,flush)); UConverter* cnv = (UConverter*)handle; jint* myData = (jint*) env->GetPrimitiveArrayCritical(data,NULL); if(cnv && myData) { UErrorCode errorCode = U_ZERO_ERROR; myData[3] = ucnv_fromUCountPending(cnv, &errorCode); if(ec == U_ILLEGAL_CHAR_FOUND || ec == U_INVALID_CHAR_FOUND) { int8_t count =32; UChar invalidUChars[32]; ucnv_getInvalidUChars(cnv,invalidUChars,&count,&errorCode); if(U_SUCCESS(errorCode)) { myData[2] = count; } } } env->ReleasePrimitiveArrayCritical(data,(jint*)myData,0); return ec; } /** * Converts a buffer of encoded bytes to Unicode code units * @param env environment handle for JNI * @param jClass handle for the class * @param handle address of ICU converter * @param source buffer of Unicode chars to convert * @param sourceEnd limit of the source buffer * @param target buffer to recieve the converted bytes * @param targetEnd the limit of the target buffer * @param data buffer to recieve state of the current conversion * @param flush boolean that specifies end of source input */ static jint convertByteToChar(JNIEnv *env, jclass jClass, jlong handle, jbyteArray source, jint sourceEnd, jcharArray target, jint targetEnd, jintArray data, jboolean flush) { UErrorCode errorCode =U_ZERO_ERROR; UConverter* cnv = (UConverter*)handle; if(cnv) { jint* myData = (jint*) env->GetPrimitiveArrayCritical(data,NULL); if(myData) { jint* sourceOffset = &myData[0]; jint* targetOffset = &myData[1]; const jbyte* uSource =(jbyte*) env->GetPrimitiveArrayCritical(source, NULL); if(uSource) { jchar* uTarget=(jchar*) env->GetPrimitiveArrayCritical(target,NULL); if(uTarget) { const jbyte* mySource = uSource+ *sourceOffset; const char* mySourceLimit = reinterpret_cast<const char*>(uSource+sourceEnd); UChar* cTarget=uTarget+ *targetOffset; const UChar* cTargetLimit=uTarget+targetEnd; ucnv_toUnicode( cnv , &cTarget, cTargetLimit,(const char**)&mySource, mySourceLimit,NULL,(UBool) flush, &errorCode); *sourceOffset = mySource - uSource - *sourceOffset ; *targetOffset = cTarget - uTarget - *targetOffset; if(U_FAILURE(errorCode)) { env->ReleasePrimitiveArrayCritical(target,uTarget,0); env->ReleasePrimitiveArrayCritical(source,(jchar*)uSource,0); env->ReleasePrimitiveArrayCritical(data,(jint*)myData,0); return errorCode; } }else{ errorCode = U_ILLEGAL_ARGUMENT_ERROR; } env->ReleasePrimitiveArrayCritical(target,uTarget,0); }else{ errorCode = U_ILLEGAL_ARGUMENT_ERROR; } env->ReleasePrimitiveArrayCritical(source,(jchar*)uSource,0); }else{ errorCode = U_ILLEGAL_ARGUMENT_ERROR; } env->ReleasePrimitiveArrayCritical(data,(jint*)myData,0); return errorCode; } errorCode = U_ILLEGAL_ARGUMENT_ERROR; return errorCode; } static jint decode(JNIEnv *env, jclass jClass, jlong handle, jbyteArray source, jint sourceEnd, jcharArray target, jint targetEnd, jintArray data, jboolean flush) { jint ec = convertByteToChar(env, jClass,handle,source,sourceEnd, target,targetEnd,data,flush); jint* myData = (jint*) env->GetPrimitiveArrayCritical(data,NULL); UConverter* cnv = (UConverter*)handle; if(myData && cnv) { UErrorCode errorCode = U_ZERO_ERROR; myData[3] = ucnv_toUCountPending(cnv, &errorCode); if(ec == U_ILLEGAL_CHAR_FOUND || ec == U_INVALID_CHAR_FOUND ) { char invalidChars[32] = {'\0'}; int8_t len = 32; ucnv_getInvalidChars(cnv,invalidChars,&len,&errorCode); if(U_SUCCESS(errorCode)) { myData[2] = len; } } } env->ReleasePrimitiveArrayCritical(data,(jint*)myData,0); return ec; } static void resetByteToChar(JNIEnv *env, jclass jClass, jlong handle) { UConverter* cnv = (UConverter*)handle; if(cnv) { ucnv_resetToUnicode(cnv); } } static void resetCharToByte(JNIEnv *env, jclass jClass, jlong handle) { UConverter* cnv = (UConverter*)handle; if(cnv) { ucnv_resetFromUnicode(cnv); } } static jint countInvalidBytes (JNIEnv *env, jclass jClass, jlong handle, jintArray length) { UConverter* cnv = (UConverter*)handle; UErrorCode errorCode = U_ZERO_ERROR; if(cnv) { char invalidChars[32]; jint* len = (jint*) env->GetPrimitiveArrayCritical(length, NULL); if(len) { ucnv_getInvalidChars(cnv,invalidChars,(int8_t*)len,&errorCode); } env->ReleasePrimitiveArrayCritical(length,(jint*)len,0); return errorCode; } errorCode = U_ILLEGAL_ARGUMENT_ERROR; return errorCode; } static jint countInvalidChars(JNIEnv *env, jclass jClass, jlong handle, jintArray length) { UErrorCode errorCode =U_ZERO_ERROR; UConverter* cnv = (UConverter*)handle; UChar invalidUChars[32]; if(cnv) { jint* len = (jint*) env->GetPrimitiveArrayCritical(length, NULL); if(len) { ucnv_getInvalidUChars(cnv,invalidUChars,(int8_t*)len,&errorCode); } env->ReleasePrimitiveArrayCritical(length,(jint*)len,0); return errorCode; } errorCode = U_ILLEGAL_ARGUMENT_ERROR; return errorCode; } static jint getMaxBytesPerChar(JNIEnv *env, jclass jClass, jlong handle) { UConverter* cnv = (UConverter*)handle; if(cnv) { return (jint)ucnv_getMaxCharSize(cnv); } return -1; } static jint getMinBytesPerChar(JNIEnv *env, jclass jClass, jlong handle) { UConverter* cnv = (UConverter*)handle; if(cnv) { return (jint)ucnv_getMinCharSize(cnv); } return -1; } static jfloat getAveBytesPerChar(JNIEnv *env, jclass jClass, jlong handle) { UConverter* cnv = (UConverter*)handle; if(cnv) { jfloat max = (jfloat)ucnv_getMaxCharSize(cnv); jfloat min = (jfloat)ucnv_getMinCharSize(cnv); return (jfloat) ( (max+min)/2 ); } return -1; } static jint flushByteToChar(JNIEnv *env, jclass jClass,jlong handle, jcharArray target, jint targetEnd, jintArray data) { UErrorCode errorCode =U_ZERO_ERROR; UConverter* cnv = (UConverter*)handle; if(cnv) { jbyte source ='\0'; jint* myData = (jint*) env->GetPrimitiveArrayCritical(data,NULL); if(myData) { jint* targetOffset = &myData[1]; jchar* uTarget=(jchar*) env->GetPrimitiveArrayCritical(target,NULL); if(uTarget) { const jbyte* mySource = &source; const char* mySourceLimit = reinterpret_cast<char*>(&source); UChar* cTarget=uTarget+ *targetOffset; const UChar* cTargetLimit=uTarget+targetEnd; ucnv_toUnicode( cnv , &cTarget, cTargetLimit,(const char**)&mySource, mySourceLimit,NULL,TRUE, &errorCode); *targetOffset = (jint) ((jchar*)cTarget - uTarget)- *targetOffset; if(U_FAILURE(errorCode)) { env->ReleasePrimitiveArrayCritical(target,uTarget,0); env->ReleasePrimitiveArrayCritical(data,(jint*)myData,0); return errorCode; } }else{ errorCode = U_ILLEGAL_ARGUMENT_ERROR; } env->ReleasePrimitiveArrayCritical(target,uTarget,0); }else{ errorCode = U_ILLEGAL_ARGUMENT_ERROR; } env->ReleasePrimitiveArrayCritical(data,(jint*)myData,0); return errorCode; } errorCode = U_ILLEGAL_ARGUMENT_ERROR; return errorCode; } static jint flushCharToByte (JNIEnv *env, jclass jClass, jlong handle, jbyteArray target, jint targetEnd, jintArray data) { UErrorCode errorCode =U_ZERO_ERROR; UConverter* cnv = (UConverter*)handle; jchar source = '\0'; if(cnv) { jint* myData = (jint*) env->GetPrimitiveArrayCritical(data,NULL); if(myData) { jint* targetOffset = &myData[1]; jbyte* uTarget=(jbyte*) env->GetPrimitiveArrayCritical(target,NULL); if(uTarget) { const jchar* mySource = &source; const UChar* mySourceLimit= &source; char* cTarget = reinterpret_cast<char*>(uTarget+ *targetOffset); const char* cTargetLimit = reinterpret_cast<char*>(uTarget+targetEnd); ucnv_fromUnicode( cnv , &cTarget, cTargetLimit,&mySource, mySourceLimit,NULL,TRUE, &errorCode); *targetOffset = (jint) ((jbyte*)cTarget - uTarget)- *targetOffset; if(U_FAILURE(errorCode)) { env->ReleasePrimitiveArrayCritical(target,uTarget,0); env->ReleasePrimitiveArrayCritical(data,(jint*)myData,0); return errorCode; } }else{ errorCode = U_ILLEGAL_ARGUMENT_ERROR; } env->ReleasePrimitiveArrayCritical(target,uTarget,0); }else{ errorCode = U_ILLEGAL_ARGUMENT_ERROR; } env->ReleasePrimitiveArrayCritical(data,(jint*)myData,0); return errorCode; } errorCode = U_ILLEGAL_ARGUMENT_ERROR; return errorCode; } static void toChars(const UChar* us, char* cs, int32_t length) { UChar u; while(length>0) { u=*us++; *cs++=(char)u; --length; } } static jint setSubstitutionBytes(JNIEnv *env, jclass jClass, jlong handle, jbyteArray subChars, jint length) { UConverter* cnv = (UConverter*) handle; UErrorCode errorCode = U_ZERO_ERROR; if(cnv) { jbyte* u_subChars = reinterpret_cast<jbyte*>(env->GetPrimitiveArrayCritical(subChars, NULL)); if(u_subChars) { char* mySubChars = new char[length]; toChars((UChar*)u_subChars,&mySubChars[0],length); ucnv_setSubstChars(cnv,mySubChars, (char)length,&errorCode); if(U_FAILURE(errorCode)) { env->ReleasePrimitiveArrayCritical(subChars,mySubChars,0); return errorCode; } delete[] mySubChars; } else{ errorCode = U_ILLEGAL_ARGUMENT_ERROR; } env->ReleasePrimitiveArrayCritical(subChars,u_subChars,0); return errorCode; } errorCode = U_ILLEGAL_ARGUMENT_ERROR; return errorCode; } #define VALUE_STRING_LENGTH 32 struct SubCharStruct { int length; UChar subChars[256]; UBool stopOnIllegal; }; static UErrorCode setToUCallbackSubs(UConverter* cnv,UChar* subChars, int32_t length,UBool stopOnIllegal ) { SubCharStruct* substitutionCharS = (SubCharStruct*) malloc(sizeof(SubCharStruct)); UErrorCode errorCode = U_ZERO_ERROR; if(substitutionCharS) { UConverterToUCallback toUOldAction; void* toUOldContext=NULL; void* toUNewContext=NULL ; if(subChars) { u_strncpy(substitutionCharS->subChars,subChars,length); }else{ substitutionCharS->subChars[length++] =0xFFFD; } substitutionCharS->subChars[length]=0; substitutionCharS->length = length; substitutionCharS->stopOnIllegal = stopOnIllegal; toUNewContext = substitutionCharS; ucnv_setToUCallBack(cnv, JNI_TO_U_CALLBACK_SUBSTITUTE, toUNewContext, &toUOldAction, (const void**)&toUOldContext, &errorCode); if(toUOldContext) { SubCharStruct* temp = (SubCharStruct*) toUOldContext; free(temp); } return errorCode; } return U_MEMORY_ALLOCATION_ERROR; } static jint setSubstitutionChars(JNIEnv *env, jclass jClass, jlong handle, jcharArray subChars, jint length) { UErrorCode errorCode = U_ZERO_ERROR; UConverter* cnv = (UConverter*) handle; jchar* u_subChars=NULL; if(cnv) { if(subChars) { int len = env->GetArrayLength(subChars); u_subChars = reinterpret_cast<jchar*>(env->GetPrimitiveArrayCritical(subChars,NULL)); if(u_subChars) { errorCode = setToUCallbackSubs(cnv,u_subChars,len,FALSE); }else{ errorCode = U_ILLEGAL_ARGUMENT_ERROR; } env->ReleasePrimitiveArrayCritical(subChars,u_subChars,0); return errorCode; } } return U_ILLEGAL_ARGUMENT_ERROR; } static void JNI_TO_U_CALLBACK_SUBSTITUTE( const void *context, UConverterToUnicodeArgs *toArgs, const char* codeUnits, int32_t length, UConverterCallbackReason reason, UErrorCode * err) { if(context) { SubCharStruct* temp = (SubCharStruct*)context; if( temp) { if(temp->stopOnIllegal==FALSE) { if (reason > UCNV_IRREGULAR) { return; } /* reset the error */ *err = U_ZERO_ERROR; ucnv_cbToUWriteUChars(toArgs,temp->subChars ,temp->length , 0, err); }else{ if(reason != UCNV_UNASSIGNED) { /* the caller must have set * the error code accordingly */ return; }else{ *err = U_ZERO_ERROR; ucnv_cbToUWriteUChars(toArgs,temp->subChars ,temp->length , 0, err); return; } } } } return; } static jboolean canEncode(JNIEnv *env, jclass jClass, jlong handle, jint codeUnit) { UErrorCode errorCode =U_ZERO_ERROR; UConverter* cnv = (UConverter*)handle; if(cnv) { UChar source[3]; UChar *mySource=source; const UChar* sourceLimit = (codeUnit<0x010000) ? &source[1] : &source[2]; char target[5]; char *myTarget = target; const char* targetLimit = &target[4]; int i=0; UTF_APPEND_CHAR(&source[0],i,2,codeUnit); ucnv_fromUnicode(cnv,&myTarget,targetLimit, (const UChar**)&mySource, sourceLimit,NULL, TRUE,&errorCode); if(U_SUCCESS(errorCode)) { return (jboolean)TRUE; } } return (jboolean)FALSE; } static jboolean canDecode(JNIEnv *env, jclass jClass, jlong handle, jbyteArray source) { UErrorCode errorCode =U_ZERO_ERROR; UConverter* cnv = (UConverter*)handle; if(cnv) { jint len = env->GetArrayLength(source); jbyte* cSource =(jbyte*) env->GetPrimitiveArrayCritical(source, NULL); if(cSource) { const char* cSourceLimit = reinterpret_cast<const char*>(cSource+len); /* Assume that we need at most twice the length of source */ UChar* target = (UChar*) malloc(sizeof(UChar)* (len<<1)); UChar* targetLimit = target + (len<<1); if(target) { ucnv_toUnicode(cnv,&target,targetLimit, (const char**)&cSource, cSourceLimit,NULL, TRUE,&errorCode); if(U_SUCCESS(errorCode)) { free(target); env->ReleasePrimitiveArrayCritical(source,cSource,0); return (jboolean)TRUE; } } free(target); } env->ReleasePrimitiveArrayCritical(source,cSource,0); } return (jboolean)FALSE; } static int32_t copyString(char* dest, int32_t destCapacity, int32_t startIndex, const char* src, UErrorCode* status) { int32_t srcLen = 0, i=0; if(U_FAILURE(*status)) { return 0; } if(dest == NULL || src == NULL || destCapacity < startIndex) { *status = U_ILLEGAL_ARGUMENT_ERROR; return 0; } srcLen = strlen(src); if(srcLen >= destCapacity) { *status = U_BUFFER_OVERFLOW_ERROR; return 0; } for(i=0; i < srcLen; i++) { dest[startIndex++] = src[i]; } /* null terminate the buffer */ dest[startIndex] = 0; /* no bounds check already made sure that we have enough room */ return startIndex; } static int32_t getJavaCanonicalName1(const char* icuCanonicalName, char* canonicalName, int32_t capacity, UErrorCode* status) { /* If a charset listed in the IANA Charset Registry is supported by an implementation of the Java platform then its canonical name must be the name listed in the registry. Many charsets are given more than one name in the registry, in which case the registry identifies one of the names as MIME-preferred. If a charset has more than one registry name then its canonical name must be the MIME-preferred name and the other names in the registry must be valid aliases. If a supported charset is not listed in the IANA registry then its canonical name must begin with one of the strings "X-" or "x-". */ int32_t retLen = 0; const char* cName = NULL; /* find out the alias with MIME tag */ if((cName =ucnv_getStandardName(icuCanonicalName, "MIME", status)) != NULL) { retLen = copyString(canonicalName, capacity, 0, cName, status); /* find out the alias with IANA tag */ }else if((cName =ucnv_getStandardName(icuCanonicalName, "IANA", status)) != NULL) { retLen = copyString(canonicalName, capacity, 0, cName, status); }else { /* check to see if an alias already exists with x- prefix, if yes then make that the canonical name */ int32_t aliasNum = ucnv_countAliases(icuCanonicalName,status); int32_t i=0; const char* name; for(i=0;i<aliasNum;i++) { name = ucnv_getAlias(icuCanonicalName,(uint16_t)i, status); if(name != NULL && name[0]=='x' && name[1]=='-') { retLen = copyString(canonicalName, capacity, 0, name, status); break; } } /* last resort just append x- to any of the alias and make it the canonical name */ if(retLen == 0 && U_SUCCESS(*status)) { name = ucnv_getStandardName(icuCanonicalName, "UTR22", status); if(name == NULL && strchr(icuCanonicalName, ',')!= NULL) { name = ucnv_getAlias(icuCanonicalName, 1, status); if(*status == U_INDEX_OUTOFBOUNDS_ERROR) { *status = U_ZERO_ERROR; } } /* if there is no UTR22 canonical name .. then just return itself*/ if(name == NULL) { name = icuCanonicalName; } if(capacity >= 2) { strcpy(canonicalName,"x-"); } retLen = copyString(canonicalName, capacity, 2, name, status); } } return retLen; } static jobjectArray getAvailable(JNIEnv *env, jclass jClass) { jobjectArray ret; int32_t i = 0; int32_t num = ucnv_countAvailable(); UErrorCode error = U_ZERO_ERROR; const char* name =NULL; char canonicalName[256]={0}; ret= env->NewObjectArray(num, env->FindClass("java/lang/String"), env->NewStringUTF("")); for(i=0;i<num;i++) { name = ucnv_getAvailableName(i); getJavaCanonicalName1(name, canonicalName, 256, &error); #if DEBUG if(U_FAILURE(error)) { printf("An error occurred retrieving index %i. Error: %s. \n", i, u_errorName(error)); } printf("canonical name for %s\n", canonicalName); #endif // BEGIN android-changed jstring canonName = env->NewStringUTF(canonicalName); env->SetObjectArrayElement(ret,i,canonName); env->DeleteLocalRef(canonName); // END android-changed /*printf("canonical name : %s at %i\n", name,i); */ canonicalName[0]='\0';/* nul terminate */ } return (ret); } static jint countAliases(JNIEnv *env, jclass jClass,jstring enc) { UErrorCode error = U_ZERO_ERROR; jint num =0; const char* encName = env->GetStringUTFChars(enc,NULL); if(encName) { num = ucnv_countAliases(encName,&error); } env->ReleaseStringUTFChars(enc,encName); return num; } static jobjectArray getAliases(JNIEnv *env, jclass jClass, jstring enc) { jobjectArray ret=NULL; int32_t aliasNum = 0; UErrorCode error = U_ZERO_ERROR; const char* encName = env->GetStringUTFChars(enc,NULL); int i=0; int j=0; const char* aliasArray[50]; // BEGIN android-removed // int32_t utf16AliasNum = 0; // END android-removed if(encName) { const char* myEncName = encName; aliasNum = ucnv_countAliases(myEncName,&error); // BEGIN android-removed // /* special case for UTF-16. In java UTF-16 is always BE*/ // if(strcmp(myEncName, UTF_16BE)==0) { // utf16AliasNum=ucnv_countAliases(UTF_16,&error); // } // END android-removed if(aliasNum==0 && encName[0] == 0x78 /*x*/ && encName[1]== 0x2d /*-*/) { myEncName = encName+2; aliasNum = ucnv_countAliases(myEncName,&error); } if(U_SUCCESS(error)) { for(i=0,j=0;i<aliasNum;i++) { const char* name = ucnv_getAlias(myEncName,(uint16_t)i,&error); if(strchr(name,'+')==0 && strchr(name,',')==0) { aliasArray[j++]= name; } } // BEGIN android-removed // if(utf16AliasNum>0) { // for(i=0;i<utf16AliasNum;i++) { // const char* name = ucnv_getAlias(UTF_16,(uint16_t)i,&error); // if(strchr(name,'+')==0 && strchr(name,',')==0) { // aliasArray[j++]= name; // } // } // } // END android-removed ret = (jobjectArray)env->NewObjectArray(j, env->FindClass("java/lang/String"), env->NewStringUTF("")); for(;--j>=0;) { // BEGIN android-changed jstring alias = env->NewStringUTF(aliasArray[j]); env->SetObjectArrayElement(ret, j, alias); env->DeleteLocalRef(alias); // END android-changed } } } env->ReleaseStringUTFChars(enc,encName); return (ret); } static jstring getCanonicalName(JNIEnv *env, jclass jClass,jstring enc) { UErrorCode error = U_ZERO_ERROR; const char* encName = env->GetStringUTFChars(enc,NULL); const char* canonicalName = ""; // BEGIN android-changed jstring ret = NULL; if(encName) { canonicalName = ucnv_getAlias(encName,0,&error); if(canonicalName !=NULL && strstr(canonicalName,",")!=0) { canonicalName = ucnv_getAlias(canonicalName,1,&error); } ret = (env->NewStringUTF(canonicalName)); env->ReleaseStringUTFChars(enc,encName); } // END android-changed return ret; } static jstring getICUCanonicalName(JNIEnv *env, jclass jClass, jstring enc) { UErrorCode error = U_ZERO_ERROR; const char* encName = env->GetStringUTFChars(enc,NULL); const char* canonicalName = NULL; jstring ret = NULL; if(encName) { // BEGIN android-removed // if(strcmp(encName,"UTF-16")==0) { // ret = (env->NewStringUTF(UTF_16BE)); // }else // END android-removed if((canonicalName = ucnv_getCanonicalName(encName, "MIME", &error))!=NULL) { ret = (env->NewStringUTF(canonicalName)); }else if((canonicalName = ucnv_getCanonicalName(encName, "IANA", &error))!=NULL) { ret = (env->NewStringUTF(canonicalName)); }else if((canonicalName = ucnv_getCanonicalName(encName, "", &error))!=NULL) { ret = (env->NewStringUTF(canonicalName)); }else if((canonicalName = ucnv_getAlias(encName, 0, &error)) != NULL) { /* we have some aliases in the form x-blah .. match those first */ ret = (env->NewStringUTF(canonicalName)); }else if( ret ==NULL && strstr(encName, "x-") == encName) { /* check if the converter can be opened with the encName given */ UConverter* conv = NULL; error = U_ZERO_ERROR; conv = ucnv_open(encName+2, &error); if(conv!=NULL) { ret = (env->NewStringUTF(encName+2)); }else{ /* unsupported encoding */ ret = (env->NewStringUTF("")); } ucnv_close(conv); }else{ /* unsupported encoding */ ret = (env->NewStringUTF("")); } } env->ReleaseStringUTFChars(enc,encName); return ret; } static jstring getJavaCanonicalName2(JNIEnv *env, jclass jClass, jstring icuCanonName) { /* If a charset listed in the IANA Charset Registry is supported by an implementation of the Java platform then its canonical name must be the name listed in the registry. Many charsets are given more than one name in the registry, in which case the registry identifies one of the names as MIME-preferred. If a charset has more than one registry name then its canonical name must be the MIME-preferred name and the other names in the registry must be valid aliases. If a supported charset is not listed in the IANA registry then its canonical name must begin with one of the strings "X-" or "x-". */ UErrorCode error = U_ZERO_ERROR; const char* icuCanonicalName = env->GetStringUTFChars(icuCanonName,NULL); char cName[UCNV_MAX_CONVERTER_NAME_LENGTH] = {0}; jstring ret; if(icuCanonicalName && icuCanonicalName[0] != 0) { getJavaCanonicalName1(icuCanonicalName, cName, UCNV_MAX_CONVERTER_NAME_LENGTH, &error); } ret = (env->NewStringUTF(cName)); env->ReleaseStringUTFChars(icuCanonName,icuCanonicalName); return ret; } #define SUBS_ARRAY_CAPACITY 256 struct EncoderCallbackContext { int length; char subChars[SUBS_ARRAY_CAPACITY]; UConverterFromUCallback onUnmappableInput; UConverterFromUCallback onMalformedInput; }; static void CHARSET_ENCODER_CALLBACK(const void *context, UConverterFromUnicodeArgs *fromArgs, const UChar* codeUnits, int32_t length, UChar32 codePoint, UConverterCallbackReason reason, UErrorCode * status) { if(context) { EncoderCallbackContext* ctx = (EncoderCallbackContext*)context; if(ctx) { UConverterFromUCallback realCB = NULL; switch(reason) { case UCNV_UNASSIGNED: realCB = ctx->onUnmappableInput; break; case UCNV_ILLEGAL:/*malformed input*/ case UCNV_IRREGULAR:/*malformed input*/ realCB = ctx->onMalformedInput; break; /* case UCNV_RESET: ucnv_resetToUnicode(args->converter); break; case UCNV_CLOSE: ucnv_close(args->converter); break; case UCNV_CLONE: ucnv_clone(args->clone); */ default: *status = U_ILLEGAL_ARGUMENT_ERROR; return; } if(realCB==NULL) { *status = U_INTERNAL_PROGRAM_ERROR; } realCB(context, fromArgs, codeUnits, length, codePoint, reason, status); } } } static void JNI_FROM_U_CALLBACK_SUBSTITUTE_ENCODER(const void *context, UConverterFromUnicodeArgs *fromArgs, const UChar* codeUnits, int32_t length, UChar32 codePoint, UConverterCallbackReason reason, UErrorCode * err) { if(context) { EncoderCallbackContext* temp = (EncoderCallbackContext*)context; *err = U_ZERO_ERROR; ucnv_cbFromUWriteBytes(fromArgs,temp->subChars ,temp->length , 0, err); } return; } static UConverterFromUCallback getFromUCallback(int32_t mode) { switch(mode) { default: /* falls through */ case com_ibm_icu4jni_converters_NativeConverter_STOP_CALLBACK: return UCNV_FROM_U_CALLBACK_STOP; case com_ibm_icu4jni_converters_NativeConverter_SKIP_CALLBACK: return UCNV_FROM_U_CALLBACK_SKIP ; case com_ibm_icu4jni_converters_NativeConverter_SUBSTITUTE_CALLBACK: return JNI_FROM_U_CALLBACK_SUBSTITUTE_ENCODER; } } static jint setCallbackEncode(JNIEnv *env, jclass jClass, jlong handle, jint onMalformedInput, jint onUnmappableInput, jbyteArray subChars, jint length) { UConverter* conv = (UConverter*)handle; UErrorCode errorCode =U_ZERO_ERROR; if(conv) { UConverterFromUCallback fromUOldAction = NULL; void* fromUOldContext = NULL; EncoderCallbackContext* fromUNewContext=NULL; UConverterFromUCallback fromUNewAction=NULL; jbyte* sub = (jbyte*) env->GetPrimitiveArrayCritical(subChars, NULL); ucnv_getFromUCallBack(conv, &fromUOldAction, const_cast<const void**>(&fromUOldContext)); /* fromUOldContext can only be DecodeCallbackContext since the converter created is private data for the decoder and callbacks can only be set via this method! */ if(fromUOldContext==NULL) { fromUNewContext = (EncoderCallbackContext*) malloc(sizeof(EncoderCallbackContext)); fromUNewAction = CHARSET_ENCODER_CALLBACK; }else{ fromUNewContext = (EncoderCallbackContext*) fromUOldContext; fromUNewAction = fromUOldAction; fromUOldAction = NULL; fromUOldContext = NULL; } fromUNewContext->onMalformedInput = getFromUCallback(onMalformedInput); fromUNewContext->onUnmappableInput = getFromUCallback(onUnmappableInput); // BEGIN android-changed if(sub!=NULL) { fromUNewContext->length = length; const char* src = const_cast<const char*>(reinterpret_cast<char*>(sub)); strncpy(fromUNewContext->subChars, src, length); env->ReleasePrimitiveArrayCritical(subChars, sub, 0); }else{ errorCode = U_ILLEGAL_ARGUMENT_ERROR; } // END android-changed ucnv_setFromUCallBack(conv, fromUNewAction, fromUNewContext, &fromUOldAction, (const void**)&fromUOldContext, &errorCode); return errorCode; } return U_ILLEGAL_ARGUMENT_ERROR; } struct DecoderCallbackContext { int length; UChar subUChars[256]; UConverterToUCallback onUnmappableInput; UConverterToUCallback onMalformedInput; }; static void JNI_TO_U_CALLBACK_SUBSTITUTE_DECODER(const void *context, UConverterToUnicodeArgs *toArgs, const char* codeUnits, int32_t length, UConverterCallbackReason reason, UErrorCode * err) { if(context) { DecoderCallbackContext* temp = (DecoderCallbackContext*)context; *err = U_ZERO_ERROR; ucnv_cbToUWriteUChars(toArgs,temp->subUChars ,temp->length , 0, err); } return; } static UConverterToUCallback getToUCallback(int32_t mode) { switch(mode) { default: /* falls through */ case com_ibm_icu4jni_converters_NativeConverter_STOP_CALLBACK: return UCNV_TO_U_CALLBACK_STOP; case com_ibm_icu4jni_converters_NativeConverter_SKIP_CALLBACK: return UCNV_TO_U_CALLBACK_SKIP ; case com_ibm_icu4jni_converters_NativeConverter_SUBSTITUTE_CALLBACK: return JNI_TO_U_CALLBACK_SUBSTITUTE_DECODER; } } static void CHARSET_DECODER_CALLBACK(const void *context, UConverterToUnicodeArgs *args, const char* codeUnits, int32_t length, UConverterCallbackReason reason, UErrorCode *status ) { if(context) { DecoderCallbackContext* ctx = (DecoderCallbackContext*)context; if(ctx) { UConverterToUCallback realCB = NULL; switch(reason) { case UCNV_UNASSIGNED: realCB = ctx->onUnmappableInput; break; case UCNV_ILLEGAL:/*malformed input*/ case UCNV_IRREGULAR:/*malformed input*/ realCB = ctx->onMalformedInput; break; /* case UCNV_RESET: ucnv_resetToUnicode(args->converter); break; case UCNV_CLOSE: ucnv_close(args->converter); break; case UCNV_CLONE: ucnv_clone(args->clone); */ default: *status = U_ILLEGAL_ARGUMENT_ERROR; return; } if(realCB==NULL) { *status = U_INTERNAL_PROGRAM_ERROR; } realCB(context, args, codeUnits, length, reason, status); } } } static jint setCallbackDecode(JNIEnv *env, jclass jClass, jlong handle, jint onMalformedInput, jint onUnmappableInput, jcharArray subChars, jint length) { UConverter* conv = (UConverter*)handle; UErrorCode errorCode =U_ZERO_ERROR; if(conv) { UConverterToUCallback toUOldAction ; void* toUOldContext; DecoderCallbackContext* toUNewContext = NULL; UConverterToUCallback toUNewAction = NULL; jchar* sub = (jchar*) env->GetPrimitiveArrayCritical(subChars, NULL); ucnv_getToUCallBack(conv, &toUOldAction, const_cast<const void**>(&toUOldContext)); /* toUOldContext can only be DecodeCallbackContext since the converter created is private data for the decoder and callbacks can only be set via this method! */ if(toUOldContext==NULL) { toUNewContext = (DecoderCallbackContext*) malloc(sizeof(DecoderCallbackContext)); toUNewAction = CHARSET_DECODER_CALLBACK; }else{ toUNewContext = reinterpret_cast<DecoderCallbackContext*>(toUOldContext); toUNewAction = toUOldAction; toUOldAction = NULL; toUOldContext = NULL; } toUNewContext->onMalformedInput = getToUCallback(onMalformedInput); toUNewContext->onUnmappableInput = getToUCallback(onUnmappableInput); // BEGIN android-changed if(sub!=NULL) { toUNewContext->length = length; u_strncpy(toUNewContext->subUChars, sub, length); env->ReleasePrimitiveArrayCritical(subChars, sub, 0); }else{ errorCode = U_ILLEGAL_ARGUMENT_ERROR; } // END android-changed ucnv_setToUCallBack(conv, toUNewAction, toUNewContext, &toUOldAction, (const void**)&toUOldContext, &errorCode); return errorCode; } return U_ILLEGAL_ARGUMENT_ERROR; } static jlong safeClone(JNIEnv *env, jclass, jlong address) { UConverter* source = reinterpret_cast<UConverter*>(static_cast<uintptr_t>(address)); if (!source) { return NULL; } UErrorCode status = U_ZERO_ERROR; jint bufferSize = U_CNV_SAFECLONE_BUFFERSIZE; UConverter* conv = ucnv_safeClone(source, NULL, &bufferSize, &status); icu4jni_error(env, status); return reinterpret_cast<uintptr_t>(conv); } static jint getMaxCharsPerByte(JNIEnv *env, jclass jClass, jlong handle) { /* * currently we know that max number of chars per byte is 2 */ return 2; } static jfloat getAveCharsPerByte(JNIEnv *env, jclass jClass, jlong handle) { jfloat ret = 0; ret = (jfloat)( 1/(jfloat)getMaxBytesPerChar(env, jClass, handle)); return ret; } static void toUChars(const char* cs, UChar* us, int32_t length) { char c; while(length>0) { c=*cs++; *us++=(char)c; --length; } } static jbyteArray getSubstitutionBytes(JNIEnv *env, jclass jClass, jlong handle) { const UConverter * cnv = (const UConverter *) handle; UErrorCode status = U_ZERO_ERROR; char subBytes[10]; int8_t len =(char)10; jbyteArray arr; if(cnv) { ucnv_getSubstChars(cnv,subBytes,&len,&status); if(U_SUCCESS(status)) { arr = (env->NewByteArray(len)); if(arr) { env->SetByteArrayRegion(arr,0,len,(jbyte*)subBytes); } return arr; } } return (env->NewByteArray(0)); } static jboolean contains( JNIEnv *env, jclass jClass, jlong handle1, jlong handle2) { UErrorCode status = U_ZERO_ERROR; const UConverter * cnv1 = (const UConverter *) handle1; const UConverter * cnv2 = (const UConverter *) handle2; USet* set1; USet* set2; UBool bRet = 0; if(cnv1 != NULL && cnv2 != NULL) { /* open charset 1 */ set1 = uset_open(1, 2); ucnv_getUnicodeSet(cnv1, set1, UCNV_ROUNDTRIP_SET, &status); if(U_SUCCESS(status)) { /* open charset 2 */ status = U_ZERO_ERROR; set2 = uset_open(1, 2); ucnv_getUnicodeSet(cnv2, set2, UCNV_ROUNDTRIP_SET, &status); /* contains? */ if(U_SUCCESS(status)) { bRet = uset_containsAll(set1, set2); uset_close(set2); } uset_close(set1); } } return bRet; } /* * JNI registration */ static JNINativeMethod gMethods[] = { /* name, signature, funcPtr */ { "convertByteToChar", "(J[BI[CI[IZ)I", (void*) convertByteToChar }, { "decode", "(J[BI[CI[IZ)I", (void*) decode }, { "convertCharToByte", "(J[CI[BI[IZ)I", (void*) convertCharToByte }, { "encode", "(J[CI[BI[IZ)I", (void*) encode }, { "flushCharToByte", "(J[BI[I)I", (void*) flushCharToByte }, { "flushByteToChar", "(J[CI[I)I", (void*) flushByteToChar }, { "openConverter", "(Ljava/lang/String;)J", (void*) openConverter }, { "resetByteToChar", "(J)V", (void*) resetByteToChar }, { "resetCharToByte", "(J)V", (void*) resetCharToByte }, { "closeConverter", "(J)V", (void*) closeConverter }, { "setSubstitutionChars", "(J[CI)I", (void*) setSubstitutionChars }, { "setSubstitutionBytes", "(J[BI)I", (void*) setSubstitutionBytes }, { "setSubstitutionModeCharToByte", "(JZ)I", (void*) setSubstitutionModeCharToByte }, { "setSubstitutionModeByteToChar", "(JZ)I", (void*) setSubstitutionModeByteToChar }, { "countInvalidBytes", "(J[I)I", (void*) countInvalidBytes }, { "countInvalidChars", "(J[I)I", (void*) countInvalidChars }, { "getMaxBytesPerChar", "(J)I", (void*) getMaxBytesPerChar }, { "getMinBytesPerChar", "(J)I", (void*) getMinBytesPerChar }, { "getAveBytesPerChar", "(J)F", (void*) getAveBytesPerChar }, { "getMaxCharsPerByte", "(J)I", (void*) getMaxCharsPerByte }, { "getAveCharsPerByte", "(J)F", (void*) getAveCharsPerByte }, { "contains", "(JJ)Z", (void*) contains }, { "getSubstitutionBytes", "(J)[B", (void*) getSubstitutionBytes }, { "canEncode", "(JI)Z", (void*) canEncode }, { "canDecode", "(J[B)Z", (void*) canDecode }, { "getAvailable", "()[Ljava/lang/String;", (void*) getAvailable }, { "countAliases", "(Ljava/lang/String;)I", (void*) countAliases }, { "getAliases", "(Ljava/lang/String;)[Ljava/lang/String;", (void*) getAliases }, { "getCanonicalName", "(Ljava/lang/String;)Ljava/lang/String;", (void*) getCanonicalName }, { "getICUCanonicalName", "(Ljava/lang/String;)Ljava/lang/String;", (void*) getICUCanonicalName }, { "getJavaCanonicalName", "(Ljava/lang/String;)Ljava/lang/String;", (void*) getJavaCanonicalName2 }, { "setCallbackDecode", "(JII[CI)I", (void*) setCallbackDecode }, { "setCallbackEncode", "(JII[BI)I", (void*) setCallbackEncode }, { "safeClone", "(J)J", (void*) safeClone } }; int register_com_ibm_icu4jni_converters_NativeConverter(JNIEnv *_env) { return jniRegisterNativeMethods(_env, "com/ibm/icu4jni/charset/NativeConverter", gMethods, NELEM(gMethods)); }
#define META #ifdef META #include "meta/meta.hpp" #include <tuple> #include <type_traits> #include <cstddef> using namespace meta; namespace detail { template<typename Ret, typename...Is, typename ...Ks, typename Tuples> Ret tuple_cat_(typelist<Is...>, typelist<Ks...>, Tuples tpls) { return Ret{std::get<Ks::value>( std::get<Is::value>(tpls))...}; } } template<typename...Tuples, typename Res = typelist_apply_t< meta_quote<std::tuple>, typelist_cat_t<typelist<as_typelist_t<Tuples>...> > > > Res tuple_cat(Tuples &&... tpls) { static constexpr std::size_t N = sizeof...(Tuples); // E.g. [0,0,0,2,2,2,3,3] using inner = typelist_cat_t< typelist_transform_t< typelist<as_typelist_t<Tuples>...>, typelist_transform_t< as_typelist_t<make_index_sequence<N> >, meta_quote<meta_always> >, meta_quote<typelist_transform_t> > >; // E.g. [0,1,2,0,1,2,0,1] using outer = typelist_cat_t< typelist_transform_t< typelist<as_typelist_t<Tuples>...>, meta_compose< meta_quote<as_typelist_t>, meta_quote_i<std::size_t, make_index_sequence>, meta_quote<typelist_size_t> > > >; return detail::tuple_cat_<Res>( inner{}, outer{}, std::forward_as_tuple(std::forward<Tuples>(tpls)...)); } #elif defined(HANA) #elif defined(HANA_CONCAT) #endif template <int> struct x { }; int main() { tuple_cat( tuple() , tuple(x<1>{}) , tuple(x<1>{}, x<2>{}) , tuple(x<1>{}, x<2>{}, x<3>{}) , tuple(x<1>{}, x<2>{}, x<3>{}, x<4>{}) , tuple(x<1>{}, x<2>{}, x<3>{}, x<4>{}, x<5>{}) , tuple(2, 3, 4, 5, 6, 2, 3, 4, 5, 6, 2, 3, 4, 5, 6, 2, 3, 4, 5, 6, 2, 3, 4, 5, 6) , tuple(2, 3, 4, 5, 6, 2, 3, 4, 5, 6, 2, 3, 4, 5, 6, 2, 3, 4, 5, 3, 4, 5, 6) , tuple(2, 3, 4, 5, 6, 2, 3, 4, '5', 6, 2, 3, 4, 5, 6) , tuple(2, 3, 4, 5, 6, 2, 3, 4, 5, 6, 2, 3, 4, 5, 6, 2, 3, 4, 5) , tuple(2, 3, 4, 5, 6, 2, 3, 4, 5, 6, 2, 3, 4, 5, 6.2, 2, 3, 4, 5, 6, 4, 5, 6) , tuple(2, 3, 4, 5, 6, 2, 3, 4, 5, 6, 2, 3, 4, 5, 6, 2, 3, 4, 5, 6, 2, 3, 4, 5, 6) , tuple(2, 3, 4, 5, 6, 2, 3, 4, 5, 6, 2, 3, 4, 5, 6, 2, 3.3f, 4, 5, 6, 5, 6) , tuple(2, 3, 4, 5, 6, 2, 3, 4, 5, 6, 2, nullptr, 4, 5, 6, 2, 3, 4, 5, 6, 2, 3, 5, 6) , tuple(2, 3, 4, 5, 6, 2, 3, 4, 5, 6, 2, 3, 4, 5, "6", 2, 3, 4, 5, 6, 2, 3, 4, 5, 6) ); }
/********************************************************************** * Copyright (c) 2008-2014, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #include "LuminaireInspectorView.hpp" #include "../shared_gui_components/OSLineEdit.hpp" #include "../shared_gui_components/OSQuantityEdit.hpp" #include "OSDropZone.hpp" #include "../model/LuminaireDefinition.hpp" #include "../model/LuminaireDefinition_Impl.hpp" #include "../utilities/core/Assert.hpp" #include <QVBoxLayout> #include <QHBoxLayout> #include <QLabel> #include <QGridLayout> #include <QScrollArea> #include <QStackedWidget> namespace openstudio { LuminaireDefinitionInspectorView::LuminaireDefinitionInspectorView(bool isIP, const openstudio::model::Model& model, QWidget * parent) : ModelObjectInspectorView(model, true, parent) { m_isIP = isIP; QWidget* visibleWidget = new QWidget(); this->stackedWidget()->addWidget(visibleWidget); QGridLayout* mainGridLayout = new QGridLayout(); mainGridLayout->setContentsMargins(7,7,7,7); mainGridLayout->setSpacing(14); visibleWidget->setLayout(mainGridLayout); // Name QLabel * label = new QLabel("Name: "); label->setObjectName("H2"); mainGridLayout->addWidget(label,0,0); m_nameEdit = new OSLineEdit(); mainGridLayout->addWidget(m_nameEdit,1,0,1,2); // Lighting Power label = new QLabel("Lighting Power: "); label->setObjectName("H2"); mainGridLayout->addWidget(label,2,0); m_lightingPowerEdit = new OSQuantityEdit(m_isIP); connect(this, &LuminaireDefinitionInspectorView::toggleUnitsClicked, m_lightingPowerEdit, &OSQuantityEdit::onUnitSystemChange); mainGridLayout->addWidget(m_lightingPowerEdit,3,0); // Fraction Radiant label = new QLabel("Fraction Radiant: "); label->setObjectName("H2"); mainGridLayout->addWidget(label,4,0); m_fractionRadiantEdit = new OSQuantityEdit(m_isIP); connect(this, &LuminaireDefinitionInspectorView::toggleUnitsClicked, m_fractionRadiantEdit, &OSQuantityEdit::onUnitSystemChange); mainGridLayout->addWidget(m_fractionRadiantEdit,5,0); // Fraction Visible label = new QLabel("Fraction Visible: "); label->setObjectName("H2"); mainGridLayout->addWidget(label,4,1); m_fractionVisibleEdit = new OSQuantityEdit(m_isIP); connect(this, &LuminaireDefinitionInspectorView::toggleUnitsClicked, m_fractionVisibleEdit, &OSQuantityEdit::onUnitSystemChange); mainGridLayout->addWidget(m_fractionVisibleEdit,5,1); // Return Air Fraction label = new QLabel("Return Air Fraction: "); label->setObjectName("H2"); mainGridLayout->addWidget(label,6,0); m_returnAirFractionEdit = new OSQuantityEdit(m_isIP); connect(this, &LuminaireDefinitionInspectorView::toggleUnitsClicked, m_returnAirFractionEdit, &OSQuantityEdit::onUnitSystemChange); mainGridLayout->addWidget(m_returnAirFractionEdit,7,0); // Stretch mainGridLayout->setRowStretch(8,100); mainGridLayout->setColumnStretch(2,100); } void LuminaireDefinitionInspectorView::onClearSelection() { ModelObjectInspectorView::onClearSelection(); // call parent implementation detach(); } void LuminaireDefinitionInspectorView::onSelectModelObject(const openstudio::model::ModelObject& modelObject) { detach(); model::LuminaireDefinition luminiareDefinition = modelObject.cast<model::LuminaireDefinition>(); attach(luminiareDefinition); refresh(); } void LuminaireDefinitionInspectorView::onUpdate() { refresh(); } void LuminaireDefinitionInspectorView::attach(openstudio::model::LuminaireDefinition & luminaireDefinition) { m_nameEdit->bind(luminaireDefinition,"name"); m_lightingPowerEdit->bind(luminaireDefinition,"lightingPower",m_isIP); m_fractionRadiantEdit->bind(luminaireDefinition,"fractionRadiant",m_isIP); m_fractionVisibleEdit->bind(luminaireDefinition,"fractionVisible",m_isIP); m_returnAirFractionEdit->bind(luminaireDefinition,"returnAirFraction",m_isIP); this->stackedWidget()->setCurrentIndex(1); } void LuminaireDefinitionInspectorView::detach() { this->stackedWidget()->setCurrentIndex(0); m_nameEdit->unbind(); m_lightingPowerEdit->unbind(); m_fractionRadiantEdit->unbind(); m_fractionVisibleEdit->unbind(); m_returnAirFractionEdit->unbind(); } void LuminaireDefinitionInspectorView::refresh() { } void LuminaireDefinitionInspectorView::toggleUnits(bool displayIP) { m_isIP = displayIP; } } // openstudio
// // Created by peter on 03.08.2020. // #include "RTShadowsPass.h" #include "BilateralFilterPass.h" #include "CameraDescription.h" #include "RTSceneDescription.h" #include "VarAwareTempAccumFilterColor.h" #include "rendering_loop/DescriptorGenerator.h" #include "utils.h" #include <Engine/Common/IDeviceState.h> #include <Engine/Common/types/sampler_filter.h> #include <Engine/VulkanImpl/VulkanCommandBuffer.h> #include <Engine/VulkanImpl/VulkanDeviceState.h> #include <array> #include <render_driver/gpu_resources/raster_pool.h> #include <render_driver/render_driver.h> #include <rw_engine/rh_backend/raster_backend.h> #include <rw_engine/system_funcs/rw_device_system_globals.h> namespace rh::rw::engine { using namespace rh::engine; RTShadowsPass::RTShadowsPass( const RTShadowsInitParams &params ) : Device( params.Device ), mCamera( params.mCamera ), mScene( params.mScene ), mWidth( params.mWidth ), mHeight( params.mHeight ) { DescriptorGenerator descriptorGenerator{ Device }; /// TLAS descriptorGenerator.AddDescriptor( 0, 0, 0, DescriptorType::RTAccelerationStruct, 1, ShaderStage::RayGen | ShaderStage::RayHit ); /// Result buffer descriptorGenerator.AddDescriptor( 0, 1, 0, DescriptorType::StorageTexture, 1, ShaderStage::RayGen ); /// Normal/depth buffer; TODO: REPLACE with ROTexture for performance descriptorGenerator.AddDescriptor( 0, 2, 0, DescriptorType::StorageTexture, 1, ShaderStage::RayGen ); /// Default sampler descriptorGenerator.AddDescriptor( 0, 3, 0, DescriptorType::Sampler, 1, ShaderStage::RayGen | ShaderStage::RayHit | ShaderStage::RayAnyHit ); /// Noise texture descriptorGenerator.AddDescriptor( 0, 4, 0, DescriptorType::ROTexture, 1, ShaderStage::RayGen ); /// SkyCfg descriptorGenerator.AddDescriptor( 0, 5, 0, DescriptorType::ROBuffer, 1, ShaderStage::RayGen ); /// ShadowCfg descriptorGenerator .AddDescriptor( 0, 6, 0, DescriptorType::ROBuffer, 1, ShaderStage::RayGen ) // pointlights .AddDescriptor( 0, 7, 0, DescriptorType::RWBuffer, 1, ShaderStage::RayGen ) .AddDescriptor( 0, 8, 0, DescriptorType::RWBuffer, 1, ShaderStage::RayGen ) .AddDescriptor( 0, 9, 0, DescriptorType::RWBuffer, 1, ShaderStage::RayGen ); // Create Layouts mRayTraceSetLayout = descriptorGenerator.FinalizeDescriptorSet( 0, 1 ); // Desc set allocator mDescSetAlloc = descriptorGenerator.FinalizeAllocator(); std::array layout_array = { static_cast<IDescriptorSetLayout *>( mRayTraceSetLayout ), mCamera->GetSetLayout(), mScene->DescLayout() }; mPipeLayout = Device.CreatePipelineLayout( { .mSetLayouts = layout_array } ); std::array tex_layout_array = { static_cast<IDescriptorSetLayout *>( mRayTraceSetLayout ) }; auto results = mDescSetAlloc->AllocateDescriptorSets( { .mLayouts = tex_layout_array } ); mRayTraceSet = results[0]; // setup camera stuff mTextureSampler = Device.CreateSampler( { Sampler{ SamplerFilter::Linear } } ); std::array sampler_upd_info = { ImageUpdateInfo{ ImageLayout::ShaderReadOnly, nullptr, mTextureSampler } }; Device.UpdateDescriptorSets( { .mSet = mRayTraceSet, .mBinding = 3, .mDescriptorType = DescriptorType::Sampler, .mImageUpdateInfo = sampler_upd_info } ); // create shaders mRayGenShader = Device.CreateShader( { .mShaderPath = "shaders/vulkan/engine/rt_shadows.rgen", .mEntryPoint = "main", .mShaderStage = ShaderStage::RayGen } ); mClosestHitShader = Device.CreateShader( { .mShaderPath = "shaders/vulkan/engine/rt_shadows.rchit", .mEntryPoint = "main", .mShaderStage = ShaderStage::RayHit } ); mAnyHitShader = Device.CreateShader( { .mShaderPath = "shaders/vulkan/engine/rt_shadows.rahit", .mEntryPoint = "main", .mShaderStage = ShaderStage::RayAnyHit } ); mMissShader = Device.CreateShader( { .mShaderPath = "shaders/vulkan/engine/raytrace_shadow.rmiss", .mEntryPoint = "main", .mShaderStage = ShaderStage::RayMiss } ); // create rt buffers mShadowsBuffer = Create2DRenderTargetBuffer( Device, params.mWidth, params.mHeight, ImageBufferFormat::RGBA16 ); mShadowsBufferView = Device.CreateImageView( { mShadowsBuffer, ImageBufferFormat::RGBA16, ImageViewUsage::RWTexture } ); mTempBlurShadowsBuffer = Create2DRenderTargetBuffer( Device, params.mWidth, params.mHeight, ImageBufferFormat::RGBA16 ); mTempBlurShadowsBufferView = Device.CreateImageView( { mTempBlurShadowsBuffer, ImageBufferFormat::RGBA16, ImageViewUsage::RWTexture } ); mBlurredShadowsBuffer = Create2DRenderTargetBuffer( Device, params.mWidth, params.mHeight, ImageBufferFormat::RGBA16 ); mBlurredShadowsBufferView = Device.CreateImageView( { mBlurredShadowsBuffer, ImageBufferFormat::RGBA16, ImageViewUsage::RWTexture } ); mParamsBuffer = Device.CreateBuffer( { .mSize = sizeof( ShadowParams ), .mUsage = BufferUsage::ConstantBuffer } ); auto noise = ReadBMP( "resources/blue_noise.bmp" ); mNoiseBuffer = noise.mImageBuffer; mNoiseBufferView = noise.mImageView; // Bind descriptor buffers { std::array<ImageUpdateInfo, 1> img_ui = { { ImageLayout::General, mShadowsBufferView, nullptr } }; Device.UpdateDescriptorSets( { .mSet = mRayTraceSet, .mBinding = 1, .mDescriptorType = DescriptorType::StorageTexture, .mImageUpdateInfo = img_ui } ); } { std::array<ImageUpdateInfo, 1> img_ui = { { ImageLayout::General, params.mNormalsView, nullptr } }; Device.UpdateDescriptorSets( { .mSet = mRayTraceSet, .mBinding = 2, .mDescriptorType = DescriptorType::StorageTexture, .mImageUpdateInfo = img_ui } ); } { std::array<ImageUpdateInfo, 1> img_ui = { { ImageLayout::ShaderReadOnly, mNoiseBufferView, nullptr } }; Device.UpdateDescriptorSets( { .mSet = mRayTraceSet, .mBinding = 4, .mDescriptorType = DescriptorType::ROTexture, .mImageUpdateInfo = img_ui } ); } { Device.UpdateDescriptorSets( { .mSet = mRayTraceSet, .mBinding = 5, .mDescriptorType = DescriptorType::ROBuffer, .mBufferUpdateInfo = { { .mOffset = 0, .mRange = VK_WHOLE_SIZE, .mBuffer = params.mSkyCfg } } } ); } { Device.UpdateDescriptorSets( { .mSet = mRayTraceSet, .mBinding = 6, .mDescriptorType = DescriptorType::ROBuffer, .mBufferUpdateInfo = { { .mOffset = 0, .mRange = VK_WHOLE_SIZE, .mBuffer = mParamsBuffer } } } ); } { Device.UpdateDescriptorSets( { .mSet = mRayTraceSet, .mBinding = 7, .mDescriptorType = DescriptorType::RWBuffer, .mBufferUpdateInfo = { { .mOffset = 0, .mRange = VK_WHOLE_SIZE, .mBuffer = params.mLightBuffer } } } ); } { Device.UpdateDescriptorSets( { .mSet = mRayTraceSet, .mBinding = 8, .mDescriptorType = DescriptorType::RWBuffer, .mBufferUpdateInfo = { { .mOffset = 0, .mRange = VK_WHOLE_SIZE, .mBuffer = params.mTileBuffer } } } ); } { Device.UpdateDescriptorSets( { .mSet = mRayTraceSet, .mBinding = 9, .mDescriptorType = DescriptorType::RWBuffer, .mBufferUpdateInfo = { { .mOffset = 0, .mRange = VK_WHOLE_SIZE, .mBuffer = params.mLightIdxBuffer } } } ); } /// TODO: Make it easier to create raytracing hitgroups/sbt's std::vector<ShaderStageDesc> stage_descs{}; std::vector<RayTracingGroup> rt_groups{}; stage_descs.push_back( ShaderStageDesc{ ShaderStage::RayGen, mRayGenShader, "main" } ); rt_groups.push_back( RayTracingGroup{ RTShaderGroupType::General, 0u } ); stage_descs.push_back( ShaderStageDesc{ ShaderStage::RayMiss, mMissShader, "main" } ); rt_groups.push_back( RayTracingGroup{ RTShaderGroupType::General, 1u } ); stage_descs.push_back( ShaderStageDesc{ ShaderStage::RayAnyHit, mAnyHitShader, "main" } ); stage_descs.push_back( ShaderStageDesc{ ShaderStage::RayHit, mClosestHitShader, "main" } ); rt_groups.push_back( RayTracingGroup{ RTShaderGroupType::TriangleHitGroup, ~0u, 2u, 3u, ~0u, } ); mPipeline = dynamic_cast<VulkanDeviceState &>( Device ).CreateRayTracingPipeline( { .mLayout = mPipeLayout, .mShaderStages = stage_descs, .mShaderGroups = rt_groups } ); auto sbt = mPipeline->GetShaderBindingTable(); mShaderBindTable = Device.CreateBuffer( { .mSize = static_cast<uint32_t>( sbt.size() ), .mUsage = BufferUsage::RayTracingScratch, .mFlags = BufferFlags::Dynamic } ); /// Weird stuff from nvidia tutorial, I guess they fill in some data with /// garbage? // TODO: move somewhere else auto *pData = reinterpret_cast<uint8_t *>( mShaderBindTable->Lock() ); for ( uint32_t g = 0; g < rt_groups.size(); g++ ) { memcpy( pData, sbt.data() + g * mPipeline->GetSBTHandleSizeUnalign(), mPipeline->GetSBTHandleSizeUnalign() ); pData += mPipeline->GetSBTHandleSize(); } mShaderBindTable->Unlock(); // Filtering mVarianceTAFilter = params.mTAFilterPipeline->GetFilter( VATAColorPassParam{ .mWidth = mWidth, .mHeight = mHeight, .mInputValue = mShadowsBufferView, .mPrevDepth = params.mPrevNormalsView, .mCurrentDepth = params.mNormalsView, .mMotionVectors = params.mMotionVectorsView } ); mBilFil0 = params.mBilFilterPipe->GetPass( BilateralFilterPassParams{ .mInputImage = mVarianceTAFilter->GetAccumulatedValue(), .mTempImage = mTempBlurShadowsBufferView, .mOutputImage = mBlurredShadowsBufferView, .mNormalDepthBuffer = params.mNormalsView, .mBlurStrength = mVarianceTAFilter->GetBlurIntensity(), .mTempImageBuffer = mTempBlurShadowsBuffer, .mOutputImageBuffer = mBlurredShadowsBuffer, .mWidth = mWidth, .mHeight = mHeight } ); } void RTShadowsPass::Execute( void * tlas, rh::engine::ICommandBuffer *cmd_buffer ) { auto *vk_cmd_buff = dynamic_cast<VulkanCommandBuffer *>( cmd_buffer ); std::array<AccelStructUpdateInfo, 1> accel_ui = { { tlas } }; Device.UpdateDescriptorSets( { .mSet = mRayTraceSet, .mBinding = 0, .mDescriptorType = DescriptorType::RTAccelerationStruct, .mASUpdateInfo = accel_ui } ); mParams.time_stamp++; mParamsBuffer->Update( &mParams, sizeof( mParams ) ); /// TRANSFORM TO GENERAL // Prepare image memory to transfer to // TODO: Add some sort of memory barrier mgr vk_cmd_buff->PipelineBarrier( { .mSrcStage = PipelineStage::Host, .mDstStage = PipelineStage::Transfer, .mImageMemoryBarriers = { GetLayoutTransformBarrier( mShadowsBuffer, ImageLayout::Undefined, ImageLayout::General ), GetLayoutTransformBarrier( mBlurredShadowsBuffer, ImageLayout::Undefined, ImageLayout::General ), GetLayoutTransformBarrier( mTempBlurShadowsBuffer, ImageLayout::Undefined, ImageLayout::General ) } } ); // bind pipeline std::array desc_sets = { static_cast<IDescriptorSet *>( mRayTraceSet ), mCamera->GetDescSet(), mScene->DescSet() }; vk_cmd_buff->BindDescriptorSets( { .mPipelineBindPoint = PipelineBindPoint::RayTracing, .mPipelineLayout = mPipeLayout, .mDescriptorSets = desc_sets } ); uint32_t sbt_size = mPipeline->GetSBTHandleSize(); vk_cmd_buff->BindRayTracingPipeline( mPipeline ); vk_cmd_buff->DispatchRays( { mShaderBindTable, 0, mShaderBindTable, sbt_size, sbt_size, mShaderBindTable, sbt_size * 2, sbt_size, nullptr, 0, 0, mWidth, mHeight, 1 } ); mVarianceTAFilter->Execute( vk_cmd_buff ); mBilFil0->Execute( vk_cmd_buff ); /* ImageMemoryBarrierInfo shader_ro_barrier = GetLayoutTransformBarrier( mShadowsBuffer, ImageLayout::General, ImageLayout::ShaderReadOnly ); shader_ro_barrier.mDstMemoryAccess = MemoryAccessFlags::ShaderRead; std::array dest_image_barriers = { shader_ro_barrier }; vk_cmd_buff->PipelineBarrier( { .mSrcStage = PipelineStage::RayTracing, .mDstStage = PipelineStage::PixelShader, .mImageMemoryBarriers = dest_image_barriers } );*/ } rh::engine::IImageView *RTShadowsPass::GetShadowsView() { return mBlurredShadowsBufferView; } } // namespace rh::rw::engine
#include <file/PlainText.hpp> #include <fstream> std::string readWholeFile(const std::string_view filename){ std::ifstream infile(filename.data(),std::ios::in | std::ios::binary | std::ios::ate); std::string contents; if (infile){ int size = infile.tellg(); contents.resize(size); infile.seekg(0, std::ios::beg); infile.read(&contents[0],size); infile.close(); } return contents; } std::string_view MMAPFile::getString(){ if (this->size) { return std::string_view(reinterpret_cast<char*>(this->mapping), this->size); } else { return ""; } } #if defined _WIN32 || defined __CYGWIN__ #define WIN32_LEAN_AND_MEAN #include <windows.h> MMAPFile::MMAPFile(const std::string_view filename){ WIN32_FILE_ATTRIBUTE_DATA file_attr_data; LARGE_INTEGER file_size = {0}; if (GetFileAttributesEx(filename.data(), GetFileExInfoStandard, &file_attr_data)){ file_size.HighPart = file_attr_data.nFileSizeHigh; file_size.LowPart = file_attr_data.nFileSizeLow; this->fd = CreateFile(filename.data(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); HANDLE mhandle = CreateFileMapping(fd, 0, PAGE_WRITECOPY, 0, 0, 0); this->mapping = MapViewOfFile(mhandle, FILE_MAP_COPY, 0, 0, 0); CloseHandle(mhandle); } this->size = file_size.QuadPart; } MMAPFile::~MMAPFile(){ UnmapViewOfFile(this->mapping); CloseHandle(this->fd); } #else #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> MMAPFile::MMAPFile(const std::string_view filename){ struct stat st; if (stat(filename.data(), &st) == 0) { this->size = st.st_size; this->fd = new int; int* fdp = reinterpret_cast<int*>(fd); *fdp = open(filename.data(), O_RDONLY); this->mapping = mmap(nullptr, this->size, PROT_READ | PROT_WRITE, MAP_PRIVATE, *fdp, 0); } else { this->mapping = nullptr; this->fd = nullptr; this->size = 0; } } MMAPFile::~MMAPFile(){ if (this->mapping) { munmap(this->mapping, this->size); int* fdp = reinterpret_cast<int*>(fd); close(*fdp); delete fdp; } } #endif
#include "..\Aspose.Pdf.h" using namespace System; using namespace Aspose::Pdf; using namespace Aspose::Pdf::Text; void ExtractTextFromRangeOfPages() { // ExStart:ExtractTextFromRangeOfPages auto extractor = MakeObject<Facades::PdfExtractor>(); extractor->BindPdf(u"..\\Data\\Text\\ExtractText-PageRange.pdf"); // Specify start and end pages extractor->set_StartPage(1); extractor->set_EndPage(1); // Use parameterless ExtractText method extractor->ExtractText(); auto memStream = MakeObject<IO::MemoryStream>(); extractor->GetText(memStream); auto unicode = System::Text::Encoding::get_Unicode(); String allText = unicode->GetString(memStream->ToArray()); Console::WriteLine(allText); // ExEnd:ExtractTextFromRangeOfPages }
// $Id: server.cpp 91825 2010-09-17 09:10:22Z johnnyw $ #include "tao/corba.h" #include "tao/PortableServer/PortableServer.h" #include "testS.h" #include "ace/Get_Opt.h" #include "ace/OS_NS_stdio.h" const ACE_TCHAR *ior_output_file = ACE_TEXT ("test.ior"); int parse_args (int argc, ACE_TCHAR *argv[]) { ACE_Get_Opt get_opts (argc, argv, ACE_TEXT("o:")); int c; while ((c = get_opts ()) != -1) switch (c) { case 'o': ior_output_file = get_opts.opt_arg (); break; case '?': default: ACE_ERROR_RETURN ((LM_ERROR, "usage: %s " "-o <iorfile>" "\n", argv [0]), -1); } // Indicates successful parsing of the command line return 0; } class ctest_impl : public virtual POA_ctest { public: /// Constructor ctest_impl (CORBA::ORB_ptr orb) : orb_ (CORBA::ORB::_duplicate (orb)) {} CORBA::Long ctestfn(CORBA::Long size, ctest::UCSeq_out data) { data = new ctest::UCSeq; data->length(size); for (CORBA::ULong i = 0; i < data->length(); ++i) { data[i] = (rand() % 26) + 'A'; } return 0; } void shutdown (void) { this->orb_->shutdown (0); } private: /// Use an ORB reference to convert strings to objects and shutdown /// the application. CORBA::ORB_var orb_; }; int ACE_TMAIN (int argc, ACE_TCHAR *argv[]) { try { CORBA::ORB_var orb = CORBA::ORB_init (argc, argv); CORBA::Object_var poa_object = orb->resolve_initial_references ("RootPOA"); PortableServer::POA_var root_poa = PortableServer::POA::_narrow (poa_object.in ()); if (CORBA::is_nil (root_poa.in ())) ACE_ERROR_RETURN ((LM_ERROR, " (%P|%t) Panic: nil RootPOA\n"), 1); PortableServer::POAManager_var poa_manager = root_poa->the_POAManager (); if (parse_args (argc, argv) != 0) return 1; ctest_impl *hello_impl = 0; ACE_NEW_RETURN (hello_impl, ctest_impl (orb.in ()), 1); PortableServer::ServantBase_var owner_transfer(hello_impl); PortableServer::ObjectId_var id = root_poa->activate_object (hello_impl); CORBA::Object_var object = root_poa->id_to_reference (id.in ()); ctest_var hello = ctest::_narrow (object.in ()); CORBA::String_var ior = orb->object_to_string (hello.in ()); // Output the IOR to the <ior_output_file> FILE *output_file= ACE_OS::fopen (ior_output_file, "w"); if (output_file == 0) ACE_ERROR_RETURN ((LM_ERROR, "Cannot open output file for writing IOR: %s\n", ior_output_file), 1); ACE_OS::fprintf (output_file, "%s", ior.in ()); ACE_OS::fclose (output_file); poa_manager->activate (); orb->run(); ACE_DEBUG ((LM_DEBUG, "(%P|%t) server - event loop finished\n")); root_poa->destroy (1, 1); orb->destroy (); } catch (const CORBA::Exception& ex) { ex._tao_print_exception ("Exception caught:"); return 1; } return 0; }
#ifndef _NEVIL_SIBLING_ROBOT_HPP_ #define _NEVIL_SIBLING_ROBOT_HPP_ #include "nevil/arena/robot.hpp" #include "nevil/robot_controller/basic_feedforward_nn.hpp" #include "nevil/sibling_individual.hpp" namespace nevil { class sibling_robot : public robot { public: sibling_robot(double x, double y, double angle, bool sibling_nn, double max_speed, const std::string &robot_name, const Enki::Color &color); virtual ~sibling_robot(); bool update(const std::vector<object *> &objects); void set_individual(nevil::individual *i); protected: bool _sibling_neuron; nevil::sibling_individual *_individual; nevil::basic_feedforward_nn _neural_network; }; } #endif // _NEVIL_SIBLING_ROBOT_HPP_
/** * @file spimasterstrategy.hpp * * @date 2018/02/11 * @author: Seiichi "Suikan" Horie * @brief SPI master root class. */ #ifndef SPIMASTERSTRATEGY_HPP_ #define SPIMASTERSTRATEGY_HPP_ #include <spicallbackstrategy.hpp> #include <spislaveadapterstrategy.hpp> namespace murasaki { /** * \brief Root class of the SPI master * \details * This class provides a thread safe, synchronous SPI transfer. * * \ingroup MURASAKI_ABSTRACT_GROUP */ class SpiMasterStrategy : public murasaki::SpiCallbackStrategy { public: /** * @brief Thread safe, synchronous SPI transfer * @param spi_spec Pointer to the SPI slave adapter which has clock configuraiton and chip select handling. * @param tx_data Data to be transmitted * @param rx_data Data buffer to receive data * @param size Transfer data size [byte] for each way. Must be smaller than 65536 * @param timeout_ms Timeout limit [mS] * @return true if transfer complete, false if timeout */ virtual SpiStatus TransmitAndReceive( murasaki::SpiSlaveAdapterStrategy *spi_spec, const uint8_t *tx_data, uint8_t *rx_data, unsigned int size, unsigned int timeout_ms = murasaki::kwmsIndefinitely)=0; }; } /* namespace murasaki */ #endif /* SPIMASTERSTRATEGY_HPP_ */
// Copyright 2015 Adam Grandquist #include "./catch.hpp" #include "./ReQL.h" TEST_CASE("c Issue 95", "[c][ast]") { SECTION("test0") { } SECTION("test1") { } SECTION("test2") { } SECTION("test3") { } SECTION("test4") { } SECTION("test5") { } SECTION("test6") { } SECTION("test7") { } SECTION("test8") { } SECTION("test9") { } SECTION("test10") { } SECTION("test11") { } SECTION("test12") { } SECTION("test13") { } SECTION("test14") { } SECTION("test15") { } SECTION("test16") { } SECTION("test17") { } SECTION("test18") { } SECTION("test19") { } SECTION("test20") { } SECTION("test21") { } }
#include "YostLabDriver.h" int main(int argc, char **argv) { ros::init(argc, argv, "imu"); ros::NodeHandle nh; ros::NodeHandle priv_nh("~"); YostLabDriver imu_drv(nh, priv_nh); imu_drv.run(); }
/** * Copyright Soramitsu Co., Ltd. 2017 All Rights Reserved. * http://soramitsu.co.jp * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef IROHA_SHARED_MODEL_ADD_ASSET_QUANTITY_HPP #define IROHA_SHARED_MODEL_ADD_ASSET_QUANTITY_HPP #include "interfaces/base/model_primitive.hpp" #include "interfaces/common_objects/amount.hpp" #include "interfaces/common_objects/types.hpp" namespace shared_model { namespace interface { /** * Add amount of asset to an account */ class AddAssetQuantity : public ModelPrimitive<AddAssetQuantity> { public: /** * @return Identity of user, that add quantity */ virtual const types::AccountIdType &accountId() const = 0; /** * @return asset identifier */ virtual const types::AssetIdType &assetId() const = 0; /** * @return quantity of asset for adding */ virtual const Amount &amount() const = 0; std::string toString() const override; bool operator==(const ModelType &rhs) const override; }; } // namespace interface } // namespace shared_model #endif // IROHA_SHARED_MODEL_ADD_ASSET_QUANTITY_HPP
// Copyright (c) 2011-2015 The Bitcoin Core developers // 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. #if defined(HAVE_CONFIG_H) #include "config/oontcoin-config.h" #endif #include "rpcconsole.h" #include "ui_debugwindow.h" #include "bantablemodel.h" #include "clientmodel.h" #include "guiutil.h" #include "platformstyle.h" #include "chainparams.h" #include "netbase.h" #include "rpc/server.h" #include "rpc/client.h" #include "util.h" #include <openssl/crypto.h> #include <univalue.h> #ifdef ENABLE_WALLET #include <db_cxx.h> #endif #include <QDir> #include <QKeyEvent> #include <QMenu> #include <QMessageBox> #include <QScrollBar> #include <QSettings> #include <QSignalMapper> #include <QThread> #include <QTime> #include <QTimer> #include <QStringList> #if QT_VERSION < 0x050000 #include <QUrl> #endif // TODO: add a scrollback limit, as there is currently none // TODO: make it possible to filter out categories (esp debug messages when implemented) // TODO: receive errors and debug messages through ClientModel const int CONSOLE_HISTORY = 50; const QSize FONT_RANGE(4, 40); const char fontSizeSettingsKey[] = "consoleFontSize"; const TrafficGraphData::GraphRange INITIAL_TRAFFIC_GRAPH_SETTING = TrafficGraphData::Range_30m; // Repair parameters const QString SALVAGEWALLET("-salvagewallet"); const QString RESCAN("-rescan"); const QString ZAPTXES1("-zapwallettxes=1"); const QString ZAPTXES2("-zapwallettxes=2"); const QString UPGRADEWALLET("-upgradewallet"); const QString REINDEX("-reindex"); const struct { const char *url; const char *source; } ICON_MAPPING[] = { {"cmd-request", "tx_input"}, {"cmd-reply", "tx_output"}, {"cmd-error", "tx_output"}, {"misc", "tx_inout"}, {NULL, NULL} }; namespace { // don't add private key handling cmd's to the history const QStringList historyFilter = QStringList() << "importprivkey" << "importmulti" << "signmessagewithprivkey" << "signrawtransaction" << "walletpassphrase" << "walletpassphrasechange" << "encryptwallet"; } /* Object for executing console RPC commands in a separate thread. */ class RPCExecutor : public QObject { Q_OBJECT public Q_SLOTS: void request(const QString &command); Q_SIGNALS: void reply(int category, const QString &command); }; /** Class for handling RPC timers * (used for e.g. re-locking the wallet after a timeout) */ class QtRPCTimerBase: public QObject, public RPCTimerBase { Q_OBJECT public: QtRPCTimerBase(boost::function<void(void)>& _func, int64_t millis): func(_func) { timer.setSingleShot(true); connect(&timer, SIGNAL(timeout()), this, SLOT(timeout())); timer.start(millis); } ~QtRPCTimerBase() {} private Q_SLOTS: void timeout() { func(); } private: QTimer timer; boost::function<void(void)> func; }; class QtRPCTimerInterface: public RPCTimerInterface { public: ~QtRPCTimerInterface() {} const char *Name() override { return "Qt"; } RPCTimerBase* NewTimer(boost::function<void(void)>& func, int64_t millis) override { return new QtRPCTimerBase(func, millis); } }; #include "rpcconsole.moc" /** * Split shell command line into a list of arguments and optionally execute the command(s). * Aims to emulate \c bash and friends. * * - Command nesting is possible with parenthesis; for example: validateaddress(getnewaddress()) * - Arguments are delimited with whitespace or comma * - Extra whitespace at the beginning and end and between arguments will be ignored * - Text can be "double" or 'single' quoted * - The backslash \c \ is used as escape character * - Outside quotes, any character can be escaped * - Within double quotes, only escape \c " and backslashes before a \c " or another backslash * - Within single quotes, no escaping is possible and no special interpretation takes place * * @param[out] result stringified Result from the executed command(chain) * @param[in] strCommand Command line to split * @param[in] fExecute set true if you want the command to be executed * @param[out] pstrFilteredOut Command line, filtered to remove any sensitive data */ bool RPCConsole::RPCParseCommandLine(std::string &strResult, const std::string &strCommand, const bool fExecute, std::string * const pstrFilteredOut) { std::vector< std::vector<std::string> > stack; stack.push_back(std::vector<std::string>()); enum CmdParseState { STATE_EATING_SPACES, STATE_EATING_SPACES_IN_ARG, STATE_EATING_SPACES_IN_BRACKETS, STATE_ARGUMENT, STATE_SINGLEQUOTED, STATE_DOUBLEQUOTED, STATE_ESCAPE_OUTER, STATE_ESCAPE_DOUBLEQUOTED, STATE_COMMAND_EXECUTED, STATE_COMMAND_EXECUTED_INNER } state = STATE_EATING_SPACES; std::string curarg; UniValue lastResult; unsigned nDepthInsideSensitive = 0; size_t filter_begin_pos = 0, chpos; std::vector<std::pair<size_t, size_t>> filter_ranges; auto add_to_current_stack = [&](const std::string& strArg) { if (stack.back().empty() && (!nDepthInsideSensitive) && historyFilter.contains(QString::fromStdString(strArg), Qt::CaseInsensitive)) { nDepthInsideSensitive = 1; filter_begin_pos = chpos; } // Make sure stack is not empty before adding something if (stack.empty()) { stack.push_back(std::vector<std::string>()); } stack.back().push_back(strArg); }; auto close_out_params = [&]() { if (nDepthInsideSensitive) { if (!--nDepthInsideSensitive) { assert(filter_begin_pos); filter_ranges.push_back(std::make_pair(filter_begin_pos, chpos)); filter_begin_pos = 0; } } stack.pop_back(); }; std::string strCommandTerminated = strCommand; if (strCommandTerminated.back() != '\n') strCommandTerminated += "\n"; for (chpos = 0; chpos < strCommandTerminated.size(); ++chpos) { char ch = strCommandTerminated[chpos]; switch(state) { case STATE_COMMAND_EXECUTED_INNER: case STATE_COMMAND_EXECUTED: { bool breakParsing = true; switch(ch) { case '[': curarg.clear(); state = STATE_COMMAND_EXECUTED_INNER; break; default: if (state == STATE_COMMAND_EXECUTED_INNER) { if (ch != ']') { // append char to the current argument (which is also used for the query command) curarg += ch; break; } if (curarg.size() && fExecute) { // if we have a value query, query arrays with index and objects with a string key UniValue subelement; if (lastResult.isArray()) { for(char argch: curarg) if (!std::isdigit(argch)) throw std::runtime_error("Invalid result query"); subelement = lastResult[atoi(curarg.c_str())]; } else if (lastResult.isObject()) subelement = find_value(lastResult, curarg); else throw std::runtime_error("Invalid result query"); //no array or object: abort lastResult = subelement; } state = STATE_COMMAND_EXECUTED; break; } // don't break parsing when the char is required for the next argument breakParsing = false; // pop the stack and return the result to the current command arguments close_out_params(); // don't stringify the json in case of a string to avoid doublequotes if (lastResult.isStr()) curarg = lastResult.get_str(); else curarg = lastResult.write(2); // if we have a non empty result, use it as stack argument otherwise as general result if (curarg.size()) { if (stack.size()) add_to_current_stack(curarg); else strResult = curarg; } curarg.clear(); // assume eating space state state = STATE_EATING_SPACES; } if (breakParsing) break; } case STATE_ARGUMENT: // In or after argument case STATE_EATING_SPACES_IN_ARG: case STATE_EATING_SPACES_IN_BRACKETS: case STATE_EATING_SPACES: // Handle runs of whitespace switch(ch) { case '"': state = STATE_DOUBLEQUOTED; break; case '\'': state = STATE_SINGLEQUOTED; break; case '\\': state = STATE_ESCAPE_OUTER; break; case '(': case ')': case '\n': if (state == STATE_EATING_SPACES_IN_ARG) throw std::runtime_error("Invalid Syntax"); if (state == STATE_ARGUMENT) { if (ch == '(' && stack.size() && stack.back().size() > 0) { if (nDepthInsideSensitive) { ++nDepthInsideSensitive; } stack.push_back(std::vector<std::string>()); } // don't allow commands after executed commands on baselevel if (!stack.size()) throw std::runtime_error("Invalid Syntax"); add_to_current_stack(curarg); curarg.clear(); state = STATE_EATING_SPACES_IN_BRACKETS; } if ((ch == ')' || ch == '\n') && stack.size() > 0) { if (fExecute) { // Convert argument list to JSON objects in method-dependent way, // and pass it along with the method name to the dispatcher. JSONRPCRequest req; req.params = RPCConvertValues(stack.back()[0], std::vector<std::string>(stack.back().begin() + 1, stack.back().end())); req.strMethod = stack.back()[0]; lastResult = tableRPC.execute(req); } state = STATE_COMMAND_EXECUTED; curarg.clear(); } break; case ' ': case ',': case '\t': if(state == STATE_EATING_SPACES_IN_ARG && curarg.empty() && ch == ',') throw std::runtime_error("Invalid Syntax"); else if(state == STATE_ARGUMENT) // Space ends argument { add_to_current_stack(curarg); curarg.clear(); } if ((state == STATE_EATING_SPACES_IN_BRACKETS || state == STATE_ARGUMENT) && ch == ',') { state = STATE_EATING_SPACES_IN_ARG; break; } state = STATE_EATING_SPACES; break; default: curarg += ch; state = STATE_ARGUMENT; } break; case STATE_SINGLEQUOTED: // Single-quoted string switch(ch) { case '\'': state = STATE_ARGUMENT; break; default: curarg += ch; } break; case STATE_DOUBLEQUOTED: // Double-quoted string switch(ch) { case '"': state = STATE_ARGUMENT; break; case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break; default: curarg += ch; } break; case STATE_ESCAPE_OUTER: // '\' outside quotes curarg += ch; state = STATE_ARGUMENT; break; case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself curarg += ch; state = STATE_DOUBLEQUOTED; break; } } if (pstrFilteredOut) { if (STATE_COMMAND_EXECUTED == state) { assert(!stack.empty()); close_out_params(); } *pstrFilteredOut = strCommand; for (auto i = filter_ranges.rbegin(); i != filter_ranges.rend(); ++i) { pstrFilteredOut->replace(i->first, i->second - i->first, "(…)"); } } switch(state) // final state { case STATE_COMMAND_EXECUTED: if (lastResult.isStr()) strResult = lastResult.get_str(); else strResult = lastResult.write(2); case STATE_ARGUMENT: case STATE_EATING_SPACES: return true; default: // ERROR to end in one of the other states return false; } } void RPCExecutor::request(const QString &command) { try { std::string result; std::string executableCommand = command.toStdString() + "\n"; if(!RPCConsole::RPCExecuteCommandLine(result, executableCommand)) { Q_EMIT reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \"")); return; } Q_EMIT reply(RPCConsole::CMD_REPLY, QString::fromStdString(result)); } catch (UniValue& objError) { try // Nice formatting for standard-format error { int code = find_value(objError, "code").get_int(); std::string message = find_value(objError, "message").get_str(); Q_EMIT reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")"); } catch (const std::runtime_error&) // raised when converting to invalid type, i.e. missing code or message { // Show raw JSON object Q_EMIT reply(RPCConsole::CMD_ERROR, QString::fromStdString(objError.write())); } } catch (const std::exception& e) { Q_EMIT reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what())); } } RPCConsole::RPCConsole(const PlatformStyle *_platformStyle, QWidget *parent) : QWidget(parent), ui(new Ui::RPCConsole), clientModel(0), historyPtr(0), platformStyle(_platformStyle), peersTableContextMenu(0), banTableContextMenu(0), consoleFontSize(0) { ui->setupUi(this); GUIUtil::restoreWindowGeometry("nRPCConsoleWindow", this->size(), this); ui->openDebugLogfileButton->setToolTip(ui->openDebugLogfileButton->toolTip().arg(tr(PACKAGE_NAME))); QString theme = GUIUtil::getThemeName(); if (platformStyle->getImagesOnButtons()) { ui->openDebugLogfileButton->setIcon(QIcon(":/icons/" + theme + "/export")); } // Needed on Mac also ui->clearButton->setIcon(QIcon(":/icons/" + theme + "/remove")); ui->fontBiggerButton->setIcon(QIcon(":/icons/" + theme + "/fontbigger")); ui->fontSmallerButton->setIcon(QIcon(":/icons/" + theme + "/fontsmaller")); // Install event filter for up and down arrow ui->lineEdit->installEventFilter(this); ui->messagesWidget->installEventFilter(this); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); connect(ui->fontBiggerButton, SIGNAL(clicked()), this, SLOT(fontBigger())); connect(ui->fontSmallerButton, SIGNAL(clicked()), this, SLOT(fontSmaller())); connect(ui->btnClearTrafficGraph, SIGNAL(clicked()), ui->trafficGraph, SLOT(clear())); // Wallet Repair Buttons // connect(ui->btn_salvagewallet, SIGNAL(clicked()), this, SLOT(walletSalvage())); // Disable salvage option in GUI, it's way too powerful and can lead to funds loss ui->btn_salvagewallet->setEnabled(false); connect(ui->btn_rescan, SIGNAL(clicked()), this, SLOT(walletRescan())); connect(ui->btn_zapwallettxes1, SIGNAL(clicked()), this, SLOT(walletZaptxes1())); connect(ui->btn_zapwallettxes2, SIGNAL(clicked()), this, SLOT(walletZaptxes2())); connect(ui->btn_upgradewallet, SIGNAL(clicked()), this, SLOT(walletUpgrade())); connect(ui->btn_reindex, SIGNAL(clicked()), this, SLOT(walletReindex())); // set library version labels #ifdef ENABLE_WALLET ui->berkeleyDBVersion->setText(DbEnv::version(0, 0, 0)); std::string walletPath = GetDataDir().string(); walletPath += QDir::separator().toLatin1() + GetArg("-wallet", "wallet.dat"); ui->wallet_path->setText(QString::fromStdString(walletPath)); #else ui->label_berkeleyDBVersion->hide(); ui->berkeleyDBVersion->hide(); #endif // Register RPC timer interface rpcTimerInterface = new QtRPCTimerInterface(); // avoid accidentally overwriting an existing, non QTThread // based timer interface RPCSetTimerInterfaceIfUnset(rpcTimerInterface); setTrafficGraphRange(INITIAL_TRAFFIC_GRAPH_SETTING); ui->peerHeading->setText(tr("Select a peer to view detailed information.")); QSettings settings; consoleFontSize = settings.value(fontSizeSettingsKey, QFontInfo(QFont()).pointSize()).toInt(); clear(); } RPCConsole::~RPCConsole() { GUIUtil::saveWindowGeometry("nRPCConsoleWindow", this); RPCUnsetTimerInterface(rpcTimerInterface); delete rpcTimerInterface; delete ui; } bool RPCConsole::eventFilter(QObject* obj, QEvent *event) { if(event->type() == QEvent::KeyPress) // Special key handling { QKeyEvent *keyevt = static_cast<QKeyEvent*>(event); int key = keyevt->key(); Qt::KeyboardModifiers mod = keyevt->modifiers(); switch(key) { case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break; case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break; case Qt::Key_PageUp: /* pass paging keys to messages widget */ case Qt::Key_PageDown: if(obj == ui->lineEdit) { QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt)); return true; } break; case Qt::Key_Return: case Qt::Key_Enter: // forward these events to lineEdit if(obj == autoCompleter->popup()) { autoCompleter->popup()->hide(); QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt)); return true; } break; default: // Typing in messages widget brings focus to line edit, and redirects key there // Exclude most combinations and keys that emit no text, except paste shortcuts if(obj == ui->messagesWidget && ( (!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) || ((mod & Qt::ControlModifier) && key == Qt::Key_V) || ((mod & Qt::ShiftModifier) && key == Qt::Key_Insert))) { ui->lineEdit->setFocus(); QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt)); return true; } } } return QWidget::eventFilter(obj, event); } void RPCConsole::setClientModel(ClientModel *model) { clientModel = model; ui->trafficGraph->setClientModel(model); if (model && clientModel->getPeerTableModel() && clientModel->getBanTableModel()) { // Keep up to date with client setNumConnections(model->getNumConnections()); connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int))); setNumBlocks(model->getNumBlocks(), model->getLastBlockDate(), model->getVerificationProgress(NULL), false); connect(model, SIGNAL(numBlocksChanged(int,QDateTime,double,bool)), this, SLOT(setNumBlocks(int,QDateTime,double,bool))); updateNetworkState(); connect(model, SIGNAL(networkActiveChanged(bool)), this, SLOT(setNetworkActive(bool))); connect(model, SIGNAL(masternodeListChanged()), this, SLOT(updateMasternodeCount())); clientModel->refreshMasternodeList(); updateTrafficStats(model->getTotalBytesRecv(), model->getTotalBytesSent()); connect(model, SIGNAL(bytesChanged(quint64,quint64)), this, SLOT(updateTrafficStats(quint64, quint64))); connect(model, SIGNAL(mempoolSizeChanged(long,size_t)), this, SLOT(setMempoolSize(long,size_t))); // set up peer table ui->peerWidget->setModel(model->getPeerTableModel()); ui->peerWidget->verticalHeader()->hide(); ui->peerWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->peerWidget->setSelectionBehavior(QAbstractItemView::SelectRows); ui->peerWidget->setSelectionMode(QAbstractItemView::ExtendedSelection); ui->peerWidget->setContextMenuPolicy(Qt::CustomContextMenu); ui->peerWidget->setColumnWidth(PeerTableModel::Address, ADDRESS_COLUMN_WIDTH); ui->peerWidget->setColumnWidth(PeerTableModel::Subversion, SUBVERSION_COLUMN_WIDTH); ui->peerWidget->setColumnWidth(PeerTableModel::Ping, PING_COLUMN_WIDTH); ui->peerWidget->horizontalHeader()->setStretchLastSection(true); // create peer table context menu actions QAction* disconnectAction = new QAction(tr("&Disconnect"), this); QAction* banAction1h = new QAction(tr("Ban for") + " " + tr("1 &hour"), this); QAction* banAction24h = new QAction(tr("Ban for") + " " + tr("1 &day"), this); QAction* banAction7d = new QAction(tr("Ban for") + " " + tr("1 &week"), this); QAction* banAction365d = new QAction(tr("Ban for") + " " + tr("1 &year"), this); // create peer table context menu peersTableContextMenu = new QMenu(this); peersTableContextMenu->addAction(disconnectAction); peersTableContextMenu->addAction(banAction1h); peersTableContextMenu->addAction(banAction24h); peersTableContextMenu->addAction(banAction7d); peersTableContextMenu->addAction(banAction365d); // Add a signal mapping to allow dynamic context menu arguments. // We need to use int (instead of int64_t), because signal mapper only supports // int or objects, which is okay because max bantime (1 year) is < int_max. QSignalMapper* signalMapper = new QSignalMapper(this); signalMapper->setMapping(banAction1h, 60*60); signalMapper->setMapping(banAction24h, 60*60*24); signalMapper->setMapping(banAction7d, 60*60*24*7); signalMapper->setMapping(banAction365d, 60*60*24*365); connect(banAction1h, SIGNAL(triggered()), signalMapper, SLOT(map())); connect(banAction24h, SIGNAL(triggered()), signalMapper, SLOT(map())); connect(banAction7d, SIGNAL(triggered()), signalMapper, SLOT(map())); connect(banAction365d, SIGNAL(triggered()), signalMapper, SLOT(map())); connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(banSelectedNode(int))); // peer table context menu signals connect(ui->peerWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showPeersTableContextMenu(const QPoint&))); connect(disconnectAction, SIGNAL(triggered()), this, SLOT(disconnectSelectedNode())); // peer table signal handling - update peer details when selecting new node connect(ui->peerWidget->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), this, SLOT(peerSelected(const QItemSelection &, const QItemSelection &))); // peer table signal handling - update peer details when new nodes are added to the model connect(model->getPeerTableModel(), SIGNAL(layoutChanged()), this, SLOT(peerLayoutChanged())); // peer table signal handling - cache selected node ids connect(model->getPeerTableModel(), SIGNAL(layoutAboutToBeChanged()), this, SLOT(peerLayoutAboutToChange())); // set up ban table ui->banlistWidget->setModel(model->getBanTableModel()); ui->banlistWidget->verticalHeader()->hide(); ui->banlistWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->banlistWidget->setSelectionBehavior(QAbstractItemView::SelectRows); ui->banlistWidget->setSelectionMode(QAbstractItemView::SingleSelection); ui->banlistWidget->setContextMenuPolicy(Qt::CustomContextMenu); ui->banlistWidget->setColumnWidth(BanTableModel::Address, BANSUBNET_COLUMN_WIDTH); ui->banlistWidget->setColumnWidth(BanTableModel::Bantime, BANTIME_COLUMN_WIDTH); ui->banlistWidget->horizontalHeader()->setStretchLastSection(true); // create ban table context menu action QAction* unbanAction = new QAction(tr("&Unban"), this); // create ban table context menu banTableContextMenu = new QMenu(this); banTableContextMenu->addAction(unbanAction); // ban table context menu signals connect(ui->banlistWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showBanTableContextMenu(const QPoint&))); connect(unbanAction, SIGNAL(triggered()), this, SLOT(unbanSelectedNode())); // ban table signal handling - clear peer details when clicking a peer in the ban table connect(ui->banlistWidget, SIGNAL(clicked(const QModelIndex&)), this, SLOT(clearSelectedNode())); // ban table signal handling - ensure ban table is shown or hidden (if empty) connect(model->getBanTableModel(), SIGNAL(layoutChanged()), this, SLOT(showOrHideBanTableIfRequired())); showOrHideBanTableIfRequired(); // Provide initial values ui->clientVersion->setText(model->formatFullVersion()); ui->clientUserAgent->setText(model->formatSubVersion()); ui->dataDir->setText(model->dataDir()); ui->startupTime->setText(model->formatClientStartupTime()); ui->networkName->setText(QString::fromStdString(Params().NetworkIDString())); //Setup autocomplete and attach it QStringList wordList; std::vector<std::string> commandList = tableRPC.listCommands(); for (size_t i = 0; i < commandList.size(); ++i) { wordList << commandList[i].c_str(); } autoCompleter = new QCompleter(wordList, this); ui->lineEdit->setCompleter(autoCompleter); autoCompleter->popup()->installEventFilter(this); // Start thread to execute RPC commands. startExecutor(); } if (!model) { // Client model is being set to 0, this means shutdown() is about to be called. // Make sure we clean up the executor thread Q_EMIT stopExecutor(); thread.wait(); } } static QString categoryClass(int category) { switch(category) { case RPCConsole::CMD_REQUEST: return "cmd-request"; break; case RPCConsole::CMD_REPLY: return "cmd-reply"; break; case RPCConsole::CMD_ERROR: return "cmd-error"; break; default: return "misc"; } } void RPCConsole::fontBigger() { setFontSize(consoleFontSize+1); } void RPCConsole::fontSmaller() { setFontSize(consoleFontSize-1); } void RPCConsole::setFontSize(int newSize) { QSettings settings; //don't allow a insane font size if (newSize < FONT_RANGE.width() || newSize > FONT_RANGE.height()) return; // temp. store the console content QString str = ui->messagesWidget->toHtml(); // replace font tags size in current content str.replace(QString("font-size:%1pt").arg(consoleFontSize), QString("font-size:%1pt").arg(newSize)); // store the new font size consoleFontSize = newSize; settings.setValue(fontSizeSettingsKey, consoleFontSize); // clear console (reset icon sizes, default stylesheet) and re-add the content float oldPosFactor = 1.0 / ui->messagesWidget->verticalScrollBar()->maximum() * ui->messagesWidget->verticalScrollBar()->value(); clear(false); ui->messagesWidget->setHtml(str); ui->messagesWidget->verticalScrollBar()->setValue(oldPosFactor * ui->messagesWidget->verticalScrollBar()->maximum()); } /** Restart wallet with "-salvagewallet" */ void RPCConsole::walletSalvage() { buildParameterlist(SALVAGEWALLET); } /** Restart wallet with "-rescan" */ void RPCConsole::walletRescan() { buildParameterlist(RESCAN); } /** Restart wallet with "-zapwallettxes=1" */ void RPCConsole::walletZaptxes1() { buildParameterlist(ZAPTXES1); } /** Restart wallet with "-zapwallettxes=2" */ void RPCConsole::walletZaptxes2() { buildParameterlist(ZAPTXES2); } /** Restart wallet with "-upgradewallet" */ void RPCConsole::walletUpgrade() { buildParameterlist(UPGRADEWALLET); } /** Restart wallet with "-reindex" */ void RPCConsole::walletReindex() { buildParameterlist(REINDEX); } /** Build command-line parameter list for restart */ void RPCConsole::buildParameterlist(QString arg) { // Get command-line arguments and remove the application name QStringList args = QApplication::arguments(); args.removeFirst(); // Remove existing repair-options args.removeAll(SALVAGEWALLET); args.removeAll(RESCAN); args.removeAll(ZAPTXES1); args.removeAll(ZAPTXES2); args.removeAll(UPGRADEWALLET); args.removeAll(REINDEX); // Append repair parameter to command line. args.append(arg); // Send command-line arguments to BitcoinGUI::handleRestart() Q_EMIT handleRestart(args); } void RPCConsole::clear(bool clearHistory) { ui->messagesWidget->clear(); if(clearHistory) { history.clear(); historyPtr = 0; } ui->lineEdit->clear(); ui->lineEdit->setFocus(); // Add smoothly scaled icon images. // (when using width/height on an img, Qt uses nearest instead of linear interpolation) QString iconPath = ":/icons/" + GUIUtil::getThemeName() + "/"; QString iconName = ""; for(int i=0; ICON_MAPPING[i].url; ++i) { iconName = ICON_MAPPING[i].source; ui->messagesWidget->document()->addResource( QTextDocument::ImageResource, QUrl(ICON_MAPPING[i].url), QImage(iconPath + iconName).scaled(QSize(consoleFontSize*2, consoleFontSize*2), Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); } // Set default style sheet QFontInfo fixedFontInfo(GUIUtil::fixedPitchFont()); ui->messagesWidget->document()->setDefaultStyleSheet( QString( "table { }" "td.time { color: #808080; font-size: %2; padding-top: 3px; } " "td.message { font-family: %1; font-size: %2; white-space:pre-wrap; } " "td.cmd-request { color: #006060; } " "td.cmd-error { color: red; } " ".secwarning { color: red; }" "b { color: #006060; } " ).arg(fixedFontInfo.family(), QString("%1pt").arg(consoleFontSize)) ); message(CMD_REPLY, (tr("Welcome to the %1 RPC console.").arg(tr(PACKAGE_NAME)) + "<br>" + tr("Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.") + "<br>" + tr("Type <b>help</b> for an overview of available commands.")) + "<br><span class=\"secwarning\">" + tr("WARNING: Scammers have been active, telling users to type commands here, stealing their wallet contents. Do not use this console without fully understanding the ramification of a command.") + "</span>", true); } void RPCConsole::keyPressEvent(QKeyEvent *event) { if(windowType() != Qt::Widget && event->key() == Qt::Key_Escape) { close(); } } void RPCConsole::message(int category, const QString &message, bool html) { QTime time = QTime::currentTime(); QString timeString = time.toString(); QString out; out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>"; out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>"; out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">"; if(html) out += message; else out += GUIUtil::HtmlEscape(message, false); out += "</td></tr></table>"; ui->messagesWidget->append(out); } void RPCConsole::updateNetworkState() { QString connections = QString::number(clientModel->getNumConnections()) + " ("; connections += tr("In:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_IN)) + " / "; connections += tr("Out:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_OUT)) + ")"; if(!clientModel->getNetworkActive()) { connections += " (" + tr("Network activity disabled") + ")"; } ui->numberOfConnections->setText(connections); } void RPCConsole::setNumConnections(int count) { if (!clientModel) return; updateNetworkState(); } void RPCConsole::setNetworkActive(bool networkActive) { updateNetworkState(); } void RPCConsole::setNumBlocks(int count, const QDateTime& blockDate, double nVerificationProgress, bool headers) { if (!headers) { ui->numberOfBlocks->setText(QString::number(count)); ui->lastBlockTime->setText(blockDate.toString()); } } void RPCConsole::updateMasternodeCount() { if (!clientModel) { return; } auto mnList = clientModel->getMasternodeList(); QString strMasternodeCount = tr("Total: %1 (Enabled: %2)") .arg(QString::number(mnList.GetAllMNsCount())) .arg(QString::number(mnList.GetValidMNsCount())); ui->masternodeCount->setText(strMasternodeCount); } void RPCConsole::setMempoolSize(long numberOfTxs, size_t dynUsage) { ui->mempoolNumberTxs->setText(QString::number(numberOfTxs)); if (dynUsage < 1000000) ui->mempoolSize->setText(QString::number(dynUsage/1000.0, 'f', 2) + " KB"); else ui->mempoolSize->setText(QString::number(dynUsage/1000000.0, 'f', 2) + " MB"); } void RPCConsole::on_lineEdit_returnPressed() { QString cmd = ui->lineEdit->text(); if(!cmd.isEmpty()) { std::string strFilteredCmd; try { std::string dummy; if (!RPCParseCommandLine(dummy, cmd.toStdString(), false, &strFilteredCmd)) { // Failed to parse command, so we cannot even filter it for the history throw std::runtime_error("Invalid command line"); } } catch (const std::exception& e) { QMessageBox::critical(this, "Error", QString("Error: ") + QString::fromStdString(e.what())); return; } ui->lineEdit->clear(); cmdBeforeBrowsing = QString(); message(CMD_REQUEST, cmd); Q_EMIT cmdRequest(cmd); cmd = QString::fromStdString(strFilteredCmd); // Remove command, if already in history history.removeOne(cmd); // Append command to history history.append(cmd); // Enforce maximum history size while(history.size() > CONSOLE_HISTORY) history.removeFirst(); // Set pointer to end of history historyPtr = history.size(); // Scroll console view to end scrollToEnd(); } } void RPCConsole::browseHistory(int offset) { // store current text when start browsing through the history if (historyPtr == history.size()) { cmdBeforeBrowsing = ui->lineEdit->text(); } historyPtr += offset; if(historyPtr < 0) historyPtr = 0; if(historyPtr > history.size()) historyPtr = history.size(); QString cmd; if(historyPtr < history.size()) cmd = history.at(historyPtr); else if (!cmdBeforeBrowsing.isNull()) { cmd = cmdBeforeBrowsing; } ui->lineEdit->setText(cmd); } void RPCConsole::startExecutor() { RPCExecutor *executor = new RPCExecutor(); executor->moveToThread(&thread); // Replies from executor object must go to this object connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString))); // Requests from this object must go to executor connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString))); // On stopExecutor signal // - quit the Qt event loop in the execution thread connect(this, SIGNAL(stopExecutor()), &thread, SLOT(quit())); // - queue executor for deletion (in execution thread) connect(&thread, SIGNAL(finished()), executor, SLOT(deleteLater()), Qt::DirectConnection); // Default implementation of QThread::run() simply spins up an event loop in the thread, // which is what we want. thread.start(); } void RPCConsole::on_tabWidget_currentChanged(int index) { if (ui->tabWidget->widget(index) == ui->tab_console) ui->lineEdit->setFocus(); else if (ui->tabWidget->widget(index) != ui->tab_peers) clearSelectedNode(); } void RPCConsole::on_openDebugLogfileButton_clicked() { GUIUtil::openDebugLogfile(); } void RPCConsole::scrollToEnd() { QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar(); scrollbar->setValue(scrollbar->maximum()); } void RPCConsole::on_sldGraphRange_valueChanged(int value) { setTrafficGraphRange(static_cast<TrafficGraphData::GraphRange>(value)); } QString RPCConsole::FormatBytes(quint64 bytes) { if(bytes < 1024) return QString(tr("%1 B")).arg(bytes); if(bytes < 1024 * 1024) return QString(tr("%1 KB")).arg(bytes / 1024); if(bytes < 1024 * 1024 * 1024) return QString(tr("%1 MB")).arg(bytes / 1024 / 1024); return QString(tr("%1 GB")).arg(bytes / 1024 / 1024 / 1024); } void RPCConsole::setTrafficGraphRange(TrafficGraphData::GraphRange range) { ui->trafficGraph->setGraphRangeMins(range); ui->lblGraphRange->setText(GUIUtil::formatDurationStr(TrafficGraphData::RangeMinutes[range] * 60)); } void RPCConsole::updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut) { ui->lblBytesIn->setText(FormatBytes(totalBytesIn)); ui->lblBytesOut->setText(FormatBytes(totalBytesOut)); } void RPCConsole::peerSelected(const QItemSelection &selected, const QItemSelection &deselected) { Q_UNUSED(deselected); if (!clientModel || !clientModel->getPeerTableModel() || selected.indexes().isEmpty()) return; const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(selected.indexes().first().row()); if (stats) updateNodeDetail(stats); } void RPCConsole::peerLayoutAboutToChange() { QModelIndexList selected = ui->peerWidget->selectionModel()->selectedIndexes(); cachedNodeids.clear(); for(int i = 0; i < selected.size(); i++) { const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(selected.at(i).row()); cachedNodeids.append(stats->nodeStats.nodeid); } } void RPCConsole::peerLayoutChanged() { if (!clientModel || !clientModel->getPeerTableModel()) return; const CNodeCombinedStats *stats = NULL; bool fUnselect = false; bool fReselect = false; if (cachedNodeids.empty()) // no node selected yet return; // find the currently selected row int selectedRow = -1; QModelIndexList selectedModelIndex = ui->peerWidget->selectionModel()->selectedIndexes(); if (!selectedModelIndex.isEmpty()) { selectedRow = selectedModelIndex.first().row(); } // check if our detail node has a row in the table (it may not necessarily // be at selectedRow since its position can change after a layout change) int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeids.first()); if (detailNodeRow < 0) { // detail node disappeared from table (node disconnected) fUnselect = true; } else { if (detailNodeRow != selectedRow) { // detail node moved position fUnselect = true; fReselect = true; } // get fresh stats on the detail node. stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow); } if (fUnselect && selectedRow >= 0) { clearSelectedNode(); } if (fReselect) { for(int i = 0; i < cachedNodeids.size(); i++) { ui->peerWidget->selectRow(clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeids.at(i))); } } if (stats) updateNodeDetail(stats); } void RPCConsole::updateNodeDetail(const CNodeCombinedStats *stats) { // update the detail ui with latest node information QString peerAddrDetails(QString::fromStdString(stats->nodeStats.addrName) + " "); peerAddrDetails += tr("(node id: %1)").arg(QString::number(stats->nodeStats.nodeid)); if (!stats->nodeStats.addrLocal.empty()) peerAddrDetails += "<br />" + tr("via %1").arg(QString::fromStdString(stats->nodeStats.addrLocal)); ui->peerHeading->setText(peerAddrDetails); ui->peerServices->setText(GUIUtil::formatServicesStr(stats->nodeStats.nServices)); ui->peerLastSend->setText(stats->nodeStats.nLastSend ? GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nLastSend) : tr("never")); ui->peerLastRecv->setText(stats->nodeStats.nLastRecv ? GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nLastRecv) : tr("never")); ui->peerBytesSent->setText(FormatBytes(stats->nodeStats.nSendBytes)); ui->peerBytesRecv->setText(FormatBytes(stats->nodeStats.nRecvBytes)); ui->peerConnTime->setText(GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nTimeConnected)); ui->peerPingTime->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingTime)); ui->peerPingWait->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingWait)); ui->peerMinPing->setText(GUIUtil::formatPingTime(stats->nodeStats.dMinPing)); ui->timeoffset->setText(GUIUtil::formatTimeOffset(stats->nodeStats.nTimeOffset)); ui->peerVersion->setText(QString("%1").arg(QString::number(stats->nodeStats.nVersion))); ui->peerSubversion->setText(QString::fromStdString(stats->nodeStats.cleanSubVer)); ui->peerDirection->setText(stats->nodeStats.fInbound ? tr("Inbound") : tr("Outbound")); ui->peerHeight->setText(QString("%1").arg(QString::number(stats->nodeStats.nStartingHeight))); ui->peerWhitelisted->setText(stats->nodeStats.fWhitelisted ? tr("Yes") : tr("No")); // This check fails for example if the lock was busy and // nodeStateStats couldn't be fetched. if (stats->fNodeStateStatsAvailable) { // Ban score is init to 0 ui->peerBanScore->setText(QString("%1").arg(stats->nodeStateStats.nMisbehavior)); // Sync height is init to -1 if (stats->nodeStateStats.nSyncHeight > -1) ui->peerSyncHeight->setText(QString("%1").arg(stats->nodeStateStats.nSyncHeight)); else ui->peerSyncHeight->setText(tr("Unknown")); // Common height is init to -1 if (stats->nodeStateStats.nCommonHeight > -1) ui->peerCommonHeight->setText(QString("%1").arg(stats->nodeStateStats.nCommonHeight)); else ui->peerCommonHeight->setText(tr("Unknown")); } ui->detailWidget->show(); } void RPCConsole::resizeEvent(QResizeEvent *event) { QWidget::resizeEvent(event); } void RPCConsole::showEvent(QShowEvent *event) { QWidget::showEvent(event); if (!clientModel || !clientModel->getPeerTableModel()) return; // start PeerTableModel auto refresh clientModel->getPeerTableModel()->startAutoRefresh(); } void RPCConsole::hideEvent(QHideEvent *event) { QWidget::hideEvent(event); if (!clientModel || !clientModel->getPeerTableModel()) return; // stop PeerTableModel auto refresh clientModel->getPeerTableModel()->stopAutoRefresh(); } void RPCConsole::showPeersTableContextMenu(const QPoint& point) { QModelIndex index = ui->peerWidget->indexAt(point); if (index.isValid()) peersTableContextMenu->exec(QCursor::pos()); } void RPCConsole::showBanTableContextMenu(const QPoint& point) { QModelIndex index = ui->banlistWidget->indexAt(point); if (index.isValid()) banTableContextMenu->exec(QCursor::pos()); } void RPCConsole::disconnectSelectedNode() { if(!g_connman) return; // Get selected peer addresses QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->peerWidget, PeerTableModel::NetNodeId); for(int i = 0; i < nodes.count(); i++) { // Get currently selected peer address NodeId id = nodes.at(i).data().toLongLong(); // Find the node, disconnect it and clear the selected node if(g_connman->DisconnectNode(id)) clearSelectedNode(); } } void RPCConsole::banSelectedNode(int bantime) { if (!clientModel || !g_connman) return; // Get selected peer addresses QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->peerWidget, PeerTableModel::NetNodeId); for(int i = 0; i < nodes.count(); i++) { // Get currently selected peer address NodeId id = nodes.at(i).data().toLongLong(); // Get currently selected peer address int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(id); if(detailNodeRow < 0) return; // Find possible nodes, ban it and clear the selected node const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow); if(stats) { g_connman->Ban(stats->nodeStats.addr, BanReasonManuallyAdded, bantime); } } clearSelectedNode(); clientModel->getBanTableModel()->refresh(); } void RPCConsole::unbanSelectedNode() { if (!clientModel) return; // Get selected ban addresses QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->banlistWidget, BanTableModel::Address); for(int i = 0; i < nodes.count(); i++) { // Get currently selected ban address QString strNode = nodes.at(i).data().toString(); CSubNet possibleSubnet; LookupSubNet(strNode.toStdString().c_str(), possibleSubnet); if (possibleSubnet.IsValid() && g_connman) { g_connman->Unban(possibleSubnet); clientModel->getBanTableModel()->refresh(); } } } void RPCConsole::clearSelectedNode() { ui->peerWidget->selectionModel()->clearSelection(); cachedNodeids.clear(); ui->detailWidget->hide(); ui->peerHeading->setText(tr("Select a peer to view detailed information.")); } void RPCConsole::showOrHideBanTableIfRequired() { if (!clientModel) return; bool visible = clientModel->getBanTableModel()->shouldShow(); ui->banlistWidget->setVisible(visible); ui->banHeading->setVisible(visible); } void RPCConsole::setTabFocus(enum TabTypes tabType) { ui->tabWidget->setCurrentIndex(tabType); }
/* * 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. */ /*! * \file auto_scheduler/search_policy/sketch_policy_rules.cc * \brief Rules for generating the sketches, sampling the initial population, and mutating the * population in SketchPolicy. */ #include "sketch_policy_rules.h" #include <set> #include <string> #include <utility> #include <vector> #include "sketch_policy.h" namespace tvm { namespace auto_scheduler { static std::vector<int> auto_unroll_configs_cpu = {0, 16, 64, 512}; static std::vector<int> auto_unroll_configs_gpu = {0, 16, 64, 512, 1024}; /********** Sketch Generation Rule **********/ /********** RuleSkipStage **********/ SketchGenerationRule::ConditionKind RuleSkipStage::MeetCondition(const SketchPolicyNode& policy, const State& state, int stage_id) const { // This rule should be the last rule, always return true to decrease the stage index count return ConditionKind::kApply; } std::vector<std::pair<State, int>> RuleSkipStage::Apply(const SketchPolicyNode& policy, const State& state, int stage_id) const { return {std::make_pair(state, stage_id - 1)}; } /********** RuleAlwaysInline **********/ inline bool ShouldAlwaysBeInlined(const SketchPolicyNode& policy, const State& state, int stage_id) { const SearchTask& task = policy.search_task; const Stage& stage = state->stages[stage_id]; // Check the inline limitation of TE if (stage->op_type == StageKind::kPlaceholder || IsOutputOp(task, state, stage_id) || HasReduceIter(stage)) { return false; } if (IsGPUTask(task)) { // Greedily inline all inlinable ops on gpu return true; } else { // Only always-inline strict-inlinable ops on cpu. // The computation location of other ops will be tuned by InitChangeComputeLocation // and MutateComputeLocation. return IsStrictlyInlineable(task, state, stage_id); } } SketchGenerationRule::ConditionKind RuleAlwaysInline::MeetCondition(const SketchPolicyNode& policy, const State& state, int stage_id) const { return ShouldAlwaysBeInlined(policy, state, stage_id) ? ConditionKind::kApplyAndSkipRest : ConditionKind::kSkip; } std::vector<std::pair<State, int>> RuleAlwaysInline::Apply(const SketchPolicyNode& policy, const State& state, int stage_id) const { State tmp_s = state; tmp_s.compute_inline(stage_id); return {std::make_pair(std::move(tmp_s), stage_id - 1)}; } /********** RuleMultiLevelTiling **********/ SketchGenerationRule::ConditionKind RuleMultiLevelTiling::MeetCondition( const SketchPolicyNode& policy, const State& state, int stage_id) const { return NeedsMultilevelTiling(policy.search_task, state, stage_id) ? ConditionKind::kApplyAndSkipRest : ConditionKind::kSkip; } std::vector<std::pair<State, int>> RuleMultiLevelTiling::Apply(const SketchPolicyNode& policy, const State& state, int stage_id) const { const std::string& multi_level_tiling_structure = IsGPUTask(policy.search_task) ? GetStringParam(policy.params, SketchParamKey::MultiLevelTiling::gpu_structure) : GetStringParam(policy.params, SketchParamKey::MultiLevelTiling::cpu_structure); State tmp_s = DoMultiLevelTiling(state, stage_id, multi_level_tiling_structure); return {std::make_pair(std::move(tmp_s), stage_id - 1)}; } /********** RuleMultiLevelTilingWithFusion **********/ SketchGenerationRule::ConditionKind RuleMultiLevelTilingWithFusion::MeetCondition( const SketchPolicyNode& policy, const State& state, int stage_id) const { if (NeedsMultilevelTiling(policy.search_task, state, stage_id) && HasSingleElementwiseMatchedConsumer(policy.search_task, state, stage_id)) { // Always do fusion for stage with cache_write or is in GPU policy return HasCacheWriteStage(state, stage_id) || IsGPUTask(policy.search_task) ? ConditionKind::kApplyAndSkipRest : ConditionKind::kApply; } return ConditionKind::kSkip; } std::vector<std::pair<State, int>> RuleMultiLevelTilingWithFusion::Apply( const SketchPolicyNode& policy, const State& state, int stage_id) const { int target_stage_id; ICHECK( HasSingleElementwiseMatchedConsumer(policy.search_task, state, stage_id, &target_stage_id)); const std::string& multi_level_tiling_structure = IsGPUTask(policy.search_task) ? GetStringParam(policy.params, SketchParamKey::MultiLevelTiling::gpu_structure) : GetStringParam(policy.params, SketchParamKey::MultiLevelTiling::cpu_structure); std::vector<int> spatial_split_step_ids; State base_state = DoMultiLevelTiling(state, stage_id, multi_level_tiling_structure, &spatial_split_step_ids); std::vector<std::pair<State, int>> ret; std::vector<int> follow_tiling_levels = IsGPUTask(policy.search_task) ? std::vector<int>{3} : std::vector<int>{1, 2}; for (int level : follow_tiling_levels) { if (tolower(multi_level_tiling_structure[level - 1]) != 's') { continue; } State tmp_s = base_state; tmp_s = FollowTiling(tmp_s, target_stage_id, spatial_split_step_ids, level); const Iterator& target_iter = tmp_s->stages[target_stage_id]->iters[level * spatial_split_step_ids.size() - 1]; tmp_s.compute_at(stage_id, target_stage_id, target_iter); ret.emplace_back(std::move(tmp_s), stage_id - 1); } return ret; } /********** RuleAddCacheRead **********/ SketchGenerationRule::ConditionKind RuleAddCacheRead::MeetCondition(const SketchPolicyNode& policy, const State& state, int stage_id) const { const SearchTask& task = policy.search_task; // Don't cache_read a stage if it has multiple consumers const std::set<int>& consumers = GetConsumers(task, state, stage_id); // Don't cache_read a stage if its consumer does not need multi-level tiling int target_stage_id = *consumers.begin(); if (!NeedsMultilevelTiling(task, state, target_stage_id)) { return ConditionKind::kSkip; } // Don't cache_read a stage if its consumer does cross-thread reduction if (HasCrossThreadReduction(state, target_stage_id)) { return ConditionKind::kSkip; } // Only direct producers can be cache read const std::set<int>& producers = GetDirectProducers(task, state, target_stage_id); if (producers.find(stage_id) == producers.end()) { return ConditionKind::kSkip; } return ConditionKind::kApplyAndSkipRest; } std::vector<std::pair<State, int>> RuleAddCacheRead::Apply(const SketchPolicyNode& policy, const State& state, int stage_id) const { const SearchTask& task = policy.search_task; const std::set<int>& consumers = GetConsumers(task, state, stage_id); State tmp_s = state; int target_stage_id_offset = 0; for (int orig_target_stage_id : consumers) { int target_stage_id = orig_target_stage_id + target_stage_id_offset; // Cache read add shared memory int added_stage_id = tmp_s.cache_read(stage_id, "shared", {target_stage_id}, task->compute_dag); target_stage_id_offset++; target_stage_id++; const auto& share_read_pos = GetLastReduceIteratorInOutermostReduceTile(tmp_s->stages[target_stage_id]); tmp_s.compute_at(added_stage_id, target_stage_id, share_read_pos); } return {std::make_pair(tmp_s, stage_id)}; } /********** RuleAddCacheWrite **********/ SketchGenerationRule::ConditionKind RuleAddCacheWrite::MeetCondition(const SketchPolicyNode& policy, const State& state, int stage_id) const { // Add cache write if a stage needs multi-level tiling, but does not have a element-wise // matched consumer if (NeedsMultilevelTiling(policy.search_task, state, stage_id) && !HasSingleElementwiseMatchedConsumer(policy.search_task, state, stage_id)) { // An apply and skip rule will be handled in RuleMultiLevelTilingWithFusion return IsGPUTask(policy.search_task) ? ConditionKind::kApplyAndSkipRest : ConditionKind::kApply; } return ConditionKind::kSkip; } std::vector<std::pair<State, int>> RuleAddCacheWrite::Apply(const SketchPolicyNode& policy, const State& state, int stage_id) const { State tmp_s = state; tmp_s.cache_write(stage_id, "local", policy.search_task->compute_dag); return {std::make_pair(std::move(tmp_s), stage_id)}; } /********** RuleAddRfactor **********/ SketchGenerationRule::ConditionKind RuleAddRfactor::MeetCondition(const SketchPolicyNode& policy, const State& state, int stage_id) const { return (NeedsRfactor(policy.search_task, state, stage_id) && !HasCacheWriteStage(state, stage_id)) ? ConditionKind::kApply : ConditionKind::kSkip; } std::vector<std::pair<State, int>> RuleAddRfactor::Apply(const SketchPolicyNode& policy, const State& state, int stage_id) const { // Fuse all reduction iters Array<Iterator> space_iters, reduce_iters; Iterator fused_reduce_iter; State base_state = FuseAllReductionIterators(state, stage_id, &fused_reduce_iter, &space_iters, &reduce_iters); // TODO(merrymercy): We can do more analysis here to generate less and more efficient sketches. // In some cases, we only need rfactor for more parallel // In some cases, we only need rfactor for vectorization. // Now we will generate two versions and let the search figure out the bette one. // Split reduction iters const auto& split_res = base_state.split(stage_id, fused_reduce_iter, {Integer(1)}); int factor_axis_id = static_cast<int>(space_iters.size()); std::vector<std::pair<State, int>> ret; for (const auto& split_iter : split_res) { State tmp_s = base_state; int rstage_id = tmp_s.rfactor(stage_id, split_iter, factor_axis_id, policy.search_task->compute_dag); // reorder the space iterator to innermost for vectorization if (split_iter == split_res[1]) { Array<Iterator> new_order; for (size_t i = 0; i < tmp_s->stages[rstage_id]->iters.size(); ++i) { if (i != space_iters.size()) { new_order.push_back(tmp_s->stages[rstage_id]->iters[i]); } } new_order.push_back(tmp_s->stages[rstage_id]->iters[space_iters.size()]); tmp_s.reorder(rstage_id, new_order); } ret.emplace_back(std::move(tmp_s), rstage_id - 1); } return ret; } /********** RuleSimplifyComputeWithConstTensor **********/ SketchGenerationRule::ConditionKind RuleSimplifyComputeWithConstTensor::MeetCondition( const SketchPolicyNode& policy, const State& state, int stage_id) const { return state->stages[stage_id]->op->attrs.count(SearchPolicyKey::simplify_const_tensor_indices) ? ConditionKind::kApplyAndSkipRest : ConditionKind::kSkip; } std::vector<std::pair<State, int>> RuleSimplifyComputeWithConstTensor::Apply( const SketchPolicyNode& policy, const State& state, int stage_id) const { std::set<std::string> const_tensor_indices = GetIterNameSetParam( state->stages[stage_id]->op->attrs, SearchPolicyKey::simplify_const_tensor_indices); State tmp_s = state; Array<Array<Iterator>> tiled_outer_iters; Array<Iterator> unrolled_inner_iters; // Currently set to 2 size_t tile_level = 2; for (const auto& iter : state->stages[stage_id]->iters) { if (const_tensor_indices.count(iter->name)) { // unroll indices of const tensors unrolled_inner_iters.push_back(tmp_s.unroll(stage_id, iter)); } else { // tile other space indices ICHECK(iter->iter_kind == IteratorKind::kSpatial); tiled_outer_iters.push_back( tmp_s.split(stage_id, iter, Array<Optional<Integer>>(tile_level - 1, NullOpt))); } } // reorder them Array<Iterator> new_order; for (size_t i = 0; i < tile_level; ++i) { for (size_t j = 0; j < tiled_outer_iters.size(); ++j) { new_order.push_back(tiled_outer_iters[j][i]); } } new_order.insert(new_order.end(), unrolled_inner_iters.begin(), unrolled_inner_iters.end()); tmp_s.reorder(stage_id, new_order); return {std::make_pair(tmp_s, stage_id - 1)}; } /********** RuleCrossThreadReduction **********/ SketchGenerationRule::ConditionKind RuleCrossThreadReduction::MeetCondition( const SketchPolicyNode& policy, const State& state, int stage_id) const { ICHECK(IsGPUTask(policy.search_task)); // If it is an intermediate state created by RuleAddCacheWrite, // we just skip it. if (HasCacheWriteStage(state, stage_id)) { return ConditionKind::kSkip; } const auto& op = state->stages[stage_id]->op; if (op->IsInstance<te::ComputeOpNode>()) { // Compute the product of lengths of all space iters and all reduce iters int cum_space_len, cum_reduce_len; std::tie(cum_space_len, cum_reduce_len) = GetCumulativeSpaceAndReductionLength(state->stages[stage_id]); if (NeedsMultilevelTiling(policy.search_task, state, stage_id)) { // Avoid rfactor if we have enough parallelism on space iters if (cum_space_len > policy.search_task->hardware_params->max_threads_per_block) { return ConditionKind::kSkip; } return cum_space_len < cum_reduce_len ? ConditionKind::kApply : ConditionKind::kSkip; } else if (cum_reduce_len > 1) { // Try rfactor for other reduction operators return cum_reduce_len > policy.search_task->hardware_params->warp_size ? ConditionKind::kApply : ConditionKind::kSkip; } } return ConditionKind::kSkip; } std::vector<std::pair<State, int>> RuleCrossThreadReduction::Apply(const SketchPolicyNode& policy, const State& state, int stage_id) const { const SearchTask& task = policy.search_task; State tmp_s = state; // fuse all reduction iters Array<Iterator> space_iters, reduce_iters; Iterator fused_reduce_iter; tmp_s = FuseAllReductionIterators(tmp_s, stage_id, &fused_reduce_iter, &space_iters, &reduce_iters); // Check the opportunity for kernel fusion bool fusible = false; int target_stage_id = GetSingleConsumerId(policy.search_task, tmp_s, stage_id); int num_common_outer = -1; if (target_stage_id >= 0) { num_common_outer = GetNumCommonOuterIterator(policy.search_task, tmp_s, stage_id, target_stage_id); if (num_common_outer > 0 && !NeedsMultilevelTiling(policy.search_task, state, target_stage_id)) { fusible = true; } } if (fusible) { const Stage& target_stage = state->stages[target_stage_id]; std::vector<int> split_step_ids; GetSplitStepIds(tmp_s, target_stage_id, &split_step_ids); if (split_step_ids.size() == 0) { // If the target stage does not have split step, // it must be a simple stage without reduce iters. // We then should do a split for it. ICHECK(!HasReduceIter(target_stage)); const auto& split_res = tmp_s.split(target_stage_id, target_stage->iters.back(), {Integer(task->hardware_params->warp_size)}); tmp_s.bind(target_stage_id, split_res[1], IteratorAnnotation::kThreadX); split_step_ids.push_back(tmp_s->transform_steps.size() - 2); } ICHECK_EQ(split_step_ids.size(), 1); const Iterator& target_iter = tmp_s->stages[target_stage_id]->iters[num_common_outer - 1]; const auto& split_res = tmp_s.follow_split(stage_id, fused_reduce_iter, split_step_ids[0], 1); tmp_s.bind(stage_id, split_res[1], IteratorAnnotation::kThreadX); tmp_s.compute_at(stage_id, target_stage_id, target_iter); } else { const auto& split_res = tmp_s.split(stage_id, fused_reduce_iter, {Integer(task->hardware_params->warp_size)}); tmp_s.bind(stage_id, split_res[1], IteratorAnnotation::kThreadX); } return {std::make_pair(std::move(tmp_s), stage_id - 1)}; } /********** RuleSpecialComputeLocationGPU **********/ SketchGenerationRule::ConditionKind RuleSpecialComputeLocationGPU::MeetCondition( const SketchPolicyNode& policy, const State& state, int stage_id) const { if (GetProducers(policy.search_task, state, stage_id).empty()) { return ConditionKind::kSkip; } if (!ShouldAlwaysBeInlined(policy, state, stage_id)) { return ConditionKind::kSkip; } const std::set<int>& consumers = GetConsumers(policy.search_task, state, stage_id); if (consumers.size() == 1 && state->stages[*consumers.begin()]->op->attrs.count( SearchPolicyKey::simplify_const_tensor_indices)) { return ConditionKind::kApplyAndSkipRest; } return ConditionKind::kSkip; } std::vector<std::pair<State, int>> RuleSpecialComputeLocationGPU::Apply( const SketchPolicyNode& policy, const State& state, int stage_id) const { State tmp_s = state; const std::set<int>& consumers = GetConsumers(policy.search_task, state, stage_id); ICHECK_EQ(consumers.size(), 1); // Get the last outer space iterator that is not unrolled. const Stage& target_stage = state->stages[*consumers.begin()]; for (size_t i = 0; i < target_stage->iters.size(); ++i) { if (target_stage->iters[i]->annotation == IteratorAnnotation::kUnroll) { ICHECK_GT(i, 0); tmp_s.compute_at(stage_id, *consumers.begin(), target_stage->iters[i - 1]); break; } } return {std::make_pair(std::move(tmp_s), stage_id - 1)}; } /********** Init Population **********/ PopulationGenerationRule::ResultKind InitFillTileSize::Apply(SketchPolicyNode* policy, State* state, std::mt19937* rand_gen) const { SplitFactorizationMemo split_memo; int max_innermost_split_factor = GetIntParam(policy->params, SketchParamKey::max_innermost_split_factor); StateNode* pstate = state->CopyOnWrite(); // Scan the transformation history and randomly fill tiles size for all SplitStep for (size_t step_id = 0; step_id < (*state)->transform_steps.size(); ++step_id) { if (auto ps = (*state)->transform_steps[step_id].as<SplitStepNode>()) { bool all_defined = true; for (const auto& len : ps->lengths) { if (!len) { all_defined = false; break; } } if (all_defined) { continue; } ICHECK(ps->extent); int extent = GetIntImm(ps->extent.value()); const auto& candidate_lens = split_memo.GetFactorizationSchemes(extent, ps->lengths.size(), max_innermost_split_factor); ICHECK(!candidate_lens.empty()); const auto& candidate_lengths = candidate_lens[(*rand_gen)() % candidate_lens.size()]; pstate->transform_steps.Set( step_id, SplitStep(ps->stage_id, ps->iter_id, ps->extent, Array<Optional<Integer>>(candidate_lengths.begin(), candidate_lengths.end()), ps->inner_to_outer)); } } pstate->concrete = true; return ResultKind::kValid; } PopulationGenerationRule::ResultKind InitChangeComputeLocation::Apply( SketchPolicyNode* policy, State* state, std::mt19937* rand_gen) const { if (GetIntParam(policy->params, SketchParamKey::disable_change_compute_location)) { return ResultKind::kValid; } for (int stage_id = static_cast<int>((*state)->stages.size()) - 1; stage_id >= 0; stage_id--) { const Stage& stage = (*state)->stages[stage_id]; // Skip the inlined stages and placeholders if (stage->op_type == StageKind::kPlaceholder || stage->compute_at == ComputeAtKind::kInlined) { continue; } // Skip the tiled stages if (IsTiled(stage) || NeedsMultilevelTiling(policy->search_task, *state, stage_id)) { continue; } std::vector<std::pair<int, int>> candidates = GetComputeLocationCandidates(policy->search_task, *state, stage_id); int choice = (*rand_gen)() % (candidates.size() + 2); if (choice == 0) { if (!HasReduceIter(stage)) { const auto& stage_to_attach_iter = (*state)->attach_map->stage_to_attach_iter; if (stage_to_attach_iter.find(stage_id) != stage_to_attach_iter.end()) { state->compute_inline(stage_id); } } } else if (choice == 1) { state->compute_root(stage_id); } else { choice = choice - 2; const Stage& stage = (*state)->stages[candidates[choice].first]; state->compute_at(stage_id, candidates[choice].first, stage->iters[candidates[choice].second]); } } try { *state = policy->search_task->compute_dag.InferBound(*state); } catch (std::exception& e) { return ResultKind::kInvalid; } return ResultKind::kValid; } PopulationGenerationRule::ResultKind InitParallel::Apply(SketchPolicyNode* policy, State* state, std::mt19937* rand_gen) const { std::function<void(const SketchPolicyNode&, State*, int stage_id, int iter_offset)> annotate_parallel; annotate_parallel = [&annotate_parallel](const SketchPolicyNode& policy, State* state, int stage_id, int iter_offset) { const Stage& stage = (*state)->stages[stage_id]; Array<Iterator> to_fuse; int64_t parallel_degree = 1; // Try to fuse and parallel the outermost n iterators // Stop if we meet reduce iterator or we have enough parallel degree size_t iter_id = iter_offset; for (; iter_id < stage->iters.size(); ++iter_id) { const Iterator& it = stage->iters[iter_id]; if (it->iter_kind == IteratorKind::kReduction || it->annotation != IteratorAnnotation::kNone) { break; } to_fuse.push_back(it); parallel_degree *= GetExtent(it); if (parallel_degree > policy.search_task->hardware_params->num_cores * 16) { break; } if ((*state)->attach_map->iter_to_attached_stages.count(std::make_pair(stage_id, iter_id))) { break; } } if (parallel_degree == 1) { auto res = (*state)->attach_map->iter_to_attached_stages.find(std::make_pair(stage_id, iter_id)); if (res != (*state)->attach_map->iter_to_attached_stages.end()) { for (int attached_stage_id : res->second) { annotate_parallel(policy, state, attached_stage_id, 0); } annotate_parallel(policy, state, stage_id, iter_id + 1); } } if (!to_fuse.empty()) { if (to_fuse.size() == 1) { state->parallel(stage_id, to_fuse[0]); } else { Iterator fused_iter = state->fuse(stage_id, to_fuse); state->parallel(stage_id, fused_iter); } } }; for (size_t stage_id = 0; stage_id < (*state)->stages.size(); ++stage_id) { const Stage& stage = (*state)->stages[stage_id]; if (stage->compute_at != ComputeAtKind::kRoot || stage->op_type == StageKind::kPlaceholder) { continue; } annotate_parallel(*policy, state, stage_id, 0); } return ResultKind::kValid; } PopulationGenerationRule::ResultKind InitUnroll::Apply(SketchPolicyNode* policy, State* state, std::mt19937* rand_gen) const { std::vector<int>& auto_unroll_configs = IsGPUTask(policy->search_task) ? auto_unroll_configs_gpu : auto_unroll_configs_cpu; for (size_t stage_id = 0; stage_id < (*state)->stages.size(); ++stage_id) { const Stage& stage = (*state)->stages[stage_id]; // Skip the inlined stage and placeholder stage if (stage->compute_at == ComputeAtKind::kInlined || stage->op_type == StageKind::kPlaceholder) { continue; } // Handle always_unroll_inner attr if (stage->op->attrs.count(SearchPolicyKey::always_unroll_inner)) { const auto& to_unroll_name_set = GetIterNameSetParam(stage->op->attrs, SearchPolicyKey::always_unroll_inner); // Unroll the space iterators and reduce iterators listed in the attrs in the innermost // tile std::set<std::string> visited_names; for (int n = static_cast<int>(stage->iters.size()) - 1; n >= 0; n--) { const Iterator& it = stage->iters[n]; // If we meet two iterators that come from a same original iterator, // then we are out of the innermost tile size_t size_before = visited_names.size(); ExtractOriginalIterators(it->name, &visited_names); if (size_before == visited_names.size()) { break; } std::set<std::string> name; ExtractOriginalIterators(it->name, &name); if (name.size() == 1 && to_unroll_name_set.count(*name.begin())) { if (it->annotation == IteratorAnnotation::kNone) { state->unroll(stage_id, it); } } } } if (HasReduceIter(stage)) { // Use auto unroll for multi level tiled stage int value = auto_unroll_configs[(*rand_gen)() % auto_unroll_configs.size()]; state->pragma(stage_id, (*state)->stages[stage_id]->iters[0], std::string("auto_unroll_max_step") + "$" + std::to_string(value)); } } return ResultKind::kValid; } PopulationGenerationRule::ResultKind InitVectorization::Apply(SketchPolicyNode* policy, State* state, std::mt19937* rand_gen) const { for (size_t stage_id = 0; stage_id < (*state)->stages.size(); ++stage_id) { const Stage& stage = (*state)->stages[stage_id]; // Skip the inlined stage and placeholder stage if (stage->compute_at == ComputeAtKind::kInlined || stage->op_type == StageKind::kPlaceholder) { continue; } // Try to fuse and vectorize the space iterators in the inner most tile int64_t cum_length_prod = 1; int num_fusible = 0; while (num_fusible < static_cast<int>(stage->iters.size())) { int iter_id = static_cast<int>(stage->iters.size()) - 1 - num_fusible; // Stop if this iterator has been a compute at attach point if ((*state)->attach_map->iter_to_attached_stages.count(std::make_pair(stage_id, iter_id))) { break; } const Iterator& it = stage->iters[iter_id]; // Stop if we meet a reduce iterator or annotated iterator if (it->iter_kind == IteratorKind::kReduction || it->annotation != IteratorAnnotation::kNone) { break; } // Stop if the memory access is not continuous (vectorizable) // Note: The check is too hard, so we use heuristic here if (IsTiled(stage) && num_fusible != 0) { // If the stage is tiled, then the memory access must not be continuous // for the innermost two iterators break; } cum_length_prod *= GetExtent(it); if (cum_length_prod > GetIntParam(policy->params, SketchParamKey::max_vectorize_size)) { break; } num_fusible++; } if (num_fusible > 1) { // Select a random range to fuse num_fusible = 1 + (*rand_gen)() % (num_fusible - 1); } if (num_fusible == 1) { state->vectorize(stage_id, stage->iters.back()); } else if (num_fusible > 1) { Array<Iterator> to_fuse(stage->iters.end() + (-num_fusible), stage->iters.end()); state->vectorize(stage_id, state->fuse(stage_id, to_fuse)); } } return ResultKind::kValid; } PopulationGenerationRule::ResultKind InitThreadBind::Apply(SketchPolicyNode* policy, State* state, std::mt19937* rand_gen) const { // Collect all stages that are roots of stages that perform multi-level tiling. std::set<int> multi_level_tiling_root_set; for (size_t stage_id = 0; stage_id < (*state)->stages.size(); ++stage_id) { if (NeedsMultilevelTiling(policy->search_task, *state, stage_id)) { const Stage& stage = (*state)->stages[stage_id]; if (stage->compute_at == ComputeAtKind::kInlined) { continue; } else if (stage->compute_at != ComputeAtKind::kIter) { // This stage is not multi-level tiled, // so it must be produced by RuleCrossThreadReduction. ICHECK(HasCrossThreadReduction(*state, stage_id)); } else { const auto res = (*state)->attach_map->stage_to_attach_iter.find(stage_id); ICHECK(res != (*state)->attach_map->stage_to_attach_iter.end()); multi_level_tiling_root_set.insert(res->second.first); } } } *state = policy->search_task->compute_dag.InferBound(*state); for (int stage_id = (*state)->stages.size() - 1; stage_id >= 0; --stage_id) { const Stage& stage = (*state)->stages[stage_id]; if (stage->compute_at == ComputeAtKind::kInlined || stage->op_type == StageKind::kPlaceholder) { continue; } // Deal with the cross-thread reduction generated by RuleCrossThreadReduction if (HasCrossThreadReduction(*state, stage_id)) { if (stage->compute_at != ComputeAtKind::kRoot) { continue; } Iterator fused_it; *state = std::move(FuseAllOuterSpaceIterators(*state, stage_id, &fused_it)); state->bind(stage_id, fused_it, IteratorAnnotation::kBlockX); continue; } // Skip if this stage has already been annotaed with threadIdx.x if (HasAnnotatedIter(stage, IteratorAnnotation::kThreadX)) { continue; } if (stage->compute_at == ComputeAtKind::kRoot) { // This stage has not been tiled, but in GPU schedule, we must tile the root stage // to do thread binding if (!multi_level_tiling_root_set.count(stage_id)) { Iterator fused_it; *state = FuseAllOuterSpaceIterators(*state, stage_id, &fused_it); if (GetExtent(fused_it) <= policy->search_task->hardware_params->warp_size) { state->bind(stage_id, fused_it, IteratorAnnotation::kThreadX); } else { // Set threadIdx.x = default_warp_size by default. // The later EvolutionarySearch will try more possibility const auto& split_its = state->split( stage_id, fused_it, {Integer(policy->search_task->hardware_params->warp_size)}); state->bind(stage_id, split_its[0], IteratorAnnotation::kBlockX); state->bind(stage_id, split_its[1], IteratorAnnotation::kThreadX); } continue; } // Otherwise, this is a tiled root stage, we assume it should be tiled with 3 space level // in the outer iterators. // The remaining part deals with the thread binding for multi-level tiled stages auto pop = stage->op.as<te::ComputeOpNode>(); std::vector<Iterator> to_fuse; int total_space_extent = 1; for (const auto& i : pop->root_iter_vars()) { ICHECK(i->dom.defined()); const auto& pint = i->dom->extent.as<IntImmNode>(); ICHECK(pint); total_space_extent *= pint->value; } bool check_min_thread_extent = true; // If the total space extent is too small, disable the check of minimal thread extent if (total_space_extent <= policy->search_task->hardware_params->warp_size * 2) { check_min_thread_extent = false; } // Fuse the outermost space tile as blockIdx for (size_t i = 0; i < pop->axis.size(); i++) { const auto& it = (*state)->stages[stage_id]->iters[i]; // There may be some iterators that are marked with no split, stop if reaches next // tiling level if (!StrEndsWith(it->name, ".0")) { break; } to_fuse.push_back(it); } const auto& blockidx_it = state->fuse(stage_id, to_fuse); state->bind(stage_id, blockidx_it, IteratorAnnotation::kBlockX); // Fuse the second outermost space tile as vthread to_fuse.clear(); for (size_t i = 1; i < pop->axis.size() + 1; i++) { const auto& it = (*state)->stages[stage_id]->iters[i]; // There may be some iterators that are marked with no split, stop if reaches next // tiling level if (!StrEndsWith(it->name, ".1")) { break; } to_fuse.push_back((*state)->stages[stage_id]->iters[i]); } const auto& vthread_it = state->fuse(stage_id, to_fuse); if (GetExtent(vthread_it) > policy->search_task->hardware_params->max_vthread_extent) { return ResultKind::kInvalid; } state->bind(stage_id, vthread_it, IteratorAnnotation::kVThread); // Fuse the third outermost space tile as threadIdx to_fuse.clear(); for (size_t i = 2; i < pop->axis.size() + 2; i++) { const auto& it = (*state)->stages[stage_id]->iters[i]; // There may be some iterators that are marked with no split, stop if reaches next // tiling level if (!StrEndsWith(it->name, ".2")) { break; } to_fuse.push_back((*state)->stages[stage_id]->iters[i]); } const auto& threadidx_it = state->fuse(stage_id, to_fuse); if (check_min_thread_extent && GetExtent(threadidx_it) < policy->search_task->hardware_params->warp_size) { return ResultKind::kInvalid; } state->bind(stage_id, threadidx_it, IteratorAnnotation::kThreadX); } else if (stage->compute_at == ComputeAtKind::kIter && StrEndsWith(stage->op->name, ".shared")) { // Do cooperative fetching for the cache read stage. // Get spatial_split_step_ids from the root stage const auto& it = (*state)->attach_map->stage_to_attach_iter.find(stage_id); ICHECK(it != (*state)->attach_map->stage_to_attach_iter.end()); Array<Integer> spatial_split_step_ids = GetSpatialSplitStepIds(*state, it->second.first); // Fuse all iterators to do cooperative fetching Iterator fused = state->fuse(stage_id, (*state)->stages[stage_id]->iters); // Split out an extra iterator for vectorization // The later EvolutionarySearch will try more possibility const auto& iters0 = state->split(stage_id, fused, {Integer(1)}); state->vectorize(stage_id, iters0[1]); // Follow split to keep a same thread extent with the root stage const auto& iters1 = state->follow_fused_split(stage_id, iters0[0], spatial_split_step_ids, 1, true); state->bind(stage_id, iters1[1], IteratorAnnotation::kThreadX); } } return ResultKind::kValid; } PopulationGenerationRule::ResultKind MutateTileSize::Apply(SketchPolicyNode* policy, State* state, std::mt19937* rand_gen) const { int max_innermost_split_factor = GetIntParam(policy->params, SketchParamKey::max_innermost_split_factor); // Extract all SplitStep std::vector<size_t> split_step_ids; for (size_t i = 0; i < (*state)->transform_steps.size(); ++i) { if (auto ps = (*state)->transform_steps[i].as<SplitStepNode>()) { if (!ps->extent.defined() || !ps->extent.value()->IsInstance<IntImmNode>()) { continue; } auto innermost_factor = ps->lengths.back().value_or(max_innermost_split_factor + 1); if (GetIntImm(innermost_factor) <= max_innermost_split_factor) { split_step_ids.push_back(i); } } } if (split_step_ids.empty()) { // No tile size could be mutated. return ResultKind::kInvalid; } // Select a SplitStep with extent larger than one to mutate. int retry_ct = 0; int64_t extent = 1; int step_id; const SplitStepNode* ps; do { step_id = split_step_ids[(*rand_gen)() % split_step_ids.size()]; ps = (*state)->transform_steps[step_id].as<SplitStepNode>(); ICHECK(ps != nullptr); extent = GetIntImm(ps->extent.value()); retry_ct += 1; } while (retry_ct < static_cast<int>(split_step_ids.size()) << 2 && (extent == 1 || extent == 0)); if (extent <= 1) { // Cannot find a step with extent larger than one. return ResultKind::kInvalid; } // Fetch the current tile sizes. std::vector<int> lengths(ps->lengths.size() + 1, 1); for (int i = 0; i < static_cast<int>(ps->lengths.size()); ++i) { lengths[i + 1] = GetIntImm(ps->lengths[i].value()); } lengths[0] = extent / ElementProduct(lengths); // Random permute the tile size order. std::vector<int> random_perm; RandomPermutation(lengths.size(), &random_perm, rand_gen); // Try to divide a factor from one tile size and multiple it to another. for (size_t i = 0; i < random_perm.size(); ++i) { size_t src_idx = random_perm[i]; int length = lengths[src_idx]; if (length <= 1) { continue; } // Divide one factor from lengths[src_idx] and multiply it to lengths[dst_idx] size_t dst_idx = random_perm[(i + 1) % random_perm.size()]; const std::vector<int>& factors = policy->split_memo.GetFactors(length); ICHECK_GE(factors.size(), 1); int divide_factor; if (dst_idx == lengths.size() - 1) { // Maintain the restriction of hardware_params.max_innermost_split_factor. int max_factor_index = static_cast<int>(factors.size()) - 1; for (; max_factor_index >= 1; max_factor_index--) { if (factors[max_factor_index] * lengths[dst_idx] <= max_innermost_split_factor) { break; } } if (max_factor_index == 0) { // Failed on this dst_idx, try next one. continue; } divide_factor = factors[1 + (*rand_gen)() % (max_factor_index)]; } else { divide_factor = factors[1 + (*rand_gen)() % (factors.size() - 1)]; } // Divide one factor from lengths[src_idx] and multiply it to lengths[dst_idx]. Array<Integer> new_lengths; for (size_t j = 1; j < lengths.size(); ++j) { if (j == src_idx) { new_lengths.push_back(Integer(lengths[j] / divide_factor)); } else if (j == dst_idx) { new_lengths.push_back(Integer(lengths[j] * divide_factor)); } else { new_lengths.push_back(Integer(lengths[j])); } } ICHECK_LE(GetIntImm(new_lengths.back()), max_innermost_split_factor); StateNode* pstate = state->CopyOnWrite(); pstate->transform_steps.Set( step_id, SplitStep(ps->stage_id, ps->iter_id, ps->extent, Array<Optional<Integer>>(new_lengths.begin(), new_lengths.end()), ps->inner_to_outer)); return ResultKind::kValid; } return ResultKind::kInvalid; } PopulationGenerationRule::ResultKind MutateAutoUnroll::Apply(SketchPolicyNode* policy, State* state, std::mt19937* rand_gen) const { // Extract all auto_unroll_max_step pragma steps. std::vector<int> pragma_steps; for (size_t i = 0; i < (*state)->transform_steps.size(); ++i) { if (auto ps = (*state)->transform_steps[i].as<PragmaStepNode>()) { if (StrStartsWith(ps->pragma_type, "auto_unroll_max_step")) { pragma_steps.push_back(i); } } } if (pragma_steps.empty()) { return ResultKind::kInvalid; } std::vector<int>& auto_unroll_configs = IsGPUTask(policy->search_task) ? auto_unroll_configs_gpu : auto_unroll_configs_cpu; // Randomly pick up an auto unroll pragma step auto step_id = pragma_steps[(*rand_gen)() % pragma_steps.size()]; auto ps = (*state)->transform_steps[step_id].as<PragmaStepNode>(); ICHECK(ps); // Mutate its value to a random candidates int val = auto_unroll_configs[(*rand_gen)() % auto_unroll_configs.size()]; StateNode* pstate = state->CopyOnWrite(); pstate->transform_steps.Set( step_id, PragmaStep(ps->stage_id, ps->iter_id, std::string("auto_unroll_max_step") + "$" + std::to_string(val))); Stage new_stage = pstate->stages[ps->stage_id]; new_stage.CopyOnWrite()->attrs.auto_unroll_max_step = val; pstate->stages.Set(ps->stage_id, new_stage); return ResultKind::kValid; } PopulationGenerationRule::ResultKind MutateComputeLocation::Apply(SketchPolicyNode* policy, State* state, std::mt19937* rand_gen) const { if (GetIntParam(policy->params, SketchParamKey::disable_change_compute_location)) { return ResultKind::kInvalid; } // Extract all compute_at steps. std::vector<int> compute_at_steps; for (size_t s = 0; s < (*state)->transform_steps.size(); ++s) { if (auto ps = (*state)->transform_steps[s].as<ComputeAtStepNode>()) { int stage_inc = GetTargetStageIDInState(*state, s) - ps->stage_id; if (IsTiled((*state)->stages[ps->stage_id + stage_inc])) { continue; } if (NeedsMultilevelTiling(policy->search_task, *state, ps->stage_id + stage_inc)) { continue; } compute_at_steps.push_back(s); } } if (compute_at_steps.empty()) { return ResultKind::kInvalid; } // Randomly pick one step size_t step_id = compute_at_steps[(*rand_gen)() % compute_at_steps.size()]; auto ps = (*state)->transform_steps[step_id].as<ComputeAtStepNode>(); int stage_inc = GetTargetStageIDInState(*state, step_id) - ps->stage_id; ICHECK(ps != nullptr); // Randomly pick a new computation location std::vector<std::pair<int, int>> candidates = GetComputeLocationCandidates(policy->search_task, *state, ps->stage_id + stage_inc); if (candidates.empty()) { return ResultKind::kInvalid; } int choice = (*rand_gen)() % (candidates.size()); int new_compute_at_stage_id = candidates[choice].first; int new_compute_at_iter_id = candidates[choice].second; // Replay a new state. State tmp_s = policy->search_task->compute_dag->init_state; for (size_t s = 0; s < (*state)->transform_steps.size(); ++s) { if (s == step_id) { tmp_s.CopyOnWrite()->transform_steps.push_back( ComputeAtStep(ps->stage_id, new_compute_at_stage_id - stage_inc, new_compute_at_iter_id)); } else { tmp_s.CopyOnWrite()->transform_steps.push_back((*state)->transform_steps[s]); } try { StepApplyToState(tmp_s->transform_steps.back(), &tmp_s, policy->search_task->compute_dag); } catch (dmlc::Error& e) { return ResultKind::kInvalid; } } *state = tmp_s; return ResultKind::kValid; } PopulationGenerationRule::ResultKind MutateParallel::Apply(SketchPolicyNode* policy, State* state, std::mt19937* rand_gen) const { // This mutation rule only focuses on a case that parallel was added to // the outermost loop and the loop is generated by fusing other loops. // In short, we mutate the fusion step before the parallel step. // Extract all parallel steps. std::vector<int> parallel_steps; for (size_t s = 0; s < (*state)->transform_steps.size(); ++s) { auto ps = (*state)->transform_steps[s].as<AnnotationStepNode>(); if (!ps || ps->annotation != IteratorAnnotation::kParallel) { continue; } // Skip non-outermost loop or the parallel step without fusion beforehand. if (ps->iter_id != 0 || s == 0 || !(*state)->transform_steps[s - 1].as<FuseStepNode>()) { continue; } auto fuse_step = (*state)->transform_steps[s - 1].as<FuseStepNode>(); if (fuse_step->fused_ids[0] != 0) { continue; } parallel_steps.push_back(s); } if (parallel_steps.empty()) { return ResultKind::kInvalid; } // Randomly pick one parallel step. size_t step_id = parallel_steps[(*rand_gen)() % parallel_steps.size()]; // Replay a new state until the picked fuse step. State tmp_s = policy->search_task->compute_dag->init_state; for (size_t s = 0; s < step_id - 1; ++s) { const auto& step = (*state)->transform_steps[s]; tmp_s.CopyOnWrite()->transform_steps.push_back(step); StepApplyToState(step, &tmp_s, policy->search_task->compute_dag); } // Compute all possible fusion granularities auto fuse_step = (*state)->transform_steps[step_id - 1].as<FuseStepNode>(); int stage_id = fuse_step->stage_id; const Stage& stage = tmp_s->stages[stage_id]; size_t max_fusable_iter_id; for (max_fusable_iter_id = 0; max_fusable_iter_id < stage->iters.size(); ++max_fusable_iter_id) { const Iterator& it = stage->iters[max_fusable_iter_id]; if (it->iter_kind == IteratorKind::kReduction || it->annotation != IteratorAnnotation::kNone) { break; } if (tmp_s->attach_map->iter_to_attached_stages.count( std::make_pair(stage_id, max_fusable_iter_id))) { break; } } if (max_fusable_iter_id == 0) { return ResultKind::kInvalid; } // Randomly pick one granularity int fuse_to_iter_id = (*rand_gen)() % max_fusable_iter_id + 1; Array<Integer> fused_ids; for (int i = 0; i < fuse_to_iter_id; ++i) { fused_ids.push_back(i); } int iter_offset = fuse_step->fused_ids.back()->value - fused_ids.back()->value; if (iter_offset == 0) { return ResultKind::kInvalid; } // Replay the mutated fused and annotation step. auto new_fuse_step = FuseStep(stage_id, fused_ids); tmp_s.CopyOnWrite()->transform_steps.push_back(new_fuse_step); StepApplyToState(new_fuse_step, &tmp_s, policy->search_task->compute_dag); tmp_s.CopyOnWrite()->transform_steps.push_back((*state)->transform_steps[step_id]); StepApplyToState((*state)->transform_steps[step_id], &tmp_s, policy->search_task->compute_dag); // Replay the rest steps. for (size_t s = step_id + 1; s < (*state)->transform_steps.size(); ++s) { auto step = (*state)->transform_steps[s]; if (step->stage_id == stage_id) { // Since we changed the loop structure, iter ID in later steps to the same stage // has to be adjusted. if (auto ps = step.as<AnnotationStepNode>()) { if (ps->iter_id == 0) { step = AnnotationStep(ps->stage_id, 0, ps->annotation); } else { ICHECK_LE(ps->iter_id + iter_offset, tmp_s->stages[stage_id]->iters.size()); step = AnnotationStep(ps->stage_id, ps->iter_id + iter_offset, ps->annotation); } } else if (auto ps = step.as<PragmaStepNode>()) { if (ps->iter_id == 0) { step = PragmaStep(ps->stage_id, 0, ps->pragma_type); } else { ICHECK_LE(ps->iter_id + iter_offset, tmp_s->stages[stage_id]->iters.size()); step = PragmaStep(ps->stage_id, ps->iter_id + iter_offset, ps->pragma_type); } } else { return ResultKind::kInvalid; } } if (IsStageNumberChangingStep(step)) { // For these steps, we have to update stage_id because these steps will make stage_id // out-dated. But here we just simply give up this mutation for simplicity. // This is not an issue because this will never happend in normal cases where all these steps // are before parallel steps. return ResultKind::kInvalid; } tmp_s.CopyOnWrite()->transform_steps.push_back(step); try { StepApplyToState(tmp_s->transform_steps.back(), &tmp_s, policy->search_task->compute_dag); } catch (dmlc::Error& e) { return ResultKind::kInvalid; } } *state = tmp_s; return ResultKind::kValid; } } // namespace auto_scheduler } // namespace tvm
// Copyright (c) 2012-2017 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 "util.h" #include "utiltime.h" #include "validation.h" #include "test/test_compute.h" #include "checkqueue.h" #include <boost/test/unit_test.hpp> #include <boost/thread.hpp> #include <atomic> #include <thread> #include <vector> #include <mutex> #include <condition_variable> #include <unordered_set> #include <memory> #include "random.h" // BasicTestingSetup not sufficient because nScriptCheckThreads is not set // otherwise. BOOST_FIXTURE_TEST_SUITE(checkqueue_tests, TestingSetup) static const int QUEUE_BATCH_SIZE = 128; struct FakeCheck { bool operator()() { return true; } void swap(FakeCheck& x){}; }; struct FakeCheckCheckCompletion { static std::atomic<size_t> n_calls; bool operator()() { ++n_calls; return true; } void swap(FakeCheckCheckCompletion& x){}; }; struct FailingCheck { bool fails; FailingCheck(bool fails) : fails(fails){}; FailingCheck() : fails(true){}; bool operator()() { return !fails; } void swap(FailingCheck& x) { std::swap(fails, x.fails); }; }; struct UniqueCheck { static std::mutex m; static std::unordered_multiset<size_t> results; size_t check_id; UniqueCheck(size_t check_id_in) : check_id(check_id_in){}; UniqueCheck() : check_id(0){}; bool operator()() { std::lock_guard<std::mutex> l(m); results.insert(check_id); return true; } void swap(UniqueCheck& x) { std::swap(x.check_id, check_id); }; }; struct MemoryCheck { static std::atomic<size_t> fake_allocated_memory; bool b {false}; bool operator()() { return true; } MemoryCheck(){}; MemoryCheck(const MemoryCheck& x) { // We have to do this to make sure that destructor calls are paired // // Really, copy constructor should be deletable, but CCheckQueue breaks // if it is deleted because of internal push_back. fake_allocated_memory += b; }; MemoryCheck(bool b_) : b(b_) { fake_allocated_memory += b; }; ~MemoryCheck(){ fake_allocated_memory -= b; }; void swap(MemoryCheck& x) { std::swap(b, x.b); }; }; struct FrozenCleanupCheck { static std::atomic<uint64_t> nFrozen; static std::condition_variable cv; static std::mutex m; // Freezing can't be the default initialized behavior given how the queue // swaps in default initialized Checks. bool should_freeze {false}; bool operator()() { return true; } FrozenCleanupCheck() {} ~FrozenCleanupCheck() { if (should_freeze) { std::unique_lock<std::mutex> l(m); nFrozen = 1; cv.notify_one(); cv.wait(l, []{ return nFrozen == 0;}); } } void swap(FrozenCleanupCheck& x){std::swap(should_freeze, x.should_freeze);}; }; // Static Allocations std::mutex FrozenCleanupCheck::m{}; std::atomic<uint64_t> FrozenCleanupCheck::nFrozen{0}; std::condition_variable FrozenCleanupCheck::cv{}; std::mutex UniqueCheck::m; std::unordered_multiset<size_t> UniqueCheck::results; std::atomic<size_t> FakeCheckCheckCompletion::n_calls{0}; std::atomic<size_t> MemoryCheck::fake_allocated_memory{0}; // Queue Typedefs typedef CCheckQueue<FakeCheckCheckCompletion> Correct_Queue; typedef CCheckQueue<FakeCheck> Standard_Queue; typedef CCheckQueue<FailingCheck> Failing_Queue; typedef CCheckQueue<UniqueCheck> Unique_Queue; typedef CCheckQueue<MemoryCheck> Memory_Queue; typedef CCheckQueue<FrozenCleanupCheck> FrozenCleanup_Queue; /** This test case checks that the CCheckQueue works properly * with each specified size_t Checks pushed. */ void Correct_Queue_range(std::vector<size_t> range) { auto small_queue = std::unique_ptr<Correct_Queue>(new Correct_Queue {QUEUE_BATCH_SIZE}); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{small_queue->Thread();}); } // Make vChecks here to save on malloc (this test can be slow...) std::vector<FakeCheckCheckCompletion> vChecks; for (auto i : range) { size_t total = i; FakeCheckCheckCompletion::n_calls = 0; CCheckQueueControl<FakeCheckCheckCompletion> control(small_queue.get()); while (total) { vChecks.resize(std::min(total, (size_t) GetRand(10))); total -= vChecks.size(); control.Add(vChecks); } BOOST_REQUIRE(control.Wait()); if (FakeCheckCheckCompletion::n_calls != i) { BOOST_REQUIRE_EQUAL(FakeCheckCheckCompletion::n_calls, i); BOOST_TEST_MESSAGE("Failure on trial " << i << " expected, got " << FakeCheckCheckCompletion::n_calls); } } tg.interrupt_all(); tg.join_all(); } /** Test that 0 checks is correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Zero) { std::vector<size_t> range; range.push_back((size_t)0); Correct_Queue_range(range); } /** Test that 1 check is correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_One) { std::vector<size_t> range; range.push_back((size_t)1); Correct_Queue_range(range); } /** Test that MAX check is correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Max) { std::vector<size_t> range; range.push_back(100000); Correct_Queue_range(range); } /** Test that random numbers of checks are correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Random) { std::vector<size_t> range; range.reserve(100000/1000); for (size_t i = 2; i < 100000; i += std::max((size_t)1, (size_t)GetRand(std::min((size_t)1000, ((size_t)100000) - i)))) range.push_back(i); Correct_Queue_range(range); } /** Test that failing checks are caught */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Catches_Failure) { auto fail_queue = std::unique_ptr<Failing_Queue>(new Failing_Queue {QUEUE_BATCH_SIZE}); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{fail_queue->Thread();}); } for (size_t i = 0; i < 1001; ++i) { CCheckQueueControl<FailingCheck> control(fail_queue.get()); size_t remaining = i; while (remaining) { size_t r = GetRand(10); std::vector<FailingCheck> vChecks; vChecks.reserve(r); for (size_t k = 0; k < r && remaining; k++, remaining--) vChecks.emplace_back(remaining == 1); control.Add(vChecks); } bool success = control.Wait(); if (i > 0) { BOOST_REQUIRE(!success); } else if (i == 0) { BOOST_REQUIRE(success); } } tg.interrupt_all(); tg.join_all(); } // Test that a block validation which fails does not interfere with // future blocks, ie, the bad state is cleared. BOOST_AUTO_TEST_CASE(test_CheckQueue_Recovers_From_Failure) { auto fail_queue = std::unique_ptr<Failing_Queue>(new Failing_Queue {QUEUE_BATCH_SIZE}); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{fail_queue->Thread();}); } for (auto times = 0; times < 10; ++times) { for (bool end_fails : {true, false}) { CCheckQueueControl<FailingCheck> control(fail_queue.get()); { std::vector<FailingCheck> vChecks; vChecks.resize(100, false); vChecks[99] = end_fails; control.Add(vChecks); } bool r =control.Wait(); BOOST_REQUIRE(r || end_fails); } } tg.interrupt_all(); tg.join_all(); } // Test that unique checks are actually all called individually, rather than // just one check being called repeatedly. Test that checks are not called // more than once as well BOOST_AUTO_TEST_CASE(test_CheckQueue_UniqueCheck) { auto queue = std::unique_ptr<Unique_Queue>(new Unique_Queue {QUEUE_BATCH_SIZE}); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{queue->Thread();}); } size_t COUNT = 100000; size_t total = COUNT; { CCheckQueueControl<UniqueCheck> control(queue.get()); while (total) { size_t r = GetRand(10); std::vector<UniqueCheck> vChecks; for (size_t k = 0; k < r && total; k++) vChecks.emplace_back(--total); control.Add(vChecks); } } bool r = true; BOOST_REQUIRE_EQUAL(UniqueCheck::results.size(), COUNT); for (size_t i = 0; i < COUNT; ++i) r = r && UniqueCheck::results.count(i) == 1; BOOST_REQUIRE(r); tg.interrupt_all(); tg.join_all(); } // Test that blocks which might allocate lots of memory free their memory agressively. // // This test attempts to catch a pathological case where by lazily freeing // checks might mean leaving a check un-swapped out, and decreasing by 1 each // time could leave the data hanging across a sequence of blocks. BOOST_AUTO_TEST_CASE(test_CheckQueue_Memory) { auto queue = std::unique_ptr<Memory_Queue>(new Memory_Queue {QUEUE_BATCH_SIZE}); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{queue->Thread();}); } for (size_t i = 0; i < 1000; ++i) { size_t total = i; { CCheckQueueControl<MemoryCheck> control(queue.get()); while (total) { size_t r = GetRand(10); std::vector<MemoryCheck> vChecks; for (size_t k = 0; k < r && total; k++) { total--; // Each iteration leaves data at the front, back, and middle // to catch any sort of deallocation failure vChecks.emplace_back(total == 0 || total == i || total == i/2); } control.Add(vChecks); } } BOOST_REQUIRE_EQUAL(MemoryCheck::fake_allocated_memory, 0); } tg.interrupt_all(); tg.join_all(); } // Test that a new verification cannot occur until all checks // have been destructed BOOST_AUTO_TEST_CASE(test_CheckQueue_FrozenCleanup) { auto queue = std::unique_ptr<FrozenCleanup_Queue>(new FrozenCleanup_Queue {QUEUE_BATCH_SIZE}); boost::thread_group tg; bool fails = false; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{queue->Thread();}); } std::thread t0([&]() { CCheckQueueControl<FrozenCleanupCheck> control(queue.get()); std::vector<FrozenCleanupCheck> vChecks(1); // Freezing can't be the default initialized behavior given how the queue // swaps in default initialized Checks (otherwise freezing destructor // would get called twice). vChecks[0].should_freeze = true; control.Add(vChecks); control.Wait(); // Hangs here }); { std::unique_lock<std::mutex> l(FrozenCleanupCheck::m); // Wait until the queue has finished all jobs and frozen FrozenCleanupCheck::cv.wait(l, [](){return FrozenCleanupCheck::nFrozen == 1;}); // Try to get control of the queue a bunch of times for (auto x = 0; x < 100 && !fails; ++x) { fails = queue->ControlMutex.try_lock(); } // Unfreeze FrozenCleanupCheck::nFrozen = 0; } // Awaken frozen destructor FrozenCleanupCheck::cv.notify_one(); // Wait for control to finish t0.join(); tg.interrupt_all(); tg.join_all(); BOOST_REQUIRE(!fails); } /** Test that CCheckQueueControl is threadsafe */ BOOST_AUTO_TEST_CASE(test_CheckQueueControl_Locks) { auto queue = std::unique_ptr<Standard_Queue>(new Standard_Queue{QUEUE_BATCH_SIZE}); { boost::thread_group tg; std::atomic<int> nThreads {0}; std::atomic<int> fails {0}; for (size_t i = 0; i < 3; ++i) { tg.create_thread( [&]{ CCheckQueueControl<FakeCheck> control(queue.get()); // While sleeping, no other thread should execute to this point auto observed = ++nThreads; MilliSleep(10); fails += observed != nThreads; }); } tg.join_all(); BOOST_REQUIRE_EQUAL(fails, 0); } { boost::thread_group tg; std::mutex m; bool has_lock {false}; bool has_tried {false}; bool done {false}; bool done_ack {false}; std::condition_variable cv; { std::unique_lock<std::mutex> l(m); tg.create_thread([&]{ CCheckQueueControl<FakeCheck> control(queue.get()); std::unique_lock<std::mutex> l(m); has_lock = true; cv.notify_one(); cv.wait(l, [&]{return has_tried;}); done = true; cv.notify_one(); // Wait until the done is acknowledged // cv.wait(l, [&]{return done_ack;}); }); // Wait for thread to get the lock cv.wait(l, [&](){return has_lock;}); bool fails = false; for (auto x = 0; x < 100 && !fails; ++x) { fails = queue->ControlMutex.try_lock(); } has_tried = true; cv.notify_one(); cv.wait(l, [&](){return done;}); // Acknowledge the done done_ack = true; cv.notify_one(); BOOST_REQUIRE(!fails); } tg.join_all(); } } BOOST_AUTO_TEST_SUITE_END()
//Copyright (c) 2019 The PIVX developers //Copyright (c) 2020 The SafeDeal developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "qt/safedeal/addresslabelrow.h" #include "qt/safedeal/forms/ui_addresslabelrow.h" AddressLabelRow::AddressLabelRow(QWidget *parent) : QWidget(parent), ui(new Ui::AddressLabelRow) { ui->setupUi(this); ui->lblAddress->setProperty("cssClass", "text-list-body1"); ui->lblLabel->setProperty("cssClass", "text-list-title1"); } void AddressLabelRow::init(bool isLightTheme, bool isHover) { updateState(isLightTheme, isHover, false); } void AddressLabelRow::updateView(QString address, QString label) { ui->lblAddress->setText(address); ui->lblLabel->setText(label); } void AddressLabelRow::updateState(bool isLightTheme, bool isHovered, bool isSelected) { if (isLightTheme) ui->lblDivisory->setStyleSheet("background-color:#bababa"); else ui->lblDivisory->setStyleSheet("background-color:#40ffffff"); ui->btnMenu->setVisible(isHovered); } void AddressLabelRow::enterEvent(QEvent *) { ui->btnMenu->setVisible(true); update(); } void AddressLabelRow::leaveEvent(QEvent *) { ui->btnMenu->setVisible(false); update(); } AddressLabelRow::~AddressLabelRow() { delete ui; }
// Copyright (c) 2017-2020 TKEY DMCC LLC & Tkeycoin Dao. All rights reserved. // Website: www.tkeycoin.com // // 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. // BaseBlob.hpp #pragma once #include <cstdint> #include <climits> #include <array> #include <vector> #include <algorithm> #include <sstream> #include <iomanip> #include <type_traits> #include "../util/Hex.hpp" #include "../serialization/Serialization.hpp" template<size_t BITS> class Blob : public std::array<uint8_t, (BITS + CHAR_BIT - 1) / CHAR_BIT>, public Serializable { public: static_assert(BITS > 0); static constexpr size_t bits = BITS; static constexpr size_t bytes = (BITS + CHAR_BIT - 1) / CHAR_BIT; protected: using base = std::array<uint8_t, bytes>; public: Blob(Blob&&) noexcept = default; // Move-constructor Blob(const Blob&) = default; // Copy-constructor ~Blob() = default; // Destructor Blob& operator=(Blob&&) noexcept = default; // Move-assignment Blob& operator=(Blob const&) = default; // Copy-assignment Blob() // Default-constructor { setNull(); } template< typename T, typename std::enable_if_t< !std::is_constructible_v<std::string_view, T> && std::is_integral_v<typename T::value_type> && sizeof(typename T::value_type) == 1, void >* = nullptr > Blob(const T& data) // Constructor by vector or array of bytes { auto size = std::min(data.rend() - data.rbegin(), base::end() - base::begin()); auto i = std::copy(data.rbegin(), data.rbegin() + size, base::begin()); std::fill(i, base::end(), 0); for (auto ii = data.begin() + size; ii != data.end(); ++ii) { if (*ii) throw std::overflow_error("Inner data overflows destination"); } } template< typename T, typename std::enable_if_t<std::is_constructible_v<std::string_view, T>, void>* = nullptr > Blob(const T& data) // Constructor by various string views { std::string_view str(data); auto srcIt = str.cbegin(); // skip leading spaces while (std::isspace(*srcIt)) ++srcIt; // skip 0x if (*srcIt == '0') { ++srcIt; if (*srcIt == 'x' || *srcIt == 'X') { ++srcIt; } else { --srcIt; } } // skip leading zeros while (*srcIt == '0') ++srcIt; auto last = srcIt; // find end of hex-digits sequence srcIt = std::find_if(srcIt, str.cend(), [](auto x){return !Hex::isDigit(x);}) - 1; // fill the blob for (auto dsrIt = base::begin(); dsrIt != base::end(); ++dsrIt) { if (srcIt < last) { std::fill(dsrIt, base::end(), 0); break; } *dsrIt = Hex::digitToInt(*srcIt--); if (srcIt >= last) { *dsrIt |= Hex::digitToInt(*srcIt--) << 4u; } } } [[nodiscard]] bool isNull() const { return std::find_if(base::cbegin(), base::cend(), [](auto byte){return byte;}) == base::end(); } void setNull() { std::fill_n(base::begin(), base::size(), 0); } [[nodiscard]] std::string str() const { std::ostringstream oss; oss << std::hex << std::setfill('0'); std::for_each(base::crbegin(), base::crend(), [&oss](auto& byte) { oss << std::setw(2) << (uint) byte; }); return oss.str(); } [[nodiscard]] uint64_t GetUint64(int pos) const { const uint8_t* ptr = base::data() + pos * 8; return ((uint64_t)ptr[0]) | \ ((uint64_t)ptr[1]) << 8u | \ ((uint64_t)ptr[2]) << 16u | \ ((uint64_t)ptr[3]) << 24u | \ ((uint64_t)ptr[4]) << 32u | \ ((uint64_t)ptr[5]) << 40u | \ ((uint64_t)ptr[6]) << 48u | \ ((uint64_t)ptr[7]) << 56u; } void Serialize(std::ostream& os) const override { os.write(reinterpret_cast<const char*>(base::data()), base::size()); } void Unserialize(std::istream& is) override { is.read(reinterpret_cast<char*>(base::data()), base::size()); } [[nodiscard]] SVal toSVal() const override { return str(); return SBinary(base::data(), base::size()); } explicit operator bool() const { return !isNull(); } friend std::ostream& operator<<(std::ostream& os, const Blob& blob) { os.write(reinterpret_cast<const char*>(blob.data()), blob.size()); return os; } friend std::istream& operator>>(std::istream& is, Blob& blob) { is.read(reinterpret_cast<char*>(blob.data()), blob.size()); return is; } friend bool operator<(const Blob& lhs, const Blob& rhs) { return std::lexicographical_compare(lhs.crbegin(), lhs.crend(), rhs.crbegin(), rhs.crend()); } friend bool operator<=(const Blob& lhs, const Blob& rhs) { return std::lexicographical_compare(lhs.crbegin(), lhs.crend(), rhs.crbegin(), rhs.crend(), [](auto& l,auto& r){return l <= r;}); } friend bool operator>(const Blob& lhs, const Blob& rhs) { return std::lexicographical_compare(lhs.crbegin(), lhs.crend(), rhs.crbegin(), rhs.crend(), [](auto& l, auto& r) { return l > r; }); } friend bool operator>=(const Blob& lhs, const Blob& rhs) { return std::lexicographical_compare(lhs.crbegin(), lhs.crend(), rhs.crbegin(), rhs.crend(), [](auto& l, auto& r) { return l >= r; }); } }; namespace std { template<size_t BITS> class hash<Blob<BITS>> { public: size_t operator()(const Blob<BITS> &blob) const { return *reinterpret_cast<const size_t*>(blob.data()); } }; }
#include "vlpch.h" #include "Material.h" namespace Velocity { }
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/tcaplusdb/v20190823/model/DeleteClusterRequest.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using namespace TencentCloud::Tcaplusdb::V20190823::Model; using namespace rapidjson; using namespace std; DeleteClusterRequest::DeleteClusterRequest() : m_clusterIdHasBeenSet(false) { } string DeleteClusterRequest::ToJsonString() const { Document d; d.SetObject(); Document::AllocatorType& allocator = d.GetAllocator(); if (m_clusterIdHasBeenSet) { Value iKey(kStringType); string key = "ClusterId"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, Value(m_clusterId.c_str(), allocator).Move(), allocator); } StringBuffer buffer; Writer<StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); } string DeleteClusterRequest::GetClusterId() const { return m_clusterId; } void DeleteClusterRequest::SetClusterId(const string& _clusterId) { m_clusterId = _clusterId; m_clusterIdHasBeenSet = true; } bool DeleteClusterRequest::ClusterIdHasBeenSet() const { return m_clusterIdHasBeenSet; }
/****************************************************************************** * * Component: OGR SQL Engine * Purpose: swq_select class implementation. * Author: Frank Warmerdam <warmerdam@pobox.com> * ****************************************************************************** * Copyright (C) 2010 Frank Warmerdam <warmerdam@pobox.com> * * 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 "swq.h" #include "swq_parser.hpp" /************************************************************************/ /* swq_select() */ /************************************************************************/ swq_select::swq_select() { query_mode = 0; raw_select = NULL; result_columns = 0; column_defs = NULL; column_summary = NULL; table_count = 0; table_defs = NULL; join_count = 0; join_defs = NULL; where_expr = NULL; order_specs = 0; order_defs = NULL; poOtherSelect = NULL; } /************************************************************************/ /* ~swq_select() */ /************************************************************************/ swq_select::~swq_select() { int i; delete where_expr; CPLFree( raw_select ); for( i = 0; i < table_count; i++ ) { swq_table_def *table_def = table_defs + i; CPLFree( table_def->data_source ); CPLFree( table_def->table_name ); CPLFree( table_def->table_alias ); } if( table_defs != NULL ) CPLFree( table_defs ); for( i = 0; i < result_columns; i++ ) { CPLFree( column_defs[i].field_name ); CPLFree( column_defs[i].field_alias ); delete column_defs[i].expr; if( column_summary != NULL && column_summary[i].distinct_list != NULL ) { int j; for( j = 0; j < column_summary[i].count; j++ ) CPLFree( column_summary[i].distinct_list[j] ); CPLFree( column_summary[i].distinct_list ); } } CPLFree( column_defs ); CPLFree( column_summary ); for( i = 0; i < order_specs; i++ ) { CPLFree( order_defs[i].field_name ); } CPLFree( order_defs ); for( i = 0; i < join_count; i++ ) { CPLFree( join_defs[i].primary_field_name ); CPLFree( join_defs[i].secondary_field_name ); } CPLFree( join_defs ); delete poOtherSelect; } /************************************************************************/ /* preparse() */ /* */ /* Parse the expression but without knowing the available */ /* tables and fields. */ /************************************************************************/ CPLErr swq_select::preparse( const char *select_statement ) { /* -------------------------------------------------------------------- */ /* Prepare a parser context. */ /* -------------------------------------------------------------------- */ swq_parse_context context; context.pszInput = select_statement; context.pszNext = select_statement; context.nStartToken = SWQT_SELECT_START; context.poCurSelect = this; /* -------------------------------------------------------------------- */ /* Do the parse. */ /* -------------------------------------------------------------------- */ if( swqparse( &context ) != 0 ) { delete context.poRoot; return CE_Failure; } postpreparse(); return CE_None; } /************************************************************************/ /* postpreparse() */ /************************************************************************/ void swq_select::postpreparse() { /* -------------------------------------------------------------------- */ /* Reorder the joins in the order they appear in the SQL string. */ /* -------------------------------------------------------------------- */ int i; for(i = 0; i < join_count / 2; i++) { swq_join_def sTmp; memcpy(&sTmp, &join_defs[i], sizeof(swq_join_def)); memcpy(&join_defs[i], &join_defs[join_count - 1 - i], sizeof(swq_join_def)); memcpy(&join_defs[join_count - 1 - i], &sTmp, sizeof(swq_join_def)); } /* We make that strong assumption in ogr_gensql */ for(i = 0; i < join_count; i++) { CPLAssert(join_defs[i].secondary_table == i + 1); } if( poOtherSelect != NULL) poOtherSelect->postpreparse(); } /************************************************************************/ /* Dump() */ /************************************************************************/ void swq_select::Dump( FILE *fp ) { int i; fprintf( fp, "SELECT Statement:\n" ); /* -------------------------------------------------------------------- */ /* query mode. */ /* -------------------------------------------------------------------- */ if( query_mode == SWQM_SUMMARY_RECORD ) fprintf( fp, " QUERY MODE: SUMMARY RECORD\n" ); else if( query_mode == SWQM_RECORDSET ) fprintf( fp, " QUERY MODE: RECORDSET\n" ); else if( query_mode == SWQM_DISTINCT_LIST ) fprintf( fp, " QUERY MODE: DISTINCT LIST\n" ); else fprintf( fp, " QUERY MODE: %d/unknown\n", query_mode ); /* -------------------------------------------------------------------- */ /* column_defs */ /* -------------------------------------------------------------------- */ fprintf( fp, " Result Columns:\n" ); for( i = 0; i < result_columns; i++ ) { swq_col_def *def = column_defs + i; fprintf( fp, " Name: %s\n", def->field_name ); if( def->field_alias ) fprintf( fp, " Alias: %s\n", def->field_alias ); if( def->col_func == SWQCF_NONE ) /* nothing */; else if( def->col_func == SWQCF_AVG ) fprintf( fp, " Function: AVG\n" ); else if( def->col_func == SWQCF_MIN ) fprintf( fp, " Function: MIN\n" ); else if( def->col_func == SWQCF_MAX ) fprintf( fp, " Function: MAX\n" ); else if( def->col_func == SWQCF_COUNT ) fprintf( fp, " Function: COUNT\n" ); else if( def->col_func == SWQCF_SUM ) fprintf( fp, " Function: SUM\n" ); else if( def->col_func == SWQCF_CUSTOM ) fprintf( fp, " Function: CUSTOM\n" ); else fprintf( fp, " Function: UNKNOWN!\n" ); if( def->distinct_flag ) fprintf( fp, " DISTINCT flag set\n" ); fprintf( fp, " Field Index: %d, Table Index: %d\n", def->field_index, def->table_index ); fprintf( fp, " Field Type: %d\n", def->field_type ); fprintf( fp, " Target Type: %d\n", def->target_type ); fprintf( fp, " Length: %d, Precision: %d\n", def->field_length, def->field_precision ); if( def->expr != NULL ) { fprintf( fp, " Expression:\n" ); def->expr->Dump( fp, 3 ); } } /* -------------------------------------------------------------------- */ /* table_defs */ /* -------------------------------------------------------------------- */ fprintf( fp, " Table Defs: %d\n", table_count ); for( i = 0; i < table_count; i++ ) { fprintf( fp, " datasource=%s, table_name=%s, table_alias=%s\n", table_defs[i].data_source, table_defs[i].table_name, table_defs[i].table_alias ); } /* -------------------------------------------------------------------- */ /* join_defs */ /* -------------------------------------------------------------------- */ if( join_count > 0 ) fprintf( fp, " joins:\n" ); for( i = 0; i < join_count; i++ ) { fprintf( fp, " %d:\n", i ); fprintf( fp, " Primary Field: %s/%d\n", join_defs[i].primary_field_name, join_defs[i].primary_field ); fprintf( fp, " Operation: %d\n", join_defs[i].op ); fprintf( fp, " Secondary Field: %s/%d\n", join_defs[i].secondary_field_name, join_defs[i].secondary_field ); fprintf( fp, " Secondary Table: %d\n", join_defs[i].secondary_table ); } /* -------------------------------------------------------------------- */ /* Where clause. */ /* -------------------------------------------------------------------- */ if( where_expr != NULL ) { fprintf( fp, " WHERE:\n" ); where_expr->Dump( fp, 2 ); } /* -------------------------------------------------------------------- */ /* Order by */ /* -------------------------------------------------------------------- */ for( i = 0; i < order_specs; i++ ) { fprintf( fp, " ORDER BY: %s (%d/%d)", order_defs[i].field_name, order_defs[i].table_index, order_defs[i].field_index ); if( order_defs[i].ascending_flag ) fprintf( fp, " ASC\n" ); else fprintf( fp, " DESC\n" ); } } /************************************************************************/ /* PushField() */ /* */ /* Create a new field definition by name and possibly alias. */ /************************************************************************/ int swq_select::PushField( swq_expr_node *poExpr, const char *pszAlias, int distinct_flag ) { /* -------------------------------------------------------------------- */ /* Grow the array. */ /* -------------------------------------------------------------------- */ result_columns++; column_defs = (swq_col_def *) CPLRealloc( column_defs, sizeof(swq_col_def) * result_columns ); swq_col_def *col_def = column_defs + result_columns - 1; memset( col_def, 0, sizeof(swq_col_def) ); /* -------------------------------------------------------------------- */ /* Try to capture a field name. */ /* -------------------------------------------------------------------- */ if( poExpr->eNodeType == SNT_COLUMN ) col_def->field_name = CPLStrdup(poExpr->string_value); else if( poExpr->eNodeType == SNT_OPERATION && poExpr->nSubExprCount >= 1 && poExpr->papoSubExpr[0]->eNodeType == SNT_COLUMN ) col_def->field_name = CPLStrdup(poExpr->papoSubExpr[0]->string_value); else col_def->field_name = CPLStrdup(""); /* -------------------------------------------------------------------- */ /* Initialize fields. */ /* -------------------------------------------------------------------- */ if( pszAlias != NULL ) col_def->field_alias = CPLStrdup( pszAlias ); col_def->table_index = -1; col_def->field_index = -1; col_def->field_type = SWQ_OTHER; col_def->field_precision = -1; col_def->target_type = SWQ_OTHER; col_def->col_func = SWQCF_NONE; col_def->distinct_flag = distinct_flag; /* -------------------------------------------------------------------- */ /* Do we have a CAST operator in play? */ /* -------------------------------------------------------------------- */ if( poExpr->eNodeType == SNT_OPERATION && poExpr->nOperation == SWQ_CAST ) { const char *pszTypeName = poExpr->papoSubExpr[1]->string_value; int parse_precision = 0; if( EQUAL(pszTypeName,"character") ) { col_def->target_type = SWQ_STRING; col_def->field_length = 1; } else if( strcasecmp(pszTypeName,"integer") == 0 ) { col_def->target_type = SWQ_INTEGER; } else if( strcasecmp(pszTypeName,"float") == 0 ) { col_def->target_type = SWQ_FLOAT; } else if( strcasecmp(pszTypeName,"numeric") == 0 ) { col_def->target_type = SWQ_FLOAT; parse_precision = 1; } else if( strcasecmp(pszTypeName,"timestamp") == 0 ) { col_def->target_type = SWQ_TIMESTAMP; } else if( strcasecmp(pszTypeName,"date") == 0 ) { col_def->target_type = SWQ_DATE; } else if( strcasecmp(pszTypeName,"time") == 0 ) { col_def->target_type = SWQ_TIME; } else { CPLError( CE_Failure, CPLE_AppDefined, "Unrecognized typename %s in CAST operator.", pszTypeName ); CPLFree(col_def->field_name); col_def->field_name = NULL; CPLFree(col_def->field_alias); col_def->field_alias = NULL; result_columns--; return FALSE; } // field width. if( poExpr->nSubExprCount > 2 ) { col_def->field_length = poExpr->papoSubExpr[2]->int_value; } // field width. if( poExpr->nSubExprCount > 3 && parse_precision ) { col_def->field_precision = poExpr->papoSubExpr[3]->int_value; } } /* -------------------------------------------------------------------- */ /* Do we have a special column function in play? */ /* -------------------------------------------------------------------- */ if( poExpr->eNodeType == SNT_OPERATION && poExpr->nOperation >= SWQ_AVG && poExpr->nOperation <= SWQ_SUM ) { if( poExpr->nSubExprCount != 1 ) { CPLError( CE_Failure, CPLE_AppDefined, "Column Summary Function '%s' has wrong number of arguments.", poExpr->string_value ? poExpr->string_value : "(null)"); CPLFree(col_def->field_name); col_def->field_name = NULL; CPLFree(col_def->field_alias); col_def->field_alias = NULL; result_columns--; return FALSE; } else { col_def->col_func = (swq_col_func) poExpr->nOperation; swq_expr_node *poSubExpr = poExpr->papoSubExpr[0]; poExpr->papoSubExpr[0] = NULL; poExpr->nSubExprCount = 0; delete poExpr; poExpr = poSubExpr; } } col_def->expr = poExpr; return TRUE; } /************************************************************************/ /* PushTableDef() */ /************************************************************************/ int swq_select::PushTableDef( const char *pszDataSource, const char *pszName, const char *pszAlias ) { table_count++; table_defs = (swq_table_def *) CPLRealloc( table_defs, sizeof(swq_table_def) * table_count ); if( pszDataSource != NULL ) table_defs[table_count-1].data_source = CPLStrdup(pszDataSource); else table_defs[table_count-1].data_source = NULL; table_defs[table_count-1].table_name = CPLStrdup(pszName); if( pszAlias != NULL ) table_defs[table_count-1].table_alias = CPLStrdup(pszAlias); else table_defs[table_count-1].table_alias = CPLStrdup(pszName); return table_count-1; } /************************************************************************/ /* PushOrderBy() */ /************************************************************************/ void swq_select::PushOrderBy( const char *pszFieldName, int bAscending ) { order_specs++; order_defs = (swq_order_def *) CPLRealloc( order_defs, sizeof(swq_order_def) * order_specs ); order_defs[order_specs-1].field_name = CPLStrdup(pszFieldName); order_defs[order_specs-1].table_index = -1; order_defs[order_specs-1].field_index = -1; order_defs[order_specs-1].ascending_flag = bAscending; } /************************************************************************/ /* PushJoin() */ /************************************************************************/ void swq_select::PushJoin( int iSecondaryTable, const char *pszPrimaryField, const char *pszSecondaryField ) { join_count++; join_defs = (swq_join_def *) CPLRealloc( join_defs, sizeof(swq_join_def) * join_count ); join_defs[join_count-1].secondary_table = iSecondaryTable; join_defs[join_count-1].primary_field_name = CPLStrdup(pszPrimaryField); join_defs[join_count-1].primary_field = -1; join_defs[join_count-1].op = SWQ_EQ; join_defs[join_count-1].secondary_field_name = CPLStrdup(pszSecondaryField); join_defs[join_count-1].secondary_field = -1; } /************************************************************************/ /* PushUnionAll() */ /************************************************************************/ void swq_select::PushUnionAll( swq_select* poOtherSelectIn ) { CPLAssert(poOtherSelect == NULL); poOtherSelect = poOtherSelectIn; } /************************************************************************/ /* expand_wildcard() */ /* */ /* This function replaces the '*' in a "SELECT *" with the list */ /* provided list of fields. Itis used by swq_select_parse(), */ /* but may be called in advance by applications wanting the */ /* "default" field list to be different than the full list of */ /* fields. */ /************************************************************************/ CPLErr swq_select::expand_wildcard( swq_field_list *field_list ) { int isrc; /* ==================================================================== */ /* Check each pre-expansion field. */ /* ==================================================================== */ for( isrc = 0; isrc < result_columns; isrc++ ) { const char *src_fieldname = column_defs[isrc].field_name; int itable, new_fields, i, iout; if( *src_fieldname == '\0' || src_fieldname[strlen(src_fieldname)-1] != '*' ) continue; /* We don't want to expand COUNT(*) */ if( column_defs[isrc].col_func == SWQCF_COUNT ) continue; /* -------------------------------------------------------------------- */ /* Parse out the table name, verify it, and establish the */ /* number of fields to insert from it. */ /* -------------------------------------------------------------------- */ if( strcmp(src_fieldname,"*") == 0 ) { itable = -1; new_fields = field_list->count; } else if( strlen(src_fieldname) < 3 || src_fieldname[strlen(src_fieldname)-2] != '.' ) { CPLError( CE_Failure, CPLE_AppDefined, "Ill formatted field definition '%s'.", src_fieldname ); return CE_Failure; } else { char *table_name = CPLStrdup( src_fieldname ); table_name[strlen(src_fieldname)-2] = '\0'; for( itable = 0; itable < field_list->table_count; itable++ ) { if( strcasecmp(table_name, field_list->table_defs[itable].table_alias ) == 0 ) break; } if( itable == field_list->table_count ) { CPLError( CE_Failure, CPLE_AppDefined, "Table %s not recognised from %s definition.", table_name, src_fieldname ); CPLFree( table_name ); return CE_Failure; } CPLFree( table_name ); /* count the number of fields in this table. */ new_fields = 0; for( i = 0; i < field_list->count; i++ ) { if( field_list->table_ids[i] == itable ) new_fields++; } } if (new_fields > 0) { /* -------------------------------------------------------------------- */ /* Reallocate the column list larger. */ /* -------------------------------------------------------------------- */ CPLFree( column_defs[isrc].field_name ); delete column_defs[isrc].expr; column_defs = (swq_col_def *) CPLRealloc( column_defs, sizeof(swq_col_def) * (result_columns + new_fields - 1 ) ); /* -------------------------------------------------------------------- */ /* Push the old definitions that came after the one to be */ /* replaced further up in the array. */ /* -------------------------------------------------------------------- */ if (new_fields != 1) { for( i = result_columns-1; i > isrc; i-- ) { memcpy( column_defs + i + new_fields - 1, column_defs + i, sizeof( swq_col_def ) ); } } result_columns += (new_fields - 1 ); /* -------------------------------------------------------------------- */ /* Zero out all the stuff in the target column definitions. */ /* -------------------------------------------------------------------- */ memset( column_defs + isrc, 0, new_fields * sizeof(swq_col_def) ); } else { /* -------------------------------------------------------------------- */ /* The wildcard expands to nothing */ /* -------------------------------------------------------------------- */ CPLFree( column_defs[isrc].field_name ); delete column_defs[isrc].expr; memmove( column_defs + isrc, column_defs + isrc + 1, sizeof( swq_col_def ) * (result_columns-1-isrc) ); result_columns --; } /* -------------------------------------------------------------------- */ /* Assign the selected fields. */ /* -------------------------------------------------------------------- */ iout = isrc; for( i = 0; i < field_list->count; i++ ) { swq_col_def *def; int compose = itable != -1; /* skip this field if it isn't in the target table. */ if( itable != -1 && field_list->table_ids != NULL && itable != field_list->table_ids[i] ) continue; /* set up some default values. */ def = column_defs + iout; def->field_precision = -1; def->target_type = SWQ_OTHER; /* does this field duplicate an earlier one? */ if( field_list->table_ids != NULL && field_list->table_ids[i] != 0 && !compose ) { int other; for( other = 0; other < i; other++ ) { if( strcasecmp(field_list->names[i], field_list->names[other]) == 0 ) { compose = 1; break; } } } if( !compose ) def->field_name = CPLStrdup( field_list->names[i] ); else { int itable = field_list->table_ids[i]; char *composed_name; const char *field_name = field_list->names[i]; const char *table_alias = field_list->table_defs[itable].table_alias; composed_name = (char *) CPLMalloc(strlen(field_name)+strlen(table_alias)+2); sprintf( composed_name, "%s.%s", table_alias, field_name ); def->field_name = composed_name; } iout++; /* All the other table info will be provided by the later parse operation. */ } /* If there are several occurrences of '*', go on, but stay on the */ /* same index in case '*' is expanded to nothing */ /* (the -- is to compensate the fact that isrc will be incremented in */ /* the after statement of the for loop) */ isrc --; } return CE_None; } /************************************************************************/ /* parse() */ /* */ /* This method really does post-parse processing. */ /************************************************************************/ CPLErr swq_select::parse( swq_field_list *field_list, int parse_flags ) { int i; CPLErr eError; eError = expand_wildcard( field_list ); if( eError != CE_None ) return eError; /* -------------------------------------------------------------------- */ /* Identify field information. */ /* -------------------------------------------------------------------- */ for( i = 0; i < result_columns; i++ ) { swq_col_def *def = column_defs + i; if( def->expr != NULL && def->expr->eNodeType != SNT_COLUMN ) { def->field_index = -1; def->table_index = -1; if( def->expr->Check( field_list ) == SWQ_ERROR ) return CE_Failure; def->field_type = def->expr->field_type; // If the field was changed from string constant to // column field then adopt the name. if( def->expr->eNodeType == SNT_COLUMN ) { def->field_index = def->expr->field_index; def->table_index = def->expr->table_index; CPLFree( def->field_name ); def->field_name = CPLStrdup(def->expr->string_value); } } else { swq_field_type this_type; /* identify field */ def->field_index = swq_identify_field( def->field_name, field_list, &this_type, &(def->table_index) ); /* record field type */ def->field_type = this_type; if( def->field_index == -1 && def->col_func != SWQCF_COUNT ) { CPLError( CE_Failure, CPLE_AppDefined, "Unrecognised field name %s.", def->field_name ); return CE_Failure; } } /* identify column function if present */ if( (def->col_func == SWQCF_MIN || def->col_func == SWQCF_MAX || def->col_func == SWQCF_AVG || def->col_func == SWQCF_SUM) && def->field_type == SWQ_STRING ) { // possibly this is already enforced by the checker? const swq_operation *op = swq_op_registrar::GetOperator( (swq_op) def->col_func ); CPLError( CE_Failure, CPLE_AppDefined, "Use of field function %s() on string field %s illegal.", op->osName.c_str(), def->field_name ); return CE_Failure; } } /* -------------------------------------------------------------------- */ /* Check if we are producing a one row summary result or a set */ /* of records. Generate an error if we get conflicting */ /* indications. */ /* -------------------------------------------------------------------- */ query_mode = -1; for( i = 0; i < result_columns; i++ ) { swq_col_def *def = column_defs + i; int this_indicator = -1; if( def->col_func == SWQCF_MIN || def->col_func == SWQCF_MAX || def->col_func == SWQCF_AVG || def->col_func == SWQCF_SUM || def->col_func == SWQCF_COUNT ) this_indicator = SWQM_SUMMARY_RECORD; else if( def->col_func == SWQCF_NONE ) { if( def->distinct_flag ) this_indicator = SWQM_DISTINCT_LIST; else this_indicator = SWQM_RECORDSET; } if( this_indicator != query_mode && this_indicator != -1 && query_mode != -1 ) { CPLError( CE_Failure, CPLE_AppDefined, "Field list implies mixture of regular recordset mode, summary mode or distinct field list mode." ); return CE_Failure; } if( this_indicator != -1 ) query_mode = this_indicator; } if( result_columns > 1 && query_mode == SWQM_DISTINCT_LIST ) { CPLError( CE_Failure, CPLE_AppDefined, "SELECTing more than one DISTINCT field is a query not supported." ); return CE_Failure; } else if (result_columns == 0) { query_mode = SWQM_RECORDSET; } /* -------------------------------------------------------------------- */ /* Process column names in JOIN specs. */ /* -------------------------------------------------------------------- */ for( i = 0; i < join_count; i++ ) { swq_join_def *def = join_defs + i; int table_id; /* identify primary field */ def->primary_field = swq_identify_field( def->primary_field_name, field_list, NULL, &table_id ); if( def->primary_field == -1 ) { CPLError( CE_Failure, CPLE_AppDefined, "Unrecognised primary field %s in JOIN clause..", def->primary_field_name ); return CE_Failure; } if( table_id != 0 ) { CPLError( CE_Failure, CPLE_AppDefined, "Currently the primary key must come from the primary table in\n" "JOIN, %s is not from the primary table.", def->primary_field_name ); return CE_Failure; } /* identify secondary field */ def->secondary_field = swq_identify_field( def->secondary_field_name, field_list, NULL,&table_id); if( def->secondary_field == -1 ) { CPLError( CE_Failure, CPLE_AppDefined, "Unrecognised secondary field %s in JOIN clause..", def->secondary_field_name ); return CE_Failure; } if( table_id != def->secondary_table ) { CPLError( CE_Failure, CPLE_AppDefined, "Currently the secondary key must come from the secondary table\n" "listed in the JOIN. %s is not from table %s..", def->secondary_field_name, table_defs[def->secondary_table].table_name); return CE_Failure; } } /* -------------------------------------------------------------------- */ /* Process column names in order specs. */ /* -------------------------------------------------------------------- */ for( i = 0; i < order_specs; i++ ) { swq_order_def *def = order_defs + i; /* identify field */ def->field_index = swq_identify_field( def->field_name, field_list, NULL, &(def->table_index) ); if( def->field_index == -1 ) { CPLError( CE_Failure, CPLE_AppDefined, "Unrecognised field name %s in ORDER BY.", def->field_name ); return CE_Failure; } } /* -------------------------------------------------------------------- */ /* Post process the where clause, subbing in field indexes and */ /* doing final validation. */ /* -------------------------------------------------------------------- */ if( where_expr != NULL && where_expr->Check( field_list ) == SWQ_ERROR ) { return CE_Failure; } return CE_None; }
/******************************************************************************* * Copyright 2019-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. *******************************************************************************/ #include <memory> #include "common/dnnl_thread.hpp" #include "common/math_utils.hpp" #include "cpu/simple_q10n.hpp" #include "cpu/x64/jit_avx512_core_bf16cvt.hpp" #include "cpu/x64/jit_generator.hpp" #include "cpu/x64/jit_uni_eltwise_injector.hpp" #include "cpu/x64/jit_uni_depthwise_injector.hpp" #include "cpu/x64/jit_gemm_inner_product_utils.hpp" namespace dnnl { namespace impl { namespace cpu { namespace x64 { namespace inner_product_utils { using namespace dnnl::impl::cpu::inner_product_utils; using namespace Xbyak; template <cpu_isa_t isa, data_type_t acc_type, data_type_t dst_type> struct jit_pp_kernel_t : public pp_kernel_t<acc_type, dst_type>, public jit_generator { DECLARE_CPU_JIT_AUX_FUNCTIONS(inner_product_utils::jit_pp_kernel_t); jit_pp_kernel_t(size_t OC, size_t MB, const primitive_attr_t *attr, data_type_t bias_dt, bool skip_sum); ~jit_pp_kernel_t() { for (auto inj : jit_eltwise_injectors_) delete inj; jit_eltwise_injectors_.clear(); for (auto inj : jit_depthwise_injectors_) delete inj; jit_depthwise_injectors_.clear(); } using acc_data_t = typename prec_traits<acc_type>::type; using dst_data_t = typename prec_traits<dst_type>::type; void operator()(dst_data_t *dst, const acc_data_t *acc, const char *bias, const float *scales, size_t start, size_t end, size_t runtime_oc, const float *dst_zero_points) const override; status_t create_kernel() override { return jit_generator::create_kernel(); } private: void generate() override; void compute_oc_channel_blk(); void compute_mb_blk(); // vectorize across minibatch void copy_elems(const Xbyak::Reg64& dst, const Xbyak::Reg64& src, const Xbyak::Reg64& size, const int elemSize); void foreach(const Xbyak::Reg64& idx, size_t step, const Xbyak::Reg64& end, std::function<void(const Xbyak::Reg64&)> && fn); struct ker_args_t { dst_data_t *dst; const acc_data_t *acc; const char *bias; const float *scales; size_t oc; size_t len; size_t oc_offset; }; enum { default_OC_loop_unroll_ = 4 }; nstl::vector<jit_uni_eltwise_injector_f32<isa == avx512_core_bf16 ? avx512_common : isa> *> jit_eltwise_injectors_; nstl::vector<jit_uni_depthwise_injector_f32<isa == avx512_core_bf16 ? avx512_common : isa> *> jit_depthwise_injectors_; std::unique_ptr<bf16_emulation_t> bf16_emu_; using Vmm = typename cpu_isa_traits<isa == avx512_core_bf16 ? avx512_common : isa>::Vmm; const size_t vlen = cpu_isa_traits<isa == avx512_core_bf16 ? avx512_common : isa>::vlen / sizeof(float); Xbyak::Reg64 reg_param = abi_param1; Xbyak::Reg64 reg_dst = rdx; Xbyak::Reg64 reg_acc = rax; Xbyak::Reg64 reg_bias = rbx; Xbyak::Reg64 reg_scales = rsi; Xbyak::Reg64 reg_oc = r13; Xbyak::Reg64 reg_len = r8; Xbyak::Reg64 reg_tmp = rcx; // intentional for shifting purposes Xbyak::Reg64 reg_oc_offset = r9; Xbyak::Reg64 reg_rem_mask = r10; Xbyak::Opmask kreg_rem_mask = k1; // Will be assigned in constructor Vmm vreg_zero, vreg_scale; Xbyak::Zmm bf16_emu_reserv_1 = Xbyak::Zmm(28); Xbyak::Zmm bf16_emu_reserv_2 = Xbyak::Zmm(29); Xbyak::Zmm bf16_emu_reserv_3 = Xbyak::Zmm(30); Xbyak::Reg64 bf16_emu_reserv_4 = r12; Xbyak::Zmm bf16_emu_reserv_5 = Xbyak::Zmm(31); // sse42/avx2 Xbyak::Reg64 reg_ptr_maskmovdqu_dst = rdi; // sse41: store destination - must be rdi Xbyak::Reg8 reg_tmp_8 = r11b; Xbyak::Reg32 reg_tmp_32 = r11d; Xbyak::Reg64 reg_tmp_64 = r11; Xbyak::Label l_table; Xbyak::Reg64 reg_table = r12; Xbyak::Reg64 reg_shift_table = r13; Vmm vreg_mask = Vmm(0); // sse41: mask for blendvps must be in xmm0 Vmm vreg_store_mask = Vmm(1); // post_ops Xbyak::Reg64 eltwise_reserved_1_ = r11; Xbyak::Opmask eltwise_reserved_2_ = k2; Xbyak::Reg64 reg_d_weights = r14; Xbyak::Reg64 reg_d_bias = r15; // todo: reg_tmp_comp = r15 Vmm vreg_d_weights, vreg_d_bias; size_t bias_data_type_size_; int max_OC_loop_unroll_ = 13; int idx_compute_vreg_start_ = 0; int idx_compute_vreg_max_ = 31; int compute_vregs_per_iter_ = 1; int idx_vreg_dst(int iter) { int idx = idx_compute_vreg_start_ + iter * compute_vregs_per_iter_ + 0; assert(idx <= idx_compute_vreg_max_); return idx; } int idx_vreg_bias(int iter) { int idx = idx_compute_vreg_start_ + iter * compute_vregs_per_iter_ + 1; assert(idx <= idx_compute_vreg_max_); return idx; } Vmm vreg_dst(int iter) { return Vmm(idx_vreg_dst(iter)); }; Xbyak::Zmm zmm_dst(int iter) { return Xbyak::Zmm(idx_vreg_dst(iter)); }; Xbyak::Ymm ymm_dst(int iter) { return Xbyak::Ymm(idx_vreg_dst(iter)); }; Xbyak::Xmm xmm_dst(int iter) { return Xbyak::Xmm(idx_vreg_dst(iter)); }; Vmm vreg_bias(int iter) { return Vmm(idx_vreg_bias(iter)); }; }; template <cpu_isa_t isa, data_type_t acc_type, data_type_t dst_type> jit_pp_kernel_t<isa, acc_type, dst_type>::jit_pp_kernel_t(size_t OC, size_t MB, const primitive_attr_t *attr, data_type_t bias_dt, bool skip_sum) : pp_kernel_t<acc_type, dst_type>(OC, MB, attr, bias_dt, skip_sum) , bf16_emu_(nullptr) , bias_data_type_size_(0) , max_OC_loop_unroll_(utils::one_of(isa, avx512_core_bf16, avx512_common) ? 13 : 6) , idx_compute_vreg_start_(0) , idx_compute_vreg_max_(utils::one_of(isa, avx512_core_bf16, avx512_common) ? 31 : 15) , compute_vregs_per_iter_(1) { if (utils::one_of(isa, avx2, sse41)) { idx_compute_vreg_start_ += 2; // Vmm(0), Vmm(1) - for masks } if (this->do_scale_) vreg_scale = Zmm(idx_compute_vreg_start_++); bool only_eltwise = true; for (int i = 0; i < this->post_ops_.len(); i++) { auto &post_op = this->post_ops_.entry_[i]; if (post_op.is_eltwise()) { jit_eltwise_injectors_.push_back(new jit_uni_eltwise_injector_f32<isa == avx512_core_bf16 ? avx512_common : isa>( this, post_op.eltwise, true, eltwise_reserved_1_, eltwise_reserved_2_)); } else if (post_op.is_depthwise()) { only_eltwise = false; jit_depthwise_injectors_.push_back(new jit_uni_depthwise_injector_f32<isa == avx512_core_bf16 ? avx512_common : isa>( this, post_op.depthwise.alg, eltwise_reserved_2_)); } else { only_eltwise = false; } } if (this->post_ops_.len() > 0 && !only_eltwise) { vreg_d_weights = Vmm(idx_compute_vreg_max_--); vreg_d_bias = Vmm(idx_compute_vreg_max_--); } if (dst_type == data_type::u8 || utils::one_of(isa, avx2, sse41)) vreg_zero = Vmm(idx_compute_vreg_start_++); if (this->do_bias_) { compute_vregs_per_iter_++; bias_data_type_size_ = types::data_type_size(this->bias_data_type_); } if (dst_type == data_type::bf16 && isa != avx512_core_bf16) { idx_compute_vreg_max_ = 27; bf16_emu_.reset(new bf16_emulation_t(this, bf16_emu_reserv_1, bf16_emu_reserv_2, bf16_emu_reserv_3, bf16_emu_reserv_4, bf16_emu_reserv_5)); } int max_unroll = (idx_compute_vreg_max_ - idx_compute_vreg_start_ + 1) / compute_vregs_per_iter_; max_OC_loop_unroll_ = nstl::min(max_OC_loop_unroll_, max_unroll); } template <cpu_isa_t isa, data_type_t acc_type, data_type_t dst_type> void jit_pp_kernel_t<isa, acc_type, dst_type>::foreach(const Xbyak::Reg64& idx, size_t step, const Xbyak::Reg64& end, std::function<void(const Xbyak::Reg64&)> && fn) { Label loop, exit; L(loop); cmp(idx, end); jge(exit); fn(idx); add(idx, step); jmp(loop); L(exit); } template <cpu_isa_t isa, data_type_t acc_type, data_type_t dst_type> void jit_pp_kernel_t<isa, acc_type, dst_type>::copy_elems(const Xbyak::Reg64& dst, const Xbyak::Reg64& src, const Xbyak::Reg64& size, const int elemSize) { push(rsi); push(r13); xor_(rsi, rsi); if (elemSize == 1) { foreach(rsi, 1, size, [&, this](const Xbyak::Reg64& idx) { mov(r13b, byte[src + idx * elemSize]); mov(byte[dst + idx * elemSize], r13b); }); } else if (elemSize == 4) { foreach(rsi, 1, size, [&, this](const Xbyak::Reg64& idx) { mov(r13d, dword[src + idx * elemSize]); mov(dword[dst + idx * elemSize], r13d); }); } pop(r13); pop(rsi); } template <cpu_isa_t isa, data_type_t acc_type, data_type_t dst_type> void jit_pp_kernel_t<isa, acc_type, dst_type>::compute_oc_channel_blk() { bool do_post_ops = this->post_ops_.len() > 0; auto store_to_stack = [&](const Reg64 &from, const Reg64 &size) { sub(rsp, vlen * sizeof(float)); mov(r8, rsp); copy_elems(r8, from, size, sizeof(float)); }; auto load_from_stack = [&](const Vmm &to) { uni_vmovups(to, ptr[rsp]); add(rsp, vlen * sizeof(float)); }; auto apply_post_ops = [&](size_t offset, int idx, bool apply_mask) { int eltwise_inj_idx = 0; int depthwise_inj_idx = 0; for (int i = 0; i < this->post_ops_.len(); i++) { auto& post_op = this->post_ops_.entry_[i]; if (post_op.is_eltwise()) { jit_eltwise_injectors_[eltwise_inj_idx]->compute_vector(vreg_dst(idx).getIdx()); eltwise_inj_idx++; } else if (post_op.is_depthwise()) { mov(reg_d_weights, reinterpret_cast<size_t>(post_op.depthwise.weights_data + offset)); mov(reg_d_bias, reinterpret_cast<size_t>(post_op.depthwise.biases_data + offset)); lea(reg_d_weights, ptr[reg_d_weights + reg_oc_offset * sizeof(float)]); lea(reg_d_bias, ptr[reg_d_bias + reg_oc_offset * sizeof(float)]); if (apply_mask) { store_to_stack(reg_d_weights, reg_tmp); mov(reg_d_weights, rsp); if (post_op.depthwise.alg == dnnl_depthwise_scale_shift) { store_to_stack(reg_d_bias, reg_tmp); mov(reg_d_bias, rsp); } } jit_depthwise_injectors_[depthwise_inj_idx]->compute_vector_range(vreg_dst(idx).getIdx(), vreg_dst(idx).getIdx() + 1, reg_d_weights, reg_d_bias); if (apply_mask) { add(rsp, (post_op.depthwise.alg == dnnl_depthwise_scale_shift ? 2 : 1) * vlen * sizeof(float)); } depthwise_inj_idx++; } else if (post_op.is_quantization()) { bool do_dequantization = post_op.quantization.alg == alg_kind::quantization_quantize_dequantize; bool do_rounding = do_dequantization || dst_type == dnnl_f32 || i != this->post_ops_.len() - 1; auto vmm_masked_load = [&](const Vmm &vmm, const Reg64 &reg_from) { lea(reg_from, ptr[reg_from + reg_oc_offset * sizeof(float)]); store_to_stack(reg_from, reg_tmp); load_from_stack(vmm); }; if (post_op.quantization.crop_low_data->count_ != 1) { mov(reg_d_weights, reinterpret_cast<size_t>(post_op.quantization.crop_low_data->shifts_ + offset)); if (apply_mask) { vmm_masked_load(vreg_d_weights, reg_d_weights); } else { uni_vmovups(vreg_d_weights, ptr[reg_d_weights + reg_oc_offset * sizeof(float)]); } } else { mov(reg_d_weights, reinterpret_cast<size_t>(post_op.quantization.crop_low_data->shifts_)); uni_vbroadcastss(vreg_d_weights, ptr[reg_d_weights]); } if (post_op.quantization.crop_high_data->count_ != 1) { mov(reg_d_bias, reinterpret_cast<size_t>(post_op.quantization.crop_high_data->shifts_ + offset)); if (apply_mask) { vmm_masked_load(vreg_d_bias, reg_d_bias); } else { uni_vmovups(vreg_d_bias, ptr[reg_d_bias + reg_oc_offset * sizeof(float)]); } } else { mov(reg_d_bias, reinterpret_cast<size_t>(post_op.quantization.crop_high_data->shifts_)); uni_vbroadcastss(vreg_d_bias, ptr[reg_d_bias]); } uni_vmaxps(vreg_dst(idx), vreg_dst(idx), vreg_d_weights); uni_vminps(vreg_dst(idx), vreg_dst(idx), vreg_d_bias); if (post_op.quantization.input_scale_data->count_ != 1) { mov(reg_d_weights, reinterpret_cast<size_t>(post_op.quantization.input_scale_data->scales_ + offset)); if (apply_mask) { vmm_masked_load(vreg_d_weights, reg_d_weights); } else { uni_vmovups(vreg_d_weights, ptr[reg_d_weights + reg_oc_offset * sizeof(float)]); } } else { mov(reg_d_weights, reinterpret_cast<size_t>(post_op.quantization.input_scale_data->scales_)); uni_vbroadcastss(vreg_d_weights, ptr[reg_d_weights]); } if (post_op.quantization.input_shift_data->count_ != 1) { mov(reg_d_bias, reinterpret_cast<size_t>(post_op.quantization.input_shift_data->shifts_ + offset)); if (apply_mask) { vmm_masked_load(vreg_d_bias, reg_d_bias); } else { uni_vmovups(vreg_d_bias, ptr[reg_d_bias + reg_oc_offset * sizeof(float)]); } } else { mov(reg_d_bias, reinterpret_cast<size_t>(post_op.quantization.input_shift_data->shifts_)); uni_vbroadcastss(vreg_d_bias, ptr[reg_d_bias]); } uni_vfmadd213ps(vreg_dst(idx), vreg_d_weights, vreg_d_bias); if (do_rounding) uni_vroundps(vreg_dst(idx), vreg_dst(idx), 0); if (do_dequantization) { if (post_op.quantization.output_scale_data->count_ != 1) { mov(reg_d_weights, reinterpret_cast<size_t>(post_op.quantization.output_scale_data->scales_ + offset)); if (apply_mask) { vmm_masked_load(vreg_d_weights, reg_d_weights); } else { uni_vmovups(vreg_d_weights, ptr[reg_d_weights + reg_oc_offset * sizeof(float)]); } } else { mov(reg_d_weights, reinterpret_cast<size_t>(post_op.quantization.output_scale_data->scales_)); uni_vbroadcastss(vreg_d_weights, ptr[reg_d_weights]); } if (post_op.quantization.output_shift_data->count_ != 1) { mov(reg_d_bias, reinterpret_cast<size_t>(post_op.quantization.output_shift_data->shifts_ + offset)); if (apply_mask) { vmm_masked_load(vreg_d_bias, reg_d_bias); } else { uni_vmovups(vreg_d_bias, ptr[reg_d_bias + reg_oc_offset * sizeof(float)]); } } else { mov(reg_d_bias, reinterpret_cast<size_t>(post_op.quantization.output_shift_data->shifts_)); uni_vbroadcastss(vreg_d_bias, ptr[reg_d_bias]); } uni_vfmadd213ps(vreg_dst(idx), vreg_d_weights, vreg_d_bias); } } } }; // Load accumulated value, convert to float, apply bias (if any), scaling, // and eltwise (if any); then convert to destination type and store auto compute = [&](size_t offset, int idx, bool apply_mask) { if (apply_mask) { push(r8); } auto acc_addr = ptr[reg_acc + offset * sizeof(acc_data_t)]; if (dst_type == data_type::bf16 && isa != avx512_core_bf16) bf16_emu_->init_vcvtneps2bf16(); if (this->do_scale_ && this->scale_idx_mult_ == 1) { auto scale_addr = ptr[reg_scales + offset * sizeof(float)]; auto vreg_scale_msk_ = vreg_scale; if (utils::one_of(isa, avx512_core_bf16, avx512_common)) { if (apply_mask) vreg_scale_msk_ = vreg_scale_msk_ | kreg_rem_mask; uni_vmovups(vreg_scale_msk_, scale_addr); } else { if (apply_mask) { add(reg_scales, offset * sizeof(acc_data_t)); store_to_stack(reg_scales, reg_tmp); load_from_stack(vreg_scale); sub(reg_scales, offset * sizeof(acc_data_t)); } else { uni_vmovups(vreg_scale, scale_addr); } } } auto vreg_dst_ = vreg_dst(idx); if (utils::one_of(isa, avx512_core_bf16, avx512_common)) { if (apply_mask) vreg_dst_ = vreg_dst_ | kreg_rem_mask; switch (acc_type) { case data_type::s32: uni_vcvtdq2ps(vreg_dst_, acc_addr); break; case data_type::f32: uni_vmovups(vreg_dst_, acc_addr); break; } } else { if (apply_mask) { add(reg_acc, offset * sizeof(acc_data_t)); store_to_stack(reg_acc, reg_tmp); load_from_stack(vreg_dst_); sub(reg_acc, offset * sizeof(acc_data_t)); if (acc_type == data_type::s32) uni_vcvtdq2ps(vreg_dst_, vreg_dst_); } else { if (isa == sse41) { uni_vmovups(vreg_dst_, acc_addr); if (acc_type == data_type::s32) uni_vcvtdq2ps(vreg_dst_, vreg_dst_); } else { switch (acc_type) { case data_type::s32: uni_vcvtdq2ps(vreg_dst_, acc_addr); break; case data_type::f32: uni_vmovups(vreg_dst_, acc_addr); break; } } } } if (this->do_bias_) { auto bias_addr = ptr[reg_bias + offset * this->bias_data_type_size_]; auto vreg_bias_ = vreg_bias(idx); if (utils::one_of(isa, avx512_core_bf16, avx512_common) && apply_mask) vreg_bias_ = vreg_bias_ | kreg_rem_mask; if (!utils::one_of(isa, avx512_core_bf16, avx512_common) && apply_mask) { add(reg_bias, offset * this->bias_data_type_size_); store_to_stack(reg_bias, reg_tmp); load_from_stack(vreg_bias_); sub(reg_bias, offset * this->bias_data_type_size_); } else { switch (this->bias_data_type_) { case data_type::s8: uni_vpmovsxbd(vreg_bias_, bias_addr); break; case data_type::u8: uni_vpmovzxbd(vreg_bias_, bias_addr); break; case data_type::s32: case data_type::f32: uni_vmovups(vreg_bias_, bias_addr); break; case data_type::bf16: vpmovzxwd(vreg_bias_, bias_addr); vpslld(vreg_bias_, vreg_bias_, 0x10); break; default: assert(!"unimplemented"); } } if (utils::one_of(this->bias_data_type_, data_type::u8, data_type::s8, data_type::s32)) uni_vcvtdq2ps(vreg_bias_, vreg_bias_); uni_vaddps(vreg_dst_, vreg_dst_, vreg_bias_); } if (this->do_scale_) uni_vmulps(vreg_dst_, vreg_dst_, vreg_scale); apply_post_ops(offset, idx, apply_mask); if (dst_type == data_type::u8) uni_vmaxps(vreg_dst(idx), vreg_dst(idx), vreg_zero); if (utils::one_of(dst_type, data_type::s8, data_type::u8, data_type::s32)) { if (utils::one_of(isa, avx512_core_bf16, avx512_common)) { auto rmode_control = T_rn_sae; vcvtps2dq(vreg_dst(idx) | rmode_control, vreg_dst(idx)); } else { uni_vcvtps2dq(vreg_dst(idx), vreg_dst(idx)); } } else if (dst_type == data_type::bf16) { if (isa == avx512_core_bf16) vcvtneps2bf16(ymm_dst(idx), vreg_dst(idx)); else bf16_emu_->vcvtneps2bf16(ymm_dst(idx), zmm_dst(idx)); } auto dst_addr = ptr[reg_dst + offset * sizeof(dst_data_t)]; auto masked_store = [&]() { add(reg_dst, offset * sizeof(dst_data_t)); sub(rsp, vlen * sizeof(float)); mov(r8, rsp); uni_vmovups(ptr[r8], vreg_dst_); copy_elems(reg_dst, r8, reg_tmp, sizeof(dst_data_t)); add(rsp, vlen * sizeof(float)); sub(reg_dst, offset * sizeof(dst_data_t)); }; switch (dst_type) { case data_type::s8: if (utils::one_of(isa, avx512_core_bf16, avx512_common)) { vpmovsdb(dst_addr, vreg_dst_); } else { uni_vpackssdw(vreg_dst_, vreg_dst_, vreg_dst_); if (isa != sse41) vpermq(ymm_dst(idx), ymm_dst(idx), 0x08); uni_vpacksswb(vreg_dst_, vreg_dst_, vreg_dst_); if (apply_mask) { masked_store(); } else { if (isa != sse41) { vmovq(dst_addr, xmm_dst(idx)); } else { movd(dst_addr, xmm_dst(idx)); } } } break; case data_type::u8: if (utils::one_of(isa, avx512_core_bf16, avx512_common)) { vpmovusdb(dst_addr, vreg_dst_); } else { uni_vpackusdw(vreg_dst_, vreg_dst_, vreg_dst_); if (isa != sse41) vpermq(ymm_dst(idx), ymm_dst(idx), 0x08); uni_vpackuswb(vreg_dst_, vreg_dst_, vreg_dst_); if (apply_mask) { masked_store(); } else { if (isa != sse41) { vmovq(dst_addr, xmm_dst(idx)); } else { movd(dst_addr, xmm_dst(idx)); } } } break; case data_type::f32: case data_type::s32: if (utils::one_of(isa, avx512_core_bf16, avx512_common)) { uni_vmovups(dst_addr, vreg_dst_); } else { if (apply_mask) { if (isa != sse41) { vmaskmovps(dst_addr, vreg_mask, vreg_dst_); } else { masked_store(); } } else { uni_vmovups(dst_addr, vreg_dst_); } } break; case data_type::bf16: vmovdqu16(dst_addr, apply_mask ? ymm_dst(idx) | kreg_rem_mask : ymm_dst(idx)); break; default: assert(!"unimplemented"); } if (apply_mask) { pop(r8); } }; // Advance all pointers by an immediate auto advance_ptrs_imm = [&](size_t offset) { add(reg_dst, offset * sizeof(dst_data_t)); add(reg_acc, offset * sizeof(acc_data_t)); if (this->do_scale_ && this->scale_idx_mult_ == 1) add(reg_scales, offset * sizeof(float)); if (this->do_bias()) add(reg_bias, offset * this->bias_data_type_size_); if (do_post_ops) add(reg_oc_offset, offset); }; // Advance all pointers by a value stored in a register auto advance_ptrs_reg = [&](Reg64 offset) { lea(reg_dst, ptr[reg_dst + offset * sizeof(dst_data_t)]); lea(reg_acc, ptr[reg_acc + offset * sizeof(acc_data_t)]); if (this->do_scale_ && this->scale_idx_mult_ == 1) lea(reg_scales, ptr[reg_scales + offset * sizeof(float)]); if (this->do_bias()) lea(reg_bias, ptr[reg_bias + offset * this->bias_data_type_size_]); if (do_post_ops) lea(reg_oc_offset, ptr[reg_oc_offset + offset]); }; // Rewind pointers that point to data that is indexed by output channel // (bias or per-oc scaling factors) auto rewind_ptrs = [&]() { neg(reg_oc); if (do_post_ops) lea(reg_oc_offset, ptr[reg_oc_offset + reg_oc]); if (this->do_bias_) lea(reg_bias, ptr[reg_bias + reg_oc * this->bias_data_type_size_]); if (this->do_scale_ && this->scale_idx_mult_ == 1) lea(reg_scales, ptr[reg_scales + reg_oc * sizeof(float)]); neg(reg_oc); }; // Process one row of reg_tmp elements auto process_runtime_oc = [&]() { Label l_loop, l_loop_tail, l_loop_end; cmp(reg_tmp, vlen); jl(l_loop_tail, T_NEAR); // Skips for reg_tmp == 16 too (?) L(l_loop); { compute(0, 0, false); advance_ptrs_imm(vlen); sub(reg_tmp, vlen); cmp(reg_tmp, vlen); jge(l_loop, T_NEAR); } cmp(reg_tmp, 0); je(l_loop_end, T_NEAR); L(l_loop_tail); if (utils::one_of(isa, avx512_core_bf16, avx512_common)) { mov(reg_rem_mask, 1); shl(reg_rem_mask, cl); // cl == reg_tmp because reg_tmp <= vlen here sub(reg_rem_mask, 1); jz(l_loop_end, T_NEAR); kmovq(kreg_rem_mask, reg_rem_mask); } else { push(reg_oc); mov(reg_shift_table, vlen); sub(reg_shift_table, reg_tmp); uni_vmovups(vreg_mask, ptr[reg_table + reg_shift_table * sizeof(float)]); if (dst_type == data_type::s8 || dst_type == data_type::u8) { mov(reg_shift_table, vlen * sizeof(float)); sub(reg_shift_table, reg_tmp); uni_vmovups(vreg_store_mask, ptr[reg_table + reg_shift_table]); } pop(reg_oc); } compute(0, 0, true); advance_ptrs_reg(reg_tmp); L(l_loop_end); }; // <-------------------- OC -------------------------------> // // ^ +....................+----------------------------------+ // | : not accessed | Prologue loop | // | +--------------------+----------------------------------+ // | | // M | Main loop (unrolled) | // B | | // +--------------------------------+----------------------+ // | | Epilogue loop | not accessed : // v +--------------------------------+......................+ // Prologue loop Label l_prologue_end; cmp(reg_oc_offset, 0); je(l_prologue_end, T_NEAR); { mov(reg_tmp, reg_oc); sub(reg_tmp, reg_oc_offset); cmp(reg_tmp, reg_len); cmovg(reg_tmp, reg_len); sub(reg_len, reg_tmp); process_runtime_oc(); rewind_ptrs(); } L(l_prologue_end); // Main loop Label l_main_loop_end; cmp(reg_len, reg_oc); jl(l_main_loop_end, T_NEAR); if (this->runtime_oc()) { // todo: antonvor: do we support this case? Label l_main_loop; L(l_main_loop); { mov(reg_tmp, reg_oc); process_runtime_oc(); rewind_ptrs(); sub(reg_len, reg_oc); cmp(reg_len, reg_oc); jge(l_main_loop, T_NEAR); } } else { size_t OC_loop, OC_tail; if (this->OC_ < max_OC_loop_unroll_ * vlen) { // Fully unroll small loops OC_loop = 0; OC_tail = this->OC_; } else { OC_loop = vlen * default_OC_loop_unroll_; OC_tail = this->OC_ % OC_loop; } assert(!!OC_loop || !!OC_tail); if (OC_tail % vlen) { int vlen_tail = OC_tail % vlen; if (utils::one_of(isa, avx512_core_bf16, avx512_common)) { unsigned tail_mask = (1 << vlen_tail) - 1; mov(reg_tmp, tail_mask); kmovq(kreg_rem_mask, reg_tmp); } else { push(reg_oc); mov(reg_shift_table, vlen - vlen_tail); uni_vmovups(vreg_mask, ptr[reg_table + reg_shift_table * sizeof(float)]); if (dst_type == data_type::s8 || dst_type == data_type::u8) { mov(reg_shift_table, vlen * sizeof(float)); sub(reg_shift_table, vlen_tail); uni_vmovups(vreg_store_mask, ptr[reg_table + reg_shift_table]); } pop(reg_oc); } } Label l_main_loop; L(l_main_loop); { if (OC_loop) { mov(reg_tmp, utils::rnd_dn(this->OC_, OC_loop)); Label l_oc_loop; L(l_oc_loop); { for (size_t offset = 0; offset < OC_loop; offset += vlen) compute(offset, offset / vlen, false); advance_ptrs_imm(OC_loop); sub(reg_tmp, OC_loop); jnz(l_oc_loop); } } if (OC_tail) { for (size_t offset = 0; offset < OC_tail; offset += vlen) { bool use_mask = (offset + vlen) > OC_tail; if (use_mask) { push(reg_tmp); mov(reg_tmp, this->OC_ % vlen); } compute(offset, offset / vlen, use_mask); if (use_mask) { pop(reg_tmp); } } advance_ptrs_imm(OC_tail); } rewind_ptrs(); sub(reg_len, reg_oc); cmp(reg_len, reg_oc); jge(l_main_loop, T_NEAR); } } L(l_main_loop_end); // Epilogue loop Label l_epilogue_end; cmp(reg_len, 0); je(l_epilogue_end, T_NEAR); { mov(reg_tmp, reg_len); process_runtime_oc(); } L(l_epilogue_end); } template <cpu_isa_t isa, data_type_t acc_type, data_type_t dst_type> void jit_pp_kernel_t<isa, acc_type, dst_type>::compute_mb_blk() { auto compute = [&](size_t mb_step, bool apply_mask) { auto zmm_bias = vreg_bias(0); auto zmm_bias_msk = apply_mask ? zmm_bias | kreg_rem_mask : zmm_bias; auto zmm_dst = vreg_dst(0); auto zmm_dst_msk = apply_mask ? zmm_dst | kreg_rem_mask : zmm_dst; switch (acc_type) { case data_type::s32: vcvtdq2ps(zmm_dst_msk, ptr[reg_acc]); break; case data_type::f32: vmovups(zmm_dst_msk, ptr[reg_acc]); break; default: assert(!"unimplemented"); } vaddps(zmm_dst, zmm_dst, zmm_bias_msk); switch (dst_type) { case data_type::f32: break; case data_type::u8: case data_type::s8: case data_type::s32: vcvtps2dq(zmm_dst, zmm_dst); break; case data_type::bf16: if (isa == avx512_core_bf16) vcvtneps2bf16(Ymm(zmm_dst.getIdx()), zmm_dst); else bf16_emu_->vcvtneps2bf16(Ymm(zmm_dst.getIdx()), Zmm(zmm_dst.getIdx())); break; default: assert(!"unimplemented"); } switch (dst_type) { case data_type::s8: vpmovsdb(ptr[reg_dst], zmm_dst_msk); break; case data_type::u8: vpmovusdb(ptr[reg_dst], zmm_dst_msk); break; case data_type::f32: case data_type::s32: vmovups(ptr[reg_dst], zmm_dst_msk); break; case data_type::bf16: vmovdqu16(ptr[reg_dst], apply_mask ? Ymm(zmm_dst.getIdx()) | kreg_rem_mask : Ymm(zmm_dst.getIdx())); break; default: assert(!"unimplemented"); } }; Label mb_main_loop, end_main_loop; bool expl_broadcast = this->OC_ == 1 && utils::one_of( this->bias_data_type_, data_type::s32, data_type::f32); size_t mb_step = vlen / this->OC_; size_t mb_tail = this->MB_ % mb_step; size_t mb_oc_blk = mb_step * this->OC_; auto zmm_bias = vreg_bias(0); if (dst_type == data_type::bf16 && isa != avx512_core_bf16) bf16_emu_->init_vcvtneps2bf16(); if (expl_broadcast) { // when OC == 1 bias can be loaded directly into simd switch (this->bias_data_type_) { case data_type::s32: vpbroadcastd(zmm_bias, ptr[reg_bias]); break; case data_type::f32: vbroadcastss(zmm_bias, ptr[reg_bias]); break; // TODO: enable broadcast for other data types default: assert(!"unimplemented"); } } else { // prepare bias data for simd computation mov(reg_tmp, (1 << this->OC_) - 1); kmovq(kreg_rem_mask, reg_tmp); auto zmm_bias_msk = zmm_bias | kreg_rem_mask; switch (this->bias_data_type_) { case data_type::s8: vpmovsxbd(zmm_bias_msk, ptr[reg_bias]); break; case data_type::u8: vpmovzxbd(zmm_bias_msk, ptr[reg_bias]); break; case data_type::s32: case data_type::f32: vmovups(zmm_bias_msk, ptr[reg_bias]); break; case data_type::bf16: vpmovzxwd(zmm_bias_msk, ptr[reg_bias]); vpslld(zmm_bias_msk, zmm_bias_msk, 0x10); break; default: assert(!"unimplemented"); } // write repeated MB*OC entries into stack sub(rsp, mb_oc_blk * sizeof(uint32_t)); for (size_t i = 0; i < mb_step; ++i) { vmovups(ptr[rsp + i * this->OC_ * sizeof(uint32_t)], zmm_bias_msk); } // load into simd mov(reg_tmp, (1 << mb_oc_blk) - 1); kmovq(kreg_rem_mask, reg_tmp); vmovups(zmm_bias | kreg_rem_mask, ptr[rsp]); } if (utils::one_of(this->bias_data_type_, data_type::u8, data_type::s8, data_type::s32)) vcvtdq2ps(zmm_bias, zmm_bias); L(mb_main_loop); { cmp(reg_len, mb_oc_blk); jl(end_main_loop, T_NEAR); compute(mb_step, !expl_broadcast); add(reg_dst, mb_oc_blk * sizeof(dst_data_t)); add(reg_acc, mb_oc_blk * sizeof(acc_data_t)); sub(reg_len, mb_oc_blk); jmp(mb_main_loop, T_NEAR); } L(end_main_loop); if (mb_tail > 0) { Label mb_tail_loop, end_tail_loop; mov(reg_tmp, (1 << (mb_tail * this->OC_)) - 1); kmovq(kreg_rem_mask, reg_tmp); L(mb_tail_loop); { cmp(reg_len, 0); jle(end_tail_loop, T_NEAR); compute(mb_tail, true); sub(reg_len, mb_tail * this->OC_); jmp(mb_tail_loop, T_NEAR); } L(end_tail_loop); } if (!expl_broadcast) add(rsp, mb_oc_blk * sizeof(uint32_t)); } template <cpu_isa_t isa, data_type_t acc_type, data_type_t dst_type> void jit_pp_kernel_t<isa, acc_type, dst_type>::generate() { preamble(); #define PARAM_OFF(x) offsetof(ker_args_t, x) mov(reg_dst, ptr[reg_param + PARAM_OFF(dst)]); mov(reg_acc, ptr[reg_param + PARAM_OFF(acc)]); mov(reg_bias, ptr[reg_param + PARAM_OFF(bias)]); if (this->do_scale_) mov(reg_scales, ptr[reg_param + PARAM_OFF(scales)]); if (this->runtime_oc()) // todo: antonvor: do we support this case? mov(reg_oc, ptr[reg_param + PARAM_OFF(oc)]); else mov(reg_oc, this->OC_); mov(reg_len, ptr[reg_param + PARAM_OFF(len)]); mov(reg_oc_offset, ptr[reg_param + PARAM_OFF(oc_offset)]); if (this->do_scale_ && this->scale_idx_mult_ == 0) uni_vbroadcastss(vreg_scale, dword[reg_scales]); #undef PARAM_OFF if (dst_type == data_type::u8 || utils::one_of(isa, avx2, sse41)) uni_vpxor(vreg_zero, vreg_zero, vreg_zero); if (utils::one_of(isa, avx2, sse41)) mov(reg_table, l_table); // at least 2 blocks of mb within vlen bool dim_restrict = !this->runtime_oc() && !this->runtime_mb() && (this->OC_ <= vlen / 2) && (this->MB_ >= vlen); bool supported_postops = this->do_scale_ || (this->post_ops_.len() > 0); if (this->do_bias() && !supported_postops && dim_restrict && !utils::one_of(isa, avx2, sse41)) { this->mb_blk_kernel_ = true; compute_mb_blk(); } else { compute_oc_channel_blk(); } postamble(); for (auto& inj : jit_eltwise_injectors_) inj->prepare_table(); if (utils::one_of(isa, avx2, sse41)) { align(64); L(l_table); for (size_t i = 0; i < vlen; i++) dd(0xFFFFFFFF); for (size_t i = 0; i < vlen; i++) dd(0x00000000); } } template <cpu_isa_t isa, data_type_t acc_type, data_type_t dst_type> void jit_pp_kernel_t<isa, acc_type, dst_type>::operator()(dst_data_t *dst, const acc_data_t *acc, const char *bias, const float *scales, size_t start, size_t end, size_t runtime_oc, const float *dst_zero_points) const { if (end <= start) return; const size_t OC = this->runtime_oc() ? runtime_oc : this->OC_; ker_args_t args; size_t oc_offset = start % OC; args.dst = dst + start; args.acc = acc + start; args.bias = bias + oc_offset * this->bias_data_type_size_; args.scales = scales + this->scale_idx_mult_ * oc_offset; args.oc = OC; args.len = end - start; args.oc_offset = oc_offset; jit_generator::operator()(&args); } template <data_type_t acc_type, data_type_t dst_type> pp_kernel_t<acc_type, dst_type> *jit_pp_kernel_create(size_t OC, size_t MB, const primitive_attr_t *attr, data_type_t bias_dt, bool skip_sum) { if (mayiuse(avx512_common)) { return new jit_pp_kernel_t<avx512_common, acc_type, dst_type>(OC, MB, attr, bias_dt, skip_sum); } else if (mayiuse(avx2)) { return new jit_pp_kernel_t<avx2, acc_type, dst_type>(OC, MB, attr, bias_dt, skip_sum); } else if (mayiuse(sse41)) { return new jit_pp_kernel_t<sse41, acc_type, dst_type>(OC, MB, attr, bias_dt, skip_sum); } return nullptr; } #define INST(acc_type, dst_type) \ template pp_kernel_t<acc_type, dst_type> * \ jit_pp_kernel_create<acc_type, dst_type>(size_t OC, size_t MB, \ const primitive_attr_t *attr, data_type_t bias_dt, bool skip_sum); using namespace data_type; INST(f32, f32); INST(s32, f32); INST(s32, s32); INST(s32, s8); INST(s32, u8); INST(f32, bf16); #undef INST } // namespace inner_product_utils } // namespace x64 } // namespace cpu } // namespace impl } // namespace dnnl
// (C) Copyright John Maddock 2001. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/config for most recent version. // MACRO: BOOST_HAS_MACRO_USE_FACET // TITLE: macro version of use_facet: _USE // DESCRIPTION: The standard library lacks a conforming std::use_facet, // but has a macro _USE(loc, Type) that does the job. // This is primarily for the Dinkumware std lib. #include <locale> #ifndef _USE #error "macro _USE not defined" #endif namespace boost_has_macro_use_facet{ int test() { std::locale l; const std::ctype<char>& ct = std::_USE(l, std::ctype<char>); return 0; } }
#include "UnrealEnginePythonPrivatePCH.h" #include "Runtime/LevelSequence/Public/LevelSequenceActor.h" #include "Runtime/LevelSequence/Public/LevelSequence.h" #include "PythonComponent.h" #include "UEPyObject.h" PyObject *py_ue_actor_has_tag(ue_PyUObject * self, PyObject * args) { ue_py_check(self); char *tag; if (!PyArg_ParseTuple(args, "s:actor_has_tag", &tag)) { return NULL; } if (!self->ue_object->IsA<AActor>()) { return PyErr_Format(PyExc_Exception, "uobject is not an AActor"); } AActor *actor = (AActor *)self->ue_object; if (actor->ActorHasTag(FName(UTF8_TO_TCHAR(tag)))) { Py_INCREF(Py_True); return Py_True; } Py_INCREF(Py_False); return Py_False; } PyObject *py_ue_actor_begin_play(ue_PyUObject * self, PyObject * args) { ue_py_check(self); AActor *actor = ue_py_check_type<AActor>(self); if (!actor) return PyErr_Format(PyExc_Exception, "uobject is not an AActor"); #if ENGINE_MINOR_VERSION > 14 actor->DispatchBeginPlay(); #else actor->BeginPlay(); #endif Py_RETURN_NONE; } PyObject *py_ue_get_actor_bounds(ue_PyUObject * self, PyObject * args) { ue_py_check(self); if (!self->ue_object->IsA<AActor>()) { return PyErr_Format(PyExc_Exception, "uobject is not an AActor"); } AActor *actor = (AActor *)self->ue_object; FVector origin; FVector extent; actor->GetActorBounds(false, origin, extent); return Py_BuildValue("OO", py_ue_new_fvector(origin), py_ue_new_fvector(extent)); } PyObject *py_ue_get_actor_component(ue_PyUObject * self, PyObject * args) { ue_py_check(self); AActor *actor = ue_get_actor(self); if (!actor) return PyErr_Format(PyExc_Exception, "cannot retrieve Actor from uobject"); char *name; if (!PyArg_ParseTuple(args, "s:get_actor_component", &name)) { return NULL; } for (UActorComponent *component : actor->GetComponents()) { if (component->GetName().Equals(UTF8_TO_TCHAR(name))) { Py_RETURN_UOBJECT(component); } } Py_RETURN_NONE; } PyObject *py_ue_actor_destroy_component(ue_PyUObject * self, PyObject * args) { ue_py_check(self); AActor *actor = ue_get_actor(self); if (!actor) return PyErr_Format(PyExc_Exception, "cannot retrieve Actor from uobject"); PyObject *py_component; if (!PyArg_ParseTuple(args, "O:actor_destroy_component", &py_component)) { return NULL; } UActorComponent *component = ue_py_check_type<UActorComponent>(py_component); if (!component) return PyErr_Format(PyExc_Exception, "argument is not a UActorComponent"); #if ENGINE_MINOR_VERSION >= 17 component->DestroyComponent(); #else actor->K2_DestroyComponent(component); #endif Py_INCREF(Py_None); return Py_None; } PyObject *py_ue_actor_destroy(ue_PyUObject * self, PyObject * args) { ue_py_check(self); AActor *actor = ue_py_check_type<AActor>(self); if (!actor) { return PyErr_Format(PyExc_Exception, "uobject is not an AActor"); } actor->Destroy(); Py_RETURN_NONE; } PyObject *py_ue_actor_components(ue_PyUObject * self, PyObject * args) { ue_py_check(self); AActor *actor = ue_get_actor(self); if (!actor) return PyErr_Format(PyExc_Exception, "cannot retrieve Actor from uobject"); PyObject *ret = PyList_New(0); for (UActorComponent *component : actor->GetComponents()) { ue_PyUObject *py_obj = ue_get_python_uobject(component); if (!py_obj) continue; PyList_Append(ret, (PyObject *)py_obj); } return ret; } PyObject *py_ue_get_actor_velocity(ue_PyUObject *self, PyObject * args) { ue_py_check(self); AActor *actor = ue_get_actor(self); if (!actor) return PyErr_Format(PyExc_Exception, "uobject is not an actor or a component"); return py_ue_new_fvector(actor->GetVelocity()); } #if WITH_EDITOR PyObject *py_ue_get_actor_label(ue_PyUObject *self, PyObject * args) { ue_py_check(self); if (self->ue_object->IsA<AActor>()) { AActor *actor = (AActor *)self->ue_object; return PyUnicode_FromString(TCHAR_TO_UTF8(*(actor->GetActorLabel()))); } if (self->ue_object->IsA<UActorComponent>()) { UActorComponent *component = (UActorComponent *)self->ue_object; return PyUnicode_FromString(TCHAR_TO_UTF8(*(component->GetOwner()->GetActorLabel()))); } return PyErr_Format(PyExc_Exception, "uobject is not an actor or a component"); } PyObject *py_ue_set_actor_label(ue_PyUObject *self, PyObject * args) { ue_py_check(self); AActor *actor = ue_get_actor(self); if (!actor) return PyErr_Format(PyExc_Exception, "cannot retrieve Actor from uobject"); char *label; if (!PyArg_ParseTuple(args, "s:set_actor_label", &label)) { return NULL; } actor->SetActorLabel(UTF8_TO_TCHAR(label), true); Py_INCREF(Py_None); return Py_None; } PyObject *py_ue_find_actor_by_label(ue_PyUObject * self, PyObject * args) { ue_py_check(self); char *name; if (!PyArg_ParseTuple(args, "s:find_actor_by_label", &name)) { return NULL; } UWorld *world = ue_get_uworld(self); if (!world) return PyErr_Format(PyExc_Exception, "unable to retrieve UWorld from uobject"); UObject *u_object = nullptr; for (TActorIterator<AActor> Itr(world); Itr; ++Itr) { AActor *u_obj = *Itr; if (u_obj->GetActorLabel().Equals(UTF8_TO_TCHAR(name))) { u_object = u_obj; break; } } if (u_object) { Py_RETURN_UOBJECT(u_object); } Py_RETURN_NONE; } #endif PyObject *py_ue_get_owner(ue_PyUObject *self, PyObject * args) { ue_py_check(self); UActorComponent *component = ue_py_check_type<UActorComponent>(self); if (!component) return PyErr_Format(PyExc_Exception, "uobject is not a component"); Py_RETURN_UOBJECT(component->GetOwner()); } PyObject *py_ue_register_component(ue_PyUObject *self, PyObject * args) { ue_py_check(self); if (!self->ue_object->IsA<UActorComponent>()) { return PyErr_Format(PyExc_Exception, "uobject is not a component"); } UActorComponent *component = (UActorComponent *)self->ue_object; if (!component->IsRegistered()) component->RegisterComponent(); Py_INCREF(Py_None); return Py_None; } PyObject *py_ue_component_is_registered(ue_PyUObject *self, PyObject * args) { ue_py_check(self); if (!self->ue_object->IsA<UActorComponent>()) { return PyErr_Format(PyExc_Exception, "uobject is not a component"); } UActorComponent *component = (UActorComponent *)self->ue_object; if (component->IsRegistered()) { Py_INCREF(Py_True); return Py_True; } Py_INCREF(Py_False); return Py_False; } PyObject *py_ue_setup_attachment(ue_PyUObject *self, PyObject * args) { ue_py_check(self); PyObject *py_component; if (!PyArg_ParseTuple(args, "O:setup_attachment", &py_component)) return nullptr; USceneComponent *child = ue_py_check_type<USceneComponent>(self); if (!child) { return PyErr_Format(PyExc_Exception, "uobject is not a USceneComponent"); } UActorComponent *parent = ue_py_check_type<UActorComponent>(py_component); Py_RETURN_NONE; } PyObject *py_ue_unregister_component(ue_PyUObject * self, PyObject * args) { ue_py_check(self); UActorComponent *component = ue_py_check_type<UActorComponent>(self); if (!component) return PyErr_Format(PyExc_Exception, "uobject is not an UActorComponent"); if (component->IsRegistered()) component->UnregisterComponent(); Py_RETURN_NONE; } PyObject *py_ue_destroy_component(ue_PyUObject * self, PyObject * args) { ue_py_check(self); UActorComponent *component = ue_py_check_type<UActorComponent>(self); if (!component) return PyErr_Format(PyExc_Exception, "uobject is not an UActorComponent"); component->DestroyComponent(); Py_RETURN_NONE; } PyObject *py_ue_add_instance_component(ue_PyUObject * self, PyObject * args) { ue_py_check(self); PyObject *py_component; if (!PyArg_ParseTuple(args, "O:add_instance_component", &py_component)) { return nullptr; } AActor *actor = ue_py_check_type<AActor>(self); if (!actor) { return PyErr_Format(PyExc_Exception, "uobject is not an AActor"); } UActorComponent *component = ue_py_check_type<UActorComponent>(py_component); if (!component) { return PyErr_Format(PyExc_Exception, "argument is not a UActorComponent"); } actor->AddInstanceComponent(component); Py_RETURN_NONE; } PyObject *py_ue_add_actor_component(ue_PyUObject * self, PyObject * args) { ue_py_check(self); PyObject *obj; char *name; PyObject *py_parent = nullptr; if (!PyArg_ParseTuple(args, "Os|O:add_actor_component", &obj, &name, &py_parent)) { return NULL; } if (!self->ue_object->IsA<AActor>()) { return PyErr_Format(PyExc_Exception, "uobject is not an AActor"); } AActor *actor = (AActor *)self->ue_object; if (!ue_is_pyuobject(obj)) { return PyErr_Format(PyExc_Exception, "argument is not a UObject"); } ue_PyUObject *py_obj = (ue_PyUObject *)obj; if (!py_obj->ue_object->IsA<UClass>()) { return PyErr_Format(PyExc_Exception, "argument is not a UClass"); } UClass *u_class = (UClass *)py_obj->ue_object; if (!u_class->IsChildOf<UActorComponent>()) { return PyErr_Format(PyExc_Exception, "argument is not a UClass derived from UActorComponent"); } USceneComponent *parent_component = nullptr; if (py_parent) { parent_component = ue_py_check_type<USceneComponent>(py_parent); if (!parent_component) { return PyErr_Format(PyExc_Exception, "argument is not a USceneComponent"); } } UActorComponent *component = NewObject<UActorComponent>(actor, u_class, FName(UTF8_TO_TCHAR(name)), RF_Public); if (!component) return PyErr_Format(PyExc_Exception, "unable to create component"); if (py_parent && component->IsA<USceneComponent>()) { USceneComponent *scene_component = (USceneComponent *)component; scene_component->SetupAttachment(parent_component); } if (actor->GetWorld() && !component->IsRegistered()) { component->RegisterComponent(); } if (component->bWantsInitializeComponent && !component->HasBeenInitialized() && component->IsRegistered()) component->InitializeComponent(); Py_RETURN_UOBJECT(component); } PyObject *py_ue_add_python_component(ue_PyUObject * self, PyObject * args) { ue_py_check(self); char *name; char *module_name; char *class_name; if (!PyArg_ParseTuple(args, "sss:add_python_component", &name, &module_name, &class_name)) { return NULL; } AActor *actor = ue_py_check_type<AActor >(self); if (!actor) { return PyErr_Format(PyExc_Exception, "uobject is not an AActor"); } UPythonComponent *component = NewObject<UPythonComponent>(actor, FName(UTF8_TO_TCHAR(name)), RF_Public); if (!component) return PyErr_Format(PyExc_Exception, "unable to create component"); component->PythonModule = FString(UTF8_TO_TCHAR(module_name)); component->PythonClass = FString(UTF8_TO_TCHAR(class_name)); if (actor->GetWorld() && !component->IsRegistered()) { component->RegisterComponent(); } if (component->bWantsInitializeComponent && !component->HasBeenInitialized() && component->IsRegistered()) component->InitializeComponent(); Py_RETURN_UOBJECT(component); } PyObject *py_ue_actor_create_default_subobject(ue_PyUObject * self, PyObject * args) { ue_py_check(self); PyObject *obj; char *name; if (!PyArg_ParseTuple(args, "Os:actor_create_default_subobject", &obj, &name)) { return NULL; } AActor *actor = ue_py_check_type<AActor>(self); if (!actor) return PyErr_Format(PyExc_Exception, "uobject is not an AActor"); UClass *u_class = ue_py_check_type<UClass>(obj); if (!u_class) return PyErr_Format(PyExc_Exception, "argument is not a UClass"); if (!FUObjectThreadContext::Get().TopInitializer()) return PyErr_Format(PyExc_Exception, "CreateDefaultSubobject() can be called only in a constructor"); UObject *ret_obj = actor->CreateDefaultSubobject(FName(UTF8_TO_TCHAR(name)), UObject::StaticClass(), u_class, false, false, true); if (!ret_obj) return PyErr_Format(PyExc_Exception, "unable to create component"); Py_RETURN_UOBJECT(ret_obj); } PyObject *py_ue_get_actor_root_component(ue_PyUObject * self, PyObject * args) { ue_py_check(self); AActor *actor = ue_get_actor(self); if (!actor) return PyErr_Format(PyExc_Exception, "cannot retrieve Actor from uobject"); UActorComponent *component = actor->GetRootComponent(); if (component) { Py_RETURN_UOBJECT(component); } Py_RETURN_NONE; } PyObject *py_ue_add_actor_root_component(ue_PyUObject * self, PyObject * args) { ue_py_check(self); PyObject *obj; char *name; if (!PyArg_ParseTuple(args, "Os:add_actor_root_component", &obj, &name)) { return NULL; } if (!self->ue_object->IsA<AActor>()) { return PyErr_Format(PyExc_Exception, "uobject is not an AActor"); } AActor *actor = (AActor *)self->ue_object; if (!ue_is_pyuobject(obj)) { return PyErr_Format(PyExc_Exception, "argument is not a UObject"); } ue_PyUObject *py_obj = (ue_PyUObject *)obj; if (!py_obj->ue_object->IsA<UClass>()) { return PyErr_Format(PyExc_Exception, "argument is not a class"); } USceneComponent *component = NewObject<USceneComponent>(actor, (UClass *)py_obj->ue_object, FName(UTF8_TO_TCHAR(name)), RF_Public); if (!component) return PyErr_Format(PyExc_Exception, "unable to create component"); actor->SetRootComponent(component); if (actor->GetWorld() && !component->IsRegistered()) { component->RegisterComponent(); } if (component->bWantsInitializeComponent && !component->HasBeenInitialized() && component->IsRegistered()) component->InitializeComponent(); Py_RETURN_UOBJECT(component); } PyObject *py_ue_actor_has_component_of_type(ue_PyUObject * self, PyObject * args) { ue_py_check(self); PyObject *obj; if (!PyArg_ParseTuple(args, "O:actor_has_component_of_type", &obj)) { return NULL; } if (!ue_is_pyuobject(obj)) { return PyErr_Format(PyExc_Exception, "argument is not a UObject"); } ue_PyUObject *py_obj = (ue_PyUObject *)obj; if (!self->ue_object->IsA<AActor>()) { return PyErr_Format(PyExc_Exception, "uobject is not an AActor"); } AActor *actor = (AActor *)self->ue_object; if (actor->GetComponentByClass((UClass *)py_obj->ue_object)) { Py_INCREF(Py_True); return Py_True; } Py_INCREF(Py_False); return Py_False; } PyObject *py_ue_get_actor_component_by_type(ue_PyUObject * self, PyObject * args) { ue_py_check(self); PyObject *obj; if (!PyArg_ParseTuple(args, "O:get_actor_component_by_type", &obj)) { return NULL; } ue_PyUObject *py_obj = nullptr; if (ue_is_pyuobject(obj)) { py_obj = (ue_PyUObject *)obj; } // shortcut for finding class by string else if (PyUnicodeOrString_Check(obj)) { char *class_name = PyUnicode_AsUTF8(obj); UClass *u_class = FindObject<UClass>(ANY_PACKAGE, UTF8_TO_TCHAR(class_name)); if (u_class) { py_obj = ue_get_python_uobject(u_class); } } if (!py_obj) return PyErr_Format(PyExc_Exception, "argument is not a UObject"); AActor *actor = ue_get_actor(self); if (!actor) return PyErr_Format(PyExc_Exception, "uobject is not an AActor"); if (!py_obj->ue_object->IsA<UClass>()) return PyErr_Format(PyExc_Exception, "argument is not a UClass"); UActorComponent *component = actor->GetComponentByClass((UClass *)py_obj->ue_object); if (component) { Py_RETURN_UOBJECT(component); } Py_RETURN_NONE; } PyObject *py_ue_get_actor_components_by_type(ue_PyUObject * self, PyObject * args) { ue_py_check(self); PyObject *obj; if (!PyArg_ParseTuple(args, "O:get_actor_components_by_type", &obj)) { return NULL; } ue_PyUObject *py_obj = nullptr; if (ue_is_pyuobject(obj)) { py_obj = (ue_PyUObject *)obj; } // shortcut for finding class by string else if (PyUnicodeOrString_Check(obj)) { char *class_name = PyUnicode_AsUTF8(obj); UClass *u_class = FindObject<UClass>(ANY_PACKAGE, UTF8_TO_TCHAR(class_name)); if (u_class) { py_obj = ue_get_python_uobject(u_class); } } if (!py_obj) return PyErr_Format(PyExc_Exception, "argument is not a UObject"); if (!py_obj->ue_object->IsA<UClass>()) return PyErr_Format(PyExc_Exception, "argument is not a UClass"); AActor *actor = ue_get_actor(self); if (!actor) return PyErr_Format(PyExc_Exception, "uobject is not an AActor"); PyObject *components = PyList_New(0); for (UActorComponent *component : actor->GetComponentsByClass((UClass *)py_obj->ue_object)) { ue_PyUObject *item = ue_get_python_uobject(component); if (item) PyList_Append(components, (PyObject *)item); } return components; } PyObject *py_ue_actor_spawn(ue_PyUObject * self, PyObject * args, PyObject *kwargs) { ue_py_check(self); PyObject *py_class; PyObject *py_obj_location = nullptr; PyObject *py_obj_rotation = nullptr; if (!PyArg_ParseTuple(args, "O|OO:actor_spawn", &py_class, &py_obj_location, &py_obj_rotation)) { return nullptr; } UWorld *world = ue_get_uworld(self); if (!world) return PyErr_Format(PyExc_Exception, "unable to retrieve UWorld from uobject"); UClass *u_class = ue_py_check_type<UClass>(py_class); if (!u_class) return PyErr_Format(PyExc_Exception, "argument is not a UClass"); if (!u_class->IsChildOf<AActor>()) { return PyErr_Format(PyExc_Exception, "argument is not a UClass derived from AActor"); } FVector location = FVector(0, 0, 0); FRotator rotation = FRotator(0, 0, 0); if (py_obj_location) { ue_PyFVector *py_location = py_ue_is_fvector(py_obj_location); if (!py_location) return PyErr_Format(PyExc_Exception, "location must be an FVector"); location = py_location->vec; } if (py_obj_rotation) { ue_PyFRotator *py_rotation = py_ue_is_frotator(py_obj_rotation); if (!py_rotation) return PyErr_Format(PyExc_Exception, "location must be an FRotator"); rotation = py_rotation->rot; } if (kwargs && PyDict_Size(kwargs) > 0) { FTransform transform; transform.SetTranslation(location); transform.SetRotation(rotation.Quaternion()); AActor *actor = world->SpawnActorDeferred<AActor>(u_class, transform); if (!actor) return PyErr_Format(PyExc_Exception, "unable to spawn a new Actor"); ue_PyUObject *py_actor = ue_get_python_uobject(actor); if (!py_actor) return PyErr_Format(PyExc_Exception, "uobject is in invalid state"); PyObject *py_iter = PyObject_GetIter(kwargs); while (PyObject *py_key = PyIter_Next(py_iter)) { PyObject *void_ret = py_ue_set_property(py_actor, Py_BuildValue("OO", py_key, PyDict_GetItem(kwargs, py_key))); if (!void_ret) { return PyErr_Format(PyExc_Exception, "unable to set property for new Actor"); } } Py_DECREF(py_iter); UGameplayStatics::FinishSpawningActor(actor, transform); return (PyObject *)py_actor; } AActor *actor = world->SpawnActor(u_class, &location, &rotation); if (!actor) return PyErr_Format(PyExc_Exception, "unable to spawn a new Actor"); Py_RETURN_UOBJECT(actor); } PyObject *py_ue_get_overlapping_actors(ue_PyUObject * self, PyObject * args) { ue_py_check(self); AActor *actor = ue_get_actor(self); if (!actor) return PyErr_Format(PyExc_Exception, "cannot retrieve actor from UObject"); PyObject *class_filter = nullptr; if (!PyArg_ParseTuple(args, "|O:get_overlapping_actors", &class_filter)) { return NULL; } UClass *filtering = AActor::StaticClass(); if (class_filter) { if (!ue_is_pyuobject(class_filter)) return PyErr_Format(PyExc_Exception, "argument is not a UObject"); ue_PyUObject *py_obj = (ue_PyUObject *)class_filter; if (!py_obj->ue_object->IsA((UClass *)py_obj->ue_object)) return PyErr_Format(PyExc_Exception, "argument is not a UClass"); filtering = (UClass *)py_obj->ue_object; } PyObject *py_overlapping_actors = PyList_New(0); TArray<AActor *> overalpping_actors; actor->GetOverlappingActors(overalpping_actors, filtering); for (AActor *overlapping_actor : overalpping_actors) { ue_PyUObject *item = ue_get_python_uobject(overlapping_actor); if (item) { PyList_Append(py_overlapping_actors, (PyObject *)item); } } return py_overlapping_actors; } PyObject *py_ue_actor_set_level_sequence(ue_PyUObject * self, PyObject * args) { ue_py_check(self); PyObject *py_sequence; if (!PyArg_ParseTuple(args, "O:actor_set_level_sequence", &py_sequence)) { return NULL; } ALevelSequenceActor *actor = ue_py_check_type<ALevelSequenceActor>(self); if (!actor) { return PyErr_Format(PyExc_Exception, "uobject is not a LevelSequenceActor"); } ULevelSequence *sequence = ue_py_check_type<ULevelSequence>(py_sequence); if (!sequence) { return PyErr_Format(PyExc_Exception, "argument is not a LevelSequence"); } actor->SetSequence(sequence); Py_RETURN_NONE; } #if WITH_EDITOR PyObject *py_ue_get_editor_world_counterpart_actor(ue_PyUObject * self, PyObject * args) { ue_py_check(self); AActor *actor = ue_get_actor(self); if (!actor) return PyErr_Format(PyExc_Exception, "cannot retrieve actor from UObject"); AActor *editor_actor = EditorUtilities::GetEditorWorldCounterpartActor(actor); if (!editor_actor) return PyErr_Format(PyExc_Exception, "unable to retrieve editor counterpart actor"); Py_RETURN_UOBJECT(editor_actor); } #endif
/* Copyright (c) 2015-2020 Max Krasnyansky <max.krasnyansky@gmail.com> 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. 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 hogl/detail/args.h * Details of the argument handling. */ #ifndef HOGL_DETAIL_ARGS_HPP #define HOGL_DETAIL_ARGS_HPP #include <stdint.h> #include <limits.h> #include <string.h> #include <string> #include <hogl/detail/compiler.hpp> __HOGL_PRIV_NS_OPEN__ namespace hogl { /** * Global string. * Special argument that tells HOGL that it's safe to use * string pointer as is. No string copy is done in this case. */ struct arg_gstr { const char *str; hogl_force_inline arg_gstr(const char *s): str(s) {} }; /** * Raw data. * Special argument that tells HOGL to store the data as is. * Default HOGL format handlers ignore RAW arguments. * This type is designed for custom format handlers. */ struct arg_raw { const void *ptr; unsigned int len; hogl_force_inline arg_raw(const void *p, unsigned int n): ptr(p), len(n) {} }; /** * Formated data dump. * Special argument that tells HOGL to store the data as is and * to generate a formated data dump on the output. */ struct arg_xdump { struct format { uint8_t type; // conversion type: d,u,f (see sprintf), H (classic hexdump) uint8_t byte_width : 4; // number of bytes for each value (1,2,4,8) uint8_t precision : 4; // precision uint8_t line_width; // number of values per line (0 - single line) uint8_t delim; // delimeter character format(uint8_t t, uint8_t bw, uint8_t pr, uint8_t lw, char d) : type(t), byte_width(bw), precision(pr), line_width(lw), delim(d) { } }; format fmt; const void *ptr; unsigned int len; hogl_force_inline arg_xdump(const void *p, unsigned int n, uint8_t t = 'H', uint8_t bw = 1, uint8_t pr = 2, uint8_t lw = 20, char d = ' '): fmt(t, bw, pr, lw, d), ptr(p), len(n) { } }; /** * Log record argument */ struct arg { /** * Argument types */ enum { NONE, /// No arg UINT32, /// 32bit unsigned int INT32, /// 32bit signed int UINT64, /// 64bit unsigned int INT64, /// 64bit signed int POINTER,/// Pointer DOUBLE, /// Floating point number CSTR, /// Regular C string GSTR, /// Global string (see below) XDUMP, /// Xdump RAW, /// Raw data }; // This layout generates the most optimal code. // Do not change it without making sure that the compiler is // able to optimize out all unnecessary code. unsigned int type; uint64_t val; unsigned int len; #if ULONG_MAX == UINT_MAX // 32bit arch static bool is_32bit(unsigned int type) { return type != UINT64 && type != INT64 && type != DOUBLE; } #else // 64bit arch static bool is_32bit(unsigned int type) { return type == UINT32 || type == INT32; } #endif bool is_32bit() const { return is_32bit(type); } bool is_simple() const { return (type != CSTR && type != XDUMP && type != RAW); } // Various constructors for autodetecting argument types. // Force inlining them to avoid unnecessary code when optimizations // are disabled. hogl_force_inline arg() : type(NONE) {} hogl_force_inline arg(bool i) : type(UINT32), val(i) {} hogl_force_inline arg(uint8_t i) : type(UINT32), val(i) {} hogl_force_inline arg(uint16_t i) : type(UINT32), val(i) {} hogl_force_inline arg(void *ptr) : type(POINTER), val((unsigned long) ptr) {} hogl_force_inline arg(volatile void *ptr) : type(POINTER), val((unsigned long) ptr) {} hogl_force_inline arg(unsigned int i) : type(UINT32), val(i) {} hogl_force_inline arg(int i) : type(INT32), val(i) {} hogl_force_inline arg(unsigned long long u) : type(UINT64), val(u) {} hogl_force_inline arg(long long i) : type(INT64), val(i) {} #if ULONG_MAX == UINT_MAX // 32bit arch hogl_force_inline arg(unsigned long u) : type(UINT32), val(u) {} hogl_force_inline arg(long i) : type(INT32), val(i) {} #else // 64bit arch hogl_force_inline arg(unsigned long u) : type(UINT64), val(u) {} hogl_force_inline arg(long i) : type(INT64), val(i) {} #endif hogl_force_inline arg(double d) : type(DOUBLE) { union { double d; uint64_t u; } u; u.d = d; val = u.u; } // For static strings the call to strlen() is resolved at compile time hogl_force_inline arg(const char *str) : type(CSTR), val((uint64_t) str), len(str ? strlen(str) : 0) {} hogl_force_inline arg(const std::string &str) : type(CSTR), val((uint64_t) str.data()), len(str.length()) {} hogl_force_inline arg(const arg_gstr &s) : type(GSTR), val((uint64_t) s.str) {} hogl_force_inline arg(const arg_xdump &xd) : type(XDUMP), val((uint64_t) &xd) {} hogl_force_inline arg(const arg_raw &raw) : type(RAW), val((uint64_t) raw.ptr), len(raw.len) {} }; // Dummy function to call for triggering VG warnings on uninitialized args. // See argpack.hpp extern void arg_check(const arg& a); } // namespace hogl __HOGL_PRIV_NS_CLOSE__ #endif // HOGL_DETAIL_ARGS_HPP
// Copyright (c) 2017-2018 The Bitcoin Core developers // Copyright (c) 2021 The Vivuscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <random.h> #include <test/test_vivuscoin.h> #include <boost/test/unit_test.hpp> #include <random> #include <algorithm> BOOST_FIXTURE_TEST_SUITE(random_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(osrandom_tests) { BOOST_CHECK(Random_SanityCheck()); } BOOST_AUTO_TEST_CASE(fastrandom_tests) { // Check that deterministic FastRandomContexts are deterministic g_mock_deterministic_tests = true; FastRandomContext ctx1(true); FastRandomContext ctx2(true); for (int i = 10; i > 0; --i) { BOOST_CHECK_EQUAL(GetRand(std::numeric_limits<uint64_t>::max()), uint64_t{10393729187455219830U}); BOOST_CHECK_EQUAL(GetRandInt(std::numeric_limits<int>::max()), int{769702006}); } BOOST_CHECK_EQUAL(ctx1.rand32(), ctx2.rand32()); BOOST_CHECK_EQUAL(ctx1.rand32(), ctx2.rand32()); BOOST_CHECK_EQUAL(ctx1.rand64(), ctx2.rand64()); BOOST_CHECK_EQUAL(ctx1.randbits(3), ctx2.randbits(3)); BOOST_CHECK(ctx1.randbytes(17) == ctx2.randbytes(17)); BOOST_CHECK(ctx1.rand256() == ctx2.rand256()); BOOST_CHECK_EQUAL(ctx1.randbits(7), ctx2.randbits(7)); BOOST_CHECK(ctx1.randbytes(128) == ctx2.randbytes(128)); BOOST_CHECK_EQUAL(ctx1.rand32(), ctx2.rand32()); BOOST_CHECK_EQUAL(ctx1.randbits(3), ctx2.randbits(3)); BOOST_CHECK(ctx1.rand256() == ctx2.rand256()); BOOST_CHECK(ctx1.randbytes(50) == ctx2.randbytes(50)); // Check that a nondeterministic ones are not g_mock_deterministic_tests = false; for (int i = 10; i > 0; --i) { BOOST_CHECK(GetRand(std::numeric_limits<uint64_t>::max()) != uint64_t{10393729187455219830U}); BOOST_CHECK(GetRandInt(std::numeric_limits<int>::max()) != int{769702006}); } { FastRandomContext ctx3, ctx4; BOOST_CHECK(ctx3.rand64() != ctx4.rand64()); // extremely unlikely to be equal } { FastRandomContext ctx3, ctx4; BOOST_CHECK(ctx3.rand256() != ctx4.rand256()); } { FastRandomContext ctx3, ctx4; BOOST_CHECK(ctx3.randbytes(7) != ctx4.randbytes(7)); } } BOOST_AUTO_TEST_CASE(fastrandom_randbits) { FastRandomContext ctx1; FastRandomContext ctx2; for (int bits = 0; bits < 63; ++bits) { for (int j = 0; j < 1000; ++j) { uint64_t rangebits = ctx1.randbits(bits); BOOST_CHECK_EQUAL(rangebits >> bits, 0U); uint64_t range = ((uint64_t)1) << bits | rangebits; uint64_t rand = ctx2.randrange(range); BOOST_CHECK(rand < range); } } } /** Does-it-compile test for compatibility with standard C++11 RNG interface. */ BOOST_AUTO_TEST_CASE(stdrandom_test) { FastRandomContext ctx; std::uniform_int_distribution<int> distribution(3, 9); for (int i = 0; i < 100; ++i) { int x = distribution(ctx); BOOST_CHECK(x >= 3); BOOST_CHECK(x <= 9); std::vector<int> test{1,2,3,4,5,6,7,8,9,10}; std::shuffle(test.begin(), test.end(), ctx); for (int j = 1; j <= 10; ++j) { BOOST_CHECK(std::find(test.begin(), test.end(), j) != test.end()); } Shuffle(test.begin(), test.end(), ctx); for (int j = 1; j <= 10; ++j) { BOOST_CHECK(std::find(test.begin(), test.end(), j) != test.end()); } } } /** Test that Shuffle reaches every permutation with equal probability. */ BOOST_AUTO_TEST_CASE(shuffle_stat_test) { FastRandomContext ctx(true); uint32_t counts[5 * 5 * 5 * 5 * 5] = {0}; for (int i = 0; i < 12000; ++i) { int data[5] = {0, 1, 2, 3, 4}; Shuffle(std::begin(data), std::end(data), ctx); int pos = data[0] + data[1] * 5 + data[2] * 25 + data[3] * 125 + data[4] * 625; ++counts[pos]; } unsigned int sum = 0; double chi_score = 0.0; for (int i = 0; i < 5 * 5 * 5 * 5 * 5; ++i) { int i1 = i % 5, i2 = (i / 5) % 5, i3 = (i / 25) % 5, i4 = (i / 125) % 5, i5 = i / 625; uint32_t count = counts[i]; if (i1 == i2 || i1 == i3 || i1 == i4 || i1 == i5 || i2 == i3 || i2 == i4 || i2 == i5 || i3 == i4 || i3 == i5 || i4 == i5) { BOOST_CHECK(count == 0); } else { chi_score += ((count - 100.0) * (count - 100.0)) / 100.0; BOOST_CHECK(count > 50); BOOST_CHECK(count < 150); sum += count; } } BOOST_CHECK(chi_score > 58.1411); // 99.9999% confidence interval BOOST_CHECK(chi_score < 210.275); BOOST_CHECK_EQUAL(sum, 12000); } BOOST_AUTO_TEST_SUITE_END()
/** * Copyright 2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "tools/converter/parser/onnx/onnx_lstm_parser.h" #include <memory> #include "ops/lstm.h" #include "nnacl/op_base.h" namespace mindspore { namespace lite { ops::PrimitiveC *OnnxLstmParser::Parse(const onnx::GraphProto &onnx_graph, const onnx::NodeProto &onnx_node) { auto prim = std::make_unique<ops::LSTM>(); MS_CHECK_TRUE_RET(prim != nullptr, nullptr); for (const auto &onnx_node_attr : onnx_node.attribute()) { if (onnx_node_attr.name() == "direction") { const auto &direction = onnx_node_attr.s(); bool bidirectional = direction == "bidirectional"; prim->set_bidirectional(bidirectional); if (bidirectional) { prim->set_num_directions(2); } else { prim->set_num_directions(1); } } else if (onnx_node_attr.name() == "hidden_size") { prim->set_hidden_size(onnx_node_attr.i()); } else if (onnx_node_attr.name() == "clip") { prim->set_dropout(onnx_node_attr.f()); } else if (onnx_node_attr.name() == "activations") { prim->set_has_bias(true); } } return prim.release(); } OnnxNodeRegistrar g_onnxLstmParser("LSTM", new OnnxLstmParser()); } // namespace lite } // namespace mindspore
/*========================================================================= Program: Visualization Toolkit Module: vtkSmoothPolyDataFilter.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 "vtkSmoothPolyDataFilter.h" #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkCellLocator.h" #include "vtkFloatArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkPolygon.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkTriangleFilter.h" #include <limits> vtkStandardNewMacro(vtkSmoothPolyDataFilter); // The following code defines a helper class for performing mesh smoothing // across the surface of another mesh. typedef struct _vtkSmoothPoint { vtkIdType cellId; // cell int subId; // cell sub id double p[3]; // parametric coords in cell } vtkSmoothPoint; class vtkSmoothPoints { //;prevent man page generation public: vtkSmoothPoints(); ~vtkSmoothPoints() { delete[] this->Array; } vtkIdType GetNumberOfPoints() { return this->MaxId + 1; } vtkSmoothPoint* GetSmoothPoint(vtkIdType i) { return this->Array + i; } vtkSmoothPoint* InsertSmoothPoint(vtkIdType ptId) { if (ptId >= this->Size) { this->Resize(ptId + 1); } if (ptId > this->MaxId) { this->MaxId = ptId; } return this->Array + ptId; } vtkSmoothPoint* Resize(vtkIdType sz); // reallocates data void Reset() { this->MaxId = -1; } vtkSmoothPoint* Array; // pointer to data vtkIdType MaxId; // maximum index inserted thus far vtkIdType Size; // allocated size of data vtkIdType Extend; // grow array by this amount }; vtkSmoothPoints::vtkSmoothPoints() { this->MaxId = -1; this->Array = new vtkSmoothPoint[1000]; this->Size = 1000; this->Extend = 5000; } vtkSmoothPoint* vtkSmoothPoints::Resize(vtkIdType sz) { vtkSmoothPoint* newArray; vtkIdType newSize; if (sz >= this->Size) { newSize = this->Size + this->Extend * (((sz - this->Size) / this->Extend) + 1); } else { newSize = sz; } newArray = new vtkSmoothPoint[newSize]; memcpy(newArray, this->Array, (sz < this->Size ? sz : this->Size) * sizeof(vtkSmoothPoint)); this->Size = newSize; delete[] this->Array; this->Array = newArray; return this->Array; } // The following code defines methods for the vtkSmoothPolyDataFilter class // // Construct object with number of iterations 20; relaxation factor .01; // feature edge smoothing turned off; feature // angle 45 degrees; edge angle 15 degrees; and boundary smoothing turned // on. Error scalars and vectors are not generated (by default). The // convergence criterion is 0.0 of the bounding box diagonal. vtkSmoothPolyDataFilter::vtkSmoothPolyDataFilter() { this->Convergence = 0.0; // goes to number of specified iterations this->NumberOfIterations = 20; this->RelaxationFactor = .01; this->FeatureAngle = 45.0; this->EdgeAngle = 15.0; this->FeatureEdgeSmoothing = 0; this->BoundarySmoothing = 1; this->GenerateErrorScalars = 0; this->GenerateErrorVectors = 0; this->OutputPointsPrecision = vtkAlgorithm::DEFAULT_PRECISION; this->SmoothPoints = nullptr; // optional second input this->SetNumberOfInputPorts(2); } void vtkSmoothPolyDataFilter::SetSourceData(vtkPolyData* source) { this->SetInputData(1, source); } vtkPolyData* vtkSmoothPolyDataFilter::GetSource() { if (this->GetNumberOfInputConnections(1) < 1) { return nullptr; } return vtkPolyData::SafeDownCast(this->GetExecutive()->GetInputData(1, 0)); } #define VTK_SIMPLE_VERTEX 0 #define VTK_FIXED_VERTEX 1 #define VTK_FEATURE_EDGE_VERTEX 2 #define VTK_BOUNDARY_EDGE_VERTEX 3 namespace { // Special structure for marking vertices typedef struct _vtkMeshVertex { char type; vtkIdList* edges; // connected edges (list of connected point ids) _vtkMeshVertex() { type = VTK_SIMPLE_VERTEX; // can smooth edges = nullptr; } } vtkMeshVertex, *vtkMeshVertexPtr; template <typename T> struct vtkSPDF_InternalParams { vtkSmoothPolyDataFilter* spdf; int numberOfIterations; vtkPoints* newPts; T factor; T conv; vtkIdType numPts; vtkMeshVertexPtr vertexPtr; vtkPolyData* source; vtkSmoothPoints* SmoothPoints; double* w; vtkCellLocator* cellLocator; }; template <typename T> void vtkSPDF_MovePoints(vtkSPDF_InternalParams<T>& params) { int iterationNumber = 0; for (T maxDist = std::numeric_limits<T>::max(); maxDist > params.conv && iterationNumber < params.numberOfIterations; ++iterationNumber) { if (iterationNumber && !(iterationNumber % 5)) { params.spdf->UpdateProgress(0.5 + 0.5 * iterationNumber / params.numberOfIterations); if (params.spdf->GetAbortExecute()) { break; } } maxDist = 0.0; T* newPtsCoords = static_cast<T*>(params.newPts->GetVoidPointer(0)); T* start = newPtsCoords; vtkMeshVertexPtr vertsPtr = params.vertexPtr; vtkIdType npts, *edgeIdPtr; T dist, deltaX[3]; double dist2, xNew[3], closestPt[3]; // For each non-fixed vertex of the mesh, move the point toward the mean // position of its connected neighbors using the relaxation factor. for (vtkIdType i = 0; i < params.numPts; ++i) { if (vertsPtr->type != VTK_FIXED_VERTEX && vertsPtr->edges != nullptr && (npts = vertsPtr->edges->GetNumberOfIds()) > 0) { deltaX[0] = deltaX[1] = deltaX[2] = 0.0; edgeIdPtr = vertsPtr->edges->GetPointer(0); // Compute the mean (cumulated) direction vector for (vtkIdType j = 0; j < npts; ++j) { for (unsigned short k = 0; k < 3; ++k) { deltaX[k] += *(start + 3 * (*edgeIdPtr) + k); } ++edgeIdPtr; } // for all connected points // Move the point *newPtsCoords += params.factor * (deltaX[0] / npts - (*newPtsCoords)); xNew[0] = *newPtsCoords; ++newPtsCoords; *newPtsCoords += params.factor * (deltaX[1] / npts - (*newPtsCoords)); xNew[1] = *newPtsCoords; ++newPtsCoords; *newPtsCoords += params.factor * (deltaX[2] / npts - (*newPtsCoords)); xNew[2] = *newPtsCoords; ++newPtsCoords; // Constrain point to surface if (params.source) { vtkSmoothPoint* sPtr = params.SmoothPoints->GetSmoothPoint(i); vtkCell* cell = nullptr; if (sPtr->cellId >= 0) // in cell { cell = params.source->GetCell(sPtr->cellId); } if (!cell || cell->EvaluatePosition(xNew, closestPt, sPtr->subId, sPtr->p, dist2, params.w) == 0) { // not in cell anymore params.cellLocator->FindClosestPoint(xNew, closestPt, sPtr->cellId, sPtr->subId, dist2); } for (int k = 0; k < 3; ++k) { xNew[k] = closestPt[k]; } params.newPts->SetPoint(i, xNew); } if ((dist = vtkMath::Norm(deltaX)) > maxDist) { maxDist = dist; } } // if can move point else { newPtsCoords += 3; } ++vertsPtr; } // for all points } // for not converged or within iteration count vtkDebugWithObjectMacro(params.spdf, << "Performed " << iterationNumber << " smoothing passes"); } } // namespace int vtkSmoothPolyDataFilter::RequestData(vtkInformation* vtkNotUsed(request), vtkInformationVector** inputVector, vtkInformationVector* outputVector) { // get the info objects vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); vtkInformation* sourceInfo = inputVector[1]->GetInformationObject(0); vtkInformation* outInfo = outputVector->GetInformationObject(0); // get the input and output vtkPolyData* input = vtkPolyData::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT())); vtkPolyData* source = nullptr; if (sourceInfo) { source = vtkPolyData::SafeDownCast(sourceInfo->Get(vtkDataObject::DATA_OBJECT())); } vtkPolyData* output = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); vtkIdType numPts, numCells, i, numPolys, numStrips; int j, k; vtkIdType npts = 0; const vtkIdType* pts = nullptr; vtkIdType p1, p2; double conv; double x1[3], x2[3], x3[3], l1[3], l2[3]; double CosFeatureAngle; // Cosine of angle between adjacent polys double CosEdgeAngle; // Cosine of angle between adjacent edges double closestPt[3], dist2, *w = nullptr; vtkIdType numSimple = 0, numBEdges = 0, numFixed = 0, numFEdges = 0; vtkPolyData *inMesh, *Mesh; vtkPoints* inPts; vtkTriangleFilter* toTris = nullptr; vtkCellArray *inVerts, *inLines, *inPolys, *inStrips; vtkPoints* newPts; vtkMeshVertexPtr Verts; vtkCellLocator* cellLocator = nullptr; // Check input // numPts = input->GetNumberOfPoints(); numCells = input->GetNumberOfCells(); if (numPts < 1 || numCells < 1) { vtkErrorMacro(<< "No data to smooth!"); return 1; } CosFeatureAngle = cos(vtkMath::RadiansFromDegrees(this->FeatureAngle)); CosEdgeAngle = cos(vtkMath::RadiansFromDegrees(this->EdgeAngle)); vtkDebugMacro(<< "Smoothing " << numPts << " vertices, " << numCells << " cells with:\n" << "\tConvergence= " << this->Convergence << "\n" << "\tIterations= " << this->NumberOfIterations << "\n" << "\tRelaxation Factor= " << this->RelaxationFactor << "\n" << "\tEdge Angle= " << this->EdgeAngle << "\n" << "\tBoundary Smoothing " << (this->BoundarySmoothing ? "On\n" : "Off\n") << "\tFeature Edge Smoothing " << (this->FeatureEdgeSmoothing ? "On\n" : "Off\n") << "\tError Scalars " << (this->GenerateErrorScalars ? "On\n" : "Off\n") << "\tError Vectors " << (this->GenerateErrorVectors ? "On\n" : "Off\n")); if (this->NumberOfIterations <= 0 || this->RelaxationFactor == 0.0) { // don't do anything! pass data through output->CopyStructure(input); output->GetPointData()->PassData(input->GetPointData()); output->GetCellData()->PassData(input->GetCellData()); return 1; } // Perform topological analysis. What we're gonna do is build a connectivity // array of connected vertices. The outcome will be one of three // classifications for a vertex: VTK_SIMPLE_VERTEX, VTK_FIXED_VERTEX. or // VTK_EDGE_VERTEX. Simple vertices are smoothed using all connected // vertices. FIXED vertices are never smoothed. Edge vertices are smoothed // using a subset of the attached vertices. // vtkDebugMacro(<< "Analyzing topology..."); Verts = new vtkMeshVertex[numPts]; inPts = input->GetPoints(); conv = this->Convergence * input->GetLength(); // check vertices first. Vertices are never smoothed_-------------- for (inVerts = input->GetVerts(), inVerts->InitTraversal(); inVerts->GetNextCell(npts, pts);) { for (j = 0; j < npts; j++) { Verts[pts[j]].type = VTK_FIXED_VERTEX; } } this->UpdateProgress(0.10); // now check lines. Only manifold lines can be smoothed------------ for (inLines = input->GetLines(), inLines->InitTraversal(); inLines->GetNextCell(npts, pts);) { for (j = 0; j < npts; j++) { if (Verts[pts[j]].type == VTK_SIMPLE_VERTEX) { if (j == (npts - 1)) // end-of-line marked FIXED { Verts[pts[j]].type = VTK_FIXED_VERTEX; } else if (j == 0) // beginning-of-line marked FIXED { Verts[pts[0]].type = VTK_FIXED_VERTEX; inPts->GetPoint(pts[0], x2); inPts->GetPoint(pts[1], x3); } else // is edge vertex (unless already edge vertex!) { Verts[pts[j]].type = VTK_FEATURE_EDGE_VERTEX; Verts[pts[j]].edges = vtkIdList::New(); Verts[pts[j]].edges->SetNumberOfIds(2); Verts[pts[j]].edges->SetId(0, pts[j - 1]); Verts[pts[j]].edges->SetId(1, pts[j + 1]); } } // if simple vertex else if (Verts[pts[j]].type == VTK_FEATURE_EDGE_VERTEX) { // multiply connected, becomes fixed! Verts[pts[j]].type = VTK_FIXED_VERTEX; Verts[pts[j]].edges->Delete(); Verts[pts[j]].edges = nullptr; } } // for all points in this line } // for all lines this->UpdateProgress(0.25); // now polygons and triangle strips------------------------------- inPolys = input->GetPolys(); numPolys = inPolys->GetNumberOfCells(); inStrips = input->GetStrips(); numStrips = inStrips->GetNumberOfCells(); if (numPolys > 0 || numStrips > 0) { // build cell structure vtkCellArray* polys; vtkIdType cellId; int numNei, nei, edge; vtkIdType numNeiPts; const vtkIdType* neiPts; double normal[3], neiNormal[3]; vtkIdList* neighbors; neighbors = vtkIdList::New(); neighbors->Allocate(VTK_CELL_SIZE); inMesh = vtkPolyData::New(); inMesh->SetPoints(inPts); inMesh->SetPolys(inPolys); Mesh = inMesh; if ((numStrips = inStrips->GetNumberOfCells()) > 0) { // convert data to triangles inMesh->SetStrips(inStrips); toTris = vtkTriangleFilter::New(); toTris->SetInputData(inMesh); toTris->Update(); Mesh = toTris->GetOutput(); } Mesh->BuildLinks(); // to do neighborhood searching polys = Mesh->GetPolys(); this->UpdateProgress(0.375); for (cellId = 0, polys->InitTraversal(); polys->GetNextCell(npts, pts); cellId++) { for (i = 0; i < npts; i++) { p1 = pts[i]; p2 = pts[(i + 1) % npts]; if (Verts[p1].edges == nullptr) { Verts[p1].edges = vtkIdList::New(); Verts[p1].edges->Allocate(16, 6); } if (Verts[p2].edges == nullptr) { Verts[p2].edges = vtkIdList::New(); Verts[p2].edges->Allocate(16, 6); } Mesh->GetCellEdgeNeighbors(cellId, p1, p2, neighbors); numNei = neighbors->GetNumberOfIds(); edge = VTK_SIMPLE_VERTEX; if (numNei == 0) { edge = VTK_BOUNDARY_EDGE_VERTEX; } else if (numNei >= 2) { // check to make sure that this edge hasn't been marked already for (j = 0; j < numNei; j++) { if (neighbors->GetId(j) < cellId) { break; } } if (j >= numNei) { edge = VTK_FEATURE_EDGE_VERTEX; } } else if (numNei == 1 && (nei = neighbors->GetId(0)) > cellId) { if (this->FeatureEdgeSmoothing) { vtkPolygon::ComputeNormal(inPts, npts, pts, normal); Mesh->GetCellPoints(nei, numNeiPts, neiPts); vtkPolygon::ComputeNormal(inPts, numNeiPts, neiPts, neiNormal); if (vtkMath::Dot(normal, neiNormal) <= CosFeatureAngle) { edge = VTK_FEATURE_EDGE_VERTEX; } } } else // a visited edge; skip rest of analysis { continue; } if (edge && Verts[p1].type == VTK_SIMPLE_VERTEX) { Verts[p1].edges->Reset(); Verts[p1].edges->InsertNextId(p2); Verts[p1].type = edge; } else if ((edge && Verts[p1].type == VTK_BOUNDARY_EDGE_VERTEX) || (edge && Verts[p1].type == VTK_FEATURE_EDGE_VERTEX) || (!edge && Verts[p1].type == VTK_SIMPLE_VERTEX)) { Verts[p1].edges->InsertNextId(p2); if (Verts[p1].type && edge == VTK_BOUNDARY_EDGE_VERTEX) { Verts[p1].type = VTK_BOUNDARY_EDGE_VERTEX; } } if (edge && Verts[p2].type == VTK_SIMPLE_VERTEX) { Verts[p2].edges->Reset(); Verts[p2].edges->InsertNextId(p1); Verts[p2].type = edge; } else if ((edge && Verts[p2].type == VTK_BOUNDARY_EDGE_VERTEX) || (edge && Verts[p2].type == VTK_FEATURE_EDGE_VERTEX) || (!edge && Verts[p2].type == VTK_SIMPLE_VERTEX)) { Verts[p2].edges->InsertNextId(p1); if (Verts[p2].type && edge == VTK_BOUNDARY_EDGE_VERTEX) { Verts[p2].type = VTK_BOUNDARY_EDGE_VERTEX; } } } } inMesh->Delete(); if (toTris) { toTris->Delete(); } neighbors->Delete(); } // if strips or polys this->UpdateProgress(0.50); // post-process edge vertices to make sure we can smooth them for (i = 0; i < numPts; i++) { if (Verts[i].type == VTK_SIMPLE_VERTEX) { numSimple++; } else if (Verts[i].type == VTK_FIXED_VERTEX) { numFixed++; } else if (Verts[i].type == VTK_FEATURE_EDGE_VERTEX || Verts[i].type == VTK_BOUNDARY_EDGE_VERTEX) { // see how many edges; if two, what the angle is if (!this->BoundarySmoothing && Verts[i].type == VTK_BOUNDARY_EDGE_VERTEX) { Verts[i].type = VTK_FIXED_VERTEX; numBEdges++; } else if ((npts = Verts[i].edges->GetNumberOfIds()) != 2) { Verts[i].type = VTK_FIXED_VERTEX; numFixed++; } else // check angle between edges { inPts->GetPoint(Verts[i].edges->GetId(0), x1); inPts->GetPoint(i, x2); inPts->GetPoint(Verts[i].edges->GetId(1), x3); for (k = 0; k < 3; k++) { l1[k] = x2[k] - x1[k]; l2[k] = x3[k] - x2[k]; } if (vtkMath::Normalize(l1) >= 0.0 && vtkMath::Normalize(l2) >= 0.0 && vtkMath::Dot(l1, l2) < CosEdgeAngle) { numFixed++; Verts[i].type = VTK_FIXED_VERTEX; } else { if (Verts[i].type == VTK_FEATURE_EDGE_VERTEX) { numFEdges++; } else { numBEdges++; } } } // if along edge } // if edge vertex } // for all points vtkDebugMacro(<< "Found\n\t" << numSimple << " simple vertices\n\t" << numFEdges << " feature edge vertices\n\t" << numBEdges << " boundary edge vertices\n\t" << numFixed << " fixed vertices\n\t"); vtkDebugMacro(<< "Beginning smoothing iterations..."); // We've setup the topology...now perform Laplacian smoothing // newPts = vtkPoints::New(); // Set the desired precision for the points in the output. if (this->OutputPointsPrecision == vtkAlgorithm::DEFAULT_PRECISION) { newPts->SetDataType(inPts->GetDataType()); } else if (this->OutputPointsPrecision == vtkAlgorithm::SINGLE_PRECISION) { newPts->SetDataType(VTK_FLOAT); } else if (this->OutputPointsPrecision == vtkAlgorithm::DOUBLE_PRECISION) { newPts->SetDataType(VTK_DOUBLE); } newPts->SetNumberOfPoints(numPts); // If Source defined, we do constrained smoothing (that is, points are // constrained to the surface of the mesh object). if (source) { this->SmoothPoints = new vtkSmoothPoints; vtkSmoothPoint* sPtr; cellLocator = vtkCellLocator::New(); w = new double[source->GetMaxCellSize()]; cellLocator->SetDataSet(source); cellLocator->BuildLocator(); for (i = 0; i < numPts; i++) { sPtr = this->SmoothPoints->InsertSmoothPoint(i); cellLocator->FindClosestPoint( inPts->GetPoint(i), closestPt, sPtr->cellId, sPtr->subId, dist2); newPts->SetPoint(i, closestPt); } } else // smooth normally { for (i = 0; i < numPts; i++) // initialize to old coordinates { newPts->SetPoint(i, inPts->GetPoint(i)); } } if (newPts->GetDataType() == VTK_DOUBLE) { vtkSPDF_InternalParams<double> params = { this, this->NumberOfIterations, newPts, this->RelaxationFactor, conv, numPts, Verts, source, this->SmoothPoints, w, cellLocator }; vtkSPDF_MovePoints(params); } else { vtkSPDF_InternalParams<float> params = { this, this->NumberOfIterations, newPts, static_cast<float>(this->RelaxationFactor), static_cast<float>(conv), numPts, Verts, source, this->SmoothPoints, w, cellLocator }; vtkSPDF_MovePoints(params); } if (source) { cellLocator->Delete(); delete this->SmoothPoints; delete[] w; } // Update output. Only point coordinates have changed. // output->GetPointData()->PassData(input->GetPointData()); output->GetCellData()->PassData(input->GetCellData()); if (this->GenerateErrorScalars) { vtkFloatArray* newScalars = vtkFloatArray::New(); newScalars->SetNumberOfTuples(numPts); for (i = 0; i < numPts; i++) { inPts->GetPoint(i, x1); newPts->GetPoint(i, x2); newScalars->SetComponent(i, 0, sqrt(vtkMath::Distance2BetweenPoints(x1, x2))); } int idx = output->GetPointData()->AddArray(newScalars); output->GetPointData()->SetActiveAttribute(idx, vtkDataSetAttributes::SCALARS); newScalars->Delete(); } if (this->GenerateErrorVectors) { vtkFloatArray* newVectors = vtkFloatArray::New(); newVectors->SetNumberOfComponents(3); newVectors->SetNumberOfTuples(numPts); for (i = 0; i < numPts; i++) { inPts->GetPoint(i, x1); newPts->GetPoint(i, x2); for (j = 0; j < 3; j++) { x3[j] = x2[j] - x1[j]; } newVectors->SetTuple(i, x3); } output->GetPointData()->SetVectors(newVectors); newVectors->Delete(); } output->SetPoints(newPts); newPts->Delete(); output->SetVerts(input->GetVerts()); output->SetLines(input->GetLines()); output->SetPolys(input->GetPolys()); output->SetStrips(input->GetStrips()); // free up connectivity storage for (i = 0; i < numPts; i++) { if (Verts[i].edges != nullptr) { Verts[i].edges->Delete(); Verts[i].edges = nullptr; } } delete[] Verts; return 1; } int vtkSmoothPolyDataFilter::FillInputPortInformation(int port, vtkInformation* info) { if (!this->Superclass::FillInputPortInformation(port, info)) { return 0; } if (port == 1) { info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1); } return 1; } void vtkSmoothPolyDataFilter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Convergence: " << this->Convergence << "\n"; os << indent << "Number of Iterations: " << this->NumberOfIterations << "\n"; os << indent << "Relaxation Factor: " << this->RelaxationFactor << "\n"; os << indent << "Feature Edge Smoothing: " << (this->FeatureEdgeSmoothing ? "On\n" : "Off\n"); os << indent << "Feature Angle: " << this->FeatureAngle << "\n"; os << indent << "Edge Angle: " << this->EdgeAngle << "\n"; os << indent << "Boundary Smoothing: " << (this->BoundarySmoothing ? "On\n" : "Off\n"); os << indent << "Generate Error Scalars: " << (this->GenerateErrorScalars ? "On\n" : "Off\n"); os << indent << "Generate Error Vectors: " << (this->GenerateErrorVectors ? "On\n" : "Off\n"); if (this->GetSource()) { os << indent << "Source: " << static_cast<void*>(this->GetSource()) << "\n"; } else { os << indent << "Source (none)\n"; } os << indent << "Output Points Precision: " << this->OutputPointsPrecision << "\n"; }
/* Copyright (c) 2013, SMB Phone Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ #include <ortc/services/IDHKeyDomain.h> #include <ortc/services/IDHPrivateKey.h> #include <ortc/services/IDHPublicKey.h> #include <ortc/services/IHelper.h> #include <zsLib/XML.h> #include <iostream> #include "config.h" #include "testing.h" using ortc::services::IHelper; using ortc::services::IDHKeyDomain; using ortc::services::IDHKeyDomainPtr; using ortc::services::IDHPrivateKey; using ortc::services::IDHPrivateKeyPtr; using ortc::services::IDHPublicKey; using ortc::services::IDHPublicKeyPtr; using ortc::services::SecureByteBlock; using ortc::services::SecureByteBlockPtr; void doTestDH() { if (!ORTC_SERVICE_TEST_DO_DH_TEST) return; TESTING_INSTALL_LOGGER(); { static IDHKeyDomain::KeyDomainPrecompiledTypes precompiled[] = { IDHKeyDomain::KeyDomainPrecompiledType_1024, IDHKeyDomain::KeyDomainPrecompiledType_1538, IDHKeyDomain::KeyDomainPrecompiledType_2048, IDHKeyDomain::KeyDomainPrecompiledType_3072, IDHKeyDomain::KeyDomainPrecompiledType_4096, IDHKeyDomain::KeyDomainPrecompiledType_6144, IDHKeyDomain::KeyDomainPrecompiledType_8192, IDHKeyDomain::KeyDomainPrecompiledType_Unknown, }; // check standard generation { SecureByteBlock p; SecureByteBlock q; SecureByteBlock g; SecureByteBlock aliceStaticPrivate; SecureByteBlock aliceStaticPublic; SecureByteBlock aliceEmpheralPrivate; SecureByteBlock aliceEmpheralPublic; SecureByteBlock bobStaticPrivate; SecureByteBlock bobStaticPublic; SecureByteBlock bobEmpheralPrivate; SecureByteBlock bobEmpheralPublic; SecureByteBlockPtr checkAgain; { TESTING_EQUAL(1, 1) IDHKeyDomainPtr keyDomain = IDHKeyDomain::generate(1024); keyDomain->save(p, q, g); IDHPublicKeyPtr alicePublicKey; IDHPrivateKeyPtr alicePrivateKey = IDHPrivateKey::generate(keyDomain, alicePublicKey); IDHPublicKeyPtr bobPublicKey; IDHPrivateKeyPtr bobPrivateKey = IDHPrivateKey::generate(keyDomain, bobPublicKey); TESTING_CHECK((bool)alicePublicKey) TESTING_CHECK((bool)alicePrivateKey) TESTING_CHECK((bool)bobPublicKey) TESTING_CHECK((bool)bobPrivateKey) alicePrivateKey->save(&aliceStaticPrivate, &aliceEmpheralPrivate); alicePublicKey->save(&aliceStaticPublic, &aliceEmpheralPublic); bobPrivateKey->save(&bobStaticPrivate, &bobEmpheralPrivate); bobPublicKey->save(&bobStaticPublic, &bobEmpheralPublic); SecureByteBlockPtr aliceSecret = alicePrivateKey->getSharedSecret(bobPublicKey); SecureByteBlockPtr bobSecret = bobPrivateKey->getSharedSecret(alicePublicKey); TESTING_CHECK(IHelper::hasData(aliceSecret)) TESTING_CHECK(IHelper::hasData(bobSecret)) TESTING_CHECK(0 == IHelper::compare(*aliceSecret, *bobSecret)) checkAgain = aliceSecret; } { TESTING_EQUAL(2, 2) IDHKeyDomainPtr keyDomain = IDHKeyDomain::load(p, q, g, true); IDHPublicKeyPtr alicePublicKey = IDHPublicKey::load(aliceStaticPublic, aliceEmpheralPublic); IDHPrivateKeyPtr alicePrivateKey = IDHPrivateKey::load(keyDomain, aliceStaticPrivate, aliceEmpheralPrivate); IDHPublicKeyPtr bobPublicKey = IDHPublicKey::load(bobStaticPublic, bobEmpheralPublic); IDHPrivateKeyPtr bobPrivateKey = IDHPrivateKey::load(keyDomain, bobStaticPrivate, bobEmpheralPrivate); TESTING_CHECK((bool)alicePublicKey) TESTING_CHECK((bool)alicePrivateKey) TESTING_CHECK((bool)bobPublicKey) TESTING_CHECK((bool)bobPrivateKey) SecureByteBlockPtr aliceSecret = alicePrivateKey->getSharedSecret(bobPublicKey); SecureByteBlockPtr bobSecret = bobPrivateKey->getSharedSecret(alicePublicKey); TESTING_CHECK(IHelper::hasData(aliceSecret)) TESTING_CHECK(IHelper::hasData(bobSecret)) TESTING_CHECK(0 == IHelper::compare(*aliceSecret, *bobSecret)) TESTING_CHECK(0 == IHelper::compare(*aliceSecret, *checkAgain)) } { TESTING_EQUAL(3, 3) IDHKeyDomainPtr keyDomain = IDHKeyDomain::load(p, q, g, true); IDHKeyDomainPtr altKeyDomain = IDHKeyDomain::loadPrecompiled(IDHKeyDomain::KeyDomainPrecompiledType_1024, true); IDHPublicKeyPtr alicePublicKey = IDHPublicKey::load(aliceStaticPublic, aliceEmpheralPublic); IDHPrivateKeyPtr alicePrivateKey = IDHPrivateKey::load(keyDomain, aliceStaticPrivate, aliceEmpheralPrivate); IDHPublicKeyPtr bobPublicKey = IDHPublicKey::load(bobStaticPublic, bobEmpheralPublic); IDHPrivateKeyPtr bobPrivateKey = IDHPrivateKey::load(altKeyDomain, bobStaticPrivate, bobEmpheralPrivate); TESTING_CHECK((bool)alicePublicKey) TESTING_CHECK((bool)alicePrivateKey) TESTING_CHECK((bool)bobPublicKey) TESTING_CHECK((bool)bobPrivateKey) SecureByteBlockPtr aliceSecret = alicePrivateKey->getSharedSecret(bobPublicKey); SecureByteBlockPtr bobSecret = bobPrivateKey->getSharedSecret(alicePublicKey); TESTING_CHECK(IHelper::hasData(aliceSecret)) // alice will pass because bob's public key was created using the original key domain if (bobSecret) { TESTING_CHECK(0 != IHelper::compare(*aliceSecret, *bobSecret)) // must not match if it exists (hopefully should fail validation) } TESTING_CHECK(0 == IHelper::compare(*aliceSecret, *checkAgain)) // must still match since it's valid } { TESTING_EQUAL(4, 4) IDHKeyDomainPtr keyDomain = IDHKeyDomain::load(p, q, g, true); IDHKeyDomainPtr altKeyDomain = IDHKeyDomain::loadPrecompiled(IDHKeyDomain::KeyDomainPrecompiledType_1024, true); // generate a whole new set of keys IDHPublicKeyPtr alicePublicKey; IDHPrivateKeyPtr alicePrivateKey = IDHPrivateKey::generate(keyDomain, alicePublicKey); IDHPublicKeyPtr bobPublicKey; IDHPrivateKeyPtr bobPrivateKey = IDHPrivateKey::generate(altKeyDomain, bobPublicKey); TESTING_CHECK((bool)alicePublicKey) TESTING_CHECK((bool)alicePrivateKey) TESTING_CHECK((bool)bobPublicKey) TESTING_CHECK((bool)bobPrivateKey) SecureByteBlockPtr aliceSecret = alicePrivateKey->getSharedSecret(bobPublicKey); SecureByteBlockPtr bobSecret = bobPrivateKey->getSharedSecret(alicePublicKey); if ((aliceSecret) && (bobSecret)) { TESTING_CHECK(0 != IHelper::compare(*aliceSecret, *bobSecret)) // must not match if it exists (hopefully should fail validation) } } { TESTING_EQUAL(5, 5) IDHKeyDomainPtr keyDomain = IDHKeyDomain::load(p, q, g, true); // generate a whole new set of keys IDHPublicKeyPtr alicePublicKey; IDHPrivateKeyPtr alicePrivateKey = IDHPrivateKey::generate(keyDomain, alicePublicKey); IDHPublicKeyPtr bobPublicKeyOfficial; // NOT USED IDHPrivateKeyPtr bobPrivateKey = IDHPrivateKey::generate(keyDomain, bobPublicKeyOfficial); // except bob's public key was messed up intentionally IDHPublicKeyPtr bobPublicKey; IDHPrivateKeyPtr bogusPrivateKey = IDHPrivateKey::generate(keyDomain, bobPublicKey); TESTING_CHECK((bool)alicePublicKey) TESTING_CHECK((bool)alicePrivateKey) TESTING_CHECK((bool)bobPublicKeyOfficial) TESTING_CHECK((bool)bobPrivateKey) SecureByteBlockPtr aliceSecret = alicePrivateKey->getSharedSecret(bobPublicKey); SecureByteBlockPtr bobSecret = bobPrivateKey->getSharedSecret(alicePublicKey); if ((aliceSecret) && (bobSecret)) { TESTING_CHECK(0 != IHelper::compare(*aliceSecret, *bobSecret)) // must not match if it exists (hopefully should fail validation) } } } TESTING_EQUAL(6, 6) for (int index = 0; precompiled[index] != IDHKeyDomain::KeyDomainPrecompiledType_Unknown; ++index) { bool found = true; IDHKeyDomainPtr keyDomain = IDHKeyDomain::loadPrecompiled(precompiled[index], true); if (!keyDomain) { keyDomain = IDHKeyDomain::generate(precompiled[index]); found = false; } TESTING_CHECK((bool)keyDomain) IDHPublicKeyPtr alicePublicKey; IDHPrivateKeyPtr alicePrivateKey = IDHPrivateKey::generate(keyDomain, alicePublicKey); IDHPublicKeyPtr bobPublicKey; IDHPrivateKeyPtr bobPrivateKey = IDHPrivateKey::generate(keyDomain, bobPublicKey); TESTING_CHECK((bool)alicePublicKey) TESTING_CHECK((bool)alicePrivateKey) TESTING_CHECK((bool)bobPublicKey) TESTING_CHECK((bool)bobPrivateKey) SecureByteBlockPtr aliceSecret = alicePrivateKey->getSharedSecret(bobPublicKey); SecureByteBlockPtr bobSecret = bobPrivateKey->getSharedSecret(alicePublicKey); TESTING_CHECK(IHelper::hasData(aliceSecret)) TESTING_CHECK(IHelper::hasData(bobSecret)) TESTING_CHECK(0 == IHelper::compare(*aliceSecret, *bobSecret)) if (found) { TESTING_CHECK(precompiled[index] == keyDomain->getPrecompiledType()) } } } }
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2020, Alliance for Sustainable Energy, LLC, and other contributors. 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 any contributors may be used to endorse or promote products * derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works * may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior * written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY 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(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED * STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 "../ForwardTranslator.hpp" #include "../../model/HeatBalanceAlgorithm.hpp" #include "../../utilities/idd/IddEnums.hpp" #include <utilities/idd/HeatBalanceAlgorithm_FieldEnums.hxx> #include <utilities/idd/IddEnums.hxx> using namespace openstudio::model; namespace openstudio { namespace energyplus { boost::optional<IdfObject> ForwardTranslator::translateHeatBalanceAlgorithm( HeatBalanceAlgorithm & modelObject ) { IdfObject idfObject( openstudio::IddObjectType::HeatBalanceAlgorithm); idfObject.setString(HeatBalanceAlgorithmFields::Algorithm,modelObject.algorithm()); idfObject.setDouble(HeatBalanceAlgorithmFields::SurfaceTemperatureUpperLimit,modelObject.surfaceTemperatureUpperLimit()); if (!modelObject.isMinimumSurfaceConvectionHeatTransferCoefficientValueDefaulted()) { idfObject.setDouble(HeatBalanceAlgorithmFields::MinimumSurfaceConvectionHeatTransferCoefficientValue, modelObject.minimumSurfaceConvectionHeatTransferCoefficientValue()); } if (!modelObject.isMaximumSurfaceConvectionHeatTransferCoefficientValueDefaulted()) { idfObject.setDouble(HeatBalanceAlgorithmFields::MaximumSurfaceConvectionHeatTransferCoefficientValue, modelObject.maximumSurfaceConvectionHeatTransferCoefficientValue()); } m_idfObjects.push_back(idfObject); return boost::optional<IdfObject>(idfObject); } } // energyplus } // openstudio
#include "Mesh.h" Vertex::Vertex(vec3 coords, vec3 normals, vec2 textures) { this->coords = coords; this->normals = normals; this->textures = textures; } vec3 Vertex::getCoords() { return coords; } vec3 Vertex::getNormals() { return normals; } vec2 Vertex::getTextures() { return textures; } vector<int> Vertex::getIndexes() { return indexes; } void Vertex::setCoords(vec3 coords) { this->coords = coords; } void Vertex::setNormals(vec3 normals) { this->normals = normals; } void Vertex::setTextures(vec2 textures) { this->textures = textures; } void Vertex::addIndex(int index) { indexes.push_back(index); } bool Vertex::equals(Vertex vertex) { return all(equal(this->coords, vertex.coords)) && all(equal(this->normals, vertex.normals)) && all(equal(this->textures, vertex.textures)); } Mesh::Mesh() { } Vertex* Mesh::add_vertex(Vertex vertex) { ostringstream oss; vec3 coords = vertex.getCoords(); return &mesh.insert(pair<string,Vertex>(oss.str(), vertex))->second; } Vertex* Mesh::get_vertex(Vertex vertex) { ostringstream oss; vec3 coords = vertex.getCoords(); pair<unordered_multimap<string, Vertex>::iterator,unordered_multimap<string, Vertex>::iterator> equal_map = mesh.equal_range(oss.str()); for (unordered_multimap<string, Vertex>::iterator it = equal_map.first; it != equal_map.second; ++it) { if (it->second.equals(vertex)) { return &it->second; } } return nullptr; } pair<unordered_multimap<string,Vertex>::iterator,unordered_multimap<string,Vertex>::iterator> Mesh::getIterators(){ return pair<unordered_multimap<string,Vertex>::iterator,unordered_multimap<string,Vertex>::iterator>(mesh.begin(), mesh.end()); } int Mesh::getSize() { return mesh.size(); }
#include "RenderList.h" #include <Engine/Output/Graphics/Scene/GraphicsScene/GraphicsScene.h> #include <Engine/Output/Graphics/Scene/TiledSpace/TiledSpace3D/TiledSpace3D.h> RenderList::RenderList(void) {} RenderList::~RenderList(void) {} MagicList<GraphicsObject>::AddressDerived* RenderList::AddObject(GraphicsObject* _object) { if(_object == NIL || _object == scene) { return NIL; } if(_object->graphicsContainer.IsNotEmpty()) { return NIL; } if(_object->IsClassPropertyExist(GraphicsScene::GRAPHICS_SCENE_CLASS)) { GraphicsScene* it = dynamic_cast<GraphicsScene*>(_object); if(IsParentScene(it)) { return NIL; } } return AddToTail(_object); } MagicList<GraphicsObject>::AddressDerived* RenderList::AddObject(GraphicsObject* _parent, GraphicsObject* _object) { if(_object == NIL || _object == scene) { return NIL; } if(_object->graphicsContainer.IsNotEmpty()) { return NIL; } if(_object->IsClassPropertyExist(GraphicsScene::GRAPHICS_SCENE_CLASS)) { GraphicsScene* it = dynamic_cast<GraphicsScene*>(_object); if(IsParentScene(it)) { return NIL; } } else if(_object->IsClassPropertyExist(TiledSpace3D::TILED_SPACE_3D_CLASS)) { TiledSpace3D* it = dynamic_cast<TiledSpace3D*>(_object); if(IsParentScene(it)) { return NIL; } } return AddToRight(_parent, _object); } bool RenderList::IsParentScene(TiledSpace3D* _tiledSpace) { if(scene->graphicsContainer.IsNotEmpty()) { if(scene->graphicsContainer.Get()->IsClassPropertyExist(GraphicsScene::GRAPHICS_SCENE_CLASS)) { GraphicsScene* it = dynamic_cast<GraphicsScene*>(scene->graphicsContainer.Get()); return it->GetRenderList().IsParentScene(_tiledSpace); } else if(scene->graphicsContainer.Get()->IsClassPropertyExist(TiledSpace3D::TILED_SPACE_3D_CLASS)) { TiledSpace3D* it = dynamic_cast<TiledSpace3D*>(scene->graphicsContainer.Get()); if(it == _tiledSpace) { return true; } return it->IsParentScene(_tiledSpace); } } return false; } bool RenderList::IsParentScene(GraphicsScene* _scene) { if(scene->graphicsContainer.IsNotEmpty()) { if(scene->graphicsContainer.Get()->IsClassPropertyExist(GraphicsScene::GRAPHICS_SCENE_CLASS)) { GraphicsScene* it = dynamic_cast<GraphicsScene*>(scene->graphicsContainer.Get()); if(it == _scene) { return true; } return it->GetRenderList().IsParentScene(_scene); } else if(scene->graphicsContainer.Get()->IsClassPropertyExist(TiledSpace3D::TILED_SPACE_3D_CLASS)) { TiledSpace3D* it = dynamic_cast<TiledSpace3D*>(scene->graphicsContainer.Get()); return it->IsParentScene(_scene); } } return false; } void RenderList::RemoveNodeEvent(MagicNode* _node) { GraphicsObject* object = dynamic_cast<GraphicsObject*>(_node); object->graphicsContainer.Clear(MagicContainer::REMOVE_NODE); object->ResetTransformationValid(); if(scene->IsReceiversExist(GraphicsScene::REMOVE_FROM_RENDER_LIST_MESSAGE)) { scene->SendPackage(GraphicsScene::REMOVE_FROM_RENDER_LIST_MESSAGE, object); } } void RenderList::AddNodeEvent(MagicNode* _node) { GraphicsObject* object = dynamic_cast<GraphicsObject*>(_node); object->graphicsContainer.Attach(scene); object->ResetTransformationValid(); if(scene->IsReceiversExist(GraphicsScene::ADD_TO_RENDER_LIST_MESSAGE)) { scene->SendPackage(GraphicsScene::ADD_TO_RENDER_LIST_MESSAGE, object); } } AbstractObject* RenderList::FindObject(StringANSI _name) { return Find(_name, &AbstractObject::GetName); }
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ // // @author raver119@gmail.com // #include <system/op_boilerplate.h> #if NOT_EXCLUDED(OP_set_seed) #include <ops/declarable/CustomOperations.h> #include <legacy/NativeOps.h> namespace sd { namespace ops { CUSTOM_OP_IMPL(set_seed, -2, 1, false, 0, -2) { // REQUIRE_TRUE(block.getRNG() != nullptr, 0, "RNG should be defined in Graph"); auto rng = block.getRng(); //.getRNG(); Nd4jLong seed = 0; if (block.getIArguments()->size() > 0) { seed = INT_ARG(0); } else if (block.width() > 0) { auto input = INPUT_VARIABLE(0); REQUIRE_TRUE(input->isScalar(),0 ,"SetSeed: Seed operand should be scalar"); seed = input->e<Nd4jLong>(0); } else { REQUIRE_TRUE(false, 0, "SetSeed: either IArg or scalr input should be provided"); } // FIXME: this approach isn't really good for cuda, since it'll assume that CUDA might get nullptr instead of stream //refreshBuffer(nullptr, seed, (Nd4jPointer) rng); rng.setSeed((int)seed); return Status::OK(); } DECLARE_SHAPE_FN(set_seed) { auto newshape = ConstantShapeHelper::getInstance().scalarShapeInfo(block.dataType()); return SHAPELIST(newshape); } DECLARE_TYPES(set_seed) { getOpDescriptor() ->setAllowedInputTypes({ALL_INTS}) ->setAllowedOutputTypes({ALL_FLOATS}); } } } #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 "chrome/browser/history/url_index_private_data.h" #include <algorithm> #include <functional> #include <iterator> #include <limits> #include <numeric> #include "base/file_util.h" #include "base/i18n/case_conversion.h" #include "base/metrics/histogram.h" #include "base/string_util.h" #include "base/time.h" #include "base/utf_string_conversions.h" #include "chrome/browser/autocomplete/autocomplete.h" #include "chrome/browser/history/history_database.h" #include "chrome/browser/history/in_memory_url_index.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" #include "net/base/net_util.h" #include "third_party/protobuf/src/google/protobuf/repeated_field.h" using google::protobuf::RepeatedField; using google::protobuf::RepeatedPtrField; using in_memory_url_index::InMemoryURLIndexCacheItem; namespace history { typedef imui::InMemoryURLIndexCacheItem_WordListItem WordListItem; typedef imui::InMemoryURLIndexCacheItem_WordMapItem_WordMapEntry WordMapEntry; typedef imui::InMemoryURLIndexCacheItem_WordMapItem WordMapItem; typedef imui::InMemoryURLIndexCacheItem_CharWordMapItem CharWordMapItem; typedef imui::InMemoryURLIndexCacheItem_CharWordMapItem_CharWordMapEntry CharWordMapEntry; typedef imui::InMemoryURLIndexCacheItem_WordIDHistoryMapItem WordIDHistoryMapItem; typedef imui:: InMemoryURLIndexCacheItem_WordIDHistoryMapItem_WordIDHistoryMapEntry WordIDHistoryMapEntry; typedef imui::InMemoryURLIndexCacheItem_HistoryInfoMapItem HistoryInfoMapItem; typedef imui::InMemoryURLIndexCacheItem_HistoryInfoMapItem_HistoryInfoMapEntry HistoryInfoMapEntry; typedef imui::InMemoryURLIndexCacheItem_WordStartsMapItem WordStartsMapItem; typedef imui::InMemoryURLIndexCacheItem_WordStartsMapItem_WordStartsMapEntry WordStartsMapEntry; // The maximum score any candidate result can achieve. const int kMaxTotalScore = 1425; // Score ranges used to get a 'base' score for each of the scoring factors // (such as recency of last visit, times visited, times the URL was typed, // and the quality of the string match). There is a matching value range for // each of these scores for each factor. Note that the top score is greater // than |kMaxTotalScore|. The score for each candidate will be capped in the // final calculation. const int kScoreRank[] = { 1450, 1200, 900, 400 }; // SearchTermCacheItem --------------------------------------------------------- URLIndexPrivateData::SearchTermCacheItem::SearchTermCacheItem( const WordIDSet& word_id_set, const HistoryIDSet& history_id_set) : word_id_set_(word_id_set), history_id_set_(history_id_set), used_(true) {} URLIndexPrivateData::SearchTermCacheItem::SearchTermCacheItem() : used_(true) {} URLIndexPrivateData::SearchTermCacheItem::~SearchTermCacheItem() {} // Algorithm Functions --------------------------------------------------------- // Comparison function for sorting search terms by descending length. bool LengthGreater(const string16& string_a, const string16& string_b) { return string_a.length() > string_b.length(); } // std::accumulate helper function to add up TermMatches' lengths. int AccumulateMatchLength(int total, const TermMatch& match) { return total + match.length; } // Converts a raw value for some particular scoring factor into a score // component for that factor. The conversion function is piecewise linear, with // input values provided in |value_ranks| and resulting output scores from // |kScoreRank| (mathematically, f(value_rank[i]) = kScoreRank[i]). A score // cannot be higher than kScoreRank[0], and drops directly to 0 if lower than // kScoreRank[3]. // // For example, take |value| == 70 and |value_ranks| == { 100, 50, 30, 10 }. // Because 70 falls between ranks 0 (100) and 1 (50), the score is given by the // linear function: // score = m * value + b, where // m = (kScoreRank[0] - kScoreRank[1]) / (value_ranks[0] - value_ranks[1]) // b = value_ranks[1] // Any value higher than 100 would be scored as if it were 100, and any value // lower than 10 scored 0. int ScoreForValue(int value, const int* value_ranks) { int i = 0; int rank_count = arraysize(kScoreRank); while ((i < rank_count) && ((value_ranks[0] < value_ranks[1]) ? (value > value_ranks[i]) : (value < value_ranks[i]))) ++i; if (i >= rank_count) return 0; int score = kScoreRank[i]; if (i > 0) { score += (value - value_ranks[i]) * (kScoreRank[i - 1] - kScoreRank[i]) / (value_ranks[i - 1] - value_ranks[i]); } return score; } // InMemoryURLIndex's Private Data --------------------------------------------- URLIndexPrivateData::URLIndexPrivateData() : restored_cache_version_(0), saved_cache_version_(kCurrentCacheFileVersion), pre_filter_item_count_(0), post_filter_item_count_(0), post_scoring_item_count_(0) { } URLIndexPrivateData::~URLIndexPrivateData() {} void URLIndexPrivateData::Clear() { word_list_.clear(); available_words_.clear(); word_map_.clear(); char_word_map_.clear(); word_id_history_map_.clear(); history_id_word_map_.clear(); history_info_map_.clear(); word_starts_map_.clear(); } bool URLIndexPrivateData::Empty() const { return history_info_map_.empty(); } scoped_refptr<URLIndexPrivateData> URLIndexPrivateData::Duplicate() const { scoped_refptr<URLIndexPrivateData> data_copy = new URLIndexPrivateData; data_copy->word_list_ = word_list_; data_copy->available_words_ = available_words_; data_copy->word_map_ = word_map_; data_copy->char_word_map_ = char_word_map_; data_copy->word_id_history_map_ = word_id_history_map_; data_copy->history_id_word_map_ = history_id_word_map_; data_copy->history_info_map_ = history_info_map_; data_copy->word_starts_map_ = word_starts_map_; return data_copy; // Not copied: // search_term_cache_ // pre_filter_item_count_ // post_filter_item_count_ // post_scoring_item_count_ }; // Cache Updating -------------------------------------------------------------- bool URLIndexPrivateData::IndexRow( const URLRow& row, const std::string& languages, const std::set<std::string>& scheme_whitelist) { const GURL& gurl(row.url()); // Index only URLs with a whitelisted scheme. if (!URLSchemeIsWhitelisted(gurl, scheme_whitelist)) return false; URLID row_id = row.id(); // Strip out username and password before saving and indexing. string16 url(net::FormatUrl(gurl, languages, net::kFormatUrlOmitUsernamePassword, net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS, NULL, NULL, NULL)); HistoryID history_id = static_cast<HistoryID>(row_id); DCHECK_LT(history_id, std::numeric_limits<HistoryID>::max()); // Add the row for quick lookup in the history info store. URLRow new_row(GURL(url), row_id); new_row.set_visit_count(row.visit_count()); new_row.set_typed_count(row.typed_count()); new_row.set_last_visit(row.last_visit()); new_row.set_title(row.title()); history_info_map_[history_id] = new_row; // Index the words contained in the URL and title of the row. RowWordStarts word_starts; AddRowWordsToIndex(new_row, &word_starts, languages); word_starts_map_[history_id] = word_starts; return true; } void URLIndexPrivateData::AddRowWordsToIndex(const URLRow& row, RowWordStarts* word_starts, const std::string& languages) { HistoryID history_id = static_cast<HistoryID>(row.id()); // Split URL into individual, unique words then add in the title words. const GURL& gurl(row.url()); string16 url(net::FormatUrl(gurl, languages, net::kFormatUrlOmitUsernamePassword, net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS, NULL, NULL, NULL)); url = base::i18n::ToLower(url); String16Set url_words = String16SetFromString16(url, word_starts ? &word_starts->url_word_starts_ : NULL); String16Set title_words = String16SetFromString16(row.title(), word_starts ? &word_starts->title_word_starts_ : NULL); String16Set words; std::set_union(url_words.begin(), url_words.end(), title_words.begin(), title_words.end(), std::insert_iterator<String16Set>(words, words.begin())); for (String16Set::iterator word_iter = words.begin(); word_iter != words.end(); ++word_iter) AddWordToIndex(*word_iter, history_id); search_term_cache_.clear(); // Invalidate the term cache. } void URLIndexPrivateData::AddWordToIndex(const string16& term, HistoryID history_id) { WordMap::iterator word_pos = word_map_.find(term); if (word_pos != word_map_.end()) UpdateWordHistory(word_pos->second, history_id); else AddWordHistory(term, history_id); } void URLIndexPrivateData::UpdateWordHistory(WordID word_id, HistoryID history_id) { WordIDHistoryMap::iterator history_pos = word_id_history_map_.find(word_id); DCHECK(history_pos != word_id_history_map_.end()); HistoryIDSet& history_id_set(history_pos->second); history_id_set.insert(history_id); AddToHistoryIDWordMap(history_id, word_id); } void URLIndexPrivateData::AddWordHistory(const string16& term, HistoryID history_id) { WordID word_id = word_list_.size(); if (available_words_.empty()) { word_list_.push_back(term); } else { word_id = *(available_words_.begin()); word_list_[word_id] = term; available_words_.erase(word_id); } word_map_[term] = word_id; HistoryIDSet history_id_set; history_id_set.insert(history_id); word_id_history_map_[word_id] = history_id_set; AddToHistoryIDWordMap(history_id, word_id); // For each character in the newly added word (i.e. a word that is not // already in the word index), add the word to the character index. Char16Set characters = Char16SetFromString16(term); for (Char16Set::iterator uni_char_iter = characters.begin(); uni_char_iter != characters.end(); ++uni_char_iter) { char16 uni_char = *uni_char_iter; CharWordIDMap::iterator char_iter = char_word_map_.find(uni_char); if (char_iter != char_word_map_.end()) { // Update existing entry in the char/word index. WordIDSet& word_id_set(char_iter->second); word_id_set.insert(word_id); } else { // Create a new entry in the char/word index. WordIDSet word_id_set; word_id_set.insert(word_id); char_word_map_[uni_char] = word_id_set; } } } void URLIndexPrivateData::RemoveRowFromIndex(const URLRow& row) { RemoveRowWordsFromIndex(row); HistoryID history_id = static_cast<HistoryID>(row.id()); history_info_map_.erase(history_id); word_starts_map_.erase(history_id); } void URLIndexPrivateData::RemoveRowWordsFromIndex(const URLRow& row) { // Remove the entries in history_id_word_map_ and word_id_history_map_ for // this row. HistoryID history_id = static_cast<HistoryID>(row.id()); WordIDSet word_id_set = history_id_word_map_[history_id]; history_id_word_map_.erase(history_id); // Reconcile any changes to word usage. for (WordIDSet::iterator word_id_iter = word_id_set.begin(); word_id_iter != word_id_set.end(); ++word_id_iter) { WordID word_id = *word_id_iter; word_id_history_map_[word_id].erase(history_id); if (!word_id_history_map_[word_id].empty()) continue; // The word is still in use. // The word is no longer in use. Reconcile any changes to character usage. string16 word = word_list_[word_id]; Char16Set characters = Char16SetFromString16(word); for (Char16Set::iterator uni_char_iter = characters.begin(); uni_char_iter != characters.end(); ++uni_char_iter) { char16 uni_char = *uni_char_iter; char_word_map_[uni_char].erase(word_id); if (char_word_map_[uni_char].empty()) char_word_map_.erase(uni_char); // No longer in use. } // Complete the removal of references to the word. word_id_history_map_.erase(word_id); word_map_.erase(word); word_list_[word_id] = string16(); available_words_.insert(word_id); } } void URLIndexPrivateData::AddToHistoryIDWordMap(HistoryID history_id, WordID word_id) { HistoryIDWordMap::iterator iter = history_id_word_map_.find(history_id); if (iter != history_id_word_map_.end()) { WordIDSet& word_id_set(iter->second); word_id_set.insert(word_id); } else { WordIDSet word_id_set; word_id_set.insert(word_id); history_id_word_map_[history_id] = word_id_set; } } bool URLIndexPrivateData::UpdateURL( const URLRow& row, const std::string& languages, const std::set<std::string>& scheme_whitelist) { // The row may or may not already be in our index. If it is not already // indexed and it qualifies then it gets indexed. If it is already // indexed and still qualifies then it gets updated, otherwise it // is deleted from the index. bool row_was_updated = false; URLID row_id = row.id(); HistoryInfoMap::iterator row_pos = history_info_map_.find(row_id); if (row_pos == history_info_map_.end()) { // This new row should be indexed if it qualifies. URLRow new_row(row); new_row.set_id(row_id); row_was_updated = RowQualifiesAsSignificant(new_row, base::Time()) && IndexRow(new_row, languages, scheme_whitelist); } else if (RowQualifiesAsSignificant(row, base::Time())) { // This indexed row still qualifies and will be re-indexed. // The url won't have changed but the title, visit count, etc. // might have changed. URLRow& row_to_update = row_pos->second; bool title_updated = row_to_update.title() != row.title(); if (row_to_update.visit_count() != row.visit_count() || row_to_update.typed_count() != row.typed_count() || row_to_update.last_visit() != row.last_visit() || title_updated) { row_to_update.set_visit_count(row.visit_count()); row_to_update.set_typed_count(row.typed_count()); row_to_update.set_last_visit(row.last_visit()); // While the URL is guaranteed to remain stable, the title may have // changed. If so, then update the index with the changed words. if (title_updated) { // Clear all words associated with this row and re-index both the // URL and title. RemoveRowWordsFromIndex(row_to_update); row_to_update.set_title(row.title()); RowWordStarts word_starts; AddRowWordsToIndex(row_to_update, &word_starts, languages); word_starts_map_[row_id] = word_starts; } row_was_updated = true; } } else { // This indexed row no longer qualifies and will be de-indexed by // clearing all words associated with this row. RemoveRowFromIndex(row); row_was_updated = true; } if (row_was_updated) search_term_cache_.clear(); // This invalidates the cache. return row_was_updated; } // Helper functor for DeleteURL. class HistoryInfoMapItemHasURL { public: explicit HistoryInfoMapItemHasURL(const GURL& url): url_(url) {} bool operator()(const std::pair<const HistoryID, URLRow>& item) { return item.second.url() == url_; } private: const GURL& url_; }; bool URLIndexPrivateData::DeleteURL(const GURL& url) { // Find the matching entry in the history_info_map_. HistoryInfoMap::iterator pos = std::find_if( history_info_map_.begin(), history_info_map_.end(), HistoryInfoMapItemHasURL(url)); if (pos == history_info_map_.end()) return false; RemoveRowFromIndex(pos->second); search_term_cache_.clear(); // This invalidates the cache. return true; } // URLIndexPrivateData::HistoryItemFactorGreater ------------------------------- URLIndexPrivateData::HistoryItemFactorGreater::HistoryItemFactorGreater( const HistoryInfoMap& history_info_map) : history_info_map_(history_info_map) { } URLIndexPrivateData::HistoryItemFactorGreater::~HistoryItemFactorGreater() {} bool URLIndexPrivateData::HistoryItemFactorGreater::operator()( const HistoryID h1, const HistoryID h2) { HistoryInfoMap::const_iterator entry1(history_info_map_.find(h1)); if (entry1 == history_info_map_.end()) return false; HistoryInfoMap::const_iterator entry2(history_info_map_.find(h2)); if (entry2 == history_info_map_.end()) return true; const URLRow& r1(entry1->second); const URLRow& r2(entry2->second); // First cut: typed count, visit count, recency. // TODO(mrossetti): This is too simplistic. Consider an approach which ranks // recently visited (within the last 12/24 hours) as highly important. Get // input from mpearson. if (r1.typed_count() != r2.typed_count()) return (r1.typed_count() > r2.typed_count()); if (r1.visit_count() != r2.visit_count()) return (r1.visit_count() > r2.visit_count()); return (r1.last_visit() > r2.last_visit()); } // Cache Searching ------------------------------------------------------------- // NOTE: This is the main public search function. ScoredHistoryMatches URLIndexPrivateData::HistoryItemsForTerms( const string16& search_string) { pre_filter_item_count_ = 0; post_filter_item_count_ = 0; post_scoring_item_count_ = 0; // The search string we receive may contain escaped characters. For reducing // the index we need individual, lower-cased words, ignoring escapings. For // the final filtering we need whitespace separated substrings possibly // containing escaped characters. string16 lower_raw_string(base::i18n::ToLower(search_string)); string16 lower_unescaped_string = net::UnescapeURLComponent(lower_raw_string, net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS); // Extract individual 'words' (as opposed to 'terms'; see below) from the // search string. When the user types "colspec=ID%20Mstone Release" we get // four 'words': "colspec", "id", "mstone" and "release". String16Vector lower_words( history::String16VectorFromString16(lower_unescaped_string, false, NULL)); ScoredHistoryMatches scored_items; // Do nothing if we have indexed no words (probably because we've not been // initialized yet) or the search string has no words. if (word_list_.empty() || lower_words.empty()) { search_term_cache_.clear(); // Invalidate the term cache. return scored_items; } // Reset used_ flags for search_term_cache_. We use a basic mark-and-sweep // approach. ResetSearchTermCache(); HistoryIDSet history_id_set = HistoryIDSetFromWords(lower_words); // Trim the candidate pool if it is large. Note that we do not filter out // items that do not contain the search terms as proper substrings -- doing // so is the performance-costly operation we are trying to avoid in order // to maintain omnibox responsiveness. const size_t kItemsToScoreLimit = 500; pre_filter_item_count_ = history_id_set.size(); // If we trim the results set we do not want to cache the results for next // time as the user's ultimately desired result could easily be eliminated // in this early rough filter. bool was_trimmed = (pre_filter_item_count_ > kItemsToScoreLimit); if (was_trimmed) { HistoryIDVector history_ids; std::copy(history_id_set.begin(), history_id_set.end(), std::back_inserter(history_ids)); // Trim down the set by sorting by typed-count, visit-count, and last // visit. HistoryItemFactorGreater item_factor_functor(history_info_map_); std::partial_sort(history_ids.begin(), history_ids.begin() + kItemsToScoreLimit, history_ids.end(), item_factor_functor); history_id_set.clear(); std::copy(history_ids.begin(), history_ids.begin() + kItemsToScoreLimit, std::inserter(history_id_set, history_id_set.end())); post_filter_item_count_ = history_id_set.size(); } // Pass over all of the candidates filtering out any without a proper // substring match, inserting those which pass in order by score. Note that // in this step we are using the raw search string complete with escaped // URL elements. When the user has specifically typed something akin to // "sort=pri&colspec=ID%20Mstone%20Release" we want to make sure that that // specific substring appears in the URL or page title. // We call these 'terms' (as opposed to 'words'; see above) as in this case // we only want to break up the search string on 'true' whitespace rather than // escaped whitespace. When the user types "colspec=ID%20Mstone Release" we // get two 'terms': "colspec=id%20mstone" and "release". history::String16Vector lower_raw_terms; Tokenize(lower_raw_string, kWhitespaceUTF16, &lower_raw_terms); scored_items = std::for_each(history_id_set.begin(), history_id_set.end(), AddHistoryMatch(*this, lower_raw_string, lower_raw_terms)).ScoredMatches(); // Select and sort only the top kMaxMatches results. if (scored_items.size() > AutocompleteProvider::kMaxMatches) { std::partial_sort(scored_items.begin(), scored_items.begin() + AutocompleteProvider::kMaxMatches, scored_items.end(), ScoredHistoryMatch::MatchScoreGreater); scored_items.resize(AutocompleteProvider::kMaxMatches); } else { std::sort(scored_items.begin(), scored_items.end(), ScoredHistoryMatch::MatchScoreGreater); } post_scoring_item_count_ = scored_items.size(); if (was_trimmed) { search_term_cache_.clear(); // Invalidate the term cache. } else { // Remove any stale SearchTermCacheItems. for (SearchTermCacheMap::iterator cache_iter = search_term_cache_.begin(); cache_iter != search_term_cache_.end(); ) { if (!cache_iter->second.used_) search_term_cache_.erase(cache_iter++); else ++cache_iter; } } return scored_items; } // URLIndexPrivateData::AddHistoryMatch ---------------------------------------- URLIndexPrivateData::AddHistoryMatch::AddHistoryMatch( const URLIndexPrivateData& private_data, const string16& lower_string, const String16Vector& lower_terms) : private_data_(private_data), lower_string_(lower_string), lower_terms_(lower_terms) {} URLIndexPrivateData::AddHistoryMatch::~AddHistoryMatch() {} void URLIndexPrivateData::AddHistoryMatch::operator()( const HistoryID history_id) { HistoryInfoMap::const_iterator hist_pos = private_data_.history_info_map_.find(history_id); // Note that a history_id may be present in the word_id_history_map_ yet not // be found in the history_info_map_. This occurs when an item has been // deleted by the user or the item no longer qualifies as a quick result. if (hist_pos != private_data_.history_info_map_.end()) { const URLRow& hist_item = hist_pos->second; WordStartsMap::const_iterator starts_pos = private_data_.word_starts_map_.find(history_id); DCHECK(starts_pos != private_data_.word_starts_map_.end()); ScoredHistoryMatch match(ScoredMatchForURL(hist_item, lower_string_, lower_terms_, starts_pos->second)); if (match.raw_score > 0) scored_matches_.push_back(match); } } // static // TODO(mrossetti): This can be made a ctor for ScoredHistoryMatch. ScoredHistoryMatch URLIndexPrivateData::ScoredMatchForURL( const URLRow& row, const string16& lower_string, const String16Vector& terms, const RowWordStarts& word_starts) { ScoredHistoryMatch match(row); GURL gurl = row.url(); if (!gurl.is_valid()) return match; // Figure out where each search term appears in the URL and/or page title // so that we can score as well as provide autocomplete highlighting. string16 url = base::i18n::ToLower(UTF8ToUTF16(gurl.spec())); string16 title = base::i18n::ToLower(row.title()); int term_num = 0; for (String16Vector::const_iterator iter = terms.begin(); iter != terms.end(); ++iter, ++term_num) { string16 term = *iter; TermMatches url_term_matches = MatchTermInString(term, url, term_num); TermMatches title_term_matches = MatchTermInString(term, title, term_num); if (url_term_matches.empty() && title_term_matches.empty()) return match; // A term was not found in either URL or title - reject. match.url_matches.insert(match.url_matches.end(), url_term_matches.begin(), url_term_matches.end()); match.title_matches.insert(match.title_matches.end(), title_term_matches.begin(), title_term_matches.end()); } // Sort matches by offset and eliminate any which overlap. match.url_matches = SortAndDeoverlapMatches(match.url_matches); match.title_matches = SortAndDeoverlapMatches(match.title_matches); // We can inline autocomplete a result if: // 1) there is only one search term // 2) AND EITHER: // 2a) the first match starts at the beginning of the candidate URL, OR // 2b) the candidate URL starts with one of the standard URL prefixes with // the URL match immediately following that prefix. // 3) AND the search string does not end in whitespace (making it look to // the IMUI as though there is a single search term when actually there // is a second, empty term). match.can_inline = !match.url_matches.empty() && terms.size() == 1 && (match.url_matches[0].offset == 0 || IsInlineablePrefix(url.substr(0, match.url_matches[0].offset))) && !IsWhitespace(*(lower_string.rbegin())); match.match_in_scheme = match.can_inline && match.url_matches[0].offset == 0; // Get partial scores based on term matching. Note that the score for // each of the URL and title are adjusted by the fraction of the // terms appearing in each. int url_score = ScoreComponentForMatches(match.url_matches, url.length()) * std::min(match.url_matches.size(), terms.size()) / terms.size(); int title_score = ScoreComponentForMatches(match.title_matches, title.length()) * std::min(match.title_matches.size(), terms.size()) / terms.size(); // Arbitrarily pick the best. // TODO(mrossetti): It might make sense that a term which appears in both the // URL and the Title should boost the score a bit. int term_score = std::max(url_score, title_score); if (term_score == 0) return match; // Determine scoring factors for the recency of visit, visit count and typed // count attributes of the URLRow. const int kDaysAgoLevel[] = { 1, 10, 20, 30 }; int days_ago_value = ScoreForValue((base::Time::Now() - row.last_visit()).InDays(), kDaysAgoLevel); const int kVisitCountLevel[] = { 50, 30, 10, 5 }; int visit_count_value = ScoreForValue(row.visit_count(), kVisitCountLevel); const int kTypedCountLevel[] = { 50, 30, 10, 5 }; int typed_count_value = ScoreForValue(row.typed_count(), kTypedCountLevel); // The final raw score is calculated by: // - multiplying each factor by a 'relevance' // - calculating the average. // Note that visit_count is reduced by typed_count because both are bumped // when a typed URL is recorded thus giving visit_count too much weight. const int kTermScoreRelevance = 4; const int kDaysAgoRelevance = 2; const int kVisitCountRelevance = 2; const int kTypedCountRelevance = 5; int effective_visit_count_value = std::max(0, visit_count_value - typed_count_value); match.raw_score = term_score * kTermScoreRelevance + days_ago_value * kDaysAgoRelevance + effective_visit_count_value * kVisitCountRelevance + typed_count_value * kTypedCountRelevance; match.raw_score /= (kTermScoreRelevance + kDaysAgoRelevance + kVisitCountRelevance + kTypedCountRelevance); match.raw_score = std::min(kMaxTotalScore, match.raw_score); return match; } int URLIndexPrivateData::ScoreComponentForMatches(const TermMatches& matches, size_t max_length) { if (matches.empty()) return 0; // Score component for whether the input terms (if more than one) were found // in the same order in the match. Start with kOrderMaxValue points divided // equally among (number of terms - 1); then discount each of those terms that // is out-of-order in the match. const int kOrderMaxValue = 1000; int order_value = kOrderMaxValue; if (matches.size() > 1) { int max_possible_out_of_order = matches.size() - 1; int out_of_order = 0; for (size_t i = 1; i < matches.size(); ++i) { if (matches[i - 1].term_num > matches[i].term_num) ++out_of_order; } order_value = (max_possible_out_of_order - out_of_order) * kOrderMaxValue / max_possible_out_of_order; } // Score component for how early in the match string the first search term // appears. Start with kStartMaxValue points and discount by // kStartMaxValue/kMaxSignificantChars points for each character later than // the first at which the term begins. No points are earned if the start of // the match occurs at or after kMaxSignificantChars. const int kStartMaxValue = 1000; int start_value = (kMaxSignificantChars - std::min(kMaxSignificantChars, matches[0].offset)) * kStartMaxValue / kMaxSignificantChars; // Score component for how much of the matched string the input terms cover. // kCompleteMaxValue points times the fraction of the URL/page title string // that was matched. size_t term_length_total = std::accumulate(matches.begin(), matches.end(), 0, AccumulateMatchLength); const size_t kMaxSignificantLength = 50; size_t max_significant_length = std::min(max_length, std::max(term_length_total, kMaxSignificantLength)); const int kCompleteMaxValue = 1000; int complete_value = term_length_total * kCompleteMaxValue / max_significant_length; const int kOrderRelevance = 1; const int kStartRelevance = 6; const int kCompleteRelevance = 3; int raw_score = order_value * kOrderRelevance + start_value * kStartRelevance + complete_value * kCompleteRelevance; raw_score /= (kOrderRelevance + kStartRelevance + kCompleteRelevance); // Scale the raw score into a single score component in the same manner as // used in ScoredMatchForURL(). const int kTermScoreLevel[] = { 1000, 750, 500, 200 }; return ScoreForValue(raw_score, kTermScoreLevel); } void URLIndexPrivateData::ResetSearchTermCache() { for (SearchTermCacheMap::iterator iter = search_term_cache_.begin(); iter != search_term_cache_.end(); ++iter) iter->second.used_ = false; } HistoryIDSet URLIndexPrivateData::HistoryIDSetFromWords( const String16Vector& unsorted_words) { // Break the terms down into individual terms (words), get the candidate // set for each term, and intersect each to get a final candidate list. // Note that a single 'term' from the user's perspective might be // a string like "http://www.somewebsite.com" which, from our perspective, // is four words: 'http', 'www', 'somewebsite', and 'com'. HistoryIDSet history_id_set; String16Vector words(unsorted_words); // Sort the words into the longest first as such are likely to narrow down // the results quicker. Also, single character words are the most expensive // to process so save them for last. std::sort(words.begin(), words.end(), LengthGreater); for (String16Vector::iterator iter = words.begin(); iter != words.end(); ++iter) { string16 uni_word = *iter; HistoryIDSet term_history_set = HistoryIDsForTerm(uni_word); if (term_history_set.empty()) { history_id_set.clear(); break; } if (iter == words.begin()) { history_id_set.swap(term_history_set); } else { HistoryIDSet new_history_id_set; std::set_intersection(history_id_set.begin(), history_id_set.end(), term_history_set.begin(), term_history_set.end(), std::inserter(new_history_id_set, new_history_id_set.begin())); history_id_set.swap(new_history_id_set); } } return history_id_set; } HistoryIDSet URLIndexPrivateData::HistoryIDsForTerm( const string16& term) { if (term.empty()) return HistoryIDSet(); // TODO(mrossetti): Consider optimizing for very common terms such as // 'http[s]', 'www', 'com', etc. Or collect the top 100 more frequently // occuring words in the user's searches. size_t term_length = term.length(); WordIDSet word_id_set; if (term_length > 1) { // See if this term or a prefix thereof is present in the cache. SearchTermCacheMap::iterator best_prefix(search_term_cache_.end()); for (SearchTermCacheMap::iterator cache_iter = search_term_cache_.begin(); cache_iter != search_term_cache_.end(); ++cache_iter) { if (StartsWith(term, cache_iter->first, false) && (best_prefix == search_term_cache_.end() || cache_iter->first.length() > best_prefix->first.length())) best_prefix = cache_iter; } // If a prefix was found then determine the leftover characters to be used // for further refining the results from that prefix. Char16Set prefix_chars; string16 leftovers(term); if (best_prefix != search_term_cache_.end()) { // If the prefix is an exact match for the term then grab the cached // results and we're done. size_t prefix_length = best_prefix->first.length(); if (prefix_length == term_length) { best_prefix->second.used_ = true; return best_prefix->second.history_id_set_; } // Otherwise we have a handy starting point. // If there are no history results for this prefix then we can bail early // as there will be no history results for the full term. if (best_prefix->second.history_id_set_.empty()) { search_term_cache_[term] = SearchTermCacheItem(); return HistoryIDSet(); } word_id_set = best_prefix->second.word_id_set_; prefix_chars = Char16SetFromString16(best_prefix->first); leftovers = term.substr(prefix_length); } // Filter for each remaining, unique character in the term. Char16Set leftover_chars = Char16SetFromString16(leftovers); Char16Set unique_chars; std::set_difference(leftover_chars.begin(), leftover_chars.end(), prefix_chars.begin(), prefix_chars.end(), std::inserter(unique_chars, unique_chars.begin())); // Reduce the word set with any leftover, unprocessed characters. if (!unique_chars.empty()) { WordIDSet leftover_set(WordIDSetForTermChars(unique_chars)); // We might come up empty on the leftovers. if (leftover_set.empty()) { search_term_cache_[term] = SearchTermCacheItem(); return HistoryIDSet(); } // Or there may not have been a prefix from which to start. if (prefix_chars.empty()) { word_id_set.swap(leftover_set); } else { WordIDSet new_word_id_set; std::set_intersection(word_id_set.begin(), word_id_set.end(), leftover_set.begin(), leftover_set.end(), std::inserter(new_word_id_set, new_word_id_set.begin())); word_id_set.swap(new_word_id_set); } } // We must filter the word list because the resulting word set surely // contains words which do not have the search term as a proper subset. for (WordIDSet::iterator word_set_iter = word_id_set.begin(); word_set_iter != word_id_set.end(); ) { if (word_list_[*word_set_iter].find(term) == string16::npos) word_id_set.erase(word_set_iter++); else ++word_set_iter; } } else { word_id_set = WordIDSetForTermChars(Char16SetFromString16(term)); } // If any words resulted then we can compose a set of history IDs by unioning // the sets from each word. HistoryIDSet history_id_set; if (!word_id_set.empty()) { for (WordIDSet::iterator word_id_iter = word_id_set.begin(); word_id_iter != word_id_set.end(); ++word_id_iter) { WordID word_id = *word_id_iter; WordIDHistoryMap::iterator word_iter = word_id_history_map_.find(word_id); if (word_iter != word_id_history_map_.end()) { HistoryIDSet& word_history_id_set(word_iter->second); history_id_set.insert(word_history_id_set.begin(), word_history_id_set.end()); } } } // Record a new cache entry for this word if the term is longer than // a single character. if (term_length > 1) search_term_cache_[term] = SearchTermCacheItem(word_id_set, history_id_set); return history_id_set; } WordIDSet URLIndexPrivateData::WordIDSetForTermChars( const Char16Set& term_chars) { WordIDSet word_id_set; for (Char16Set::const_iterator c_iter = term_chars.begin(); c_iter != term_chars.end(); ++c_iter) { CharWordIDMap::iterator char_iter = char_word_map_.find(*c_iter); if (char_iter == char_word_map_.end()) { // A character was not found so there are no matching results: bail. word_id_set.clear(); break; } WordIDSet& char_word_id_set(char_iter->second); // It is possible for there to no longer be any words associated with // a particular character. Give up in that case. if (char_word_id_set.empty()) { word_id_set.clear(); break; } if (c_iter == term_chars.begin()) { // First character results becomes base set of results. word_id_set = char_word_id_set; } else { // Subsequent character results get intersected in. WordIDSet new_word_id_set; std::set_intersection(word_id_set.begin(), word_id_set.end(), char_word_id_set.begin(), char_word_id_set.end(), std::inserter(new_word_id_set, new_word_id_set.begin())); word_id_set.swap(new_word_id_set); } } return word_id_set; } // Cache Saving ---------------------------------------------------------------- // static void URLIndexPrivateData::WritePrivateDataToCacheFileTask( scoped_refptr<URLIndexPrivateData> private_data, const FilePath& file_path, scoped_refptr<RefCountedBool> succeeded) { DCHECK(private_data.get()); DCHECK(!file_path.empty()); succeeded->set_value(private_data->SaveToFile(file_path)); } bool URLIndexPrivateData::SaveToFile(const FilePath& file_path) { base::TimeTicks beginning_time = base::TimeTicks::Now(); InMemoryURLIndexCacheItem index_cache; SavePrivateData(&index_cache); std::string data; if (!index_cache.SerializeToString(&data)) { LOG(WARNING) << "Failed to serialize the InMemoryURLIndex cache."; return false; } int size = data.size(); if (file_util::WriteFile(file_path, data.c_str(), size) != size) { LOG(WARNING) << "Failed to write " << file_path.value(); return false; } UMA_HISTOGRAM_TIMES("History.InMemoryURLIndexSaveCacheTime", base::TimeTicks::Now() - beginning_time); return true; } void URLIndexPrivateData::SavePrivateData( InMemoryURLIndexCacheItem* cache) const { DCHECK(cache); cache->set_timestamp(base::Time::Now().ToInternalValue()); cache->set_version(saved_cache_version_); // history_item_count_ is no longer used but rather than change the protobuf // definition use a placeholder. This will go away with the switch to SQLite. cache->set_history_item_count(0); SaveWordList(cache); SaveWordMap(cache); SaveCharWordMap(cache); SaveWordIDHistoryMap(cache); SaveHistoryInfoMap(cache); SaveWordStartsMap(cache); } void URLIndexPrivateData::SaveWordList(InMemoryURLIndexCacheItem* cache) const { if (word_list_.empty()) return; WordListItem* list_item = cache->mutable_word_list(); list_item->set_word_count(word_list_.size()); for (String16Vector::const_iterator iter = word_list_.begin(); iter != word_list_.end(); ++iter) list_item->add_word(UTF16ToUTF8(*iter)); } void URLIndexPrivateData::SaveWordMap(InMemoryURLIndexCacheItem* cache) const { if (word_map_.empty()) return; WordMapItem* map_item = cache->mutable_word_map(); map_item->set_item_count(word_map_.size()); for (WordMap::const_iterator iter = word_map_.begin(); iter != word_map_.end(); ++iter) { WordMapEntry* map_entry = map_item->add_word_map_entry(); map_entry->set_word(UTF16ToUTF8(iter->first)); map_entry->set_word_id(iter->second); } } void URLIndexPrivateData::SaveCharWordMap( InMemoryURLIndexCacheItem* cache) const { if (char_word_map_.empty()) return; CharWordMapItem* map_item = cache->mutable_char_word_map(); map_item->set_item_count(char_word_map_.size()); for (CharWordIDMap::const_iterator iter = char_word_map_.begin(); iter != char_word_map_.end(); ++iter) { CharWordMapEntry* map_entry = map_item->add_char_word_map_entry(); map_entry->set_char_16(iter->first); const WordIDSet& word_id_set(iter->second); map_entry->set_item_count(word_id_set.size()); for (WordIDSet::const_iterator set_iter = word_id_set.begin(); set_iter != word_id_set.end(); ++set_iter) map_entry->add_word_id(*set_iter); } } void URLIndexPrivateData::SaveWordIDHistoryMap( InMemoryURLIndexCacheItem* cache) const { if (word_id_history_map_.empty()) return; WordIDHistoryMapItem* map_item = cache->mutable_word_id_history_map(); map_item->set_item_count(word_id_history_map_.size()); for (WordIDHistoryMap::const_iterator iter = word_id_history_map_.begin(); iter != word_id_history_map_.end(); ++iter) { WordIDHistoryMapEntry* map_entry = map_item->add_word_id_history_map_entry(); map_entry->set_word_id(iter->first); const HistoryIDSet& history_id_set(iter->second); map_entry->set_item_count(history_id_set.size()); for (HistoryIDSet::const_iterator set_iter = history_id_set.begin(); set_iter != history_id_set.end(); ++set_iter) map_entry->add_history_id(*set_iter); } } void URLIndexPrivateData::SaveHistoryInfoMap( InMemoryURLIndexCacheItem* cache) const { if (history_info_map_.empty()) return; HistoryInfoMapItem* map_item = cache->mutable_history_info_map(); map_item->set_item_count(history_info_map_.size()); for (HistoryInfoMap::const_iterator iter = history_info_map_.begin(); iter != history_info_map_.end(); ++iter) { HistoryInfoMapEntry* map_entry = map_item->add_history_info_map_entry(); map_entry->set_history_id(iter->first); const URLRow& url_row(iter->second); // Note: We only save information that contributes to the index so there // is no need to save search_term_cache_ (not persistent). map_entry->set_visit_count(url_row.visit_count()); map_entry->set_typed_count(url_row.typed_count()); map_entry->set_last_visit(url_row.last_visit().ToInternalValue()); map_entry->set_url(url_row.url().spec()); map_entry->set_title(UTF16ToUTF8(url_row.title())); } } void URLIndexPrivateData::SaveWordStartsMap( InMemoryURLIndexCacheItem* cache) const { if (word_starts_map_.empty()) return; // For unit testing: Enable saving of the cache as an earlier version to // allow testing of cache file upgrading in ReadFromFile(). // TODO(mrossetti): Instead of intruding on production code with this kind of // test harness, save a copy of an older version cache with known results. // Implement this when switching the caching over to SQLite. if (saved_cache_version_ < 1) return; WordStartsMapItem* map_item = cache->mutable_word_starts_map(); map_item->set_item_count(word_starts_map_.size()); for (WordStartsMap::const_iterator iter = word_starts_map_.begin(); iter != word_starts_map_.end(); ++iter) { WordStartsMapEntry* map_entry = map_item->add_word_starts_map_entry(); map_entry->set_history_id(iter->first); const RowWordStarts& word_starts(iter->second); for (WordStarts::const_iterator i = word_starts.url_word_starts_.begin(); i != word_starts.url_word_starts_.end(); ++i) map_entry->add_url_word_starts(*i); for (WordStarts::const_iterator i = word_starts.title_word_starts_.begin(); i != word_starts.title_word_starts_.end(); ++i) map_entry->add_title_word_starts(*i); } } // Cache Restoring ------------------------------------------------------------- // static void URLIndexPrivateData::RestoreFromFileTask( const FilePath& file_path, scoped_refptr<URLIndexPrivateData> private_data, const std::string& languages) { private_data = URLIndexPrivateData::RestoreFromFile(file_path, languages); } // static scoped_refptr<URLIndexPrivateData> URLIndexPrivateData::RestoreFromFile( const FilePath& file_path, const std::string& languages) { base::TimeTicks beginning_time = base::TimeTicks::Now(); if (!file_util::PathExists(file_path)) return NULL; std::string data; // If there is no cache file then simply give up. This will cause us to // attempt to rebuild from the history database. if (!file_util::ReadFileToString(file_path, &data)) return NULL; scoped_refptr<URLIndexPrivateData> restored_data(new URLIndexPrivateData); InMemoryURLIndexCacheItem index_cache; if (!index_cache.ParseFromArray(data.c_str(), data.size())) { LOG(WARNING) << "Failed to parse URLIndexPrivateData cache data read from " << file_path.value(); return restored_data; } if (!restored_data->RestorePrivateData(index_cache, languages)) return NULL; UMA_HISTOGRAM_TIMES("History.InMemoryURLIndexRestoreCacheTime", base::TimeTicks::Now() - beginning_time); UMA_HISTOGRAM_COUNTS("History.InMemoryURLHistoryItems", restored_data->history_id_word_map_.size()); UMA_HISTOGRAM_COUNTS("History.InMemoryURLCacheSize", data.size()); UMA_HISTOGRAM_COUNTS_10000("History.InMemoryURLWords", restored_data->word_map_.size()); UMA_HISTOGRAM_COUNTS_10000("History.InMemoryURLChars", restored_data->char_word_map_.size()); if (restored_data->Empty()) return NULL; // 'No data' is the same as a failed reload. return restored_data; } // static scoped_refptr<URLIndexPrivateData> URLIndexPrivateData::RebuildFromHistory( HistoryDatabase* history_db, const std::string& languages, const std::set<std::string>& scheme_whitelist) { if (!history_db) return NULL; base::TimeTicks beginning_time = base::TimeTicks::Now(); scoped_refptr<URLIndexPrivateData> rebuilt_data(new URLIndexPrivateData); URLDatabase::URLEnumerator history_enum; if (!history_db->InitURLEnumeratorForSignificant(&history_enum)) return NULL; for (URLRow row; history_enum.GetNextURL(&row); ) rebuilt_data->IndexRow(row, languages, scheme_whitelist); UMA_HISTOGRAM_TIMES("History.InMemoryURLIndexingTime", base::TimeTicks::Now() - beginning_time); UMA_HISTOGRAM_COUNTS("History.InMemoryURLHistoryItems", rebuilt_data->history_id_word_map_.size()); UMA_HISTOGRAM_COUNTS_10000("History.InMemoryURLWords", rebuilt_data->word_map_.size()); UMA_HISTOGRAM_COUNTS_10000("History.InMemoryURLChars", rebuilt_data->char_word_map_.size()); return rebuilt_data; } bool URLIndexPrivateData::RestorePrivateData( const InMemoryURLIndexCacheItem& cache, const std::string& languages) { if (cache.has_version()) restored_cache_version_ = cache.version(); return RestoreWordList(cache) && RestoreWordMap(cache) && RestoreCharWordMap(cache) && RestoreWordIDHistoryMap(cache) && RestoreHistoryInfoMap(cache) && RestoreWordStartsMap(cache, languages); } bool URLIndexPrivateData::RestoreWordList( const InMemoryURLIndexCacheItem& cache) { if (!cache.has_word_list()) return false; const WordListItem& list_item(cache.word_list()); uint32 expected_item_count = list_item.word_count(); uint32 actual_item_count = list_item.word_size(); if (actual_item_count == 0 || actual_item_count != expected_item_count) return false; const RepeatedPtrField<std::string>& words(list_item.word()); for (RepeatedPtrField<std::string>::const_iterator iter = words.begin(); iter != words.end(); ++iter) word_list_.push_back(UTF8ToUTF16(*iter)); return true; } bool URLIndexPrivateData::RestoreWordMap( const InMemoryURLIndexCacheItem& cache) { if (!cache.has_word_map()) return false; const WordMapItem& list_item(cache.word_map()); uint32 expected_item_count = list_item.item_count(); uint32 actual_item_count = list_item.word_map_entry_size(); if (actual_item_count == 0 || actual_item_count != expected_item_count) return false; const RepeatedPtrField<WordMapEntry>& entries(list_item.word_map_entry()); for (RepeatedPtrField<WordMapEntry>::const_iterator iter = entries.begin(); iter != entries.end(); ++iter) word_map_[UTF8ToUTF16(iter->word())] = iter->word_id(); return true; } bool URLIndexPrivateData::RestoreCharWordMap( const InMemoryURLIndexCacheItem& cache) { if (!cache.has_char_word_map()) return false; const CharWordMapItem& list_item(cache.char_word_map()); uint32 expected_item_count = list_item.item_count(); uint32 actual_item_count = list_item.char_word_map_entry_size(); if (actual_item_count == 0 || actual_item_count != expected_item_count) return false; const RepeatedPtrField<CharWordMapEntry>& entries(list_item.char_word_map_entry()); for (RepeatedPtrField<CharWordMapEntry>::const_iterator iter = entries.begin(); iter != entries.end(); ++iter) { expected_item_count = iter->item_count(); actual_item_count = iter->word_id_size(); if (actual_item_count == 0 || actual_item_count != expected_item_count) return false; char16 uni_char = static_cast<char16>(iter->char_16()); WordIDSet word_id_set; const RepeatedField<int32>& word_ids(iter->word_id()); for (RepeatedField<int32>::const_iterator jiter = word_ids.begin(); jiter != word_ids.end(); ++jiter) word_id_set.insert(*jiter); char_word_map_[uni_char] = word_id_set; } return true; } bool URLIndexPrivateData::RestoreWordIDHistoryMap( const InMemoryURLIndexCacheItem& cache) { if (!cache.has_word_id_history_map()) return false; const WordIDHistoryMapItem& list_item(cache.word_id_history_map()); uint32 expected_item_count = list_item.item_count(); uint32 actual_item_count = list_item.word_id_history_map_entry_size(); if (actual_item_count == 0 || actual_item_count != expected_item_count) return false; const RepeatedPtrField<WordIDHistoryMapEntry>& entries(list_item.word_id_history_map_entry()); for (RepeatedPtrField<WordIDHistoryMapEntry>::const_iterator iter = entries.begin(); iter != entries.end(); ++iter) { expected_item_count = iter->item_count(); actual_item_count = iter->history_id_size(); if (actual_item_count == 0 || actual_item_count != expected_item_count) return false; WordID word_id = iter->word_id(); HistoryIDSet history_id_set; const RepeatedField<int64>& history_ids(iter->history_id()); for (RepeatedField<int64>::const_iterator jiter = history_ids.begin(); jiter != history_ids.end(); ++jiter) { history_id_set.insert(*jiter); AddToHistoryIDWordMap(*jiter, word_id); } word_id_history_map_[word_id] = history_id_set; } return true; } bool URLIndexPrivateData::RestoreHistoryInfoMap( const InMemoryURLIndexCacheItem& cache) { if (!cache.has_history_info_map()) return false; const HistoryInfoMapItem& list_item(cache.history_info_map()); uint32 expected_item_count = list_item.item_count(); uint32 actual_item_count = list_item.history_info_map_entry_size(); if (actual_item_count == 0 || actual_item_count != expected_item_count) return false; const RepeatedPtrField<HistoryInfoMapEntry>& entries(list_item.history_info_map_entry()); for (RepeatedPtrField<HistoryInfoMapEntry>::const_iterator iter = entries.begin(); iter != entries.end(); ++iter) { HistoryID history_id = iter->history_id(); GURL url(iter->url()); URLRow url_row(url, history_id); url_row.set_visit_count(iter->visit_count()); url_row.set_typed_count(iter->typed_count()); url_row.set_last_visit(base::Time::FromInternalValue(iter->last_visit())); if (iter->has_title()) { string16 title(UTF8ToUTF16(iter->title())); url_row.set_title(title); } history_info_map_[history_id] = url_row; } return true; } bool URLIndexPrivateData::RestoreWordStartsMap( const InMemoryURLIndexCacheItem& cache, const std::string& languages) { // Note that this function must be called after RestoreHistoryInfoMap() has // been run as the word starts may have to be recalculated from the urls and // page titles. if (cache.has_word_starts_map()) { const WordStartsMapItem& list_item(cache.word_starts_map()); uint32 expected_item_count = list_item.item_count(); uint32 actual_item_count = list_item.word_starts_map_entry_size(); if (actual_item_count == 0 || actual_item_count != expected_item_count) return false; const RepeatedPtrField<WordStartsMapEntry>& entries(list_item.word_starts_map_entry()); for (RepeatedPtrField<WordStartsMapEntry>::const_iterator iter = entries.begin(); iter != entries.end(); ++iter) { HistoryID history_id = iter->history_id(); RowWordStarts word_starts; // Restore the URL word starts. const RepeatedField<int32>& url_starts(iter->url_word_starts()); for (RepeatedField<int32>::const_iterator jiter = url_starts.begin(); jiter != url_starts.end(); ++jiter) word_starts.url_word_starts_.push_back(*jiter); // Restore the page title word starts. const RepeatedField<int32>& title_starts(iter->title_word_starts()); for (RepeatedField<int32>::const_iterator jiter = title_starts.begin(); jiter != title_starts.end(); ++jiter) word_starts.title_word_starts_.push_back(*jiter); word_starts_map_[history_id] = word_starts; } } else { // Since the cache did not contain any word starts we must rebuild then from // the URL and page titles. for (HistoryInfoMap::const_iterator iter = history_info_map_.begin(); iter != history_info_map_.end(); ++iter) { RowWordStarts word_starts; const URLRow& row(iter->second); string16 url(net::FormatUrl(row.url(), languages, net::kFormatUrlOmitUsernamePassword, net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS, NULL, NULL, NULL)); url = base::i18n::ToLower(url); String16VectorFromString16(url, false, &word_starts.url_word_starts_); String16VectorFromString16( row.title(), false, &word_starts.title_word_starts_); word_starts_map_[iter->first] = word_starts; } } return true; } // static bool URLIndexPrivateData::URLSchemeIsWhitelisted( const GURL& gurl, const std::set<std::string>& whitelist) { return whitelist.find(gurl.scheme()) != whitelist.end(); } } // namespace history
// Copyright (c) 2014-2017 The Dash Core developers // Copyright (c) 2019 The DreamTeam3 Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. //#define ENABLE_DT3_DEBUG #include "core_io.h" #include "governance-classes.h" #include "init.h" #include "validation.h" #include "utilstrencodings.h" #include <boost/algorithm/string.hpp> #include <univalue.h> // DECLARE GLOBAL VARIABLES FOR GOVERNANCE CLASSES CGovernanceTriggerManager triggerman; // SPLIT UP STRING BY DELIMITER // http://www.boost.org/doc/libs/1_58_0/doc/html/boost/algorithm/split_idp202406848.html std::vector<std::string> SplitBy(const std::string& strCommand, const std::string& strDelimit) { std::vector<std::string> vParts; boost::split(vParts, strCommand, boost::is_any_of(strDelimit)); for(int q=0; q<(int)vParts.size(); q++) { if(strDelimit.find(vParts[q]) != std::string::npos) { vParts.erase(vParts.begin()+q); --q; } } return vParts; } CAmount ParsePaymentAmount(const std::string& strAmount) { DBG( std::cout << "ParsePaymentAmount Start: strAmount = " << strAmount << std::endl; ); CAmount nAmount = 0; if (strAmount.empty()) { std::ostringstream ostr; ostr << "ParsePaymentAmount: Amount is empty"; throw std::runtime_error(ostr.str()); } if(strAmount.size() > 20) { // String is much too long, the functions below impose stricter // requirements std::ostringstream ostr; ostr << "ParsePaymentAmount: Amount string too long"; throw std::runtime_error(ostr.str()); } // Make sure the string makes sense as an amount // Note: No spaces allowed // Also note: No scientific notation size_t pos = strAmount.find_first_not_of("0123456789."); if (pos != std::string::npos) { std::ostringstream ostr; ostr << "ParsePaymentAmount: Amount string contains invalid character"; throw std::runtime_error(ostr.str()); } pos = strAmount.find("."); if (pos == 0) { // JSON doesn't allow values to start with a decimal point std::ostringstream ostr; ostr << "ParsePaymentAmount: Invalid amount string, leading decimal point not allowed"; throw std::runtime_error(ostr.str()); } // Make sure there's no more than 1 decimal point if ((pos != std::string::npos) && (strAmount.find(".", pos+1) != std::string::npos)) { std::ostringstream ostr; ostr << "ParsePaymentAmount: Invalid amount string, too many decimal points"; throw std::runtime_error(ostr.str()); } // Note this code is taken from AmountFromValue in rpcserver.cpp // which is used for parsing the amounts in createrawtransaction. if (!ParseFixedPoint(strAmount, 8, &nAmount)) { nAmount = 0; std::ostringstream ostr; ostr << "ParsePaymentAmount: ParseFixedPoint failed for string: " << strAmount; throw std::runtime_error(ostr.str()); } if (!MoneyRange(nAmount)) { nAmount = 0; std::ostringstream ostr; ostr << "ParsePaymentAmount: Invalid amount string, value outside of valid money range"; throw std::runtime_error(ostr.str()); } DBG( std::cout << "ParsePaymentAmount Returning true nAmount = " << nAmount << std::endl; ); return nAmount; } /** * Add Governance Object */ bool CGovernanceTriggerManager::AddNewTrigger(uint256 nHash) { DBG( std::cout << "CGovernanceTriggerManager::AddNewTrigger: Start" << std::endl; ); AssertLockHeld(governance.cs); // IF WE ALREADY HAVE THIS HASH, RETURN if(mapTrigger.count(nHash)) { DBG( std::cout << "CGovernanceTriggerManager::AddNewTrigger: Already have hash" << ", nHash = " << nHash.GetHex() << ", count = " << mapTrigger.count(nHash) << ", mapTrigger.size() = " << mapTrigger.size() << std::endl; ); return false; } CSuperblock_sptr pSuperblock; try { CSuperblock_sptr pSuperblockTmp(new CSuperblock(nHash)); pSuperblock = pSuperblockTmp; } catch(std::exception& e) { DBG( std::cout << "CGovernanceTriggerManager::AddNewTrigger Error creating superblock" << ", e.what() = " << e.what() << std::endl; ); LogPrintf("CGovernanceTriggerManager::AddNewTrigger -- Error creating superblock: %s\n", e.what()); return false; } catch(...) { LogPrintf("CGovernanceTriggerManager::AddNewTrigger: Unknown Error creating superblock\n"); DBG( std::cout << "CGovernanceTriggerManager::AddNewTrigger Error creating superblock catchall" << std::endl; ); return false; } pSuperblock->SetStatus(SEEN_OBJECT_IS_VALID); DBG( std::cout << "CGovernanceTriggerManager::AddNewTrigger: Inserting trigger" << std::endl; ); mapTrigger.insert(std::make_pair(nHash, pSuperblock)); DBG( std::cout << "CGovernanceTriggerManager::AddNewTrigger: End" << std::endl; ); return true; } /** * * Clean And Remove * */ void CGovernanceTriggerManager::CleanAndRemove() { LogPrint("gobject", "CGovernanceTriggerManager::CleanAndRemove -- Start\n"); DBG( std::cout << "CGovernanceTriggerManager::CleanAndRemove: Start" << std::endl; ); AssertLockHeld(governance.cs); // Remove triggers that are invalid or expired DBG( std::cout << "CGovernanceTriggerManager::CleanAndRemove: mapTrigger.size() = " << mapTrigger.size() << std::endl; ); LogPrint("gobject", "CGovernanceTriggerManager::CleanAndRemove -- mapTrigger.size() = %d\n", mapTrigger.size()); trigger_m_it it = mapTrigger.begin(); while(it != mapTrigger.end()) { bool remove = false; CGovernanceObject* pObj = nullptr; CSuperblock_sptr& pSuperblock = it->second; if(!pSuperblock) { DBG( std::cout << "CGovernanceTriggerManager::CleanAndRemove: NULL superblock marked for removal" << std::endl; ); LogPrint("gobject", "CGovernanceTriggerManager::CleanAndRemove -- NULL superblock marked for removal\n"); remove = true; } else { pObj = governance.FindGovernanceObject(it->first); if(!pObj || pObj->GetObjectType() != GOVERNANCE_OBJECT_TRIGGER) { DBG( std::cout << "CGovernanceTriggerManager::CleanAndRemove: Unknown or non-trigger superblock" << std::endl; ); LogPrint("gobject", "CGovernanceTriggerManager::CleanAndRemove -- Unknown or non-trigger superblock\n"); pSuperblock->SetStatus(SEEN_OBJECT_ERROR_INVALID); } DBG( std::cout << "CGovernanceTriggerManager::CleanAndRemove: superblock status = " << pSuperblock->GetStatus() << std::endl; ); LogPrint("gobject", "CGovernanceTriggerManager::CleanAndRemove -- superblock status = %d\n", pSuperblock->GetStatus()); switch(pSuperblock->GetStatus()) { case SEEN_OBJECT_ERROR_INVALID: case SEEN_OBJECT_UNKNOWN: LogPrint("gobject", "CGovernanceTriggerManager::CleanAndRemove -- Unknown or invalid trigger found\n"); remove = true; break; case SEEN_OBJECT_IS_VALID: case SEEN_OBJECT_EXECUTED: remove = pSuperblock->IsExpired(); break; default: break; } } LogPrint("gobject", "CGovernanceTriggerManager::CleanAndRemove -- %smarked for removal\n", remove ? "" : "NOT "); if(remove) { DBG( std::string strDataAsPlainString = "NULL"; if(pObj) { strDataAsPlainString = pObj->GetDataAsPlainString(); } std::cout << "CGovernanceTriggerManager::CleanAndRemove: Removing object: " << strDataAsPlainString << std::endl; ); LogPrint("gobject", "CGovernanceTriggerManager::CleanAndRemove -- Removing trigger object\n"); // mark corresponding object for deletion if (pObj) { pObj->fCachedDelete = true; if (pObj->nDeletionTime == 0) { pObj->nDeletionTime = GetAdjustedTime(); } } // delete the trigger mapTrigger.erase(it++); } else { ++it; } } DBG( std::cout << "CGovernanceTriggerManager::CleanAndRemove: End" << std::endl; ); } /** * Get Active Triggers * * - Look through triggers and scan for active ones * - Return the triggers in a list */ std::vector<CSuperblock_sptr> CGovernanceTriggerManager::GetActiveTriggers() { AssertLockHeld(governance.cs); std::vector<CSuperblock_sptr> vecResults; DBG( std::cout << "GetActiveTriggers: mapTrigger.size() = " << mapTrigger.size() << std::endl; ); // LOOK AT THESE OBJECTS AND COMPILE A VALID LIST OF TRIGGERS trigger_m_it it = mapTrigger.begin(); while(it != mapTrigger.end()) { CGovernanceObject* pObj = governance.FindGovernanceObject((*it).first); if(pObj) { DBG( std::cout << "GetActiveTriggers: pObj->GetDataAsPlainString() = " << pObj->GetDataAsPlainString() << std::endl; ); vecResults.push_back(it->second); } ++it; } DBG( std::cout << "GetActiveTriggers: vecResults.size() = " << vecResults.size() << std::endl; ); return vecResults; } /** * Is Superblock Triggered * * - Does this block have a non-executed and actived trigger? */ bool CSuperblockManager::IsSuperblockTriggered(int nBlockHeight) { LogPrint("gobject", "CSuperblockManager::IsSuperblockTriggered -- Start nBlockHeight = %d\n", nBlockHeight); if (!CSuperblock::IsValidBlockHeight(nBlockHeight)) { return false; } LOCK(governance.cs); // GET ALL ACTIVE TRIGGERS std::vector<CSuperblock_sptr> vecTriggers = triggerman.GetActiveTriggers(); LogPrint("gobject", "CSuperblockManager::IsSuperblockTriggered -- vecTriggers.size() = %d\n", vecTriggers.size()); DBG( std::cout << "IsSuperblockTriggered Number triggers = " << vecTriggers.size() << std::endl; ); for (const auto& pSuperblock : vecTriggers) { if(!pSuperblock) { LogPrintf("CSuperblockManager::IsSuperblockTriggered -- Non-superblock found, continuing\n"); DBG( std::cout << "IsSuperblockTriggered Not a superblock, continuing " << std::endl; ); continue; } CGovernanceObject* pObj = pSuperblock->GetGovernanceObject(); if(!pObj) { LogPrintf("CSuperblockManager::IsSuperblockTriggered -- pObj == NULL, continuing\n"); DBG( std::cout << "IsSuperblockTriggered pObj is NULL, continuing" << std::endl; ); continue; } LogPrint("gobject", "CSuperblockManager::IsSuperblockTriggered -- data = %s\n", pObj->GetDataAsPlainString()); // note : 12.1 - is epoch calculation correct? if(nBlockHeight != pSuperblock->GetBlockHeight()) { LogPrint("gobject", "CSuperblockManager::IsSuperblockTriggered -- block height doesn't match nBlockHeight = %d, blockStart = %d, continuing\n", nBlockHeight, pSuperblock->GetBlockHeight()); DBG( std::cout << "IsSuperblockTriggered Not the target block, continuing" << ", nBlockHeight = " << nBlockHeight << ", superblock->GetBlockHeight() = " << pSuperblock->GetBlockHeight() << std::endl; ); continue; } // MAKE SURE THIS TRIGGER IS ACTIVE VIA FUNDING CACHE FLAG pObj->UpdateSentinelVariables(); if(pObj->IsSetCachedFunding()) { LogPrint("gobject", "CSuperblockManager::IsSuperblockTriggered -- fCacheFunding = true, returning true\n"); DBG( std::cout << "IsSuperblockTriggered returning true" << std::endl; ); return true; } else { LogPrint("gobject", "CSuperblockManager::IsSuperblockTriggered -- fCacheFunding = false, continuing\n"); DBG( std::cout << "IsSuperblockTriggered No fCachedFunding, continuing" << std::endl; ); } } return false; } bool CSuperblockManager::GetBestSuperblock(CSuperblock_sptr& pSuperblockRet, int nBlockHeight) { if(!CSuperblock::IsValidBlockHeight(nBlockHeight)) { return false; } AssertLockHeld(governance.cs); std::vector<CSuperblock_sptr> vecTriggers = triggerman.GetActiveTriggers(); int nYesCount = 0; for (const auto& pSuperblock : vecTriggers) { if(!pSuperblock) { DBG( std::cout << "GetBestSuperblock Not a superblock, continuing" << std::endl; ); continue; } CGovernanceObject* pObj = pSuperblock->GetGovernanceObject(); if(!pObj) { DBG( std::cout << "GetBestSuperblock pObj is NULL, continuing" << std::endl; ); continue; } if(nBlockHeight != pSuperblock->GetBlockHeight()) { DBG( std::cout << "GetBestSuperblock Not the target block, continuing" << std::endl; ); continue; } // DO WE HAVE A NEW WINNER? int nTempYesCount = pObj->GetAbsoluteYesCount(VOTE_SIGNAL_FUNDING); DBG( std::cout << "GetBestSuperblock nTempYesCount = " << nTempYesCount << std::endl; ); if(nTempYesCount > nYesCount) { nYesCount = nTempYesCount; pSuperblockRet = pSuperblock; DBG( std::cout << "GetBestSuperblock Valid superblock found, pSuperblock set" << std::endl; ); } } return nYesCount > 0; } /** * Create Superblock Payments * * - Create the correct payment structure for a given superblock */ void CSuperblockManager::CreateSuperblock(CMutableTransaction& txNewRet, int nBlockHeight, std::vector<CTxOut>& voutSuperblockRet) { DBG( std::cout << "CSuperblockManager::CreateSuperblock Start" << std::endl; ); LOCK(governance.cs); // GET THE BEST SUPERBLOCK FOR THIS BLOCK HEIGHT CSuperblock_sptr pSuperblock; if(!CSuperblockManager::GetBestSuperblock(pSuperblock, nBlockHeight)) { LogPrint("gobject", "CSuperblockManager::CreateSuperblock -- Can't find superblock for height %d\n", nBlockHeight); DBG( std::cout << "CSuperblockManager::CreateSuperblock Failed to get superblock for height, returning" << std::endl; ); return; } // make sure it's empty, just in case voutSuperblockRet.clear(); // CONFIGURE SUPERBLOCK OUTPUTS // Superblock payments are appended to the end of the coinbase vout vector DBG( std::cout << "CSuperblockManager::CreateSuperblock Number payments: " << pSuperblock->CountPayments() << std::endl; ); // TODO: How many payments can we add before things blow up? // Consider at least following limits: // - max coinbase tx size // - max "budget" available for(int i = 0; i < pSuperblock->CountPayments(); i++) { CGovernancePayment payment; DBG( std::cout << "CSuperblockManager::CreateSuperblock i = " << i << std::endl; ); if(pSuperblock->GetPayment(i, payment)) { DBG( std::cout << "CSuperblockManager::CreateSuperblock Payment found " << std::endl; ); // SET COINBASE OUTPUT TO SUPERBLOCK SETTING CTxOut txout = CTxOut(payment.nAmount, payment.script); txNewRet.vout.push_back(txout); voutSuperblockRet.push_back(txout); // PRINT NICE LOG OUTPUT FOR SUPERBLOCK PAYMENT CTxDestination address1; ExtractDestination(payment.script, address1); CBitcoinAddress address2(address1); // TODO: PRINT NICE N.N DT3 OUTPUT DBG( std::cout << "CSuperblockManager::CreateSuperblock Before LogPrintf call, nAmount = " << payment.nAmount << std::endl; ); LogPrintf("NEW Superblock : output %d (addr %s, amount %d)\n", i, address2.ToString(), payment.nAmount); DBG( std::cout << "CSuperblockManager::CreateSuperblock After LogPrintf call " << std::endl; ); } else { DBG( std::cout << "CSuperblockManager::CreateSuperblock Payment not found " << std::endl; ); } } DBG( std::cout << "CSuperblockManager::CreateSuperblock End" << std::endl; ); } bool CSuperblockManager::IsValid(const CTransaction& txNew, int nBlockHeight, CAmount blockReward) { // GET BEST SUPERBLOCK, SHOULD MATCH LOCK(governance.cs); CSuperblock_sptr pSuperblock; if(CSuperblockManager::GetBestSuperblock(pSuperblock, nBlockHeight)) { return pSuperblock->IsValid(txNew, nBlockHeight, blockReward); } return false; } void CSuperblockManager::ExecuteBestSuperblock(int nBlockHeight) { LOCK(governance.cs); CSuperblock_sptr pSuperblock; if(GetBestSuperblock(pSuperblock, nBlockHeight)) { // All checks are done in CSuperblock::IsValid via IsBlockValueValid and IsBlockPayeeValid, // tip wouldn't be updated if anything was wrong. Mark this trigger as executed. pSuperblock->SetExecuted(); } } CSuperblock:: CSuperblock() : nGovObjHash(), nBlockHeight(0), nStatus(SEEN_OBJECT_UNKNOWN), vecPayments() {} CSuperblock:: CSuperblock(uint256& nHash) : nGovObjHash(nHash), nBlockHeight(0), nStatus(SEEN_OBJECT_UNKNOWN), vecPayments() { DBG( std::cout << "CSuperblock Constructor Start" << std::endl; ); CGovernanceObject* pGovObj = GetGovernanceObject(); if(!pGovObj) { DBG( std::cout << "CSuperblock Constructor pGovObjIn is NULL, returning" << std::endl; ); throw std::runtime_error("CSuperblock: Failed to find Governance Object"); } DBG( std::cout << "CSuperblock Constructor pGovObj : " << pGovObj->GetDataAsPlainString() << ", nObjectType = " << pGovObj->GetObjectType() << std::endl; ); if (pGovObj->GetObjectType() != GOVERNANCE_OBJECT_TRIGGER) { DBG( std::cout << "CSuperblock Constructor pGovObj not a trigger, returning" << std::endl; ); throw std::runtime_error("CSuperblock: Governance Object not a trigger"); } UniValue obj = pGovObj->GetJSONObject(); // FIRST WE GET THE START HEIGHT, THE BLOCK HEIGHT AT WHICH THE PAYMENT SHALL OCCUR nBlockHeight = obj["event_block_height"].get_int(); // NEXT WE GET THE PAYMENT INFORMATION AND RECONSTRUCT THE PAYMENT VECTOR std::string strAddresses = obj["payment_addresses"].get_str(); std::string strAmounts = obj["payment_amounts"].get_str(); ParsePaymentSchedule(strAddresses, strAmounts); LogPrint("gobject", "CSuperblock -- nBlockHeight = %d, strAddresses = %s, strAmounts = %s, vecPayments.size() = %d\n", nBlockHeight, strAddresses, strAmounts, vecPayments.size()); DBG( std::cout << "CSuperblock Constructor End" << std::endl; ); } /** * Is Valid Superblock Height * * - See if a block at this height can be a superblock */ bool CSuperblock::IsValidBlockHeight(int nBlockHeight) { // SUPERBLOCKS CAN HAPPEN ONLY after hardfork and only ONCE PER CYCLE return nBlockHeight >= Params().GetConsensus().nSuperblockStartBlock && ((nBlockHeight % Params().GetConsensus().nSuperblockCycle) == 0); } void CSuperblock::GetNearestSuperblocksHeights(int nBlockHeight, int& nLastSuperblockRet, int& nNextSuperblockRet) { const Consensus::Params& consensusParams = Params().GetConsensus(); int nSuperblockStartBlock = consensusParams.nSuperblockStartBlock; int nSuperblockCycle = consensusParams.nSuperblockCycle; // Get first superblock int nFirstSuperblockOffset = (nSuperblockCycle - nSuperblockStartBlock % nSuperblockCycle) % nSuperblockCycle; int nFirstSuperblock = nSuperblockStartBlock + nFirstSuperblockOffset; if(nBlockHeight < nFirstSuperblock) { nLastSuperblockRet = 0; nNextSuperblockRet = nFirstSuperblock; } else { nLastSuperblockRet = nBlockHeight - nBlockHeight % nSuperblockCycle; nNextSuperblockRet = nLastSuperblockRet + nSuperblockCycle; } } CAmount CSuperblock::GetPaymentsLimit(int nBlockHeight) { const Consensus::Params& consensusParams = Params().GetConsensus(); if(!IsValidBlockHeight(nBlockHeight)) { return 0; } // min subsidy for high diff networks and vice versa int nBits = consensusParams.fPowAllowMinDifficultyBlocks ? UintToArith256(consensusParams.powLimit).GetCompact() : 1; // some part of all blocks issued during the cycle goes to superblock, see GetBlockSubsidy CAmount nSuperblockPartOfSubsidy = GetBlockSubsidy(nBits, nBlockHeight - 1, consensusParams, true); CAmount nPaymentsLimit = nSuperblockPartOfSubsidy * consensusParams.nSuperblockCycle; LogPrint("gobject", "CSuperblock::GetPaymentsLimit -- Valid superblock height %d, payments max %lld\n", nBlockHeight, nPaymentsLimit); return nPaymentsLimit; } void CSuperblock::ParsePaymentSchedule(const std::string& strPaymentAddresses, const std::string& strPaymentAmounts) { // SPLIT UP ADDR/AMOUNT STRINGS AND PUT IN VECTORS std::vector<std::string> vecParsed1; std::vector<std::string> vecParsed2; vecParsed1 = SplitBy(strPaymentAddresses, "|"); vecParsed2 = SplitBy(strPaymentAmounts, "|"); // IF THESE DONT MATCH, SOMETHING IS WRONG if (vecParsed1.size() != vecParsed2.size()) { std::ostringstream ostr; ostr << "CSuperblock::ParsePaymentSchedule -- Mismatched payments and amounts"; LogPrintf("%s\n", ostr.str()); throw std::runtime_error(ostr.str()); } if (vecParsed1.size() == 0) { std::ostringstream ostr; ostr << "CSuperblock::ParsePaymentSchedule -- Error no payments"; LogPrintf("%s\n", ostr.str()); throw std::runtime_error(ostr.str()); } // LOOP THROUGH THE ADDRESSES/AMOUNTS AND CREATE PAYMENTS /* ADDRESSES = [ADDR1|2|3|4|5|6] AMOUNTS = [AMOUNT1|2|3|4|5|6] */ DBG( std::cout << "CSuperblock::ParsePaymentSchedule vecParsed1.size() = " << vecParsed1.size() << std::endl; ); for (int i = 0; i < (int)vecParsed1.size(); i++) { CBitcoinAddress address(vecParsed1[i]); if (!address.IsValid()) { std::ostringstream ostr; ostr << "CSuperblock::ParsePaymentSchedule -- Invalid DreamTeam3 Address : " << vecParsed1[i]; LogPrintf("%s\n", ostr.str()); throw std::runtime_error(ostr.str()); } /* TODO - There might be an issue with multisig in the coinbase on mainnet, we will add support for it in a future release. - Post 12.3+ (test multisig coinbase transaction) */ if(address.IsScript()) { std::ostringstream ostr; ostr << "CSuperblock::ParsePaymentSchedule -- Script addresses are not supported yet : " << vecParsed1[i]; LogPrintf("%s\n", ostr.str()); throw std::runtime_error(ostr.str()); } DBG( std::cout << "CSuperblock::ParsePaymentSchedule i = " << i << ", vecParsed2[i] = " << vecParsed2[i] << std::endl; ); CAmount nAmount = ParsePaymentAmount(vecParsed2[i]); DBG( std::cout << "CSuperblock::ParsePaymentSchedule: " << "amount string = " << vecParsed2[i] << ", nAmount = " << nAmount << std::endl; ); CGovernancePayment payment(address, nAmount); if(payment.IsValid()) { vecPayments.push_back(payment); } else { vecPayments.clear(); std::ostringstream ostr; ostr << "CSuperblock::ParsePaymentSchedule -- Invalid payment found: address = " << address.ToString() << ", amount = " << nAmount; LogPrintf("%s\n", ostr.str()); throw std::runtime_error(ostr.str()); } } } bool CSuperblock::GetPayment(int nPaymentIndex, CGovernancePayment& paymentRet) { if((nPaymentIndex<0) || (nPaymentIndex >= (int)vecPayments.size())) { return false; } paymentRet = vecPayments[nPaymentIndex]; return true; } CAmount CSuperblock::GetPaymentsTotalAmount() { CAmount nPaymentsTotalAmount = 0; int nPayments = CountPayments(); for(int i = 0; i < nPayments; i++) { nPaymentsTotalAmount += vecPayments[i].nAmount; } return nPaymentsTotalAmount; } /** * Is Transaction Valid * * - Does this transaction match the superblock? */ bool CSuperblock::IsValid(const CTransaction& txNew, int nBlockHeight, CAmount blockReward) { // TODO : LOCK(cs); // No reason for a lock here now since this method only accesses data // internal to *this and since CSuperblock's are accessed only through // shared pointers there's no way our object can get deleted while this // code is running. if(!IsValidBlockHeight(nBlockHeight)) { LogPrintf("CSuperblock::IsValid -- ERROR: Block invalid, incorrect block height\n"); return false; } std::string strPayeesPossible = ""; // CONFIGURE SUPERBLOCK OUTPUTS int nOutputs = txNew.vout.size(); int nPayments = CountPayments(); int nMinerPayments = nOutputs - nPayments; LogPrint("gobject", "CSuperblock::IsValid nOutputs = %d, nPayments = %d, GetDataAsHexString = %s\n", nOutputs, nPayments, GetGovernanceObject()->GetDataAsHexString()); // We require an exact match (including order) between the expected // superblock payments and the payments actually in the block. if(nMinerPayments < 0) { // This means the block cannot have all the superblock payments // so it is not valid. // TODO: could that be that we just hit coinbase size limit? LogPrintf("CSuperblock::IsValid -- ERROR: Block invalid, too few superblock payments\n"); return false; } // payments should not exceed limit CAmount nPaymentsTotalAmount = GetPaymentsTotalAmount(); CAmount nPaymentsLimit = GetPaymentsLimit(nBlockHeight); if(nPaymentsTotalAmount > nPaymentsLimit) { LogPrintf("CSuperblock::IsValid -- ERROR: Block invalid, payments limit exceeded: payments %lld, limit %lld\n", nPaymentsTotalAmount, nPaymentsLimit); return false; } // miner should not get more than he would usually get CAmount nBlockValue = txNew.GetValueOut(); if(nBlockValue > blockReward + nPaymentsTotalAmount) { LogPrintf("CSuperblock::IsValid -- ERROR: Block invalid, block value limit exceeded: block %lld, limit %lld\n", nBlockValue, blockReward + nPaymentsTotalAmount); return false; } int nVoutIndex = 0; for(int i = 0; i < nPayments; i++) { CGovernancePayment payment; if(!GetPayment(i, payment)) { // This shouldn't happen so log a warning LogPrintf("CSuperblock::IsValid -- WARNING: Failed to find payment: %d of %d total payments\n", i, nPayments); continue; } bool fPaymentMatch = false; for (int j = nVoutIndex; j < nOutputs; j++) { // Find superblock payment fPaymentMatch = ((payment.script == txNew.vout[j].scriptPubKey) && (payment.nAmount == txNew.vout[j].nValue)); if (fPaymentMatch) { nVoutIndex = j; break; } } if(!fPaymentMatch) { // Superblock payment not found! CTxDestination address1; ExtractDestination(payment.script, address1); CBitcoinAddress address2(address1); LogPrintf("CSuperblock::IsValid -- ERROR: Block invalid: %d payment %d to %s not found\n", i, payment.nAmount, address2.ToString()); return false; } } return true; } bool CSuperblock::IsExpired() { bool fExpired{false}; int nExpirationBlocks{0}; // Executed triggers are kept for another superblock cycle (approximately 1 month), // other valid triggers are kept for ~1 day only, everything else is pruned after ~1h. switch (nStatus) { case SEEN_OBJECT_EXECUTED: nExpirationBlocks = Params().GetConsensus().nSuperblockCycle; break; case SEEN_OBJECT_IS_VALID: nExpirationBlocks = 576; break; default: nExpirationBlocks = 24; break; } int nExpirationBlock = nBlockHeight + nExpirationBlocks; LogPrint("gobject", "CSuperblock::IsExpired -- nBlockHeight = %d, nExpirationBlock = %d\n", nBlockHeight, nExpirationBlock); if(governance.GetCachedBlockHeight() > nExpirationBlock) { LogPrint("gobject", "CSuperblock::IsExpired -- Outdated trigger found\n"); fExpired = true; CGovernanceObject* pgovobj = GetGovernanceObject(); if(pgovobj) { LogPrint("gobject", "CSuperblock::IsExpired -- Expiring outdated object: %s\n", pgovobj->GetHash().ToString()); pgovobj->fExpired = true; pgovobj->nDeletionTime = GetAdjustedTime(); } } return fExpired; } /** * Get Required Payment String * * - Get a string representing the payments required for a given superblock */ std::string CSuperblockManager::GetRequiredPaymentsString(int nBlockHeight) { LOCK(governance.cs); std::string ret = "Unknown"; // GET BEST SUPERBLOCK CSuperblock_sptr pSuperblock; if(!GetBestSuperblock(pSuperblock, nBlockHeight)) { LogPrint("gobject", "CSuperblockManager::GetRequiredPaymentsString -- Can't find superblock for height %d\n", nBlockHeight); return "error"; } // LOOP THROUGH SUPERBLOCK PAYMENTS, CONFIGURE OUTPUT STRING for(int i = 0; i < pSuperblock->CountPayments(); i++) { CGovernancePayment payment; if(pSuperblock->GetPayment(i, payment)) { // PRINT NICE LOG OUTPUT FOR SUPERBLOCK PAYMENT CTxDestination address1; ExtractDestination(payment.script, address1); CBitcoinAddress address2(address1); // RETURN NICE OUTPUT FOR CONSOLE if(ret != "Unknown") { ret += ", " + address2.ToString(); } else { ret = address2.ToString(); } } } return ret; }
# pragma once # include <Siv3D.hpp> # include "Axis.hpp" namespace asc { using namespace s3d; /// <summary> /// 軸グループ /// </summary> class AxisGroup { private: Array<Axis> m_axes; template <class Type, class ...Args> void append(const Type& axis, const Args&... args) { append(axis); append(args...); } void append() { } void append(const Axis& axis) { m_axes << axis; } void append(const AxisGroup& group) { m_axes.append(group.m_axes); } public: template <class ...Args> explicit AxisGroup(const Args&... args) { append(args...); } [[nodiscard]] operator double() const { return get(); } AxisGroup& operator |=(const Axis& axis) { append(axis); return *this; } AxisGroup& operator |=(const AxisGroup& group) { m_axes.append(group.m_axes); return *this; } /// <summary> /// 軸の状態を取得します。 /// </summary> /// <returns> /// 軸の状態。軸が無効、または閾値以下の場合は 0 を返します。 /// </returns> [[nodiscard]] double get(double threshold = 0.12) const { return getValueOr(0.0, threshold); } /// <summary> /// 軸の状態を取得します。 /// </summary> /// <param name="threshold"> /// 軸の閾値 /// </param> /// <param name="defaultValue"> /// 軸のデフォルト値 /// </param> /// <returns> /// 軸の状態。軸が無効、または閾値以下の場合はデフォルト値を返します。 /// </returns> [[nodiscard]] double getValueOr(double&& defaultValue, double threshold = 0.12) const { return getValueOpt(threshold).value_or(defaultValue); } /// <summary> /// 軸の状態を取得します。 /// </summary> /// <param name="threshold"> /// 軸の閾値 /// </param> /// <returns> /// 軸の状態。軸が無効、または閾値以下の場合はnoneを返します。 /// </returns> [[nodiscard]] Optional<double> getValueOpt(double threshold = 0.12) const { for (const auto& axis : m_axes) { const auto axisValueOpt = axis.getOpt(threshold); if (axisValueOpt) { return axisValueOpt; } } return none; } }; [[nodiscard]] inline AxisGroup operator |(const Axis& axis1, const Axis& axis2) { return AxisGroup(axis1, axis2); } [[nodiscard]] inline AxisGroup operator |(const Axis& axis, const AxisGroup& group) { return AxisGroup(axis, group); } [[nodiscard]] inline AxisGroup operator |(const AxisGroup& group, const Axis& axis) { return AxisGroup(group, axis); } }
#include <iostream> #include "TChain.h" #include "TH1F.h" #include "TList.h" #include "TRandom3.h" #include "TGeoGlobalMagField.h" #include "AliAnalysisTask.h" #include "AliAnalysisManager.h" #include "AliESDEvent.h" #include "AliESDInputHandler.h" #include "AliESDtrack.h" #include "AliAODEvent.h" #include "AliHeader.h" #include "AliMCEvent.h" #include "AliGenEventHeader.h" #include "AliESDtrackCuts.h" #include "AlidNdPtTools.h" #include "AliMCSpectraWeights.h" #include "AliAnalysisTaskMKBase.h" #include "AliAnalysisTaskBaseWeights.h" class AliAnalysisTaskBaseWeights; using namespace std; /// \cond CLASSIMP ClassImp(AliAnalysisTaskBaseWeights) /// \endcond //_____________________________________________________________________________ AliAnalysisTaskBaseWeights::AliAnalysisTaskBaseWeights() : AliAnalysisTaskMKBase() , fUseMCWeights(kTRUE) , fUseRandomSeed(kFALSE) , fRand(0) , fMCSpectraWeights(0) , fMCweight(1) { // default contructor } //_____________________________________________________________________________ AliAnalysisTaskBaseWeights::AliAnalysisTaskBaseWeights(const char* name) : AliAnalysisTaskMKBase(name) , fUseMCWeights(kTRUE) , fUseRandomSeed(kFALSE) , fRand(0) , fMCSpectraWeights(0) , fMCweight(1) { // constructor } //_____________________________________________________________________________ AliAnalysisTaskBaseWeights::~AliAnalysisTaskBaseWeights() { if (fRand) { delete fRand; fRand=0; } } //_____________________________________________________________________________ void AliAnalysisTaskBaseWeights::BaseAddOutput() { // add also all the default output from the base class AliAnalysisTaskMKBase::BaseAddOutput(); // TODO add some control histograms here // if there are weights and they are used add them to the ouput if (fMCSpectraWeights && fUseMCWeights) { fOutputList->Add(fMCSpectraWeights); } } //_____________________________________________________________________________ UInt_t AliAnalysisTaskBaseWeights::GetSeed() { if (fUseRandomSeed) { return 0; } UInt_t seed = fEventNumberInFile; seed <<= 7; seed += fRunNumber; seed <<= 7; seed += fMCLabel; seed <<= 7; seed += fTimeStamp; return seed; } //_____________________________________________________________________________ void AliAnalysisTaskBaseWeights::LoopOverAllTracks(Int_t flag) { // on data or if fUseMCWeights is not set we do not modify anything if (!fIsMC) { AliAnalysisTaskMKBase::LoopOverAllTracks(flag); } if (!fUseMCWeights) { AliAnalysisTaskMKBase::LoopOverAllTracks(flag); } fNTracksESD = fESD->GetNumberOfTracks(); for (Int_t i = 0; i < fNTracksESD; i++) { fESDTrack = dynamic_cast<AliESDtrack*>(fESD->GetTrack(i)); if (!fESDTrack) { Err("noESDtrack"); continue; } InitTrack(); // get the scaling factor fMCweight = MCScalingFactor(); Double_t s = fMCweight; while (s >= 1) { BaseAnaTrack(flag); s--; } if (s > 0) { if (!fRand) { fRand = new TRandom3(); } fRand->SetSeed(GetSeed()); if (fRand->Rndm() < s) { BaseAnaTrack(flag); } } } } //_____________________________________________________________________________ void AliAnalysisTaskBaseWeights::LoopOverAllParticles(Int_t flag) { // this method should not be called on data if (!fIsMC) return; // only if fUseMCWeights is set we do re weighting if (!fUseMCWeights) { AliAnalysisTaskMKBase::LoopOverAllParticles(flag); } fMCnTracks = fMC->GetNumberOfTracks(); for (Int_t i = 0; i < fMCnTracks; i++) { fMCParticle = dynamic_cast<AliMCParticle*>(fMC->GetTrack(i)); if (!fMCParticle) { Err("noMCParticle"); continue; } fMCLabel = i; InitMCParticle(); // get the scaling factor fMCweight = MCScalingFactor(); Double_t s = fMCweight; while (s >= 1) { BaseAnaParticleMC(flag); s--; } if (s > 0) { if (!fRand) { fRand = new TRandom3(); } fRand->SetSeed(GetSeed()); if (fRand->Rndm() < s) { BaseAnaParticleMC(flag); } } } } //_____________________________________________________________________________ Double_t AliAnalysisTaskBaseWeights::MCScalingFactor() { // determine the MC scaling factor for the current particle // in case the weights are not activated, they are always unity if (!fUseMCWeights) { return 1.0; } // in case mcspectraweights are there we use them for primary particles if (fMCSpectraWeights && fMCisPrim) { // for now I pass the V0M multiplicity percentile // TODO check if this the correct one or what should be passed // TODO maybe ideal is to pass simply the event and let the SpectraWeights decide on which mult to use return fMCSpectraWeights->GetMCSpectraWeight(fMCParticle->Particle(), fMultPercentileV0M); } // if there are no spectraweights or for secondaries we use the static tools function // TODO this has to be modified, currently values for the LCH17pq are hardcoded // TODO also the systematic varation should be set in the addtask somewhere // now always nominal values are used return AlidNdPtTools::MCScalingFactor(fMCParticle, fMC, 0); } //_____________________________________________________________________________ void AliAnalysisTaskBaseWeights::FillDefaultHistograms(Int_t step) { // fill the spectra weights if needed // but do it before any event selection // because this might depent on the derived task //protection if (fMCSpectraWeights && step==0) { if(fMCSpectraWeights->GetTaskStatus() < AliMCSpectraWeights::TaskState::kMCSpectraObtained) { fMCSpectraWeights->FillMCSpectra(fMC); } } //also fill the default histograms AliAnalysisTaskMKBase::FillDefaultHistograms(step); } //_____________________________________________________________________________ AliAnalysisTaskBaseWeights* AliAnalysisTaskBaseWeights::AddTaskBaseWeights(const char* name, const char* outfile, const char* collisionSystem, Int_t sysFlag, const char* prevTrainOutputPath) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskBaseWeights", "No analysis manager to connect to."); return 0; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskBaseWeights", "This task requires an input event handler"); return NULL; } // Setup output file //=========================================================================== TString fileName = AliAnalysisManager::GetCommonFileName(); fileName += ":"; fileName += name; // create a subfolder in the file if (outfile) { // if a finename is given, use that one fileName = TString(outfile); } // create the task //=========================================================================== AliAnalysisTaskBaseWeights *task = new AliAnalysisTaskBaseWeights(name); if (!task) { return 0; } // configure the task //=========================================================================== task->SelectCollisionCandidates(AliVEvent::kAnyINT); task->SetESDtrackCutsM(AlidNdPtTools::CreateESDtrackCuts("defaultEta08")); task->SetESDtrackCuts(0,AlidNdPtTools::CreateESDtrackCuts("defaultEta08")); // configure the use of AliMCSpectraWeights //=========================================================================== if (collisionSystem) { AliMCSpectraWeights* weights = new AliMCSpectraWeights(collisionSystem, "fMCSpectraWeights", (AliMCSpectraWeights::SysFlag)sysFlag); if (prevTrainOutputPath) { weights->SetMCSpectraFile(prevTrainOutputPath); } // path to previous train output weights->Init(); task->fMCSpectraWeights = weights; } // attach the task to the manager and configure in and ouput //=========================================================================== mgr->AddTask(task); mgr->ConnectInput(task,0,mgr->GetCommonInputContainer()); mgr->ConnectOutput(task,1,mgr->CreateContainer(name, TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data())); return task; }
#include <vector> struct vec3d { float x, y, z; }; struct triangle { vec3d p[3]; }; struct mesh { std::vector<triangle> mVector; void createCube() { mVector = { // SOUTH { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f }, // EAST { 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f }, { 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f }, // NORTH { 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f }, { 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f }, // WEST { 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f }, // TOP { 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f }, { 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f }, // BOTTOM { 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f }, }; } }; struct mat4x4 { float mat[4][4] = { 0 }; };
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #include "vclxbutton.hxx" #include <layout/core/helper.hxx> #include <com/sun/star/awt/ImagePosition.hpp> #include <vcl/button.hxx> namespace css = com::sun::star; namespace layoutimpl { VCLXIconButton::VCLXIconButton( Window *p, rtl::OUString aDefaultLabel, char const *pGraphName ) : VCLXButton() { /* FIXME: before Window is set, setLabel, setProperty->setImage * are silent no-ops. */ p->SetComponentInterface( this ); setLabel( aDefaultLabel ); setProperty( rtl::OUString::createFromAscii( "Graphic" ), css::uno::Any( layoutimpl::loadGraphic( pGraphName ) ) ); setProperty( rtl::OUString::createFromAscii( "ImagePosition" ), css::uno::Any( css::awt::ImagePosition::LeftCenter ) ); setProperty( rtl::OUString::createFromAscii( "Align" ), css::uno::Any( (sal_Int16) 1 /* magic - center */ ) ); } // FIXME: l10n/i18n of Reset & Apply VCLXOKButton::VCLXOKButton( Window *p ) : VCLXIconButton( p, Button::GetStandardText( BUTTON_OK ), "res/commandimagelist/sc_ok.png" ) { } VCLXCancelButton::VCLXCancelButton( Window *p ) : VCLXIconButton( p, Button::GetStandardText( BUTTON_CANCEL ), // : VCLXIconButton( xButton, rtl::OUString::createFromAscii( "~Cancel " ), "res/commandimagelist/sc_cancel.png" ) { } VCLXYesButton::VCLXYesButton( Window *p ) : VCLXIconButton( p, Button::GetStandardText( BUTTON_YES ), "res/commandimagelist/sc_yes.png" ) { } VCLXNoButton::VCLXNoButton( Window *p ) : VCLXIconButton( p, Button::GetStandardText( BUTTON_NO ), "res/commandimagelist/sc_no.png" ) { } VCLXRetryButton::VCLXRetryButton( Window *p ) : VCLXIconButton( p, Button::GetStandardText( BUTTON_RETRY ), "res/commandimagelist/sc_retry.png" ) { } VCLXIgnoreButton::VCLXIgnoreButton( Window *p ) : VCLXIconButton( p, Button::GetStandardText( BUTTON_IGNORE ), "res/commandimagelist/sc_ignore.png" ) { } VCLXResetButton::VCLXResetButton( Window *p ) : VCLXIconButton( p, rtl::OUString::createFromAscii( "~Reset " ), "res/commandimagelist/sc_reset.png" ) { } VCLXApplyButton::VCLXApplyButton( Window *p ) : VCLXIconButton( p, rtl::OUString::createFromAscii( "Apply" ), "res/commandimagelist/sc_apply.png" ) { } VCLXHelpButton::VCLXHelpButton( Window *p ) : VCLXIconButton( p, Button::GetStandardText( BUTTON_HELP ), "res/commandimagelist/sc_help.png" ) { } VCLXMoreButton::VCLXMoreButton( Window *p ) : VCLXIconButton( p, Button::GetStandardText( BUTTON_MORE ), // : VCLXIconButton( p, rtl::OUString::createFromAscii( "More " ), "res/commandimagelist/sc_more.png" ) { } VCLXAdvancedButton::VCLXAdvancedButton( Window *p ) // : VCLXIconButton( p, Button::GetStandardText( BUTTON_ADVANCED ), : VCLXIconButton( p, rtl::OUString::createFromAscii( "Advanced " ), "res/commandimagelist/sc_advanced.png" ) { } } // namespace layoutimpl
#include <memory> #include <string> #include <utility> #include "base_test.hpp" #include "gtest/gtest.h" #include "storage/chunk_encoder.hpp" #include "storage/dictionary_segment.hpp" #include "storage/segment_encoding_utils.hpp" #include "storage/value_segment.hpp" #include "storage/vector_compression/fixed_size_byte_aligned/fixed_size_byte_aligned_vector.hpp" namespace opossum { class StorageDictionarySegmentTest : public BaseTest { protected: std::shared_ptr<ValueSegment<int>> vs_int = std::make_shared<ValueSegment<int>>(); std::shared_ptr<ValueSegment<std::string>> vs_str = std::make_shared<ValueSegment<std::string>>(); std::shared_ptr<ValueSegment<double>> vs_double = std::make_shared<ValueSegment<double>>(); }; TEST_F(StorageDictionarySegmentTest, CompressSegmentInt) { vs_int->append(4); vs_int->append(4); vs_int->append(3); vs_int->append(4); vs_int->append(5); vs_int->append(3); auto segment = encode_segment(EncodingType::Dictionary, DataType::Int, vs_int); auto dict_segment = std::dynamic_pointer_cast<DictionarySegment<int>>(segment); // Test attribute_vector size EXPECT_EQ(dict_segment->size(), 6u); // Test dictionary size (uniqueness) EXPECT_EQ(dict_segment->unique_values_count(), 3u); // Test sorting auto dict = dict_segment->dictionary(); EXPECT_EQ((*dict)[0], 3); EXPECT_EQ((*dict)[1], 4); EXPECT_EQ((*dict)[2], 5); } TEST_F(StorageDictionarySegmentTest, CompressSegmentString) { vs_str->append("Bill"); vs_str->append("Steve"); vs_str->append("Alexander"); vs_str->append("Steve"); vs_str->append("Hasso"); vs_str->append("Bill"); auto segment = encode_segment(EncodingType::Dictionary, DataType::String, vs_str); auto dict_segment = std::dynamic_pointer_cast<DictionarySegment<std::string>>(segment); // Test attribute_vector size EXPECT_EQ(dict_segment->size(), 6u); // Test dictionary size (uniqueness) EXPECT_EQ(dict_segment->unique_values_count(), 4u); // Test sorting auto dict = dict_segment->dictionary(); EXPECT_EQ((*dict)[0], "Alexander"); EXPECT_EQ((*dict)[1], "Bill"); EXPECT_EQ((*dict)[2], "Hasso"); EXPECT_EQ((*dict)[3], "Steve"); } TEST_F(StorageDictionarySegmentTest, CompressSegmentDouble) { vs_double->append(0.9); vs_double->append(1.0); vs_double->append(1.0); vs_double->append(1.1); vs_double->append(0.9); vs_double->append(1.1); auto segment = encode_segment(EncodingType::Dictionary, DataType::Double, vs_double); auto dict_segment = std::dynamic_pointer_cast<DictionarySegment<double>>(segment); // Test attribute_vector size EXPECT_EQ(dict_segment->size(), 6u); // Test dictionary size (uniqueness) EXPECT_EQ(dict_segment->unique_values_count(), 3u); // Test sorting auto dict = dict_segment->dictionary(); EXPECT_EQ((*dict)[0], 0.9); EXPECT_EQ((*dict)[1], 1.0); EXPECT_EQ((*dict)[2], 1.1); } TEST_F(StorageDictionarySegmentTest, CompressNullableSegmentInt) { vs_int = std::make_shared<ValueSegment<int>>(true); vs_int->append(4); vs_int->append(4); vs_int->append(3); vs_int->append(4); vs_int->append(NULL_VALUE); vs_int->append(3); auto segment = encode_segment(EncodingType::Dictionary, DataType::Int, vs_int); auto dict_segment = std::dynamic_pointer_cast<DictionarySegment<int>>(segment); // Test attribute_vector size EXPECT_EQ(dict_segment->size(), 6u); // Test dictionary size (uniqueness) EXPECT_EQ(dict_segment->unique_values_count(), 2u); // Test sorting auto dict = dict_segment->dictionary(); EXPECT_EQ((*dict)[0], 3); EXPECT_EQ((*dict)[1], 4); // Test retrieval of null value EXPECT_TRUE(variant_is_null((*dict_segment)[4])); } TEST_F(StorageDictionarySegmentTest, LowerUpperBound) { for (int i = 0; i <= 10; i += 2) vs_int->append(i); auto segment = encode_segment(EncodingType::Dictionary, DataType::Int, vs_int); auto dict_segment = std::dynamic_pointer_cast<DictionarySegment<int>>(segment); // Test for AllTypeVariant as parameter EXPECT_EQ(dict_segment->lower_bound(AllTypeVariant(4)), ValueID{2}); EXPECT_EQ(dict_segment->upper_bound(AllTypeVariant(4)), ValueID{3}); EXPECT_EQ(dict_segment->lower_bound(AllTypeVariant(5)), ValueID{3}); EXPECT_EQ(dict_segment->upper_bound(AllTypeVariant(5)), ValueID{3}); EXPECT_EQ(dict_segment->lower_bound(AllTypeVariant(15)), INVALID_VALUE_ID); EXPECT_EQ(dict_segment->upper_bound(AllTypeVariant(15)), INVALID_VALUE_ID); } TEST_F(StorageDictionarySegmentTest, FixedSizeByteAlignedVectorSize) { vs_int->append(0); vs_int->append(1); vs_int->append(2); auto segment = encode_segment(EncodingType::Dictionary, DataType::Int, vs_int); auto dict_segment = std::dynamic_pointer_cast<DictionarySegment<int>>(segment); auto attribute_vector_uint8_t = std::dynamic_pointer_cast<const FixedSizeByteAlignedVector<uint8_t>>(dict_segment->attribute_vector()); auto attribute_vector_uint16_t = std::dynamic_pointer_cast<const FixedSizeByteAlignedVector<uint16_t>>(dict_segment->attribute_vector()); EXPECT_NE(attribute_vector_uint8_t, nullptr); EXPECT_EQ(attribute_vector_uint16_t, nullptr); for (int i = 3; i < 257; ++i) { vs_int->append(i); } segment = encode_segment(EncodingType::Dictionary, DataType::Int, vs_int); dict_segment = std::dynamic_pointer_cast<DictionarySegment<int>>(segment); attribute_vector_uint8_t = std::dynamic_pointer_cast<const FixedSizeByteAlignedVector<uint8_t>>(dict_segment->attribute_vector()); attribute_vector_uint16_t = std::dynamic_pointer_cast<const FixedSizeByteAlignedVector<uint16_t>>(dict_segment->attribute_vector()); EXPECT_EQ(attribute_vector_uint8_t, nullptr); EXPECT_NE(attribute_vector_uint16_t, nullptr); } TEST_F(StorageDictionarySegmentTest, MemoryUsageEstimation) { /** * WARNING: Since it's hard to assert what constitutes a correct "estimation", this just tests basic sanity of the * memory usage estimations */ const auto empty_memory_usage = encode_segment(EncodingType::Dictionary, DataType::Int, vs_int)->estimate_memory_usage(); vs_int->append(0); vs_int->append(1); vs_int->append(2); const auto compressed_segment = encode_segment(EncodingType::Dictionary, DataType::Int, vs_int); const auto dictionary_segment = std::dynamic_pointer_cast<DictionarySegment<int>>(compressed_segment); static constexpr auto size_of_attribute = 1u; EXPECT_GE(dictionary_segment->estimate_memory_usage(), empty_memory_usage + 3 * size_of_attribute); } } // namespace opossum
/* Apoorvaa has created an elevated roof. She wants to know how much water can she save during rain. Given n non negative integers representing the elevation map where width of every bar is 1, Find the maximum water that she can save. */ #include<bits/stdc++.h> using namespace std; int findWater(int arr[], int n) { // left[i] contains height of tallest bar to the // left of i'th bar including itself int left[n]; // Right [i] contains height of tallest bar to // the right of ith bar including itself int right[n]; // Initialize result int water = 0; // Fill left array left[0] = arr[0]; for (int i = 1; i < n; i++) left[i] = max(left[i-1], arr[i]); // Fill right array right[n-1] = arr[n-1]; for (int i = n-2; i >= 0; i--) right[i] = max(right[i+1], arr[i]); // Calculate the accumulated water element by element // consider the amount of water on i'th bar, the // amount of water accumulated on this particular // bar will be equal to min(left[i], right[i]) - arr[i] . for (int i = 0; i < n; i++) water += min(left[i],right[i]) - arr[i]; return water; } int main() { int n, ans=0,left=0,right=0,j; cin>>n; int arr[n]; for(int i=0; i<n; i++){ cin>>arr[i]; } cout<<findWater(arr,n); return 0; }
#include "BetaStar.h" using namespace sc2; // returns the nearest neutral unit of type target_unit_type // if there is none, returns nullptr const Unit* BetaStar::FindNearestNeutralUnit(const Point2D& start, UnitTypeID target_unit_type) { Units units = Observation()->GetUnits(Unit::Alliance::Neutral); float distance = std::numeric_limits<float>::max(); const Unit* target = nullptr; for (const auto& unit : units) { if (unit->unit_type == target_unit_type) { float d = DistanceSquared2D(unit->pos, start); if (d < distance) { distance = d; target = unit; } } } return target; } // returns a vector containing friendly units of type unit_type const Units BetaStar::FriendlyUnitsOfType(UnitTypeID unit_type) const { return Observation()->GetUnits(Unit::Alliance::Self, IsUnit(unit_type)); } // returns an uncapped mineral or vespene geyser, or the closest mineral if they are all capped const Unit* BetaStar::FindResourceToGather(Point2D unit_pos) { for (const auto& cc : FriendlyUnitsOfType(m_base_typeid)) { if (cc->assigned_harvesters < cc->ideal_harvesters) { return FindNearestNeutralUnit(cc->pos, UNIT_TYPEID::NEUTRAL_MINERALFIELD); } } for (const auto& vg : FriendlyUnitsOfType(m_gas_building_typeid)) { if (vg->assigned_harvesters < vg->ideal_harvesters) { return vg; } } return FindNearestNeutralUnit(unit_pos, UNIT_TYPEID::NEUTRAL_MINERALFIELD); } bool BetaStar::TrainUnit(UnitTypeID unitType) { const UnitTypeID unitBuilder = GetUnitBuilder(unitType); // Only select unit production buildings that aren't doing anything right now Units buildings = Observation()->GetUnits(Unit::Alliance::Self, BetterIsUnit(unitBuilder, HasNoOrders())); // warpgates = gateways, so we can build at them too if (unitBuilder == UNIT_TYPEID::PROTOSS_GATEWAY) { Units warpgates = Observation()->GetUnits(Unit::Alliance::Self, BetterIsUnit(UNIT_TYPEID::PROTOSS_WARPGATE, HasNoOrders())); if (!warpgates.empty()) { buildings.insert(buildings.end(), warpgates.begin(), warpgates.end()); } } // can't build at buildings that aren't built yet for (auto iter = buildings.begin(); iter != buildings.end(); ) { if ((*iter)->build_progress < 1.0f) { iter = buildings.erase(iter); } else { ++iter; } } // we don't have any building that can build this unit if (buildings.size() == 0) { return false; } // get random building from vector and build unit there return TrainUnit(GetRandomEntry(buildings), unitType); } bool BetaStar::TrainUnit(const Unit *building, UnitTypeID unitType) { // note that all TrainUnit variants resolve themselves here, so this is where we can do all of our // checks and handle edge-cases // if a building isn't finished, it can't build units if (building->build_progress < 1.0f) { return false; } // only the nexus can build units without power if (building->unit_type != UNIT_TYPEID::PROTOSS_NEXUS && !building->is_powered) { return false; } UnitTypeID unitBuilder = GetUnitBuilder(unitType); // building at a warpgate instead of a gateway (warp close to warpgate) if (unitBuilder == UNIT_TYPEID::PROTOSS_GATEWAY && building->unit_type == UNIT_TYPEID::PROTOSS_WARPGATE) { if (!m_attacking) { return WarpUnit(building, m_starting_pos, unitType); } else { Units friendlyArmy = GetFriendlyArmyUnits(); if (friendlyArmy.empty()) { return WarpUnit(building, m_starting_pos, unitType); } else { if (m_attacking) { return WarpUnit(building, GetUnitsCentroidNearPoint(friendlyArmy, 0.25f, m_enemy_base_pos), unitType); } else { return WarpUnit(building, GetUnitsCentroid(friendlyArmy), unitType); } } } } // normal training process else if (unitBuilder == building->unit_type) { AbilityID buildAbility = GetUnitBuildAbility(unitType); for (UnitOrder order : building->orders) { // if we have this unit queued to build already, don't queue another one if (order.ability_id == buildAbility) { return false; } } // Return true if training succeeds, false otherwise return TryIssueCommand(building, buildAbility); } // couldn't build that unit at that building - should probably never reach this exit point return false; } bool BetaStar::WarpUnit(Point2D warpLocation, UnitTypeID unitType) { Units warpgates = FriendlyUnitsOfType(UNIT_TYPEID::PROTOSS_WARPGATE); // we don't have any warpgates if (warpgates.size() == 0) { return false; } // get random warpgate and warp unit in with that warpgate return WarpUnit(GetRandomEntry(warpgates), warpLocation, unitType); } bool BetaStar::WarpUnit(const Unit *building, Point2D warpLocation, UnitTypeID unitType) { // if a building isn't finished, it can't build units if (building->build_progress < 1.0f) { return false; } // if our warpgate isn't powered, it can't build units if (!building->is_powered) { return false; } const ObservationInterface* observation = Observation(); const GameInfo gameInfo = observation->GetGameInfo(); std::vector<PowerSource> powerSources = observation->GetPowerSources(); if (powerSources.empty()) { return false; } // find the closest power source to the specified point to warp in around size_t minIndex = 0; float minDist = DistanceSquared2D(warpLocation, powerSources[0].position); for (size_t i = 1; i < powerSources.size(); ++i) { float testDist = DistanceSquared2D(warpLocation, powerSources[i].position); if (testDist < minDist) { minDist = testDist; minIndex = i; } } const PowerSource &targetPowerSource = powerSources[minIndex]; float randomX = GetRandomScalar(); float randomY = GetRandomScalar(); Point2D finalWarpPoint = Point2D(targetPowerSource.position.x + randomX * targetPowerSource.radius, targetPowerSource.position.y + randomY * targetPowerSource.radius); // If the warp location is walled off, don't warp there. // We check this to see if there is pathing from the build location to the center of the map if (Query()->PathingDistance(finalWarpPoint, Point2D(gameInfo.playable_max.x / 2, gameInfo.playable_max.y / 2)) < .01f) { return false; } // If this succeeds, return true. Otherwise, return false. return TryIssueCommand(building, GetUnitWarpAbility(unitType), finalWarpPoint); } size_t BetaStar::MassTrainUnit(UnitTypeID unitType) { UnitTypeID unitBuilder = GetUnitBuilder(unitType); Units buildings = Observation()->GetUnits(Unit::Alliance::Self, IsUnit(unitBuilder)); // warpgates = gateways, so build for them too if (unitBuilder == UNIT_TYPEID::PROTOSS_GATEWAY) { Units warpgates = Observation()->GetUnits(Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_WARPGATE)); if (!warpgates.empty()) { buildings.insert(buildings.end(), warpgates.begin(), warpgates.end()); } } size_t buildCount = 0; for (const Unit* building : buildings) { if (TrainUnit(building, unitType)) { ++buildCount; } } return buildCount; } void BetaStar::TryBuildStructureNearPylon(AbilityID ability_type_for_structure, UnitTypeID unit_type) { const ObservationInterface* observation = Observation(); std::vector<PowerSource> power_sources = observation->GetPowerSources(); if (power_sources.empty()) { return; } int num_tries = 10; for (int i = 0; i < num_tries; ++i) { const PowerSource& random_power_source = GetRandomEntry(power_sources); if (observation->GetUnit(random_power_source.tag)->unit_type == UNIT_TYPEID::PROTOSS_WARPPRISM) { continue; } float radius = random_power_source.radius; float rx = GetRandomScalar(); float ry = GetRandomScalar(); Point2D build_location = Point2D(random_power_source.position.x + rx * radius, random_power_source.position.y + ry * radius); if (Query()->Placement(ability_type_for_structure, build_location)) { Units workers = FriendlyUnitsOfType(unit_type); for (const auto& worker : workers) { for (const auto& order : worker->orders) { if (order.ability_id == ability_type_for_structure) { return; } } } const Unit* closest_worker = nullptr; float closest_distance = std::numeric_limits<float>::max(); for (const auto& worker : workers) { float distance = DistanceSquared2D(build_location, worker->pos); if (distance < closest_distance) { closest_worker = worker; closest_distance = distance; } } if (closest_worker == nullptr) { return; } // try to build the structure in the valid build location if (TryIssueCommand(closest_worker, ability_type_for_structure, build_location)) { // Build valid, add info //bool seen = false; //for (const auto& building : m_buildings) { // if (build_location == position) { // seen = true; // Don't add to vector // } //} //if (!seen) { m_buildings.push_back(std::make_tuple(build_location, ability_type_for_structure)); //} } // if we get here, we either succeeded or can't succeed. Exit. return; } } } bool BetaStar::TryBuildStructureNearPylon(UnitTypeID buildingType, const Unit *builder) { const ObservationInterface *observation = Observation(); AbilityID buildAbility = GetUnitBuildAbility(buildingType); Units allBuilders = FriendlyUnitsOfType(m_worker_typeid); // We don't have any workers. GG. if (allBuilders.empty()) { return false; } // Don't try to build another building until the current one is finished for (const Unit *unit : allBuilders) { for (UnitOrder order : unit->orders) { if (order.ability_id == buildAbility) { return false; } } } // Get all power sources (radius property differs from Unit radius property for pylons) std::vector<PowerSource> powerSources = observation->GetPowerSources(); // Clean out Warp Prisms since we only want to build by pylons for (auto iter = powerSources.begin(); iter != powerSources.end(); ) { UnitTypeID testType = observation->GetUnit(iter->tag)->unit_type; if (testType == UNIT_TYPEID::PROTOSS_WARPPRISM || testType == UNIT_TYPEID::PROTOSS_WARPPRISMPHASING) { iter = powerSources.erase(iter); } else { ++iter; } } // no pylons on the map. GG. if (powerSources.empty()) { return false; } const PowerSource &chosenPylon = GetRandomEntry(powerSources); Point2D buildPos = Point2D(chosenPylon.position.x + GetRandomScalar()*chosenPylon.radius, chosenPylon.position.y + GetRandomScalar()*chosenPylon.radius); // if we don't have a builder selected, get the closest worker if (builder == nullptr) { GetClosestUnit(buildPos, allBuilders); } // We have everything we need to attempt construction return TryBuildStructure(buildingType, buildPos, builder); } bool BetaStar::TryBuildStructureNearPylon(UnitTypeID buildingType, Point2D nearPosition, const Unit *builder) { const ObservationInterface *observation = Observation(); AbilityID buildAbility = GetUnitBuildAbility(buildingType); Units allBuilders = FriendlyUnitsOfType(m_worker_typeid); // We don't have any workers. GG. if (allBuilders.empty()) { return false; } // Don't try to build another building until the current one is finished for (const Unit *unit : allBuilders) { for (UnitOrder order : unit->orders) { if (order.ability_id == buildAbility) { return false; } } } // Get all power sources (radius property differs from Unit radius property for pylons) std::vector<PowerSource> powerSources = observation->GetPowerSources(); // Clean out Warp Prisms since we only want to build by pylons for (auto iter = powerSources.begin(); iter != powerSources.end(); ) { UnitTypeID testType = observation->GetUnit(iter->tag)->unit_type; if (testType == UNIT_TYPEID::PROTOSS_WARPPRISM || testType == UNIT_TYPEID::PROTOSS_WARPPRISMPHASING) { iter = powerSources.erase(iter); } else { ++iter; } } // no pylons on the map. GG. if (powerSources.empty()) { return false; } size_t minIndex = 0; float minDistSqrd = DistanceSquared2D(powerSources[minIndex].position, nearPosition); for (size_t index = 1; index < powerSources.size(); ++index) { float testDistSqrd = DistanceSquared2D(powerSources[index].position, nearPosition); if (testDistSqrd < minDistSqrd) { minIndex = index; minDistSqrd = testDistSqrd; } } const PowerSource &chosenPylon = powerSources[minIndex]; Point2D buildPos = Point2D(chosenPylon.position.x + GetRandomScalar()*chosenPylon.radius, chosenPylon.position.y + GetRandomScalar()*chosenPylon.radius); // if we don't have a builder selected, get the closest worker if (builder == nullptr) { GetClosestUnit(buildPos, allBuilders); } // We have everything we need to attempt construction return TryBuildStructure(buildingType, buildPos, builder); } bool BetaStar::TryBuildStructureNearPylon(UnitTypeID buildingType, Point2D nearPosition, float maxRadius, const Unit *builder) { const ObservationInterface *observation = Observation(); AbilityID buildAbility = GetUnitBuildAbility(buildingType); Units allBuilders = FriendlyUnitsOfType(m_worker_typeid); // We don't have any workers. GG. if (allBuilders.empty()) { return false; } // Don't try to build another building until the current one is finished for (const Unit *unit : allBuilders) { for (UnitOrder order : unit->orders) { if (order.ability_id == buildAbility) { return false; } } } // Get all power sources (radius property differs from Unit radius property for pylons) std::vector<PowerSource> powerSources = observation->GetPowerSources(); float radiusSqrd = maxRadius * maxRadius; // Clean out Warp Prisms since we only want to build by pylons // Also clean out pylons not within the specified radius for (auto iter = powerSources.begin(); iter != powerSources.end(); ) { UnitTypeID testType = observation->GetUnit(iter->tag)->unit_type; if (testType == UNIT_TYPEID::PROTOSS_WARPPRISM || testType == UNIT_TYPEID::PROTOSS_WARPPRISMPHASING) { iter = powerSources.erase(iter); } else if (DistanceSquared2D(iter->position, nearPosition) > radiusSqrd) { iter = powerSources.erase(iter); } else { ++iter; } } // no valid pylons if (powerSources.empty()) { return false; } const PowerSource &chosenPylon = GetRandomEntry(powerSources); Point2D buildPos = Point2D(chosenPylon.position.x + GetRandomScalar()*chosenPylon.radius, chosenPylon.position.y + GetRandomScalar()*chosenPylon.radius); // if we don't have a builder selected, get the closest worker if (builder == nullptr) { builder = GetClosestUnit(buildPos, allBuilders); } // We have everything we need to attempt construction return TryBuildStructure(buildingType, buildPos, builder); } bool BetaStar::TryBuildStructure(UnitTypeID buildingType, Point2D buildPos, const Unit *builder) { AbilityID buildAbility = GetUnitBuildAbility(buildingType); // Test building placement at that location to make sure nothing is in the way if (Query()->Placement(buildAbility, buildPos)) { // The builder can't build there if they can't get there if (!AlmostEqual(Query()->PathingDistance(builder, buildPos), 0.0f)) { // try to build the structure in the valid build location if (TryIssueCommand(builder, buildAbility, buildPos)) { // Pylons are managed in a different place if (buildingType != m_supply_building_typeid) { m_buildings.push_back(std::make_tuple(buildPos, buildAbility)); } return true; } } } // Couldn't build return false; } void BetaStar::TryResearchUpgrade(AbilityID upgrade_abilityid, UnitTypeID building_type) { const ObservationInterface* observation = Observation(); Units buildings = FriendlyUnitsOfType(building_type); // check whether the upgrade is already being researched for (const auto& building : buildings) { if (building->build_progress != 1) { continue; } for (const auto& order : building->orders) { if (order.ability_id == upgrade_abilityid) { return; } } } // look for unoccupied building, research upgrade for (const auto& building : buildings) { if (building->build_progress != 1) { continue; } if (building->orders.size() == 0) { // if we're successful in researching the upgrade, exit if (TryIssueCommand(building, upgrade_abilityid)) { return; } } } } void BetaStar::ClearArmyRatios() { army_ratios.clear(); } size_t BetaStar::CountUnitType(UnitTypeID unitType, bool includeIncomplete) { const ObservationInterface *observation = Observation(); const Units allUnits = observation->GetUnits(Unit::Alliance::Self, IsUnit(unitType)); size_t count = 0; // count structures differently than units if (IsStructure(unitType)) { // buildings under construction will be included in allUnits if (includeIncomplete) { count = allUnits.size(); } // only count buildings that are fully constructed else { for (const Unit *building : allUnits) { if (building->build_progress == 1.0f) { ++count; } } } } else { count = allUnits.size(); // units in the queue are not included in allUnits if (includeIncomplete) { const Units trainingUnits = observation->GetUnits(Unit::Alliance::Self, IsUnit(GetUnitBuilder(unitType))); for (const Unit *trainer : trainingUnits) { AbilityID buildAbility = GetUnitBuildAbility(unitType); for (UnitOrder order : trainer->orders) { if (order.ability_id == buildAbility) { ++count; } } } } } return count; } void BetaStar::SetStrategy(Strategy newStrategy) { m_current_strategy = newStrategy; // Set all ratios to 0. No new units will be built automatically. ClearArmyRatios(); // Set new army ratios based on the strategy (can be fine-tuned elsewhere) switch (newStrategy) { case Strategy::Blink_Stalker_Rush: army_ratios[UNIT_TYPEID::PROTOSS_STALKER] = 1.0f; break; default: army_ratios[UNIT_TYPEID::PROTOSS_STALKER] = 1.0f; break; } } bool BetaStar::TryIssueCommand(const Unit *unit, AbilityID ability) { // Generic catch for when we can't use this ability (i.e. can't afford it, don't have the upgrades, on cooldown, etc.) AvailableAbilities abilities = Query()->GetAbilitiesForUnit(unit); for (const auto &tempAbility : abilities.abilities) { if (tempAbility.ability_id == ability) { Actions()->UnitCommand(unit, ability); return true; } } return false; } bool BetaStar::TryIssueCommand(const Unit *unit, AbilityID ability, const Unit *target) { // Generic catch for when we can't use this ability (i.e. can't afford it, don't have the upgrades, on cooldown, etc.) AvailableAbilities abilities = Query()->GetAbilitiesForUnit(unit); for (const auto &tempAbility : abilities.abilities) { if (tempAbility.ability_id == ability) { Actions()->UnitCommand(unit, ability, target); return true; } } return false; } bool BetaStar::TryIssueCommand(const Unit *unit, AbilityID ability, Point2D point) { // Generic catch for when we can't use this ability (i.e. can't afford it, don't have the upgrades, on cooldown, etc.) AvailableAbilities abilities = Query()->GetAbilitiesForUnit(unit); for (const auto &tempAbility : abilities.abilities) { if (tempAbility.ability_id == ability) { Actions()->UnitCommand(unit, ability, point); return true; } } return false; } const Unit* BetaStar::GetClosestUnit(Point2D position, const Units units) { // empty collections of units should never be passed if (units.empty()) { return nullptr; } size_t minIndex = 0; float minDist = DistanceSquared2D(position, units[minIndex]->pos); for (size_t i = 1; i < units.size(); ++i) { float testDist = DistanceSquared2D(position, units[i]->pos); if (testDist < minDist) { minDist = testDist; minIndex = i; } } return units[minIndex]; } Point2D BetaStar::GetUnitsCentroid(const Units units) { if (units.empty()) { return Point2D(96, 96); } Point2D centroid(0, 0); for (const Unit *unit : units) { centroid += unit->pos; } return centroid / (float)units.size(); } Point2D BetaStar::GetUnitsCentroidNearPoint(Units units, float unitFrac, Point2D desiredTarget) { // Can't work with 0 units if (AlmostEqual(unitFrac, 0.0f) || units.empty()) return Point2D(96, 96); std::sort(units.begin(), units.end(), IsCloser(desiredTarget)); int nUnits = (int)ceil(units.size() * unitFrac); Point2D centroid(0.0f, 0.0f); for (size_t i = 0; i < nUnits; ++i) { centroid += units[i]->pos; } return centroid / (float)nUnits; } float BetaStar::GetGameTime() { return Observation()->GetGameLoop() / 22.4f; } int BetaStar::GetQuadrantByPoint(Point2D pos) { if (pos.x < 96) { if (pos.y < 96) { return SW; } else { return NW; } } else { if (pos.y < 96) { return SE; } else { return NE; } } } // assumes points are in the south-west quadrant (x < 96, y < 96) Point2D BetaStar::RotatePosition(Point2D pos, int new_quadrant) { Point2D new_pos(pos); new_pos.x = new_pos.x - 96; new_pos.y = new_pos.y - 96; switch (new_quadrant) { case (SW): { break; } case (NW): { for (int i = 0; i < 1; i++) { float x = new_pos.x; float y = new_pos.y; new_pos.x = y; new_pos.y = x * -1; } break; } case (NE): { for (int i = 0; i < 2; i++) { float x = new_pos.x; float y = new_pos.y; new_pos.x = y; new_pos.y = x * -1; } break; } case (SE): { for (int i = 0; i < 3; i++) { float x = new_pos.x; float y = new_pos.y; new_pos.x = y; new_pos.y = x * -1; } break; } } new_pos.x = new_pos.x + 96; new_pos.y = new_pos.y + 96; return new_pos; } UnitTypeID BetaStar::GetUnitBuilder(UnitTypeID unitToBuild) { // TODO: Warp gates are not represented as a builder switch (unitToBuild.ToType()) { // Protoss Units case UNIT_TYPEID::PROTOSS_ADEPT: return UNIT_TYPEID::PROTOSS_GATEWAY; case UNIT_TYPEID::PROTOSS_ASSIMILATOR: return UNIT_TYPEID::PROTOSS_PROBE; case UNIT_TYPEID::PROTOSS_CARRIER: return UNIT_TYPEID::PROTOSS_STARGATE; case UNIT_TYPEID::PROTOSS_COLOSSUS: return UNIT_TYPEID::PROTOSS_ROBOTICSFACILITY; case UNIT_TYPEID::PROTOSS_CYBERNETICSCORE: return UNIT_TYPEID::PROTOSS_PROBE; case UNIT_TYPEID::PROTOSS_DARKSHRINE: return UNIT_TYPEID::PROTOSS_PROBE; case UNIT_TYPEID::PROTOSS_DARKTEMPLAR: return UNIT_TYPEID::PROTOSS_GATEWAY; case UNIT_TYPEID::PROTOSS_DISRUPTOR: return UNIT_TYPEID::PROTOSS_ROBOTICSFACILITY; case UNIT_TYPEID::PROTOSS_FLEETBEACON: return UNIT_TYPEID::PROTOSS_PROBE; case UNIT_TYPEID::PROTOSS_FORGE: return UNIT_TYPEID::PROTOSS_PROBE; case UNIT_TYPEID::PROTOSS_GATEWAY: return UNIT_TYPEID::PROTOSS_PROBE; case UNIT_TYPEID::PROTOSS_HIGHTEMPLAR: return UNIT_TYPEID::PROTOSS_GATEWAY; case UNIT_TYPEID::PROTOSS_IMMORTAL: return UNIT_TYPEID::PROTOSS_ROBOTICSFACILITY; case UNIT_TYPEID::PROTOSS_INTERCEPTOR: return UNIT_TYPEID::PROTOSS_CARRIER; case UNIT_TYPEID::PROTOSS_MOTHERSHIP: return UNIT_TYPEID::PROTOSS_NEXUS; case UNIT_TYPEID::PROTOSS_NEXUS: return UNIT_TYPEID::PROTOSS_PROBE; case UNIT_TYPEID::PROTOSS_OBSERVER: return UNIT_TYPEID::PROTOSS_ROBOTICSFACILITY; case UNIT_TYPEID::PROTOSS_ORACLE: return UNIT_TYPEID::PROTOSS_STARGATE; case UNIT_TYPEID::PROTOSS_PHOENIX: return UNIT_TYPEID::PROTOSS_STARGATE; case UNIT_TYPEID::PROTOSS_PHOTONCANNON: return UNIT_TYPEID::PROTOSS_PROBE; case UNIT_TYPEID::PROTOSS_PROBE: return UNIT_TYPEID::PROTOSS_NEXUS; case UNIT_TYPEID::PROTOSS_PYLON: return UNIT_TYPEID::PROTOSS_PROBE; case UNIT_TYPEID::PROTOSS_ROBOTICSBAY: return UNIT_TYPEID::PROTOSS_PROBE; case UNIT_TYPEID::PROTOSS_ROBOTICSFACILITY: return UNIT_TYPEID::PROTOSS_PROBE; case UNIT_TYPEID::PROTOSS_SENTRY: return UNIT_TYPEID::PROTOSS_GATEWAY; case UNIT_TYPEID::PROTOSS_SHIELDBATTERY: return UNIT_TYPEID::PROTOSS_PROBE; case UNIT_TYPEID::PROTOSS_STALKER: return UNIT_TYPEID::PROTOSS_GATEWAY; case UNIT_TYPEID::PROTOSS_STARGATE: return UNIT_TYPEID::PROTOSS_PROBE; case UNIT_TYPEID::PROTOSS_TEMPEST: return UNIT_TYPEID::PROTOSS_STARGATE; case UNIT_TYPEID::PROTOSS_TEMPLARARCHIVE: return UNIT_TYPEID::PROTOSS_PROBE; case UNIT_TYPEID::PROTOSS_TWILIGHTCOUNCIL: return UNIT_TYPEID::PROTOSS_PROBE; case UNIT_TYPEID::PROTOSS_VOIDRAY: return UNIT_TYPEID::PROTOSS_STARGATE; case UNIT_TYPEID::PROTOSS_WARPPRISM: return UNIT_TYPEID::PROTOSS_ROBOTICSFACILITY; case UNIT_TYPEID::PROTOSS_ZEALOT: return UNIT_TYPEID::PROTOSS_GATEWAY; // Terran Units - no need to complete case UNIT_TYPEID::TERRAN_BARRACKS: return UNIT_TYPEID::TERRAN_SCV; case UNIT_TYPEID::TERRAN_COMMANDCENTER: return UNIT_TYPEID::TERRAN_SCV; case UNIT_TYPEID::TERRAN_MARINE: return UNIT_TYPEID::TERRAN_BARRACKS; case UNIT_TYPEID::TERRAN_SCV: return UNIT_TYPEID::TERRAN_COMMANDCENTER; // Should never be reached default: // Program broke because unit you asked for wasn't added to the switch case yet. Add it. std::cout << "ERROR: GetUnitBuilder could not find a builder for [" << unitToBuild.to_string() << "]. Add this to the switch case." << std::endl; return UNIT_TYPEID::INVALID; } } AbilityID BetaStar::GetUnitBuildAbility(UnitTypeID unitToBuild) { // TODO: Warping units is a different action. Not represented. switch (unitToBuild.ToType()) { // Protoss Build Actions case UNIT_TYPEID::PROTOSS_ADEPT: return ABILITY_ID::TRAIN_ADEPT; case UNIT_TYPEID::PROTOSS_ASSIMILATOR: return ABILITY_ID::BUILD_ASSIMILATOR; case UNIT_TYPEID::PROTOSS_CARRIER: return ABILITY_ID::TRAIN_CARRIER; case UNIT_TYPEID::PROTOSS_COLOSSUS: return ABILITY_ID::TRAIN_COLOSSUS; case UNIT_TYPEID::PROTOSS_CYBERNETICSCORE: return ABILITY_ID::BUILD_CYBERNETICSCORE; case UNIT_TYPEID::PROTOSS_DARKSHRINE: return ABILITY_ID::BUILD_DARKSHRINE; case UNIT_TYPEID::PROTOSS_DARKTEMPLAR: return ABILITY_ID::TRAIN_DARKTEMPLAR; case UNIT_TYPEID::PROTOSS_DISRUPTOR: return ABILITY_ID::TRAIN_DISRUPTOR; case UNIT_TYPEID::PROTOSS_FLEETBEACON: return ABILITY_ID::BUILD_FLEETBEACON; case UNIT_TYPEID::PROTOSS_FORGE: return ABILITY_ID::BUILD_FORGE; case UNIT_TYPEID::PROTOSS_GATEWAY: return ABILITY_ID::BUILD_GATEWAY; case UNIT_TYPEID::PROTOSS_HIGHTEMPLAR: return ABILITY_ID::TRAIN_HIGHTEMPLAR; case UNIT_TYPEID::PROTOSS_IMMORTAL: return ABILITY_ID::TRAIN_IMMORTAL; case UNIT_TYPEID::PROTOSS_INTERCEPTOR: return ABILITY_ID::BUILD_INTERCEPTORS; case UNIT_TYPEID::PROTOSS_MOTHERSHIP: return ABILITY_ID::TRAIN_MOTHERSHIP; case UNIT_TYPEID::PROTOSS_NEXUS: return ABILITY_ID::BUILD_NEXUS; case UNIT_TYPEID::PROTOSS_OBSERVER: return ABILITY_ID::TRAIN_OBSERVER; case UNIT_TYPEID::PROTOSS_ORACLE: return ABILITY_ID::TRAIN_ORACLE; case UNIT_TYPEID::PROTOSS_PHOENIX: return ABILITY_ID::TRAIN_PHOENIX; case UNIT_TYPEID::PROTOSS_PHOTONCANNON: return ABILITY_ID::BUILD_PHOTONCANNON; case UNIT_TYPEID::PROTOSS_PROBE: return ABILITY_ID::TRAIN_PROBE; case UNIT_TYPEID::PROTOSS_PYLON: return ABILITY_ID::BUILD_PYLON; case UNIT_TYPEID::PROTOSS_ROBOTICSBAY: return ABILITY_ID::BUILD_ROBOTICSBAY; case UNIT_TYPEID::PROTOSS_ROBOTICSFACILITY: return ABILITY_ID::BUILD_ROBOTICSFACILITY; case UNIT_TYPEID::PROTOSS_SENTRY: return ABILITY_ID::TRAIN_SENTRY; case UNIT_TYPEID::PROTOSS_SHIELDBATTERY: return ABILITY_ID::BUILD_SHIELDBATTERY; case UNIT_TYPEID::PROTOSS_STALKER: return ABILITY_ID::TRAIN_STALKER; case UNIT_TYPEID::PROTOSS_STARGATE: return ABILITY_ID::BUILD_STARGATE; case UNIT_TYPEID::PROTOSS_TEMPEST: return ABILITY_ID::TRAIN_TEMPEST; case UNIT_TYPEID::PROTOSS_TEMPLARARCHIVE: return ABILITY_ID::BUILD_TEMPLARARCHIVE; case UNIT_TYPEID::PROTOSS_TWILIGHTCOUNCIL: return ABILITY_ID::BUILD_TWILIGHTCOUNCIL; case UNIT_TYPEID::PROTOSS_VOIDRAY: return ABILITY_ID::TRAIN_VOIDRAY; case UNIT_TYPEID::PROTOSS_WARPPRISM: return ABILITY_ID::TRAIN_WARPPRISM; case UNIT_TYPEID::PROTOSS_ZEALOT: return ABILITY_ID::TRAIN_ZEALOT; // Terran Build Actions - no need to complete case UNIT_TYPEID::TERRAN_BARRACKS: return ABILITY_ID::BUILD_BARRACKS; case UNIT_TYPEID::TERRAN_COMMANDCENTER: return ABILITY_ID::BUILD_COMMANDCENTER; case UNIT_TYPEID::TERRAN_MARINE: return ABILITY_ID::TRAIN_MARINE; case UNIT_TYPEID::TERRAN_SCV: return ABILITY_ID::TRAIN_SCV; // Should never be reached default: // Program broke because unit you asked for wasn't added to the switch case yet. Add it. std::cout << "ERROR: GetUnitBuildAbility could not find a build command for [" << unitToBuild.to_string() << "]. Add this to the switch case." << std::endl; return ABILITY_ID::INVALID; } } AbilityID BetaStar::GetUnitWarpAbility(UnitTypeID unitToWarp) { switch (unitToWarp.ToType()) { case UNIT_TYPEID::PROTOSS_ZEALOT: return ABILITY_ID::TRAINWARP_ZEALOT; case UNIT_TYPEID::PROTOSS_SENTRY: return ABILITY_ID::TRAINWARP_SENTRY; case UNIT_TYPEID::PROTOSS_STALKER: return ABILITY_ID::TRAINWARP_STALKER; case UNIT_TYPEID::PROTOSS_ADEPT: return ABILITY_ID::TRAINWARP_ADEPT; case UNIT_TYPEID::PROTOSS_HIGHTEMPLAR: return ABILITY_ID::TRAINWARP_HIGHTEMPLAR; case UNIT_TYPEID::PROTOSS_DARKTEMPLAR: return ABILITY_ID::TRAINWARP_DARKTEMPLAR; // unit cannot be warped default: return ABILITY_ID::INVALID; } } bool BetaStar::IsStructure(UnitTypeID unitType) { switch (unitType.ToType()) { case UNIT_TYPEID::PROTOSS_ASSIMILATOR: case UNIT_TYPEID::PROTOSS_CYBERNETICSCORE: case UNIT_TYPEID::PROTOSS_DARKSHRINE: case UNIT_TYPEID::PROTOSS_FLEETBEACON: case UNIT_TYPEID::PROTOSS_FORGE: case UNIT_TYPEID::PROTOSS_GATEWAY: case UNIT_TYPEID::PROTOSS_NEXUS: case UNIT_TYPEID::PROTOSS_PHOTONCANNON: case UNIT_TYPEID::PROTOSS_PYLON: case UNIT_TYPEID::PROTOSS_PYLONOVERCHARGED: case UNIT_TYPEID::PROTOSS_ROBOTICSBAY: case UNIT_TYPEID::PROTOSS_ROBOTICSFACILITY: case UNIT_TYPEID::PROTOSS_STARGATE: case UNIT_TYPEID::PROTOSS_TEMPLARARCHIVE: case UNIT_TYPEID::PROTOSS_TWILIGHTCOUNCIL: case UNIT_TYPEID::PROTOSS_WARPGATE: case UNIT_TYPEID::TERRAN_ARMORY: case UNIT_TYPEID::TERRAN_AUTOTURRET: case UNIT_TYPEID::TERRAN_BARRACKS: case UNIT_TYPEID::TERRAN_BARRACKSFLYING: case UNIT_TYPEID::TERRAN_BARRACKSREACTOR: case UNIT_TYPEID::TERRAN_BARRACKSTECHLAB: case UNIT_TYPEID::TERRAN_BUNKER: case UNIT_TYPEID::TERRAN_COMMANDCENTER: case UNIT_TYPEID::TERRAN_COMMANDCENTERFLYING: case UNIT_TYPEID::TERRAN_ENGINEERINGBAY: case UNIT_TYPEID::TERRAN_FACTORY: case UNIT_TYPEID::TERRAN_FACTORYFLYING: case UNIT_TYPEID::TERRAN_FACTORYREACTOR: case UNIT_TYPEID::TERRAN_FACTORYTECHLAB: case UNIT_TYPEID::TERRAN_FUSIONCORE: case UNIT_TYPEID::TERRAN_GHOSTACADEMY: case UNIT_TYPEID::TERRAN_MISSILETURRET: case UNIT_TYPEID::TERRAN_ORBITALCOMMAND: case UNIT_TYPEID::TERRAN_ORBITALCOMMANDFLYING: case UNIT_TYPEID::TERRAN_PLANETARYFORTRESS: case UNIT_TYPEID::TERRAN_POINTDEFENSEDRONE: case UNIT_TYPEID::TERRAN_REACTOR: case UNIT_TYPEID::TERRAN_REFINERY: case UNIT_TYPEID::TERRAN_SENSORTOWER: case UNIT_TYPEID::TERRAN_STARPORT: case UNIT_TYPEID::TERRAN_STARPORTFLYING: case UNIT_TYPEID::TERRAN_STARPORTREACTOR: case UNIT_TYPEID::TERRAN_STARPORTTECHLAB: case UNIT_TYPEID::TERRAN_SUPPLYDEPOT: case UNIT_TYPEID::TERRAN_SUPPLYDEPOTLOWERED: case UNIT_TYPEID::TERRAN_TECHLAB: case UNIT_TYPEID::ZERG_BANELINGNEST: case UNIT_TYPEID::ZERG_CREEPTUMOR: case UNIT_TYPEID::ZERG_CREEPTUMORBURROWED: case UNIT_TYPEID::ZERG_CREEPTUMORQUEEN: case UNIT_TYPEID::ZERG_EVOLUTIONCHAMBER: case UNIT_TYPEID::ZERG_EXTRACTOR: case UNIT_TYPEID::ZERG_GREATERSPIRE: case UNIT_TYPEID::ZERG_HATCHERY: case UNIT_TYPEID::ZERG_HIVE: case UNIT_TYPEID::ZERG_HYDRALISKDEN: case UNIT_TYPEID::ZERG_INFESTATIONPIT: case UNIT_TYPEID::ZERG_LAIR: case UNIT_TYPEID::ZERG_NYDUSCANAL: case UNIT_TYPEID::ZERG_NYDUSNETWORK: case UNIT_TYPEID::ZERG_ROACHWARREN: case UNIT_TYPEID::ZERG_SPAWNINGPOOL: case UNIT_TYPEID::ZERG_SPIRE: case UNIT_TYPEID::ZERG_SPINECRAWLER: case UNIT_TYPEID::ZERG_SPINECRAWLERUPROOTED: case UNIT_TYPEID::ZERG_SPORECRAWLER: case UNIT_TYPEID::ZERG_SPORECRAWLERUPROOTED: case UNIT_TYPEID::ZERG_ULTRALISKCAVERN: return true; default: return false; } } bool BetaStar::AlmostEqual(float lhs, float rhs, float threshold) { return abs(lhs - rhs) <= threshold; } bool BetaStar::AlmostEqual(Point2D lhs, Point2D rhs, Point2D threshold) { Point2D diff = lhs - rhs; return abs(diff.x) <= threshold.x && abs(diff.y) <= threshold.y; } //Returns an double, higher for higher priority units double BetaStar::GetUnitAttackPriority(const Unit* unit, Point2D army_centroid) { double targeting_value = 0.0; // add a penalty to the targeting value based on distance to our army double distance_weight = -3.0; double no_penalty_range = 5.0; double distance_to_army = Distance2D(unit->pos, army_centroid); double distance_term = pow(std::max(0.0, distance_to_army - no_penalty_range), 2); targeting_value += distance_term * distance_weight; // add a bonus to the targeting value if the unit is low on health / shields double health_weight = 50.0; double unit_health_percent = ((unit->health + unit->shield) / (unit->health_max + unit->shield_max)); double health_term = pow(1 - unit_health_percent, 2); targeting_value += health_term * health_weight; // add a bonus to the targeting value based on the unit type // Between 0 and 100 for structural units // Between 100 and 200 for low priority units // Between 200 and 300 for medium priority units // Between 300 and 400 for high priority units double priority_weight = 1.0; double priority_value = std::numeric_limits<double>::min(); switch (enemy_race) { case Race::Protoss: priority_value = GetProtossUnitAttackPriority(unit); break; case Race::Terran: priority_value = GetTerranUnitAttackPriority(unit); break; case Race::Zerg: priority_value = GetZergUnitAttackPriority(unit); break; case Race::Random: std::cout << "Enemy Race not yet detected. Using fallbacks."; priority_value = GenericPriorityFallbacks(unit); break; default: std::cout << "Should not be reached"; return std::numeric_limits<double>::min(); } targeting_value += priority_value * priority_weight; // return the final targeting value return targeting_value; } double BetaStar::GetProtossUnitAttackPriority(const Unit* unit) { // Order in descending priority, except for the default case switch ((unit->unit_type).ToType()) { case UNIT_TYPEID::PROTOSS_DARKTEMPLAR: case UNIT_TYPEID::PROTOSS_WARPPRISM: case UNIT_TYPEID::PROTOSS_MOTHERSHIP: return 500; case UNIT_TYPEID::PROTOSS_DARKSHRINE: return 400; case UNIT_TYPEID::PROTOSS_DISRUPTOR: case UNIT_TYPEID::PROTOSS_HIGHTEMPLAR: case UNIT_TYPEID::PROTOSS_SENTRY: return 300; case UNIT_TYPEID::PROTOSS_PHOTONCANNON: return unit->is_powered ? 300 : 3; case UNIT_TYPEID::PROTOSS_IMMORTAL: return 225; // default units with weapons will be 199 case UNIT_TYPEID::PROTOSS_OBSERVER: return AlmostEqual(army_ratios[UNIT_TYPEID::PROTOSS_DARKTEMPLAR], 0.0f) ? 0 : 150; case UNIT_TYPEID::PROTOSS_PYLON: return 125; case UNIT_TYPEID::PROTOSS_NEXUS: return 115; case UNIT_TYPEID::PROTOSS_PROBE: return 110; case UNIT_TYPEID::PROTOSS_GATEWAY: case UNIT_TYPEID::PROTOSS_WARPGATE: case UNIT_TYPEID::PROTOSS_STARGATE: case UNIT_TYPEID::PROTOSS_ROBOTICSFACILITY: return unit->is_powered ? 100 : 2; // default units without weapons will be 99 // default buildings without weapons will be 1 default: return GenericPriorityFallbacks(unit); } } double BetaStar::GetTerranUnitAttackPriority(const Unit* unit) { // Order in descending priority, except for the default case switch ((unit->unit_type).ToType()) { case UNIT_TYPEID::TERRAN_SIEGETANK: return 1000; case UNIT_TYPEID::TERRAN_GHOST: return 400; case UNIT_TYPEID::TERRAN_BATTLECRUISER: return 300; case UNIT_TYPEID::TERRAN_MEDIVAC: case UNIT_TYPEID::TERRAN_PLANETARYFORTRESS: return 200; // default units with weapons will be 199 case UNIT_TYPEID::TERRAN_MARINE: case UNIT_TYPEID::TERRAN_REAPER: return 150; case UNIT_TYPEID::TERRAN_SCV: return 125; case UNIT_TYPEID::TERRAN_COMMANDCENTER: case UNIT_TYPEID::TERRAN_COMMANDCENTERFLYING: case UNIT_TYPEID::TERRAN_ORBITALCOMMAND: case UNIT_TYPEID::TERRAN_ORBITALCOMMANDFLYING: return 125; case UNIT_TYPEID::TERRAN_FACTORY: case UNIT_TYPEID::TERRAN_BARRACKS: case UNIT_TYPEID::TERRAN_STARPORT: return 100; // default units without weapons will be 99 // default buildings without weapons will be 1 default: return GenericPriorityFallbacks(unit); } } double BetaStar::GetZergUnitAttackPriority(const Unit* unit) { // Order in descending priority, except for the default case switch ((unit->unit_type).ToType()) { case UNIT_TYPEID::ZERG_BROODLORD: case UNIT_TYPEID::ZERG_ULTRALISK: return 400; case UNIT_TYPEID::ZERG_VIPER: case UNIT_TYPEID::ZERG_SWARMHOSTMP: case UNIT_TYPEID::ZERG_INFESTOR: case UNIT_TYPEID::ZERG_LURKERMP: return 300; case UNIT_TYPEID::ZERG_QUEEN: case UNIT_TYPEID::ZERG_RAVAGER: return 225; // default units with weapons will be 199 case UNIT_TYPEID::ZERG_HATCHERY: case UNIT_TYPEID::ZERG_LAIR: case UNIT_TYPEID::ZERG_HIVE: return 100; // default units without weapons will be 99 case UNIT_TYPEID::ZERG_DRONE: return 75; case UNIT_TYPEID::ZERG_OVERSEER: case UNIT_TYPEID::ZERG_OVERLORD: return 50; // default buildings without weapons will be 1 case UNIT_TYPEID::ZERG_LARVA: case UNIT_TYPEID::ZERG_BROODLORDCOCOON: case UNIT_TYPEID::ZERG_RAVAGERCOCOON: case UNIT_TYPEID::ZERG_OVERLORDCOCOON: case UNIT_TYPEID::ZERG_TRANSPORTOVERLORDCOCOON: case UNIT_TYPEID::ZERG_EGG: return 0; default: return GenericPriorityFallbacks(unit); } } double BetaStar::GenericPriorityFallbacks(const Unit* unit) { // Units with weapons are more dangerous if (all_unit_type_data[unit->unit_type].weapons.size() > 0) { return 199; } // Of the units that can't attack, structures are lowest priority (leave room for 0 priority units) else { return IsStructure(unit->unit_type) ? 1 : 99; } } bool BetaStar::CanAttackAirUnits(const Unit* unit) { for (Weapon w : all_unit_type_data[unit->unit_type].weapons) { if (w.type == Weapon::TargetType::Air || w.type == Weapon::TargetType::Any) { return true; } } return false; } Units BetaStar::GetFriendlyArmyUnits() { const ObservationInterface *observation = Observation(); Units army = observation->GetUnits(Unit::Alliance::Self, BetterIsUnit(managed_unit_types[0])); for (size_t i = 1; i < managed_unit_types.size(); ++i) { Units moreUnits = observation->GetUnits(Unit::Alliance::Self, BetterIsUnit(managed_unit_types[i])); army.insert(army.begin(), moreUnits.begin(), moreUnits.end()); } return army; }
// ----------------------------------------------------------------------------- // FILE: GraphUpdateThread.cpp // DESCRIPTION: thread used for reading and displaying data results from library // DATE: 2013-05-06 // AUTHOR(s): Lime Microsystems // REVISIONS: // ----------------------------------------------------------------------------- #include "GraphUpdateThread.h" #include "ctr_6002dr2_LogicDLL.h" #include "pnlSpectrum.h" #ifdef WIN32 #else #include "TimeCounter.h" #endif // WIN32 #include "GUIUtils.h" /** Sets up buffers for FFT results calculating and drawing @param frm pointer to Spectrum panel */ GraphUpdateThread::GraphUpdateThread(pnlSpectrum *frm) { m_spectrum = frm; work = false; terminated = true; //buffer count for averaging FFT results m_buffersCount = 4; // must be power of 2 m_buffersCountMask = m_buffersCount - 1; //allocates memory for FFT results averaging m_FFTamplitudesBuffer = new float*[m_buffersCount+1]; for(int i=0; i<m_buffersCount+1; i++) m_FFTamplitudesBuffer[i] = new float[m_spectrum->m_FFTsamplesCount]; bufferPos = 0; } GraphUpdateThread::~GraphUpdateThread() { if(m_FFTamplitudesBuffer) { for(int i=0; i<m_buffersCount+1; i++) delete []m_FFTamplitudesBuffer[i]; delete []m_FFTamplitudesBuffer; m_FFTamplitudesBuffer = NULL; } } /** Performs FFT calculation and updates graphs */ void GraphUpdateThread::Execute() { terminated = false; int fps = 60; //max number of graph updates per second int currentFps = 60; // currently achieved fps long waitTime = 1000/fps; // time to wait between updates unsigned int frames=0; long t1, t2; long t1fps, t2fps; int fftsLeft = 0; // FFT results left in queue t1 = t1fps = GetTickCount(); bool averageFFT = m_spectrum->chkAverage->GetValue(); bool calculated = false; if(averageFFT != true) { while( work ) { if(m_spectrum->chkUpdateGraphs->GetValue() == true) { //calculate FFT calculated = LMLL_Testing_CalculateFFT(); //if FFT has been calculated if(calculated) { //not averaging, take only one result LMLL_Testing_GetFFTData(m_spectrum->m_IchannelData, m_spectrum->m_QchannelData, m_spectrum->m_IQdataSize, m_spectrum->m_FFTamplitudes, m_spectrum->m_FFTdataSize, fftsLeft); //convert FFT results to dB for(int i=0; i<m_spectrum->m_FFTdataSize; i++) { if( m_spectrum->m_FFTamplitudes[i] <= 0) { m_spectrum->m_FFTamplitudes[i] = -370; } else m_spectrum->m_FFTamplitudes[i] = 10 * log10( m_spectrum->m_FFTamplitudes[i] ); } } } t2 = GetTickCount(); if(t2 - t1 < waitTime) //framerate limiter { milSleep(waitTime-(t2-t1)); } t1 = t2; m_spectrum->UpdateGraphs(); //update IQ line, IQ scatter and FFT graphs ++frames; t2fps = GetTickCount(); //show update rate, frames per second //wait until next update if( t2fps - t1fps > 1000) { currentFps = 1000.0*frames/(t2fps-t1fps); m_spectrum->lblFPS->SetLabel( wxString::Format("%i", currentFps)); frames = 0; t1fps = GetTickCount(); } } } else { while( work ) { if(m_spectrum->chkUpdateGraphs->GetValue() == true) { calculated = LMLL_Testing_CalculateFFT(); if(calculated) { //takes one FFT results and add it to averaging buffer LMLL_Testing_GetFFTData(m_spectrum->m_IchannelData, m_spectrum->m_QchannelData, m_spectrum->m_IQdataSize, m_FFTamplitudesBuffer[bufferPos], m_spectrum->m_FFTdataSize, fftsLeft); bufferPos = (bufferPos + 1) & m_buffersCountMask; memset(m_FFTamplitudesBuffer[m_buffersCount], 0, sizeof(float)*m_spectrum->m_FFTsamplesCount); //calculate average for(int i=0; i<m_buffersCount; ++i) { for(int j=0; j<m_spectrum->m_FFTsamplesCount; ++j) m_FFTamplitudesBuffer[m_buffersCount][j] += m_FFTamplitudesBuffer[bufferPos][j]; bufferPos = (bufferPos + 1) & m_buffersCountMask; } for(int j=0; j<m_spectrum->m_FFTsamplesCount; ++j) m_FFTamplitudesBuffer[m_buffersCount][j] = m_FFTamplitudesBuffer[m_buffersCount][j]/m_buffersCount; //convert to dB for(int i=0; i<m_spectrum->m_FFTdataSize; i++) { if( m_FFTamplitudesBuffer[m_buffersCount][i] <= 0) { m_spectrum->m_FFTamplitudes[i] = -370; } else m_spectrum->m_FFTamplitudes[i] = 10 * log10( m_FFTamplitudesBuffer[m_buffersCount][i] ); } } } //update graphs t2 = GetTickCount(); if(t2 - t1 < waitTime) //framerate limiter { milSleep(waitTime-(t2-t1)); } t1 = t2; m_spectrum->UpdateGraphs(); ++frames; t2fps = GetTickCount(); if( t2fps - t1fps > 1000) { currentFps = 1000.0*frames/(t2fps-t1fps); m_spectrum->lblFPS->SetLabel( wxString::Format("%i", currentFps)); frames = 0; t1fps = GetTickCount(); } } } LMLL_Testing_StopSdramRead(); terminated = true; } /** @brief Signals to stop thread */ bool GraphUpdateThread::Stop() { if(!terminated) { void *status; work = false; milSleep(100); return terminated; //!pthread_join(threadID, &status); } return terminated; } void* GraphUpdateThread::ThreadEntry(void *ptrThread) { GraphUpdateThread *thread = reinterpret_cast<GraphUpdateThread*>(ptrThread); if( thread ) thread->Execute(); return NULL; } /** Starts thread for FFT calculation and graphs update */ bool GraphUpdateThread::Start() { if(!work && terminated) { LMLL_Testing_StartSdramRead(); milSleep(100); //wait for some samples to accumulate than start calculations thread if( pthread_create(&threadID, NULL, ThreadEntry, this) == 0) { work = true; cout << "STARTED SDRAM READ" << endl; return true; } else { LMLL_Testing_StopSdramRead(); work = false; cout << "ERROR STARTING SDRAM READ" << endl; } } return false; } //---------------------------------------------------------------------------
// 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 "chrome/browser/ui/views/autofill/password_generation_popup_view_views.h" #include "base/macros.h" #include "base/strings/string16.h" #include "chrome/browser/ui/autofill/password_generation_popup_controller.h" #include "chrome/browser/ui/autofill/popup_constants.h" #include "ui/accessibility/ax_node_data.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/canvas.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/gfx/vector_icons_public.h" #include "ui/views/background.h" #include "ui/views/border.h" #include "ui/views/controls/image_view.h" #include "ui/views/controls/label.h" #include "ui/views/controls/styled_label.h" #include "ui/views/layout/box_layout.h" #include "ui/views/widget/widget.h" namespace autofill { namespace { // The amount of whitespace that is present when there is no padding. Used // to get the proper spacing in the help section. const int kHelpVerticalOffset = 5; // Wrapper around just the text portions of the generation UI (password and // prompting text). class PasswordTextBox : public views::View { public: PasswordTextBox() {} ~PasswordTextBox() override {} // |suggestion_text| prompts the user to select the password, // |generated_password| is the generated password, and |font_list| is the font // used for all text in this class. void Init(const base::string16& suggestion_text, const base::string16& generated_password, const gfx::FontList& font_list) { views::BoxLayout* box_layout = new views::BoxLayout( views::BoxLayout::kVertical, 0, 12, 5); box_layout->set_main_axis_alignment( views::BoxLayout::MAIN_AXIS_ALIGNMENT_START); SetLayoutManager(box_layout); views::Label* suggestion_label = new views::Label( suggestion_text, font_list.DeriveWithWeight(gfx::Font::Weight::BOLD)); suggestion_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); suggestion_label->SetEnabledColor( PasswordGenerationPopupView::kPasswordTextColor); AddChildView(suggestion_label); views::Label* password_label = new views::Label(generated_password, font_list); password_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); password_label->SetEnabledColor( PasswordGenerationPopupView::kPasswordTextColor); AddChildView(password_label); } // views::View: bool CanProcessEventsWithinSubtree() const override { // Send events to the parent view for handling. return false; } private: DISALLOW_COPY_AND_ASSIGN(PasswordTextBox); }; } // namespace // Class that shows the generated password and associated UI (currently a key // image and some explanatory text). class PasswordGenerationPopupViewViews::PasswordBox : public views::View { public: PasswordBox() {} ~PasswordBox() override {} // |password| is the generated password, |suggestion| is the text prompting // the user to select the password, and |font_list| is the font used for all // the text. void Init(const base::string16& password, const base::string16& suggestion, const gfx::FontList& font_list) { views::BoxLayout* box_layout = new views::BoxLayout( views::BoxLayout::kHorizontal, PasswordGenerationPopupController::kHorizontalPadding, 0, PasswordGenerationPopupController::kHorizontalPadding); box_layout->set_main_axis_alignment( views::BoxLayout::MAIN_AXIS_ALIGNMENT_START); SetLayoutManager(box_layout); views::ImageView* key_image = new views::ImageView(); key_image->SetImage(gfx::CreateVectorIcon(gfx::VectorIconId::AUTOLOGIN, 32, gfx::kChromeIconGrey)); AddChildView(key_image); PasswordTextBox* password_text_box = new PasswordTextBox(); password_text_box->Init(suggestion, password, font_list); AddChildView(password_text_box); } // views::View: bool CanProcessEventsWithinSubtree() const override { // Send events to the parent view for handling. return false; } private: DISALLOW_COPY_AND_ASSIGN(PasswordBox); }; PasswordGenerationPopupViewViews::PasswordGenerationPopupViewViews( PasswordGenerationPopupController* controller, views::Widget* parent_widget) : AutofillPopupBaseView(controller, parent_widget), password_view_(NULL), font_list_(ResourceBundle::GetSharedInstance().GetFontList( ResourceBundle::SmallFont)), controller_(controller) { if (controller_->display_password()) CreatePasswordView(); help_label_ = new views::StyledLabel(controller_->HelpText(), this); help_label_->SetBaseFontList(font_list_); help_label_->SetLineHeight(20); views::StyledLabel::RangeStyleInfo default_style; default_style.color = kExplanatoryTextColor; help_label_->SetDefaultStyle(default_style); views::StyledLabel::RangeStyleInfo link_style = views::StyledLabel::RangeStyleInfo::CreateForLink(); link_style.disable_line_wrapping = false; help_label_->AddStyleRange(controller_->HelpTextLinkRange(), link_style); help_label_->set_background( views::Background::CreateSolidBackground( kExplanatoryTextBackgroundColor)); help_label_->SetBorder(views::CreateEmptyBorder( PasswordGenerationPopupController::kHelpVerticalPadding - kHelpVerticalOffset, PasswordGenerationPopupController::kHorizontalPadding, PasswordGenerationPopupController::kHelpVerticalPadding - kHelpVerticalOffset, PasswordGenerationPopupController::kHorizontalPadding)); AddChildView(help_label_); set_background(views::Background::CreateSolidBackground(kPopupBackground)); } PasswordGenerationPopupViewViews::~PasswordGenerationPopupViewViews() {} void PasswordGenerationPopupViewViews::CreatePasswordView() { if (password_view_) return; password_view_ = new PasswordBox(); password_view_->Init(controller_->password(), controller_->SuggestedText(), font_list_); password_view_->SetPosition(gfx::Point(kPopupBorderThickness, kPopupBorderThickness)); password_view_->SizeToPreferredSize(); AddChildView(password_view_); } gfx::Size PasswordGenerationPopupViewViews::GetPreferredSizeOfPasswordView() { int height = kPopupBorderThickness; if (controller_->display_password()) { // Add divider height as well. height += PasswordGenerationPopupController::kPopupPasswordSectionHeight + 1; } int width = controller_->GetMinimumWidth(); int popup_width = width - 2 * kPopupBorderThickness; height += help_label_->GetHeightForWidth(popup_width); return gfx::Size(width, height + kPopupBorderThickness); } void PasswordGenerationPopupViewViews::Show() { DoShow(); } void PasswordGenerationPopupViewViews::Hide() { // The controller is no longer valid after it hides us. controller_ = NULL; DoHide(); } void PasswordGenerationPopupViewViews::UpdateBoundsAndRedrawPopup() { DoUpdateBoundsAndRedrawPopup(); } void PasswordGenerationPopupViewViews::PasswordSelectionUpdated() { if (!password_view_) return; if (controller_->password_selected()) NotifyAccessibilityEvent(ui::AX_EVENT_SELECTION, true); password_view_->set_background( views::Background::CreateSolidBackground( controller_->password_selected() ? kHoveredBackgroundColor : kPopupBackground)); } void PasswordGenerationPopupViewViews::Layout() { // Need to leave room for the border. int y = kPopupBorderThickness; int popup_width = bounds().width() - 2 * kPopupBorderThickness; if (controller_->display_password()) { // Currently the UI can change from not offering a password to offering // a password (e.g. the user is editing a generated password and deletes // it), but it can't change the other way around. CreatePasswordView(); password_view_->SetBounds( kPopupBorderThickness, y, popup_width, PasswordGenerationPopupController::kPopupPasswordSectionHeight); divider_bounds_ = gfx::Rect(kPopupBorderThickness, password_view_->bounds().bottom(), popup_width, 1); y = divider_bounds_.bottom(); } help_label_->SetBounds(kPopupBorderThickness, y, popup_width, help_label_->GetHeightForWidth(popup_width)); } void PasswordGenerationPopupViewViews::OnPaint(gfx::Canvas* canvas) { if (!controller_) return; // Draw border and background. views::View::OnPaint(canvas); // Divider line needs to be drawn after OnPaint() otherwise the background // will overwrite the divider. if (password_view_) canvas->FillRect(divider_bounds_, kDividerColor); } void PasswordGenerationPopupViewViews::StyledLabelLinkClicked( views::StyledLabel* label, const gfx::Range& range, int event_flags) { controller_->OnSavedPasswordsLinkClicked(); } bool PasswordGenerationPopupViewViews::IsPointInPasswordBounds( const gfx::Point& point) { if (password_view_) return password_view_->bounds().Contains(point); return false; } PasswordGenerationPopupView* PasswordGenerationPopupView::Create( PasswordGenerationPopupController* controller) { views::Widget* observing_widget = views::Widget::GetTopLevelWidgetForNativeView( controller->container_view()); // If the top level widget can't be found, cancel the popup since we can't // fully set it up. if (!observing_widget) return NULL; return new PasswordGenerationPopupViewViews(controller, observing_widget); } void PasswordGenerationPopupViewViews::GetAccessibleNodeData( ui::AXNodeData* node_data) { node_data->SetName(controller_->SuggestedText()); node_data->role = ui::AX_ROLE_MENU_ITEM; } } // namespace autofill
/*============================================================================= Copyright (c) 2001-2011 Joel de Guzman Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) This is an auto-generated file. Do not edit! ==============================================================================*/ namespace boost { namespace fusion { struct deque_tag; template<typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19> struct deque : detail::deque_keyed_values<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19>::type, sequence_base<deque<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19> > { typedef deque_tag fusion_tag; typedef bidirectional_traversal_tag category; typedef typename detail::deque_keyed_values<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19>::type base; typedef typename detail::deque_initial_size<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19>::type size; typedef mpl::int_<size::value> next_up; typedef mpl::int_< mpl::if_<mpl::equal_to<size, mpl::int_<0> >, mpl::int_<0>, mpl::int_<-1> >::type::value> next_down; typedef mpl::false_ is_view; deque(typename add_reference<typename add_const<T0 >::type>::type t0 , typename add_reference<typename add_const<T1 >::type>::type t1) : base(detail::deque_keyed_values<T0 , T1>::call(t0 , t1)) {} deque(typename add_reference<typename add_const<T0 >::type>::type t0 , typename add_reference<typename add_const<T1 >::type>::type t1 , typename add_reference<typename add_const<T2 >::type>::type t2) : base(detail::deque_keyed_values<T0 , T1 , T2>::call(t0 , t1 , t2)) {} deque(typename add_reference<typename add_const<T0 >::type>::type t0 , typename add_reference<typename add_const<T1 >::type>::type t1 , typename add_reference<typename add_const<T2 >::type>::type t2 , typename add_reference<typename add_const<T3 >::type>::type t3) : base(detail::deque_keyed_values<T0 , T1 , T2 , T3>::call(t0 , t1 , t2 , t3)) {} deque(typename add_reference<typename add_const<T0 >::type>::type t0 , typename add_reference<typename add_const<T1 >::type>::type t1 , typename add_reference<typename add_const<T2 >::type>::type t2 , typename add_reference<typename add_const<T3 >::type>::type t3 , typename add_reference<typename add_const<T4 >::type>::type t4) : base(detail::deque_keyed_values<T0 , T1 , T2 , T3 , T4>::call(t0 , t1 , t2 , t3 , t4)) {} deque(typename add_reference<typename add_const<T0 >::type>::type t0 , typename add_reference<typename add_const<T1 >::type>::type t1 , typename add_reference<typename add_const<T2 >::type>::type t2 , typename add_reference<typename add_const<T3 >::type>::type t3 , typename add_reference<typename add_const<T4 >::type>::type t4 , typename add_reference<typename add_const<T5 >::type>::type t5) : base(detail::deque_keyed_values<T0 , T1 , T2 , T3 , T4 , T5>::call(t0 , t1 , t2 , t3 , t4 , t5)) {} deque(typename add_reference<typename add_const<T0 >::type>::type t0 , typename add_reference<typename add_const<T1 >::type>::type t1 , typename add_reference<typename add_const<T2 >::type>::type t2 , typename add_reference<typename add_const<T3 >::type>::type t3 , typename add_reference<typename add_const<T4 >::type>::type t4 , typename add_reference<typename add_const<T5 >::type>::type t5 , typename add_reference<typename add_const<T6 >::type>::type t6) : base(detail::deque_keyed_values<T0 , T1 , T2 , T3 , T4 , T5 , T6>::call(t0 , t1 , t2 , t3 , t4 , t5 , t6)) {} deque(typename add_reference<typename add_const<T0 >::type>::type t0 , typename add_reference<typename add_const<T1 >::type>::type t1 , typename add_reference<typename add_const<T2 >::type>::type t2 , typename add_reference<typename add_const<T3 >::type>::type t3 , typename add_reference<typename add_const<T4 >::type>::type t4 , typename add_reference<typename add_const<T5 >::type>::type t5 , typename add_reference<typename add_const<T6 >::type>::type t6 , typename add_reference<typename add_const<T7 >::type>::type t7) : base(detail::deque_keyed_values<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7>::call(t0 , t1 , t2 , t3 , t4 , t5 , t6 , t7)) {} deque(typename add_reference<typename add_const<T0 >::type>::type t0 , typename add_reference<typename add_const<T1 >::type>::type t1 , typename add_reference<typename add_const<T2 >::type>::type t2 , typename add_reference<typename add_const<T3 >::type>::type t3 , typename add_reference<typename add_const<T4 >::type>::type t4 , typename add_reference<typename add_const<T5 >::type>::type t5 , typename add_reference<typename add_const<T6 >::type>::type t6 , typename add_reference<typename add_const<T7 >::type>::type t7 , typename add_reference<typename add_const<T8 >::type>::type t8) : base(detail::deque_keyed_values<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8>::call(t0 , t1 , t2 , t3 , t4 , t5 , t6 , t7 , t8)) {} deque(typename add_reference<typename add_const<T0 >::type>::type t0 , typename add_reference<typename add_const<T1 >::type>::type t1 , typename add_reference<typename add_const<T2 >::type>::type t2 , typename add_reference<typename add_const<T3 >::type>::type t3 , typename add_reference<typename add_const<T4 >::type>::type t4 , typename add_reference<typename add_const<T5 >::type>::type t5 , typename add_reference<typename add_const<T6 >::type>::type t6 , typename add_reference<typename add_const<T7 >::type>::type t7 , typename add_reference<typename add_const<T8 >::type>::type t8 , typename add_reference<typename add_const<T9 >::type>::type t9) : base(detail::deque_keyed_values<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9>::call(t0 , t1 , t2 , t3 , t4 , t5 , t6 , t7 , t8 , t9)) {} deque(typename add_reference<typename add_const<T0 >::type>::type t0 , typename add_reference<typename add_const<T1 >::type>::type t1 , typename add_reference<typename add_const<T2 >::type>::type t2 , typename add_reference<typename add_const<T3 >::type>::type t3 , typename add_reference<typename add_const<T4 >::type>::type t4 , typename add_reference<typename add_const<T5 >::type>::type t5 , typename add_reference<typename add_const<T6 >::type>::type t6 , typename add_reference<typename add_const<T7 >::type>::type t7 , typename add_reference<typename add_const<T8 >::type>::type t8 , typename add_reference<typename add_const<T9 >::type>::type t9 , typename add_reference<typename add_const<T10 >::type>::type t10) : base(detail::deque_keyed_values<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10>::call(t0 , t1 , t2 , t3 , t4 , t5 , t6 , t7 , t8 , t9 , t10)) {} deque(typename add_reference<typename add_const<T0 >::type>::type t0 , typename add_reference<typename add_const<T1 >::type>::type t1 , typename add_reference<typename add_const<T2 >::type>::type t2 , typename add_reference<typename add_const<T3 >::type>::type t3 , typename add_reference<typename add_const<T4 >::type>::type t4 , typename add_reference<typename add_const<T5 >::type>::type t5 , typename add_reference<typename add_const<T6 >::type>::type t6 , typename add_reference<typename add_const<T7 >::type>::type t7 , typename add_reference<typename add_const<T8 >::type>::type t8 , typename add_reference<typename add_const<T9 >::type>::type t9 , typename add_reference<typename add_const<T10 >::type>::type t10 , typename add_reference<typename add_const<T11 >::type>::type t11) : base(detail::deque_keyed_values<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11>::call(t0 , t1 , t2 , t3 , t4 , t5 , t6 , t7 , t8 , t9 , t10 , t11)) {} deque(typename add_reference<typename add_const<T0 >::type>::type t0 , typename add_reference<typename add_const<T1 >::type>::type t1 , typename add_reference<typename add_const<T2 >::type>::type t2 , typename add_reference<typename add_const<T3 >::type>::type t3 , typename add_reference<typename add_const<T4 >::type>::type t4 , typename add_reference<typename add_const<T5 >::type>::type t5 , typename add_reference<typename add_const<T6 >::type>::type t6 , typename add_reference<typename add_const<T7 >::type>::type t7 , typename add_reference<typename add_const<T8 >::type>::type t8 , typename add_reference<typename add_const<T9 >::type>::type t9 , typename add_reference<typename add_const<T10 >::type>::type t10 , typename add_reference<typename add_const<T11 >::type>::type t11 , typename add_reference<typename add_const<T12 >::type>::type t12) : base(detail::deque_keyed_values<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12>::call(t0 , t1 , t2 , t3 , t4 , t5 , t6 , t7 , t8 , t9 , t10 , t11 , t12)) {} deque(typename add_reference<typename add_const<T0 >::type>::type t0 , typename add_reference<typename add_const<T1 >::type>::type t1 , typename add_reference<typename add_const<T2 >::type>::type t2 , typename add_reference<typename add_const<T3 >::type>::type t3 , typename add_reference<typename add_const<T4 >::type>::type t4 , typename add_reference<typename add_const<T5 >::type>::type t5 , typename add_reference<typename add_const<T6 >::type>::type t6 , typename add_reference<typename add_const<T7 >::type>::type t7 , typename add_reference<typename add_const<T8 >::type>::type t8 , typename add_reference<typename add_const<T9 >::type>::type t9 , typename add_reference<typename add_const<T10 >::type>::type t10 , typename add_reference<typename add_const<T11 >::type>::type t11 , typename add_reference<typename add_const<T12 >::type>::type t12 , typename add_reference<typename add_const<T13 >::type>::type t13) : base(detail::deque_keyed_values<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13>::call(t0 , t1 , t2 , t3 , t4 , t5 , t6 , t7 , t8 , t9 , t10 , t11 , t12 , t13)) {} deque(typename add_reference<typename add_const<T0 >::type>::type t0 , typename add_reference<typename add_const<T1 >::type>::type t1 , typename add_reference<typename add_const<T2 >::type>::type t2 , typename add_reference<typename add_const<T3 >::type>::type t3 , typename add_reference<typename add_const<T4 >::type>::type t4 , typename add_reference<typename add_const<T5 >::type>::type t5 , typename add_reference<typename add_const<T6 >::type>::type t6 , typename add_reference<typename add_const<T7 >::type>::type t7 , typename add_reference<typename add_const<T8 >::type>::type t8 , typename add_reference<typename add_const<T9 >::type>::type t9 , typename add_reference<typename add_const<T10 >::type>::type t10 , typename add_reference<typename add_const<T11 >::type>::type t11 , typename add_reference<typename add_const<T12 >::type>::type t12 , typename add_reference<typename add_const<T13 >::type>::type t13 , typename add_reference<typename add_const<T14 >::type>::type t14) : base(detail::deque_keyed_values<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14>::call(t0 , t1 , t2 , t3 , t4 , t5 , t6 , t7 , t8 , t9 , t10 , t11 , t12 , t13 , t14)) {} deque(typename add_reference<typename add_const<T0 >::type>::type t0 , typename add_reference<typename add_const<T1 >::type>::type t1 , typename add_reference<typename add_const<T2 >::type>::type t2 , typename add_reference<typename add_const<T3 >::type>::type t3 , typename add_reference<typename add_const<T4 >::type>::type t4 , typename add_reference<typename add_const<T5 >::type>::type t5 , typename add_reference<typename add_const<T6 >::type>::type t6 , typename add_reference<typename add_const<T7 >::type>::type t7 , typename add_reference<typename add_const<T8 >::type>::type t8 , typename add_reference<typename add_const<T9 >::type>::type t9 , typename add_reference<typename add_const<T10 >::type>::type t10 , typename add_reference<typename add_const<T11 >::type>::type t11 , typename add_reference<typename add_const<T12 >::type>::type t12 , typename add_reference<typename add_const<T13 >::type>::type t13 , typename add_reference<typename add_const<T14 >::type>::type t14 , typename add_reference<typename add_const<T15 >::type>::type t15) : base(detail::deque_keyed_values<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15>::call(t0 , t1 , t2 , t3 , t4 , t5 , t6 , t7 , t8 , t9 , t10 , t11 , t12 , t13 , t14 , t15)) {} deque(typename add_reference<typename add_const<T0 >::type>::type t0 , typename add_reference<typename add_const<T1 >::type>::type t1 , typename add_reference<typename add_const<T2 >::type>::type t2 , typename add_reference<typename add_const<T3 >::type>::type t3 , typename add_reference<typename add_const<T4 >::type>::type t4 , typename add_reference<typename add_const<T5 >::type>::type t5 , typename add_reference<typename add_const<T6 >::type>::type t6 , typename add_reference<typename add_const<T7 >::type>::type t7 , typename add_reference<typename add_const<T8 >::type>::type t8 , typename add_reference<typename add_const<T9 >::type>::type t9 , typename add_reference<typename add_const<T10 >::type>::type t10 , typename add_reference<typename add_const<T11 >::type>::type t11 , typename add_reference<typename add_const<T12 >::type>::type t12 , typename add_reference<typename add_const<T13 >::type>::type t13 , typename add_reference<typename add_const<T14 >::type>::type t14 , typename add_reference<typename add_const<T15 >::type>::type t15 , typename add_reference<typename add_const<T16 >::type>::type t16) : base(detail::deque_keyed_values<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16>::call(t0 , t1 , t2 , t3 , t4 , t5 , t6 , t7 , t8 , t9 , t10 , t11 , t12 , t13 , t14 , t15 , t16)) {} deque(typename add_reference<typename add_const<T0 >::type>::type t0 , typename add_reference<typename add_const<T1 >::type>::type t1 , typename add_reference<typename add_const<T2 >::type>::type t2 , typename add_reference<typename add_const<T3 >::type>::type t3 , typename add_reference<typename add_const<T4 >::type>::type t4 , typename add_reference<typename add_const<T5 >::type>::type t5 , typename add_reference<typename add_const<T6 >::type>::type t6 , typename add_reference<typename add_const<T7 >::type>::type t7 , typename add_reference<typename add_const<T8 >::type>::type t8 , typename add_reference<typename add_const<T9 >::type>::type t9 , typename add_reference<typename add_const<T10 >::type>::type t10 , typename add_reference<typename add_const<T11 >::type>::type t11 , typename add_reference<typename add_const<T12 >::type>::type t12 , typename add_reference<typename add_const<T13 >::type>::type t13 , typename add_reference<typename add_const<T14 >::type>::type t14 , typename add_reference<typename add_const<T15 >::type>::type t15 , typename add_reference<typename add_const<T16 >::type>::type t16 , typename add_reference<typename add_const<T17 >::type>::type t17) : base(detail::deque_keyed_values<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17>::call(t0 , t1 , t2 , t3 , t4 , t5 , t6 , t7 , t8 , t9 , t10 , t11 , t12 , t13 , t14 , t15 , t16 , t17)) {} deque(typename add_reference<typename add_const<T0 >::type>::type t0 , typename add_reference<typename add_const<T1 >::type>::type t1 , typename add_reference<typename add_const<T2 >::type>::type t2 , typename add_reference<typename add_const<T3 >::type>::type t3 , typename add_reference<typename add_const<T4 >::type>::type t4 , typename add_reference<typename add_const<T5 >::type>::type t5 , typename add_reference<typename add_const<T6 >::type>::type t6 , typename add_reference<typename add_const<T7 >::type>::type t7 , typename add_reference<typename add_const<T8 >::type>::type t8 , typename add_reference<typename add_const<T9 >::type>::type t9 , typename add_reference<typename add_const<T10 >::type>::type t10 , typename add_reference<typename add_const<T11 >::type>::type t11 , typename add_reference<typename add_const<T12 >::type>::type t12 , typename add_reference<typename add_const<T13 >::type>::type t13 , typename add_reference<typename add_const<T14 >::type>::type t14 , typename add_reference<typename add_const<T15 >::type>::type t15 , typename add_reference<typename add_const<T16 >::type>::type t16 , typename add_reference<typename add_const<T17 >::type>::type t17 , typename add_reference<typename add_const<T18 >::type>::type t18) : base(detail::deque_keyed_values<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18>::call(t0 , t1 , t2 , t3 , t4 , t5 , t6 , t7 , t8 , t9 , t10 , t11 , t12 , t13 , t14 , t15 , t16 , t17 , t18)) {} deque(typename add_reference<typename add_const<T0 >::type>::type t0 , typename add_reference<typename add_const<T1 >::type>::type t1 , typename add_reference<typename add_const<T2 >::type>::type t2 , typename add_reference<typename add_const<T3 >::type>::type t3 , typename add_reference<typename add_const<T4 >::type>::type t4 , typename add_reference<typename add_const<T5 >::type>::type t5 , typename add_reference<typename add_const<T6 >::type>::type t6 , typename add_reference<typename add_const<T7 >::type>::type t7 , typename add_reference<typename add_const<T8 >::type>::type t8 , typename add_reference<typename add_const<T9 >::type>::type t9 , typename add_reference<typename add_const<T10 >::type>::type t10 , typename add_reference<typename add_const<T11 >::type>::type t11 , typename add_reference<typename add_const<T12 >::type>::type t12 , typename add_reference<typename add_const<T13 >::type>::type t13 , typename add_reference<typename add_const<T14 >::type>::type t14 , typename add_reference<typename add_const<T15 >::type>::type t15 , typename add_reference<typename add_const<T16 >::type>::type t16 , typename add_reference<typename add_const<T17 >::type>::type t17 , typename add_reference<typename add_const<T18 >::type>::type t18 , typename add_reference<typename add_const<T19 >::type>::type t19) : base(detail::deque_keyed_values<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19>::call(t0 , t1 , t2 , t3 , t4 , t5 , t6 , t7 , t8 , t9 , t10 , t11 , t12 , t13 , t14 , t15 , t16 , t17 , t18 , t19)) {} deque() {} explicit deque(typename add_reference<typename add_const<T0>::type>::type t0) : base(t0, detail::nil_keyed_element()) {} template<typename U0 , typename U1 , typename U2 , typename U3 , typename U4 , typename U5 , typename U6 , typename U7 , typename U8 , typename U9 , typename U10 , typename U11 , typename U12 , typename U13 , typename U14 , typename U15 , typename U16 , typename U17 , typename U18 , typename U19> deque(deque<U0 , U1 , U2 , U3 , U4 , U5 , U6 , U7 , U8 , U9 , U10 , U11 , U12 , U13 , U14 , U15 , U16 , U17 , U18 , U19> const& seq) : base(seq) {} template<typename Sequence> deque(Sequence const& seq, typename disable_if<is_convertible<Sequence, T0> >::type* = 0) : base(base::from_iterator(fusion::begin(seq))) {} template <typename U0 , typename U1 , typename U2 , typename U3 , typename U4 , typename U5 , typename U6 , typename U7 , typename U8 , typename U9 , typename U10 , typename U11 , typename U12 , typename U13 , typename U14 , typename U15 , typename U16 , typename U17 , typename U18 , typename U19> deque& operator=(deque<U0 , U1 , U2 , U3 , U4 , U5 , U6 , U7 , U8 , U9 , U10 , U11 , U12 , U13 , U14 , U15 , U16 , U17 , U18 , U19> const& rhs) { base::operator=(rhs); return *this; } template <typename T> deque& operator=(T const& rhs) { base::operator=(rhs); return *this; } }; }}
// -*- C++ -*- //===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // REQUIRES: host-has-gdb // UNSUPPORTED: libcpp-has-no-localization // UNSUPPORTED: c++03 // RUN: %{cxx} %{flags} %s -o %t.exe %{compile_flags} -g %{link_flags} // Ensure locale-independence for unicode tests. // RUN: %{gdb} -nx -batch -iex "set autoload off" -ex "source %S/../../../utils/gdb/libcxx/printers.py" -ex "python register_libcxx_printer_loader()" -ex "source %S/gdb_pretty_printer_test.py" %t.exe #include <bitset> #include <deque> #include <list> #include <map> #include <memory> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include "test_macros.h" // To write a pretty-printer test: // // 1. Declare a variable of the type you want to test // // 2. Set its value to something which will test the pretty printer in an // interesting way. // // 3. Call ComparePrettyPrintToChars with that variable, and a "const char*" // value to compare to the printer's output. // // Or // // Call ComparePrettyPrintToChars with that variable, and a "const char*" // *python* regular expression to match against the printer's output. // The set of special characters in a Python regular expression overlaps // with a lot of things the pretty printers print--brackets, for // example--so take care to escape appropriately. // // Alternatively, construct a string that gdb can parse as an expression, // so that printing the value of the expression will test the pretty printer // in an interesting way. Then, call CompareExpressionPrettyPrintToChars or // CompareExpressionPrettyPrintToRegex to compare the printer's output. // Avoids setting a breakpoint in every-single instantiation of // ComparePrettyPrintTo*. Also, make sure neither it, nor the // variables we need present in the Compare functions are optimized // away. #ifdef TEST_COMPILER_GCC #define OPT_NONE __attribute__((noinline)) #else #define OPT_NONE __attribute__((optnone)) #endif void StopForDebugger(void *, void *) OPT_NONE; void StopForDebugger(void *, void *) {} // Prevents the compiler optimizing away the parameter in the caller function. template <typename Type> void MarkAsLive(Type &&) OPT_NONE; template <typename Type> void MarkAsLive(Type &&) {} // In all of the Compare(Expression)PrettyPrintTo(Regex/Chars) functions below, // the python script sets a breakpoint just before the call to StopForDebugger, // compares the result to the expectation. // // The expectation is a literal string to be matched exactly in // *PrettyPrintToChars functions, and is a python regular expression in // *PrettyPrintToRegex functions. // // In ComparePrettyPrint* functions, the value is a variable of any type. In // CompareExpressionPrettyPrint functions, the value is a string expression that // gdb will parse and print the result. // // The python script will print either "PASS", or a detailed failure explanation // along with the line that has invoke the function. The testing will continue // in either case. template <typename TypeToPrint> void ComparePrettyPrintToChars( TypeToPrint value, const char *expectation) { StopForDebugger(&value, &expectation); } template <typename TypeToPrint> void ComparePrettyPrintToRegex( TypeToPrint value, const char *expectation) { StopForDebugger(&value, &expectation); } void CompareExpressionPrettyPrintToChars( std::string value, const char *expectation) { StopForDebugger(&value, &expectation); } void CompareExpressionPrettyPrintToRegex( std::string value, const char *expectation) { StopForDebugger(&value, &expectation); } namespace example { struct example_struct { int a = 0; int arr[1000]; }; } // If enabled, the self test will "fail"--because we want to be sure it properly // diagnoses tests that *should* fail. Evaluate the output by hand. void framework_self_test() { #ifdef FRAMEWORK_SELF_TEST // Use the most simple data structure we can. const char a = 'a'; // Tests that should pass ComparePrettyPrintToChars(a, "97 'a'"); ComparePrettyPrintToRegex(a, ".*"); // Tests that should fail. ComparePrettyPrintToChars(a, "b"); ComparePrettyPrintToRegex(a, "b"); #endif } // A simple pass-through allocator to check that we handle CompressedPair // correctly. template <typename T> class UncompressibleAllocator : public std::allocator<T> { public: char X; }; void string_test() { std::string short_string("kdjflskdjf"); // The display_hint "string" adds quotes the printed result. ComparePrettyPrintToChars(short_string, "\"kdjflskdjf\""); std::basic_string<char, std::char_traits<char>, UncompressibleAllocator<char>> long_string("mehmet bizim dostumuz agzi kirik testimiz"); ComparePrettyPrintToChars(long_string, "\"mehmet bizim dostumuz agzi kirik testimiz\""); } namespace a_namespace { // To test name-lookup in the presence of using inside a namespace. Inside this // namespace, unqualified string_view variables will appear in the debug info as // "a_namespace::string_view, rather than "std::string_view". // // There is nothing special here about string_view; it's just the data structure // where lookup with using inside a namespace wasn't always working. using string_view = std::string_view; void string_view_test() { std::string_view i_am_empty; ComparePrettyPrintToChars(i_am_empty, "std::string_view of length 0: \"\""); std::string source_string("to be or not to be"); std::string_view to_be(source_string); ComparePrettyPrintToChars( to_be, "std::string_view of length 18: \"to be or not to be\""); const char char_arr[] = "what a wonderful world"; std::string_view wonderful(&char_arr[7], 9); ComparePrettyPrintToChars( wonderful, "std::string_view of length 9: \"wonderful\""); const char char_arr1[] = "namespace_stringview"; string_view namespace_stringview(&char_arr1[10], 10); ComparePrettyPrintToChars( namespace_stringview, "std::string_view of length 10: \"stringview\""); } } void u16string_test() { std::u16string test0 = u"Hello World"; ComparePrettyPrintToChars(test0, "u\"Hello World\""); std::u16string test1 = u"\U00010196\u20AC\u00A3\u0024"; ComparePrettyPrintToChars(test1, "u\"\U00010196\u20AC\u00A3\u0024\""); std::u16string test2 = u"\u0024\u0025\u0026\u0027"; ComparePrettyPrintToChars(test2, "u\"\u0024\u0025\u0026\u0027\""); std::u16string test3 = u"mehmet bizim dostumuz agzi kirik testimiz"; ComparePrettyPrintToChars(test3, ("u\"mehmet bizim dostumuz agzi kirik testimiz\"")); } void u32string_test() { std::u32string test0 = U"Hello World"; ComparePrettyPrintToChars(test0, "U\"Hello World\""); std::u32string test1 = U"\U0001d552\U0001d553\U0001d554\U0001d555\U0001d556\U0001d557"; ComparePrettyPrintToChars( test1, ("U\"\U0001d552\U0001d553\U0001d554\U0001d555\U0001d556\U0001d557\"")); std::u32string test2 = U"\U00004f60\U0000597d"; ComparePrettyPrintToChars(test2, ("U\"\U00004f60\U0000597d\"")); std::u32string test3 = U"mehmet bizim dostumuz agzi kirik testimiz"; ComparePrettyPrintToChars(test3, ("U\"mehmet bizim dostumuz agzi kirik testimiz\"")); } void tuple_test() { std::tuple<int, int, int> test0(2, 3, 4); ComparePrettyPrintToChars( test0, "std::tuple containing = {[1] = 2, [2] = 3, [3] = 4}"); std::tuple<> test1; ComparePrettyPrintToChars( test1, "empty std::tuple"); } void unique_ptr_test() { std::unique_ptr<std::string> matilda(new std::string("Matilda")); ComparePrettyPrintToRegex( std::move(matilda), R"(std::unique_ptr<std::string> containing = {__ptr_ = 0x[a-f0-9]+})"); std::unique_ptr<int> forty_two(new int(42)); ComparePrettyPrintToRegex(std::move(forty_two), R"(std::unique_ptr<int> containing = {__ptr_ = 0x[a-f0-9]+})"); std::unique_ptr<int> this_is_null; ComparePrettyPrintToChars(std::move(this_is_null), R"(std::unique_ptr is nullptr)"); } void bitset_test() { std::bitset<258> i_am_empty(0); ComparePrettyPrintToChars(i_am_empty, "std::bitset<258>"); std::bitset<0> very_empty; ComparePrettyPrintToChars(very_empty, "std::bitset<0>"); std::bitset<15> b_000001111111100(1020); ComparePrettyPrintToChars(b_000001111111100, "std::bitset<15> = {[2] = 1, [3] = 1, [4] = 1, [5] = 1, [6] = 1, " "[7] = 1, [8] = 1, [9] = 1}"); std::bitset<258> b_0_129_132(0); b_0_129_132[0] = true; b_0_129_132[129] = true; b_0_129_132[132] = true; ComparePrettyPrintToChars(b_0_129_132, "std::bitset<258> = {[0] = 1, [129] = 1, [132] = 1}"); } void list_test() { std::list<int> i_am_empty{}; ComparePrettyPrintToChars(i_am_empty, "std::list is empty"); std::list<int> one_two_three {1, 2, 3}; ComparePrettyPrintToChars(one_two_three, "std::list with 3 elements = {1, 2, 3}"); std::list<std::string> colors {"red", "blue", "green"}; ComparePrettyPrintToChars(colors, R"(std::list with 3 elements = {"red", "blue", "green"})"); } void deque_test() { std::deque<int> i_am_empty{}; ComparePrettyPrintToChars(i_am_empty, "std::deque is empty"); std::deque<int> one_two_three {1, 2, 3}; ComparePrettyPrintToChars(one_two_three, "std::deque with 3 elements = {1, 2, 3}"); std::deque<example::example_struct> bfg; for (int i = 0; i < 10; ++i) { example::example_struct current; current.a = i; bfg.push_back(current); } for (int i = 0; i < 3; ++i) { bfg.pop_front(); } for (int i = 0; i < 3; ++i) { bfg.pop_back(); } ComparePrettyPrintToRegex(bfg, "std::deque with 4 elements = {" "{a = 3, arr = {[^}]+}}, " "{a = 4, arr = {[^}]+}}, " "{a = 5, arr = {[^}]+}}, " "{a = 6, arr = {[^}]+}}}"); } void map_test() { std::map<int, int> i_am_empty{}; ComparePrettyPrintToChars(i_am_empty, "std::map is empty"); std::map<int, std::string> one_two_three; one_two_three.insert({1, "one"}); one_two_three.insert({2, "two"}); one_two_three.insert({3, "three"}); ComparePrettyPrintToChars(one_two_three, "std::map with 3 elements = " R"({[1] = "one", [2] = "two", [3] = "three"})"); std::map<int, example::example_struct> bfg; for (int i = 0; i < 4; ++i) { example::example_struct current; current.a = 17 * i; bfg.insert({i, current}); } ComparePrettyPrintToRegex(bfg, R"(std::map with 4 elements = {)" R"(\[0\] = {a = 0, arr = {[^}]+}}, )" R"(\[1\] = {a = 17, arr = {[^}]+}}, )" R"(\[2\] = {a = 34, arr = {[^}]+}}, )" R"(\[3\] = {a = 51, arr = {[^}]+}}})"); } void multimap_test() { std::multimap<int, int> i_am_empty{}; ComparePrettyPrintToChars(i_am_empty, "std::multimap is empty"); std::multimap<int, std::string> one_two_three; one_two_three.insert({1, "one"}); one_two_three.insert({3, "three"}); one_two_three.insert({1, "ein"}); one_two_three.insert({2, "two"}); one_two_three.insert({2, "zwei"}); one_two_three.insert({1, "bir"}); ComparePrettyPrintToChars(one_two_three, "std::multimap with 6 elements = " R"({[1] = "one", [1] = "ein", [1] = "bir", )" R"([2] = "two", [2] = "zwei", [3] = "three"})"); } void queue_test() { std::queue<int> i_am_empty; ComparePrettyPrintToChars(i_am_empty, "std::queue wrapping = {std::deque is empty}"); std::queue<int> one_two_three(std::deque<int>{1, 2, 3}); ComparePrettyPrintToChars(one_two_three, "std::queue wrapping = {" "std::deque with 3 elements = {1, 2, 3}}"); } void priority_queue_test() { std::priority_queue<int> i_am_empty; ComparePrettyPrintToChars(i_am_empty, "std::priority_queue wrapping = {std::vector of length 0, capacity 0}"); std::priority_queue<int> one_two_three; one_two_three.push(11111); one_two_three.push(22222); one_two_three.push(33333); ComparePrettyPrintToRegex(one_two_three, R"(std::priority_queue wrapping = )" R"({std::vector of length 3, capacity 3 = {33333)"); ComparePrettyPrintToRegex(one_two_three, ".*11111.*"); ComparePrettyPrintToRegex(one_two_three, ".*22222.*"); } void set_test() { std::set<int> i_am_empty; ComparePrettyPrintToChars(i_am_empty, "std::set is empty"); std::set<int> one_two_three {3, 1, 2}; ComparePrettyPrintToChars(one_two_three, "std::set with 3 elements = {1, 2, 3}"); std::set<std::pair<int, int>> prime_pairs { std::make_pair(3, 5), std::make_pair(5, 7), std::make_pair(3, 5)}; ComparePrettyPrintToChars(prime_pairs, "std::set with 2 elements = {" "{first = 3, second = 5}, {first = 5, second = 7}}"); using using_set = std::set<int>; using_set other{1, 2, 3}; ComparePrettyPrintToChars(other, "std::set with 3 elements = {1, 2, 3}"); } void stack_test() { std::stack<int> test0; ComparePrettyPrintToChars(test0, "std::stack wrapping = {std::deque is empty}"); test0.push(5); test0.push(6); ComparePrettyPrintToChars( test0, "std::stack wrapping = {std::deque with 2 elements = {5, 6}}"); std::stack<bool> test1; test1.push(true); test1.push(false); ComparePrettyPrintToChars( test1, "std::stack wrapping = {std::deque with 2 elements = {true, false}}"); std::stack<std::string> test2; test2.push("Hello"); test2.push("World"); ComparePrettyPrintToChars(test2, "std::stack wrapping = {std::deque with 2 elements " "= {\"Hello\", \"World\"}}"); } void multiset_test() { std::multiset<int> i_am_empty; ComparePrettyPrintToChars(i_am_empty, "std::multiset is empty"); std::multiset<std::string> one_two_three {"1:one", "2:two", "3:three", "1:one"}; ComparePrettyPrintToChars(one_two_three, "std::multiset with 4 elements = {" R"("1:one", "1:one", "2:two", "3:three"})"); } void vector_test() { std::vector<bool> test0 = {true, false}; ComparePrettyPrintToChars(test0, "std::vector<bool> of " "length 2, capacity 64 = {1, 0}"); for (int i = 0; i < 31; ++i) { test0.push_back(true); test0.push_back(false); } ComparePrettyPrintToRegex( test0, "std::vector<bool> of length 64, " "capacity 64 = {1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, " "0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, " "0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0}"); test0.push_back(true); ComparePrettyPrintToRegex( test0, "std::vector<bool> of length 65, " "capacity 128 = {1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, " "1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, " "1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1}"); std::vector<int> test1; ComparePrettyPrintToChars(test1, "std::vector of length 0, capacity 0"); std::vector<int> test2 = {5, 6, 7}; ComparePrettyPrintToChars(test2, "std::vector of length " "3, capacity 3 = {5, 6, 7}"); std::vector<int, UncompressibleAllocator<int>> test3({7, 8}); ComparePrettyPrintToChars(std::move(test3), "std::vector of length " "2, capacity 2 = {7, 8}"); } void set_iterator_test() { std::set<int> one_two_three {1111, 2222, 3333}; auto it = one_two_three.find(2222); MarkAsLive(it); CompareExpressionPrettyPrintToRegex("it", R"(std::__tree_const_iterator = {\[0x[a-f0-9]+\] = 2222})"); auto not_found = one_two_three.find(1234); MarkAsLive(not_found); // Because the end_node is not easily detected, just be sure it doesn't crash. CompareExpressionPrettyPrintToRegex("not_found", R"(std::__tree_const_iterator ( = {\[0x[a-f0-9]+\] = .*}|<error reading variable:.*>))"); } void map_iterator_test() { std::map<int, std::string> one_two_three; one_two_three.insert({1, "one"}); one_two_three.insert({2, "two"}); one_two_three.insert({3, "three"}); auto it = one_two_three.begin(); MarkAsLive(it); CompareExpressionPrettyPrintToRegex("it", R"(std::__map_iterator = )" R"({\[0x[a-f0-9]+\] = {first = 1, second = "one"}})"); auto not_found = one_two_three.find(7); MarkAsLive(not_found); // Because the end_node is not easily detected, just be sure it doesn't crash. CompareExpressionPrettyPrintToRegex( "not_found", R"(std::__map_iterator ( = {\[0x[a-f0-9]+\] = .*}|<error reading variable:.*>))"); } void unordered_set_test() { std::unordered_set<int> i_am_empty; ComparePrettyPrintToChars(i_am_empty, "std::unordered_set is empty"); std::unordered_set<int> numbers {12345, 67890, 222333, 12345}; numbers.erase(numbers.find(222333)); ComparePrettyPrintToRegex(numbers, "std::unordered_set with 2 elements = "); ComparePrettyPrintToRegex(numbers, ".*12345.*"); ComparePrettyPrintToRegex(numbers, ".*67890.*"); std::unordered_set<std::string> colors {"red", "blue", "green"}; ComparePrettyPrintToRegex(colors, "std::unordered_set with 3 elements = "); ComparePrettyPrintToRegex(colors, R"(.*"red".*)"); ComparePrettyPrintToRegex(colors, R"(.*"blue".*)"); ComparePrettyPrintToRegex(colors, R"(.*"green".*)"); } void unordered_multiset_test() { std::unordered_multiset<int> i_am_empty; ComparePrettyPrintToChars(i_am_empty, "std::unordered_multiset is empty"); std::unordered_multiset<int> numbers {12345, 67890, 222333, 12345}; ComparePrettyPrintToRegex(numbers, "std::unordered_multiset with 4 elements = "); ComparePrettyPrintToRegex(numbers, ".*12345.*12345.*"); ComparePrettyPrintToRegex(numbers, ".*67890.*"); ComparePrettyPrintToRegex(numbers, ".*222333.*"); std::unordered_multiset<std::string> colors {"red", "blue", "green", "red"}; ComparePrettyPrintToRegex(colors, "std::unordered_multiset with 4 elements = "); ComparePrettyPrintToRegex(colors, R"(.*"red".*"red".*)"); ComparePrettyPrintToRegex(colors, R"(.*"blue".*)"); ComparePrettyPrintToRegex(colors, R"(.*"green".*)"); } void unordered_map_test() { std::unordered_map<int, int> i_am_empty; ComparePrettyPrintToChars(i_am_empty, "std::unordered_map is empty"); std::unordered_map<int, std::string> one_two_three; one_two_three.insert({1, "one"}); one_two_three.insert({2, "two"}); one_two_three.insert({3, "three"}); ComparePrettyPrintToRegex(one_two_three, "std::unordered_map with 3 elements = "); ComparePrettyPrintToRegex(one_two_three, R"(.*\[1\] = "one".*)"); ComparePrettyPrintToRegex(one_two_three, R"(.*\[2\] = "two".*)"); ComparePrettyPrintToRegex(one_two_three, R"(.*\[3\] = "three".*)"); } void unordered_multimap_test() { std::unordered_multimap<int, int> i_am_empty; ComparePrettyPrintToChars(i_am_empty, "std::unordered_multimap is empty"); std::unordered_multimap<int, std::string> one_two_three; one_two_three.insert({1, "one"}); one_two_three.insert({2, "two"}); one_two_three.insert({3, "three"}); one_two_three.insert({2, "two"}); ComparePrettyPrintToRegex(one_two_three, "std::unordered_multimap with 4 elements = "); ComparePrettyPrintToRegex(one_two_three, R"(.*\[1\] = "one".*)"); ComparePrettyPrintToRegex(one_two_three, R"(.*\[2\] = "two".*\[2\] = "two")"); ComparePrettyPrintToRegex(one_two_three, R"(.*\[3\] = "three".*)"); } void unordered_map_iterator_test() { std::unordered_map<int, int> ones_to_eights; ones_to_eights.insert({1, 8}); ones_to_eights.insert({11, 88}); ones_to_eights.insert({111, 888}); auto ones_to_eights_begin = ones_to_eights.begin(); MarkAsLive(ones_to_eights_begin); CompareExpressionPrettyPrintToRegex("ones_to_eights_begin", R"(std::__hash_map_iterator = {\[1+\] = 8+})"); auto not_found = ones_to_eights.find(5); MarkAsLive(not_found); CompareExpressionPrettyPrintToRegex("not_found", R"(std::__hash_map_iterator = end\(\))"); } void unordered_set_iterator_test() { std::unordered_set<int> ones; ones.insert(111); ones.insert(1111); ones.insert(11111); auto ones_begin = ones.begin(); MarkAsLive(ones_begin); CompareExpressionPrettyPrintToRegex("ones_begin", R"(std::__hash_const_iterator = {1+})"); auto not_found = ones.find(5); MarkAsLive(not_found); CompareExpressionPrettyPrintToRegex("not_found", R"(std::__hash_const_iterator = end\(\))"); } // Check that libc++ pretty printers do not handle pointers. void pointer_negative_test() { int abc = 123; int *int_ptr = &abc; // Check that the result is equivalent to "p/r int_ptr" command. ComparePrettyPrintToRegex(int_ptr, R"(\(int \*\) 0x[a-f0-9]+)"); } void shared_ptr_test() { // Shared ptr tests while using test framework call another function // due to which there is one more count for the pointer. Hence, all the // following tests are testing with expected count plus 1. std::shared_ptr<const int> test0 = std::make_shared<const int>(5); ComparePrettyPrintToRegex( test0, R"(std::shared_ptr<int> count 2, weak 0 containing = {__ptr_ = 0x[a-f0-9]+})"); std::shared_ptr<const int> test1(test0); ComparePrettyPrintToRegex( test1, R"(std::shared_ptr<int> count 3, weak 0 containing = {__ptr_ = 0x[a-f0-9]+})"); { std::weak_ptr<const int> test2 = test1; ComparePrettyPrintToRegex( test0, R"(std::shared_ptr<int> count 3, weak 1 containing = {__ptr_ = 0x[a-f0-9]+})"); } ComparePrettyPrintToRegex( test0, R"(std::shared_ptr<int> count 3, weak 0 containing = {__ptr_ = 0x[a-f0-9]+})"); std::shared_ptr<const int> test3; ComparePrettyPrintToChars(test3, "std::shared_ptr is nullptr"); } void streampos_test() { std::streampos test0 = 67; ComparePrettyPrintToChars( test0, "std::fpos with stream offset:67 with state: {count:0 value:0}"); std::istringstream input("testing the input stream here"); std::streampos test1 = input.tellg(); ComparePrettyPrintToChars( test1, "std::fpos with stream offset:0 with state: {count:0 value:0}"); std::unique_ptr<char[]> buffer(new char[5]); input.read(buffer.get(), 5); test1 = input.tellg(); ComparePrettyPrintToChars( test1, "std::fpos with stream offset:5 with state: {count:0 value:0}"); } int main(int, char**) { framework_self_test(); string_test(); a_namespace::string_view_test(); u32string_test(); tuple_test(); unique_ptr_test(); shared_ptr_test(); bitset_test(); list_test(); deque_test(); map_test(); multimap_test(); queue_test(); priority_queue_test(); stack_test(); set_test(); multiset_test(); vector_test(); set_iterator_test(); map_iterator_test(); unordered_set_test(); unordered_multiset_test(); unordered_map_test(); unordered_multimap_test(); unordered_map_iterator_test(); unordered_set_iterator_test(); pointer_negative_test(); streampos_test(); return 0; }
//======================================================== // Hazi feladat keret. // A //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // sorokon beluli reszben celszeru garazdalkodni, mert // a tobbit ugyis toroljuk. // A Hazi feladat csak ebben a fajlban lehet // Tilos: // - mast "beincludolni", illetve mas konyvtarat hasznalni // - faljmuveleteket vegezni //======================================================== #include <math.h> #include <stdlib.h> #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) // MsWindows-on ez is kell #include <windows.h> #else // g++ nem fordit a stanard include-ok nelkul :-/ #include <string.h> #endif // Win32 platform #include <GL/gl.h> #include <GL/glu.h> // A GLUT-ot le kell tolteni: http://www.opengl.org/resources/libraries/glut/ #include <GL/glut.h> #include <stdio.h> //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Innentol modosithatod... //-------------------------------------------------------- // Nev: Vajna Miklos // Neptun: AYU9RZ //-------------------------------------------------------- #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0])) class Vector { public: float x, y, z; Vector(float x0, float y0, float z0) { x = x0; y = y0; z = z0; } Vector operator+(const Vector& v) { return Vector(x + v.x, y + v.y, z + v.z); } Vector operator*(float f) { return Vector(x * f, y * f, z * f); } }; class Matrix { public: float m[16]; void Clear() { memset(&m[0], 0, sizeof(m)); } void LoadIdentify() { Clear(); m[0] = m[5] = m[10] = m[15] = 1; } Vector operator*(const Vector& v) { float Xh = m[0] * v.x + m[1] * v.y + m[2] * v.z + m[3]; float Yh = m[4] * v.x + m[5] * v.y + m[6] * v.z + m[7]; float Zh = m[8] * v.x + m[9] * v.y + m[10] * v.z + m[11]; float h = m[12] * v.x + m[13] * v.y + m[14] * v.z + m[15]; return Vector(Xh/h, Yh/h, Zh/h); } Matrix operator*(const Matrix &arg) { Matrix res; for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) { res.m[i * 4 + j] = 0; for (int k = 0; k < 4; k++) res.m[i * 4 + j] += m[i * 4 + k] * arg.m[k * 4 + j]; } return res; } float *GetArray() { return &m[0]; } Matrix Transpose() { Matrix result; for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) result.m[j * 4 + i] = m[i * 4 + j]; return result; } }; enum { NOOP = 0, SCALE, ROTATE, SHIFT }; enum { DEFAULT = 0, OPENGL, MANUAL }; int matrix_state = DEFAULT; int matrix_dirty = 0; const Vector* points[2][13]; Matrix* transs[4]; void CatmullClark(const Vector** p, int len) { for (int i = 1; i < len; i += 2) p[i] = new Vector(((Vector)*p[i-1]) * 0.5 + ((Vector)*p[i+1]) * 0.5); for (int i = 2; i + 2 < len; i += 2) p[i] = new Vector(((Vector)*p[i-1]) * 0.25 + ((Vector)*p[i+1]) * 0.25 + ((Vector)*p[i]) * 0.5); } void onInitialization( ) { points[0][0] = new Vector(160, 20, 0); points[0][2] = new Vector(250, 80, 0); points[0][4] = new Vector(270, 20, 0); points[0][6] = new Vector(360, 80, 0); points[0][8] = new Vector(390, 20, 0); points[0][10] = new Vector(470, 80, 0); points[0][12] = new Vector(490, 20, 0); CatmullClark(points[0], ARRAY_SIZE(points[0])); points[1][0] = new Vector(160, 120, 0); points[1][2] = new Vector(250, 180, 0); points[1][4] = new Vector(270, 120, 0); points[1][6] = new Vector(360, 180, 0); points[1][8] = new Vector(390, 120, 0); points[1][10] = new Vector(470, 180, 0); points[1][12] = new Vector(490, 120, 0); CatmullClark(points[1], ARRAY_SIZE(points[1])); /* * 1 0 0 0 * 0 1 0 0 * 0 0 1 0 * 0 0 0 1 */ transs[NOOP] = new Matrix(); transs[NOOP]->LoadIdentify(); /* * 0.5 0 0 0 * 0 0.5 0 0 * 0 0 0.5 0 * 0 0 0 1 */ transs[SCALE] = new Matrix(); transs[SCALE]->LoadIdentify(); transs[SCALE]->m[0] = 0.5; transs[SCALE]->m[5] = 0.5; transs[SCALE]->m[10] = 0.5; /* * cos sin 0 0 * -sin cos 0 0 * 0 0 1 0 * 0 0 0 1 */ float angle = M_PI/4; transs[ROTATE] = new Matrix(); transs[ROTATE]->LoadIdentify(); transs[ROTATE]->m[0] = cosf(angle); transs[ROTATE]->m[1] = -sinf(angle); transs[ROTATE]->m[4] = sinf(angle); transs[ROTATE]->m[5] = cosf(angle); /* * 1 0 0 0 * 0 1 0 0 * 0 0 1 0 * px py pz 1 */ transs[SHIFT] = new Matrix(); transs[SHIFT]->LoadIdentify(); transs[SHIFT]->m[3] = 50; transs[SHIFT]->m[7] = 50; gluOrtho2D(0., 600., 0., 600.); } void onDisplay() { Matrix m; glClearColor(0.1f, 0.2f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glColor4d(0.9f, 0.8f, 0.7f, 1.0f); if (matrix_state == DEFAULT) m = *transs[NOOP]; else m = *transs[SCALE] * *transs[ROTATE] * *transs[SHIFT]; if (matrix_state == MANUAL && matrix_dirty) { glTranslatef(-50, -50, 0); glRotatef(-180/4, 0, 0, 1); glScalef(1/0.5, 1/0.5, 0); matrix_dirty = 0; } else if (matrix_state == OPENGL && !matrix_dirty){ glScalef(0.5, 0.5, 0); glRotatef(180/4, 0, 0, 1); glTranslatef(50, 50, 0); matrix_dirty = 1; } for (unsigned int i = 0; i < ARRAY_SIZE(points); i++) { glBegin(GL_LINE_STRIP); for (unsigned int j = 0; j < ARRAY_SIZE(points[i]); j++) { if (matrix_state == MANUAL) { Vector v = m * *points[i][j]; glVertex2d(v.x, v.y); } else { Vector v = *points[i][j]; glVertex2d(v.x, v.y); } } glEnd(); } // Buffercsere: rajzolas vege glFinish(); glutSwapBuffers(); } void onMouse(int button, int state, int x, int y) { // A GLUT_LEFT_BUTTON / GLUT_RIGHT_BUTTON // ill. a GLUT_DOWN / GLUT_UP makrokat hasznald. } void onIdle() { } void onKeyboard(unsigned char key, int x, int y) { if (key != 's' && key != 'S') return; matrix_state = key == 's' ? MANUAL : OPENGL; onDisplay(); } // ...Idaig modosithatod //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ int main(int argc, char **argv) { glutInit(&argc, argv); glutInitWindowSize(600, 600); glutInitWindowPosition(100, 100); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); glutCreateWindow("Grafika hazi feladat"); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); onInitialization(); glutDisplayFunc(onDisplay); glutMouseFunc(onMouse); glutIdleFunc(onIdle); glutKeyboardFunc(onKeyboard); glutMainLoop(); return 0; }
#include <iostream> #include <math.h> #include <fstream> #include <string> #include <sstream> #include "Vector.h" using namespace std; double antiderivativeAt(double m, double b, double xVal) { return m*xVal*xVal/2.0 + b*xVal; } double area(double x1, double y1, double x2, double y2, int N) { double m = (y2-y1)/(x2-x1); double b = y1-m*x1; return antiderivativeAt(m, b, min(double(N), x2) ) - antiderivativeAt(m, b, x1); } int main(int argc, char**argv) { if ( argc == 2 ) { int N=atoi(argv[1]); Array<double> fpArray, tpArray; cin >> fpArray >> tpArray; double rocN = 0.0; if ( fpArray.back() < N ) { cerr << "There are not enough false positives; needed " << N << " and was only given " << fpArray.back() << endl << endl; exit(1); } for (int k=0; k<fpArray.size()-1; k++) { // find segments where the fp value changes if ( fpArray[k] >= N ) break; if ( fpArray[k] != fpArray[k+1] ) { // this line segment is a function double currentArea = area(fpArray[k], tpArray[k], fpArray[k+1], tpArray[k+1], N); rocN += currentArea; } } cout << rocN / (N * tpArray.back()); } else { cerr << "usage: ROCN n < roc_file" << endl << endl; } return 0; }
class Solution { public: int minPathSum(vector<vector<int>> &grid) { int n = grid.size(); if (n == 0) return 0; int m = grid[0].size(); if (m == 0) return 0; for (int i = n - 1; i >= 0; --i) for (int j = m - 1; j >= 0; --j) { if (i == n - 1 && j != m - 1) grid[i][j] = grid[i][j] + grid[i][j + 1]; else if (j == m - 1 && i != n - 1) grid[i][j] = grid[i][j] + grid[i + 1][j]; else if (j != m - 1 && i != n - 1) grid[i][j] = grid[i][j] + min(grid[i + 1][j], grid[i][j + 1]); } return grid[0][0]; } };
/* * Copyright (C) 2005 - 2013 MaNGOS <http://www.getmangos.com/> * * Copyright (C) 2008 - 2013 Trinity <http://www.trinitycore.org/> * * Copyright (C) 2010 - 2013 ProjectSkyfire <http://www.projectskyfire.org/> * * Copyright (C) 2011 - 2013 ArkCORE <http://www.arkania.net/> * * 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 */ #include "gamePCH.h" #include "Opcodes.h" #include "WorldSession.h" #include "WorldPacket.h" void WorldSession::SendAuthResponse (uint8 code, bool shortForm, uint32 queuePos) { WorldPacket packet(SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 2 + 1 + (shortForm ? 0 : (4 + 1))); packet << uint8(code); packet << uint32(0); // BillingTimeRemaining packet << uint8(0); // BillingPlanFlags packet << uint32(0); // BillingTimeRested packet << uint8(Expansion()); // payed expansion packet << uint8(Expansion()); // server expansion if (!shortForm) { packet << uint32(queuePos); // Queue position packet << uint8(0); // Unk 3.3.0 } SendPacket(&packet); } void WorldSession::SendClientCacheVersion (uint32 version) { WorldPacket data(SMSG_CLIENTCACHE_VERSION, 4); data << uint32(version); SendPacket(&data); }
// // Created by Gael Aglin on 2019-12-23. // #include "rCover.h" bool isZero(float x){ return x == 0.0; } RCover::RCover(DataManager *dmm, vector<float>* weights):dm(dmm) { nWords = (int)ceil((float)dm->getNTransactions()/M); coverWords = new stack<bitset<M>>[nWords]; validWords = new int[nWords]; for (int i = 0; i < nWords; ++i) { stack<bitset<M>> rword; bitset<M> word; word.set(); if(i == 0 && dm->getNTransactions()%M != 0){ for (int j = dm->getNTransactions()%M; j < M; ++j) { word.set(j, false); } /*if (weights){ int size = dm->getNTransactions()%M; vector<float> tmp = vector<float>(weights->begin(), weights->begin() + size); auto it = tmp.begin(); while ((it = std::find_if(it, tmp.end(), isZero)) != tmp.end()) { int ind = distance(tmp.begin(), it); word.set(size - ind - 1, false); it++; } }*/ } else { /*if (weights){ vector<float> tmp = vector<float>(weights->begin() + i * M, weights->begin() + ((i+1) * M - 1)); auto it = tmp.begin(); while ((it = std::find_if(it, tmp.end(), isZero)) != tmp.end()) { int ind = distance(tmp.begin(), it); word.set(M - ind - 1, false); it++; } }*/ } rword.push(word); coverWords[i] = rword; validWords[i] = i; } limit.push(nWords); support = dm->getNTransactions(); } RCover::RCover(RCover &&cover) noexcept { coverWords = cover.coverWords; validWords = cover.validWords; limit = cover.limit; nWords = cover.nWords; dm = cover.dm; sup_class = cover.sup_class; support= cover.support; } bitset<M>* RCover::getTopBitsetArray() const{ auto* tmp = new bitset<M>[nWords]; for (int j = 0; j < nWords; ++j) { tmp[j] = coverWords[j].top(); } return tmp; } /** * temporaryIntersectSup - this function intersect the cover with an item just to * compute the support of the intersection. Nothing is change in the current cover * At the end of the function, the cover is still the same * @param attribute - the attribute to intersect with * @param positive - the item of the attribute * @return the value of the support of the intersection */ Support RCover::temporaryIntersectSup(Attribute attribute, bool positive) { Support sup = 0; for (int i = 0; i < limit.top(); ++i) { bitset<M> word; if (positive) word = coverWords[validWords[i]].top() & dm->getAttributeCover(attribute)[validWords[i]]; else word = coverWords[validWords[i]].top() & ~(dm->getAttributeCover(attribute)[validWords[i]]); sup += word.count(); } return sup; } /** * minusMe - this function computes the support per class for the cover c = cover1 - currentcover * @param cover1 - a cover to perform the minus operation * @return the support per class of the resultant cover */ /*Supports RCover::minusMe(bitset<M>* cover1) { int* tmpValid = new int[nWords]; for (int j = 0; j < nWords; ++j) { tmpValid[j] = validWords[j]; } int nvalid = 0; for (int i = 0; i < nWords; ++i) { coverWords[validWords[i]].push(~coverWords[validWords[i]].top() ); if (!coverWords[validWords[i]].top().none()){ validWords[nvalid] = i; ++nvalid; } } limit.push(nvalid); int climit = nvalid; for (int i = 0; i < climit; ++i) { coverWords[validWords[i]].push(coverWords[validWords[i]].top() & (cover1[validWords[i]]) ); if (coverWords[validWords[i]].top().none()){ int tmp = validWords[climit-1]; validWords[climit-1] = validWords[i]; validWords[i] = tmp; --climit; --i; } } limit.push(climit); deleteSupports(sup_class); // Supports tmp = sup_class; sup_class = nullptr; Supports toreturn = copySupports(getSupportPerClass()); backtrack(); limit.pop(); for (int i = 0; i < nWords; ++i) { coverWords[i].pop(); validWords[i] = tmpValid[i]; } delete [] tmpValid; // sup_class = tmp; return toreturn; }*/ Supports RCover::minusMe(bitset<M>* cover1) { int maxValidNumber = limit.top(); bitset<M>** difcover = new bitset<M>*[maxValidNumber]; int* validIndexes = new int[maxValidNumber]; int nvalid = 0; for (int i = 0; i < maxValidNumber; ++i) { bitset<M> potential_word = cover1[validWords[i]] & ~coverWords[validWords[i]].top(); if (!potential_word.none()){ difcover[nvalid] = &potential_word; validIndexes[nvalid] = validWords[i]; ++nvalid; } } Supports toreturn = getSupportPerClass(difcover, nvalid, validIndexes); delete [] difcover; delete [] validIndexes; return toreturn; } SupportClass RCover::countDif(bitset<M>* cover1) { SupportClass sup = 0; for (int i = 0; i < limit.top(); ++i) { bitset<M> potential_word = cover1[validWords[i]] & ~coverWords[validWords[i]].top(); if (!potential_word.none()){ sup += countSupportClass(potential_word, validWords[i]); } } return sup; } int RCover::getSupport() { if (support > -1) return support; int sum = 0; for (int i = 0; i < limit.top(); ++i) { sum += coverWords[validWords[i]].top().count(); } support = sum; return sum; } void RCover::backtrack() { limit.pop(); int climit = limit.top(); for (int i = 0; i < climit; ++i) { coverWords[validWords[i]].pop(); } support = -1; deleteSupports(sup_class); sup_class = nullptr; } void RCover::print() { for (int i = 0; i < nWords; ++i) { cout << coverWords[i].top().to_string() << " "; } cout << endl; } string RCover::outprint() { string s = ""; for (int i = 0; i < nWords; ++i) { s += coverWords[i].top().to_string() + " "; } return s; }
#include "tools.h" #include <iostream> using Eigen::VectorXd; using Eigen::MatrixXd; using std::vector; using std::cout; using std::endl; Tools::Tools() {} Tools::~Tools() {} VectorXd Tools::CalculateRMSE(const vector<VectorXd> &estimations, const vector<VectorXd> &ground_truth) { /** * TODO: Calculate the RMSE here. */ VectorXd rmse(4); rmse << 0, 0, 0, 0; // check the validity of the following inputs: // * the estimation vector size should not be zero // * the estimation vector size should equal ground truth vector size if (estimations.size() != ground_truth.size() || estimations.size() == 0) { cout << "Invalid estimation or ground_truth data" << endl; return rmse; } //accumulate squared residuals for (unsigned int i = 0; i < estimations.size(); ++i) { VectorXd residual = estimations[i] - ground_truth[i]; //coefficient-wise multiplication residual = residual.array() * residual.array(); rmse += residual; } //calculate the mean rmse = rmse / estimations.size(); //calculate the squared root rmse = rmse.array().sqrt(); //return the result return rmse; } MatrixXd Tools::CalculateJacobian(const VectorXd& x_state) { /** * TODO: * Calculate a Jacobian here. */ MatrixXd Hj(3, 4); //recover state parameters float px = x_state(0); float py = x_state(1); float vx = x_state(2); float vy = x_state(3); //pre-compute a set of terms to avoid repeated calculation float c1 = px * px + py*py; float c2 = sqrt(c1); float c3 = (c1 * c2); //check division by zero if (fabs(c1) < 0.0001) { cout << "CalculateJacobian () - Error - Division by Zero" << endl; return Hj; } //compute the Jacobian matrix Hj << (px / c2), (py / c2), 0, 0, -(py / c1), (px / c1), 0, 0, py * (vx * py - vy * px) / c3, px * (px * vy - py * vx) / c3, px / c2, py / c2; return Hj; }