hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
299f7eb25b88375facdc564689648ec61ad869d7 | 3,532 | cpp | C++ | leetcode/weekly/184.cpp | bvbasavaraju/competitive_programming | a82ffc1b639588a84f4273b44285d57cdc2f4b11 | [
"Apache-2.0"
] | 1 | 2020-05-05T13:06:51.000Z | 2020-05-05T13:06:51.000Z | leetcode/weekly/184.cpp | bvbasavaraju/competitive_programming | a82ffc1b639588a84f4273b44285d57cdc2f4b11 | [
"Apache-2.0"
] | null | null | null | leetcode/weekly/184.cpp | bvbasavaraju/competitive_programming | a82ffc1b639588a84f4273b44285d57cdc2f4b11 | [
"Apache-2.0"
] | null | null | null | /****************************************************
Date: April 12th, 2020
Successful submissions : 3
Time expiration : 0
Not Solved : 1
Wrong Answer/ Partial result : 0
link: https://leetcode.com/contest/weekly-contest-184
****************************************************/
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <stack>
#include <queue>
#include <map>
#include <unordered_map>
#include <cmath>
using namespace std;
/*
Q: 1408. String Matching in an Array
*/
class Solution1_t
{
public:
vector<string> stringMatching(vector<string>& words)
{
sort(words.begin(), words.end(), [](const string& s1, const string& s2) -> bool { return (s1.size() > s2.size()); } );
vector<string> result;
int l = words.size();
for(int j = l-1; j >= 0; --j)
{
string& to_find = words[j];
for(int i = 0; i < j; ++i)
{
if(words[i].find(to_find) != string::npos)
{
result.push_back(to_find);
break;
}
}
}
return result;
}
};
/*
Q: 1409. Queries on a Permutation With Key
*/
class Solution2_t
{
public:
vector<int> processQueries(vector<int>& queries, int m)
{
vector<int> p(m);
for(int i = 0; i < m; ++i)
{
p[i] = i + 1;
}
int l = queries.size();
vector<int> ans(l);
for(int j = 0; j < l; ++j)
{
for(int i = 0; i < m; ++i)
{
if(p[i] == queries[j])
{
ans[j] = i;
p.erase(p.begin() + i);
p.insert(p.begin(), queries[j]);
break;
}
}
}
return ans;
}
};
/*
Q: 1410. HTML Entity Parser
*/
class Solution3_t
{
public:
string entityParser(string t)
{
string result = "";
int l = t.size();
for(int i = 0; i < l; ++i)
{
//printf("%d,", i);
if(t[i] != '&')
{
result += t[i];
continue;
}
i++;
if(i >= l)
{
break;
}
string s = t.substr(i, 6);
bool replaced = false;
switch(t[i])
{
case 'q':
if(s.find("uot;", 1) != string::npos)
{
result += "\"";
i += 4;
replaced = true;
}
break;
case 'a':
if(s.find("pos;", 1) != string::npos)
{
result += "\'";
i += 4;
replaced = true;
}
else if(s.find("mp;", 1) != string::npos)
{
result += "&";
i += 3;
replaced = true;
}
break;
case 'g':
if(s.find("t;", 1) != string::npos)
{
result += ">";
i += 2;
replaced = true;
}
break;
case 'l':
if(s.find("t;", 1) != string::npos)
{
result += "<";
i += 2;
replaced = true;
}
break;
case 'f':
if(s.find("rasl;", 1) != string::npos)
{
result += "/";
i += 5;
replaced = true;
}
break;
default:
break;
}
if(!replaced)
{
result += "&";
result += t[i];
}
}
return result;
}
};
/*
Q: 1411. Number of Ways to Paint N × 3 Grid
*/
class Solution4_t
{
public:
int numOfWays(int n)
{
}
}; | 18.395833 | 122 | 0.398075 | [
"vector"
] |
29a0fc1cc46786ed1880c8c5eb8f5626ce86cfb0 | 1,088 | cpp | C++ | postgreSQL/basics-2-create-table.cpp | adeekshith/code-snippets | a70e596d6f6b99171588a2f702f54f285b3a45ce | [
"Apache-2.0"
] | 1 | 2021-03-24T01:21:27.000Z | 2021-03-24T01:21:27.000Z | postgreSQL/basics-2-create-table.cpp | adeekshith/code-snippets | a70e596d6f6b99171588a2f702f54f285b3a45ce | [
"Apache-2.0"
] | null | null | null | postgreSQL/basics-2-create-table.cpp | adeekshith/code-snippets | a70e596d6f6b99171588a2f702f54f285b3a45ce | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <pqxx/pqxx>
#include <string>
using namespace std;
using namespace pqxx;
int main(int argc, char* argv[])
{
string sql;
try{
connection C("dbname=testdb user=postgres password=postgres \
hostaddr=127.0.0.1 port=5432");
if (C.is_open()) {
cout << "Opened database successfully: " << C.dbname() << endl;
} else {
cout << "Can't open database" << endl;
return 1;
}
/* Create SQL statement */
sql = "CREATE TABLE GPSLOG(" \
"ID INT PRIMARY KEY NOT NULL," \
"DATE DATE NOT NULL," \
"TIME TIME NOT NULL," \
"LATITUDE varchar(12) NOT NULL," \
"LONGITUDE varchar(12) NOT NULL );";
/* Create a transactional object. */
work W(C);
/* Execute SQL query */
W.exec( sql );
W.commit();
cout << "Table created successfully" << endl;
C.disconnect ();
}catch (const std::exception &e){
cerr << e.what() << std::endl;
return 1;
}
return 0;
} | 25.302326 | 72 | 0.522059 | [
"object"
] |
29a34ee4362b814aa32a56eff444766f9ef62b53 | 18,263 | cpp | C++ | src/device_trezor/device_trezor.cpp | equisde/quorax_dev | 46358ed0062971cb9d81af4884b7cc359dce29f4 | [
"BSD-3-Clause"
] | 1 | 2022-01-21T01:52:55.000Z | 2022-01-21T01:52:55.000Z | src/device_trezor/device_trezor.cpp | equisde/quorax_dev | 46358ed0062971cb9d81af4884b7cc359dce29f4 | [
"BSD-3-Clause"
] | null | null | null | src/device_trezor/device_trezor.cpp | equisde/quorax_dev | 46358ed0062971cb9d81af4884b7cc359dce29f4 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2017-2018, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#include "device_trezor.hpp"
namespace hw {
namespace trezor {
#ifdef WITH_DEVICE_TREZOR
#undef QUORAX_DEFAULT_LOG_CATEGORY
#define QUORAX_DEFAULT_LOG_CATEGORY "device.trezor"
#define HW_TREZOR_NAME "Trezor"
static device_trezor *trezor_device = nullptr;
static device_trezor *ensure_trezor_device(){
if (!trezor_device) {
trezor_device = new device_trezor();
trezor_device->set_name(HW_TREZOR_NAME);
}
return trezor_device;
}
void register_all(std::map<std::string, std::unique_ptr<device>> ®istry) {
registry.insert(std::make_pair(HW_TREZOR_NAME, std::unique_ptr<device>(ensure_trezor_device())));
}
void register_all() {
hw::register_device(HW_TREZOR_NAME, ensure_trezor_device());
}
device_trezor::device_trezor() {
}
device_trezor::~device_trezor() {
try {
disconnect();
release();
} catch(std::exception const& e){
MWARNING("Could not disconnect and release: " << e.what());
}
}
/* ======================================================================= */
/* WALLET & ADDRESS */
/* ======================================================================= */
bool device_trezor::get_public_address(cryptonote::account_public_address &pubkey) {
try {
auto res = get_address();
cryptonote::address_parse_info info{};
bool r = cryptonote::get_account_address_from_str(info, this->network_type, res->address());
CHECK_AND_ASSERT_MES(r, false, "Could not parse returned address. Address parse failed: " + res->address());
CHECK_AND_ASSERT_MES(!info.is_subaddress, false, "Trezor returned a sub address");
pubkey = info.address;
return true;
} catch(std::exception const& e){
MERROR("Get public address exception: " << e.what());
return false;
}
}
bool device_trezor::get_secret_keys(crypto::secret_key &viewkey , crypto::secret_key &spendkey) {
try {
MDEBUG("Loading view-only key from the Trezor. Please check the Trezor for a confirmation.");
auto res = get_view_key();
CHECK_AND_ASSERT_MES(res->watch_key().size() == 32, false, "Trezor returned invalid view key");
spendkey = crypto::null_skey; // not given
memcpy(viewkey.data, res->watch_key().data(), 32);
return true;
} catch(std::exception const& e){
MERROR("Get secret keys exception: " << e.what());
return false;
}
}
/* ======================================================================= */
/* Helpers */
/* ======================================================================= */
/* ======================================================================= */
/* TREZOR PROTOCOL */
/* ======================================================================= */
std::shared_ptr<messages::monero::MoneroAddress> device_trezor::get_address(
const boost::optional<std::vector<uint32_t>> & path,
const boost::optional<cryptonote::network_type> & network_type){
AUTO_LOCK_CMD();
require_connected();
device_state_reset_unsafe();
require_initialized();
auto req = std::make_shared<messages::monero::MoneroGetAddress>();
this->set_msg_addr<messages::monero::MoneroGetAddress>(req.get(), path, network_type);
auto response = this->client_exchange<messages::monero::MoneroAddress>(req);
MTRACE("Get address response received");
return response;
}
std::shared_ptr<messages::monero::MoneroWatchKey> device_trezor::get_view_key(
const boost::optional<std::vector<uint32_t>> & path,
const boost::optional<cryptonote::network_type> & network_type){
AUTO_LOCK_CMD();
require_connected();
device_state_reset_unsafe();
require_initialized();
auto req = std::make_shared<messages::monero::MoneroGetWatchKey>();
this->set_msg_addr<messages::monero::MoneroGetWatchKey>(req.get(), path, network_type);
auto response = this->client_exchange<messages::monero::MoneroWatchKey>(req);
MTRACE("Get watch key response received");
return response;
}
void device_trezor::ki_sync(wallet_shim * wallet,
const std::vector<tools::wallet2::transfer_details> & transfers,
hw::device_cold::exported_key_image & ski)
{
AUTO_LOCK_CMD();
require_connected();
device_state_reset_unsafe();
require_initialized();
std::shared_ptr<messages::monero::MoneroKeyImageExportInitRequest> req;
std::vector<protocol::ki::MoneroTransferDetails> mtds;
std::vector<protocol::ki::MoneroExportedKeyImage> kis;
protocol::ki::key_image_data(wallet, transfers, mtds);
protocol::ki::generate_commitment(mtds, transfers, req);
this->set_msg_addr<messages::monero::MoneroKeyImageExportInitRequest>(req.get());
auto ack1 = this->client_exchange<messages::monero::MoneroKeyImageExportInitAck>(req);
const auto batch_size = 10;
const auto num_batches = (mtds.size() + batch_size - 1) / batch_size;
for(uint64_t cur = 0; cur < num_batches; ++cur){
auto step_req = std::make_shared<messages::monero::MoneroKeyImageSyncStepRequest>();
auto idx_finish = std::min(static_cast<uint64_t>((cur + 1) * batch_size), static_cast<uint64_t>(mtds.size()));
for(uint64_t idx = cur * batch_size; idx < idx_finish; ++idx){
auto added_tdis = step_req->add_tdis();
CHECK_AND_ASSERT_THROW_MES(idx < mtds.size(), "Invalid transfer detail index");
*added_tdis = mtds[idx];
}
auto step_ack = this->client_exchange<messages::monero::MoneroKeyImageSyncStepAck>(step_req);
auto kis_size = step_ack->kis_size();
kis.reserve(static_cast<size_t>(kis_size));
for(int i = 0; i < kis_size; ++i){
auto ckis = step_ack->kis(i);
kis.push_back(ckis);
}
MTRACE("Batch " << cur << " / " << num_batches << " batches processed");
}
auto final_req = std::make_shared<messages::monero::MoneroKeyImageSyncFinalRequest>();
auto final_ack = this->client_exchange<messages::monero::MoneroKeyImageSyncFinalAck>(final_req);
ski.reserve(kis.size());
for(auto & sub : kis){
char buff[32*3];
protocol::crypto::chacha::decrypt(sub.blob().data(), sub.blob().size(),
reinterpret_cast<const uint8_t *>(final_ack->enc_key().data()),
reinterpret_cast<const uint8_t *>(sub.iv().data()), buff);
::crypto::signature sig{};
::crypto::key_image ki;
memcpy(ki.data, buff, 32);
memcpy(sig.c.data, buff + 32, 32);
memcpy(sig.r.data, buff + 64, 32);
ski.push_back(std::make_pair(ki, sig));
}
}
void device_trezor::tx_sign(wallet_shim * wallet,
const tools::wallet2::unsigned_tx_set & unsigned_tx,
tools::wallet2::signed_tx_set & signed_tx,
hw::tx_aux_data & aux_data)
{
CHECK_AND_ASSERT_THROW_MES(unsigned_tx.transfers.first == 0, "Unsuported non zero offset");
size_t num_tx = unsigned_tx.txes.size();
signed_tx.key_images.clear();
signed_tx.key_images.resize(unsigned_tx.transfers.second.size());
for(size_t tx_idx = 0; tx_idx < num_tx; ++tx_idx) {
std::shared_ptr<protocol::tx::Signer> signer;
tx_sign(wallet, unsigned_tx, tx_idx, aux_data, signer);
auto & cdata = signer->tdata();
auto aux_info_cur = signer->store_tx_aux_info();
aux_data.tx_device_aux.emplace_back(aux_info_cur);
// Pending tx reconstruction
signed_tx.ptx.emplace_back();
auto & cpend = signed_tx.ptx.back();
cpend.tx = cdata.tx;
cpend.dust = 0;
cpend.fee = 0;
cpend.dust_added_to_fee = false;
cpend.change_dts = cdata.tx_data.change_dts;
cpend.selected_transfers = cdata.tx_data.selected_transfers;
cpend.key_images = "";
cpend.dests = cdata.tx_data.dests;
cpend.construction_data = cdata.tx_data;
// Transaction check
try {
transaction_check(cdata, aux_data);
} catch(const std::exception &e){
throw exc::ProtocolException(std::string("Transaction verification failed: ") + e.what());
}
std::string key_images;
bool all_are_txin_to_key = std::all_of(cdata.tx.vin.begin(), cdata.tx.vin.end(), [&](const cryptonote::txin_v& s_e) -> bool
{
CHECKED_GET_SPECIFIC_VARIANT(s_e, const cryptonote::txin_to_key, in, false);
key_images += boost::to_string(in.k_image) + " ";
return true;
});
if(!all_are_txin_to_key) {
throw std::invalid_argument("Not all are txin_to_key");
}
cpend.key_images = key_images;
// KI sync
size_t num_sources = cdata.tx_data.sources.size();
CHECK_AND_ASSERT_THROW_MES(num_sources == cdata.source_permutation.size(), "Invalid permutation size");
CHECK_AND_ASSERT_THROW_MES(num_sources == cdata.tx.vin.size(), "Invalid tx.vin size");
for(size_t src_idx = 0; src_idx < num_sources; ++src_idx){
size_t idx_mapped = cdata.source_permutation[src_idx];
CHECK_AND_ASSERT_THROW_MES(idx_mapped < cdata.tx_data.selected_transfers.size(), "Invalid idx_mapped");
CHECK_AND_ASSERT_THROW_MES(src_idx < cdata.tx.vin.size(), "Invalid idx_mapped");
size_t idx_map_src = cdata.tx_data.selected_transfers[idx_mapped];
auto vini = boost::get<cryptonote::txin_to_key>(cdata.tx.vin[src_idx]);
CHECK_AND_ASSERT_THROW_MES(idx_map_src < signed_tx.key_images.size(), "Invalid key image index");
signed_tx.key_images[idx_map_src] = vini.k_image;
}
}
}
void device_trezor::tx_sign(wallet_shim * wallet,
const tools::wallet2::unsigned_tx_set & unsigned_tx,
size_t idx,
hw::tx_aux_data & aux_data,
std::shared_ptr<protocol::tx::Signer> & signer)
{
AUTO_LOCK_CMD();
require_connected();
device_state_reset_unsafe();
require_initialized();
CHECK_AND_ASSERT_THROW_MES(idx < unsigned_tx.txes.size(), "Invalid transaction index");
signer = std::make_shared<protocol::tx::Signer>(wallet, &unsigned_tx, idx, &aux_data);
const tools::wallet2::tx_construction_data & cur_tx = unsigned_tx.txes[idx];
unsigned long num_sources = cur_tx.sources.size();
unsigned long num_outputs = cur_tx.splitted_dsts.size();
// Step: Init
auto init_msg = signer->step_init();
this->set_msg_addr(init_msg.get());
transaction_pre_check(init_msg);
auto response = this->client_exchange<messages::monero::MoneroTransactionInitAck>(init_msg);
signer->step_init_ack(response);
// Step: Set transaction inputs
for(size_t cur_src = 0; cur_src < num_sources; ++cur_src){
auto src = signer->step_set_input(cur_src);
auto ack = this->client_exchange<messages::monero::MoneroTransactionSetInputAck>(src);
signer->step_set_input_ack(ack);
}
// Step: sort
auto perm_req = signer->step_permutation();
if (perm_req){
auto perm_ack = this->client_exchange<messages::monero::MoneroTransactionInputsPermutationAck>(perm_req);
signer->step_permutation_ack(perm_ack);
}
// Step: input_vini
if (!signer->in_memory()){
for(size_t cur_src = 0; cur_src < num_sources; ++cur_src){
auto src = signer->step_set_vini_input(cur_src);
auto ack = this->client_exchange<messages::monero::MoneroTransactionInputViniAck>(src);
signer->step_set_vini_input_ack(ack);
}
}
// Step: all inputs set
auto all_inputs_set = signer->step_all_inputs_set();
auto ack_all_inputs = this->client_exchange<messages::monero::MoneroTransactionAllInputsSetAck>(all_inputs_set);
signer->step_all_inputs_set_ack(ack_all_inputs);
// Step: outputs
for(size_t cur_dst = 0; cur_dst < num_outputs; ++cur_dst){
auto src = signer->step_set_output(cur_dst);
auto ack = this->client_exchange<messages::monero::MoneroTransactionSetOutputAck>(src);
signer->step_set_output_ack(ack);
}
// Step: all outs set
auto all_out_set = signer->step_all_outs_set();
auto ack_all_out_set = this->client_exchange<messages::monero::MoneroTransactionAllOutSetAck>(all_out_set);
signer->step_all_outs_set_ack(ack_all_out_set, *this);
// Step: sign each input
for(size_t cur_src = 0; cur_src < num_sources; ++cur_src){
auto src = signer->step_sign_input(cur_src);
auto ack_sign = this->client_exchange<messages::monero::MoneroTransactionSignInputAck>(src);
signer->step_sign_input_ack(ack_sign);
}
// Step: final
auto final_msg = signer->step_final();
auto ack_final = this->client_exchange<messages::monero::MoneroTransactionFinalAck>(final_msg);
signer->step_final_ack(ack_final);
}
void device_trezor::transaction_pre_check(std::shared_ptr<messages::monero::MoneroTransactionInitRequest> init_msg)
{
CHECK_AND_ASSERT_THROW_MES(init_msg, "TransactionInitRequest is empty");
CHECK_AND_ASSERT_THROW_MES(init_msg->has_tsx_data(), "TransactionInitRequest has no transaction data");
CHECK_AND_ASSERT_THROW_MES(m_features, "Device state not initialized"); // make sure the caller did not reset features
const bool nonce_required = init_msg->tsx_data().has_payment_id() && init_msg->tsx_data().payment_id().size() > 0;
if (nonce_required){
// Versions 2.0.9 and lower do not support payment ID
CHECK_AND_ASSERT_THROW_MES(m_features->has_major_version() && m_features->has_minor_version() && m_features->has_patch_version(), "Invalid Trezor firmware version information");
const uint32_t vma = m_features->major_version();
const uint32_t vmi = m_features->minor_version();
const uint32_t vpa = m_features->patch_version();
if (vma < 2 || (vma == 2 && vmi == 0 && vpa <= 9)) {
throw exc::TrezorException("Trezor firmware 2.0.9 and lower does not support transactions with short payment IDs or integrated addresses. Please update.");
}
}
}
void device_trezor::transaction_check(const protocol::tx::TData & tdata, const hw::tx_aux_data & aux_data)
{
// Simple serialization check
cryptonote::blobdata tx_blob;
cryptonote::transaction tx_deserialized;
bool r = cryptonote::t_serializable_object_to_blob(tdata.tx, tx_blob);
CHECK_AND_ASSERT_THROW_MES(r, "Transaction serialization failed");
r = cryptonote::parse_and_validate_tx_from_blob(tx_blob, tx_deserialized);
CHECK_AND_ASSERT_THROW_MES(r, "Transaction deserialization failed");
// Extras check
std::vector<cryptonote::tx_extra_field> tx_extra_fields;
cryptonote::tx_extra_nonce nonce;
r = cryptonote::parse_tx_extra(tdata.tx.extra, tx_extra_fields);
CHECK_AND_ASSERT_THROW_MES(r, "tx.extra parsing failed");
const bool nonce_required = tdata.tsx_data.has_payment_id() && tdata.tsx_data.payment_id().size() > 0;
const bool has_nonce = cryptonote::find_tx_extra_field_by_type(tx_extra_fields, nonce);
CHECK_AND_ASSERT_THROW_MES(has_nonce == nonce_required, "Transaction nonce presence inconsistent");
if (nonce_required){
const std::string & payment_id = tdata.tsx_data.payment_id();
if (payment_id.size() == 32){
crypto::hash payment_id_long{};
CHECK_AND_ASSERT_THROW_MES(cryptonote::get_payment_id_from_tx_extra_nonce(nonce.nonce, payment_id_long), "Long payment ID not present");
} else if (payment_id.size() == 8){
crypto::hash8 payment_id_short{};
CHECK_AND_ASSERT_THROW_MES(cryptonote::get_encrypted_payment_id_from_tx_extra_nonce(nonce.nonce, payment_id_short), "Short payment ID not present");
}
}
}
#else //WITH_DEVICE_TREZOR
void register_all(std::map<std::string, std::unique_ptr<device>> ®istry) {
}
void register_all() {
}
#endif //WITH_DEVICE_TREZOR
}}
| 43.380048 | 185 | 0.645458 | [
"vector"
] |
29a4ce8381baa8fb0c50a59019e93cbffd93edb7 | 4,270 | cc | C++ | third_party/webrtc/src/chromium/src/device/bluetooth/dbus/bluetooth_dbus_client_bundle.cc | bopopescu/webrtc-streaming-node | 727a441204344ff596401b0253caac372b714d91 | [
"MIT"
] | 8 | 2016-02-08T11:59:31.000Z | 2020-05-31T15:19:54.000Z | third_party/webrtc/src/chromium/src/device/bluetooth/dbus/bluetooth_dbus_client_bundle.cc | bopopescu/webrtc-streaming-node | 727a441204344ff596401b0253caac372b714d91 | [
"MIT"
] | 1 | 2021-05-05T11:11:31.000Z | 2021-05-05T11:11:31.000Z | third_party/webrtc/src/chromium/src/device/bluetooth/dbus/bluetooth_dbus_client_bundle.cc | bopopescu/webrtc-streaming-node | 727a441204344ff596401b0253caac372b714d91 | [
"MIT"
] | 7 | 2016-02-09T09:28:14.000Z | 2020-07-25T19:03:36.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "device/bluetooth/dbus/bluetooth_dbus_client_bundle.h"
#include <vector>
#include "base/command_line.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "chromeos/chromeos_switches.h"
#include "device/bluetooth/dbus/bluetooth_adapter_client.h"
#include "device/bluetooth/dbus/bluetooth_agent_manager_client.h"
#include "device/bluetooth/dbus/bluetooth_device_client.h"
#include "device/bluetooth/dbus/bluetooth_gatt_characteristic_client.h"
#include "device/bluetooth/dbus/bluetooth_gatt_descriptor_client.h"
#include "device/bluetooth/dbus/bluetooth_gatt_manager_client.h"
#include "device/bluetooth/dbus/bluetooth_gatt_service_client.h"
#include "device/bluetooth/dbus/bluetooth_input_client.h"
#include "device/bluetooth/dbus/bluetooth_le_advertising_manager_client.h"
#include "device/bluetooth/dbus/bluetooth_media_client.h"
#include "device/bluetooth/dbus/bluetooth_media_transport_client.h"
#include "device/bluetooth/dbus/bluetooth_profile_manager_client.h"
#include "device/bluetooth/dbus/fake_bluetooth_adapter_client.h"
#include "device/bluetooth/dbus/fake_bluetooth_agent_manager_client.h"
#include "device/bluetooth/dbus/fake_bluetooth_device_client.h"
#include "device/bluetooth/dbus/fake_bluetooth_gatt_characteristic_client.h"
#include "device/bluetooth/dbus/fake_bluetooth_gatt_descriptor_client.h"
#include "device/bluetooth/dbus/fake_bluetooth_gatt_manager_client.h"
#include "device/bluetooth/dbus/fake_bluetooth_gatt_service_client.h"
#include "device/bluetooth/dbus/fake_bluetooth_input_client.h"
#include "device/bluetooth/dbus/fake_bluetooth_le_advertising_manager_client.h"
#include "device/bluetooth/dbus/fake_bluetooth_media_client.h"
#include "device/bluetooth/dbus/fake_bluetooth_media_transport_client.h"
#include "device/bluetooth/dbus/fake_bluetooth_profile_manager_client.h"
namespace bluez {
BluetoothDBusClientBundle::BluetoothDBusClientBundle(bool use_stubs)
: use_stubs_(use_stubs) {
if (!use_stubs) {
bluetooth_adapter_client_.reset(BluetoothAdapterClient::Create());
bluetooth_le_advertising_manager_client_.reset(
BluetoothLEAdvertisingManagerClient::Create());
bluetooth_agent_manager_client_.reset(
BluetoothAgentManagerClient::Create());
bluetooth_device_client_.reset(BluetoothDeviceClient::Create());
bluetooth_input_client_.reset(BluetoothInputClient::Create());
bluetooth_media_client_.reset(BluetoothMediaClient::Create());
bluetooth_media_transport_client_.reset(
BluetoothMediaTransportClient::Create());
bluetooth_profile_manager_client_.reset(
BluetoothProfileManagerClient::Create());
bluetooth_gatt_characteristic_client_.reset(
BluetoothGattCharacteristicClient::Create());
bluetooth_gatt_descriptor_client_.reset(
BluetoothGattDescriptorClient::Create());
bluetooth_gatt_manager_client_.reset(BluetoothGattManagerClient::Create());
bluetooth_gatt_service_client_.reset(BluetoothGattServiceClient::Create());
} else {
bluetooth_adapter_client_.reset(new FakeBluetoothAdapterClient);
bluetooth_le_advertising_manager_client_.reset(
new FakeBluetoothLEAdvertisingManagerClient);
bluetooth_agent_manager_client_.reset(new FakeBluetoothAgentManagerClient);
bluetooth_device_client_.reset(new FakeBluetoothDeviceClient);
bluetooth_input_client_.reset(new FakeBluetoothInputClient);
bluetooth_media_client_.reset(new FakeBluetoothMediaClient);
bluetooth_media_transport_client_.reset(
new FakeBluetoothMediaTransportClient);
bluetooth_profile_manager_client_.reset(
new FakeBluetoothProfileManagerClient);
bluetooth_gatt_characteristic_client_.reset(
new FakeBluetoothGattCharacteristicClient);
bluetooth_gatt_descriptor_client_.reset(
new FakeBluetoothGattDescriptorClient);
bluetooth_gatt_manager_client_.reset(new FakeBluetoothGattManagerClient);
bluetooth_gatt_service_client_.reset(new FakeBluetoothGattServiceClient);
}
}
BluetoothDBusClientBundle::~BluetoothDBusClientBundle() {}
} // namespace bluez
| 50.235294 | 79 | 0.82623 | [
"vector"
] |
29a9184273c186efcc278b80e1f010591f0d8410 | 3,787 | cpp | C++ | lightcyclesplusplus/player.cpp | wildp/command-line-games | 96cc68d42f48320a7a6a05297598a82a004f0491 | [
"Apache-2.0"
] | null | null | null | lightcyclesplusplus/player.cpp | wildp/command-line-games | 96cc68d42f48320a7a6a05297598a82a004f0491 | [
"Apache-2.0"
] | null | null | null | lightcyclesplusplus/player.cpp | wildp/command-line-games | 96cc68d42f48320a7a6a05297598a82a004f0491 | [
"Apache-2.0"
] | 1 | 2020-03-15T17:46:59.000Z | 2020-03-15T17:46:59.000Z | // player.cpp
// contains code for the Player class
#include <SDL.h>
#include <iostream>
#include <string>
#include <vector>
#include "colours.h"
#include "directions.h"
#include "player.h"
// defaults in case setMidpoint is not called
short Player::s_playerNoGenerator = 0;
SDL_Point Player::s_midpoint = { 50, 50 };
SDL_Point Player::s_endpoint = { 100, 100 };
void Player::setMidpoint(SDL_Point gridSize) //static
{
s_midpoint.x = (gridSize.x / 2);
s_midpoint.y = (gridSize.y / 2);
s_endpoint = gridSize;
}
void Player::resetGenerator() //static
{
s_playerNoGenerator = 0;
}
const SDL_Point Player::getStartLocation()
{
switch (m_playerNo)
{
case 0: return { 0, s_midpoint.y };
case 1: return { s_endpoint.x, s_midpoint.y };
case 2: return { s_midpoint.x, 0 };
case 3: return { s_midpoint.x, s_endpoint.y };
default: return { s_midpoint.x, s_midpoint.y };
}
}
Player::Player():
m_playerNo{ s_playerNoGenerator++ },
m_alive{ State::ISALIVE }
{
m_dir = Game::startDir[m_playerNo];
m_trail.reserve(s_endpoint.x * s_endpoint.y);
m_location = getStartLocation();
m_trail = { m_location };
}
void Player::move(Directions cdir)
{
if (m_alive == State::ISALIVE)
{
switch (cdir)
{
case(Directions::RIGHT): if (m_dir != Directions::LEFT) m_dir = cdir; break;
case(Directions::LEFT): if (m_dir != Directions::RIGHT) m_dir = cdir; break;
case(Directions::DOWN): if (m_dir != Directions::UP) m_dir = cdir; break;
case(Directions::UP): if (m_dir != Directions::DOWN) m_dir = cdir; break;
}
switch (m_dir)
{
case(Directions::RIGHT): m_location.x++; break;
case(Directions::LEFT): m_location.x--; break;
case(Directions::DOWN): m_location.y++; break;
case(Directions::UP): m_location.y--; break;
}
m_trail.push_back(m_location);
}
}
bool Player::collide(std::vector<Player> &p, const short &PLAYERS, const bool &DELETETRAILS)
{
if (m_alive == State::ISALIVE)
{
for (int player{ 0 }; player < PLAYERS; player++)
{
std::vector<SDL_Point> &t{ p[player].m_trail };
int no = p[player].getPlayerNo();
for (int i{ 0 }; i < ((no == m_playerNo) ? (t.size() - 1) : (t.size())); ++i)
if ((m_location.x == t[i].x) && (m_location.y == t[i].y))
{
if (no == m_playerNo)
std::cout << "Player " << Game::colourNames[m_playerNo] << " has committed suicide.\n";
else
std::cout << "Player " << Game::colourNames[m_playerNo] << " was killed by Player " << Game::colourNames[no] <<".\n";
die(p, PLAYERS, DELETETRAILS);
return false;
}
}
if ((m_location.x < 0) || (m_location.x > s_endpoint.x) || (m_location.y < 0) || (m_location.y > s_endpoint.y))
{
std::cout << "Player " << Game::colourNames[m_playerNo] << " has died.\n";
die(p, PLAYERS, DELETETRAILS);
return false;
}
return true;
}
if (m_alive == State::NONE) die(p, PLAYERS, DELETETRAILS);
return false;
}
void Player::die(std::vector<Player> &p, const short &PLAYERS, const bool &DELETETRAILS)
{
if (m_alive == State::NONE)
{
m_alive = State::ISDEAD;
if (DELETETRAILS) m_trail.clear();
else
{
bool status{ false };
for (int player{ 0 }; player < PLAYERS; player++)
{
if (p[player].getPlayerNo() != m_playerNo)
if ((m_location.x == p[player].m_trail.back().x) && (m_location.y == p[player].m_trail.back().y))
status = true;
}
if (!status) m_trail.pop_back();
}
}
else m_alive = State::NONE;
}
void Player::test() { std::cout << "Player Object " << m_playerNo << "\n"; }
// is this even needed?
Player::~Player()
{
uint64_t s{ m_trail.size() };
for (int i{ 0 }; i < s; i++)
m_trail.pop_back();
} | 25.938356 | 124 | 0.608661 | [
"object",
"vector"
] |
29aa9f707acaeb98ae7fb03365ac068d38d40054 | 672 | cpp | C++ | codeforces/contests/round/617-div3/d.cpp | tysm/cpsols | 262212646203e516d1706edf962290de93762611 | [
"MIT"
] | 4 | 2020-10-05T19:24:10.000Z | 2021-07-15T00:45:43.000Z | codeforces/contests/round/617-div3/d.cpp | tysm/cpsols | 262212646203e516d1706edf962290de93762611 | [
"MIT"
] | null | null | null | codeforces/contests/round/617-div3/d.cpp | tysm/cpsols | 262212646203e516d1706edf962290de93762611 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define INF int32_t(1e9)+1
#define int long long
#define ii pair<int, int>
#define ff first
#define ss second
using namespace std;
int32_t main(){
int n, a, b, k, ans = 0;
cin >> n >> a >> b >> k;
vector<int> v;
for(int i=0; i<n; ++i){
int x;
cin >> x;
int hp = x%(a+b);
if(hp == 0)
hp = a+b;
if(hp <= a)
ans++;
else{
hp-=a;
v.push_back(hp/a+(hp%a?1:0));
}
}
sort(v.begin(), v.end());
for(auto i:v){
if(i<=k){
ans++;
k-=i;
}
}
cout << ans << endl;
return 0;
}
| 17.684211 | 41 | 0.40625 | [
"vector"
] |
29aef9ed433615e8ea89c45e8611532f480f8c36 | 837 | cpp | C++ | src/problem/heuristic.cpp | pawelswoboda/MQLib | 600dd8e22de385c6045455cea66e9fb2fb369c36 | [
"MIT"
] | null | null | null | src/problem/heuristic.cpp | pawelswoboda/MQLib | 600dd8e22de385c6045455cea66e9fb2fb369c36 | [
"MIT"
] | null | null | null | src/problem/heuristic.cpp | pawelswoboda/MQLib | 600dd8e22de385c6045455cea66e9fb2fb369c36 | [
"MIT"
] | 1 | 2020-02-18T10:55:02.000Z | 2020-02-18T10:55:02.000Z | #include <stdlib.h>
#include <time.h>
#include <iomanip>
#include <iostream>
#include <vector>
#include "problem/heuristic.h"
namespace mqlib {
Heuristic::Heuristic(double runtime_limit, bool validation) :
validation_(validation),
best_(0.0),
runtime_limit_(runtime_limit) {
gettimeofday(&start_time_, 0);
}
double Heuristic::Runtime() {
struct timeval tv;
gettimeofday(&tv, 0);
double secs = (tv.tv_sec - start_time_.tv_sec) + 0.000001 *
(tv.tv_usec - start_time_.tv_usec);
return secs;
}
std::string Heuristic::History() {
std::stringstream out_str;
out_str << std::setprecision(15) << "[";
for (int i = 0; i < past_solution_values_.size(); i++) {
if (i > 0) out_str << ";";
out_str << past_solution_values_[i] << ":" << past_solution_times_[i];
}
out_str << "]";
return out_str.str();
}
}
| 22.621622 | 74 | 0.665472 | [
"vector"
] |
29af9985b380e7c85d6ebd0957cacab2cbfd0ebd | 1,780 | cc | C++ | cartographer/mapping/trajectory_node_test.cc | zhaozhi1995/cartographer | a9d4be9f46d5fad898dc0ceeea08bd985a57f0e6 | [
"Apache-2.0"
] | 12 | 2020-11-24T03:46:44.000Z | 2022-03-07T07:35:24.000Z | cartographer/mapping/trajectory_node_test.cc | rancheng/cartographer | a9d4be9f46d5fad898dc0ceeea08bd985a57f0e6 | [
"Apache-2.0"
] | null | null | null | cartographer/mapping/trajectory_node_test.cc | rancheng/cartographer | a9d4be9f46d5fad898dc0ceeea08bd985a57f0e6 | [
"Apache-2.0"
] | 9 | 2021-01-13T08:58:47.000Z | 2022-03-29T10:27:07.000Z | /*
* Copyright 2017 The Cartographer Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "cartographer/mapping/trajectory_node.h"
#include <limits>
#include "Eigen/Core"
#include "cartographer/common/time.h"
#include "cartographer/mapping/proto/trajectory_node_data.pb.h"
#include "cartographer/transform/rigid_transform_test_helpers.h"
#include "gtest/gtest.h"
namespace cartographer {
namespace mapping {
namespace {
TEST(TrajectoryNodeTest, ToAndFromProto) {
const TrajectoryNode::Data expected{
common::FromUniversal(42),
{},
sensor::CompressedPointCloud({{Eigen::Vector3f{1.f, 2.f, 0.f}, 0.f},
{Eigen::Vector3f{0.f, 0.f, 1.f}, 0.f}})
.Decompress(),
{},
transform::Rigid3d({1., 2., 3.},
Eigen::Quaterniond(4., 5., -6., -7.).normalized())};
const proto::TrajectoryNodeData proto = ToProto(expected);
const TrajectoryNode::Data actual = FromProto(proto);
EXPECT_EQ(expected.time, actual.time);
EXPECT_EQ(expected.filtered_point_cloud, actual.filtered_point_cloud);
EXPECT_THAT(actual.local_pose,
transform::IsNearly(expected.local_pose, 1e-9));
}
} // namespace
} // namespace mapping
} // namespace cartographer
| 34.230769 | 77 | 0.695506 | [
"transform"
] |
29b21080605540cad8f69a6666e7adc4edededc6 | 6,747 | cpp | C++ | aws-cpp-sdk-lightsail/source/model/Instance.cpp | Gohan/aws-sdk-cpp | 51aa785289d9a76ac27f026d169ddf71ec2d0686 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-lightsail/source/model/Instance.cpp | Gohan/aws-sdk-cpp | 51aa785289d9a76ac27f026d169ddf71ec2d0686 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-lightsail/source/model/Instance.cpp | Gohan/aws-sdk-cpp | 51aa785289d9a76ac27f026d169ddf71ec2d0686 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/lightsail/model/Instance.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Lightsail
{
namespace Model
{
Instance::Instance() :
m_nameHasBeenSet(false),
m_arnHasBeenSet(false),
m_supportCodeHasBeenSet(false),
m_createdAtHasBeenSet(false),
m_locationHasBeenSet(false),
m_resourceType(ResourceType::NOT_SET),
m_resourceTypeHasBeenSet(false),
m_blueprintIdHasBeenSet(false),
m_blueprintNameHasBeenSet(false),
m_bundleIdHasBeenSet(false),
m_isStaticIp(false),
m_isStaticIpHasBeenSet(false),
m_privateIpAddressHasBeenSet(false),
m_publicIpAddressHasBeenSet(false),
m_ipv6AddressHasBeenSet(false),
m_hardwareHasBeenSet(false),
m_networkingHasBeenSet(false),
m_stateHasBeenSet(false),
m_usernameHasBeenSet(false),
m_sshKeyNameHasBeenSet(false)
{
}
Instance::Instance(JsonView jsonValue) :
m_nameHasBeenSet(false),
m_arnHasBeenSet(false),
m_supportCodeHasBeenSet(false),
m_createdAtHasBeenSet(false),
m_locationHasBeenSet(false),
m_resourceType(ResourceType::NOT_SET),
m_resourceTypeHasBeenSet(false),
m_blueprintIdHasBeenSet(false),
m_blueprintNameHasBeenSet(false),
m_bundleIdHasBeenSet(false),
m_isStaticIp(false),
m_isStaticIpHasBeenSet(false),
m_privateIpAddressHasBeenSet(false),
m_publicIpAddressHasBeenSet(false),
m_ipv6AddressHasBeenSet(false),
m_hardwareHasBeenSet(false),
m_networkingHasBeenSet(false),
m_stateHasBeenSet(false),
m_usernameHasBeenSet(false),
m_sshKeyNameHasBeenSet(false)
{
*this = jsonValue;
}
Instance& Instance::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("name"))
{
m_name = jsonValue.GetString("name");
m_nameHasBeenSet = true;
}
if(jsonValue.ValueExists("arn"))
{
m_arn = jsonValue.GetString("arn");
m_arnHasBeenSet = true;
}
if(jsonValue.ValueExists("supportCode"))
{
m_supportCode = jsonValue.GetString("supportCode");
m_supportCodeHasBeenSet = true;
}
if(jsonValue.ValueExists("createdAt"))
{
m_createdAt = jsonValue.GetDouble("createdAt");
m_createdAtHasBeenSet = true;
}
if(jsonValue.ValueExists("location"))
{
m_location = jsonValue.GetObject("location");
m_locationHasBeenSet = true;
}
if(jsonValue.ValueExists("resourceType"))
{
m_resourceType = ResourceTypeMapper::GetResourceTypeForName(jsonValue.GetString("resourceType"));
m_resourceTypeHasBeenSet = true;
}
if(jsonValue.ValueExists("blueprintId"))
{
m_blueprintId = jsonValue.GetString("blueprintId");
m_blueprintIdHasBeenSet = true;
}
if(jsonValue.ValueExists("blueprintName"))
{
m_blueprintName = jsonValue.GetString("blueprintName");
m_blueprintNameHasBeenSet = true;
}
if(jsonValue.ValueExists("bundleId"))
{
m_bundleId = jsonValue.GetString("bundleId");
m_bundleIdHasBeenSet = true;
}
if(jsonValue.ValueExists("isStaticIp"))
{
m_isStaticIp = jsonValue.GetBool("isStaticIp");
m_isStaticIpHasBeenSet = true;
}
if(jsonValue.ValueExists("privateIpAddress"))
{
m_privateIpAddress = jsonValue.GetString("privateIpAddress");
m_privateIpAddressHasBeenSet = true;
}
if(jsonValue.ValueExists("publicIpAddress"))
{
m_publicIpAddress = jsonValue.GetString("publicIpAddress");
m_publicIpAddressHasBeenSet = true;
}
if(jsonValue.ValueExists("ipv6Address"))
{
m_ipv6Address = jsonValue.GetString("ipv6Address");
m_ipv6AddressHasBeenSet = true;
}
if(jsonValue.ValueExists("hardware"))
{
m_hardware = jsonValue.GetObject("hardware");
m_hardwareHasBeenSet = true;
}
if(jsonValue.ValueExists("networking"))
{
m_networking = jsonValue.GetObject("networking");
m_networkingHasBeenSet = true;
}
if(jsonValue.ValueExists("state"))
{
m_state = jsonValue.GetObject("state");
m_stateHasBeenSet = true;
}
if(jsonValue.ValueExists("username"))
{
m_username = jsonValue.GetString("username");
m_usernameHasBeenSet = true;
}
if(jsonValue.ValueExists("sshKeyName"))
{
m_sshKeyName = jsonValue.GetString("sshKeyName");
m_sshKeyNameHasBeenSet = true;
}
return *this;
}
JsonValue Instance::Jsonize() const
{
JsonValue payload;
if(m_nameHasBeenSet)
{
payload.WithString("name", m_name);
}
if(m_arnHasBeenSet)
{
payload.WithString("arn", m_arn);
}
if(m_supportCodeHasBeenSet)
{
payload.WithString("supportCode", m_supportCode);
}
if(m_createdAtHasBeenSet)
{
payload.WithDouble("createdAt", m_createdAt.SecondsWithMSPrecision());
}
if(m_locationHasBeenSet)
{
payload.WithObject("location", m_location.Jsonize());
}
if(m_resourceTypeHasBeenSet)
{
payload.WithString("resourceType", ResourceTypeMapper::GetNameForResourceType(m_resourceType));
}
if(m_blueprintIdHasBeenSet)
{
payload.WithString("blueprintId", m_blueprintId);
}
if(m_blueprintNameHasBeenSet)
{
payload.WithString("blueprintName", m_blueprintName);
}
if(m_bundleIdHasBeenSet)
{
payload.WithString("bundleId", m_bundleId);
}
if(m_isStaticIpHasBeenSet)
{
payload.WithBool("isStaticIp", m_isStaticIp);
}
if(m_privateIpAddressHasBeenSet)
{
payload.WithString("privateIpAddress", m_privateIpAddress);
}
if(m_publicIpAddressHasBeenSet)
{
payload.WithString("publicIpAddress", m_publicIpAddress);
}
if(m_ipv6AddressHasBeenSet)
{
payload.WithString("ipv6Address", m_ipv6Address);
}
if(m_hardwareHasBeenSet)
{
payload.WithObject("hardware", m_hardware.Jsonize());
}
if(m_networkingHasBeenSet)
{
payload.WithObject("networking", m_networking.Jsonize());
}
if(m_stateHasBeenSet)
{
payload.WithObject("state", m_state.Jsonize());
}
if(m_usernameHasBeenSet)
{
payload.WithString("username", m_username);
}
if(m_sshKeyNameHasBeenSet)
{
payload.WithString("sshKeyName", m_sshKeyName);
}
return payload;
}
} // namespace Model
} // namespace Lightsail
} // namespace Aws
| 20.633028 | 101 | 0.718097 | [
"model"
] |
29b5f6708b9c5c448c31fa8c6bb7d5ff130c3da2 | 195 | cpp | C++ | src/gitwrapper/tag.cpp | SiliconSloth/Metro | 4111984922f0402dee6ef5d5b099a814c267a46a | [
"MIT"
] | 1 | 2020-04-10T21:07:24.000Z | 2020-04-10T21:07:24.000Z | src/gitwrapper/tag.cpp | SiliconSloth/Metro | 4111984922f0402dee6ef5d5b099a814c267a46a | [
"MIT"
] | 58 | 2019-09-03T16:24:03.000Z | 2020-07-01T12:52:09.000Z | src/gitwrapper/tag.cpp | SiliconSloth/Metro | 4111984922f0402dee6ef5d5b099a814c267a46a | [
"MIT"
] | 1 | 2019-11-01T00:49:37.000Z | 2019-11-01T00:49:37.000Z | namespace git {
Object Tag::target() const {
git_object *object;
int err = git_tag_target(&object, tag.get());
check_error(err);
return Object(object);
}
} | 24.375 | 53 | 0.574359 | [
"object"
] |
29b8a85a166de10f94e311d0886ef5cb22173896 | 8,824 | hpp | C++ | include/strategies/market_maker.hpp | Kautenja/CBOE-emulator | b4544cf61b938f2db98df107371954b8fdda130f | [
"MIT"
] | null | null | null | include/strategies/market_maker.hpp | Kautenja/CBOE-emulator | b4544cf61b938f2db98df107371954b8fdda130f | [
"MIT"
] | null | null | null | include/strategies/market_maker.hpp | Kautenja/CBOE-emulator | b4544cf61b938f2db98df107371954b8fdda130f | [
"MIT"
] | null | null | null | // A market maker trading agent.
// Copyright 2020 Christian Kauten
//
// Author: Christian Kauten (kautenja@auburn.edu)
//
// 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 3 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, see <http://www.gnu.org/licenses/>.
//
// Reference: High frequency trading strategies, market fragility and price
// spikes: an agent based model perspective
// Reference: An Agent-Based Model for Market Impact
//
#ifndef STRATEGIES_MARKET_MAKER_HPP
#define STRATEGIES_MARKET_MAKER_HPP
#include "data_feed/receiver.hpp"
#include "order_entry/client.hpp"
#include "maths/probability.hpp"
#include "maths/exponential_moving_average.hpp"
#include <nlohmann/json.hpp>
#include <atomic>
#include <iostream>
/// Direct market access trading strategies.
namespace Strategies {
/// @brief The market maker strategy logic.
/// @details
/// \image html market-maker/market-maker.svg "Market Maker Agent Algorithm"
/// \image latex market-maker/market-maker.pdf "Market Maker Agent Algorithm"
///
class MarketMaker {
private:
/// a type for the receiver using this class as an event handler
typedef DataFeed::Receiver<MarketMaker> DataFeedReceiver;
/// the receiver for rebuilding the instrument's book
DataFeedReceiver receiver;
/// the client for managing orders on the market
OrderEntry::Client client;
/// the timer for waiting
asio::steady_timer timer;
/// the amount of time to sleep between actions
uint32_t sleep_time;
/// the probability of running the strategy when acting
float P_act;
/// a flag determining if the strategy is running
std::atomic<bool> is_running;
/// the minimal order size to sample
OrderEntry::Quantity minimum_size;
/// the maximal order size to sample
OrderEntry::Quantity maximum_size;
/// the number of shares to hedge with
OrderEntry::Quantity hedge_size;
/// the decision boundary for when to place an order
double decision_boundary;
/// the exponential moving average of trade side
Maths::ExponentialMovingAverage<double> trade_side;
/// @brief start the strategy
inline void start_strategy() {
timer.expires_after(std::chrono::milliseconds(sleep_time));
timer.async_wait([this](const std::error_code& error) {
if (error) { // TODO: handle error code
std::cout << "MarketMaker::start_strategy - " << error << std::endl;
return;
}
if (Maths::Probability::boolean(P_act)) do_strategy();
start_strategy();
});
}
/// @brief do the strategy.
void do_strategy() {
if (client.has_active_order()) // cancel existing orders
client.send<OrderEntry::Messages::PurgeRequest>();
// compare the average to the decision boundary
if (trade_side.get_average() > decision_boundary) { // buy order likely
// place sell
client.send<OrderEntry::Messages::OrderRequest>(
receiver.get_book().last_best_sell(),
Maths::Probability::uniform_int(minimum_size, maximum_size),
OrderEntry::Side::Sell
);
// hedge buy
client.send<OrderEntry::Messages::OrderRequest>(
receiver.get_book().last_best_buy(),
hedge_size,
OrderEntry::Side::Buy
);
} else if (trade_side.get_average() < -decision_boundary) { // sell order likely
// place buy
client.send<OrderEntry::Messages::OrderRequest>(
receiver.get_book().last_best_buy(),
Maths::Probability::uniform_int(minimum_size, maximum_size),
OrderEntry::Side::Buy
);
// hedge sell
client.send<OrderEntry::Messages::OrderRequest>(
receiver.get_book().last_best_sell(),
hedge_size,
OrderEntry::Side::Sell
);
}
}
public:
/// @brief Initialize the strategy.
///
/// @param feed_context the IO context to create the feed with
/// @param context the IO context to create the strategy with
/// @param options the JSON object with agent-dependent options
///
MarketMaker(
asio::io_context& feed_context,
asio::io_context& context,
nlohmann::json options
) :
receiver(
feed_context,
asio::ip::make_address(options["data_feed"]["listen"].get<std::string>()),
asio::ip::make_address(options["data_feed"]["group"].get<std::string>()),
options["data_feed"]["port"].get<uint16_t>(),
*this
),
client(
context,
options["order_entry"]["host"].get<std::string>(),
std::to_string(options["order_entry"]["port"].get<uint16_t>())
),
timer(context),
sleep_time(options["strategy"]["sleep_time"].get<uint32_t>()),
P_act(options["strategy"]["P_act"].get<double>()),
is_running(false),
minimum_size(options["strategy"]["minimum_size"].get<OrderEntry::Quantity>()),
maximum_size(options["strategy"]["maximum_size"].get<OrderEntry::Quantity>()),
hedge_size(options["strategy"]["hedge_size"].get<OrderEntry::Quantity>()),
decision_boundary(options["strategy"]["decision_boundary"].get<double>()),
trade_side(options["strategy"]["weight"].get<double>(), options["strategy"]["average"].get<double>()) {
// login to the order entry client
auto username = OrderEntry::make_username(options["order_entry"]["username"].get<std::string>());
auto password = OrderEntry::make_password(options["order_entry"]["password"].get<std::string>());
client.send<OrderEntry::Messages::LoginRequest>(username, password);
}
/// @brief Handle a start of session message.
///
/// @param receiver the receiver that is handling the message
/// @param message the message to handle
///
inline void did_receive(DataFeedReceiver* receiver, const DataFeed::Messages::StartOfSession& message) {
if (is_running) {
std::cerr << "received start of session when already running" << std::endl;
return;
}
// clear the average trade direction
trade_side.reset(Maths::Probability::uniform_real(-1.0, 1.0));
// start the strategy
start_strategy();
// set the running flag to true
is_running = true;
}
/// @brief Handle an end of session message.
///
/// @param receiver the receiver that is handling the message
/// @param message the message to handle
///
inline void did_receive(DataFeedReceiver* receiver, const DataFeed::Messages::EndOfSession& message) {
if (not is_running) {
std::cerr << "received end of session when not running" << std::endl;
return;
}
// stop the strategy
timer.cancel();
is_running = false;
}
/// @brief Handle a clear book message.
///
/// @param receiver the receiver that is handling the message
/// @param message the message to handle
///
inline void did_receive(DataFeedReceiver* receiver, const DataFeed::Messages::Clear& message) { }
/// @brief Handle an add order message.
///
/// @param receiver the receiver that is handling the message
/// @param message the message to handle
///
inline void did_receive(DataFeedReceiver* receiver, const DataFeed::Messages::AddOrder& message) { }
/// @brief Handle a delete order message.
///
/// @param receiver the receiver that is handling the message
/// @param message the message to handle
///
inline void did_receive(DataFeedReceiver* receiver, const DataFeed::Messages::DeleteOrder& message) { }
/// @brief Handle a trade message.
///
/// @param receiver the receiver that is handling the message
/// @param message the message to handle
///
inline void did_receive(DataFeedReceiver* receiver, const DataFeed::Messages::Trade& message) {
trade_side.process(DataFeed::side_to_double(message.side));
}
};
} // namespace Strategies
#endif // STRATEGIES_MARKET_MAKER_HPP
| 39.569507 | 111 | 0.643472 | [
"object",
"model"
] |
29c450d6ae29cb422758319fc3847c910e6f657d | 13,819 | cpp | C++ | src/mongo/db/query/index_tag.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/query/index_tag.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/query/index_tag.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2018-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/db/query/index_tag.h"
#include "mongo/db/matcher/expression_array.h"
#include "mongo/db/matcher/expression_tree.h"
#include "mongo/db/query/indexability.h"
#include "mongo/stdx/unordered_map.h"
#include <algorithm>
#include <limits>
namespace mongo {
using TagType = MatchExpression::TagData::Type;
namespace {
// Compares 'lhs' for 'rhs', using the tag-based ordering expected by the access planner. Returns a
// negative number if 'lhs' is smaller than 'rhs', 0 if they are equal, and 1 if 'lhs' is larger.
int tagComparison(const MatchExpression* lhs, const MatchExpression* rhs) {
IndexTag* lhsTag = static_cast<IndexTag*>(lhs->getTag());
size_t lhsValue = (nullptr == lhsTag) ? IndexTag::kNoIndex : lhsTag->index;
size_t lhsPos = (nullptr == lhsTag) ? IndexTag::kNoIndex : lhsTag->pos;
IndexTag* rhsTag = static_cast<IndexTag*>(rhs->getTag());
size_t rhsValue = (nullptr == rhsTag) ? IndexTag::kNoIndex : rhsTag->index;
size_t rhsPos = (nullptr == rhsTag) ? IndexTag::kNoIndex : rhsTag->pos;
// First, order on indices.
if (lhsValue != rhsValue) {
// This relies on kNoIndex being larger than every other possible index.
return lhsValue < rhsValue ? -1 : 1;
}
// Next, order so that if there's a GEO_NEAR it's first.
if (MatchExpression::GEO_NEAR == lhs->matchType()) {
return -1;
} else if (MatchExpression::GEO_NEAR == rhs->matchType()) {
return 1;
}
// Ditto text.
if (MatchExpression::TEXT == lhs->matchType()) {
return -1;
} else if (MatchExpression::TEXT == rhs->matchType()) {
return 1;
}
// Next, order so that the first field of a compound index appears first.
if (lhsPos != rhsPos) {
return lhsPos < rhsPos ? -1 : 1;
}
// Next, order on fields.
int cmp = lhs->path().compare(rhs->path());
if (0 != cmp) {
return cmp;
}
// Next, order on expression type.
if (lhs->matchType() != rhs->matchType()) {
return lhs->matchType() < rhs->matchType() ? -1 : 1;
}
// The 'lhs' and 'rhs' are equal. Break ties by comparing child nodes.
const size_t numChildren = std::min(lhs->numChildren(), rhs->numChildren());
for (size_t childIdx = 0; childIdx < numChildren; ++childIdx) {
int childCompare = tagComparison(lhs->getChild(childIdx), rhs->getChild(childIdx));
if (childCompare != 0) {
return childCompare;
}
}
// If all else is equal, sort whichever node has fewer children first.
if (lhs->numChildren() != rhs->numChildren()) {
return lhs->numChildren() < rhs->numChildren() ? -1 : 1;
}
return 0;
}
// Sorts the tree using its IndexTag(s). Nodes that use the same index will sort so that they are
// adjacent to one another.
void sortUsingTags(MatchExpression* tree) {
for (size_t i = 0; i < tree->numChildren(); ++i) {
sortUsingTags(tree->getChild(i));
}
if (auto&& children = tree->getChildVector())
std::stable_sort(children->begin(), children->end(), [](auto&& lhs, auto&& rhs) {
return tagComparison(lhs.get(), rhs.get()) < 0;
});
}
// Attaches 'node' to 'target'. If 'target' is an AND, adds 'node' as a child of 'target'.
// Otherwise, creates an AND that is a child of 'targetParent' at position 'targetPosition', and
// adds 'target' and 'node' as its children. Tags 'node' with 'tagData'.
void attachNode(MatchExpression* node,
MatchExpression* target,
OrMatchExpression* targetParent,
size_t targetPosition,
std::unique_ptr<MatchExpression::TagData> tagData) {
auto clone = node->shallowClone();
if (clone->matchType() == MatchExpression::NOT) {
IndexTag* indexTag = static_cast<IndexTag*>(tagData.get());
clone->setTag(new IndexTag(indexTag->index));
clone->getChild(0)->setTag(tagData.release());
} else {
clone->setTag(tagData.release());
}
if (MatchExpression::AND == target->matchType()) {
auto andNode = static_cast<AndMatchExpression*>(target);
andNode->add(std::move(clone));
} else {
auto andNode = std::make_unique<AndMatchExpression>();
auto indexTag = static_cast<IndexTag*>(clone->getTag());
andNode->setTag(new IndexTag(indexTag->index));
andNode->add(std::move((*targetParent->getChildVector())[targetPosition]));
andNode->add(std::move(clone));
targetParent->getChildVector()->operator[](targetPosition) = std::move(andNode);
}
}
// Partitions destinations according to the first element of the destination's route. Trims the
// first element off of each destination's route.
stdx::unordered_map<size_t, std::vector<OrPushdownTag::Destination>> partitionChildDestinations(
std::vector<OrPushdownTag::Destination> destinations) {
stdx::unordered_map<size_t, std::vector<OrPushdownTag::Destination>> childDestinations;
for (auto&& dest : destinations) {
invariant(!dest.route.empty());
auto index = dest.route.front();
dest.route.pop_front();
childDestinations[index].push_back(std::move(dest));
}
return childDestinations;
}
// Finds the node within 'tree' that is an indexed OR, if one exists.
MatchExpression* getIndexedOr(MatchExpression* tree) {
if (MatchExpression::OR == tree->matchType() && tree->getTag()) {
return tree;
}
for (size_t i = 0; i < tree->numChildren(); ++i) {
if (auto indexedOrChild = getIndexedOr(tree->getChild(i))) {
return indexedOrChild;
}
}
return nullptr;
}
// Pushes down 'node' along the routes in 'target' specified in 'destinations'. Each value in the
// route is the index of a child in an indexed OR. Returns true if 'node' is moved to every indexed
// descendant of 'target'.
bool pushdownNode(MatchExpression* node,
MatchExpression* target,
std::vector<OrPushdownTag::Destination> destinations) {
if (MatchExpression::OR == target->matchType()) {
OrMatchExpression* orNode = static_cast<OrMatchExpression*>(target);
bool moveToAllChildren = true;
auto childDestinationsMap = partitionChildDestinations(std::move(destinations));
for (size_t i = 0; i < orNode->numChildren(); ++i) {
auto childDestinations = childDestinationsMap.find(i);
if (childDestinations == childDestinationsMap.end()) {
// This child was not specified by any route in 'destinations'.
moveToAllChildren = false;
} else {
invariant(!childDestinations->second.empty());
if (childDestinations->second[0].route.empty()) {
// There should only be one destination if we have reached the end of a route.
// Otherwise, we started with duplicate routes.
invariant(childDestinations->second.size() == 1);
// We have reached the position at which to attach 'node'.
attachNode(node,
orNode->getChild(i),
orNode,
i,
std::move(childDestinations->second[0].tagData));
} else {
// This child was specified by a non-trivial route in destinations, so we recur.
moveToAllChildren = pushdownNode(node,
orNode->getChild(i),
std::move(childDestinations->second)) &&
moveToAllChildren;
}
}
}
return moveToAllChildren;
}
if (MatchExpression::AND == target->matchType()) {
auto indexedOr = getIndexedOr(target);
invariant(indexedOr);
return pushdownNode(node, indexedOr, std::move(destinations));
}
MONGO_UNREACHABLE_TASSERT(4457014);
}
// Populates 'out' with all descendants of 'node' that have OrPushdownTags, assuming the initial
// input is an ELEM_MATCH_OBJECT.
void getElemMatchOrPushdownDescendants(MatchExpression* node, std::vector<MatchExpression*>* out) {
if (node->getTag() && node->getTag()->getType() == TagType::OrPushdownTag) {
out->push_back(node);
} else if (node->matchType() == MatchExpression::ELEM_MATCH_OBJECT ||
node->matchType() == MatchExpression::AND) {
for (size_t i = 0; i < node->numChildren(); ++i) {
getElemMatchOrPushdownDescendants(node->getChild(i), out);
}
} else if (node->matchType() == MatchExpression::NOT) {
// The immediate child of NOT may be tagged, but there should be no tags deeper than this.
auto* childNode = node->getChild(0);
if (childNode->getTag() && childNode->getTag()->getType() == TagType::OrPushdownTag) {
out->push_back(node);
}
}
}
// Attempts to push the given node down into the 'indexedOr' subtree. Returns true if the predicate
// can subsequently be trimmed from the MatchExpression tree, false otherwise.
bool processOrPushdownNode(MatchExpression* node, MatchExpression* indexedOr) {
// If the node is a negation, then its child is the predicate node that may be tagged.
auto* predNode = node->matchType() == MatchExpression::NOT ? node->getChild(0) : node;
// If the predicate node is not tagged for pushdown, return false immediately.
if (!predNode->getTag() || predNode->getTag()->getType() != TagType::OrPushdownTag) {
return false;
}
invariant(indexedOr);
// Predicate node is tagged for pushdown. Extract its route through the $or and its index tag.
auto* orPushdownTag = static_cast<OrPushdownTag*>(predNode->getTag());
auto destinations = orPushdownTag->releaseDestinations();
auto indexTag = orPushdownTag->releaseIndexTag();
predNode->setTag(nullptr);
// Attempt to push the node into the indexedOr, then re-set its tag to the indexTag.
const bool pushedDown = pushdownNode(node, indexedOr, std::move(destinations));
predNode->setTag(indexTag.release());
// Return true if we can trim the predicate. We could trim the node even if it had an index tag
// for this position, but that could make the index tagging of the tree wrong.
return pushedDown && !predNode->getTag();
}
// Finds all the nodes in the tree with OrPushdownTags and copies them to the Destinations specified
// in the OrPushdownTag, tagging them with the TagData in the Destination. Removes the node from its
// current location if possible.
void resolveOrPushdowns(MatchExpression* tree) {
if (tree->numChildren() == 0) {
return;
}
if (MatchExpression::AND == tree->matchType()) {
AndMatchExpression* andNode = static_cast<AndMatchExpression*>(tree);
MatchExpression* indexedOr = getIndexedOr(andNode);
for (size_t i = 0; i < andNode->numChildren(); ++i) {
auto child = andNode->getChild(i);
// For ELEM_MATCH_OBJECT, we push down all tagged descendants. However, we cannot trim
// any of these predicates, since the $elemMatch filter must be applied in its entirety.
if (child->matchType() == MatchExpression::ELEM_MATCH_OBJECT) {
std::vector<MatchExpression*> orPushdownDescendants;
getElemMatchOrPushdownDescendants(child, &orPushdownDescendants);
for (auto descendant : orPushdownDescendants) {
static_cast<void>(processOrPushdownNode(descendant, indexedOr));
}
} else if (processOrPushdownNode(child, indexedOr)) {
// The indexed $or can completely satisfy the child predicate, so we trim it.
auto ownedChild = andNode->removeChild(i);
--i;
}
}
}
for (size_t i = 0; i < tree->numChildren(); ++i) {
resolveOrPushdowns(tree->getChild(i));
}
}
} // namespace
const size_t IndexTag::kNoIndex = std::numeric_limits<size_t>::max();
void prepareForAccessPlanning(MatchExpression* tree) {
resolveOrPushdowns(tree);
sortUsingTags(tree);
}
} // namespace mongo
| 42.916149 | 100 | 0.64158 | [
"vector"
] |
29c51c97bb034b97601c56e65485d3f97efe96c8 | 16,304 | cpp | C++ | Lib/LLVMJIT/EmitCore.cpp | faasm/WAVM | 2434b3b170404b63afbd2103eecbf510dd1665f4 | [
"BSD-3-Clause"
] | null | null | null | Lib/LLVMJIT/EmitCore.cpp | faasm/WAVM | 2434b3b170404b63afbd2103eecbf510dd1665f4 | [
"BSD-3-Clause"
] | null | null | null | Lib/LLVMJIT/EmitCore.cpp | faasm/WAVM | 2434b3b170404b63afbd2103eecbf510dd1665f4 | [
"BSD-3-Clause"
] | 2 | 2021-08-23T14:57:37.000Z | 2022-03-01T16:46:46.000Z | #include <memory>
#include <vector>
#include "EmitFunctionContext.h"
#include "EmitModuleContext.h"
#include "LLVMJITPrivate.h"
#include "WAVM/IR/Module.h"
#include "WAVM/IR/Operators.h"
#include "WAVM/IR/Types.h"
#include "WAVM/Inline/Assert.h"
#include "WAVM/Inline/BasicTypes.h"
#include "WAVM/RuntimeABI/RuntimeABI.h"
PUSH_DISABLE_WARNINGS_FOR_LLVM_HEADERS
#include <llvm/ADT/ArrayRef.h>
#include <llvm/ADT/SmallVector.h>
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/Constant.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/DerivedTypes.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/Instructions.h>
POP_DISABLE_WARNINGS_FOR_LLVM_HEADERS
namespace llvm {
class Value;
}
using namespace WAVM;
using namespace WAVM::IR;
using namespace WAVM::LLVMJIT;
using namespace WAVM::Runtime;
void EmitFunctionContext::block(ControlStructureImm imm)
{
FunctionType blockType = resolveBlockType(irModule, imm.type);
// Create an end block+phi for the block result.
auto endBlock = llvm::BasicBlock::Create(llvmContext, "blockEnd", function);
auto endPHIs = createPHIs(endBlock, blockType.results());
// Pop the block arguments.
llvm::Value** blockArgs
= (llvm::Value**)alloca(sizeof(llvm::Value*) * blockType.params().size());
popMultiple(blockArgs, blockType.params().size());
// Push a control context that ends at the end block/phi.
pushControlStack(ControlContext::Type::block, blockType.results(), endBlock, endPHIs);
// Push a branch target for the end block/phi.
pushBranchTarget(blockType.results(), endBlock, endPHIs);
// Repush the block arguments.
pushMultiple(blockArgs, blockType.params().size());
}
void EmitFunctionContext::loop(ControlStructureImm imm)
{
FunctionType blockType = resolveBlockType(irModule, imm.type);
llvm::BasicBlock* loopEntryBlock = irBuilder.GetInsertBlock();
// Create a loop block, and an end block for the loop result.
auto loopBodyBlock = llvm::BasicBlock::Create(llvmContext, "loopBody", function);
auto endBlock = llvm::BasicBlock::Create(llvmContext, "loopEnd", function);
// Create PHIs for the loop's parameters, and PHIs for the loop result.
auto parameterPHIs = createPHIs(loopBodyBlock, blockType.params());
auto endPHIs = createPHIs(endBlock, blockType.results());
// Pop the initial values of the loop's parameters from the stack.
for(Iptr elementIndex = Iptr(blockType.params().size()) - 1; elementIndex >= 0; --elementIndex)
{ parameterPHIs[elementIndex]->addIncoming(coerceToCanonicalType(pop()), loopEntryBlock); }
// Branch to the loop body and switch the IR builder to emit there.
irBuilder.CreateBr(loopBodyBlock);
irBuilder.SetInsertPoint(loopBodyBlock);
// Push a control context that ends at the end block/phi.
pushControlStack(ControlContext::Type::loop, blockType.results(), endBlock, endPHIs);
// Push a branch target for the loop body start.
pushBranchTarget(blockType.params(), loopBodyBlock, parameterPHIs);
// Push the loop argument PHIs on the stack.
pushMultiple((llvm::Value**)parameterPHIs.data(), parameterPHIs.size());
}
void EmitFunctionContext::if_(ControlStructureImm imm)
{
FunctionType blockType = resolveBlockType(irModule, imm.type);
// Create a then block and else block for the if, and an end block+phi for the if result.
auto thenBlock = llvm::BasicBlock::Create(llvmContext, "ifThen", function);
auto elseBlock = llvm::BasicBlock::Create(llvmContext, "ifElse", function);
auto endBlock = llvm::BasicBlock::Create(llvmContext, "ifElseEnd", function);
auto endPHIs = createPHIs(endBlock, blockType.results());
// Pop the if condition from the operand stack.
auto condition = pop();
irBuilder.CreateCondBr(coerceI32ToBool(condition), thenBlock, elseBlock);
// Pop the arguments from the operand stack.
ValueVector args;
WAVM_ASSERT(stack.size() >= blockType.params().size());
args.resize(blockType.params().size());
popMultiple(args.data(), args.size());
// Switch the IR builder to emit the then block.
irBuilder.SetInsertPoint(thenBlock);
// Push an ifThen control context that ultimately ends at the end block/phi, but may be
// terminated by an else operator that changes the control context to the else block.
pushControlStack(
ControlContext::Type::ifThen, blockType.results(), endBlock, endPHIs, elseBlock, args);
// Push a branch target for the if end.
pushBranchTarget(blockType.results(), endBlock, endPHIs);
// Repush the if arguments on the stack.
pushMultiple(args.data(), args.size());
}
void EmitFunctionContext::else_(NoImm imm)
{
WAVM_ASSERT(controlStack.size());
ControlContext& currentContext = controlStack.back();
branchToEndOfControlContext();
// Switch the IR emitter to the else block.
WAVM_ASSERT(currentContext.elseBlock);
WAVM_ASSERT(currentContext.type == ControlContext::Type::ifThen);
currentContext.elseBlock->moveAfter(irBuilder.GetInsertBlock());
irBuilder.SetInsertPoint(currentContext.elseBlock);
// Push the if arguments back on the operand stack.
for(llvm::Value* argument : currentContext.elseArgs) { push(argument); }
// Change the top of the control stack to an else clause.
currentContext.type = ControlContext::Type::ifElse;
currentContext.isReachable = true;
currentContext.elseBlock = nullptr;
}
void EmitFunctionContext::end(NoImm)
{
WAVM_ASSERT(controlStack.size());
ControlContext& currentContext = controlStack.back();
if(currentContext.type == ControlContext::Type::try_) { endTryWithoutCatch(); }
else if(currentContext.type == ControlContext::Type::catch_)
{
endTryCatch();
}
branchToEndOfControlContext();
// If this is the end of an if without an else clause, create a dummy else clause.
if(currentContext.elseBlock)
{
currentContext.elseBlock->moveAfter(irBuilder.GetInsertBlock());
irBuilder.SetInsertPoint(currentContext.elseBlock);
// Add the if arguments to the end PHIs as if they just passed through the absent else
// block.
WAVM_ASSERT(currentContext.elseArgs.size() == currentContext.endPHIs.size());
for(Uptr argIndex = 0; argIndex < currentContext.elseArgs.size(); ++argIndex)
{
currentContext.endPHIs[argIndex]->addIncoming(
coerceToCanonicalType(currentContext.elseArgs[argIndex]), currentContext.elseBlock);
}
irBuilder.CreateBr(currentContext.endBlock);
}
// Switch the IR emitter to the end block.
currentContext.endBlock->moveAfter(irBuilder.GetInsertBlock());
irBuilder.SetInsertPoint(currentContext.endBlock);
if(currentContext.endPHIs.size())
{
// If the control context yields results, take the PHIs that merges all the control flow to
// the end and push their values onto the operand stack.
WAVM_ASSERT(currentContext.endPHIs.size() == currentContext.resultTypes.size());
for(Uptr elementIndex = 0; elementIndex < currentContext.endPHIs.size(); ++elementIndex)
{
if(currentContext.endPHIs[elementIndex]->getNumIncomingValues())
{ push(currentContext.endPHIs[elementIndex]); }
else
{
// If there weren't any incoming values for the end PHI, remove it and push
// a dummy value.
currentContext.endPHIs[elementIndex]->eraseFromParent();
push(
llvmContext.typedZeroConstants[(Uptr)currentContext.resultTypes[elementIndex]]);
}
}
}
// Pop and branch targets introduced by this control context.
WAVM_ASSERT(currentContext.outerBranchTargetStackSize <= branchTargetStack.size());
branchTargetStack.resize(currentContext.outerBranchTargetStackSize);
// Pop this control context.
controlStack.pop_back();
}
void EmitFunctionContext::br_if(BranchImm imm)
{
// Pop the condition from operand stack.
auto condition = pop();
BranchTarget& target = getBranchTargetByDepth(imm.targetDepth);
WAVM_ASSERT(target.params.size() == target.phis.size());
for(Uptr argIndex = 0; argIndex < target.params.size(); ++argIndex)
{
// Take the branch target operands from the stack (without popping them) and add them to the
// target's incoming value PHIs.
llvm::Value* argument = getValueFromTop(target.params.size() - argIndex - 1);
target.phis[argIndex]->addIncoming(coerceToCanonicalType(argument),
irBuilder.GetInsertBlock());
}
// Create a new basic block for the case where the branch is not taken.
auto falseBlock = llvm::BasicBlock::Create(llvmContext, "br_ifElse", function);
// Emit a conditional branch to either the falseBlock or the target block.
irBuilder.CreateCondBr(coerceI32ToBool(condition), target.block, falseBlock);
// Resume emitting instructions in the falseBlock.
irBuilder.SetInsertPoint(falseBlock);
}
void EmitFunctionContext::br(BranchImm imm)
{
BranchTarget& target = getBranchTargetByDepth(imm.targetDepth);
WAVM_ASSERT(target.params.size() == target.phis.size());
// Pop the branch target operands from the stack and add them to the target's incoming value
// PHIs.
for(Iptr argIndex = Iptr(target.params.size()) - 1; argIndex >= 0; --argIndex)
{
llvm::Value* argument = pop();
target.phis[argIndex]->addIncoming(coerceToCanonicalType(argument),
irBuilder.GetInsertBlock());
}
// Branch to the target block.
irBuilder.CreateBr(target.block);
enterUnreachable();
}
void EmitFunctionContext::br_table(BranchTableImm imm)
{
// Pop the table index from the operand stack.
auto index = pop();
// Look up the default branch target, and assume its argument type applies to all targets. (this
// is guaranteed by the validator)
BranchTarget& defaultTarget = getBranchTargetByDepth(imm.defaultTargetDepth);
// Pop the branch arguments from the stack.
const Uptr numArgs = defaultTarget.params.size();
llvm::Value** args = (llvm::Value**)alloca(sizeof(llvm::Value*) * numArgs);
popMultiple(args, numArgs);
// Add the branch arguments to the default target's parameter PHI nodes.
for(Uptr argIndex = 0; argIndex < numArgs; ++argIndex)
{
defaultTarget.phis[argIndex]->addIncoming(coerceToCanonicalType(args[argIndex]),
irBuilder.GetInsertBlock());
}
// Create a LLVM switch instruction.
WAVM_ASSERT(imm.branchTableIndex < functionDef.branchTables.size());
const std::vector<Uptr>& targetDepths = functionDef.branchTables[imm.branchTableIndex];
auto llvmSwitch
= irBuilder.CreateSwitch(index, defaultTarget.block, (unsigned int)targetDepths.size());
for(Uptr targetIndex = 0; targetIndex < targetDepths.size(); ++targetIndex)
{
BranchTarget& target = getBranchTargetByDepth(targetDepths[targetIndex]);
// Add this target to the switch instruction.
WAVM_ERROR_UNLESS(targetIndex < UINT32_MAX);
llvmSwitch->addCase(emitLiteral(llvmContext, (U32)targetIndex), target.block);
// Add the branch arguments to the PHI nodes for the branch target's parameters.
WAVM_ASSERT(target.phis.size() == numArgs);
for(Uptr argIndex = 0; argIndex < numArgs; ++argIndex)
{
target.phis[argIndex]->addIncoming(coerceToCanonicalType(args[argIndex]),
irBuilder.GetInsertBlock());
}
}
enterUnreachable();
}
void EmitFunctionContext::return_(NoImm)
{
// Pop the branch target operands from the stack and add them to the target's incoming value
// PHIs.
for(Iptr argIndex = functionType.results().size() - 1; argIndex >= 0; --argIndex)
{
llvm::Value* argument = pop();
controlStack[0].endPHIs[argIndex]->addIncoming(coerceToCanonicalType(argument),
irBuilder.GetInsertBlock());
}
// Branch to the return block.
irBuilder.CreateBr(controlStack[0].endBlock);
enterUnreachable();
}
void EmitFunctionContext::unreachable(NoImm)
{
// Call an intrinsic that causes a trap, and insert the LLVM unreachable terminator.
emitRuntimeIntrinsic(
"unreachableTrap", FunctionType({}, {}, IR::CallingConvention::intrinsic), {});
irBuilder.CreateUnreachable();
enterUnreachable();
}
//
// Call operators
//
void EmitFunctionContext::call(FunctionImm imm)
{
WAVM_ASSERT(imm.functionIndex < moduleContext.functions.size());
WAVM_ASSERT(imm.functionIndex < irModule.functions.size());
llvm::Value* callee = moduleContext.functions[imm.functionIndex];
FunctionType calleeType = irModule.types[irModule.functions.getType(imm.functionIndex).index];
// Pop the call arguments from the operand stack.
const Uptr numArguments = calleeType.params().size();
auto llvmArgs = (llvm::Value**)alloca(sizeof(llvm::Value*) * numArguments);
popMultiple(llvmArgs, numArguments);
// Coerce the arguments to their canonical type.
for(Uptr argIndex = 0; argIndex < numArguments; ++argIndex)
{ llvmArgs[argIndex] = coerceToCanonicalType(llvmArgs[argIndex]); }
// Call the function.
ValueVector results = emitCallOrInvoke(callee,
llvm::ArrayRef<llvm::Value*>(llvmArgs, numArguments),
calleeType,
getInnermostUnwindToBlock());
// Push the results on the operand stack.
for(llvm::Value* result : results) { push(result); }
}
void EmitFunctionContext::call_indirect(CallIndirectImm imm)
{
WAVM_ASSERT(imm.type.index < irModule.types.size());
const FunctionType calleeType = irModule.types[imm.type.index];
// Compile the function index.
auto tableElementIndex = pop();
// Pop the call arguments from the operand stack.
const Uptr numArguments = calleeType.params().size();
auto llvmArgs = (llvm::Value**)alloca(sizeof(llvm::Value*) * numArguments);
popMultiple(llvmArgs, numArguments);
// Coerce the arguments to their canonical type.
for(Uptr argIndex = 0; argIndex < numArguments; ++argIndex)
{ llvmArgs[argIndex] = coerceToCanonicalType(llvmArgs[argIndex]); }
// Zero extend the function index to the pointer size.
auto functionIndexZExt = zext(tableElementIndex, llvmContext.iptrType);
auto tableBasePointer = loadFromUntypedPointer(
irBuilder.CreateInBoundsGEP(getCompartmentAddress(),
{moduleContext.tableOffsets[imm.tableIndex]}),
llvmContext.iptrType->getPointerTo(),
sizeof(Uptr));
// Load the funcref referenced by the table.
auto elementPointer = irBuilder.CreateInBoundsGEP(tableBasePointer, {functionIndexZExt});
llvm::LoadInst* biasedValueLoad = irBuilder.CreateLoad(elementPointer);
biasedValueLoad->setAtomic(llvm::AtomicOrdering::Acquire);
biasedValueLoad->setAlignment(LLVM_ALIGNMENT(sizeof(Uptr)));
auto runtimeFunction = irBuilder.CreateIntToPtr(
irBuilder.CreateAdd(biasedValueLoad, moduleContext.tableReferenceBias),
llvmContext.i8PtrType);
// 24/04/2019 - Some code in CPython is a bit sloppy in its casting of function pointers, so
// causes type mismatches at runtime. As a temporary hack I'm removing the type check on
// call_indirect in the generated code.
// auto elementTypeId = loadFromUntypedPointer(
// irBuilder.CreateInBoundsGEP(
// runtimeFunction,
// emitLiteral(llvmContext, Uptr(offsetof(Runtime::Function, encodedType)))),
// llvmContext.iptrType,
// sizeof(Uptr));
// auto calleeTypeId = moduleContext.typeIds[imm.type.index];
// If the function type doesn't match, trap.
//emitConditionalTrapIntrinsic(
// irBuilder.CreateICmpNE(calleeTypeId, elementTypeId),
// "callIndirectFail",
// FunctionType(TypeTuple(),
// TypeTuple({ValueType::i32,
// inferValueType<Uptr>(),
// ValueType::funcref,
// inferValueType<Uptr>()}),
// IR::CallingConvention::intrinsic),
// {tableElementIndex,
// getTableIdFromOffset(llvmContext, moduleContext.tableOffsets[imm.tableIndex]),
// irBuilder.CreatePointerCast(runtimeFunction, llvmContext.externrefType),
// calleeTypeId});
// Call the function loaded from the table.
auto functionPointer = irBuilder.CreatePointerCast(
irBuilder.CreateInBoundsGEP(
runtimeFunction, emitLiteral(llvmContext, Uptr(offsetof(Runtime::Function, code)))),
asLLVMType(llvmContext, calleeType)->getPointerTo());
ValueVector results = emitCallOrInvoke(functionPointer,
llvm::ArrayRef<llvm::Value*>(llvmArgs, numArguments),
calleeType,
getInnermostUnwindToBlock());
// Push the results on the operand stack.
for(llvm::Value* result : results) { push(result); }
}
void EmitFunctionContext::nop(IR::NoImm) {}
void EmitFunctionContext::drop(IR::NoImm) { stack.pop_back(); }
void EmitFunctionContext::select(IR::SelectImm)
{
auto condition = pop();
auto falseValue = coerceToCanonicalType(pop());
auto trueValue = coerceToCanonicalType(pop());
push(irBuilder.CreateSelect(coerceI32ToBool(condition), trueValue, falseValue));
}
| 37.223744 | 97 | 0.750797 | [
"vector"
] |
29c7bf92d1ec0d8304af03379c1c9bca1bde365a | 6,294 | hxx | C++ | opencascade/TDataXtd_Geometry.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/TDataXtd_Geometry.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/TDataXtd_Geometry.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | // Created on: 2009-04-06
// Created by: Sergey ZARITCHNY
// Copyright (c) 2009-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _TDataXtd_Geometry_HeaderFile
#define _TDataXtd_Geometry_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <TDataXtd_GeometryEnum.hxx>
#include <TDF_Attribute.hxx>
#include <Standard_Boolean.hxx>
#include <Standard_OStream.hxx>
class TDF_Label;
class TNaming_NamedShape;
class gp_Pnt;
class gp_Ax1;
class gp_Lin;
class gp_Circ;
class gp_Elips;
class gp_Pln;
class gp_Cylinder;
class Standard_GUID;
class TDF_Attribute;
class TDF_RelocationTable;
class TDataXtd_Geometry;
DEFINE_STANDARD_HANDLE(TDataXtd_Geometry, TDF_Attribute)
//! This class is used to model construction geometry.
//! The specific geometric construction of the
//! attribute is defined by an element of the
//! enumeration TDataXtd_GeometryEnum.
//! This attribute may also be used to qualify underlying
//! geometry of the associated NamedShape. for
//! Constructuion element by example.
class TDataXtd_Geometry : public TDF_Attribute
{
public:
//! API class methods
//! =================
//! Finds, or creates, a Geometry attribute defined by the label label.
//! The default type of geometry is the value
//! ANY_GEOM of the enumeration TDataXtd_GeometryEnum.
//! To specify another value of this enumeration, use
//! the function SetType.
Standard_EXPORT static Handle(TDataXtd_Geometry) Set (const TDF_Label& label);
//! Returns the label L used to define the type of
//! geometric construction for the geometry attribute.
Standard_EXPORT static TDataXtd_GeometryEnum Type (const TDF_Label& L);
//! Returns the topological attribute S used to define
//! the type of geometric construction for the geometry attribute.
Standard_EXPORT static TDataXtd_GeometryEnum Type (const Handle(TNaming_NamedShape)& S);
//! Returns the point attribute defined by the label L and the point G.
Standard_EXPORT static Standard_Boolean Point (const TDF_Label& L, gp_Pnt& G);
//! Returns the point attribute defined by the topological attribute S and the point G.
Standard_EXPORT static Standard_Boolean Point (const Handle(TNaming_NamedShape)& S, gp_Pnt& G);
//! Returns the axis attribute defined by the label L and the axis G.
Standard_EXPORT static Standard_Boolean Axis (const TDF_Label& L, gp_Ax1& G);
//! Returns the axis attribute defined by the topological attribute S and the axis G.
Standard_EXPORT static Standard_Boolean Axis (const Handle(TNaming_NamedShape)& S, gp_Ax1& G);
//! Returns the line attribute defined by the label L and the line G.
Standard_EXPORT static Standard_Boolean Line (const TDF_Label& L, gp_Lin& G);
//! Returns the line attribute defined by the topological attribute S and the line G.
Standard_EXPORT static Standard_Boolean Line (const Handle(TNaming_NamedShape)& S, gp_Lin& G);
//! Returns the circle attribute defined by the label L and the circle G.
Standard_EXPORT static Standard_Boolean Circle (const TDF_Label& L, gp_Circ& G);
//! Returns the circle attribute defined by the topological attribute S and the circle G.
Standard_EXPORT static Standard_Boolean Circle (const Handle(TNaming_NamedShape)& S, gp_Circ& G);
//! Returns the ellipse attribute defined by the label L and the ellipse G.
Standard_EXPORT static Standard_Boolean Ellipse (const TDF_Label& L, gp_Elips& G);
//! Returns the ellipse attribute defined by the
//! topological attribute S and the ellipse G.
Standard_EXPORT static Standard_Boolean Ellipse (const Handle(TNaming_NamedShape)& S, gp_Elips& G);
//! Returns the plane attribute defined by the label L and the plane G.
Standard_EXPORT static Standard_Boolean Plane (const TDF_Label& L, gp_Pln& G);
//! Returns the plane attribute defined by the
//! topological attribute S and the plane G.
Standard_EXPORT static Standard_Boolean Plane (const Handle(TNaming_NamedShape)& S, gp_Pln& G);
//! Returns the cylinder attribute defined by the label L and the cylinder G.
Standard_EXPORT static Standard_Boolean Cylinder (const TDF_Label& L, gp_Cylinder& G);
//! Returns the cylinder attribute defined by the
//! topological attribute S and the cylinder G.
Standard_EXPORT static Standard_Boolean Cylinder (const Handle(TNaming_NamedShape)& S, gp_Cylinder& G);
//! Returns the GUID for geometry attributes.
Standard_EXPORT static const Standard_GUID& GetID();
//! This and the next methods are used to retrieve underlying geometry of the NamedShape,
//! even if no Geometry Attribute is associated.
//! if not found or not compliant geometry return False.
Standard_EXPORT TDataXtd_Geometry();
//! Returns the type of geometric construction T of this attribute.
//! T will be a value of the enumeration TDataXtd_GeometryEnum.
Standard_EXPORT void SetType (const TDataXtd_GeometryEnum T);
//! Returns the type of geometric construction.
Standard_EXPORT TDataXtd_GeometryEnum GetType() const;
Standard_EXPORT const Standard_GUID& ID() const Standard_OVERRIDE;
Standard_EXPORT void Restore (const Handle(TDF_Attribute)& with) Standard_OVERRIDE;
Standard_EXPORT Handle(TDF_Attribute) NewEmpty() const Standard_OVERRIDE;
Standard_EXPORT void Paste (const Handle(TDF_Attribute)& into, const Handle(TDF_RelocationTable)& RT) const Standard_OVERRIDE;
Standard_EXPORT virtual Standard_OStream& Dump (Standard_OStream& anOS) const Standard_OVERRIDE;
DEFINE_STANDARD_RTTIEXT(TDataXtd_Geometry,TDF_Attribute)
protected:
private:
TDataXtd_GeometryEnum myType;
};
#endif // _TDataXtd_Geometry_HeaderFile
| 34.393443 | 128 | 0.765809 | [
"geometry",
"model"
] |
29c993c6272932175e40f8a208c89f69f73ef085 | 14,088 | cpp | C++ | Chinese version/flip.cpp | woodyhoko/First_Cpp_games | 28ab889da5095b91998cf5c5da60609c4d779df2 | [
"MIT"
] | null | null | null | Chinese version/flip.cpp | woodyhoko/First_Cpp_games | 28ab889da5095b91998cf5c5da60609c4d779df2 | [
"MIT"
] | null | null | null | Chinese version/flip.cpp | woodyhoko/First_Cpp_games | 28ab889da5095b91998cf5c5da60609c4d779df2 | [
"MIT"
] | null | null | null | #include<iostream>
#include<iomanip>
#include<cstdlib>
#include<cmath>
#include<ctime>
#include<ctype.h>
#include<string>
#include<conio.h>
#include<windows.h>
void shape(int,int);
using namespace std;
bool gameover3=0,fail,endg,rright=0,showtime;
int selected[8],randed[17],backur[17],rbackur[17],backt,timet,aaa,bbb,hard,tem,times;
void mainmg()
{
system("cls");
cout<<endl;
cout<<" __ __ _______ __ __ _______ ______ __ __ \n";
cout<<" | |_| || || |_| || || _ | | | | |\n";
cout<<" | || ___|| || _ || | || | |_| |\n";
cout<<" | || |___ | || | | || |_||_ | |\n";
cout<<" | || ___|| || |_| || __ ||_ _|\n";
cout<<" | ||_|| || |___ | ||_|| || || | | | | | \n";
cout<<" |_| |_||_______||_| |_||_______||___| |_| |___| \n";
cout<<" _______ _______ __ __ _______ \n";
cout<<" | || _ || |_| || | \n";
cout<<" | ___|| |_| || || ___| \n";
cout<<" | | __ | || || |___ \n";
cout<<" | || || || || ___| \n";
cout<<" | |_| || _ || ||_|| || |___ \n";
cout<<" |_______||__| |__||_| |_||_______|\n\n\n";
cout<<" press anykey to get started\n\n";
while(1)
{
if(_getch())
break;
}
}
void shape(int bbb,int aaa)
{
if(bbb==1)
{
if(aaa==1)
cout<<"11111111";
if(aaa==2)
cout<<"11111111";
if(aaa==3)
cout<<"11111111";
if(aaa==4)
cout<<"11111111";
if(aaa==5)
cout<<"11111111";
}
if(bbb==2)
{
if(aaa==1)
cout<<"22222222";
if(aaa==2)
cout<<"22222222";
if(aaa==3)
cout<<"22222222";
if(aaa==4)
cout<<"22222222";
if(aaa==5)
cout<<"22222222";
}
if(bbb==3)
{
if(aaa==1)
cout<<"########";
if(aaa==2)
cout<<"########";
if(aaa==3)
cout<<"########";
if(aaa==4)
cout<<"########";
if(aaa==5)
cout<<"########";
}
if(bbb==4)
{
if(aaa==1)
cout<<"@@@@@@@@";
if(aaa==2)
cout<<"@@@@@@@@";
if(aaa==3)
cout<<"@@@@@@@@";
if(aaa==4)
cout<<"@@@@@@@@";
if(aaa==5)
cout<<"@@@@@@@@";
}
if(bbb==5)
{
if(aaa==1)
cout<<"&&&&&&&&";
if(aaa==2)
cout<<"&&&&&&&&";
if(aaa==3)
cout<<"&&&&&&&&";
if(aaa==4)
cout<<"&&&&&&&&";
if(aaa==5)
cout<<"&&&&&&&&";
}
if(bbb==6)
{
if(aaa==1)
cout<<"%%%%%%%%";
if(aaa==2)
cout<<"%%%%%%%%";
if(aaa==3)
cout<<"%%%%%%%%";
if(aaa==4)
cout<<"%%%%%%%%";
if(aaa==5)
cout<<"%%%%%%%%";
}
if(bbb==7)
{
if(aaa==1)
cout<<"$$$$$$$$";
if(aaa==2)
cout<<"$$$$$$$$";
if(aaa==3)
cout<<"$$$$$$$$";
if(aaa==4)
cout<<"$$$$$$$$";
if(aaa==5)
cout<<"$$$$$$$$";
}
if(bbb==8)
{
if(aaa==1)
cout<<"********";
if(aaa==2)
cout<<"********";
if(aaa==3)
cout<<"********";
if(aaa==4)
cout<<"********";
if(aaa==5)
cout<<"********";
}
if(bbb==9)
{
if(aaa==1)
cout<<"^^^^^^^^";
if(aaa==2)
cout<<"^^^^^^^^";
if(aaa==3)
cout<<"^^^^^^^^";
if(aaa==4)
cout<<"^^^^^^^^";
if(aaa==5)
cout<<"^^^^^^^^";
}
if(bbb==10)
{
if(aaa==1)
cout<<"!!!!!!!!";
if(aaa==2)
cout<<"!!!!!!!!";
if(aaa==3)
cout<<"!!!!!!!!";
if(aaa==4)
cout<<"!!!!!!!!";
if(aaa==5)
cout<<"!!!!!!!!";
}
if(bbb==11)
{
if(aaa==1)
cout<<"????????";
if(aaa==2)
cout<<"????????";
if(aaa==3)
cout<<"????????";
if(aaa==4)
cout<<"????????";
if(aaa==5)
cout<<"????????";
}
if(bbb==12)
{
if(aaa==1)
cout<<"~~~~~~~~";
if(aaa==2)
cout<<"~~~~~~~~";
if(aaa==3)
cout<<"~~~~~~~~";
if(aaa==4)
cout<<"~~~~~~~~";
if(aaa==5)
cout<<"~~~~~~~~";
}
if(bbb==13)
{
if(aaa==1)
cout<<"<<<<<<<<";
if(aaa==2)
cout<<">>>>>>>>";
if(aaa==3)
cout<<"<<<<<<<<";
if(aaa==4)
cout<<">>>>>>>>";
if(aaa==5)
cout<<"<<<<<<<<";
}
if(bbb==14)
{
if(aaa==1)
cout<<"++++++++";
if(aaa==2)
cout<<"++++++++";
if(aaa==3)
cout<<"++++++++";
if(aaa==4)
cout<<"++++++++";
if(aaa==5)
cout<<"++++++++";
}
if(bbb==15)
{
if(aaa==1)
cout<<"--------";
if(aaa==2)
cout<<"--------";
if(aaa==3)
cout<<"--------";
if(aaa==4)
cout<<"--------";
if(aaa==5)
cout<<"--------";
}
if(bbb==16)
{
if(aaa==1)
cout<<"========";
if(aaa==2)
cout<<"========";
if(aaa==3)
cout<<"========";
if(aaa==4)
cout<<"========";
if(aaa==5)
cout<<"========";
}
if(bbb==17)
{
if(aaa==1)
cout<<" ";
if(aaa==2)
cout<<" ";
if(aaa==3)
cout<<" ";
if(aaa==4)
cout<<" ";
if(aaa==5)
cout<<" ";
}
}
void print1()
{
system("cls");
int n=1,m=1;
cout<<endl;
cout<<" 1 2 3 4 \n";
cout<<" ╔════════╗╔════════╗╔════════╗╔════════╗\n";
cout<<" ║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m++);cout<<"║\n";n=1;
cout<<" ║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m++);cout<<"║\n";n=1;
cout<<" ║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m++);cout<<"║\n";n=1;
cout<<" ║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m++);cout<<"║\n";n=1;
cout<<" ║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m++);cout<<"║\n";n=5;m=1;
cout<<" ╚════════╝╚════════╝╚════════╝╚════════╝\n\n";
cout<<" 5 6 7 8 \n";
cout<<" ╔════════╗╔════════╗╔════════╗╔════════╗\n";
cout<<" ║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m++);cout<<"║\n";n=5;
cout<<" ║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m++);cout<<"║\n";n=5;
cout<<" ║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m++);cout<<"║\n";n=5;
cout<<" ║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m++);cout<<"║\n";n=5;
cout<<" ║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m++);cout<<"║\n";n=9;m=1;
cout<<" ╚════════╝╚════════╝╚════════╝╚════════╝\n\n";
cout<<" 9 10 11 12 \n";
cout<<" ╔════════╗╔════════╗╔════════╗╔════════╗\n";
cout<<" ║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m++);cout<<"║\n";n=9;
cout<<" ║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m++);cout<<"║\n";n=9;
cout<<" ║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m++);cout<<"║\n";n=9;
cout<<" ║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m++);cout<<"║\n";n=9;
cout<<" ║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m++);cout<<"║\n";n=13;m=1;
cout<<" ╚════════╝╚════════╝╚════════╝╚════════╝\n\n";
cout<<" 13 14 15 16 \n";
cout<<" ╔════════╗╔════════╗╔════════╗╔════════╗\n";
cout<<" ║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m++);cout<<"║\n";n=13;
cout<<" ║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m++);cout<<"║\n";n=13;
cout<<" ║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m++);cout<<"║\n";n=13;
cout<<" ║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m++);cout<<"║\n";n=13;
cout<<" ║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m);cout<<"║║";shape(n++,m++);cout<<"║\n";
cout<<" ╚════════╝╚════════╝╚════════╝╚════════╝\n";
}
void pick()
{
int randm,reading;
times=0;
showtime=1;
srand(time(0));
cout<<"請選擇難度(難請輸入1,普通請輸入2,簡單請輸入3):";
cin>>reading;
timet=reading*5;
hard=reading;
cout<<"你想要用哪八款花色?";
for(int k=0;k++<8;)
{
cin>>selected[k];
if(selected[k]>16||selected[k]<1)
{
cout<<"別亂選\n";
k--;
}
for(int n=0;n++<k-1;)
{
if(selected[n]==selected[k])
{
cout<<"請別重複選擇款式\n";
k--;
}
}
}
for(int k=0;k++<8;)
{
for(int t=0;t++<2;)
{
while(1)
{
randm=rand()%16+1;
if(randed[randm]==0)
{
randed[randm]=rbackur[randm]=selected[k];
break;
}
}
}
}
// for(int c=0;c++<16;)
// backur[n]=0;
}
void realprinting()
{
system("cls");
int n=1,m=1;
cout<<endl;
cout<<" 1 2 3 4 \n";
cout<<" ╔════════╗╔════════╗╔════════╗╔════════╗\n";
cout<<" ║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m++);cout<<"║\n";n=1;
cout<<" ║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m++);cout<<"║\n";n=1;
cout<<" ║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m++);cout<<"║\n";n=1;
cout<<" ║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m++);cout<<"║\n";n=1;
cout<<" ║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m++);cout<<"║\n";n=5;m=1;
cout<<" ╚════════╝╚════════╝╚════════╝╚════════╝\n\n";
cout<<" 5 6 7 8 \n";
cout<<" ╔════════╗╔════════╗╔════════╗╔════════╗\n";
cout<<" ║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m++);cout<<"║\n";n=5;
cout<<" ║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m++);cout<<"║\n";n=5;
cout<<" ║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m++);cout<<"║\n";n=5;
cout<<" ║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m++);cout<<"║\n";n=5;
cout<<" ║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m++);cout<<"║";n=9;m=1;if(showtime==1){
cout<<"記憶時間剩下:"<<timet<<"秒鐘";}cout<<endl;
cout<<" ╚════════╝╚════════╝╚════════╝╚════════╝\n\n";
cout<<" 9 10 11 12 \n";
cout<<" ╔════════╗╔════════╗╔════════╗╔════════╗\n";
cout<<" ║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m++);cout<<"║\n";n=9;
cout<<" ║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m++);cout<<"║\n";n=9;
cout<<" ║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m++);cout<<"║\n";n=9;
cout<<" ║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m++);cout<<"║\n";n=9;
cout<<" ║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m++);cout<<"║\n";n=13;m=1;
cout<<" ╚════════╝╚════════╝╚════════╝╚════════╝\n\n";
cout<<" 13 14 15 16 \n";
cout<<" ╔════════╗╔════════╗╔════════╗╔════════╗\n";
cout<<" ║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m++);cout<<"║\n";n=13;
cout<<" ║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m++);cout<<"║\n";n=13;
cout<<" ║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m++);cout<<"║\n";n=13;
cout<<" ║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m++);cout<<"║\n";n=13;
cout<<" ║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m);cout<<"║║";shape(randed[n++],m++);cout<<"║\n";
cout<<" ╚════════╝╚════════╝╚════════╝╚════════╝\n";
}
void guess()
{
aaa=bbb=0;
fail=0;
rright=0;
cout<<"請輸入你記得是一樣牌的編號:";
cin>>aaa>>bbb;
times++;
while(aaa==bbb||aaa>16||aaa<1||bbb>16||bbb<1||randed[aaa]!=17||randed[bbb]!=17)
{
cout<<"請別亂輸入編號,重新輸入:";
cin>>aaa>>bbb;
times++;
}
if(rbackur[aaa]==rbackur[bbb])
{
rright=1;
randed[aaa]=randed[bbb]=rbackur[aaa];
}
else
{
randed[aaa]=rbackur[aaa];
randed[bbb]=rbackur[bbb];
fail=1;
}
}
void startg()
{
for(int gg=0;gg++<16;)
randed[gg]=17;
endg=0;
}
void check3()
{
int checking;
for(int f=0;f++<16;)
{
if(randed[f]==rbackur[f])
checking++;
}
if(checking>15)
endg=1;
}
int mainpro_flip()
{
while(!gameover3)
{
mainmg();
int time1;
int time2;
char tempe;
time_t timer;
print1();
pick();
while(timet-->0)
{
realprinting();
Sleep(1000);
}
showtime=0;
startg();
time1=time(&timer);
while(!endg)
{
realprinting();
if(rright==1)
cout<<"恭喜!";
Sleep(1000);
guess();
tem=hard;
if(fail==1)
{
while(tem-->0)
{
realprinting();
cout<<"失敗囉請重新選擇";
Sleep(1000);
}
randed[aaa]=randed[bbb]=17;
fail=0;
}
check3();
}
time2=time(&timer);
cout<<" _______ _______ __ __ _______ _______ __ __ _______ ______ \n";
cout<<"| || _ || |_| || || || | | || || _ | \n";
cout<<"| ___|| |_| || || ___|| _ || |_| || ___|| | || \n";
cout<<"| | __ | || || |___ | | | || || |___ | |_||_ \n";
cout<<"| || || || || ___|| |_| || || ___|| __ |\n";
cout<<"| |_| || _ || ||_|| || |___ | | | | | |___ | | | |\n";
cout<<"|_______||__| |__||_| |_||_______||_______| |___| |_______||___| |_|\n\n\n";
cout<<" 你共用了"<<time2-time1<<"秒完成\n\n";
cout<<" 你共翻了"<<times<<"次\n\n";
cout<<" 重新開始遊戲請任意輸入一個字元\n 離開請輸入0\n";
cin>>tempe;
if(tempe=='0')
break;
}
}
| 27.461988 | 166 | 0.402186 | [
"shape"
] |
29cc4835093808683e11002352c741b777ffe0d0 | 22,146 | cpp | C++ | mlir/lib/Dialect/Linalg/Transforms/HoistPadding.cpp | 1samhicks/llvm-project | c3017819cb7fe22dcfabf90ecb34130fb6bed314 | [
"Apache-2.0"
] | 1 | 2021-12-10T01:17:03.000Z | 2021-12-10T01:17:03.000Z | mlir/lib/Dialect/Linalg/Transforms/HoistPadding.cpp | 1samhicks/llvm-project | c3017819cb7fe22dcfabf90ecb34130fb6bed314 | [
"Apache-2.0"
] | null | null | null | mlir/lib/Dialect/Linalg/Transforms/HoistPadding.cpp | 1samhicks/llvm-project | c3017819cb7fe22dcfabf90ecb34130fb6bed314 | [
"Apache-2.0"
] | null | null | null | //===- HoistPadding.cpp - Hoisting transformation for PadTensorOp ---------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements functions concerned with hoisting padding operations.
//
//===----------------------------------------------------------------------===//
#include "mlir/Dialect/Linalg/Transforms/HoistPadding.h"
#include "mlir/Analysis/SliceAnalysis.h"
#include "mlir/Dialect/Affine/Utils.h"
#include "mlir/Dialect/Linalg/IR/LinalgOps.h"
#include "mlir/Dialect/Linalg/Transforms/Transforms.h"
#include "mlir/Dialect/SCF/SCF.h"
#include "mlir/Dialect/SCF/Utils.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/Dialect/Tensor/IR/Tensor.h"
#include "mlir/Dialect/Vector/VectorOps.h"
#include "mlir/Dialect/Vector/VectorUtils.h"
#include "mlir/IR/AsmState.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/Dominance.h"
#include "mlir/Transforms/LoopUtils.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Debug.h"
using llvm::dbgs;
#define DEBUG_TYPE "hoist-padding"
#define DBGS() (dbgs() << '[' << DEBUG_TYPE << "] ")
using namespace mlir;
using namespace mlir::linalg;
/// Analysis class to support PadTensorOp hoisting across multiple enclosing
/// loops. The failure conditions are:
/// 1. Pad op has a use that is not an input of a LinalgOp.
/// 2. Pad op does not have a constant padding value.
/// 3. There is no immediately enclosing scf::ForOp.
/// 4. The backward slice from the pad op to the scf::ForOp to hoist above
/// contains an unknown op with non index type operands, a region, or a
/// memory effect.
/// 5. The backward slice from the pad op to the scf::ForOp to hoist above is
/// empty.
/// 6. The source tensor of pad op is not defined by an extract slice op.
/// 7. The source tensor of the extract slice op is not defined outside of
/// the outermost enclosing scf::ForOp.
/// 8. There is no enclosing scf::ForOp that indexes the padded data.
/// Other cases succeed and will trigger hoisting of the pad op.
struct HoistingAnalysis {
HoistingAnalysis(PadTensorOp padTensorOp, int numLoops);
bool isValid() { return valid; }
/// Footprint of the packedTensor, computed from the packingLoops.
SmallVector<Value> getPackedTensorSizes(ImplicitLocOpBuilder &b);
/// The outermost loop, determined by `nLevels` above which `padTensorOp` will
/// be hoisted.
scf::ForOp outermostEnclosingForOp;
/// Backward slice rooted at `padTensorOp` and nested under
/// `outermostEnclosingForOp`.
SetVector<Operation *> backwardSlice;
/// The scf::ForOp immediately enclosing `padTensorOp` such that:
/// 1. they are nested under `outermostEnclosingForOp` (inclusive)
/// 2. whose induction variable is used, directly or indirectly, in the
/// computation of `padTensorOp`.
/// The span of these loops determines the footprint of the packed tensor.
SmallVector<scf::ForOp> packingLoops;
private:
/// Drop any non-index dependencies of `padTensorOp` and `sliceOp` from
/// `backwardSlice`. The method follows the use-def chains of the index
/// operands consumed by `padTensorOp` and `sliceOp` and drops the operations
/// not part of this index computation. Afterwards, the filtered
/// `backwardSlice` contains only the loops whose induction variable is used,
/// directly or indirectly, to index the padded tensor. The method returns
/// failure if the filtered backward slice contains an unexpected operation.
///
/// Example:
/// ```
/// %source = linalg.fill(%cst, %arg0)
/// scf.for %i
/// %unrelated = linalg.fill(%cst, %arg1) // not used to index %source!
/// scf.for %j (%arg2 = %unrelated)
/// scf.for %k // not used to index %source!
/// %ubi = affine.min #map(%i)
/// %ubj = affine.min #map(%j)
/// %slice = tensor.extract_slice %source [%i, %j] [%ubi, %ubj]
/// %padded_slice = linalg.pad_tensor %slice
/// ```
/// dropNonIndexDependencies(%padded_slice, %slice)
/// removes [scf.for %k, linalg.fill(%cst, %arg1)] from backwardSlice.
LogicalResult dropNonIndexDependencies(PadTensorOp padTensorOp,
tensor::ExtractSliceOp sliceOp);
/// Encodes whether the analysis is valid and hoisting can proceed.
bool valid;
};
/// Return true if all uses of `padTensorOp` are an input tensor of some
/// LinalgOp.
static bool isOnlyUsedAsInputOfLinalgOp(PadTensorOp padTensorOp) {
for (OpOperand &use : padTensorOp.result().getUses()) {
auto linalgUser = dyn_cast<linalg::LinalgOp>(use.getOwner());
if (!linalgUser || !linalgUser.isInputTensor(&use)) {
LLVM_DEBUG(DBGS() << "Found a use of " << *(padTensorOp)
<< "\nthat is not an input tensor of a LinalgOp, "
<< "cannot hoist\n"
<< *(use.getOwner()) << "\n");
return false;
}
}
return true;
}
/// Return at most nLevels of immediately enclosing scf::ForOp loops.
/// Stops at the first parent that is not an scf::ForOp.
/// Multi-loops such as scf.parallel or linalg.tiled_loop are not modeled atm.
/// Control-flow and other containing ops with regions are not modeled atm.
static void
getAtMostNEnclosingLoops(PadTensorOp padTensorOp, int nLevels,
SmallVector<scf::ForOp> &reverseEnclosingLoops) {
AsmState state(padTensorOp->getParentOfType<mlir::FuncOp>());
(void)state;
scf::ForOp outermostEnclosingForOp = nullptr;
Operation *nextEnclosingOp = padTensorOp->getParentOp();
while (nLevels-- > 0 &&
(outermostEnclosingForOp = dyn_cast<scf::ForOp>(nextEnclosingOp))) {
LLVM_DEBUG(
DBGS() << "loops: ";
outermostEnclosingForOp.getInductionVar().printAsOperand(dbgs(), state);
dbgs() << "\n");
reverseEnclosingLoops.push_back(outermostEnclosingForOp);
nextEnclosingOp = outermostEnclosingForOp->getParentOp();
}
}
HoistingAnalysis::HoistingAnalysis(PadTensorOp padTensorOp, int numLoops) {
valid = false;
// Bail on any use that isn't an input of a Linalg op.
// Hoisting of inplace updates happens after vectorization.
if (!isOnlyUsedAsInputOfLinalgOp(padTensorOp))
return;
// Get at most `numLoops` of immediately enclosing loops.
SmallVector<scf::ForOp> reverseEnclosingLoops;
getAtMostNEnclosingLoops(padTensorOp, numLoops, reverseEnclosingLoops);
if (reverseEnclosingLoops.empty()) {
LLVM_DEBUG(DBGS() << "No immediately enclosing loop -> skip\n");
return;
}
outermostEnclosingForOp = reverseEnclosingLoops.back();
// Get the `sliceOp` that defines the source tensor of `padTensorOp` and
// check its source is defined outside of the outermost loop. This check
// ensures the padded data is available for packing before entering the
// outermost enclosing loop.
//
// Example:
// ```
// %source = linalg.fill(%cst, %arg0)
// // %source is available for packing here!
// scf.for %i
// scf.for %j
// scf.for %k
// %slice = tensor.extract_slice %source [%i, %j]
// %padded_slice = linalg.pad_tensor %slice
// ```
auto sliceOp = padTensorOp.source().getDefiningOp<tensor::ExtractSliceOp>();
if (!sliceOp) {
LLVM_DEBUG(DBGS() << "Cannot find the extract slice op -> skip\n");
return;
}
if (!outermostEnclosingForOp.isDefinedOutsideOfLoop(sliceOp.source())) {
LLVM_DEBUG(DBGS() << "Source not defined outside of loops -> skip\n");
return;
}
// Check the region of `padTensorOp` depends on a constant only. Adding
// hoisting support for arbitrary padding regions would require cloning all
// dependencies captured by the padding region.
Value paddingValue = padTensorOp.getConstantPaddingValue();
if (!paddingValue ||
!isa_and_nonnull<arith::ConstantOp>(paddingValue.getDefiningOp())) {
LLVM_DEBUG(DBGS() << "Cannot find constant padding value -> skip\n");
return;
}
// Get all the ops in the backwards slice starting from `padTensorOp` and that
// are dominated by the outermost enclosing loop.
DominanceInfo domInfo(outermostEnclosingForOp);
getBackwardSlice(padTensorOp.getOperation(), &backwardSlice,
[&](Operation *op) {
return domInfo.dominates(outermostEnclosingForOp, op);
});
if (backwardSlice.empty())
return;
// Add `padTensorOp` itself to the backward slice.
backwardSlice.insert(padTensorOp.getOperation());
// Remove all ops in the backward slice that are not used to index the padded
// tensor. In particular, keep `padTensorOp`, `sliceOp`, and the loop and
// affine operations used for the index computation.
if (failed(dropNonIndexDependencies(padTensorOp, sliceOp)))
return;
// Add only the loops part of the filtered `backwardSlice` to the packing
// loops. All other loops are not used to index the padded data and
// consequently access the same data in every loop iteration. Adding them to
// the packing loops would increase the cache footprint of the packed data
// by storing the same data multiple times.
for (scf::ForOp forOp : llvm::reverse(reverseEnclosingLoops))
if (backwardSlice.contains(forOp))
packingLoops.push_back(forOp);
if (packingLoops.empty()) {
LLVM_DEBUG(DBGS() << "Cannot find a packing loop -> skip\n");
return;
}
// The analysis is valid and hoisting can occur.
valid = true;
}
LogicalResult
HoistingAnalysis::dropNonIndexDependencies(PadTensorOp padTensorOp,
tensor::ExtractSliceOp sliceOp) {
// Set of all values used for index computation.
SetVector<Value> indexEdges;
// Add all index operands of `operation` to `indexEdges`. An index operand is
// an operand of type index.
auto addIndexOperandsToIndexEdges = [&](Operation *operation) {
for (Value operand : operation->getOperands())
if (operand.getType().isIndex())
indexEdges.insert(operand);
};
// Check if any operation result is contained in `indexEdges`.
auto hasIndexResult = [&](Operation *operation) {
return llvm::any_of(operation->getResults(), [&](Value result) {
return indexEdges.contains(result);
});
};
// Starting from `padTensorOp` and `sliceOp` walk the use-def edges of index
// type in `backwardSlice`. Add the index operands of an operation to
// `indexEdges` and remove all operations from `backwardSlice` that are not
// part of the index computation.
//
// Example:
// ```
// %source = linalg.fill(%cst, %arg0)
// scf.for %i
// %unrelated = linalg.fill(%cst, %arg1) // not used to index %source!
// scf.for %j (%arg2 = %unrelated)
// scf.for %k // not used to index %source!
// %ubi = affine.min #map(%i)
// %ubj = affine.min #map(%j)
// %slice = tensor.extract_slice %source [%i, %j] [%ubi, %ubj]
// %padded_slice = linalg.pad_tensor %slice
// ```
// After iterating `backwardSlice` we obtain:
// indexEdges = [%i, %j, %ubi, %ubj]
// backwardSlice = backwardSlice / [linalg.fill(%cst, %arg1), scf.for %k]
for (Operation *op : llvm::reverse(backwardSlice)) {
// Add the index operands of `padTensorOp` and `sliceOp` to start the
// exploration of the index computation.
if (op == padTensorOp || op == sliceOp) {
addIndexOperandsToIndexEdges(op);
continue;
}
// Add the index operands of the loop if its induction variable is
// used for index computation.
if (auto forOp = dyn_cast<scf::ForOp>(op)) {
if (!hasIndexResult(op) && indexEdges.contains(forOp.getInductionVar())) {
addIndexOperandsToIndexEdges(op);
continue;
}
}
// Add the index operands of all other operations if at least one result is
// used for index computation.
if (hasIndexResult(op)) {
addIndexOperandsToIndexEdges(op);
// Check the operands of the remaining operations all have index type.
if (llvm::any_of(op->getOperandTypes(),
[](Type type) { return !type.isIndex(); })) {
LLVM_DEBUG(DBGS() << "Unsupported op with non index type operands: "
<< op << " -> skip\n");
return failure();
}
// Check the remaining operations do not have regions or memory effects.
auto effectInterface = dyn_cast<MemoryEffectOpInterface>(op);
bool hasMemoryEffect = effectInterface && !effectInterface.hasNoEffect();
if (hasMemoryEffect || op->getNumRegions() != 0) {
LLVM_DEBUG(DBGS() << "Unsupported op with region or memory effect: "
<< op << " -> skip\n");
return failure();
}
continue;
}
// Remove all other operation not used by the index computation except for
// constant operations that may be padding values used by `padTensorOp`.
if (!isa<arith::ConstantOp>(op))
backwardSlice.remove(op);
}
return success();
}
SmallVector<Value>
HoistingAnalysis::getPackedTensorSizes(ImplicitLocOpBuilder &b) {
SmallVector<Value> dynamicTensorSizes;
// Upper bound the packing loop lengths to size the packed tensor. Taking
// upper bounds can make the sizes of the packed tensor independent of the
// enclosing loops. This independence is a prerequisite for reusing the same
// buffer for all enclosing loop iterations and hoisting its allocation out of
// the enclosing loops.
for (auto forOp : packingLoops) {
// Compute an upper bound `ubVal` for the upper bound of `forOp`.
AffineMap boundMap;
SmallVector<Value> boundOperands;
getUpperBoundForIndex(forOp.upperBound(), boundMap, boundOperands);
Value ubVal = b.createOrFold<AffineMinOp>(boundMap, boundOperands);
// Compute the maximal packing loop length as (ub - lb).ceilDiv(step) and
// store the result to `dynamicTensorSizes`.
// TODO: instead of using the lower bound of `forOp` directly, implement a
// lower bound computation similar to the upper bound computation.
AffineExpr lb, ub, step;
bindDims(b.getContext(), lb, ub);
bindSymbols(b.getContext(), step);
Value res = b.createOrFold<AffineApplyOp>(
(ub - lb).ceilDiv(step),
ValueRange{forOp.lowerBound(), ubVal, cast<scf::ForOp>(forOp).step()});
dynamicTensorSizes.push_back(res);
}
return dynamicTensorSizes;
}
static bool isDefinedOutsideOrConstant(scf::ForOp outer, Value v) {
return outer.isDefinedOutsideOfLoop(v) || v.getDefiningOp<ConstantOp>();
}
/// Return the current iteration number in the loop (iv - lb).ceilDiv(step).
/// The returned Value is guaranteed not to depend on any loop comprised in
/// [`outer`, `forOp`].
/// Return null if such a loop-independent quantity cannot be computed.
static Value buildLoopIterationCount(OpBuilder &b, scf::ForOp outer,
scf::ForOp forOp) {
MLIRContext *ctx = forOp->getContext();
AffineExpr iv, lb, step;
bindDims(ctx, iv, lb);
bindSymbols(ctx, step);
if (!isDefinedOutsideOrConstant(outer, forOp.lowerBound()) ||
!isDefinedOutsideOrConstant(outer, forOp.step()))
return Value();
Value ivVal = forOp.getInductionVar(), lbVal = forOp.lowerBound(),
stepVal = forOp.step();
auto loc = forOp->getLoc();
return b.createOrFold<AffineApplyOp>(loc, (iv - lb).ceilDiv(step),
ValueRange{ivVal, lbVal, stepVal});
}
FailureOr<Value> mlir::linalg::hoistPaddingOnTensors(PadTensorOp opToHoist,
int numLoops,
PadTensorOp &hoistedOp) {
LLVM_DEBUG(DBGS() << "Try to hoist " << *(opToHoist) << " by " << numLoops
<< " loops\n");
HoistingAnalysis analysis(opToHoist, numLoops);
if (!analysis.isValid()) {
LLVM_DEBUG(DBGS() << "Analysis failed -> Skip\n");
return failure();
}
scf::ForOp outer = analysis.outermostEnclosingForOp;
ImplicitLocOpBuilder b(outer->getLoc(), outer);
SmallVector<Value> dynamicTensorSizes = analysis.getPackedTensorSizes(b);
// Update actual number of loops, which may be smaller.
int nPackedLoops = analysis.packingLoops.size();
Location loc = opToHoist->getLoc();
RankedTensorType paddedTensorType = opToHoist.getResultType();
int paddedRank = paddedTensorType.getRank();
// Create the packed tensor<?x?x..?xpadded_shape> into which we amortize
// padding.
SmallVector<int64_t> packedShape(nPackedLoops, ShapedType::kDynamicSize);
// TODO: go grab dims when necessary, for now PadTensorOp returns a static
// tensor.
llvm::append_range(packedShape, paddedTensorType.getShape());
auto packedTensorType =
RankedTensorType::get(packedShape, paddedTensorType.getElementType());
Value packedTensor = b.create<linalg::InitTensorOp>(
loc, dynamicTensorSizes, packedTensorType.getShape(),
packedTensorType.getElementType());
// Clone the operations involved in the backward slice, iteratively stepping
// into the loops that we encounter.
// The implementation proceeds in a stack-like fashion:
// 1. Iteratively clone and step into the loops, pushing the `packedTensor`
// deeper in the stack.
// 2. Create a InsertSliceOp at the top of the stack.
// 3. Iteratively pop and yield the result of the InsertSliceOp across
// the cloned loops.
SmallVector<Value> clonedLoopIvs, leadingPackedTensorIndexings;
clonedLoopIvs.reserve(nPackedLoops);
leadingPackedTensorIndexings.reserve(nPackedLoops);
BlockAndValueMapping bvm;
// Stack step 1. iteratively clone loops and push `packedTensor`.
for (Operation *op : analysis.backwardSlice) {
// Specifically sit out in the extract_slice(packedTensor) case: this is the
// piece we seek to replace.
if (auto sliceOp = dyn_cast<tensor::ExtractSliceOp>(op))
if (bvm.lookupOrDefault(sliceOp.source()) == packedTensor)
continue;
// Clone all operations except it is a loop.
auto forOp = dyn_cast<scf::ForOp>(op);
if (!forOp) {
b.clone(*op, bvm);
continue;
}
// Create a packing loop that takes `packedTensor` as iteration argument.
auto clonedForOp =
b.create<scf::ForOp>(loc, bvm.lookupOrDefault(forOp.lowerBound()),
bvm.lookupOrDefault(forOp.upperBound()),
bvm.lookupOrDefault(forOp.step()), packedTensor);
// Map the induction var, region args and results to the `clonedForOp`.
bvm.map(forOp.getInductionVar(), clonedForOp.getInductionVar());
bvm.map(forOp.getRegionIterArgs(), clonedForOp.getRegionIterArgs());
bvm.map(forOp.getResults(), clonedForOp.getResults());
assert(clonedForOp->getNumRegions() == 1);
clonedLoopIvs.push_back(clonedForOp.getInductionVar());
b.setInsertionPointToStart(&clonedForOp->getRegion(0).front());
Value loopIndependentIterationCount =
buildLoopIterationCount(b, outer, clonedForOp);
// Assert the loop-independent iteration count can be computed.
if (!loopIndependentIterationCount)
llvm_unreachable("loop independence prerequisite not met");
leadingPackedTensorIndexings.push_back(loopIndependentIterationCount);
packedTensor = clonedForOp.getRegionIterArgs().front();
}
// Stack step 2. create InsertSliceOp at the top of the stack.
// offsets = [clonedLoopIvs, 0 .. 0].
SmallVector<OpFoldResult> offsets(leadingPackedTensorIndexings.begin(),
leadingPackedTensorIndexings.end());
offsets.append(paddedRank, b.getIndexAttr(0));
// sizes = [1 .. 1, paddedShape].
SmallVector<OpFoldResult> sizes(nPackedLoops, b.getIndexAttr(1));
for (int64_t sz : paddedTensorType.getShape()) {
// TODO: go grab dims when necessary, for now PadTensorOp returns a static
// tensor.
assert(!ShapedType::isDynamic(sz) && "padded tensor needs static sizes");
sizes.push_back(b.getIndexAttr(sz));
}
// strides = [1 .. 1].
SmallVector<OpFoldResult> strides(nPackedLoops + paddedRank,
b.getIndexAttr(1));
Value inserted =
b.create<tensor::InsertSliceOp>(loc, bvm.lookup(opToHoist.result()),
packedTensor, offsets, sizes, strides);
// Stack step 3. iteratively pop the stack and propagate the yield.
Value valueToYield = inserted;
for (Value iv : llvm::reverse(clonedLoopIvs)) {
auto forOp = scf::getForInductionVarOwner(iv);
b.setInsertionPointToEnd(&forOp.getRegion().front());
b.create<scf::YieldOp>(loc, valueToYield);
valueToYield = forOp.getResult(0);
}
// Now the packed tensor is ready, replace the original padding op by a
// 1x..x1 slice [originalLoopIvs, 0 .. 0][1 .. 1, paddedShape][1 .. 1].
b.setInsertionPoint(opToHoist);
SmallVector<Value> loopIterationCounts = llvm::to_vector<4>(
llvm::map_range(analysis.packingLoops, [&](Operation *loop) {
return buildLoopIterationCount(b, outer, cast<scf::ForOp>(loop));
}));
// Assert all loop iteration counts can be computed.
if (llvm::any_of(loopIterationCounts, [](Value v) { return !v; }))
llvm_unreachable("loop independence prerequisite not met");
// offsets = [originalLoopIvs, 0 .. 0].
offsets.assign(loopIterationCounts.begin(), loopIterationCounts.end());
offsets.append(paddedRank, b.getIndexAttr(0));
// sizes = [1 .. 1, paddedShape] (definedabove).
// strides = [1 .. 1] (defined above)
packedTensor =
scf::getForInductionVarOwner(clonedLoopIvs.front())->getResult(0);
Value newResult = b.create<tensor::ExtractSliceOp>(
loc, opToHoist.getResultType(), packedTensor, offsets, sizes, strides);
// Make the newly cloned `opToHoist` available to the caller.
hoistedOp = cast<PadTensorOp>(bvm.lookup(opToHoist.result()).getDefiningOp());
return newResult;
}
| 43.423529 | 80 | 0.675336 | [
"vector"
] |
29cf10b3aa4c3c135e787958c224db8c75af51a4 | 4,634 | cpp | C++ | WBF/src/WBF_GPS/GeometryBuffer.cpp | heesok2/OpenGL | 6ba159a77428635bf73eab9a0080203b248b015c | [
"MIT"
] | null | null | null | WBF/src/WBF_GPS/GeometryBuffer.cpp | heesok2/OpenGL | 6ba159a77428635bf73eab9a0080203b248b015c | [
"MIT"
] | null | null | null | WBF/src/WBF_GPS/GeometryBuffer.cpp | heesok2/OpenGL | 6ba159a77428635bf73eab9a0080203b248b015c | [
"MIT"
] | 1 | 2019-11-25T02:03:08.000Z | 2019-11-25T02:03:08.000Z | #include "stdafx.h"
#include "GeometryBuffer.h"
#include "BufferType.h"
#include "..\WBF_LIB\Package.h"
#include "..\WBF_GLCORE\ViewHelper.h"
#include "..\WBF_DATA\ModuleVertex.h"
#include "..\WBF_DATA\ModuleSubBody.h"
#include "..\WBF_DATA\ModuleBody.h"
#include "..\WBF_BASE\DocBase.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
IMPLEMENT_DYNAMIC_BUFFER(CGeometryBuffer, E_BUFFER_GEOMETRY);
CGeometryBuffer::CGeometryBuffer()
{
}
CGeometryBuffer::~CGeometryBuffer()
{
}
void CGeometryBuffer::GLRelease()
{
auto itr = m_mObjectBuffer.begin();
while (itr != m_mObjectBuffer.end())
{
auto& tObjectBuffer = itr->second;
glDeleteVertexArrays(1, &tObjectBuffer.uiVAO);
glDeleteBuffers(1, &tObjectBuffer.uiVBO);
glDeleteBuffers(1, &tObjectBuffer.uiEBO);
itr++;
}
m_mObjectBuffer.clear();
}
void CGeometryBuffer::GLBuild(CViewHelper * pHelper, UINT)
{
auto pDoc = (CDocBase*)pHelper->GetDocument();
auto pPackage = pDoc->GetPackage();
auto pModuleVertex = (CModuleVertex*)pPackage->GetModule(E_TYPE_VERTEX);
auto pModuleSubBody = (CModuleSubBody*)pPackage->GetModule(E_TYPE_SUBBODY);
auto pModuleBody = (CModuleBody*)pPackage->GetModule(E_TYPE_BODY);
auto lambda_glm_copy = [](float* pSrc, UINT uiSize, float* pDest)
{
std::copy(pSrc, pSrc + uiSize, pDest);
return uiSize;
};
auto VERTEX_NUM = 3;
auto NORMAL_NUM = 3;
auto TEXCORD_NUM = 2;
auto BUFFER_NUM = VERTEX_NUM + NORMAL_NUM + TEXCORD_NUM;
std::map<DKEY, UINT> mVertexIndex;
std::vector<CEntityVertex> lstVertex;
std::vector<CEntityBody> lstBody;
auto lVertexNum = pModuleVertex->GetDataList(lstVertex);
auto lBodyNum = pModuleBody->GetDataList(lstBody);
float* aBuffer = new float[lVertexNum * BUFFER_NUM];
auto lBufferNum = 0;
for (auto lvtx = 0; lvtx < lVertexNum; ++lvtx)
{
auto& EntVertex = lstVertex[lvtx];
lBufferNum += lambda_glm_copy(glm::value_ptr(EntVertex.vPos), VERTEX_NUM, &aBuffer[lBufferNum]);
lBufferNum += lambda_glm_copy(glm::value_ptr(EntVertex.vNormal), NORMAL_NUM, &aBuffer[lBufferNum]);
lBufferNum += lambda_glm_copy(glm::value_ptr(EntVertex.vTexcord), TEXCORD_NUM, &aBuffer[lBufferNum]);
mVertexIndex[EntVertex.dbKey] = lvtx;
}
UINT VBO;
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(float)*(lVertexNum*BUFFER_NUM), aBuffer, GL_STATIC_DRAW);
_SAFE_DELETE_ARRAY(aBuffer);
for (auto lbody = 0; lbody < lBodyNum; ++lbody)
{
auto& EntBody = lstBody[lbody];
auto lIndexNum = 0;
for (auto lsub = 0; lsub < static_cast<int>(EntBody.aItrSubBody.size()); ++lsub)
{
auto itr = EntBody.aItrSubBody[lsub];
auto key = ITR_TO_KEY(itr);
CEntitySubBody EntSubBody;
if (!pModuleSubBody->Find(key, EntSubBody))
continue;
lIndexNum += static_cast<int>(EntSubBody.aItrVertex.size());
}
auto lBufferIndxNum = 0;
UINT* aIndex = new UINT[lIndexNum];
for (auto lsub = 0; lsub < static_cast<int>(EntBody.aItrSubBody.size()); ++lsub)
{
auto itr = EntBody.aItrSubBody[lsub];
auto key = ITR_TO_KEY(itr);
CEntitySubBody EntSubBody;
if (!pModuleSubBody->Find(key, EntSubBody))
continue;
for (auto itrVertex : EntSubBody.aItrVertex)
{
auto dbKey = ITR_TO_KEY(itrVertex);
aIndex[lBufferIndxNum++] = mVertexIndex[dbKey];
}
}
///////////////////////////////////////////////////////////
UINT EBO, VAO;
glGenBuffers(1, &EBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(UINT)*lBufferIndxNum, aIndex, GL_STATIC_DRAW);
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, VERTEX_NUM, GL_FLOAT, GL_FALSE, sizeof(float)*BUFFER_NUM, 0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, NORMAL_NUM, GL_FLOAT, GL_FALSE, sizeof(float)*BUFFER_NUM, (void*)(sizeof(float)*(VERTEX_NUM)));
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, TEXCORD_NUM, GL_FLOAT, GL_FALSE, sizeof(float)*BUFFER_NUM, (void*)(sizeof(float)*(VERTEX_NUM + NORMAL_NUM)));
glBindVertexArray(0);
TObjectBuffer tObjectBuffer;
tObjectBuffer.uiVAO = VAO;
tObjectBuffer.uiVBO = VBO;
tObjectBuffer.uiEBO = EBO;
tObjectBuffer.uiSize = lBufferIndxNum;
m_mObjectBuffer[EntBody.dbKey] = tObjectBuffer;
_SAFE_DELETE_ARRAY(aIndex);
}
}
long CGeometryBuffer::GetObjectBuffer(std::map<UINT, TObjectBuffer>& mObjectBuffer)
{
mObjectBuffer.insert(m_mObjectBuffer.begin(), m_mObjectBuffer.end());
return (long)mObjectBuffer.size();
}
| 27.099415 | 136 | 0.726586 | [
"vector"
] |
29d8498ff91e6360fa7a133b7efc5f39805bd3b5 | 1,457 | hh | C++ | inc/DqmValue.hh | Mu2e/DQM | 52fd36c89e514d6cef6940f7dd6564a43c94ccad | [
"Apache-2.0"
] | null | null | null | inc/DqmValue.hh | Mu2e/DQM | 52fd36c89e514d6cef6940f7dd6564a43c94ccad | [
"Apache-2.0"
] | null | null | null | inc/DqmValue.hh | Mu2e/DQM | 52fd36c89e514d6cef6940f7dd6564a43c94ccad | [
"Apache-2.0"
] | 1 | 2022-01-06T02:17:07.000Z | 2022-01-06T02:17:07.000Z | #ifndef DQM_DqmValue_hh
#define DQM_DqmValue_hh
//
// holds a single Dqm value, its name and uncertainty
//
#include <string>
#include <vector>
namespace mu2e {
class DqmValue {
public:
enum codeValues { OK = 0, lowStats = 1, missing = 2, error = 3 };
DqmValue() {}
DqmValue(const std::string& group, const std::string& subgroup,
const std::string& name, const std::string& value,
const std::string& sigma, int code = 0) :
_group(group),
_subgroup(subgroup), _name(name), _valueStr(value),
_value(std::stof(value)), _sigmaStr(sigma), _sigma(std::stof(value)),
_code(code) {}
const std::string& group() const { return _group; }
const std::string& subgroup() const { return _subgroup; }
const std::string& name() const { return _name; }
const std::string& valueStr() const { return _valueStr; }
float value() const { return _value; }
const std::string& sigmaStr() const { return _sigmaStr; }
float sigma() const { return _sigma; }
int code() const { return _code; }
std::string csv() const {
return _group + "," + _subgroup + "," + _name + "," + _valueStr + "," +
_sigmaStr + "," + std::to_string(_code);
}
private:
std::string _group;
std::string _subgroup;
std::string _name;
std::string _valueStr;
float _value;
std::string _sigmaStr;
float _sigma;
int _code;
};
typedef std::vector<DqmValue> DqmValueCollection;
} // namespace mu2e
#endif
| 26.490909 | 75 | 0.64722 | [
"vector"
] |
29d863d2adf0139f705a64d651ca275d0cd59fe4 | 9,337 | cpp | C++ | modules/dnn/src/layers/layers_common.cpp | balaji-kss/opencv-1 | 80e3e5620421dbdc9f69f4fcbb0046d19e635c77 | [
"BSD-3-Clause"
] | 2 | 2020-03-24T05:42:26.000Z | 2020-04-20T17:45:41.000Z | modules/dnn/src/layers/layers_common.cpp | FireFeathers06/opencv | f3de2b4be75c120e2c3c59a89d6f1453ee055166 | [
"BSD-3-Clause"
] | 1 | 2019-05-13T13:42:39.000Z | 2019-05-13T13:42:39.000Z | modules/dnn/src/layers/layers_common.cpp | FireFeathers06/opencv | f3de2b4be75c120e2c3c59a89d6f1453ee055166 | [
"BSD-3-Clause"
] | 1 | 2020-01-09T09:34:26.000Z | 2020-01-09T09:34:26.000Z | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Copyright (C) 2017, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "../precomp.hpp"
#include "layers_common.hpp"
namespace cv
{
namespace dnn
{
namespace util
{
std::string makeName(const std::string& str1, const std::string& str2)
{
return str1 + str2;
}
bool getParameter(const LayerParams ¶ms, const std::string& nameBase, const std::string& nameAll,
std::vector<size_t>& parameter, bool hasDefault = false, const std::vector<size_t>& defaultValue = std::vector<size_t>(2, 0))
{
std::string nameH = makeName(nameBase, std::string("_h"));
std::string nameW = makeName(nameBase, std::string("_w"));
std::string nameAll_ = nameAll;
if (nameAll_ == "")
nameAll_ = nameBase;
if (params.has(nameH) && params.has(nameW))
{
CV_Assert(params.get<int>(nameH) >= 0 && params.get<int>(nameW) >= 0);
parameter.push_back(params.get<int>(nameH));
parameter.push_back(params.get<int>(nameW));
return true;
}
else
{
if (params.has(nameAll_))
{
DictValue param = params.get(nameAll_);
for (int i = 0; i < param.size(); i++) {
CV_Assert(param.get<int>(i) >= 0);
parameter.push_back(param.get<int>(i));
}
if (parameter.size() == 1)
parameter.resize(2, parameter[0]);
return true;
}
else
{
if (hasDefault)
{
parameter = defaultValue;
return true;
}
else
{
return false;
}
}
}
}
void getKernelSize(const LayerParams ¶ms, std::vector<size_t>& kernel)
{
if (!util::getParameter(params, "kernel", "kernel_size", kernel))
CV_Error(cv::Error::StsBadArg, "kernel_size (or kernel_h and kernel_w) not specified");
for (int i = 0; i < kernel.size(); i++)
CV_Assert(kernel[i] > 0);
}
void getStrideAndPadding(const LayerParams ¶ms, std::vector<size_t>& pads_begin, std::vector<size_t>& pads_end,
std::vector<size_t>& strides, cv::String& padMode, size_t kernel_size = 2)
{
if (params.has("pad_l") && params.has("pad_t") && params.has("pad_r") && params.has("pad_b")) {
CV_Assert(params.get<int>("pad_t") >= 0 && params.get<int>("pad_l") >= 0 &&
params.get<int>("pad_b") >= 0 && params.get<int>("pad_r") >= 0);
pads_begin.push_back(params.get<int>("pad_t"));
pads_begin.push_back(params.get<int>("pad_l"));
pads_end.push_back(params.get<int>("pad_b"));
pads_end.push_back(params.get<int>("pad_r"));
}
else {
util::getParameter(params, "pad", "pad", pads_begin, true, std::vector<size_t>(kernel_size, 0));
if (pads_begin.size() < 4)
pads_end = pads_begin;
else
{
pads_end = std::vector<size_t>(pads_begin.begin() + pads_begin.size() / 2, pads_begin.end());
pads_begin.resize(pads_begin.size() / 2);
}
CV_Assert(pads_begin.size() == pads_end.size());
}
util::getParameter(params, "stride", "stride", strides, true, std::vector<size_t>(kernel_size, 1));
padMode = "";
if (params.has("pad_mode"))
{
padMode = params.get<String>("pad_mode");
}
for (int i = 0; i < strides.size(); i++)
CV_Assert(strides[i] > 0);
}
}
void getPoolingKernelParams(const LayerParams ¶ms, std::vector<size_t>& kernel, bool &globalPooling,
std::vector<size_t>& pads_begin, std::vector<size_t>& pads_end,
std::vector<size_t>& strides, cv::String &padMode)
{
util::getStrideAndPadding(params, pads_begin, pads_end, strides, padMode);
globalPooling = params.has("global_pooling") &&
params.get<bool>("global_pooling");
if (globalPooling)
{
if(params.has("kernel_h") || params.has("kernel_w") || params.has("kernel_size"))
{
CV_Error(cv::Error::StsBadArg, "In global_pooling mode, kernel_size (or kernel_h and kernel_w) cannot be specified");
}
for (int i = 0; i < pads_begin.size(); i++) {
if (pads_begin[i] != 0 || pads_end[i] != 0)
CV_Error(cv::Error::StsBadArg, "In global_pooling mode, pads must be = 0");
}
for (int i = 0; i < strides.size(); i++) {
if (strides[i] != 1)
CV_Error(cv::Error::StsBadArg, "In global_pooling mode, strides must be = 1");
}
}
else
{
util::getKernelSize(params, kernel);
}
}
void getConvolutionKernelParams(const LayerParams ¶ms, std::vector<size_t>& kernel, std::vector<size_t>& pads_begin,
std::vector<size_t>& pads_end, std::vector<size_t>& strides, std::vector<size_t>& dilations, cv::String &padMode)
{
util::getKernelSize(params, kernel);
util::getStrideAndPadding(params, pads_begin, pads_end, strides, padMode, kernel.size());
util::getParameter(params, "dilation", "dilation", dilations, true, std::vector<size_t>(kernel.size(), 1));
for (int i = 0; i < dilations.size(); i++)
CV_Assert(dilations[i] > 0);
}
// From TensorFlow code:
// Total padding on rows and cols is
// Pr = (R' - 1) * S + Kr - R
// Pc = (C' - 1) * S + Kc - C
// where (R', C') are output dimensions, (R, C) are input dimensions, S
// is stride, (Kr, Kc) are filter dimensions.
// We pad Pr/2 on the left and Pr - Pr/2 on the right, Pc/2 on the top
// and Pc - Pc/2 on the bottom. When Pr or Pc is odd, this means
// we pad more on the right and bottom than on the top and left.
void getConvPoolOutParams(const std::vector<int>& inp, const std::vector<size_t>& kernel,
const std::vector<size_t>& stride, const String &padMode,
const std::vector<size_t>& dilation, std::vector<int>& out)
{
if (padMode == "VALID")
{
for (int i = 0; i < inp.size(); i++)
out.push_back((inp[i] - dilation[i] * (kernel[i] - 1) - 1 + stride[i]) / stride[i]);
}
else if (padMode == "SAME")
{
for (int i = 0; i < inp.size(); i++)
out.push_back((inp[i] - 1 + stride[i]) / stride[i]);
}
else
{
CV_Error(Error::StsError, "Unsupported padding mode");
}
}
void getConvPoolPaddings(const std::vector<int>& inp, const std::vector<size_t>& kernel,
const std::vector<size_t>& strides, const String &padMode,
std::vector<size_t>& pads_begin, std::vector<size_t>& pads_end)
{
if (padMode == "SAME" || padMode == "VALID")
{
pads_begin.assign(kernel.size(), 0);
pads_end.assign(kernel.size(), 0);
}
if (padMode == "SAME")
{
CV_Assert_N(kernel.size() == strides.size(), kernel.size() == inp.size());
for (int i = 0; i < pads_begin.size(); i++) {
// There are test cases with stride > kernel.
if (strides[i] <= kernel[i])
{
int pad = (kernel[i] - 1 - (inp[i] - 1 + strides[i]) % strides[i]) / 2;
pads_begin[i] = pads_end[i] = pad;
}
}
}
}
}
}
| 38.582645 | 145 | 0.595909 | [
"vector"
] |
29e0353b3da9dd869686adde791bf224547b5b14 | 7,037 | ipp | C++ | include/stats_incl/dens/dlogis.ipp | davidnsw/sss | 8ca2e4c28027e62ca1238724dc2912d2205e16b6 | [
"Apache-2.0"
] | null | null | null | include/stats_incl/dens/dlogis.ipp | davidnsw/sss | 8ca2e4c28027e62ca1238724dc2912d2205e16b6 | [
"Apache-2.0"
] | null | null | null | include/stats_incl/dens/dlogis.ipp | davidnsw/sss | 8ca2e4c28027e62ca1238724dc2912d2205e16b6 | [
"Apache-2.0"
] | null | null | null | /*################################################################################
##
## Copyright (C) 2011-2020 Keith O'Hara
##
## This file is part of the StatsLib C++ library.
##
## 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.
##
################################################################################*/
/*
* pdf of the univariate logistic distribution
*/
//
// single input
namespace internal
{
template<typename T>
statslib_constexpr
T
dlogis_log_compute(const T z, const T sigma_par)
noexcept
{
return( - z - stmath::log(sigma_par) - T(2)*stmath::log(T(1) + stmath::exp(-z)) );
}
template<typename T>
statslib_constexpr
T
dlogis_limit_vals(const T x, const T mu_par, const T sigma_par)
noexcept
{
return( // sigma == Inf
GCINT::is_posinf(sigma_par) ? \
T(0) :
// sigma finite; x == mu == Inf or -Inf
GCINT::all_posinf(x,mu_par) || GCINT::all_neginf(x,mu_par) ? \
STLIM<T>::quiet_NaN() :
// sigma == 0 and x-mu == 0
sigma_par == T(0) && x == mu_par ? \
STLIM<T>::infinity() :
//
T(0) );
}
template<typename T>
statslib_constexpr
T
dlogis_vals_check(const T x, const T mu_par, const T sigma_par, const bool log_form)
noexcept
{
return( !logis_sanity_check(x,mu_par,sigma_par) ? \
STLIM<T>::quiet_NaN() :
//
GCINT::any_inf(x,mu_par,sigma_par) ? \
log_if(dlogis_limit_vals(x,mu_par,sigma_par),log_form) :
//
exp_if(dlogis_log_compute((x-mu_par)/sigma_par,sigma_par), !log_form) );
}
template<typename T1, typename T2, typename T3, typename TC = common_return_t<T1,T2,T3>>
statslib_constexpr
TC
dlogis_type_check(const T1 x, const T2 mu_par, const T3 sigma_par, const bool log_form)
noexcept
{
return dlogis_vals_check(static_cast<TC>(x),static_cast<TC>(mu_par),
static_cast<TC>(sigma_par),log_form);
}
}
/**
* @brief Density function of the Logistic distribution
*
* @param x a real-valued input.
* @param mu_par the location parameter, a real-valued input.
* @param sigma_par the scale parameter, a real-valued input.
* @param log_form return the log-density or the true form.
*
* @return the density function evaluated at \c x.
*
* Example:
* \code{.cpp} stats::dlogis(2.0,1.0,2.0,false); \endcode
*/
template<typename T1, typename T2, typename T3>
statslib_constexpr
common_return_t<T1,T2,T3>
dlogis(const T1 x, const T2 mu_par, const T3 sigma_par, const bool log_form)
noexcept
{
return internal::dlogis_type_check(x,mu_par,sigma_par,log_form);
}
//
// vector/matrix input
namespace internal
{
#ifdef STATS_ENABLE_INTERNAL_VEC_FEATURES
template<typename eT, typename T1, typename T2, typename rT>
statslib_inline
void
dlogis_vec(const eT* __stats_pointer_settings__ vals_in, const T1 mu_par, const T2 sigma_par, const bool log_form,
rT* __stats_pointer_settings__ vals_out, const ullint_t num_elem)
{
EVAL_DIST_FN_VEC(dlogis,vals_in,vals_out,num_elem,mu_par,sigma_par,log_form);
}
#endif
}
/**
* @brief Density function of the Logistic distribution
*
* @param x a standard vector.
* @param mu_par the location parameter, a real-valued input.
* @param sigma_par the scale parameter, a real-valued input.
* @param log_form return the log-density or the true form.
*
* @return a vector of density function values corresponding to the elements of \c x.
*
* Example:
* \code{.cpp}
* std::vector<double> x = {0.0, 1.0, 2.0};
* stats::dlogis(x,1.0,2.0,false);
* \endcode
*/
#ifdef STATS_ENABLE_STDVEC_WRAPPERS
template<typename eT, typename T1, typename T2, typename rT>
statslib_inline
std::vector<rT>
dlogis(const std::vector<eT>& x, const T1 mu_par, const T2 sigma_par, const bool log_form)
{
STDVEC_DIST_FN(dlogis_vec,mu_par,sigma_par,log_form);
}
#endif
/**
* @brief Density function of the Logistic distribution
*
* @param X a matrix of input values.
* @param mu_par the location parameter, a real-valued input.
* @param sigma_par the scale parameter, a real-valued input.
* @param log_form return the log-density or the true form.
*
* @return a matrix of density function values corresponding to the elements of \c X.
*
* Example:
* \code{.cpp}
* arma::mat X = { {0.2, -1.7, 0.1},
* {0.9, 4.0, -0.3} };
* stats::dlogis(X,1.0,1.0,false);
* \endcode
*/
#ifdef STATS_ENABLE_ARMA_WRAPPERS
template<typename eT, typename T1, typename T2, typename rT>
statslib_inline
ArmaMat<rT>
dlogis(const ArmaMat<eT>& X, const T1 mu_par, const T2 sigma_par, const bool log_form)
{
ARMA_DIST_FN(dlogis_vec,mu_par,sigma_par,log_form);
}
template<typename mT, typename tT, typename T1, typename T2>
statslib_inline
mT
dlogis(const ArmaGen<mT,tT>& X, const T1 mu_par, const T2 sigma_par, const bool log_form)
{
return dlogis(X.eval(),mu_par,sigma_par,log_form);
}
#endif
/**
* @brief Density function of the Logistic distribution
*
* @param X a matrix of input values.
* @param mu_par the location parameter, a real-valued input.
* @param sigma_par the scale parameter, a real-valued input.
* @param log_form return the log-density or the true form.
*
* @return a matrix of density function values corresponding to the elements of \c X.
*
* Example:
* \code{.cpp}
* stats::dlogis(X,1.0,1.0,false);
* \endcode
*/
#ifdef STATS_ENABLE_BLAZE_WRAPPERS
template<typename eT, typename T1, typename T2, typename rT, bool To>
statslib_inline
BlazeMat<rT,To>
dlogis(const BlazeMat<eT,To>& X, const T1 mu_par, const T2 sigma_par, const bool log_form)
{
BLAZE_DIST_FN(dlogis,mu_par,sigma_par,log_form);
}
#endif
/**
* @brief Density function of the Logistic distribution
*
* @param X a matrix of input values.
* @param mu_par the location parameter, a real-valued input.
* @param sigma_par the scale parameter, a real-valued input.
* @param log_form return the log-density or the true form.
*
* @return a matrix of density function values corresponding to the elements of \c X.
*
* Example:
* \code{.cpp}
* stats::dlogis(X,1.0,1.0,false);
* \endcode
*/
#ifdef STATS_ENABLE_EIGEN_WRAPPERS
template<typename eT, typename T1, typename T2, typename rT, int iTr, int iTc>
statslib_inline
EigenMat<rT,iTr,iTc>
dlogis(const EigenMat<eT,iTr,iTc>& X, const T1 mu_par, const T2 sigma_par, const bool log_form)
{
EIGEN_DIST_FN(dlogis_vec,mu_par,sigma_par,log_form);
}
#endif
| 29.078512 | 115 | 0.67543 | [
"vector"
] |
29e0b32978dfd515b0b013f116e4ca8f44bd458c | 52,287 | cpp | C++ | libraries/distanceField/marchingCubes.cpp | dyollb/VegaFEM | 83bb9e52f68dec5511393af0469abd85cfff4a7f | [
"BSD-3-Clause"
] | null | null | null | libraries/distanceField/marchingCubes.cpp | dyollb/VegaFEM | 83bb9e52f68dec5511393af0469abd85cfff4a7f | [
"BSD-3-Clause"
] | null | null | null | libraries/distanceField/marchingCubes.cpp | dyollb/VegaFEM | 83bb9e52f68dec5511393af0469abd85cfff4a7f | [
"BSD-3-Clause"
] | null | null | null | /*************************************************************************
* *
* Vega FEM Simulation Library Version 4.0 *
* *
* "distance field" library , Copyright (C) 2007 CMU, 2018 USC *
* All rights reserved. *
* *
* Code authors: Danyong Zhao, Jernej Barbic *
* http://www.jernejbarbic.com/vega *
* *
* Research: Jernej Barbic, Hongyi Xu, Yijing Li, *
* Danyong Zhao, Bohan Wang, *
* Fun Shing Sin, Daniel Schroeder, *
* Doug L. James, Jovan Popovic *
* *
* Funding: National Science Foundation, Link Foundation, *
* Singapore-MIT GAMBIT Game Lab, *
* Zumberge Research and Innovation Fund at USC, *
* Sloan Foundation, Okawa Foundation, *
* USC Annenberg Foundation *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the BSD-style license that is *
* included with this library in the file LICENSE.txt *
* *
* 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 file *
* LICENSE.TXT for more details. *
* *
*************************************************************************/
/*
The labelings of the vertices, edges and faces of the cube follow the one in:
Thomas Lewiner, Hélio Lopes, Antônio Wilson Vieira, Geovan Tavares:
Efficient implementation of marching cubes cases with topological guarantees
Journal of Graphics Tools 8(2): pp. 1-15, 2003
*/
// when a static table is not used, the table is generated from scratch using our code ("createTable()")
// otherwise, the marching cubes table is read from a static array (that was previously generated using "createTable()")
#define USE_STATIC_TABLE
#include <float.h>
#include <memory.h>
#include <string>
#include <algorithm>
#include <set>
#include <iomanip>
#include <fstream>
#include <cassert>
#include <unordered_map>
using namespace std;
#include "vec3d.h"
#include "marchingCubes.h"
#include "performanceCounter.h"
#ifdef USE_TBB
#include <tbb/tbb.h>
#else
#include "range.h"
#endif
static const unsigned char edge_vertices[12][2] =
{
{ 0, 1 },
{ 1, 2 },
{ 2, 3 },
{ 0, 3 },
{ 4, 5 },
{ 5, 6 },
{ 6, 7 },
{ 4, 7 },
{ 0, 4 },
{ 1, 5 },
{ 2, 6 },
{ 3, 7 } };
static const unsigned char face_vertices[6][4] =
{
{ 0, 1, 4, 5 },
{ 1, 2, 5, 6 },
{ 2, 3, 6, 7 },
{ 0, 3, 4, 7 },
{ 0, 1, 2, 3 },
{ 4, 5, 6, 7 } };
/*
The 24 symmetries are:
Identity
3 rotations (by +- pi/2 or pi) about centres of 3 pairs of opposite faces. (9)
1 rotation (by pi) about centres of 6 pairs of opposite edges. (6)
2 rotations (by +- 2pi/3) about 4 pairs of opposite vertices (diagonals). (8)
*/
// this table was generated manually, by physically manufacturing two cubes,
// labeling the corners and applying each transformation
static const unsigned char cubeSymmetryVertices[25][8] =
{
{ 0, 1, 2, 3, 4, 5, 6, 7 }, // identity 1
{ 3, 2, 6, 7, 0, 1, 5, 4 }, // rotation by +pi/2 about faces 1,3 2
{ 1, 5, 6, 2, 0, 4, 7, 3 }, // rotation by +pi/2 about faces 0,2 3
{ 1, 2, 3, 0, 5, 6, 7, 4 }, // rotation by +pi/2 about faces 4,5 4
{ 4, 5, 1, 0, 7, 6, 2, 3 }, // rotation by -pi/2 about faces 1,3 5
{ 4, 0, 3, 7, 5, 1, 2, 6 }, // rotation by -pi/2 about faces 0,2 6
{ 3, 0, 1, 2, 7, 4, 5, 6 }, // rotation by -pi/2 about faces 4,5 7
{ 7, 6, 5, 4, 3, 2, 1, 0 }, // rotation by pi about faces 1,3 8
{ 5, 4, 7, 6, 1, 0, 3, 2 }, // rotation by pi about faces 0,2 9
{ 2, 3, 0, 1, 6, 7, 4, 5 }, // rotation by pi about faces 4,5 10
{ 1, 0, 4, 5, 2, 3, 7, 6 }, // rotation by pi about edges 0, 6 11
{ 6, 2, 1, 5, 7, 3, 0, 4 }, // rotation by pi about edges 1, 7 12
{ 6, 7, 3, 2, 5, 4, 0, 1 }, // rotation by pi about edges 2, 4 13
{ 3, 7, 4, 0, 2, 6, 5, 1 }, // rotation by pi about edges 3, 5 14
{ 4, 7, 6, 5, 0, 3, 2, 1 }, // rotation by pi about edges 8, 10 15
{ 6, 5, 4, 7, 2, 1, 0, 3 }, // rotation by pi about edges 9, 11 16
{ 0, 4, 5, 1, 3, 7, 6, 2 }, // rotation by +2pi/3 about vertices 0, 6 17
{ 5, 1, 0, 4, 6, 2, 3, 7 }, // rotation by +2pi/3 about vertices 1, 7 18
{ 5, 6, 2, 1, 4, 7, 3, 0 }, // rotation by +2pi/3 about vertices 2, 4
{ 7, 4, 0, 3, 6, 5, 1, 2 }, // rotation by +2pi/3 about vertices 3, 5
{ 0, 3, 7, 4, 1, 2, 6, 5 }, // rotation by -2pi/3 about vertices 0, 6
{ 2, 1, 5, 6, 3, 0, 4, 7 }, // rotation by -2pi/3 about vertices 1, 7
{ 7, 3, 2, 6, 4, 0, 1, 5 }, // rotation by -2pi/3 about vertices 2, 4
{ 2, 6, 7, 3, 1, 5, 4, 0 }, // rotation by -2pi/3 about vertices 3, 5
{ 4, 5, 6, 7, 0, 1, 2, 3 } };
// The positions of the eight vertices
static const unsigned char vertex_position[8][3] =
{
{ 0, 0, 0 },
{ 1, 0, 0 },
{ 1, 1, 0 },
{ 0, 1, 0 },
{ 0, 0, 1 },
{ 1, 0, 1 },
{ 1, 1, 1 },
{ 0, 1, 1 }
};
// The four corners of the six faces
static const unsigned char face_vertex[6][4] =
{
{ 0, 1, 5, 4 },
{ 1, 2, 6, 5 },
{ 3, 2, 6, 7 },
{ 0, 3, 7, 4 },
{ 0, 1, 2, 3 },
{ 4, 5, 6, 7 }
};
// edge_map and edge_vertex: how vertices are placed around an edge
/*
edge_map
first index can be 0, 1 or 2. 0 means this edge is parallel to X axis. 1 means parallel to Y axis. 2 means parallel to Z axis.
second index: which specific place is the edge in the X, Y or Z direction.
This to indices point to the start position of edge_vertex
*/
static const unsigned char edge_map[12][2] =
{
{ 0, 0 },
{ 1, 0 },
{ 0, 2 },
{ 1, 2 },
{ 0, 6 },
{ 1, 6 },
{ 0, 4 },
{ 1, 4 },
{ 2, 0 },
{ 2, 6 },
{ 2, 4 },
{ 2, 2 } };
/*
edge_vertex: how the 8 vertices are placed around an edge
The start vertex is determined by edge_map, and then pick up 8 consecutive vertices.
The first two vertices are the two endpoints of this edge.
The next 6 vertices make up 3 pairs(two consecutive vertices make up one pair). Each pair is the two endpoints of an edge whose direction is the same of this edge.
The four edges are in clockwise or counter clockwise (depending on how you look).
*/
static const unsigned char edge_vertex[3][14] =
{
{ 0, 1, 3, 2, 7, 6, 4, 5, 0, 1, 3, 2, 7, 6 }, // X direction
{ 1, 2, 0, 3, 4, 7, 5, 6, 1, 2, 0, 3, 4, 7 }, // Y direction
{ 0, 4, 3, 7, 2, 6, 1, 5, 0, 4, 3, 7, 2, 6 } // Z direction
};
#ifdef USE_STATIC_TABLE
#include "marchingCubesTable.h"
#else
static char cubeSymmetryEdges[25][13]; // determined algorithmically from cubeSymmetryVertices
static char cubeSymmetryFaces[24][6]; // determined algorithmically from cubeSymmetryVertices
// if first entry is negative, this is a representative case, second entry has no meaning (it is always set to 0)
// if first entry i is non-negative, this is a symmetry and/or complement of the representative case i; second entry specifies the symmetry and/or complement;
// if second entry j is positive, this is a symmetry using the permutation j from cubeSymmetryVertices;
// if second entry j is zero or negative, this is symmetry |j|, plus complement
// can determine algorithmically from cubeSymmetryVertices
static int marchingCubeSymmetries[256][3];
//used to build the look up table for case 13 mentioned in Chernyaev’s paper
const int oppositeFace[3][2] = {{1, 3}, {2, 4}, {5, 6}};
const int vtxAdjacentFaces[8][3] = {{1,4,5}, {1,2,5}, {2,3,5}, {3,4,5}, {1,4,6}, {1,2,6}, {2,3,6}, {3,4,6}};
static const unsigned char caseNumber[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 11, 9, 14, 12, 10, 13 };
static const char representativeCase1[3] = { 8, 3, 0 };
static const char representativeCase2[6] = { 3, 1, 8, 9, 8, 1 };
static const char representativeCase3_1[6] = { 1, 2, 10, 8, 3, 0 };
static const char representativeCase3_2[12] = { 8, 3, 10, 10, 1, 0, 0, 8, 10, 2, 10, 3 };
static const char representativeCase4_1[6] = { 6, 5, 10, 3, 0, 8 };
static const char representativeCase4_2[18] = { 8, 6, 5, 8, 5, 0, 6, 3, 10, 0, 5, 10, 0, 10, 3, 3, 6, 8 };
static const char representativeCase5[9] = { 8, 3, 2, 10, 8, 2, 10, 9, 8 };
static const char representativeCase6_1_1[9] = { 6, 5, 10, 8, 1, 9, 8, 3, 1 };
static const char representativeCase6_2[15] = { 8, 6, 5, 10, 3, 1, 8, 3, 6, 9, 8, 5, 6, 3, 10 };
static const char representativeCase7_1[9] = { 1, 2, 10, 9, 5, 4, 8, 3, 0 };
static const char representativeCase7_2_0[15] = { 1, 2, 10, 4, 8, 3, 5, 4, 3, 0, 5, 3, 5, 0, 9 };
static char representativeCase7_2_1[15]; // determined algorithmically
static char representativeCase7_2_2[15]; // determined algorithmically
static const char representativeCase7_3_0[27] = { 12, 1, 2, 12, 9, 1, 5, 12, 10, 9, 12, 0, 12, 8, 3, 12, 5, 4, 0, 12, 3, 10, 12, 2, 4, 8, 12 };
static char representativeCase7_3_1[27]; // determined algorithmically
static char representativeCase7_3_2[27]; // determined algorithmically
static const char representativeCase7_4_1[15] = { 5, 4, 8, 3, 2, 8, 9, 1, 0, 2, 5, 8, 5, 2, 10 };
static const char representativeCase8[6] = { 10, 9, 8, 8, 11, 10 };
static const char representativeCase9[12] = { 3, 5, 8, 3, 10, 5, 2, 10, 3, 8, 5, 4 };
static const char representativeCase10_1_1[12] = { 11, 7, 10, 3, 1, 8, 1, 9, 8, 7, 5, 10 };
static char representativeCase10_1_1_[12]; // determined algorithmically
static const char representativeCase10_1_2[24] = { 11, 3, 10, 9, 7, 5, 9, 5, 10, 1, 10, 3, 7, 9, 8, 3, 7, 8, 9, 10, 1, 7, 3, 11 };
static const char representativeCase10_2[24] = { 12, 3, 1, 7, 12, 11, 12, 7, 5, 12, 8, 3, 1, 10, 12, 11, 12, 10, 5, 9, 12, 12, 9, 8 };
static char representativeCase10_2_[24]; // determined algorithmically
static const char representativeCase11[12] = { 4, 7, 9, 2, 10, 9, 7, 3, 2, 7, 2, 9 };
static const char representativeCase12_1_1[12] = { 3, 2, 10, 8, 3, 10, 6, 11, 7, 8, 10, 9 };
static char representativeCase12_1_1_[12]; // determined algorithmically
static const char representativeCase12_2[24] = { 12, 6, 11, 9, 12, 10, 8, 7, 12, 2, 12, 3, 3, 12, 11, 12, 9, 8, 12, 2, 10, 6, 12, 7 };
static char representativeCase12_2_[24]; // determined algorithmically
/* The subcases of Case 13 are not clearly defined in Lewiner's paper, they are described in Chernyaev’s paper */
static const char representativeCase13_1[12] = { 10, 1, 2, 7, 6, 11, 0, 8, 3, 5, 4, 9 };
static char representativeCase13_1_[12]; // determined algorithmically
static const char representativeCase13_2_0[18] = { 1, 2, 10, 11, 7, 6, 5, 4, 3, 0, 9, 5, 4, 8, 3, 5, 3, 0 };
static char representativeCase13_2[5][18]; // determined algorithmically
static char representativeCase13_2_0_[18]; // determined algorithmically
static char representativeCase13_2_[5][18]; // determined algorithmically
static const char representativeCase13_3_0[30] = { 4, 12, 5, 12, 2, 10, 1, 12, 9, 12, 1, 2, 12, 8, 3, 5, 12, 10, 9, 12, 0, 6, 11, 7, 3, 0, 12, 8, 12, 4 };
static char representativeCase13_3[11][30]; // determined algorithmically
static char representativeCase13_3_0_[30]; // determined algorithmically
static char representativeCase13_3_[11][30]; // determined algorithmically
static const char representativeCase13_4_0[36] = { 12, 4, 8, 10, 5, 12, 0, 12, 3, 4, 12, 7, 2, 12, 1, 12, 0, 9, 1, 12, 9, 12, 11, 7, 8, 3, 12, 6, 12, 5, 2, 10, 12, 6, 11, 12 };
static char representativeCase13_4[3][36]; // determined algorithmically
static const char representativeCase13_5_1_0[18] = { 2, 10, 4, 4, 8, 2, 1, 0, 9, 2, 8, 3, 6, 11, 7, 4, 10, 5 };
static char representativeCase13_5_1[3][18]; // determined algorithmically
static const char representativeCase14[12] = { 2, 6, 3, 6, 5, 9, 6, 9, 8, 3, 6, 8 };
// the numbers of faces should be used in face test for all 256 cases
static vector<char> faceTest_num[256];
// may be removed later
static char interiorTest_num[256];
static vector<char> ambiguityTable[15];
/*
"triangleTable" is a three-dimensional data structure.
The first dimension is the 256 cases, depending on the signs of values of eight corners.
The second dimension is for each case, there may exist some subcases depending on the results of face tests and interior tests.
The third dimension is an array, the midpoints of each three consecutive edges form a triangle and a boolean value indicating whether this case has an point in the center of a cube, encoded as 12.
*/
static vector<vector<unsigned char> > triangleTable[256];
static vector<bool> centerVertexNeeded[256];
/*
"rc" is a three-dimensional data structure.
The first dimension is the 15 representive cases, depending on the signs of values of eight corners.
The second dimension is for each representive case, there may exist some subcases depending on the results of face tests and interior tests.
The third dimension is an array, the center of the cube, encoded as 12, the midpoints of each three consecutive edges form a triangle.
*/
static std::vector<std::vector<char> > rc[15];
static const char faceTest3[1] = { 5 };
static const char faceTest6[1] = { 2 };
static const char faceTest7[3] = { 1, 2, 5 };
static const char faceTest10[2] = { 2, 4 };
static const char faceTest12[2] = { 4, 3 };
static const char faceTest13[6] = { 1, 2, 3, 4, 5, 6 };
static const char * faceTest_number[15] = { 0, 0, 0, faceTest3, 0, 0, faceTest6, faceTest7, 0, 0, faceTest10, 0, faceTest12, faceTest13, 0 };
static const char faceTest_size[15] = { 0, 0, 0, 1, 0, 0, 1, 3, 0, 0, 2, 0, 2, 6, 0 };
static const char interiorTest_number[15] = { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 };
// Whether the look up tables have been loaded. Only need to be loaded once.
static bool tableLoaded = false;
#endif
MarchingCubes::MarchingCubes(const DistanceFieldBase * field, float iv) : distanceFieldBase(field), isoValue(iv)
{
resolutionX = distanceFieldBase->getResolutionX();
resolutionY = distanceFieldBase->getResolutionY();
resolutionZ = distanceFieldBase->getResolutionZ();
}
/*
Perform the face test: whether the product of the two positive values is larger than the product of the two negative values.
If the face is negative, the result needs to be reversed.
*/
bool MarchingCubes::faceTest(int face_, float cube[8])
{
int face = abs(face_) - 1;
return (((cube[face_vertex[face][0]] * cube[face_vertex[face][2]] > cube[face_vertex[face][1]] * cube[face_vertex[face][3]])
== (face_ > 0)) == (cube[face_vertex[face][0]] > 0));
}
/*
Perform the interior test.
If the face is negative, the result needs to be reversed.
*/
int MarchingCubes::interiorTest(int edge, float cube[8])
{
//printf("%d", edge);
//for (int p = 0; p < 8; p++) printf(" %.5f", cube[p]); printf("\n");
double aux1 = (cube[1] - cube[0]) * (cube[6] - cube[7]) - (cube[5] - cube[4]) * (cube[2] - cube[3]);
double aux2 = cube[0] * (cube[6] - cube[7]) - cube[4] * (cube[2] - cube[3]) + cube[7] * (cube[1] - cube[0]) - cube[3] * (cube[5] - cube[4]);
double s = -aux2 / (2.0 * aux1);
if ((s < 0.0) || (s > 1.0))
return edge > 0;
double A = cube[0] + (cube[1] - cube[0]) * s;
double B = cube[4] + (cube[5] - cube[4]) * s;
double C = cube[7] + (cube[6] - cube[7]) * s;
double D = cube[3] + (cube[2] - cube[3]) * s;
int result = ((A >= 0)) | ((B >= 0) << 1) | ((C >= 0) << 2) | ((D >= 0) << 3);
switch (result)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 6:
case 8:
case 9:
case 12:
return edge > 0;
case 7:
case 11:
case 13:
case 14:
case 15:
return edge < 0;
case 5:
return (A * C < B * D) == (edge > 0);
case 10:
return (A * C >= B * D) == (edge > 0);
default:
return -1;
}
}
ObjMesh * MarchingCubes::compute()
{
#ifndef USE_STATIC_TABLE
if (tableLoaded == false)
createTable(); // data needs to be loaded
//printTable();
#endif
int gpResX = distanceFieldBase->getResolutionX()+1; // grid point resolution
int gpResY = distanceFieldBase->getResolutionY()+1;
int gpResZ = distanceFieldBase->getResolutionZ()+1;
if (gpResX <= 1 || gpResY <= 1 || gpResZ <= 1)
return new ObjMesh();
double gridSize[3];
distanceFieldBase->getGridSpacing(gridSize, gridSize+1, gridSize+2);
// cout << "Begin computing: " << endl;
PerformanceCounter pc;
//
// vector<Vec3d> allVertices;
// vector<int> allTriangles;
// // edgeInersectionID: an ID to each edge if it intersects with the iso-surface
// unordered_map<int64_t, int> edgeIntersectionID2MeshVtxID;
pc.StartCounter();
vector<Vec3d> allVertices;
vector<int> allTriangles;
unordered_map<int64_t, int> edgeInterID2AllMeshVtxID;
#ifdef USE_TBB
struct ThreadLocalData
{
vector<Vec3d> vertices;
vector<int> triangles;
unordered_map<int64_t, int> edgeInterID2LocalVtxID;
};
tbb::enumerable_thread_specific<ThreadLocalData> threadLocalData;
// loop over all voxels again to compute triangles
tbb::parallel_for(tbb::blocked_range<int>(0, distanceFieldBase->getResolutionZ()), [&](const tbb::blocked_range<int> & rng)
// for (int k = 0; k < distanceFieldBase->getResolutionZ(); k++)
{
auto & localData = threadLocalData.local();
auto & edgeInterID2MeshVtxID = localData.edgeInterID2LocalVtxID;
auto & meshVertices = localData.vertices;
auto & meshTriangles = localData.triangles;
#else
Range<int> rng(0, distanceFieldBase->getResolutionZ());
auto & edgeInterID2MeshVtxID = edgeInterID2AllMeshVtxID;
auto & meshVertices = allVertices;
auto & meshTriangles = allTriangles;
#endif
for (int k = rng.begin(); k != rng.end(); ++k)
for (int j = 0; j < distanceFieldBase->getResolutionY(); ++j)
for (int i = 0; i < distanceFieldBase->getResolutionX(); ++i)
{
float cube[8];
//get distance field values at 8 cube vertices
for (int p = 0; p < 8; p++)
{
cube[p] = getDistance(i + vertex_position[p][0], j + vertex_position[p][1], k + vertex_position[p][2]);
}
// raw case [0,255] -> major case [0,14]
int rawCaseNumber = 0; //raw case number, 0-255
for (int p = 0; p < 8; p++)
rawCaseNumber |= ((cube[p] > 0) << p);
//get the major case number, 0-14
int majorCaseNumber = marchingCubeSymmetries[rawCaseNumber][0];
if ((majorCaseNumber == 0) || (majorCaseNumber == 255))
continue; //No triangles
int faceAndInteriorTestResult = 0;
int faceTestNumCase = 0;
#ifdef USE_STATIC_TABLE
// the first entry in the faceTest_num table stores number of entries
faceTestNumCase = faceTest_num[rawCaseNumber][0];
if (faceTestNumCase > 0)
for (int p = faceTestNumCase; p > 0; p--)
{
int o = faceTest(faceTest_num[rawCaseNumber][p], cube);
faceAndInteriorTestResult = (faceAndInteriorTestResult << 1) | o;
}
#else
faceTestNumCase = int(faceTest_num[rawCaseNumber].size());
if (!faceTest_num[rawCaseNumber].empty())
for (vector<char>::const_iterator p = faceTest_num[rawCaseNumber].end() - 1; p >= faceTest_num[rawCaseNumber].begin(); p--)
{
int o = faceTest(*p, cube);
faceAndInteriorTestResult = (faceAndInteriorTestResult << 1) | o;
}
#endif
if (interiorTest_num[rawCaseNumber] != 0)
faceAndInteriorTestResult = faceAndInteriorTestResult | (interiorTest(interiorTest_num[rawCaseNumber], cube) << faceTestNumCase);
int ambiguityNumber = ambiguityTable[majorCaseNumber][faceAndInteriorTestResult];
if (ambiguityNumber < 0)
{
cerr << "Internal error in computing marching cubes, ambiguityNumber is: " << ambiguityNumber << endl;
continue;
}
//Get the list of triangle vertices
#ifdef USE_STATIC_TABLE
unsigned char * triangles = NULL;
int numTri = 0;
unsigned char ** tableEntry = triangleTable[rawCaseNumber];
bool hasCenter = false;
assert(tableEntry);
{
unsigned char * tableEntry2 = tableEntry[ambiguityNumber];
numTri = tableEntry2[0] / 3;
hasCenter = (tableEntry2[1] != 0);
triangles = tableEntry2 + 2;
}
#else
const vector<unsigned char> & triangles = triangleTable[rawCaseNumber][ambiguityNumber];
bool hasCenter = centerVertexNeeded[rawCaseNumber][ambiguityNumber];
int numTri = triangles.size() / 3;
#endif
int cubeVtxIndices[13] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
Vec3d center = Vec3d(0, 0, 0); // an additional vertex in the middle of the cube may be needed
int sum = 0;
for (int edgeID = 0; edgeID < 12; edgeID++) // go to 12 edges of the cube
{
int node = edge_vertex[edge_map[edgeID][0]][edge_map[edgeID][1]];
int direction = edge_map[edgeID][0]; //can be 0, 1 or 2. 0 means this edge is parallel to X axis. 1 means parallel to Y axis. 2 means parallel to Z axis.
assert(direction >= 0 && direction <= 2);
int _i = i + vertex_position[node][0];
int _j = j + vertex_position[node][1];
int _k = k + vertex_position[node][2];
float edgeStartValue = getDistance(_i, _j, _k);
float edgeEndValue = getDistance(_i+(direction==0), _j+(direction==1), _k+(direction==2));
if (edgeStartValue * edgeEndValue <= 0 && edgeEndValue != 0) // TODO: check degenerate case here
{
// int64_t packedIndex = 3 * (_j * (resX+1) + _i) + direction;
int64_t edgeInterID = 3 * ((int64_t)gpResX*gpResY*_k + _j*gpResX + _i) + direction;
auto it = edgeInterID2MeshVtxID.find(edgeInterID);
if (it == edgeInterID2MeshVtxID.end())
{
// compute pos
Vec3d pos(0.0);
Vec3d gridPoint = distanceFieldBase->getGridPosition(_i,_j,_k);
if (direction == 0)
{
pos = Vec3d(gridPoint[0] + gridSize[0] * edgeStartValue / (edgeStartValue - edgeEndValue), gridPoint[1], gridPoint[2]);
}
else if (direction == 1)
{
pos = Vec3d(gridPoint[0], gridPoint[1] + gridSize[1] * edgeStartValue / (edgeStartValue - edgeEndValue), gridPoint[2]);
}
else // direction == 2
{
pos = Vec3d(gridPoint[0], gridPoint[1], gridPoint[2] + gridSize[2] * edgeStartValue / (edgeStartValue - edgeEndValue));
}
cubeVtxIndices[edgeID] = meshVertices.size();
meshVertices.push_back(pos);
edgeInterID2MeshVtxID.emplace(edgeInterID, cubeVtxIndices[edgeID]);
}
else
{
cubeVtxIndices[edgeID] = it->second;
}
if (hasCenter)
{
center += meshVertices[cubeVtxIndices[edgeID]];
sum++;
}
}
}
if (hasCenter)
{
center /= sum;
// store this vertex globally in allVertices
cubeVtxIndices[12] = meshVertices.size();
meshVertices.push_back(center);
int64_t centerID = - (int64_t)gpResX*gpResY*k + j*gpResX + i - 1; // define an ID to store center vtx into edgeInterID2LocalVtxID
edgeInterID2MeshVtxID.emplace(centerID, cubeVtxIndices[12]);
}
for(int triID = 0; triID < numTri; triID++)
{
if ((triangles[3*triID+0] >= 13) || (triangles[3*triID+1] >= 13) || (triangles[3*triID+2] >= 13)) // this is for safety
continue;
int v1 = cubeVtxIndices[triangles[3*triID+0]];
int v2 = cubeVtxIndices[triangles[3*triID+1]];
int v3 = cubeVtxIndices[triangles[3*triID+2]];
assert(v1 != -1 && v2 != -1 && v3 != -1);
meshTriangles.push_back(v1);
meshTriangles.push_back(v2);
meshTriangles.push_back(v3);
}
} // end for (distance loop)
#ifdef USE_TBB
}); //end for locations
// pc.StopCounter();
// cout << "Large loop: " << pc.GetElapsedTime() << endl;
// pc.StartCounter();
for(const auto & local : threadLocalData)
{
vector<int> localVtxID2AllVtxID(local.vertices.size());
assert(local.edgeInterID2LocalVtxID.size() == local.vertices.size());
for(const auto & localPair : local.edgeInterID2LocalVtxID)
{
int localID = localPair.second;
assert(localID < (int)localVtxID2AllVtxID.size());
auto allIt = edgeInterID2AllMeshVtxID.find(localPair.first);
if (allIt == edgeInterID2AllMeshVtxID.end())
{
int globalID = allVertices.size();
edgeInterID2AllMeshVtxID.emplace(localPair.first, globalID);
localVtxID2AllVtxID[localID] = globalID;
allVertices.push_back(local.vertices[localID]);
}
else
{
localVtxID2AllVtxID[localID] = allIt->second;
}
}
for(size_t i = 0; i < local.triangles.size(); i++)
{
allTriangles.push_back(localVtxID2AllVtxID[local.triangles[i]]);
}
}
#endif
ObjMesh * objMesh = new ObjMesh(allVertices.size(), (const double*)&allVertices[0], allTriangles.size() / 3, allTriangles.data());
// pc.StopCounter();
// cout << "build objMesh: " << pc.GetElapsedTime() << endl;
return objMesh;
}
namespace
{
class ObjSorter
{
public:
ObjSorter(const ObjMesh * objMesh) : objMesh(objMesh) {}
bool operator() (const int a, const int b)
{
return objMesh->getPosition(a) < objMesh->getPosition(b);
}
bool operator () (const ObjMesh::Face a, ObjMesh::Face b)
{
return triple<Vec3d, Vec3d, Vec3d>(objMesh->getPosition(a.getVertex(0)), objMesh->getPosition(a.getVertex(1)), objMesh->getPosition(a.getVertex(2))) < triple<Vec3d, Vec3d, Vec3d>(objMesh->getPosition(b.getVertex(0)), objMesh->getPosition(b.getVertex(1)), objMesh->getPosition(b.getVertex(2))) ;
}
protected:
const ObjMesh * objMesh;
};
void sortMesh(ObjMesh * objMesh)
{
ObjSorter sorter(objMesh);
//sort vertices
vector <int> a(objMesh->getNumVertices());
for (size_t i = 0; i < objMesh->getNumVertices(); i++)
a[i] = i;
sort(a.begin(), a.end(), sorter);
vector <int> b(objMesh->getNumVertices());
for (size_t i = 0; i < objMesh->getNumVertices(); i++)
b[a[i]] = i;
objMesh->renumberVertices(b);
//sort faces
const ObjMesh::Group *group = objMesh->getGroupHandle(0);
int n = group->getNumFaces();
vector <ObjMesh::Face> faces(n);
for (int i = 0; i < n; i++)
{
const ObjMesh::Face *face = group->getFaceHandle(i);
int _min = 0;
int m = face->getNumVertices();
for(int j = 1; j < m; j++)
if (objMesh->getPosition(face->getVertex(j)) < objMesh->getPosition(face->getVertex(_min))) _min = j;
for (int j = 0; j < m; j++)
faces[i].addVertex(face->getVertex((j + _min) % m));
}
sort(faces.begin(), faces.end(), sorter);
objMesh->removeGroup(0);
objMesh->addGroup("Sorted faces");
for (int i = 0; i < n; i++)
objMesh->addFaceToGroup(faces[i], 0);
}
}
ObjMesh * MarchingCubes::compute(const DistanceFieldBase * distanceFieldBase, float isoValue)
{
MarchingCubes m(distanceFieldBase, isoValue);
ObjMesh * ret = m.compute();
sortMesh(ret);
return ret;
}
#ifdef USE_STATIC_TABLE
//create dummy functions
void MarchingCubes::printTable() {}
void MarchingCubes::createTable() {}
#else
// --- the functions below are used to create the case tables ---
static void binaray(int num, int * array)
{
for (int i = 0; i < 8; i++)
{
array[i] = num & 0x1;
num >>= 1;
}
}
static int permute(int src_, int dst_, int transform)
{
int src[8], dst[8], permute[8];
binaray(src_, src);
binaray(dst_, dst);
int i;
for (i = 0; i < 8; i++)
permute[i] = src[cubeSymmetryVertices[transform][i]];
for (i = 0; i < 8; i++)
{
if (permute[i] != dst[i])
break;
}
if (i == 8)
return 1;
for (i = 0; i < 8; i++)
{
if (permute[i] != 1 - dst[i])
break;
}
if (i == 8)
return -1;
return 0;
}
static inline int f_hash_edge(int a, int b)
{
return a * a + b * b;
}
static inline int f_hash_face(int a, int b, int c, int d)
{
return a + b + c + d + (a > 0 && b > 0 && c > 0 && d > 0);
}
static void permute_face(const char *src, char *dst, int n, int permute)
{
int permute_ = abs(permute);
for (int i = 0; i < n; i++)
dst[i] = cubeSymmetryFaces[permute_][src[i] - 1] + 1;
if (permute <= 0)
{
for (int i = 0; i < n; i++)
dst[i] = -dst[i];
}
}
static void permute_edge(const char *src, char *dst, int n, int permute)
{
int permute_ = abs(permute);
for (int i = 0; i < n; i++)
dst[i] = cubeSymmetryEdges[permute_][(unsigned char) src[i]];
if (permute <= 0)
{
for (int i = 1; i < n; i += 3)
swap(dst[i - 1], dst[i + 1]);
}
}
static vector<char> make_vector_impl(const char *p, int n)
{
vector<char> ret;
ret.resize(n);
memcpy(&ret[0], p, sizeof(char) * n);
return ret;
}
static bool violate(int k, vector<vector<int> >& binaryRepresentation)
{
int p = 0, n = 0;
for (int i = 0; i < 3; i++)
{
bool r0 = find(binaryRepresentation[k].begin(), binaryRepresentation[k].end(), oppositeFace[i][0]) == binaryRepresentation[k].end();
bool r1 = find(binaryRepresentation[k].begin(), binaryRepresentation[k].end(), oppositeFace[i][1]) == binaryRepresentation[k].end();
n += r0 && r1;
p += !(r0 || r1);
}
return (n > 0) && (p > 0);
}
static bool compare(const int *a, const int *b)
{
for (int i = 0; i < 3; i++)
if (a[i] != b[i]) return false;
return true;
}
static bool cmp(const vector<int> a, const vector<int> b)
{
bool interiora = ((a.size() == 3) && (compare(&a[0], vtxAdjacentFaces[1]) || compare(&a[0], vtxAdjacentFaces[3]) || compare(&a[0], vtxAdjacentFaces[4]) || compare(&a[0], vtxAdjacentFaces[6])));
bool interiorb = ((b.size() == 3) && (compare(&b[0], vtxAdjacentFaces[1]) || compare(&b[0], vtxAdjacentFaces[3]) || compare(&b[0], vtxAdjacentFaces[4]) || compare(&b[0], vtxAdjacentFaces[6])));
if (!interiora && interiorb)
return true;
if (interiora && !interiorb)
return false;
if (a.size() < b.size())
return true;
if (a.size() > b.size())
return false;
if (a.size() <= 3)
{
for (unsigned int i = 0; i < a.size(); i++)
{
if (a[i] < b[i])
return true;
if (a[i] > b[i])
return false;
}
return true;
}
else
{
for (int i = 0; i < 6; i++)
{
bool ra = find(a.begin(), a.end(), i) == a.end();
bool rb = find(b.begin(), b.end(), i) == b.end();
if (ra && !rb)
return true;
if (!ra && rb)
return false;
}
return true;
}
}
static vector<int> make_vector13(unsigned int p)
{
vector <int> ret;
for (int i = 1; i <= 6; i++)
{
if ((p | ((1 << i) >> 1)) == p)
ret.push_back(i);
}
return ret;
}
#define make(x, y, z) permute_edge(x, y, sizeof(x) / sizeof(x[0]), z)
#define make_vector(x) make_vector_impl(x, sizeof(x) / sizeof(x[0]))
void MarchingCubes::createTable()
{
// fill the ambiguity table
ambiguityTable[0].push_back(0);
ambiguityTable[1].push_back(0);
ambiguityTable[2].push_back(0);
ambiguityTable[3].push_back(0);
ambiguityTable[3].push_back(1);
ambiguityTable[4].push_back(1);
ambiguityTable[4].push_back(0);
ambiguityTable[5].push_back(0);
ambiguityTable[6].push_back(0);
ambiguityTable[6].push_back(1);
ambiguityTable[7].push_back(0);
ambiguityTable[7].push_back(1);
ambiguityTable[7].push_back(2);
ambiguityTable[7].push_back(4);
ambiguityTable[7].push_back(3);
ambiguityTable[7].push_back(5);
ambiguityTable[7].push_back(6);
ambiguityTable[7].push_back(7);
ambiguityTable[8].push_back(0);
ambiguityTable[9].push_back(0);
ambiguityTable[10].push_back(2);
ambiguityTable[10].push_back(3);
ambiguityTable[10].push_back(4);
ambiguityTable[10].push_back(1);
ambiguityTable[10].push_back(0);
ambiguityTable[10].push_back(3);
ambiguityTable[10].push_back(4);
ambiguityTable[10].push_back(1);
ambiguityTable[11].push_back(0);
ambiguityTable[12].push_back(0);
ambiguityTable[12].push_back(2);
ambiguityTable[12].push_back(3);
ambiguityTable[12].push_back(1);
ambiguityTable[14].push_back(0);
ambiguityTable[13].resize(64);
vector<vector<int> > binaryRepresentation;
for (int i = 0; i < 64; i++)
binaryRepresentation.push_back(make_vector13(i));
for (int i = 63; i >= 0; i--)
{
if (violate(i, binaryRepresentation))
binaryRepresentation.erase(binaryRepresentation.begin() + i);
}
sort(binaryRepresentation.begin(), binaryRepresentation.end(), cmp);
memset(&ambiguityTable[13][0], 0xff, sizeof(ambiguityTable[13][0]) * 64);
int pp = 0;
for (unsigned int i = 0; i < binaryRepresentation.size(); i++)
{
int k = 0;
for (unsigned int j = 0; j < binaryRepresentation[i].size(); j++)
k += (1 << binaryRepresentation[i][j]) >> 1;
ambiguityTable[13][k] = pp++;
}
// build marchingCubeSymmetries
int major_case = 0;
int sub_case[100];
const unsigned char sequence[256] =
{ 0, 1, 2, 4, 8, 16, 32, 64, 128, 3, 5, 9, 17, 33, 65, 129, 6, 10, 18, 34, 66, 130, 12, 20, 36, 68, 132, 24, 40, 72, 136, 48, 80, 144, 96, 160, 192, 7, 11, 19, 35, 67, 131, 13, 21, 37, 69, 133, 25, 41, 73, 137, 49, 81, 145, 97, 161, 193, 14, 22, 38, 70, 134, 26, 42, 74, 138, 50, 82, 146, 98, 162, 194, 28, 44, 76, 140, 52, 84, 148, 100, 164, 196, 56, 88, 152, 104, 168, 200, 112, 176, 208, 224, 15, 23, 39, 71, 135, 27, 43, 75, 139, 51, 83, 147, 99, 163, 195, 29, 45, 77, 141, 53, 85, 149, 101, 165, 197, 57, 89, 153, 105, 169, 201, 113, 177, 209, 225, 30, 46, 78, 142, 54, 86, 150, 102, 166, 198, 58, 90, 154, 106, 170, 202, 114, 178, 210, 226, 60, 92, 156, 108, 172, 204, 116, 180, 212, 228, 120, 184, 216, 232, 240, 31, 47, 79, 143, 55, 87, 151, 103, 167, 199, 59, 91, 155, 107, 171, 203, 115, 179, 211, 227, 61, 93, 157, 109, 173, 205, 117, 181, 213, 229, 121, 185, 217, 233, 241, 62, 94, 158, 110, 174, 206, 118, 182, 214, 230, 122, 186, 218, 234, 242, 124, 188, 220, 236, 244, 248, 63, 95, 159, 111, 175, 207, 119, 183, 215, 231, 123, 187, 219, 235, 243, 125, 189, 221, 237, 245, 249, 126, 190, 222, 238, 246, 250, 252, 127, 191, 223, 239, 247, 251, 253, 254, 255 };
vector<char> c[15];
pair<int, int> candidate;
set<int> am;
for (int i_ = 0; i_ < 256; i_++)
{
int i = sequence[i_];
int j = 0, k, p, j_;
for (j_ = 0; j_ < i_; j_++)
{
j = sequence[j_];
for (k = 0; k < 24; k++)
{
p = permute(i, j, k);
if (p > 0)
{
candidate = make_pair(k, p);
break;
}
}
if (k < 24)
break;
for (k = 0; k < 24; k++)
{
p = permute(i, j, k);
if (p < 0)
{
candidate = make_pair(k, p);
break;
}
}
if (k < 24)
break;
}
if (i_ == j_)
{
marchingCubeSymmetries[i][0] = caseNumber[major_case];
marchingCubeSymmetries[i][1] = 0;
marchingCubeSymmetries[i][2] = 0;
sub_case[caseNumber[major_case++]] = 0;
}
else
{
k = candidate.first;
p = candidate.second;
am.insert(marchingCubeSymmetries[j][0]);
marchingCubeSymmetries[i][0] = marchingCubeSymmetries[j][0];
sub_case[marchingCubeSymmetries[j][0]]++;
marchingCubeSymmetries[i][1] = sub_case[marchingCubeSymmetries[j][0]];
marchingCubeSymmetries[i][2] = p * k;
}
c[marchingCubeSymmetries[i][0]].push_back(i);
}
unsigned char hash_edge[86];
memset(hash_edge, 0xff, sizeof(hash_edge));
for (unsigned int i = 0; i < 12; i++)
hash_edge[f_hash_edge(edge_vertices[i][0], edge_vertices[i][1])] = i;
unsigned char hash_face[23];
memset(hash_face, 0xff, sizeof(hash_face));
for (unsigned int i = 0; i < 6; i++)
hash_face[f_hash_face(face_vertices[i][0], face_vertices[i][1], face_vertices[i][2], face_vertices[i][3])] = i;
//build cubeSymmetryEdges
for (unsigned int i = 0; i < 25; i++)
{
for (unsigned int j = 0; j < 12; j++)
{
unsigned int p0 = cubeSymmetryVertices[i][edge_vertices[j][0]];
unsigned int p1 = cubeSymmetryVertices[i][edge_vertices[j][1]];
cubeSymmetryEdges[i][j] = hash_edge[f_hash_edge(p0, p1)];
}
cubeSymmetryEdges[i][12] = 12;
}
// build cubeSymmetryFaces
for (unsigned int i = 0; i < 24; i++)
{
for (unsigned int j = 0; j < 6; j++)
{
unsigned char p0 = cubeSymmetryVertices[i][face_vertices[j][0]];
unsigned int p1 = cubeSymmetryVertices[i][face_vertices[j][1]];
unsigned int p2 = cubeSymmetryVertices[i][face_vertices[j][2]];
unsigned int p3 = cubeSymmetryVertices[i][face_vertices[j][3]];
cubeSymmetryFaces[i][j] = hash_face[f_hash_face(p0, p1, p2, p3)];
}
}
//fix 13 for marchingCubeSymmetries
marchingCubeSymmetries[90][2] = 3;
//build rc
make(representativeCase7_2_0, representativeCase7_2_1, 17);
make(representativeCase7_2_0, representativeCase7_2_2, 21);
make(representativeCase7_3_0, representativeCase7_3_1, 21);
make(representativeCase7_3_0, representativeCase7_3_2, 17);
make(representativeCase10_1_1, representativeCase10_1_1_, -1);
make(representativeCase10_2, representativeCase10_2_, 12);
make(representativeCase12_1_1, representativeCase12_1_1_, 24);
make(representativeCase12_2, representativeCase12_2_, 24);
make(representativeCase13_1, representativeCase13_1_, -3);
make(representativeCase13_2_0, representativeCase13_2[0], 23);
make(representativeCase13_2_0, representativeCase13_2[1], 9);
make(representativeCase13_2_0, representativeCase13_2[2], 16);
make(representativeCase13_2_0, representativeCase13_2[3], 20);
make(representativeCase13_2_0, representativeCase13_2[4], 19);
make(representativeCase13_2_0, representativeCase13_2_0_, -2);
make(representativeCase13_2_0_, representativeCase13_2_[0], 23);
make(representativeCase13_2_0_, representativeCase13_2_[1], 9);
make(representativeCase13_2_0_, representativeCase13_2_[2], 16);
make(representativeCase13_2_0_, representativeCase13_2_[3], 20);
make(representativeCase13_2_0_, representativeCase13_2_[4], 19);
make(representativeCase13_3_0, representativeCase13_3_0_, 24);
make(representativeCase13_3_0, representativeCase13_3[0], 8);
make(representativeCase13_3_0_, representativeCase13_3_[0], 8);
make(representativeCase13_3_0, representativeCase13_3_[1], -5);
make(representativeCase13_3_0_, representativeCase13_3[1], -5);
make(representativeCase13_3_0, representativeCase13_3_[2], -2);
make(representativeCase13_3_0_, representativeCase13_3[2], -2);
make(representativeCase13_3_0, representativeCase13_3_[3], -3);
make(representativeCase13_3_0_, representativeCase13_3[3], -3);
make(representativeCase13_3_0, representativeCase13_3[4], 17);
make(representativeCase13_3_0_, representativeCase13_3_[4], 17);
make(representativeCase13_3_0, representativeCase13_3_[5], -4);
make(representativeCase13_3_0_, representativeCase13_3[5], -4);
make(representativeCase13_3_0, representativeCase13_3[6], 9);
make(representativeCase13_3_0_, representativeCase13_3_[6], 9);
make(representativeCase13_3_0, representativeCase13_3_[7], -11);
make(representativeCase13_3_0_, representativeCase13_3_[7], -11);
make(representativeCase13_3_0, representativeCase13_3[8], 18);
make(representativeCase13_3_0_, representativeCase13_3_[8], 18);
make(representativeCase13_3_0, representativeCase13_3_[9], -10);
make(representativeCase13_3_0_, representativeCase13_3[9], -10);
make(representativeCase13_3_0, representativeCase13_3[10], 16);
make(representativeCase13_3_0_, representativeCase13_3_[10], 16);
make(representativeCase13_4_0, representativeCase13_4[0], 8);
make(representativeCase13_4_0, representativeCase13_4[1], 17);
make(representativeCase13_4_0, representativeCase13_4[2], 9);
make(representativeCase13_5_1_0, representativeCase13_5_1[0], 8);
make(representativeCase13_5_1_0, representativeCase13_5_1[1], 7);
make(representativeCase13_5_1_0, representativeCase13_5_1[2], 9);
rc[1].push_back(make_vector(representativeCase1));
rc[2].push_back(make_vector(representativeCase2));
rc[3].push_back(make_vector(representativeCase3_1));
rc[3].push_back(make_vector(representativeCase3_2));
rc[4].push_back(make_vector(representativeCase4_1));
rc[4].push_back(make_vector(representativeCase4_2));
rc[5].push_back(make_vector(representativeCase5));
rc[6].push_back(make_vector(representativeCase6_1_1));
rc[6].push_back(make_vector(representativeCase6_2));
rc[7].push_back(make_vector(representativeCase7_1));
rc[7].push_back(make_vector(representativeCase7_2_0));
rc[7].push_back(make_vector(representativeCase7_2_1));
rc[7].push_back(make_vector(representativeCase7_2_2));
rc[7].push_back(make_vector(representativeCase7_3_0));
rc[7].push_back(make_vector(representativeCase7_3_1));
rc[7].push_back(make_vector(representativeCase7_3_2));
rc[7].push_back(make_vector(representativeCase7_4_1));
rc[8].push_back(make_vector(representativeCase8));
rc[9].push_back(make_vector(representativeCase9));
rc[10].push_back(make_vector(representativeCase10_1_1));
rc[10].push_back(make_vector(representativeCase10_1_1_));
rc[10].push_back(make_vector(representativeCase10_1_2));
rc[10].push_back(make_vector(representativeCase10_2));
rc[10].push_back(make_vector(representativeCase10_2_));
rc[11].push_back(make_vector(representativeCase11));
rc[12].push_back(make_vector(representativeCase12_1_1));
rc[12].push_back(make_vector(representativeCase12_1_1_));
rc[12].push_back(make_vector(representativeCase12_2));
rc[12].push_back(make_vector(representativeCase12_2_));
rc[13].push_back(make_vector(representativeCase13_1));
rc[13].push_back(make_vector(representativeCase13_2_0));
for (unsigned int i = 0; i < 5; i++)
rc[13].push_back(make_vector(representativeCase13_2[i]));
rc[13].push_back(make_vector(representativeCase13_3_0));
for (unsigned int i = 0; i < 11; i++)
rc[13].push_back(make_vector(representativeCase13_3[i]));
rc[13].push_back(make_vector(representativeCase13_4_0));
for (unsigned int i = 0; i < 3; i++)
rc[13].push_back(make_vector(representativeCase13_4[i]));
rc[13].push_back(make_vector(representativeCase13_3_0_));
for (unsigned int i = 0; i < 11; i++)
rc[13].push_back(make_vector(representativeCase13_3_[i]));
rc[13].push_back(make_vector(representativeCase13_2_0_));
for (unsigned int i = 0; i < 5; i++)
rc[13].push_back(make_vector(representativeCase13_2_[i]));
rc[13].push_back(make_vector(representativeCase13_1_));
rc[13].push_back(make_vector(representativeCase13_5_1_0));
for (unsigned int i = 0; i < 3; i++)
rc[13].push_back(make_vector(representativeCase13_5_1[i]));
rc[14].push_back(make_vector(representativeCase14));
//build faceTest vector
for (unsigned int i = 0; i < 15; i++)
{
for (unsigned int j = 0; j < c[i].size(); j++)
{
const unsigned char k = c[i][j];
const char n = faceTest_size[i];
faceTest_num[k].resize(n);
if (n == 0)
continue;
if (j == 0)
memcpy(&faceTest_num[k][0], faceTest_number[i], sizeof(faceTest_number[i][0]) * n);
else
permute_face(faceTest_number[i], &faceTest_num[k][0], n, marchingCubeSymmetries[k][2]);
}
}
//build interiorTest vector
for (unsigned int i = 0; i < 15; i++)
{
for (unsigned int j = 0; j < c[i].size(); j++)
{
const unsigned char k = c[i][j];
interiorTest_num[k] = interiorTest_number[i];
if (marchingCubeSymmetries[k][2] < 0 || (j > 0 && marchingCubeSymmetries[k][2] == 0))
interiorTest_num[k] = -interiorTest_num[k];
}
}
//build triangleTable
for (unsigned int i = 0; i < 256; i++)
{
const int major_case = marchingCubeSymmetries[i][0];
triangleTable[i].resize(rc[major_case].size());
centerVertexNeeded[i].resize(rc[major_case].size());
for (unsigned int j = 0; j < rc[major_case].size(); j++)
{
triangleTable[i][j].resize(rc[major_case][j].size());
if (marchingCubeSymmetries[i][1] == 0) //
{
memcpy(&triangleTable[i][j][0], &rc[major_case][j][0], rc[major_case][j].size() * sizeof(rc[major_case][j][0]));
}
else
{
permute_edge(&rc[major_case][j][0], (char*) &triangleTable[i][j][0], rc[major_case][j].size(), marchingCubeSymmetries[i][2]);
}
centerVertexNeeded[i][j] = false;
for (unsigned int k = 0; k < triangleTable[i][j].size(); k++)
centerVertexNeeded[i][j] = centerVertexNeeded[i][j] | (triangleTable[i][j][k] == 12);// |= (triangleTable[i][j][k] == 12);
}
}
tableLoaded = true;
}
void MarchingCubes::printTable()
{
// once the file is OK, rename it to marchingCubesTable.h
ofstream fout("marchingCubesTable_.h", ios::binary);
if (!fout)
return;
fout << endl;
//static vector<char> ambiguityTable[15];
unsigned int maxSize = 0;
for(unsigned int i = 0; i < 15; i++)
{
if (ambiguityTable[i].size() > maxSize)
maxSize = ambiguityTable[i].size();
}
fout << "static char ambiguityTable[15][" << maxSize << "] = " << endl << "{" << endl;
//char buffer[100];
//fout <<
for(int i = 0; i < 15; i++)
{
fout << " { ";
unsigned int j = 0;
for(j = 0; j < ambiguityTable[i].size(); j++)
{
fout << int(ambiguityTable[i][j]);
if (j < maxSize-1)
fout << ", ";
}
for(; j < maxSize; j++)
{
fout << "0";
if (j < maxSize-1)
fout << ", ";
}
fout << " }";
if (i < 15 - 1)
fout << ", ";
fout << endl;
}
fout << "};" << endl;
fout << endl;
// static int marchingCubeSymmetries[256][3];
fout << "static int marchingCubeSymmetries[256][3] = {" << endl;
for(int i = 0; i < 256; i++)
{
fout << " {";
for(int j = 0; j < 3; j++)
{
fout << setw(3) << marchingCubeSymmetries[i][j];
if (j < 3 - 1)
fout << ",";
}
fout << " }";
if (i < 256 -1)
fout << ", ";
if (i % 8 == 7)
fout << endl;
}
fout << "};" << endl;
fout << endl;
//static vector<char> faceTest_num[256];
maxSize = 0;
for(unsigned int i = 0; i < 256; i++)
{
if (faceTest_num[i].size() > maxSize)
maxSize = faceTest_num[i].size();
}
fout << "static char faceTest_num[256][" << maxSize+1 << "] = " << endl << "{" << endl;
//char buffer[100];
for(int i = 0; i < 256; i++)
{
fout << " {";
fout << setw(2) << faceTest_num[i].size();
//if (faceTest_num[i].size() > 0)
fout << ",";
unsigned int j = 0;
for(j = 0; j < faceTest_num[i].size(); j++)
{
fout << setw(2) << int(faceTest_num[i][j]);
if (j < maxSize-1)
fout << ",";
}
for(; j < maxSize; j++)
{
fout << " 0";
if (j < maxSize-1)
fout << ",";
}
fout << " }";
if (i < 256 - 1)
fout << ",";
if (i % 8 == 7)
fout << endl;
}
fout << "};" << endl;
fout << endl;
//static char interiorTest_num[256];
fout << "static char interiorTest_num[256] = " << endl << " { ";
for(int i = 0; i < 256; i++)
{
fout << int(interiorTest_num[i]);
if (i < 256 - 1)
fout << ", ";
}
fout << " };" << endl;
fout << endl;
// static vector< vector<unsigned char> > triangleTable[256];
for(int i = 0; i < 256; i++)
{
if (triangleTable[i].size() == 0)
continue;
for(unsigned int j = 0; j < triangleTable[i].size(); j++)
{
vector<unsigned char> & table = triangleTable[i][j];
unsigned int num = table.size();
fout << "static unsigned char triangleTable_" << i << "_" << j << "[" << num+2 << "] = " << " { ";
fout << num << ", " << centerVertexNeeded[i][j];
if (num > 0)
fout << ", ";
for(unsigned int k = 0; k < table.size(); k++)
{
fout << int(table[k]);
if (k < table.size() - 1)
fout << ", ";
}
fout << " };" << endl;
}
unsigned int num = triangleTable[i].size();
fout << "static unsigned char * triangleTable_" << i << "[" << num << "] = ";
if (num <= 7)
{
fout << "{ ";
for(unsigned int k = 0; k < num; k++)
{
fout << "triangleTable_" << i << "_" << k;
if (k < num - 1)
fout << ", ";
}
fout << " };" << endl;
}
else
{
fout << endl << "{ " << endl;
for(unsigned int k = 0; k < num; k++)
{
if (k % 8 == 0)
fout << " ";
fout << "triangleTable_" << i << "_" << k;
if (k < num - 1)
fout << ", ";
if (k % 8 == 7)
fout << endl;
}
if (num % 8 != 0)
fout << endl;
fout << "};" << endl;
}
fout << endl;
} //end 256
fout << "static unsigned char ** triangleTable[256] = " << endl << "{ " << endl;
for(unsigned int k = 0; k < 256; k++)
{
if (k % 8 == 0)
fout << " ";
if (triangleTable[k].size() == 0)
fout << "NULL";
else
fout << "triangleTable_" << k;
if (k < 256 - 1)
fout << ", ";
if (k % 8 == 7)
fout << endl;
}
fout << "};" << endl << endl;
fout.close();
//exit(0);
}
#endif
| 38.249451 | 1,177 | 0.580125 | [
"vector",
"transform"
] |
29ef6d1d3a77884787f915593ca2050812976c93 | 3,110 | cc | C++ | MuonAnalysis/MomentumScaleCalibration/src/ResolutionFunction.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | MuonAnalysis/MomentumScaleCalibration/src/ResolutionFunction.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | MuonAnalysis/MomentumScaleCalibration/src/ResolutionFunction.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #include "MuonAnalysis/MomentumScaleCalibration/interface/ResolutionFunction.h"
void ResolutionFunction::readParameters(TString fileName) {
iterationNum_ = 0;
parArray_ = nullptr;
// std::vector<double> parameterErrors;
// Read the parameters file
std::ifstream parametersFile(fileName.Data());
std::string line;
std::string iteration("Iteration ");
// Loop on the file lines
while (parametersFile) {
getline(parametersFile, line);
size_t lineInt = line.find("value");
// if( line.find(iteration) != std::string::npos ) {
size_t iterationSubStr = line.find(iteration);
// Take the iteration number
if (iterationSubStr != std::string::npos) {
int functionNum = 0;
// This can be used when dealing with multiple iterations
// std::cout << "line = " << line << std::endl;
std::stringstream sLine(line);
std::string num;
int wordCounter = 0;
// Warning: this strongly depends on the parameters file structure.
while (sLine >> num) {
++wordCounter;
// std::cout << "num["<<wordCounter<<"] = " << num << std::endl;
if (wordCounter == 8) {
std::stringstream in(num);
in >> functionNum;
}
if (wordCounter == 13) {
std::stringstream in(num);
in >> iterationNum_;
}
}
// std::cout << "iteration number = " << iterationNum_ << std::endl;
// std::cout << "scale function number = " << scaleFunctionNum << std::endl;
// Create a new vector to hold the parameters for this iteration
// std::vector<double> parVec;
// parVecVec_.push_back(parVec);
// Set the scaleFunction
// scaleFunction_ = scaleFunctionArrayForVec[scaleFunctionNum];
// scaleFunction_ = scaleFunctionArray[scaleFunctionNum];
functionId_.push_back(functionNum);
// scaleFunctionVec_.push_back( scaleFunctionArray[scaleFunctionNum] );
resolutionFunctionVec_.push_back(resolutionFunctionService(functionNum));
}
// Take the parameters for the current iteration
if ((lineInt != std::string::npos)) {
size_t subStr1 = line.find("value");
std::stringstream paramStr;
double param = 0;
// Even if all the rest of the line is taken, the following
// convertion to a double will stop at the end of the first number.
paramStr << line.substr(subStr1 + 5);
paramStr >> param;
// // Fill the last vector of parameters, which corresponds to this iteration.
// parVecVec_.back().push_back(param);
parVecVec_.push_back(param);
// std::cout << "param = " << param << std::endl;
// This is to extract parameter errors
// size_t subStr2 = line.find("+-");
// std::stringstream parErrorStr;
// double parError = 0;
// parErrorStr << line.substr(subStr2+1);
// parErrorStr >> parError;
// parameterErrors.push_back(parError);
// std::cout << "parError = " << parError << std::endl;
}
}
convertToArrays(resolutionFunction_, resolutionFunctionVec_);
}
| 37.02381 | 90 | 0.626045 | [
"vector"
] |
29ef7e2f7de2ace7428427002978417d2c6bfc1e | 13,194 | cpp | C++ | renderer/VulkanMesh.cpp | Esentiel/HurricaneEngine3D | 321617957afda7d7f30f4e72c0056d69a32df906 | [
"BSD-3-Clause"
] | 2 | 2021-06-23T20:30:58.000Z | 2022-01-10T23:57:54.000Z | renderer/VulkanMesh.cpp | Esentiel/HurricaneEngine3D | 321617957afda7d7f30f4e72c0056d69a32df906 | [
"BSD-3-Clause"
] | 35 | 2021-02-23T10:13:53.000Z | 2021-04-01T09:57:55.000Z | renderer/VulkanMesh.cpp | Esentiel/HurricaneEngine3D | 321617957afda7d7f30f4e72c0056d69a32df906 | [
"BSD-3-Clause"
] | null | null | null | #include "VulkanMesh.h"
#include "VulkanMemoryManager.h"
#include "VulkanCommandQueueDispatcher.h"
#include "VulkanPipelineCollection.h"
#include "VulkanBackend.h"
#include "VulkanCamera.h"
#include <meshoptimizer.h>
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h> // TODO: move loading image to another class. probably after vfs implementation?
#pragma warning(disable : 4996)
#define FAST_OBJ_IMPLEMENTATION
#include <../extern/fast_obj.h>
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/ext/matrix_transform.hpp>
#include <glm/ext/matrix_clip_space.hpp>
#include <string>
#include <glm/gtx/quaternion.hpp>
VulkanMesh::VulkanMesh(VulkanBackend * backend) :
r_device(nullptr),
m_pipelineType(iface::RenderPipelineCollection::PipelineType::PT_size),
r_backend(backend)
{
m_color[0] = 0.7f;
m_color[1] = 0.5f;
m_color[2] = 0.2f;
m_color[3] = 1.f;
}
VulkanMesh::~VulkanMesh(){
// TODO: move this to memory manager
if (r_device){
if (m_imagePtr.sampler)
vkDestroySampler(r_device, m_imagePtr.sampler, nullptr);
if (m_imagePtr.imageView)
vkDestroyImageView(r_device, m_imagePtr.imageView, nullptr);
if (m_imagePtr.imageRef)
vkDestroyImage(r_device, m_imagePtr.imageRef, nullptr);
if (m_imagePtr.memoryRef)
vkFreeMemory(r_device, m_imagePtr.memoryRef, nullptr);
}
}
VulkanMesh::VulkanMesh(VulkanMesh && other){
this->m_vertices.swap(other.m_vertices);
this->m_indices.swap(other.m_indices);
std::swap(this->m_vBuffPtr, other.m_vBuffPtr);
std::swap(this->m_iBuffPtr, other.m_iBuffPtr);
std::swap(this->m_vsBuffPtr, other.m_vsBuffPtr);
std::swap(this->m_tsBuffPtr, other.m_tsBuffPtr);
std::swap(this->m_imagePtr, other.m_imagePtr);
this->m_uniformBuffers.swap(other.m_uniformBuffers);
this->m_descriptorSets.swap(other.m_descriptorSets);
std::swap(this->r_device, other.r_device);
std::swap(this->m_pipelineType, other.m_pipelineType);
std::swap(this->r_pipelineCollection, other.r_pipelineCollection);
std::swap(this->m_color, other.m_color);
std::swap(this->r_backend, other.r_backend);
std::swap(this->m_model, other.m_model);
}
VulkanMesh& VulkanMesh::operator=(VulkanMesh&& other){
this->m_vertices.swap(other.m_vertices);
this->m_indices.swap(other.m_indices);
std::swap(this->m_vBuffPtr, other.m_vBuffPtr);
std::swap(this->m_iBuffPtr, other.m_iBuffPtr);
std::swap(this->m_vsBuffPtr, other.m_vsBuffPtr);
std::swap(this->m_tsBuffPtr, other.m_tsBuffPtr);
std::swap(this->m_imagePtr, other.m_imagePtr);
this->m_uniformBuffers.swap(other.m_uniformBuffers);
this->m_descriptorSets.swap(other.m_descriptorSets);
std::swap(this->r_device, other.r_device);
std::swap(this->m_pipelineType, other.m_pipelineType);
std::swap(this->r_pipelineCollection, other.r_pipelineCollection);
std::swap(this->m_color, other.m_color);
std::swap(this->r_backend, other.r_backend);
std::swap(this->m_model, other.m_model);
return *this;
}
// TODO:
void VulkanMesh::UpdateModelMx(float * mx){
glm::vec3 p(mx[4], mx[5], mx[6]);
glm::quat q(mx[0], mx[1], mx[2], mx[3]);
glm::mat4 model(1.0f);
model = glm::translate(model, p);
glm::mat4 RotationMatrix = glm::toMat4(q);
m_model = model * RotationMatrix;
m_model = glm::scale(m_model, glm::vec3(mx[7], mx[8], mx[9]));
}
void VulkanMesh::Initialize(const char *path,
const char *texturePath,
VulkanMemoryManager * memoryMgr,
VulkanCommandQueueDispatcher * queueDispatcher,
VkDevice device, VkDescriptorPool descriptorPool,
iface::RenderPipelineCollection::PipelineType pipelineType,
VulkanPipelineCollection *pipelineCollection,
uint32_t imageCount){
assert(ParseObj(path));
r_device = device;
r_pipelineCollection = pipelineCollection;
m_pipelineType = pipelineType;
// Allocate buffers for vertex, index buffers
assert(memoryMgr);
m_vBuffPtr = memoryMgr->AllocateBuffer(m_vertices.size() * sizeof(Vertex), VulkanMemoryManager::BufferUsageType::BUT_vertex_buffer);
m_vBuffPtr.Validate();
m_iBuffPtr = memoryMgr->AllocateBuffer(m_indices.size() * sizeof(uint32_t), VulkanMemoryManager::BufferUsageType::BUT_index_buffer);
m_iBuffPtr.Validate();
m_vsBuffPtr = memoryMgr->AllocateBuffer(m_vertices.size() * sizeof(Vertex), VulkanMemoryManager::BufferUsageType::BUT_transfer_src);
m_vsBuffPtr.Validate();
// load vertex, index data to memory
void* vData = 0;
VK_CHECK(vkMapMemory(r_device, m_vsBuffPtr.memoryRef, m_vsBuffPtr.offset, m_vsBuffPtr.size, 0, &vData));
assert(vData);
memcpy(vData, m_vertices.data(), m_vertices.size() * sizeof(Vertex)); // TODO: for primitive we don't actually need uv coords
vkUnmapMemory(r_device, m_vsBuffPtr.memoryRef);
// copy from staging buffer to vertex
queueDispatcher->CopyBuffer(m_vsBuffPtr, m_vBuffPtr);
void* iData = 0;
VK_CHECK(vkMapMemory(r_device, m_iBuffPtr.memoryRef, m_iBuffPtr.offset, m_iBuffPtr.size, 0, &iData));
assert(iData);
memcpy(iData, m_indices.data(), m_indices.size() * sizeof(uint32_t));
vkUnmapMemory(r_device, m_iBuffPtr.memoryRef);
// texture
if (m_pipelineType != iface::RenderPipelineCollection::PipelineType::PT_primitive){
LoadTexture(memoryMgr, queueDispatcher, texturePath);
}
// allocate uniform buffers
m_uniformBuffers.resize(imageCount);
for (uint32_t i = 0u; i < imageCount; i++){
m_uniformBuffers[i] = memoryMgr->AllocateBuffer(sizeof(UniformBufferObject), VulkanMemoryManager::BufferUsageType::BUT_uniform_buffer);
m_uniformBuffers[i].Validate();
}
const VulkanPipelineCollection::VulkanPipelineSetup &pipeline = r_pipelineCollection->GetPipeline(m_pipelineType);
CreateDescriptorSets(descriptorPool, pipeline.descriptorSetLayout, imageCount);
UpdateDescriptorSets(); // TODO: maybe there is some reasons to add flexibility here?
}
void VulkanMesh::Render(float dt, VkCommandBuffer commandBuffer, uint32_t imageIndex){
UpdateUniformBuffers(dt, imageIndex);
const VulkanPipelineCollection::VulkanPipelineSetup &pipeline = r_pipelineCollection->GetPipeline(m_pipelineType);
vkCmdBindVertexBuffers(commandBuffer, 0, 1, &m_vBuffPtr.bufferRef, &m_vBuffPtr.offset);
vkCmdBindIndexBuffer(commandBuffer, m_iBuffPtr.bufferRef, m_iBuffPtr.offset, VK_INDEX_TYPE_UINT32);
vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.layout, 0, 1, &m_descriptorSets[imageIndex], 0, nullptr);
for (const VkPushConstantRange &pushConstant : pipeline.pushConstants){
vkCmdPushConstants(commandBuffer, pipeline.layout, pushConstant.stageFlags, pushConstant.offset, pushConstant.size, m_color); // TODO: what if multiple push constants? think a bit later
}
vkCmdDrawIndexed(commandBuffer, m_indices.size(), 1, 0, 0, 0);
}
iface::RenderPipelineCollection::PipelineType VulkanMesh::GetPipelineType() const{
return m_pipelineType;
}
bool VulkanMesh::ParseObj(const char* path){
fastObjMesh* obj = fast_obj_read(path);
if (!obj)
{
printf("Error loading %s: file not found\n", path);
return false;
}
size_t total_indices = 0;
for (unsigned int i = 0; i < obj->face_count; ++i)
total_indices += 3 * (obj->face_vertices[i] - 2);
std::vector<Vertex> vertices(total_indices);
size_t vertex_offset = 0;
size_t index_offset = 0;
for (unsigned int i = 0; i < obj->face_count; ++i)
{
for (unsigned int j = 0; j < obj->face_vertices[i]; ++j)
{
fastObjIndex gi = obj->indices[index_offset + j];
Vertex v =
{
obj->positions[gi.p * 3 + 0],
obj->positions[gi.p * 3 + 1],
obj->positions[gi.p * 3 + 2],
obj->normals[gi.n * 3 + 0],
obj->normals[gi.n * 3 + 1],
obj->normals[gi.n * 3 + 2],
obj->texcoords[gi.t * 2 + 0],
1.f - obj->texcoords[gi.t * 2 + 1], // TODO: god damn obj rotates y!
};
// triangulate polygon on the fly; offset-3 is always the first polygon vertex
if (j >= 3)
{
vertices[vertex_offset + 0] = vertices[vertex_offset - 3];
vertices[vertex_offset + 1] = vertices[vertex_offset - 1];
vertex_offset += 2;
}
vertices[vertex_offset] = v;
vertex_offset++;
}
index_offset += obj->face_vertices[i];
}
fast_obj_destroy(obj);
std::vector<unsigned int> remap(total_indices);
size_t total_vertices = meshopt_generateVertexRemap(&remap[0], NULL, total_indices, &vertices[0], total_indices, sizeof(Vertex));
m_indices.resize(total_indices);
meshopt_remapIndexBuffer(&m_indices[0], NULL, total_indices, &remap[0]);
m_vertices.resize(total_vertices);
meshopt_remapVertexBuffer(&m_vertices[0], &vertices[0], total_indices, sizeof(Vertex), &remap[0]);
return true;
}
void VulkanMesh::UpdateUniformBuffers(float dt, uint32_t imageIndex){
static float time = dt;
time+=dt;
UniformBufferObject ubo{};
ubo.model = m_model;
auto pos = glm::vec3(m_model[3]);
ubo.proj = r_backend->GetCamera()->GetProjection(); // TODO: move away to scene UBO when scene is implemented
ubo.view = r_backend->GetCamera()->GetView();
//ubo.proj = glm::perspective(glm::radians(45.0f), 1280 / (float) 720, 0.1f, 10.0f); // TODO: move to Camera
//ubo.view = glm::lookAt(glm::vec3(5.0f, 5.0f, -5.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
void* data;
vkMapMemory(r_device, m_uniformBuffers[imageIndex].memoryRef, m_uniformBuffers[imageIndex].offset, m_uniformBuffers[imageIndex].size, 0, &data);
memcpy(data, &ubo, sizeof(ubo));
vkUnmapMemory(r_device, m_uniformBuffers[imageIndex].memoryRef);
}
void VulkanMesh::CreateDescriptorSets(VkDescriptorPool descriptorPool, VkDescriptorSetLayout descriptorSetLayout, uint32_t imageCount){
std::vector<VkDescriptorSetLayout> layouts(imageCount, descriptorSetLayout);
VkDescriptorSetAllocateInfo allocInfo{ VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO };
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = static_cast<uint32_t>(imageCount);
allocInfo.pSetLayouts = layouts.data();
m_descriptorSets.resize(imageCount);
VK_CHECK(vkAllocateDescriptorSets(r_device, &allocInfo, m_descriptorSets.data()));
}
void VulkanMesh::UpdateDescriptorSets(){
for (size_t i = 0; i < m_descriptorSets.size(); i++) {
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = m_uniformBuffers[i].bufferRef;
bufferInfo.offset = m_uniformBuffers[i].offset;
bufferInfo.range = m_uniformBuffers[i].size;
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = m_imagePtr.imageView;
imageInfo.sampler = m_imagePtr.sampler;
std::vector<VkWriteDescriptorSet> descriptorWrites(1);
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = m_descriptorSets[i];
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[0].pImageInfo = nullptr;
descriptorWrites[0].pTexelBufferView = nullptr;
if (m_pipelineType != iface::RenderPipelineCollection::PipelineType::PT_primitive){
descriptorWrites.resize(2);
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = m_descriptorSets[i];
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
}
vkUpdateDescriptorSets(r_device, descriptorWrites.size(), descriptorWrites.data(), 0, nullptr); // Seems you can'not send array of writes if they all are set to the same bindings
}
}
void VulkanMesh::LoadTexture(VulkanMemoryManager * memoryMgr, VulkanCommandQueueDispatcher * queueDispatcher, const char *texturePath){
int texWidth, texHeight, texChannels;
stbi_uc* pixels = stbi_load(texturePath, &texWidth, &texHeight, &texChannels, STBI_rgb_alpha);
VkDeviceSize imageSize = texWidth * texHeight * 4;
assert(pixels);
m_tsBuffPtr = memoryMgr->AllocateBuffer(imageSize, VulkanMemoryManager::BufferUsageType::BUT_transfer_src);
m_tsBuffPtr.Validate();
void* data;
vkMapMemory(r_device, m_tsBuffPtr.memoryRef, m_tsBuffPtr.offset, imageSize, 0, &data);
memcpy(data, pixels, static_cast<size_t>(imageSize));
vkUnmapMemory(r_device, m_tsBuffPtr.memoryRef);
stbi_image_free(pixels);
VkFormat format = VK_FORMAT_R8G8B8A8_SRGB;
m_imagePtr = memoryMgr->CreateImage(texWidth, texHeight, format, VK_IMAGE_TILING_OPTIMAL, VulkanMemoryManager::BufferUsageType::BUT_transfer_dst | VulkanMemoryManager::BufferUsageType::BUT_sampled, VK_IMAGE_ASPECT_COLOR_BIT, true);
queueDispatcher->TransitionImageLayout(m_imagePtr.imageRef, format, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
queueDispatcher->CopyBufferToImage(m_tsBuffPtr, m_imagePtr.imageRef, static_cast<uint32_t>(texWidth), static_cast<uint32_t>(texHeight));
queueDispatcher->TransitionImageLayout(m_imagePtr.imageRef, format, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
} | 39.981818 | 232 | 0.754131 | [
"render",
"vector",
"model"
] |
29f0a073b3341fe6039360b7e64e18208b243936 | 919 | cpp | C++ | flare/Mesh.cpp | freakMeduza/flare | 32003c1be20e8876948a4c97d9715059f1d32e5c | [
"MIT"
] | 2 | 2022-01-02T15:45:36.000Z | 2022-01-12T15:31:24.000Z | flare/Mesh.cpp | freakMeduza/flare | 32003c1be20e8876948a4c97d9715059f1d32e5c | [
"MIT"
] | null | null | null | flare/Mesh.cpp | freakMeduza/flare | 32003c1be20e8876948a4c97d9715059f1d32e5c | [
"MIT"
] | null | null | null | #include "Mesh.hpp"
#include "Device.hpp"
namespace fve {
Mesh::Mesh(Device& device, const std::vector<Vertex>& vertices, const std::vector<Index>& indices) : device_{ device } {
vertexBuffer_ = createBuffer(vk::BufferUsageFlagBits::eVertexBuffer, vertices);
if (!indices.empty())
indexBuffer_ = createBuffer(vk::BufferUsageFlagBits::eIndexBuffer, indices);
}
void Mesh::bind(vk::CommandBuffer commandBuffer) {
std::vector<vk::Buffer> buffers{ vertexBuffer_->buffer() };
std::vector<vk::DeviceSize> offsets{ 0 };
commandBuffer.bindVertexBuffers(0, buffers, offsets);
if (indexBuffer_)
commandBuffer.bindIndexBuffer(indexBuffer_->buffer(), 0, vk::IndexType::eUint32);
}
void Mesh::draw(vk::CommandBuffer commandBuffer) {
if (indexBuffer_)
commandBuffer.drawIndexed(indexBuffer_->instanceCount(), 1, 0, 0, 0);
else
commandBuffer.draw(vertexBuffer_->instanceCount(), 1, 0, 0);
}
} | 32.821429 | 121 | 0.725789 | [
"mesh",
"vector"
] |
29f111e310665c5465e6a072b01996ac1f27d350 | 17,769 | cpp | C++ | src/tensorrt/tensorrt-6.0.1.5/samples/sampleUffSSD/sampleUffSSD.cpp | aimuch/AIEnvConfig | 4ccd54e9c601e8c91efebcec1a50115d75d0cf96 | [
"MIT"
] | 250 | 2019-06-14T16:12:20.000Z | 2022-03-27T09:56:26.000Z | src/tensorrt/tensorrt-6.0.1.5/samples/sampleUffSSD/sampleUffSSD.cpp | aimuch/AIEnvConfig | 4ccd54e9c601e8c91efebcec1a50115d75d0cf96 | [
"MIT"
] | 6 | 2018-08-10T07:15:39.000Z | 2018-10-23T01:51:17.000Z | src/tensorrt/tensorrt-6.0.1.5/samples/sampleUffSSD/sampleUffSSD.cpp | aimuch/AIEnvConfig | 4ccd54e9c601e8c91efebcec1a50115d75d0cf96 | [
"MIT"
] | 41 | 2019-08-16T13:42:13.000Z | 2022-02-23T03:38:09.000Z | /*
* Copyright 1993-2019 NVIDIA Corporation. All rights reserved.
*
* NOTICE TO LICENSEE:
*
* This source code and/or documentation ("Licensed Deliverables") are
* subject to NVIDIA intellectual property rights under U.S. and
* international Copyright laws.
*
* These Licensed Deliverables contained herein is PROPRIETARY and
* CONFIDENTIAL to NVIDIA and is being provided under the terms and
* conditions of a form of NVIDIA software license agreement by and
* between NVIDIA and Licensee ("License Agreement") or electronically
* accepted by Licensee. Notwithstanding any terms or conditions to
* the contrary in the License Agreement, reproduction or disclosure
* of the Licensed Deliverables to any third party without the express
* written consent of NVIDIA is prohibited.
*
* NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
* LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
* SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS
* PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
* NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
* DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
* NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
* NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
* LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
* SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
* DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THESE LICENSED DELIVERABLES.
*
* U.S. Government End Users. These Licensed Deliverables are a
* "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
* 1995), consisting of "commercial computer software" and "commercial
* computer software documentation" as such terms are used in 48
* C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government
* only as a commercial end item. Consistent with 48 C.F.R.12.212 and
* 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
* U.S. Government End Users acquire the Licensed Deliverables with
* only those rights set forth herein.
*
* Any use of the Licensed Deliverables in individual and commercial
* software must include, in the user documentation and internal
* comments to the code, the above Disclaimer and U.S. Government End
* Users Notice.
*/
//!
//! SampleUffSSD.cpp
//! This file contains the implementation of the Uff SSD sample. It creates the network using
//! the SSD UFF model.
//! It can be run with the following command line:
//! Command: ./sample_uff_ssd [-h or --help] [-d=/path/to/data/dir or --datadir=/path/to/data/dir]
//!
#include "BatchStream.h"
#include "EntropyCalibrator.h"
#include "argsParser.h"
#include "buffers.h"
#include "common.h"
#include "logger.h"
#include "NvInfer.h"
#include "NvUffParser.h"
#include <cuda_runtime_api.h>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <sstream>
const std::string gSampleName = "TensorRT.sample_uff_ssd";
//!
//! \brief The SampleUffSSDParams structure groups the additional parameters required by
//! the Uff SSD sample.
//!
struct SampleUffSSDParams : public samplesCommon::SampleParams
{
std::string uffFileName; //!< The file name of the UFF model to use
std::string labelsFileName; //!< The file namefo the class labels
int outputClsSize; //!< The number of output classes
int calBatchSize; //!< The size of calibration batch
int nbCalBatches; //!< The number of batches for calibration
int keepTopK; //!< The maximum number of detection post-NMS
float visualThreshold; //!< The minimum score threshold to consider a detection
};
//! \brief The SampleUffSSD class implements the SSD sample
//!
//! \details It creates the network using an UFF model
//!
class SampleUffSSD
{
template <typename T>
using SampleUniquePtr = std::unique_ptr<T, samplesCommon::InferDeleter>;
public:
SampleUffSSD(const SampleUffSSDParams& params)
: mParams(params)
, mEngine(nullptr)
{
}
//!
//! \brief Function builds the network engine
//!
bool build();
//!
//! \brief Runs the TensorRT inference engine for this sample
//!
bool infer();
//!
//! \brief Cleans up any state created in the sample class
//!
bool teardown();
private:
SampleUffSSDParams mParams; //!< The parameters for the sample.
nvinfer1::Dims mInputDims; //!< The dimensions of the input to the network.
std::vector<samplesCommon::PPM<3, 300, 300>> mPPMs; //!< PPMs of test images
std::shared_ptr<nvinfer1::ICudaEngine> mEngine; //!< The TensorRT engine used to run the network
//!
//! \brief Parses an UFF model for SSD and creates a TensorRT network
//!
bool constructNetwork(SampleUniquePtr<nvinfer1::IBuilder>& builder,
SampleUniquePtr<nvinfer1::INetworkDefinition>& network, SampleUniquePtr<nvinfer1::IBuilderConfig>& config,
SampleUniquePtr<nvuffparser::IUffParser>& parser);
//!
//! \brief Reads the input and mean data, preprocesses, and stores the result in a managed buffer
//!
bool processInput(const samplesCommon::BufferManager& buffers);
//!
//! \brief Filters output detections and verify results
//!
bool verifyOutput(const samplesCommon::BufferManager& buffers);
};
//!
//! \brief Creates the network, configures the builder and creates the network engine
//!
//! \details This function creates the SSD network by parsing the UFF model and builds
//! the engine that will be used to run SSD (mEngine)
//!
//! \return Returns true if the engine was created successfully and false otherwise
//!
bool SampleUffSSD::build()
{
initLibNvInferPlugins(&gLogger.getTRTLogger(), "");
auto builder = SampleUniquePtr<nvinfer1::IBuilder>(nvinfer1::createInferBuilder(gLogger.getTRTLogger()));
if (!builder)
{
return false;
}
auto network = SampleUniquePtr<nvinfer1::INetworkDefinition>(builder->createNetwork());
if (!network)
{
return false;
}
auto config = SampleUniquePtr<nvinfer1::IBuilderConfig>(builder->createBuilderConfig());
if (!config)
{
return false;
}
auto parser = SampleUniquePtr<nvuffparser::IUffParser>(nvuffparser::createUffParser());
if (!parser)
{
return false;
}
auto constructed = constructNetwork(builder, network, config, parser);
if (!constructed)
{
return false;
}
assert(network->getNbInputs() == 1);
mInputDims = network->getInput(0)->getDimensions();
assert(mInputDims.nbDims == 3);
assert(network->getNbOutputs() == 2);
return true;
}
//!
//! \brief Uses a UFF parser to create the SSD Network and marks the
//! output layers
//!
//! \param network Pointer to the network that will be populated with the SSD network
//!
//! \param builder Pointer to the engine builder
//!
bool SampleUffSSD::constructNetwork(SampleUniquePtr<nvinfer1::IBuilder>& builder,
SampleUniquePtr<nvinfer1::INetworkDefinition>& network, SampleUniquePtr<nvinfer1::IBuilderConfig>& config,
SampleUniquePtr<nvuffparser::IUffParser>& parser)
{
parser->registerInput(mParams.inputTensorNames[0].c_str(), DimsCHW(3, 300, 300), nvuffparser::UffInputOrder::kNCHW);
parser->registerOutput(mParams.outputTensorNames[0].c_str());
auto parsed = parser->parse(locateFile(mParams.uffFileName, mParams.dataDirs).c_str(), *network, DataType::kFLOAT);
if (!parsed)
{
return false;
}
builder->setMaxBatchSize(mParams.batchSize);
config->setMaxWorkspaceSize(1_GiB);
if (mParams.fp16)
{
config->setFlag(BuilderFlag::kFP16);
}
// Calibrator life time needs to last until after the engine is built.
std::unique_ptr<IInt8Calibrator> calibrator;
if (mParams.int8)
{
gLogInfo << "Using Entropy Calibrator 2" << std::endl;
const std::string listFileName = "list.txt";
const int imageC = 3;
const int imageH = 300;
const int imageW = 300;
nvinfer1::DimsNCHW imageDims{};
imageDims = nvinfer1::DimsNCHW{mParams.calBatchSize, imageC, imageH, imageW};
BatchStream calibrationStream(mParams.nbCalBatches, imageDims, listFileName, mParams.dataDirs);
calibrator.reset(
new Int8EntropyCalibrator2<BatchStream>(calibrationStream, 0, "UffSSD", mParams.inputTensorNames[0].c_str()));
config->setFlag(BuilderFlag::kINT8);
config->setInt8Calibrator(calibrator.get());
}
mEngine = std::shared_ptr<nvinfer1::ICudaEngine>(builder->buildEngineWithConfig(*network, *config), samplesCommon::InferDeleter());
if (!mEngine)
{
return false;
}
return true;
}
//!
//! \brief Runs the TensorRT inference engine for this sample
//!
//! \details This function is the main execution function of the sample. It allocates the buffer,
//! sets inputs and executes the engine.
//!
bool SampleUffSSD::infer()
{
// Create RAII buffer manager object
samplesCommon::BufferManager buffers(mEngine, mParams.batchSize);
auto context = SampleUniquePtr<nvinfer1::IExecutionContext>(mEngine->createExecutionContext());
if (!context)
{
return false;
}
// Read the input data into the managed buffers
assert(mParams.inputTensorNames.size() == 1);
if (!processInput(buffers))
{
return false;
}
// Memcpy from host input buffers to device input buffers
buffers.copyInputToDevice();
bool status = context->execute(mParams.batchSize, buffers.getDeviceBindings().data());
if (!status)
{
return false;
}
// Memcpy from device output buffers to host output buffers
buffers.copyOutputToHost();
// Post-process detections and verify results
if (!verifyOutput(buffers))
{
return false;
}
return true;
}
//!
//! \brief Cleans up any state created in the sample class
//!
bool SampleUffSSD::teardown()
{
//! Clean up the libprotobuf files as the parsing is complete
//! \note It is not safe to use any other part of the protocol buffers library after
//! ShutdownProtobufLibrary() has been called.
nvuffparser::shutdownProtobufLibrary();
return true;
}
//!
//! \brief Reads the input and mean data, preprocesses, and stores the result in a managed buffer
//!
bool SampleUffSSD::processInput(const samplesCommon::BufferManager& buffers)
{
const int inputC = mInputDims.d[0];
const int inputH = mInputDims.d[1];
const int inputW = mInputDims.d[2];
const int batchSize = mParams.batchSize;
// Available images
std::vector<std::string> imageList = {"dog.ppm", "bus.ppm"};
mPPMs.resize(batchSize);
assert(mPPMs.size() <= imageList.size());
for (int i = 0; i < batchSize; ++i)
{
readPPMFile(locateFile(imageList[i], mParams.dataDirs), mPPMs[i]);
}
float* hostDataBuffer = static_cast<float*>(buffers.getHostBuffer(mParams.inputTensorNames[0]));
// Host memory for input buffer
for (int i = 0, volImg = inputC * inputH * inputW; i < mParams.batchSize; ++i)
{
for (int c = 0; c < inputC; ++c)
{
// The color image to input should be in BGR order
for (unsigned j = 0, volChl = inputH * inputW; j < volChl; ++j)
{
hostDataBuffer[i * volImg + c * volChl + j]
= (2.0 / 255.0) * float(mPPMs[i].buffer[j * inputC + c]) - 1.0;
}
}
}
return true;
}
//!
//! \brief Filters output detections and verify result
//!
//! \return whether the detection output matches expectations
//!
bool SampleUffSSD::verifyOutput(const samplesCommon::BufferManager& buffers)
{
const int inputH = mInputDims.d[1];
const int inputW = mInputDims.d[2];
const int batchSize = mParams.batchSize;
const int keepTopK = mParams.keepTopK;
const float visualThreshold = mParams.visualThreshold;
const int outputClsSize = mParams.outputClsSize;
const float* detectionOut = static_cast<const float*>(buffers.getHostBuffer(mParams.outputTensorNames[0]));
const int* keepCount = static_cast<const int*>(buffers.getHostBuffer(mParams.outputTensorNames[1]));
std::vector<std::string> classes(outputClsSize);
// Gather class labels
std::ifstream labelFile(locateFile(mParams.labelsFileName, mParams.dataDirs));
string line;
int id = 0;
while (getline(labelFile, line))
{
classes[id++] = line;
}
bool pass = true;
for (int p = 0; p < batchSize; ++p)
{
int numDetections = 0;
// at least one correct detection
bool correctDetection = false;
for (int i = 0; i < keepCount[p]; ++i)
{
const float* det = &detectionOut[0] + (p * keepTopK + i) * 7;
if (det[2] < visualThreshold)
{
continue;
}
// Output format for each detection is stored in the below order
// [image_id, label, confidence, xmin, ymin, xmax, ymax]
int detection = det[1];
assert(detection < outputClsSize);
std::string storeName = classes[detection] + "-" + std::to_string(det[2]) + ".ppm";
numDetections++;
if ((p == 0 && classes[detection] == "dog")
|| (p == 1 && (classes[detection] == "truck" || classes[detection] == "car")))
{
correctDetection = true;
}
gLogInfo << "Detected " << classes[detection].c_str() << " in the image " << int(det[0]) << " ("
<< mPPMs[p].fileName.c_str() << ")"
<< " with confidence " << det[2] * 100.f << " and coordinates (" << det[3] * inputW << ","
<< det[4] * inputH << ")"
<< ",(" << det[5] * inputW << "," << det[6] * inputH << ")." << std::endl;
gLogInfo << "Result stored in " << storeName.c_str() << "." << std::endl;
samplesCommon::writePPMFileWithBBox(
storeName, mPPMs[p], {det[3] * inputW, det[4] * inputH, det[5] * inputW, det[6] * inputH});
}
pass &= correctDetection;
pass &= numDetections >= 1;
}
return pass;
}
//!
//! \brief Initializes members of the params struct using the command line args
//!
SampleUffSSDParams initializeSampleParams(const samplesCommon::Args& args)
{
SampleUffSSDParams params;
if (args.dataDirs.empty()) //!< Use default directories if user hasn't provided directory paths
{
params.dataDirs.push_back("data/ssd/");
params.dataDirs.push_back("data/ssd/VOC2007/");
params.dataDirs.push_back("data/ssd/VOC2007/PPMImages/");
params.dataDirs.push_back("data/samples/ssd/");
params.dataDirs.push_back("data/samples/ssd/VOC2007/");
params.dataDirs.push_back("data/samples/ssd/VOC2007/PPMImages/");
}
else //!< Use the data directory provided by the user
{
params.dataDirs = args.dataDirs;
}
params.uffFileName = "sample_ssd_relu6.uff";
params.labelsFileName = "ssd_coco_labels.txt";
params.inputTensorNames.push_back("Input");
params.batchSize = 2;
params.outputTensorNames.push_back("NMS");
params.outputTensorNames.push_back("NMS_1");
params.dlaCore = args.useDLACore;
params.int8 = args.runInInt8;
params.fp16 = args.runInFp16;
params.outputClsSize = 91;
params.calBatchSize = 10;
params.nbCalBatches = 10;
params.keepTopK = 100;
params.visualThreshold = 0.5;
return params;
}
//!
//! \brief Prints the help information for running this sample
//!
void printHelpInfo()
{
std::cout
<< "Usage: ./sample_uff_ssd [-h or --help] [-d or --datadir=<path to data directory>] [--useDLACore=<int>]"
<< std::endl;
std::cout << "--help Display help information" << std::endl;
std::cout << "--datadir Specify path to a data directory, overriding the default. This option can be used "
"multiple times to add multiple directories. If no data directories are given, the default is to use "
"data/samples/ssd/ and data/ssd/"
<< std::endl;
std::cout << "--useDLACore=N Specify a DLA engine for layers that support DLA. Value can range from 0 to n-1, "
"where n is the number of DLA engines on the platform."
<< std::endl;
std::cout << "--fp16 Specify to run in fp16 mode." << std::endl;
std::cout << "--int8 Specify to run in int8 mode." << std::endl;
}
int main(int argc, char** argv)
{
samplesCommon::Args args;
bool argsOK = samplesCommon::parseArgs(args, argc, argv);
if (!argsOK)
{
gLogError << "Invalid arguments" << std::endl;
printHelpInfo();
return EXIT_FAILURE;
}
if (args.help)
{
printHelpInfo();
return EXIT_SUCCESS;
}
auto sampleTest = gLogger.defineTest(gSampleName, argc, argv);
gLogger.reportTestStart(sampleTest);
SampleUffSSD sample(initializeSampleParams(args));
gLogInfo << "Building and running a GPU inference engine for SSD" << std::endl;
if (!sample.build())
{
return gLogger.reportFail(sampleTest);
}
if (!sample.infer())
{
return gLogger.reportFail(sampleTest);
}
if (!sample.teardown())
{
return gLogger.reportFail(sampleTest);
}
return gLogger.reportPass(sampleTest);
}
| 34.04023 | 135 | 0.656762 | [
"object",
"vector",
"model"
] |
29f121e8410a212f789ee09538a84bf28b545323 | 4,626 | cpp | C++ | src/test/test_code/system_test.cpp | LaoZZZZZ/bartender-1.1 | ddfb2e52bdf92258dd837ab8ee34306e9fb45b81 | [
"MIT"
] | 22 | 2016-08-11T06:16:25.000Z | 2022-02-22T00:06:59.000Z | src/test/test_code/system_test.cpp | LaoZZZZZ/bartender-1.1 | ddfb2e52bdf92258dd837ab8ee34306e9fb45b81 | [
"MIT"
] | 9 | 2016-12-08T12:42:38.000Z | 2021-12-28T20:12:15.000Z | src/test/test_code/system_test.cpp | LaoZZZZZ/bartender-1.1 | ddfb2e52bdf92258dd837ab8ee34306e9fb45b81 | [
"MIT"
] | 8 | 2017-06-26T13:15:06.000Z | 2021-11-12T18:39:54.000Z | #include <iostream>
#include <boost/regex.hpp>
#include <string>
#include <memory>
#include <algorithm>
#include "../clusterpipeline.h"
#include "../pattern.h"
#include "../timer.h"
#include "../clusteralgorithm.h"
#include "../binaryoutfilebuf.h"
#include "../binaryinfilebuf.h"
#include "../barcodeextractor.h"
#include "../testSimulation.h"
#include "../clusteroutput.h"
#include "../singleendbarcodeprocessor.h"
#include "../barcodecounter.h"
#include "../testSimulation.h"
#include "../formats.h"
#include "../util.h"
using boost::regex;
using std::unique_ptr;
using std::list;
using std::vector;
using std::string;
using barcodeSpace::Sequence;
using barcodeSpace::file_format;
using barcodeSpace::clusterPipline;
using barcodeSpace::ClusterOutput;
using barcodeSpace::cluster;
using barcodeSpace::BarcodeCounter;
using barcodeSpace::SingleEndBarcodeProcessor;
using barcodeSpace::loadData;
using barcodeSpace::outputPositionWeightMatrix;
// The whole clustering process.
// 1. Loads the read from the sequence file and filter out those unqualified read
// based on the constraints on the barcode region.
// 2. Clusters those valid barcodes using the first k basepair.
// 3. Recursively Clusters those initial clusters based the second k basepair until
// the number of cluster does not change or change is very small.
struct CompareObject {
bool operator()(const std::shared_ptr<cluster>& a, const std::shared_ptr<cluster>& b) {
return a->size() < b->size();
}
};
void drive(std::string seqfile, // origina read file
double qualityThres, // quality threshold
size_t freq_cutoff, // frequency cutoff
size_t seedlen, // seed len
std::string outprefix,
const boost::regex& pattern,
bool head = true){
Timer* t = new realTimer(cout);
//1. first argument is the sequence file
//2. file format is fastq
file_format format = file_format::FASTQ;
//3. quality threshold
SingleEndBarcodeProcessor single_end_processor(seqfile,
pattern,
format,
qualityThres);
single_end_processor.Extract();
const unordered_map<size_t, BarcodeCounter*>& stats = single_end_processor.AllBarcodeTables();
std::list<std::shared_ptr<cluster>> clusters;
size_t frequency_number_column = 0;
for(auto iter = stats.begin(); iter != stats.end(); iter++){
size_t start = 0;
size_t klen = iter->first*2;
if(seedlen*2 > klen)
seedlen = 1;
clusterPipline* pipe = new clusterPipline(start,seedlen*2,klen,freq_cutoff);
std::shared_ptr<clusterPipline> pPipe(pipe);
pPipe->clusterDrive(iter->second->BarcodeTable());
const std::list<std::shared_ptr<cluster>>& temp_clusters = pPipe->clusters();
clusters.insert(clusters.end(), temp_clusters.begin(), temp_clusters.end());
//std::sort(result.begin(), result.end(), CompareObject());
cout<<"There are totally " << temp_clusters.size() <<" clusters with length " << iter->first <<endl;
if (!temp_clusters.empty())
frequency_number_column = max(frequency_number_column, iter->first);
}
if (!clusters.empty()) {
cout << "There are totally " << clusters.size() << " clusters!" << endl;
cout<<"Starting to dump the cluster to file "<< outprefix <<endl;
ClusterOutput out(outprefix, head);
std::cout << frequency_number_column << std::endl;
// Dumps the cluster information.
out.WriteToFile(clusters, 5, frequency_number_column + 1);
}
// Dumps the frequency information to the file
// outputPositionWeightMatrix(outprefix + ".bp", result);
delete t;
}
int main(int argc,char* argv[])
{
boost::regex pattern("(.ACC|T.CC|TA.C|TAC.)(A|T|C|G|N){4,7}(AA)(A|T|C|G|N){4,7}(AA)(A|T|C|G|N){4,7}(TT)(A|T|C|G|N){4,7}(.TAA|A.AA|AT.A|ATA.)",boost::regex::ECMAScript);
assert(argc >= 3);
//1. first argument is the sequence file
string sequencefile(argv[1]);
//2. out put file
string outprefix(argv[2]);
size_t freq_cutoff = 10;
if(argc >= 4)
freq_cutoff = atoi(argv[3]);
double qualityThres = 30;
if(argc >= 5)
//3. quality threshold
qualityThres = (atoi(argv[4]));
size_t seedlen = 5;
if(argc >= 6)
seedlen = atoi(argv[5]);
drive(sequencefile,
qualityThres,
freq_cutoff,
seedlen,
outprefix,
pattern);
return 0;
}
| 34.781955 | 172 | 0.638997 | [
"vector"
] |
29f401abd8c974c0172184571598ca4f7083a7a6 | 1,788 | hpp | C++ | logic/main-settings.hpp | cpuwolf/opentrack | 5541cfc68d87c2fc254eb2f2a5aad79831871a88 | [
"ISC"
] | 1 | 2018-02-06T08:36:39.000Z | 2018-02-06T08:36:39.000Z | logic/main-settings.hpp | cpuwolf/opentrack | 5541cfc68d87c2fc254eb2f2a5aad79831871a88 | [
"ISC"
] | null | null | null | logic/main-settings.hpp | cpuwolf/opentrack | 5541cfc68d87c2fc254eb2f2a5aad79831871a88 | [
"ISC"
] | null | null | null | /* Copyright (c) 2015, Stanislaw Halik <sthalik@misaki.pl>
* Permission to use, copy, modify, and/or distribute this
* software for any purpose with or without fee is hereby granted,
* provided that the above copyright notice and this permission
* notice appear in all copies.
*/
#pragma once
#include <QString>
#include "options/options.hpp"
using namespace options;
#include "api/plugin-api.hpp"
#include "spline/axis-opts.hpp"
#include "export.hpp"
struct OTR_LOGIC_EXPORT key_opts
{
value<QString> keycode, guid;
value<int> button;
key_opts(bundle b, const QString& name);
};
struct OTR_LOGIC_EXPORT module_settings
{
bundle b;
value<QString> tracker_dll, filter_dll, protocol_dll;
module_settings();
};
struct OTR_LOGIC_EXPORT main_settings final
{
bundle b, b_map;
axis_opts a_x, a_y, a_z;
axis_opts a_yaw, a_pitch, a_roll;
std::vector<axis_opts*> all_axis_opts;
value<bool> tcomp_p, tcomp_disable_tx, tcomp_disable_ty, tcomp_disable_tz;
value<bool> tcomp_disable_src_yaw, tcomp_disable_src_pitch, tcomp_disable_src_roll;
value<bool> tray_enabled, tray_start;
value<bool> center_at_startup;
value<int> center_method;
value<int> neck_z;
value<bool> neck_enable;
key_opts key_start_tracking1, key_start_tracking2;
key_opts key_stop_tracking1, key_stop_tracking2;
key_opts key_toggle_tracking1, key_toggle_tracking2;
key_opts key_restart_tracking1, key_restart_tracking2;
key_opts key_center1, key_center2;
key_opts key_toggle1, key_toggle2;
key_opts key_zero1, key_zero2;
key_opts key_toggle_press1, key_toggle_press2;
key_opts key_zero_press1, key_zero_press2;
value<bool> tracklogging_enabled;
value<QString> tracklogging_filename;
main_settings();
};
| 29.311475 | 87 | 0.75783 | [
"vector"
] |
29f823d9949c622722fd5b03be79e32c22ed7bfa | 2,643 | cc | C++ | onnxruntime/contrib_ops/cuda/bert/fast_gelu.cc | lchang20/onnxruntime | 97b8f6f394ae02c73ed775f456fd85639c91ced1 | [
"MIT"
] | 1 | 2021-11-07T18:53:47.000Z | 2021-11-07T18:53:47.000Z | onnxruntime/contrib_ops/cuda/bert/fast_gelu.cc | lchang20/onnxruntime | 97b8f6f394ae02c73ed775f456fd85639c91ced1 | [
"MIT"
] | 30 | 2021-09-26T08:05:58.000Z | 2022-03-31T10:45:30.000Z | onnxruntime/contrib_ops/cuda/bert/fast_gelu.cc | lchang20/onnxruntime | 97b8f6f394ae02c73ed775f456fd85639c91ced1 | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "core/providers/cuda/cuda_common.h"
#include "core/providers/cuda/cudnn_common.h"
#include "fast_gelu.h"
#include "fast_gelu_impl.h"
#include "contrib_ops/cpu/bert/bias_gelu_helper.h"
#include "transformer_common.h"
namespace onnxruntime {
namespace contrib {
namespace cuda {
#define REGISTER_KERNEL_TYPED(T) \
ONNX_OPERATOR_TYPED_KERNEL_EX( \
FastGelu, \
kMSDomain, \
1, \
T, \
kCudaExecutionProvider, \
(*KernelDefBuilder::Create()) \
.TypeConstraint("T", DataTypeImpl::GetTensorType<T>()), \
FastGelu<T>);
REGISTER_KERNEL_TYPED(float)
REGISTER_KERNEL_TYPED(MLFloat16)
REGISTER_KERNEL_TYPED(BFloat16)
using namespace ONNX_NAMESPACE;
template <typename T>
FastGelu<T>::FastGelu(const OpKernelInfo& op_kernel_info) : CudaKernel(op_kernel_info) {
const TransformerOptions* options = TransformerOptions::GetInstance();
use_half2_ = !options->DisableHalf2();
}
template <typename T>
Status FastGelu<T>::ComputeInternal(OpKernelContext* context) const {
ORT_RETURN_IF_ERROR(bias_gelu_helper::CheckInputs(context));
const Tensor* input = context->Input<Tensor>(0);
const Tensor* bias = context->Input<Tensor>(1);
Tensor* output = context->Output(0, input->Shape());
int64_t input_length = input->Shape().Size();
int64_t bias_length = (nullptr == bias) ? 0 : bias->Shape().Size();
typedef typename ToCudaType<T>::MappedType CudaT;
if (!LaunchFastGeluKernel<CudaT>(GetDeviceProp(),
Stream(),
static_cast<int>(input_length),
static_cast<int>(bias_length),
reinterpret_cast<const CudaT*>(input->template Data<T>()),
(nullptr != bias) ? reinterpret_cast<const CudaT*>(bias->template Data<T>()) : nullptr,
reinterpret_cast<CudaT*>(output->template MutableData<T>()),
use_half2_)) {
CUDA_CALL(cudaGetLastError());
return Status(common::ONNXRUNTIME, common::FAIL);
}
return Status::OK();
}
} //namespace cuda
} // namespace contrib
} // namespace onnxruntime
| 38.867647 | 122 | 0.566402 | [
"shape"
] |
29fd93ec0d89c9e006defcffc94255fbe9387280 | 118,270 | cpp | C++ | ngraph/test/type_prop/convolution.cpp | vurusovs/openvino | 0b1ef99fd73a3da77e93eaf8db0864948313b1d9 | [
"Apache-2.0"
] | null | null | null | ngraph/test/type_prop/convolution.cpp | vurusovs/openvino | 0b1ef99fd73a3da77e93eaf8db0864948313b1d9 | [
"Apache-2.0"
] | null | null | null | ngraph/test/type_prop/convolution.cpp | vurusovs/openvino | 0b1ef99fd73a3da77e93eaf8db0864948313b1d9 | [
"Apache-2.0"
] | null | null | null | //*****************************************************************************
// Copyright 2017-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 "gtest/gtest.h"
#include "ngraph/ngraph.hpp"
#include "util/type_prop.hpp"
using namespace std;
using namespace ngraph;
TEST(type_prop, conv_1d_deduce)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{64, 3, 100});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{128, 3, 10});
auto conv = make_shared<op::Convolution>(param0, param1);
EXPECT_EQ(conv->get_element_type(), element::f32);
EXPECT_EQ(conv->get_shape(), (Shape{64, 128, 91}));
EXPECT_EQ(conv->get_window_movement_strides(), Strides{1});
EXPECT_EQ(conv->get_window_dilation_strides(), Strides{1});
EXPECT_EQ(conv->get_data_dilation_strides(), Strides{1});
EXPECT_EQ(conv->get_padding_below(), CoordinateDiff{0});
EXPECT_EQ(conv->get_padding_above(), CoordinateDiff{0});
}
TEST(type_prop, conv_1d_back_data_batch_deduce)
{
// Deduce type
Shape data_batch_shape{64, 3, 100};
auto param0 = make_shared<op::Parameter>(element::f32, Shape{128, 3, 10}); // filters
auto param1 = make_shared<op::Parameter>(element::f32, Shape{64, 128, 91}); // output delta
auto conv = make_shared<op::ConvolutionBackpropData>(data_batch_shape,
param0,
param1,
Strides{1},
Strides{1},
CoordinateDiff{0},
CoordinateDiff{0},
Strides{1});
EXPECT_EQ(conv->get_element_type(), element::f32);
EXPECT_EQ(conv->get_shape(), data_batch_shape);
EXPECT_EQ(conv->get_window_movement_strides_forward(), Strides{1});
EXPECT_EQ(conv->get_window_dilation_strides_forward(), Strides{1});
EXPECT_EQ(conv->get_data_dilation_strides_forward(), Strides{1});
EXPECT_EQ(conv->get_padding_below_forward(), CoordinateDiff{0});
EXPECT_EQ(conv->get_padding_above_forward(), CoordinateDiff{0});
}
TEST(type_prop, conv_1d_deduce_padded)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{64, 3, 100});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{128, 3, 10});
auto move_strides = Strides{1};
auto dilation_strides = Strides{1};
auto padding_below = CoordinateDiff{2};
auto padding_above = CoordinateDiff{3};
auto conv = make_shared<op::Convolution>(
param0, param1, move_strides, dilation_strides, padding_below, padding_above);
EXPECT_EQ(conv->get_element_type(), element::f32);
EXPECT_EQ(conv->get_shape(), (Shape{64, 128, 96}));
EXPECT_EQ(conv->get_window_movement_strides(), Strides{1});
EXPECT_EQ(conv->get_window_dilation_strides(), Strides{1});
EXPECT_EQ(conv->get_data_dilation_strides(), Strides{1});
EXPECT_EQ(conv->get_padding_below(), CoordinateDiff{2});
EXPECT_EQ(conv->get_padding_above(), CoordinateDiff{3});
}
TEST(type_prop, conv_1d_back_data_batch_deduce_padded)
{
// Deduce type
Shape data_batch_shape{64, 3, 100};
auto param0 = make_shared<op::Parameter>(element::f32, Shape{128, 3, 10}); // filters
auto param1 = make_shared<op::Parameter>(element::f32, Shape{64, 128, 96}); // output delta
auto move_strides = Strides{1};
auto dilation_strides = Strides{1};
auto padding_below = CoordinateDiff{2};
auto padding_above = CoordinateDiff{3};
auto conv = make_shared<op::ConvolutionBackpropData>(data_batch_shape,
param0,
param1,
move_strides,
dilation_strides,
padding_below,
padding_above,
Strides{1});
EXPECT_EQ(conv->get_element_type(), element::f32);
EXPECT_EQ(conv->get_shape(), data_batch_shape);
EXPECT_EQ(conv->get_window_movement_strides_forward(), Strides{1});
EXPECT_EQ(conv->get_window_dilation_strides_forward(), Strides{1});
EXPECT_EQ(conv->get_data_dilation_strides_forward(), Strides{1});
EXPECT_EQ(conv->get_padding_below_forward(), CoordinateDiff{2});
EXPECT_EQ(conv->get_padding_above_forward(), CoordinateDiff{3});
}
TEST(type_prop, conv_1d_deduce_strided)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{64, 3, 100});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{128, 3, 10});
auto move_strides = Strides{2};
auto conv = make_shared<op::Convolution>(param0, param1, move_strides);
EXPECT_EQ(conv->get_element_type(), element::f32);
EXPECT_EQ(conv->get_shape(), (Shape{64, 128, 46}));
EXPECT_EQ(conv->get_window_movement_strides(), Strides{2});
EXPECT_EQ(conv->get_window_dilation_strides(), Strides{1});
EXPECT_EQ(conv->get_data_dilation_strides(), Strides{1});
EXPECT_EQ(conv->get_padding_below(), CoordinateDiff{0});
EXPECT_EQ(conv->get_padding_above(), CoordinateDiff{0});
}
TEST(type_prop, conv_1d_back_data_batch_deduce_strided)
{
// Deduce type
Shape data_batch_shape{64, 3, 100};
auto param0 = make_shared<op::Parameter>(element::f32, Shape{128, 3, 10}); // filters
auto param1 = make_shared<op::Parameter>(element::f32, Shape{64, 128, 46}); // output delta
auto move_strides = Strides{2};
auto conv = make_shared<op::ConvolutionBackpropData>(data_batch_shape,
param0,
param1,
move_strides,
Strides{1},
CoordinateDiff{0},
CoordinateDiff{0},
Strides{1});
EXPECT_EQ(conv->get_element_type(), element::f32);
EXPECT_EQ(conv->get_shape(), data_batch_shape);
EXPECT_EQ(conv->get_window_movement_strides_forward(), Strides{2});
EXPECT_EQ(conv->get_window_dilation_strides_forward(), Strides{1});
EXPECT_EQ(conv->get_data_dilation_strides_forward(), Strides{1});
EXPECT_EQ(conv->get_padding_below_forward(), CoordinateDiff{0});
EXPECT_EQ(conv->get_padding_above_forward(), CoordinateDiff{0});
}
TEST(type_prop, conv_1d_deduce_strided_padded)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{64, 3, 100});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{128, 3, 10});
auto move_strides = Strides{2};
auto dilation_strides = Strides{1};
auto padding_below = CoordinateDiff{2};
auto padding_above = CoordinateDiff{3};
auto conv = make_shared<op::Convolution>(
param0, param1, move_strides, dilation_strides, padding_below, padding_above);
EXPECT_EQ(conv->get_element_type(), element::f32);
EXPECT_EQ(conv->get_shape(), (Shape{64, 128, 48}));
EXPECT_EQ(conv->get_window_movement_strides(), Strides{2});
EXPECT_EQ(conv->get_window_dilation_strides(), Strides{1});
EXPECT_EQ(conv->get_data_dilation_strides(), Strides{1});
EXPECT_EQ(conv->get_padding_below(), CoordinateDiff{2});
EXPECT_EQ(conv->get_padding_above(), CoordinateDiff{3});
}
TEST(type_prop, conv_1d_back_data_batch_deduce_strided_padded)
{
// Deduce type
Shape data_batch_shape{64, 3, 100};
auto param0 = make_shared<op::Parameter>(element::f32, Shape{128, 3, 10}); // filters
auto param1 = make_shared<op::Parameter>(element::f32, Shape{64, 128, 48}); // output delta
auto move_strides = Strides{2};
auto dilation_strides = Strides{1};
auto padding_below = CoordinateDiff{2};
auto padding_above = CoordinateDiff{3};
auto conv = make_shared<op::ConvolutionBackpropData>(data_batch_shape,
param0,
param1,
move_strides,
dilation_strides,
padding_below,
padding_above,
Strides{1});
EXPECT_EQ(conv->get_element_type(), element::f32);
EXPECT_EQ(conv->get_shape(), data_batch_shape);
EXPECT_EQ(conv->get_window_movement_strides_forward(), Strides{2});
EXPECT_EQ(conv->get_window_dilation_strides_forward(), Strides{1});
EXPECT_EQ(conv->get_data_dilation_strides_forward(), Strides{1});
EXPECT_EQ(conv->get_padding_below_forward(), CoordinateDiff{2});
EXPECT_EQ(conv->get_padding_above_forward(), CoordinateDiff{3});
}
TEST(type_prop, conv_1d_deduce_strided_small_uneven)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{64, 3, 5});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{128, 3, 2});
auto move_strides = Strides{2};
auto conv = make_shared<op::Convolution>(param0, param1, move_strides);
EXPECT_EQ(conv->get_element_type(), element::f32);
EXPECT_EQ(conv->get_shape(), (Shape{64, 128, 2}));
EXPECT_EQ(conv->get_window_movement_strides(), Strides{2});
EXPECT_EQ(conv->get_window_dilation_strides(), Strides{1});
EXPECT_EQ(conv->get_data_dilation_strides(), Strides{1});
EXPECT_EQ(conv->get_padding_below(), CoordinateDiff{0});
EXPECT_EQ(conv->get_padding_above(), CoordinateDiff{0});
}
TEST(type_prop, conv_1d_back_data_batch_deduce_strided_small_uneven)
{
// Deduce type
Shape data_batch_shape{64, 3, 5};
auto param0 = make_shared<op::Parameter>(element::f32, Shape{128, 3, 2}); // filters
auto param1 = make_shared<op::Parameter>(element::f32, Shape{64, 128, 2}); // output delta
auto move_strides = Strides{2};
auto conv = make_shared<op::ConvolutionBackpropData>(data_batch_shape,
param0,
param1,
move_strides,
Strides{1},
CoordinateDiff{0},
CoordinateDiff{0},
Strides{1});
EXPECT_EQ(conv->get_element_type(), element::f32);
EXPECT_EQ(conv->get_shape(), data_batch_shape);
EXPECT_EQ(conv->get_window_movement_strides_forward(), Strides{2});
EXPECT_EQ(conv->get_window_dilation_strides_forward(), Strides{1});
EXPECT_EQ(conv->get_data_dilation_strides_forward(), Strides{1});
EXPECT_EQ(conv->get_padding_below_forward(), CoordinateDiff{0});
EXPECT_EQ(conv->get_padding_above_forward(), CoordinateDiff{0});
}
TEST(type_prop, conv_1d_deduce_strided_small_even)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{64, 3, 6});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{128, 3, 2});
auto move_strides = Strides{2};
auto conv = make_shared<op::Convolution>(param0, param1, move_strides);
EXPECT_EQ(conv->get_element_type(), element::f32);
EXPECT_EQ(conv->get_shape(), (Shape{64, 128, 3}));
EXPECT_EQ(conv->get_window_movement_strides(), Strides{2});
EXPECT_EQ(conv->get_window_dilation_strides(), Strides{1});
EXPECT_EQ(conv->get_data_dilation_strides(), Strides{1});
EXPECT_EQ(conv->get_padding_below(), CoordinateDiff{0});
EXPECT_EQ(conv->get_padding_above(), CoordinateDiff{0});
}
TEST(type_prop, conv_1d_back_data_batch_deduce_strided_small_even)
{
// Deduce type
Shape data_batch_shape{64, 3, 6};
auto param0 = make_shared<op::Parameter>(element::f32, Shape{128, 3, 2}); // filters
auto param1 = make_shared<op::Parameter>(element::f32, Shape{64, 128, 3}); // output delta
auto move_strides = Strides{2};
auto conv = make_shared<op::ConvolutionBackpropData>(data_batch_shape,
param0,
param1,
move_strides,
Strides{1},
CoordinateDiff{0},
CoordinateDiff{0},
Strides{1});
EXPECT_EQ(conv->get_element_type(), element::f32);
EXPECT_EQ(conv->get_shape(), data_batch_shape);
EXPECT_EQ(conv->get_window_movement_strides_forward(), Strides{2});
EXPECT_EQ(conv->get_window_dilation_strides_forward(), Strides{1});
EXPECT_EQ(conv->get_data_dilation_strides_forward(), Strides{1});
EXPECT_EQ(conv->get_padding_below_forward(), CoordinateDiff{0});
EXPECT_EQ(conv->get_padding_above_forward(), CoordinateDiff{0});
}
TEST(type_prop, conv_1d_deduce_window_dilated)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{64, 3, 100});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{128, 3, 10});
auto move_strides = Strides{1};
auto dilate_strides = Strides{2};
auto conv = make_shared<op::Convolution>(param0, param1, move_strides, dilate_strides);
EXPECT_EQ(conv->get_element_type(), element::f32);
EXPECT_EQ(conv->get_shape(), (Shape{64, 128, 82}));
EXPECT_EQ(conv->get_window_movement_strides(), Strides{1});
EXPECT_EQ(conv->get_window_dilation_strides(), Strides{2});
EXPECT_EQ(conv->get_data_dilation_strides(), Strides{1});
EXPECT_EQ(conv->get_padding_below(), CoordinateDiff{0});
EXPECT_EQ(conv->get_padding_above(), CoordinateDiff{0});
}
TEST(type_prop, conv_1d_back_data_batch_deduce_window_dilated)
{
// Deduce type
Shape data_batch_shape{64, 3, 100};
auto param0 = make_shared<op::Parameter>(element::f32, Shape{128, 3, 10}); // filters
auto param1 = make_shared<op::Parameter>(element::f32, Shape{64, 128, 82}); // output delta
auto move_strides = Strides{1};
auto dilate_strides = Strides{2};
auto conv = make_shared<op::ConvolutionBackpropData>(data_batch_shape,
param0,
param1,
move_strides,
dilate_strides,
CoordinateDiff{0},
CoordinateDiff{0},
Strides{1});
EXPECT_EQ(conv->get_element_type(), element::f32);
EXPECT_EQ(conv->get_shape(), data_batch_shape);
EXPECT_EQ(conv->get_window_movement_strides_forward(), Strides{1});
EXPECT_EQ(conv->get_window_dilation_strides_forward(), Strides{2});
EXPECT_EQ(conv->get_data_dilation_strides_forward(), Strides{1});
EXPECT_EQ(conv->get_padding_below_forward(), CoordinateDiff{0});
EXPECT_EQ(conv->get_padding_above_forward(), CoordinateDiff{0});
}
TEST(type_prop, conv_1d_deduce_window_dilated_padded)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{64, 3, 100});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{128, 3, 10});
auto move_strides = Strides{1};
auto dilate_strides = Strides{2};
auto padding_below = CoordinateDiff{2};
auto padding_above = CoordinateDiff{3};
auto conv = make_shared<op::Convolution>(
param0, param1, move_strides, dilate_strides, padding_below, padding_above);
EXPECT_EQ(conv->get_element_type(), element::f32);
EXPECT_EQ(conv->get_shape(), (Shape{64, 128, 87}));
EXPECT_EQ(conv->get_window_movement_strides(), Strides{1});
EXPECT_EQ(conv->get_window_dilation_strides(), Strides{2});
EXPECT_EQ(conv->get_data_dilation_strides(), Strides{1});
EXPECT_EQ(conv->get_padding_below(), CoordinateDiff{2});
EXPECT_EQ(conv->get_padding_above(), CoordinateDiff{3});
}
TEST(type_prop, conv_1d_back_data_batch_deduce_window_dilated_padded)
{
// Deduce type
Shape data_batch_shape{64, 3, 100};
auto param0 = make_shared<op::Parameter>(element::f32, Shape{128, 3, 10}); // filters
auto param1 = make_shared<op::Parameter>(element::f32, Shape{64, 128, 87}); // output delta
auto move_strides = Strides{1};
auto dilate_strides = Strides{2};
auto padding_below = CoordinateDiff{2};
auto padding_above = CoordinateDiff{3};
auto conv = make_shared<op::ConvolutionBackpropData>(data_batch_shape,
param0,
param1,
move_strides,
dilate_strides,
padding_below,
padding_above,
Strides{1});
EXPECT_EQ(conv->get_element_type(), element::f32);
EXPECT_EQ(conv->get_shape(), data_batch_shape);
EXPECT_EQ(conv->get_window_movement_strides_forward(), Strides{1});
EXPECT_EQ(conv->get_window_dilation_strides_forward(), Strides{2});
EXPECT_EQ(conv->get_data_dilation_strides_forward(), Strides{1});
EXPECT_EQ(conv->get_padding_below_forward(), CoordinateDiff{2});
EXPECT_EQ(conv->get_padding_above_forward(), CoordinateDiff{3});
}
TEST(type_prop, conv_1d_deduce_window_dilated_data_dilated_padded)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{64, 3, 100});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{128, 3, 10});
auto move_strides = Strides{1};
auto dilate_strides = Strides{2};
auto padding_below = CoordinateDiff{2};
auto padding_above = CoordinateDiff{3};
auto data_dilate_strides = Strides{3};
auto conv = make_shared<op::Convolution>(param0,
param1,
move_strides,
dilate_strides,
padding_below,
padding_above,
data_dilate_strides);
EXPECT_EQ(conv->get_element_type(), element::f32);
EXPECT_EQ(conv->get_shape(), (Shape{64, 128, 285}));
EXPECT_EQ(conv->get_window_movement_strides(), Strides{1});
EXPECT_EQ(conv->get_window_dilation_strides(), Strides{2});
EXPECT_EQ(conv->get_data_dilation_strides(), Strides{3});
EXPECT_EQ(conv->get_padding_below(), CoordinateDiff{2});
EXPECT_EQ(conv->get_padding_above(), CoordinateDiff{3});
}
TEST(type_prop, conv_1d_back_data_batch_deduce_window_dilated_data_dilated_padded)
{
// Deduce type
Shape data_batch_shape{64, 3, 100};
auto param0 = make_shared<op::Parameter>(element::f32, Shape{128, 3, 10}); // filters
auto param1 = make_shared<op::Parameter>(element::f32, Shape{64, 128, 285}); // output delta
auto move_strides = Strides{1};
auto dilate_strides = Strides{2};
auto padding_below = CoordinateDiff{2};
auto padding_above = CoordinateDiff{3};
auto data_dilate_strides = Strides{3};
auto conv = make_shared<op::ConvolutionBackpropData>(data_batch_shape,
param0,
param1,
move_strides,
dilate_strides,
padding_below,
padding_above,
data_dilate_strides);
EXPECT_EQ(conv->get_element_type(), element::f32);
EXPECT_EQ(conv->get_shape(), data_batch_shape);
EXPECT_EQ(conv->get_window_movement_strides_forward(), Strides{1});
EXPECT_EQ(conv->get_window_dilation_strides_forward(), Strides{2});
EXPECT_EQ(conv->get_data_dilation_strides_forward(), Strides{3});
EXPECT_EQ(conv->get_padding_below_forward(), CoordinateDiff{2});
EXPECT_EQ(conv->get_padding_above_forward(), CoordinateDiff{3});
}
TEST(type_prop, conv_2d_deduce)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{64, 3, 100, 150});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{128, 3, 10, 20});
auto conv = make_shared<op::Convolution>(param0, param1);
EXPECT_EQ(conv->get_element_type(), element::f32);
EXPECT_EQ(conv->get_shape(), (Shape{64, 128, 91, 131}));
EXPECT_EQ(conv->get_window_movement_strides(), (Strides{1, 1}));
EXPECT_EQ(conv->get_window_dilation_strides(), (Strides{1, 1}));
EXPECT_EQ(conv->get_data_dilation_strides(), (Strides{1, 1}));
EXPECT_EQ(conv->get_padding_below(), (CoordinateDiff{0, 0}));
EXPECT_EQ(conv->get_padding_above(), (CoordinateDiff{0, 0}));
}
TEST(type_prop, conv_2d_deduce_padded)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{64, 3, 100, 150});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{128, 3, 10, 20});
auto move_strides = Strides{1, 1};
auto dilate_strides = Strides{1, 1};
auto padding_below = CoordinateDiff{2, 3};
auto padding_above = CoordinateDiff{3, 4};
auto conv = make_shared<op::Convolution>(
param0, param1, move_strides, dilate_strides, padding_below, padding_above);
EXPECT_EQ(conv->get_element_type(), element::f32);
EXPECT_EQ(conv->get_shape(), (Shape{64, 128, 96, 138}));
EXPECT_EQ(conv->get_window_movement_strides(), (Strides{1, 1}));
EXPECT_EQ(conv->get_window_dilation_strides(), (Strides{1, 1}));
EXPECT_EQ(conv->get_data_dilation_strides(), (Strides{1, 1}));
EXPECT_EQ(conv->get_padding_below(), (CoordinateDiff{2, 3}));
EXPECT_EQ(conv->get_padding_above(), (CoordinateDiff{3, 4}));
}
TEST(type_prop, conv_2d_deduce_padded_neg)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{64, 3, 100, 150});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{128, 3, 10, 20});
auto move_strides = Strides{1, 1};
auto dilate_strides = Strides{1, 1};
auto padding_below = CoordinateDiff{2, -3};
auto padding_above = CoordinateDiff{3, -4};
auto conv = make_shared<op::Convolution>(
param0, param1, move_strides, dilate_strides, padding_below, padding_above);
EXPECT_EQ(conv->get_element_type(), element::f32);
EXPECT_EQ(conv->get_shape(), (Shape{64, 128, 96, 124}));
EXPECT_EQ(conv->get_window_movement_strides(), (Strides{1, 1}));
EXPECT_EQ(conv->get_window_dilation_strides(), (Strides{1, 1}));
EXPECT_EQ(conv->get_data_dilation_strides(), (Strides{1, 1}));
EXPECT_EQ(conv->get_padding_below(), (CoordinateDiff{2, -3}));
EXPECT_EQ(conv->get_padding_above(), (CoordinateDiff{3, -4}));
}
struct DeduceAutoPadTest
: ::testing::TestWithParam<
std::tuple<Shape, Shape, Strides, Strides, CoordinateDiff, CoordinateDiff>>
{
};
TEST_P(DeduceAutoPadTest, same_lower)
{
auto image_shape = std::get<0>(GetParam());
image_shape.insert(image_shape.begin(), {1, 1}); // Add {N, C}
auto filter_shape = std::get<1>(GetParam());
filter_shape.insert(filter_shape.begin(), {1, 1}); // Add {O, I}
auto param0 = make_shared<op::Parameter>(element::f32, image_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filter_shape);
auto conv = make_shared<op::Convolution>(param0,
param1,
std::get<2>(GetParam()),
std::get<3>(GetParam()),
CoordinateDiff(),
CoordinateDiff(),
Strides(),
op::PadType::SAME_LOWER);
EXPECT_EQ(conv->get_padding_above(), std::get<4>(GetParam()));
EXPECT_EQ(conv->get_padding_below(), std::get<5>(GetParam()));
}
INSTANTIATE_TEST_CASE_P(type_prop,
DeduceAutoPadTest,
::testing::Values(std::make_tuple(Shape{5, 6},
Shape{3, 4},
Strides{2, 1},
Strides{1, 1},
CoordinateDiff{1, 1},
CoordinateDiff{1, 2}),
std::make_tuple(Shape{3, 3},
Shape{2, 2},
Strides{1, 1},
Strides{1, 1},
CoordinateDiff{0, 0},
CoordinateDiff{1, 1}),
std::make_tuple(Shape{28, 28},
Shape{3, 3},
Strides{2, 2},
Strides{1, 1},
CoordinateDiff{0, 0},
CoordinateDiff{1, 1}),
std::make_tuple(Shape{100, 150},
Shape{10, 20},
Strides{1, 1},
Strides{1, 1},
CoordinateDiff{4, 9},
CoordinateDiff{5, 10}),
std::make_tuple(Shape{2},
Shape{1},
Strides{3},
Strides{1},
CoordinateDiff{0},
CoordinateDiff{0}),
std::make_tuple(Shape{10, 1},
Shape{4, 1},
Strides{1, 1},
Strides{2, 1},
CoordinateDiff{3, 0},
CoordinateDiff{3, 0}),
std::make_tuple(Shape{10, 5, 6},
Shape{3, 3, 4},
Strides{1, 2, 1},
Strides{2, 1, 1},
CoordinateDiff{2, 1, 1},
CoordinateDiff{2, 1, 2})), );
TEST(type_prop, conv_2d_deduce_strided)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{64, 3, 100, 150});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{128, 3, 10, 20});
auto move_strides = Strides{2, 3};
auto conv = make_shared<op::Convolution>(param0, param1, move_strides);
EXPECT_EQ(conv->get_element_type(), element::f32);
EXPECT_EQ(conv->get_shape(), (Shape{64, 128, 46, 44}));
EXPECT_EQ(conv->get_window_movement_strides(), (Strides{2, 3}));
EXPECT_EQ(conv->get_window_dilation_strides(), (Strides{1, 1}));
EXPECT_EQ(conv->get_data_dilation_strides(), (Strides{1, 1}));
EXPECT_EQ(conv->get_padding_below(), (CoordinateDiff{0, 0}));
EXPECT_EQ(conv->get_padding_above(), (CoordinateDiff{0, 0}));
}
TEST(type_prop, conv_2d_deduce_strided_window_dilated)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{64, 3, 100, 150});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{128, 3, 10, 20});
auto move_strides = Strides{2, 3};
auto dilate_strides = Strides{3, 2};
auto conv = make_shared<op::Convolution>(param0, param1, move_strides, dilate_strides);
EXPECT_EQ(conv->get_element_type(), element::f32);
EXPECT_EQ(conv->get_shape(), (Shape{64, 128, 37, 38}));
EXPECT_EQ(conv->get_window_movement_strides(), (Strides{2, 3}));
EXPECT_EQ(conv->get_window_dilation_strides(), (Strides{3, 2}));
EXPECT_EQ(conv->get_data_dilation_strides(), (Strides{1, 1}));
EXPECT_EQ(conv->get_padding_below(), (CoordinateDiff{0, 0}));
EXPECT_EQ(conv->get_padding_above(), (CoordinateDiff{0, 0}));
}
TEST(type_prop, conv_2d_deduce_strided_window_dilated_data_dilated)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{64, 3, 100, 150});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{128, 3, 10, 20});
auto move_strides = Strides{2, 3};
auto dilate_strides = Strides{3, 2};
auto padding_below = CoordinateDiff{0, 0};
auto padding_above = CoordinateDiff{0, 0};
auto data_dilate_strides = Strides{2, 3};
auto conv = make_shared<op::Convolution>(param0,
param1,
move_strides,
dilate_strides,
padding_below,
padding_above,
data_dilate_strides);
EXPECT_EQ(conv->get_element_type(), element::f32);
EXPECT_EQ(conv->get_shape(), (Shape{64, 128, 86, 137}));
EXPECT_EQ(conv->get_window_movement_strides(), (Strides{2, 3}));
EXPECT_EQ(conv->get_window_dilation_strides(), (Strides{3, 2}));
EXPECT_EQ(conv->get_data_dilation_strides(), (Strides{2, 3}));
EXPECT_EQ(conv->get_padding_below(), (CoordinateDiff{0, 0}));
EXPECT_EQ(conv->get_padding_above(), (CoordinateDiff{0, 0}));
}
TEST(type_prop, conv_2d_deduce_strided_window_dilated_small)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{64, 3, 7, 8});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{128, 3, 2, 3});
auto move_strides = Strides{2, 3};
auto dilate_strides = Strides{3, 2};
auto conv = make_shared<op::Convolution>(param0, param1, move_strides, dilate_strides);
EXPECT_EQ(conv->get_element_type(), element::f32);
EXPECT_EQ(conv->get_shape(), (Shape{64, 128, 2, 2}));
EXPECT_EQ(conv->get_window_movement_strides(), (Strides{2, 3}));
EXPECT_EQ(conv->get_window_dilation_strides(), (Strides{3, 2}));
EXPECT_EQ(conv->get_data_dilation_strides(), (Strides{1, 1}));
EXPECT_EQ(conv->get_padding_below(), (CoordinateDiff{0, 0}));
EXPECT_EQ(conv->get_padding_above(), (CoordinateDiff{0, 0}));
}
TEST(type_prop, conv_3d_deduce_strided_window_dilated_small)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{64, 3, 7, 8, 10});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{128, 3, 2, 3, 2});
auto move_strides = Strides{2, 3, 4};
auto dilate_strides = Strides{3, 2, 2};
auto conv = make_shared<op::Convolution>(param0, param1, move_strides, dilate_strides);
EXPECT_EQ(conv->get_element_type(), element::f32);
EXPECT_EQ(conv->get_shape(), (Shape{64, 128, 2, 2, 2}));
EXPECT_EQ(conv->get_window_movement_strides(), (Strides{2, 3, 4}));
EXPECT_EQ(conv->get_window_dilation_strides(), (Strides{3, 2, 2}));
EXPECT_EQ(conv->get_data_dilation_strides(), (Strides{1, 1, 1}));
EXPECT_EQ(conv->get_padding_below(), (CoordinateDiff{0, 0, 0}));
EXPECT_EQ(conv->get_padding_above(), (CoordinateDiff{0, 0, 0}));
}
TEST(type_prop, conv_3d_deduce_strided_window_dilated_data_dilated_small)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{64, 3, 7, 8, 10});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{128, 3, 2, 3, 2});
auto move_strides = Strides{2, 3, 4};
auto dilate_strides = Strides{3, 2, 2};
auto padding_below = CoordinateDiff{0, 0, 0};
auto padding_above = CoordinateDiff{0, 0, 0};
auto data_dilate_strides = Strides{2, 3, 2};
auto conv = make_shared<op::Convolution>(param0,
param1,
move_strides,
dilate_strides,
padding_below,
padding_above,
data_dilate_strides);
EXPECT_EQ(conv->get_element_type(), element::f32);
EXPECT_EQ(conv->get_shape(), (Shape{64, 128, 5, 6, 5}));
EXPECT_EQ(conv->get_window_movement_strides(), (Strides{2, 3, 4}));
EXPECT_EQ(conv->get_window_dilation_strides(), (Strides{3, 2, 2}));
EXPECT_EQ(conv->get_data_dilation_strides(), (Strides{2, 3, 2}));
EXPECT_EQ(conv->get_padding_below(), (CoordinateDiff{0, 0, 0}));
EXPECT_EQ(conv->get_padding_above(), (CoordinateDiff{0, 0, 0}));
}
TEST(type_prop, conv_invalid_element_type_mismatch)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{3, 3, 3, 3});
auto param1 = make_shared<op::Parameter>(element::i32, Shape{3, 3, 2, 2});
try
{
auto conv = make_shared<op::Convolution>(param0, param1);
// Should have thrown, so fail if it didn't
FAIL() << "Invalid input with element type mismatch not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(error.what(),
std::string("Element types for data batch and filters do not match"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_invalid_0d_input)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{});
try
{
auto conv = make_shared<op::Convolution>(param0, param1);
// Should have thrown, so fail if it didn't
FAIL() << "Invalid 0D input not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(error.what(),
std::string("Data batch and filters must have rank of at least 3 "
"(one batch axis, one input-channel axis, "
"and at least one spatial dimension)"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_invalid_1d_input)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{2});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{2});
try
{
auto conv = make_shared<op::Convolution>(param0, param1);
// Should have thrown, so fail if it didn't
FAIL() << "Invalid 1D input not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(error.what(),
std::string("Data batch and filters must have rank of at least 3 "
"(one batch axis, one input-channel axis, "
"and at least one spatial dimension)"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_invalid_2d_input)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{2, 6});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{2, 6});
try
{
auto conv = make_shared<op::Convolution>(param0, param1);
// Should have thrown, so fail if it didn't
FAIL() << "Invalid 2D input not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(error.what(),
std::string("Data batch and filters must have rank of at least 3 "
"(one batch axis, one input-channel axis, "
"and at least one spatial dimension)"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_invalid_0_batch_size)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{0, 6, 1});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{0, 6, 1});
try
{
auto conv = make_shared<op::Convolution>(param0, param1);
// Should have thrown, so fail if it didn't
FAIL() << "Invalid input with 0 batch size not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(error.what(), std::string("Batch size is zero"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_invalid_0_input_channels)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{6, 0, 1});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{5, 0, 1});
try
{
auto conv = make_shared<op::Convolution>(param0, param1);
// Should have thrown, so fail if it didn't
FAIL() << "Invalid input with 0 input channels not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(
error.what(),
std::string("Data batch channel count and/or filter input channel count is zero"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_invalid_wrong_number_of_filter_dimensions_too_many)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 10, 10});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{5, 2, 3, 3, 3});
try
{
auto conv = make_shared<op::Convolution>(param0, param1);
// Should have thrown, so fail if it didn't
FAIL() << "Invalid input with too many filter dimensions not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(error.what(), std::string("Data batch and filters rank do not match"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_invalid_wrong_number_of_filter_dimensions_too_few)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 10, 10});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{5, 2, 3});
try
{
auto conv = make_shared<op::Convolution>(param0, param1);
// Should have thrown, so fail if it didn't
FAIL() << "Invalid input with too few filter dimensions not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(error.what(), std::string("Data batch and filters rank do not match"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_invalid_0_output_channels)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 10, 10});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{0, 2, 3, 3});
try
{
auto conv = make_shared<op::Convolution>(param0, param1);
// Should have thrown, so fail if it didn't
FAIL() << "Invalid input with 0 output channels not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(error.what(), std::string("Filter output channel count is zero"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_invalid_input_channel_mismatch)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 10, 10});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{6, 3, 3, 3});
try
{
auto conv = make_shared<op::Convolution>(param0, param1);
// Should have thrown, so fail if it didn't
FAIL() << "Invalid input with channel count mismatch not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(
error.what(),
std::string(
"Data batch channel count (2) does not match filter input channel count (3)"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_invalid_movement_stride_rank)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 10, 10});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 3, 3});
try
{
auto conv = make_shared<op::Convolution>(param0, param1, Strides{2, 3, 8});
// Should have thrown, so fail if it didn't
FAIL() << "Invalid input with wrong movement stride rank not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(
error.what(),
std::string("Ranks for data item shape/filters shape (data batch has shape "
"{6,2,10,10}, so data item rank is 2 and filters have shape {6,2,3,3}, so "
"filters spatial rank is 2), data dilation (Strides{1, 1}), padding below "
"(CoordinateDiff{0, 0}), padding above (CoordinateDiff{0, 0}), filter "
"strides (Strides{2, 3, 8}), and filter dilation (Strides{1, 1}) do not "
"match"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_invalid_window_dilation_stride_rank)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 10, 10});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 3, 3});
try
{
auto conv = make_shared<op::Convolution>(param0, param1, Strides{2, 3}, Strides{2, 3, 8});
// Should have thrown, so fail if it didn't
FAIL() << "Invalid input with wrong window dilation stride rank not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(
error.what(),
std::string("Ranks for data item shape/filters shape (data batch has shape "
"{6,2,10,10}, so data item rank is 2 and filters have shape {6,2,3,3}, so "
"filters spatial rank is 2), data dilation (Strides{1, 1}), padding below "
"(CoordinateDiff{0, 0}), padding above (CoordinateDiff{0, 0}), filter "
"strides (Strides{2, 3}), and filter dilation (Strides{2, 3, 8}) do not "
"match"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_invalid_data_dilation_stride_rank)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 10, 10});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 3, 3});
try
{
auto conv = make_shared<op::Convolution>(param0,
param1,
Strides{2, 3},
Strides{2, 3},
CoordinateDiff{0, 0},
CoordinateDiff{0, 0},
Strides{2, 3, 8});
// Should have thrown, so fail if it didn't
FAIL() << "Invalid input with wrong data dilation stride rank not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(
error.what(),
std::string("Ranks for data item shape/filters shape (data batch has shape "
"{6,2,10,10}, so data item rank is 2 and filters have shape {6,2,3,3}, so "
"filters spatial rank is 2), data dilation (Strides{2, 3, 8}), padding "
"below (CoordinateDiff{0, 0}), padding above (CoordinateDiff{0, 0}), "
"filter strides (Strides{2, 3}), and filter dilation (Strides{2, 3}) do "
"not match"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_invalid_padding_below_rank)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 10, 10});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 3, 3});
try
{
auto conv = make_shared<op::Convolution>(param0,
param1,
Strides{2, 3},
Strides{1, 1},
CoordinateDiff{0, 0, 0},
CoordinateDiff{0, 0});
// Should have thrown, so fail if it didn't
FAIL() << "Invalid input with wrong padding-below rank not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(
error.what(),
std::string(
"Ranks for data item shape/filters shape (data batch has shape "
"{6,2,10,10}, so data item rank is 2 and filters have shape {6,2,3,3}, so "
"filters spatial rank is 2), data dilation (Strides{1, 1}), padding below "
"(CoordinateDiff{0, 0, 0}), padding above (CoordinateDiff{0, 0}), filter "
"strides (Strides{2, 3}), and filter dilation (Strides{1, 1}) do not match"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_invalid_padding_above_rank)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 10, 10});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 3, 3});
try
{
auto conv = make_shared<op::Convolution>(param0,
param1,
Strides{2, 3},
Strides{2, 3},
CoordinateDiff{0, 0},
CoordinateDiff{0, 0, 0});
// Should have thrown, so fail if it didn't
FAIL() << "Invalid input with wrong padding-above rank not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(
error.what(),
std::string(
"Ranks for data item shape/filters shape (data batch has shape "
"{6,2,10,10}, so data item rank is 2 and filters have shape {6,2,3,3}, so "
"filters spatial rank is 2), data dilation (Strides{1, 1}), padding below "
"(CoordinateDiff{0, 0}), padding above (CoordinateDiff{0, 0, 0}), filter "
"strides (Strides{2, 3}), and filter dilation (Strides{2, 3}) do not match"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_invalid_input_spatial_size_negative_after_padding)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 10, 10});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 3, 3});
try
{
auto conv = make_shared<op::Convolution>(param0,
param1,
Strides{1, 1},
Strides{1, 1},
CoordinateDiff{-4, 0},
CoordinateDiff{-7, 0});
// Should have thrown, so fail if it didn't
FAIL() << "Invalid input with negative-length post-padding spatial axis not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(error.what(),
std::string("Data shape after padding and dilation has dimension less "
"than 1 (dim: -1) at axis 0"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_invalid_input_spatial_size_zero_after_padding)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 10, 10});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 3, 3});
try
{
auto conv = make_shared<op::Convolution>(param0,
param1,
Strides{1, 1},
Strides{1, 1},
CoordinateDiff{-4, 0},
CoordinateDiff{-6, 0});
// Should have thrown, so fail if it didn't
FAIL() << "Invalid input with zero-length post-padding spatial axis not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(error.what(),
std::string("Data shape after padding and dilation has dimension less "
"than 1 (dim: 0) at axis 0"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_invalid_input_spatial_size_0)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 0, 10});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 3, 3});
try
{
auto conv = make_shared<op::Convolution>(param0, param1);
// Should have thrown, so fail if it didn't
FAIL() << "Invalid input with zero-length spatial axis not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(error.what(),
std::string("Data shape after padding and dilation has "
"dimension less than 1 (dim: 0) at axis 0"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_invalid_window_size_0)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 10, 10});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 3, 0});
try
{
auto conv = make_shared<op::Convolution>(param0, param1);
// Should have thrown, so fail if it didn't
FAIL() << "Invalid input with zero-length window axis not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(
error.what(),
std::string("Window after dilation has dimension less than 1 (dim: 0) at axis 1"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_invalid_window_dilation_stride_0)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 10, 10});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 3, 3});
try
{
auto conv = make_shared<op::Convolution>(param0, param1, Strides{2, 3}, Strides{2, 0});
// Should have thrown, so fail if it didn't
FAIL() << "Invalid input with wrong 0-length window dilation stride axis not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(
error.what(),
std::string("Window dilation (Strides{2, 0}) has zero dimension at axis 1"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_invalid_data_dilation_stride_0)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 10, 10});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 3, 3});
try
{
auto conv = make_shared<op::Convolution>(param0,
param1,
Strides{2, 3},
Strides{2, 3},
CoordinateDiff{0, 0},
CoordinateDiff{0, 0},
Strides{2, 0});
// Should have thrown, so fail if it didn't
FAIL() << "Invalid input with wrong 0-length data dilation stride axis not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(
error.what(),
std::string("Data dilation (Strides{2, 0}) has zero dimension at axis 1"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_invalid_dilated_window_too_large)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 8, 8});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 3, 3});
try
{
auto conv = make_shared<op::Convolution>(param0, param1, Strides{1, 1}, Strides{4, 4});
// Should have thrown, so fail if it didn't
FAIL() << "Invalid input with oversized dilated window not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(error.what(),
std::string("Window after dilation has dimension (dim: 9) larger than "
"the data shape after padding (dim: 8) at axis 0"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_invalid_movement_stride_0)
{
// Deduce type
auto param0 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 10, 10});
auto param1 = make_shared<op::Parameter>(element::f32, Shape{6, 2, 3, 3});
try
{
auto conv = make_shared<op::Convolution>(param0, param1, Strides{0, 1});
// Should have thrown, so fail if it didn't
FAIL() << "Invalid input with wrong 0-length movement stride axis not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(
error.what(),
std::string("Window strides (Strides{0, 1}) has zero dimension at axis 0"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_partial_rank_dynamic_rank_dynamic_ok)
{
PartialShape data_batch_shape{PartialShape::dynamic()};
PartialShape filters_shape{PartialShape::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
ASSERT_EQ(conv->get_output_element_type(0), element::f32);
ASSERT_TRUE(conv->get_output_partial_shape(0).same_scheme(PartialShape::dynamic(4)));
}
TEST(type_prop, conv_partial_rank_dynamic_rank_dynamic_window_strides_rank_wrong)
{
PartialShape data_batch_shape{PartialShape::dynamic()};
PartialShape filters_shape{PartialShape::dynamic()};
Strides window_movement_strides{1, 1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
try
{
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
FAIL() << "Window stride rank mismatch not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(
error.what(),
std::string("Ranks for data item shape/filters shape (data batch has shape ?, so data "
"item rank is ? and filters have shape ?, so filters spatial rank is ?), "
"data dilation (Strides{1, 1}), padding below (CoordinateDiff{0, 0}), "
"padding above (CoordinateDiff{0, 0}), filter strides (Strides{1, 1, 1}), "
"and filter dilation (Strides{1, 1}) do not match"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_partial_rank_dynamic_rank_dynamic_window_strides_dim_zero)
{
PartialShape data_batch_shape{PartialShape::dynamic()};
PartialShape filters_shape{PartialShape::dynamic()};
Strides window_movement_strides{1, 0};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
try
{
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
FAIL() << "Window stride with dimension zero not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(
error.what(),
std::string("Window strides (Strides{1, 0}) has zero dimension at axis 1"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_partial_rank_dynamic_rank_dynamic_window_dilation_rank_wrong)
{
PartialShape data_batch_shape{PartialShape::dynamic()};
PartialShape filters_shape{PartialShape::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
try
{
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
FAIL() << "Window dilation rank mismatch not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(
error.what(),
std::string("Ranks for data item shape/filters shape (data batch has shape ?, so data "
"item rank is ? and filters have shape ?, so filters spatial rank is ?), "
"data dilation (Strides{1, 1}), padding below (CoordinateDiff{0, 0}), "
"padding above (CoordinateDiff{0, 0}), filter strides (Strides{1, 1}), and "
"filter dilation (Strides{1, 1, 1}) do not match"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_partial_rank_dynamic_rank_dynamic_window_dilation_dim_zero)
{
PartialShape data_batch_shape{PartialShape::dynamic()};
PartialShape filters_shape{PartialShape::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 0};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
try
{
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
FAIL() << "Window dilation with dimension zero not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(
error.what(),
std::string("Window dilation (Strides{1, 0}) has zero dimension at axis 1"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_partial_rank_dynamic_rank_dynamic_padding_below_rank_wrong)
{
PartialShape data_batch_shape{PartialShape::dynamic()};
PartialShape filters_shape{PartialShape::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
try
{
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
FAIL() << "Padding below rank mismatch not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(
error.what(),
std::string("Ranks for data item shape/filters shape (data batch has shape ?, so data "
"item rank is ? and filters have shape ?, so filters spatial rank is ?), "
"data dilation (Strides{1, 1}), padding below (CoordinateDiff{0, 0, 0}), "
"padding above (CoordinateDiff{0, 0}), filter strides (Strides{1, 1}), and "
"filter dilation (Strides{1, 1}) do not match"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_partial_rank_dynamic_rank_dynamic_padding_above_rank_wrong)
{
PartialShape data_batch_shape{PartialShape::dynamic()};
PartialShape filters_shape{PartialShape::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0, 0};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
try
{
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
FAIL() << "Padding above rank mismatch not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(
error.what(),
std::string("Ranks for data item shape/filters shape (data batch has shape ?, so data "
"item rank is ? and filters have shape ?, so filters spatial rank is ?), "
"data dilation (Strides{1, 1}), padding below (CoordinateDiff{0, 0}), "
"padding above (CoordinateDiff{0, 0, 0}), filter strides (Strides{1, 1}), "
"and filter dilation (Strides{1, 1}) do not match"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_partial_rank_dynamic_rank_dynamic_data_dilation_rank_wrong)
{
PartialShape data_batch_shape{PartialShape::dynamic()};
PartialShape filters_shape{PartialShape::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{1, 1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
try
{
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
FAIL() << "Data dilation rank mismatch not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(
error.what(),
std::string("Ranks for data item shape/filters shape (data batch has shape ?, so data "
"item rank is ? and filters have shape ?, so filters spatial rank is ?), "
"data dilation (Strides{1, 1, 1}), padding below (CoordinateDiff{0, 0}), "
"padding above (CoordinateDiff{0, 0}), filter strides (Strides{1, 1}), and "
"filter dilation (Strides{1, 1}) do not match"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_partial_rank_dynamic_rank_dynamic_data_dilation_dim_zero)
{
PartialShape data_batch_shape{PartialShape::dynamic()};
PartialShape filters_shape{PartialShape::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{1, 0};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
try
{
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
FAIL() << "Data dilation with dimension zero not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(
error.what(),
std::string("Data dilation (Strides{1, 0}) has zero dimension at axis 1"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_partial_rank_static_dynamic_rank_dynamic_ok)
{
PartialShape data_batch_shape{PartialShape::dynamic(4)};
PartialShape filters_shape{PartialShape::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
ASSERT_EQ(conv->get_output_element_type(0), element::f32);
ASSERT_TRUE(conv->get_output_partial_shape(0).same_scheme(PartialShape::dynamic(4)));
}
TEST(type_prop, conv_partial_rank_static_dynamic_rank_dynamic_data_batch_rank_wrong)
{
PartialShape data_batch_shape{PartialShape::dynamic(5)};
PartialShape filters_shape{PartialShape::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
try
{
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
FAIL() << "Data batch rank mismatch not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(
error.what(),
std::string("Ranks for data item shape/filters shape (data batch has shape "
"{?,?,?,?,?}, so data item rank is 3 and filters have shape ?, so filters "
"spatial rank is ?), data dilation (Strides{1, 1}), padding below "
"(CoordinateDiff{0, 0}), padding above (CoordinateDiff{0, 0}), filter "
"strides (Strides{1, 1}), and filter dilation (Strides{1, 1}) do not "
"match"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_partial_rank_static_dynamic_rank_dynamic_batch_size_known_ok)
{
PartialShape data_batch_shape{
64, Dimension::dynamic(), Dimension::dynamic(), Dimension::dynamic()};
PartialShape filters_shape{PartialShape::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
ASSERT_EQ(conv->get_output_element_type(0), element::f32);
ASSERT_TRUE(conv->get_output_partial_shape(0).same_scheme(
PartialShape{64, Dimension::dynamic(), Dimension::dynamic(), Dimension::dynamic()}));
}
TEST(type_prop, conv_partial_rank_static_dynamic_rank_dynamic_batch_size_known_zero)
{
PartialShape data_batch_shape{
0, Dimension::dynamic(), Dimension::dynamic(), Dimension::dynamic()};
PartialShape filters_shape{PartialShape::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
try
{
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
FAIL() << "Zero batch size not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(error.what(), std::string("Batch size is zero"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_partial_rank_static_dynamic_rank_dynamic_input_channel_count_known_ok)
{
PartialShape data_batch_shape{
Dimension::dynamic(), 3, Dimension::dynamic(), Dimension::dynamic()};
PartialShape filters_shape{PartialShape::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
ASSERT_EQ(conv->get_output_element_type(0), element::f32);
ASSERT_TRUE(conv->get_output_partial_shape(0).same_scheme(PartialShape::dynamic(4)));
}
TEST(type_prop, conv_partial_rank_static_dynamic_rank_dynamic_input_channel_count_known_zero)
{
PartialShape data_batch_shape{
Dimension::dynamic(), 0, Dimension::dynamic(), Dimension::dynamic()};
PartialShape filters_shape{PartialShape::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
try
{
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
FAIL() << "Zero input channel count not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(
error.what(),
std::string("Data batch channel count and/or filter input channel count is zero"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_partial_rank_dynamic_rank_static_dynamic_output_channel_count_known_ok)
{
PartialShape data_batch_shape{PartialShape::dynamic(4)};
PartialShape filters_shape{
32, Dimension::dynamic(), Dimension::dynamic(), Dimension::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
ASSERT_EQ(conv->get_output_element_type(0), element::f32);
ASSERT_TRUE(conv->get_output_partial_shape(0).same_scheme(
PartialShape{Dimension::dynamic(), 32, Dimension::dynamic(), Dimension::dynamic()}));
}
TEST(type_prop, conv_partial_rank_dynamic_rank_static_dynamic_output_channel_count_known_zero)
{
PartialShape data_batch_shape{PartialShape::dynamic(4)};
PartialShape filters_shape{0, Dimension::dynamic(), Dimension::dynamic(), Dimension::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
try
{
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
FAIL() << "Zero output channel count not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(error.what(), std::string("Filter output channel count is zero"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_partial_rank_dynamic_rank_static_dynamic_input_channel_count_known_ok)
{
PartialShape data_batch_shape{PartialShape::dynamic(4)};
PartialShape filters_shape{Dimension::dynamic(), 4, Dimension::dynamic(), Dimension::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
ASSERT_EQ(conv->get_output_element_type(0), element::f32);
ASSERT_TRUE(conv->get_output_partial_shape(0).same_scheme(PartialShape::dynamic(4)));
}
TEST(type_prop, conv_partial_rank_dynamic_rank_static_dynamic_input_channel_count_known_zero)
{
PartialShape data_batch_shape{PartialShape::dynamic(4)};
PartialShape filters_shape{Dimension::dynamic(), 0, Dimension::dynamic(), Dimension::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
try
{
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
FAIL() << "Zero input channel count not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(
error.what(),
std::string("Data batch channel count and/or filter input channel count is zero"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_partial_rank_static_dynamic_rank_static_dynamic_ok)
{
PartialShape data_batch_shape{PartialShape::dynamic(4)};
PartialShape filters_shape{PartialShape::dynamic(4)};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
ASSERT_EQ(conv->get_output_element_type(0), element::f32);
ASSERT_TRUE(conv->get_output_partial_shape(0).same_scheme(PartialShape::dynamic(4)));
}
TEST(type_prop, conv_partial_rank_static_dynamic_rank_static_dynamic_arg_ranks_mismatch)
{
PartialShape data_batch_shape{PartialShape::dynamic(5)};
PartialShape filters_shape{PartialShape::dynamic(4)};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
try
{
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
FAIL() << "Argument rank mismatch not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(error.what(),
std::string("Data batch and filters rank do not match (data batch "
"shape: {?,?,?,?,?}, filters shape: {?,?,?,?})"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_partial_rank_static_dynamic_rank_static_dynamic_input_channel_counts_known_ok)
{
PartialShape data_batch_shape{
Dimension::dynamic(), 3, Dimension::dynamic(), Dimension::dynamic()};
PartialShape filters_shape{Dimension::dynamic(), 3, Dimension::dynamic(), Dimension::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
ASSERT_EQ(conv->get_output_element_type(0), element::f32);
ASSERT_TRUE(conv->get_output_partial_shape(0).same_scheme(PartialShape::dynamic(4)));
}
TEST(type_prop, conv_partial_rank_static_dynamic_rank_static_dynamic_input_channel_counts_mismatch)
{
PartialShape data_batch_shape{
Dimension::dynamic(), 3, Dimension::dynamic(), Dimension::dynamic()};
PartialShape filters_shape{
Dimension::dynamic(), 22, Dimension::dynamic(), Dimension::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
try
{
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
FAIL() << "Input channel count mismatch not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(
error.what(),
std::string(
"Data batch channel count (3) does not match filter input channel count (22)"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_partial_rank_static_dynamic_rank_static_dynamic_all_nonspatial_known_ok)
{
PartialShape data_batch_shape{64, 3, Dimension::dynamic(), Dimension::dynamic()};
PartialShape filters_shape{100, 3, Dimension::dynamic(), Dimension::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
ASSERT_EQ(conv->get_output_element_type(0), element::f32);
ASSERT_TRUE(conv->get_output_partial_shape(0).same_scheme(
PartialShape{64, 100, Dimension::dynamic(), Dimension::dynamic()}));
}
TEST(type_prop,
conv_partial_rank_static_dynamic_rank_static_dynamic_all_nonspatial_some_spatial_known_ok)
{
PartialShape data_batch_shape{64, 3, 200, Dimension::dynamic()};
PartialShape filters_shape{100, 3, 5, Dimension::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
ASSERT_EQ(conv->get_output_element_type(0), element::f32);
ASSERT_TRUE(conv->get_output_partial_shape(0).same_scheme(
PartialShape{64, 100, 196, Dimension::dynamic()}));
}
TEST(
type_prop,
conv_partial_rank_static_dynamic_rank_static_dynamic_all_nonspatial_some_spatial_known_filters_too_big)
{
PartialShape data_batch_shape{64, 3, 200, Dimension::dynamic()};
PartialShape filters_shape{100, 3, 201, Dimension::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
try
{
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
FAIL() << "Oversize filter not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(error.what(),
std::string("Window after dilation has dimension (dim: 201) larger "
"than the data shape after padding (dim: 200) at axis 0"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(
type_prop,
conv_partial_rank_static_dynamic_rank_static_dynamic_all_nonspatial_some_spatial_known_filters_not_too_big_after_padding)
{
PartialShape data_batch_shape{64, 3, 200, Dimension::dynamic()};
PartialShape filters_shape{100, 3, 201, Dimension::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{2, 0};
CoordinateDiff padding_above{-1, 0};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
ASSERT_EQ(conv->get_output_element_type(0), element::f32);
ASSERT_TRUE(conv->get_output_partial_shape(0).same_scheme(
PartialShape{64, 100, 1, Dimension::dynamic()}));
}
TEST(
type_prop,
conv_partial_rank_static_dynamic_rank_static_dynamic_all_nonspatial_some_spatial_known_filters_not_too_big_after_data_dilation)
{
PartialShape data_batch_shape{64, 3, 200, Dimension::dynamic()};
PartialShape filters_shape{100, 3, 201, Dimension::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{2, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
ASSERT_EQ(conv->get_output_element_type(0), element::f32);
ASSERT_TRUE(conv->get_output_partial_shape(0).same_scheme(
PartialShape{64, 100, 199, Dimension::dynamic()}));
}
TEST(
type_prop,
conv_partial_rank_static_dynamic_rank_static_dynamic_all_nonspatial_some_spatial_known_filters_not_too_big_after_data_dilation_strided)
{
PartialShape data_batch_shape{64, 3, 200, Dimension::dynamic()};
PartialShape filters_shape{100, 3, 201, Dimension::dynamic()};
Strides window_movement_strides{3, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{2, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
ASSERT_EQ(conv->get_output_element_type(0), element::f32);
ASSERT_TRUE(conv->get_output_partial_shape(0).same_scheme(
PartialShape{64, 100, 67, Dimension::dynamic()}));
}
TEST(
type_prop,
conv_partial_rank_static_dynamic_rank_static_dynamic_all_nonspatial_some_spatial_known_filters_too_big_after_filter_dilation)
{
PartialShape data_batch_shape{64, 3, 200, Dimension::dynamic()};
PartialShape filters_shape{100, 3, 101, Dimension::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{2, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
try
{
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
FAIL() << "Oversize filter after window dilation not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(error.what(),
std::string("Window after dilation has dimension (dim: 201) larger "
"than the data shape after padding (dim: 200) at axis 0"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(
type_prop,
conv_partial_rank_static_dynamic_rank_static_dynamic_all_nonspatial_some_spatial_zero_data_batch_dim)
{
PartialShape data_batch_shape{64, 3, 200, 0};
PartialShape filters_shape{100, 3, 5, Dimension::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
try
{
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
FAIL() << "Zero dimension in data batch not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(error.what(),
std::string("Data shape after padding and dilation has "
"dimension less than 1 (dim: 0) at axis 1"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(
type_prop,
conv_partial_rank_static_dynamic_rank_static_dynamic_all_nonspatial_some_spatial_positive_data_batch_dim_after_padding)
{
PartialShape data_batch_shape{64, 3, 200, 0};
PartialShape filters_shape{100, 3, 5, Dimension::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 2};
CoordinateDiff padding_above{0, -1};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
ASSERT_EQ(conv->get_output_element_type(0), element::f32);
ASSERT_TRUE(conv->get_output_partial_shape(0).same_scheme(
PartialShape{64, 100, 196, Dimension::dynamic()}));
}
TEST(
type_prop,
conv_partial_rank_static_dynamic_rank_static_dynamic_all_nonspatial_some_spatial_zero_data_batch_dim_after_padding)
{
PartialShape data_batch_shape{64, 3, 200, 20};
PartialShape filters_shape{100, 3, 5, Dimension::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, -20};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
try
{
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
FAIL() << "Zero padded dimension in data batch not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(error.what(),
std::string("Data shape after padding and dilation has "
"dimension less than 1 (dim: 0) at axis 1"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(
type_prop,
conv_partial_rank_static_dynamic_rank_static_dynamic_all_nonspatial_some_spatial_negative_data_batch_dim_after_padding)
{
PartialShape data_batch_shape{64, 3, 200, 20};
PartialShape filters_shape{100, 3, 5, Dimension::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, -1};
CoordinateDiff padding_above{0, -20};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
try
{
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
FAIL() << "Negative padded dimension in data batch not detected";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(error.what(),
std::string("Data shape after padding and dilation has dimension less "
"than 1 (dim: -1) at axis 1"));
}
catch (...)
{
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, conv_partial_dynamic_et)
{
// For this test the exact shape parameters are kind of arbitrary---just copied and pasted
// from some known-"OK" test above. We're only concerned about the element types.
PartialShape data_batch_shape{64, 3, 200, Dimension::dynamic()};
PartialShape filters_shape{100, 3, 201, Dimension::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{2, 0};
CoordinateDiff padding_above{-1, 0};
Strides data_dilation_strides{1, 1};
auto param0 = make_shared<op::Parameter>(element::dynamic, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::dynamic, filters_shape);
auto conv = make_shared<op::Convolution>(param0,
param1,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides);
ASSERT_TRUE(conv->get_output_element_type(0).is_dynamic());
ASSERT_TRUE(conv->get_output_partial_shape(0).same_scheme(
PartialShape{64, 100, 1, Dimension::dynamic()}));
}
TEST(type_prop, conv_bprop_data_v1_output_partial_shape_dynamic)
{
Shape shape_filter{6, 3, 3, 3};
auto filters = make_shared<op::Parameter>(element::f32, shape_filter);
Shape shape_delta{2, 6, 3, 3};
auto deltas = make_shared<op::Parameter>(element::f32, shape_delta);
Shape shape_data_batch_shape{2, 3, 5, 5};
auto data_batch_shape = make_shared<op::Parameter>(element::i64, Shape{2, 3, 5, 5});
auto strides = Strides{1, 1};
auto dilations = Strides{1, 1};
auto padding_begin = CoordinateDiff{0, 0};
auto padding_end = CoordinateDiff{0, 0};
auto conv1 = make_shared<op::v1::ConvolutionBackpropData>(
deltas, filters, data_batch_shape, strides, padding_begin, padding_end, dilations);
ASSERT_TRUE(conv1->get_output_partial_shape(0).is_dynamic());
}
TEST(type_prop, conv_bprop_data_v1_output_partial_shape_dynamic_static_rank)
{
PartialShape shape_filter{20, 10, 3, 3};
auto filters = make_shared<op::Parameter>(element::f32, shape_filter);
PartialShape shape_delta{Dimension(), 20, 224, 224};
auto deltas = make_shared<op::Parameter>(element::f32, shape_delta);
auto strides = Strides{2, 2};
auto dilations = Strides{1, 1};
auto padding_begin = CoordinateDiff{1, 1};
auto padding_end = CoordinateDiff{1, 1};
auto conv1 = make_shared<op::v1::ConvolutionBackpropData>(
deltas, filters, strides, padding_begin, padding_end, dilations);
ASSERT_TRUE(conv1->get_output_partial_shape(0).rank().is_static());
ASSERT_TRUE(conv1->get_output_partial_shape(0).rank().same_scheme(Rank{4}));
ASSERT_TRUE(conv1->get_output_partial_shape(0).is_dynamic());
ASSERT_TRUE(conv1->get_output_partial_shape(0).same_scheme(
PartialShape{Dimension::dynamic(), 10, 447, 447}));
}
TEST(type_prop, conv_v1_partial_rank)
{
PartialShape data_batch_shape{PartialShape::dynamic()};
PartialShape filters_shape{PartialShape::dynamic()};
Strides window_movement_strides{1, 1};
Strides window_dilation_strides{1, 1};
CoordinateDiff padding_below{0, 0};
CoordinateDiff padding_above{0, 0};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, filters_shape);
auto conv = make_shared<op::v1::Convolution>(param0,
param1,
window_movement_strides,
padding_below,
padding_above,
window_dilation_strides);
ASSERT_TRUE(conv->get_output_partial_shape(0).is_dynamic());
}
TEST(type_prop, conv_v1_partial_auto_padding_same)
{
const PartialShape data_batch_shape{1, 1, 5, 5};
const PartialShape filters_shape{1, 1, 3, 3};
Strides strides{1, 1};
CoordinateDiff pads_begin{0, 0};
CoordinateDiff pads_end{0, 0};
Strides dilations{1, 1};
const auto auto_pad = op::PadType::SAME_LOWER;
auto data_batch = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto filters = make_shared<op::Parameter>(element::f32, filters_shape);
auto conv = make_shared<op::v1::Convolution>(
data_batch, filters, strides, pads_begin, pads_end, dilations, auto_pad);
ASSERT_TRUE(conv->get_output_partial_shape(0).same_scheme(PartialShape{1, 1, 5, 5}));
ASSERT_EQ(conv->get_pads_begin(), (CoordinateDiff{1, 1}));
ASSERT_EQ(conv->get_pads_end(), (CoordinateDiff{1, 1}));
}
TEST(type_prop, conv_v1_partial_auto_padding_same_nc_dims_dynamic_same_lower)
{
const PartialShape data_batch_shape{Dimension::dynamic(), Dimension::dynamic(), 5, 5};
const PartialShape filters_shape{1, 1, 3, 3};
Strides strides{1, 1};
CoordinateDiff pads_begin{0, 0};
CoordinateDiff pads_end{0, 0};
Strides dilations{1, 1};
const auto auto_pad = op::PadType::SAME_LOWER;
auto data_batch = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto filters = make_shared<op::Parameter>(element::f32, filters_shape);
auto conv = make_shared<op::v1::Convolution>(
data_batch, filters, strides, pads_begin, pads_end, dilations, auto_pad);
ASSERT_TRUE(conv->get_output_partial_shape(0).same_scheme({Dimension::dynamic(), 1, 5, 5}));
ASSERT_EQ(conv->get_pads_begin(), (CoordinateDiff{1, 1}));
ASSERT_EQ(conv->get_pads_end(), (CoordinateDiff{1, 1}));
}
TEST(type_prop, conv_v1_partial_auto_padding_same_nc_dims_dynamic_same_upper)
{
const PartialShape data_batch_shape{Dimension::dynamic(), Dimension::dynamic(), 5, 5};
const PartialShape filters_shape{1, 1, 2, 2};
Strides strides{1, 1};
CoordinateDiff pads_begin{0, 0};
CoordinateDiff pads_end{0, 0};
Strides dilations{1, 1};
const auto auto_pad = op::PadType::SAME_UPPER;
auto data_batch = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto filters = make_shared<op::Parameter>(element::f32, filters_shape);
auto conv = make_shared<op::v1::Convolution>(
data_batch, filters, strides, pads_begin, pads_end, dilations, auto_pad);
ASSERT_TRUE(conv->get_output_partial_shape(0).same_scheme({Dimension::dynamic(), 1, 5, 5}));
ASSERT_EQ(conv->get_pads_begin(), (CoordinateDiff{0, 0}));
ASSERT_EQ(conv->get_pads_end(), (CoordinateDiff{1, 1}));
}
TEST(type_prop, conv_v1_partial_auto_padding_same_spatial_dims_dynamic)
{
const PartialShape data_batch_shape{1, 1, Dimension::dynamic(), 5};
const PartialShape filters_shape{1, 1, 3, 3};
Strides strides{1, 1};
CoordinateDiff pads_begin{0, 0};
CoordinateDiff pads_end{0, 0};
Strides dilations{1, 1};
const auto auto_pad = op::PadType::SAME_LOWER;
auto data_batch = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto filters = make_shared<op::Parameter>(element::f32, filters_shape);
auto conv = make_shared<op::v1::Convolution>(
data_batch, filters, strides, pads_begin, pads_end, dilations, auto_pad);
ASSERT_TRUE(conv->get_output_partial_shape(0).same_scheme(
{1, 1, Dimension::dynamic(), Dimension::dynamic()}));
ASSERT_EQ(conv->get_pads_begin(), (CoordinateDiff{}));
ASSERT_EQ(conv->get_pads_end(), (CoordinateDiff{}));
}
TEST(type_prop, conv_v1_partial_data_shape_dynamic)
{
const PartialShape data_batch_shape{PartialShape::dynamic()};
const PartialShape filters_shape{1, 1, 3, 3};
Strides strides{1, 1};
CoordinateDiff pads_begin{0, 0};
CoordinateDiff pads_end{0, 0};
Strides dilations{1, 1};
const auto auto_pad = op::PadType::SAME_LOWER;
auto data_batch = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto filters = make_shared<op::Parameter>(element::f32, filters_shape);
auto conv = make_shared<op::v1::Convolution>(
data_batch, filters, strides, pads_begin, pads_end, dilations, auto_pad);
ASSERT_TRUE(conv->get_output_partial_shape(0).same_scheme({PartialShape::dynamic()}));
ASSERT_EQ(conv->get_pads_begin(), (CoordinateDiff{}));
ASSERT_EQ(conv->get_pads_end(), (CoordinateDiff{}));
}
TEST(type_prop, deformable_conv_incorrect_group)
{
const PartialShape data_batch_shape{1, 3, 96, 96};
const PartialShape deformable_values_shape{1, 50, 5, 5};
const PartialShape filters_shape{4, 3, 5, 5};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, deformable_values_shape);
auto param2 = make_shared<op::Parameter>(element::f32, filters_shape);
try
{
make_shared<op::v1::DeformableConvolution>(param0,
param1,
param2,
Strides{},
CoordinateDiff{},
CoordinateDiff{},
Strides{},
op::PadType::EXPLICIT,
2);
FAIL() << "DeformableConvolution created with incorrect 'group' value";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(error.what(), "input data shape must be evenly divisible");
}
try
{
make_shared<op::v1::DeformableConvolution>(param0,
param1,
param2,
Strides{},
CoordinateDiff{},
CoordinateDiff{},
Strides{},
op::PadType::EXPLICIT,
3);
FAIL() << "DeformableConvolution created with incorrect 'group' value";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(error.what(), "weights shape must be evenly divisible");
}
}
TEST(type_prop, deformable_conv_incorrect_deformable_group)
{
const PartialShape data_batch_shape{1, 3, 96, 96};
const PartialShape deformable_values_shape{1, 50, 5, 5};
const PartialShape filters_shape{3, 3, 5, 5};
auto param0 = make_shared<op::Parameter>(element::f32, data_batch_shape);
auto param1 = make_shared<op::Parameter>(element::f32, deformable_values_shape);
auto param2 = make_shared<op::Parameter>(element::f32, filters_shape);
try
{
make_shared<op::v1::DeformableConvolution>(param0,
param1,
param2,
Strides{},
CoordinateDiff{},
CoordinateDiff{},
Strides{},
op::PadType::EXPLICIT,
1,
7);
FAIL() << "DeformableConvolution created with incorrect 'deformable group' value";
}
catch (const NodeValidationFailure& error)
{
EXPECT_HAS_SUBSTRING(error.what(), "deformable values input must be evenly divisible");
}
}
| 43.08561 | 139 | 0.568597 | [
"shape"
] |
4b01cf73c34cf43e8a470f42a617ab67e709b384 | 3,968 | hpp | C++ | cpp/lib/asr.hpp | benjaminum/adaptive-surface-reconstruction | 32fa4cdcb56e10451cc93e574d6a628f883277b7 | [
"Apache-2.0"
] | 29 | 2021-11-02T08:35:33.000Z | 2022-03-28T16:26:17.000Z | cpp/lib/asr.hpp | benjaminum/adaptive-surface-reconstruction | 32fa4cdcb56e10451cc93e574d6a628f883277b7 | [
"Apache-2.0"
] | 1 | 2022-03-24T12:36:50.000Z | 2022-03-24T12:36:50.000Z | cpp/lib/asr.hpp | benjaminum/adaptive-surface-reconstruction | 32fa4cdcb56e10451cc93e574d6a628f883277b7 | [
"Apache-2.0"
] | 4 | 2021-12-11T00:34:14.000Z | 2021-12-20T00:24:24.000Z | //
// Copyright 2021 Intel (Autonomous Agents Lab)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#pragma once
#include <functional>
#include <memory>
#include "asr_config.h"
#include "asr_types.h"
ASR_NAMESPACE_BEGIN
/// Verbosity levels used for setting up the print function callbacks.
enum VERBOSITY_LEVELS { DEBUG = 0, INFO = 1, WARN = 2, ERROR = 3 };
/// Sets the print callback for specific verbosity levels.
/// \param print_callback Callback function used for printing.
/// \param levels The verbosity levelsfor which the callback should be
/// installed.
void SetPrintCallbackFunction(std::function<void(const char*)> print_callback,
std::vector<int> levels);
/// Sets the resource dir to the \p path .
void SetResourceDir(const char* path);
/// Returns the resource dir. The initial default resource dir is
/// <tt>$ORIGIN/asr_resources</tt>
const char* GetResourceDir();
/// Returns the version string of the library.
const char* GetVersionStr();
/// Returns the third-party notices as string.
const char* GetThirdPartyNotices();
/// Struct with the parameters for the ReconstructSurface function.
/// Use InitReconstructSurfaceParams() to create instances.
struct ReconstructSurfaceParams {
/// Scalar used for scaling the per point radius/footprint size.
float point_radius_scale;
/// The density threshold as percentile. To remove 10% of the points with
/// the lowest density set this to 10.
float density_percentile_threshold;
/// The number of neighbors to use for estimating the point radius/footprint
/// size. This parameter is used if the radii array is empty.
int point_radius_estimation_knn;
/// The maximum depth for the octree. This value should be in the range
/// [6..21].
int octree_max_depth;
/// The threshold for the unsigned distance for generating mesh vertices.
/// For small values only vertices will be generated where the algorithm is
/// certain about the surface. For large values the algorithm will generate
/// vertices even far away from the input data. The range of this value is
/// [0..2] and the default value is 1.
float contouring_value_threshold;
/// The number of connected components to keep in the postprocessing.
/// Set this to \w n to keep only the \w n largest connected components.
/// By default all components will be kept.
int64_t keep_n_connected_components;
/// The minimum size of a component to be kept. The default is 3 which means
/// even single triangles will be kept.
int64_t minimum_component_size;
};
/// Returns a ReconstructSurfaceParams struct with default values.
ReconstructSurfaceParams InitReconstructSurfaceParams();
/// Reconstruct the surface from an oriented point cloud with optional
/// radii/scale/footprint information.
///
/// \param points Points with shape [num_points, 3].
/// \param normals Normals with shape [num_points, 3].
/// \param radii The footprint size for each point with shape [num_points] or
/// an empty vector.
/// \param params Struct with parameters. Use InitReconstructSurfaceParams() to
/// create a set of default parameters.
/// \return A triangle mesh.
std::shared_ptr<ASRTriangleMesh> ReconstructSurface(
std::vector<float>& points,
std::vector<float>& normals,
std::vector<float>& radii,
const ReconstructSurfaceParams& params);
ASR_NAMESPACE_END
| 38.153846 | 80 | 0.728327 | [
"mesh",
"shape",
"vector"
] |
4b026650d192d5e458230a04b943614fe6d66a70 | 7,631 | cpp | C++ | src/linux_parser.cpp | hikuga/sysmonitor | 63180616635ca0aa051bd34baf06747141a5c714 | [
"MIT"
] | null | null | null | src/linux_parser.cpp | hikuga/sysmonitor | 63180616635ca0aa051bd34baf06747141a5c714 | [
"MIT"
] | null | null | null | src/linux_parser.cpp | hikuga/sysmonitor | 63180616635ca0aa051bd34baf06747141a5c714 | [
"MIT"
] | null | null | null | #include <dirent.h>
#include <unistd.h>
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
#include "linux_parser.h"
using std::stof;
using std::string;
using std::to_string;
using std::vector;
using std::for_each;
// DONE: An example of how to read data from the filesystem
// TODO clean this up, use the extract_p
string LinuxParser::OperatingSystem() {
string line;
string key;
string value;
std::ifstream filestream(kOSPath);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::replace(line.begin(), line.end(), ' ', '_');
std::replace(line.begin(), line.end(), '=', ' ');
std::replace(line.begin(), line.end(), '"', ' ');
std::istringstream linestream(line);
while (linestream >> key >> value) {
if (key == "PRETTY_NAME") {
std::replace(value.begin(), value.end(), '_', ' ');
return value;
}
}
}
}
return value;
}
// DONE: An example of how to read data from the filesystem
string LinuxParser::Kernel() {
string os, kernel, version;
string line;
std::ifstream stream(kProcDirectory + kVersionFilename);
if (stream.is_open()) {
std::getline(stream, line);
std::istringstream linestream(line);
linestream >> os >> kernel >> version;
}
return version;
}
vector<int> LinuxParser::Pids2() {
vector<int> pids;
auto pp = fs::path(kProcDirectory.c_str() );
auto dir_itr = fs::directory_iterator( pp); //fs::current_path());
for_each( begin(dir_itr), end(dir_itr), [&](auto& p){
string fn= p.path().filename().string();
if( fn.end() == find_if( begin(fn), end(fn), [&](char ch){
return !isdigit(ch);
})) {
pids.push_back( stoi(fn) );
}
}) ;
return pids;
}
// BONUS: Update this to use std::filesystem
// Pids2
// TODO: Read and return the system memory utilization
float LinuxParser::MemoryUtilization() { return 0.0; }
// TODO: Read and return the system uptime
long LinuxParser::UpTime() {
string line;
string wholeTime;
std::ifstream filestream(kProcDirectory + kUptimeFilename);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::istringstream linestream(line);
while (linestream >> wholeTime) {
try {
return std::stol(wholeTime);
} catch (const std::invalid_argument& arg) {
return 0;
}
}
}
}
return 0;
//auto res = extract_p(string{"/proc/uptime"}, string{"(.*)\\s+.*"});
//return (res.size()) ? stol(res[0]) : 0;
}
// TODO: Read and return the number of jiffies for the system
long LinuxParser::Jiffies() { return 0; }
// TODO: Read and return the number of active jiffies for a PID
// REMOVE: [[maybe_unused]] once you define the function
long LinuxParser::ActiveJiffies(int pid[[maybe_unused]]) { return 0; }
// TODO: Read and return the number of active jiffies for the system
long LinuxParser::ActiveJiffies() { return 0; }
// TODO: Read and return the number of idle jiffies for the system
long LinuxParser::IdleJiffies() { return 0; }
// TODO: Read and return CPU utilization
vector<string> LinuxParser::CpuUtilization() { return {}; }
// TODO: Read and return the total number of processes
int LinuxParser::TotalProcesses() {
auto res_running = extract_p( std::string{kProcDirectory+kStatFilename}, std::string{"processes\\s+(\\d+).*"});
return (res_running.size() > 0) ? stoi(res_running[0]) : 0;
}
// TODO: Read and return the number of running processes
int LinuxParser::RunningProcesses() {
auto res_running = extract_p( std::string{kProcDirectory+kStatFilename}, std::string{"procs_running\\s+(\\d+).*"});
return (res_running.size() > 0) ? stoi(res_running[0]) : 0;
}
// TODO: Read and return the command associated with a process
// REMOVE: [[maybe_unused]] once you define the function
string LinuxParser::Command(int pid) {
auto res = extract_p(string{"/proc/" + to_string(pid) + "/cmdline"}, string{"(.*)"});
//TODO clamp to cap the max.
return (res.size()) ? res[0] : "unknown cmd";
}
// TODO: Read and return the user ID associated with a process
// REMOVE: [[maybe_unused]] once you define the function
string LinuxParser::Uid(int pid) {
auto res_uuid = extract_p( string{"/proc/"+to_string(pid)+"/status"},
string{"Uid:\\s+(\\d+)\\s+.*"});
if(res_uuid.size())
return res_uuid[0];
return string("0000"); }
// TODO: Read and return the user associated with a process
// REMOVE: [[maybe_unused]] once you define the function
string LinuxParser::User(int pid) {
auto res_uuid = extract_p( string{"/proc/"+to_string(pid)+"/status"},
string{"Uid:\\s+(\\d+)\\s+.*"});
if(res_uuid.size()){
string uuid = res_uuid[0];
auto res_usr = extract_p(string{"/etc/passwd"}, string{"(.*):x:"}+uuid+":"+uuid+":.*");
if(res_usr.size())
return res_usr[0];
}
return string("nouser"); }
// TODO: Read and return the uptime of a process
// REMOVE: [[maybe_unused]] once you define the function
long LinuxParser::UpTime(int pid) {
// if file does not exist return -1?
/*
// get the latest from /proc/{PID}/stat column #22
auto res = extract_p( string{"/proc/"+to_string(pid)+"/stat"},
string{"\\-?\\d+\\s+\\(\\w+\\)\\s+\\w+\\s+[\\-?\\d+\\s+]{18}(\\d+)\\s+.*"} );
if(res.size()){
char* ends;
return strtol(res[0].c_str(), &ends, 10) / sysconf(_SC_CLK_TCK);
}
*/
string line;
string value;
std::ifstream filestream(kProcDirectory + "/" + std::to_string(pid) +
kStatFilename);
if (filestream.is_open()) {
std::getline(filestream, line);
std::istringstream linestream(line);
for (int i = 1; i <= 22; i++) {
linestream >> value;
if (i == 22) {
try {
return UpTime() - std::stol(value)/sysconf(_SC_CLK_TCK) ;
} catch (const std::invalid_argument &arg) {
return 0;
}
}
}
}
return 0;
}
/*
* Given a file path and a regex pattern extract matches.
* Return the first match only.
*/
std::vector<std::string> LinuxParser::extract_p(std::string path, std::string pattern){
std::string line;
std::vector<string> results;
std::ifstream f(path);
if (f.is_open()) {
while (std::getline(f, line)) {
std::regex rgx{pattern};
std::cmatch match;
if (regex_search(line.c_str(), match, rgx))
return std::vector<string>{next(begin(match)), end(match)};
//results.push_back(match[1]);
}
}
return results;
}
/*
std::string LinuxParser::extract(std::string path, std::string pattern){
std::string extracted;
std::ifstream f(path, std::ios::in | std::ios::binary);
// Obtain the size of the file.
const auto sz = fs::file_size( fs::path(path.c_str()) );
// Create a buffer.
std::string result(sz, '\0');
// Read the whole file into the buffer.
f.read(result.data(), sz);
std::regex rgx(pattern);
std::cmatch match;
//std::basic_regex match;
if (std::regex_search(result.c_str(), match , rgx)) {
//std::cout << "match: " << match[1];
extracted = match[1];
}
return extracted;
}
*/ | 31.403292 | 120 | 0.599004 | [
"vector"
] |
4b0487ea25cb5ddff3693c6346cf62794524a8c8 | 14,782 | cc | C++ | src/gmm/ebw-diag-gmm.cc | hihihippp/Kaldi | 861f838a2aea264a9e4ffa4df253df00a8b1247f | [
"Apache-2.0"
] | 19 | 2015-03-19T10:53:38.000Z | 2020-12-17T06:12:32.000Z | src/gmm/ebw-diag-gmm.cc | UdyanSachdev/kaldi | 861f838a2aea264a9e4ffa4df253df00a8b1247f | [
"Apache-2.0"
] | 1 | 2018-12-18T17:43:44.000Z | 2018-12-18T17:43:44.000Z | src/gmm/ebw-diag-gmm.cc | UdyanSachdev/kaldi | 861f838a2aea264a9e4ffa4df253df00a8b1247f | [
"Apache-2.0"
] | 47 | 2015-01-27T06:22:57.000Z | 2021-11-11T20:59:04.000Z | // gmm/ebw-diag-gmm.cc
// Copyright 2009-2011 Arnab Ghoshal, Petr Motlicek
// 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
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include <algorithm> // for std::max
#include <string>
#include <vector>
#include "gmm/diag-gmm.h"
#include "gmm/ebw-diag-gmm.h"
namespace kaldi {
// This function is used inside the EBW update routines.
// returns true if all variances were positive.
static bool EBWUpdateGaussian(
BaseFloat D,
GmmFlagsType flags,
const VectorBase<double> &orig_mean,
const VectorBase<double> &orig_var,
const VectorBase<double> &x_stats,
const VectorBase<double> &x2_stats,
double occ,
VectorBase<double> *mean,
VectorBase<double> *var,
double *auxf_impr) {
if (! (flags&(kGmmMeans|kGmmVariances))) { // nothing to do.
if (auxf_impr) *auxf_impr = 0.0;
mean->CopyFromVec(orig_mean);
var->CopyFromVec(orig_var);
return true;
}
KALDI_ASSERT(!( (flags&kGmmVariances) && !(flags&kGmmMeans))
&& "We didn't make the update cover this case sensibly (update vars not means)");
mean->SetZero();
var->SetZero();
mean->AddVec(D, orig_mean);
var->AddVec2(D, orig_mean);
var->AddVec(D, orig_var);
mean->AddVec(1.0, x_stats);
var->AddVec(1.0, x2_stats);
BaseFloat scale = 1.0 / (occ + D);
mean->Scale(scale);
var->Scale(scale);
var->AddVec2(-1.0, *mean);
if (!(flags&kGmmVariances)) var->CopyFromVec(orig_var);
if (!(flags&kGmmMeans)) mean->CopyFromVec(orig_mean);
// Return false if any NaN's.
for (int32 i = 0; i < mean->Dim(); i++) {
double m = ((*mean)(i)), v = ((*var)(i));
if (m!=m || v!=v || m-m != 0 || v-v != 0) {
return false;
}
}
if (var->Min() > 0.0) {
if (auxf_impr != NULL) {
// work out auxf improvement.
BaseFloat old_auxf = 0.0, new_auxf = 0.0;
int32 dim = orig_mean.Dim();
for (int32 i = 0; i < dim; i++) {
BaseFloat mean_diff = (*mean)(i) - orig_mean(i);
old_auxf += (occ+D) * -0.5 * (log(orig_var(i)) +
((*var)(i) + mean_diff*mean_diff)
/ orig_var(i));
new_auxf += (occ+D) * -0.5 * (log((*var)(i)) + 1.0);
}
*auxf_impr = new_auxf - old_auxf;
}
return true;
} else return false;
}
// Update Gaussian parameters only (no weights)
void UpdateEbwDiagGmm(const AccumDiagGmm &num_stats, // with I-smoothing, if used.
const AccumDiagGmm &den_stats,
GmmFlagsType flags,
const EbwOptions &opts,
DiagGmm *gmm,
BaseFloat *auxf_change_out,
BaseFloat *count_out,
int32 *num_floored_out) {
GmmFlagsType acc_flags = num_stats.Flags();
if (flags & ~acc_flags)
KALDI_ERR << "Incompatible flags: you requested to update flags \""
<< GmmFlagsToString(flags) << "\" but accumulators have only \""
<< GmmFlagsToString(acc_flags) << '"';
// It could be that the num stats actually contain the difference between
// num and den (for mean and var stats), and den stats only have the weights.
bool den_has_stats;
if (den_stats.Flags() != acc_flags) {
den_has_stats = false;
if (den_stats.Flags() != kGmmWeights)
KALDI_ERR << "Incompatible flags: num stats have flags \""
<< GmmFlagsToString(acc_flags) << "\" vs. den stats \""
<< GmmFlagsToString(den_stats.Flags()) << '"';
} else {
den_has_stats = true;
}
int32 num_comp = num_stats.NumGauss();
int32 dim = num_stats.Dim();
KALDI_ASSERT(num_stats.NumGauss() == den_stats.NumGauss());
KALDI_ASSERT(num_stats.Dim() == gmm->Dim());
KALDI_ASSERT(gmm->NumGauss() == num_comp);
if ( !(flags & (kGmmMeans | kGmmVariances)) ) {
return; // Nothing to update.
}
// copy DiagGMM model and transform this to the normal case
DiagGmmNormal diaggmmnormal;
gmm->ComputeGconsts();
diaggmmnormal.CopyFromDiagGmm(*gmm);
// go over all components
Vector<double> mean(dim), var(dim), mean_stats(dim), var_stats(dim);
for (int32 g = 0; g < num_comp; g++) {
BaseFloat num_count = num_stats.occupancy()(g),
den_count = den_stats.occupancy()(g);
if (num_count == 0.0 && den_count == 0.0) {
KALDI_VLOG(2) << "Not updating Gaussian " << g << " since counts are zero";
continue;
}
mean_stats.CopyFromVec(num_stats.mean_accumulator().Row(g));
if (den_has_stats)
mean_stats.AddVec(-1.0, den_stats.mean_accumulator().Row(g));
if (flags & kGmmVariances) {
var_stats.CopyFromVec(num_stats.variance_accumulator().Row(g));
if (den_has_stats)
var_stats.AddVec(-1.0, den_stats.variance_accumulator().Row(g));
}
double D = (opts.tau + opts.E * den_count) / 2;
if (D+num_count-den_count <= 0.0) {
// ensure +ve-- can be problem if num count == 0 and E=2.
D = -1.0001*(num_count-den_count) + 1.0e-10;
KALDI_ASSERT(D+num_count-den_count > 0.0);
}
// We initialize to half the value of D that would be dictated by E (and
// tau); this is part of the strategy used to ensure that the value of D we
// use is at least twice the value that would ensure positive variances.
int32 iter, max_iter = 100;
for (iter = 0; iter < max_iter; iter++) { // will normally break from the loop
// the first time.
if (EBWUpdateGaussian(D, flags,
diaggmmnormal.means_.Row(g),
diaggmmnormal.vars_.Row(g),
mean_stats, var_stats, num_count-den_count,
&mean, &var, NULL)) {
// Succeeded in getting all +ve vars at this value of D.
// So double D and commit changes.
D *= 2.0;
double auxf_impr = 0.0;
bool ans = EBWUpdateGaussian(D, flags,
diaggmmnormal.means_.Row(g),
diaggmmnormal.vars_.Row(g),
mean_stats, var_stats, num_count-den_count,
&mean, &var, &auxf_impr);
KALDI_ASSERT(ans);
if (auxf_change_out) *auxf_change_out += auxf_impr;
if (count_out) *count_out += den_count; // The idea is that for MMI, this will
// reflect the actual #frames trained on (the numerator one would be I-smoothed).
// In general (e.g. for MPE), we won't know the #frames.
diaggmmnormal.means_.CopyRowFromVec(mean, g);
diaggmmnormal.vars_.CopyRowFromVec(var, g);
break;
} else {
// small step
D *= 1.1;
}
}
if (iter > 0 && num_floored_out != NULL) (*num_floored_out)++;
if (iter == max_iter) KALDI_WARN << "Dropped off end of loop, recomputing D. (unexpected.)";
}
// copy to natural representation according to flags.
diaggmmnormal.CopyToDiagGmm(gmm, flags);
gmm->ComputeGconsts();
}
void UpdateEbwWeightsDiagGmm(const AccumDiagGmm &num_stats, // should have no I-smoothing
const AccumDiagGmm &den_stats,
const EbwWeightOptions &opts,
DiagGmm *gmm,
BaseFloat *auxf_change_out,
BaseFloat *count_out) {
DiagGmmNormal diaggmmnormal;
gmm->ComputeGconsts();
diaggmmnormal.CopyFromDiagGmm(*gmm);
Vector<double> weights(diaggmmnormal.weights_),
num_occs(num_stats.occupancy()),
den_occs(den_stats.occupancy());
if (opts.tau == 0.0 &&
num_occs.Sum() + den_occs.Sum() < opts.min_num_count_weight_update) {
KALDI_LOG << "Not updating weights for this state because total count is "
<< num_occs.Sum() + den_occs.Sum() << " < "
<< opts.min_num_count_weight_update;
if (count_out)
*count_out += num_occs.Sum();
return;
}
num_occs.AddVec(opts.tau, weights);
KALDI_ASSERT(weights.Dim() == num_occs.Dim() && num_occs.Dim() == den_occs.Dim());
if (weights.Dim() == 1) return; // Nothing to do: only one mixture.
double weight_auxf_at_start = 0.0, weight_auxf_at_end = 0.0;
int32 num_comp = weights.Dim();
for (int32 g = 0; g < num_comp; g++) { // c.f. eq. 4.32 in Dan Povey's thesis.
weight_auxf_at_start +=
num_occs(g) * log (weights(g))
- den_occs(g) * weights(g) / diaggmmnormal.weights_(g);
}
for (int32 iter = 0; iter < 50; iter++) {
Vector<double> k_jm(num_comp); // c.f. eq. 4.35
double max_m = 0.0;
for (int32 g = 0; g < num_comp; g++)
max_m = std::max(max_m, den_occs(g)/diaggmmnormal.weights_(g));
for (int32 g = 0; g < num_comp; g++)
k_jm(g) = max_m - den_occs(g)/diaggmmnormal.weights_(g);
for (int32 g = 0; g < num_comp; g++) // c.f. eq. 4.34
weights(g) = num_occs(g) + k_jm(g)*weights(g);
weights.Scale(1.0 / weights.Sum()); // c.f. eq. 4.34 (denominator)
}
for (int32 g = 0; g < num_comp; g++) { // weight flooring.
if (weights(g) < opts.min_gaussian_weight)
weights(g) = opts.min_gaussian_weight;
}
weights.Scale(1.0 / weights.Sum()); // renormalize after flooring..
// floor won't be exact now but doesn't really matter.
for (int32 g = 0; g < num_comp; g++) { // c.f. eq. 4.32 in Dan Povey's thesis.
weight_auxf_at_end +=
num_occs(g) * log (weights(g))
- den_occs(g) * weights(g) / diaggmmnormal.weights_(g);
}
if (auxf_change_out)
*auxf_change_out += weight_auxf_at_end - weight_auxf_at_start;
if (count_out)
*count_out += num_occs.Sum(); // only really valid for MMI [not MPE, or MMI
// with canceled stats]
diaggmmnormal.weights_.CopyFromVec(weights);
// copy to natural representation
diaggmmnormal.CopyToDiagGmm(gmm, kGmmAll);
gmm->ComputeGconsts();
}
void UpdateEbwAmDiagGmm(const AccumAmDiagGmm &num_stats, // with I-smoothing, if used.
const AccumAmDiagGmm &den_stats,
GmmFlagsType flags,
const EbwOptions &opts,
AmDiagGmm *am_gmm,
BaseFloat *auxf_change_out,
BaseFloat *count_out,
int32 *num_floored_out) {
KALDI_ASSERT(num_stats.NumAccs() == den_stats.NumAccs()
&& num_stats.NumAccs() == am_gmm->NumPdfs());
if (auxf_change_out) *auxf_change_out = 0.0;
if (count_out) *count_out = 0.0;
if (num_floored_out) *num_floored_out = 0.0;
for (int32 pdf = 0; pdf < num_stats.NumAccs(); pdf++)
UpdateEbwDiagGmm(num_stats.GetAcc(pdf), den_stats.GetAcc(pdf), flags,
opts, &(am_gmm->GetPdf(pdf)), auxf_change_out,
count_out, num_floored_out);
}
void UpdateEbwWeightsAmDiagGmm(const AccumAmDiagGmm &num_stats, // with I-smoothing, if used.
const AccumAmDiagGmm &den_stats,
const EbwWeightOptions &opts,
AmDiagGmm *am_gmm,
BaseFloat *auxf_change_out,
BaseFloat *count_out) {
KALDI_ASSERT(num_stats.NumAccs() == den_stats.NumAccs()
&& num_stats.NumAccs() == am_gmm->NumPdfs());
if (auxf_change_out) *auxf_change_out = 0.0;
if (count_out) *count_out = 0.0;
for (int32 pdf = 0; pdf < num_stats.NumAccs(); pdf++)
UpdateEbwWeightsDiagGmm(num_stats.GetAcc(pdf), den_stats.GetAcc(pdf),
opts, &(am_gmm->GetPdf(pdf)), auxf_change_out,
count_out);
}
void IsmoothStatsDiagGmm(const AccumDiagGmm &src_stats,
double tau,
AccumDiagGmm *dst_stats) {
KALDI_ASSERT(src_stats.NumGauss() == dst_stats->NumGauss());
int32 dim = src_stats.Dim(), num_gauss = src_stats.NumGauss();
for (int32 g = 0; g < num_gauss; g++) {
double occ = src_stats.occupancy()(g);
if (occ != 0.0) { // can only do this for nonzero occupancies...
Vector<double> x_stats(dim), x2_stats(dim);
if (dst_stats->Flags() & kGmmMeans)
x_stats.CopyFromVec(src_stats.mean_accumulator().Row(g));
if (dst_stats->Flags() & kGmmVariances)
x2_stats.CopyFromVec(src_stats.variance_accumulator().Row(g));
x_stats.Scale(tau / occ);
x2_stats.Scale(tau / occ);
dst_stats->AddStatsForComponent(g, tau, x_stats, x2_stats);
}
}
}
/// Creates stats from the GMM. Resizes them as needed.
void DiagGmmToStats(const DiagGmm &gmm,
GmmFlagsType flags,
double state_occ,
AccumDiagGmm *dst_stats) {
dst_stats->Resize(gmm, AugmentGmmFlags(flags));
int32 num_gauss = gmm.NumGauss(), dim = gmm.Dim();
DiagGmmNormal gmmnormal(gmm);
Vector<double> x_stats(dim), x2_stats(dim);
for (int32 g = 0; g < num_gauss; g++) {
double occ = state_occ * gmmnormal.weights_(g);
x_stats.SetZero();
x_stats.AddVec(occ, gmmnormal.means_.Row(g));
x2_stats.SetZero();
x2_stats.AddVec2(occ, gmmnormal.means_.Row(g));
x2_stats.AddVec(occ, gmmnormal.vars_.Row(g));
dst_stats->AddStatsForComponent(g, occ, x_stats, x2_stats);
}
}
void IsmoothStatsAmDiagGmm(const AccumAmDiagGmm &src_stats,
double tau,
AccumAmDiagGmm *dst_stats) {
int num_pdfs = src_stats.NumAccs();
KALDI_ASSERT(num_pdfs == dst_stats->NumAccs());
for (int32 pdf = 0; pdf < num_pdfs; pdf++)
IsmoothStatsDiagGmm(src_stats.GetAcc(pdf), tau, &(dst_stats->GetAcc(pdf)));
}
void IsmoothStatsAmDiagGmmFromModel(const AmDiagGmm &src_model,
double tau,
AccumAmDiagGmm *dst_stats) {
int num_pdfs = src_model.NumPdfs();
KALDI_ASSERT(num_pdfs == dst_stats->NumAccs());
for (int32 pdf = 0; pdf < num_pdfs; pdf++) {
AccumDiagGmm tmp_stats;
double occ = 1.0; // its value doesn't matter.
DiagGmmToStats(src_model.GetPdf(pdf), kGmmAll, occ, &tmp_stats);
IsmoothStatsDiagGmm(tmp_stats, tau, &(dst_stats->GetAcc(pdf)));
}
}
} // End of namespace kaldi
| 39.31383 | 96 | 0.601948 | [
"vector",
"model",
"transform"
] |
4b0521bf86bb0b1c22016b774cb7c417e8688b8b | 1,679 | cpp | C++ | persist/persist-vector-main.cpp | zhuhaijun753/cplusplus11.Examples | 30076615a88039084a4478e4ce091c00c3bfc9d6 | [
"Unlicense"
] | 59 | 2016-05-22T08:09:03.000Z | 2022-02-20T13:37:36.000Z | persist/persist-vector-main.cpp | zhuhaijun753/cplusplus11.Examples | 30076615a88039084a4478e4ce091c00c3bfc9d6 | [
"Unlicense"
] | 1 | 2017-10-26T11:40:43.000Z | 2017-10-26T15:14:04.000Z | persist/persist-vector-main.cpp | lostjared/cplusplus11.Examples | 30076615a88039084a4478e4ce091c00c3bfc9d6 | [
"Unlicense"
] | 15 | 2017-03-09T16:15:43.000Z | 2021-09-22T16:36:17.000Z | #include"persist-vector.hpp"
#include<sstream>
struct Record {
char str_value[100];
int data;
};
class CustomRead {
public:
void operator()(std::string &type, std::fstream &file) {
unsigned int value = 0;
file.read(reinterpret_cast<char*>(&value), sizeof(unsigned int));
char *tmp = new char[value+1];
file.read(tmp, value);
type = tmp;
delete [] tmp;
}
};
class CustomWrite {
public:
void operator()(std::string &type, std::fstream &file) {
unsigned int value = type.length();
file.write(reinterpret_cast<char*>(&value), sizeof(value));
file.write(type.c_str(), value);
}
};
void outputItems(persist::Vector<Record> &pv) {
for(auto start = pv->begin(), stop = pv->end(); start != stop; ++start) {
std::cout << "Record string: " << start->str_value << "\n";
std::cout << "Record integer: " << start->data << "\n\n\n";
}
}
void outputCustomItems(persist::Vector<std::string, CustomRead, CustomWrite> &cv) {
for(unsigned int i = 0; i < cv->size(); ++i) {
std::cout << "Value: " << cv[i] << "\n";
}
}
int main(int argc, char **argv) {
persist::Vector<Record> pv("file.txt", 100);
outputItems(pv);
persist::Vector<std::string, CustomRead, CustomWrite> cv("custom.txt", 100);
outputCustomItems(cv);
std::ostringstream stream;
stream << "test run @ " << static_cast<unsigned int>(time(0)) << "\n";
cv->push_back(stream.str());
Record r;
std::cout << "Enter string: ";
std::cin >> r.str_value;
std::cout << "Enter integer: ";
std::cin >> r.data;
pv->push_back(r);
return 0;
} | 27.52459 | 83 | 0.57832 | [
"vector"
] |
4b060ba1d1cb7c55dc13896d05b5914a10087dfe | 1,913 | cpp | C++ | td-4/main-4a-1.cpp | badouralix/itr-tutorial | 7cae15b96167e2c09341cdb5cbbb9ebed6242a3a | [
"MIT"
] | null | null | null | td-4/main-4a-1.cpp | badouralix/itr-tutorial | 7cae15b96167e2c09341cdb5cbbb9ebed6242a3a | [
"MIT"
] | null | null | null | td-4/main-4a-1.cpp | badouralix/itr-tutorial | 7cae15b96167e2c09341cdb5cbbb9ebed6242a3a | [
"MIT"
] | null | null | null | #include <ctime>
#include <iostream>
#include <memory>
#include <sstream>
#include <vector>
#include "td-4a-1.h"
class IncrThread : public Thread
{
private:
unsigned int nLoops;
double *pCounter;
public:
IncrThread(unsigned int nLoops, double* pCounter) :
nLoops(nLoops), pCounter(pCounter)
{
}
~IncrThread()
{
}
protected:
void run()
{
for (unsigned int i = 0; i < nLoops; i++) {
*pCounter += 1.0;
}
}
};
int main(int argc, char* argv[])
{
unsigned int nTasks = 0, nLoops;
double accum, nCounter;
struct timespec start, stop;
// Parse args
if (argc != 3) {
std::cout << "Usage: " << argv[0] << " nLoops nTasks" << std::endl;
return EXIT_FAILURE;
}
std::istringstream iss(argv[1]);
iss >> nLoops;
iss.clear();
iss.str(argv[2]);
iss >> nTasks;
// Initialize threads
std::vector<std::unique_ptr<Thread>> threads(nTasks);
// Call incr and print with time measure
if( clock_gettime( CLOCK_REALTIME, &start) == -1 ) {
perror( "clock gettime" );
exit( EXIT_FAILURE );
}
// Create threads
for (auto it = threads.begin(); it != threads.end(); it++) {
it->reset(new IncrThread(nLoops, &nCounter));
}
// Start threads
for (auto it = threads.begin(); it != threads.end(); it++) {
(*it)->start();
}
// Join threads
for (auto it = threads.begin(); it != threads.end(); it++) {
(*it)->join();
}
if( clock_gettime( CLOCK_REALTIME, &stop) == -1 ) {
perror( "clock gettime" );
exit( EXIT_FAILURE );
}
// Print results
accum = (stop.tv_sec - start.tv_sec) + (stop.tv_nsec - start.tv_nsec) * 1e-9;
std::cout << "Counter value: " << nCounter << std::endl;
std::cout << "Timeit: " << accum << "s" << std::endl;
return EXIT_SUCCESS;
}
| 20.793478 | 81 | 0.55149 | [
"vector"
] |
4b0bd387b93002db2f50cc654486936b6ad9ede0 | 5,555 | cpp | C++ | Code/UnitTests/GameEngineTest/TestClass/TestClass.cpp | JohannStudanski/ezEngine | bb9d7dc4ad1ba52c2725f0a8bd1b851d59dbf43c | [
"MIT"
] | 1 | 2021-06-23T14:44:02.000Z | 2021-06-23T14:44:02.000Z | Code/UnitTests/GameEngineTest/TestClass/TestClass.cpp | aemeltsev/ezEngine | 98528c268dbf8cf37bb1f31e8664bd9651b7023f | [
"MIT"
] | null | null | null | Code/UnitTests/GameEngineTest/TestClass/TestClass.cpp | aemeltsev/ezEngine | 98528c268dbf8cf37bb1f31e8664bd9651b7023f | [
"MIT"
] | null | null | null | #include <GameEngineTestPCH.h>
#include "TestClass.h"
#include <Core/World/World.h>
#include <Core/World/WorldDesc.h>
#include <Core/WorldSerializer/WorldReader.h>
#include <Foundation/Configuration/Startup.h>
#include <Foundation/IO/FileSystem/FileReader.h>
#include <Foundation/IO/FileSystem/FileSystem.h>
#include <RendererFoundation/Device/Device.h>
ezGameEngineTest::ezGameEngineTest() = default;
ezGameEngineTest::~ezGameEngineTest() = default;
ezResult ezGameEngineTest::GetImage(ezImage& img)
{
img.ResetAndCopy(m_pApplication->GetLastScreenshot());
return EZ_SUCCESS;
}
ezResult ezGameEngineTest::InitializeTest()
{
m_pApplication = CreateApplication();
if (m_pApplication == nullptr)
return EZ_FAILURE;
ezRun_Startup(m_pApplication);
if (ezGALDevice::HasDefaultDevice() &&
ezGALDevice::GetDefaultDevice()->GetCapabilities().m_sAdapterName == "Microsoft Basic Render Driver")
{
// Use different images for comparison when running the D3D11 Reference Device
ezTestFramework::GetInstance()->SetImageReferenceOverrideFolderName("Images_Reference_D3D11Ref");
}
else
{
ezTestFramework::GetInstance()->SetImageReferenceOverrideFolderName("");
}
return EZ_SUCCESS;
}
ezResult ezGameEngineTest::DeInitializeTest()
{
if (m_pApplication)
{
m_pApplication->RequestQuit();
ezInt32 iSteps = 2;
while (m_pApplication->Run() == ezApplication::Continue && iSteps > 0)
{
--iSteps;
}
ezRun_Shutdown(m_pApplication);
EZ_DEFAULT_DELETE(m_pApplication);
if (iSteps == 0)
return EZ_FAILURE;
}
return EZ_SUCCESS;
}
ezResult ezGameEngineTest::InitializeSubTest(ezInt32 iIdentifier)
{
SUPER::InitializeSubTest(iIdentifier);
ezResourceManager::ForceNoFallbackAcquisition(3);
return EZ_SUCCESS;
}
//////////////////////////////////////////////////////////////////////////
ezGameEngineTestApplication::ezGameEngineTestApplication(const char* szProjectDirName)
: ezGameApplication("ezGameEngineTest", nullptr)
{
m_pWorld = nullptr;
m_sProjectDirName = szProjectDirName;
}
ezString ezGameEngineTestApplication::FindProjectDirectory() const
{
return m_sAppProjectPath;
}
ezString ezGameEngineTestApplication::GetProjectDataDirectoryPath() const
{
ezStringBuilder sProjectPath(">sdk/", ezTestFramework::GetInstance()->GetRelTestDataPath(), "/", m_sProjectDirName);
return sProjectPath;
}
ezResult ezGameEngineTestApplication::LoadScene(const char* szSceneFile)
{
EZ_LOCK(m_pWorld->GetWriteMarker());
m_pWorld->Clear();
ezFileReader file;
if (file.Open(szSceneFile).Succeeded())
{
// File Header
{
ezAssetFileHeader header;
header.Read(file);
char szSceneTag[16];
file.ReadBytes(szSceneTag, sizeof(char) * 16);
EZ_ASSERT_RELEASE(ezStringUtils::IsEqualN(szSceneTag, "[ezBinaryScene]", 16), "The given file is not a valid scene file");
}
ezWorldReader reader;
reader.ReadWorldDescription(file);
reader.InstantiateWorld(*m_pWorld, nullptr);
return EZ_SUCCESS;
}
else
{
ezLog::Error("Failed to load scene '{0}'", szSceneFile);
return EZ_FAILURE;
}
}
ezResult ezGameEngineTestApplication::BeforeCoreSystemsStartup()
{
EZ_SUCCEED_OR_RETURN(SUPER::BeforeCoreSystemsStartup());
ezStringBuilder sProject;
ezFileSystem::ResolveSpecialDirectory(GetProjectDataDirectoryPath(), sProject);
m_sAppProjectPath = sProject;
return EZ_SUCCESS;
}
void ezGameEngineTestApplication::AfterCoreSystemsStartup()
{
ExecuteInitFunctions();
ezStartup::StartupHighLevelSystems();
ezWorldDesc desc("GameEngineTestWorld");
m_pWorld = EZ_DEFAULT_NEW(ezWorld, desc);
m_pWorld->GetClock().SetFixedTimeStep(ezTime::Seconds(1.0 / 30.0));
ActivateGameState(m_pWorld.Borrow());
}
void ezGameEngineTestApplication::BeforeHighLevelSystemsShutdown()
{
m_pWorld = nullptr;
SUPER::BeforeHighLevelSystemsShutdown();
}
void ezGameEngineTestApplication::StoreScreenshot(ezImage&& image, const char* szContext)
{
// store this for image comparison purposes
m_LastScreenshot.ResetAndMove(std::move(image));
}
void ezGameEngineTestApplication::Init_FileSystem_ConfigureDataDirs()
{
SUPER::Init_FileSystem_ConfigureDataDirs();
// additional data directories for the tests to work
{
ezFileSystem::SetSpecialDirectory("testout", ezTestFramework::GetInstance()->GetAbsOutputPath());
ezStringBuilder sBaseDir = ">sdk/Data/Base/";
ezStringBuilder sReadDir(">sdk/", ezTestFramework::GetInstance()->GetRelTestDataPath());
ezFileSystem::AddDataDirectory(">eztest/", "ImageComparisonDataDir", "imgout", ezFileSystem::AllowWrites);
ezFileSystem::AddDataDirectory(sReadDir, "ImageComparisonDataDir");
}
}
ezUniquePtr<ezGameStateBase> ezGameEngineTestApplication::CreateGameState(ezWorld* pWorld)
{
return EZ_DEFAULT_NEW(ezGameEngineTestGameState);
}
//////////////////////////////////////////////////////////////////////////
EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezGameEngineTestGameState, 1, ezRTTIDefaultAllocator<ezGameEngineTestGameState>)
EZ_END_DYNAMIC_REFLECTED_TYPE;
void ezGameEngineTestGameState::ProcessInput()
{
// Do nothing, user input should be ignored
// trigger taking a screenshot every frame, for image comparison purposes
ezGameApplicationBase::GetGameApplicationBaseInstance()->TakeScreenshot();
}
ezGameStatePriority ezGameEngineTestGameState::DeterminePriority(ezWorld* pWorld) const
{
return ezGameStatePriority::Default;
}
void ezGameEngineTestGameState::ConfigureInputActions()
{
// do nothing
}
| 25.957944 | 128 | 0.744554 | [
"render"
] |
4b0f521162614b2ceabbf99e9e9835e98bfc487e | 2,729 | cpp | C++ | code archive/toi/20170718-p2.cpp | brianbbsu/program | c4505f2b8c0b91010e157db914a63c49638516bc | [
"MIT"
] | 4 | 2018-04-08T08:07:58.000Z | 2021-06-07T14:55:24.000Z | code archive/toi/20170718-p2.cpp | brianbbsu/program | c4505f2b8c0b91010e157db914a63c49638516bc | [
"MIT"
] | null | null | null | code archive/toi/20170718-p2.cpp | brianbbsu/program | c4505f2b8c0b91010e157db914a63c49638516bc | [
"MIT"
] | 1 | 2018-10-29T12:37:25.000Z | 2018-10-29T12:37:25.000Z | //{
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef double lf;
typedef pair<ll,ll> ii;
#define REP(i,n) for(ll i=0;i<n;i++)
#define REP1(i,n) for(ll i=1;i<=n;i++)
#define FILL(i,n) memset(i,n,sizeof i)
#define X first
#define Y second
#define SZ(_a) (int)_a.size()
#define ALL(_a) _a.begin(),_a.end()
#define pb push_back
#ifdef brian
#define debug(...) do{\
fprintf(stderr,"%s - %d (%s) = ",__PRETTY_FUNCTION__,__LINE__,#__VA_ARGS__);\
_do(__VA_ARGS__);\
}while(0)
template<typename T>void _do(T &&_x){cerr<<_x<<endl;}
template<typename T,typename ...S> void _do(T &&_x,S &&..._t){cerr<<_x<<" ,";_do(_t...);}
template<typename _a,typename _b> ostream& operator << (ostream &_s,const pair<_a,_b> &_p){return _s<<"("<<_p.X<<","<<_p.Y<<")";}
template<typename It> ostream& _OUTC(ostream &_s,It _ita,It _itb)
{
_s<<"{";
for(It _it=_ita;_it!=_itb;_it++)
{
_s<<(_it==_ita?"":",")<<*_it;
}
_s<<"}";
return _s;
}
template<typename _a> ostream &operator << (ostream &_s,vector<_a> &_c){return _OUTC(_s,ALL(_c));}
template<typename _a> ostream &operator << (ostream &_s,set<_a> &_c){return _OUTC(_s,ALL(_c));}
template<typename _a,typename _b> ostream &operator << (ostream &_s,map<_a,_b> &_c){return _OUTC(_s,ALL(_c));}
template<typename _t> void pary(_t _a,_t _b){_OUTC(cerr,_a,_b);cerr<<endl;}
#define IOS()
#else
#define debug(...)
#define pary(...)
#define endl '\n'
#define IOS() ios_base::sync_with_stdio(0);cin.tie(0);
#endif // brian
//}
const ll MAXn=1e5+5,MAXlg=__lg(MAXn)+2;
const ll MOD=1000000007;
const ll INF=ll(1e15);
ll d[MAXn][6];
bool tp[MAXn];
vector<lf> ans,pt;
ll bst=INF;
vector<lf> tmp;
ll n=0,mx=0,mn=INF;
bool cal(ll t)
{
ll ct[2][2];
FILL(ct,0);
REP(i,n)
{
lf tt=0;
REP(j,5)tt+=tmp[j]*lf(d[i][j]-d[t][j]);
if(tt<=0)ct[tp[i]][0]++;
else ct[tp[i]][1]++;
}
ll a=min(ct[0][0]+ct[1][1],ct[0][1]+ct[1][0]);
if(a<=bst)
{
bst=a;
ans=tmp;
pt.clear();
REP(i,5)pt.pb(d[t][i]);
return 1;
}
return 0;
}
int main()
{
IOS();
srand(time(0));
while(cin>>d[n][0])
{
REP1(i,4)cin>>d[n][i];
cin>>tp[n];
REP(i,5)mx=max(mx,d[n][i]),mn=min(mn,d[n][i]);
n++;
}
debug(n,mx,mn);
const ll MAXc=210;
lf dlt=100;
ans.pb(1);
REP(i,4)ans.pb(lf(rand()%(2*100*MAXc)-100*MAXc)/100.0);
REP(T,MAXn/10)
{
tmp=ans;
ll t=rand()%4+1;
dlt=rand()%100+1;
if(rand()%2)tmp[t]+=dlt;
else tmp[t]-=dlt;
//REP(i,4)tmp.pb(lf(rand()%(2*100*MAXc)-100*MAXc)/100.0);
bool b=0;
REP(i,n)b|=cal(i);
//if(b)dlt=max(dlt-5,5.0);
}
debug(bst,ans,pt,dlt);
}
| 22.553719 | 129 | 0.559179 | [
"vector"
] |
4b135f774dd972829fda8fdfb65c3a350d5005b7 | 305 | cpp | C++ | aoj/ALDS1/ALDS1_6_A/solve.cpp | tobyapi/online-judge-solutions | 4088adb97ea592e8e6582ae7d2ecde2f85e2ed9c | [
"MIT"
] | null | null | null | aoj/ALDS1/ALDS1_6_A/solve.cpp | tobyapi/online-judge-solutions | 4088adb97ea592e8e6582ae7d2ecde2f85e2ed9c | [
"MIT"
] | null | null | null | aoj/ALDS1/ALDS1_6_A/solve.cpp | tobyapi/online-judge-solutions | 4088adb97ea592e8e6582ae7d2ecde2f85e2ed9c | [
"MIT"
] | null | null | null | #include<iostream>
#include<algorithm>
#include<vector>
#define all(c) (c).begin(),(c).end()
using namespace std;
int main(void){
int n;
cin >> n;
vector<int>v(n);
while(n--)cin >> v[n];
sort(all(v));
for(int i=0;i<v.size();i++)
cout << v[i] << (i<v.size()-1?" ":"\n");
return 0;
}
| 15.25 | 45 | 0.544262 | [
"vector"
] |
4b167cf3ef74f57ddec65880e6aff0dc52a0d074 | 99,128 | inl | C++ | src/jpeg.inl | bitbank2/JPEGENC | 08317cc22d8b0efcba439f4c23aec8588fac33d7 | [
"Apache-2.0"
] | 28 | 2021-08-02T12:31:05.000Z | 2022-03-17T01:38:25.000Z | src/jpeg.inl | bitbank2/JPEGENC | 08317cc22d8b0efcba439f4c23aec8588fac33d7 | [
"Apache-2.0"
] | 2 | 2021-08-23T09:17:50.000Z | 2021-09-09T16:46:48.000Z | src/jpeg.inl | bitbank2/JPEGENC | 08317cc22d8b0efcba439f4c23aec8588fac33d7 | [
"Apache-2.0"
] | 2 | 2021-08-03T13:03:14.000Z | 2021-08-10T15:15:59.000Z | // Returns the magnitude and fixes negative values for JPEG encoding
// Upper 16 bits is the new delta value, lower 16 is the magnitude
const uint32_t ulMagnitudeFix[2048] PROGMEM = {
0x03ff000b, 0x0000000a, 0x0001000a, 0x0002000a, 0x0003000a, 0x0004000a, 0x0005000a, 0x0006000a,
0x0007000a, 0x0008000a, 0x0009000a, 0x000a000a, 0x000b000a, 0x000c000a, 0x000d000a, 0x000e000a,
0x000f000a, 0x0010000a, 0x0011000a, 0x0012000a, 0x0013000a, 0x0014000a, 0x0015000a, 0x0016000a,
0x0017000a, 0x0018000a, 0x0019000a, 0x001a000a, 0x001b000a, 0x001c000a, 0x001d000a, 0x001e000a,
0x001f000a, 0x0020000a, 0x0021000a, 0x0022000a, 0x0023000a, 0x0024000a, 0x0025000a, 0x0026000a,
0x0027000a, 0x0028000a, 0x0029000a, 0x002a000a, 0x002b000a, 0x002c000a, 0x002d000a, 0x002e000a,
0x002f000a, 0x0030000a, 0x0031000a, 0x0032000a, 0x0033000a, 0x0034000a, 0x0035000a, 0x0036000a,
0x0037000a, 0x0038000a, 0x0039000a, 0x003a000a, 0x003b000a, 0x003c000a, 0x003d000a, 0x003e000a,
0x003f000a, 0x0040000a, 0x0041000a, 0x0042000a, 0x0043000a, 0x0044000a, 0x0045000a, 0x0046000a,
0x0047000a, 0x0048000a, 0x0049000a, 0x004a000a, 0x004b000a, 0x004c000a, 0x004d000a, 0x004e000a,
0x004f000a, 0x0050000a, 0x0051000a, 0x0052000a, 0x0053000a, 0x0054000a, 0x0055000a, 0x0056000a,
0x0057000a, 0x0058000a, 0x0059000a, 0x005a000a, 0x005b000a, 0x005c000a, 0x005d000a, 0x005e000a,
0x005f000a, 0x0060000a, 0x0061000a, 0x0062000a, 0x0063000a, 0x0064000a, 0x0065000a, 0x0066000a,
0x0067000a, 0x0068000a, 0x0069000a, 0x006a000a, 0x006b000a, 0x006c000a, 0x006d000a, 0x006e000a,
0x006f000a, 0x0070000a, 0x0071000a, 0x0072000a, 0x0073000a, 0x0074000a, 0x0075000a, 0x0076000a,
0x0077000a, 0x0078000a, 0x0079000a, 0x007a000a, 0x007b000a, 0x007c000a, 0x007d000a, 0x007e000a,
0x007f000a, 0x0080000a, 0x0081000a, 0x0082000a, 0x0083000a, 0x0084000a, 0x0085000a, 0x0086000a,
0x0087000a, 0x0088000a, 0x0089000a, 0x008a000a, 0x008b000a, 0x008c000a, 0x008d000a, 0x008e000a,
0x008f000a, 0x0090000a, 0x0091000a, 0x0092000a, 0x0093000a, 0x0094000a, 0x0095000a, 0x0096000a,
0x0097000a, 0x0098000a, 0x0099000a, 0x009a000a, 0x009b000a, 0x009c000a, 0x009d000a, 0x009e000a,
0x009f000a, 0x00a0000a, 0x00a1000a, 0x00a2000a, 0x00a3000a, 0x00a4000a, 0x00a5000a, 0x00a6000a,
0x00a7000a, 0x00a8000a, 0x00a9000a, 0x00aa000a, 0x00ab000a, 0x00ac000a, 0x00ad000a, 0x00ae000a,
0x00af000a, 0x00b0000a, 0x00b1000a, 0x00b2000a, 0x00b3000a, 0x00b4000a, 0x00b5000a, 0x00b6000a,
0x00b7000a, 0x00b8000a, 0x00b9000a, 0x00ba000a, 0x00bb000a, 0x00bc000a, 0x00bd000a, 0x00be000a,
0x00bf000a, 0x00c0000a, 0x00c1000a, 0x00c2000a, 0x00c3000a, 0x00c4000a, 0x00c5000a, 0x00c6000a,
0x00c7000a, 0x00c8000a, 0x00c9000a, 0x00ca000a, 0x00cb000a, 0x00cc000a, 0x00cd000a, 0x00ce000a,
0x00cf000a, 0x00d0000a, 0x00d1000a, 0x00d2000a, 0x00d3000a, 0x00d4000a, 0x00d5000a, 0x00d6000a,
0x00d7000a, 0x00d8000a, 0x00d9000a, 0x00da000a, 0x00db000a, 0x00dc000a, 0x00dd000a, 0x00de000a,
0x00df000a, 0x00e0000a, 0x00e1000a, 0x00e2000a, 0x00e3000a, 0x00e4000a, 0x00e5000a, 0x00e6000a,
0x00e7000a, 0x00e8000a, 0x00e9000a, 0x00ea000a, 0x00eb000a, 0x00ec000a, 0x00ed000a, 0x00ee000a,
0x00ef000a, 0x00f0000a, 0x00f1000a, 0x00f2000a, 0x00f3000a, 0x00f4000a, 0x00f5000a, 0x00f6000a,
0x00f7000a, 0x00f8000a, 0x00f9000a, 0x00fa000a, 0x00fb000a, 0x00fc000a, 0x00fd000a, 0x00fe000a,
0x00ff000a, 0x0100000a, 0x0101000a, 0x0102000a, 0x0103000a, 0x0104000a, 0x0105000a, 0x0106000a,
0x0107000a, 0x0108000a, 0x0109000a, 0x010a000a, 0x010b000a, 0x010c000a, 0x010d000a, 0x010e000a,
0x010f000a, 0x0110000a, 0x0111000a, 0x0112000a, 0x0113000a, 0x0114000a, 0x0115000a, 0x0116000a,
0x0117000a, 0x0118000a, 0x0119000a, 0x011a000a, 0x011b000a, 0x011c000a, 0x011d000a, 0x011e000a,
0x011f000a, 0x0120000a, 0x0121000a, 0x0122000a, 0x0123000a, 0x0124000a, 0x0125000a, 0x0126000a,
0x0127000a, 0x0128000a, 0x0129000a, 0x012a000a, 0x012b000a, 0x012c000a, 0x012d000a, 0x012e000a,
0x012f000a, 0x0130000a, 0x0131000a, 0x0132000a, 0x0133000a, 0x0134000a, 0x0135000a, 0x0136000a,
0x0137000a, 0x0138000a, 0x0139000a, 0x013a000a, 0x013b000a, 0x013c000a, 0x013d000a, 0x013e000a,
0x013f000a, 0x0140000a, 0x0141000a, 0x0142000a, 0x0143000a, 0x0144000a, 0x0145000a, 0x0146000a,
0x0147000a, 0x0148000a, 0x0149000a, 0x014a000a, 0x014b000a, 0x014c000a, 0x014d000a, 0x014e000a,
0x014f000a, 0x0150000a, 0x0151000a, 0x0152000a, 0x0153000a, 0x0154000a, 0x0155000a, 0x0156000a,
0x0157000a, 0x0158000a, 0x0159000a, 0x015a000a, 0x015b000a, 0x015c000a, 0x015d000a, 0x015e000a,
0x015f000a, 0x0160000a, 0x0161000a, 0x0162000a, 0x0163000a, 0x0164000a, 0x0165000a, 0x0166000a,
0x0167000a, 0x0168000a, 0x0169000a, 0x016a000a, 0x016b000a, 0x016c000a, 0x016d000a, 0x016e000a,
0x016f000a, 0x0170000a, 0x0171000a, 0x0172000a, 0x0173000a, 0x0174000a, 0x0175000a, 0x0176000a,
0x0177000a, 0x0178000a, 0x0179000a, 0x017a000a, 0x017b000a, 0x017c000a, 0x017d000a, 0x017e000a,
0x017f000a, 0x0180000a, 0x0181000a, 0x0182000a, 0x0183000a, 0x0184000a, 0x0185000a, 0x0186000a,
0x0187000a, 0x0188000a, 0x0189000a, 0x018a000a, 0x018b000a, 0x018c000a, 0x018d000a, 0x018e000a,
0x018f000a, 0x0190000a, 0x0191000a, 0x0192000a, 0x0193000a, 0x0194000a, 0x0195000a, 0x0196000a,
0x0197000a, 0x0198000a, 0x0199000a, 0x019a000a, 0x019b000a, 0x019c000a, 0x019d000a, 0x019e000a,
0x019f000a, 0x01a0000a, 0x01a1000a, 0x01a2000a, 0x01a3000a, 0x01a4000a, 0x01a5000a, 0x01a6000a,
0x01a7000a, 0x01a8000a, 0x01a9000a, 0x01aa000a, 0x01ab000a, 0x01ac000a, 0x01ad000a, 0x01ae000a,
0x01af000a, 0x01b0000a, 0x01b1000a, 0x01b2000a, 0x01b3000a, 0x01b4000a, 0x01b5000a, 0x01b6000a,
0x01b7000a, 0x01b8000a, 0x01b9000a, 0x01ba000a, 0x01bb000a, 0x01bc000a, 0x01bd000a, 0x01be000a,
0x01bf000a, 0x01c0000a, 0x01c1000a, 0x01c2000a, 0x01c3000a, 0x01c4000a, 0x01c5000a, 0x01c6000a,
0x01c7000a, 0x01c8000a, 0x01c9000a, 0x01ca000a, 0x01cb000a, 0x01cc000a, 0x01cd000a, 0x01ce000a,
0x01cf000a, 0x01d0000a, 0x01d1000a, 0x01d2000a, 0x01d3000a, 0x01d4000a, 0x01d5000a, 0x01d6000a,
0x01d7000a, 0x01d8000a, 0x01d9000a, 0x01da000a, 0x01db000a, 0x01dc000a, 0x01dd000a, 0x01de000a,
0x01df000a, 0x01e0000a, 0x01e1000a, 0x01e2000a, 0x01e3000a, 0x01e4000a, 0x01e5000a, 0x01e6000a,
0x01e7000a, 0x01e8000a, 0x01e9000a, 0x01ea000a, 0x01eb000a, 0x01ec000a, 0x01ed000a, 0x01ee000a,
0x01ef000a, 0x01f0000a, 0x01f1000a, 0x01f2000a, 0x01f3000a, 0x01f4000a, 0x01f5000a, 0x01f6000a,
0x01f7000a, 0x01f8000a, 0x01f9000a, 0x01fa000a, 0x01fb000a, 0x01fc000a, 0x01fd000a, 0x01fe000a,
0x01ff000a, 0x00000009, 0x00010009, 0x00020009, 0x00030009, 0x00040009, 0x00050009, 0x00060009,
0x00070009, 0x00080009, 0x00090009, 0x000a0009, 0x000b0009, 0x000c0009, 0x000d0009, 0x000e0009,
0x000f0009, 0x00100009, 0x00110009, 0x00120009, 0x00130009, 0x00140009, 0x00150009, 0x00160009,
0x00170009, 0x00180009, 0x00190009, 0x001a0009, 0x001b0009, 0x001c0009, 0x001d0009, 0x001e0009,
0x001f0009, 0x00200009, 0x00210009, 0x00220009, 0x00230009, 0x00240009, 0x00250009, 0x00260009,
0x00270009, 0x00280009, 0x00290009, 0x002a0009, 0x002b0009, 0x002c0009, 0x002d0009, 0x002e0009,
0x002f0009, 0x00300009, 0x00310009, 0x00320009, 0x00330009, 0x00340009, 0x00350009, 0x00360009,
0x00370009, 0x00380009, 0x00390009, 0x003a0009, 0x003b0009, 0x003c0009, 0x003d0009, 0x003e0009,
0x003f0009, 0x00400009, 0x00410009, 0x00420009, 0x00430009, 0x00440009, 0x00450009, 0x00460009,
0x00470009, 0x00480009, 0x00490009, 0x004a0009, 0x004b0009, 0x004c0009, 0x004d0009, 0x004e0009,
0x004f0009, 0x00500009, 0x00510009, 0x00520009, 0x00530009, 0x00540009, 0x00550009, 0x00560009,
0x00570009, 0x00580009, 0x00590009, 0x005a0009, 0x005b0009, 0x005c0009, 0x005d0009, 0x005e0009,
0x005f0009, 0x00600009, 0x00610009, 0x00620009, 0x00630009, 0x00640009, 0x00650009, 0x00660009,
0x00670009, 0x00680009, 0x00690009, 0x006a0009, 0x006b0009, 0x006c0009, 0x006d0009, 0x006e0009,
0x006f0009, 0x00700009, 0x00710009, 0x00720009, 0x00730009, 0x00740009, 0x00750009, 0x00760009,
0x00770009, 0x00780009, 0x00790009, 0x007a0009, 0x007b0009, 0x007c0009, 0x007d0009, 0x007e0009,
0x007f0009, 0x00800009, 0x00810009, 0x00820009, 0x00830009, 0x00840009, 0x00850009, 0x00860009,
0x00870009, 0x00880009, 0x00890009, 0x008a0009, 0x008b0009, 0x008c0009, 0x008d0009, 0x008e0009,
0x008f0009, 0x00900009, 0x00910009, 0x00920009, 0x00930009, 0x00940009, 0x00950009, 0x00960009,
0x00970009, 0x00980009, 0x00990009, 0x009a0009, 0x009b0009, 0x009c0009, 0x009d0009, 0x009e0009,
0x009f0009, 0x00a00009, 0x00a10009, 0x00a20009, 0x00a30009, 0x00a40009, 0x00a50009, 0x00a60009,
0x00a70009, 0x00a80009, 0x00a90009, 0x00aa0009, 0x00ab0009, 0x00ac0009, 0x00ad0009, 0x00ae0009,
0x00af0009, 0x00b00009, 0x00b10009, 0x00b20009, 0x00b30009, 0x00b40009, 0x00b50009, 0x00b60009,
0x00b70009, 0x00b80009, 0x00b90009, 0x00ba0009, 0x00bb0009, 0x00bc0009, 0x00bd0009, 0x00be0009,
0x00bf0009, 0x00c00009, 0x00c10009, 0x00c20009, 0x00c30009, 0x00c40009, 0x00c50009, 0x00c60009,
0x00c70009, 0x00c80009, 0x00c90009, 0x00ca0009, 0x00cb0009, 0x00cc0009, 0x00cd0009, 0x00ce0009,
0x00cf0009, 0x00d00009, 0x00d10009, 0x00d20009, 0x00d30009, 0x00d40009, 0x00d50009, 0x00d60009,
0x00d70009, 0x00d80009, 0x00d90009, 0x00da0009, 0x00db0009, 0x00dc0009, 0x00dd0009, 0x00de0009,
0x00df0009, 0x00e00009, 0x00e10009, 0x00e20009, 0x00e30009, 0x00e40009, 0x00e50009, 0x00e60009,
0x00e70009, 0x00e80009, 0x00e90009, 0x00ea0009, 0x00eb0009, 0x00ec0009, 0x00ed0009, 0x00ee0009,
0x00ef0009, 0x00f00009, 0x00f10009, 0x00f20009, 0x00f30009, 0x00f40009, 0x00f50009, 0x00f60009,
0x00f70009, 0x00f80009, 0x00f90009, 0x00fa0009, 0x00fb0009, 0x00fc0009, 0x00fd0009, 0x00fe0009,
0x00ff0009, 0x00000008, 0x00010008, 0x00020008, 0x00030008, 0x00040008, 0x00050008, 0x00060008,
0x00070008, 0x00080008, 0x00090008, 0x000a0008, 0x000b0008, 0x000c0008, 0x000d0008, 0x000e0008,
0x000f0008, 0x00100008, 0x00110008, 0x00120008, 0x00130008, 0x00140008, 0x00150008, 0x00160008,
0x00170008, 0x00180008, 0x00190008, 0x001a0008, 0x001b0008, 0x001c0008, 0x001d0008, 0x001e0008,
0x001f0008, 0x00200008, 0x00210008, 0x00220008, 0x00230008, 0x00240008, 0x00250008, 0x00260008,
0x00270008, 0x00280008, 0x00290008, 0x002a0008, 0x002b0008, 0x002c0008, 0x002d0008, 0x002e0008,
0x002f0008, 0x00300008, 0x00310008, 0x00320008, 0x00330008, 0x00340008, 0x00350008, 0x00360008,
0x00370008, 0x00380008, 0x00390008, 0x003a0008, 0x003b0008, 0x003c0008, 0x003d0008, 0x003e0008,
0x003f0008, 0x00400008, 0x00410008, 0x00420008, 0x00430008, 0x00440008, 0x00450008, 0x00460008,
0x00470008, 0x00480008, 0x00490008, 0x004a0008, 0x004b0008, 0x004c0008, 0x004d0008, 0x004e0008,
0x004f0008, 0x00500008, 0x00510008, 0x00520008, 0x00530008, 0x00540008, 0x00550008, 0x00560008,
0x00570008, 0x00580008, 0x00590008, 0x005a0008, 0x005b0008, 0x005c0008, 0x005d0008, 0x005e0008,
0x005f0008, 0x00600008, 0x00610008, 0x00620008, 0x00630008, 0x00640008, 0x00650008, 0x00660008,
0x00670008, 0x00680008, 0x00690008, 0x006a0008, 0x006b0008, 0x006c0008, 0x006d0008, 0x006e0008,
0x006f0008, 0x00700008, 0x00710008, 0x00720008, 0x00730008, 0x00740008, 0x00750008, 0x00760008,
0x00770008, 0x00780008, 0x00790008, 0x007a0008, 0x007b0008, 0x007c0008, 0x007d0008, 0x007e0008,
0x007f0008, 0x00000007, 0x00010007, 0x00020007, 0x00030007, 0x00040007, 0x00050007, 0x00060007,
0x00070007, 0x00080007, 0x00090007, 0x000a0007, 0x000b0007, 0x000c0007, 0x000d0007, 0x000e0007,
0x000f0007, 0x00100007, 0x00110007, 0x00120007, 0x00130007, 0x00140007, 0x00150007, 0x00160007,
0x00170007, 0x00180007, 0x00190007, 0x001a0007, 0x001b0007, 0x001c0007, 0x001d0007, 0x001e0007,
0x001f0007, 0x00200007, 0x00210007, 0x00220007, 0x00230007, 0x00240007, 0x00250007, 0x00260007,
0x00270007, 0x00280007, 0x00290007, 0x002a0007, 0x002b0007, 0x002c0007, 0x002d0007, 0x002e0007,
0x002f0007, 0x00300007, 0x00310007, 0x00320007, 0x00330007, 0x00340007, 0x00350007, 0x00360007,
0x00370007, 0x00380007, 0x00390007, 0x003a0007, 0x003b0007, 0x003c0007, 0x003d0007, 0x003e0007,
0x003f0007, 0x00000006, 0x00010006, 0x00020006, 0x00030006, 0x00040006, 0x00050006, 0x00060006,
0x00070006, 0x00080006, 0x00090006, 0x000a0006, 0x000b0006, 0x000c0006, 0x000d0006, 0x000e0006,
0x000f0006, 0x00100006, 0x00110006, 0x00120006, 0x00130006, 0x00140006, 0x00150006, 0x00160006,
0x00170006, 0x00180006, 0x00190006, 0x001a0006, 0x001b0006, 0x001c0006, 0x001d0006, 0x001e0006,
0x001f0006, 0x00000005, 0x00010005, 0x00020005, 0x00030005, 0x00040005, 0x00050005, 0x00060005,
0x00070005, 0x00080005, 0x00090005, 0x000a0005, 0x000b0005, 0x000c0005, 0x000d0005, 0x000e0005,
0x000f0005, 0x00000004, 0x00010004, 0x00020004, 0x00030004, 0x00040004, 0x00050004, 0x00060004,
0x00070004, 0x00000003, 0x00010003, 0x00020003, 0x00030003, 0x00000002, 0x00010002, 0x00000001,
0x00000000, 0x00010001, 0x00020002, 0x00030002, 0x00040003, 0x00050003, 0x00060003, 0x00070003,
0x00080004, 0x00090004, 0x000a0004, 0x000b0004, 0x000c0004, 0x000d0004, 0x000e0004, 0x000f0004,
0x00100005, 0x00110005, 0x00120005, 0x00130005, 0x00140005, 0x00150005, 0x00160005, 0x00170005,
0x00180005, 0x00190005, 0x001a0005, 0x001b0005, 0x001c0005, 0x001d0005, 0x001e0005, 0x001f0005,
0x00200006, 0x00210006, 0x00220006, 0x00230006, 0x00240006, 0x00250006, 0x00260006, 0x00270006,
0x00280006, 0x00290006, 0x002a0006, 0x002b0006, 0x002c0006, 0x002d0006, 0x002e0006, 0x002f0006,
0x00300006, 0x00310006, 0x00320006, 0x00330006, 0x00340006, 0x00350006, 0x00360006, 0x00370006,
0x00380006, 0x00390006, 0x003a0006, 0x003b0006, 0x003c0006, 0x003d0006, 0x003e0006, 0x003f0006,
0x00400007, 0x00410007, 0x00420007, 0x00430007, 0x00440007, 0x00450007, 0x00460007, 0x00470007,
0x00480007, 0x00490007, 0x004a0007, 0x004b0007, 0x004c0007, 0x004d0007, 0x004e0007, 0x004f0007,
0x00500007, 0x00510007, 0x00520007, 0x00530007, 0x00540007, 0x00550007, 0x00560007, 0x00570007,
0x00580007, 0x00590007, 0x005a0007, 0x005b0007, 0x005c0007, 0x005d0007, 0x005e0007, 0x005f0007,
0x00600007, 0x00610007, 0x00620007, 0x00630007, 0x00640007, 0x00650007, 0x00660007, 0x00670007,
0x00680007, 0x00690007, 0x006a0007, 0x006b0007, 0x006c0007, 0x006d0007, 0x006e0007, 0x006f0007,
0x00700007, 0x00710007, 0x00720007, 0x00730007, 0x00740007, 0x00750007, 0x00760007, 0x00770007,
0x00780007, 0x00790007, 0x007a0007, 0x007b0007, 0x007c0007, 0x007d0007, 0x007e0007, 0x007f0007,
0x00800008, 0x00810008, 0x00820008, 0x00830008, 0x00840008, 0x00850008, 0x00860008, 0x00870008,
0x00880008, 0x00890008, 0x008a0008, 0x008b0008, 0x008c0008, 0x008d0008, 0x008e0008, 0x008f0008,
0x00900008, 0x00910008, 0x00920008, 0x00930008, 0x00940008, 0x00950008, 0x00960008, 0x00970008,
0x00980008, 0x00990008, 0x009a0008, 0x009b0008, 0x009c0008, 0x009d0008, 0x009e0008, 0x009f0008,
0x00a00008, 0x00a10008, 0x00a20008, 0x00a30008, 0x00a40008, 0x00a50008, 0x00a60008, 0x00a70008,
0x00a80008, 0x00a90008, 0x00aa0008, 0x00ab0008, 0x00ac0008, 0x00ad0008, 0x00ae0008, 0x00af0008,
0x00b00008, 0x00b10008, 0x00b20008, 0x00b30008, 0x00b40008, 0x00b50008, 0x00b60008, 0x00b70008,
0x00b80008, 0x00b90008, 0x00ba0008, 0x00bb0008, 0x00bc0008, 0x00bd0008, 0x00be0008, 0x00bf0008,
0x00c00008, 0x00c10008, 0x00c20008, 0x00c30008, 0x00c40008, 0x00c50008, 0x00c60008, 0x00c70008,
0x00c80008, 0x00c90008, 0x00ca0008, 0x00cb0008, 0x00cc0008, 0x00cd0008, 0x00ce0008, 0x00cf0008,
0x00d00008, 0x00d10008, 0x00d20008, 0x00d30008, 0x00d40008, 0x00d50008, 0x00d60008, 0x00d70008,
0x00d80008, 0x00d90008, 0x00da0008, 0x00db0008, 0x00dc0008, 0x00dd0008, 0x00de0008, 0x00df0008,
0x00e00008, 0x00e10008, 0x00e20008, 0x00e30008, 0x00e40008, 0x00e50008, 0x00e60008, 0x00e70008,
0x00e80008, 0x00e90008, 0x00ea0008, 0x00eb0008, 0x00ec0008, 0x00ed0008, 0x00ee0008, 0x00ef0008,
0x00f00008, 0x00f10008, 0x00f20008, 0x00f30008, 0x00f40008, 0x00f50008, 0x00f60008, 0x00f70008,
0x00f80008, 0x00f90008, 0x00fa0008, 0x00fb0008, 0x00fc0008, 0x00fd0008, 0x00fe0008, 0x00ff0008,
0x01000009, 0x01010009, 0x01020009, 0x01030009, 0x01040009, 0x01050009, 0x01060009, 0x01070009,
0x01080009, 0x01090009, 0x010a0009, 0x010b0009, 0x010c0009, 0x010d0009, 0x010e0009, 0x010f0009,
0x01100009, 0x01110009, 0x01120009, 0x01130009, 0x01140009, 0x01150009, 0x01160009, 0x01170009,
0x01180009, 0x01190009, 0x011a0009, 0x011b0009, 0x011c0009, 0x011d0009, 0x011e0009, 0x011f0009,
0x01200009, 0x01210009, 0x01220009, 0x01230009, 0x01240009, 0x01250009, 0x01260009, 0x01270009,
0x01280009, 0x01290009, 0x012a0009, 0x012b0009, 0x012c0009, 0x012d0009, 0x012e0009, 0x012f0009,
0x01300009, 0x01310009, 0x01320009, 0x01330009, 0x01340009, 0x01350009, 0x01360009, 0x01370009,
0x01380009, 0x01390009, 0x013a0009, 0x013b0009, 0x013c0009, 0x013d0009, 0x013e0009, 0x013f0009,
0x01400009, 0x01410009, 0x01420009, 0x01430009, 0x01440009, 0x01450009, 0x01460009, 0x01470009,
0x01480009, 0x01490009, 0x014a0009, 0x014b0009, 0x014c0009, 0x014d0009, 0x014e0009, 0x014f0009,
0x01500009, 0x01510009, 0x01520009, 0x01530009, 0x01540009, 0x01550009, 0x01560009, 0x01570009,
0x01580009, 0x01590009, 0x015a0009, 0x015b0009, 0x015c0009, 0x015d0009, 0x015e0009, 0x015f0009,
0x01600009, 0x01610009, 0x01620009, 0x01630009, 0x01640009, 0x01650009, 0x01660009, 0x01670009,
0x01680009, 0x01690009, 0x016a0009, 0x016b0009, 0x016c0009, 0x016d0009, 0x016e0009, 0x016f0009,
0x01700009, 0x01710009, 0x01720009, 0x01730009, 0x01740009, 0x01750009, 0x01760009, 0x01770009,
0x01780009, 0x01790009, 0x017a0009, 0x017b0009, 0x017c0009, 0x017d0009, 0x017e0009, 0x017f0009,
0x01800009, 0x01810009, 0x01820009, 0x01830009, 0x01840009, 0x01850009, 0x01860009, 0x01870009,
0x01880009, 0x01890009, 0x018a0009, 0x018b0009, 0x018c0009, 0x018d0009, 0x018e0009, 0x018f0009,
0x01900009, 0x01910009, 0x01920009, 0x01930009, 0x01940009, 0x01950009, 0x01960009, 0x01970009,
0x01980009, 0x01990009, 0x019a0009, 0x019b0009, 0x019c0009, 0x019d0009, 0x019e0009, 0x019f0009,
0x01a00009, 0x01a10009, 0x01a20009, 0x01a30009, 0x01a40009, 0x01a50009, 0x01a60009, 0x01a70009,
0x01a80009, 0x01a90009, 0x01aa0009, 0x01ab0009, 0x01ac0009, 0x01ad0009, 0x01ae0009, 0x01af0009,
0x01b00009, 0x01b10009, 0x01b20009, 0x01b30009, 0x01b40009, 0x01b50009, 0x01b60009, 0x01b70009,
0x01b80009, 0x01b90009, 0x01ba0009, 0x01bb0009, 0x01bc0009, 0x01bd0009, 0x01be0009, 0x01bf0009,
0x01c00009, 0x01c10009, 0x01c20009, 0x01c30009, 0x01c40009, 0x01c50009, 0x01c60009, 0x01c70009,
0x01c80009, 0x01c90009, 0x01ca0009, 0x01cb0009, 0x01cc0009, 0x01cd0009, 0x01ce0009, 0x01cf0009,
0x01d00009, 0x01d10009, 0x01d20009, 0x01d30009, 0x01d40009, 0x01d50009, 0x01d60009, 0x01d70009,
0x01d80009, 0x01d90009, 0x01da0009, 0x01db0009, 0x01dc0009, 0x01dd0009, 0x01de0009, 0x01df0009,
0x01e00009, 0x01e10009, 0x01e20009, 0x01e30009, 0x01e40009, 0x01e50009, 0x01e60009, 0x01e70009,
0x01e80009, 0x01e90009, 0x01ea0009, 0x01eb0009, 0x01ec0009, 0x01ed0009, 0x01ee0009, 0x01ef0009,
0x01f00009, 0x01f10009, 0x01f20009, 0x01f30009, 0x01f40009, 0x01f50009, 0x01f60009, 0x01f70009,
0x01f80009, 0x01f90009, 0x01fa0009, 0x01fb0009, 0x01fc0009, 0x01fd0009, 0x01fe0009, 0x01ff0009,
0x0200000a, 0x0201000a, 0x0202000a, 0x0203000a, 0x0204000a, 0x0205000a, 0x0206000a, 0x0207000a,
0x0208000a, 0x0209000a, 0x020a000a, 0x020b000a, 0x020c000a, 0x020d000a, 0x020e000a, 0x020f000a,
0x0210000a, 0x0211000a, 0x0212000a, 0x0213000a, 0x0214000a, 0x0215000a, 0x0216000a, 0x0217000a,
0x0218000a, 0x0219000a, 0x021a000a, 0x021b000a, 0x021c000a, 0x021d000a, 0x021e000a, 0x021f000a,
0x0220000a, 0x0221000a, 0x0222000a, 0x0223000a, 0x0224000a, 0x0225000a, 0x0226000a, 0x0227000a,
0x0228000a, 0x0229000a, 0x022a000a, 0x022b000a, 0x022c000a, 0x022d000a, 0x022e000a, 0x022f000a,
0x0230000a, 0x0231000a, 0x0232000a, 0x0233000a, 0x0234000a, 0x0235000a, 0x0236000a, 0x0237000a,
0x0238000a, 0x0239000a, 0x023a000a, 0x023b000a, 0x023c000a, 0x023d000a, 0x023e000a, 0x023f000a,
0x0240000a, 0x0241000a, 0x0242000a, 0x0243000a, 0x0244000a, 0x0245000a, 0x0246000a, 0x0247000a,
0x0248000a, 0x0249000a, 0x024a000a, 0x024b000a, 0x024c000a, 0x024d000a, 0x024e000a, 0x024f000a,
0x0250000a, 0x0251000a, 0x0252000a, 0x0253000a, 0x0254000a, 0x0255000a, 0x0256000a, 0x0257000a,
0x0258000a, 0x0259000a, 0x025a000a, 0x025b000a, 0x025c000a, 0x025d000a, 0x025e000a, 0x025f000a,
0x0260000a, 0x0261000a, 0x0262000a, 0x0263000a, 0x0264000a, 0x0265000a, 0x0266000a, 0x0267000a,
0x0268000a, 0x0269000a, 0x026a000a, 0x026b000a, 0x026c000a, 0x026d000a, 0x026e000a, 0x026f000a,
0x0270000a, 0x0271000a, 0x0272000a, 0x0273000a, 0x0274000a, 0x0275000a, 0x0276000a, 0x0277000a,
0x0278000a, 0x0279000a, 0x027a000a, 0x027b000a, 0x027c000a, 0x027d000a, 0x027e000a, 0x027f000a,
0x0280000a, 0x0281000a, 0x0282000a, 0x0283000a, 0x0284000a, 0x0285000a, 0x0286000a, 0x0287000a,
0x0288000a, 0x0289000a, 0x028a000a, 0x028b000a, 0x028c000a, 0x028d000a, 0x028e000a, 0x028f000a,
0x0290000a, 0x0291000a, 0x0292000a, 0x0293000a, 0x0294000a, 0x0295000a, 0x0296000a, 0x0297000a,
0x0298000a, 0x0299000a, 0x029a000a, 0x029b000a, 0x029c000a, 0x029d000a, 0x029e000a, 0x029f000a,
0x02a0000a, 0x02a1000a, 0x02a2000a, 0x02a3000a, 0x02a4000a, 0x02a5000a, 0x02a6000a, 0x02a7000a,
0x02a8000a, 0x02a9000a, 0x02aa000a, 0x02ab000a, 0x02ac000a, 0x02ad000a, 0x02ae000a, 0x02af000a,
0x02b0000a, 0x02b1000a, 0x02b2000a, 0x02b3000a, 0x02b4000a, 0x02b5000a, 0x02b6000a, 0x02b7000a,
0x02b8000a, 0x02b9000a, 0x02ba000a, 0x02bb000a, 0x02bc000a, 0x02bd000a, 0x02be000a, 0x02bf000a,
0x02c0000a, 0x02c1000a, 0x02c2000a, 0x02c3000a, 0x02c4000a, 0x02c5000a, 0x02c6000a, 0x02c7000a,
0x02c8000a, 0x02c9000a, 0x02ca000a, 0x02cb000a, 0x02cc000a, 0x02cd000a, 0x02ce000a, 0x02cf000a,
0x02d0000a, 0x02d1000a, 0x02d2000a, 0x02d3000a, 0x02d4000a, 0x02d5000a, 0x02d6000a, 0x02d7000a,
0x02d8000a, 0x02d9000a, 0x02da000a, 0x02db000a, 0x02dc000a, 0x02dd000a, 0x02de000a, 0x02df000a,
0x02e0000a, 0x02e1000a, 0x02e2000a, 0x02e3000a, 0x02e4000a, 0x02e5000a, 0x02e6000a, 0x02e7000a,
0x02e8000a, 0x02e9000a, 0x02ea000a, 0x02eb000a, 0x02ec000a, 0x02ed000a, 0x02ee000a, 0x02ef000a,
0x02f0000a, 0x02f1000a, 0x02f2000a, 0x02f3000a, 0x02f4000a, 0x02f5000a, 0x02f6000a, 0x02f7000a,
0x02f8000a, 0x02f9000a, 0x02fa000a, 0x02fb000a, 0x02fc000a, 0x02fd000a, 0x02fe000a, 0x02ff000a,
0x0300000a, 0x0301000a, 0x0302000a, 0x0303000a, 0x0304000a, 0x0305000a, 0x0306000a, 0x0307000a,
0x0308000a, 0x0309000a, 0x030a000a, 0x030b000a, 0x030c000a, 0x030d000a, 0x030e000a, 0x030f000a,
0x0310000a, 0x0311000a, 0x0312000a, 0x0313000a, 0x0314000a, 0x0315000a, 0x0316000a, 0x0317000a,
0x0318000a, 0x0319000a, 0x031a000a, 0x031b000a, 0x031c000a, 0x031d000a, 0x031e000a, 0x031f000a,
0x0320000a, 0x0321000a, 0x0322000a, 0x0323000a, 0x0324000a, 0x0325000a, 0x0326000a, 0x0327000a,
0x0328000a, 0x0329000a, 0x032a000a, 0x032b000a, 0x032c000a, 0x032d000a, 0x032e000a, 0x032f000a,
0x0330000a, 0x0331000a, 0x0332000a, 0x0333000a, 0x0334000a, 0x0335000a, 0x0336000a, 0x0337000a,
0x0338000a, 0x0339000a, 0x033a000a, 0x033b000a, 0x033c000a, 0x033d000a, 0x033e000a, 0x033f000a,
0x0340000a, 0x0341000a, 0x0342000a, 0x0343000a, 0x0344000a, 0x0345000a, 0x0346000a, 0x0347000a,
0x0348000a, 0x0349000a, 0x034a000a, 0x034b000a, 0x034c000a, 0x034d000a, 0x034e000a, 0x034f000a,
0x0350000a, 0x0351000a, 0x0352000a, 0x0353000a, 0x0354000a, 0x0355000a, 0x0356000a, 0x0357000a,
0x0358000a, 0x0359000a, 0x035a000a, 0x035b000a, 0x035c000a, 0x035d000a, 0x035e000a, 0x035f000a,
0x0360000a, 0x0361000a, 0x0362000a, 0x0363000a, 0x0364000a, 0x0365000a, 0x0366000a, 0x0367000a,
0x0368000a, 0x0369000a, 0x036a000a, 0x036b000a, 0x036c000a, 0x036d000a, 0x036e000a, 0x036f000a,
0x0370000a, 0x0371000a, 0x0372000a, 0x0373000a, 0x0374000a, 0x0375000a, 0x0376000a, 0x0377000a,
0x0378000a, 0x0379000a, 0x037a000a, 0x037b000a, 0x037c000a, 0x037d000a, 0x037e000a, 0x037f000a,
0x0380000a, 0x0381000a, 0x0382000a, 0x0383000a, 0x0384000a, 0x0385000a, 0x0386000a, 0x0387000a,
0x0388000a, 0x0389000a, 0x038a000a, 0x038b000a, 0x038c000a, 0x038d000a, 0x038e000a, 0x038f000a,
0x0390000a, 0x0391000a, 0x0392000a, 0x0393000a, 0x0394000a, 0x0395000a, 0x0396000a, 0x0397000a,
0x0398000a, 0x0399000a, 0x039a000a, 0x039b000a, 0x039c000a, 0x039d000a, 0x039e000a, 0x039f000a,
0x03a0000a, 0x03a1000a, 0x03a2000a, 0x03a3000a, 0x03a4000a, 0x03a5000a, 0x03a6000a, 0x03a7000a,
0x03a8000a, 0x03a9000a, 0x03aa000a, 0x03ab000a, 0x03ac000a, 0x03ad000a, 0x03ae000a, 0x03af000a,
0x03b0000a, 0x03b1000a, 0x03b2000a, 0x03b3000a, 0x03b4000a, 0x03b5000a, 0x03b6000a, 0x03b7000a,
0x03b8000a, 0x03b9000a, 0x03ba000a, 0x03bb000a, 0x03bc000a, 0x03bd000a, 0x03be000a, 0x03bf000a,
0x03c0000a, 0x03c1000a, 0x03c2000a, 0x03c3000a, 0x03c4000a, 0x03c5000a, 0x03c6000a, 0x03c7000a,
0x03c8000a, 0x03c9000a, 0x03ca000a, 0x03cb000a, 0x03cc000a, 0x03cd000a, 0x03ce000a, 0x03cf000a,
0x03d0000a, 0x03d1000a, 0x03d2000a, 0x03d3000a, 0x03d4000a, 0x03d5000a, 0x03d6000a, 0x03d7000a,
0x03d8000a, 0x03d9000a, 0x03da000a, 0x03db000a, 0x03dc000a, 0x03dd000a, 0x03de000a, 0x03df000a,
0x03e0000a, 0x03e1000a, 0x03e2000a, 0x03e3000a, 0x03e4000a, 0x03e5000a, 0x03e6000a, 0x03e7000a,
0x03e8000a, 0x03e9000a, 0x03ea000a, 0x03eb000a, 0x03ec000a, 0x03ed000a, 0x03ee000a, 0x03ef000a,
0x03f0000a, 0x03f1000a, 0x03f2000a, 0x03f3000a, 0x03f4000a, 0x03f5000a, 0x03f6000a, 0x03f7000a,
0x03f8000a, 0x03f9000a, 0x03fa000a, 0x03fb000a, 0x03fc000a, 0x03fd000a, 0x03fe000a, 0x03ff000a};
const unsigned char cMagnitudes[512] PROGMEM = {0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9};
// zigzag ordering of DCT coefficients
const unsigned char cZigZag[64] PROGMEM = {0,1,5,6,14,15,27,28,
2,4,7,13,16,26,29,42,
3,8,12,17,25,30,41,43,
9,11,18,24,31,40,44,53,
10,19,23,32,39,45,52,54,
20,22,33,38,46,51,55,60,
21,34,37,47,50,56,59,61,
35,36,48,49,57,58,62,63};
const unsigned char cZigZag2[64] PROGMEM = {0,1,8,16,9,2,3,10,
17,24,32,25,18,11,4,5,
12,19,26,33,40,48,41,34,
27,20,13,6,7,14,21,28,
35,42,49,56,57,50,43,36,
29,22,15,23,30,37,44,51,
58,59,52,45,38,31,39,46,
53,60,61,54,47,55,62,63};
//
// Typical DC difference huffman tables for luminance and chrominance
//
const unsigned char huffl_dc[28] PROGMEM = {0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0,
0,1,2,3,4,5,6,7,8,9,0xa,0xb};
const unsigned char huffcr_dc[28] PROGMEM = {0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0,
0,1,2,3,4,5,6,7,8,9,0xa,0xb};
//
// Typical AC difference huffman tables for luminance and chrominance
//
const unsigned char huffl_ac[256] PROGMEM = {0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d,
1,2,3,0,4,0x11,5,0x12,0x21,0x31,0x41,6,0x13,0x51,0x61,7,
0x22,0x71,0x14,0x32,0x81,0x91,0xa1,8,0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,
0x24,0x33,0x62,0x72,0x82,9,0xa,0x16,0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,
0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,
0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,
0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,
0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,
0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,
0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,
0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
0xf9,0xfa};
const unsigned char huffcr_ac[256] PROGMEM = {0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77,
0,1,2,3,0x11,4,5,0x21,0x31,6,0x12,0x41,0x51,7,0x61,0x71,
0x13,0x22,0x32,0x81,0x8,0x14,0x42,0x91,0xa1,0xb1,0xc1,9,0x23,0x33,0x52,0xf0,
0x15,0x62,0x72,0xd1,0xa,0x16,0x24,0x34,0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,
0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,
0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,
0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,
0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,
0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,
0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,
0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
0xf9,0xfa};
// Sample quantization table which can be divided by 2 or 4 or multiplied by 2
// to give different quality levels
const unsigned char quant_lum[64] PROGMEM =
{16,11,12,14,12,10,16,14,13,14,18,17,16,19,24,
40,26,24,22,22,24,49,35,37,29,40,58,51,61,60,
57,51,56,55,64,72,92,78,64,68,87,69,55,56,80,
109,81,87,95,98,103,104,103,62,77,113,121,112,
100,120,92,101,103,99};
const unsigned char quant_color[64] PROGMEM =
{17,18,18,24,21,24,47,26,26,47,99,66,56,66,99,99,
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99};
const unsigned char quant95_lum[64] PROGMEM =
{ 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01,
0x01, 0x01, 0x02, 0x02, 0x02, 0x02, 0x02, 0x04,
0x03, 0x02, 0x02, 0x02, 0x02, 0x05, 0x04, 0x04,
0x03, 0x04, 0x06, 0x05, 0x06, 0x06, 0x06, 0x05,
0x06, 0x06, 0x06, 0x07, 0x09, 0x08, 0x06, 0x07,
0x09, 0x07, 0x06, 0x06, 0x08, 0x0b, 0x08, 0x09,
0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x06, 0x08, 0x0b,
0x0c, 0x0b, 0x0a, 0x0c, 0x09, 0x0a, 0x0a, 0x0a };
const unsigned char quant95_color[64] PROGMEM =
{ 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x05, 0x03,
0x03, 0x05, 0x0a, 0x07, 0x06, 0x07, 0x0a, 0x0a,
0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a,
0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a,
0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a,
0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a,
0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a,
0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a };
// For AA&N IDCT method, multipliers are equal to quantization
// coefficients scaled by scalefactor[row]*scalefactor[col], where
// scalefactor[0] = 1
// scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
// For integer operation, the multiplier table is to be scaled by
// IFAST_SCALE_BITS.
const int iScaleBits[64] PROGMEM = {16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247};
// Pre-calculated Huffman encode tables (4K bytes)
const uint8_t hufftable[] PROGMEM = {
0x00,0x00,0x02,0x00,0x03,0x00,0x04,0x00,0x05,0x00,0x06,0x00,0x0e,0x00,0x1e,0x00,
0x3e,0x00,0x7e,0x00,0xfe,0x00,0xfe,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x02,0x00,0x03,0x00,0x03,0x00,0x03,0x00,0x03,0x00,0x03,0x00,0x04,0x00,0x05,0x00,
0x06,0x00,0x07,0x00,0x08,0x00,0x09,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x0a,0x00,0x00,0x00,0x01,0x00,0x04,0x00,0x0b,0x00,0x1a,0x00,0x78,0x00,0xf8,0x00,
0xf6,0x03,0x82,0xff,0x83,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x0c,0x00,0x1b,0x00,0x79,0x00,0xf6,0x01,0xf6,0x07,0x84,0xff,0x85,0xff,
0x86,0xff,0x87,0xff,0x88,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x1c,0x00,0xf9,0x00,0xf7,0x03,0xf4,0x0f,0x89,0xff,0x8a,0xff,0x8b,0xff,
0x8c,0xff,0x8d,0xff,0x8e,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x3a,0x00,0xf7,0x01,0xf5,0x0f,0x8f,0xff,0x90,0xff,0x91,0xff,0x92,0xff,
0x93,0xff,0x94,0xff,0x95,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x3b,0x00,0xf8,0x03,0x96,0xff,0x97,0xff,0x98,0xff,0x99,0xff,0x9a,0xff,
0x9b,0xff,0x9c,0xff,0x9d,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x7a,0x00,0xf7,0x07,0x9e,0xff,0x9f,0xff,0xa0,0xff,0xa1,0xff,0xa2,0xff,
0xa3,0xff,0xa4,0xff,0xa5,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x7b,0x00,0xf6,0x0f,0xa6,0xff,0xa7,0xff,0xa8,0xff,0xa9,0xff,0xaa,0xff,
0xab,0xff,0xac,0xff,0xad,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0xfa,0x00,0xf7,0x0f,0xae,0xff,0xaf,0xff,0xb0,0xff,0xb1,0xff,0xb2,0xff,
0xb3,0xff,0xb4,0xff,0xb5,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0xf8,0x01,0xc0,0x7f,0xb6,0xff,0xb7,0xff,0xb8,0xff,0xb9,0xff,0xba,0xff,
0xbb,0xff,0xbc,0xff,0xbd,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0xf9,0x01,0xbe,0xff,0xbf,0xff,0xc0,0xff,0xc1,0xff,0xc2,0xff,0xc3,0xff,
0xc4,0xff,0xc5,0xff,0xc6,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0xfa,0x01,0xc7,0xff,0xc8,0xff,0xc9,0xff,0xca,0xff,0xcb,0xff,0xcc,0xff,
0xcd,0xff,0xce,0xff,0xcf,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0xf9,0x03,0xd0,0xff,0xd1,0xff,0xd2,0xff,0xd3,0xff,0xd4,0xff,0xd5,0xff,
0xd6,0xff,0xd7,0xff,0xd8,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0xfa,0x03,0xd9,0xff,0xda,0xff,0xdb,0xff,0xdc,0xff,0xdd,0xff,0xde,0xff,
0xdf,0xff,0xe0,0xff,0xe1,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0xf8,0x07,0xe2,0xff,0xe3,0xff,0xe4,0xff,0xe5,0xff,0xe6,0xff,0xe7,0xff,
0xe8,0xff,0xe9,0xff,0xea,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0xeb,0xff,0xec,0xff,0xed,0xff,0xee,0xff,0xef,0xff,0xf0,0xff,0xf1,0xff,
0xf2,0xff,0xf3,0xff,0xf4,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0xf9,0x07,0xf5,0xff,0xf6,0xff,0xf7,0xff,0xf8,0xff,0xf9,0xff,0xfa,0xff,0xfb,0xff,
0xfc,0xff,0xfd,0xff,0xfe,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x04,0x00,0x02,0x00,0x02,0x00,0x03,0x00,0x04,0x00,0x05,0x00,0x07,0x00,0x08,0x00,
0x0a,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x04,0x00,0x05,0x00,0x07,0x00,0x09,0x00,0x0b,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x05,0x00,0x08,0x00,0x0a,0x00,0x0c,0x00,0x10,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x06,0x00,0x09,0x00,0x0c,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x06,0x00,0x0a,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x07,0x00,0x0b,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x07,0x00,0x0c,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x08,0x00,0x0c,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x09,0x00,0x0f,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x09,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x09,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x0a,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x0a,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x0b,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x0b,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x01,0x00,0x02,0x00,0x06,0x00,0x0e,0x00,0x1e,0x00,0x3e,0x00,0x7e,0x00,
0xfe,0x00,0xfe,0x01,0xfe,0x03,0xfe,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x02,0x00,0x02,0x00,0x02,0x00,0x03,0x00,0x04,0x00,0x05,0x00,0x06,0x00,0x07,0x00,
0x08,0x00,0x09,0x00,0x0a,0x00,0x0b,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x01,0x00,0x04,0x00,0x0a,0x00,0x18,0x00,0x19,0x00,0x38,0x00,0x78,0x00,
0xf4,0x01,0xf6,0x03,0xf4,0x0f,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x0b,0x00,0x39,0x00,0xf6,0x00,0xf5,0x01,0xf6,0x07,0xf5,0x0f,0x88,0xff,
0x89,0xff,0x8a,0xff,0x8b,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x1a,0x00,0xf7,0x00,0xf7,0x03,0xf6,0x0f,0xc2,0x7f,0x8c,0xff,0x8d,0xff,
0x8e,0xff,0x8f,0xff,0x90,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x1b,0x00,0xf8,0x00,0xf8,0x03,0xf7,0x0f,0x91,0xff,0x92,0xff,0x93,0xff,
0x94,0xff,0x95,0xff,0x96,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x3a,0x00,0xf6,0x01,0x97,0xff,0x98,0xff,0x99,0xff,0x9a,0xff,0x9b,0xff,
0x9c,0xff,0x9d,0xff,0x9e,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x3b,0x00,0xf9,0x03,0x9f,0xff,0xa0,0xff,0xa1,0xff,0xa2,0xff,0xa3,0xff,
0xa4,0xff,0xa5,0xff,0xa6,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x79,0x00,0xf7,0x07,0xa7,0xff,0xa8,0xff,0xa9,0xff,0xaa,0xff,0xab,0xff,
0xac,0xff,0xad,0xff,0xae,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x7a,0x00,0xf8,0x07,0xaf,0xff,0xb0,0xff,0xb1,0xff,0xb2,0xff,0xb3,0xff,
0xb4,0xff,0xb5,0xff,0xb6,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0xf9,0x00,0xb7,0xff,0xb8,0xff,0xb9,0xff,0xba,0xff,0xbb,0xff,0xbc,0xff,
0xbd,0xff,0xbe,0xff,0xbf,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0xf7,0x01,0xc0,0xff,0xc1,0xff,0xc2,0xff,0xc3,0xff,0xc4,0xff,0xc5,0xff,
0xc6,0xff,0xc7,0xff,0xc8,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0xf8,0x01,0xc9,0xff,0xca,0xff,0xcb,0xff,0xcc,0xff,0xcd,0xff,0xce,0xff,
0xcf,0xff,0xd0,0xff,0xd1,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0xf9,0x01,0xd2,0xff,0xd3,0xff,0xd4,0xff,0xd5,0xff,0xd6,0xff,0xd7,0xff,
0xd8,0xff,0xd9,0xff,0xda,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0xfa,0x01,0xdb,0xff,0xdc,0xff,0xdd,0xff,0xde,0xff,0xdf,0xff,0xe0,0xff,
0xe1,0xff,0xe2,0xff,0xe3,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0xf9,0x07,0xe4,0xff,0xe5,0xff,0xe6,0xff,0xe7,0xff,0xe8,0xff,0xe9,0xff,
0xea,0xff,0xeb,0xff,0xec,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0xe0,0x3f,0xed,0xff,0xee,0xff,0xef,0xff,0xf0,0xff,0xf1,0xff,0xf2,0xff,
0xf3,0xff,0xf4,0xff,0xf5,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0xfa,0x03,0xc3,0x7f,0xf6,0xff,0xf7,0xff,0xf8,0xff,0xf9,0xff,0xfa,0xff,0xfb,0xff,
0xfc,0xff,0xfd,0xff,0xfe,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x02,0x00,0x02,0x00,0x03,0x00,0x04,0x00,0x05,0x00,0x05,0x00,0x06,0x00,0x07,0x00,
0x09,0x00,0x0a,0x00,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x04,0x00,0x06,0x00,0x08,0x00,0x09,0x00,0x0b,0x00,0x0c,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x05,0x00,0x08,0x00,0x0a,0x00,0x0c,0x00,0x0f,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x05,0x00,0x08,0x00,0x0a,0x00,0x0c,0x00,0x10,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x06,0x00,0x09,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x06,0x00,0x0a,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x07,0x00,0x0b,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x07,0x00,0x0b,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x08,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x09,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x09,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x09,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x09,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x0b,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x0e,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x0a,0x00,0x0f,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,
0x10,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
void JPEGFixQuantE(JPEGIMAGE *pJPEG)
{
int iTable, iTableOffset;
signed short sTemp[DCTSIZE];
int i, iCount;
signed short *p;
unsigned short *pus;
if (pJPEG->ucNumComponents == 1)
iCount = 1;
else
iCount = 2;
for (iTable = 0; iTable < iCount; iTable++)
{
iTableOffset = iTable * DCTSIZE;
p = (signed short *) &pJPEG->sQuantTable[iTableOffset];
for (i = 0; i < DCTSIZE; i++)
{
sTemp[i] = p[cZigZag[i]];
}
memcpy(&pJPEG->sQuantTable[iTableOffset], sTemp, DCTSIZE*sizeof(short)); // copy back to original spot
// Prescale for DCT multiplication
p = (signed short *) &pJPEG->sQuantTable[iTableOffset];
for (i = 0; i < DCTSIZE; i++)
{
p[i] = (short) ((p[i] * iScaleBits[i]) >> 11);
}
// Create "inverted" values for quicker multiplication instead of division
pus = (unsigned short *) &pJPEG->sQuantTable[iTableOffset];
for (i = 0; i < DCTSIZE; i++)
{
int j;
if (pus[i] != 0)
j = 65536 / pus[i];
else
j = 0;
pus[i+(DCTSIZE*2)] = (unsigned short)j;
}
} // for iTable
} /* JPEGFixQuantE() */
void JPEGMakeHuffE(JPEGIMAGE *pJPEG)
{
#ifdef USE_RAM_FOR_TABLES
int code, iLen, iTable;
unsigned short *pTable;
int iBitNum; // current code bit length
int n_bits; // number of bits to do
int cc; // code
unsigned char *p, *pBits;
int iTableCount;
if (pJPEG->ucNumComponents == 1)
iTableCount = 1;
else
iTableCount = 2;
// first do DC components (up to 12-bit codes)
for (iTable = 0; iTable < iTableCount; iTable++)
{
pJPEG->huffdc[iTable] = (int *)&pJPEG->ucHuffACDCBuf[iTable*0x800]; // each table gets 2K
pTable = (unsigned short *)pJPEG->huffdc[iTable];
if (iTable == 0)
pBits = (unsigned char *)huffl_dc;
else
pBits = (unsigned char *)huffcr_dc;
p = (unsigned char *)pBits;
p += 16; // point to bit data
iBitNum = 1;
cc = 0; // start with a code of 0
for (n_bits = 0; n_bits < 16; n_bits++)
{
iLen = *pBits++; // get number of codes for this bit length
while (iLen)
{
code = *p++; // get actual huffman code
pTable[code] = (unsigned short)cc;
pTable[code+256] = (unsigned short)iBitNum; // store the length here
cc++;
iLen--;
}
iBitNum++;
cc <<= 1;
}
}
// now do AC components (up to 16-bit codes)
for (iTable = 0; iTable < iTableCount; iTable++)
{
pTable = (unsigned short *)pJPEG->huffdc[iTable];
if (iTable == 0)
pBits = (unsigned char *)huffl_ac;
else
pBits = (unsigned char *)huffcr_ac;
p = (unsigned char *)pBits;
p += 16; // point to bit data
iBitNum = 1;
cc = 0; // start with a code of 0
for (n_bits = 0; n_bits < 16; n_bits++)
{
iLen = *pBits++; // get number of codes for this bit length
while (iLen)
{
code = *p++; // get actual huffman code
pTable[512+code] = (unsigned short)cc;
pTable[768+code] = (unsigned short)iBitNum;
cc++;
iLen--;
}
iBitNum++;
cc <<= 1;
}
}
// write it to a file
// {
// FILE *ohandle = fopen("/Users/laurencebank/Downloads/hufftable.bin", "w+b");
// if (ohandle) {
// fwrite(pJPEG->ucHuffACDCBuf, 1, 4096, ohandle);
// fclose(ohandle);
// }
// }
#else // read it from FLASH
pJPEG->huffdc[0] = (int *)&hufftable[0];
pJPEG->huffdc[1] = (int *)&hufftable[2048];
#endif // USE_RAM_FOR_TABLES
} /* JPEGMakeHuffE() */
//
// Finish the file
//
int JPEGEncodeEnd(JPEGIMAGE *pJPEG)
{
if (pJPEG->iError == JPEG_SUCCESS)
{
if (pJPEG->pOutput == NULL) { // file I/O
int iLen;
*pJPEG->pc.pOut++ = 0xff; // end of image (EOI)
*pJPEG->pc.pOut++ = 0xd9;
iLen = (int)(pJPEG->pc.pOut - pJPEG->ucFileBuf);
pJPEG->pfnWrite(&pJPEG->JPEGFile, pJPEG->ucFileBuf, iLen);
pJPEG->iDataSize += iLen;
} else { // user-supplied buffer
uint8_t *pBuf = pJPEG->pOutput; // DEBUG - check for non-buffer option
int iOutSize = pJPEG->iDataSize;
pBuf[iOutSize++] = 0xff;
pBuf[iOutSize++] = 0xd9; // end of image (EOI)
pJPEG->iDataSize = iOutSize;
}
return pJPEG->iDataSize; // return the size of the compressed data
}
return 0; // something went wrong
} /* JPEGEncodeEnd() */
//
// Initialize the encoder
//
int JPEGEncodeBegin(JPEGIMAGE *pJPEG, JPEGENCODE *pEncode, int iWidth, int iHeight, uint8_t ucPixelType, uint8_t ucSubSample, uint8_t ucQFactor)
{
uint8_t *pBuf;
int i;
int iOffset = 0;
if (pEncode == NULL || pJPEG == NULL) {
return JPEG_INVALID_PARAMETER;
}
pJPEG->iDCPred0 = pJPEG->iDCPred1 = pJPEG->iDCPred2 = 0; // DC predictor values reset to 0
pJPEG->iWidth = iWidth;
pJPEG->iHeight = iHeight;
pJPEG->ucPixelType = ucPixelType;
pJPEG->ucSubSample = ucSubSample;
pEncode->x = pEncode->y = 0; // starting point
if (ucSubSample == JPEG_SUBSAMPLE_444) {
pEncode->cx = pEncode->cy = 8;
} else {
pEncode->cx = pEncode->cy = 16; // MCU size
}
// Number of MCUs in each dimension
pJPEG->iMCUWidth = (pJPEG->iWidth + pEncode->cx - 1) / pEncode->cx;
pJPEG->iMCUHeight = (pJPEG->iHeight + pEncode->cy - 1) / pEncode->cy;
// Set up the output buffer
pJPEG->pc.iLen = pJPEG->pc.ulAcc = 0;
if (pJPEG->pOutput) {
pBuf = pJPEG->pOutput;
} else {
pBuf = pJPEG->ucFileBuf;
}
// Write the JPEG header
if (pJPEG->ucPixelType == JPEG_PIXEL_GRAYSCALE)
pJPEG->ucNumComponents = 1;
else
pJPEG->ucNumComponents = 3;
WRITEMOTO32(pBuf, iOffset, 0xffd8ffe0); // write app0 marker
iOffset += 4;
WRITEMOTO32(pBuf, iOffset, 0x00104a46); // JFIF
iOffset += 4;
WRITEMOTO32(pBuf, iOffset, 0x49460001);
iOffset += 4;
WRITEMOTO16(pBuf, iOffset, 0x0101); // resolution units = dots per inch
iOffset += 2;
WRITEMOTO16(pBuf, iOffset, 0); // DEBUG - store spacial resolution as 0 for now
iOffset += 2;
WRITEMOTO16(pBuf, iOffset, 0);
iOffset += 2;
WRITEMOTO16(pBuf, iOffset, 0); // add 2 zeros
iOffset += 2;
// define quantization tables
WRITEMOTO16(pBuf, iOffset, 0xffdb); // quantization table marker
iOffset += 2;
WRITEMOTO16(pBuf, iOffset, 0x0043); // table size
iOffset += 2;
pBuf[iOffset++] = 0; // table type and number 0,8 bit
for (i=0; i<64; i++)
{
switch (ucQFactor) // adjust table depending on quality factor
{
default:
case JPEG_Q_BEST: // best quality, divide by 4
pBuf[iOffset++] = quant_lum[i] >> 2;
break;
case JPEG_Q_HIGH: // high quality, divide by 2
pBuf[iOffset++] = quant_lum[i] >> 1;
break;
case JPEG_Q_MED: // medium quality factor, use values unchanged
pBuf[iOffset++] = quant_lum[i];
break;
case JPEG_Q_LOW: // low quality, use values * 2
pBuf[iOffset++] = quant_lum[i] << 1;
break;
// case 4: // ridiculously high quality
// pBuf[iOffset++] = quant95_lum[i];
// break;
}
}
if (pJPEG->ucPixelType != JPEG_PIXEL_GRAYSCALE) // add color quant tables
{
WRITEMOTO16(pBuf, iOffset, 0xffdb); // quantization table
iOffset += 2;
WRITEMOTO16(pBuf, iOffset, 0x0043); // table size
iOffset += 2;
pBuf[iOffset++] = 1; // table 1, 8 bit
for (i=0; i<64; i++)
{
switch (ucQFactor) // adjust table depending on quality factor
{
case JPEG_Q_BEST: // best quality, divide by 4
pBuf[iOffset++] = quant_color[i] >> 2;
break;
case JPEG_Q_HIGH: // high quality, divide by 2
pBuf[iOffset++] = quant_color[i] >> 1;
break;
case JPEG_Q_MED: // medium quality factor, use values unchanged
pBuf[iOffset++] = quant_color[i];
break;
case JPEG_Q_LOW: // low quality, use values * 2
pBuf[iOffset++] = quant_color[i] << 1;
break;
// case 4: // ridiculously high quality
// pBuf[iOffset++] = quant95_color[i];
// break;
}
}
}
// store the restart interval
// use an interval of one MCU row
if (pJPEG->ucPixelType != JPEG_PIXEL_GRAYSCALE && pJPEG->ucSubSample == JPEG_SUBSAMPLE_420)
i = (pJPEG->iWidth + 15) / 16; // number of MCUs in a row
else
i = (pJPEG->iWidth + 7) / 8;
WRITEMOTO16(pBuf, iOffset, 0xffdd); // DRI marker
iOffset += 2;
WRITEMOTO16(pBuf, iOffset, 4); // fixed length of 4
iOffset += 2;
WRITEMOTO16(pBuf, iOffset, i); // restart interval count
iOffset += 2;
// store the frame header
WRITEMOTO16(pBuf, iOffset, 0xffc0); // SOF0 marker
iOffset += 2;
if (pJPEG->ucPixelType == JPEG_PIXEL_GRAYSCALE)
{
pBuf[iOffset++] = 0;
pBuf[iOffset++] = 11; // length = 11
pBuf[iOffset++] = 8; // sample precision
WRITEMOTO16(pBuf, iOffset, pJPEG->iHeight); // image height
iOffset += 2;
WRITEMOTO16(pBuf, iOffset, pJPEG->iWidth); // image width
iOffset += 2;
pBuf[iOffset++] = 1; // number of components = 1 (grayscale)
pBuf[iOffset++] = 0; // component number
WRITEMOTO16(pBuf, iOffset, 0x1100); // subsampling and quant table selector
iOffset += 2;
}
else // set up color stuff
{
pBuf[iOffset++] = 0;
pBuf[iOffset++] = 17; // length = 17
pBuf[iOffset++] = 8; // sample precision
WRITEMOTO16(pBuf, iOffset, pJPEG->iHeight); // image height
iOffset += 2;
WRITEMOTO16(pBuf, iOffset, pJPEG->iWidth); // image width
iOffset += 2;
pBuf[iOffset++] = 3; // number of components = 3 (Ycc)
pBuf[iOffset++] = 0; // component number 0 (Y)
if (pJPEG->ucSubSample == JPEG_SUBSAMPLE_420)
{
WRITEMOTO16(pBuf, iOffset, 0x2200); // 2:1 subsampling and quant table selector
}
else
{
WRITEMOTO16(pBuf, iOffset, 0x1100); // no subsampling and quant table selector
}
iOffset += 2;
pBuf[iOffset++] = 1; // component number 1 (Cb)
WRITEMOTO16(pBuf, iOffset, 0x1101); // subsampling and quant table selector
iOffset += 2;
pBuf[iOffset++] = 2; // component number 2 (Cr)
WRITEMOTO16(pBuf, iOffset, 0x1101); // subsampling and quant table selector
iOffset += 2;
}
// define Huffman tables
WRITEMOTO16(pBuf, iOffset, 0xffc4); // Huffman DC table
iOffset += 2;
WRITEMOTO16(pBuf, iOffset, 0x1f); // Table length = 31
iOffset += 2;
pBuf[iOffset++] = 0; // table class = 0 (DC), id = 0
memcpy(&pBuf[iOffset], huffl_dc, 28); // copy DC table
iOffset += 28;
// now the AC table
WRITEMOTO16(pBuf, iOffset, 0xffc4); // Huffman AC table
iOffset += 2;
WRITEMOTO16(pBuf, iOffset, 0xb5); // Table length = 181
iOffset += 2;
pBuf[iOffset++] = 0x10; // table class = 1 (AC), id = 0
memcpy(&pBuf[iOffset], huffl_ac, 178); // copy AC table
iOffset += 178;
if (pJPEG->ucPixelType != JPEG_PIXEL_GRAYSCALE) // define a second set of tables for color
{
WRITEMOTO16(pBuf, iOffset, 0xffc4); // Huffman DC table
iOffset += 2;
WRITEMOTO16(pBuf, iOffset, 0x1f); // Table length = 31
iOffset += 2;
pBuf[iOffset++] = 1; // table class = 0 (DC), id = 1
memcpy(&pBuf[iOffset], huffcr_dc, 28); // copy DC table
iOffset += 28;
// now the AC table
WRITEMOTO16(pBuf, iOffset, 0xffc4); // Huffman AC table
iOffset += 2;
WRITEMOTO16(pBuf, iOffset, 0xb5); // Table length = 181
iOffset += 2;
pBuf[iOffset++] = 0x11; // table class = 1 (AC), id = 1
memcpy(&pBuf[iOffset], huffcr_ac, 178); // copy AC table
iOffset += 178;
}
// Define the start of scan header (SOS)
WRITEMOTO16(pBuf, iOffset, 0xffda); // SOS
iOffset += 2;
if (pJPEG->ucPixelType == JPEG_PIXEL_GRAYSCALE)
{
WRITEMOTO16(pBuf, iOffset, 0x8); // Table length = 8
iOffset += 2;
pBuf[iOffset++] = 1; // number of components in scan = 1 (grayscale)
pBuf[iOffset++] = 0; // component id = 0
pBuf[iOffset++] = 0; // dc/ac huffman table = 0/0
}
else // color
{
WRITEMOTO16(pBuf, iOffset, 0xc); // Table length = 12
iOffset += 2;
pBuf[iOffset++] = 3; // number of components in scan = 3 (color)
pBuf[iOffset++] = 0; // component id = 0
pBuf[iOffset++] = 0; // dc/ac huffman table = 0/0
pBuf[iOffset++] = 1; // component id = 1
pBuf[iOffset++] = 0x11; // dc/ac huffman table = 1/1
pBuf[iOffset++] = 2; // component id = 2
pBuf[iOffset++] = 0x11; // dc/ac huffman table = 1/1
}
pBuf[iOffset++] = 0; // start of spectral selection
pBuf[iOffset++] = 63; // end of spectral selection
pBuf[iOffset++] = 0; // successive approximation bit
// Set the output pointer for writing the variable length codes
pJPEG->pc.pOut = &pBuf[iOffset];
// prepare the luma & chroma quantization tables
for (i = 0; i<64; i++)
{
switch (ucQFactor)
{
case JPEG_Q_BEST:
pJPEG->sQuantTable[i] = quant_lum[i] >> 2;
pJPEG->sQuantTable[i + 64] = quant_color[i] >> 2;
break;
case JPEG_Q_HIGH:
pJPEG->sQuantTable[i] = (quant_lum[i] >> 1);
pJPEG->sQuantTable[i + 64] = (quant_color[i] >> 1);
break;
case JPEG_Q_MED:
pJPEG->sQuantTable[i] = quant_lum[i];
pJPEG->sQuantTable[i + 64] = quant_color[i];
break;
case JPEG_Q_LOW:
pJPEG->sQuantTable[i] = (quant_lum[i] << 1);
pJPEG->sQuantTable[i + 64] = (quant_color[i] << 1);
break;
// case 4: // ridiculous quality
// pJPEG->sQuantTable[i] = quant95_lum[i];
// pJPEG->sQuantTable[i + 64] = quant95_color[i];
// break;
}
}
JPEGFixQuantE(pJPEG); // reorder and scale quant table(s)
JPEGMakeHuffE(pJPEG); // create the Huffman tables to encode
pJPEG->iError = JPEG_SUCCESS;
return JPEG_SUCCESS;
} /* JPEGEncodeBegin() */
int JPEGQuantize(JPEGIMAGE *pJPEG, signed short *pMCUSrc, int iTable)
{
signed int d, sQ1, sQ2, sum;
int i;
signed short *pQuant;
pQuant = (signed short *)&pJPEG->sQuantTable[iTable * DCTSIZE];
for (i=0; i<33; i++) // do first half and then check for second half being all 0's
{
sQ1 = pQuant[i];
sQ2 = sQ1 >> 1;
d = *pMCUSrc;
// Avoid doing divides; the second half of the quantization table has 65536/Q values
// so that we can use multiplies in this step
if (d < 0)
{
*pMCUSrc++ = 0 - (((sQ2 - d) * pQuant[i + 128]) >> 16);
}
else
{
*pMCUSrc++ = (((sQ2 + d) * pQuant[i + 128]) >> 16);
}
} // for
sum = 0;
for (i=33; i<64; i++) // second half; check for 'sparseness'
{
sQ1 = pQuant[i];
sQ2 = sQ1 >> 1;
d = *pMCUSrc;
// Avoid doing divides; the second half of the quantization table has 65536/Q values
// so that we can use multiplies in this step
if (d < 0)
{
d = 0 - (((sQ2 - d) * pQuant[i + 128]) >> 16);
sum -= d;
}
else
{
d = (((sQ2 + d) * pQuant[i + 128]) >> 16);
sum += d;
}
*pMCUSrc++ = d;
} // for
return (sum == 0); // if the last half of the quantized results was 0, call it 'sparse'
} /* JPEGQuantize() */
int JPEGEncodeMCU(int iDCTable, JPEGIMAGE *pJPEG, signed short *pMCUData, int iDCPred, int bSparse)
{
//int iOff, iBitnum; // faster access
unsigned char cMagnitude;
unsigned char ucCode, *pZig, *pZigEnd, *pZigStart;
int iZeroCount;
BIGINT iDelta;
BIGUINT iLen, iNewLen;
unsigned short *pHuff;
BIGUINT ulCode;
unsigned char *pOut;
BIGUINT ulAcc;
uint32_t ulMagVal;
uint32_t *pMagFix = (uint32_t *)&ulMagnitudeFix[1024]; // allows indexing positive and negative values - speeds up total encode time by 15%
// Put in local vars to allow compiler to do a better job of optimization using registers
ulAcc = pJPEG->pc.ulAcc;
pOut = pJPEG->pc.pOut;
iLen = pJPEG->pc.iLen;
// compress the DC component
iDelta = pMCUData[0] - iDCPred;
iDCPred = pMCUData[0]; // this is the new DC value
pHuff = (unsigned short *) pJPEG->huffdc[iDCTable];
ulMagVal = pMagFix[iDelta]; // get magnitude and new delta in one table read
iDelta = (ulMagVal >> 16);
cMagnitude = ulMagVal & 0xf;
// Old way of dealing with negative and positive magnitudes; faster to use a lookup table once
// if (iDelta < 0)
// {
// iDelta = 0 - iDelta;
// cMagnitude = cMagnitudes[iDelta];
// iDelta = iBitMasks[cMagnitude] - iDelta;
// }
// else
// {
// cMagnitude = cMagnitudes[iDelta];
// }
ulCode = (BIGUINT) pHuff[cMagnitude];
iNewLen = pHuff[cMagnitude + 256];
ulCode = (ulCode << cMagnitude) | iDelta; // code in msb, followed by delta
iNewLen += cMagnitude; // add lengths together
STORECODE(pOut, iLen, ulCode, ulAcc, iNewLen)
// Encode the AC components
pZig = (unsigned char *)&cZigZag2[1];
if (bSparse)
pZigEnd = (unsigned char *)&cZigZag2[33]; // second half is all zeros
else
pZigEnd = (unsigned char *)&cZigZag2[64];
pHuff += 512; // point to AC table
while (pZig < pZigEnd)
{
// count the number of leading zeros
pZigStart = pZig;
while (pZig < pZigEnd && (iDelta = pMCUData[pZig[0]]) == 0) {
pZig++;
}
if (pZig == pZigEnd) // special case, no more coefficients
{ // encode EOB (end of block)
ulCode = (BIGUINT) pHuff[0];
iNewLen = pHuff[256];
STORECODE(pOut, iLen, ulCode, ulAcc, iNewLen)
goto encodemcuz;
}
else // Encode a zero count and AC coefficient
{
iZeroCount = (int)(pZig - pZigStart);
while (iZeroCount >= 16) // maximum that can be encoded at once
{ // 16 zeros is called ZRL (f0)
ulCode = (uint32_t)pHuff[0xf0];
iNewLen = pHuff[256 + 0xf0];
STORECODE(pOut, iLen, ulCode, ulAcc, iNewLen)
iZeroCount -= 16;
}
// Encode a normal RRRR/SSSS pair
ulMagVal = pMagFix[iDelta]; // get magnitude and new delta in one table read
iDelta = (ulMagVal >> 16);
cMagnitude = ulMagVal & 0xf;
ucCode = (unsigned char)((iZeroCount << 4) | cMagnitude); // combine zero count and 'extra' size
// store the huffman code
ulCode = (uint32_t)pHuff[ucCode];
iNewLen = pHuff[256 + ucCode];
ulCode = (ulCode << cMagnitude) | iDelta; // code followed by magnitude
pZig++; // skip to next coefficient
iNewLen += cMagnitude;
STORECODE(pOut, iLen, ulCode, ulAcc, iNewLen)
}
}
encodemcuz:
pJPEG->pc.ulAcc = ulAcc; // place local copies back in the object pointer version
pJPEG->pc.pOut = pOut;
pJPEG->pc.iLen = iLen;
return iDCPred;
} /* JPEGEncodeMCU() */
void JPEGGetMCU(unsigned char *pSrc, int iPitch, signed char *pMCU)
{
int cy;
for (cy = 0; cy < 8; cy++) {
*(uint32_t *)pMCU = *(uint32_t *)pSrc ^ 0x80808080;
*(uint32_t *)&pMCU[4] = *(uint32_t *)&pSrc[4] ^ 0x80808080;
pMCU += 8;
pSrc += iPitch; // - 8; // skip to next line
}
} /* JPEGGetMCU() */
void JPEGSubSample24(unsigned char *pSrc, signed char *pLUM, signed char *pCb, signed char *pCr, int lsize, int cx, int cy)
{
int x;
unsigned char cRed, cGreen, cBlue;
int iY1, iY2, iY3, iY4, iCr1, iCr2, iCr3, iCr4, iCb1, iCb2, iCb3, iCb4;
int y;
cx = (cx + 1)>>1; // do pixels in 2x2 blocks
cy = (cy + 1)>>1;
for (y=0; y<cy; y++)
{
for (x = 0; x<cx; x++) // do 8x8 pixels in 2x2 blocks
{
cBlue = pSrc[0];
cGreen = pSrc[1];
cRed = pSrc[2];
iY1 = (((cRed * 1225) + (cGreen * 2404) + (cBlue * 467)) >> 12) - 0x80;
iCb1 = (cBlue << 11) + (cRed * -691) + (cGreen * -1357);
iCr1 = (cRed << 11) + (cGreen * -1715) + (cBlue * -333);
cBlue = pSrc[3];
cGreen = pSrc[4];
cRed = pSrc[5];
iY2 = (((cRed * 1225) + (cGreen * 2404) + (cBlue * 467)) >> 12) - 0x80;
iCb2 = (cBlue << 11) + (cRed * -691) + (cGreen * -1357);
iCr2 = (cRed << 11) + (cGreen * -1715) + (cBlue * -333);
cBlue = pSrc[lsize];
cGreen = pSrc[lsize+1];
cRed = pSrc[lsize+2];
iY3 = (((cRed * 1225) + (cGreen * 2404) + (cBlue * 467)) >> 12) - 0x80;
iCb3 = (cBlue << 11) + (cRed * -691) + (cGreen * -1357);
iCr3 = (cRed << 11) + (cGreen * -1715) + (cBlue * -333);
cBlue = pSrc[lsize+3];
cGreen = pSrc[lsize+4];
cRed = pSrc[lsize+5];
iY4 = (((cRed * 1225) + (cGreen * 2404) + (cBlue * 467)) >> 12) - 0x80;
iCb4 = (cBlue << 11) + (cRed * -691) + (cGreen * -1357);
iCr4 = (cRed << 11) + (cGreen * -1715) + (cBlue * -333);
// Average the chroma values together
iCr1 = (iCr1 + iCr2 + iCr3 + iCr4) >> 14;
iCb1 = (iCb1 + iCb2 + iCb3 + iCb4) >> 14;
// store in the MCUs
pLUM[0] = (signed char)iY1;
pLUM[1] = (signed char)iY2;
pLUM[8] = (signed char)iY3;
pLUM[9] = (signed char)iY4;
pLUM += 2;
pCr[0] = (signed char)iCr1;
pCb[0] = (signed char)iCb1;
pCr++;
pCb++;
pSrc += 6; // skip 2 pixels to right
} // for x
pCr += 8 - cx; // skip to next row;
pCb += 8 - cx;
pLUM += 8 + (4-cx)*2; // skip down a row since 2 at a time
pSrc += lsize*2 - cx*6; // skip 2 lines
} // for y
} /* JPEGSubSample24() */
void JPEGSubSample16(unsigned char *pSrc, signed char *pLUM, signed char *pCb, signed char *pCr, int lsize, int cx, int cy)
{
int x, y;
unsigned short us;
unsigned short *pUS = (unsigned short *)pSrc;
unsigned char cRed, cGreen, cBlue;
int iY1, iY2, iY3, iY4, iCr1, iCr2, iCr3, iCr4, iCb1, iCb2, iCb3, iCb4;
cx = (cx + 1)>>1; // do pixels in 2x2 blocks
cy = (cy + 1)>>1;
for (y=0; y<cy; y++)
{
for (x=0; x<cx; x++) // do 8x8 pixels in 2x2 blocks
{
us = pUS[0];
cBlue = (unsigned char)(((us & 0x1f)<<3) | (us & 7));
cGreen = (unsigned char)(((us & 0x7e0)>>3) | ((us & 0x60)>>5));
cRed = (unsigned char)(((us & 0xf800)>>8) | ((us & 0x3800)>>11));
iY1 = (((cRed * 1225) + (cGreen * 2404) + (cBlue * 467)) >> 12) - 0x80;
iCb1 = (cBlue << 11) + (cRed * -691) + (cGreen * -1357);
iCr1 = (cRed << 11) + (cGreen * -1715) + (cBlue * -333);
us = pUS[1];
cBlue = (unsigned char)(((us & 0x1f)<<3) | (us & 7));
cGreen = (unsigned char)(((us & 0x7e0)>>3) | ((us & 0x60)>>5));
cRed = (unsigned char)(((us & 0xf800)>>8) | ((us & 0x3800)>>11));
iY2 = (((cRed * 1225) + (cGreen * 2404) + (cBlue * 467)) >> 12) - 0x80;
iCb2 = (cBlue << 11) + (cRed * -691) + (cGreen * -1357);
iCr2 = (cRed << 11) + (cGreen * -1715) + (cBlue * -333);
us = pUS[lsize>>1];
cBlue = (unsigned char)(((us & 0x1f)<<3) | (us & 7));
cGreen = (unsigned char)(((us & 0x7e0)>>3) | ((us & 0x60)>>5));
cRed = (unsigned char)(((us & 0xf800)>>8) | ((us & 0x3800)>>11));
iY3 = (((cRed * 1225) + (cGreen * 2404) + (cBlue * 467)) >> 12) - 0x80;
iCb3 = (cBlue << 11) + (cRed * -691) + (cGreen * -1357);
iCr3 = (cRed << 11) + (cGreen * -1715) + (cBlue * -333);
us = pUS[(lsize>>1)+1];
cBlue = (unsigned char)(((us & 0x1f)<<3) | (us & 7));
cGreen = (unsigned char)(((us & 0x7e0)>>3) | ((us & 0x60)>>5));
cRed = (unsigned char)(((us & 0xf800)>>8) | ((us & 0x3800)>>11));
iY4 = (((cRed * 1225) + (cGreen * 2404) + (cBlue * 467)) >> 12) - 0x80;
iCb4 = (cBlue << 11) + (cRed * -691) + (cGreen * -1357);
iCr4 = (cRed << 11) + (cGreen * -1715) + (cBlue * -333);
// Average the chroma values together
iCr1 = (iCr1 + iCr2 + iCr3 + iCr4) >> 14;
iCb1 = (iCb1 + iCb2 + iCb3 + iCb4) >> 14;
// store in the MCUs
pLUM[0] = (signed char)iY1;
pLUM[1] = (signed char)iY2;
pLUM[8] = (signed char)iY3;
pLUM[9] = (signed char)iY4;
pLUM += 2;
pCr[0] = (signed char)iCr1;
pCb[0] = (signed char)iCb1;
pCr++;
pCb++;
pUS += 2; // skip 2 pixels to right
} // for x
pCr += 8 - cx; // skip to next row;
pCb += 8 - cx;
pLUM += 8 + (4-cx)*2; // skip down a row since 2 at a time
pUS += lsize - cx*2; // skip 2 lines
} // for y
} /* JPEGSubSample16() */
void JPEGSubSample32(unsigned char *pSrc, signed char *pLUM, signed char *pCb, signed char *pCr, int lsize, int cx, int cy)
{
int x;
unsigned char cRed, cGreen, cBlue;
int iY1, iY2, iY3, iY4, iCr1, iCr2, iCr3, iCr4, iCb1, iCb2, iCb3, iCb4;
int y;
cx = (cx + 1)>>1; // do pixels in 2x2 blocks
cy = (cy + 1)>>1;
for (y = 0; y<cy; y++)
{
for (x=0; x<cx; x++) // do 8x8 pixels in 2x2 blocks
{
cRed = pSrc[0];
cGreen = pSrc[1];
cBlue = pSrc[2];
iY1 = (((cRed * 1225) + (cGreen * 2404) + (cBlue * 467)) >> 12) - 0x80;
iCb1 = (cBlue << 11) + (cRed * -691) + (cGreen * -1357);
iCr1 = (cRed << 11) + (cGreen * -1715) + (cBlue * -333);
cRed = pSrc[4];
cGreen = pSrc[5];
cBlue = pSrc[6];
iY2 = (((cRed * 1225) + (cGreen * 2404) + (cBlue * 467)) >> 12) - 0x80;
iCb2 = (cBlue << 11) + (cRed * -691) + (cGreen * -1357);
iCr2 = (cRed << 11) + (cGreen * -1715) + (cBlue * -333);
cRed = pSrc[lsize+0];
cGreen = pSrc[lsize+1];
cBlue = pSrc[lsize+2];
iY3 = (((cRed * 1225) + (cGreen * 2404) + (cBlue * 467)) >> 12) - 0x80;
iCb3 = (cBlue << 11) + (cRed * -691) + (cGreen * -1357);
iCr3 = (cRed << 11) + (cGreen * -1715) + (cBlue * -333);
cRed = pSrc[lsize+4];
cGreen = pSrc[lsize+5];
cBlue = pSrc[lsize+6];
iY4 = (((cRed * 1225) + (cGreen * 2404) + (cBlue * 467)) >> 12) - 0x80;
iCb4 = (cBlue << 11) + (cRed * -691) + (cGreen * -1357);
iCr4 = (cRed << 11) + (cGreen * -1715) + (cBlue * -333);
// Average the chroma values together
iCr1 = (iCr1 + iCr2 + iCr3 + iCr4) >> 14;
iCb1 = (iCb1 + iCb2 + iCb3 + iCb4) >> 14;
// store in the MCUs
pLUM[0] = (signed char)iY1;
pLUM[1] = (signed char)iY2;
pLUM[8] = (signed char)iY3;
pLUM[9] = (signed char)iY4;
pLUM += 2;
pCr[0] = (signed char)iCr1;
pCb[0] = (signed char)iCb1;
pCr++;
pCb++;
pSrc += 8; // skip 2 pixels to right
} // for x
pCr += 8 - cx; // skip to next row;
pCb += 8 - cx;
pLUM += 8 + (4-cx)*2; // skip down a row since 2 at a time
pSrc += lsize*2 - cx*8; // skip 2 lines
} // for y
} /* JPEGSubSample32() */
void JPEGSample32(unsigned char *pSrc, signed char *pMCU, int lsize, int cx, int cy)
{
int x, y;
unsigned char cRed, cGreen, cBlue;
int iY, iCr, iCb;
for (y=0; y<cy; y++)
{
for (x=0; x<cx; x++) // do 8x8 pixels
{
cRed = pSrc[0];
cGreen = pSrc[1];
cBlue = pSrc[2];
pSrc += 4;
iY = (((cRed * 1225) + (cGreen * 2404) + (cBlue * 467)) >> 12) - 0x80;
iCb = (cBlue << 11) + (cRed * -691) + (cGreen * -1357);
iCr = (cRed << 11) + (cGreen * -1715) + (cBlue * -333);
// store in the MCUs
pMCU[64] = (signed char)(iCb >> 12);
pMCU[128] = (signed char)(iCr >> 12);
*pMCU++ = (signed char)iY;
} // for x
pMCU += 8 - cx;
pSrc += lsize - cx*4;
} // for y
} /* JPEGSample32() */
void JPEGGetMCU22(unsigned char *pImage, JPEGIMAGE *pPage, int iPitch)
{
int cx, cy, width, height;
signed char *pMCUData = pPage->MCUc;
// if (pPage->ucPixelType == JPEG_PIXEL_RGB565)
// pSrc = pImage + x*16*2 + (y * 16 * lsize);
// else if (pPage->ucPixelType == JPEG_PIXEL_RGB888)
// pSrc = pImage + x*16*3 + (y * 16 * lsize);
// else if (pPage->ucPixelType == JPEG_PIXEL_ARGB8888)
// pSrc = pImage + x*16*4 + (y * 16 * lsize);
// else
// return; // invalid bit depth
// pDest = pMCUData;
cx = cy = 8;
width = height = 16;
// if (x*16 + width > pPage->iWidth)
// width = pPage->iWidth & 15;
// if (y*16 + height > pPage->iHeight)
// height = pPage->iHeight & 15;
// if (width < 8)
// cx = width;
// else
// cx = 8;
// if (height < 8)
// cy = height;
// else
// cy = 8;
// if (cy != 8 || cx != 8) // for edge MCUs, make sure all unused slots are 0
// memset(pMCUData, 0, 6*64*sizeof(short));
if (pPage->ucPixelType == JPEG_PIXEL_RGB565)
{
// upper left
JPEGSubSample16(pImage, pMCUData, &pMCUData[DCTSIZE*4], &pMCUData[DCTSIZE*5], iPitch, cx, cy);
// upper right
if (width > 8)
JPEGSubSample16(pImage+8*2, &pMCUData[DCTSIZE*1], &pMCUData[4+DCTSIZE*4], &pMCUData[4+DCTSIZE*5], iPitch, width-8, cy);
if (height > 8)
{
// lower left
JPEGSubSample16(pImage+8*iPitch, &pMCUData[DCTSIZE*2], &pMCUData[32+DCTSIZE*4], &pMCUData[32+DCTSIZE*5], iPitch, cx, height - 8);
// lower right
if (width > 8)
JPEGSubSample16(pImage+8*iPitch + 8*2, &pMCUData[DCTSIZE*3], &pMCUData[36+DCTSIZE*4], &pMCUData[36+DCTSIZE*5], iPitch, width - 8, height - 8);
}
}
else if (pPage->ucPixelType == JPEG_PIXEL_RGB888)
{
// upper left
JPEGSubSample24(pImage, pMCUData, &pMCUData[DCTSIZE*4], &pMCUData[DCTSIZE*5], iPitch, cx, cy);
// upper right
if (width > 8)
JPEGSubSample24(pImage+8*3, &pMCUData[DCTSIZE*1], &pMCUData[4+DCTSIZE*4], &pMCUData[4+DCTSIZE*5], iPitch, width-8, cy);
if (height > 8)
{
// lower left
JPEGSubSample24(pImage+8*iPitch, &pMCUData[DCTSIZE*2], &pMCUData[32+DCTSIZE*4], &pMCUData[32+DCTSIZE*5], iPitch, cx, height - 8);
// lower right
if (width > 8)
JPEGSubSample24(pImage+8*iPitch + 8*3, &pMCUData[DCTSIZE*3], &pMCUData[36+DCTSIZE*4], &pMCUData[36+DCTSIZE*5], iPitch, width - 8, height - 8);
}
}
else if (pPage->ucPixelType == JPEG_PIXEL_ARGB8888)
{
// upper left
JPEGSubSample32(pImage, pMCUData, &pMCUData[DCTSIZE*4], &pMCUData[DCTSIZE*5], iPitch, cx, cy);
// upper right
if (width > 8)
JPEGSubSample32(pImage+8*4, &pMCUData[DCTSIZE*1], &pMCUData[4+DCTSIZE*4], &pMCUData[4+DCTSIZE*5], iPitch, width-8, cy);
if (height > 8)
{
// lower left
JPEGSubSample32(pImage+8*iPitch, &pMCUData[DCTSIZE*2], &pMCUData[32+DCTSIZE*4], &pMCUData[32+DCTSIZE*5], iPitch, cx, height - 8);
// lower right
if (width > 8)
JPEGSubSample32(pImage+8*iPitch + 8*4, &pMCUData[DCTSIZE*3], &pMCUData[36+DCTSIZE*4], &pMCUData[36+DCTSIZE*5], iPitch, width - 8, height - 8);
}
}
} /* JPEGGetMCU22() */
/****************************************************************************
* *
* FUNCTION : JPEGSample16() *
* *
* PURPOSE : Sample a 8x8 color block *
* *
****************************************************************************/
void JPEGSample16(unsigned char *pSrc, signed char *pMCU, int lsize, int cx, int cy)
{
int x, y;
unsigned short us;
unsigned short *pUS = (unsigned short *)pSrc;
unsigned char cRed, cGreen, cBlue;
int iY, iCr, iCb;
for (y=0; y<cy; y++)
{
for (x=0; x<cx; x++) // do 8x8 pixels
{
us = *pUS++;
cBlue = (unsigned char)(((us & 0x1f)<<3) | (us & 7));
cGreen = (unsigned char)(((us & 0x7e0)>>3) | ((us & 0x60)>>5));
cRed = (unsigned char)(((us & 0xf800)>>8) | ((us & 0x3800)>>11));
iY = (((cRed * 1225) + (cGreen * 2404) + (cBlue * 467)) >> 12) - 0x80;
iCb = (cBlue << 11) + (cRed * -691) + (cGreen * -1357);
iCr = (cRed << 11) + (cGreen * -1715) + (cBlue * -333);
// store in the MCUs
pMCU[64] = (signed char)(iCb >> 12);
pMCU[128] = (signed char)(iCr >> 12);
*pMCU++ = (signed char)iY;
} // for x
pMCU += 8 - cx;
pUS += (lsize>>1) - cx;
} // for y
} /* JPEGSample16() */
/****************************************************************************
* *
* FUNCTION : JPEGSample24() *
* *
* PURPOSE : Sample a 8x8 color block *
* *
****************************************************************************/
void JPEGSample24(unsigned char *pSrc, signed char *pMCU, int lsize, int cx, int cy)
{
int x;
unsigned char cRed, cGreen, cBlue;
int iY, iCr, iCb;
int y;
for (y=0; y<cy; y++)
{
for (x=0; x<cx; x++) // do 8x8 pixels
{
cBlue = *pSrc++;
cGreen = *pSrc++;
cRed = *pSrc++;
iY = (((cRed * 1225) + (cGreen * 2404) + (cBlue * 467)) >> 12) - 0x80;
iCb = (cBlue << 11) + (cRed * -691) + (cGreen * -1357);
iCr = (cRed << 11) + (cGreen * -1715) + (cBlue * -333);
// store in the MCUs
pMCU[64] = (signed char)(iCb >> 12);
pMCU[128] = (signed char)(iCr >> 12);
*pMCU++ = (signed char)iY;
} // for x
pMCU += 8 - cx;
pSrc += lsize - cx*3;
} // for y
} /* JPEGSample24() */
void JPEGGetMCU11(unsigned char *pImage, JPEGIMAGE *pPage, int iPitch)
{
int cx, cy;
signed char *pMCUData = pPage->MCUc;
// if (x*8 + 8 > pPage->iWidth)
// cx = pPage->iWidth & 7;
// else
cx = 8;
// if (y*8 + 8 > pPage->iHeight)
// cy = pPage->iHeight & 7;
// else
cy = 8;
// if (cy != 8 || cx != 8)
// memset(pMCUData, 0, 3*64*sizeof(short)); // make sure unused pixels are 0
if (pPage->ucPixelType == JPEG_PIXEL_RGB888)
JPEGSample24(pImage, pMCUData, iPitch, cx, cy);
else if (pPage->ucPixelType == JPEG_PIXEL_RGB565)
JPEGSample16(pImage, pMCUData, iPitch, cx, cy);
else // must be 32-bpp
JPEGSample32(pImage, pMCUData, iPitch, cx, cy);
} /* JPEGGetMCU11() */
void JPEGFDCT(signed char *pMCUSrc, signed short *pMCUDest)
{
int iCol;
int iRow;
signed int tmp0,tmp1,tmp2,tmp3,tmp4,tmp5,tmp6,tmp7,tmp10,tmp11,tmp12,tmp13;
signed int z1,z2,z3,z4,z5,z11,z13;
signed char *s = pMCUSrc;
signed short *d = pMCUDest;
// do rows first
for (iRow=0; iRow<64; iRow+=8, s += 8, d += 8)
{
tmp0 = s[0] + s[7];
tmp7 = s[0] - s[7];
tmp1 = s[1] + s[6];
tmp6 = s[1] - s[6];
tmp2 = s[2] + s[5];
tmp5 = s[2] - s[5];
tmp3 = s[3] + s[4];
tmp4 = s[3] - s[4];
// even part
tmp10 = tmp0 + tmp3;
tmp13 = tmp0 - tmp3;
tmp11 = tmp1 + tmp2;
tmp12 = tmp1 - tmp2;
d[0] = (short)(tmp10 + tmp11);
d[4] = (short)(tmp10 - tmp11);
z1 = (((tmp12 + tmp13) * 181) >> 8); // 181>>8 = 0.7071
d[2] = (short)(tmp13 + z1);
d[6] = (short)(tmp13 - z1);
// odd part
tmp10 = tmp4 + tmp5;
tmp11 = tmp5 + tmp6;
tmp12 = tmp6 + tmp7;
z5 = ((tmp10 - tmp12) * 98); // 98 >>8 = 0.3826
z2 = ((z5 + tmp10 * 139) >> 8); // 139 >>8 = 0.541196
z4 = ((z5 + tmp12 * 334) >> 8); // 334 >>8 = 1.3065
z3 = ((tmp11 * 181) >> 8);
z11 = tmp7 + z3;
z13 = tmp7 - z3;
d[5] = (short)(z13 + z2);
d[3] = (short)(z13 - z2);
d[1] = (short)(z11 + z4);
d[7] = (short)(z11 - z4);
} // for each row
// now do the columns
d = pMCUDest;
for (iCol=0; iCol < 8; iCol++, d++)
{
tmp0 = d[0*8] + d[7*8];
tmp7 = d[0*8] - d[7*8];
tmp1 = d[1*8] + d[6*8];
tmp6 = d[1*8] - d[6*8];
tmp2 = d[2*8] + d[5*8];
tmp5 = d[2*8] - d[5*8];
tmp3 = d[3*8] + d[4*8];
tmp4 = d[3*8] - d[4*8];
// even part
tmp10 = tmp0 + tmp3;
tmp13 = tmp0 - tmp3;
tmp11 = tmp1 + tmp2;
tmp12 = tmp1 - tmp2;
d[0] = (short)(tmp10 + tmp11);
d[4*8] = (short)(tmp10 - tmp11);
z1 = (((tmp12 + tmp13) * 181) >> 8);
d[2*8] = (short)(tmp13 + z1);
d[6*8] = (short)(tmp13 - z1);
// odd part
tmp10 = tmp4 + tmp5;
tmp11 = tmp5 + tmp6;
tmp12 = tmp6 + tmp7;
z5 = ((tmp10 - tmp12) * 98);
z2 = ((z5 + tmp10 * 139) >> 8);
z4 = ((z5 + tmp12 * 334) >> 8);
z3 = (tmp11 * 181) >> 8;
z11 = tmp7 + z3;
z13 = tmp7 - z3;
d[5*8] = (short)(z13 + z2);
d[3*8] = (short)(z13 - z2);
d[1*8] = (short)(z11 + z4);
d[7*8] = (short)(z11 - z4);
} // for each column
} /* JPEGFDCT() */
void FlushCode(PIL_CODE *pPC)
{
unsigned char c;
while (pPC->iLen > 0)
{
c = (unsigned char) (pPC->ulAcc >> (REGISTER_WIDTH-8));
*pPC->pOut++ = c;
if (c == 0xff) // stuffed 0
*pPC->pOut++ = 0;
pPC->ulAcc <<= 8;
pPC->iLen -= 8;
}
pPC->iLen = 0;
} /* FlushCode() */
int JPEGAddMCU(JPEGIMAGE *pJPEG, JPEGENCODE *pEncode, uint8_t *pPixels, int iPitch)
{
int bSparse;
if (pEncode->y >= pJPEG->iHeight) {
// the image is already complete or was not initialized properly
pJPEG->iError = JPEG_INVALID_PARAMETER;
return JPEG_INVALID_PARAMETER;
}
if (pJPEG->ucPixelType == JPEG_PIXEL_GRAYSCALE) {
JPEGGetMCU(pPixels, iPitch, pJPEG->MCUc);
JPEGFDCT(pJPEG->MCUc, pJPEG->MCUs);
bSparse = JPEGQuantize(pJPEG, pJPEG->MCUs, 0);
pJPEG->iDCPred0 = JPEGEncodeMCU(0, pJPEG, pJPEG->MCUs, pJPEG->iDCPred0, bSparse);
if (pEncode->x >= (pJPEG->iWidth - pEncode->cx)) { // end of the row?
// Store the restart marker
FlushCode(&pJPEG->pc);
*(pJPEG->pc.pOut)++ = 0xff; // store restart marker
*(pJPEG->pc.pOut)++ = (unsigned char) (0xd0 + (pJPEG->iRestart & 7));
pJPEG->iRestart++;
pJPEG->iDCPred0 = 0; // reset the DC predictor
pEncode->x = 0;
pEncode->y += pEncode->cy;
if (pEncode->y >= pJPEG->iHeight && pJPEG->pOutput != NULL) {
pJPEG->iDataSize = (int)(pJPEG->pc.pOut - pJPEG->pOutput);
}
} else {
pEncode->x += pEncode->cx;
} // grayscale
} else { // color
if (pJPEG->ucSubSample == JPEG_SUBSAMPLE_444) {
JPEGGetMCU11(pPixels, pJPEG, iPitch);
JPEGFDCT(&pJPEG->MCUc[0*DCTSIZE], pJPEG->MCUs);
// Y
bSparse = JPEGQuantize(pJPEG, pJPEG->MCUs, 0);
pJPEG->iDCPred0 = JPEGEncodeMCU(0, pJPEG, pJPEG->MCUs, pJPEG->iDCPred0, bSparse);
JPEGFDCT(&pJPEG->MCUc[1*DCTSIZE], pJPEG->MCUs);
// Cb
bSparse = JPEGQuantize(pJPEG, pJPEG->MCUs, 1);
pJPEG->iDCPred1 = JPEGEncodeMCU(1, pJPEG, pJPEG->MCUs, pJPEG->iDCPred1, bSparse);
JPEGFDCT(&pJPEG->MCUc[2*DCTSIZE], pJPEG->MCUs);
// Cr
bSparse = JPEGQuantize(pJPEG, pJPEG->MCUs, 1);
pJPEG->iDCPred2 = JPEGEncodeMCU(1, pJPEG, pJPEG->MCUs, pJPEG->iDCPred2, bSparse);
} else { // must be 420
JPEGGetMCU22(pPixels, pJPEG, iPitch);
JPEGFDCT(&pJPEG->MCUc[0*DCTSIZE], pJPEG->MCUs); // Y0
bSparse = JPEGQuantize(pJPEG, pJPEG->MCUs, 0);
pJPEG->iDCPred0 = JPEGEncodeMCU(0, pJPEG, pJPEG->MCUs, pJPEG->iDCPred0, bSparse);
JPEGFDCT(&pJPEG->MCUc[1*DCTSIZE], pJPEG->MCUs); // Y1
bSparse = JPEGQuantize(pJPEG, pJPEG->MCUs, 0);
pJPEG->iDCPred0 = JPEGEncodeMCU(0, pJPEG, pJPEG->MCUs, pJPEG->iDCPred0, bSparse);
JPEGFDCT(&pJPEG->MCUc[2*DCTSIZE], pJPEG->MCUs); // Y2
bSparse = JPEGQuantize(pJPEG, pJPEG->MCUs, 0);
pJPEG->iDCPred0 = JPEGEncodeMCU(0, pJPEG, pJPEG->MCUs, pJPEG->iDCPred0, bSparse);
JPEGFDCT(&pJPEG->MCUc[3*DCTSIZE], pJPEG->MCUs); // Y3
bSparse = JPEGQuantize(pJPEG, pJPEG->MCUs, 0);
pJPEG->iDCPred0 = JPEGEncodeMCU(0, pJPEG, pJPEG->MCUs, pJPEG->iDCPred0, bSparse);
JPEGFDCT(&pJPEG->MCUc[4*DCTSIZE], pJPEG->MCUs); // Cb
bSparse = JPEGQuantize(pJPEG, pJPEG->MCUs, 1);
pJPEG->iDCPred1 = JPEGEncodeMCU(1, pJPEG, pJPEG->MCUs, pJPEG->iDCPred1, bSparse);
JPEGFDCT(&pJPEG->MCUc[5*DCTSIZE], pJPEG->MCUs); // Cr
bSparse = JPEGQuantize(pJPEG, pJPEG->MCUs, 1);
pJPEG->iDCPred2 = JPEGEncodeMCU(1, pJPEG, pJPEG->MCUs, pJPEG->iDCPred2, bSparse);
} // 420 subsample
if (pEncode->x >= (pJPEG->iWidth - pEncode->cx)) { // end of the row?
// Store the restart marker
FlushCode(&pJPEG->pc);
*(pJPEG->pc.pOut)++ = 0xff; // store restart marker
*(pJPEG->pc.pOut)++ = (unsigned char) (0xd0 + (pJPEG->iRestart & 7));
pJPEG->iRestart++;
pJPEG->iDCPred0 = pJPEG->iDCPred1 = pJPEG->iDCPred2 = 0; // reset the DC predictors
pEncode->x = 0;
pEncode->y += pEncode->cy;
if (pEncode->y >= pJPEG->iHeight && pJPEG->pOutput) {
pJPEG->iDataSize = (int)(pJPEG->pc.pOut - pJPEG->pOutput);
}
} else {
pEncode->x += pEncode->cx;
} // grayscale
}
if (pJPEG->pc.pOut >= pJPEG->pHighWater) { // out of space or need to write incremental buffer
if (pJPEG->pOutput) { // the user-supplied buffer is not big enough
pJPEG->iError = JPEG_NO_BUFFER;
return JPEG_NO_BUFFER;
} else { // write current block of data
int iLen = (int)(pJPEG->pc.pOut - pJPEG->ucFileBuf);
pJPEG->pfnWrite(&pJPEG->JPEGFile, pJPEG->ucFileBuf, iLen);
pJPEG->iDataSize += iLen;
pJPEG->pc.pOut = pJPEG->ucFileBuf;
}
}
return JPEG_SUCCESS;
} /* JPEGAddMCU() */
| 54.495877 | 158 | 0.641756 | [
"object"
] |
4b16a16a46a2421c563ad50dcaecb7a1bc834432 | 7,926 | cpp | C++ | ssl/src/v20191205/model/DvAuthDetail.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | ssl/src/v20191205/model/DvAuthDetail.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | ssl/src/v20191205/model/DvAuthDetail.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | /*
* 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/ssl/v20191205/model/DvAuthDetail.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Ssl::V20191205::Model;
using namespace std;
DvAuthDetail::DvAuthDetail() :
m_dvAuthKeyHasBeenSet(false),
m_dvAuthValueHasBeenSet(false),
m_dvAuthDomainHasBeenSet(false),
m_dvAuthPathHasBeenSet(false),
m_dvAuthKeySubDomainHasBeenSet(false),
m_dvAuthsHasBeenSet(false)
{
}
CoreInternalOutcome DvAuthDetail::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("DvAuthKey") && !value["DvAuthKey"].IsNull())
{
if (!value["DvAuthKey"].IsString())
{
return CoreInternalOutcome(Error("response `DvAuthDetail.DvAuthKey` IsString=false incorrectly").SetRequestId(requestId));
}
m_dvAuthKey = string(value["DvAuthKey"].GetString());
m_dvAuthKeyHasBeenSet = true;
}
if (value.HasMember("DvAuthValue") && !value["DvAuthValue"].IsNull())
{
if (!value["DvAuthValue"].IsString())
{
return CoreInternalOutcome(Error("response `DvAuthDetail.DvAuthValue` IsString=false incorrectly").SetRequestId(requestId));
}
m_dvAuthValue = string(value["DvAuthValue"].GetString());
m_dvAuthValueHasBeenSet = true;
}
if (value.HasMember("DvAuthDomain") && !value["DvAuthDomain"].IsNull())
{
if (!value["DvAuthDomain"].IsString())
{
return CoreInternalOutcome(Error("response `DvAuthDetail.DvAuthDomain` IsString=false incorrectly").SetRequestId(requestId));
}
m_dvAuthDomain = string(value["DvAuthDomain"].GetString());
m_dvAuthDomainHasBeenSet = true;
}
if (value.HasMember("DvAuthPath") && !value["DvAuthPath"].IsNull())
{
if (!value["DvAuthPath"].IsString())
{
return CoreInternalOutcome(Error("response `DvAuthDetail.DvAuthPath` IsString=false incorrectly").SetRequestId(requestId));
}
m_dvAuthPath = string(value["DvAuthPath"].GetString());
m_dvAuthPathHasBeenSet = true;
}
if (value.HasMember("DvAuthKeySubDomain") && !value["DvAuthKeySubDomain"].IsNull())
{
if (!value["DvAuthKeySubDomain"].IsString())
{
return CoreInternalOutcome(Error("response `DvAuthDetail.DvAuthKeySubDomain` IsString=false incorrectly").SetRequestId(requestId));
}
m_dvAuthKeySubDomain = string(value["DvAuthKeySubDomain"].GetString());
m_dvAuthKeySubDomainHasBeenSet = true;
}
if (value.HasMember("DvAuths") && !value["DvAuths"].IsNull())
{
if (!value["DvAuths"].IsArray())
return CoreInternalOutcome(Error("response `DvAuthDetail.DvAuths` is not array type"));
const rapidjson::Value &tmpValue = value["DvAuths"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
DvAuths item;
CoreInternalOutcome outcome = item.Deserialize(*itr);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_dvAuths.push_back(item);
}
m_dvAuthsHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void DvAuthDetail::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_dvAuthKeyHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DvAuthKey";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_dvAuthKey.c_str(), allocator).Move(), allocator);
}
if (m_dvAuthValueHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DvAuthValue";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_dvAuthValue.c_str(), allocator).Move(), allocator);
}
if (m_dvAuthDomainHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DvAuthDomain";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_dvAuthDomain.c_str(), allocator).Move(), allocator);
}
if (m_dvAuthPathHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DvAuthPath";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_dvAuthPath.c_str(), allocator).Move(), allocator);
}
if (m_dvAuthKeySubDomainHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DvAuthKeySubDomain";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_dvAuthKeySubDomain.c_str(), allocator).Move(), allocator);
}
if (m_dvAuthsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DvAuths";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_dvAuths.begin(); itr != m_dvAuths.end(); ++itr, ++i)
{
value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(value[key.c_str()][i], allocator);
}
}
}
string DvAuthDetail::GetDvAuthKey() const
{
return m_dvAuthKey;
}
void DvAuthDetail::SetDvAuthKey(const string& _dvAuthKey)
{
m_dvAuthKey = _dvAuthKey;
m_dvAuthKeyHasBeenSet = true;
}
bool DvAuthDetail::DvAuthKeyHasBeenSet() const
{
return m_dvAuthKeyHasBeenSet;
}
string DvAuthDetail::GetDvAuthValue() const
{
return m_dvAuthValue;
}
void DvAuthDetail::SetDvAuthValue(const string& _dvAuthValue)
{
m_dvAuthValue = _dvAuthValue;
m_dvAuthValueHasBeenSet = true;
}
bool DvAuthDetail::DvAuthValueHasBeenSet() const
{
return m_dvAuthValueHasBeenSet;
}
string DvAuthDetail::GetDvAuthDomain() const
{
return m_dvAuthDomain;
}
void DvAuthDetail::SetDvAuthDomain(const string& _dvAuthDomain)
{
m_dvAuthDomain = _dvAuthDomain;
m_dvAuthDomainHasBeenSet = true;
}
bool DvAuthDetail::DvAuthDomainHasBeenSet() const
{
return m_dvAuthDomainHasBeenSet;
}
string DvAuthDetail::GetDvAuthPath() const
{
return m_dvAuthPath;
}
void DvAuthDetail::SetDvAuthPath(const string& _dvAuthPath)
{
m_dvAuthPath = _dvAuthPath;
m_dvAuthPathHasBeenSet = true;
}
bool DvAuthDetail::DvAuthPathHasBeenSet() const
{
return m_dvAuthPathHasBeenSet;
}
string DvAuthDetail::GetDvAuthKeySubDomain() const
{
return m_dvAuthKeySubDomain;
}
void DvAuthDetail::SetDvAuthKeySubDomain(const string& _dvAuthKeySubDomain)
{
m_dvAuthKeySubDomain = _dvAuthKeySubDomain;
m_dvAuthKeySubDomainHasBeenSet = true;
}
bool DvAuthDetail::DvAuthKeySubDomainHasBeenSet() const
{
return m_dvAuthKeySubDomainHasBeenSet;
}
vector<DvAuths> DvAuthDetail::GetDvAuths() const
{
return m_dvAuths;
}
void DvAuthDetail::SetDvAuths(const vector<DvAuths>& _dvAuths)
{
m_dvAuths = _dvAuths;
m_dvAuthsHasBeenSet = true;
}
bool DvAuthDetail::DvAuthsHasBeenSet() const
{
return m_dvAuthsHasBeenSet;
}
| 29.464684 | 143 | 0.68105 | [
"vector",
"model"
] |
4b1715b964836abde70304f3d8e5b2f44f10e652 | 13,346 | cpp | C++ | src/13_Camera_round/src/main.cpp | AnselmoGPP/OGL_tests | 68072c208bccb86f864e4394928f227fbb308a17 | [
"MIT"
] | null | null | null | src/13_Camera_round/src/main.cpp | AnselmoGPP/OGL_tests | 68072c208bccb86f864e4394928f227fbb308a17 | [
"MIT"
] | null | null | null | src/13_Camera_round/src/main.cpp | AnselmoGPP/OGL_tests | 68072c208bccb86f864e4394928f227fbb308a17 | [
"MIT"
] | null | null | null | /*
* https://stackoverflow.com/questions/57336940/how-to-glutdisplayfunc-glutmainloop-in-glfw
*/
// Includes --------------------
#ifdef IMGUI_IMPL_OPENGL_LOADER_GLEW
#include "GL/glew.h"
#elif IMGUI_IMPL_OPENGL_LOADER_GLAD
#include "glad/glad.h"
#endif
#include "GLFW/glfw3.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtc/type_ptr.hpp"
#include "auxiliar.hpp" // chronometer, fps
#include "shader.hpp"
#include <iostream>
// Settings (typedef and global data section) --------------------
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
// Function declarations --------------------
void framebuffer_resize_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow *window);
void printOGLdata();
void printFrameData(int &frameCount, int fps);
// Function definitions --------------------
int main()
{
// glfw: initialize and configure
if (!glfwInit())
{
std::cerr << "Failed to initialize GLFW\n" << std::endl;
return -1;
}
glfwWindowHint(GLFW_SAMPLES, 0); // antialiasing
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
#endif
// ----- GLFW window creation
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Testing", nullptr, nullptr);
if (window == nullptr)
{
std::cerr << "Failed to create GLFW window (note: Intel GPUs are not 3.3 compatible)" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
// ----- Event callbacks and control handling
glfwSetFramebufferSizeCallback(window, framebuffer_resize_callback);
glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); // Sticky keys: Make sure that any pressed key is captured
// ----- Load OGL function pointers with GLEW or GLAD
#ifdef IMGUI_IMPL_OPENGL_LOADER_GLEW
glewExperimental = true; // Needed for core profile (no more from GLEW 2.0)
GLenum glewErr = glewInit();
if (glewErr != GLEW_OK)
{
std::cerr << "GLEW error (" << glewErr << "): " << glewGetErrorString(glewErr) << "\n" << std::endl;
glfwTerminate();
return -1;
}
#elif IMGUI_IMPL_OPENGL_LOADER_GLAD
// ----- GLAD: Load all OpenGL function pointers
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "GLAD initialization failed" << std::endl;
return -1;
}
#endif
// ----- OGL general options
printOGLdata();
glEnable(GL_DEPTH_TEST);
glFrontFace(GL_CCW);
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); // Wireframe mode
//glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // Back to default
// ----- Build and compile our shader program
Shader myProgram(
"../../../src/13_Camera_round/shaders/vertexShader.vs",
"../../../src/13_Camera_round/shaders/fragmentShader.fs" );
// ----- Set up vertex data, buffers, and configure vertex attributes
float vertices0[] = {
// positions // colors // texture
0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top right
0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom right
-0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom left
-0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f // top left
};
unsigned indices0[] = {
0, 1, 3,
1, 2, 3
};
float vertices[] = {
// position // texture
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, // front
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
0.5f, -0.5f, -0.5f, 0.0f, 0.0f, // back
-0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, // top
-0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, 1.0f, // floor
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 1.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 1.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f, // right
0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // left
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f
};
glm::vec3 cubePositions[] = {
glm::vec3( 0.0f, 0.0f, 0.0f),
glm::vec3( 2.0f, 5.0f, -15.0f),
glm::vec3(-1.5f, -2.2f, -2.5f),
glm::vec3(-3.8f, -2.0f, -12.3f),
glm::vec3( 2.4f, -0.4f, -3.5f),
glm::vec3(-1.7f, 3.0f, -7.5f),
glm::vec3( 1.3f, -2.0f, -2.5f),
glm::vec3( 1.5f, 2.0f, -2.5f),
glm::vec3( 1.5f, 0.2f, -1.5f),
glm::vec3(-1.3f, 1.0f, -1.5f)
};
unsigned VAO, VBO, EBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
//glGenBuffers(1, &EBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // GL_DYNAMIC_DRAW, GL_STATIC_DRAW, GL_STREAM_DRAW
//glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
//glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void *)nullptr); // position attribute
glEnableVertexAttribArray(0);
//glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void *)(3 * sizeof(float))); // color attribute
//glEnableVertexAttribArray(1);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float))); // texture coords
glEnableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, 0); // unbind VBO (not usual)
glBindVertexArray(0); // unbind VAO (not usual)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // unbind EBO
// ----- Load and create a texture
unsigned texture1, texture2;
int width, height, numberChannels;
unsigned char *image;
stbi_set_flip_vertically_on_load(true);
// Texture 1
glGenTextures(1, &texture1);
glBindTexture(GL_TEXTURE_2D, texture1);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // Texture wrapping
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // Texture filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
image = stbi_load("../../../textures/box1.jpg", &width, &height, &numberChannels, 0);
if(image)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, (numberChannels == 4? GL_RGBA : GL_RGB), GL_UNSIGNED_BYTE, image);
glGenerateMipmap(GL_TEXTURE_2D);
}
else std::cout << "Failed to load texture" << std::endl;
stbi_image_free(image);
// Texture 2
glGenTextures(1, &texture2);
glBindTexture(GL_TEXTURE_2D, texture2);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
image = stbi_load("../../../textures/note.png", &width, &height, &numberChannels, 0);
if(image)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, (numberChannels == 4? GL_RGBA : GL_RGB), GL_UNSIGNED_BYTE, image);
glGenerateMipmap(GL_TEXTURE_2D);
}
else std::cout << "Failed to load texture" << std::endl;
stbi_image_free(image);
// Tell OGL for each sampler to which texture unit it belongs to (only has to be done once)
myProgram.UseProgram();
glUniform1i(glGetUniformLocation(myProgram.ID, "texture1"), 0);
glUniform1i(glGetUniformLocation(myProgram.ID, "texture2"), 1);
// ----- Other operations
stdTime chron;
fpsCheck fpsC;
int frameCounter = 0;
// ----- Render loop
while (!glfwWindowShouldClose(window))
{
processInput(window);
// render ----------
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // GL_STENCIL_BUFFER_BIT
glActiveTexture(GL_TEXTURE0); // Bind textures on corresponding texture unit
glBindTexture(GL_TEXTURE_2D, texture1);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texture2);
myProgram.UseProgram();
//glm::mat4 model = glm::mat4(1.0f);
//model = glm::translate(model, glm::vec3(0.0f, 0.0f, 0.0f));
//model = glm::rotate(model, (float)chron.GetTime() * glm::radians(50.0f), glm::vec3(0.5f, 1.0f, 0.0f));
//model = glm::scale(model, glm::vec3(1.0, 1.0, 1.0));
glm::mat4 view = glm::mat4(1.0f);
float radius = 10.0f;
float camX = sin(chron.GetTime()) * radius;
float camZ = cos(chron.GetTime()) * radius;
view = glm::lookAt(glm::vec3(camX, 0.0f, camZ), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
glUniformMatrix4fv(glGetUniformLocation(myProgram.ID, "view"), 1, GL_FALSE, &view[0][0]);
glm::mat4 projection = glm::mat4(1.0f);
projection = glm::perspective(glm::radians(45.0f), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); // If it doesn't change each frame, it can be placed outside the render loop
glUniformMatrix4fv(glGetUniformLocation(myProgram.ID, "projection"), 1, GL_FALSE, &projection[0][0]);
glBindVertexArray(VAO);
for(unsigned i = 0; i < 10; i++)
{
glm::mat4 model = glm::mat4(1.0f);
model = glm::translate(model, cubePositions[i]);
model = glm::rotate(model, (float)chron.GetTime() * glm::radians(20.0f * i), glm::vec3(1.0f, 0.3f, 0.5f));
model = glm::scale(model, glm::vec3(1.0, 1.0, 1.0));
glUniformMatrix4fv(glGetUniformLocation(myProgram.ID, "model"), 1, GL_FALSE, glm::value_ptr(model));
glDrawArrays(GL_TRIANGLES, 0, 6*2*3);
//glDrawElements(GL_TRIANGLES, 3*12, GL_UNSIGNED_INT, nullptr);
}
// -----------------
printFrameData(frameCounter, fpsC.GetFPS());
glfwSwapBuffers(window);
glfwPollEvents();
}
// Render loop End
// ----- De-allocate all resources
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
//glDeleteBuffers(1, &EBO);
glDeleteProgram(myProgram.ID);
glfwTerminate();
return 0;
}
// -----------------------------------------------------------------------------------
// Process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
void processInput(GLFWwindow *window)
{
if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
}
// GLFW: whenever the window size changed (by OS or user resize) this callback function executes
void framebuffer_resize_callback(GLFWwindow* window, int width, int height)
{
//glfwGetFramebufferSize(window, &width, &height); // Get viewport size from GLFW
glViewport(0, 0, width, height); // Tell OGL the viewport size
// projection adjustments
}
void printOGLdata()
{
int maxNumberAttributes;
glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &maxNumberAttributes);
std::cout << "OpenGL data: " <<
"\n Version: " << glGetString(GL_VERSION) <<
"\n Vendor: " << glGetString(GL_VENDOR) <<
"\n Renderer: " << glGetString(GL_RENDERER) <<
"\n GLSL version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) <<
"\n Max. attributes supported: " << maxNumberAttributes << std::endl;
}
void printFrameData(int &frameCount, int fps)
{
//std::cout << "Frame " << ++frameCount << '\r'; // Number of frames
std::cout << "FPS: " << fps << '\r'; // FPS
}
| 37.175487 | 188 | 0.581448 | [
"render",
"model"
] |
4b1f914f76cae9b6dd748cce7621510e376bebb8 | 1,155 | cpp | C++ | Day3/part1.cpp | Roxtaru/aoc | 1e00f70b3c41a65df4aeac62bc0acdcb874626c7 | [
"Unlicense"
] | null | null | null | Day3/part1.cpp | Roxtaru/aoc | 1e00f70b3c41a65df4aeac62bc0acdcb874626c7 | [
"Unlicense"
] | null | null | null | Day3/part1.cpp | Roxtaru/aoc | 1e00f70b3c41a65df4aeac62bc0acdcb874626c7 | [
"Unlicense"
] | null | null | null | #include<iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
int main(){
int zeros = 0;
int ones = 0;
int binSize = 12;
int gammaNum = 0;
int epsilonNum = 0;
vector<string> list;
string holder = "";
string checker = "";
string gammaStr = "";
string epsilonStr = "";
ifstream infile;
infile.open("input.txt");
while(!infile.eof()){
infile >> holder;
list.push_back(holder);
}
for(int i = 0; i < binSize; i++){
for(int j = 0; j < list.size(); j++){
holder = list[j];
if(holder[i] == '0'){
zeros++;
}
else{
ones++;
}
}
if(zeros > ones){
gammaStr += '0';
epsilonStr += '1';
}
else{
gammaStr += '1';
epsilonStr += '0';
}
zeros = 0;
ones = 0;
}
gammaNum = stoi(gammaStr, nullptr, 2);
epsilonNum = stoi(epsilonStr, nullptr, 2);
cout << "Power Cunsumtion: " << gammaNum * epsilonNum << endl;
return 0;
}
| 17.769231 | 66 | 0.454545 | [
"vector"
] |
4b267b7418d845ac8b44aab6c84c8397fb3ce414 | 10,160 | cpp | C++ | third_party/mesa/src/src/gallium/state_trackers/clover/llvm/invocation.cpp | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | third_party/mesa/src/src/gallium/state_trackers/clover/llvm/invocation.cpp | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | third_party/mesa/src/src/gallium/state_trackers/clover/llvm/invocation.cpp | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | //
// Copyright 2012 Francisco Jerez
//
// 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
// OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#include "core/compiler.hpp"
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Frontend/TextDiagnosticPrinter.h>
#include <clang/CodeGen/CodeGenAction.h>
#include <llvm/Bitcode/BitstreamWriter.h>
#include <llvm/Bitcode/ReaderWriter.h>
#include <llvm/DerivedTypes.h>
#include <llvm/Linker.h>
#include <llvm/LLVMContext.h>
#include <llvm/Module.h>
#include <llvm/PassManager.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/Support/PathV1.h>
#include <llvm/Target/TargetData.h>
#include <llvm/Transforms/IPO.h>
#include <llvm/Transforms/IPO/PassManagerBuilder.h>
#include "pipe/p_state.h"
#include "util/u_memory.h"
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdio>
using namespace clover;
namespace {
#if 0
void
build_binary(const std::string &source, const std::string &target,
const std::string &name) {
clang::CompilerInstance c;
clang::EmitObjAction act(&llvm::getGlobalContext());
std::string log;
llvm::raw_string_ostream s_log(log);
LLVMInitializeTGSITarget();
LLVMInitializeTGSITargetInfo();
LLVMInitializeTGSITargetMC();
LLVMInitializeTGSIAsmPrinter();
c.getFrontendOpts().Inputs.push_back(
std::make_pair(clang::IK_OpenCL, name));
c.getHeaderSearchOpts().UseBuiltinIncludes = false;
c.getHeaderSearchOpts().UseStandardIncludes = false;
c.getLangOpts().NoBuiltin = true;
c.getTargetOpts().Triple = target;
c.getInvocation().setLangDefaults(clang::IK_OpenCL);
c.createDiagnostics(0, NULL, new clang::TextDiagnosticPrinter(
s_log, c.getDiagnosticOpts()));
c.getPreprocessorOpts().addRemappedFile(
name, llvm::MemoryBuffer::getMemBuffer(source));
if (!c.ExecuteAction(act))
throw build_error(log);
}
module
load_binary(const char *name) {
std::ifstream fs((name));
std::vector<unsigned char> str((std::istreambuf_iterator<char>(fs)),
(std::istreambuf_iterator<char>()));
compat::istream cs(str);
return module::deserialize(cs);
}
#endif
llvm::Module *
compile(const std::string &source, const std::string &name,
const std::string &triple) {
clang::CompilerInstance c;
clang::EmitLLVMOnlyAction act(&llvm::getGlobalContext());
std::string log;
llvm::raw_string_ostream s_log(log);
c.getFrontendOpts().Inputs.push_back(
clang::FrontendInputFile(name, clang::IK_OpenCL));
c.getFrontendOpts().ProgramAction = clang::frontend::EmitLLVMOnly;
c.getHeaderSearchOpts().UseBuiltinIncludes = true;
c.getHeaderSearchOpts().UseStandardSystemIncludes = true;
c.getHeaderSearchOpts().ResourceDir = CLANG_RESOURCE_DIR;
// Add libclc generic search path
c.getHeaderSearchOpts().AddPath(LIBCLC_INCLUDEDIR,
clang::frontend::Angled,
false, false, false);
// Add libclc include
c.getPreprocessorOpts().Includes.push_back("clc/clc.h");
// clc.h requires that this macro be defined:
c.getPreprocessorOpts().addMacroDef("cl_clang_storage_class_specifiers");
c.getLangOpts().NoBuiltin = true;
c.getTargetOpts().Triple = triple;
c.getInvocation().setLangDefaults(clang::IK_OpenCL);
c.createDiagnostics(0, NULL, new clang::TextDiagnosticPrinter(
s_log, c.getDiagnosticOpts()));
c.getPreprocessorOpts().addRemappedFile(name,
llvm::MemoryBuffer::getMemBuffer(source));
// Compile the code
if (!c.ExecuteAction(act))
throw build_error(log);
return act.takeModule();
}
void
find_kernels(llvm::Module *mod, std::vector<llvm::Function *> &kernels) {
const llvm::NamedMDNode *kernel_node =
mod->getNamedMetadata("opencl.kernels");
for (unsigned i = 0; i < kernel_node->getNumOperands(); ++i) {
kernels.push_back(llvm::dyn_cast<llvm::Function>(
kernel_node->getOperand(i)->getOperand(0)));
}
}
void
link(llvm::Module *mod, const std::string &triple,
const std::vector<llvm::Function *> &kernels) {
llvm::PassManager PM;
llvm::PassManagerBuilder Builder;
bool isNative;
llvm::Linker linker("clover", mod);
// Link the kernel with libclc
linker.LinkInFile(llvm::sys::Path(LIBCLC_LIBEXECDIR + triple + ".bc"), isNative);
mod = linker.releaseModule();
// Add a function internalizer pass.
//
// By default, the function internalizer pass will look for a function
// called "main" and then mark all other functions as internal. Marking
// functions as internal enables the optimizer to perform optimizations
// like function inlining and global dead-code elimination.
//
// When there is no "main" function in a module, the internalize pass will
// treat the module like a library, and it won't internalize any functions.
// Since there is no "main" function in our kernels, we need to tell
// the internalizer pass that this module is not a library by passing a
// list of kernel functions to the internalizer. The internalizer will
// treat the functions in the list as "main" functions and internalize
// all of the other functions.
std::vector<const char*> export_list;
for (std::vector<llvm::Function *>::const_iterator I = kernels.begin(),
E = kernels.end();
I != E; ++I) {
llvm::Function *kernel = *I;
export_list.push_back(kernel->getName().data());
}
PM.add(llvm::createInternalizePass(export_list));
// Run link time optimizations
Builder.OptLevel = 2;
Builder.populateLTOPassManager(PM, false, true);
PM.run(*mod);
}
module
build_module_llvm(llvm::Module *mod,
const std::vector<llvm::Function *> &kernels) {
module m;
struct pipe_llvm_program_header header;
llvm::SmallVector<char, 1024> llvm_bitcode;
llvm::raw_svector_ostream bitcode_ostream(llvm_bitcode);
llvm::BitstreamWriter writer(llvm_bitcode);
llvm::WriteBitcodeToFile(mod, bitcode_ostream);
bitcode_ostream.flush();
llvm::Function *kernel_func;
std::string kernel_name;
compat::vector<module::argument> args;
// XXX: Support more than one kernel
assert(kernels.size() == 1);
kernel_func = kernels[0];
kernel_name = kernel_func->getName();
for (llvm::Function::arg_iterator I = kernel_func->arg_begin(),
E = kernel_func->arg_end(); I != E; ++I) {
llvm::Argument &arg = *I;
llvm::Type *arg_type = arg.getType();
llvm::TargetData TD(kernel_func->getParent());
unsigned arg_size = TD.getTypeStoreSize(arg_type);
if (llvm::isa<llvm::PointerType>(arg_type) && arg.hasByValAttr()) {
arg_type =
llvm::dyn_cast<llvm::PointerType>(arg_type)->getElementType();
}
if (arg_type->isPointerTy()) {
// XXX: Figure out LLVM->OpenCL address space mappings for each
// target. I think we need to ask clang what these are. For now,
// pretend everything is in the global address space.
unsigned address_space = llvm::cast<llvm::PointerType>(arg_type)->getAddressSpace();
switch (address_space) {
default:
args.push_back(module::argument(module::argument::global, arg_size));
break;
}
} else {
args.push_back(module::argument(module::argument::scalar, arg_size));
}
}
header.num_bytes = llvm_bitcode.size();
std::string data;
data.insert(0, (char*)(&header), sizeof(header));
data.insert(data.end(), llvm_bitcode.begin(),
llvm_bitcode.end());
m.syms.push_back(module::symbol(kernel_name, 0, 0, args ));
m.secs.push_back(module::section(0, module::section::text,
header.num_bytes, data));
return m;
}
} // End anonymous namespace
module
clover::compile_program_llvm(const compat::string &source,
enum pipe_shader_ir ir,
const compat::string &triple) {
std::vector<llvm::Function *> kernels;
llvm::Module *mod = compile(source, "cl_input", triple);
find_kernels(mod, kernels);
link(mod, triple, kernels);
// Build the clover::module
switch (ir) {
case PIPE_SHADER_IR_TGSI:
//XXX: Handle TGSI
assert(0);
return module();
default:
return build_module_llvm(mod, kernels);
}
}
| 36.945455 | 96 | 0.635039 | [
"vector"
] |
4b27868664c9117e85c52866d3fb6a66cb370980 | 4,620 | hpp | C++ | Code/Runtime/BerserkVulkan/VulkanDebug.hpp | EgorOrachyov/Berserk | 0fcd3571b5aa0a1e073a2280035d445b2be94cbf | [
"MIT"
] | 43 | 2018-12-21T15:01:20.000Z | 2022-01-12T04:22:38.000Z | Code/Runtime/BerserkVulkan/VulkanDebug.hpp | EgorOrachyov/Berserk | 0fcd3571b5aa0a1e073a2280035d445b2be94cbf | [
"MIT"
] | 22 | 2018-10-06T14:10:05.000Z | 2021-12-31T17:58:40.000Z | Code/Runtime/BerserkVulkan/VulkanDebug.hpp | EgorOrachyov/Berserk | 0fcd3571b5aa0a1e073a2280035d445b2be94cbf | [
"MIT"
] | 4 | 2019-04-14T05:59:33.000Z | 2021-05-21T10:34:57.000Z | /**********************************************************************************/
/* This file is part of Berserk Engine project */
/* https://github.com/EgorOrachyov/Berserk */
/**********************************************************************************/
/* MIT License */
/* */
/* Copyright (c) 2018 - 2021 Egor Orachyov */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining a copy */
/* of this software and associated documentation files (the "Software"), to deal */
/* in the Software without restriction, including without limitation the rights */
/* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell */
/* copies of the Software, and to permit persons to whom the Software is */
/* furnished to do so, subject to the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be included in all */
/* copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR */
/* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, */
/* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE */
/* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER */
/* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, */
/* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */
/* SOFTWARE. */
/**********************************************************************************/
#ifndef BERSERK_VULKANDEBUG_HPP
#define BERSERK_VULKANDEBUG_HPP
#include <BerserkVulkan/VulkanDefs.hpp>
#ifdef BERSERK_DEBUG
#define BERSERK_VK_NAME(device,object,type,name) \
VulkanDebug::AddDebugName(device, object, type, name);
#define BERSERK_VK_BEGIN_LABEL(buffer,name) \
VulkanDebug::BeginLabel(buffer, name);
#define BERSERK_VK_END_LABEL(buffer) \
VulkanDebug::EndLabel(buffer);
#else
#define BERSERK_VK_NAME(device,object,type,name)
#define BERSERK_VK_BEGIN_LABEL(buffer,name)
#define BERSERK_VK_END_LABEL(buffer)
#endif
namespace Berserk {
namespace RHI {
/** Extension functions loader for vulkan debugging */
class VulkanDebug {
public:
// Called once when the instance in initialized
static void LoadInstanceFunctions(VkInstance instance);
static void AddDebugName(VkDevice device, void* object, VkObjectType objectType, const char* name);
static void AddDebugName(VkDevice device, void* object, VkObjectType objectType, const String& name);
static void AddDebugName(VkDevice device, void* object, VkObjectType objectType, const StringName& name);
static void AddDebugName(VkDevice device, uint64 object, VkObjectType objectType, const char* name);
static void AddDebugName(VkDevice device, uint64 object, VkObjectType objectType, const String& name);
static void AddDebugName(VkDevice device, uint64 object, VkObjectType objectType, const StringName& name);
static void BeginLabel(VkCommandBuffer buffer, const char* name, const Color& color = Color());
static void BeginLabel(VkCommandBuffer buffer, const String& name, const Color& color = Color());
static void BeginLabel(VkCommandBuffer buffer, const StringName& name, const Color& color = Color());
static void EndLabel(VkCommandBuffer buffer);
static PFN_vkCreateDebugUtilsMessengerEXT vkCreateDebugUtilsMessengerEXT;
static PFN_vkDestroyDebugUtilsMessengerEXT vkDestroyDebugUtilsMessengerEXT;
static PFN_vkSetDebugUtilsObjectNameEXT vkSetDebugUtilsObjectNameEXT;
static PFN_vkCmdBeginDebugUtilsLabelEXT vkCmdBeginDebugUtilsLabelEXT;
static PFN_vkCmdEndDebugUtilsLabelEXT vkCmdEndDebugUtilsLabelEXT;
};
}
}
#endif //BERSERK_VULKANDEBUG_HPP | 60 | 118 | 0.583117 | [
"object"
] |
4b2a8250c5dee55830aa8305a5d48ff8610d8fc5 | 1,840 | cpp | C++ | RealEngine/Transformation.cpp | Meeeri08/Motores-de-Videojuegos | cbc593601f62c483581fcb1908360e1b71757980 | [
"MIT"
] | null | null | null | RealEngine/Transformation.cpp | Meeeri08/Motores-de-Videojuegos | cbc593601f62c483581fcb1908360e1b71757980 | [
"MIT"
] | null | null | null | RealEngine/Transformation.cpp | Meeeri08/Motores-de-Videojuegos | cbc593601f62c483581fcb1908360e1b71757980 | [
"MIT"
] | null | null | null | #include "Transformation.h"
Transformation::Transformation(Component::ComponentType type, GameObject* GO) :Component(type, GO)
{
this->GO = GO;
position = { 0.0f,0.0f,0.0f };
scale = { 1.0f,1.0f,1.0f };
rotationVector = { 0.0f,0.0f,0.0f }; // user-friendly
quatRotation = { 0.0f,0.0f,0.0f,1.0f }; // used for calculations
localMatrix = float4x4::identity;
globalMatrix = float4x4::identity;
}
Transformation::~Transformation(){}
Component::ComponentType Transformation::GetComponentType()
{
return Component::ComponentType::Transformation;
}
float3 Transformation::GetPosition()
{
return position;
}
float3 Transformation::GetScale()
{
return scale;
}
float3 Transformation::GetEulerRotation()
{
return rotationVector;
}
Quat Transformation::GetQuatRotation()
{
return quatRotation;
}
void Transformation::SetPosition(float3 position)
{
this->position = position;
CalculateMatrix();
}
void Transformation::SetScale(float3 scale)
{
this->scale = scale;
CalculateMatrix();
}
void Transformation::SetRotation(float3 rotation)
{
rotationVector = rotation;
this->quatRotation = Quat::FromEulerXYZ(rotationVector.x * DEGTORAD, rotationVector.y * DEGTORAD, rotationVector.z * DEGTORAD);
CalculateMatrix();
}
void Transformation::SetQuatRotation(Quat quatRotation)
{
this->quatRotation = quatRotation;
rotationVector = this->quatRotation.ToEulerXYZ() * RADTODEG;
CalculateMatrix();
}
void Transformation::CalculateMatrix()
{
localMatrix.Set(float4x4::FromTRS(position, quatRotation, scale));
}
/*
bool Transformation::Save(JsonParser* data)
{
bool ret = true;
data->AddString("Component", "Transform");
data->AddInt("Type", Component::ComponentType::Transformation);
return ret;
}
bool Transformation::Load(JsonParser* data)
{
bool ret = true;
component_UUID = data->GetUInt("UUID");
return ret;
}
*/ | 20.21978 | 128 | 0.740217 | [
"transform"
] |
4b2b1398180f2d9157048cd8eb4bfdf7e990845c | 35,795 | cpp | C++ | Source/SIMPLib/TestFilters/GenericExample.cpp | mhitzem/SIMPL | cd8a58f8d955d232ea039121cc5286cc9545c7a6 | [
"NRL"
] | 3 | 2018-01-18T18:27:02.000Z | 2021-06-13T06:10:52.000Z | Source/SIMPLib/TestFilters/GenericExample.cpp | mhitzem/SIMPL | cd8a58f8d955d232ea039121cc5286cc9545c7a6 | [
"NRL"
] | 211 | 2016-07-27T12:18:16.000Z | 2021-11-02T13:42:11.000Z | Source/SIMPLib/TestFilters/GenericExample.cpp | mhitzem/SIMPL | cd8a58f8d955d232ea039121cc5286cc9545c7a6 | [
"NRL"
] | 23 | 2016-02-15T21:23:47.000Z | 2021-08-11T15:35:24.000Z | /* ============================================================================
* Copyright (c) 2009-2016 BlueQuartz Software, LLC
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* Neither the name of BlueQuartz Software, the US Air Force, nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The code contained herein was partially funded by the following contracts:
* United States Air Force Prime Contract FA8650-07-D-5800
* United States Air Force Prime Contract FA8650-10-D-5210
* United States Prime Contract Navy N00173-07-C-2068
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
#include <memory>
#include "GenericExample.h"
#include <QtCore/QDebug>
#include "SIMPLib/FilterParameters/AbstractFilterParametersReader.h"
#include "SIMPLib/FilterParameters/AttributeMatrixCreationFilterParameter.h"
#include "SIMPLib/FilterParameters/AttributeMatrixSelectionFilterParameter.h"
#include "SIMPLib/FilterParameters/AxisAngleFilterParameter.h"
#include "SIMPLib/FilterParameters/BooleanFilterParameter.h"
#include "SIMPLib/FilterParameters/CalculatorFilterParameter.h"
#include "SIMPLib/FilterParameters/ChoiceFilterParameter.h"
#include "SIMPLib/FilterParameters/ComparisonSelectionFilterParameter.h"
#include "SIMPLib/FilterParameters/DataArrayCreationFilterParameter.h"
#include "SIMPLib/FilterParameters/DataArraySelectionFilterParameter.h"
#include "SIMPLib/FilterParameters/DataContainerArrayProxyFilterParameter.h"
#include "SIMPLib/FilterParameters/DataContainerCreationFilterParameter.h"
#include "SIMPLib/FilterParameters/DataContainerSelectionFilterParameter.h"
#include "SIMPLib/FilterParameters/DoubleFilterParameter.h"
#include "SIMPLib/FilterParameters/DynamicChoiceFilterParameter.h"
#include "SIMPLib/FilterParameters/FloatVec3FilterParameter.h"
#include "SIMPLib/FilterParameters/InputFileFilterParameter.h"
#include "SIMPLib/FilterParameters/InputPathFilterParameter.h"
#include "SIMPLib/FilterParameters/IntFilterParameter.h"
#include "SIMPLib/FilterParameters/LinkedBooleanFilterParameter.h"
#include "SIMPLib/FilterParameters/LinkedChoicesFilterParameter.h"
#include "SIMPLib/FilterParameters/MontageSelectionFilterParameter.h"
#include "SIMPLib/FilterParameters/MultiDataArraySelectionFilterParameter.h"
#include "SIMPLib/FilterParameters/OutputFileFilterParameter.h"
#include "SIMPLib/FilterParameters/OutputPathFilterParameter.h"
#include "SIMPLib/FilterParameters/PreflightUpdatedValueFilterParameter.h"
#include "SIMPLib/FilterParameters/RangeFilterParameter.h"
#include "SIMPLib/FilterParameters/SeparatorFilterParameter.h"
#include "SIMPLib/FilterParameters/ShapeTypeSelectionFilterParameter.h"
#include "SIMPLib/FilterParameters/StringFilterParameter.h"
#include "SIMPLib/Utilities/FileSystemPathHelper.h"
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
GenericExample::GenericExample()
: m_StlFilePrefix("Some Prefix")
, m_ShowPrefix(false)
, m_MaxIterations(0)
, m_MisorientationTolerance(0)
, m_PhaseCount(1)
, m_InputFile("/Some/Path/file.cpp")
, m_InputPath("/Some/Path")
, m_OutputFile("/Some/Path/Out.bin")
, m_OutputPath("/Some/Path")
, m_WriteAlignmentShifts(false)
, m_ConversionType(0)
, m_FeatureIdsArrayPath(SIMPL::Defaults::DataContainerName, SIMPL::Defaults::CellAttributeMatrixName, "Garbly Gook")
, m_AttributeMatrixPath(SIMPL::Defaults::DataContainerName, SIMPL::Defaults::NewCellFeatureAttributeMatrixName, "")
, m_DataContainerName(SIMPL::Defaults::StatsGenerator)
, m_CreatedDataArray(SIMPL::Defaults::DataContainerName, SIMPL::Defaults::CellAttributeMatrixName, SIMPL::CellData::EulerColor)
, m_Bool1(false)
, m_Bool2(false)
, m_AlgorithmSelection(0)
, m_DistanceMetric(1)
{
m_Dimensions[0] = 0;
m_Dimensions[1] = 0;
m_Dimensions[2] = 0;
m_Origin[0] = 0.0;
m_Origin[1] = 0.0;
m_Origin[2] = 0.0;
StackFileListInfo flInfo;
flInfo.PaddingDigits = 2;
flInfo.Ordering = 0;
flInfo.StartIndex = 0;
flInfo.EndIndex = 1;
flInfo.InputPath = "";
flInfo.FilePrefix = "prefix_";
flInfo.FileSuffix = "_suffix";
flInfo.FileExtension = ".png";
setInputFileListInfo(flInfo);
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
GenericExample::~GenericExample() = default;
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void GenericExample::setupFilterParameters()
{
FilterParameterVectorType parameters;
/* Place all your option initialization code here */
/* For String input use this code */
parameters.push_back(SIMPL_NEW_STRING_FP("STL Output Prefix", StlFilePrefix, FilterParameter::Category::Parameter, GenericExample));
/* For an output file use this code*/
parameters.push_back(SIMPL_NEW_OUTPUT_FILE_FP("Output File", OutputFile, FilterParameter::Category::Parameter, GenericExample));
/* For an output path use this code*/
parameters.push_back(SIMPL_NEW_OUTPUT_PATH_FP("Output Path", OutputPath, FilterParameter::Category::Parameter, GenericExample));
/* For a simple true/false boolean use this code*/
parameters.push_back(SIMPL_NEW_BOOL_FP("Write Alignment Shift File", WriteAlignmentShifts, FilterParameter::Category::Parameter, GenericExample));
parameters.push_back(SeparatorFilterParameter::Create("Choice Example", FilterParameter::Category::Parameter));
parameters.push_back(SIMPL_NEW_FILELISTINFO_FP("Input File List", InputFileListInfo, FilterParameter::Category::Parameter, GenericExample));
{
std::vector<QString> choices;
choices.push_back("Beta");
choices.push_back("Lognormal");
choices.push_back("Power");
parameters.push_back(SIMPL_NEW_CHOICE_FP("Size Distribution Fit Type", SizeDistributionFitType, FilterParameter::Category::Parameter, GenericExample, choices, false));
}
{
std::vector<QString> choices;
choices.push_back("CellData");
choices.push_back("CellEnsemble");
choices.push_back("FeatureIds");
parameters.push_back(SIMPL_NEW_COMP_SEL_FP("Select Arrays to Threshold", SelectedThresholds, FilterParameter::Category::Parameter, GenericExample, choices, true));
}
/* For presenting a set of choices to the user use this code*/
{
ChoiceFilterParameter::Pointer parameter = ChoiceFilterParameter::New();
parameter->setHumanLabel("Conversion Type");
parameter->setPropertyName("ConversionType");
parameter->setSetterCallback(SIMPL_BIND_SETTER(GenericExample, this, ConversionType));
parameter->setGetterCallback(SIMPL_BIND_GETTER(GenericExample, this, ConversionType));
////parameter->setValueType("unsigned int");
std::vector<QString> choices;
choices.push_back("Degrees To Radians");
choices.push_back("Radians To Degrees");
parameter->setChoices(choices);
parameter->setCategory(FilterParameter::Category::Parameter);
parameters.push_back(parameter);
}
parameters.push_back(SIMPL_NEW_PREFLIGHTUPDATEDVALUE_FP("Estimated Primary Features", EstimatedPrimaryFeatures, FilterParameter::Category::Parameter, GenericExample));
/* Display a group of 3 text boxes to collect 3 integer values */
parameters.push_back(SIMPL_NEW_INT_VEC3_FP("Dimensions (XYZ)", Dimensions, FilterParameter::Category::Parameter, GenericExample));
parameters.push_back(SIMPL_NEW_INT_VEC2_FP("Range (XY)", Range, FilterParameter::Category::Parameter, GenericExample));
parameters.push_back(SIMPL_NEW_RANGE_FP("Initialization Range", InitRange, FilterParameter::Category::Parameter, GenericExample));
parameters.push_back(SIMPL_NEW_SecondO_POLY_FP("Second Order A Coefficients", SecondOrderACoeff, FilterParameter::Category::Parameter, GenericExample, 0));
parameters.push_back(SIMPL_NEW_ThirdO_POLY_FP("Third Order A Coefficients", ThirdOrderACoeff, FilterParameter::Category::Parameter, GenericExample, 1));
parameters.push_back(SIMPL_NEW_SHAPETYPE_SELECTION_FP("Shape Types", ShapeTypeData, FilterParameter::Category::CreatedArray, GenericExample, "PhaseCount", "InputPhaseTypesArrayPath"));
{
DataArraySelectionFilterParameter::RequirementType req;
parameters.push_back(SIMPL_NEW_DA_SELECTION_FP("Feature Ids", FeatureIdsArrayPath, FilterParameter::Category::Parameter, GenericExample, req));
}
{
DataContainerArrayProxy proxy;
parameters.push_back(SIMPL_NEW_DCA_PROXY_FP("Array to Select", DcaProxy, FilterParameter::Category::Parameter, GenericExample, proxy, Qt::Checked));
}
parameters.push_back(SIMPL_NEW_DC_CREATION_FP("Created Data Container", CreatedDataContainer, FilterParameter::Category::CreatedArray, GenericExample));
{
std::vector<QString> linkedProps;
linkedProps.push_back("Bool2");
linkedProps.push_back("Double2");
parameters.push_back(SIMPL_NEW_LINKED_BOOL_FP("Bool1", Bool1, FilterParameter::Category::Parameter, GenericExample, linkedProps));
parameters.push_back(SIMPL_NEW_DOUBLE_FP("Double 2", Double2, FilterParameter::Category::Parameter, GenericExample));
}
parameters.push_back(SIMPL_NEW_DYN_CHOICE_FP("X Coordinate Array", SelectedXCoordArrayName, FilterParameter::Category::CreatedArray, GenericExample, "DataArrayList"));
{
std::vector<QString> linkedProps;
linkedProps.push_back("AttributeMatrixPath");
parameters.push_back(SIMPL_NEW_LINKED_BOOL_FP("Bool2", Bool2, FilterParameter::Category::Parameter, GenericExample, linkedProps));
}
{
AttributeMatrixSelectionFilterParameter::RequirementType req;
parameters.push_back(SIMPL_NEW_AM_SELECTION_FP("Attribute Matrix", AttributeMatrixPath, FilterParameter::Category::Parameter, GenericExample, req));
}
{
AttributeMatrixCreationFilterParameter::RequirementType req;
parameters.push_back(SIMPL_NEW_AM_CREATION_FP("Created Attribute Matrix", CreatedAttributeMatrix, FilterParameter::Category::CreatedArray, GenericExample, req));
}
parameters.push_back(SeparatorFilterParameter::Create("Linked Combo Box Example (1)", FilterParameter::Category::Parameter));
{
LinkedChoicesFilterParameter::Pointer parameter = LinkedChoicesFilterParameter::New();
parameter->setHumanLabel("Select Distance Metric");
parameter->setPropertyName("DistanceMetric");
parameter->setSetterCallback(SIMPL_BIND_SETTER(GenericExample, this, DistanceMetric));
parameter->setGetterCallback(SIMPL_BIND_GETTER(GenericExample, this, DistanceMetric));
parameter->setDefaultValue(getDistanceMetric()); // Just set the first index
std::vector<QString> choices;
choices.push_back("Alt Choice 0");
choices.push_back("Alt Choice 1");
choices.push_back("Alt Choice 2");
parameter->setChoices(choices);
std::vector<QString> linkedProps;
linkedProps.push_back("MaxIterations");
linkedProps.push_back("MisorientationTolerance");
linkedProps.push_back("InputFile");
linkedProps.push_back("InputPath");
parameter->setLinkedProperties(linkedProps);
parameter->setEditable(false);
parameter->setCategory(FilterParameter::Category::Parameter);
parameters.push_back(parameter);
/* For an Integer use this code*/
parameters.push_back(SIMPL_NEW_INTEGER_FP("Max Iterations", MaxIterations, FilterParameter::Category::Parameter, GenericExample, 0)); /* For a Floating point value use this code*/
parameters.push_back(SIMPL_NEW_DOUBLE_FP("Misorientation Tolerance", MisorientationTolerance, FilterParameter::Category::Parameter, GenericExample, 1));
/* For an input file use this code*/
parameters.push_back(SIMPL_NEW_INPUT_FILE_FP("Input File", InputFile, FilterParameter::Category::Parameter, GenericExample, "*.txt", "", 1));
/* For an input path use this code*/
parameters.push_back(SIMPL_NEW_INPUT_PATH_FP("Input Path", InputPath, FilterParameter::Category::Parameter, GenericExample, 2));
}
//------------------
parameters.push_back(SeparatorFilterParameter::Create("Linked Combo Box Example (2)", FilterParameter::Category::Parameter));
/* For presenting a set of choices to the user use this code*/
{
LinkedChoicesFilterParameter::Pointer parameter = LinkedChoicesFilterParameter::New();
parameter->setHumanLabel("Select Algorithm");
parameter->setPropertyName("AlgorithmSelection");
parameter->setSetterCallback(SIMPL_BIND_SETTER(GenericExample, this, AlgorithmSelection));
parameter->setGetterCallback(SIMPL_BIND_GETTER(GenericExample, this, AlgorithmSelection));
parameter->setDefaultValue(getAlgorithmSelection()); // Just set the first index
std::vector<QString> choices;
choices.push_back("Choice 0");
choices.push_back("Choice 1");
choices.push_back("Choice 2");
parameter->setChoices(choices);
std::vector<QString> linkedProps;
linkedProps.push_back("CreatedDataArray");
linkedProps.push_back("Origin");
linkedProps.push_back("CrystalSymmetryRotations");
linkedProps.push_back("DataContainerName");
parameter->setLinkedProperties(linkedProps);
parameter->setEditable(false);
parameter->setCategory(FilterParameter::Category::Parameter);
parameters.push_back(parameter);
{
DataArrayCreationFilterParameter::RequirementType req;
parameters.push_back(SIMPL_NEW_DA_CREATION_FP("Created Data Array", CreatedDataArray, FilterParameter::Category::Parameter, GenericExample, req, 0));
}
/* Display a group of 3 text boxes to collect 3 float values */
parameters.push_back(SIMPL_NEW_FLOAT_VEC3_FP("Origin", Origin, FilterParameter::Category::Parameter, GenericExample, 1));
/* Display the AxisAngleWidget to collect Axis-Angle pairs from the user */
parameters.push_back(SIMPL_NEW_AXISANGLE_FP("Crystal Rotations", CrystalSymmetryRotations, FilterParameter::Category::Parameter, GenericExample, 2));
parameters.push_back(SIMPL_NEW_FourthO_POLY_FP("Fourth Order A Coefficients", FourthOrderACoeff, FilterParameter::Category::Parameter, GenericExample, 2));
{
DataContainerSelectionFilterParameter::RequirementType req;
parameters.push_back(SIMPL_NEW_DC_SELECTION_FP("Data Container", DataContainerName, FilterParameter::Category::Parameter, GenericExample, req, 2));
}
}
QVector<DataArrayPath> paths;
paths.push_back(DataArrayPath("StatsGeneratorDataContainer", "CellEnsembleData", "CrystalStructures"));
paths.push_back(DataArrayPath("StatsGeneratorDataContainer", "CellEnsembleData", "Statistics"));
{
MultiDataArraySelectionFilterParameter::RequirementType req;
parameters.push_back(SIMPL_NEW_MDA_SELECTION_FP("Multi Data Array Test", SelectedMultiArrayPaths, FilterParameter::Category::Parameter, GenericExample, req, 0));
}
parameters.push_back(SeparatorFilterParameter::Create("Montage Selection Example", FilterParameter::Category::Parameter));
parameters.push_back(SIMPL_NEW_MONTAGE_SELECTION_FP("Montage Selection", MontageSelection, FilterParameter::Category::Parameter, GenericExample));
setFilterParameters(parameters);
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void GenericExample::readFilterParameters(QJsonObject& obj)
{
AbstractFilter::readFilterParameters(obj);
setInputFile(obj["InputFile"].toString());
setInputPath(obj["InputPath"].toString());
setOutputFile(obj["OutputFile"].toString());
setOutputPath(obj["OutputPath"].toString());
}
// FP: Check why these values are not connected to a filter parameter!
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void GenericExample::writeFilterParameters(QJsonObject& obj) const
{
AbstractFilter::writeFilterParameters(obj);
obj["InputFile"] = getInputFile();
obj["InputPath"] = getInputPath();
obj["OutputFile"] = getOutputFile();
obj["OutputPath"] = getOutputPath();
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void GenericExample::initialize()
{
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void GenericExample::dataCheck()
{
clearErrorCode();
clearWarningCode();
DataArrayPath tempPath;
FileSystemPathHelper::CheckOutputFile(this, "Output File Name", getOutputFile(), true);
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void computeEulerAngle(float pq, float* eulerAngle)
{
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void GenericExample::execute()
{
clearErrorCode();
clearWarningCode();
// Run the data check to get references to all of our data arrays initialized to the values stored in memory
dataCheck();
if(getErrorCode() < 0)
{
return;
}
qDebug() << "Feature Ids: " << getFeatureIdsArrayPath().getDataArrayName();
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
AbstractFilter::Pointer GenericExample::newFilterInstance(bool copyFilterParameters) const
{
GenericExample::Pointer filter = GenericExample::New();
if(copyFilterParameters)
{
copyFilterParameterInstanceVariables(filter.get());
}
return filter;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
QString GenericExample::getCompiledLibraryName() const
{
return Core::CoreBaseName;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
QString GenericExample::getGroupName() const
{
return SIMPL::FilterGroups::Generic;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
QUuid GenericExample::getUuid() const
{
return QUuid("{b1b9da5c-4ad8-5b61-9615-2a3e17b38970}");
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
QString GenericExample::getSubGroupName() const
{
return "Test";
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
QString GenericExample::getHumanLabel() const
{
return "Generic Example";
}
// -----------------------------------------------------------------------------
GenericExample::Pointer GenericExample::NullPointer()
{
return Pointer(static_cast<Self*>(nullptr));
}
// -----------------------------------------------------------------------------
std::shared_ptr<GenericExample> GenericExample::New()
{
struct make_shared_enabler : public GenericExample
{
};
std::shared_ptr<make_shared_enabler> val = std::make_shared<make_shared_enabler>();
val->setupFilterParameters();
return val;
}
// -----------------------------------------------------------------------------
QString GenericExample::getNameOfClass() const
{
return QString("GenericExample");
}
// -----------------------------------------------------------------------------
QString GenericExample::ClassName()
{
return QString("GenericExample");
}
// -----------------------------------------------------------------------------
void GenericExample::setStlFilePrefix(const QString& value)
{
m_StlFilePrefix = value;
}
// -----------------------------------------------------------------------------
QString GenericExample::getStlFilePrefix() const
{
return m_StlFilePrefix;
}
// -----------------------------------------------------------------------------
void GenericExample::setShowPrefix(bool value)
{
m_ShowPrefix = value;
}
// -----------------------------------------------------------------------------
bool GenericExample::getShowPrefix() const
{
return m_ShowPrefix;
}
// -----------------------------------------------------------------------------
void GenericExample::setMaxIterations(int value)
{
m_MaxIterations = value;
}
// -----------------------------------------------------------------------------
int GenericExample::getMaxIterations() const
{
return m_MaxIterations;
}
// -----------------------------------------------------------------------------
void GenericExample::setSecondOrderACoeff(const Float2ndOrderPolynomial& value)
{
m_SecondOrderACoeff = value;
}
// -----------------------------------------------------------------------------
Float2ndOrderPolynomial GenericExample::getSecondOrderACoeff() const
{
return m_SecondOrderACoeff;
}
// -----------------------------------------------------------------------------
void GenericExample::setThirdOrderACoeff(const Float3rdOrderPoly_t& value)
{
m_ThirdOrderACoeff = value;
}
// -----------------------------------------------------------------------------
Float3rdOrderPoly_t GenericExample::getThirdOrderACoeff() const
{
return m_ThirdOrderACoeff;
}
// -----------------------------------------------------------------------------
void GenericExample::setFourthOrderACoeff(const Float4thOrderPolynomial& value)
{
m_FourthOrderACoeff = value;
}
// -----------------------------------------------------------------------------
Float4thOrderPolynomial GenericExample::getFourthOrderACoeff() const
{
return m_FourthOrderACoeff;
}
// -----------------------------------------------------------------------------
void GenericExample::setMisorientationTolerance(double value)
{
m_MisorientationTolerance = value;
}
// -----------------------------------------------------------------------------
double GenericExample::getMisorientationTolerance() const
{
return m_MisorientationTolerance;
}
// -----------------------------------------------------------------------------
void GenericExample::setInputPhaseTypesArrayPath(const DataArrayPath& value)
{
m_InputPhaseTypesArrayPath = value;
}
// -----------------------------------------------------------------------------
DataArrayPath GenericExample::getInputPhaseTypesArrayPath() const
{
return m_InputPhaseTypesArrayPath;
}
// -----------------------------------------------------------------------------
void GenericExample::setShapeTypeData(const ShapeType::Types& value)
{
m_ShapeTypeData = value;
}
// -----------------------------------------------------------------------------
ShapeType::Types GenericExample::getShapeTypeData() const
{
return m_ShapeTypeData;
}
// -----------------------------------------------------------------------------
void GenericExample::setPhaseCount(int value)
{
m_PhaseCount = value;
}
// -----------------------------------------------------------------------------
int GenericExample::getPhaseCount() const
{
return m_PhaseCount;
}
// -----------------------------------------------------------------------------
void GenericExample::setInitRange(const FPRangePair& value)
{
m_InitRange = value;
}
// -----------------------------------------------------------------------------
FPRangePair GenericExample::getInitRange() const
{
return m_InitRange;
}
// -----------------------------------------------------------------------------
void GenericExample::setEstimatedPrimaryFeatures(const QString& value)
{
m_EstimatedPrimaryFeatures = value;
}
// -----------------------------------------------------------------------------
QString GenericExample::getEstimatedPrimaryFeatures() const
{
return m_EstimatedPrimaryFeatures;
}
// -----------------------------------------------------------------------------
void GenericExample::setInputFile(const QString& value)
{
m_InputFile = value;
}
// -----------------------------------------------------------------------------
QString GenericExample::getInputFile() const
{
return m_InputFile;
}
// -----------------------------------------------------------------------------
void GenericExample::setInputFileListInfo(const StackFileListInfo& value)
{
m_InputFileListInfo = value;
}
// -----------------------------------------------------------------------------
StackFileListInfo GenericExample::getInputFileListInfo() const
{
return m_InputFileListInfo;
}
// -----------------------------------------------------------------------------
void GenericExample::setSelectedXCoordArrayName(const QString& value)
{
m_SelectedXCoordArrayName = value;
}
// -----------------------------------------------------------------------------
QString GenericExample::getSelectedXCoordArrayName() const
{
return m_SelectedXCoordArrayName;
}
// -----------------------------------------------------------------------------
void GenericExample::setDataArrayList(const QStringList& value)
{
m_DataArrayList = value;
}
// -----------------------------------------------------------------------------
QStringList GenericExample::getDataArrayList() const
{
return m_DataArrayList;
}
// -----------------------------------------------------------------------------
void GenericExample::setCreatedDataContainer(const DataArrayPath& value)
{
m_CreatedDataContainer = value;
}
// -----------------------------------------------------------------------------
DataArrayPath GenericExample::getCreatedDataContainer() const
{
return m_CreatedDataContainer;
}
// -----------------------------------------------------------------------------
void GenericExample::setDcaProxy(const DataContainerArrayProxy& value)
{
m_DcaProxy = value;
}
// -----------------------------------------------------------------------------
DataContainerArrayProxy GenericExample::getDcaProxy() const
{
return m_DcaProxy;
}
// -----------------------------------------------------------------------------
void GenericExample::setInputPath(const QString& value)
{
m_InputPath = value;
}
// -----------------------------------------------------------------------------
QString GenericExample::getInputPath() const
{
return m_InputPath;
}
// -----------------------------------------------------------------------------
void GenericExample::setOutputFile(const QString& value)
{
m_OutputFile = value;
}
// -----------------------------------------------------------------------------
QString GenericExample::getOutputFile() const
{
return m_OutputFile;
}
// -----------------------------------------------------------------------------
void GenericExample::setOutputPath(const QString& value)
{
m_OutputPath = value;
}
// -----------------------------------------------------------------------------
QString GenericExample::getOutputPath() const
{
return m_OutputPath;
}
// -----------------------------------------------------------------------------
void GenericExample::setSelectedMultiArrayPaths(const std::vector<DataArrayPath>& value)
{
m_SelectedMultiArrayPaths = value;
}
// -----------------------------------------------------------------------------
std::vector<DataArrayPath> GenericExample::getSelectedMultiArrayPaths() const
{
return m_SelectedMultiArrayPaths;
}
// -----------------------------------------------------------------------------
void GenericExample::setWriteAlignmentShifts(bool value)
{
m_WriteAlignmentShifts = value;
}
// -----------------------------------------------------------------------------
bool GenericExample::getWriteAlignmentShifts() const
{
return m_WriteAlignmentShifts;
}
// -----------------------------------------------------------------------------
void GenericExample::setConversionType(int value)
{
m_ConversionType = value;
}
// -----------------------------------------------------------------------------
int GenericExample::getConversionType() const
{
return m_ConversionType;
}
// -----------------------------------------------------------------------------
void GenericExample::setDimensions(const IntVec3Type& value)
{
m_Dimensions = value;
}
// -----------------------------------------------------------------------------
IntVec3Type GenericExample::getDimensions() const
{
return m_Dimensions;
}
// -----------------------------------------------------------------------------
void GenericExample::setRange(const IntVec2Type& value)
{
m_Range = value;
}
// -----------------------------------------------------------------------------
IntVec2Type GenericExample::getRange() const
{
return m_Range;
}
// -----------------------------------------------------------------------------
void GenericExample::setOrigin(const FloatVec3Type& value)
{
m_Origin = value;
}
// -----------------------------------------------------------------------------
FloatVec3Type GenericExample::getOrigin() const
{
return m_Origin;
}
// -----------------------------------------------------------------------------
void GenericExample::setCrystalSymmetryRotations(const AxisAngleInput& value)
{
m_CrystalSymmetryRotations = value;
}
// -----------------------------------------------------------------------------
AxisAngleInput GenericExample::getCrystalSymmetryRotations() const
{
return m_CrystalSymmetryRotations;
}
// -----------------------------------------------------------------------------
void GenericExample::setFeatureIdsArrayPath(const DataArrayPath& value)
{
m_FeatureIdsArrayPath = value;
}
// -----------------------------------------------------------------------------
DataArrayPath GenericExample::getFeatureIdsArrayPath() const
{
return m_FeatureIdsArrayPath;
}
// -----------------------------------------------------------------------------
void GenericExample::setAttributeMatrixPath(const DataArrayPath& value)
{
m_AttributeMatrixPath = value;
}
// -----------------------------------------------------------------------------
DataArrayPath GenericExample::getAttributeMatrixPath() const
{
return m_AttributeMatrixPath;
}
// -----------------------------------------------------------------------------
void GenericExample::setCreatedAttributeMatrix(const DataArrayPath& value)
{
m_CreatedAttributeMatrix = value;
}
// -----------------------------------------------------------------------------
DataArrayPath GenericExample::getCreatedAttributeMatrix() const
{
return m_CreatedAttributeMatrix;
}
// -----------------------------------------------------------------------------
void GenericExample::setDataContainerName(const DataArrayPath& value)
{
m_DataContainerName = value;
}
// -----------------------------------------------------------------------------
DataArrayPath GenericExample::getDataContainerName() const
{
return m_DataContainerName;
}
// -----------------------------------------------------------------------------
void GenericExample::setSizeDistributionFitType(int value)
{
m_SizeDistributionFitType = value;
}
// -----------------------------------------------------------------------------
int GenericExample::getSizeDistributionFitType() const
{
return m_SizeDistributionFitType;
}
// -----------------------------------------------------------------------------
void GenericExample::setSelectedThresholds(const ComparisonInputs& value)
{
m_SelectedThresholds = value;
}
// -----------------------------------------------------------------------------
ComparisonInputs GenericExample::getSelectedThresholds() const
{
return m_SelectedThresholds;
}
// -----------------------------------------------------------------------------
void GenericExample::setCalcExpression(const QString& value)
{
m_CalcExpression = value;
}
// -----------------------------------------------------------------------------
QString GenericExample::getCalcExpression() const
{
return m_CalcExpression;
}
// -----------------------------------------------------------------------------
void GenericExample::setCreatedDataArray(const DataArrayPath& value)
{
m_CreatedDataArray = value;
}
// -----------------------------------------------------------------------------
DataArrayPath GenericExample::getCreatedDataArray() const
{
return m_CreatedDataArray;
}
// -----------------------------------------------------------------------------
void GenericExample::setBool1(bool value)
{
m_Bool1 = value;
}
// -----------------------------------------------------------------------------
bool GenericExample::getBool1() const
{
return m_Bool1;
}
// -----------------------------------------------------------------------------
void GenericExample::setDouble2(double value)
{
m_Double2 = value;
}
// -----------------------------------------------------------------------------
double GenericExample::getDouble2() const
{
return m_Double2;
}
// -----------------------------------------------------------------------------
void GenericExample::setBool2(bool value)
{
m_Bool2 = value;
}
// -----------------------------------------------------------------------------
bool GenericExample::getBool2() const
{
return m_Bool2;
}
// -----------------------------------------------------------------------------
void GenericExample::setAlgorithmSelection(int value)
{
m_AlgorithmSelection = value;
}
// -----------------------------------------------------------------------------
int GenericExample::getAlgorithmSelection() const
{
return m_AlgorithmSelection;
}
// -----------------------------------------------------------------------------
void GenericExample::setDistanceMetric(int value)
{
m_DistanceMetric = value;
}
// -----------------------------------------------------------------------------
int GenericExample::getDistanceMetric() const
{
return m_DistanceMetric;
}
// -----------------------------------------------------------------------------
void GenericExample::setMontageSelection(const MontageSelection& value)
{
m_MontageSelection = value;
}
// -----------------------------------------------------------------------------
MontageSelection GenericExample::getMontageSelection() const
{
return m_MontageSelection;
}
| 36.675205 | 186 | 0.571588 | [
"shape",
"vector"
] |
4b2d5a67bb7bebfcd11ab6235f51f7bb1733b261 | 4,614 | cpp | C++ | day_21/day_21.cpp | ClementTsang/aoc_2021 | 8661d295f14b10f7208227c2b105131c43c983b6 | [
"Unlicense"
] | null | null | null | day_21/day_21.cpp | ClementTsang/aoc_2021 | 8661d295f14b10f7208227c2b105131c43c983b6 | [
"Unlicense"
] | null | null | null | day_21/day_21.cpp | ClementTsang/aoc_2021 | 8661d295f14b10f7208227c2b105131c43c983b6 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
void solve(string file)
{
fstream new_file;
new_file.open(file, ios::in);
vector<int> init_pos;
string line;
while (getline(new_file, line))
{
init_pos.emplace_back(stoi(line.substr(line.length() - 1)));
}
new_file.close();
// Part 1
{
vector<int> pos = init_pos;
vector<int> score(pos.size());
int num_rolls = 0;
int i = 1;
while (true)
{
num_rolls += 3;
int a = i;
int b = (i + 1 > 100) ? (i + 1 - 100) : (i + 1);
int c = (i + 2 > 100) ? (i + 2 - 100) : (i + 2);
pos[(i + 1) % 2] += a + b + c;
while (pos[(i + 1) % 2] > 10)
{
pos[(i + 1) % 2] -= 10;
}
score[(i + 1) % 2] += pos[(i + 1) % 2];
if (score[(i + 1) % 2] >= 1000)
{
cout << "Part 1: " << score[i % 2] * num_rolls << endl;
break;
}
i += 3;
if (i > 100)
{
i -= 100;
}
}
}
// Part 2
{
vector<int> pos = init_pos;
long long memo[22][22][11][11];
for (int i = 0; i < 22; ++i)
{
for (int j = 0; j < 22; ++j)
{
for (int m = 0; m < 11; ++m)
{
for (int n = 0; n < 11; ++n)
{
memo[i][j][m][n] = 0;
}
}
}
}
memo[0][0][pos[0]][pos[1]] = 1;
for (int i = 0; i < 21; ++i)
{
for (int j = 0; j < 21; ++j)
{
for (int m = 1; m <= 10; ++m)
{
for (int n = 1; n <= 10; ++n)
{
for (int x = 1; x <= 3; ++x)
{
for (int y = 1; y <= 3; ++y)
{
for (int z = 1; z <= 3; ++z)
{
auto pos = (m + x + y + z);
while (pos > 10)
{
pos -= 10;
}
auto min_score = min(21, i + pos);
if (min_score >= 21)
{
memo[min_score][j][pos][n] += memo[i][j][m][n];
}
else
{
for (int a = 1; a <= 3; ++a)
{
for (int b = 1; b <= 3; ++b)
{
for (int c = 1; c <= 3; ++c)
{
auto new_pos = (n + a + b + c);
while (new_pos > 10)
{
new_pos -= 10;
}
auto new_score = min(21, j + new_pos);
memo[min_score][new_score][pos][new_pos] += memo[i][j][m][n];
}
}
}
}
}
}
}
}
}
}
}
long long x = 0;
long long y = 0;
for (int i = 0; i < 21; ++i)
{
for (int m = 1; m <= 10; ++m)
{
for (int n = 1; n <= 10; ++n)
{
x += memo[21][i][m][n];
y += memo[i][21][m][n];
}
}
}
cout << x << ", " << y << endl;
cout << "Part 2: " << max(x, y) << endl;
}
}
int main(int argc, char *argv[])
{
string file = "input.txt";
if (argc == 2)
{
file = argv[1];
}
solve(file);
} | 29.767742 | 113 | 0.228652 | [
"vector"
] |
4b39477565d7278aaede7d88eadd5d18548106e5 | 4,227 | cc | C++ | library/gd_mf_weights.cc | MBNTHUEE404/vowpal_wabbit | 63b182d33295f7110e2b3c5bd25e310b032c5389 | [
"BSD-3-Clause"
] | 1 | 2017-04-07T14:31:51.000Z | 2017-04-07T14:31:51.000Z | library/gd_mf_weights.cc | chhshen/vowpal_wabbit | 7e22b80e918c04e2adf9c33a71e41957e1375ba5 | [
"BSD-3-Clause"
] | null | null | null | library/gd_mf_weights.cc | chhshen/vowpal_wabbit | 7e22b80e918c04e2adf9c33a71e41957e1375ba5 | [
"BSD-3-Clause"
] | 1 | 2021-10-05T20:48:13.000Z | 2021-10-05T20:48:13.000Z | #include <stdio.h>
#include "../vowpalwabbit/parser.h"
#include "../vowpalwabbit/vw.h"
#include <fstream>
#include <iostream>
#include <string.h>
#include <boost/program_options.hpp>
using namespace std;
namespace po = boost::program_options;
int main(int argc, char *argv[])
{
string infile;
string outdir(".");
string vwparams;
po::variables_map vm;
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "produce help message")
("infile,I", po::value<string>(&infile), "input (in vw format) of weights to extract")
("outdir,O", po::value<string>(&outdir), "directory to write model files to (default: .)")
("vwparams", po::value<string>(&vwparams), "vw parameters for model instantiation (-i model.reg -t ...")
;
try {
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
}
catch(exception & e)
{
cout << endl << argv[0] << ": " << e.what() << endl << endl << desc << endl;
exit(2);
}
if (vm.count("help") || infile.empty() || vwparams.empty()) {
cout << "Dumps weights for matrix factorization model (gd_mf)." << endl;
cout << "The constant will be written to <outdir>/constant." << endl;
cout << "Linear and quadratic weights corresponding to the input features will be " << endl;
cout << "written to <outdir>/<ns>.linear and <outdir>/<ns>.quadratic,respectively." << endl;
cout << endl;
cout << desc << "\n";
cout << "Example usage:" << endl;
cout << " Extract weights for user 42 and item 7 under randomly initialized rank 10 model:" << endl;
cout << " echo '|u 42 |i 7' | ./gd_mf_weights -I /dev/stdin --vwparams '-q ui --rank 10'" << endl;
return 1;
}
// initialize model
vw* model = VW::initialize(vwparams);
model->audit = true;
// global model params
unsigned char left_ns = model->pairs[0][0];
unsigned char right_ns = model->pairs[0][1];
weight* weights = model->reg.weight_vector;
size_t mask = model->reg.weight_mask;
// const char *filename = argv[0];
FILE* file = fopen(infile.c_str(), "r");
char* line = NULL;
size_t len = 0;
ssize_t read;
// output files
ofstream constant((outdir + string("/") + string("constant")).c_str()),
left_linear((outdir + string("/") + string(1, left_ns) + string(".linear")).c_str()),
left_quadratic((outdir + string("/") + string(1, left_ns) + string(".quadratic")).c_str()),
right_linear((outdir + string("/") + string(1, right_ns) + string(".linear")).c_str()),
right_quadratic((outdir + string("/") + string(1, right_ns) + string(".quadratic")).c_str());
example *ec = NULL;
while ((read = getline(&line, &len, file)) != -1)
{
line[strlen(line)-1] = 0; // chop
ec = VW::read_example(*model, line);
// write out features for left namespace
if (ec->audit_features[left_ns].begin != ec->audit_features[left_ns].end)
{
for (audit_data *f = ec->audit_features[left_ns].begin; f != ec->audit_features[left_ns].end; f++)
{
left_linear << f->feature << '\t' << weights[f->weight_index & mask];
left_quadratic << f->feature;
for (size_t k = 1; k <= model->rank; k++)
left_quadratic << '\t' << weights[(f->weight_index + k) & mask];
}
left_linear << endl;
left_quadratic << endl;
}
// write out features for right namespace
if (ec->audit_features[right_ns].begin != ec->audit_features[right_ns].end)
{
for (audit_data *f = ec->audit_features[right_ns].begin; f != ec->audit_features[right_ns].end; f++)
{
right_linear << f->feature << '\t' << weights[f->weight_index & mask];
right_quadratic << f->feature;
for (size_t k = 1; k <= model->rank; k++)
right_quadratic << '\t' << weights[(f->weight_index + k + model->rank) & mask];
}
right_linear << endl;
right_quadratic << endl;
}
VW::finish_example(*model, ec);
}
// write constant
feature* f = ec->atomics[constant_namespace].begin;
constant << weights[f->weight_index & mask] << endl;
// clean up
VW::finish(*model);
fclose(file);
}
| 34.647541 | 109 | 0.59948 | [
"model"
] |
4b3adc568b29badf7daa8e9ade37ea20c8560e74 | 1,470 | cpp | C++ | Binomial vs Fibonacci/main.cpp | concatto/complexidade | 1a31d68cc6b30ab1ce18d8520b5eae03bb3e1cc8 | [
"MIT"
] | null | null | null | Binomial vs Fibonacci/main.cpp | concatto/complexidade | 1a31d68cc6b30ab1ce18d8520b5eae03bb3e1cc8 | [
"MIT"
] | null | null | null | Binomial vs Fibonacci/main.cpp | concatto/complexidade | 1a31d68cc6b30ab1ce18d8520b5eae03bb3e1cc8 | [
"MIT"
] | null | null | null | #include <iostream>
#include <chrono>
#include <vector>
#include <unordered_map>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <utility>
#include <boost/heap/fibonacci_heap.hpp>
#include <boost/heap/binomial_heap.hpp>
using namespace std::chrono;
using namespace boost::heap;
using uint_pair = std::pair<unsigned int, unsigned int>;
template <class Heap>
uint_pair test_with_elements(int n) {
Heap heap;
auto start = high_resolution_clock::now();
for (int i = 0; i < n; i++) {
heap.push(std::rand());
}
auto end = high_resolution_clock::now();
unsigned int full = duration_cast<nanoseconds>(end - start).count();
start = high_resolution_clock::now();
heap.push(std::rand());
end = high_resolution_clock::now();
unsigned int last = duration_cast<nanoseconds>(end - start).count();
return {full, last};
}
template <class Heap>
void run_experiment(std::ostream& output, const std::string& heap_name) {
for (int i = 0; i < 1000; i++) {
int n = 100 * (i + 1);
for (int j = 0; j < 30; j++) {
uint_pair result = test_with_elements<Heap>(n);
output << heap_name << "," << n << "," << result.first << "," << result.second << "\n";
}
}
}
int main(int argc, char** argv) {
std::srand(std::time(nullptr));
std::ofstream output("experiments.csv");
output << "heap,n,full,last\n";
run_experiment<binomial_heap<int>>(output, "binomial");
run_experiment<fibonacci_heap<int>>(output, "fibonacci");
}
| 22.96875 | 90 | 0.672109 | [
"vector"
] |
4b3f9b70f59cfb9182b012e167eb943fd8a467f9 | 10,746 | cpp | C++ | compiler/optimizations/removeUnnecessaryAutoCopyCalls.cpp | krishnakeshav/chapel | c7840d76944cfb1b63878e51e81138d1a0c808cf | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | compiler/optimizations/removeUnnecessaryAutoCopyCalls.cpp | krishnakeshav/chapel | c7840d76944cfb1b63878e51e81138d1a0c808cf | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | compiler/optimizations/removeUnnecessaryAutoCopyCalls.cpp | krishnakeshav/chapel | c7840d76944cfb1b63878e51e81138d1a0c808cf | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
* Copyright 2004-2017 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is 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 "optimizations.h"
#include "astutil.h"
#include "bb.h"
#include "expr.h"
#include "passes.h"
#include "stlUtil.h"
#include "stmt.h"
//
// Tracking machinery
//
// The AutoTrack class is used to track autoCopy and autoDestroy calls within a
// basic block, and also to record sets of variables that share ownership of a
// specific object. The meaning of shared ownership is that even though each
// such variable has its own storage and a separate copy of the data, the record
// object has only been "created" once (through a call to chpl__autoCopy) and
// therefore only needs to be "deleted" once (through a call to
// chpl__autoDestroy).
//
// Because they are all mutual aliases, the variables which share ownership of a
// record object are members of an equivalence class. Each equivalence class is
// represented by a root (containing identifying information) and a linked list
// of members.
class AutoTrack {
public:
AutoTrack();
~AutoTrack();
public:
void move(CallExpr* call); // Track a move primitive.
void autoCopy(CallExpr* call); // Track an autoCopy call.
void autoDestroy(CallExpr* call); // Track an autoDestroy call.
bool update(); // Update the current block using tracking info.
private:
struct Link {
CallExpr* call;
Link* next;
};
struct Root {
Symbol* var;
int refCnt;
int destCnt;
Link* copyHead;
Link* destHead;
Root* next;
};
private:
void updateAutoCopy(CallExpr* call);
void updateAutoDestroy(CallExpr* call);
Root* getRoot(Symbol* var);
void insertLink(Link** head, CallExpr* call);
private:
bool confPart;
Root* rootHead;
Map<Symbol*, Root*> rootMap;
};
AutoTrack::AutoTrack() {
confPart = true;
rootHead = NULL;
}
AutoTrack::~AutoTrack() {
Root* r = rootHead;
// For each root.
while (r != NULL) {
Root* rnext = r->next;
// Clean out the list of autoCopies.
Link* p = r->copyHead;
while (p != NULL) {
Link* pnext = p->next;
delete p;
p = pnext;
}
// Clean out the list of autoDestroys.
p = r->destHead;
while (p != NULL) {
Link* pnext = p->next;
delete p;
p = pnext;
}
delete r; // Delete the root.
r = rnext;
}
}
void AutoTrack::move(CallExpr* call) {
SymExpr* lhs = toSymExpr(call->get(1));
SymExpr* rhs = toSymExpr(call->get(2));
INT_ASSERT(lhs);
INT_ASSERT(rhs);
Root* r = getRoot(rhs->symbol());
rootMap.put(lhs->symbol(), r);
}
void AutoTrack::autoCopy(CallExpr* call) {
SymExpr* lhs = toSymExpr(call->get(1));
CallExpr* rhs = toCallExpr(call->get(2));
INT_ASSERT(lhs);
INT_ASSERT(rhs);
SymExpr* se = toSymExpr(rhs->get(1));
INT_ASSERT(se);
Root* r = getRoot(se->symbol());
rootMap.put(lhs->symbol(), r);
insertLink(&r->copyHead, call);
if (r->refCnt >= 0)
r->refCnt++;
}
void AutoTrack::autoDestroy(CallExpr* call) {
SymExpr* se = toSymExpr(call->get(1));
INT_ASSERT(se);
Root* r = getRoot(se->symbol());
insertLink(&r->destHead, call);
if (r->refCnt >= 0)
r->refCnt--;
r->destCnt++;
}
// Remove only as many autoCopy calls as we have matching autoDestroys.
// Then remove those autodestroys.
bool AutoTrack::update() {
bool changed = false;
for (Root* r = rootHead; r != NULL; r = r->next) {
if (r->refCnt < 0 || (!confPart && r->refCnt > 0))
continue;
int destCnt = r->destCnt;
if (destCnt <= 0)
continue;
for (Link* p = r->copyHead; p != NULL; p = p->next) {
if (destCnt <= 0)
break;
updateAutoCopy(p->call);
destCnt--;
}
for (Link* p = r->destHead; p != NULL; p = p->next)
updateAutoDestroy(p->call);
changed = true;
}
return changed;
}
void AutoTrack::updateAutoCopy(CallExpr* call) {
//fprintf(stderr, "@@@ updateAutoCopy %d\n", call->id);
CallExpr* rhs = toCallExpr(call->get(2));
Type* lhsType = call->get(1)->typeInfo();
Type* rhsType = rhs->get(1)->typeInfo();
SET_LINENO(call);
if (lhsType->getValType() == rhsType) {
rhs->replace(rhs->get(1)->remove());
} else if (lhsType->getRefType() == rhsType) {
rhs->replace(new CallExpr(PRIM_DEREF, rhs->get(1)->remove()));
} else {
INT_ASSERT("Type mismatch in updateAutoCopy");
}
}
void AutoTrack::updateAutoDestroy(CallExpr* call) {
//fprintf(stderr, "@@@ updateAutoDestroy %d\n", call->id);
call->remove();
}
// Gets an existing root for the given symbol, or creates a new one.
AutoTrack::Root* AutoTrack::getRoot(Symbol* var) {
Root* r = rootMap.get(var);
if (r != NULL)
return r;
r = new Root();
r->var = var;
r->refCnt = 0;
r->destCnt = 0;
r->copyHead = NULL;
r->destHead = NULL;
r->next = rootHead;
rootHead = r;
rootMap.put(var, r);
return r;
}
void AutoTrack::insertLink(Link** head, CallExpr* call) {
Link* p = new Link();
p->call = call;
p->next = *head;
*head = p;
}
//
// Remove autoCopy (and matching autoDestroy calls) that are
// unnecessary within a function
//
static void removeUnnecessaryAutoCopyCalls(FnSymbol* fn) {
BasicBlock::buildBasicBlocks(fn);
bool changed = false;
// Scan each basic block in turn.
for_vector(BasicBlock, bb, *fn->basicBlocks) {
// We only match up and remove autoCopy/autoDestroy pairs within one basic block.
AutoTrack track;
// Scan the expressions in this basic block.
for_vector(Expr, expr, bb->exprs) {
if (CallExpr* call = toCallExpr(expr)) {
// If it is a call expression, then we want to see if it is either an
// autocopy call or a straight copy of one variable to another. Both of
// these have a 'move' primitive as the outer call.
if (isMoveOrAssign(call)) {
// If the RHS is a SymExpr, then this is a straight move. Record the alias.
if (toSymExpr(call->get(2)))
track.move(call);
// If the RHS is a CallExpr, then check to see if it is an autoCopy call.
if (CallExpr* rhs = toCallExpr(call->get(2))) {
if (FnSymbol* ac = rhs->isResolved()) {
if (ac->hasFlag(FLAG_REMOVABLE_AUTO_COPY)) {
// Yup. So track the autoCopy
INT_ASSERT(rhs->argList.head);
SymExpr* se = toSymExpr(call->get(1));
// Do not remove necessary autoCopies!
if (!se->symbol()->hasFlag(FLAG_NECESSARY_AUTO_COPY))
track.autoCopy(call);
}
}
}
}
// Check if the call is a removable autoDestroy call.
if (FnSymbol* ad = call->isResolved()) {
if (ad->hasFlag(FLAG_REMOVABLE_AUTO_DESTROY)) {
INT_ASSERT(call->argList.head);
SymExpr* se = toSymExpr(call->get(1));
// Global/module-level symbols have lifetimes larger than function
// scope, so we ignore them here.
if (se->symbol()->defPoint->parentSymbol == fn)
track.autoDestroy(call);
}
}
}
}
// Now, look for and delete autoCopy/autoDestroy pairs, and set "changed" if
// any were removed.
if (track.update())
changed = true;
}
#if DEBUG_CP < 2 // That is, disabled if DEBUG_CP >= 2
// Re-run some other optimizations if progress was made.
if (changed) {
if (!fNoCopyPropagation) {
localCopyPropagation(fn);
if (!fNoDeadCodeElimination)
deadVariableElimination(fn);
globalCopyPropagation(fn);
singleAssignmentRefPropagation(fn);
}
if (!fNoDeadCodeElimination)
deadCodeElimination(fn);
}
#endif
}
// We can remove the calls to chpl__initCopy (should actually be chpl__autoCopy)
// and corresponding calls to chpl__autoDestroy for Plain-Old-Data (POD) types.
// See isPOD() and propagateNotPOD().
static void removePODinitDestroy()
{
compute_call_sites();
forv_Vec(FnSymbol, fn, gFnSymbols) {
if (fn->hasFlag(FLAG_INIT_COPY_FN) || fn->hasFlag(FLAG_AUTO_COPY_FN))
{
if (fn->retType == dtVoid)
// initCopy(void) and autoCopy(void) will have had their void
// argument removed
continue;
// We expect both initCopy and autoCopy functions to have one argument
// whose type is the same as the return type.
INT_ASSERT(fn->numFormals() >= 1);
if (fn->getFormal(1)->type != fn->retType)
// In some cases, the autoCopy function has a different return type than
// its argument type.
// In that case, the replace() below won't work because it will cause a
// type mismatch at the call sites, so we just punt.
continue;
if (isPOD(fn->retType)) {
forv_Vec(CallExpr, call, *fn->calledBy) {
Expr* actual = call->get(1);
ArgSymbol* arg = actual_to_formal(actual);
if (arg)
{
arg->removeFlag(FLAG_INSERT_AUTO_DESTROY);
arg->removeFlag(FLAG_INSERT_AUTO_DESTROY_FOR_EXPLICIT_NEW);
}
else
INT_FATAL(arg, "Expected autoCopy argument to be a SymExpr.");
// Bridge out the autoCopy call.
Type* lhsType = NULL;
Type* rhsType = actual->typeInfo();
CallExpr* move = toCallExpr(call->parentExpr);
INT_ASSERT(isMoveOrAssign(move));
lhsType = move->get(1)->typeInfo();
SET_LINENO(call);
if (lhsType->getValType() != rhsType->getValType()) {
INT_FATAL(actual, "Type mismatch in updateAutoCopy");
} else {
call->replace(actual->remove());
}
}
}
}
}
}
void removeUnnecessaryAutoCopyCalls() {
if (fNoRemoveCopyCalls)
return;
//
// remove pointless initCopy calls, e.g., initCopy calls on records of
// primitive types
//
removePODinitDestroy();
return; // TODO -- delete more in removeUnnecessaryAutoCopyCalls.
//
// remove matched pairs of autoCopy and autoDestroy calls marked with the
// removable auto destroy pragma
//
forv_Vec(FnSymbol, fn, gFnSymbols) {
removeUnnecessaryAutoCopyCalls(fn);
}
}
| 29.521978 | 85 | 0.628978 | [
"object"
] |
4b4257d90f8ad267e4549dc88b4df373c4173a03 | 788 | cpp | C++ | src/xr_3da/xrGame/object_action_switch.cpp | ixray-team/ixray-b2945 | ad5ef375994ee9cd790c4144891e9f00e7efe565 | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:19.000Z | 2022-03-26T17:00:19.000Z | src/xr_3da/xrGame/object_action_switch.cpp | ixray-team/ixray-b2945 | ad5ef375994ee9cd790c4144891e9f00e7efe565 | [
"Linux-OpenIB"
] | null | null | null | src/xr_3da/xrGame/object_action_switch.cpp | ixray-team/ixray-b2945 | ad5ef375994ee9cd790c4144891e9f00e7efe565 | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:21.000Z | 2022-03-26T17:00:21.000Z | ////////////////////////////////////////////////////////////////////////////
// Module : object_action_switch.cpp
// Created : 14.03.2004
// Modified : 14.03.2004
// Author : Dmitriy Iassenev
// Description : Object switch command
////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "object_action_switch.h"
CObjectActionSwitch::CObjectActionSwitch (CInventoryItem *item, CAI_Stalker *owner, u32 type, LPCSTR action_name) :
inherited (item,owner,action_name),
m_type (type)
{
}
void CObjectActionSwitch::initialize ()
{
inherited::initialize ();
}
void CObjectActionSwitch::execute ()
{
inherited::execute ();
}
void CObjectActionSwitch::finalize ()
{
inherited::finalize ();
}
| 24.625 | 116 | 0.550761 | [
"object"
] |
4b453e236c0d85b50b2f880a10725533765fd52b | 5,173 | hpp | C++ | src/core/net/dhcp6_client.hpp | open-degu/openthread | 882e7074b5986027b85cb4f3ba1dc563a11ca013 | [
"BSD-3-Clause"
] | null | null | null | src/core/net/dhcp6_client.hpp | open-degu/openthread | 882e7074b5986027b85cb4f3ba1dc563a11ca013 | [
"BSD-3-Clause"
] | null | null | null | src/core/net/dhcp6_client.hpp | open-degu/openthread | 882e7074b5986027b85cb4f3ba1dc563a11ca013 | [
"BSD-3-Clause"
] | 1 | 2019-11-26T06:13:59.000Z | 2019-11-26T06:13:59.000Z | /*
* Copyright (c) 2016, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* This file includes definitions for DHCPv6 Client.
*/
#ifndef DHCP6_CLIENT_HPP_
#define DHCP6_CLIENT_HPP_
#include "openthread-core-config.h"
#include "common/locator.hpp"
#include "common/message.hpp"
#include "common/timer.hpp"
#include "common/trickle_timer.hpp"
#include "mac/mac.hpp"
#include "mac/mac_frame.hpp"
#include "net/dhcp6.hpp"
#include "net/udp6.hpp"
namespace ot {
namespace Dhcp6 {
/**
* @addtogroup core-dhcp6
*
* @brief
* This module includes definitions for DHCPv6 Client.
*
* @{
*
*/
/**
* Some constants
*
*/
enum
{
kTrickleTimerImin = 1,
kTrickleTimerImax = 120,
};
/**
* Status of IdentityAssociation
*
*/
enum IaStatus
{
kIaStatusInvalid,
kIaStatusSolicit,
kIaStatusSoliciting,
kIaStatusSolicitReplied,
};
/**
* This class implements IdentityAssociation.
*
*/
struct IdentityAssociation
{
otNetifAddress mNetifAddress; ///< the NetifAddress
uint32_t mPreferredLifetime; ///< The preferred lifetime.
uint32_t mValidLifetime; ///< The valid lifetime.
uint16_t mPrefixAgentRloc; ///< Rloc of Prefix Agent
uint8_t mStatus; ///< Status of IdentityAssociation
};
/**
* This class implements DHCPv6 Client.
*
*/
class Dhcp6Client : public InstanceLocator
{
public:
/**
* This constructor initializes the object.
*
* @param[in] aInstance A reference to the OpenThread instance.
*
*/
explicit Dhcp6Client(Instance &aInstance);
/**
* This method update addresses that shall be automatically created using DHCP.
*
*
*/
void UpdateAddresses(void);
private:
void Start(void);
void Stop(void);
static bool MatchNetifAddressWithPrefix(const otNetifAddress &aNetifAddress, const otIp6Prefix &aIp6Prefix);
otError Solicit(uint16_t aRloc16);
void AddIdentityAssociation(uint16_t aRloc16, otIp6Prefix &aIp6Prefix);
void RemoveIdentityAssociation(uint16_t aRloc16, otIp6Prefix &aIp6Prefix);
bool ProcessNextIdentityAssociation(void);
otError AppendHeader(Message &aMessage);
otError AppendClientIdentifier(Message &aMessage);
otError AppendIaNa(Message &aMessage, uint16_t aRloc16);
otError AppendIaAddress(Message &aMessage, uint16_t aRloc16);
otError AppendElapsedTime(Message &aMessage);
otError AppendRapidCommit(Message &aMessage);
static void HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo);
void HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo);
void ProcessReply(Message &aMessage);
uint16_t FindOption(Message &aMessage, uint16_t aOffset, uint16_t aLength, Code aCode);
otError ProcessServerIdentifier(Message &aMessage, uint16_t aOffset);
otError ProcessClientIdentifier(Message &aMessage, uint16_t aOffset);
otError ProcessIaNa(Message &aMessage, uint16_t aOffset);
otError ProcessStatusCode(Message &aMessage, uint16_t aOffset);
otError ProcessIaAddress(Message &aMessage, uint16_t aOffset);
static bool HandleTrickleTimer(TrickleTimer &aTrickleTimer);
bool HandleTrickleTimer(void);
Ip6::UdpSocket mSocket;
TrickleTimer mTrickleTimer;
uint8_t mTransactionId[kTransactionIdSize];
TimeMilli mStartTime;
IdentityAssociation mIdentityAssociations[OPENTHREAD_CONFIG_DHCP6_CLIENT_NUM_PREFIXES];
IdentityAssociation *mIdentityAssociationCurrent;
};
} // namespace Dhcp6
} // namespace ot
#endif // DHCP6_CLIENT_HPP_
| 30.791667 | 112 | 0.731877 | [
"object"
] |
4b47435c8cf31ffa1a99b48ac2bb1b198550f35e | 2,015 | cpp | C++ | 57.cpp | zfang399/LeetCode-Problems | 4cb25718a3d1361569f5ee6fde7b4a9a4fde2186 | [
"MIT"
] | 8 | 2018-10-31T11:00:19.000Z | 2020-07-31T05:25:06.000Z | 57.cpp | zfang399/LeetCode-Problems | 4cb25718a3d1361569f5ee6fde7b4a9a4fde2186 | [
"MIT"
] | null | null | null | 57.cpp | zfang399/LeetCode-Problems | 4cb25718a3d1361569f5ee6fde7b4a9a4fde2186 | [
"MIT"
] | 2 | 2018-05-31T11:29:22.000Z | 2019-09-11T06:34:40.000Z | /**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
class Solution {
public:
vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
vector<Interval> ans;
if(newInterval.start>newInterval.end){
for(int i=0;i<intervals.size();i++) ans.push_back(intervals[i]);
return ans;
}
if(intervals.size()==0){
ans.push_back(newInterval);
return ans;
}
bool inserted=false;
for(int i=0;i<intervals.size();i++){
if(inserted){
ans.push_back(intervals[i]);
continue;
}
if(intervals[i].end<newInterval.start){
ans.push_back(intervals[i]);
}else if(intervals[i].end==newInterval.start){
newInterval.start=min(newInterval.start,intervals[i].start);
}else{
if(intervals[i].start>newInterval.end){
ans.push_back(newInterval);
ans.push_back(intervals[i]);
inserted=true;
continue;
}else if(intervals[i].start==newInterval.end){
newInterval.end=intervals[i].end;
ans.push_back(newInterval);
inserted=true;
continue;
}
if(intervals[i].end>=newInterval.end){
newInterval.end=max(newInterval.end,intervals[i].end);
newInterval.start=min(newInterval.start,intervals[i].start);
ans.push_back(newInterval);
inserted=true;
}else{
newInterval.start=min(newInterval.start,intervals[i].start);
}
}
}
if(!inserted) ans.push_back(newInterval);
return ans;
}
};
| 34.741379 | 80 | 0.498263 | [
"vector"
] |
4b4a2b7f51d21acb061e8b42b47947dafcf5022f | 3,834 | cpp | C++ | src/ECS/Systems/Network/InitializePlayerSystem.cpp | novuscore/NovusCore-Service | 68384dfa15e66a3c9e4be576b671f6ed9d15be23 | [
"MIT"
] | 2 | 2020-03-16T09:52:03.000Z | 2021-09-03T20:05:16.000Z | src/ECS/Systems/Network/InitializePlayerSystem.cpp | novuscore/NovusCore-Service | 68384dfa15e66a3c9e4be576b671f6ed9d15be23 | [
"MIT"
] | null | null | null | src/ECS/Systems/Network/InitializePlayerSystem.cpp | novuscore/NovusCore-Service | 68384dfa15e66a3c9e4be576b671f6ed9d15be23 | [
"MIT"
] | 4 | 2020-03-16T09:52:04.000Z | 2021-12-20T22:16:05.000Z | #include "InitializePlayerSystem.h"
#include <memory>
#include <entt.hpp>
#include <tracy/Tracy.hpp>
#include <Utils/ByteBuffer.h>
#include <Networking/NetStructures.h>
#include "../../../Utils/EntityUtils.h"
#include "../../Components/Transform.h"
#include "../../Components/GameEntityInfo.h"
#include "../../Components/Network/ConnectionComponent.h"
#include "../../Components/Network/InitializedConnection.h"
#include "../../Components/InitializeWorldState.h"
#include "../../Components/JustSpawned.h"
void InitializePlayerSystem::Update(entt::registry& registry)
{
// This is a very naive approach, primarily due to the fact that we are currently limited to just sending 8192 bytes at a time.
std::shared_ptr<Bytebuffer> buffer = Bytebuffer::Borrow<8192>();
std::shared_ptr<Bytebuffer> initialConnectionBuffer = Bytebuffer::Borrow<8192>();
auto initialConnectionView = registry.view<ConnectionComponent, InitializeWorldState, JustSpawned>();
auto connectionView = registry.view<ConnectionComponent, InitializedConnection>();
if (initialConnectionView.size_hint() == 0 && connectionView.size_hint() == 0)
return;
auto newEntityView = registry.view<GameEntityInfo, Transform, JustSpawned>();
newEntityView.each([®istry, &buffer](const entt::entity& entity, GameEntityInfo& gameEntityInfo, Transform& transform)
{
buffer->Put(Opcode::SMSG_CREATE_ENTITY);
size_t sizeOffset = buffer->writtenData;
buffer->PutU16(0);
u16 payloadSize = EntityUtils::Serialize(entity, gameEntityInfo, transform, buffer);
buffer->Put(payloadSize, sizeOffset);
transform.isDirty = false;
});
auto entitiesView = registry.view<GameEntityInfo, Transform>();
entitiesView.each([®istry, &initialConnectionView, &connectionView, &buffer, &initialConnectionBuffer](const entt::entity& entity, GameEntityInfo& gameEntityInfo, Transform& transform)
{
if (initialConnectionView.size_hint())
{
initialConnectionBuffer->Put(Opcode::SMSG_CREATE_ENTITY);
size_t sizeOffset = initialConnectionBuffer->writtenData;
initialConnectionBuffer->PutU16(0);
u16 payloadSize = EntityUtils::Serialize(entity, gameEntityInfo, transform, initialConnectionBuffer);
initialConnectionBuffer->Put(payloadSize, sizeOffset);
}
if (connectionView.size_hint())
{
if (transform.isDirty)
{
buffer->Put(Opcode::SMSG_UPDATE_ENTITY);
buffer->PutU16(40);
buffer->PutEnttId(entity);
buffer->Put(transform.position);
buffer->Put(transform.rotation);
buffer->Put(transform.scale);
transform.isDirty = false;
}
}
});
if (connectionView.size_hint() && buffer->writtenData)
{
connectionView.each([®istry, &buffer](const entt::entity& entity, ConnectionComponent& connectionComponent)
{
connectionComponent.AddPacket(buffer, PacketPriority::HIGH);
});
}
if (initialConnectionView.size_hint() && initialConnectionBuffer->writtenData)
{
initialConnectionView.each([®istry, &initialConnectionBuffer](const entt::entity& entity, ConnectionComponent& connectionComponent)
{
connectionComponent.AddPacket(initialConnectionBuffer, PacketPriority::HIGH);
});
registry.insert<InitializedConnection>(initialConnectionView.begin(), initialConnectionView.end());
registry.remove<InitializeWorldState, JustSpawned>(initialConnectionView.begin(), initialConnectionView.end());
}
if (newEntityView.size_hint())
{
registry.remove<JustSpawned>(newEntityView.begin(), newEntityView.end());
}
} | 40.787234 | 191 | 0.684142 | [
"transform"
] |
4b4a584bd85abed1f110eaddb378f7bf4a2e7d7c | 1,130 | hpp | C++ | modele.hpp | TheoLeCalvar/MineGl | 42b356be4e12c428a8b1f8dbfbec9d9966606567 | [
"Unlicense"
] | null | null | null | modele.hpp | TheoLeCalvar/MineGl | 42b356be4e12c428a8b1f8dbfbec9d9966606567 | [
"Unlicense"
] | null | null | null | modele.hpp | TheoLeCalvar/MineGl | 42b356be4e12c428a8b1f8dbfbec9d9966606567 | [
"Unlicense"
] | null | null | null | #ifndef MODEL_H
#define MODEL_H
#include <vector>
#include <map>
#include "material.hpp"
class Groupe;
class Modele
{
private:
std::map<const std::string, Groupe *> _groupes;
std::map<const std::string, Material *> _materials;
std::vector<GLfloat> _vertices;
std::vector<GLfloat> _normals;
std::vector<GLfloat> _texCoord;
bool _useTex;
public:
Modele(const std::string & file);
~Modele();
virtual void draw();
void useTex(bool b);
bool useTex(){return _useTex;}
private:
void loadMtl(const std::string & path);
void parse(const std::string & file);
};
class Groupe
{
private:
std::vector<GLfloat> *_vertices;
std::vector<GLfloat> *_normals;
std::vector<GLfloat> *_texCoord;
std::vector<unsigned int> _faces;
Material * _mat;
GLuint _callId;
bool _useTex;
public:
Groupe(std::vector<GLfloat> * vertices, std::vector<GLfloat> * normals, std::vector<GLfloat> * texCoord);
~Groupe();
void setMaterial(Material * m);
void addFace(unsigned int v, unsigned int n, unsigned int t);
void draw();
void useTex(bool b){_useTex = b;}
bool useTex(){return _useTex;}
};
#endif
| 16.376812 | 106 | 0.688496 | [
"vector"
] |
4b4de220f02bdbdde940d851d36d04781f3b4192 | 390 | hpp | C++ | projects/engine/src/rendering/opengl/assets/glmodel.hpp | zCubed3/Aurora | f1e4ba2166a2d674fc20939111a03a1adccf4088 | [
"MIT"
] | null | null | null | projects/engine/src/rendering/opengl/assets/glmodel.hpp | zCubed3/Aurora | f1e4ba2166a2d674fc20939111a03a1adccf4088 | [
"MIT"
] | 3 | 2021-11-06T19:36:42.000Z | 2021-11-06T19:37:35.000Z | projects/engine/src/rendering/opengl/assets/glmodel.hpp | zCubed3/Manta | f1e4ba2166a2d674fc20939111a03a1adccf4088 | [
"MIT"
] | null | null | null | #ifndef MANTA_GLMODEL_H
#define MANTA_GLMODEL_H
#include <assets/model.hpp>
typedef unsigned int uint;
class GLVertexBuffer : public VertexBuffer {
public:
void Populate(Model *model);
void Draw(MEngine *engine, AActor *pActor, Material *material);
~GLVertexBuffer();
protected:
uint vao, vbo, ibo; // IBO stands for "index buffer object"
uint indices;
};
#endif
| 17.727273 | 67 | 0.717949 | [
"object",
"model"
] |
4b4ecf85de991aa70584c27991c5d54f745d6a06 | 16,946 | cxx | C++ | Libs/MRML/Widgets/qMRMLTableView.cxx | TheInterventionCentre/NorMIT-Plan-App | 765ed9a5dccc1cc134b65ccabe93fc132baeb2ea | [
"MIT"
] | null | null | null | Libs/MRML/Widgets/qMRMLTableView.cxx | TheInterventionCentre/NorMIT-Plan-App | 765ed9a5dccc1cc134b65ccabe93fc132baeb2ea | [
"MIT"
] | null | null | null | Libs/MRML/Widgets/qMRMLTableView.cxx | TheInterventionCentre/NorMIT-Plan-App | 765ed9a5dccc1cc134b65ccabe93fc132baeb2ea | [
"MIT"
] | null | null | null | /*==============================================================================
Program: 3D Slicer
Portions (c) Copyright 2015 Brigham and Women's Hospital (BWH) All Rights Reserved.
See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.
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.
This file was originally developed by Andras Lasso (PerkLab, Queen's
University) and Kevin Wang (Princess Margaret Hospital, Toronto) and was
supported through OCAIRO and the Applied Cancer Research Unit program of
Cancer Care Ontario.
==============================================================================*/
// QT includes
#include <QApplication>
#include <QClipboard>
#include <QDebug>
#include <QHeaderView>
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QSortFilterProxyModel>
#include <QToolButton>
// CTK includes
#include <ctkPopupWidget.h>
// qMRML includes
#include "qMRMLTableView.h"
#include "qMRMLTableView_p.h"
#include "qMRMLTableModel.h"
// MRML includes
#include <vtkMRMLScene.h>
#include <vtkMRMLTableNode.h>
#include <vtkMRMLTableViewNode.h>
#define CTK_CHECK_AND_RETURN_IF_FAIL(FUNC) \
if (!FUNC(Q_FUNC_INFO)) \
{ \
return; \
}
#define CTK_CHECK_AND_RETURN_FALSE_IF_FAIL(FUNC) \
if (!FUNC(Q_FUNC_INFO)) \
{ \
return false; \
}
//------------------------------------------------------------------------------
qMRMLTableViewPrivate::qMRMLTableViewPrivate(qMRMLTableView& object)
: q_ptr(&object)
, MRMLScene(0)
, MRMLTableViewNode(0)
{
}
//---------------------------------------------------------------------------
qMRMLTableViewPrivate::~qMRMLTableViewPrivate()
{
}
//------------------------------------------------------------------------------
void qMRMLTableViewPrivate::init()
{
Q_Q(qMRMLTableView);
qMRMLTableModel* tableModel = new qMRMLTableModel(q);
QSortFilterProxyModel* sortFilterModel = new QSortFilterProxyModel(q);
sortFilterModel->setSourceModel(tableModel);
q->setModel(sortFilterModel);
q->horizontalHeader()->setStretchLastSection(false);
// Let the view expand in both directions
q->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
this->PopupWidget = new ctkPopupWidget;
QHBoxLayout* popupLayout = new QHBoxLayout;
popupLayout->addWidget(new QToolButton);
this->PopupWidget->setLayout(popupLayout);
}
//---------------------------------------------------------------------------
void qMRMLTableViewPrivate::setMRMLScene(vtkMRMLScene* newScene)
{
//Q_Q(qMRMLTableView);
if (newScene == this->MRMLScene)
{
return;
}
this->qvtkReconnect(
this->mrmlScene(), newScene,
vtkMRMLScene::StartBatchProcessEvent, this, SLOT(startProcessing()));
this->qvtkReconnect(
this->mrmlScene(), newScene,
vtkMRMLScene::EndBatchProcessEvent, this, SLOT(endProcessing()));
this->MRMLScene = newScene;
}
// --------------------------------------------------------------------------
void qMRMLTableViewPrivate::startProcessing()
{
}
// --------------------------------------------------------------------------
void qMRMLTableViewPrivate::endProcessing()
{
this->updateWidgetFromViewNode();
}
// --------------------------------------------------------------------------
vtkMRMLScene* qMRMLTableViewPrivate::mrmlScene()
{
return this->MRMLScene;
}
// --------------------------------------------------------------------------
bool qMRMLTableViewPrivate::verifyTableModelAndNode(const char* methodName) const
{
Q_Q(const qMRMLTableView);
if (!q->tableModel())
{
qWarning() << "qMRMLTableView:: " << methodName << " failed: invalid model";
return false;
}
if (!q->mrmlTableNode())
{
qWarning() << "qMRMLTableView::" << methodName << " failed: invalid node";
return false;
}
return true;
}
// --------------------------------------------------------------------------
void qMRMLTableViewPrivate::updateWidgetFromViewNode()
{
Q_Q(qMRMLTableView);
if (!this->MRMLScene || !this->MRMLTableViewNode)
{
q->setMRMLTableNode((vtkMRMLNode*)NULL);
return;
}
if (!q->isEnabled())
{
return;
}
// Get the TableNode
q->setMRMLTableNode(this->MRMLTableViewNode->GetTableNode());
}
//------------------------------------------------------------------------------
qMRMLTableView::qMRMLTableView(QWidget *_parent)
: QTableView(_parent)
, d_ptr(new qMRMLTableViewPrivate(*this))
{
Q_D(qMRMLTableView);
d->init();
}
//------------------------------------------------------------------------------
qMRMLTableView::~qMRMLTableView()
{
}
//------------------------------------------------------------------------------
qMRMLTableModel* qMRMLTableView::tableModel()const
{
return qobject_cast<qMRMLTableModel*>(this->sortFilterProxyModel()->sourceModel());
}
//------------------------------------------------------------------------------
QSortFilterProxyModel* qMRMLTableView::sortFilterProxyModel()const
{
return qobject_cast<QSortFilterProxyModel*>(this->model());
}
//------------------------------------------------------------------------------
void qMRMLTableView::setMRMLTableNode(vtkMRMLNode* node)
{
this->setMRMLTableNode(vtkMRMLTableNode::SafeDownCast(node));
}
//------------------------------------------------------------------------------
void qMRMLTableView::setMRMLTableNode(vtkMRMLTableNode* node)
{
qMRMLTableModel* mrmlModel = this->tableModel();
if (!mrmlModel)
{
qCritical("qMRMLTableView::setMRMLTableNode failed: invalid model");
return;
}
mrmlModel->setMRMLTableNode(node);
this->sortFilterProxyModel()->invalidate();
this->horizontalHeader()->setMinimumSectionSize(60);
this->resizeColumnsToContents();
}
//------------------------------------------------------------------------------
vtkMRMLTableNode* qMRMLTableView::mrmlTableNode()const
{
qMRMLTableModel* mrmlModel = this->tableModel();
if (!mrmlModel)
{
qCritical("qMRMLTableView::mrmlTableNode failed: model is invalid");
return 0;
}
return mrmlModel->mrmlTableNode();
}
//------------------------------------------------------------------------------
bool qMRMLTableView::transposed()const
{
Q_D(const qMRMLTableView);
CTK_CHECK_AND_RETURN_FALSE_IF_FAIL(d->verifyTableModelAndNode)
return tableModel()->transposed();
}
//------------------------------------------------------------------------------
void qMRMLTableView::setTransposed(bool transposed)
{
Q_D(qMRMLTableView);
CTK_CHECK_AND_RETURN_IF_FAIL(d->verifyTableModelAndNode)
tableModel()->setTransposed(transposed);
}
//------------------------------------------------------------------------------
void qMRMLTableView::keyPressEvent(QKeyEvent *event)
{
if(event->matches(QKeySequence::Copy) )
{
this->copySelection();
return;
}
if(event->matches(QKeySequence::Paste) )
{
this->pasteSelection();
return;
}
// Prevent giving the focus to the previous/next widget if arrow keys are used
// at the edge of the table (without this: if the current cell is in the top
// row and user press the Up key, the focus goes from the table to the previous
// widget in the tab order)
if (model() && (
(event->key() == Qt::Key_Left && currentIndex().column() == 0)
|| (event->key() == Qt::Key_Up && currentIndex().row() == 0)
|| (event->key() == Qt::Key_Right && currentIndex().column() == model()->columnCount()-1)
|| (event->key() == Qt::Key_Down && currentIndex().row() == model()->rowCount()-1) ) )
{
return;
}
QTableView::keyPressEvent(event);
}
//-----------------------------------------------------------------------------
void qMRMLTableView::copySelection()
{
Q_D(qMRMLTableView);
CTK_CHECK_AND_RETURN_IF_FAIL(d->verifyTableModelAndNode)
if (!selectionModel()->hasSelection())
{
return;
}
qMRMLTableModel* mrmlModel = tableModel();
QItemSelectionModel* selection = selectionModel();
QString textToCopy;
bool firstLine = true;
for (int rowIndex=0; rowIndex<mrmlModel->rowCount(); rowIndex++)
{
if (!selection->rowIntersectsSelection(rowIndex, QModelIndex()))
{
// no items are selected in this entire row, skip it
continue;
}
if (firstLine)
{
firstLine = false;
}
else
{
textToCopy.append('\n');
}
bool firstItemInLine = true;
for (int columnIndex=0; columnIndex<mrmlModel->columnCount(); columnIndex++)
{
if (!selection->columnIntersectsSelection(columnIndex, QModelIndex()))
{
// no items are selected in this entire column, skip it
continue;
}
if (firstItemInLine)
{
firstItemInLine = false;
}
else
{
textToCopy.append('\t');
}
textToCopy.append(mrmlModel->item(rowIndex,columnIndex)->text());
}
}
QApplication::clipboard()->setText(textToCopy);
}
//-----------------------------------------------------------------------------
void qMRMLTableView::pasteSelection()
{
Q_D(qMRMLTableView);
CTK_CHECK_AND_RETURN_IF_FAIL(d->verifyTableModelAndNode)
QString text = QApplication::clipboard()->text();
if (text.isEmpty())
{
return;
}
QStringList lines = text.split('\n');
if (lines.empty())
{
// nothing to paste
return;
}
if (lines.back().isEmpty())
{
// usually there is an extra empty line at the end
// remove that to avoid adding an extra empty line to the table
lines.pop_back();
}
if (lines.empty())
{
// nothing to paste
return;
}
// If there is no selection then paste from top-left
qMRMLTableModel* mrmlModel = tableModel();
int rowIndex = currentIndex().row();
if (rowIndex < 0)
{
rowIndex = 0;
}
int startColumnIndex = currentIndex().column();
if (startColumnIndex < 0)
{
startColumnIndex = 0;
}
// If there are multiple table views then each cell modification would trigger
// a table update, which may be very slow in case of large tables, therefore
// we need to use StartModify/EndModify.
vtkMRMLTableNode* tableNode = mrmlTableNode();
int wasModified = tableNode->StartModify();
// Pre-allocate new rows (to reduce number of updateModelFromMRML() calls
if (tableNode->GetNumberOfColumns() == 0)
{
// insertRow() may insert two rows if the table is empty (one column header + one data item),
// which could cause an extra row added to the table. To prevent this, we add a column instead,
// which is just a single value.
insertColumn();
mrmlModel->updateModelFromMRML();
}
for (int i = lines.size() - (mrmlModel->rowCount() - rowIndex); i>0; i--)
{
insertRow();
}
mrmlModel->updateModelFromMRML();
foreach(QString line, lines)
{
int columnIndex = startColumnIndex;
QStringList cells = line.split('\t');
foreach(QString cell, cells)
{
// Pre-allocate new columns (enough for at least for storing all the items in the current row)
if (columnIndex >= mrmlModel->columnCount())
{
for (int i = cells.size() - (mrmlModel->columnCount() - startColumnIndex); i>0; i--)
{
insertColumn();
}
mrmlModel->updateModelFromMRML();
}
// Set values in items
QStandardItem* item = mrmlModel->item(rowIndex,columnIndex);
if (item != NULL)
{
item->setText(cell);
}
else
{
qWarning() << "Failed to set " << cell << " in table cell (" << rowIndex << ", " << columnIndex << ")";
}
columnIndex++;
}
rowIndex++;
}
tableNode->EndModify(wasModified);
}
//-----------------------------------------------------------------------------
void qMRMLTableView::insertColumn()
{
Q_D(qMRMLTableView);
CTK_CHECK_AND_RETURN_IF_FAIL(d->verifyTableModelAndNode)
if (tableModel()->transposed())
{
mrmlTableNode()->AddEmptyRow();
}
else
{
mrmlTableNode()->AddColumn();
}
}
//-----------------------------------------------------------------------------
void qMRMLTableView::deleteColumn()
{
Q_D(qMRMLTableView);
CTK_CHECK_AND_RETURN_IF_FAIL(d->verifyTableModelAndNode)
tableModel()->removeSelectionFromMRML(selectionModel()->selectedIndexes(), false);
clearSelection();
}
//-----------------------------------------------------------------------------
void qMRMLTableView::insertRow()
{
Q_D(qMRMLTableView);
CTK_CHECK_AND_RETURN_IF_FAIL(d->verifyTableModelAndNode)
if (tableModel()->transposed())
{
mrmlTableNode()->AddColumn();
}
else
{
mrmlTableNode()->AddEmptyRow();
}
}
//-----------------------------------------------------------------------------
void qMRMLTableView::deleteRow()
{
Q_D(qMRMLTableView);
CTK_CHECK_AND_RETURN_IF_FAIL(d->verifyTableModelAndNode)
tableModel()->removeSelectionFromMRML(selectionModel()->selectedIndexes(), true);
clearSelection();
}
//-----------------------------------------------------------------------------
bool qMRMLTableView::firstRowLocked()const
{
Q_D(const qMRMLTableView);
CTK_CHECK_AND_RETURN_FALSE_IF_FAIL(d->verifyTableModelAndNode)
if (tableModel()->transposed())
{
return mrmlTableNode()->GetUseFirstColumnAsRowHeader();
}
else
{
return mrmlTableNode()->GetUseColumnNameAsColumnHeader();
}
}
//-----------------------------------------------------------------------------
void qMRMLTableView::setFirstRowLocked(bool locked)
{
Q_D(qMRMLTableView);
CTK_CHECK_AND_RETURN_IF_FAIL(d->verifyTableModelAndNode)
if (tableModel()->transposed())
{
if (mrmlTableNode()->GetUseFirstColumnAsRowHeader()==locked)
{
//no change
return;
}
mrmlTableNode()->SetUseFirstColumnAsRowHeader(locked);
}
else
{
if (mrmlTableNode()->GetUseColumnNameAsColumnHeader()==locked)
{
//no change
return;
}
mrmlTableNode()->SetUseColumnNameAsColumnHeader(locked);
}
this->resizeColumnsToContents();
}
//-----------------------------------------------------------------------------
bool qMRMLTableView::firstColumnLocked()const
{
Q_D(const qMRMLTableView);
CTK_CHECK_AND_RETURN_FALSE_IF_FAIL(d->verifyTableModelAndNode)
if (tableModel()->transposed())
{
return mrmlTableNode()->GetUseColumnNameAsColumnHeader();
}
else
{
return mrmlTableNode()->GetUseFirstColumnAsRowHeader();
}
}
//-----------------------------------------------------------------------------
void qMRMLTableView::setFirstColumnLocked(bool locked)
{
Q_D(qMRMLTableView);
CTK_CHECK_AND_RETURN_IF_FAIL(d->verifyTableModelAndNode)
if (tableModel()->transposed())
{
if (mrmlTableNode()->GetUseColumnNameAsColumnHeader()==locked)
{
//no change
return;
}
mrmlTableNode()->SetUseColumnNameAsColumnHeader(locked);
}
else
{
if (mrmlTableNode()->GetUseFirstColumnAsRowHeader()==locked)
{
//no change
return;
}
mrmlTableNode()->SetUseFirstColumnAsRowHeader(locked);
}
this->resizeColumnsToContents();
}
//------------------------------------------------------------------------------
void qMRMLTableView::setMRMLScene(vtkMRMLScene* newScene)
{
Q_D(qMRMLTableView);
if (newScene == d->MRMLScene)
{
return;
}
d->setMRMLScene(newScene);
if (d->MRMLTableViewNode && newScene != d->MRMLTableViewNode->GetScene())
{
this->setMRMLTableViewNode(0);
}
emit mrmlSceneChanged(newScene);
}
//---------------------------------------------------------------------------
void qMRMLTableView::setMRMLTableViewNode(vtkMRMLTableViewNode* newTableViewNode)
{
Q_D(qMRMLTableView);
if (d->MRMLTableViewNode == newTableViewNode)
{
return;
}
// connect modified event on TableViewNode to updating the widget
d->qvtkReconnect(
d->MRMLTableViewNode, newTableViewNode,
vtkCommand::ModifiedEvent, d, SLOT(updateWidgetFromViewNode()));
// cache the TableViewNode
d->MRMLTableViewNode = newTableViewNode;
// make sure the gui is up to date
d->updateWidgetFromViewNode();
}
//---------------------------------------------------------------------------
vtkMRMLTableViewNode* qMRMLTableView::mrmlTableViewNode()const
{
Q_D(const qMRMLTableView);
return d->MRMLTableViewNode;
}
//---------------------------------------------------------------------------
vtkMRMLScene* qMRMLTableView::mrmlScene()const
{
Q_D(const qMRMLTableView);
return d->MRMLScene;
}
| 28.196339 | 111 | 0.568571 | [
"object",
"model",
"3d"
] |
4b50c7b8a4b394f5070f4de9b79532ea57c763c0 | 527 | hpp | C++ | include/decima/serializable/object/prefetch.hpp | torandi/ProjectDecima | 617e98164a0e9bf906cf85c86a16dfea3610fc63 | [
"MIT"
] | 15 | 2020-08-08T16:17:53.000Z | 2022-03-19T19:17:57.000Z | include/decima/serializable/object/prefetch.hpp | torandi/ProjectDecima | 617e98164a0e9bf906cf85c86a16dfea3610fc63 | [
"MIT"
] | 6 | 2020-08-09T23:50:50.000Z | 2022-02-24T20:52:35.000Z | include/decima/serializable/object/prefetch.hpp | torandi/ProjectDecima | 617e98164a0e9bf906cf85c86a16dfea3610fc63 | [
"MIT"
] | 6 | 2021-04-06T09:27:44.000Z | 2022-01-14T06:38:45.000Z | #pragma once
#include <string>
#include <vector>
#include "object.hpp"
#include "decima/serializable/array.hpp"
#include "decima/serializable/string.hpp"
namespace Decima {
class Prefetch : public CoreObject {
public:
void parse(ArchiveManager& manager, ash::buffer& buffer, CoreFile& file) override;
void draw() override;
public:
Array<StringHashed> paths;
Array<std::uint32_t> sizes;
std::uint32_t links_total;
std::vector<Array<std::uint32_t>> links;
};
}
| 22.913043 | 90 | 0.666034 | [
"object",
"vector"
] |
4b5318d561f84b96ffac383bce6b2feb9adb03e0 | 4,826 | cpp | C++ | includes/ForcefulClassifier.cpp | WalkingDexter/simple_image_v2 | d02dfe19adedf8b33fb94bad0ce88fbbe46de41e | [
"Apache-2.0"
] | null | null | null | includes/ForcefulClassifier.cpp | WalkingDexter/simple_image_v2 | d02dfe19adedf8b33fb94bad0ce88fbbe46de41e | [
"Apache-2.0"
] | null | null | null | includes/ForcefulClassifier.cpp | WalkingDexter/simple_image_v2 | d02dfe19adedf8b33fb94bad0ce88fbbe46de41e | [
"Apache-2.0"
] | null | null | null | /*
Copyright © 2017 Andrey Tymchuk.
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 <string.h>
#include <vector>
#include <algorithm>
#include "HaarFeature.h"
#include "WeaklyClassifier.h"
#include "ForcefulClassifier.h"
/**
* ForcefulClassifier first constructor.
*/
ForcefulClassifier::ForcefulClassifier() {
this->limit = 0;
}
/**
* ForcefulClassifier second constructor.
*/
ForcefulClassifier::ForcefulClassifier(std::vector<WeaklyClassifier*> weakly_classifiers, float *weights) {
this->weakly_classifiers = weakly_classifiers;
for (unsigned int i = 0; i < weakly_classifiers.size(); i++) {
this->weights.push_back(weights[i]);
}
this->limit = 0;
}
/**
* ForcefulClassifier third constructor.
*/
ForcefulClassifier::ForcefulClassifier(std::vector<WeaklyClassifier*> weakly_classifiers, float *weights, float limit) {
this->weakly_classifiers = weakly_classifiers;
for (unsigned int i = 0; i < weakly_classifiers.size(); i++) {
this->weights.push_back(weights[i]);
}
this->limit = limit;
}
/**
* Get weakly classifiers set.
*/
std::vector<WeaklyClassifier*> ForcefulClassifier::getWeaklyClassifiers() {
return this->weakly_classifiers;
}
/**
* Scale each weakly classifier in set by value.
*/
void ForcefulClassifier::scaleByValue(float value) {
std::vector<WeaklyClassifier*>::iterator iterator;
for (iterator = this->weakly_classifiers.begin(); iterator != this->weakly_classifiers.end(); iterator++) {
(*iterator)->scaleByValue(value);
}
}
/**
* Put new weakly classifier in set.
*/
void ForcefulClassifier::addClassifier(WeaklyClassifier* weakly_classifier, float weight) {
this->weakly_classifiers.push_back(weakly_classifier);
this->weights.push_back(weight);
}
/**
* Calculate classifier limit.
*/
void ForcefulClassifier::calculateLimit(std::vector<float*> &positive_samples, int size, float maximum_fnr) {
unsigned int positive_size = positive_samples.size(), temp = maximum_fnr * positive_size;
int weights_index;
float temp2, *counters = new float[positive_size];
std::vector<WeaklyClassifier*>::iterator iterator;
for (unsigned int i = 0; i < positive_size; i++) {
counters[i] = 0;
weights_index = 0;
for (iterator = this->weakly_classifiers.begin(); iterator != this->weakly_classifiers.end(); iterator++) {
counters[i] += this->weights[weights_index] * (*iterator)->classifyImage(positive_samples[i], size, 0, 0, 0, 1);
weights_index++;
}
}
std::sort(counters, counters + positive_size);
if (temp >= 0 && temp < positive_size) {
temp2 = counters[temp];
while (temp > 0 && counters[temp] == temp2) {
temp--;
}
this->limit = counters[temp];
}
delete[] counters;
}
/**
* Calculate classifier FPR.
*/
float ForcefulClassifier::calculateFpr(std::vector<float*> &negative_samples, int size) {
unsigned int negative_size = negative_samples.size();
int classify_image_count = 0;
for (unsigned int i = 0; i < negative_size; i++) {
if (this->classifyImage(negative_samples[i], size, 0, 0, 0, 1)) {
classify_image_count++;
}
}
return float(classify_image_count) / float(negative_samples.size());
}
/**
* Scale only limit by value.
*/
void ForcefulClassifier::scaleLimitByValue(float value) {
this->limit *= value;
}
/**
* Classify image by classifier.
*/
bool ForcefulClassifier::classifyImage(float *image, int image_width, int x, int y, float temp1, float temp2) {
float counter = 0;
int weights_index = 0;
std::vector<WeaklyClassifier*>::iterator iterator;
for (iterator = this->weakly_classifiers.begin(); iterator != this->weakly_classifiers.end(); iterator++) {
counter += this->weights[weights_index++] * (*iterator)->classifyImage(image, image_width, x, y, temp1, temp2);
}
return counter >= this->limit;
}
/**
* Transform classifier to string representation.
*/
std::string ForcefulClassifier::toString() {
std::vector<WeaklyClassifier*>::iterator iterator;
std::string result = std::to_string(this->weakly_classifiers.size()) + " " + std::to_string(this->limit) + "\n";
int weights_index = 0;
for (iterator = this->weakly_classifiers.begin(); iterator != this->weakly_classifiers.end(); iterator++) {
result += std::to_string(this->weights[weights_index++]) + " " + (*iterator)->toString() + "\n";
}
return result;
}
| 31.75 | 120 | 0.709697 | [
"vector",
"transform"
] |
4b5490a12317384608712a7fe9fcaf233814ad59 | 16,270 | hpp | C++ | Include/SA/Maths/Space/Vector3.hpp | SapphireSuite/Maths | df193e3d8fc5cd127626f2f1e2b0bd14cd6cb4eb | [
"MIT"
] | null | null | null | Include/SA/Maths/Space/Vector3.hpp | SapphireSuite/Maths | df193e3d8fc5cd127626f2f1e2b0bd14cd6cb4eb | [
"MIT"
] | 1 | 2022-02-08T18:22:21.000Z | 2022-02-08T18:22:21.000Z | Include/SA/Maths/Space/Vector3.hpp | SapphireSuite/Maths | df193e3d8fc5cd127626f2f1e2b0bd14cd6cb4eb | [
"MIT"
] | null | null | null | // Copyright (c) 2022 Sapphire development team. All Rights Reserved.
#pragma once
#ifndef SAPPHIRE_MATHS_VECTOR3_GUARD
#define SAPPHIRE_MATHS_VECTOR3_GUARD
#include <cstdint>
#include <SA/Maths/Debug.hpp>
#include <SA/Maths/Angle/Degree.hpp>
#include <SA/Maths/Algorithms/Cos.hpp>
#include <SA/Maths/Algorithms/Sqrt.hpp>
#include <SA/Maths/Algorithms/Lerp.hpp>
#include <SA/Maths/Algorithms/Equals.hpp>
/**
* \file Vector3.hpp
*
* \brief <b>Vector 3</b> type implementation.
*
* \ingroup Maths_Space
* \{
*/
namespace Sa
{
template <typename T>
struct Vec2;
template <typename T>
struct Vec4;
/**
* \brief \e Vector 3 Sapphire-Maths class.
*
* \tparam T Type of the vector.
*/
template <typename T>
struct Vec3
{
/// Type of the Vector.
using Type = T;
/// Vector's X component (axis value).
T x = T();
/// Vector's Y component (axis value).
T y = T();
/// Vector's Z component (axis value).
T z = T();
//{ Constants
/// Zero vector constant {0, 0, 0}.
static const Vec3 Zero;
/// One vector constant {1, 1, 1}.
static const Vec3 One;
/// Right vector constant {1, 0, 0}.
static const Vec3 Right;
/// Left vector constant {-1, 0, 0}.
static const Vec3 Left;
/// Up vector constant {0, 1, 0}.
static const Vec3 Up;
/// Down vector constant {0, -1, 0}.
static const Vec3 Down;
/// Down vector constant {0, 0, 1}.
static const Vec3 Forward;
/// Down vector constant {0, 0, -1}.
static const Vec3 Backward;
//}
//{ Constructors
/// \e Default constructor.
Vec3() = default;
/**
* \brief \e Value constructor.
*
* \param[in] _x X axis value.
* \param[in] _y Y axis value.
* \param[in] _z Z axis value.
*/
constexpr Vec3(T _x, T _y, T _z) noexcept;
/**
* \brief \b Scale \e Value constructor.
*
* \param[in] _scale Axis value to apply on all axis.
*/
constexpr Vec3(T _scale) noexcept;
/// Default move constructor.
Vec3(Vec3&&) = default;
/// Default copy constructor.
Vec3(const Vec3&) = default;
/**
* \brief \e Value constructor from another Vec3 type.
*
* \tparam TIn Type of the input Vec3.
*
* \param[in] _other Vec3 to construct from.
*/
template <typename TIn>
constexpr Vec3(const Vec3<TIn>& _other) noexcept;
/**
* \brief \e Value constructor from Vec2.
*
* \tparam TIn Type of the in Vec2.
*
* \param[in] _other Vec2 to construct from.
* \param[in] _z Z axis value.
*/
template <typename TIn>
constexpr Vec3(const Vec2<TIn>& _other, T _z = T(0)) noexcept;
/**
* \brief \e Value constructor from Vec4.
*
* \tparam TIn Type of the in Vec4.
*
* \param[in] _other Vec4 to construct from.
*/
template <typename TIn>
constexpr Vec3(const Vec4<TIn>& _other) noexcept;
//}
//{ Equals
/**
* \brief Whether this vector is a zero vector.
*
* \return True if this is a zero vector.
*/
constexpr bool IsZero() const noexcept;
/**
* \brief \e Compare 2 vector.
*
* \param[in] _other Other vector to compare to.
* \param[in] _epsilon Epsilon value for threshold comparison.
*
* \return Whether this and _other are equal.
*/
constexpr bool Equals(const Vec3& _other, T _epsilon = std::numeric_limits<T>::epsilon()) const noexcept;
/**
* \brief \e Compare 2 vector equality.
*
* \param[in] _rhs Other vector to compare to.
*
* \return Whether this and _rhs are equal.
*/
constexpr bool operator==(const Vec3 & _rhs) const noexcept;
/**
* \brief \e Compare 2 vector inequality.
*
* \param[in] _rhs Other vector to compare to.
*
* \return Whether this and _rhs are non-equal.
*/
constexpr bool operator!=(const Vec3 & _rhs) const noexcept;
//}
//{ Accessors
/**
* \brief \e Getter of vector data
*
* \return this vector as a T*.
*/
T* Data() noexcept;
/**
* \brief <em> Const Getter </em> of vector data
*
* \return this vector as a const T*.
*/
const T* Data() const noexcept;
/**
* \brief \e Access operator by index: x, y, z using 0, 1, 2.
*
* \param[in] _index Index to access.
*
* \return T value at index.
*/
T& operator[](uint32_t _index);
/**
* \brief <em> Const Access </em> operator by index: x, y, z using 0, 1, 2.
*
* \param[in] _index Index to access.
*
* \return T value at index.
*/
const T& operator[](uint32_t _index) const;
//}
//{ Length
/**
* \brief \e Getter of the \b length of this vector.
*
* \return Length of this vector.
*/
constexpr T Length() const;
/**
* \brief \e Getter of the <b> Squared Length </b> of this vector.
*
* \return Squared Length of this vector.
*/
constexpr T SqrLength() const noexcept;
/**
* \brief \b Normalize this vector.
*
* \return self vector normalized.
*/
Vec3& Normalize();
/**
* \brief \b Normalize this vector.
*
* \return new normalized vector.
*/
Vec3 GetNormalized() const;
/**
* \brief Whether this vector is normalized.
*
* \return True if this vector is normalized, otherwise false.
*/
constexpr bool IsNormalized() const noexcept;
//}
//{ Project
/**
* \brief \b Reflect this vector over the normal.
*
* \param[in] _normal Normal used for reflection.
* \param[in] _elasticity Elasticity reflection coefficient (use 1.0f for full reflection).
*
* \return new vector reflected.
*/
Vec3 Reflect(const Vec3& _normal, float _elasticity = 1.0f) const noexcept;
/**
* \brief \b Project this vector onto an other vector.
*
* Reference: https://en.wikipedia.org/wiki/Vector_projection
*
* \param[in] _other Vector used for projection.
*
* \return new vector projected.
*/
Vec3 ProjectOnTo(const Vec3& _other) const noexcept;
/**
* \brief \b Project this vector onto s normal.
*
* Assume _normal is normalized.
* Use GetProjectOnTo() for non normalized vector.
* Reference: https://en.wikipedia.org/wiki/Vector_projection
*
* \param[in] _normal Normal used for projection.
*
* \return new vector projected.
*/
Vec3 ProjectOnToNormal(const Vec3& _normal) const noexcept;
//}
//{ Dot/Cross
/**
* \brief \e Compute the <b> Dot product </b> between _lhs and _rhs.
*
* \param[in] _lhs Left hand side operand to compute dot product with.
* \param[in] _rhs Right hand side operand to compute dot product with.
*
* \return <b> Dot product </b> between _lhs and _rhs.
*/
static constexpr T Dot(const Vec3& _lhs, const Vec3& _rhs) noexcept;
/**
* \brief \e Compute the <b> Cross product </b> between _lhs and _rhs.
*
* \param[in] _lhs Left hand side operand to compute cross product with.
* \param[in] _rhs Right hand side operand to compute cross product with.
*
* \return <b> Cross product </b> between _lhs and _rhs.
*/
static constexpr Vec3<T> Cross(const Vec3& _lhs, const Vec3& _rhs) noexcept;
//}
//{ Angle
/**
* \brief \e Compute the <b> Signed Angle </b> between _lhs and _rhs.
*
* \param[in] _start Left hand side operand to compute angle with.
* \param[in] _end Right hand side operand to compute angle with.
* \param[in] _normal Normal of the plan between _lhs and _rhs, used to determine angle's sign.
*
* \return <b> Signed Angle </b> between _start and _end.
*/
static Deg<T> Angle(const Vec3& _start, const Vec3& _end, const Vec3& _normal = Vec3::Up) noexcept;
/**
* \brief \e Compute the <b> Unsigned Angle </b> between _lhs and _rhs.
*
* \param[in] _start Left hand side operand to compute angle with.
* \param[in] _end Right hand side operand to compute angle with.
*
* \return <b> Unsigned Angle </b> between _start and _end.
*/
static Deg<T> AngleUnsigned(const Vec3& _start, const Vec3& _end) noexcept;
//}
//{ Dist/Dir
/**
* \brief \e Compute the <b> Distance </b> between _lhs and _rhs.
*
* \param[in] _start Left hand side operand to compute distance with.
* \param[in] _end Right hand side operand to compute distance with.
*
* \return <b> Distance </b> between _start and _end.
*/
static constexpr T Dist(const Vec3& _start, const Vec3& _end);
/**
* \brief \e Compute the <b> Squared Distance </b> between _lhs and _rhs.
*
* \param[in] _start Left hand side operand to compute squared distance with.
* \param[in] _end Right hand side operand to compute squared distance with.
*
* \return <b> Squared Distance </b> between _start and _end.
*/
static constexpr T SqrDist(const Vec3& _start, const Vec3& _end) noexcept;
/**
* \brief \e Compute the <b> Non-Normalized Direction </b> from _lhs and _rhs.
*
* Direction get not normalized. Use DirN instead.
*
* \param[in] _start Left hand side operand to compute direction from.
* \param[in] _end Right hand side operand to compute direction to
*
* \return <b> Non-Normalized Direction </b> from _start and _end.
*/
static constexpr Vec3 Dir(const Vec3& _start, const Vec3& _end) noexcept;
/**
* \brief \e Compute the <b> Normalized Direction </b> from _start to _end.
*
* \param[in] _start Starting point to compute direction from.
* \param[in] _end ending point to compute direction to.
*
* \return <b> Normalized Direction </b> from _start to _end.
*/
static constexpr Vec3 DirN(const Vec3& _start, const Vec3& _end);
//}
//{ Lerp
/**
* \brief <b> Clamped Lerp </b> from _start to _end at _alpha.
*
* Reference: https://en.wikipedia.org/wiki/Linear_interpolation
*
* \param _start Starting point of the lerp.
* \param _end Ending point of the lerp.
* \param _alpha Alpha of the lerp.
*
* \return interpolation between _start and _end. return _start when _alpha == 0.0f and _end when _alpha == 1.0f.
*/
static Vec3 Lerp(const Vec3& _start, const Vec3& _end, float _alpha) noexcept;
/**
* \brief <b> Unclamped Lerp </b> from _start to _end at _alpha.
*
* Reference: https://en.wikipedia.org/wiki/Linear_interpolation
*
* \param _start Starting point of the lerp.
* \param _end Ending point of the lerp.
* \param _alpha Alpha of the lerp.
*
* \return interpolation between _start and _end. return _start when _alpha == 0.0f and _end when _alpha == 1.0f.
*/
static Vec3 LerpUnclamped(const Vec3& _start, const Vec3& _end, float _alpha) noexcept;
/**
* \brief <b> Clamped SLerp </b> from _start to _end at _alpha.
*
* Reference: https://en.wikipedia.org/wiki/Slerp
*
* \param _start Starting point of the lerp.
* \param _end Ending point of the lerp.
* \param _alpha Alpha of the lerp.
*
* \return interpolation between _start and _end. return _start when _alpha == 0.0f and _end when _alpha == 1.0f.
*/
static Vec3 SLerp(const Vec3& _start, const Vec3& _end, float _alpha) noexcept;
/**
* \brief <b> Unclamped SLerp </b> from _start to _end at _alpha.
*
* Reference: https://en.wikipedia.org/wiki/Slerp
*
* \param _start Starting point of the lerp.
* \param _end Ending point of the lerp.
* \param _alpha Alpha of the lerp.
*
* \return interpolation between _start and _end. return _start when _alpha == 0.0f and _end when _alpha == 1.0f.
*/
static Vec3 SLerpUnclamped(const Vec3& _start, const Vec3& _end, float _alpha) noexcept;
//}
//{ Operators
/**
* \brief \e Default assignment move operator.
*
* \return self vector assigned.
*/
Vec3& operator=(Vec3&&) = default;
/**
* \brief \e Default assignment copy operator.
*
* \return self vector assigned.
*/
Vec3& operator=(const Vec3&) = default;
/**
* \brief \e Getter of the opposite signed vector.
*
* \return new opposite signed vector.
*/
constexpr Vec3 operator-() const noexcept;
/**
* \brief \b Scale each vector axis by _scale.
*
* \param[in] _scale Scale value to apply on all axis.
*
* \return new vector scaled.
*/
Vec3 operator*(T _scale) const noexcept;
/**
* \brief <b> Inverse Scale </b> each vector axis by _scale.
*
* \param[in] _scale Inverse scale value to apply on all axis.
*
* \return new vector inverse-scaled.
*/
Vec3 operator/(T _scale) const;
/**
* \brief \b Add term by term vector values.
*
* \param[in] _rhs Vector to add.
*
* \return new vector result.
*/
constexpr Vec3 operator+(const Vec3& _rhs) const noexcept;
/**
* \brief \b Subtract term by term vector values.
*
* \param[in] _rhs Vector to substract.
*
* \return new vector result.
*/
constexpr Vec3 operator-(const Vec3& _rhs) const noexcept;
/**
* \brief \b Multiply term by term vector values.
*
* \param[in] _rhs Vector to multiply.
*
* \return new vector result.
*/
constexpr Vec3 operator*(const Vec3& _rhs) const noexcept;
/**
* \brief \b Divide term by term vector values.
*
* \param[in] _rhs Vector to divide.
*
* \return new vector result.
*/
constexpr Vec3 operator/(const Vec3& _rhs) const;
/**
* \brief \e Compute the <b> Dot product </b> between this and _rhs.
*
* \param[in] _rhs Right hand side operand vector to compute dot product with.
*
* \return <b> Dot product </b> between this vector and _other.
*/
constexpr T operator|(const Vec3& _rhs) const noexcept;
/**
* \brief \e Compute the <b> Cross product </b> between this and _rhs.
*
* \param[in] _rhs Right hand side operand vector to compute cross product with.
*
* \return <b> Cross product </b> between this vector and _other.
*/
constexpr Vec3 operator^(const Vec3& _rhs) const noexcept;
/**
* \brief \b Scale each vector axis by _scale.
*
* \param[in] _scale Scale value to apply on all axis.
*
* \return self vector scaled.
*/
Vec3& operator*=(T _scale) noexcept;
/**
* \brief <b> Inverse Scale </b> each vector axis by _scale.
*
* \param[in] _scale Scale value to apply on all axis.
*
* \return self vector inverse-scaled.
*/
Vec3& operator/=(T _scale);
/**
* \brief \b Add term by term vector values.
*
* \param[in] _rhs Vector to add.
*
* \return self vector result.
*/
Vec3& operator+=(const Vec3& _rhs) noexcept;
/**
* \brief \b Substract term by term vector values.
*
* \param[in] _rhs Vector to substract.
*
* \return self vector result.
*/
Vec3& operator-=(const Vec3& _rhs) noexcept;
/**
* \brief \b Multiply term by term vector values.
*
* \param[in] _rhs Vector to multiply.
*
* \return self vector result.
*/
Vec3 operator*=(const Vec3& _rhs) noexcept;
/**
* \brief \b Divide term by term vector values.
*
* \param[in] _rhs Vector to divide.
*
* \return self vector result.
*/
Vec3 operator/=(const Vec3& _rhs);
//}
};
/**
* \brief \b Scale each vector axis by _lhs.
*
* \param[in] _lhs Scale value to apply on all axis.
* \param[in] _rhs Vector to scale.
*
* \return new vector scaled.
*/
template <typename T>
constexpr Vec3<T> operator*(typename std::remove_cv<T>::type _lhs, const Vec3<T>& _rhs) noexcept;
/**
* \brief <b> Inverse Scale </b> each vector axis by _lhs.
*
* \param[in] _lhs Inverse scale value to apply on all axis.
* \param[in] _rhs Vector to scale.
*
* \return new vector inverse-scaled.
*/
template <typename T>
constexpr Vec3<T> operator/(typename std::remove_cv<T>::type _lhs, const Vec3<T>& _rhs);
#if SA_LOGGER_IMPL
/**
* \brief ToString Vec3 implementation
*
* Convert Vec3 as a string.
*
* \tparam T Input vector type.
*
* \param[in] _v Input vector.
*
* \return input vector as a string.
*/
template <typename T>
std::string ToString(const Vec3<T>& _v);
#endif
//{ Aliases
/// Alias for int32 Vec3.
using Vec3i = Vec3<int32_t>;
/// Alias for uint32 Vec3.
using Vec3ui = Vec3<uint32_t>;
/// Alias for float Vec3.
using Vec3f = Vec3<float>;
/// Alias for double Vec3.
using Vec3d = Vec3<double>;
/// Template alias of Vec3
template <typename T>
using Vector3 = Vec3<T>;
/// Alias for int32 Vector3.
using Vector3i = Vector3<int32_t>;
/// Alias for uint32 Vector3.
using Vector3ui = Vector3<uint32_t>;
/// Alias for float Vector3.
using Vector3f = Vector3<float>;
/// Alias for double Vector3.
using Vector3d = Vector3<double>;
//}
}
/**
* \example Vector3Tests.cpp
* Examples and Unitary Tests for Vec3.
*/
/** \} */
#include <SA/Maths/Space/Vector3.inl>
#endif // GUARD
| 23.477633 | 114 | 0.649846 | [
"vector"
] |
4b57172920fcad362b9cb07acfdfd009ba48e8ac | 6,643 | cpp | C++ | src/conformance/conformance_test/test_xrEnumerateEnvironmentBlendModes.cpp | rpavlik/OpenXR-CTS | 5600673d550ddd5692614d11fabe0f9ceae16ed6 | [
"Unlicense",
"BSD-3-Clause",
"Apache-2.0",
"MIT"
] | 35 | 2020-07-07T18:10:11.000Z | 2022-03-13T10:48:45.000Z | src/conformance/conformance_test/test_xrEnumerateEnvironmentBlendModes.cpp | rpavlik/OpenXR-CTS | 5600673d550ddd5692614d11fabe0f9ceae16ed6 | [
"Unlicense",
"BSD-3-Clause",
"Apache-2.0",
"MIT"
] | 29 | 2020-09-10T16:36:59.000Z | 2022-03-31T18:17:32.000Z | src/conformance/conformance_test/test_xrEnumerateEnvironmentBlendModes.cpp | rpavlik/OpenXR-CTS | 5600673d550ddd5692614d11fabe0f9ceae16ed6 | [
"Unlicense",
"BSD-3-Clause",
"Apache-2.0",
"MIT"
] | 9 | 2020-09-10T16:01:57.000Z | 2022-01-21T18:28:35.000Z | // Copyright (c) 2019-2021, The Khronos Group Inc.
//
// SPDX-License-Identifier: Apache-2.0
//
// 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 "utils.h"
#include "conformance_utils.h"
#include "conformance_framework.h"
#include "matchers.h"
#include <array>
#include <vector>
#include <set>
#include <string>
#include <cstring>
#include <catch2/catch.hpp>
#include <openxr/openxr.h>
#include <openxr/openxr_reflection.h>
using Catch::Matchers::VectorContains;
#define AS_LIST(name, val) name,
constexpr XrViewConfigurationType KnownViewTypes[] = {XR_LIST_ENUM_XrViewConfigurationType(AS_LIST)};
#undef AS_LIST
namespace Conformance
{
TEST_CASE("xrEnumerateEnvironmentBlendModes", "")
{
GlobalData& globalData = GetGlobalData();
AutoBasicInstance instance(AutoBasicInstance::createSystemId);
// Exercise all known view configurations types and ensure unsupported types fail.
{
// Get the list of supported view configurations
uint32_t viewCount = 0;
REQUIRE(XR_SUCCESS == xrEnumerateViewConfigurations(instance, instance.systemId, 0, &viewCount, nullptr));
std::vector<XrViewConfigurationType> runtimeViewTypes(viewCount);
REQUIRE(XR_SUCCESS ==
xrEnumerateViewConfigurations(instance, instance.systemId, viewCount, &viewCount, runtimeViewTypes.data()));
// Test every view configuration type in the spec.
for (XrViewConfigurationType viewType : KnownViewTypes) {
CAPTURE(viewType);
// Is this enum valid, check against enabled extensions.
bool valid = IsViewConfigurationTypeEnumValid(viewType);
const bool isSupportedType =
std::find(runtimeViewTypes.begin(), runtimeViewTypes.end(), viewType) != runtimeViewTypes.end();
if (!valid) {
CHECK_MSG(valid == isSupportedType, "Can not support invalid view configuration type");
}
uint32_t countOutput;
const XrResult res = xrEnumerateEnvironmentBlendModes(instance, instance.systemId, viewType, 0, &countOutput, nullptr);
if (isSupportedType) {
REQUIRE_MSG(XR_SUCCESS == res, "Expected success for supported view configuration type " << viewType);
REQUIRE_MSG(countOutput > 0, "Expected non-zero list of blend modes");
}
else if (!valid) {
REQUIRE_THAT(res, In<XrResult>({XR_ERROR_VALIDATION_FAILURE, XR_ERROR_VIEW_CONFIGURATION_TYPE_UNSUPPORTED}));
if (res == XR_ERROR_VIEW_CONFIGURATION_TYPE_UNSUPPORTED) {
WARN(
"Runtime accepted an invalid enum value as unsupported, which makes it harder for apps to reason about the error.");
}
}
else {
REQUIRE_MSG(XR_ERROR_VIEW_CONFIGURATION_TYPE_UNSUPPORTED == res,
"Unexpected return code for unsupported view config type");
}
}
}
XrResult result;
std::vector<XrEnvironmentBlendMode> v;
uint32_t countOutput;
// Exercise zero input size.
result = xrEnumerateEnvironmentBlendModes(instance, instance.systemId, globalData.options.viewConfigurationValue, 0, &countOutput,
nullptr);
REQUIRE_MSG(result == XR_SUCCESS, "xrEnumerateEnvironmentBlendModes failure.");
CHECK_MSG(countOutput >= 1, "xrEnumerateEnvironmentBlendModes must enumerate at least one blend mode");
// Exercise XR_ERROR_SIZE_INSUFFICIENT
if (countOutput >= 2) { // Need at least two in order to exercise XR_ERROR_SIZE_INSUFFICIENT
v.resize(countOutput, XR_ENVIRONMENT_BLEND_MODE_MAX_ENUM);
result = xrEnumerateEnvironmentBlendModes(instance, instance.systemId, globalData.options.viewConfigurationValue, 1,
&countOutput, v.data());
REQUIRE(result == XR_ERROR_SIZE_INSUFFICIENT);
REQUIRE_MSG(v[1] == XR_ENVIRONMENT_BLEND_MODE_MAX_ENUM,
"xrEnumerateEnvironmentBlendModes failure: data written beyond input count.");
REQUIRE_MSG(countOutput == v.size(), "xrEnumerateEnvironmentBlendModes failure: required size changed unexpectectedly.");
}
// Exercise invalid system id
{
REQUIRE(XR_ERROR_SYSTEM_INVALID == xrEnumerateEnvironmentBlendModes(instance, XR_NULL_SYSTEM_ID,
globalData.options.viewConfigurationValue, 0, &countOutput,
nullptr));
}
// Exercise enough capacity
v = std::vector<XrEnvironmentBlendMode>(countOutput, XR_ENVIRONMENT_BLEND_MODE_MAX_ENUM);
REQUIRE_RESULT_UNQUALIFIED_SUCCESS(xrEnumerateEnvironmentBlendModes(
instance, instance.systemId, globalData.options.viewConfigurationValue, countOutput, &countOutput, v.data()));
CHECK_THAT(v, VectorHasOnlyUniqueElements<XrEnvironmentBlendMode>());
CHECK_THAT(v, !VectorContains(XR_ENVIRONMENT_BLEND_MODE_MAX_ENUM));
// To do: Verify that the values reported are within the set of valid values for the given runtime version.
// This is best done in a forward-looking way via a generated table.
// The following is close but not quite.
if (globalData.runtimeMatchesAPIVersion) {
for (auto blendMode : v) {
if (blendMode < 1000000000) { // If it's a core type
CHECK_THAT(blendMode, In<XrEnvironmentBlendMode>({XR_ENVIRONMENT_BLEND_MODE_OPAQUE, XR_ENVIRONMENT_BLEND_MODE_ADDITIVE,
XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND}));
}
}
}
}
} // namespace Conformance
| 48.489051 | 144 | 0.63661 | [
"vector"
] |
4b5b48356796afe686ee2e3c6614c76839777300 | 18,119 | hpp | C++ | 3party/osrm/osrm-backend/routing_algorithms/routing_base.hpp | kudlav/organicmaps | 390236365749e0525b9229684132c2888d11369d | [
"Apache-2.0"
] | 4,879 | 2015-09-30T10:56:36.000Z | 2022-03-31T18:43:03.000Z | 3party/osrm/osrm-backend/routing_algorithms/routing_base.hpp | mbrukman/omim | d22fe2b6e0beee697f096e931df97a64f9db9dc1 | [
"Apache-2.0"
] | 7,549 | 2015-09-30T10:52:53.000Z | 2022-03-31T22:04:22.000Z | 3party/osrm/osrm-backend/routing_algorithms/routing_base.hpp | mbrukman/omim | d22fe2b6e0beee697f096e931df97a64f9db9dc1 | [
"Apache-2.0"
] | 1,493 | 2015-09-30T10:43:06.000Z | 2022-03-21T09:16:49.000Z | /*
Copyright (c) 2015, Project OSRM 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:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ROUTING_BASE_HPP
#define ROUTING_BASE_HPP
#include "../data_structures/coordinate_calculation.hpp"
#include "../data_structures/internal_route_result.hpp"
#include "../data_structures/search_engine_data.hpp"
#include "../data_structures/turn_instructions.hpp"
// #include "../util/simple_logger.hpp"
#include <boost/assert.hpp>
#include <stack>
SearchEngineData::SearchEngineHeapPtr SearchEngineData::forward_heap_1;
SearchEngineData::SearchEngineHeapPtr SearchEngineData::reverse_heap_1;
SearchEngineData::SearchEngineHeapPtr SearchEngineData::forward_heap_2;
SearchEngineData::SearchEngineHeapPtr SearchEngineData::reverse_heap_2;
SearchEngineData::SearchEngineHeapPtr SearchEngineData::forward_heap_3;
SearchEngineData::SearchEngineHeapPtr SearchEngineData::reverse_heap_3;
template <class DataFacadeT, class Derived> class BasicRoutingInterface
{
private:
using EdgeData = typename DataFacadeT::EdgeData;
protected:
DataFacadeT *facade;
public:
BasicRoutingInterface() = delete;
BasicRoutingInterface(const BasicRoutingInterface &) = delete;
explicit BasicRoutingInterface(DataFacadeT *facade) : facade(facade) {}
~BasicRoutingInterface() {}
void RoutingStep(SearchEngineData::QueryHeap &forward_heap,
SearchEngineData::QueryHeap &reverse_heap,
NodeID *middle_node_id,
int *upper_bound,
const int min_edge_offset,
const bool forward_direction) const
{
const NodeID node = forward_heap.DeleteMin();
const int distance = forward_heap.GetKey(node);
// const NodeID parentnode = forward_heap.GetData(node).parent;
// SimpleLogger().Write() << (forward_direction ? "[fwd] " : "[rev] ") << "settled edge ("
// << parentnode << "," << node << "), dist: " << distance;
if (reverse_heap.WasInserted(node))
{
const int new_distance = reverse_heap.GetKey(node) + distance;
if (new_distance < *upper_bound)
{
if (new_distance >= 0)
{
*middle_node_id = node;
*upper_bound = new_distance;
// SimpleLogger().Write() << "accepted middle node " << node << " at
// distance " << new_distance;
// } else {
// SimpleLogger().Write() << "discared middle node " << node << " at
// distance " << new_distance;
}
}
}
if (distance + min_edge_offset > *upper_bound)
{
// SimpleLogger().Write() << "min_edge_offset: " << min_edge_offset;
forward_heap.DeleteAll();
return;
}
// Stalling
for (const auto edge : facade->GetAdjacentEdgeRange(node))
{
const EdgeData &data = facade->GetEdgeData(edge, node);
const bool reverse_flag = ((!forward_direction) ? data.forward : data.backward);
if (reverse_flag)
{
const NodeID to = facade->GetTarget(edge);
const int edge_weight = data.distance;
BOOST_ASSERT_MSG(edge_weight > 0, "edge_weight invalid");
if (forward_heap.WasInserted(to))
{
if (forward_heap.GetKey(to) + edge_weight < distance)
{
return;
}
}
}
}
for (const auto edge : facade->GetAdjacentEdgeRange(node))
{
const EdgeData &data = facade->GetEdgeData(edge, node);
bool forward_directionFlag = (forward_direction ? data.forward : data.backward);
if (forward_directionFlag)
{
const NodeID to = facade->GetTarget(edge);
const int edge_weight = data.distance;
BOOST_ASSERT_MSG(edge_weight > 0, "edge_weight invalid");
const int to_distance = distance + edge_weight;
// New Node discovered -> Add to Heap + Node Info Storage
if (!forward_heap.WasInserted(to))
{
forward_heap.Insert(to, to_distance, node);
}
// Found a shorter Path -> Update distance
else if (to_distance < forward_heap.GetKey(to))
{
// new parent
forward_heap.GetData(to).parent = node;
forward_heap.DecreaseKey(to, to_distance);
}
}
}
}
void UnpackPath(const std::vector<NodeID> &packed_path,
const PhantomNodes &phantom_node_pair,
std::vector<PathData> &unpacked_path) const
{
//const bool start_traversed_in_reverse =
// (packed_path.front() != phantom_node_pair.source_phantom.forward_node_id);
//const bool target_traversed_in_reverse =
// (packed_path.back() != phantom_node_pair.target_phantom.forward_node_id);
const unsigned packed_path_size = static_cast<unsigned>(packed_path.size());
std::stack<std::pair<NodeID, NodeID>> recursion_stack;
// We have to push the path in reverse order onto the stack because it's LIFO.
for (unsigned i = packed_path_size - 1; i > 0; --i)
{
recursion_stack.emplace(packed_path[i - 1], packed_path[i]);
}
unpacked_path.emplace_back(packed_path[0], INVALID_EDGE_WEIGHT, TurnInstruction::NoTurn, INVALID_EDGE_WEIGHT, TRAVEL_MODE_INACCESSIBLE);
std::pair<NodeID, NodeID> edge;
while (!recursion_stack.empty())
{
/*
Graphical representation of variables:
edge.first edge.second
*------------------>*
edge_id
*/
edge = recursion_stack.top();
recursion_stack.pop();
// facade->FindEdge does not suffice here in case of shortcuts.
// The above explanation unclear? Think!
EdgeID smaller_edge_id = SPECIAL_EDGEID;
NodeID smaller_node_id = SPECIAL_NODEID;
int edge_weight = std::numeric_limits<EdgeWeight>::max();
for (const auto edge_id : facade->GetAdjacentEdgeRange(edge.first))
{
auto const & edgeData = facade->GetEdgeData(edge_id, edge.first);
const int weight = edgeData.distance;
if ((facade->GetTarget(edge_id) == edge.second) && (weight < edge_weight) &&
edgeData.forward)
{
smaller_edge_id = edge_id;
smaller_node_id = edge.first;
edge_weight = weight;
}
}
/*
Graphical representation of variables:
edge.first edge.second
*<------------------*
edge_id
*/
if (SPECIAL_EDGEID == smaller_edge_id)
{
for (const auto edge_id : facade->GetAdjacentEdgeRange(edge.second))
{
auto const & edgeData = facade->GetEdgeData(edge_id, edge.second);
const int weight = edgeData.distance;
if ((facade->GetTarget(edge_id) == edge.first) && (weight < edge_weight) &&
edgeData.backward)
{
smaller_edge_id = edge_id;
edge_weight = weight;
smaller_node_id = edge.second;
}
}
}
BOOST_ASSERT_MSG(edge_weight != INVALID_EDGE_WEIGHT, "edge id invalid");
const EdgeData &ed = facade->GetEdgeData(smaller_edge_id, smaller_node_id);
if (ed.shortcut)
{ // unpack
const NodeID middle_node_id = ed.id;
// again, we need to this in reversed order
recursion_stack.emplace(middle_node_id, edge.second);
recursion_stack.emplace(edge.first, middle_node_id);
}
else
{
const TravelMode travel_mode = facade->GetTravelModeForEdgeID(ed.id);
unpacked_path.emplace_back(edge.second, INVALID_EDGE_WEIGHT,
TurnInstruction::NoTurn,
ed.distance, travel_mode);
}
}
// there is no equivalent to a node-based node in an edge-expanded graph.
// two equivalent routes may start (or end) at different node-based edges
// as they are added with the offset how much "distance" on the edge
// has already been traversed. Depending on offset one needs to remove
// the last node.
if (unpacked_path.size() > 1)
{
const std::size_t last_index = unpacked_path.size() - 1;
const std::size_t second_to_last_index = last_index - 1;
// looks like a trivially true check but tests for underflow
BOOST_ASSERT(last_index > second_to_last_index);
if (unpacked_path[last_index].node == unpacked_path[second_to_last_index].node)
{
unpacked_path.pop_back();
}
BOOST_ASSERT(!unpacked_path.empty());
}
}
void UnpackEdge(const NodeID s, const NodeID t, std::vector<NodeID> &unpacked_path) const
{
std::stack<std::pair<NodeID, NodeID>> recursion_stack;
recursion_stack.emplace(s, t);
std::pair<NodeID, NodeID> edge;
while (!recursion_stack.empty())
{
edge = recursion_stack.top();
recursion_stack.pop();
EdgeID smaller_edge_id = SPECIAL_EDGEID;
NodeID smaller_node_id = SPECIAL_NODEID;
int edge_weight = std::numeric_limits<EdgeWeight>::max();
for (const auto edge_id : facade->GetAdjacentEdgeRange(edge.first))
{
auto const & edgeData = facade->GetEdgeData(edge_id, edge.first);
const int weight = edgeData.distance;
if ((facade->GetTarget(edge_id) == edge.second) && (weight < edge_weight) &&
edgeData.forward)
{
smaller_edge_id = edge_id;
smaller_node_id = edge.first;
edge_weight = weight;
}
}
if (SPECIAL_EDGEID == smaller_edge_id)
{
for (const auto edge_id : facade->GetAdjacentEdgeRange(edge.second))
{
auto const & edgeData = facade->GetEdgeData(edge_id, edge.second);
const int weight = edgeData.distance;
if ((facade->GetTarget(edge_id) == edge.first) && (weight < edge_weight) &&
edgeData.backward)
{
smaller_edge_id = edge_id;
smaller_node_id = edge.second;
edge_weight = weight;
}
}
}
BOOST_ASSERT_MSG(edge_weight != std::numeric_limits<EdgeWeight>::max(),
"edge weight invalid");
const EdgeData &ed = facade->GetEdgeData(smaller_edge_id, smaller_node_id);
if (ed.shortcut)
{ // unpack
const NodeID middle_node_id = ed.id;
// again, we need to this in reversed order
recursion_stack.emplace(middle_node_id, edge.second);
recursion_stack.emplace(edge.first, middle_node_id);
}
else
{
BOOST_ASSERT_MSG(!ed.shortcut, "edge must be shortcut");
unpacked_path.emplace_back(edge.first);
}
}
unpacked_path.emplace_back(t);
}
void RetrievePackedPathFromHeap(const SearchEngineData::QueryHeap &forward_heap,
const SearchEngineData::QueryHeap &reverse_heap,
const NodeID middle_node_id,
std::vector<NodeID> &packed_path) const
{
RetrievePackedPathFromSingleHeap(forward_heap, middle_node_id, packed_path);
std::reverse(packed_path.begin(), packed_path.end());
packed_path.emplace_back(middle_node_id);
RetrievePackedPathFromSingleHeap(reverse_heap, middle_node_id, packed_path);
}
void RetrievePackedPathFromSingleHeap(const SearchEngineData::QueryHeap &search_heap,
const NodeID middle_node_id,
std::vector<NodeID> &packed_path) const
{
NodeID current_node_id = middle_node_id;
while (current_node_id != search_heap.GetData(current_node_id).parent)
{
current_node_id = search_heap.GetData(current_node_id).parent;
packed_path.emplace_back(current_node_id);
}
}
double get_network_distance(SearchEngineData::QueryHeap &forward_heap,
SearchEngineData::QueryHeap &reverse_heap,
const PhantomNode &source_phantom,
const PhantomNode &target_phantom) const
{
EdgeWeight upper_bound = INVALID_EDGE_WEIGHT;
NodeID middle_node = SPECIAL_NODEID;
EdgeWeight edge_offset = std::min(0, -source_phantom.GetForwardWeightPlusOffset());
edge_offset = std::min(edge_offset, -source_phantom.GetReverseWeightPlusOffset());
if (source_phantom.forward_node_id != SPECIAL_NODEID)
{
forward_heap.Insert(source_phantom.forward_node_id,
-source_phantom.GetForwardWeightPlusOffset(),
source_phantom.forward_node_id);
}
if (source_phantom.reverse_node_id != SPECIAL_NODEID)
{
forward_heap.Insert(source_phantom.reverse_node_id,
-source_phantom.GetReverseWeightPlusOffset(),
source_phantom.reverse_node_id);
}
if (target_phantom.forward_node_id != SPECIAL_NODEID)
{
reverse_heap.Insert(target_phantom.forward_node_id,
target_phantom.GetForwardWeightPlusOffset(),
target_phantom.forward_node_id);
}
if (target_phantom.reverse_node_id != SPECIAL_NODEID)
{
reverse_heap.Insert(target_phantom.reverse_node_id,
target_phantom.GetReverseWeightPlusOffset(),
target_phantom.reverse_node_id);
}
// search from s and t till new_min/(1+epsilon) > length_of_shortest_path
while (0 < (forward_heap.Size() + reverse_heap.Size()))
{
if (0 < forward_heap.Size())
{
RoutingStep(forward_heap, reverse_heap, &middle_node, &upper_bound, edge_offset,
true);
}
if (0 < reverse_heap.Size())
{
RoutingStep(reverse_heap, forward_heap, &middle_node, &upper_bound, edge_offset,
false);
}
}
double distance = std::numeric_limits<double>::max();
if (upper_bound != INVALID_EDGE_WEIGHT)
{
std::vector<NodeID> packed_leg;
RetrievePackedPathFromHeap(forward_heap, reverse_heap, middle_node, packed_leg);
std::vector<PathData> unpacked_path;
PhantomNodes nodes;
nodes.source_phantom = source_phantom;
nodes.target_phantom = target_phantom;
UnpackPath(packed_leg, nodes, unpacked_path);
FixedPointCoordinate previous_coordinate = source_phantom.location;
FixedPointCoordinate current_coordinate;
distance = 0;
for (const auto &p : unpacked_path)
{
current_coordinate = facade->GetCoordinateOfNode(p.node);
distance += coordinate_calculation::great_circle_distance(previous_coordinate,
current_coordinate);
previous_coordinate = current_coordinate;
}
distance += coordinate_calculation::great_circle_distance(previous_coordinate,
target_phantom.location);
}
return distance;
}
};
#endif // ROUTING_BASE_HPP
| 42.137209 | 144 | 0.575363 | [
"vector"
] |
4b5b8587c04e18af0f391f89aea943c4c8bf68f6 | 5,976 | cc | C++ | src/tty_wrap.cc | kurhula/node | ae0299287209e6d1dd0606c885ca087e82ed0e7d | [
"Artistic-2.0"
] | null | null | null | src/tty_wrap.cc | kurhula/node | ae0299287209e6d1dd0606c885ca087e82ed0e7d | [
"Artistic-2.0"
] | null | null | null | src/tty_wrap.cc | kurhula/node | ae0299287209e6d1dd0606c885ca087e82ed0e7d | [
"Artistic-2.0"
] | 1 | 2020-04-13T17:46:42.000Z | 2020-04-13T17:46:42.000Z | // Copyright Joyent, Inc. and other Node contributors.
//
// 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 "tty_wrap.h"
#include "env.h"
#include "env-inl.h"
#include "handle_wrap.h"
#include "node_buffer.h"
#include "node_wrap.h"
#include "req_wrap.h"
#include "stream_wrap.h"
#include "util.h"
#include "util-inl.h"
namespace node {
using v8::Array;
using v8::Context;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Handle;
using v8::HandleScope;
using v8::Integer;
using v8::Local;
using v8::Object;
using v8::PropertyAttribute;
using v8::String;
using v8::Value;
void TTYWrap::Initialize(Handle<Object> target,
Handle<Value> unused,
Handle<Context> context) {
Environment* env = Environment::GetCurrent(context);
Local<FunctionTemplate> t = FunctionTemplate::New(New);
t->SetClassName(FIXED_ONE_BYTE_STRING(node_isolate, "TTY"));
t->InstanceTemplate()->SetInternalFieldCount(1);
enum PropertyAttribute attributes =
static_cast<PropertyAttribute>(v8::ReadOnly | v8::DontDelete);
t->InstanceTemplate()->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "fd"),
StreamWrap::GetFD,
NULL,
Handle<Value>(),
v8::DEFAULT,
attributes);
NODE_SET_PROTOTYPE_METHOD(t, "close", HandleWrap::Close);
NODE_SET_PROTOTYPE_METHOD(t, "unref", HandleWrap::Unref);
NODE_SET_PROTOTYPE_METHOD(t, "readStart", StreamWrap::ReadStart);
NODE_SET_PROTOTYPE_METHOD(t, "readStop", StreamWrap::ReadStop);
NODE_SET_PROTOTYPE_METHOD(t, "writeBuffer", StreamWrap::WriteBuffer);
NODE_SET_PROTOTYPE_METHOD(t,
"writeAsciiString",
StreamWrap::WriteAsciiString);
NODE_SET_PROTOTYPE_METHOD(t, "writeUtf8String", StreamWrap::WriteUtf8String);
NODE_SET_PROTOTYPE_METHOD(t, "writeUcs2String", StreamWrap::WriteUcs2String);
NODE_SET_PROTOTYPE_METHOD(t, "getWindowSize", TTYWrap::GetWindowSize);
NODE_SET_PROTOTYPE_METHOD(t, "setRawMode", SetRawMode);
NODE_SET_METHOD(target, "isTTY", IsTTY);
NODE_SET_METHOD(target, "guessHandleType", GuessHandleType);
target->Set(FIXED_ONE_BYTE_STRING(node_isolate, "TTY"), t->GetFunction());
env->set_tty_constructor_template(t);
}
uv_tty_t* TTYWrap::UVHandle() {
return &handle_;
}
void TTYWrap::GuessHandleType(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate);
int fd = args[0]->Int32Value();
assert(fd >= 0);
uv_handle_type t = uv_guess_handle(fd);
const char* type = NULL;
switch (t) {
case UV_TCP: type = "TCP"; break;
case UV_TTY: type = "TTY"; break;
case UV_UDP: type = "UDP"; break;
case UV_FILE: type = "FILE"; break;
case UV_NAMED_PIPE: type = "PIPE"; break;
case UV_UNKNOWN_HANDLE: type = "UNKNOWN"; break;
default:
abort();
}
args.GetReturnValue().Set(OneByteString(node_isolate, type));
}
void TTYWrap::IsTTY(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate);
int fd = args[0]->Int32Value();
assert(fd >= 0);
bool rc = uv_guess_handle(fd) == UV_TTY;
args.GetReturnValue().Set(rc);
}
void TTYWrap::GetWindowSize(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate);
TTYWrap* wrap = Unwrap<TTYWrap>(args.This());
assert(args[0]->IsArray());
int width, height;
int err = uv_tty_get_winsize(&wrap->handle_, &width, &height);
if (err == 0) {
Local<v8::Array> a = args[0].As<Array>();
a->Set(0, Integer::New(width, node_isolate));
a->Set(1, Integer::New(height, node_isolate));
}
args.GetReturnValue().Set(err);
}
void TTYWrap::SetRawMode(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate);
TTYWrap* wrap = Unwrap<TTYWrap>(args.This());
int err = uv_tty_set_mode(&wrap->handle_, args[0]->IsTrue());
args.GetReturnValue().Set(err);
}
void TTYWrap::New(const FunctionCallbackInfo<Value>& args) {
HandleScope handle_scope(args.GetIsolate());
Environment* env = Environment::GetCurrent(args.GetIsolate());
// This constructor should not be exposed to public javascript.
// Therefore we assert that we are not trying to call this as a
// normal function.
assert(args.IsConstructCall());
int fd = args[0]->Int32Value();
assert(fd >= 0);
TTYWrap* wrap = new TTYWrap(env, args.This(), fd, args[1]->IsTrue());
wrap->UpdateWriteQueueSize();
}
TTYWrap::TTYWrap(Environment* env, Handle<Object> object, int fd, bool readable)
: StreamWrap(env,
object,
reinterpret_cast<uv_stream_t*>(&handle_),
AsyncWrap::PROVIDER_TTYWRAP) {
uv_tty_init(env->event_loop(), &handle_, fd, readable);
}
} // namespace node
NODE_MODULE_CONTEXT_AWARE_BUILTIN(tty_wrap, node::TTYWrap::Initialize)
| 31.957219 | 80 | 0.692102 | [
"object"
] |
4b60e29cf8e0fdf91fc6284aa7e0fdb50f112434 | 78,604 | cc | C++ | src/lib/dhcpsrv/tests/memfile_lease_mgr_unittest.cc | sjbonarrigo/kea | b6bf5214650c0b8ee94027d02f98adb1bfd9a166 | [
"Apache-2.0"
] | null | null | null | src/lib/dhcpsrv/tests/memfile_lease_mgr_unittest.cc | sjbonarrigo/kea | b6bf5214650c0b8ee94027d02f98adb1bfd9a166 | [
"Apache-2.0"
] | null | null | null | src/lib/dhcpsrv/tests/memfile_lease_mgr_unittest.cc | sjbonarrigo/kea | b6bf5214650c0b8ee94027d02f98adb1bfd9a166 | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2012-2019 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <config.h>
#include <asiolink/asio_wrapper.h>
#include <asiolink/interval_timer.h>
#include <asiolink/io_address.h>
#include <dhcp/duid.h>
#include <dhcp/iface_mgr.h>
#include <dhcpsrv/cfgmgr.h>
#include <dhcpsrv/lease_mgr.h>
#include <dhcpsrv/lease_mgr_factory.h>
#include <dhcpsrv/memfile_lease_mgr.h>
#include <dhcpsrv/timer_mgr.h>
#include <dhcpsrv/testutils/lease_file_io.h>
#include <dhcpsrv/tests/test_utils.h>
#include <dhcpsrv/tests/generic_lease_mgr_unittest.h>
#include <util/pid_file.h>
#include <util/range_utilities.h>
#include <util/stopwatch.h>
#include <boost/bind.hpp>
#include <gtest/gtest.h>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <queue>
#include <sstream>
#include <unistd.h>
using namespace std;
using namespace isc;
using namespace isc::asiolink;
using namespace isc::db;
using namespace isc::dhcp;
using namespace isc::dhcp::test;
using namespace isc::util;
namespace {
/// @brief Class derived from @c Memfile_LeaseMgr to test LFC timer.
///
/// This class provides a custom callback function which is invoked
/// when the timer for Lease File Cleanup goes off. It is used to
/// test that the timer is correctly installed.
class LFCMemfileLeaseMgr : public Memfile_LeaseMgr {
public:
/// @brief Constructor.
///
/// Sets the counter for callbacks to 0.
LFCMemfileLeaseMgr(const DatabaseConnection::ParameterMap& parameters)
: Memfile_LeaseMgr(parameters), lfc_cnt_(0) {
}
/// @brief Returns the number of callback executions.
int getLFCCount() {
return (lfc_cnt_);
}
protected:
/// @brief Custom callback.
///
/// This callback function increases the counter of callback executions.
/// By examining the counter value a test may verify that the callback
/// was triggered an expected number of times.
virtual void lfcCallback() {
++lfc_cnt_;
}
private:
/// @brief Counter of callback function executions.
int lfc_cnt_;
};
/// @brief A derivation of the lease manager exposing protected methods.
class NakedMemfileLeaseMgr : public Memfile_LeaseMgr {
public:
/// @brief Constructor.
///
/// Creates instance of the lease manager.
NakedMemfileLeaseMgr(const DatabaseConnection::ParameterMap& parameters)
: Memfile_LeaseMgr(parameters) {
}
using Memfile_LeaseMgr::lfcCallback;
};
/// @brief Test fixture class for @c Memfile_LeaseMgr
class MemfileLeaseMgrTest : public GenericLeaseMgrTest {
public:
/// @brief memfile lease mgr test constructor
///
/// Creates memfile and stores it in lmptr_ pointer
MemfileLeaseMgrTest() :
io4_(getLeaseFilePath("leasefile4_0.csv")),
io6_(getLeaseFilePath("leasefile6_0.csv")),
io_service_(new IOService()),
timer_mgr_(TimerMgr::instance()) {
timer_mgr_->setIOService(io_service_);
std::ostringstream s;
s << KEA_LFC_BUILD_DIR << "/kea-lfc";
setenv("KEA_LFC_EXECUTABLE", s.str().c_str(), 1);
// Remove lease files and products of Lease File Cleanup.
removeFiles(getLeaseFilePath("leasefile4_0.csv"));
removeFiles(getLeaseFilePath("leasefile6_0.csv"));
}
/// @brief Reopens the connection to the backend.
///
/// This function is called by unit tests to force reconnection of the
/// backend to check that the leases are stored and can be retrieved
/// from the storage.
///
/// @param u Universe (V4 or V6)
virtual void reopen(Universe u) {
LeaseMgrFactory::destroy();
startBackend(u);
}
/// @brief destructor
///
/// destroys lease manager backend.
virtual ~MemfileLeaseMgrTest() {
// Stop TimerMgr worker thread if it is running.
// Make sure there are no timers registered.
timer_mgr_->unregisterTimers();
LeaseMgrFactory::destroy();
// Remove lease files and products of Lease File Cleanup.
removeFiles(getLeaseFilePath("leasefile4_0.csv"));
removeFiles(getLeaseFilePath("leasefile6_0.csv"));
}
/// @brief Remove files being products of Lease File Cleanup.
///
/// @param base_name Path to the lease file name. This file is removed
/// and all files which names are created from this name (having specific
/// suffixes used by Lease File Cleanup mechanism).
void removeFiles(const std::string& base_name) const {
// Generate suffixes and append them to the base name. The
// resulting file names are the ones that may exist as a
// result of LFC.
for (int i = static_cast<int>(Memfile_LeaseMgr::FILE_CURRENT);
i <= static_cast<int>(Memfile_LeaseMgr::FILE_FINISH);
++i) {
Memfile_LeaseMgr::LFCFileType type = static_cast<
Memfile_LeaseMgr::LFCFileType>(i);
LeaseFileIO io(Memfile_LeaseMgr::appendSuffix(base_name, type));
io.removeFile();
}
}
/// @brief Return path to the lease file used by unit tests.
///
/// @param filename Name of the lease file appended to the path to the
/// directory where test data is held.
///
/// @return Full path to the lease file.
static std::string getLeaseFilePath(const std::string& filename) {
std::ostringstream s;
s << TEST_DATA_BUILDDIR << "/" << filename;
return (s.str());
}
/// @brief Returns the configuration string for the backend.
///
/// This string configures the @c LeaseMgrFactory to create the memfile
/// backend and use leasefile4_0.csv and leasefile6_0.csv files as
/// storage for leases.
///
/// @param no_universe Indicates whether universe parameter should be
/// included (false), or not (true).
///
/// @return Configuration string for @c LeaseMgrFactory.
static std::string getConfigString(Universe u) {
std::ostringstream s;
s << "type=memfile " << (u == V4 ? "universe=4 " : "universe=6 ")
<< "name="
<< getLeaseFilePath(u == V4 ? "leasefile4_0.csv" : "leasefile6_0.csv")
<< " lfc-interval=0";
return (s.str());
}
/// @brief Creates instance of the backend.
///
/// @param u Universe (v4 or V6).
void startBackend(Universe u) {
try {
LeaseMgrFactory::create(getConfigString(u));
} catch (...) {
std::cerr << "*** ERROR: unable to create instance of the Memfile\n"
" lease database backend.\n";
throw;
}
lmptr_ = &(LeaseMgrFactory::instance());
}
/// @brief Runs @c IfaceMgr::receive6 in a look for a specified time.
///
/// @param ms Duration in milliseconds.
void setTestTime(const uint32_t ms) {
IntervalTimer timer(*io_service_);
timer.setup([this]() {
io_service_->stop();
}, ms, IntervalTimer::ONE_SHOT);
io_service_->run();
io_service_->get_io_service().reset();
}
/// @brief Waits for the specified process to finish.
///
/// @param process An object which started the process.
/// @param timeout Timeout in seconds.
///
/// @return true if the process ended, false otherwise
bool waitForProcess(const Memfile_LeaseMgr& lease_mgr,
const uint8_t timeout) {
uint32_t iterations = 0;
const uint32_t iterations_max = timeout * 1000;
while (lease_mgr.isLFCRunning() && (iterations < iterations_max)) {
usleep(1000);
++iterations;
}
return (iterations < iterations_max);
}
/// @brief Generates a DHCPv4 lease with random content.
///
/// The following lease parameters are randomly generated:
/// - HW address,
/// - client identifier,
/// - hostname,
/// - subnet identifier,
/// - client last transmission time,
///
/// The following lease parameters are set to constant values:
/// - valid lifetime = 1200,
/// - T1 = 600,
/// - T2 = 900,
/// - DNS update forward flag = false,
/// - DNS update reverse flag = false,
///
/// The lease address is set to address passed as function
/// argument.
///
/// @param address Lease address.
///
/// @return new lease with random content
Lease4Ptr initiateRandomLease4(const IOAddress& address) {
// Randomize HW address.
vector<uint8_t> mac(6);
fillRandom(mac.begin(), mac.end());
HWAddrPtr hwaddr(new HWAddr(mac, HTYPE_ETHER));
// Let's generate clientid of random length
vector<uint8_t> clientid(4 + random()%20);
// And then fill it with random value.
fillRandom(clientid.begin(), clientid.end());
uint32_t valid_lft = 1200;
uint32_t t1 = 600;
uint32_t t2 = 900;
time_t timestamp = time(NULL) - 86400 + random()%86400;
bool fqdn_fwd = false;
bool fqdn_rev = false;
uint32_t subnet_id = 1000 + random()%16;
std::ostringstream hostname;
hostname << "hostname" << (random() % 2048);
// Return created lease.
return (Lease4Ptr(new Lease4(address, hwaddr, &clientid[0],
clientid.size(), valid_lft, t1, t2,
timestamp, subnet_id, fqdn_fwd,
fqdn_rev, hostname.str())));
}
/// @brief Generates a DHCPv6 lease with random content.
///
/// The following lease parameters are randomly generated:
/// - DUID,
/// - IAID,
/// - hostname,
/// - subnet identifier,
/// - client last transmission time,
///
/// The following lease parameters are set to constant values:
/// - lease type = IA_NA
/// - valid lifetime = 1200,
/// - preferred lifetime = 1000
/// - T1 = 600,
/// - T2 = 900,
/// - DNS update forward flag = false,
/// - DNS update reverse flag = false,
///
/// The lease address is set to address passed as function
/// argument.
///
/// @param address Lease address.
///
/// @return new lease with random content
Lease6Ptr initiateRandomLease6(const IOAddress& address) {
// Let's generate DUID of random length.
std::vector<uint8_t> duid_vec(8 + random()%20);
// And then fill it with random value.
fillRandom(duid_vec.begin(), duid_vec.end());
DuidPtr duid(new DUID(duid_vec));
Lease::Type lease_type = Lease::TYPE_NA;
uint32_t iaid = 1 + random()%100;
uint32_t valid_lft = 1200;
uint32_t preferred_lft = 1000;
uint32_t t1 = 600;
uint32_t t2 = 900;
time_t timestamp = time(NULL) - 86400 + random()%86400;
bool fqdn_fwd = false;
bool fqdn_rev = false;
uint32_t subnet_id = 1000 + random()%16;
std::ostringstream hostname;
hostname << "hostname" << (random() % 2048);
// Return created lease.
Lease6Ptr lease(new Lease6(lease_type, address, duid, iaid,
preferred_lft, valid_lft, t1, t2,
subnet_id, fqdn_fwd, fqdn_rev,
hostname.str()));
lease->cltt_ = timestamp;
return (lease);
}
/// @brief Object providing access to v4 lease IO.
LeaseFileIO io4_;
/// @brief Object providing access to v6 lease IO.
LeaseFileIO io6_;
/// @brief Pointer to the IO service used by the tests.
IOServicePtr io_service_;
/// @brief Pointer to the instance of the @c TimerMgr.
TimerMgrPtr timer_mgr_;
};
// This test checks if the LeaseMgr can be instantiated and that it
// parses parameters string properly.
TEST_F(MemfileLeaseMgrTest, constructor) {
DatabaseConnection::ParameterMap pmap;
pmap["universe"] = "4";
pmap["persist"] = "false";
boost::scoped_ptr<Memfile_LeaseMgr> lease_mgr;
EXPECT_NO_THROW(lease_mgr.reset(new Memfile_LeaseMgr(pmap)));
pmap["lfc-interval"] = "10";
pmap["persist"] = "true";
pmap["name"] = getLeaseFilePath("leasefile4_1.csv");
pmap["max-row-errors"] = "5";
EXPECT_NO_THROW(lease_mgr.reset(new Memfile_LeaseMgr(pmap)));
// Expecting that persist parameter is yes or no. Everything other than
// that is wrong.
pmap["persist"] = "bogus";
pmap["name"] = getLeaseFilePath("leasefile4_1.csv");
EXPECT_THROW(lease_mgr.reset(new Memfile_LeaseMgr(pmap)), isc::BadValue);
// The lfc-interval must be an integer.
pmap["persist"] = "true";
pmap["lfc-interval"] = "bogus";
EXPECT_THROW(lease_mgr.reset(new Memfile_LeaseMgr(pmap)), isc::BadValue);
// The max-row-errors must be an integer.
pmap["persist"] = "true";
pmap["max-row-errors"] = "bogus";
EXPECT_THROW(lease_mgr.reset(new Memfile_LeaseMgr(pmap)), isc::BadValue);
// The max-row-errors must be >= 0.
pmap["persist"] = "true";
pmap["max-row-errors"] = "-1";
EXPECT_THROW(lease_mgr.reset(new Memfile_LeaseMgr(pmap)), isc::BadValue);
}
// Checks if there is no lease manager NoLeaseManager is thrown.
TEST_F(MemfileLeaseMgrTest, noLeaseManager) {
LeaseMgrFactory::destroy();
EXPECT_THROW(LeaseMgrFactory::instance(), NoLeaseManager);
}
// Checks if the getType() and getName() methods both return "memfile".
TEST_F(MemfileLeaseMgrTest, getTypeAndName) {
startBackend(V4);
EXPECT_EQ(std::string("memfile"), lmptr_->getType());
EXPECT_EQ(std::string("memory"), lmptr_->getName());
}
// Checks if the path to the lease files is initialized correctly.
TEST_F(MemfileLeaseMgrTest, getLeaseFilePath) {
// Initialize IO objects, so as the test csv files get removed after the
// test (when destructors are called).
LeaseFileIO io4(getLeaseFilePath("leasefile4_1.csv"));
LeaseFileIO io6(getLeaseFilePath("leasefile6_1.csv"));
DatabaseConnection::ParameterMap pmap;
pmap["universe"] = "4";
pmap["name"] = getLeaseFilePath("leasefile4_1.csv");
boost::scoped_ptr<Memfile_LeaseMgr> lease_mgr(new Memfile_LeaseMgr(pmap));
EXPECT_EQ(pmap["name"],
lease_mgr->getLeaseFilePath(Memfile_LeaseMgr::V4));
pmap["persist"] = "false";
lease_mgr.reset(new Memfile_LeaseMgr(pmap));
EXPECT_TRUE(lease_mgr->getLeaseFilePath(Memfile_LeaseMgr::V4).empty());
EXPECT_TRUE(lease_mgr->getLeaseFilePath(Memfile_LeaseMgr::V6).empty());
}
// Check if the persistLeases correctly checks that leases should not be written
// to disk when disabled through configuration.
TEST_F(MemfileLeaseMgrTest, persistLeases) {
// Initialize IO objects, so as the test csv files get removed after the
// test (when destructors are called).
LeaseFileIO io4(getLeaseFilePath("leasefile4_1.csv"));
LeaseFileIO io6(getLeaseFilePath("leasefile6_1.csv"));
DatabaseConnection::ParameterMap pmap;
pmap["universe"] = "4";
pmap["lfc-interval"] = "0";
// Specify the names of the lease files. Leases will be written.
pmap["name"] = getLeaseFilePath("leasefile4_1.csv");
boost::scoped_ptr<Memfile_LeaseMgr> lease_mgr(new Memfile_LeaseMgr(pmap));
lease_mgr.reset(new Memfile_LeaseMgr(pmap));
EXPECT_TRUE(lease_mgr->persistLeases(Memfile_LeaseMgr::V4));
EXPECT_FALSE(lease_mgr->persistLeases(Memfile_LeaseMgr::V6));
pmap["universe"] = "6";
pmap["name"] = getLeaseFilePath("leasefile6_1.csv");
lease_mgr.reset(new Memfile_LeaseMgr(pmap));
EXPECT_FALSE(lease_mgr->persistLeases(Memfile_LeaseMgr::V4));
EXPECT_TRUE(lease_mgr->persistLeases(Memfile_LeaseMgr::V6));
// This should disable writes of leases to disk.
pmap["persist"] = "false";
lease_mgr.reset(new Memfile_LeaseMgr(pmap));
EXPECT_FALSE(lease_mgr->persistLeases(Memfile_LeaseMgr::V4));
EXPECT_FALSE(lease_mgr->persistLeases(Memfile_LeaseMgr::V6));
}
// Check if it is possible to schedule the timer to perform the Lease
// File Cleanup periodically.
TEST_F(MemfileLeaseMgrTest, lfcTimer) {
DatabaseConnection::ParameterMap pmap;
pmap["type"] = "memfile";
pmap["universe"] = "4";
// Specify the names of the lease files. Leases will be written.
pmap["name"] = getLeaseFilePath("leasefile4_0.csv");
pmap["lfc-interval"] = "1";
boost::scoped_ptr<LFCMemfileLeaseMgr>
lease_mgr(new LFCMemfileLeaseMgr(pmap));
// Run the test for at most 2.9 seconds.
setTestTime(2900);
// Within 2.9 we should record two LFC executions.
EXPECT_EQ(2, lease_mgr->getLFCCount());
}
// This test checks if the LFC timer is disabled (doesn't trigger)
// cleanups when the lfc-interval is set to 0.
TEST_F(MemfileLeaseMgrTest, lfcTimerDisabled) {
DatabaseConnection::ParameterMap pmap;
pmap["type"] = "memfile";
pmap["universe"] = "4";
pmap["name"] = getLeaseFilePath("leasefile4_0.csv");
// Set the LFC interval to 0, which should effectively disable it.
pmap["lfc-interval"] = "0";
boost::scoped_ptr<LFCMemfileLeaseMgr>
lease_mgr(new LFCMemfileLeaseMgr(pmap));
// Run the test for at most 1.9 seconds.
setTestTime(1900);
// There should be no LFC execution recorded.
EXPECT_EQ(0, lease_mgr->getLFCCount());
}
// This test checks that the callback function executing the cleanup of the
// DHCPv4 lease file works as expected.
TEST_F(MemfileLeaseMgrTest, leaseFileCleanup4) {
// This string contains the lease file header, which matches
// the contents of the new file in which no leases have been
// stored.
std::string new_file_contents =
"address,hwaddr,client_id,valid_lifetime,expire,"
"subnet_id,fqdn_fwd,fqdn_rev,hostname,state,user_context\n";
// This string contains the contents of the lease file with exactly
// one lease, but two entries. One of the entries should be removed
// as a result of lease file cleanup.
std::string current_file_contents = new_file_contents +
"192.0.2.2,02:02:02:02:02:02,,200,200,8,1,1,,1,{ \"foo\": true }\n"
"192.0.2.2,02:02:02:02:02:02,,200,800,8,1,1,,1,\n";
LeaseFileIO current_file(getLeaseFilePath("leasefile4_0.csv"));
current_file.writeFile(current_file_contents);
std::string previous_file_contents = new_file_contents +
"192.0.2.3,03:03:03:03:03:03,,200,200,8,1,1,,1,\n"
"192.0.2.3,03:03:03:03:03:03,,200,800,8,1,1,,1,{ \"bar\": true }\n";
LeaseFileIO previous_file(getLeaseFilePath("leasefile4_0.csv.2"));
previous_file.writeFile(previous_file_contents);
// Create the backend.
DatabaseConnection::ParameterMap pmap;
pmap["type"] = "memfile";
pmap["universe"] = "4";
pmap["name"] = getLeaseFilePath("leasefile4_0.csv");
pmap["lfc-interval"] = "1";
boost::scoped_ptr<NakedMemfileLeaseMgr> lease_mgr(new NakedMemfileLeaseMgr(pmap));
// Try to run the lease file cleanup.
ASSERT_NO_THROW(lease_mgr->lfcCallback());
// The new lease file should have been created and it should contain
// no leases.
ASSERT_TRUE(current_file.exists());
EXPECT_EQ(new_file_contents, current_file.readFile());
// Wait for the LFC process to complete.
ASSERT_TRUE(waitForProcess(*lease_mgr, 2));
// And make sure it has returned an exit status of 0.
EXPECT_EQ(0, lease_mgr->getLFCExitStatus())
<< "Executing the LFC process failed: make sure that"
" the kea-lfc program has been compiled.";
// Check if we can still write to the lease file.
std::vector<uint8_t> hwaddr_vec(6);
HWAddrPtr hwaddr(new HWAddr(hwaddr_vec, HTYPE_ETHER));
Lease4Ptr new_lease(new Lease4(IOAddress("192.0.2.45"), hwaddr,
static_cast<const uint8_t*>(0), 0,
100, 50, 60, 0, 1));
ASSERT_NO_THROW(lease_mgr->addLease(new_lease));
std::string updated_file_contents = new_file_contents +
"192.0.2.45,00:00:00:00:00:00,,100,100,1,0,0,,0,\n";
EXPECT_EQ(updated_file_contents, current_file.readFile());
// This string contains the contents of the lease file we
// expect after the LFC run. It has two leases with one
// entry each.
std::string result_file_contents = new_file_contents +
"192.0.2.2,02:02:02:02:02:02,,200,800,8,1,1,,1,\n"
"192.0.2.3,03:03:03:03:03:03,,200,800,8,1,1,,1,{ \"bar\": true }\n";
// The LFC should have created a file with the two leases and moved it
// to leasefile4_0.csv.2
LeaseFileIO input_file(getLeaseFilePath("leasefile4_0.csv.2"), false);
ASSERT_TRUE(input_file.exists());
// And this file should contain the contents of the result file.
EXPECT_EQ(result_file_contents, input_file.readFile());
}
// This test checks that the callback function executing the cleanup of the
// DHCPv6 lease file works as expected.
TEST_F(MemfileLeaseMgrTest, leaseFileCleanup6) {
// This string contains the lease file header, which matches
// the contents of the new file in which no leases have been
// stored.
std::string new_file_contents =
"address,duid,valid_lifetime,expire,subnet_id,"
"pref_lifetime,lease_type,iaid,prefix_len,fqdn_fwd,"
"fqdn_rev,hostname,hwaddr,state,user_context\n";
// This string contains the contents of the lease file with exactly
// one lease, but two entries. One of the entries should be removed
// as a result of lease file cleanup.
std::string current_file_contents = new_file_contents +
"2001:db8:1::1,00:01:02:03:04:05:06:0a:0b:0c:0d:0e:0f,200,200,"
"8,100,0,7,0,1,1,,,1,\n"
"2001:db8:1::1,00:01:02:03:04:05:06:0a:0b:0c:0d:0e:0f,200,800,"
"8,100,0,7,0,1,1,,,1,{ \"foo\": true }\n";
LeaseFileIO current_file(getLeaseFilePath("leasefile6_0.csv"));
current_file.writeFile(current_file_contents);
std::string previous_file_contents = new_file_contents +
"2001:db8:1::2,01:01:01:01:01:01:01:01:01:01:01:01:01,200,200,"
"8,100,0,7,0,1,1,,,1,{ \"bar\": true }\n"
"2001:db8:1::2,01:01:01:01:01:01:01:01:01:01:01:01:01,200,800,"
"8,100,0,7,0,1,1,,,1,\n";
LeaseFileIO previous_file(getLeaseFilePath("leasefile6_0.csv.2"));
previous_file.writeFile(previous_file_contents);
// Create the backend.
DatabaseConnection::ParameterMap pmap;
pmap["type"] = "memfile";
pmap["universe"] = "6";
pmap["name"] = getLeaseFilePath("leasefile6_0.csv");
pmap["lfc-interval"] = "1";
boost::scoped_ptr<NakedMemfileLeaseMgr> lease_mgr(new NakedMemfileLeaseMgr(pmap));
// Try to run the lease file cleanup.
ASSERT_NO_THROW(lease_mgr->lfcCallback());
// The new lease file should have been created and it should contain
// no leases.
ASSERT_TRUE(current_file.exists());
EXPECT_EQ(new_file_contents, current_file.readFile());
// Wait for the LFC process to complete.
ASSERT_TRUE(waitForProcess(*lease_mgr, 2));
// And make sure it has returned an exit status of 0.
EXPECT_EQ(0, lease_mgr->getLFCExitStatus())
<< "Executing the LFC process failed: make sure that"
" the kea-lfc program has been compiled.";
// Check if we can still write to the lease file.
std::vector<uint8_t> duid_vec(13);
DuidPtr duid(new DUID(duid_vec));
Lease6Ptr new_lease(new Lease6(Lease::TYPE_NA, IOAddress("3000::1"),duid,
123, 300, 400, 100, 300, 2));
new_lease->cltt_ = 0;
ASSERT_NO_THROW(lease_mgr->addLease(new_lease));
std::string update_file_contents = new_file_contents +
"3000::1,00:00:00:00:00:00:00:00:00:00:00:00:00,400,"
"400,2,300,0,123,128,0,0,,,0,\n";
EXPECT_EQ(update_file_contents, current_file.readFile());
// This string contains the contents of the lease file we
// expect after the LFC run. It has two leases with one
// entry each.
std::string result_file_contents = new_file_contents +
"2001:db8:1::1,00:01:02:03:04:05:06:0a:0b:0c:0d:0e:0f,200,800,"
"8,100,0,7,0,1,1,,,1,{ \"foo\": true }\n"
"2001:db8:1::2,01:01:01:01:01:01:01:01:01:01:01:01:01,200,800,"
"8,100,0,7,0,1,1,,,1,\n";
// The LFC should have created a file with the two leases and moved it
// to leasefile6_0.csv.2
LeaseFileIO input_file(getLeaseFilePath("leasefile6_0.csv.2"), false);
ASSERT_TRUE(input_file.exists());
// And this file should contain the contents of the result file.
EXPECT_EQ(result_file_contents, input_file.readFile());
}
// This test verifies that EXIT_FAILURE status code is returned when
// the LFC process fails to start.
TEST_F(MemfileLeaseMgrTest, leaseFileCleanupStartFail) {
// This string contains the lease file header, which matches
// the contents of the new file in which no leases have been
// stored.
std::string new_file_contents =
"address,hwaddr,client_id,valid_lifetime,expire,"
"subnet_id,fqdn_fwd,fqdn_rev,hostname,state,user_context\n";
// Create the lease file to be used by the backend.
std::string current_file_contents = new_file_contents +
"192.0.2.2,02:02:02:02:02:02,,200,200,8,1,1,,1,\n";
LeaseFileIO current_file(getLeaseFilePath("leasefile4_0.csv"));
current_file.writeFile(current_file_contents);
// Specify invalid path to the kea-lfc executable. This should result
// in failure status code returned by the child process.
setenv("KEA_LFC_EXECUTABLE", "foobar", 1);
// Create the backend.
DatabaseConnection::ParameterMap pmap;
pmap["type"] = "memfile";
pmap["universe"] = "4";
pmap["name"] = getLeaseFilePath("leasefile4_0.csv");
pmap["lfc-interval"] = "1";
boost::scoped_ptr<NakedMemfileLeaseMgr> lease_mgr(new NakedMemfileLeaseMgr(pmap));
// Try to run the lease file cleanup.
ASSERT_NO_THROW(lease_mgr->lfcCallback());
// Wait for the LFC process to complete.
ASSERT_TRUE(waitForProcess(*lease_mgr, 2));
// And make sure it has returned an error.
EXPECT_EQ(EXIT_FAILURE, lease_mgr->getLFCExitStatus())
<< "Executing the LFC process failed: make sure that"
" the kea-lfc program has been compiled.";
}
// This test checks that the callback function executing the cleanup of the
// files doesn't move the current file if the finish file exists
TEST_F(MemfileLeaseMgrTest, leaseFileFinish) {
// This string contains the lease file header, which matches
// the contents of the new file in which no leases have been
// stored.
std::string new_file_contents =
"address,duid,valid_lifetime,expire,subnet_id,"
"pref_lifetime,lease_type,iaid,prefix_len,fqdn_fwd,"
"fqdn_rev,hostname,hwaddr,state,user_context\n";
// This string contains the contents of the current lease file.
// It should not be moved.
std::string current_file_contents = new_file_contents +
"2001:db8:1::1,00:01:02:03:04:05:06:0a:0b:0c:0d:0e:0f,200,200,"
"8,100,0,7,0,1,1,,,1,\n"
"2001:db8:1::1,00:01:02:03:04:05:06:0a:0b:0c:0d:0e:0f,200,800,"
"8,100,0,7,0,1,1,,,1,\n";
LeaseFileIO current_file(getLeaseFilePath("leasefile6_0.csv"));
current_file.writeFile(current_file_contents);
// This string contains the contents of the finish file. It should
// be moved to the previous file.
std::string finish_file_contents = new_file_contents +
"2001:db8:1::2,01:01:01:01:01:01:01:01:01:01:01:01:01,200,800,"
"8,100,0,7,0,1,1,,,1,\n";
LeaseFileIO finish_file(getLeaseFilePath("leasefile6_0.csv.completed"));
finish_file.writeFile(finish_file_contents);
// Create the backend.
DatabaseConnection::ParameterMap pmap;
pmap["type"] = "memfile";
pmap["universe"] = "6";
pmap["name"] = getLeaseFilePath("leasefile6_0.csv");
pmap["lfc-interval"] = "1";
boost::scoped_ptr<NakedMemfileLeaseMgr> lease_mgr(new NakedMemfileLeaseMgr(pmap));
// Try to run the lease file cleanup.
ASSERT_NO_THROW(lease_mgr->lfcCallback());
// The current lease file should not have been touched.
ASSERT_TRUE(current_file.exists());
EXPECT_EQ(current_file_contents, current_file.readFile());
// Wait for the LFC process to complete.
ASSERT_TRUE(waitForProcess(*lease_mgr, 5));
// And make sure it has returned an exit status of 0.
EXPECT_EQ(0, lease_mgr->getLFCExitStatus())
<< "Executing the LFC process failed: make sure that"
" the kea-lfc program has been compiled.";
// The LFC should have moved the finish file to the previous file -
// leasefile6_0.csv.2
LeaseFileIO previous_file(getLeaseFilePath("leasefile6_0.csv.2"), false);
ASSERT_TRUE(previous_file.exists());
// And this file should contain the contents of the finish file.
EXPECT_EQ(finish_file_contents, previous_file.readFile());
// The finish file should have been removed
ASSERT_FALSE(finish_file.exists());
}
// This test checks that the callback function executing the cleanup of the
// files doesn't move the current file if the copy file exists
TEST_F(MemfileLeaseMgrTest, leaseFileCopy) {
// This string contains the lease file header, which matches
// the contents of the new file in which no leases have been
// stored.
std::string new_file_contents =
"address,duid,valid_lifetime,expire,subnet_id,"
"pref_lifetime,lease_type,iaid,prefix_len,fqdn_fwd,"
"fqdn_rev,hostname,hwaddr,state,user_context\n";
// This string contains the contents of the current lease file.
// It should not be moved.
std::string current_file_contents = new_file_contents +
"2001:db8:1::1,00:01:02:03:04:05:06:0a:0b:0c:0d:0e:0f,200,200,"
"8,100,0,7,0,1,1,,,1,\n"
"2001:db8:1::1,00:01:02:03:04:05:06:0a:0b:0c:0d:0e:0f,200,800,"
"8,100,0,7,0,1,1,,,1,{ \"foo\": true }\n";
LeaseFileIO current_file(getLeaseFilePath("leasefile6_0.csv"));
current_file.writeFile(current_file_contents);
// This string contains the contents of the copy file. It should
// be processed and moved to the previous file. As there is only
// one lease the processing should result in the previous file being
// the same.
std::string input_file_contents = new_file_contents +
"2001:db8:1::2,01:01:01:01:01:01:01:01:01:01:01:01:01,200,800,"
"8,100,0,7,0,1,1,,,1,{ \"foo\": true }\n";
LeaseFileIO input_file(getLeaseFilePath("leasefile6_0.csv.1"));
input_file.writeFile(input_file_contents);
// Create the backend.
DatabaseConnection::ParameterMap pmap;
pmap["type"] = "memfile";
pmap["universe"] = "6";
pmap["name"] = getLeaseFilePath("leasefile6_0.csv");
pmap["lfc-interval"] = "1";
boost::scoped_ptr<NakedMemfileLeaseMgr> lease_mgr(new NakedMemfileLeaseMgr(pmap));
// Try to run the lease file cleanup.
ASSERT_NO_THROW(lease_mgr->lfcCallback());
// The current lease file should not have been touched.
ASSERT_TRUE(current_file.exists());
EXPECT_EQ(current_file_contents, current_file.readFile());
// Wait for the LFC process to complete.
ASSERT_TRUE(waitForProcess(*lease_mgr, 5));
// And make sure it has returned an exit status of 0.
EXPECT_EQ(0, lease_mgr->getLFCExitStatus())
<< "Executing the LFC process failed: make sure that"
" the kea-lfc program has been compiled.";
// The LFC should have processed the lease and moved it to the previous
// file - leasefile6_0.csv.2
LeaseFileIO previous_file(getLeaseFilePath("leasefile6_0.csv.2"), false);
ASSERT_TRUE(previous_file.exists());
// And this file should contain the contents of the copy file.
EXPECT_EQ(input_file_contents, previous_file.readFile());
// The input file should have been removed
ASSERT_FALSE(input_file.exists());
}
// Checks that adding/getting/deleting a Lease6 object works.
TEST_F(MemfileLeaseMgrTest, addGetDelete6) {
startBackend(V6);
testAddGetDelete6(true); // true - check T1,T2 values
// memfile is able to preserve those values, but some other
// backends can't do that.
}
/// @brief Basic Lease4 Checks
///
/// Checks that the addLease, getLease4 (by address) and deleteLease (with an
/// IPv4 address) works.
TEST_F(MemfileLeaseMgrTest, basicLease4) {
startBackend(V4);
testBasicLease4();
}
/// @todo Write more memfile tests
// Simple test about lease4 retrieval through client id method
TEST_F(MemfileLeaseMgrTest, getLease4ClientId) {
startBackend(V4);
testGetLease4ClientId();
}
// Checks that lease4 retrieval client id is null is working
TEST_F(MemfileLeaseMgrTest, getLease4NullClientId) {
startBackend(V4);
testGetLease4NullClientId();
}
// Checks lease4 retrieval through HWAddr
TEST_F(MemfileLeaseMgrTest, getLease4HWAddr1) {
startBackend(V4);
testGetLease4HWAddr1();
}
/// @brief Check GetLease4 methods - access by Hardware Address
///
/// Adds leases to the database and checks that they can be accessed via
/// a combination of DUID and IAID.
TEST_F(MemfileLeaseMgrTest, getLease4HWAddr2) {
startBackend(V4);
testGetLease4HWAddr2();
}
// Checks lease4 retrieval with clientId, HWAddr and subnet_id
TEST_F(MemfileLeaseMgrTest, getLease4ClientIdHWAddrSubnetId) {
startBackend(V4);
testGetLease4ClientIdHWAddrSubnetId();
}
/// @brief Basic Lease4 Checks
///
/// Checks that the addLease, getLease4(by address), getLease4(hwaddr,subnet_id),
/// updateLease4() and deleteLease can handle NULL client-id.
/// (client-id is optional and may not be present)
TEST_F(MemfileLeaseMgrTest, lease4NullClientId) {
startBackend(V4);
testLease4NullClientId();
}
/// @brief Check GetLease4 methods - access by Hardware Address & Subnet ID
///
/// Adds leases to the database and checks that they can be accessed via
/// a combination of hardware address and subnet ID
TEST_F(MemfileLeaseMgrTest, DISABLED_getLease4HwaddrSubnetId) {
/// @todo: fails on memfile. It's probably a memfile bug.
startBackend(V4);
testGetLease4HWAddrSubnetId();
}
/// @brief Check GetLease4 methods - access by Client ID
///
/// Adds leases to the database and checks that they can be accessed via
/// the Client ID.
TEST_F(MemfileLeaseMgrTest, getLease4ClientId2) {
startBackend(V4);
testGetLease4ClientId2();
}
// @brief Get Lease4 by client ID
//
// Check that the system can cope with a client ID of any size.
TEST_F(MemfileLeaseMgrTest, getLease4ClientIdSize) {
startBackend(V4);
testGetLease4ClientIdSize();
}
/// @brief Check GetLease4 methods - access by Client ID & Subnet ID
///
/// Adds leases to the database and checks that they can be accessed via
/// a combination of client and subnet IDs.
TEST_F(MemfileLeaseMgrTest, getLease4ClientIdSubnetId) {
startBackend(V4);
testGetLease4ClientIdSubnetId();
}
// This test checks that all IPv4 leases for a specified subnet id are returned.
TEST_F(MemfileLeaseMgrTest, getLeases4SubnetId) {
startBackend(V4);
testGetLeases4SubnetId();
}
// This test checks that all IPv4 leases are returned.
TEST_F(MemfileLeaseMgrTest, getLeases4) {
startBackend(V4);
testGetLeases4();
}
// Test that a range of IPv4 leases is returned with paging.
TEST_F(MemfileLeaseMgrTest, getLeases4Paged) {
startBackend(V4);
testGetLeases4Paged();
}
// This test checks that all IPv6 leases for a specified subnet id are returned.
TEST_F(MemfileLeaseMgrTest, getLeases6SubnetId) {
startBackend(V6);
testGetLeases6SubnetId();
}
// This test adds 3 leases and verifies fetch by DUID.
// Verifies retrival of non existant DUID fails
TEST_F(MemfileLeaseMgrTest, getLeases6Duid) {
startBackend(V6);
testGetLeases6Duid();
}
// This test checks that all IPv6 leases are returned.
TEST_F(MemfileLeaseMgrTest, getLeases6) {
startBackend(V6);
testGetLeases6();
}
// Test that a range of IPv6 leases is returned with paging.
TEST_F(MemfileLeaseMgrTest, getLeases6Paged) {
startBackend(V6);
testGetLeases6Paged();
}
/// @brief Basic Lease6 Checks
///
/// Checks that the addLease, getLease6 (by address) and deleteLease (with an
/// IPv6 address) works.
TEST_F(MemfileLeaseMgrTest, basicLease6) {
startBackend(V6);
testBasicLease6();
}
/// @brief Check GetLease6 methods - access by DUID/IAID
///
/// Adds leases to the database and checks that they can be accessed via
/// a combination of DUID and IAID.
/// @todo: test disabled, because Memfile_LeaseMgr::getLeases6(Lease::Type,
/// const DUID& duid, uint32_t iaid) const is not implemented yet.
TEST_F(MemfileLeaseMgrTest, getLeases6DuidIaid) {
startBackend(V6);
testGetLeases6DuidIaid();
}
/// @brief Check that the system can cope with a DUID of allowed size.
TEST_F(MemfileLeaseMgrTest, getLeases6DuidSize) {
startBackend(V6);
testGetLeases6DuidSize();
}
/// @brief Check that the expired DHCPv4 leases can be retrieved.
///
/// This test adds a number of leases to the lease database and marks
/// some of them as expired. Then it queries for expired leases and checks
/// whether only expired leases are returned, and that they are returned in
/// the order from most to least expired. It also checks that the lease
/// which is marked as 'reclaimed' is not returned.
TEST_F(MemfileLeaseMgrTest, getExpiredLeases4) {
startBackend(V4);
testGetExpiredLeases4();
}
/// @brief Check that the expired DHCPv6 leases can be retrieved.
///
/// This test adds a number of leases to the lease database and marks
/// some of them as expired. Then it queries for expired leases and checks
/// whether only expired leases are returned, and that they are returned in
/// the order from most to least expired. It also checks that the lease
/// which is marked as 'reclaimed' is not returned.
TEST_F(MemfileLeaseMgrTest, getExpiredLeases6) {
startBackend(V6);
testGetExpiredLeases6();
}
/// @brief Check that expired reclaimed DHCPv6 leases are removed.
TEST_F(MemfileLeaseMgrTest, deleteExpiredReclaimedLeases6) {
startBackend(V6);
testDeleteExpiredReclaimedLeases6();
}
/// @brief Check that expired reclaimed DHCPv4 leases are removed.
TEST_F(MemfileLeaseMgrTest, deleteExpiredReclaimedLeases4) {
startBackend(V4);
testDeleteExpiredReclaimedLeases4();
}
/// @brief Check that getLease6 methods discriminate by lease type.
///
/// Adds six leases, two per lease type all with the same duid and iad but
/// with alternating subnet_ids.
/// It then verifies that all of getLeases6() method variants correctly
/// discriminate between the leases based on lease type alone.
/// @todo: Disabled, because type parameter in Memfile_LeaseMgr::getLease6
/// (Lease::Type, const isc::asiolink::IOAddress& addr) const is not used.
TEST_F(MemfileLeaseMgrTest, lease6LeaseTypeCheck) {
startBackend(V6);
testLease6LeaseTypeCheck();
}
/// @brief Check GetLease6 methods - access by DUID/IAID/SubnetID
///
/// Adds leases to the database and checks that they can be accessed via
/// a combination of DIUID and IAID.
TEST_F(MemfileLeaseMgrTest, getLease6DuidIaidSubnetId) {
startBackend(V6);
testGetLease6DuidIaidSubnetId();
}
/// Checks that getLease6(type, duid, iaid, subnet-id) works with different
/// DUID sizes
TEST_F(MemfileLeaseMgrTest, getLease6DuidIaidSubnetIdSize) {
startBackend(V6);
testGetLease6DuidIaidSubnetIdSize();
}
/// @brief Lease4 update tests
///
/// Checks that we are able to update a lease in the database.
/// @todo: Disabled, because memfile does not throw when lease is updated.
/// We should reconsider if lease{4,6} structures should have a limit
/// implemented in them.
TEST_F(MemfileLeaseMgrTest, DISABLED_updateLease4) {
startBackend(V4);
testUpdateLease4();
}
/// @brief Lease6 update tests
///
/// Checks that we are able to update a lease in the database.
/// @todo: Disabled, because memfile does not throw when lease is updated.
/// We should reconsider if lease{4,6} structures should have a limit
/// implemented in them.
TEST_F(MemfileLeaseMgrTest, DISABLED_updateLease6) {
startBackend(V6);
testUpdateLease6();
}
/// @brief DHCPv4 Lease recreation tests
///
/// Checks that the lease can be created, deleted and recreated with
/// different parameters. It also checks that the re-created lease is
/// correctly stored in the lease database.
TEST_F(MemfileLeaseMgrTest, testRecreateLease4) {
startBackend(V4);
testRecreateLease4();
}
/// @brief DHCPv6 Lease recreation tests
///
/// Checks that the lease can be created, deleted and recreated with
/// different parameters. It also checks that the re-created lease is
/// correctly stored in the lease database.
TEST_F(MemfileLeaseMgrTest, testRecreateLease6) {
startBackend(V6);
testRecreateLease6();
}
// The following tests are not applicable for memfile. When adding
// new tests to the list here, make sure to provide brief explanation
// why they are not applicable:
//
// testGetLease4HWAddrSubnetIdSize() - memfile just keeps Lease structure
// and does not do any checks of HWAddr content
/// @brief Checks that null DUID is not allowed.
/// Test is disabled as Memfile does not currently defend against a null DUID.
TEST_F(MemfileLeaseMgrTest, DISABLED_nullDuid) {
// Create leases, although we need only one.
vector<Lease6Ptr> leases = createLeases6();
leases[1]->duid_.reset();
ASSERT_THROW(lmptr_->addLease(leases[1]), DbOperationError);
}
/// @brief Tests whether memfile can store and retrieve hardware addresses
TEST_F(MemfileLeaseMgrTest, testLease6Mac) {
startBackend(V6);
testLease6MAC();
}
// Check that memfile reports version correctly.
TEST_F(MemfileLeaseMgrTest, versionCheck) {
// Check that V4 backend reports versions correctly.
startBackend(V4);
testVersion(Memfile_LeaseMgr::MAJOR_VERSION,
Memfile_LeaseMgr::MINOR_VERSION);
LeaseMgrFactory::destroy();
// Check that V6 backends reports them ok, too.
startBackend(V6);
testVersion(Memfile_LeaseMgr::MAJOR_VERSION,
Memfile_LeaseMgr::MINOR_VERSION);
LeaseMgrFactory::destroy();
}
// Checks that declined IPv4 leases can be returned correctly.
TEST_F(MemfileLeaseMgrTest, getDeclined4) {
startBackend(V4);
testGetDeclinedLeases4();
}
// Checks that declined IPv6 leases can be returned correctly.
TEST_F(MemfileLeaseMgrTest, getDeclined6) {
startBackend(V6);
testGetDeclinedLeases6();
}
// This test checks that the backend reads DHCPv4 lease data from multiple
// files.
TEST_F(MemfileLeaseMgrTest, load4MultipleLeaseFiles) {
LeaseFileIO io2(getLeaseFilePath("leasefile4_0.csv.2"));
io2.writeFile("address,hwaddr,client_id,valid_lifetime,expire,subnet_id,"
"fqdn_fwd,fqdn_rev,hostname,state,user_context\n"
"192.0.2.2,02:02:02:02:02:02,,200,200,8,1,1,,1,\n"
"192.0.2.11,bb:bb:bb:bb:bb:bb,,200,200,8,1,1,,1,\n");
LeaseFileIO io1(getLeaseFilePath("leasefile4_0.csv.1"));
io1.writeFile("address,hwaddr,client_id,valid_lifetime,expire,subnet_id,"
"fqdn_fwd,fqdn_rev,hostname,state,user_context\n"
"192.0.2.1,01:01:01:01:01:01,,200,200,8,1,1,,1,\n"
"192.0.2.11,bb:bb:bb:bb:bb:bb,,200,400,8,1,1,,1,\n"
"192.0.2.12,cc:cc:cc:cc:cc:cc,,200,200,8,1,1,,1,\n");
LeaseFileIO io(getLeaseFilePath("leasefile4_0.csv"));
io.writeFile("address,hwaddr,client_id,valid_lifetime,expire,subnet_id,"
"fqdn_fwd,fqdn_rev,hostname,state,user_context\n"
"192.0.2.10,0a:0a:0a:0a:0a:0a,,200,200,8,1,1,,1,\n"
"192.0.2.12,cc:cc:cc:cc:cc:cc,,200,400,8,1,1,,1,\n");
startBackend(V4);
// This lease only exists in the second file and the cltt should
// be 0.
Lease4Ptr lease = lmptr_->getLease4(IOAddress("192.0.2.1"));
ASSERT_TRUE(lease);
EXPECT_EQ(0, lease->cltt_);
// This lease only exists in the first file and the cltt should
// be 0.
lease = lmptr_->getLease4(IOAddress("192.0.2.2"));
ASSERT_TRUE(lease);
EXPECT_EQ(0, lease->cltt_);
// This lease only exists in the third file and the cltt should
// be 0.
lease = lmptr_->getLease4(IOAddress("192.0.2.10"));
ASSERT_TRUE(lease);
EXPECT_EQ(0, lease->cltt_);
// This lease exists in the first and second file and the cltt
// should be calculated using the expiration time and the
// valid lifetime from the second file.
lease = lmptr_->getLease4(IOAddress("192.0.2.11"));
ASSERT_TRUE(lease);
EXPECT_EQ(200, lease->cltt_);
// This lease exists in the second and third file and the cltt
// should be calculated using the expiration time and the
// valid lifetime from the third file.
lease = lmptr_->getLease4(IOAddress("192.0.2.12"));
ASSERT_TRUE(lease);
EXPECT_EQ(200, lease->cltt_);
}
// This test checks that the lease database backend loads the file with
// the .completed postfix instead of files with postfixes .1 and .2 if
// the file with .completed postfix exists.
TEST_F(MemfileLeaseMgrTest, load4CompletedFile) {
LeaseFileIO io2(getLeaseFilePath("leasefile4_0.csv.2"));
io2.writeFile("address,hwaddr,client_id,valid_lifetime,expire,subnet_id,"
"fqdn_fwd,fqdn_rev,hostname,state,user_context\n"
"192.0.2.2,02:02:02:02:02:02,,200,200,8,1,1,,1,\n"
"192.0.2.11,bb:bb:bb:bb:bb:bb,,200,200,8,1,1,,1,\n");
LeaseFileIO io1(getLeaseFilePath("leasefile4_0.csv.1"));
io1.writeFile("address,hwaddr,client_id,valid_lifetime,expire,subnet_id,"
"fqdn_fwd,fqdn_rev,hostname,state,user_context\n"
"192.0.2.1,01:01:01:01:01:01,,200,200,8,1,1,,1,\n"
"192.0.2.11,bb:bb:bb:bb:bb:bb,,200,400,8,1,1,,1,\n"
"192.0.2.12,cc:cc:cc:cc:cc:cc,,200,200,8,1,1,,1,\n");
LeaseFileIO io(getLeaseFilePath("leasefile4_0.csv"));
io.writeFile("address,hwaddr,client_id,valid_lifetime,expire,subnet_id,"
"fqdn_fwd,fqdn_rev,hostname,state,user_context\n"
"192.0.2.10,0a:0a:0a:0a:0a:0a,,200,200,8,1,1,,1,\n"
"192.0.2.12,cc:cc:cc:cc:cc:cc,,200,400,8,1,1,,1,\n");
LeaseFileIO ioc(getLeaseFilePath("leasefile4_0.csv.completed"));
ioc.writeFile("address,hwaddr,client_id,valid_lifetime,expire,subnet_id,"
"fqdn_fwd,fqdn_rev,hostname,state,user_context\n"
"192.0.2.13,ff:ff:ff:ff:ff:ff,,200,200,8,1,1,,1,\n");
startBackend(V4);
// We expect that this file only holds leases that belong to the
// lease file or to the file with .completed postfix.
Lease4Ptr lease = lmptr_->getLease4(IOAddress("192.0.2.10"));
ASSERT_TRUE(lease);
EXPECT_EQ(0, lease->cltt_);
lease = lmptr_->getLease4(IOAddress("192.0.2.12"));
ASSERT_TRUE(lease);
EXPECT_EQ(200, lease->cltt_);
// This lease is in the .completed file.
lease = lmptr_->getLease4(IOAddress("192.0.2.13"));
ASSERT_TRUE(lease);
EXPECT_EQ(0, lease->cltt_);
// Leases from the .1 and .2 files should not be loaded.
EXPECT_FALSE(lmptr_->getLease4(IOAddress("192.0.2.11")));
EXPECT_FALSE(lmptr_->getLease4(IOAddress("192.0.2.1")));
}
// This test checks that backend constructor refuses to load leases from the
// lease files if the LFC is in progress.
TEST_F(MemfileLeaseMgrTest, load4LFCInProgress) {
// Create the backend configuration.
DatabaseConnection::ParameterMap pmap;
pmap["type"] = "memfile";
pmap["universe"] = "4";
pmap["name"] = getLeaseFilePath("leasefile4_0.csv");
pmap["lfc-interval"] = "1";
// Create a pid file holding the PID of the current process. Choosing the
// pid of the current process guarantees that when the backend starts up
// the process is alive.
PIDFile pid_file(Memfile_LeaseMgr::appendSuffix(pmap["name"], Memfile_LeaseMgr::FILE_PID));
pid_file.write();
// There is a pid file and the process which pid is in the file is
// running, so the backend should refuse to start.
boost::scoped_ptr<NakedMemfileLeaseMgr> lease_mgr;
ASSERT_THROW(lease_mgr.reset(new NakedMemfileLeaseMgr(pmap)),
DbOpenError);
// Remove the pid file, and retry. The backend should be created.
pid_file.deleteFile();
ASSERT_NO_THROW(lease_mgr.reset(new NakedMemfileLeaseMgr(pmap)));
}
// This test checks that the backend reads DHCPv6 lease data from multiple
// files.
TEST_F(MemfileLeaseMgrTest, load6MultipleLeaseFiles) {
LeaseFileIO io2(getLeaseFilePath("leasefile6_0.csv.2"));
io2.writeFile("address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
"lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
"hwaddr,state,user_context\n"
"2001:db8:1::1,01:01:01:01:01:01:01:01:01:01:01:01:01,"
"200,200,8,100,0,7,0,1,1,,,1,\n"
"2001:db8:1::2,02:02:02:02:02:02:02:02:02:02:02:02:02,"
"200,200,8,100,0,7,0,1,1,,,1,\n");
LeaseFileIO io1(getLeaseFilePath("leasefile6_0.csv.1"));
io1.writeFile("address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
"lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
"hwaddr,state,user_context\n"
"2001:db8:1::3,03:03:03:03:03:03:03:03:03:03:03:03:03,"
"200,200,8,100,0,7,0,1,1,,,1,\n"
"2001:db8:1::2,02:02:02:02:02:02:02:02:02:02:02:02:02,"
"300,800,8,100,0,7,0,1,1,,,1,\n"
"2001:db8:1::4,04:04:04:04:04:04:04:04:04:04:04:04:04,"
"200,200,8,100,0,7,0,1,1,,,1,\n");
LeaseFileIO io(getLeaseFilePath("leasefile6_0.csv"));
io.writeFile("address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
"lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
"hwaddr,state,user_context\n"
"2001:db8:1::4,04:04:04:04:04:04:04:04:04:04:04:04:04,"
"400,1000,8,100,0,7,0,1,1,,,1,\n"
"2001:db8:1::5,05:05:05:05:05:05:05:05:05:05:05:05:05,"
"200,200,8,100,0,7,0,1,1,,,1,\n");
startBackend(V6);
// This lease only exists in the first file and the cltt should be 0.
Lease6Ptr lease = lmptr_->getLease6(Lease::TYPE_NA,
IOAddress("2001:db8:1::1"));
ASSERT_TRUE(lease);
EXPECT_EQ(0, lease->cltt_);
// This lease exists in the first and second file and the cltt should
// be calculated using the expiration time and the valid lifetime
// from the second file.
lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::2"));
ASSERT_TRUE(lease);
EXPECT_EQ(500, lease->cltt_);
// This lease only exists in the second file and the cltt should be 0.
lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::3"));
ASSERT_TRUE(lease);
EXPECT_EQ(0, lease->cltt_);
// This lease exists in the second and third file and the cltt should
// be calculated using the expiration time and the valid lifetime
// from the third file.
lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::4"));
ASSERT_TRUE(lease);
EXPECT_EQ(600, lease->cltt_);
// This lease only exists in the third file and the cltt should be 0.
lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::5"));
ASSERT_TRUE(lease);
EXPECT_EQ(0, lease->cltt_);
}
// This test checks that the backend reads DHCPv6 lease data from the
// leasefile without the postfix and the file with a .1 postfix when
// the file with the .2 postfix is missing.
TEST_F(MemfileLeaseMgrTest, load6MultipleNoSecondFile) {
LeaseFileIO io1(getLeaseFilePath("leasefile6_0.csv.1"));
io1.writeFile("address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
"lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
"hwaddr,state,user_context\n"
"2001:db8:1::3,03:03:03:03:03:03:03:03:03:03:03:03:03,"
"200,200,8,100,0,7,0,1,1,,,1,\n"
"2001:db8:1::2,02:02:02:02:02:02:02:02:02:02:02:02:02,"
"300,800,8,100,0,7,0,1,1,,,1,\n"
"2001:db8:1::4,04:04:04:04:04:04:04:04:04:04:04:04:04,"
"200,200,8,100,0,7,0,1,1,,,1,\n");
LeaseFileIO io(getLeaseFilePath("leasefile6_0.csv"));
io.writeFile("address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
"lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
"hwaddr,state,user_context\n"
"2001:db8:1::4,04:04:04:04:04:04:04:04:04:04:04:04:04,"
"400,1000,8,100,0,7,0,1,1,,,1,\n"
"2001:db8:1::5,05:05:05:05:05:05:05:05:05:05:05:05:05,"
"200,200,8,100,0,7,0,1,1,,,1,\n");
startBackend(V6);
// Check that leases from the leasefile6_0 and leasefile6_0.1 have
// been loaded.
Lease6Ptr lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::2"));
ASSERT_TRUE(lease);
EXPECT_EQ(500, lease->cltt_);
lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::3"));
ASSERT_TRUE(lease);
EXPECT_EQ(0, lease->cltt_);
lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::4"));
ASSERT_TRUE(lease);
EXPECT_EQ(600, lease->cltt_);
lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::5"));
ASSERT_TRUE(lease);
EXPECT_EQ(0, lease->cltt_);
// Make sure that a lease which is not in those files is not loaded.
EXPECT_FALSE(lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::1")));
}
// This test checks that the backend reads DHCPv6 lease data from the
// leasefile without the postfix and the file with a .2 postfix when
// the file with the .1 postfix is missing.
TEST_F(MemfileLeaseMgrTest, load6MultipleNoFirstFile) {
LeaseFileIO io2(getLeaseFilePath("leasefile6_0.csv.2"));
io2.writeFile("address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
"lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
"hwaddr,state,user_context\n"
"2001:db8:1::1,01:01:01:01:01:01:01:01:01:01:01:01:01,"
"200,200,8,100,0,7,0,1,1,,,1,\n"
"2001:db8:1::2,02:02:02:02:02:02:02:02:02:02:02:02:02,"
"200,200,8,100,0,7,0,1,1,,,1,\n");
LeaseFileIO io(getLeaseFilePath("leasefile6_0.csv"));
io.writeFile("address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
"lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
"hwaddr,state,user_context\n"
"2001:db8:1::4,04:04:04:04:04:04:04:04:04:04:04:04:04,"
"400,1000,8,100,0,7,0,1,1,,,1,\n"
"2001:db8:1::5,05:05:05:05:05:05:05:05:05:05:05:05:05,"
"200,200,8,100,0,7,0,1,1,,,1,\n");
startBackend(V6);
// Verify that leases which belong to the leasefile6_0.csv and
// leasefile6_0.2 are loaded.
Lease6Ptr lease = lmptr_->getLease6(Lease::TYPE_NA,
IOAddress("2001:db8:1::1"));
ASSERT_TRUE(lease);
EXPECT_EQ(0, lease->cltt_);
lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::2"));
ASSERT_TRUE(lease);
EXPECT_EQ(0, lease->cltt_);
lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::4"));
ASSERT_TRUE(lease);
EXPECT_EQ(600, lease->cltt_);
lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::5"));
ASSERT_TRUE(lease);
EXPECT_EQ(0, lease->cltt_);
// A lease which doesn't belong to these files should not be loaded.
EXPECT_FALSE(lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::3")));
}
// This test checks that the lease database backend loads the file with
// the .completed postfix instead of files with postfixes .1 and .2 if
// the file with .completed postfix exists.
TEST_F(MemfileLeaseMgrTest, load6CompletedFile) {
LeaseFileIO io2(getLeaseFilePath("leasefile6_0.csv.2"));
io2.writeFile("address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
"lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
"hwaddr,state,user_context\n"
"2001:db8:1::1,01:01:01:01:01:01:01:01:01:01:01:01:01,"
"200,200,8,100,0,7,0,1,1,,,1,\n"
"2001:db8:1::2,02:02:02:02:02:02:02:02:02:02:02:02:02,"
"200,200,8,100,0,7,0,1,1,,,1,\n");
LeaseFileIO io1(getLeaseFilePath("leasefile6_0.csv.1"));
io1.writeFile("address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
"lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
"hwaddr,state,user_context\n"
"2001:db8:1::3,03:03:03:03:03:03:03:03:03:03:03:03:03,"
"200,200,8,100,0,7,0,1,1,,,1,\n"
"2001:db8:1::2,02:02:02:02:02:02:02:02:02:02:02:02:02,"
"300,800,8,100,0,7,0,1,1,,,1,\n"
"2001:db8:1::4,04:04:04:04:04:04:04:04:04:04:04:04:04,"
"200,200,8,100,0,7,0,1,1,,,1,\n");
LeaseFileIO io(getLeaseFilePath("leasefile6_0.csv"));
io.writeFile("address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
"lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
"hwaddr,state,user_context\n"
"2001:db8:1::4,04:04:04:04:04:04:04:04:04:04:04:04:04,"
"400,1000,8,100,0,7,0,1,1,,,1,\n"
"2001:db8:1::5,05:05:05:05:05:05:05:05:05:05:05:05:05,"
"200,200,8,100,0,7,0,1,1,,,1,\n");
LeaseFileIO ioc(getLeaseFilePath("leasefile6_0.csv.completed"));
ioc.writeFile("address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
"lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
"hwaddr,state,user_context\n"
"2001:db8:1::125,ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff,"
"400,1000,8,100,0,7,0,1,1,,,1,\n");
startBackend(V6);
// We expect that this file only holds leases that belong to the
// lease file or to the file with .completed postfix.
Lease6Ptr lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::4"));
ASSERT_TRUE(lease);
EXPECT_EQ(600, lease->cltt_);
lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::5"));
ASSERT_TRUE(lease);
EXPECT_EQ(0, lease->cltt_);
lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::125"));
ASSERT_TRUE(lease);
EXPECT_EQ(600, lease->cltt_);
// Leases from the .1 and .2 files should not be loaded.
EXPECT_FALSE(lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::1")));
EXPECT_FALSE(lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::2")));
EXPECT_FALSE(lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::3")));
}
// This test checks that backend constructor refuses to load leases from the
// lease files if the LFC is in progress.
TEST_F(MemfileLeaseMgrTest, load6LFCInProgress) {
// Create the backend configuration.
DatabaseConnection::ParameterMap pmap;
pmap["type"] = "memfile";
pmap["universe"] = "6";
pmap["name"] = getLeaseFilePath("leasefile6_0.csv");
pmap["lfc-interval"] = "1";
// Create a pid file holding the PID of the current process. Choosing the
// pid of the current process guarantees that when the backend starts up
// the process is alive.
PIDFile pid_file(Memfile_LeaseMgr::appendSuffix(pmap["name"], Memfile_LeaseMgr::FILE_PID));
pid_file.write();
// There is a pid file and the process which pid is in the file is
// running, so the backend should refuse to start.
boost::scoped_ptr<NakedMemfileLeaseMgr> lease_mgr;
ASSERT_THROW(lease_mgr.reset(new NakedMemfileLeaseMgr(pmap)),
DbOpenError);
// Remove the pid file, and retry. The backend should be created.
pid_file.deleteFile();
ASSERT_NO_THROW(lease_mgr.reset(new NakedMemfileLeaseMgr(pmap)));
}
// Verifies that LFC is automatically run during MemfileLeasemMgr construction
// when the lease file(s) being loaded need to be upgraded.
TEST_F(MemfileLeaseMgrTest, leaseUpgrade4) {
// Create header strings for each schema
std::string header_1_0 =
"address,hwaddr,client_id,valid_lifetime,expire,"
"subnet_id,fqdn_fwd,fqdn_rev,hostname\n";
std::string header_2_0 =
"address,hwaddr,client_id,valid_lifetime,expire,"
"subnet_id,fqdn_fwd,fqdn_rev,hostname,state,user_context\n";
// Create 1.0 Schema current lease file with two entries for
// the same lease
std::string current_file_contents = header_1_0 +
"192.0.2.2,02:02:02:02:02:02,,200,200,8,1,1,\n"
"192.0.2.2,02:02:02:02:02:02,,200,800,8,1,1,\n";
LeaseFileIO current_file(getLeaseFilePath("leasefile4_0.csv"));
current_file.writeFile(current_file_contents);
// Create 1.0 Schema previous lease file, with two entries for
// a another lease
std::string previous_file_contents = header_1_0 +
"192.0.2.3,03:03:03:03:03:03,,200,200,8,1,1,\n"
"192.0.2.3,03:03:03:03:03:03,,200,800,8,1,1,\n";
LeaseFileIO previous_file(getLeaseFilePath("leasefile4_0.csv.2"));
previous_file.writeFile(previous_file_contents);
// Create the backend.
DatabaseConnection::ParameterMap pmap;
pmap["type"] = "memfile";
pmap["universe"] = "4";
pmap["name"] = getLeaseFilePath("leasefile4_0.csv");
pmap["lfc-interval"] = "0";
boost::scoped_ptr<NakedMemfileLeaseMgr> lease_mgr(new NakedMemfileLeaseMgr(pmap));
// Since lease files are loaded during lease manager
// constructor, LFC should get launched automatically.
// The new lease file should be 2.0 schema and have no entries
ASSERT_TRUE(current_file.exists());
EXPECT_EQ(header_2_0, current_file.readFile());
// Wait for the LFC process to complete and
// make sure it has returned an exit status of 0.
ASSERT_TRUE(waitForProcess(*lease_mgr, 2));
ASSERT_EQ(0, lease_mgr->getLFCExitStatus())
<< "Executing the LFC process failed: make sure that"
" the kea-lfc program has been compiled.";
// The LFC should have created a 2.0 schema completion file with the
// one entry for each lease and moved it to leasefile4_0.csv.2
LeaseFileIO input_file(getLeaseFilePath("leasefile4_0.csv.2"), false);
ASSERT_TRUE(input_file.exists());
// Verify cleaned, converted contents
std::string result_file_contents = header_2_0 +
"192.0.2.2,02:02:02:02:02:02,,200,800,8,1,1,,0,\n"
"192.0.2.3,03:03:03:03:03:03,,200,800,8,1,1,,0,\n";
EXPECT_EQ(result_file_contents, input_file.readFile());
}
TEST_F(MemfileLeaseMgrTest, leaseUpgrade6) {
// Create header strings for all three schemas
std::string header_1_0 =
"address,duid,valid_lifetime,expire,subnet_id,"
"pref_lifetime,lease_type,iaid,prefix_len,fqdn_fwd,"
"fqdn_rev,hostname\n";
std::string header_2_0 =
"address,duid,valid_lifetime,expire,subnet_id,"
"pref_lifetime,lease_type,iaid,prefix_len,fqdn_fwd,"
"fqdn_rev,hostname,hwaddr\n";
std::string header_3_0 =
"address,duid,valid_lifetime,expire,subnet_id,"
"pref_lifetime,lease_type,iaid,prefix_len,fqdn_fwd,"
"fqdn_rev,hostname,hwaddr,state,user_context\n";
// The current lease file is schema 1.0 and has two entries for
// the same lease
std::string current_file_contents = header_1_0 +
"2001:db8:1::1,00:01:02:03:04:05:06:0a:0b:0c:0d:0e:0f,200,200,"
"8,100,0,7,0,1,1,,\n"
"2001:db8:1::1,00:01:02:03:04:05:06:0a:0b:0c:0d:0e:0f,200,800,"
"8,100,0,7,0,1,1,,\n";
LeaseFileIO current_file(getLeaseFilePath("leasefile6_0.csv"));
current_file.writeFile(current_file_contents);
// The previous lease file is schema 2.0 and has two entries for
// a different lease
std::string previous_file_contents = header_2_0 +
"2001:db8:1::2,01:01:01:01:01:01:01:01:01:01:01:01:01,200,200,"
"8,100,0,7,0,1,1,,11:22:33:44:55\n"
"2001:db8:1::2,01:01:01:01:01:01:01:01:01:01:01:01:01,200,800,"
"8,100,0,7,0,1,1,,11:22:33:44:55\n";
LeaseFileIO previous_file(getLeaseFilePath("leasefile6_0.csv.2"));
previous_file.writeFile(previous_file_contents);
// Create the backend.
DatabaseConnection::ParameterMap pmap;
pmap["type"] = "memfile";
pmap["universe"] = "6";
pmap["name"] = getLeaseFilePath("leasefile6_0.csv");
pmap["lfc-interval"] = "0";
boost::scoped_ptr<NakedMemfileLeaseMgr> lease_mgr(new NakedMemfileLeaseMgr(pmap));
// Since lease files are loaded during lease manager
// constructor, LFC should get launched automatically.
// The new lease file should been 3.0 and contain no leases.
ASSERT_TRUE(current_file.exists());
EXPECT_EQ(header_3_0, current_file.readFile());
// Wait for the LFC process to complete and
// make sure it has returned an exit status of 0.
ASSERT_TRUE(waitForProcess(*lease_mgr, 2));
ASSERT_EQ(0, lease_mgr->getLFCExitStatus())
<< "Executing the LFC process failed: make sure that"
" the kea-lfc program has been compiled.";
// The LFC should have created a 3.0 schema cleaned file with one entry
// for each lease as leasefile6_0.csv.2
LeaseFileIO input_file(getLeaseFilePath("leasefile6_0.csv.2"), false);
ASSERT_TRUE(input_file.exists());
// Verify cleaned, converted contents
std::string result_file_contents = header_3_0 +
"2001:db8:1::1,00:01:02:03:04:05:06:0a:0b:0c:0d:0e:0f,200,800,"
"8,100,0,7,0,1,1,,,0,\n"
"2001:db8:1::2,01:01:01:01:01:01:01:01:01:01:01:01:01,200,800,"
"8,100,0,7,0,1,1,,11:22:33:44:55,0,\n";
EXPECT_EQ(result_file_contents, input_file.readFile());
}
// This test verifies that the indexes of the container holding
// DHCPv4 leases are updated correctly when a lease is updated.
TEST_F(MemfileLeaseMgrTest, lease4ContainerIndexUpdate) {
const uint32_t seed = 12345678; // Used to initialize the random generator
const uint32_t leases_cnt = 100; // Number of leases generated per round.
const uint32_t updates_cnt = 5; // Number of times existing leases are updated
const string leasefile(getLeaseFilePath("leasefile4_0.csv"));
// Parameters for the lease file. Make sure the leases are persistent, so they
// are written to disk.
DatabaseConnection::ParameterMap pmap;
pmap["universe"] = "4";
pmap["name"] = leasefile;
pmap["persist"] = "true";
pmap["lfc-interval"] = "0";
srand(seed);
IOAddress addr("10.0.0.1"); // Let's generate leases sequentially
// Recreate Memfile_LeaseMgr.
LeaseMgrFactory::destroy();
ASSERT_NO_THROW(lmptr_ = new Memfile_LeaseMgr(pmap));
// We will store addresses here, so it will be easier to randomly
// pick a lease.
std::vector<IOAddress> lease_addresses;
// Generate random leases. We remember their addresses in
// lease_addresses.
for (uint32_t i = 0; i < leases_cnt; ++i) {
Lease4Ptr lease = initiateRandomLease4(addr);
lease_addresses.push_back(addr);
ASSERT_NO_THROW(lmptr_->addLease(lease));
addr = IOAddress::increase(addr);
}
// Check that we inserted correct number of leases.
ASSERT_EQ(leases_cnt, lease_addresses.size());
// Now, conduct updates. We call initiateRandomLease4(), so most
// of the fields are randomly changed. The only constant field
// is the address.
for (uint32_t i = 0; i < updates_cnt; ++i) {
uint32_t offset = random() % lease_addresses.size();
Lease4Ptr existing(lmptr_->getLease4(lease_addresses[offset]));
Lease4Ptr updated(initiateRandomLease4(lease_addresses[offset]));
// Update a lease with new data but preserve lease address.
// This update should also cause lease container indexes to
// be updated.
ASSERT_NO_THROW(lmptr_->updateLease4(updated))
<< "Attempt " << i << " out of " << updates_cnt
<< ":Failed to update lease for address "
<< lease_addresses[offset];
}
// Re-create lease manager to cause it to reload leases
// from a lease file. We want to make sure that lease
// container is rebuilt correctly and the indexes are
// consistent with lease information held.
ASSERT_NO_THROW({
LeaseMgrFactory::destroy();
lmptr_ = new Memfile_LeaseMgr(pmap);
});
// Ok, let's check if the leases are really accessible.
// First, build an array of leases. Get them by address.
// This should work in general, as we haven't updated the addresses.
std::vector<Lease4Ptr> leases;
for (uint32_t i = 0; i < lease_addresses.size(); ++i) {
Lease4Ptr from_mgr = lmptr_->getLease4(lease_addresses[i]);
ASSERT_TRUE(from_mgr) << "Lease for address " << lease_addresses[i].toText()
<< " not found";
leases.push_back(from_mgr);
}
ASSERT_EQ(leases_cnt, leases.size());
// Now do the actual checks.
for (uint32_t i = 0; i < leases.size(); ++i) {
Lease4Ptr tested = leases[i];
// Get the lease by different access patterns.
// In properly working lease manager all queries should return
// exactly the same lease.
std::string error_desc = " which indicates that the lease indexes were"
" not updated correctly when the lease was updated.";
// Retrieve lease by address.
Lease4Ptr lease_by_address = lmptr_->getLease4(tested->addr_);
ASSERT_TRUE(lease_by_address)
<< "Lease " << tested->addr_.toText()
<< " not found by getLease4(addr)"
<< error_desc;
detailCompareLease(tested, lease_by_address);
// Retrieve lease by HW address and subnet id.
Lease4Ptr lease_by_hwaddr_subnet = lmptr_->getLease4(*tested->hwaddr_,
tested->subnet_id_);
ASSERT_TRUE(lease_by_hwaddr_subnet)
<< "Lease " << tested->addr_.toText()
<< " not found by getLease4(hwaddr, subnet_id)"
<< error_desc;
detailCompareLease(tested, lease_by_hwaddr_subnet);
// Retrieve lease by client identifier and subnet id.
Lease4Ptr lease_by_clientid_subnet = lmptr_->getLease4(*tested->client_id_,
tested->subnet_id_);
ASSERT_TRUE(lease_by_clientid_subnet)
<< "Lease " << tested->addr_.toText()
<< " not found by getLease4(clientid, subnet_id)"
<< error_desc;
detailCompareLease(tested, lease_by_clientid_subnet);
// Retrieve lease by client id, HW address and subnet.
Lease4Ptr lease_by_clientid_hwaddr_subnet = lmptr_->getLease4(*tested->client_id_,
*tested->hwaddr_,
tested->subnet_id_);
ASSERT_TRUE(lease_by_clientid_hwaddr_subnet)
<< "Lease " << tested->addr_.toText()
<< " not found by getLease4(clientid, hwaddr, subnet_id)"
<< error_desc;
detailCompareLease(tested, lease_by_clientid_hwaddr_subnet);
// Retrieve lease by HW address.
Lease4Collection leases_by_hwaddr = lmptr_->getLease4(*tested->hwaddr_);
ASSERT_EQ(1, leases_by_hwaddr.size());
detailCompareLease(tested, leases_by_hwaddr[0]);
// Retrieve lease by client identifier.
Lease4Collection leases_by_client_id = lmptr_->getLease4(*tested->client_id_);
ASSERT_EQ(1, leases_by_client_id.size());
detailCompareLease(tested, leases_by_client_id[0]);
}
}
// This test verifies that the indexes of the container holding
// DHCPv4 leases are updated correctly when a lease is updated.
TEST_F(MemfileLeaseMgrTest, lease6ContainerIndexUpdate) {
const uint32_t seed = 12345678; // Used to initialize the random generator
const uint32_t leases_cnt = 100; // Number of leases generated per round.
const uint32_t updates_cnt = 5; // Number of times existing leases are updated
const string leasefile(getLeaseFilePath("leasefile6_0.csv"));
// Parameters for the lease file. Make sure the leases are persistent, so they
// are written to disk.
DatabaseConnection::ParameterMap pmap;
pmap["universe"] = "6";
pmap["name"] = leasefile;
pmap["persist"] = "true";
pmap["lfc-interval"] = "0";
srand(seed);
IOAddress addr("2001:db8:1::1"); // Let's generate leases sequentially
// Recreate Memfile_LeaseMgr.
LeaseMgrFactory::destroy();
ASSERT_NO_THROW(lmptr_ = new Memfile_LeaseMgr(pmap));
// We will store addresses here, so it will be easier to randomly
// pick a lease.
std::vector<IOAddress> lease_addresses;
// Generate random leases. We remember their addresses in
// lease_addresses.
for (uint32_t i = 0; i < leases_cnt; ++i) {
Lease6Ptr lease = initiateRandomLease6(addr);
lease_addresses.push_back(addr);
ASSERT_NO_THROW(lmptr_->addLease(lease));
addr = IOAddress::increase(addr);
}
// Check that we inserted correct number of leases.
ASSERT_EQ(leases_cnt, lease_addresses.size());
// Now, conduct updates. We call initiateRandomLease6(), so most
// of the fields are randomly changed. The only constant field
// is the address.
for (uint32_t i = 0; i < updates_cnt; ++i) {
uint32_t offset = random() % lease_addresses.size();
Lease6Ptr existing(lmptr_->getLease6(Lease::TYPE_NA,
lease_addresses[offset]));
Lease6Ptr updated(initiateRandomLease6(lease_addresses[offset]));
// Update a lease with new data but preserve lease address.
// This update should also cause lease container indexes to
// be updated.
ASSERT_NO_THROW(lmptr_->updateLease6(updated))
<< "Attempt " << i << " out of " << updates_cnt
<< ":Failed to update lease for address "
<< lease_addresses[offset];
}
// Re-create lease manager to cause it to reload leases
// from a lease file. We want to make sure that lease
// container is rebuilt correctly and the indexes are
// consistent with lease information held.
ASSERT_NO_THROW({
LeaseMgrFactory::destroy();
lmptr_ = new Memfile_LeaseMgr(pmap);
});
// Ok, let's check if the leases are really accessible.
// First, build an array of leases. Get them by address.
// This should work in general, as we haven't updated the addresses.
std::vector<Lease6Ptr> leases;
for (uint32_t i = 0; i < lease_addresses.size(); ++i) {
Lease6Ptr from_mgr = lmptr_->getLease6(Lease::TYPE_NA,
lease_addresses[i]);
ASSERT_TRUE(from_mgr) << "Lease for address " << lease_addresses[i].toText()
<< " not found";
leases.push_back(from_mgr);
}
ASSERT_EQ(leases_cnt, leases.size());
// Now do the actual checks.
for (uint32_t i = 0; i < leases.size(); ++i) {
Lease6Ptr tested = leases[i];
// Get the lease by different access patterns.
// In properly working lease manager all queries should return
// exactly the same lease.
std::string error_desc = " which indicates that the lease indexes were"
" not updated correctly when the lease was updated.";
// Retrieve lease by address.
Lease6Ptr lease_by_address = lmptr_->getLease6(Lease::TYPE_NA,
tested->addr_);
ASSERT_TRUE(lease_by_address)
<< "Lease " << tested->addr_.toText()
<< " not found by getLease6(addr)"
<< error_desc;
detailCompareLease(tested, lease_by_address);
// Retrieve lease by type, DUID, IAID.
Lease6Collection leases_by_duid_iaid = lmptr_->getLeases6(tested->type_,
*tested->duid_,
tested->iaid_);
ASSERT_EQ(1, leases_by_duid_iaid.size());
ASSERT_TRUE(leases_by_duid_iaid[0])
<< "Lease " << tested->addr_.toText()
<< " not found by getLease6(type, duid, iaid)"
<< error_desc;
detailCompareLease(tested, leases_by_duid_iaid[0]);
// Retrieve lease by type, DUID, IAID, subnet identifier.
Lease6Collection leases_by_duid_iaid_subnet =
lmptr_->getLeases6(tested->type_, *tested->duid_,
tested->iaid_, tested->subnet_id_);
ASSERT_EQ(1, leases_by_duid_iaid_subnet.size());
ASSERT_TRUE(leases_by_duid_iaid_subnet[0])
<< "Lease " << tested->addr_.toText()
<< " not found by getLease6(type, duid, iaid, subnet_id)"
<< error_desc;
detailCompareLease(tested, leases_by_duid_iaid_subnet[0]);
}
}
// Verifies that IPv4 lease statistics can be recalculated.
TEST_F(MemfileLeaseMgrTest, recountLeaseStats4) {
startBackend(V4);
testRecountLeaseStats4();
}
// Verifies that IPv6 lease statistics can be recalculated.
TEST_F(MemfileLeaseMgrTest, recountLeaseStats6) {
startBackend(V6);
testRecountLeaseStats6();
}
// Tests that leases from specific subnet can be removed.
TEST_F(MemfileLeaseMgrTest, wipeLeases4) {
startBackend(V4);
testWipeLeases4();
}
// Tests that leases from specific subnet can be removed.
TEST_F(MemfileLeaseMgrTest, wipeLeases6) {
startBackend(V6);
testWipeLeases6();
}
// Tests v4 lease stats query variants.
TEST_F(MemfileLeaseMgrTest, leaseStatsQuery4) {
startBackend(V4);
testLeaseStatsQuery4();
}
// Tests v6 lease stats query variants.
TEST_F(MemfileLeaseMgrTest, leaseStatsQuery6) {
startBackend(V6);
testLeaseStatsQuery6();
}
} // namespace
| 39.638931 | 95 | 0.663274 | [
"object",
"vector"
] |
4b627b81fa53a6895db230e5d288c70221a9bc4f | 349 | cpp | C++ | Codeforces/1165B - Polycarp Training.cpp | naimulcsx/online-judge-solutions | 0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f | [
"MIT"
] | null | null | null | Codeforces/1165B - Polycarp Training.cpp | naimulcsx/online-judge-solutions | 0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f | [
"MIT"
] | null | null | null | Codeforces/1165B - Polycarp Training.cpp | naimulcsx/online-judge-solutions | 0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
int n;
cin >> n;
vector<int> arr(n);
for (auto &el: arr) cin >> el;
sort( begin(arr), end(arr) );
int k = 1, cnt = 0;
for (auto el: arr) {
if ( el >= k ) { cnt++, k++; }
}
cout << cnt << endl;
return 0;
}
| 16.619048 | 38 | 0.47851 | [
"vector"
] |
4b63125c18d87171498bc8b9c1fe92fd420c6850 | 2,501 | cpp | C++ | LinkList/mergeTwoSortedList.cpp | JacobLee121/interview_code | d014027f152d8c3b6352581f1846dda6cd2664b7 | [
"Apache-2.0"
] | null | null | null | LinkList/mergeTwoSortedList.cpp | JacobLee121/interview_code | d014027f152d8c3b6352581f1846dda6cd2664b7 | [
"Apache-2.0"
] | null | null | null | LinkList/mergeTwoSortedList.cpp | JacobLee121/interview_code | d014027f152d8c3b6352581f1846dda6cd2664b7 | [
"Apache-2.0"
] | null | null | null | //
// mergeTwoSortedList.cpp
// LinkListTest
//
// Created by 李鑫强 on 2020/5/31星期日.
// Copyright © 2020年 lixinqiang. All rights reserved.
//
#include "mergeTwoSortedList.hpp"
#include <vector>
#include <unordered_map>
class MergeList {
public:
ListNode* mergeTwoListsRecursive(ListNode* l1, ListNode* l2) {
/*
function :return merged list by order
*/
if (l1 == nullptr) {
return l2;
}
if (l2 == nullptr) {
return l1;
}
ListNode *mHead = nullptr;
// mHead has been created Ntimes(N = call recursive times), the first
// mHead return as the final answer. others return as the mid ans
if ( l2->val > l1->val) {
mHead = l1;
mHead->next = mergeTwoListsRecursive(l1->next, l2);
}
else {
mHead = l2;
mHead->next = mergeTwoListsRecursive(l1, l2->next);
}
//mHead = ret;
//ret->next = mHead;
//mHead = ret;
//mHead->next = ret;
return mHead;
}
ListNode * MergeTwoSortedListLoop(ListNode* l1, ListNode* l2)
{
if (l1 == nullptr) {
return l2;
}
if (l2 == nullptr) {
return l1;
}
ListNode *pre = new ListNode(-1);
ListNode *head = pre;
//cur= head;
while (l1 != nullptr && l2 != nullptr) {
if (l1->val < l2->val) {
pre->next = l1;
l1 = l1->next;
}
else {
pre->next = l2;
l2 = l2->next;
}
pre = pre->next;
}
pre->next = l1 == nullptr? l2: l1;
return head->next;
}
};
/*int main ()
{
printf("merge to sorted list \n");
LinkListManager llm;
ListNode node1(1);
ListNode node2(3);
ListNode node4(5);
llm.LinkLists(&node1, &node2);
llm.LinkLists(&node2, &node4);
llm.PrintLists(&node1);
ListNode nodeb1(2);
ListNode nodeb3(4);
ListNode nodeb4(8);
ListNode nodeb5(10);
llm.LinkLists(&nodeb1, &nodeb3);
llm.LinkLists(&nodeb3, &nodeb4);
llm.LinkLists(&nodeb4, &nodeb5);
llm.PrintLists(&nodeb1);
MergeList s;
//ListNode *ret = s.mergeTwoListsRecursive(&node1, &nodeb1);
//llm.PrintLists(ret);
ListNode *retLoop = s.MergeTwoSortedListLoop(&node1, &nodeb1);
llm.PrintLists(retLoop);
}
*/
| 25.262626 | 78 | 0.509396 | [
"vector"
] |
b49bb6b2f7e7a24e85cd8b4008606c47494f9561 | 2,613 | cpp | C++ | ams_sketch.cpp | streaminglib/streaminglib | 3be40b0084f36250ddb5a19c1d834d07a6e42b6e | [
"MIT"
] | null | null | null | ams_sketch.cpp | streaminglib/streaminglib | 3be40b0084f36250ddb5a19c1d834d07a6e42b6e | [
"MIT"
] | null | null | null | ams_sketch.cpp | streaminglib/streaminglib | 3be40b0084f36250ddb5a19c1d834d07a6e42b6e | [
"MIT"
] | null | null | null | #include "ams_sketch.h"
ams_sketch::ams_sketch(size_t c, size_t c_w, vector<int> s): hash_table(32, c_w, c), seeds(&s[0], &s[c]){
cells = c;
cell_width = c_w;
}
void ams_sketch::insert_element(const string &ele, int freq){
for(int i = 0; i < cells; i += 1){
char hash_val[16] = {};
char mult_fac[16] = {};
MurmurHash3_x64_128(ele.c_str(), ele.size(), seeds[i], hash_val);
MurmurHash3_x64_128(ele.c_str(), ele.size(), seeds[i], mult_fac);
update_sketch(*(int* )mult_fac, i, *(int* )hash_val, freq);
}
}
void ams_sketch::insert_element(const vector<string> &ele, vector<int> freq) {
size_t n = ele.size();
#pragma omp parallel for
for (size_t i = 0; i < n; i++)
insert_element(ele[i], freq[i]);
}
int ams_sketch::update_sketch(int mult, int idx, int hash, int freq){
if (mult & 1) {
hash_table.inc(hash, freq, idx);
}
else {
hash_table.dec(hash, freq, idx);
}
return 0;
}
int ams_sketch::get_estimateF2(){
std::vector<int> estimates(cells);
mult_by_position(hash_table, hash_table, estimates);
return get_final_estimates(estimates);
}
int ams_sketch::get_final_estimates(std::vector<int> &estimates) {
vector<int> pv(estimates);
nth_element(pv.begin(), pv.begin() + pv.size() / 2, pv.end());
return pv[pv.size() / 2];
}
void ams_sketch::mult_by_position(Hashtable &s1, Hashtable &s2, std::vector<int> & estimates) {
for (int i = 0; i < cells; i += 1) {
estimates[i] = 0;
for (int j = 0; j < cell_width; j += 1) {
estimates[i] += s1.get(j, i) * s2.get(j, i);
}
}
}
int ams_sketch::obj_count(const string & ele) {
std::vector<int> estimates(cells);
for (int i = 0; i < cells; i += 1) {
estimates[i] = 0;
char hash_val[16] = {};
char mult_fac[16] = {};
MurmurHash3_x64_128(ele.c_str(), ele.size(), seeds[i], hash_val);
MurmurHash3_x64_128(ele.c_str(), ele.size(), seeds[i], mult_fac);
get_estimate(*(int* )hash_val, *(int* )mult_fac, i, estimates);
}
size_t ans = get_final_estimates(estimates);
return ans;
}
vector<int> ams_sketch::obj_count(const vector<string> &ele) {
vector<int> results;
size_t len = ele.size();
results.resize(len);
#pragma omp parallel for
for (size_t i = 0; i < len; i++)
results[i] = obj_count(ele[i]);
return results;
}
void ams_sketch::get_estimate(int hash, int mult, int idx, std::vector<int> & estimates) {
if (mult & 1) {
estimates[idx] += hash_table.get(hash % cell_width, idx);
} else {
estimates[idx] -= hash_table.get(hash % cell_width, idx);
}
}
| 29.359551 | 105 | 0.62036 | [
"vector"
] |
b4a286e08e5a68661c1c8968a623ad138a53b536 | 11,895 | cpp | C++ | onnxruntime/core/providers/dml/DmlExecutionProvider/src/TensorDesc.cpp | KsenijaS/onnxruntime | 5086e55a35f83e3137bdb34b6d7210c97a512e6a | [
"MIT"
] | 2 | 2021-07-24T01:13:36.000Z | 2021-11-17T11:03:52.000Z | onnxruntime/core/providers/dml/DmlExecutionProvider/src/TensorDesc.cpp | KsenijaS/onnxruntime | 5086e55a35f83e3137bdb34b6d7210c97a512e6a | [
"MIT"
] | 17 | 2020-07-21T11:13:27.000Z | 2022-03-27T02:37:05.000Z | onnxruntime/core/providers/dml/DmlExecutionProvider/src/TensorDesc.cpp | Surfndez/onnxruntime | 9d748afff19e9604a00632d66b97159b917dabb2 | [
"MIT"
] | 1 | 2020-07-30T12:50:02.000Z | 2020-07-30T12:50:02.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "precomp.h"
using namespace Dml;
TensorDesc::TensorDesc(
DML_TENSOR_DATA_TYPE dataType,
gsl::span<const uint32_t> sizes,
std::optional<gsl::span<const uint32_t>> strides,
uint32_t guaranteedBaseOffsetAlignment
)
{
m_tensorType = DML_TENSOR_TYPE_BUFFER;
m_bufferTensorDesc.DataType = dataType;
m_mlOperatorTensorDataType = GetMlDataTypeFromDmlDataType(dataType);
ML_CHECK_VALID_ARGUMENT(gsl::narrow_cast<size_t>(sizes.size()) <= std::size(m_sizes));
std::copy(sizes.begin(), sizes.end(), m_sizes);
m_bufferTensorDesc.Sizes = m_sizes;
if (strides)
{
ML_CHECK_VALID_ARGUMENT(strides->size() == sizes.size());
std::copy(strides->begin(), strides->end(), m_strides);
m_bufferTensorDesc.Strides = m_strides;
}
m_bufferTensorDesc.DimensionCount = gsl::narrow_cast<uint32_t>(sizes.size());
m_bufferTensorDesc.Flags = DML_TENSOR_FLAG_NONE;
m_bufferTensorDesc.GuaranteedBaseOffsetAlignment = guaranteedBaseOffsetAlignment;
m_bufferTensorDesc.TotalTensorSizeInBytes = DMLCalcBufferTensorSize(
m_bufferTensorDesc.DataType,
m_bufferTensorDesc.DimensionCount,
m_sizes,
strides ? m_strides : nullptr
);
}
TensorDesc::TensorDesc(MLOperatorTensorDataType dataType)
{
m_mlOperatorTensorDataType = dataType;
m_bufferTensorDesc.DataType = GetDmlDataTypeFromMlDataType(dataType);
// Leave all other fields deferred, including m_tensorType = DML_TENSOR_TYPE_INVALID.
}
TensorDesc::TensorDesc(
MLOperatorTensorDataType dataType,
gsl::span<const uint32_t> dimensions, // Desired dimensions
gsl::span<const uint32_t> nonBroadcastDimensions, // Actual physical dimensions
uint32_t coerceAxis,
int32_t placement, // Adjustment offset of the passed dimensions within the minDimensionCount.
int32_t leftAlignedDimensionCount, // Number of dimensions that remain left aligned when expanded to minimum count (INT32_MAX means all, 0 means all right aligned).
uint32_t minDimensionCount,
uint32_t guaranteedBaseOffsetAlignment
)
{
m_tensorType = DML_TENSOR_TYPE_BUFFER;
m_mlOperatorTensorDataType = dataType;
m_bufferTensorDesc.DataType = GetDmlDataTypeFromMlDataType(dataType);
ML_CHECK_VALID_ARGUMENT(ApiTraits::IsValidEnumValue(m_bufferTensorDesc.DataType));
gsl::span<const uint32_t> sizes;
// If needed, flatten the tensor dimensions to a 2D tensor of size [a_0 * ... * a_{coerceAxis-1}, a_{coerceAxis} * ... * a_{n-1}]
// e.g. Flattening [1,2,3,4] with axis 2 yields [2,12].
uint32_t coercedSizes[2];
if (dimensions.size() > 1 && coerceAxis < gsl::narrow_cast<uint32_t>(dimensions.size()))
{
uint32_t dimension0 = 1u;
uint32_t dimension1 = dimensions[coerceAxis];
for (uint32_t i = 0; i < coerceAxis; ++i)
{
dimension0 *= dimensions[i];
}
for (size_t i = coerceAxis + 1, ci = dimensions.size(); i < ci; ++i)
{
dimension1 *= dimensions[i];
}
coercedSizes[0] = dimension0;
coercedSizes[1] = dimension1;
sizes = coercedSizes;
}
else
{
sizes = dimensions;
}
////////////////////////////////////////
// Align dimensions
// Determine the number of dimensions that should be aligned to the left edge when promoting to the minimum dimension count.
// Negative values mean align from the right.
const int32_t rank = gsl::narrow_cast<int32_t>(sizes.size());
leftAlignedDimensionCount = leftAlignedDimensionCount < 0 ? std::max(0, leftAlignedDimensionCount + rank) : std::min(rank, leftAlignedDimensionCount);
ML_CHECK_VALID_ARGUMENT(rank <= MaximumDimensionCount);
m_bufferTensorDesc.DimensionCount = std::max(rank, int32_t(minDimensionCount));
// Many DirectML operators accept only certain dimension counts, but it's very common for ONNX models
// to have fewer dimensions than that. So this logic massages the dimension count up to what is needed
// by filling unused dimensions with size 1, by left-aligning, right-aligning, or even mid-filling.
//
// e.g.:
//
// elementwise addition - [H W] -> [1 1 H W], leftAlignedCount = 0, placement = 0
// 1D convolution - [N C W] -> [N C 1 W], leftAlignedCount = 2, placement = 0
// batch normalization - [C] -> [1 C 1 1], leftAlignedCount = 1, placement = 1
//
{
// Compute the total number of additional dimensions to fill with 1's,
// before, after, and in the middle.
const int32_t totalFillerCount = m_bufferTensorDesc.DimensionCount - rank;
const int32_t leadingFillerCount = std::clamp(placement, 0, totalFillerCount);
const int32_t remainingFillerCount = totalFillerCount - leadingFillerCount;
const int32_t trailingFillerCount = std::clamp(-placement, 0, remainingFillerCount);
const int32_t middleFillerCount = remainingFillerCount - trailingFillerCount;
const int32_t firstRightAlignedDim = leadingFillerCount + leftAlignedDimensionCount + middleFillerCount;
int i = 0, j = 0;
while (j < leadingFillerCount) { m_sizes[j++] = 1; }
while (i < leftAlignedDimensionCount) { m_sizes[j++] = sizes[i++]; }
while (j < firstRightAlignedDim) { m_sizes[j++] = 1; }
while (i < rank) { m_sizes[j++] = sizes[i++]; }
while (j < MaximumDimensionCount) { m_sizes[j++] = 1; }
}
////////////////////////////////////////
// Coerce the physical shape to the desired shape.
// By default, assume strides are not necessary.
bool useStrides = false;
if (dimensions != nonBroadcastDimensions)
{
// This broadcasting and subset logic is only applicable to the simple case where all
// dimensions are contiguously right aligned, which means no flattening coercion,
// placement offset, or split alignment. In such cases, the right side of m_sizes
// should match the original dimensions.
ML_CHECK_VALID_ARGUMENT(std::equal(
dimensions.begin(),
dimensions.end(),
&m_sizes[m_bufferTensorDesc.DimensionCount - rank],
&m_sizes[m_bufferTensorDesc.DimensionCount]
));
// Stretch any dimensions with a single element.
//
// e.g. physical [2,1,4]
// desired [2,3,4]
// output [2,3,4]
// strides [4,0,1]
//
// If broadcasting is used, then strides are used.
useStrides = true;
// Walk backwards through both input shapes and broadcast or default each dimension.
auto nonBroadcastDimsIter = nonBroadcastDimensions.rbegin();
uint32_t elementCount = 1;
for (int descDimIndex = m_bufferTensorDesc.DimensionCount - 1; descDimIndex >= 0; --descDimIndex)
{
if (nonBroadcastDimsIter == nonBroadcastDimensions.rend() || (*nonBroadcastDimsIter == 1))
{
m_strides[descDimIndex] = 0;
}
else
{
m_strides[descDimIndex] = elementCount;
elementCount *= (*nonBroadcastDimsIter);
}
if (nonBroadcastDimsIter != nonBroadcastDimensions.rend())
{
++nonBroadcastDimsIter;
}
}
}
////////////////////////////////////////
// Handle 64-bit tensors.
uint64_t endPaddingInBytes = 0;
if (dataType == MLOperatorTensorDataType::UInt64 || dataType == MLOperatorTensorDataType::Int64)
{
// DirectML doesn't support tensor of int64 because Direct3D doesn't support
// the data type. A workaround is to use strides to fake 64-bit memory access
// while only the lower 32 bits contains the data. This trick obviously doesn't
// work if the data element is genuine 64-bit. It also doesn't work if the data
// element is negative as the signed bit will be incorrectly interpreted.
m_bufferTensorDesc.DataType = DML_TENSOR_DATA_TYPE_UINT32;
// If the strides haven't been calculated yet, initialize them as packed.
if (!useStrides)
{
uint32_t stride = 1;
for (int i = m_bufferTensorDesc.DimensionCount - 1; i >= 0; i--)
{
m_strides[i] = stride;
stride *= m_sizes[i];
}
}
// Double the stride values to emulate 64-bit integer support.
for (uint32_t i = 0; i < m_bufferTensorDesc.DimensionCount; ++i)
{
m_strides[i] *= 2;
}
useStrides = true;
// The physical size of the tensor will have an extra 4 bytes at the end.
// DMLCalcBufferTensorSize calculates the minimum implied size, which is based on the last
// addressable element of the tensor plus the space for the last element. However, the size
// of the last element is now halved from 8 bytes to 4 bytes.
//
// Example:
// Original Tensor: size={2,3}, strides={3,1}, type=int64, size = (1+{1,2}*{3,1})*sizeof(int64) = 6 * 8 = 48
// Emulated Tensor: size={2,3}, strides={6,2}, type=int32, size = (1+{1,2}*{6,2})*sizeof(int32) = 11 * 4 = 44
//
// DirectML itself won't read/write the last 4 bytes, but we want the total size to be accurate
// so that the entire region can be zeroed.
endPaddingInBytes = sizeof(uint32_t);
}
if (useStrides)
{
m_bufferTensorDesc.Strides = m_strides;
}
m_bufferTensorDesc.Flags = DML_TENSOR_FLAG_NONE;
m_bufferTensorDesc.GuaranteedBaseOffsetAlignment = guaranteedBaseOffsetAlignment;
m_bufferTensorDesc.TotalTensorSizeInBytes = DMLCalcBufferTensorSize(
m_bufferTensorDesc.DataType,
m_bufferTensorDesc.DimensionCount,
m_sizes,
useStrides ? m_strides : nullptr
) + endPaddingInBytes;
}
gsl::span<const uint32_t> TensorDesc::GetStrides() const
{
if (m_bufferTensorDesc.Strides == nullptr)
{
return {};
}
return { m_strides, m_strides + m_bufferTensorDesc.DimensionCount };
}
DML_TENSOR_DESC TensorDesc::GetDmlDesc()
{
if (m_tensorType == DML_TENSOR_TYPE_INVALID)
{
return { m_tensorType, nullptr };
}
m_bufferTensorDesc.Sizes = m_sizes;
if (m_bufferTensorDesc.Strides)
{
m_bufferTensorDesc.Strides = m_strides;
}
// Only buffer tensors are supported right now.
assert(m_tensorType == DML_TENSOR_TYPE_BUFFER);
return { m_tensorType, &m_bufferTensorDesc };
}
// ONNX likes to use signed types for logically unsigned index data. DML avoids this inconsistency and therefore
// requires coercion by the caller.
void TensorDesc::ForceUnsignedDataType()
{
static_assert(ApiTraits::EnumValueCount<DML_TENSOR_DATA_TYPE> == 12, "New tensor data type. Update cases.");
switch (m_bufferTensorDesc.DataType)
{
case DML_TENSOR_DATA_TYPE_INT64:
m_bufferTensorDesc.DataType = DML_TENSOR_DATA_TYPE_UINT64;
break;
case DML_TENSOR_DATA_TYPE_INT32:
m_bufferTensorDesc.DataType = DML_TENSOR_DATA_TYPE_UINT32;
break;
case DML_TENSOR_DATA_TYPE_INT16:
m_bufferTensorDesc.DataType = DML_TENSOR_DATA_TYPE_UINT16;
break;
case DML_TENSOR_DATA_TYPE_INT8:
m_bufferTensorDesc.DataType = DML_TENSOR_DATA_TYPE_UINT8;
break;
// Nothing to do if already unsigned
case DML_TENSOR_DATA_TYPE_UINT32:
case DML_TENSOR_DATA_TYPE_UINT16:
case DML_TENSOR_DATA_TYPE_UINT8:
break;
default:
ML_INVALID_ARGUMENT("Can't coerce unknown or non-integral data type");
}
}
| 38.370968 | 168 | 0.652963 | [
"shape"
] |
b4a85280773e21f3303451f35ab61952cc718db3 | 2,925 | cpp | C++ | Source/Geometry/Analytic/imstkPlane.cpp | Kitware/iMSTK | fa84907c77c524a45c126d836f15275d76648be6 | [
"Apache-2.0"
] | 15 | 2021-09-20T17:33:52.000Z | 2022-02-12T09:49:57.000Z | Source/Geometry/Analytic/imstkPlane.cpp | Kitware/iMSTK | fa84907c77c524a45c126d836f15275d76648be6 | [
"Apache-2.0"
] | null | null | null | Source/Geometry/Analytic/imstkPlane.cpp | Kitware/iMSTK | fa84907c77c524a45c126d836f15275d76648be6 | [
"Apache-2.0"
] | 3 | 2021-10-06T19:55:41.000Z | 2022-02-17T21:59:16.000Z | /*=========================================================================
Library: iMSTK
Copyright (c) Kitware, Inc. & Center for Modeling, Simulation,
& Imaging in Medicine, Rensselaer Polytechnic Institute.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
#include "imstkPlane.h"
#include "imstkLogger.h"
namespace imstk
{
Vec3d
Plane::getNormal(DataType type /* = DataType::PostTransform */)
{
if (type == DataType::PostTransform)
{
this->updatePostTransformData();
return m_normalPostTransform;
}
return m_normal;
}
void
Plane::setNormal(const Vec3d n)
{
// A normal with no direction would destroy the basis
// of the transform
if (m_normal == n || n.norm() == 0.0)
{
return;
}
m_normal = n.normalized();
m_transformApplied = false;
this->postModified();
}
void
Plane::setNormal(const double x, const double y, const double z)
{
this->setNormal(Vec3d(x, y, z));
}
double
Plane::getWidth()
{
return m_width;
}
void
Plane::setWidth(const double w)
{
if (m_width == w || m_width <= 0.0)
{
return;
}
m_width = w;
this->postModified();
}
void
Plane::applyTransform(const Mat4d& m)
{
AnalyticalGeometry::applyTransform(m);
this->postModified();
}
void
Plane::updatePostTransformData() const
{
if (m_transformApplied)
{
return;
}
AnalyticalGeometry::updatePostTransformData();
m_normalPostTransform = m_orientation._transformVector(m_normal);
m_transformApplied = true;
}
void
Plane::computeBoundingBox(Vec3d& min, Vec3d& max, const double imstkNotUsed(paddingPercent))
{
updatePostTransformData();
Vec3d p1 = m_position + Vec3d(0.5, 0.0, 0.5);
Vec3d p2 = m_position + Vec3d(0.5, 0.0, -0.5);
Vec3d p3 = m_position + Vec3d(-0.5, 0.0, 0.5);
Vec3d p4 = m_position + Vec3d(-0.5, 0.0, -0.5);
p1 = (m_transform * Vec4d(p1[0], p1[1], p1[2], 1.0)).head<3>();
p2 = (m_transform * Vec4d(p2[0], p2[1], p2[2], 1.0)).head<3>();
p3 = (m_transform * Vec4d(p3[0], p3[1], p3[2], 1.0)).head<3>();
p4 = (m_transform * Vec4d(p4[0], p4[1], p4[2], 1.0)).head<3>();
min = p1.cwiseMin(p2);
min = min.cwiseMin(p3);
min = min.cwiseMin(p4);
max = p1.cwiseMax(p2);
max = max.cwiseMax(p3);
max = max.cwiseMax(p4);
}
} // namespace imstk | 25 | 92 | 0.615726 | [
"transform"
] |
b4ab337772596420003cb7291839d37f9b94ed65 | 6,072 | hh | C++ | src/OpenMesh/Apps/Unsupported/IvViewer/SoOpenMeshNodeT.hh | rzoller/OpenMesh | f84bca0b26c61eab5f9335b2191962ca8545c5f6 | [
"BSD-3-Clause"
] | null | null | null | src/OpenMesh/Apps/Unsupported/IvViewer/SoOpenMeshNodeT.hh | rzoller/OpenMesh | f84bca0b26c61eab5f9335b2191962ca8545c5f6 | [
"BSD-3-Clause"
] | null | null | null | src/OpenMesh/Apps/Unsupported/IvViewer/SoOpenMeshNodeT.hh | rzoller/OpenMesh | f84bca0b26c61eab5f9335b2191962ca8545c5f6 | [
"BSD-3-Clause"
] | null | null | null | /* ========================================================================= *
* *
* OpenMesh *
* Copyright (c) 2001-2015, RWTH-Aachen University *
* Department of Computer Graphics and Multimedia *
* All rights reserved. *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
*---------------------------------------------------------------------------*
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions *
* are met: *
* *
* 1. Redistributions of source code must retain the above copyright notice, *
* this list of conditions and the following disclaimer. *
* *
* 2. Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* *
* 3. Neither the name of the copyright holder nor the names of its *
* contributors may be used to endorse or promote products derived from *
* this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A *
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER *
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, *
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, *
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR *
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF *
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING *
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
* *
* ========================================================================= */
/*===========================================================================*\
* *
* $Revision: 1258 $ *
* $Date: 2015-04-28 15:07:46 +0200 (Di, 28 Apr 2015) $ *
* *
\*===========================================================================*/
//=============================================================================
//
// Class SoOpenMeshNode
//
// This class defines an basic inventor node to display an OpenMesh
//
//=============================================================================
#ifndef OPENMESH_SOOPENMESHNODE_HH
#define OPENMESH_SOOPENMESHNODE_HH
//== INCLUDES =================================================================
#include <OpenMesh/Core/Utils/GenProg.hh>
#include <Inventor/nodes/SoNode.h>
#include <Inventor/nodes/SoShape.h>
//== NAMESPACES ===============================================================
namespace OpenMesh {
//== CLASS DEFINITION =========================================================
template <class Mesh>
class SoOpenMeshNodeT : public SoShape
{
SO_NODE_HEADER(SoOpenMeshNodeT<Mesh>);
public:
static void initClass();
SoOpenMeshNodeT(const Mesh* _mesh=0);
void setMesh(const Mesh* mesh) { d_mesh = mesh; }
protected:
virtual void GLRender(SoGLRenderAction *action);
virtual void computeBBox(SoAction *action, SbBox3f &box, SbVec3f ¢er);
virtual void generatePrimitives(SoAction *action);
private:
virtual ~SoOpenMeshNodeT() {};
// Draw faces as triangles / polygons
void drawFaces(bool _send_normals) {
typedef typename Mesh::Face Face;
drawFaces(_send_normals, typename Face::IsTriangle());
}
void drawFaces(bool _send_normals, OpenMesh::GenProg::Bool2Type<true>);
void drawFaces(bool _send_normals, OpenMesh::GenProg::Bool2Type<false>);
// Generate primitives
void genPrimitives(SoAction* _action) {
typedef typename Mesh::Face Face;
genPrimitives(_action, typename Face::IsTriangle());
}
void genPrimitives(SoAction* _action, OpenMesh::GenProg::Bool2Type<true>);
void genPrimitives(SoAction* _action, OpenMesh::GenProg::Bool2Type<false>);
const Mesh* mesh_;
};
//=============================================================================
} // namespace OpenMesh
//=============================================================================
#if defined(INCLUDE_TEMPLATES) && !defined(OPENMESH_SOOPENMESHNODE_CC)
# define OPENMESH_SOOPENMESHMODE_TEMPLATES
# include "SoOpenMeshNodeT.cc"
#endif
//=============================================================================
#endif // OPENMESH_SOOPENMESHNODE_HH
//=============================================================================
| 44.647059 | 91 | 0.438076 | [
"mesh"
] |
b4ab859baf51e1ceab593d6ce2031bd6e7571045 | 21,468 | cc | C++ | third_party/fuchsia-sdk/pkg/scenic_cpp/resources.cc | zachary0101/fuchsia-sample | f89a96f6d320b9963fa8168954b84441ca2fdf40 | [
"BSD-3-Clause"
] | 2 | 2020-08-16T15:32:35.000Z | 2021-11-07T20:09:46.000Z | third_party/fuchsia-sdk/pkg/scenic_cpp/resources.cc | zachary0101/fuchsia-sample | f89a96f6d320b9963fa8168954b84441ca2fdf40 | [
"BSD-3-Clause"
] | null | null | null | third_party/fuchsia-sdk/pkg/scenic_cpp/resources.cc | zachary0101/fuchsia-sample | f89a96f6d320b9963fa8168954b84441ca2fdf40 | [
"BSD-3-Clause"
] | 1 | 2021-08-15T04:29:11.000Z | 2021-08-15T04:29:11.000Z | // Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <lib/images/cpp/images.h>
#include <lib/ui/scenic/cpp/commands.h>
#include <lib/ui/scenic/cpp/resources.h>
#include <lib/ui/scenic/cpp/view_token_pair.h>
#include <algorithm>
namespace scenic {
namespace {
template <class T>
constexpr const T& clamp(const T& v, const T& lo, const T& hi) {
return (v < lo) ? lo : (hi < v) ? hi : v;
}
} // namespace
Resource::Resource(Session* session) : session_(session), id_(session->AllocResourceId()) {}
Resource::Resource(Resource&& moved) noexcept : session_(moved.session_), id_(moved.id_) {
auto& moved_session = *const_cast<Session**>(&moved.session_);
auto& moved_id = *const_cast<uint32_t*>(&moved.id_);
moved_session = nullptr;
moved_id = 0;
}
Resource::~Resource() {
// If this resource was moved, it is not responsible for releasing the ID.
if (session_)
session_->ReleaseResource(id_);
}
void Resource::Export(zx::eventpair export_token) {
session_->Enqueue(NewExportResourceCmd(id(), std::move(export_token)));
}
void Resource::ExportAsRequest(zx::eventpair* out_import_token) {
session_->Enqueue(NewExportResourceCmdAsRequest(id(), out_import_token));
}
void Resource::SetEventMask(uint32_t event_mask) {
session_->Enqueue(NewSetEventMaskCmd(id(), event_mask));
}
void Resource::SetLabel(const std::string& label) {
session_->Enqueue(NewSetLabelCmd(id(), label));
}
Shape::Shape(Session* session) : Resource(session) {}
Shape::Shape(Shape&& moved) noexcept : Resource(std::move(moved)) {}
Shape::~Shape() = default;
Circle::Circle(Session* session, float radius) : Shape(session) {
session->Enqueue(NewCreateCircleCmd(id(), radius));
}
Circle::Circle(Circle&& moved) noexcept : Shape(std::move(moved)) {}
Circle::~Circle() = default;
Rectangle::Rectangle(Session* session, float width, float height) : Shape(session) {
session->Enqueue(NewCreateRectangleCmd(id(), width, height));
}
Rectangle::Rectangle(Rectangle&& moved) noexcept : Shape(std::move(moved)) {}
Rectangle::~Rectangle() = default;
RoundedRectangle::RoundedRectangle(Session* session, float width, float height,
float top_left_radius, float top_right_radius,
float bottom_right_radius, float bottom_left_radius)
: Shape(session) {
session->Enqueue(NewCreateRoundedRectangleCmd(id(), width, height, top_left_radius,
top_right_radius, bottom_right_radius,
bottom_left_radius));
}
RoundedRectangle::RoundedRectangle(RoundedRectangle&& moved) noexcept : Shape(std::move(moved)) {}
RoundedRectangle::~RoundedRectangle() = default;
Image::Image(const Memory& memory, off_t memory_offset, fuchsia::images::ImageInfo info)
: Image(memory.session(), memory.id(), memory_offset, info) {}
Image::Image(Session* session, uint32_t memory_id, off_t memory_offset,
fuchsia::images::ImageInfo info)
: Resource(session), memory_offset_(memory_offset), info_(info) {
session->Enqueue(NewCreateImageCmd(id(), memory_id, memory_offset_, info));
}
Image::Image(Image&& moved) noexcept
: Resource(std::move(moved)), memory_offset_(moved.memory_offset_), info_(moved.info_) {}
Image::~Image() = default;
size_t Image::ComputeSize(const fuchsia::images::ImageInfo& image_info) {
return images::ImageSize(image_info);
}
Buffer::Buffer(const Memory& memory, off_t memory_offset, size_t num_bytes)
: Buffer(memory.session(), memory.id(), memory_offset, num_bytes) {}
Buffer::Buffer(Session* session, uint32_t memory_id, off_t memory_offset, size_t num_bytes)
: Resource(session) {
session->Enqueue(NewCreateBufferCmd(id(), memory_id, memory_offset, num_bytes));
}
Buffer::Buffer(Buffer&& moved) noexcept : Resource(std::move(moved)) {}
Buffer::~Buffer() = default;
Memory::Memory(Session* session, zx::vmo vmo, uint64_t allocation_size,
fuchsia::images::MemoryType memory_type)
: Resource(session), memory_type_(memory_type) {
session->Enqueue(NewCreateMemoryCmd(id(), std::move(vmo), allocation_size, memory_type));
}
Memory::Memory(Memory&& moved) noexcept
: Resource(std::move(moved)), memory_type_(moved.memory_type_) {}
Memory::~Memory() = default;
Mesh::Mesh(Session* session) : Shape(session) { session->Enqueue(NewCreateMeshCmd(id())); }
Mesh::Mesh(Mesh&& moved) noexcept : Shape(std::move(moved)) {}
Mesh::~Mesh() = default;
void Mesh::BindBuffers(const Buffer& index_buffer, fuchsia::ui::gfx::MeshIndexFormat index_format,
uint64_t index_offset, uint32_t index_count, const Buffer& vertex_buffer,
fuchsia::ui::gfx::MeshVertexFormat vertex_format, uint64_t vertex_offset,
uint32_t vertex_count, const std::array<float, 3>& bounding_box_min,
const std::array<float, 3>& bounding_box_max) {
ZX_DEBUG_ASSERT(session() == index_buffer.session() && session() == vertex_buffer.session());
session()->Enqueue(NewBindMeshBuffersCmd(
id(), index_buffer.id(), index_format, index_offset, index_count, vertex_buffer.id(),
vertex_format, vertex_offset, vertex_count, bounding_box_min, bounding_box_max));
}
Material::Material(Session* session) : Resource(session) {
session->Enqueue(NewCreateMaterialCmd(id()));
}
Material::Material(Material&& moved) noexcept : Resource(std::move(moved)) {}
Material::~Material() = default;
void Material::SetTexture(uint32_t image_id) {
session()->Enqueue(NewSetTextureCmd(id(), image_id));
}
void Material::SetColor(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha) {
session()->Enqueue(NewSetColorCmd(id(), red, green, blue, alpha));
}
Node::Node(Session* session) : Resource(session) {}
Node::Node(Node&& moved) noexcept : Resource(std::move(moved)) {}
Node::~Node() = default;
void Node::SetTranslation(const std::array<float, 3>& translation) {
session()->Enqueue(NewSetTranslationCmd(id(), translation));
}
void Node::SetTranslation(uint32_t variable_id) {
session()->Enqueue(NewSetTranslationCmd(id(), variable_id));
}
void Node::SetScale(const std::array<float, 3>& scale) {
session()->Enqueue(NewSetScaleCmd(id(), scale));
}
void Node::SetScale(uint32_t variable_id) { session()->Enqueue(NewSetScaleCmd(id(), variable_id)); }
void Node::SetRotation(const std::array<float, 4>& quaternion) {
session()->Enqueue(NewSetRotationCmd(id(), quaternion));
}
void Node::SetRotation(uint32_t variable_id) {
session()->Enqueue(NewSetRotationCmd(id(), variable_id));
}
void Node::SetAnchor(const std::array<float, 3>& anchor) {
session()->Enqueue(NewSetAnchorCmd(id(), anchor));
}
void Node::SetAnchor(uint32_t variable_id) {
session()->Enqueue(NewSetAnchorCmd(id(), variable_id));
}
void Node::SendSizeChangeHint(float width_change_factor, float height_change_factor) {
session()->Enqueue(NewSendSizeChangeHintCmdHACK(id(), width_change_factor, height_change_factor));
}
void Node::SetTag(uint32_t tag_value) { session()->Enqueue(NewSetTagCmd(id(), tag_value)); }
void Node::SetHitTestBehavior(fuchsia::ui::gfx::HitTestBehavior hit_test_behavior) {
session()->Enqueue(NewSetHitTestBehaviorCmd(id(), hit_test_behavior));
}
void Node::Detach() { session()->Enqueue(NewDetachCmd(id())); }
ShapeNode::ShapeNode(Session* session) : Node(session) {
session->Enqueue(NewCreateShapeNodeCmd(id()));
}
ShapeNode::ShapeNode(ShapeNode&& moved) noexcept : Node(std::move(moved)) {}
ShapeNode::~ShapeNode() = default;
void ShapeNode::SetShape(uint32_t shape_id) { session()->Enqueue(NewSetShapeCmd(id(), shape_id)); }
void ShapeNode::SetMaterial(uint32_t material_id) {
session()->Enqueue(NewSetMaterialCmd(id(), material_id));
}
ContainerNode::ContainerNode(Session* session) : Node(session) {}
ContainerNode::ContainerNode(ContainerNode&& moved) noexcept : Node(std::move(moved)) {}
ContainerNode::~ContainerNode() = default;
void ContainerNode::AddChild(uint32_t child_node_id) {
session()->Enqueue(NewAddChildCmd(id(), child_node_id));
}
void ContainerNode::DetachChildren() { session()->Enqueue(NewDetachChildrenCmd(id())); }
EntityNode::EntityNode(Session* session) : ContainerNode(session) {
session->Enqueue(NewCreateEntityNodeCmd(id()));
}
EntityNode::EntityNode(EntityNode&& moved) noexcept : ContainerNode(std::move(moved)) {}
EntityNode::~EntityNode() = default;
void EntityNode::Attach(const ViewHolder& view_holder) { AddChild(view_holder); }
void EntityNode::SetClip(uint32_t clip_id, bool clip_to_self) {
session()->Enqueue(NewSetClipCmd(id(), clip_id, clip_to_self));
}
void EntityNode::SetClipPlanes(std::vector<fuchsia::ui::gfx::Plane3> planes) {
session()->Enqueue(NewSetClipPlanesCmd(id(), std::move(planes)));
}
ImportNode::ImportNode(Session* session) : ContainerNode(session) {}
ImportNode::ImportNode(ImportNode&& moved) noexcept : ContainerNode(std::move(moved)) {}
ImportNode::~ImportNode() { ZX_DEBUG_ASSERT_MSG(is_bound_, "Import was never bound."); }
void ImportNode::Bind(zx::eventpair import_token) {
ZX_DEBUG_ASSERT(!is_bound_);
session()->Enqueue(
NewImportResourceCmd(id(), fuchsia::ui::gfx::ImportSpec::NODE, std::move(import_token)));
is_bound_ = true;
}
void ImportNode::BindAsRequest(zx::eventpair* out_export_token) {
ZX_DEBUG_ASSERT(!is_bound_);
session()->Enqueue(
NewImportResourceCmdAsRequest(id(), fuchsia::ui::gfx::ImportSpec::NODE, out_export_token));
is_bound_ = true;
}
void ImportNode::Attach(const ViewHolder& view_holder) {
session()->Enqueue(NewAddChildCmd(id(), view_holder.id()));
}
ViewHolder::ViewHolder(Session* session, zx::eventpair token, const std::string& debug_name)
: Node(session) {
session->Enqueue(
NewCreateViewHolderCmd(id(), scenic::ToViewHolderToken(std::move(token)), debug_name));
}
ViewHolder::ViewHolder(Session* session, fuchsia::ui::views::ViewHolderToken token,
const std::string& debug_name)
: Node(session) {
session->Enqueue(NewCreateViewHolderCmd(id(), std::move(token), debug_name));
}
ViewHolder::ViewHolder(ViewHolder&& moved) noexcept : Node(std::move(moved)) {}
ViewHolder::~ViewHolder() = default;
void ViewHolder::SetViewProperties(const std::array<float, 3>& bounding_box_min,
const std::array<float, 3>& bounding_box_max,
const std::array<float, 3>& inset_from_min,
const std::array<float, 3>& inset_from_max) {
session()->Enqueue(NewSetViewPropertiesCmd(id(), bounding_box_min, bounding_box_max,
inset_from_min, inset_from_max));
}
void ViewHolder::SetViewProperties(const fuchsia::ui::gfx::ViewProperties& props) {
session()->Enqueue(NewSetViewPropertiesCmd(id(), props));
}
void ViewHolder::SetDebugBoundsColor(uint8_t red, uint8_t green, uint8_t blue) {
session()->Enqueue(NewSetViewHolderBoundsColorCmd(id(), red, green, blue));
}
View::View(Session* session, zx::eventpair token, const std::string& debug_name)
: Resource(session) {
session->Enqueue(NewCreateViewCmd(id(), scenic::ToViewToken(std::move(token)), debug_name));
}
View::View(Session* session, fuchsia::ui::views::ViewToken token, const std::string& debug_name)
: Resource(session) {
session->Enqueue(NewCreateViewCmd(id(), std::move(token), debug_name));
}
View::View(Session* session, fuchsia::ui::views::ViewToken token,
fuchsia::ui::views::ViewRefControl control_ref, fuchsia::ui::views::ViewRef view_ref,
const std::string& debug_name)
: Resource(session) {
session->Enqueue(NewCreateViewCmd(id(), std::move(token), std::move(control_ref),
std::move(view_ref), debug_name));
}
View::View(View&& moved) noexcept : Resource(std::move(moved)) {}
View::~View() = default;
void View::AddChild(const Node& child) const {
ZX_DEBUG_ASSERT(session() == child.session());
session()->Enqueue(NewAddChildCmd(id(), child.id()));
}
void View::DetachChild(const Node& child) const {
ZX_DEBUG_ASSERT(session() == child.session());
session()->Enqueue(NewDetachCmd(child.id()));
}
void View::enableDebugBounds(bool enable) {
session()->Enqueue(NewSetEnableDebugViewBoundsCmd(id(), enable));
}
ClipNode::ClipNode(Session* session) : ContainerNode(session) {
session->Enqueue(NewCreateClipNodeCmd(id()));
}
ClipNode::ClipNode(ClipNode&& moved) noexcept : ContainerNode(std::move(moved)) {}
ClipNode::~ClipNode() = default;
OpacityNodeHACK::OpacityNodeHACK(Session* session) : ContainerNode(session) {
session->Enqueue(NewCreateOpacityNodeCmdHACK(id()));
}
OpacityNodeHACK::OpacityNodeHACK(OpacityNodeHACK&& moved) noexcept
: ContainerNode(std::move(moved)) {}
OpacityNodeHACK::~OpacityNodeHACK() = default;
void OpacityNodeHACK::SetOpacity(float opacity) {
opacity = clamp(opacity, 0.f, 1.f);
session()->Enqueue(NewSetOpacityCmd(id(), opacity));
}
Variable::Variable(Session* session, fuchsia::ui::gfx::Value initial_value) : Resource(session) {
session->Enqueue(NewCreateVariableCmd(id(), std::move(initial_value)));
}
Variable::Variable(Variable&& moved) noexcept : Resource(std::move(moved)) {}
Variable::~Variable() = default;
Scene::Scene(Session* session) : ContainerNode(session) {
session->Enqueue(NewCreateSceneCmd(id()));
}
Scene::Scene(Scene&& moved) noexcept : ContainerNode(std::move(moved)) {}
Scene::~Scene() = default;
void Scene::AddLight(uint32_t light_id) { session()->Enqueue(NewAddLightCmd(id(), light_id)); }
void Scene::AddAmbientLight(uint32_t light_id) {
session()->Enqueue(NewSceneAddAmbientLightCmd(id(), light_id));
}
void Scene::AddDirectionalLight(uint32_t light_id) {
session()->Enqueue(NewSceneAddDirectionalLightCmd(id(), light_id));
}
void Scene::AddPointLight(uint32_t light_id) {
session()->Enqueue(NewSceneAddPointLightCmd(id(), light_id));
}
void Scene::DetachLights() { session()->Enqueue(NewDetachLightsCmd(id())); }
void CameraBase::SetTransform(const std::array<float, 3>& eye_position,
const std::array<float, 3>& eye_look_at,
const std::array<float, 3>& eye_up) {
session()->Enqueue(NewSetCameraTransformCmd(id(), eye_position, eye_look_at, eye_up));
}
void CameraBase::SetClipSpaceTransform(float x, float y, float scale) {
session()->Enqueue(NewSetCameraClipSpaceTransformCmd(id(), x, y, scale));
}
void CameraBase::SetPoseBuffer(const Buffer& buffer, uint32_t num_entries, int64_t base_time,
uint64_t time_interval) {
session()->Enqueue(
NewSetCameraPoseBufferCmd(id(), buffer.id(), num_entries, base_time, time_interval));
}
void CameraBase::SetPoseBuffer(const Buffer& buffer, uint32_t num_entries, zx::time base_time,
zx::duration time_interval) {
SetPoseBuffer(buffer, num_entries, base_time.get(), time_interval.get());
}
Camera::Camera(const Scene& scene) : Camera(scene.session(), scene.id()) {}
Camera::Camera(Session* session, uint32_t scene_id) : CameraBase(session) {
session->Enqueue(NewCreateCameraCmd(id(), scene_id));
}
Camera::Camera(Camera&& moved) noexcept : CameraBase(std::move(moved)) {}
Camera::~Camera() = default;
void Camera::SetProjection(const float fovy) {
session()->Enqueue(NewSetCameraProjectionCmd(id(), fovy));
}
StereoCamera::StereoCamera(const Scene& scene) : StereoCamera(scene.session(), scene.id()) {}
StereoCamera::StereoCamera(Session* session, uint32_t scene_id) : CameraBase(session) {
session->Enqueue(NewCreateStereoCameraCmd(id(), scene_id));
}
StereoCamera::StereoCamera(StereoCamera&& moved) noexcept : CameraBase(std::move(moved)) {}
StereoCamera::~StereoCamera() = default;
void StereoCamera::SetStereoProjection(const std::array<float, 4 * 4>& left_projection,
const std::array<float, 4 * 4>& right_projection) {
session()->Enqueue(NewSetStereoCameraProjectionCmd(id(), left_projection, right_projection));
}
Renderer::Renderer(Session* session) : Resource(session) {
session->Enqueue(NewCreateRendererCmd(id()));
}
Renderer::Renderer(Renderer&& moved) noexcept : Resource(std::move(moved)) {}
Renderer::~Renderer() = default;
void Renderer::SetCamera(uint32_t camera_id) {
session()->Enqueue(NewSetCameraCmd(id(), camera_id));
}
void Renderer::SetParam(fuchsia::ui::gfx::RendererParam param) {
session()->Enqueue(NewSetRendererParamCmd(id(), std::move(param)));
}
void Renderer::SetShadowTechnique(fuchsia::ui::gfx::ShadowTechnique technique) {
auto param = fuchsia::ui::gfx::RendererParam();
param.set_shadow_technique(technique);
SetParam(std::move(param));
}
void Renderer::SetDisableClipping(bool disable_clipping) {
session()->Enqueue(NewSetDisableClippingCmd(id(), disable_clipping));
}
void Renderer::SetEnableDebugging(bool enable_debugging) {
auto param = fuchsia::ui::gfx::RendererParam();
param.set_enable_debugging(enable_debugging);
SetParam(std::move(param));
}
Layer::Layer(Session* session) : Resource(session) { session->Enqueue(NewCreateLayerCmd(id())); }
Layer::Layer(Layer&& moved) noexcept : Resource(std::move(moved)) {}
Layer::~Layer() = default;
void Layer::SetRenderer(uint32_t renderer_id) {
session()->Enqueue(NewSetRendererCmd(id(), renderer_id));
}
void Layer::SetSize(const std::array<float, 2>& size) {
session()->Enqueue(NewSetSizeCmd(id(), size));
}
LayerStack::LayerStack(Session* session) : Resource(session) {
session->Enqueue(NewCreateLayerStackCmd(id()));
}
LayerStack::LayerStack(LayerStack&& moved) noexcept : Resource(std::move(moved)) {}
LayerStack::~LayerStack() = default;
void LayerStack::AddLayer(uint32_t layer_id) { session()->Enqueue(NewAddLayerCmd(id(), layer_id)); }
void LayerStack::RemoveLayer(uint32_t layer_id) {
session()->Enqueue(NewRemoveLayerCmd(id(), layer_id));
}
void LayerStack::RemoveAllLayers() { session()->Enqueue(NewRemoveAllLayersCmd(id())); }
DisplayCompositor::DisplayCompositor(Session* session) : Resource(session) {
session->Enqueue(NewCreateDisplayCompositorCmd(id()));
}
DisplayCompositor::DisplayCompositor(DisplayCompositor&& moved) noexcept
: Resource(std::move(moved)) {}
DisplayCompositor::~DisplayCompositor() = default;
void DisplayCompositor::SetLayerStack(uint32_t layer_stack_id) {
session()->Enqueue(NewSetLayerStackCmd(id(), layer_stack_id));
}
void DisplayCompositor::SetColorConversion(const std::array<float, 3>& preoffsets,
const std::array<float, 3 * 3>& matrix,
const std::array<float, 3>& postoffsets) {
session()->Enqueue(NewSetDisplayColorConversionCmdHACK(id(), preoffsets, matrix, postoffsets));
}
void DisplayCompositor::SetLayoutRotation(uint32_t rotation_degrees) {
session()->Enqueue(NewSetDisplayRotationCmdHACK(id(), rotation_degrees));
}
Compositor::Compositor(Session* session) : Resource(session) {
session->Enqueue(NewCreateCompositorCmd(id()));
}
Compositor::Compositor(Compositor&& moved) noexcept : Resource(std::move(moved)) {}
Compositor::~Compositor() = default;
void Compositor::SetLayerStack(uint32_t layer_stack_id) {
session()->Enqueue(NewSetLayerStackCmd(id(), layer_stack_id));
}
void Compositor::SetLayoutRotation(uint32_t rotation_degrees) {
session()->Enqueue(NewSetDisplayRotationCmdHACK(id(), rotation_degrees));
}
Light::Light(Session* session) : Resource(session) {}
Light::Light(Light&& moved) noexcept : Resource(std::move(moved)) {}
Light::~Light() = default;
void Light::SetColor(const std::array<float, 3>& rgb) {
session()->Enqueue(NewSetLightColorCmd(id(), rgb));
}
void Light::SetColor(uint32_t variable_id) {
session()->Enqueue(NewSetLightColorCmd(id(), variable_id));
}
void Light::Detach() { session()->Enqueue(NewDetachLightCmd(id())); }
AmbientLight::AmbientLight(Session* session) : Light(session) {
session->Enqueue(NewCreateAmbientLightCmd(id()));
}
AmbientLight::AmbientLight(AmbientLight&& moved) noexcept : Light(std::move(moved)) {}
AmbientLight::~AmbientLight() = default;
DirectionalLight::DirectionalLight(Session* session) : Light(session) {
session->Enqueue(NewCreateDirectionalLightCmd(id()));
}
DirectionalLight::DirectionalLight(DirectionalLight&& moved) noexcept : Light(std::move(moved)) {}
DirectionalLight::~DirectionalLight() = default;
void DirectionalLight::SetDirection(const std::array<float, 3>& direction) {
session()->Enqueue(NewSetLightDirectionCmd(id(), direction));
}
void DirectionalLight::SetDirection(uint32_t variable_id) {
session()->Enqueue(NewSetLightDirectionCmd(id(), variable_id));
}
PointLight::PointLight(Session* session) : Light(session) {
session->Enqueue(NewCreatePointLightCmd(id()));
}
PointLight::PointLight(PointLight&& moved) noexcept : Light(std::move(moved)) {}
PointLight::~PointLight() = default;
void PointLight::SetPosition(const std::array<float, 3>& position) {
session()->Enqueue(NewSetPointLightPositionCmd(id(), position));
}
void PointLight::SetPosition(uint32_t variable_id) {
session()->Enqueue(NewSetPointLightPositionCmd(id(), variable_id));
}
void PointLight::SetFalloff(float falloff) {
session()->Enqueue(NewSetPointLightFalloffCmd(id(), falloff));
}
} // namespace scenic
| 35.193443 | 100 | 0.71581 | [
"mesh",
"shape",
"vector"
] |
b4ae0fce83213642e9d0387065d20abe65fddd0a | 6,337 | cpp | C++ | engine/test/gtest/test_split_op.cpp | kevinintel/neural-compressor | b57645566aeff8d3c18dc49d2739a583c072f940 | [
"Apache-2.0"
] | 100 | 2020-12-01T02:40:12.000Z | 2021-09-09T08:14:22.000Z | engine/test/gtest/test_split_op.cpp | kevinintel/neural-compressor | b57645566aeff8d3c18dc49d2739a583c072f940 | [
"Apache-2.0"
] | 25 | 2021-01-05T00:16:17.000Z | 2021-09-10T03:24:01.000Z | engine/test/gtest/test_split_op.cpp | kevinintel/neural-compressor | b57645566aeff8d3c18dc49d2739a583c072f940 | [
"Apache-2.0"
] | 25 | 2020-12-01T19:07:08.000Z | 2021-08-30T14:20:07.000Z | // Copyright (c) 2021 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <map>
#include <string>
#include "gtest/gtest.h"
#include "../../include/conf.hpp"
#include "../../include/common.hpp"
#include "../../include/operators/split.hpp"
using executor::Tensor;
using executor::OperatorConfig;
using executor::TensorConfig;
using executor::AttrConfig;
using executor::MemoryAllocator;
struct OpArgs {
std::vector<Tensor*> input;
std::vector<Tensor*> output;
OperatorConfig conf;
};
struct TestParams {
std::pair<OpArgs, OpArgs> args;
bool expect_to_fail;
};
void GetTrueData(const std::vector<Tensor*>& input, const std::vector<Tensor*>& output,
const OperatorConfig& conf) {
auto attrs_map = conf.attributes();
int axis = 0;
auto iter = attrs_map.find("axis");
if (iter != attrs_map.end() && iter->second != "") {
axis = stoi(iter->second);
}
auto src_tensor_shape = input[0]->shape();
vector<int64_t> src_stride = executor::GetStrides(src_tensor_shape);
vector<int64_t> dst_shape;
for (int n = 0; n < src_stride.size(); ++n) {
if (n != axis) {
dst_shape.emplace_back(src_tensor_shape[n]);
} else {
dst_shape.emplace_back(1);
}
}
// dst shape
output[0]->set_shape(dst_shape);
output[1]->set_shape(dst_shape);
float* dst_data = static_cast<float*>(output[0]->mutable_data());
float* dst_data1 = static_cast<float*>(output[1]->mutable_data());
const auto src_tensor_data = static_cast<const float*>(input[0]->data());
int h = dst_shape[0];
int w = dst_shape[1];
if (axis == 0) {
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
dst_data[i * w + j] = src_tensor_data[i * src_tensor_shape[1]+ j];
dst_data1[i * w + j] = src_tensor_data[(i + 1) * src_tensor_shape[1]+ j];
}
}
}
}
bool CheckResult(const TestParams& t) {
const auto& p = t.args.first;
const auto& q = t.args.second;
executor::SplitOperator split(p.conf);
split.Reshape(p.input, p.output);
split.Forward(p.input, p.output);
if (!t.expect_to_fail) {
GetTrueData(q.input, q.output, q.conf);
// Should compare buffer with different addresses
EXPECT_NE(p.output[0]->data(), q.output[0]->data());
return executor::CompareData<float>(p.output[0]->data(), p.output[0]->size(),
q.output[0]->data(), q.output[0]->size());
}
return false;
}
class ConcatTest : public testing::TestWithParam<TestParams> {
protected:
ConcatTest() {}
~ConcatTest() {}
void SetUp() override {}
void TearDown() override {}
};
TEST_P(ConcatTest, TestPostfix) {
TestParams t = testing::TestWithParam<TestParams>::GetParam();
EXPECT_TRUE(CheckResult(t));
}
std::pair<OpArgs, OpArgs> GenerateFp32Case(const std::vector<std::vector<int64_t>>& input_shape,
std::string axis, std::string split) {
// Step 1: Construct Tensor config ptr
const auto& src_shape = input_shape[0];
TensorConfig* src_config = new TensorConfig("src", src_shape);
std::vector<TensorConfig*> input_config = {src_config};
std::vector<int64_t> dst_shape = {};
TensorConfig* dst_config = new TensorConfig("dst", dst_shape);
std::vector<TensorConfig*> output_config = {dst_config, dst_config};
// Step 1.1: Construct Operator config obj
std::map<std::string, std::string> attr_map;
attr_map = {
{"axis", axis},
{"split", split}
};
AttrConfig* op_attr = new AttrConfig(attr_map);
OperatorConfig op_config = OperatorConfig("split", "fp32",
input_config, output_config, op_attr);
// Step 2: Construct Tensor ptr
auto make_tensor_obj = [&](const TensorConfig* a_tensor_config) {
// step1: set shape
Tensor* a_tensor = new Tensor(*a_tensor_config);
// step2: set tensor life
a_tensor->add_tensor_life(1);
// step3: library buffer can only be obtained afterwards
auto tensor_data = a_tensor->mutable_data();
executor::InitVector(static_cast<float*>(tensor_data), a_tensor->size());
Tensor* a_tensor_copy = new Tensor(*a_tensor_config);
a_tensor_copy->add_tensor_life(1);
auto tensor_data_copy = a_tensor_copy->mutable_data();
memcpy(reinterpret_cast<void*>(tensor_data_copy), tensor_data,
a_tensor_copy->size() * sizeof(float));
return std::pair<Tensor*, Tensor*>{a_tensor, a_tensor_copy};
};
auto src_tensors = make_tensor_obj(src_config);
Tensor* dst_tensor = new Tensor(*dst_config);
dst_tensor->add_tensor_life(1);
Tensor* dst_tensor1 = new Tensor(*dst_config);
dst_tensor1->add_tensor_life(1);
Tensor* dst_tensor_copy = new Tensor(*dst_config);
dst_tensor_copy->add_tensor_life(1);
Tensor* dst_tensor_copy1 = new Tensor(*dst_config);
dst_tensor_copy1->add_tensor_life(1);
OpArgs op_args = {{src_tensors.first, src_tensors.first},
{dst_tensor, dst_tensor1}, op_config};
OpArgs op_args_copy = {{src_tensors.second, src_tensors.second},
{dst_tensor_copy, dst_tensor_copy1}, op_config};
return {op_args, op_args_copy};
}
static auto CasesFp32 = []() {
std::string memory_strategy = getenv("DIRECT_BUFFER") == NULL \
? "cycle_buffer" : "direct_buffer";
MemoryAllocator::SetStrategy(memory_strategy);
std::vector<TestParams> cases;
// Config
std::vector<int64_t> src_shape;
// case: simple for 0 axis
src_shape = {2, 32};
cases.push_back({GenerateFp32Case({src_shape}, "0", "1, 1"), false});
return ::testing::ValuesIn(cases);
};
INSTANTIATE_TEST_SUITE_P(Prefix, ConcatTest, CasesFp32());
| 35.01105 | 97 | 0.650781 | [
"shape",
"vector"
] |
b4aec1a0884c6c212eda42e53407d11d9a0b2e87 | 2,601 | cpp | C++ | src/marnav/ais/message_24.cpp | PappaD/marnav | ea82c58c71d3c09ab7d91bdcfda5299f83a84f5c | [
"BSD-4-Clause"
] | null | null | null | src/marnav/ais/message_24.cpp | PappaD/marnav | ea82c58c71d3c09ab7d91bdcfda5299f83a84f5c | [
"BSD-4-Clause"
] | null | null | null | src/marnav/ais/message_24.cpp | PappaD/marnav | ea82c58c71d3c09ab7d91bdcfda5299f83a84f5c | [
"BSD-4-Clause"
] | 1 | 2020-12-21T16:38:02.000Z | 2020-12-21T16:38:02.000Z | #include "message_24.hpp"
#include <marnav/utils/mmsi.hpp>
namespace marnav
{
namespace ais
{
constexpr message_id message_24::ID;
constexpr std::size_t message_24::SIZE_BITS;
constexpr std::size_t message_24::SIZE_BITS_IGNORED_SPARES_OF_TYPE_A;
message_24::message_24()
: message_24(ID)
{
}
message_24::message_24(message_id id)
: message(id)
, shipname("@@@@@@@@@@@@@@@@@@@@")
, vendor_id("@@@")
, callsign("@@@@@@@")
{
}
message_24::message_24(const raw & bits)
: message_24(ID)
{
if ((bits.size() != SIZE_BITS) && (bits.size() != SIZE_BITS_IGNORED_SPARES_OF_TYPE_A))
throw std::invalid_argument{"invalid number of bits in ais/message_24"};
get(bits, part_number);
if ((part_number != part::A) && (part_number != part::B))
throw std::invalid_argument{"invalid part number ais/message_24"};
read_data(bits);
}
bool message_24::is_auxiliary_vessel() const
{
return utils::mmsi{mmsi}.is_auxiliary();
}
void message_24::read_data(const raw & bits)
{
get(bits, repeat_indicator);
get(bits, mmsi);
get(bits, part_number);
if (part_number == part::A) {
get(bits, shipname);
} else {
get(bits, shiptype);
get(bits, vendor_id);
get(bits, model);
get(bits, serial);
get(bits, callsign);
if (is_auxiliary_vessel()) {
get(bits, mothership_mmsi);
} else {
get(bits, to_bow);
get(bits, to_stern);
get(bits, to_port);
get(bits, to_starboard);
}
}
}
raw message_24::get_data() const
{
raw bits(SIZE_BITS);
bits.set(type(), 0, 6);
set(bits, repeat_indicator);
set(bits, mmsi);
set(bits, part_number);
if (part_number == part::A) {
set(bits, shipname);
} else {
set(bits, shiptype);
set(bits, vendor_id);
set(bits, model);
set(bits, serial);
set(bits, callsign);
if (is_auxiliary_vessel()) {
set(bits, mothership_mmsi);
} else {
set(bits, to_bow);
set(bits, to_stern);
set(bits, to_port);
set(bits, to_starboard);
}
}
return bits;
}
std::string message_24::get_shipname() const
{
return trim_ais_string(shipname);
}
std::string message_24::get_vendor_id() const
{
return trim_ais_string(vendor_id);
}
std::string message_24::get_callsign() const
{
return trim_ais_string(callsign);
}
void message_24::set_shipname(const std::string & t)
{
if (t.size() > 20) {
shipname = t.substr(0, 20);
} else {
shipname = t;
}
}
void message_24::set_vendor_id(const std::string & t)
{
if (t.size() > 3) {
callsign = t.substr(0, 3);
} else {
callsign = t;
}
}
void message_24::set_callsign(const std::string & t)
{
if (t.size() > 7) {
callsign = t.substr(0, 7);
} else {
callsign = t;
}
}
}
}
| 18.578571 | 87 | 0.662822 | [
"model"
] |
b4b1371826cb92f70768ea93f3b7d3c16dc4e583 | 8,957 | cc | C++ | src/client/StartCommand.cc | ryan-rao/LTFS-Data-Management | 041960282d20aeefb8da20eabf04367a164a5903 | [
"Apache-2.0"
] | 19 | 2018-06-28T03:53:41.000Z | 2022-03-15T16:17:33.000Z | src/client/StartCommand.cc | ryan-rao/LTFS-Data-Management | 041960282d20aeefb8da20eabf04367a164a5903 | [
"Apache-2.0"
] | 13 | 2018-04-25T15:40:14.000Z | 2021-01-18T11:03:27.000Z | src/client/StartCommand.cc | ryan-rao/LTFS-Data-Management | 041960282d20aeefb8da20eabf04367a164a5903 | [
"Apache-2.0"
] | 8 | 2018-08-08T05:40:31.000Z | 2022-03-22T16:21:06.000Z | /*******************************************************************************
* Copyright 2018 IBM Corp. 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
*
* 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.
*
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <limits.h>
#include <libgen.h>
#include <fcntl.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/resource.h>
#include <errno.h>
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif
#include <string>
#include <sstream>
#include <list>
#include <exception>
#include "src/common/errors.h"
#include "src/common/LTFSDMException.h"
#include "src/common/Message.h"
#include "src/common/Trace.h"
#include "src/common/Const.h"
#include "src/communication/ltfsdm.pb.h"
#include "src/communication/LTFSDmComm.h"
#include "LTFSDMCommand.h"
#include "StartCommand.h"
/** @page ltfsdm_start ltfsdm start
The ltfsdm start command starts the LTFS Data Management service.
<tt>@LTFSDMC0006I</tt>
parameters | description
---|---
- | -
Example:
@verbatim
[root@visp ~]# ltfsdm start
LTFSDMC0099I(0073): Starting the LTFS Data Management backend service.
LTFSDMX0029I(0062): LTFS Data Management version: 0.0.624-master.2017-11-09T10.57.51
LTFSDMC0100I(0097): Connecting.
LTFSDMC0097I(0141): The LTFS Data Management server process has been started with pid 13378.
@endverbatim
The corresponding class is @ref StartCommand.
@page start_processing start processing
The following is a summary of the start command processing:
@code
StartCommand::doCommand
StartCommand::determineServerPath
StartCommand::startServer
StartCommand::waitForResponse
while not connected and retry<10
LTFSDmCommClient::connect
sleep 1
if retry == 10
exit with failue
create statusrequest message
LTFSDmCommClient::send
LTFSDmCommClient::recv
evaluate response
@endcode
@dot
digraph start_command {
compound=true;
fontname="courier";
fontsize=11;
labeljust=l;
node [shape=record, width=2, fontname="courier", fontsize=11, fillcolor=white, style=filled];
do_command [fontname="courier bold", fontcolor=dodgerblue4, label="StartCommand::doCommand", URL="@ref StartCommand::doCommand"];
subgraph cluster_do_command {
label="StartCommand::doCommand";
determine_server_path [fontname="courier bold", fontcolor=dodgerblue4, label="StartCommand::determineServerPath", URL="@ref StartCommand::determineServerPath"];
start_server [fontname="courier bold", fontcolor=dodgerblue4, label="StartCommand::startServer", URL="@ref StartCommand::startServer"];
wait_for_response [fontname="courier bold", fontcolor=dodgerblue4, label="StartCommand::waitForResponse", URL="@ref StartCommand::waitForResponse"];
}
subgraph cluster_wait_for_response {
label="StartCommand::waitForResponse";
subgraph cluster_loop {
label="while not connected and retry<10";
connect [fontname="courier bold", fontcolor=dodgerblue4, label="LTFSDmCommClient::connect", URL="@ref LTFSDmCommClient::connect"];
sleep [label="sleep 1"];
}
subgraph cluster_condition {
label="if retry == 10";
exit [label="exit with failue"];
}
create_message [label="create statusrequest message"];
send [fontname="courier bold", fontcolor=dodgerblue4, label="LTFSDmCommClient::send", URL="@ref LTFSDmCommClient::send"];
recv [fontname="courier bold", fontcolor=dodgerblue4, label="LTFSDmCommClient::recv", URL="@ref LTFSDmCommClient::recv"];
response [label="evaluate response"];
}
do_command -> determine_server_path [lhead=cluster_do_command,minlen=2];
determine_server_path -> start_server [];
start_server -> wait_for_response [];
wait_for_response -> connect [lhead=cluster_wait_for_response,minlen=2];
connect -> sleep [];
sleep -> exit [ltail=cluster_loop,lhead=cluster_condition,minlen=2];
exit -> create_message [ltail=cluster_condition,minlen=2];
create_message -> send [];
send -> recv [];
recv -> response [];
}
@enddot
The start commands starts the LTFS Data Management server. To do so
its path name needs to be detected. This is performed by the
StartCommand::determineServerPath method. Since the client and the
server path are the same it is just necessary to read
the link to the executable of the current client process via procfs.
The backend is started within the StartCommand::startServer method.
It is started via popen system call.
After the backend is started the status information is requested
within the StartCommand::waitForResponse method. A connection is
retried 10 times before giving up and reporting a failure.
*/
void StartCommand::printUsage()
{
INFO(LTFSDMC0006I);
}
void StartCommand::determineServerPath()
{
char exepath[PATH_MAX];
TRACE(Trace::normal, Const::SERVER_COMMAND);
memset(exepath, 0, PATH_MAX);
if (readlink("/proc/self/exe", exepath, PATH_MAX - 1) == -1) {
MSG(LTFSDMC0021E);
THROW(Error::GENERAL_ERROR);
}
serverPath << dirname(exepath) << "/" << Const::SERVER_COMMAND;
TRACE(Trace::normal, serverPath.str());
}
void StartCommand::startServer()
{
struct stat statbuf;
FILE *ltfsdmd = NULL;
char line[Const::OUTPUT_LINE_SIZE];
int ret;
if (stat(serverPath.str().c_str(), &statbuf) == -1) {
MSG(LTFSDMC0021E);
TRACE(Trace::error, serverPath.str(), errno);
THROW(Error::GENERAL_ERROR);
}
MSG(LTFSDMC0099I);
ltfsdmd = popen(serverPath.str().c_str(), "r");
if (!ltfsdmd) {
MSG(LTFSDMC0022E);
TRACE(Trace::error, errno);
THROW(Error::GENERAL_ERROR);
}
while (fgets(line, sizeof(line), ltfsdmd)) {
INFO(LTFSDMC0024I, line);
}
ret = pclose(ltfsdmd);
if (!WIFEXITED(ret) || WEXITSTATUS(ret)) {
MSG(LTFSDMC0022E);
TRACE(Trace::error, ret, WIFEXITED(ret), WEXITSTATUS(ret));
THROW(Error::GENERAL_ERROR);
}
}
void StartCommand::waitForResponse()
{
int pid;
int retry = 0;
bool success = false;
int lockfd;
MSG(LTFSDMC0100I);
while (retry < Const::STARTUP_TIMEOUT) {
try {
connect();
success = true;
break;
} catch (const std::exception& e) {
INFO(LTFSDMC0103I);
if ((lockfd = open(Const::SERVER_LOCK_FILE.c_str(),
O_RDWR | O_CREAT, 0600)) == -1) {
INFO(LTFSDMC0104I);
MSG(LTFSDMC0033E);
THROW(Error::GENERAL_ERROR);
}
if (flock(lockfd, LOCK_EX | LOCK_NB) == 0) {
INFO(LTFSDMC0104I);
MSG(LTFSDMC0096E);
THROW(Error::GENERAL_ERROR);
}
retry++;
sleep(1);
}
}
INFO(LTFSDMC0104I);
if (success == false) {
MSG(LTFSDMC0096E);
THROW(Error::GENERAL_ERROR);
}
LTFSDmProtocol::LTFSDmStatusRequest *statusreq =
commCommand.mutable_statusrequest();
statusreq->set_key(key);
statusreq->set_reqnumber(requestNumber);
try {
commCommand.send();
} catch (const std::exception& e) {
MSG(LTFSDMC0027E);
THROW(Error::GENERAL_ERROR);
}
try {
commCommand.recv();
} catch (const std::exception& e) {
MSG(LTFSDMC0098E);
THROW(Error::GENERAL_ERROR);
}
const LTFSDmProtocol::LTFSDmStatusResp statusresp =
commCommand.statusresp();
if (statusresp.success() == true) {
pid = statusresp.pid();
MSG(LTFSDMC0097I, pid);
} else {
MSG(LTFSDMC0098E);
THROW(Error::GENERAL_ERROR);
}
}
void StartCommand::doCommand(int argc, char **argv)
{
if (argc > 1) {
printUsage();
THROW(Error::GENERAL_ERROR);
}
determineServerPath();
startServer();
waitForResponse();
}
| 30.465986 | 172 | 0.626772 | [
"shape"
] |
b4b40ea94dd43c13ca418138b636a59b9d67690f | 1,105 | cpp | C++ | practice/interviewPrepKit/dictionariesAndMaps/towPairs.cpp | Kiandr/dataStructure | 5cf8bd07df1c115cac9fcc69ae359500a72ad986 | [
"Apache-2.0"
] | null | null | null | practice/interviewPrepKit/dictionariesAndMaps/towPairs.cpp | Kiandr/dataStructure | 5cf8bd07df1c115cac9fcc69ae359500a72ad986 | [
"Apache-2.0"
] | null | null | null | practice/interviewPrepKit/dictionariesAndMaps/towPairs.cpp | Kiandr/dataStructure | 5cf8bd07df1c115cac9fcc69ae359500a72ad986 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <vector>
#include<map>
#include <utility>
#include <string>
bool aExistsInB(std::string prtToSubstring,char prtB){
for (int i=0;i<prtToSubstring.length();i++)
if (prtToSubstring[i]==prtB) return 1;
return 0;
}
char *twoPairs(std::string sA, std::string sB){
std::string prtToSubstring;
char *prtA =(char*) sA.c_str();
char *prtB = (char*) sB.c_str();
while (prtA != nullptr && *prtA!='\0'){
prtB =(char*) sB.c_str();
while (prtB != nullptr && *prtB!='\0'){
// std::cout<<"A= "<<*prtA<<" B= "<<*prtB<<std::endl;
if (tolower(*prtA)==tolower(*prtB)) {
if (!aExistsInB(prtToSubstring, tolower(*prtB)))
prtToSubstring+= tolower(*prtB);
}
prtB++;
}
prtA++;
}
return(char*) prtToSubstring.c_str();
}
int main(){
std::cout<<twoPairs("Hello", "world");
return 0;
}
| 26.95122 | 76 | 0.464253 | [
"vector"
] |
b4b5e5b17d3fa970129922941b08bcee5401a190 | 142,046 | cpp | C++ | deployment/deployutils/deployutils.cpp | emuharemagic/HPCC-Platform | bbd5423b25f6ba2d675521c8917f9ecfa97dace5 | [
"Apache-2.0"
] | 1 | 2020-08-01T19:54:56.000Z | 2020-08-01T19:54:56.000Z | deployment/deployutils/deployutils.cpp | emuharemagic/HPCC-Platform | bbd5423b25f6ba2d675521c8917f9ecfa97dace5 | [
"Apache-2.0"
] | null | null | null | deployment/deployutils/deployutils.cpp | emuharemagic/HPCC-Platform | bbd5423b25f6ba2d675521c8917f9ecfa97dace5 | [
"Apache-2.0"
] | null | null | null | /*##############################################################################
HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems.
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.
############################################################################## */
// DeployUtils.cpp : Defines the exported functions for the DLL application.
//
#include "deployutils.hpp"
#include "XMLTags.h"
#include "jliball.hpp"
#include "buildset.hpp"
#include "computerpicker.hpp"
#include "configenvhelper.hpp"
#include "configengcallback.hpp"
#include "xslprocessor.hpp"
#include "jwrapper.hpp"
#include "wizardInputs.hpp"
#include "build-config.h"
#include "confighelper.hpp"
#define TRACE_SCHEMA_NODE(msg, schemaNode)
#define CONFIGMGR_JSPATH "./"
#define STANDARD_COMPFILESDIR INSTALL_DIR
#define STANDARD_CONFIGXMLDIR COMPONENTFILES_DIR"/configxml"
static bool schemaNodeHasAttributes(IPropertyTree* pNode)
{
//skip over xs:complexType, if any
IPropertyTree* pTemp = pNode->queryPropTree(XSD_TAG_COMPLEX_TYPE);
if (pTemp)
pNode = pTemp;
Owned<IPropertyTreeIterator> itAttr = pNode->getElements(XSD_TAG_ATTRIBUTE);
return itAttr ->first() && itAttr ->isValid();
}
static bool schemaNodeHasAttributeGroups(IPropertyTree* pNode)
{
//skip over xs:complexType, if any
IPropertyTree* pTemp = pNode->queryPropTree(XSD_TAG_COMPLEX_TYPE);
if (pTemp)
pNode = pTemp;
Owned<IPropertyTreeIterator> itAttrGr = pNode->getElements(XSD_TAG_ATTRIBUTE_GROUP);
return itAttrGr->first() && itAttrGr->isValid();
}
bool writeToFile(const char* fileName, StringBuffer sb)
{
StringBuffer jsName(fileName);
recursiveCreateDirectoryForFile(fileName);
Owned<IFile> pFile = createIFile(jsName);
Owned<IFileIO> pFileIO = pFile->open(IFOcreaterw);
pFileIO->write(0, sb.length(), sb.str());
return true;
}
//check if this has any child elements - returns first element
IPropertyTree* schemaNodeHasElements(IPropertyTree* pNode)
{
//skip over xs:complexType, if any
IPropertyTree* pTemp = pNode->queryPropTree(XSD_TAG_COMPLEX_TYPE);
if (pTemp)
pNode = pTemp;
//skip over xs:sequence, if any
pTemp = pNode->queryPropTree(XSD_TAG_SEQUENCE);
if (pTemp)
pNode = pTemp;
else
{
pTemp = pNode->queryPropTree(XSD_TAG_CHOICE);
if (pTemp)
pNode = pTemp;
}
Owned<IPropertyTreeIterator> it = pNode->getElements(XSD_TAG_ELEMENT);
if (it->first() && it->isValid())
pTemp = &it->query();
else
pTemp = NULL;
return pTemp;
}
const char* getRealTabName(const char* tabName)
{
if (!strcmp(tabName, XML_TAG_INSTANCE))
return XML_TAG_INSTANCES;
else if (!strcmp(tabName, XML_TAG_DOMAIN))
return "Domains";
else if (!strcmp(tabName, TAG_COMPUTERTYPE))
return "Type";
else if (!strcmp(tabName, XML_TAG_COMPUTERTYPE))
return "Computer Types";
else if (!strcmp(tabName, XML_TAG_COMPUTER))
return "Computers";
else if (!strcmp(tabName, XML_TAG_SWITCH))
return "Switches";
else
return tabName;
}
//Gets the list of installed components by looking at the directories
void getInstalledComponents(const char* pszInstallDir, StringBuffer& sbOutComps, StringBuffer& sbOutEspServices, StringBuffer& sbOutPlugins, const IPropertyTree* pEnv)
{
StringBuffer sbDir;
sbOutComps.clear();
sbOutEspServices.clear();
sbOutPlugins.clear();
if (pszInstallDir && *pszInstallDir)
sbDir.append(pszInstallDir);
else
sbDir.append(COMPONENTFILES_DIR"/configxml");
bool getFromDirs = false;
if (getFromDirs)
{
Owned<IFile> inFiles = NULL;
try
{
inFiles.setown(createIFile(sbDir.str()));
if(!inFiles->exists())
{
printf("Input directory %s does not exist", sbDir.str());
return;
}
}
catch(IException* e)
{
StringBuffer errmsg;
e->errorMessage(errmsg);
printf("Error when trying to access source directory.Error: %s ", errmsg.str());
e->Release();
return;
}
if(inFiles.get() != NULL && inFiles->isDirectory())
{
Owned<IDirectoryIterator> di = inFiles->directoryFiles(NULL, 0, true);
bool bCompFound = false;
StringBuffer dirName, compName, fileName;
if(di.get())
{
ForEach(*di)
{
IFile &file = di->query();
if (!file.isFile())
{
dirName.clear();
di->getName(dirName);
compName.clear().append(dirName);
Owned<IFile> dirFiles = NULL;
dirName.clear().append(sbDir);
if(dirName.charAt(dirName.length() - 1) != PATHSEPCHAR)
dirName.append(PATHSEPCHAR);
dirName.append(compName);
fileName.clear().append(dirName).append(PATHSEPCHAR).append("deploy_map.xml");
Owned<IFile> depfile(createIFile(fileName));
if(depfile->exists())
{
Owned<IPropertyTree> pInstallSet = createPTreeFromXMLFile(fileName);
const char* szDeployable = pInstallSet->queryProp("@deployable");
const char* szProcessName = pInstallSet->queryProp("@processName");
if (!szDeployable || strcmp(szDeployable, "no"))
{
const char* szOveride = pInstallSet->queryProp("@overide");
if(!szOveride || strcmp(szOveride, "no") !=0 )
{
if (sbOutComps.length())
sbOutComps.append(",");
sbOutComps.append("'").append(compName).append("'");
}
}
else if (!strcmp(szProcessName, XML_TAG_ESPSERVICE))
{
if (sbOutEspServices.length())
sbOutEspServices.append(",");
sbOutEspServices.append("'").append(compName).append("'");
}
else if (!strcmp(szProcessName, XML_TAG_PLUGINPROCESS))
{
if (sbOutPlugins.length())
sbOutPlugins.append(",");
sbOutPlugins.append("'").append(compName).append("'");
}
}
else
{
if (!strcmp(compName.str(), "plugins"))
{
StringBuffer sb;
getInstalledComponents(dirName.str(), sb, sb, sbOutPlugins, pEnv);
}
}
}
}
}
}
}
else
{
Owned<IPropertyTreeIterator> iter = CConfigHelper::getInstance() != NULL ? CConfigHelper::getInstance()->getBuildSetTree()->getElements("Programs/Build[1]/*") : pEnv->getElements("Programs/Build[1]/*");
ForEach(*iter)
{
IPropertyTree* pBuildSet = &iter->query();
const char* szName = pBuildSet->queryProp(XML_ATTR_NAME);
const char* szProcessName = pBuildSet->queryProp(XML_ATTR_PROCESS_NAME);
if (szProcessName && !strcmp(szProcessName, XML_TAG_ESPSERVICE))
{
if (sbOutEspServices.length())
sbOutEspServices.append(",");
sbOutEspServices.append("'").append(szName).append("'");
}
else if (szProcessName && !strcmp(szProcessName, XML_TAG_PLUGINPROCESS))
{
if (sbOutPlugins.length())
sbOutPlugins.append(",");
sbOutPlugins.append("'").append(szName).append("'");
}
else
{
if (!szName || !*szName)
continue;
const char* szOveride = pBuildSet->queryProp("@overide");
if(!szOveride || strcmp(szOveride, "no") !=0 )
{
if (sbOutComps.length())
sbOutComps.append(",");
sbOutComps.append("'").append(szName).append("'");
}
}
}
}
}
void LoadComboBox(const char* szPath, bool bAddBlank, const IPropertyTree* pNode, const IPropertyTree* pParentNode, StringBuffer& sbComboBox, bool appendParentName = false, bool addDeclStart = true, bool addDeclEnd = true)
{
if (addDeclStart)
sbComboBox.append("new Array(");
if (bAddBlank)
sbComboBox.append("''");
const char* buildSet = NULL;
if (!strncmp(szPath, "$process", 8))
{
szPath += strlen("$process");
if (*szPath == '\0')
{
const char* szName = pNode->queryProp(XML_ATTR_NAME);
if (szName && *szName)
{
if (bAddBlank)
sbComboBox.append(",");
sbComboBox.appendf("'%s'", szName);
}
return;
}
szPath++; //skip over '/'
}
else
{
if (pParentNode && !strcmp(szPath, "Programs/Build"))
buildSet = pParentNode->queryProp(XML_ATTR_BUILDSET);
}
Owned<IPropertyTreeIterator> iter = pNode->getElements(szPath);
ForEach(*iter)
{
IPropertyTree* pChildNode = &iter->query();
const char* szName = pChildNode->queryProp(XML_ATTR_NAME);
if (szName)
{
bool bAdd;
if (buildSet)
{
StringBuffer xpath;
xpath.appendf("BuildSet[@name='%s']", buildSet);
bAdd = pChildNode->queryPropTree(xpath.str()) != NULL;
}
else
bAdd = true;
if (bAdd)
{
if (sbComboBox.length() > 10)
sbComboBox.append(",");
if (!appendParentName)
sbComboBox.appendf("'%s'", szName);
else
sbComboBox.appendf("'%s/%s'", pParentNode->queryProp(XML_ATTR_NAME), szName);
}
}
}
if (addDeclEnd)
sbComboBox.append(")");
}
void addItem(StringBuffer& jsStrBuf,
const IPropertyTree* pEnv,
const char* tabName,
const char* attrName,
const char* tip,
bool hidden,
bool required,
const char* extra,
short ctrlType)
{
StringBuffer sbAttr("Attributes");
jsStrBuf.appendf("var attr%s%s = {};", attrName, tabName);
jsStrBuf.appendf("attr%s%s.tab = '%s';", attrName, tabName, *tabName ? getRealTabName(tabName): sbAttr.str());
jsStrBuf.appendf("attr%s%s.tip = '%s';", attrName, tabName, tip);
jsStrBuf.appendf("attr%s%s.hidden = %d;", attrName, tabName, hidden);
jsStrBuf.appendf("attr%s%s.required = 1;", attrName, tabName);
jsStrBuf.appendf("attr%s%s.ctrlType = %d;", attrName, tabName, ctrlType);
jsStrBuf.appendf("cS['%s%s']=attr%s%s;", attrName, tabName, attrName, tabName);
StringBuffer sb;
if (ctrlType == 4)
{
if (extra[0] != '|')
LoadComboBox(extra, false, pEnv, pEnv, sb);
else
sb.append(++extra);
jsStrBuf.appendf("attr%s%s.extra = %s;", attrName, tabName, sb.str());
}
}
void addTopologyType(StringBuffer& jsStrBuf, const IPropertyTree* pEnv, const char* tabName, const char* attrName, const char* tip, bool hidden, bool required, const char* extra, short ctrlType)
{
jsStrBuf.appendf("var attr%s%s = {};", attrName, tabName);
jsStrBuf.appendf("attr%s%s.tab = '%s';", attrName, tabName, "Topology");
jsStrBuf.appendf("attr%s%s.tip = '%s';", attrName, tabName, tip);
jsStrBuf.appendf("attr%s%s.hidden = %d;", attrName, tabName, hidden);
jsStrBuf.appendf("attr%s%s.required = 1;", attrName, tabName);
jsStrBuf.appendf("attr%s%s.ctrlType = %d;", attrName, tabName, ctrlType);
jsStrBuf.appendf("cS['%s%s']=attr%s%s;", attrName, tabName, attrName, tabName);
StringBuffer sb;
if (!strcmp(attrName, TAG_BUILD))
{
sb.append("new Array(");
Owned<IPropertyTreeIterator> iBuild = pEnv->getElements("Programs/Build[@name]");
ForEach (*iBuild)
{
IPropertyTree* pBuild = &iBuild->query();
if (pBuild->queryPropTree("BuildSet[@name='topology']"))
{
const char* szName = pBuild->queryProp(XML_ATTR_NAME);
if (szName && *szName)
{
if (sb.length() > 10)
sb.append(",");
sb.appendf("'%s'", szName);
}
}
}
sb.append(")");
jsStrBuf.appendf("attr%s%s.extra = %s;", attrName, tabName, sb.str());
}
else if (ctrlType == 4)
{
if (extra[0] != '|')
LoadComboBox(extra, false, pEnv, pEnv, sb);
else
sb.append(++extra);
jsStrBuf.appendf("attr%s%s.extra = %s;", attrName, tabName, sb.str());
}
}
const char* GetDisplayProcessName(const char* processName, char* buf)
{
//produces "LDAPServerProcess" as "LDAP Server" and "EspService" as "Esp Service", etc.
const char* begin = buf;
const char* end = strstr(processName, "Process");
if (!end)
end = processName + strlen(processName);
*buf++ = *processName++;
bool bLower = false;
while (processName < end)
{
char ch = *processName;
if (isupper(ch))
{
if (bLower || //last char was uppercase or the following character is lowercase?
((processName+1 < end) && islower(*(processName+1))))
{
*buf++ = ' ';
}
bLower = false;
}
else
bLower = true;
*buf++ = *processName++;
}
*buf = '\0';
return begin;
}
void GetDisplayName(IPropertyTree* pNode, StringBuffer& sb, bool bAppendProcessName)
{
// Get the display name for the node
// Use szBuf because CString was too slow when loading a large tree
static char szBuf[128];
size32_t cnt = sizeof(szBuf);
GetDisplayProcessName(pNode->queryName(), szBuf);
const char* szName = pNode->queryProp(XML_ATTR_NAME);
if (!szName || !*szName)
szName = pNode->queryProp(XML_ATTR_PROCESS);
if (bAppendProcessName)
{
if (szName && *szName)
{
cnt -= strlen(szName);
strncat(szBuf, " - ", cnt);
strncat(szBuf, szName, cnt - 3);
}
sb.clear().append(szBuf);
}
else
sb.clear().append(szName);
}
class CGenerateJSFromXSD
{
public:
CGenerateJSFromXSD(const IPropertyTree* pEnv, const char* xsdName, const char* jsName):
m_xsdName(xsdName), m_jsName(jsName), m_pCompTree(NULL), m_pSchemaRoot(NULL),m_pDefTree(NULL),m_numAttrs(0),m_allSubTypes(true),m_genOptional(true)
{
m_pEnv.set(pEnv);
m_colIndex.append("var colIndex = new Array();");
m_columns.append("var tabCols = new Array();");
}
CGenerateJSFromXSD(const IPropertyTree* pEnv, IPropertyTree* pSchemaRoot, const char* jsName, const char* compName):
m_pSchemaRoot(pSchemaRoot), m_jsName(jsName), m_compName(compName),m_pCompTree(NULL), m_pDefTree(NULL),m_numAttrs(0),m_allSubTypes(true),m_wizFlag(false),m_wizard(NULL),m_genOptional(true)
{
m_pEnv.set(pEnv);
m_colIndex.append("var colIndex = new Array();");
m_columns.append("var tabCols = new Array();");
}
void setNameInCompTabArray(const char* tabName, const char* nodeName)
{
if (m_tabNameArray.find(tabName) == NotFound)
{
m_tabNameArray.append(tabName);
m_jsStrBuf.appendf("compTabs['%s'][compTabs['%s'].length]= '%s';", m_compName.str(), m_compName.str(), tabName);
if (nodeName && *nodeName)
m_jsStrBuf.appendf("compTabToNode['%s'] = '%s';", tabName, nodeName);
m_columns.appendf("tabCols['%s'] = new Array();", tabName);
}
}
void setNameInHiddenTabArray(const char* tabName)
{
if (m_hiddenTabNameArray.find(tabName) == NotFound)
{
m_hiddenTabNameArray.append(tabName);
m_jsStrBuf.appendf("hiddenTabs['%s'][hiddenTabs['%s'].length]= '%s';", m_compName.str(), m_compName.str(), tabName);
}
}
void addRoxieMisc(StringBuffer& jsStrBuf)
{
addItem(jsStrBuf, m_pEnv.get(), XML_TAG_ROXIE_SERVER, TAG_COMPUTER, "", 0, 1, "", 0);
addItem(jsStrBuf, m_pEnv.get(), XML_TAG_ROXIE_SERVER, TAG_PROCESS, "", 0, 1, "", 0);
addItem(jsStrBuf, m_pEnv.get(), XML_TAG_ROXIE_FARM, TAG_NAME, "", 0, 1, "", 0);
addItem(jsStrBuf, m_pEnv.get(), XML_TAG_ROXIE_FARM, TAG_PROCESS, "", 0, 1, "", 0);
addItem(jsStrBuf, m_pEnv.get(), XML_TAG_ROXIE_FARM, TAG_LISTENQUEUE, "", 0, 1, "", 1);
addItem(jsStrBuf, m_pEnv.get(), XML_TAG_ROXIE_FARM, TAG_NUMTHREADS, "", 0, 1, "", 1);
addItem(jsStrBuf, m_pEnv.get(), XML_TAG_ROXIE_FARM, TAG_PORT, "", 0, 1, "", 1);
addItem(jsStrBuf, m_pEnv.get(), XML_TAG_ROXIE_FARM, TAG_REQARRAYTHREADS, "", 0, 1, "", 1);
addItem(jsStrBuf, m_pEnv.get(), XML_TAG_ROXIE_FARM, "aclName", "", 0, 1, "|'#$process/ACL'", 4);
addItem(jsStrBuf, m_pEnv.get(), XML_TAG_ROXIE_ONLY_SLAVE, TAG_NAME, "", 0, 1, "", 0);
addItem(jsStrBuf, m_pEnv.get(), XML_TAG_ROXIE_ONLY_SLAVE, TAG_COMPUTER, "", 0, 1, "", 0);
addItem(jsStrBuf, m_pEnv.get(), XML_TAG_ROXIE_ONLY_SLAVE, TAG_NETADDRESS, "", 0, 1, "", 0);
addItem(jsStrBuf, m_pEnv.get(), XML_TAG_ROXIE_ONLY_SLAVE, TAG_ITEMTYPE, "", 0, 1, "", 0);
addItem(jsStrBuf, m_pEnv.get(), XML_TAG_ROXIE_CHANNEL, TAG_NAME, "", 0, 1, "", 0);
addItem(jsStrBuf, m_pEnv.get(), XML_TAG_ROXIE_CHANNEL, TAG_ITEMTYPE, "", 0, 1, "", 0);
addItem(jsStrBuf, m_pEnv.get(), XML_TAG_ROXIE_CHANNEL, TAG_COMPUTER, "", 0, 1, "", 0);
addItem(jsStrBuf, m_pEnv.get(), XML_TAG_ROXIE_CHANNEL, TAG_NUMBER, "", 0, 1, "", 0);
}
void addMisc()
{
if (!strcmp(m_compName.str(), "RoxieCluster"))
{
addRoxieMisc(m_jsStrBuf);
const char* serverStr = "Servers";
short index = 0;
m_colIndex.appendf("colIndex['computer%s']=%d;", serverStr, index++);
m_colIndex.appendf("colIndex['process%s']=%d;", serverStr, index++);
m_colIndex.appendf("colIndex['netAddress%s']=%d;", serverStr, index++);
m_colIndex.appendf("colIndex['port%s']=%d;", serverStr, index++);
m_colIndex.appendf("colIndex['listenQueue%s']=%d;", serverStr, index++);
m_colIndex.appendf("colIndex['numThreads%s']=%d;", serverStr, index++);
m_colIndex.appendf("colIndex['requestArrayThreads%s']=%d;", serverStr, index++);
m_colIndex.appendf("colIndex['aclName%s']=%d;", serverStr, index++);
index = 0;
const char* agentStr = "Agents";
m_colIndex.appendf("colIndex['computer%s']=%d;", agentStr, index++);
m_colIndex.appendf("colIndex['netAddress%s']=%d;", agentStr, index++);
}
else if (!strcmp(m_compName.str(), XML_TAG_THORCLUSTER))
{
short index = 0;
m_jsStrBuf.append("compTabs['ThorCluster'][compTabs['ThorCluster'].length]= 'Topology';");
m_colIndex.appendf("colIndex['nameTopology']=%d;", index++);
m_colIndex.appendf("colIndex['processTopology']=%d;", index++);
m_colIndex.appendf("colIndex['netAddressTopology']=%d;", index++);
m_jsStrBuf.append("compTabToNode['Topology']= 'Topology';");
}
}
void CreateAttributeFromSchema(IPropertyTree& attr, StringBuffer compName, const char* tabName, const char* childElementName)
{
StringBuffer attrname;
StringBuffer combovalues;
StringBuffer strBuf;
StringBuffer aName;
StringBuffer value, tempPath, wizDefVal;
attrname.append(attr.queryProp(XML_ATTR_NAME));
const char *use = attr.queryProp("@use");
if (!m_genOptional && use && *use && !strcmp(use, "optional"))
{
if(childElementName)
{
StringBuffer xpath;
xpath.clear().append(childElementName);
IPropertyTree* pChild = m_pCompTree->queryPropTree(xpath.str());
if(!pChild)
pChild = m_pCompTree->addPropTree(childElementName, createPTree());
}
return;
}
if(m_wizFlag)
{
if(attr.hasProp("./xs:annotation/xs:appinfo/autogenforwizard"))
{
value.clear().append(attr.queryProp("./xs:annotation/xs:appinfo/autogenforwizard"));
if(!strcmp(value.str(),"1"))
{
getValueForTypeInXSD(attr, compName, wizDefVal);
}
}
else
return ;
}
if (childElementName)
attrname.append(childElementName);
aName.appendf("a%d", m_numAttrs++);
m_jsStrBuf.appendf("var %s = {};", aName.str());
m_jsStrBuf.appendf("%s.tab = '%s';", aName.str(), getRealTabName(tabName));
setNameInCompTabArray(getRealTabName(tabName), childElementName);
IPropertyTree* pField = NULL;
if (m_pDefTree)
{
IPropertyTree* pProcess = m_pDefTree->queryPropTree(compName.str());
if (!pProcess)
pProcess = m_pDefTree->addPropTree(compName, createPTree());
IPropertyTree* pTab = m_pDefTree->queryPropTree(getRealTabName(tabName));
if (!pTab)
pTab = pProcess->addPropTree(getRealTabName(tabName), createPTree());
pField = pTab->addPropTree("Field", createPTree());
}
const char *defaultValue = attr.queryProp("@default");
StringBuffer sbdefaultValue;
if (defaultValue)
{
sbdefaultValue.clear().append(defaultValue);
sbdefaultValue.replaceString("\\", "\\\\");
m_jsStrBuf.appendf("%s.defaultValue = '%s';", aName.str(), sbdefaultValue.str());
if (pField)
pField->addProp(UI_FIELD_ATTR_DEFAULTVALUE, sbdefaultValue.str());
}
if(wizDefVal.length() > 0)
{
sbdefaultValue.clear().append(wizDefVal);
if (pField)
pField->addProp(UI_FIELD_ATTR_DEFAULTVALUE, sbdefaultValue.str());
}
if (m_pCompTree)
{
StringBuffer xpath;
if(!childElementName)
{
xpath.clear().append("@").append(attrname);
m_pCompTree->addProp(xpath, sbdefaultValue.str());
}
else
{
xpath.clear().append(childElementName);
IPropertyTree* pChild = m_pCompTree->queryPropTree(xpath.str());
if(!pChild)
pChild = m_pCompTree->addPropTree(childElementName, createPTree());
xpath.clear().append("@").append(attr.queryProp(XML_ATTR_NAME));
pChild->addProp(xpath, sbdefaultValue.str());
}
}
IPropertyTree* pAppInfo = attr.queryPropTree("xs:annotation/xs:appinfo");
const char *viewtype;
const char *displayMode = NULL;
if (pAppInfo)
{
const char* caption = pAppInfo->queryProp("title");
if (caption)
m_jsStrBuf.appendf("%s.caption = '%s';", aName.str(), caption);
const char* tip = pAppInfo->queryProp("tooltip");
if (tip)
{
StringBuffer sbtip(tip);
sbtip.replaceString("\"", "\\\"");
sbtip.replaceString("\'", "\\\'");
m_jsStrBuf.appendf("%s.tip = '%s';", aName.str(), sbtip.str());
}
m_jsStrBuf.appendf("%s.width = %d;", aName.str(), pAppInfo->getPropInt("width", 90));
viewtype = pAppInfo->queryProp("viewType");
m_jsStrBuf.appendf("%s.hidden = %d;", aName.str(), viewtype && !strcmp(viewtype, "hidden"));
displayMode = pAppInfo->queryProp("displayMode");
m_jsStrBuf.appendf("%s.displayMode = %d;", aName.str(), displayMode && !strcmp(displayMode, "simple"));
const char* colIndex = pAppInfo->queryProp("colIndex");
if (colIndex && *colIndex)
{
int i = atoi(colIndex);
m_colIndex.appendf("colIndex['%s%s'] = %d;", attr.queryProp(XML_ATTR_NAME),getRealTabName(tabName), i - 1);
if (!viewtype || (viewtype && strcmp(viewtype, "hidden")))
{
m_columns.appendf("tabCols['%s'][%d] = '%s';", getRealTabName(tabName), i - 1, caption? caption:attr.queryProp(XML_ATTR_NAME));
if (childElementName && i == 1 && m_splitterTabName.length())
{
setNameInCompTabArray(m_splitterTabName, compName.str());
m_columns.appendf("tabCols['%s'][%d] = '_%s';", m_splitterTabName.str(), m_numAttrs, tabName);
}
}
}
else if (childElementName && m_splitterTabName.length())
{
m_colIndex.appendf("colIndex['%s%s'] = %d;", attr.queryProp(XML_ATTR_NAME),getRealTabName(tabName), 0);
if (!viewtype || (viewtype && strcmp(viewtype, "hidden")))
{
m_columns.appendf("tabCols['%s'][%d] = '%s';", getRealTabName(tabName), 0, caption? caption:attr.queryProp(XML_ATTR_NAME));
setNameInCompTabArray(m_splitterTabName, compName.str());
m_columns.appendf("tabCols['%s'][%d] = '_%s';", m_splitterTabName.str(), m_numAttrs, tabName);
}
}
IPropertyTree* onChangeNode = pAppInfo->queryPropTree("onchange");
if (onChangeNode)
{
const char* msg = onChangeNode->queryProp("message");
if (msg && *msg)
{
StringBuffer sbmsg(msg);
sbmsg.replace('\n',' ');
sbmsg.replaceString(" ", " ");
m_jsStrBuf.appendf("%s.onChange = 1;", aName.str());
m_jsStrBuf.appendf("%s.onChangeMsg = '%s';", aName.str(), sbmsg.str());
}
const char* onChangeXslt = onChangeNode->queryProp("xslt");
if (onChangeXslt)
m_jsStrBuf.appendf("%s.onChange = 2;", aName.str());
}
else
m_jsStrBuf.appendf("%s.onChange = %d;", aName.str(), onChangeNode != NULL);
}
else
{
viewtype = NULL;
}
StringBuffer xpath(m_xpathDefn);
xpath.appendf("[@%s]", attr.queryProp(XML_ATTR_NAME));
if (viewtype)
{
if (pField)
{
pField->addProp(attr.queryProp(XML_ATTR_NAME), m_pEnv->queryProp(xpath.str()));
}
}
else
{
if (pField)
{
pField->addProp(UI_FIELD_ATTR_NAME, attr.queryProp(XML_ATTR_NAME));
pField->addProp(UI_FIELD_ATTR_NAME"Type", "0");
pField->addProp(UI_FIELD_ATTR_VALUE, m_pEnv->queryProp(xpath.str()));
}
}
m_jsStrBuf.appendf("%s.required = %d;", aName.str(), (use && strcmp(use, "required")==0) || (pAppInfo && pAppInfo->getPropBool("required")));
m_jsStrBuf.appendf("%s.loadRoot = %d;", aName.str(),1);
const char *type = attr.queryProp("@type");
const char *extraInfo = NULL;
bool bAddBlank = false;
StringBuffer typeNameSpace;
StringBuffer typeName;
int nCtrlType = 1;//LVC_EDIT;
if (viewtype && !strcmp(viewtype, "readonly"))
nCtrlType = 0;//LVC_NONE;
else if (viewtype && !strcmp(viewtype, TAG_PASSWORD))
nCtrlType = 5;//LVC_EDITPASSWORD;
else if (type)
{
while (*type && *type!=':')
typeNameSpace.append(*type++);
if (*type)
{
type++;
while (*type)
typeName.append(*type++);
}
else
{
typeName.append(typeNameSpace);
typeNameSpace.clear();
}
type = typeName.str();
if (strcmp(typeNameSpace.str(),"xs")==0)
{
if (strcmp(type, "string")==0)
nCtrlType = 1;//LVC_EDIT;
else if (strcmp(type, "boolean")==0)
{
nCtrlType = 4;//ret->m_bRequired ? LVC_TRUEFALSE : LVC_TRUEFALSE2;
strBuf.clear().append("new Array('false','true');");
extraInfo = strBuf.str();
}
}
else if (strcmp(typeNameSpace.str(),"seisint")==0 || typeNameSpace.length()==0)
{
bAddBlank = !((use && strcmp(use, "required")==0) || (pAppInfo && pAppInfo->getPropBool("required")));
if (strcmp(type, "commonDirsCompType")==0)
{
nCtrlType = 4;//LVC_COMBO;
StringBuffer compList, espServiceList, pluginsList;
getInstalledComponents(NULL, compList, espServiceList, pluginsList, m_pEnv.get());
strBuf.clear().append("new Array(").append(compList).append(");");
extraInfo = strBuf.str();
}
else if (strcmp(type, "commonDirsInstType")==0)
{
nCtrlType = 4;//LVC_COMBO;
strBuf.clear().append("new Array('');");
extraInfo = strBuf.str();
}
else if (strcmp(type, "daliServersType")==0)
{
nCtrlType = 4;//LVC_COMBO;
LoadComboBox("Software/DaliServerProcess", bAddBlank, m_pEnv, m_pEnv, strBuf);
extraInfo = strBuf.str();
}
else if (strcmp(type, "dataBuildType")==0)
{
nCtrlType = 4;//LVC_COMBO;
LoadComboBox("Data/Build", bAddBlank, m_pEnv, m_pEnv, strBuf);
extraInfo = strBuf.str();
}
else if (strcmp(type, "dataModelType")==0)
{
nCtrlType = 4;//LVC_COMBO;
LoadComboBox("Data/Model", bAddBlank, m_pEnv, m_pEnv, strBuf);
extraInfo = strBuf.str();
}
else if (strcmp(type, "dataThorTableType")==0)
{
nCtrlType = 4;//LVC_COMBO;
LoadComboBox("Data/$model/ThorTable", bAddBlank, m_pEnv, m_pEnv, strBuf);
extraInfo = strBuf.str();
}
else if (strcmp(type, "dataTableType")==0)
{
nCtrlType = 4;//LVC_COMBO;
LoadComboBox("Data/$parentmodel/*", bAddBlank, m_pEnv, m_pEnv, strBuf);
extraInfo = strBuf.str();
}
else if (strcmp(type, "sybaseType")==0)
{
nCtrlType = 4;//LVC_COMBO;
bAddBlank = true;
LoadComboBox("Software/SybaseProcess", bAddBlank, m_pEnv, m_pEnv, strBuf);
extraInfo = strBuf.str();
//ret->m_bAddEmpty = true;
}
else if (strcmp(type, "mysqlType")==0)
{
nCtrlType = 4;//LVC_COMBO;
bAddBlank = true;
LoadComboBox("Software/MySQLProcess", bAddBlank, m_pEnv, m_pEnv, strBuf);
extraInfo = strBuf.str();
//ret->m_bAddEmpty = true;
}
else if (strcmp(type, "ldapServerType")==0)
{
nCtrlType = 4;//LVC_COMBO;
LoadComboBox("Software/LDAPServerProcess", bAddBlank, m_pEnv, m_pEnv, strBuf);
extraInfo = strBuf.str();
}
else if (strcmp(type, "sashaServerType")==0)
{
nCtrlType = 4;//LVC_COMBO;
LoadComboBox("Software/SashaServerProcess", bAddBlank, m_pEnv, m_pEnv, strBuf);
extraInfo = strBuf.str();
}
else if (strcmp(type, "accurintServerType")==0)
{
nCtrlType = 4;//LVC_COMBO;
LoadComboBox("Software/AccurintServerProcess", bAddBlank, m_pEnv, m_pEnv, strBuf);
extraInfo = strBuf.str();
}
else if (strcmp(type, "buildSetType")==0)
{
nCtrlType = 4;//LVC_COMBO;
extraInfo = "Programs/Build[@name=$build]/BuildSet";
}
else if (strcmp(type, "buildType")==0)
{
nCtrlType = 4;//LVC_COMBO;
LoadComboBox("Programs/Build", bAddBlank, m_pEnv, m_pEnv, strBuf);
extraInfo = strBuf.str();//"Programs/Build";
}
else if (strcmp(type, TAG_COMPUTERTYPE)==0)
{
nCtrlType = 4;//LVC_COMBO;
LoadComboBox("Hardware/Computer", bAddBlank, m_pEnv, m_pEnv, strBuf);
extraInfo = strBuf.str();
}
else if (strcmp(type, "dataBuildType")==0)
{
nCtrlType = 4;//LVC_COMBO;
LoadComboBox("Data/Build", bAddBlank, m_pEnv, m_pEnv, strBuf);
extraInfo = strBuf.str();
}
else if (strcmp(type, "dataModelType")==0)
{
nCtrlType = 4;//LVC_COMBO;
LoadComboBox("Data/Model", bAddBlank, m_pEnv, m_pEnv, strBuf);
extraInfo = strBuf.str();
}
else if (strcmp(type, "espServiceType")==0)
{
nCtrlType = 4;//LVC_COMBO;
LoadComboBox("Software/EspService", bAddBlank, m_pEnv, m_pEnv, strBuf);
extraInfo = strBuf.str();
}
else if (strcmp(type, "espProcessType")==0)
{
nCtrlType = 4;//LVC_COMBO;
LoadComboBox("Software/EspProcess", bAddBlank, m_pEnv, m_pEnv, strBuf);
extraInfo = strBuf.str();
}
else if (strcmp(type, "roxieClusterType")==0)
{
nCtrlType = 4;//LVC_COMBO;
LoadComboBox("Software/RoxieCluster", bAddBlank, m_pEnv, m_pEnv, strBuf);
extraInfo = strBuf.str();
}
else if (strcmp(type, "eclServerType")==0)
{
// MORE - attribute servers would be ok here too
nCtrlType = 4;//LVC_COMBO;
LoadComboBox("Software/EclServerProcess", bAddBlank, m_pEnv, m_pEnv, strBuf);
extraInfo = strBuf.str();
}
else if (strcmp(type, "eclCCServerType")==0)
{
nCtrlType = 4;//LVC_COMBO;
LoadComboBox("Software/EclCCServerProcess", bAddBlank, m_pEnv, m_pEnv, strBuf);
extraInfo = strBuf.str();
}
else if (strcmp(type, "wsLogListenerType")==0)
{
nCtrlType = 4;//LVC_COMBO;
LoadComboBox("Software/WsLogListener", bAddBlank, m_pEnv, m_pEnv, strBuf);
extraInfo = strBuf.str();
}
else if (strcmp(type, "processType")==0)
{
nCtrlType = 4;//LVC_COMBO;
LoadComboBox(pAppInfo->queryProp(TAG_NAME), bAddBlank, m_pEnv, m_pEnv, strBuf);
extraInfo = strBuf.str();
}
else if (strcmp(type, "topologyClusterType")==0)
{
nCtrlType = 4;//LVC_COMBO;
LoadComboBox("Software/Topology/Cluster", bAddBlank, m_pEnv, m_pEnv, strBuf);
extraInfo = strBuf.str();
}
else if (strcmp(type, "xpathType")==0)
{
const char* xpath1 = pAppInfo->queryProp("xpath");
const char* xpath2;
if (xpath1 && *xpath1)
{
nCtrlType = 4;//LVC_COMBO;
const char* prefix = "/Environment/";
const int len = strlen(prefix);
if (!strncmp(xpath1, prefix, len)) //xpath is absolute
xpath2 = xpath1 + len; //IPropertyTree root does not take absolute paths
else
xpath2 = xpath1;
if (!strstr(xpath2, "$"))
LoadComboBox(xpath2, bAddBlank, m_pEnv, m_pEnv, strBuf);
else
strBuf.append("#").append(xpath2);
extraInfo = strBuf.str();
}
}
else if (strcmp(type, "espBindingType")==0)
{
nCtrlType = 4;//LVC_COMBO;
m_jsStrBuf.appendf("%s.custom = %d;", aName.str(), 1);
const char* serviceType = NULL;
if (pAppInfo)
{
serviceType = pAppInfo->queryProp("serviceType");
if (serviceType)
xpath.clear().append("Software/EspService");
}
else
xpath.clear().appendf("Software/*[@buildSet='%s']", type);
strBuf.clear();
Owned<IPropertyTreeIterator> iterEspServices = m_pEnv->getElements(xpath);
short blank = 0;
ForEach (*iterEspServices)
{
IPropertyTree* pEspService = &iterEspServices->query();
if (serviceType)
{
xpath.clear().appendf("Properties[@type='%s']", serviceType);
if (pEspService->queryPropTree(xpath.str()) == NULL)
continue;
}
Owned<IPropertyTreeIterator> iter = m_pEnv->getElements("Software/EspProcess");
ForEach (*iter)
{
IPropertyTree* pEspProcess = &iter->query();
xpath.clear().appendf("EspBinding[@service='%s']", pEspService->queryProp(XML_ATTR_NAME));
if (pEspProcess->queryPropTree(xpath.str()) != NULL)
LoadComboBox(xpath.str(), (blank == 0), pEspProcess, pEspProcess, strBuf, true, (blank == 0), false);
blank++;
}
}
strBuf.append(")");
extraInfo = strBuf.str();
}
else if (strcmp(type, "AutoTimeStampType")==0 ||
strcmp(type, "AutoComputerType")==0 ||
strcmp(type, "AutoUseridType")==0)
{
if (nCtrlType != 0/*LVC_NONE*/)//is not read only
nCtrlType = 1;//LVC_EDIT;
m_jsStrBuf.appendf("%s.custom = %d;", aName.str(), 1);
m_jsStrBuf.appendf("%s.extra = '%s';", aName.str(), type);
}
else if (strcmp(type, "absolutePath")==0 || strcmp(type, "relativePath")==0)
{
nCtrlType = 1;//LVC_EDIT;
extraInfo = type;
}
else if (strcmp(type, "YesNo")==0)
{
nCtrlType = 4;//ret->m_bRequired ? LVC_YESNO : LVC_YESNO_OPTIONAL;
strBuf.clear().append("new Array('No','Yes');");
extraInfo = strBuf.str();
}
}
else if (strcmp(typeNameSpace.str(),TAG_PROCESS)==0) //for backwards compatibility only - use xpathType instead
{
nCtrlType = 4;//LVC_COMBO;
m_jsStrBuf.appendf("%s.extra = '%s%s';", aName.str(), "Software/", typeName.str());
}
// MORE - type could be a reference to a simpletype defined elsewhere....
}
else if (attr.hasProp("xs:simpleType/xs:restriction/xs:enumeration"))
{
Owned<IPropertyTreeIterator> values = attr.getElements("xs:simpleType/xs:restriction/xs:enumeration");
combovalues.append("new Array(");
ForEach(*values)
{
IPropertyTree &value = values->query();
if (combovalues.length() > 10)
combovalues.append(",");
combovalues.append("'").append(value.queryProp("@value")).append("'");
}
combovalues.append(")");
nCtrlType = 4;//LVC_COMBO;
extraInfo = combovalues.str();
}
if (extraInfo)
{
if (!strncmp(extraInfo, "new Array", 9))
{
m_jsStrBuf.appendf("%s.extra = %s;", aName.str(), extraInfo);
if (pField)
{
//["Alabama","Alaska","Arizona","Arkansas"]
StringBuffer sb(extraInfo);
sb.replaceString("new Array(", "[");
sb.replaceString(");", "]");
StringBuffer sbAttr("@");
sbAttr.append(attr.queryProp(XML_ATTR_NAME));
if (viewtype)
pField->addProp(sbAttr.append("_extraInfo"), sb.str());
else
pField->addProp(UI_FIELD_ATTR_VALUE"_extra", sb.str());
}
}
else
m_jsStrBuf.appendf("%s.extra = '%s';", aName.str(), extraInfo);
}
m_jsStrBuf.appendf("%s.ctrlType = %d;", aName.str(), nCtrlType);
m_jsStrBuf.appendf("cS['%s']=%s;", attrname.str(), aName.str());
}
void AddAttributeFromSchema(IPropertyTree& schemaNode,
StringBuffer elemName,
StringBuffer& compName,
const char* tabName,
const char* childElementName)
{
CreateAttributeFromSchema(schemaNode, compName, tabName, childElementName);
}
void AddAttributesFromSchema(IPropertyTree* pSchema,
StringBuffer& compName,
const char* tabName,
const char* childElementName)
{
if (pSchema)
{
//add attributes defined for this element
Owned<IPropertyTreeIterator> attrIter = pSchema->getElements("xs:complexType/xs:attribute");
ForEach(*attrIter)
{
AddAttributeFromSchema(attrIter->query(), "", compName, tabName, childElementName);
}
if (childElementName && !strcmp(childElementName, XML_TAG_INSTANCE))
{
const char* pszNameAttr = "<xs:attribute name='name' type='xs:string' use='optional'><xs:annotation><xs:appinfo><viewType>hidden</viewType></xs:appinfo></xs:annotation></xs:attribute>";
Owned<IPropertyTree> pSchemaAttrNode = createPTreeFromXMLString(pszNameAttr);
AddAttributeFromSchema(*pSchemaAttrNode, "", compName, tabName, childElementName);
}
// or if it's an attribute group, then try this variety...
attrIter.setown(pSchema->getElements("xs:attribute"));
ForEach(*attrIter)
{
AddAttributeFromSchema(attrIter->query(), "", compName, tabName, childElementName);
}
Owned<IPropertyTreeIterator> simple = pSchema->getElements("*");
ForEach(*simple)
{
IPropertyTree &element = simple->query();
const char* pszElementName = element.queryName();
if (!strcmp(pszElementName, "xs:complexContent"))
AddAttributesFromSchema(&element, compName, tabName, NULL);
}
}
}
void ProcessElementSchemaNode(IPropertyTree* pElement,
IPropertyTree* pParentElement,
StringBuffer& sbCompName)
{
bool bOptSubType = false;
if (pElement)
{
TRACE_SCHEMA_NODE("ProcessElementSchemaNode", pElement);
const char* szParentElementName = pParentElement->queryProp(XML_ATTR_NAME);
const char* szElementName = pElement->queryProp(XML_ATTR_NAME);
const char* szCaption = szElementName;
const char* tabName = pElement->queryProp("xs:annotation/xs:appinfo/title");
if (tabName)
szCaption = tabName;
IPropertyTree* pViewSchemaNode = pElement; //default for child view
IPropertyTree* pInstanceNode = pParentElement;//default for child view
bool bInstanceView = false;
bool bViewChildNodes = true;
if (pElement->hasProp("xs:annotation/xs:appinfo/viewType"))
{
const char* viewType = pElement->queryProp("xs:annotation/xs:appinfo/viewType");
const char* viewChildNodes = pElement->queryProp("xs:annotation/xs:appinfo/viewChildNodes");
bViewChildNodes = viewChildNodes && !stricmp(viewChildNodes, "true");
bool needParent = true;
//select first parent node that matches schema
if (pInstanceNode && needParent)
{
Owned<IPropertyTreeIterator> it = pInstanceNode->getElements(szElementName);
if (it->first() && it->isValid())
pInstanceNode = &it->query();
}
if (!strcmp(viewType, "list"))
{
const char* title = pElement->queryProp("xs:annotation/xs:appinfo/title");
setNameInHiddenTabArray(title? title : szElementName);
bOptSubType = true;
}
if (!strcmp(viewType, "Instance") || !strcmp(viewType, "instance") ||
!strcmp(viewType, "RoxiePorts") || !strcmp(viewType, "RoxieSlaves"))
bOptSubType = true;
}
bool bHasElements = schemaNodeHasElements(pElement) != NULL;
if (bViewChildNodes)
{
bool bHasAttribs = schemaNodeHasAttributes(pElement);
bool bHasAttribGroups = schemaNodeHasAttributeGroups(pElement);
bool bMaxOccursOnce = !pElement->hasProp(XML_ATTR_MAXOCCURS) || !strcmp(pElement->queryProp(XML_ATTR_MAXOCCURS), "1");
bOptSubType = !bMaxOccursOnce;
//figure out the type of child view to create
if (bHasElements)
{
// MORE - this assumes there is only one nested element type and that it is repeated....
StringBuffer sbElemName(szElementName);
if (bHasAttribs) //has child elements and attributes
{
Owned<IPropertyTreeIterator> iter = pElement->getElements("*");
ForEach(*iter)
{
IPropertyTree &subSchemaElement = iter->query();
const char* szSubElementName = subSchemaElement.queryName();
StringBuffer sbSubElemName(szSubElementName);
TRACE_SCHEMA_NODE("ProcessSchemaElement", &subSchemaElement);
m_splitterTabName.clear().append(getRealTabName(szCaption));
if (m_allSubTypes || !bOptSubType)
ProcessComplexTypeSchemaNode(&subSchemaElement, m_pSchemaRoot, sbElemName);
m_splitterTabName.clear();
}
}
else
{
//no attributes
if (bMaxOccursOnce)
{
//has child elements but no attribs and only occurs once
//so skip this element and create node list view for its children
pViewSchemaNode = schemaNodeHasElements(pElement);
if (pInstanceNode)
{
IPropertyTree* pNewInstanceNode = pInstanceNode->queryPropTree(szElementName);
if (!pNewInstanceNode)
pNewInstanceNode = pInstanceNode->addPropTree(szElementName, createPTree());
pInstanceNode = pNewInstanceNode;
}
szElementName = pViewSchemaNode->queryProp(XML_ATTR_NAME);
}
}
}
else
{
//no child elements
if (bHasAttribs)
{
if (!bMaxOccursOnce) //occurs multiple times
{
//select first parent node that matches schema
if (pInstanceNode)
{
Owned<IPropertyTreeIterator> it = pInstanceNode->getElements(szParentElementName);
if (it->first() && it->isValid())
pInstanceNode = &it->query();
}
}
}
else
{
const char* type = pElement->queryProp("@type");
if (type && !strcmp(type, "xs:string"))
{
m_jsStrBuf.appendf("var attr%s%s = {};", szElementName, sbCompName.str());
m_jsStrBuf.appendf("attr%s%s.tab = '%s';", szElementName, sbCompName.str(), getRealTabName(szElementName));
m_jsStrBuf.appendf("attr%s%s.hidden = 0;", szElementName, sbCompName.str());
m_jsStrBuf.appendf("attr%s%s.required = 1;", szElementName, sbCompName.str());
m_jsStrBuf.appendf("attr%s%s.ctrlType = %d;", szElementName, sbCompName.str(), 6);
m_jsStrBuf.appendf("cS['%s%s']=attr%s%s;", szElementName, sbCompName.str(), szElementName, sbCompName.str());
//add additional entry for this special case where element value is shown as a column
m_jsStrBuf.appendf("cS['%s%s']=attr%s%s;", szElementName, szElementName, szElementName, sbCompName.str());
setNameInCompTabArray(m_splitterTabName, sbCompName.str());
m_columns.appendf("tabCols['%s'][%d] = '_%s';", m_splitterTabName.str(), m_numAttrs++, szElementName);
setNameInCompTabArray(szElementName, szElementName);
setNameInHiddenTabArray(szElementName);
m_columns.appendf("tabCols['%s'][%d] = '%s';", szElementName, 0, szElementName);
if (m_pCompTree)
{
StringBuffer sb(sbCompName);
if (!m_pCompTree->queryPropTree(sbCompName.str()))
m_pCompTree->addPropTree(sbCompName.str(), createPTree());
sb.append("/").append(szElementName);
m_pCompTree->addPropTree(sb.str()/*szElementName*/, createPTree());
}
}
}
}
}
if (m_allSubTypes || !bOptSubType)
AddAttributesFromSchema(pViewSchemaNode, sbCompName, szCaption, szElementName);
if (bOptSubType && m_viewChildNodes.get() && m_multiRowNodes.get())
{
if (bHasElements)
m_viewChildNodes->addProp("Node", szElementName);
else
m_multiRowNodes->addProp("Node", szElementName);
}
if (pInstanceNode)
{
//select first child node for which we are creating view
Owned<IPropertyTreeIterator> it = pInstanceNode->getElements(pElement->queryProp(XML_ATTR_NAME));
pInstanceNode = (it->first() && it->isValid()) ? &it->query() : NULL;
}
}
}
void ProcessComplexTypeSchemaNode(IPropertyTree* schemaNode,
IPropertyTree* pParentElement,
StringBuffer& sbCompName)
{
if (schemaNode)
{
TRACE_SCHEMA_NODE("ProcessComplexTypeSchemaNode", schemaNode);
const char* szParentElementName = pParentElement->queryProp(XML_ATTR_NAME);
//now process the rest...
Owned<IPropertyTreeIterator> iter = schemaNode->getElements(XSD_TAG_ATTRIBUTE_GROUP);
ForEach(*iter)
{
IPropertyTree &schemaElement = iter->query();
const char* name = schemaElement.queryProp("@ref");
StringBuffer xPath;
xPath.append("//xs:attributeGroup[@name='").append(name).append("']");
Owned<IPropertyTreeIterator> iter2 = m_pSchemaRoot->getElements(xPath.str());
ForEach(*iter2)
{
IPropertyTree &agDef = iter2->query();
if (agDef.hasProp("xs:annotation/xs:appinfo/title"))
name = agDef.queryProp("xs:annotation/xs:appinfo/title");
AddAttributesFromSchema(&agDef, sbCompName, name, NULL);
break; // should be exactly one!
// MORE - this will not get scoping correct. Do I care?
}
}
iter.setown(schemaNode->getElements("*"));
ForEach(*iter)
{
IPropertyTree &schemaElement = iter->query();
const char* szSchemaElementName = schemaElement.queryName();
if (!strcmp(szSchemaElementName, XSD_TAG_SEQUENCE) || !strcmp(szSchemaElementName, XSD_TAG_CHOICE))
{
Owned<IPropertyTreeIterator> iter2 = schemaElement.getElements(XSD_TAG_ELEMENT);
ForEach(*iter2)
{
IPropertyTree* pElement = &iter2->query();
ProcessElementSchemaNode(pElement, pParentElement, sbCompName);
}
}
}
}
}
bool generateHeaders()
{
StringBuffer sbTabName;
StringBuffer sbPropName;
if (!m_pSchemaRoot)
m_pSchemaRoot.setown(createPTreeFromXMLFile(m_xsdName));
IPropertyTree *schemaNode = m_pSchemaRoot->queryPropTree("xs:element");
if (m_compName.length() == 0)
m_compName.append(schemaNode->queryProp(XML_ATTR_NAME));
if (!strcmp(m_compName.str(), "Eclserver"))
m_compName.clear().append(XML_TAG_ECLSERVERPROCESS);
m_jsStrBuf.append("var compTabs = new Array();\n ");
m_jsStrBuf.appendf("compTabs['%s'] = new Array();\n", m_compName.str());
m_jsStrBuf.append("var hiddenTabs = new Array();\n ");
m_jsStrBuf.appendf("hiddenTabs['%s'] = new Array();\n", m_compName.str());
m_jsStrBuf.append("var compTabToNode = new Array();\n");
m_jsStrBuf.append("var cS = new Array();\n");
Owned<IPropertyTreeIterator> iter = schemaNode->getElements("*");
ForEach(*iter)
{
IPropertyTree &schemaElement = iter->query();
const char* szElementName = schemaElement.queryName();
TRACE_SCHEMA_NODE("ProcessSchemaElement", &schemaElement);
//if node is xs:complexType and xs:complexContent then process children
if (!strcmp(szElementName, XSD_TAG_COMPLEX_TYPE) ||
!strcmp(szElementName, XSD_TAG_COMPLEX_CONTENT))
{
//if this schema node has any attributes then add an attribute tab
//
bool bHasAttribs = schemaNodeHasAttributes(&schemaElement);
if (bHasAttribs)
{
AddAttributesFromSchema(schemaNode, m_compName, "Attributes", NULL);
}
}
ProcessComplexTypeSchemaNode(&schemaElement, m_pSchemaRoot, m_compName);
}
addMisc();
if (m_jsName.length())
writeToFile(m_jsName, m_jsStrBuf);
return true;
}
void setCompTree(IPropertyTree* pTree, bool allSubTypes)
{
m_pCompTree = pTree;
m_allSubTypes = allSubTypes;
}
void getTabNameArray(StringArray& tabNameArray)
{
CloneArray(tabNameArray, m_tabNameArray);
}
void getDefnPropTree(IPropertyTree* pTree, StringBuffer xpathDefn)
{
m_pDefTree = pTree;
m_xpathDefn.clear().append(xpathDefn);
generateHeaders();
}
void getDefnString(StringBuffer& compDefn, StringBuffer& viewChildNodes, StringBuffer& multiRowNodes)
{
m_viewChildNodes.clear();
m_viewChildNodes.setown(createPTree("viewChildNodes"));
m_multiRowNodes.clear();
m_multiRowNodes.setown(createPTree("multiRowNodes"));
generateHeaders();
compDefn.clear().append(m_jsStrBuf);
if (m_colIndex.length() > 27)
compDefn.append(m_colIndex);
if (m_columns.length() > 26)
compDefn.append(m_columns);
toXML(m_viewChildNodes, viewChildNodes);
toXML(m_multiRowNodes, multiRowNodes);
}
void setWizardFlag(bool flag)
{
m_wizFlag = flag;
}
void setGenerateOptional(bool flag)
{
m_genOptional = flag;
}
void setWizard(CWizardInputs* ptr)
{
m_wizard.set(ptr);
}
void getValueForTypeInXSD(IPropertyTree& attr, StringBuffer compName, StringBuffer& wizDefVal)
{
StringBuffer tempPath;
const char* type = attr.queryProp("@type");
const char* name = attr.queryProp("@name");
//first check for all the tags autogen then proceed with type checking.
if(attr.hasProp("./xs:annotation/xs:appinfo/autogendefaultvalue"))
{
tempPath.clear().append("./xs:annotation/xs:appinfo/autogendefaultvalue");
if(!strcmp(attr.queryProp(tempPath.str()), "$defaultenvfile"))
{
tempPath.clear().appendf("Software/EspProcess/EspService[@name='%s']/LocalEnvConfFile", (m_wizard->getService()).str());
IPropertyTree* pCfg = m_wizard->getConfig();
const char* pConfFile = pCfg->queryProp(tempPath.str());
if(pConfFile && *pConfFile)
{
Owned<IProperties> pParams = createProperties(pConfFile);
wizDefVal.clear().append(pParams->queryProp("configs")).append("/environment.xml");
}
}
else if(!strcmp(attr.queryProp(tempPath.str()), "$componentfilesdir"))
{
tempPath.clear().append("EnvSettings/path");
wizDefVal.clear().append(m_pEnv->queryProp(tempPath.str()));
if(!wizDefVal.length())
wizDefVal.append(STANDARD_COMPFILESDIR);
wizDefVal.append(PATHSEPSTR"componentfiles");
}
else if(!strcmp(attr.queryProp(tempPath.str()), "$processname"))
{
tempPath.clear().appendf("Software/%s[1]/@name",compName.str());
wizDefVal.clear().append(m_pEnv->queryProp(tempPath.str()));
}
else if(!strcmp(attr.queryProp(tempPath.str()), "$hthorcluster"))
{
tempPath.clear().append(XML_TAG_SOFTWARE"/"XML_TAG_TOPOLOGY"/"XML_TAG_CLUSTER);
Owned<IPropertyTreeIterator> iterClusters = m_pEnv->getElements(tempPath.str());
ForEach (*iterClusters)
{
IPropertyTree* pCluster = &iterClusters->query();
if (pCluster->queryPropTree(XML_TAG_ROXIECLUSTER) ||
pCluster->queryPropTree(XML_TAG_THORCLUSTER))
continue;
else
{
wizDefVal.clear().append(pCluster->queryProp(XML_ATTR_NAME));
break;
}
}
}
else
{
wizDefVal.clear().append(attr.queryProp(tempPath.str()));
tempPath.clear().appendf("Software/%s[1]/@buildSet", compName.str());
if(m_pEnv->queryProp(tempPath.str()))
{
if(m_wizard->getNumOfNodes(m_pEnv->queryProp(tempPath.str())) > 1)
{
tempPath.clear().append("./xs:annotation/xs:appinfo/autogendefaultformultinode");
if(attr.hasProp(tempPath.str()))
wizDefVal.clear().append(attr.queryProp(tempPath.str()));
}
}
}
}
else if(attr.hasProp("./xs:annotation/xs:appinfo/autogenprefix") || attr.hasProp("./xs:annotation/xs:appinfo/autogensuffix"))
{
StringBuffer sb;
StringBuffer nameOfComp;
tempPath.clear().appendf("./Software/%s[1]/@name",m_compName.str());
nameOfComp.clear().append(m_pEnv->queryProp(tempPath.str()));
tempPath.clear().append("./xs:annotation/xs:appinfo/autogenprefix");
if(attr.hasProp(tempPath.str()))
sb.clear().append(attr.queryProp(tempPath.str())).append(nameOfComp);
tempPath.clear().append("./xs:annotation/xs:appinfo/autogensuffix");
if(attr.hasProp(tempPath.str()))
{
if (sb.length())
sb.append(attr.queryProp(tempPath.str()));
else
sb.append(nameOfComp).append(attr.queryProp(tempPath.str()));
}
wizDefVal.clear().append(sb);
}
else if(!strcmp(type,"computerType"))
{
if(m_wizard)
{
StringBuffer buildSetName, ipAddr;
tempPath.clear().appendf("./Programs/Build/BuildSet[%s=\"%s\"]",XML_ATTR_PROCESS_NAME,m_compName.str());
IPropertyTree* pCompTree = m_pEnv->queryPropTree(tempPath.str());
if(pCompTree)
{
buildSetName.append(pCompTree->queryProp(XML_ATTR_NAME));
CInstDetails* pInst = m_wizard->getServerIPMap(compName, buildSetName,m_pEnv);
if( pInst )
{
StringArray& ipArray = pInst->getIpAssigned();
ForEachItemIn(x, ipArray)
{
if(ipArray.ordinality() == 1)
ipAddr.append(ipArray.item(x));
else
ipAddr.append(ipArray.item(x)).append(",");
tempPath.clear().appendf("./Hardware/Computer[@netAddress=\"%s\"]",ipAddr.str());
IPropertyTree* pHard = m_pEnv->queryPropTree(tempPath.str());
if(pHard)
{
tempPath.clear().append("@name");
wizDefVal.clear().append(pHard->queryProp(tempPath.str()));
}
}
}
}
}
}
else if(!strcmp(type,"xs:string"))
{
StringBuffer nameOfComp;
tempPath.clear().appendf("./Software/%s[1]/@name",m_compName.str());
nameOfComp.clear().append(m_pEnv->queryProp(tempPath.str()));
if(!strcmp(name, "dbUser"))
{
wizDefVal.clear().append(m_wizard->getDbUser());
}
else if(!strcmp(name, "dbPassword"))
{
wizDefVal.clear().append(m_wizard->getDbPassword());
}
}
else if(!strcmp(type,"mysqlType"))
{
tempPath.clear().append("./Software/MySQLProcess[1]/@name");
wizDefVal.clear().append(m_pEnv->queryProp(tempPath.str()));
}
else if(!strcmp(type,"daliServersType"))
{
tempPath.clear().append("./Software/DaliServerProcess[1]/@name");
wizDefVal.clear().append(m_pEnv->queryProp(tempPath.str()));
}
else if(!strcmp(type,"ldapServerType"))
{
tempPath.clear().append("./Software/LdapServerProcess[1]/@name");
wizDefVal.clear().append(m_pEnv->queryProp(tempPath.str()));
}
else if(!strcmp(type, "roxieClusterType"))
{
tempPath.clear().append("./Software/RoxieCluster[1]/@name");
wizDefVal.clear().append(m_pEnv->queryProp(tempPath.str()));
}
else if(!strcmp(type, "eclServerType"))
{
tempPath.clear().append("./Software/EclServerProcess[1]/@name");
wizDefVal.clear().append(m_pEnv->queryProp(tempPath.str()));
}
else if(!strcmp(type, "eclCCServerType"))
{
tempPath.clear().append("./Software/EclCCServerProcess[1]/@name");
wizDefVal.clear().append(m_pEnv->queryProp(tempPath.str()));
}
else if(!strcmp(type, "espProcessType"))
{
tempPath.clear().append("./Software/EspProcess[1]/@name");
wizDefVal.clear().append(m_pEnv->queryProp(tempPath.str()));
}
else if(!strcmp(type, "espBindingType"))
{
IPropertyTree* pAppInfo = attr.queryPropTree("xs:annotation/xs:appinfo");
StringBuffer xpath;
const char* serviceType = NULL;
if (pAppInfo)
{
serviceType = pAppInfo->queryProp("serviceType");
if (serviceType)
xpath.clear().append("Software/EspService");
}
else
xpath.clear().appendf("Software/*[@buildSet='%s']", type);
wizDefVal.clear();
Owned<IPropertyTreeIterator> iterEspServices = m_pEnv->getElements(xpath);
short blank = 0;
ForEach (*iterEspServices)
{
IPropertyTree* pEspService = &iterEspServices->query();
if(serviceType)
{
xpath.clear().appendf("Properties[@type='%s']", serviceType);
if (pEspService->queryPropTree(xpath.str()) == NULL)
continue;
}
Owned<IPropertyTreeIterator> iter = m_pEnv->getElements("Software/EspProcess[1]");
ForEach (*iter)
{
IPropertyTree* pEspProcess = &iter->query();
xpath.clear().appendf("EspBinding[@service='%s']", pEspService->queryProp(XML_ATTR_NAME));
if(pEspProcess->queryPropTree(xpath.str()) != NULL)
wizDefVal.append(pEspProcess->queryProp(XML_ATTR_NAME)).append("/").append(pEspService->queryProp(XML_ATTR_NAME));
}
}
}
else if(!strcmp(type, "ipAddressAndPort"))
{
StringBuffer defaultPort;
tempPath.clear().append("./xs:annotation/xs:appinfo/defaultPort");
defaultPort.append(attr.queryProp(tempPath.str()));
tempPath.clear().append("./xs:annotation/xs:appinfo/autogenxpath");
if(attr.hasProp(tempPath.str()))
{
StringBuffer computerName;
computerName.append(m_pEnv->queryProp(attr.queryProp(tempPath.str())));
tempPath.clear().appendf("./Hardware/Computer[@name=\"%s\"]",computerName.str());
if(m_pEnv->hasProp(tempPath.str()))
{
IPropertyTree* pHard = m_pEnv->queryPropTree(tempPath.str());
if(pHard)
wizDefVal.clear().append(pHard->queryProp("./"XML_ATTR_NETADDRESS)).append(":").append(defaultPort);
}
}
}
}
private:
Linked<const IPropertyTree> m_pEnv;
Linked<IPropertyTree> m_pSchemaRoot;
IPropertyTree* m_pCompTree;
IPropertyTree* m_pDefTree;
Owned<IPropertyTree> m_viewChildNodes;
Owned<IPropertyTree> m_multiRowNodes;
StringBuffer m_jsStrBuf;
StringBuffer m_colIndex;
StringBuffer m_columns;
StringBuffer m_xsdName;
StringBuffer m_jsName;
StringBuffer m_compName;
StringBuffer m_xpathDefn;
StringBuffer m_splitterTabName;
StringArray m_tabNameArray;
StringArray m_hiddenTabNameArray;
short m_numAttrs;
bool m_allSubTypes;
bool m_wizFlag;
bool m_genOptional;
Linked<CWizardInputs> m_wizard;
};
short treeHasMultipleCompsOfSameType(Linked<IPropertyTree> compTypeTree, const char* xpath)
{
Owned<IPropertyTreeIterator> iter = compTypeTree->getElements(xpath);
IPropertyTree *element = NULL;
short count = 0;
if (iter)
if (iter->first())
{
if (iter->isValid())
{
element = &iter->query();
if (iter->next())
{
Owned<IPropertyTreeIterator> iterDup = compTypeTree->getElements(xpath);
ForEach(*iterDup) count++;
}
else
count = 1;
}
}
return count;
}
bool generateHeadersFromXsd(IPropertyTree* pEnv, const char* xsdName, const char* jsName)
{
CGenerateJSFromXSD obj(pEnv, xsdName, jsName);
return obj.generateHeaders();
}
IPropertyTree* generateTreeFromXsd(const IPropertyTree* pEnv, IPropertyTree* pSchema,
const char* compName, const char* buildSetName,
const IPropertyTree* pCfg, const char* servicename,
bool allSubTypes, bool wizFlag, CWizardInputs* pWInputs,
bool forceOptional)
{
bool flag = true;
if (!forceOptional)
{
StringBuffer xpath, genEnvConf, prop;
Owned<IProperties> algProp;
xpath.clear().appendf("Software/EspProcess/EspService[@name='%s']/LocalConfFile", servicename);
const char* pConfFile = pCfg->queryProp(xpath.str());
xpath.clear().appendf("Software/EspProcess/EspService[@name='%s']/LocalEnvConfFile", servicename);
const char* pEnvConfFile = pCfg->queryProp(xpath.str());
if (pConfFile && *pConfFile && pEnvConfFile && *pEnvConfFile)
{
Owned<IProperties> pParams = createProperties(pConfFile);
Owned<IProperties> pEnvParams = createProperties(pEnvConfFile);
const char* genenv = pParams->queryProp("wizardalgorithm");
if (!genenv || !*genenv)
genenv = "genenvrules.conf";
const char* cfgpath = pEnvParams->queryProp("configs");
if (!cfgpath || !*cfgpath)
cfgpath = CONFIG_DIR;
genEnvConf.clear().append(cfgpath);
if (genEnvConf.charAt(genEnvConf.length() - 1) != PATHSEPCHAR)
genEnvConf.append(PATHSEPCHAR);
genEnvConf.append(genenv);
}
if (genEnvConf.length() && checkFileExists(genEnvConf.str()))
algProp.setown(createProperties(genEnvConf.str()));
CConfigHelper::getInstance()->addPluginsToGenEnvRules(algProp.get());
enum GenOptional {GENOPTIONAL_ALL, GENOPTIONAL_NONE, GENOPTIONAL_COMPS};
GenOptional genOpt = GENOPTIONAL_COMPS;
algProp->getProp("do_not_gen_optional", prop);
StringArray doNotGenOpt;
doNotGenOpt.appendList(prop.str(), ",");
if (doNotGenOpt.length() == 0)
genOpt = GENOPTIONAL_ALL;
else if (doNotGenOpt.length() == 1 && !strcmp(doNotGenOpt.item(0), "all"))
genOpt = GENOPTIONAL_NONE;
if (genOpt == GENOPTIONAL_ALL || (genOpt == GENOPTIONAL_COMPS && doNotGenOpt.find(buildSetName) == NotFound ))
flag = true;
else if (genOpt == GENOPTIONAL_NONE || (genOpt == GENOPTIONAL_COMPS && doNotGenOpt.find(buildSetName) != NotFound ))
flag = false;
}
Owned<IPropertyTree> pCompTree(createPTree(compName));
CGenerateJSFromXSD obj(pEnv, pSchema, "", compName);
obj.setCompTree(pCompTree, allSubTypes);
obj.setWizardFlag(wizFlag);
obj.setGenerateOptional(flag);
obj.setWizard(pWInputs);
obj.generateHeaders();
return pCompTree.getLink();
}
bool generateHardwareHeaders(const IPropertyTree* pEnv, StringBuffer& sbDefn, bool writeOut, IPropertyTree* pCompTree, bool bIncludeNAS)
{
if (pCompTree)
{
StringBuffer xpath,sbdefaultValue("");
IPropertyTree* pComputerType = pCompTree->addPropTree(XML_TAG_COMPUTERTYPE, createPTree());
xpath.clear().append(XML_ATTR_NAME);
pComputerType->addProp(xpath, sbdefaultValue.str());
xpath.clear().append(XML_ATTR_MANUFACTURER);
pComputerType->addProp(xpath, sbdefaultValue.str());
xpath.clear().append(XML_ATTR_COMPUTERTYPE);
pComputerType->addProp(xpath, sbdefaultValue.str());
xpath.clear().append(XML_ATTR_OPSYS);
pComputerType->addProp(xpath, sbdefaultValue.str());
xpath.clear().append(XML_ATTR_MEMORY);
pComputerType->addProp(xpath, sbdefaultValue.str());
xpath.clear().append(XML_ATTR_NICSPEED);
pComputerType->addProp(xpath, sbdefaultValue.str());
IPropertyTree* pComputer = pCompTree->addPropTree(XML_TAG_COMPUTER, createPTree());
xpath.clear().append(XML_ATTR_NAME);
pComputer->addProp(xpath, sbdefaultValue.str());
xpath.clear().append(XML_ATTR_NETADDRESS);
pComputer->addProp(xpath, sbdefaultValue.str());
xpath.clear().append(XML_ATTR_DOMAIN);
pComputer->addProp(xpath, sbdefaultValue.str());
xpath.clear().append(XML_ATTR_COMPUTERTYPE);
pComputer->addProp(xpath, sbdefaultValue.str());
IPropertyTree* pSwitch = pCompTree->addPropTree(XML_TAG_SWITCH, createPTree());
xpath.clear().append(XML_ATTR_NAME);
IPropertyTree* pDomain = pCompTree->addPropTree(XML_TAG_DOMAIN, createPTree());
xpath.clear().append(XML_ATTR_NAME);
pDomain->addProp(xpath, sbdefaultValue.str());
xpath.clear().append(XML_ATTR_USERNAME);
pDomain->addProp(xpath, sbdefaultValue.str());
xpath.clear().append(XML_ATTR_PASSWORD);
pDomain->addProp(xpath, sbdefaultValue.str());
xpath.clear().append("@snmpSecurityString");
pDomain->addProp(xpath, sbdefaultValue.str());
if (bIncludeNAS == true)
{
IPropertyTree* pNAS = pCompTree->addPropTree(XML_TAG_NAS, createPTree());
xpath.clear().append(XML_ATTR_NAME);
pNAS->addProp(xpath, sbdefaultValue.str());
xpath.clear().append(XML_ATTR_MASK);
pNAS->addProp(xpath, "255.255.255.255");
xpath.clear().append(XML_ATTR_SUBNET);
pNAS->addProp(xpath, "0.0.0.0");
xpath.clear().append(XML_ATTR_DIRECTORY);
pNAS->addProp(xpath, sbdefaultValue.str());
xpath.clear().append(XML_ATTR_TRACE);
pNAS->addProp(xpath, sbdefaultValue.str());
}
}
else
{
StringBuffer jsStrBuf("var compTabs = new Array();");
jsStrBuf.append("compTabs['Hardware'] = new Array();");
jsStrBuf.append("var compTabToNode = new Array();");
jsStrBuf.append("var cS = new Array();");
addItem(jsStrBuf, pEnv, XML_TAG_COMPUTERTYPE, TAG_NAME, "", 0, 1, "", 1);
addItem(jsStrBuf, pEnv, XML_TAG_COMPUTERTYPE, TAG_MANUFACTURER, "", 0, 1, "", 1);
addItem(jsStrBuf, pEnv, XML_TAG_COMPUTERTYPE, TAG_COMPUTERTYPE, "", 0, 1, "", 1);
addItem(jsStrBuf, pEnv, XML_TAG_COMPUTERTYPE, TAG_OPSYS, "", 0, 1, "|new Array('W2K','solaris','linux')", 4);
addItem(jsStrBuf, pEnv, XML_TAG_COMPUTERTYPE, TAG_MEMORY, "", 0, 1, "", 1);
addItem(jsStrBuf, pEnv, XML_TAG_COMPUTERTYPE, TAG_NICSPEED, "", 0, 1, "", 1);
addItem(jsStrBuf, pEnv, XML_TAG_SWITCH, TAG_NAME, "", 0, 1, "", 1);
addItem(jsStrBuf, pEnv, XML_TAG_DOMAIN, TAG_NAME, "", 0, 1, "", 1);
addItem(jsStrBuf, pEnv, XML_TAG_DOMAIN, TAG_USERNAME, "", 0, 1, "", 1);
addItem(jsStrBuf, pEnv, XML_TAG_DOMAIN, TAG_PASSWORD, "", 0, 1, "", 5);
addItem(jsStrBuf, pEnv, XML_TAG_DOMAIN, TAG_SNMPSECSTRING, "", 0, 1, "", 5);
addItem(jsStrBuf, pEnv, XML_TAG_COMPUTER, TAG_NAME, "", 0, 1, "", 1);
addItem(jsStrBuf, pEnv, XML_TAG_COMPUTER, TAG_NETADDRESS, "", 0, 1, "", 1);
addItem(jsStrBuf, pEnv, XML_TAG_COMPUTER, TAG_DOMAIN, "", 0, 1, XML_TAG_HARDWARE"/"XML_TAG_DOMAIN, 4);
addItem(jsStrBuf, pEnv, XML_TAG_COMPUTER, TAG_COMPUTERTYPE, "", 0, 1, XML_TAG_HARDWARE"/"XML_TAG_COMPUTERTYPE, 4);
addItem(jsStrBuf, pEnv, XML_TAG_NAS, TAG_NAME, "", 0, 1, "", 1);
addItem(jsStrBuf, pEnv, XML_TAG_NAS, TAG_SUBNET, "", 0, 1, "", 1);
addItem(jsStrBuf, pEnv, XML_TAG_NAS, TAG_DIRECTORY, "", 0, 1, "", 1);
addItem(jsStrBuf, pEnv, XML_TAG_NAS, TAG_MASK, "", 0, 1, "", 1);
addItem(jsStrBuf, pEnv, XML_TAG_NAS, TAG_TRACE, "", 0, 1, "", 1);
jsStrBuf.append("compTabs['Hardware'][compTabs['Hardware'].length]= 'Computer Types';");
jsStrBuf.append("compTabs['Hardware'][compTabs['Hardware'].length]= 'Switches';");
jsStrBuf.append("compTabs['Hardware'][compTabs['Hardware'].length]= 'Domains';");
jsStrBuf.append("compTabs['Hardware'][compTabs['Hardware'].length]= 'Computers';");
jsStrBuf.append("compTabs['Hardware'][compTabs['Hardware'].length]= 'NAS';");
jsStrBuf.append("compTabToNode['Computer Types']= 'ComputerType';");
jsStrBuf.append("compTabToNode['Switches']= 'Switch';");
jsStrBuf.append("compTabToNode['Domains']= 'Domain';");
jsStrBuf.append("compTabToNode['Computers']= 'Computer';");
jsStrBuf.append("compTabToNode['NAS']= 'NAS';");
int index = 0;
jsStrBuf.append("var colIndex = new Array();");
jsStrBuf.appendf("colIndex['nameComputer Types']=%d;", index++);
jsStrBuf.appendf("colIndex['manufacturerComputer Types']=%d;", index++);
jsStrBuf.appendf("colIndex['computerTypeComputer Types']=%d;", index++);
jsStrBuf.appendf("colIndex['opSysComputer Types']=%d;", index++);
jsStrBuf.appendf("colIndex['nameSwitches']=%d;", 0);
index=0;
jsStrBuf.appendf("colIndex['nameDomains']=%d;", index++);
jsStrBuf.appendf("colIndex['usernameDomains']=%d;", index++);
jsStrBuf.appendf("colIndex['passwordDomains']=%d;", index++);
index=0;
jsStrBuf.appendf("colIndex['nameComputers']=%d;", index++);
jsStrBuf.appendf("colIndex['netAddressComputers']=%d;", index++);
jsStrBuf.appendf("colIndex['domainComputers']=%d;", index++);
jsStrBuf.appendf("colIndex['computerTypeComputers']=%d;", index++);
index=0;
jsStrBuf.appendf("colIndex['nameNAS']=%d;", index++);
jsStrBuf.appendf("colIndex['maskNAS']=%d;", index++);
jsStrBuf.appendf("colIndex['subnetNAS']=%d;", index++);
jsStrBuf.appendf("colIndex['directoryNAS']=%d;", index++);
jsStrBuf.appendf("colIndex['traceNAS']=%d;", index++);
sbDefn.clear().append(jsStrBuf);
if (writeOut)
writeToFile(CONFIGMGR_JSPATH"hardware.js", jsStrBuf);
}
return true;
}
bool generateHeadersForEnvSettings(const IPropertyTree* pEnv, StringBuffer& sbDefn, bool writeOut)
{
StringBuffer jsStrBuf("var compTabs = new Array();");
jsStrBuf.append("compTabs['EnvSettings'] = new Array();");
jsStrBuf.append("var compTabToNode = new Array();");
jsStrBuf.append("var cS = new Array();");
addItem(jsStrBuf, pEnv, "", TAG_SRCPATH, "", 0, 1, "", 0);
addItem(jsStrBuf, pEnv, "", TAG_LOCK, "", 0, 1, "", 0);
addItem(jsStrBuf, pEnv, "", TAG_CONFIGS, "", 0, 1, "", 0);
addItem(jsStrBuf, pEnv, "", TAG_PATH, "", 0, 1, "", 0);
addItem(jsStrBuf, pEnv, "", TAG_RUNTIME, "", 0, 1, "", 0);
jsStrBuf.append("compTabs['EnvSettings'][compTabs['EnvSettings'].length]= 'Attributes';");
sbDefn.clear().append(jsStrBuf);
if (writeOut)
writeToFile(CONFIGMGR_JSPATH"EnvSettings.js", jsStrBuf);
return true;
}
bool generateHeadersForEnvXmlView(const IPropertyTree* pEnv, StringBuffer& sbDefn, bool writeOut)
{
StringBuffer jsStrBuf("var compTabs = new Array();");
jsStrBuf.append("compTabs['Environment'] = new Array();");
jsStrBuf.append("var compTabToNode = new Array();");
jsStrBuf.append("var cS = new Array();");
jsStrBuf.append("var colIndex = new Array();");
int index = 0;
jsStrBuf.appendf("colIndex['nameEnvironment']=%d;", index++);
jsStrBuf.appendf("colIndex['valueEnvironment']=%d;", index++);
jsStrBuf.appendf("var attr%s%s = {};", TAG_NAME, TAG_ATTRIBUTE);
jsStrBuf.appendf("attr%s%s.tab = 'Environment';", TAG_NAME, TAG_ATTRIBUTE);
jsStrBuf.appendf("attr%s%s.tip = '';", TAG_NAME, TAG_ATTRIBUTE);
jsStrBuf.appendf("attr%s%s.hidden = 0;", TAG_NAME, TAG_ATTRIBUTE);
jsStrBuf.appendf("attr%s%s.required = 1;", TAG_NAME, TAG_ATTRIBUTE);
jsStrBuf.appendf("attr%s%s.ctrlType = 1;", TAG_NAME, TAG_ATTRIBUTE);
jsStrBuf.appendf("cS['%s%s']=attr%s%s;", TAG_NAME, TAG_ATTRIBUTE, TAG_NAME, TAG_ATTRIBUTE);
jsStrBuf.appendf("var attr%s%s = {};", TAG_VALUE, TAG_ATTRIBUTE);
jsStrBuf.appendf("attr%s%s.tab = 'Environment';", TAG_VALUE, TAG_ATTRIBUTE);
jsStrBuf.appendf("attr%s%s.tip = '';", TAG_VALUE, TAG_ATTRIBUTE);
jsStrBuf.appendf("attr%s%s.hidden = 0;", TAG_VALUE, TAG_ATTRIBUTE);
jsStrBuf.appendf("attr%s%s.required = 1;", TAG_VALUE, TAG_ATTRIBUTE);
jsStrBuf.appendf("attr%s%s.ctrlType = 1;", TAG_VALUE, TAG_ATTRIBUTE);
jsStrBuf.appendf("cS['%s%s']=attr%s%s;", TAG_VALUE, TAG_ATTRIBUTE, TAG_VALUE, TAG_ATTRIBUTE);
jsStrBuf.appendf("var attr%s%s = {};", TAG_NAME, TAG_ELEMENT);
jsStrBuf.appendf("attr%s%s.tab = 'Environment';", TAG_NAME, TAG_ELEMENT);
jsStrBuf.appendf("attr%s%s.tip = '';", TAG_NAME, TAG_ELEMENT);
jsStrBuf.appendf("attr%s%s.hidden = 0;", TAG_NAME, TAG_ELEMENT);
jsStrBuf.appendf("attr%s%s.required = 1;", TAG_NAME, TAG_ELEMENT);
jsStrBuf.appendf("attr%s%s.ctrlType = 1;", TAG_NAME, TAG_ELEMENT);
jsStrBuf.appendf("cS['%s%s']=attr%s%s;", TAG_NAME, TAG_ELEMENT, TAG_NAME, TAG_ELEMENT);
jsStrBuf.appendf("var attr%s%s = {};", TAG_VALUE, TAG_ELEMENT);
jsStrBuf.appendf("attr%s%s.tab = 'Environment';", TAG_VALUE, TAG_ELEMENT);
jsStrBuf.appendf("attr%s%s.tip = '';", TAG_VALUE, TAG_ELEMENT);
jsStrBuf.appendf("attr%s%s.hidden = 0;", TAG_VALUE, TAG_ELEMENT);
jsStrBuf.appendf("attr%s%s.required = 1;", TAG_VALUE, TAG_ELEMENT);
jsStrBuf.appendf("attr%s%s.ctrlType = 1;", TAG_VALUE, TAG_ELEMENT);
jsStrBuf.appendf("cS['%s%s']=attr%s%s;", TAG_VALUE, TAG_ELEMENT, TAG_VALUE, TAG_ELEMENT);
jsStrBuf.append("compTabs['Environment'][compTabs['Environment'].length]= 'Environment';");
sbDefn.clear().append(jsStrBuf);
if (writeOut)
writeToFile(CONFIGMGR_JSPATH"Environment.js", jsStrBuf);
return true;
}
bool generateHeaderForDeployableComps(const IPropertyTree* pEnv, StringBuffer& sbDefn, bool writeOut)
{
short index = 0;
StringBuffer jsStrBuf("var compTabs = new Array();");
jsStrBuf.append("compTabs['Deploy'] = new Array();");
jsStrBuf.append("var compTabToNode = new Array();");
jsStrBuf.append("var cS = new Array();");
jsStrBuf.append("var colIndex = new Array();");
addItem(jsStrBuf, pEnv, XML_TAG_COMPONENT, TAG_BUILD, "", 0, 1, "", 0);
addItem(jsStrBuf, pEnv, XML_TAG_COMPONENT, TAG_BUILDSET, "", 0, 1, "", 0);
addItem(jsStrBuf, pEnv, XML_TAG_COMPONENT, TAG_NAME, "", 0, 1, "", 0);
addItem(jsStrBuf, pEnv, XML_TAG_INSTANCES, TAG_BUILDSET, "", 0, 1, "", 0);
addItem(jsStrBuf, pEnv, XML_TAG_INSTANCES, TAG_DIRECTORY, "", 0, 1, "", 0);
addItem(jsStrBuf, pEnv, XML_TAG_INSTANCES, TAG_NODENAME, "", 0, 1, "", 0);
jsStrBuf.append("compTabs['Deploy'][compTabs['Deploy'].length]= 'Deploy';");
jsStrBuf.appendf("colIndex['nameDeploy']=%d;", index++);
jsStrBuf.appendf("colIndex['buildDeploy']=%d;", index++);
jsStrBuf.appendf("colIndex['buildSetDeploy']=%d;", index++);
sbDefn.clear().append(jsStrBuf);
if (writeOut)
writeToFile(CONFIGMGR_JSPATH"deploy.js", jsStrBuf);
return true;
}
bool generateHeaderForTopology(const IPropertyTree* pEnv, StringBuffer& sbDefn, bool writeOut)
{
short index = 0;
StringBuffer jsStrBuf("var compTabs = new Array();");
jsStrBuf.append("compTabs['Topology'] = new Array();");
jsStrBuf.append("var compTabToNode = new Array();");
jsStrBuf.append("var cS = new Array();");
addTopologyType(jsStrBuf, pEnv, "", TAG_NAME, "", 1, 1, "", 1);
addTopologyType(jsStrBuf, pEnv, "", TAG_BUILDSET, "", 1, 1, "", 1);
addTopologyType(jsStrBuf, pEnv, XML_TAG_ECLCCSERVERPROCESS, TAG_PROCESS, "", 0, 1, XML_TAG_SOFTWARE"/EclCCServerProcess", 4);
addTopologyType(jsStrBuf, pEnv, XML_TAG_ECLSERVERPROCESS, TAG_PROCESS, "", 0, 1, XML_TAG_SOFTWARE"/EclServerProcess", 4);
addTopologyType(jsStrBuf, pEnv, XML_TAG_ECLSCHEDULERPROCESS, TAG_PROCESS, "", 0, 1, XML_TAG_SOFTWARE"/EclSchedulerProcess", 4);
addTopologyType(jsStrBuf, pEnv, XML_TAG_ECLAGENTPROCESS, TAG_PROCESS, "", 0, 1, XML_TAG_SOFTWARE"/EclAgentProcess", 4);
addTopologyType(jsStrBuf, pEnv, XML_TAG_THORCLUSTER, TAG_PROCESS, "", 0, 1, XML_TAG_SOFTWARE"/ThorCluster", 4);
addTopologyType(jsStrBuf, pEnv, XML_TAG_ROXIECLUSTER, TAG_PROCESS, "", 0, 1, XML_TAG_SOFTWARE"/RoxieCluster", 4);
addTopologyType(jsStrBuf, pEnv, XML_TAG_CLUSTER, TAG_NAME, "", 0, 1, "", 1);
addTopologyType(jsStrBuf, pEnv, XML_TAG_CLUSTER, TAG_PREFIX, "", 0, 1, "", 1);
jsStrBuf.append("compTabs['Topology'][compTabs['Topology'].length]= 'Topology';");
jsStrBuf.append("var colIndex = new Array();");
jsStrBuf.appendf("colIndex['nameTopology']=%d;", index++);
jsStrBuf.appendf("colIndex['valueTopology']=%d;", index++);
sbDefn.append(jsStrBuf);
if (writeOut)
writeToFile(CONFIGMGR_JSPATH"Topology.js", jsStrBuf);
return true;
}
bool generateBuildHeaders(const IPropertyTree* pEnv, bool isPrograms, StringBuffer& sbDefn, bool writeOut)
{
short index = 0;
StringBuffer jsStrBuf("var compTabs = new Array();");
jsStrBuf.append("compTabs['Programs'] = new Array();");
jsStrBuf.append("var compTabToNode = new Array();");
jsStrBuf.append("var cS = new Array();");
addItem(jsStrBuf, pEnv, XML_TAG_PROGRAMS, TAG_NAME, "", 0, 1, "", 1);
addItem(jsStrBuf, pEnv, XML_TAG_PROGRAMS, TAG_URL, "", 0, 1, "", 1);
addItem(jsStrBuf, pEnv, XML_TAG_PROGRAMS, TAG_PATH, "", 0, 1, "", 1);
addItem(jsStrBuf, pEnv, XML_TAG_PROGRAMS, TAG_INSTALLSET, "", 0, 1, "", 1);
addItem(jsStrBuf, pEnv, XML_TAG_PROGRAMS, TAG_PROCESSNAME, "", 0, 1, "", 1);
addItem(jsStrBuf, pEnv, XML_TAG_PROGRAMS, TAG_SCHEMA, "", 0, 1, "", 1);
addItem(jsStrBuf, pEnv, XML_TAG_PROGRAMS, TAG_DEPLOYABLE, "", 0, 1, "", 1);
jsStrBuf.append("compTabs['Programs'][compTabs['Programs'].length]= 'Programs';");
jsStrBuf.append("var colIndex = new Array();");
jsStrBuf.appendf("colIndex['namePrograms']=%d;", index++);
jsStrBuf.appendf("colIndex['pathPrograms']=%d;", index++);
jsStrBuf.appendf("colIndex['installSetPrograms']=%d;", index++);
jsStrBuf.appendf("colIndex['processNamePrograms']=%d;", index++);
jsStrBuf.appendf("colIndex['schemaPrograms']=%d;", index++);
jsStrBuf.appendf("colIndex['deployablePrograms']=%d;", index++);
if (isPrograms)
sbDefn.clear().append(jsStrBuf);
if (writeOut)
writeToFile(CONFIGMGR_JSPATH"programs.js", jsStrBuf);
jsStrBuf.clear().append("var compTabs = new Array();");
jsStrBuf.append("compTabs['BuildSet'] = new Array();");
jsStrBuf.append("var compTabToNode = new Array();");
jsStrBuf.append("var cS = new Array();");
addItem(jsStrBuf, pEnv, XML_TAG_BUILDSET, TAG_NAME, "", 0, 1, "", 1);
addItem(jsStrBuf, pEnv, XML_TAG_BUILDSET, TAG_METHOD, "", 0, 1, "", 1);
addItem(jsStrBuf, pEnv, XML_TAG_BUILDSET, TAG_SRCPATH, "", 0, 1, "", 1);
addItem(jsStrBuf, pEnv, XML_TAG_BUILDSET, TAG_DESTPATH, "", 0, 1, "", 1);
addItem(jsStrBuf, pEnv, XML_TAG_BUILDSET, TAG_DESTNAME, "", 0, 1, "", 1);
jsStrBuf.append("compTabs['BuildSet'][compTabs['BuildSet'].length]= 'BuildSet';");
if (!isPrograms)
sbDefn.clear().append(jsStrBuf);
if (writeOut)
writeToFile(CONFIGMGR_JSPATH"buildset.js", jsStrBuf);
return true;
}
bool generateHeadersFromEnv(const IPropertyTree* pEnv, StringBuffer& sbDefn, bool writeOut)
{
StringBuffer jsStrBuf(" var nodeFullData = new Array(); \
var nodeRoot = {}; \
nodeRoot['Name'] = 'Environment'; \
nodeRoot['DisplayName'] = 'Environment'; \
nodeRoot['CompType'] = 'Environment'; \
nodeRoot['Build'] = ''; \
nodeRoot['BuildSet'] = ''; \
nodeRoot['Params'] = ''; \
nodeRoot['id'] = 0; \
nodeRoot['parent'] = -1; \
nodeRoot['depth'] = 0; \
nodeFullData[0] = nodeRoot; \
");
StringBuffer compList, espServiceList, pluginsList;
getInstalledComponents(NULL, compList, espServiceList, pluginsList, pEnv);
jsStrBuf.append("nodeRoot['menuComps'] = new Array(").append(compList).append(");");
jsStrBuf.append("nodeRoot['menuEspServices'] = new Array(").append(espServiceList).append(");");
jsStrBuf.append("nodeRoot['menuPlugins'] = new Array(").append(pluginsList).append(");");
short nodeIndex = 1;
short index = 1;
short compTypeIndex = 0;
short buildSetIndex = 0;
StringBuffer lastCompAdded;
StringBuffer xPath;
xPath.append("*");
Owned<IPropertyTreeIterator> iter = pEnv->getElements(xPath.str(), iptiter_sort);
ForEach(*iter)
{
IPropertyTree& compTypeTree = iter->query();
StringBuffer compTypeName;
compTypeTree.getName(compTypeName);
if (!stricmp(compTypeName.str(), "Data") || !stricmp(compTypeName.str(), "EnvSettings") || !strcmp(compTypeName.str(), XML_TAG_PROGRAMS))
continue;
const char* pszCompTypeName = compTypeName.str();
jsStrBuf.appendf("var node%s = {};", pszCompTypeName);
jsStrBuf.appendf("node%s['Name'] = '%s';", pszCompTypeName, pszCompTypeName);
if (!strcmp(pszCompTypeName, XML_TAG_PROGRAMS))
jsStrBuf.appendf("node%s['DisplayName'] = '%s';", pszCompTypeName, "Builds");
else if (!strcmp(pszCompTypeName, "EnvSettings"))
jsStrBuf.appendf("node%s['DisplayName'] = '%s';", pszCompTypeName, "Environment Settings");
else
jsStrBuf.appendf("node%s['DisplayName'] = '%s';", pszCompTypeName, pszCompTypeName);
jsStrBuf.appendf("node%s['CompType'] = '%s';", pszCompTypeName, pszCompTypeName);
jsStrBuf.appendf("node%s['Build'] = '%s';", pszCompTypeName, "");
jsStrBuf.appendf("node%s['BuildSet'] = '%s';", pszCompTypeName, "");
jsStrBuf.appendf("node%s['menu'] = '%s';", pszCompTypeName, "m4");
jsStrBuf.appendf("node%s['Params'] = '%s';", pszCompTypeName, "");
jsStrBuf.appendf("node%s['id'] = %d;", pszCompTypeName, index);
jsStrBuf.appendf("node%s['parent'] = %d;", pszCompTypeName, 0);
jsStrBuf.appendf("node%s['depth'] = 1;", pszCompTypeName);
jsStrBuf.appendf("nodeFullData[%d] = node%s;", nodeIndex++, pszCompTypeName);
compTypeIndex = index;
index++;
Owned<IPropertyTreeIterator> iter2 = compTypeTree.getElements(xPath.str(), iptiter_sort);
ForEach(*iter2)
{
IPropertyTree &compTree = iter2->query();
StringBuffer compName;
compTree.getName(compName);
const char* pszCompName = compName.str();
StringBuffer build;
StringBuffer buildset;
StringBuffer compAttrName;
build = compTree.queryProp(XML_ATTR_BUILD);
buildset = compTree.queryProp(XML_ATTR_BUILDSET);
xPath.clear().appendf("%s", pszCompName);
short multipleComps = treeHasMultipleCompsOfSameType(&compTypeTree, xPath.str());
xPath.clear().append("*");
if (compTree.hasProp(XML_ATTR_BUILD) && compTree.hasProp(XML_ATTR_BUILDSET))
{
const char* pszBuildset;
if (!strcmp(pszCompName, XML_TAG_ESPSERVICE))
pszBuildset = XML_TAG_ESPSERVICE;
else if (!strcmp(pszCompName, XML_TAG_PLUGINPROCESS))
pszBuildset = "Plugin";
else if(!strcmp(pszCompName, XML_TAG_ECLSERVERPROCESS))
pszBuildset = "EclServer";
else
pszBuildset = buildset.str();
if ((multipleComps > 1) && (lastCompAdded.length() == 0 || strcmp(lastCompAdded.str(), pszBuildset)))
{
char szBuf[200];
GetDisplayProcessName(compTree.queryName(), szBuf);
compAttrName.append(szBuf).appendf(" (%d)", multipleComps);
jsStrBuf.appendf("var node%s = {};", pszBuildset);
jsStrBuf.appendf("node%s['Name'] = '%s';", pszBuildset, ""/*pszBuildset*/);
jsStrBuf.appendf("node%s['DisplayName'] = '%s';", pszBuildset, compAttrName.str());
jsStrBuf.appendf("node%s['CompType'] = '%s';", pszBuildset, pszBuildset);
jsStrBuf.appendf("node%s['Build'] = '%s';", pszBuildset, "");
jsStrBuf.appendf("node%s['BuildSet'] = '%s';", pszBuildset, "");
jsStrBuf.appendf("node%s['menu'] = '%s';", pszBuildset, "");
jsStrBuf.appendf("node%s['Params'] = '%s';", pszBuildset, "");
jsStrBuf.appendf("node%s['id'] = %d;", pszBuildset, index);
jsStrBuf.appendf("node%s['parent'] = %d;", pszBuildset, compTypeIndex);
jsStrBuf.appendf("node%s['depth'] = 2;", pszBuildset);
jsStrBuf.appendf("nodeFullData[%d] = node%s;", nodeIndex++, pszBuildset);
buildSetIndex = index;
index++;
}
lastCompAdded.clear().append(pszBuildset);
GetDisplayName(&compTree, compAttrName, (multipleComps <= 1));
jsStrBuf.appendf("var node%s = {};", pszCompName);
jsStrBuf.appendf("node%s['Name'] = '%s';", pszCompName, compTree.queryProp(XML_ATTR_NAME));
jsStrBuf.appendf("node%s['DisplayName'] = '%s';", pszCompName, compAttrName.str());
jsStrBuf.appendf("node%s['CompType'] = '%s';", pszCompName, pszCompName);
jsStrBuf.appendf("node%s['Build'] = '%s';", pszCompName, build.str());
jsStrBuf.appendf("node%s['BuildSet'] = '%s';", pszCompName, buildset.str());
jsStrBuf.appendf("node%s['menu'] = '%s';", pszCompName, "");
jsStrBuf.appendf("node%s['Params'] = '%s';", pszCompName, "");
jsStrBuf.appendf("node%s['id'] = %d;", pszCompName, index);
jsStrBuf.appendf("node%s['parent'] = %d;", pszCompName, (multipleComps > 1)?buildSetIndex:compTypeIndex);
jsStrBuf.appendf("node%s['depth'] = %d;", pszCompName, (multipleComps > 1)?3:2);
jsStrBuf.appendf("nodeFullData[%d] = node%s;", nodeIndex++, pszCompName);
index++;
}
else if (!strcmp(pszCompName, "Directories"))
{
jsStrBuf.appendf("var node%s = {};", pszCompName);
jsStrBuf.appendf("node%s['Name'] = '%s';", pszCompName, pszCompName);
jsStrBuf.appendf("node%s['DisplayName'] = '%s';", pszCompName, pszCompName);
jsStrBuf.appendf("node%s['CompType'] = '%s';", pszCompName, pszCompName);
jsStrBuf.appendf("node%s['Build'] = '';", pszCompName);
jsStrBuf.appendf("node%s['BuildSet'] = '';", pszCompName);
jsStrBuf.appendf("node%s['menu'] = '%s';", pszCompName, "");
jsStrBuf.appendf("node%s['Params'] = '%s';", pszCompName, "");
jsStrBuf.appendf("node%s['id'] = %d;", pszCompName, index);
jsStrBuf.appendf("node%s['parent'] = %d;", pszCompName, compTypeIndex);
jsStrBuf.appendf("node%s['depth'] = %d;", pszCompName, 2);
jsStrBuf.appendf("nodeFullData[%d] = node%s;", nodeIndex++, pszCompName);
index++;
}
}
}
jsStrBuf.append("function getNavTreeData(){return nodeFullData;}");
jsStrBuf.append("(function(){navTreeData = nodeFullData;})();");
sbDefn.clear().append(jsStrBuf);
if (writeOut)
{
StringBuffer jsName(CONFIGMGR_JSPATH);
jsName.append("navtreedata.js");
writeToFile(jsName, jsStrBuf);
}
return true;
}
void generateHeaderForMisc()
{
//this file is expected when the environment is updated. so just create an empty file
StringBuffer jsName(CONFIGMGR_JSPATH);
jsName.append("refresh.js");
Owned<IFile> pFile = createIFile(jsName);
}
bool generateHeaders(const IPropertyTree* pEnv, IConstEnvironment* pConstEnv)
{
StringBuffer sbTemp;
generateHeadersFromEnv(pEnv, sbTemp, true);
generateHardwareHeaders(pEnv, sbTemp, true);
generateBuildHeaders(pEnv, true, sbTemp, true);
StringBuffer xPath;
xPath.append("Software/*");
Owned<IPropertyTreeIterator> iter2 = pEnv->getElements(xPath.str());
ForEach(*iter2)
{
IPropertyTree &agDef = iter2->query();
if (agDef.hasProp(XML_ATTR_BUILD) && agDef.hasProp(XML_ATTR_BUILDSET))
{
StringBuffer build;
StringBuffer buildset;
StringBuffer schemaPath;
StringBuffer jsName;
StringBuffer compName;
build = agDef.queryProp(XML_ATTR_BUILD);
buildset = agDef.queryProp(XML_ATTR_BUILDSET);
StringBuffer agName;
agDef.getName(agName);
if (!strcmp(agName.str(), XML_TAG_ESPSERVICE) || !strcmp(agName.str(), XML_TAG_PLUGINPROCESS))
compName.append(buildset);
else
compName.append(agName);
jsName.append(CONFIGMGR_JSPATH).append(compName).append(".js");
StringBuffer s;
s.append("./Programs/Build[@name='").append(build).append("']");
IPropertyTree *b = pEnv->queryPropTree(s.str());
if (b)
{
s.clear().append("BuildSet[@name='").append(buildset).append("']");
IPropertyTree *bs = b->queryPropTree(s.str());
IPropertyTree * pTree = loadSchema(b, bs, schemaPath, pConstEnv);
fprintf(stdout, "Loading schema file %s", schemaPath.str());
try
{
CGenerateJSFromXSD obj(pEnv, pTree, jsName, compName);
obj.generateHeaders();
}
catch(IException *E)
{
StringBuffer buf;
(E->errorMessage(buf).str());
printf("%s", buf.str());
E->Release();
}
}
}
}
generateHeaderForTopology(pEnv, sbTemp, true);
generateHeaderForDeployableComps(pEnv, sbTemp, true);
generateHeaderForMisc();
return true;
}
bool getComputersListWithUsage(const IPropertyTree* pEnv, StringBuffer& sbComputers, StringBuffer& sbFilter)
{
CComputerPicker cpick;
cpick.SetRootNode(pEnv);
sbComputers.clear();
toXML(cpick.getComputerTree(), sbComputers, false);
toXML(cpick.getFilterTree(), sbFilter, false);
return true;
}
bool handleRoxieOperation(IPropertyTree* pEnv, const char* cmd, const char* xmlStr)
{
CConfigEnvHelper configEnv(pEnv);
bool result = configEnv.handleRoxieOperation(cmd, xmlStr);
return result;
}
bool handleThorTopologyOp(IPropertyTree* pEnv, const char* cmd, const char* xmlStr, StringBuffer& sMsg)
{
CConfigEnvHelper configEnv(pEnv);
bool result = configEnv.handleThorTopologyOp(cmd, xmlStr, sMsg);
return result;
}
void addComponentToEnv(IPropertyTree* pEnv, const char* buildSet, StringBuffer& sbNewName, IPropertyTree* pCompTree)
{
CConfigEnvHelper configEnv(pEnv);
configEnv.addComponent(buildSet, sbNewName, pCompTree);
}
bool generateHeaderForComponent(const IPropertyTree* pEnv, IPropertyTree* pSchema, const char* compName)
{
try
{
StringBuffer jsName;
jsName.append(CONFIGMGR_JSPATH).append(compName).append(".js");
CGenerateJSFromXSD obj(pEnv, pSchema, jsName.str(), compName);
obj.generateHeaders();
return true;
}
catch(IException *E)
{
StringBuffer buf;
(E->errorMessage(buf).str());
printf("%s", buf.str());
E->Release();
}
return false;
}
void deleteRecursive(const char* path)
{
Owned<IFile> pDir = createIFile(path);
if (pDir->exists())
{
if (pDir->isDirectory())
{
Owned<IDirectoryIterator> it = pDir->directoryFiles(NULL, false, true);
ForEach(*it)
{
StringBuffer name;
it->getName(name);
StringBuffer childPath(path);
childPath.append(PATHSEPCHAR);
childPath.append(name);
deleteRecursive(childPath.str());
}
}
pDir->remove();
}
}
void getTabNameArray(const IPropertyTree* pEnv, IPropertyTree* pSchema, const char* compName, StringArray& strArray)
{
try
{
CGenerateJSFromXSD obj(pEnv, pSchema, "", compName);
obj.generateHeaders();
obj.getTabNameArray(strArray);
}
catch(IException *E)
{
StringBuffer buf;
(E->errorMessage(buf).str());
printf("%s", buf.str());
E->Release();
}
}
void getDefnPropTree(const IPropertyTree* pEnv, IPropertyTree* pSchema, const char* compName, IPropertyTree* pDefTree, StringBuffer xpathDefn)
{
try
{
CGenerateJSFromXSD obj(pEnv, pSchema, "", compName);
obj.getDefnPropTree(pDefTree, xpathDefn);
}
catch(IException *E)
{
StringBuffer buf;
(E->errorMessage(buf).str());
printf("%s", buf.str());
E->Release();
}
}
void getDefnString(const IPropertyTree* pEnv, IPropertyTree* pSchema, const char* compName, StringBuffer& compDefn, StringBuffer& viewChildNodes, StringBuffer& multiRowNodes)
{
try
{
CGenerateJSFromXSD obj(pEnv, pSchema, "", compName);
obj.getDefnString(compDefn, viewChildNodes, multiRowNodes);
}
catch(IException *E)
{
StringBuffer buf;
(E->errorMessage(buf).str());
printf("%s", buf.str());
E->Release();
}
}
bool checkComponentReferences(const IPropertyTree* pEnv,
IPropertyTree* pOrigNode,
const char* szName,
const char* xpath,
StringBuffer& sMsg,
const StringArray& attribArray,
const char* szNewName/*=NULL*/)
{
const IPropertyTree* pSoftware = pEnv->queryPropTree(XML_TAG_SOFTWARE);
// split xpath into 2 strings: one for component and the other for its childrens' xpath
// so we can report its name, if needed. For instance, if xpath is
// "Topology/EclServerProcess/EclAgentProcess" then create 2 separate xpaths:
// "Topology" and "EclServerProcess/EclAgentProcess" so we can report Topology's name.
//
StringBuffer xpath1;//component
const char* xpath2;//remaining
const char* pSlash = strchr(xpath, '/');
if (pSlash)
{
String str(xpath);
String* pStr = str.substring(0, strcspn(xpath, "/"));
xpath1.append(pStr->toCharArray());
delete pStr;
xpath2 = pSlash+1;
}
else
{
xpath1.append(xpath);
xpath2 = NULL;
}
const bool bEspProcess = !strcmp(pOrigNode->queryName(), XML_TAG_ESPPROCESS);
int nAttribs = attribArray.length();
Owned<IPropertyTreeIterator> iComp = pSoftware->getElements(xpath1);
ForEach(*iComp)
{
IPropertyTree* pComp = &iComp->query();
if (pComp == pOrigNode)//resolve circular dependency - don't check against the original node!
continue;
Owned<IPropertyTreeIterator> iter;
if (xpath2)
iter.setown(pComp->getElements(xpath2));
else
{
iComp->Link();
iter.setown(iComp.get());
}
ForEach(*iter)
{
pComp = &iComp->query(); //inner loop may have changed the component if xpath2 is NULL
if (pComp == pOrigNode)//resolve circular dependency - don't check against the original node!
continue;
IPropertyTree* pNode = &iter->query();
for (int i=0; i<nAttribs; i++)
{
const char* attribName = attribArray.item(i);
const char* szValue = pNode->queryProp(attribName);
if (!szValue)
continue;
bool bMatch;
if (bEspProcess)
{
const unsigned int len = strlen(szName);
bMatch = !strncmp(szValue, szName, len) && szValue[len] == '/';
}
else
bMatch = strcmp(szValue, szName)==0;
if (bMatch)
{
if (szNewName==NULL)
{
const char* szCompName = pComp->queryProp(XML_ATTR_NAME);
const char* szElemName = pComp->queryName();
sMsg.appendf("Component '%s' is referenced by %s %s component", szName, szCompName ? "the":"an instance of", szElemName);
if (szCompName)
sMsg.appendf(" '%s'", szCompName);
sMsg.append(".\nYou must remove all references before it can be deleted.");
return false;
}
else
{
if (bEspProcess)
{
StringBuffer sNewName(szNewName);
sNewName.append(szValue).appendf("%d", (int) strlen(szName));
pNode->setProp(attribName, sNewName);
}
else
pNode->setProp(attribName, szNewName);
}
}
}
}
if (xpath2==NULL)
break;
}
return true;
}
bool checkComponentReferences(const IPropertyTree* pEnv, IPropertyTree* pNode, const char* szPrevName, StringBuffer& sMsg, const char* szNewName/*=NULL*/)
{
const char* szProcess = pNode->queryName();
// A component may be referenced by other components with any attribute name
// (and not just @process), for e.g. @eclServer, @mySQL, @MySQL etc. The
// components are inter-twined with cross links amongst them and there is
// no way to figure them out dynamically generically based on just the
// schema etc. (we only load one schema at a time anyway).
// So we would hard code these rules for dependency checks based on current
// relationships until we figure out a better way to do the same in future.
// The drawback is that these rules will have to be kept in sync with the
// the introduction of newer relationships.
// We need to check for other components with different xpaths and each
// with possibly more than one attribute name so define an StringArray
// to store xpaths and another array of StringArray objects to hold list of
// attributes corresponding to the xpaths to be validated.
//
// This avoids multiple traversals of the xpath for multiple attribute names.
//
StringArray xpathArray;
StringArray attribArray[6];//we don't add attributes for more than 6 xpaths
//as for EspBinding below
int numXpaths = 0;
StringArray& attribs = attribArray[numXpaths++];
if (!strcmp(szProcess, XML_TAG_DALISERVERPROCESS))
{
xpathArray.append("*");
attribs.append("@daliServer");//EclServerProcess
attribs.append("@daliServers");
attribs.append("@daliservers");//DfuProcess
}
else if (!strcmp(szProcess, XML_TAG_ECLAGENTPROCESS))
{
xpathArray.append("Topology/Cluster/EclAgentProcess");
attribs.append("@process");
}
else if (!strcmp(szProcess, XML_TAG_ECLSERVERPROCESS))
{
xpathArray.append("*");
attribs.append("@eclServer");
xpathArray.append("Topology/EclServerProcess");
StringArray& attribs2 = attribArray[numXpaths++];
attribs2.append("@process");
}
else if (!strcmp(szProcess, XML_TAG_ECLCCSERVERPROCESS))
{
xpathArray.append("*");
attribs.append("@eclServer");
xpathArray.append("Topology/Cluster/EclCCServerProcess");
StringArray& attribs2 = attribArray[numXpaths++];
attribs2.append("@process");
}
else if (!strcmp(szProcess, XML_TAG_ECLSCHEDULERPROCESS))
{
xpathArray.append("*");
attribs.append("@eclScheduler");
xpathArray.append("Topology/Cluster/EclSchedulerProcess");
StringArray& attribs2 = attribArray[numXpaths++];
attribs2.append("@process");
}
else if (!strcmp(szProcess, XML_TAG_ESPSERVICE))
{
xpathArray.append("EspProcess/EspBinding");
attribs.append("@service");
}
else if (!strcmp(szProcess, "LDAPServerProcess"))
{
xpathArray.append("*");
attribs.append("@ldapServer");
attribs.append("ldapSecurity/@server");//under EclServer
xpathArray.append("EspProcess/Authentication");
StringArray& attribs2 = attribArray[numXpaths++];
attribs2.append("@ldapServer");
}
else if (!strcmp(szProcess, "MySQLProcess"))
{
xpathArray.append("*");
attribs.append("@mySql");
attribs.append("@MySql");
attribs.append("@MySQL");
attribs.append("@database");
}
else if (!strcmp(szProcess, XML_TAG_PLUGINPROCESS))
{
xpathArray.append("EclServerProcess/PluginRef");
attribs.append("@process");
}
else if (!strcmp(szProcess, "RoxieCluster"))
{
xpathArray.append("Topology/Cluster/RoxieCluster");
attribs.append("@process");
}
else if (!strcmp(szProcess, XML_TAG_THORCLUSTER))
{
xpathArray.append("Topology/Cluster/ThorCluster");
attribs.append("@process");
}
else if (!strcmp(szProcess, XML_TAG_ESPBINDING) || !strcmp(szProcess, XML_TAG_ESPPROCESS))
{
xpathArray.append(XML_TAG_ESPSERVICE);
attribs.append("@eclWatch"); //ws_ecl
attribs.append("@attributeServer");//ws_ecl and ws_roxieconfig
xpathArray.append("EspService/WsEcl");//ws_facts and ws_distrix
attribArray[numXpaths++].append("@espBinding");
xpathArray.append("EspService/SourceAttributeServer");//ws_roxieconfig
attribArray[numXpaths++].append("@espBinding");
xpathArray.append(XML_TAG_ECLSERVERPROCESS);
attribArray[numXpaths++].append("@eclWatch");
xpathArray.append("DfuplusProcess");
attribArray[numXpaths++].append("@server");
xpathArray.append("RegressionSuite");
StringArray& attribs2 = attribArray[numXpaths++];
attribs2.append("@server");
attribs2.append("@roxieconfig");
}
else
{
xpathArray.append("*");
attribs.append(XML_ATTR_NAME);
}
bool rc = true;
for (int i=0; i<numXpaths && rc; i++)
rc = checkComponentReferences(pEnv, pNode, szPrevName, xpathArray.item(i), sMsg, attribArray[i], szNewName);
return rc;
}
const char* getUniqueName(const IPropertyTree* pEnv, StringBuffer& sName, const char* processName, const char* category)
{
//if the name ends in _N (where N is a number) then ignore _N to avoid duplicating
//number suffix as in _N_M
//
StringBuffer sPrefix = sName;
const char* pdx = strrchr(sName.str(), '_');
if (pdx)
{
StringBuffer num(sName);
char* pszNum = num.detach();
char *token = NULL;
j_strtok_r(pszNum, "_", &token);
if (strspn(token, "0123456789") == strlen(token))
{
sName.remove(pdx - sName.str(), sName.length() - (pdx - sName.str()));
sPrefix.clear().append(sName);
}
else
{
int len = sPrefix.length();
if (len > 0 && endsWith(sPrefix.str(), "_")) //ends with '_'
sPrefix = sPrefix.remove(sPrefix.length() - 1, 1); //lose it
}
free(pszNum);
}
StringBuffer xpath;
xpath.appendf("./%s/%s[@name='%s']", category, processName, sName.str());
int iIdx = 2;
while (pEnv->queryPropTree(xpath))
{
sName.clear().appendf("%s_", sPrefix.str()).append(iIdx);
xpath.clear().appendf("./%s/%s[@name='%s']", category, processName, sName.str());
iIdx++;
}
return sName.str();
}
const char* getUniqueName2(const IPropertyTree* pEnv, StringBuffer& sName, const char* processName, const char* keyAttrib)
{
//if the name ends in _N (where N is a number) then ignore _N to avoid duplicating
//number suffix as in _N_M
//
StringBuffer sPrefix = sName;
const char* pdx = strrchr(sName.str(), '_');
if (pdx)
{
StringBuffer num(sName);
char* pszNum = num.detach();
char *token = NULL;
j_strtok_r(pszNum, "_", &token);
if (strspn(token, "0123456789") == strlen(token))
{
sName.remove(pdx - sName.str(), sName.length() - (pdx - sName.str()));
sPrefix.clear().append(sName);
}
else
{
int len = sPrefix.length();
if (len > 0 && endsWith(sPrefix.str(), "_")) //ends with '_'
sPrefix = sPrefix.remove(sPrefix.length() - 1, 1); //lose it
}
free(pszNum);
}
StringBuffer xpath;
xpath.appendf("./%s[%s='%s']", processName, keyAttrib, sName.str());
int iIdx = 2;
while (pEnv->queryPropTree(xpath))
{
sName.clear().appendf("%s_", sPrefix.str()).append(iIdx);
xpath.clear().appendf("./%s[%s='%s']", processName, keyAttrib, sName.str());
iIdx++;
}
return sName.str();
}
void getCommonDir(const IPropertyTree* pEnv, const char* catType, const char* buildSetName, const char* compName, StringBuffer& sbVal)
{
const IPropertyTree* pEnvDirs = pEnv->queryPropTree("Software/Directories");
const char* commonDirName = pEnvDirs->queryProp(XML_ATTR_NAME);
StringBuffer xpath;
xpath.appendf("Category[@name='%s']", catType);
Owned<IPropertyTreeIterator> iterCats = pEnvDirs->getElements(xpath.str());
ForEach (*iterCats)
{
IPropertyTree* pCat = &iterCats->query();
StringBuffer sb("Override");
sb.appendf("[@component='%s'][@instance='%s']",buildSetName, compName);
IPropertyTree* pCatOver = pCat->queryPropTree(sb.str());
if (!pCatOver)
{
sb.clear().appendf("Override[@instance='%s']", compName);
Owned<IPropertyTreeIterator> overIter = pCat->getElements(sb.str());
ForEach(*overIter)
{
IPropertyTree* pTmp = &overIter->query();
if (!pTmp->queryProp("@component"))
{
pCatOver = pTmp;
sbVal.clear().append(pCatOver->queryProp("@dir"));
break;
}
}
if (!pCatOver)
sbVal.clear().append(pCat->queryProp("@dir"));
}
else
sbVal.clear().append(pCatOver->queryProp("@dir"));
sbVal.replaceString("[COMPONENT]",buildSetName);
sbVal.replaceString("[INST]", compName);
sbVal.replaceString("[NAME]", commonDirName);
break;
}
}
IPropertyTree* getNewRange(const IPropertyTree* pEnv, const char* prefix, const char* domain, const char* cType, const char* startIP, const char* endIP)
{
StringBuffer sXML;
int nCount = 0;
IpAddress start(startIP);
IpAddress end(endIP);
unsigned s, e;
start.getNetAddress(sizeof(s),&s);
end.getNetAddress(sizeof(e),&e);
if( s > e)
{
s^=e^=s^=e;
const char* temp = startIP;
startIP = endIP;
endIP= temp;
}
if (start.isNull())
throw MakeStringException(-1, "Invalid start ip address: %s", startIP);
if (end.isNull())
throw MakeStringException(-1, "Invalid stop ip address: %s", endIP);
if ((s << 8) != (e << 8))
throw MakeStringException(-1, "Start and stop IP addresses must be within same subnet");
// Create string for common attributes
StringBuffer attr, val, sAttributes;
attr.appendf(" %s=\"%s\"", &XML_ATTR_DOMAIN[1], domain);
attr.appendf(" %s=\"%s\"", &XML_ATTR_COMPUTERTYPE[1], cType);
IpAddress range;
StringBuffer iprange(startIP);
String str(startIP);
iprange.append("-").append(endIP + str.lastIndexOf('.') + 1);
range.ipsetrange(iprange.str());
StringBuffer sNode("<"XML_TAG_HARDWARE">"), sName, sIP;
int count = (e >> 24) - (s >> 24) + 1;
nCount = count;
while (count--)
{
range.getIpText(sIP.clear());
unsigned x;
range.getNetAddress(sizeof(x),&x);
sName.clear().appendf("%s%03d%03d", prefix, (x >> 16) & 0xFF, (x >> 24) & 0xFF);
sNode.appendf("<"XML_TAG_COMPUTER" %s=\"%s\" %s=\"%s\" %s/>",
&XML_ATTR_NAME[1], getUniqueName(pEnv, sName, XML_TAG_COMPUTER, XML_TAG_HARDWARE),
&XML_ATTR_NETADDRESS[1], sIP.str(),
attr.str());
range.ipincrement(1);
}
if (sNode.length() > 10)
{
sNode.append("</"XML_TAG_HARDWARE">");
IPropertyTree* pTree = createPTreeFromXMLString(sNode);
return pTree;
}
else
return NULL;
}
bool ensureUniqueName(const IPropertyTree* pEnv, IPropertyTree* pParentNode, const char* sectionName, const char* newName)
{
//this function finds out nodes with a given name in a section (Hardware, Software,
//Programs or Data
//
bool bOriginalFound = false;
bool bDuplicateFound = false;
StringBuffer xpath(sectionName);
xpath.append("/").append(pParentNode->queryName());
Owned<IPropertyTreeIterator> iter = pEnv->getElements(xpath);
ForEach(*iter)
{
IPropertyTree* pNode = &iter->query();
const char* name = pNode->queryProp("@name");
if (name)
{
if (pNode == pParentNode)
bOriginalFound = true;
else
if (!strcmp(name, newName))
{
bDuplicateFound = true;//cannot exit loop prematurely since this
if (bOriginalFound) //until this is set
break;
}
}
}
if (bOriginalFound && bDuplicateFound)
{
throw MakeStringException(-1, "Another %s already exists with the same name!\nPlease specify a unique name",
pParentNode->queryName());
}
return true;
}
bool ensureUniqueName(const IPropertyTree* pEnv, IPropertyTree* pParentNode, const char* szText)
{
if (!strcmp(szText, "Directories"))
throw MakeStringException(-1, "%s already exists!\nPlease specify a unique name", szText);
bool rc = ensureUniqueName(pEnv, pParentNode, "Software", szText) &&
ensureUniqueName(pEnv, pParentNode,"Hardware", szText) &&
ensureUniqueName(pEnv, pParentNode,"Programs", szText);
return rc;
}
const char* expandXPath(StringBuffer& xpath, IPropertyTree* pNode, IPropertyTree* pParentNode, int position)
{
StringBuffer xpathOut;
StringBuffer subxpath = strpbrk(xpath.str(), "/=");
if (!strcmp(subxpath.str(), ".."))
{
int skip = 2;
if (xpath.length() > 2 && xpath.charAt(2) == '/')
skip++;
subxpath = strpbrk(xpath.str() + skip, "/=]");
xpathOut.append(expandXPath(subxpath, pParentNode, NULL, -1));
}
else
if (!strcmp(subxpath.str(), "position()"))
{
char sPos[32];
itoa(position, sPos, 10);
StringBuffer sb(xpathOut.str() + position);
xpathOut.clear().append(sb);
}
else
if (subxpath.length() && subxpath.charAt(0) == '@')
xpathOut.append("`").append(pNode->queryProp(subxpath.str())).append("`");
xpath.clear().append(xpathOut);
return xpath;
}
bool xsltTransform(const StringBuffer& xml, const char* sheet, IProperties *params, StringBuffer& ret)
{
if (!checkFileExists(sheet))
throw MakeStringException(-1, "Could not find stylesheet %s",sheet);
Owned<IXslProcessor> proc = getXslProcessor();
Owned<IXslTransform> trans = proc->createXslTransform();
trans->setXmlSource(xml.str(), xml.length());
trans->loadXslFromFile(sheet);
if (params)
{
Owned<IPropertyIterator> it = params->getIterator();
for (it->first(); it->isValid(); it->next())
{
const char *key = it->getPropKey();
//set parameter in the XSL transform skipping over the @ prefix, if any
const char* paramName = *key == '@' ? key+1 : key;
trans->setParameter(paramName, StringBuffer().append('\'').append(params->queryProp(key)).append('\'').str());
}
}
trans->transform(ret);
return true;
}
bool onChangeAttribute(const IPropertyTree* pEnv,
IConstEnvironment* pConstEnv,
const char* attrName,
IPropertyTree* pOnChange,
IPropertyTree*& pNode,
IPropertyTree* pParentNode,
int position,
const char* szNewValue,
const char* prevValue,
const char* buildSet)
{
bool rc = false;
StringBuffer sbAttr("@");
sbAttr.append(attrName);
try
{
IPropertyTree* pComponent = pNode;
const char* xslt = pOnChange->queryProp("xslt");
StringBuffer xpath("Programs/Build");
IPropertyTree *pBuild = pEnv->queryPropTree(xpath.str());
if (pBuild)
{
xpath.clear().append("BuildSet[@name='").append(buildSet).append("']");
IPropertyTree *pBuildSet = pBuild->queryPropTree(xpath.str());
StringBuffer sXsltPath;
if (pBuildSet && connectBuildSet(pBuild, pBuildSet, sXsltPath, pConstEnv))
{
sXsltPath.append(xslt);
Owned<IProperties> params(createProperties());
params->setProp("@attribName", attrName);
params->setProp("@oldValue", prevValue);
params->setProp("@newValue", szNewValue);
xpath = pOnChange->queryProp("xpath");
if (xpath.length())
{
/* sample xpath is as follows so expand it:
RemoteNScfg[@espBinding=current()/../@espBinding]/Configuration[current()/position()]
*/
const char* pos;
while ((pos=strstr(xpath.str(), "current()/")) != NULL)
{
const char* pos2 = pos + sizeof("current()/")-1;
StringBuffer subxpath(strpbrk(strstr(xpath.str(), pos2), "=]"));
const int len = subxpath.length();
//xpath = xpath.Left(pos) + expandXPath(subxpath, pNode, pParentNode, position) + xpath.Mid(pos2+len);
}
params->setProp("@xpath", xpath);
}
const char* source = pOnChange->queryProp("xml");
IPropertyTree* pSourceNode = pNode;
if (source && *source)//default is just the element whose attribute got changed
{
if (!stricmp(source, "component"))
pSourceNode = pComponent;
else
throw MakeStringException(0, "Invalid source specified.");
}
StringBuffer xml;
toXML(pSourceNode, xml);
StringBuffer ret;
if (xsltTransform(xml, sXsltPath, params, ret))
{
Owned<IPropertyTree> result = createPTreeFromXMLString(ret.str());
Owned<IAttributeIterator> iAttr = result->getAttributes();
ForEach(*iAttr)
{
const char* attrName = iAttr->queryName();
if (!pSourceNode->hasProp(attrName))
pSourceNode->addProp(attrName, iAttr->queryValue());
else
pSourceNode->setProp(attrName, iAttr->queryValue());
}
rc = true;
}
}
}
}
catch (IException* e)
{
pNode->setProp(sbAttr.str(), prevValue);
StringBuffer sMsg;
e->errorMessage(sMsg);
throw e;
}
catch(...)
{
pNode->setProp(sbAttr.str(), prevValue);
throw;
}
if (!rc)
pNode->setProp(sbAttr.str(), prevValue);
return rc;
}
void UpdateRefAttributes(IPropertyTree* pEnv, const char* szPath, const char* szAttr, const char* szOldVal, const char* szNewVal)
{
Owned<IPropertyTreeIterator> iter = pEnv->getElements(szPath);
for (iter->first(); iter->isValid(); iter->next())
{
IPropertyTree& node = iter->query();
const char* szVal = node.queryProp(szAttr);
if (szVal && strcmp(szVal, szOldVal)==0)
node.setProp(szAttr, szNewVal);
}
}
void addInstanceToCompTree(const IPropertyTree* pEnvRoot,const IPropertyTree* pInstance,StringBuffer& dups,StringBuffer& resp,IConstEnvironment* pConstEnv)
{
StringBuffer buildSetPath, xpath;
const char* buildSet = pInstance->queryProp(XML_ATTR_BUILDSET);
const char* compName = pInstance->queryProp("@compName");
xpath.appendf("./Programs/Build/BuildSet[@name=\"%s\"]", buildSet);
Owned<IPropertyTreeIterator> buildSetIter = pEnvRoot->getElements(xpath.str());
buildSetIter->first();
IPropertyTree* pBuildSet = &buildSetIter->query();
const char* processName = pBuildSet->queryProp(XML_ATTR_PROCESS_NAME);
Owned<IPropertyTree> pSchema = loadSchema(pEnvRoot->queryPropTree("./Programs/Build[1]"), pBuildSet, buildSetPath, pConstEnv);
xpath.clear().appendf("./Software/%s[@name=\"%s\"]", processName, compName);
IPropertyTree* pCompTree = pEnvRoot->queryPropTree(xpath.str());
Owned<IPropertyTreeIterator> iterInst = pInstance->getElements("*");
bool bAdded = false;
ForEach(*iterInst)
{
IPropertyTree& pComputer = iterInst->query();
xpath.clear().appendf("./Hardware/Computer[@name=\"%s\"]", pComputer.queryProp(XML_ATTR_NAME));
IPropertyTree* pComputerNode = pEnvRoot->queryPropTree(xpath.str());
xpath.clear().appendf("Instance[@netAddress=\"%s\"]", pComputerNode->queryProp(XML_ATTR_NETADDRESS));
if (pCompTree->queryPropTree(xpath.str()))
{
dups.appendf("\n%s", pComputerNode->queryProp(XML_ATTR_NETADDRESS));
continue;
}
IPropertyTree* pNode = pCompTree->addPropTree(XML_TAG_INSTANCE, createPTree());
if (pSchema)
{
Owned<IPropertyTreeIterator> iter = pSchema->getElements("xs:element/xs:complexType/xs:sequence/xs:element[@name=\"Instance\"]/xs:complexType/xs:attribute");
ForEach(*iter)
{
IPropertyTree &attr = iter->query();
StringBuffer attrName("@");
attrName.append(attr.queryProp(XML_ATTR_NAME));
// we try to pull @computer and @netAddress from computerNode. Others come from default values in schema (if supplied)
const char *szAttrib;
StringBuffer sb;
if (!strcmp(attrName.str(), XML_ATTR_COMPUTER))
{
szAttrib = pComputerNode->queryProp(XML_ATTR_NAME);
if (!bAdded)
{
bAdded = true;
resp.append(szAttrib);
}
}
else if (!strcmp(attrName.str(), XML_ATTR_NETADDRESS))
szAttrib = pComputerNode->queryProp(XML_ATTR_NETADDRESS);
else if (!strcmp(attrName.str(), XML_ATTR_DIRECTORY))
{
StringBuffer rundir;
if (!getConfigurationDirectory(pEnvRoot->queryPropTree("Software/Directories"), "run", processName, compName, rundir))
sb.clear().appendf(RUNTIME_DIR"/%s", compName);
else
sb.clear().append(rundir);
szAttrib = sb.str();
}
else
szAttrib = attr.queryProp("@default");
pNode->addProp(attrName.str(), szAttrib);
}
}
}
int nCount = 1;
xpath.clear().appendf("Instance");
Owned<IPropertyTreeIterator> iter = pCompTree->getElements(xpath.str());
StringBuffer sName;
ForEach(*iter)
{
sName.clear().append("s").append(nCount);
iter->query().setProp(XML_ATTR_NAME, sName.str());
nCount++;
}
}
void formIPList(const char* ip, StringArray& formattedIpList)
{
StringBuffer ipList(ip);
if(ipList.length())
{
ipList.replace('\n',';');
if(ipList.charAt(ipList.length()-1) == ';')
ipList.setCharAt((ipList.length()-1),' ');
StringArray sArray;
sArray.appendList(ipList, ";");
if(sArray.ordinality() > 0 )
{
for( unsigned i = 0; i < sArray.ordinality() ; i++)
{
const char* ip = sArray.item(i);
if(ip && *ip)
{
if( strchr(ip, '-') != 0 )
{
StringArray rangeArr, commIPPart ;
StringBuffer comip;
rangeArr.appendList(ip, "-");
if( rangeArr.ordinality() == 2 )
{
unsigned endAddr = atoi(rangeArr.item(1));
//to get common part of IP
commIPPart.appendList(rangeArr.item(0),".");
StringBuffer newip;
if(commIPPart.ordinality() == 4)
{
unsigned startAddr = atoi(commIPPart.item(3));
comip.clear().append(commIPPart.item(0)).append(".").append(commIPPart.item(1)).append(".").append(commIPPart.item(2)).append(".");
if( startAddr > endAddr)
startAddr^=endAddr^=startAddr^=endAddr;
while(startAddr <= endAddr)
{
newip.clear().append(comip).append(startAddr);
startAddr++;
formattedIpList.appendUniq(newip);
}
}
}
}
else
{
formattedIpList.appendUniq(ip);
}
}
}
}
}
else
throw MakeStringException(-1, "List of IP Addresses cannot be empty");
}
void buildEnvFromWizard(const char * wizardXml, const char* service,IPropertyTree* cfg, StringBuffer& envXml, MapStringTo<StringBuffer>* dirMap)
{
if(wizardXml && *wizardXml)
{
CWizardInputs wizardInputs(wizardXml, service, cfg, dirMap);
wizardInputs.setEnvironment();
wizardInputs.generateEnvironment(envXml);
if(envXml.length() == 0)
throw MakeStringException(-1, "Failed to generated the environment xml for unknown reason");
}
else
throw MakeStringException(-1, "User inputs are needed to generate the environment");
}
void runScript(StringBuffer& output, StringBuffer& errMsg, const char* pathToScript)
{
StringBuffer cmdLine;
if(checkFileExists(pathToScript))
{
char buffer[128];
cmdLine.clear().append(pathToScript);
#ifdef _WINDOWS
FILE *fp = _popen(cmdLine.str(), "r");
#else
FILE *fp = popen(cmdLine.str(), "r");
#endif
if(fp != NULL)
{
while ( !feof(fp) )
{
if( fgets(buffer, 128, fp))
{
output.append(buffer);
}
}
if(ferror(fp))
errMsg.clear().append("Some file operation error");
#ifdef _WINDOWS
_pclose(fp);
#else
pclose(fp);
#endif
if( output.length() == 0)
errMsg.clear().append("No IPAddresses found for environment.");
}
else
errMsg.clear().append("Could not open or run autodiscovery script ").append(pathToScript);
}
else
throw MakeStringException(-1,"The Script [%s] for getting IP addresses for environment does not exist", pathToScript);
}
bool validateIPS(const char* ipAddressList)
{
StringArray ipFormatted ;
formIPList(ipAddressList,ipFormatted);
if(ipFormatted.ordinality() > 0)
{
for (unsigned i = 0; i < ipFormatted.ordinality(); i++)
{
const char* ip = ipFormatted.item(i);
unsigned x ;
IpAddress ipaddr(ip);
ipaddr.getNetAddress(sizeof(x), &x);
if ( ipaddr.isNull())
throw MakeStringException(-1, "Invalid ip address: %s", ip);
}
}
else
throw MakeStringException(-1, "List for IP Addresses cannot be empty");
return true;
}
void getSummary(const IPropertyTree* pEnvRoot, StringBuffer& respXmlStr, bool prepareLink)
{
if(pEnvRoot)
{
StringBuffer xpath, compName, ipAssigned, computerName, linkString, buildSetName;
Owned<IPropertyTree> pSummaryTree = createPTree("ComponentList");
IPropertyTree* pSWCompTree = pEnvRoot->queryPropTree(XML_TAG_SOFTWARE);
if(pSWCompTree)
{
Owned<IPropertyTreeIterator> swCompIter = pSWCompTree->getElements("*");
StringArray espServiceArr;
ForEach(*swCompIter)
{
bool instanceFound = false;
IPropertyTree* pCompTree = &swCompIter->query();
if(pCompTree)
{
ipAssigned.clear();
compName.clear().append(pCompTree->queryProp(XML_ATTR_NAME));
buildSetName.clear().append(pCompTree->queryProp(XML_ATTR_BUILDSET));
xpath.clear().append("./Instance");
Owned<IPropertyTreeIterator> instanceIter = pCompTree->getElements(xpath.str());
ForEach(*instanceIter)
{
instanceFound = true;
IPropertyTree* pInstance = &instanceIter->query();
if(pInstance)
{
const char* netAddr = pInstance->queryProp(XML_ATTR_NETADDRESS);
if(netAddr && *netAddr)
{
ipAssigned.append(netAddr);
ipAssigned.append(",");
}
}
}
if(!strcmp(pCompTree->queryName(), XML_TAG_ESPPROCESS))
{
if(ipAssigned.length())
{
Owned<IPropertyTreeIterator> espSerIter = pCompTree->getElements("./"XML_TAG_ESPBINDING);
ForEach(*espSerIter)
{
IPropertyTree* pEspBinding = &espSerIter->query();
const char* serviceName = pEspBinding->queryProp(XML_ATTR_SERVICE);
const char* port = pEspBinding->queryProp(XML_ATTR_PORT);
const char* protocol = pEspBinding->queryProp(XML_ATTR_PROTOCOL);
const char* buildset = NULL;
xpath.clear().appendf("./%s/%s[%s=\"%s\"]", XML_TAG_SOFTWARE, XML_TAG_ESPSERVICE, XML_ATTR_NAME, serviceName);
IPropertyTree* pEspService = pEnvRoot->queryPropTree(xpath.str());
if(pEspService)
buildset = pEspService->queryProp(XML_ATTR_BUILDSET);
if(serviceName && *serviceName && port && *port)
{
if(ipAssigned.length() && ipAssigned.charAt(ipAssigned.length()-1) == ',')
ipAssigned.setCharAt((ipAssigned.length()-1),' ');
linkString.clear().appendf("%s-%s-", serviceName, (( buildset && *buildset ) ? buildset: ""));
if(prepareLink)
linkString.appendf("<a href=\"%s://%s:%s\"/>%s://%s:%s</a>", ( (protocol && *protocol) ? protocol :"http" ), (ipAssigned.trim()).str(), port, ( (protocol && *protocol) ? protocol :"http" ), (ipAssigned.trim()).str(), port );
else
linkString.appendf("%s", port);
espServiceArr.append(linkString);
}
}
}
}
if(!instanceFound && (strcmp(pCompTree->queryName(), XML_TAG_ROXIECLUSTER) != 0 && strcmp(pCompTree->queryName(), XML_TAG_THORCLUSTER) != 0))
{
if(pCompTree->hasProp(XML_ATTR_COMPUTER))
{
xpath.clear().appendf("./Hardware/%s/[%s=\"%s\"]", XML_TAG_COMPUTER, XML_ATTR_NAME, pCompTree->queryProp(XML_ATTR_COMPUTER));
IPropertyTree* pHardware = pEnvRoot->queryPropTree(xpath.str());
if(pHardware)
ipAssigned.clear().append(pHardware->queryProp(XML_ATTR_NETADDRESS));
}
}
else if(!strcmp(pCompTree->queryName(), XML_TAG_ROXIECLUSTER))
{
IPropertyTree* pCluster = pEnvRoot->queryPropTree("./Software/RoxieCluster");
if(pCluster)
{
compName.clear().append(pCluster->queryProp("@name"));
xpath.clear().append("./RoxieServerProcess");
Owned<IPropertyTreeIterator> serverIter = pCluster->getElements(xpath.str());
ForEach(*serverIter)
{
IPropertyTree* pServer = &serverIter->query();
const char* netAddr = pServer->queryProp(XML_ATTR_NETADDRESS);
if(netAddr && *netAddr)
{
ipAssigned.append(netAddr).append(",");
}
}
}
}
else if(!strcmp(pCompTree->queryName(), XML_TAG_THORCLUSTER))
{
IPropertyTree* pCluster = pEnvRoot->queryPropTree("./Software/ThorCluster");
if(pCluster)
{
compName.clear().append(pCluster->queryProp("@name"));
IPropertyTree* pMaster = pCluster->queryPropTree("./ThorMasterProcess");
if(pMaster)
{
computerName.clear().append(pMaster->queryProp(XML_ATTR_COMPUTER));
if(computerName.length())
{
xpath.clear().appendf("./Hardware/%s/[%s=\"%s\"]", XML_TAG_COMPUTER, XML_ATTR_NAME, computerName.str());
IPropertyTree* pHardware = pEnvRoot->queryPropTree(xpath.str());
if(pHardware)
ipAssigned.clear().append(pHardware->queryProp(XML_ATTR_NETADDRESS)).append(",");
}
}
Owned<IPropertyTreeIterator> serverIter = pCluster->getElements("./ThorSlaveProcess");
ForEach(*serverIter)
{
IPropertyTree* pServer = &serverIter->query();
computerName.clear().append(pServer->queryProp(XML_ATTR_COMPUTER));
if(computerName.length())
{
xpath.clear().appendf("./Hardware/%s/[%s=\"%s\"]", XML_TAG_COMPUTER, XML_ATTR_NAME, computerName.str());
IPropertyTree* pHardware = pEnvRoot->queryPropTree(xpath.str());
if(pHardware)
ipAssigned.append(pHardware->queryProp(XML_ATTR_NETADDRESS)).append(",");
}
}
}
}
if(ipAssigned.length() && ipAssigned.charAt(ipAssigned.length()-1) == ',')
ipAssigned.setCharAt((ipAssigned.length()-1),' ');
if(ipAssigned.length() && compName.length())
{
IPropertyTree* pComponentType = pSummaryTree->addPropTree("Component", createPTree("Component"));
pComponentType->addProp("@name", compName.str());
pComponentType->addProp("@netaddresses", ipAssigned.str());
pComponentType->addProp("@buildset", ( buildSetName.length() ? buildSetName.str(): ""));
pComponentType->addProp("@espservice", "false");
}
}
}
if(espServiceArr.length() > 0)
{
ForEachItemIn(x, espServiceArr)
{
linkString.clear().append(espServiceArr.item(x));
StringArray sArray;
sArray.appendList(linkString.str(), "-");
if(sArray.ordinality() == 3)
{
IPropertyTree* pEspServiceType = pSummaryTree->addPropTree("Component", createPTree("Component"));
pEspServiceType->addProp("@name", sArray.item(0));
pEspServiceType->addProp("@buildset", sArray.item(1));
pEspServiceType->addProp("@netaddresses", sArray.item(2));
pEspServiceType->addProp("@espservice", "true");
}
}
}
}
if(pSummaryTree)
toXML(pSummaryTree,respXmlStr);
}
else
throw MakeStringException(-1, "Environment does not have any configuration information");
}
void mergeAttributes(IPropertyTree* pTo, IPropertyTree* pFrom)
{
if (!pFrom)
return;
Owned<IAttributeIterator> iAttr = pFrom->getAttributes();
ForEach(*iAttr)
{
const char* attrName = iAttr->queryName();
if (!pTo->hasProp(attrName))
pTo->addProp(attrName, iAttr->queryValue());
}
}
void addEspBindingInformation(const char* xmlArg, IPropertyTree* pEnvRoot, StringBuffer& sbNewName, IConstEnvironment* pEnvironment,
const IPropertyTree* pCfg, const char* serviceName)
{
Owned<IPropertyTree> pBindings = createPTreeFromXMLString(xmlArg && *xmlArg ? xmlArg : "<EspServiceBindings/>");
const char* type = pBindings->queryProp(XML_ATTR_TYPE);
const char* espName = pBindings->queryProp("@compName");
StringBuffer xpath;
xpath.append("./Programs/Build/BuildSet[@processName=\"EspProcess\"]");
Owned<IPropertyTreeIterator> buildSetIter = pEnvRoot->getElements(xpath.str());
buildSetIter->first();
IPropertyTree* pBuildSet = &buildSetIter->query();
const char* buildSetName = pBuildSet->queryProp(XML_ATTR_NAME);
const char* processName = pBuildSet->queryProp(XML_ATTR_PROCESS_NAME);
StringBuffer buildSetPath;
Owned<IPropertyTree> pSchema = loadSchema(pEnvRoot->queryPropTree("./Programs/Build[1]"), pBuildSet, buildSetPath, pEnvironment);
xpath.clear().appendf("./Software/%s[@name='%s']", processName, espName);
Owned<IPropertyTreeIterator> iterItems = pBindings->getElements("Item");
bool flag = false;
ForEach (*iterItems)
{
flag = true;
IPropertyTree* pItem = &iterItems->query();
const char* bindingName = pItem->queryProp(XML_ATTR_NAME);
const char* params = pItem->queryProp("@params");
StringBuffer decodedParams(params);
decodedParams.replaceString("::", "\n");
Owned<IProperties> pParams = createProperties();
pParams->loadProps(decodedParams.str());
const char* pszCompType = pParams->queryProp("pcType");
const char* pszCompName = pParams->queryProp("pcName");
const char* pszSubType = pParams->queryProp("subType");
const char* pszSubTypeKey = pParams->queryProp("subTypeKey");
if (strcmp(type, XML_TAG_ESPBINDING) && bindingName)
xpath.appendf("/EspBinding[@name='%s']", bindingName);
else if (pszSubType && *pszSubType)
{
String subType(pszSubType);
int idx = subType.lastIndexOf('/');
if (idx > 0)
{
String* tmpstr = subType.substring(0, idx);
xpath.append("/").append(*tmpstr);
delete tmpstr;
}
}
IPropertyTree* pEspService = pEnvRoot->queryPropTree(xpath.str());
IPropertyTree* pCompTree = generateTreeFromXsd(pEnvRoot, pSchema, processName, buildSetName, pCfg, serviceName);
StringBuffer sb(type);
if (!strncmp(sb.str(), "_", 1))
sb.remove(0, 1);
if (!strcmp(type, XML_TAG_ESPBINDING))
{
StringBuffer sbNewName(XML_TAG_ESPBINDING);
xpath.clear().appendf("%s[@name='%s']/EspBinding", processName, espName);
getUniqueName(pEnvRoot, sbNewName, xpath.str(), XML_TAG_SOFTWARE);
xpath.clear().append(sb.str()).append("/").append(XML_ATTR_NAME);
pCompTree->setProp(xpath.str(), sbNewName);
}
if (pEspService && pCompTree)
pEspService->addPropTree(sb.str(), pCompTree->queryPropTree(sb.str()));
//If we are adding, just consider the first selection.
break;
}
if (!flag)
{
IPropertyTree* pEspService = pEnvRoot->queryPropTree(xpath.str());
IPropertyTree* pCompTree = generateTreeFromXsd(pEnvRoot, pSchema, processName, buildSetName, pCfg, serviceName);
StringBuffer sbNewName(XML_TAG_ESPBINDING);
xpath.clear().appendf("%s[@name='%s']/EspBinding", processName, espName);
getUniqueName(pEnvRoot, sbNewName, xpath.str(), XML_TAG_SOFTWARE);
xpath.clear().append(XML_TAG_ESPBINDING).append("/").append(XML_ATTR_NAME);
pCompTree->setProp(xpath.str(), sbNewName);
if (pEspService && pCompTree)
pEspService->addPropTree(XML_TAG_ESPBINDING, pCompTree->queryPropTree(XML_TAG_ESPBINDING));
}
}
bool updateDirsWithConfSettings(IPropertyTree* pEnvRoot, IProperties* pParams, bool ovrLog, bool ovrRun)
{
bool ret = false;
const char* rundir = pEnvRoot->queryProp("Software/Directories/Category[@name='run']/@dir");
StringBuffer sbdir;
if (rundir && ovrRun)
{
sbdir.clear().append(rundir);
sbdir.replaceString("[NAME]", pParams->queryProp("blockname"));
String str(sbdir.str());
if (!str.startsWith(pParams->queryProp("runtime")))
{
StringBuffer sb;
if (str.indexOf('[') > 0)
sb.append(pParams->queryProp("runtime")).append(PATHSEPCHAR).append(sbdir.str() + str.indexOf('['));
else
sb.append(str.toCharArray());
pEnvRoot->setProp("Software/Directories/Category[@name='run']/@dir", sb.str());
ret = true;
}
}
const char* logdir = pEnvRoot->queryProp("Software/Directories/Category[@name='log']/@dir");
if (logdir && ovrLog)
{
sbdir.clear().append(logdir);
sbdir.replaceString("[NAME]", pParams->queryProp("blockname"));
String str(sbdir.str());
if (!str.startsWith(pParams->queryProp("log")))
{
StringBuffer sb;
if (str.indexOf('[') > 0)
sb.append(pParams->queryProp("log")).append(PATHSEPCHAR).append(sbdir.str() + str.indexOf('['));
else
sb.append(str.toCharArray());
pEnvRoot->setProp("Software/Directories/Category[@name='log']/@dir", sb.str());
ret = true;
}
}
return ret;
}
//returns temp path that ends with path sep
//
#ifdef _WIN32
extern DWORD getLastError() { return ::GetLastError(); }
void getTempPath(char* tempPath, unsigned int bufsize, const char* subdir/*=NULL*/)
{
::GetTempPath(bufsize, tempPath);
::GetLongPathName(tempPath, tempPath, bufsize);
if (subdir && *subdir)
{
const int len = strlen(tempPath);
char* p = tempPath + len;
strcpy(p, subdir);
p += strlen(subdir);
*p++ = '\\';
*p = '\0';
}
}
#else//Linux specifics follow
extern DWORD getLastError() { return errno; }
void getTempPath(char* tempPath, unsigned int bufsize, const char* subdir/*=NULL*/)
{
assert(bufsize > 5);
strcpy(tempPath, "/tmp/");
if (subdir && *subdir)
{
strcat(tempPath, subdir);
strcat(tempPath, "/");
}
}
#endif
bool validateEnv(IConstEnvironment* pConstEnv, bool abortOnException)
{
char tempdir[_MAX_PATH];
StringBuffer sb;
while(true)
{
sb.clear().appendf("%d", msTick());
getTempPath(tempdir, sizeof(tempdir), sb.str());
if (!checkDirExists(tempdir))
{
if (recursiveCreateDirectory(tempdir))
break;
}
}
try
{
CConfigEngCallback callback(false, abortOnException);
Owned<IEnvDeploymentEngine> configGenMgr;
Owned<IPropertyTree> pEnvRoot = &pConstEnv->getPTree();
const char* inDir = pEnvRoot->queryProp(XML_TAG_ENVSETTINGS"/path");
StringBuffer sb(inDir);
sb.append("/componentfiles/configxml");
configGenMgr.setown(createConfigGenMgr(*pConstEnv, callback, NULL, inDir?sb.str():STANDARD_CONFIGXMLDIR, tempdir, NULL, NULL, NULL));
configGenMgr->deploy(DEFLAGS_CONFIGFILES, DEBACKUP_NONE, false, false);
deleteRecursive(tempdir);
const char* msg = callback.getErrorMsg();
if (msg && *msg)
{
StringBuffer sb("Errors or warnings were found when validating the environment.\n\n");
sb.append(msg).append("\n");
sb.appendf("Total errors/warnings: %d", callback.getErrorCount() - 1);
throw MakeStringExceptionDirect(-1, sb.str());
}
}
catch(IException* e)
{
deleteRecursive(tempdir);
throw e;
}
return true;
}
| 37.253082 | 244 | 0.60153 | [
"model",
"transform"
] |
b4bfdebecc23e88dc705106b2db16bce96ae6878 | 11,319 | cc | C++ | src/odc/odb2netcdf/Odb2NetCDF.cc | JCSDA/odc-1 | 8a120ebc744778248dda0267094cbf9aaa9d7246 | [
"Apache-2.0"
] | null | null | null | src/odc/odb2netcdf/Odb2NetCDF.cc | JCSDA/odc-1 | 8a120ebc744778248dda0267094cbf9aaa9d7246 | [
"Apache-2.0"
] | null | null | null | src/odc/odb2netcdf/Odb2NetCDF.cc | JCSDA/odc-1 | 8a120ebc744778248dda0267094cbf9aaa9d7246 | [
"Apache-2.0"
] | null | null | null | #include "Odb2NetCDF.h"
#include <iostream>
#include <netcdfcpp.h>
#include <algorithm>
#include <odb_api/Reader.h>
#include <odb_api/Select.h>
#include "eckit/exception/Exceptions.h"
/// @author Anne Fouilloux
using namespace std;
using namespace eckit;
/// Replaces all occurences of '@' with '_'
string patchName(const string& s)
{
string r (s);
// ODB-334
//replace(r.begin(), r.end(), '@', '_');
return r;
}
Odb2NetCDF::Odb2NetCDF(const string & inputfile, const string & outputfile)
: inputfile_(inputfile), outputfile_(outputfile)
{}
Odb2NetCDF::~Odb2NetCDF() {}
Odb2NetCDF_1D::Odb2NetCDF_1D(const string & inputfile, const string & outputfile)
: Odb2NetCDF(inputfile,outputfile)
{
Log::info() << "The following files will be opened and read: " << endl;
Log::info() << "ODB filename = " << inputfile << endl;
Log::info() << "Output NetCDF filename = " << outputfile << endl;
}
vector<NcVar*> Odb2NetCDF_1D::createVariables(NcFile& dataFile, const odc::MetaData& columns, NcDim* xDim)
{
vector<NcVar*> vars;
for (size_t i(0); i < columns.size(); ++i)
{
const odc::Column& column (*(columns[i]));
NcVar* v;
switch (column.type())
{
case odc::INTEGER:
case odc::BITFIELD:
v = dataFile.add_var(patchName(column.name()).c_str(), ncInt, xDim);
v->add_att(_FillValue, int (column.missingValue()));
break;
case odc::REAL:
v = dataFile.add_var(patchName(column.name()).c_str(), ncFloat, xDim);
v->add_att(_FillValue, float (column.missingValue()));
break;
case odc::DOUBLE:
v = dataFile.add_var(patchName(column.name()).c_str(), ncDouble, xDim);
v->add_att(_FillValue, double (column.missingValue()));
break;
case odc::STRING:
v = dataFile.add_var(patchName(column.name()).c_str(), ncChar, xDim);
//v->add_att(_FillValue, ""); // TODO: missing value for strings ????
break;
case odc::IGNORE:
default:
Log::error() << "Unknown column type: name=" << column.name() << ", type=" << column.type() << endl;
ASSERT("Unknown type" && false);
break;
}
vars.push_back(v);
}
return vars;
}
void Odb2NetCDF_1D::convert() {
// Create the file. The Replace parameter tells netCDF to overwrite
// this file, if it already exists.
NcFile dataFile(outputfile().c_str(), NcFile::Replace);
// You should always check whether a netCDF file creation or open
// constructor succeeded.
if (! dataFile.is_valid())
throw UserError("Could not open file"); // TODO: find appropriate exception
Log::info() << "Conversion to NetCDF 1D" << endl;
////////////////////////////// ODB from MARS //////////////////////////////
NcDim* xDim (dataFile.add_dim("hdrlen"));
dataFile.add_att("Conventions", "CF-1.6");
odc::Reader odb(inputfile());
odc::Reader::iterator it (odb.begin());
vector<NcVar*> vars (createVariables(dataFile, it->columns(), xDim));
union { double n; char b[sizeof(double) + 1]; } buffer;
memset(&buffer, 0, sizeof(buffer));
size_t nrows (0);
for(; it != odb.end(); ++it, ++nrows)
for (int i(0); i < it->columns().size(); ++i)
{
buffer.n = ((*it)[i]);
switch (it->columns()[i]->type())
{
case odc::STRING:
vars[i]->put_rec(buffer.b, nrows);
break;
default:
vars[i]->put_rec(&buffer.n, nrows);
break;
}
}
Log::info() << "Converted " << nrows << " row(s)." << endl;
}
//----------------------------------------------------------------
Odb2NetCDF_2D::Odb2NetCDF_2D(const string & inputfile, const string & outputfile)
: Odb2NetCDF(inputfile,outputfile) {
fileNameHdr_ = inputfile + "_hdr.odb";
fileNameBody_ = inputfile + "_body.odb";
Log::info() << "The following files will be opened and read: " << endl;
Log::info() << "Header filename = " << fileNameHdr_ << endl;
Log::info() << "Body filename = " << fileNameBody_ << endl;
Log::info() << "Output filename = " << outputfile << endl;
}
//----------------------------------------------------------------
void Odb2NetCDF_2D::convert() {
// Create the file. The Replace parameter tells netCDF to overwrite
// this file, if it already exists.
NcFile dataFile(outputfile().c_str(), NcFile::Replace);
// You should always check whether a netCDF file creation or open
// constructor succeeded.
if (! dataFile.is_valid())
throw UserError ("Couldn't open file!");
Log::info() << "Conversion to NetCDF 2D" << endl;
// Check how many channel/bodylen
string sql = "select distinct vertco_reference_1 from \"" + fileNameBody_ + "\" order by vertco_reference_1;";
odc::Select odbs(sql);
int nmaxchannel = 0;
for (odc::Select::iterator its = odbs.begin(); its != odbs.end(); ++its, ++nmaxchannel);
Log::info() << " There are = " << nmaxchannel << " channels" << endl;
// When we create netCDF dimensions, we get back a pointer to an
// NcDim for each one.
NcDim* xDim = dataFile.add_dim("hdrlen");
NcDim* yDim = dataFile.add_dim("maxbodylen", nmaxchannel);
NcVar *colChannel;
int * channel = new int [nmaxchannel];
int i=0;
odc::Select odbs2(sql);
for (odc::Select::iterator its = odbs2.begin(); its != odbs2.end(); ++its, ++i)
{
if (i==0)
colChannel = dataFile.add_var(its->columns()[0]->name().c_str(), ncInt, yDim);
channel[i] = ((*its)[0]);
}
colChannel->put(channel, nmaxchannel);
////////////////////////////// HDR //////////////////////////////
odc::Reader odb_hdr(fileNameHdr_);
odc::Reader::iterator it_hdr = odb_hdr.begin();
NcVar **colHdr;
colHdr = new NcVar * [it_hdr->columns().size()];
for (int i=0;i<it_hdr->columns().size();++i) {
switch(it_hdr->columns()[i]->type())
{
case odc::INTEGER:
case odc::BITFIELD:
colHdr[i] = dataFile.add_var(it_hdr->columns()[i]->name().c_str(), ncInt, xDim);
colHdr[i]->add_att(_FillValue,(int)it_hdr->columns()[i]->missingValue());
break;
case odc::REAL:
colHdr[i] = dataFile.add_var(it_hdr->columns()[i]->name().c_str(), ncFloat, xDim);
colHdr[i]->add_att(_FillValue, (float)it_hdr->columns()[i]->missingValue());
break;
case odc::STRING:
// colHdr[i] = dataFile.add_var(it_hdr->columns()[i]->name().c_str(), ncInt, xDim);
// colHdr[i]->add_att();
break;
case odc::IGNORE:
default:
ASSERT("Unknown type" && false);
break;
}
}
int nrows=0;
double nr;
for(; it_hdr != odb_hdr.end(); ++it_hdr)
{
++nrows;
for (int i=0;i<it_hdr->columns().size();++i) {
nr = ((*it_hdr)[i]);
colHdr[i]->put(&nr, 1);
colHdr[i]->set_cur(nrows);
}
}
////////////////////////////// BODY //////////////////////////////
odc::Reader odb_body(fileNameBody_);
odc::Reader::iterator it_body = odb_body.begin();
NcVar **colBody;
colBody = new NcVar * [it_body->columns().size()];
int index_channel=-1;
int index_seqno=-1;
for (int i=0;i<it_body->columns().size();++i) {
if (it_body->columns()[i]->name() == "vertco_reference_1" || it_body->columns()[i]->name() == "vertco_reference_1@body")
index_channel = i;
if (it_body->columns()[i]->name() == "seqno" || it_body->columns()[i]->name() == "seqno@hdr")
index_seqno = i;
}
Log::info() << " index_vertco_reference_1 = " << index_channel << endl;
Log::info() << " index_seqno = " << index_seqno << endl;
if (index_channel != -1 && index_seqno != -1) {
for (int i=0;i<it_body->columns().size();++i) {
if ((it_body->columns()[i]->name() != "seqno" && it_body->columns()[i]->name() != "vertco_reference_1") &&
(it_body->columns()[i]->name() != "seqno@hdr" && it_body->columns()[i]->name() != "vertco_reference_1@body")) {
switch(it_body->columns()[i]->type())
{
case odc::INTEGER:
case odc::BITFIELD:
colBody[i] = dataFile.add_var(it_body->columns()[i]->name().c_str(), ncInt, xDim, yDim);
colBody[i]->add_att(_FillValue,(int)it_body->columns()[i]->missingValue());
break;
case odc::REAL:
colBody[i] = dataFile.add_var(it_body->columns()[i]->name().c_str(), ncFloat, xDim, yDim);
colBody[i]->add_att(_FillValue,(float) it_body->columns()[i]->missingValue());
break;
case odc::STRING:
// colBody[i] = dataFile.add_var(it_body->columns()[i]->name().c_str(), ncInt, xDim, yDim);
break;
case odc::IGNORE:
default:
ASSERT("Unknown type" && false);
break;
}
}
}
int nrows = 0;
int nchannel = 0;
double nd[it_body->columns().size()][nmaxchannel];
double lnd[nmaxchannel];
long icurrent_seqno=-1;
int icurrent_channel=-1;
for(; it_body != odb_body.end(); ++it_body)
{
if (((*it_body)[index_seqno]) != icurrent_seqno) {
if (nrows > 0) { // not the first time
for (int i=0;i<it_body->columns().size();++i) {
if ((it_body->columns()[i]->name() != "seqno" && it_body->columns()[i]->name() != "vertco_reference_1") &&
(it_body->columns()[i]->name() != "seqno@hdr" && it_body->columns()[i]->name() != "vertco_reference_1@body")) {
// copy to a local array (this specific ODB column) to write in netCDF
for (int j=0; j<nmaxchannel; ++j)
lnd[j] = nd[i][j];
colBody[i]->put_rec(&lnd[0], nrows-1); // nrows -1 because we start to write at line 0 and not 1
}
}
}
++nrows;
icurrent_seqno = ((*it_body)[index_seqno]);
icurrent_channel = 0;
nchannel=0;
// initialize to missing value nd for all columns and all channel
for (int i=0;i<it_body->columns().size();++i) {
for (int j=0; j< nmaxchannel; ++j) {
nd[i][j] = it_body->columns()[i]->missingValue();
}
}
}
while (icurrent_channel < nmaxchannel && channel[icurrent_channel] < ((*it_body)[index_channel])) {
++icurrent_channel;
++nchannel;
}
for (int i=0;i<it_body->columns().size();++i) {
if ((it_body->columns()[i]->name() != "seqno" && it_body->columns()[i]->name() != "vertco_reference_1") &&
(it_body->columns()[i]->name() != "seqno@hdr" && it_body->columns()[i]->name() != "vertco_reference_1@body")) {
nd[i][icurrent_channel] = ((*it_body)[i]);
}
}
++nchannel;
++icurrent_channel;
}
for (int i=0;i<it_body->columns().size();++i) {
if ((it_body->columns()[i]->name() != "seqno" && it_body->columns()[i]->name() != "vertco_reference_1") &&
(it_body->columns()[i]->name() != "seqno@hdr" && it_body->columns()[i]->name() != "vertco_reference_1@body")) {
for (int j=0; j<nmaxchannel; ++j)
lnd[j] = nd[i][j];
for (int j=0; j<nmaxchannel; ++j)
Log::info() << nrows << " lnd[" << j << "]=" << lnd[j] << " " ;
Log::info() << endl;
colBody[i]->put_rec(&lnd[0], nrows-1);
}
}
}
}
| 35.482759 | 126 | 0.557116 | [
"vector"
] |
b4c17840241b1d468ecb7f07534b2ce1ad50a16e | 149 | cpp | C++ | Face.cpp | zeunix/Bota-Pelota- | 575f7cd098083f10d59af05cb9734e51ab4c2bbf | [
"Unlicense"
] | null | null | null | Face.cpp | zeunix/Bota-Pelota- | 575f7cd098083f10d59af05cb9734e51ab4c2bbf | [
"Unlicense"
] | null | null | null | Face.cpp | zeunix/Bota-Pelota- | 575f7cd098083f10d59af05cb9734e51ab4c2bbf | [
"Unlicense"
] | null | null | null | #include "Face.h"
Face::Face()
{
//ctor
}
Face::Face(vector<Edge> edges_in)
{
edges = edges_in;
}
Face::~Face()
{
//dtor
}
| 7.842105 | 34 | 0.503356 | [
"vector"
] |
b4cb5bfd5631bd799683fd9206c7eac88b7a6f7a | 5,703 | cpp | C++ | src/fileformat/file_format/raw_data/raw_data_format.cpp | nimeshvaghasiya/retdec | 30b3cb3402fe59d992bf0558681f051bcd7f7849 | [
"MIT",
"BSD-3-Clause"
] | 521 | 2019-03-29T15:44:08.000Z | 2022-03-22T09:46:19.000Z | src/fileformat/file_format/raw_data/raw_data_format.cpp | nimeshvaghasiya/retdec | 30b3cb3402fe59d992bf0558681f051bcd7f7849 | [
"MIT",
"BSD-3-Clause"
] | 30 | 2019-06-04T17:00:49.000Z | 2021-09-08T20:44:19.000Z | src/fileformat/file_format/raw_data/raw_data_format.cpp | nimeshvaghasiya/retdec | 30b3cb3402fe59d992bf0558681f051bcd7f7849 | [
"MIT",
"BSD-3-Clause"
] | 99 | 2019-03-29T16:04:13.000Z | 2022-03-28T16:59:34.000Z | /**
* @file src/fileformat/file_format/raw_data/raw_data_format.cpp
* @brief Methods of RawDataFormat class.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*/
#include <algorithm>
#include <iomanip>
#include <string>
#include "retdec/fileformat/file_format/raw_data/raw_data_format.h"
using namespace retdec::utils;
namespace retdec {
namespace fileformat {
/**
* Constructor
* @param inputStream Input stream
* @param loadFlags Load flags
*/
RawDataFormat::RawDataFormat(std::istream &inputStream, LoadFlags loadFlags) : FileFormat(inputStream, loadFlags)
{
initStructures();
}
RawDataFormat::RawDataFormat(const std::string &filePath, LoadFlags loadFlags) : FileFormat(filePath, loadFlags)
{
secName = ".text";
secType = Section::Type::CODE;
initStructures();
}
/**
* Destructor
*/
RawDataFormat::~RawDataFormat()
{
}
/**
* Init internal structures
*/
void RawDataFormat::initStructures()
{
stateIsValid = true;
fileFormat = Format::RAW_DATA;
section = new Section;
section->setName(secName);
section->setType(secType);
section->setIndex(0);
section->setOffset(0);
section->setAddress(0);
section->setMemory(true);
section->setSizeInFile(bytes.size());
section->setSizeInMemory(bytes.size());
section->load(this);
sections.push_back(section);
computeSectionTableHashes();
loadStrings();
}
std::size_t RawDataFormat::initSectionTableHashOffsets()
{
return 0;
}
/**
* Check entry point information validity
* @return @c false if EP is out of VA space, @c true otherwise
*/
bool RawDataFormat::isEntryPointValid() const
{
if((epAddress >= section->getAddress()) && (epAddress < section->getAddress() + bytes.size()))
{
return true;
}
return false;
}
retdec::utils::Endianness RawDataFormat::getEndianness() const
{
return endianness;
}
std::size_t RawDataFormat::getBytesPerWord() const
{
return bytesPerWord;
}
std::size_t RawDataFormat::getByteLength() const
{
return bytesLength;
}
bool RawDataFormat::hasMixedEndianForDouble() const
{
return false;
}
std::size_t RawDataFormat::getDeclaredFileLength() const
{
return getFileLength();
}
bool RawDataFormat::areSectionsValid() const
{
return true;
}
bool RawDataFormat::isObjectFile() const
{
return false;
}
bool RawDataFormat::isDll() const
{
return false;
}
bool RawDataFormat::isExecutable() const
{
return true;
}
bool RawDataFormat::getMachineCode(unsigned long long &result) const
{
return false;
}
bool RawDataFormat::getAbiVersion(unsigned long long &result) const
{
return false;
}
bool RawDataFormat::getImageBaseAddress(unsigned long long &imageBase) const
{
return false;
}
bool RawDataFormat::getEpAddress(unsigned long long &result) const
{
if(hasEntryPoint && isEntryPointValid())
{
result = epAddress;
}
else
{
result = section->getAddress();
}
return true;
}
bool RawDataFormat::getEpOffset(unsigned long long &result) const
{
if(hasEntryPoint && isEntryPointValid())
{
// Compute offset
result = epAddress - section->getAddress();
}
else
{
// Not set - decompilation will start from beginning
result = 0x0;
}
return true;
}
Architecture RawDataFormat::getTargetArchitecture() const
{
return architecture;
}
std::size_t RawDataFormat::getDeclaredNumberOfSections() const
{
return getNumberOfSections();
}
std::size_t RawDataFormat::getDeclaredNumberOfSegments() const
{
return getNumberOfSegments();
}
std::size_t RawDataFormat::getSectionTableOffset() const
{
return 0;
}
std::size_t RawDataFormat::getSectionTableEntrySize() const
{
return 0;
}
std::size_t RawDataFormat::getSegmentTableOffset() const
{
return 0;
}
std::size_t RawDataFormat::getSegmentTableEntrySize() const
{
return 0;
}
/**
* Set binary code architecture
* @param a Architecture
*/
void RawDataFormat::setTargetArchitecture(Architecture a)
{
architecture = a;
}
/**
* Set binary code endianness
* @param e Endianness
*/
void RawDataFormat::setEndianness(Endianness e)
{
endianness = e;
}
/**
* Set word size
* @param b Word size in bytes
*/
void RawDataFormat::setBytesPerWord(std::size_t b)
{
bytesPerWord = b;
}
/**
* Set byte length
* @param l Byte length in bits
*/
void RawDataFormat::setBytesLength(std::size_t l)
{
bytesLength = l;
}
/**
* Set entry point address
* @param entryPoint Entry point address
*/
void RawDataFormat::setEntryPoint(Address entryPoint)
{
hasEntryPoint = true;
epAddress = entryPoint;
}
/**
* Set section base address
* @param baseAddress Section base address
*/
void RawDataFormat::setBaseAddress(Address baseAddress)
{
section->setAddress(baseAddress);
}
/**
* Dump section data
* @return Dump of section data
*/
std::string RawDataFormat::dumpData() const
{
std::vector<unsigned char> d;
if(!section || !section->getBytes(d))
{
return std::string();
}
std::stringstream ss;
ss << section->getName()
<< " @ " << section->getAddress()
<< " has " << std::dec << d.size()
<< " = 0x" << std::hex << d.size() << " bytes\n";
const std::size_t lineLength = 8;
std::size_t cntr = 0;
std::string line;
for(std::size_t i = 0, e = d.size(); i < e; ++i)
{
auto c = d[i];
if(!cntr)
{
ss << std::hex << std::setfill('0')
<< std::setw(8) << (section->getAddress() + i) << ": ";
}
ss << std::hex << std::setfill('0') << std::setw(2) << int(c);
line += isprint(c) ? c : '.';
++cntr;
if(cntr == lineLength)
{
ss << " |" << line << "|\n";
cntr = 0;
line.clear();
}
else if(i == (e - 1))
{
for (; cntr != lineLength; ++cntr)
{
ss << " ";
line += " ";
}
ss << " |" << line << "|\n";
}
else
{
ss << " ";
}
}
return ss.str();
}
} // namespace fileformat
} // namespace retdec
| 17.821875 | 113 | 0.686656 | [
"vector"
] |
b4cf19dff25270a1dc9e628a16960ffa7182920b | 9,084 | cpp | C++ | gadgets/mri_core/AcquisitionAccumulateTriggerGadget.cpp | roopchansinghv/gadgetron | fb6c56b643911152c27834a754a7b6ee2dd912da | [
"MIT"
] | 1 | 2022-02-22T21:06:36.000Z | 2022-02-22T21:06:36.000Z | gadgets/mri_core/AcquisitionAccumulateTriggerGadget.cpp | apd47/gadgetron | 073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2 | [
"MIT"
] | null | null | null | gadgets/mri_core/AcquisitionAccumulateTriggerGadget.cpp | apd47/gadgetron | 073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2 | [
"MIT"
] | null | null | null | #include "AcquisitionAccumulateTriggerGadget.h"
#include "log.h"
#include "mri_core_data.h"
#include <boost/algorithm/string.hpp>
namespace Gadgetron {
using TriggerDimension = AcquisitionAccumulateTriggerGadget::TriggerDimension;
namespace {
bool is_noise(Core::Acquisition& acq) {
return std::get<ISMRMRD::AcquisitionHeader>(acq).isFlagSet(ISMRMRD::ISMRMRD_ACQ_IS_NOISE_MEASUREMENT);
}
unsigned short get_index(const ISMRMRD::AcquisitionHeader& header, TriggerDimension index) {
switch (index) {
case TriggerDimension::kspace_encode_step_1: return header.idx.kspace_encode_step_1;
case TriggerDimension::kspace_encode_step_2: return header.idx.kspace_encode_step_2;
case TriggerDimension::average: return header.idx.average;
case TriggerDimension::slice: return header.idx.slice;
case TriggerDimension::contrast: return header.idx.contrast;
case TriggerDimension::phase: return header.idx.phase;
case TriggerDimension::repetition: return header.idx.repetition;
case TriggerDimension::set: return header.idx.set;
case TriggerDimension::segment: return header.idx.segment;
case TriggerDimension::user_0: return header.idx.user[0];
case TriggerDimension::user_1: return header.idx.user[1];
case TriggerDimension::user_2: return header.idx.user[2];
case TriggerDimension::user_3: return header.idx.user[3];
case TriggerDimension::user_4: return header.idx.user[4];
case TriggerDimension::user_5: return header.idx.user[5];
case TriggerDimension::user_6: return header.idx.user[6];
case TriggerDimension::user_7: return header.idx.user[7];
case TriggerDimension::n_acquisitions: return 0;
case TriggerDimension::none: return 0;
}
throw std::runtime_error("Illegal enum");
}
struct EqualityTrigger {
explicit EqualityTrigger(TriggerDimension trig) : trigger{ trig } {}
const TriggerDimension trigger;
Core::optional<unsigned short> previous_trigger;
bool trigger_before(const ISMRMRD::AcquisitionHeader& head) {
auto acq_index = get_index(head, trigger);
auto result = (previous_trigger != acq_index && previous_trigger != Core::none);
previous_trigger = acq_index;
return result;
}
static bool trigger_after(const ISMRMRD::AcquisitionHeader& head) {
return false;
}
};
struct NumAcquisitionsTrigger {
explicit NumAcquisitionsTrigger(size_t target_acquisitions_first, size_t target_acquisitions) : target_acquisitions_first{target_acquisitions_first},target_acquisitions{ target_acquisitions } {}
const size_t target_acquisitions_first;
const size_t target_acquisitions;
size_t num_acquisitions = 0;
bool first = true;
static bool trigger_before(const ISMRMRD::AcquisitionHeader& head) {
return false;
}
bool trigger_after(const ISMRMRD::AcquisitionHeader& head) {
// Handle possible n_acq trigger _after_ pushing data - all others come before
size_t current_target_acquisitions = first ? target_acquisitions_first : target_acquisitions;
bool result = ++num_acquisitions >= current_target_acquisitions;
if (result)
{
first = false;
num_acquisitions = 0;
}
return result;
}
};
struct NoneTrigger {
static bool trigger_before(const ISMRMRD::AcquisitionHeader& head) {
return false;
}
static bool trigger_after(const ISMRMRD::AcquisitionHeader& head) {
return false;
}
};
using Trigger = Core::variant<EqualityTrigger, NumAcquisitionsTrigger, NoneTrigger>;
Trigger get_trigger(const AcquisitionAccumulateTriggerGadget& gadget) {
switch (gadget.trigger_dimension) {
case TriggerDimension::kspace_encode_step_1:
case TriggerDimension::kspace_encode_step_2:
case TriggerDimension::average:
case TriggerDimension::slice:
case TriggerDimension::contrast:
case TriggerDimension::phase:
case TriggerDimension::repetition:
case TriggerDimension::set:
case TriggerDimension::segment:
case TriggerDimension::user_0:
case TriggerDimension::user_1:
case TriggerDimension::user_2:
case TriggerDimension::user_3:
case TriggerDimension::user_4:
case TriggerDimension::user_5:
case TriggerDimension::user_6:
case TriggerDimension::user_7: return EqualityTrigger(gadget.trigger_dimension);
case TriggerDimension::n_acquisitions: return NumAcquisitionsTrigger(gadget.n_acquisitions_before_trigger,gadget.n_acquisitions_before_ongoing_trigger);
case TriggerDimension::none: return NoneTrigger();
default: throw std::runtime_error("ENUM TriggerDimension is in an invalid state.");
}
}
bool trigger_before(Trigger& trigger, const ISMRMRD::AcquisitionHeader& head) {
return Core::visit([&](auto& var) { return var.trigger_before(head); }, trigger);
}
bool trigger_after(Trigger& trigger, const ISMRMRD::AcquisitionHeader& acq) {
return Core::visit([&](auto& var) { return var.trigger_after(acq); }, trigger);
}
}
void AcquisitionAccumulateTriggerGadget::send_data(Core::OutputChannel& out, std::map<unsigned short, AcquisitionBucket>& buckets,
std::vector<Core::Waveform>& waveforms) {
trigger_events++;
GDEBUG("Trigger (%d) occurred, sending out %d buckets\n", trigger_events, buckets.size());
buckets.begin()->second.waveform_ = std::move(waveforms);
// Pass all buckets down the chain
for (auto& bucket : buckets)
out.push(std::move(bucket.second));
buckets.clear();
}
void AcquisitionAccumulateTriggerGadget ::process(
Core::InputChannel<Core::variant<Core::Acquisition, Core::Waveform>>& in, Core::OutputChannel& out) {
auto waveforms = std::vector<Core::Waveform>{};
auto buckets = std::map<unsigned short, AcquisitionBucket>{};
auto trigger = get_trigger(*this);
for (auto message : in) {
if (Core::holds_alternative<Core::Waveform>(message)) {
waveforms.emplace_back(std::move(Core::get<Core::Waveform>(message)));
continue;
}
auto& acq = Core::get<Core::Acquisition>(message);
if (is_noise(acq))
continue;
auto head = std::get<ISMRMRD::AcquisitionHeader>(acq);
if (trigger_before(trigger, head))
send_data(out, buckets, waveforms);
// It is enough to put the first one, since they are linked
unsigned short sorting_index = get_index(head, sorting_dimension);
AcquisitionBucket& bucket = buckets[sorting_index];
bucket.add_acquisition(std::move(acq));
if (trigger_after(trigger, head))
send_data(out, buckets, waveforms);
}
send_data(out,buckets,waveforms);
}
GADGETRON_GADGET_EXPORT(AcquisitionAccumulateTriggerGadget);
namespace {
const std::map<std::string, TriggerDimension> triggerdimension_from_name = {
{ "kspace_encode_step_1", TriggerDimension::kspace_encode_step_1 },
{ "kspace_encode_step_2", TriggerDimension::kspace_encode_step_2 },
{ "average", TriggerDimension::average }, { "slice", TriggerDimension::slice },
{ "contrast", TriggerDimension::contrast }, { "phase", TriggerDimension::phase },
{ "repetition", TriggerDimension::repetition }, { "set", TriggerDimension::set },
{ "segment", TriggerDimension::segment }, { "user_0", TriggerDimension::user_0 },
{ "user_1", TriggerDimension::user_1 }, { "user_2", TriggerDimension::user_2 },
{ "user_3", TriggerDimension::user_3 }, { "user_4", TriggerDimension::user_4 },
{ "user_5", TriggerDimension::user_5 }, { "user_6", TriggerDimension::user_6 },
{ "user_7", TriggerDimension::user_7 }, { "n_acquisitions", TriggerDimension::n_acquisitions },
{ "none", TriggerDimension::none }, { "", TriggerDimension::none }
};
}
void from_string(const std::string& str, TriggerDimension& trigger) {
auto lower = str;
boost::to_lower(lower);
trigger = triggerdimension_from_name.at(lower);
}
}
| 46.824742 | 206 | 0.630009 | [
"vector"
] |
b4d469afbe6920de27db94387036b75e94cd708b | 10,156 | cpp | C++ | src/qpid/management/ManagementObject.cpp | gcsideal/debian-qpid-cpp | e4d034036f29408f940805f5505ae62ce89650cc | [
"Apache-2.0"
] | null | null | null | src/qpid/management/ManagementObject.cpp | gcsideal/debian-qpid-cpp | e4d034036f29408f940805f5505ae62ce89650cc | [
"Apache-2.0"
] | null | null | null | src/qpid/management/ManagementObject.cpp | gcsideal/debian-qpid-cpp | e4d034036f29408f940805f5505ae62ce89650cc | [
"Apache-2.0"
] | null | null | null | /*
*
* 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 "qpid/management/Manageable.h"
#include "qpid/management/ManagementObject.h"
#include "qpid/framing/FieldTable.h"
#include "qpid/framing/Buffer.h"
#include "qpid/sys/Time.h"
#include "qpid/sys/Thread.h"
#include "qpid/log/Statement.h"
#include <boost/lexical_cast.hpp>
#include <stdlib.h>
using namespace std;
using namespace qpid;
using namespace qpid::management;
void AgentAttachment::setBanks(uint32_t broker, uint32_t bank)
{
first =
((uint64_t) (broker & 0x000fffff)) << 28 |
((uint64_t) (bank & 0x0fffffff));
}
// Deprecated
ObjectId::ObjectId(uint8_t flags, uint16_t seq, uint32_t broker, uint64_t object)
: agent(0), agentEpoch(seq)
{
first =
((uint64_t) (flags & 0x0f)) << 60 |
((uint64_t) (seq & 0x0fff)) << 48 |
((uint64_t) (broker & 0x000fffff)) << 28;
second = object;
}
ObjectId::ObjectId(uint8_t flags, uint16_t seq, uint32_t broker)
: agent(0), second(0), agentEpoch(seq)
{
first =
((uint64_t) (flags & 0x0f)) << 60 |
((uint64_t) (seq & 0x0fff)) << 48 |
((uint64_t) (broker & 0x000fffff)) << 28;
}
ObjectId::ObjectId(AgentAttachment* _agent, uint8_t flags, uint16_t seq)
: agent(_agent), second(0), agentEpoch(seq)
{
first =
((uint64_t) (flags & 0x0f)) << 60 |
((uint64_t) (seq & 0x0fff)) << 48;
}
ObjectId::ObjectId(istream& in) : agent(0)
{
string text;
in >> text;
fromString(text);
}
ObjectId::ObjectId(const string& text) : agent(0)
{
fromString(text);
}
void ObjectId::fromString(const string& text)
{
#define FIELDS 5
#if defined (_WIN32) && !defined (atoll)
# define atoll(X) _atoi64(X)
#endif
// format:
// V1: <flags>-<sequence>-<broker-bank>-<agent-bank>-<uint64-app-id>
// V2: Not used
string copy(text.c_str());
char* cText;
char* field[FIELDS];
bool atFieldStart = true;
int idx = 0;
cText = const_cast<char*>(copy.c_str());
for (char* cursor = cText; *cursor; cursor++) {
if (atFieldStart) {
if (idx >= FIELDS)
throw Exception("Invalid ObjectId format");
field[idx++] = cursor;
atFieldStart = false;
} else {
if (*cursor == '-') {
*cursor = '\0';
atFieldStart = true;
}
}
}
if (idx != FIELDS)
throw Exception("Invalid ObjectId format");
agentEpoch = atoll(field[1]);
first = (atoll(field[0]) << 60) +
(atoll(field[1]) << 48) +
(atoll(field[2]) << 28);
agentName = string(field[3]);
second = atoll(field[4]);
}
bool ObjectId::operator==(const ObjectId &other) const
{
return v2Key == other.v2Key;
}
bool ObjectId::operator<(const ObjectId &other) const
{
return v2Key < other.v2Key;
}
bool ObjectId::equalV1(const ObjectId &other) const
{
uint64_t otherFirst = agent == 0 ? other.first : other.first & 0xffff000000000000LL;
return first == otherFirst && second == other.second;
}
// encode as V1-format binary
void ObjectId::encode(string& buffer) const
{
const uint32_t len = 16;
char _data[len];
qpid::framing::Buffer body(_data, len);
if (agent == 0)
body.putLongLong(first);
else
body.putLongLong(first | agent->first);
body.putLongLong(second);
body.reset();
body.getRawData(buffer, len);
}
// decode as V1-format binary
void ObjectId::decode(const string& buffer)
{
const uint32_t len = 16;
char _data[len];
qpid::framing::Buffer body(_data, len);
body.checkAvailable(buffer.length());
body.putRawData(buffer);
body.reset();
first = body.getLongLong();
second = body.getLongLong();
v2Key = boost::lexical_cast<string>(second);
}
// generate the V2 key from the index fields defined
// in the schema.
void ObjectId::setV2Key(const ManagementObject& object)
{
stringstream oname;
oname << object.getPackageName() << ":" << object.getClassName() << ":" << object.getKey();
v2Key = oname.str();
}
// encode as V2-format map
void ObjectId::mapEncode(types::Variant::Map& map) const
{
map["_object_name"] = v2Key;
if (!agentName.empty())
map["_agent_name"] = agentName;
if (agentEpoch)
map["_agent_epoch"] = agentEpoch;
}
// decode as v2-format map
void ObjectId::mapDecode(const types::Variant::Map& map)
{
types::Variant::Map::const_iterator i;
if ((i = map.find("_object_name")) != map.end())
v2Key = i->second.asString();
else
throw Exception("Required _object_name field missing.");
if ((i = map.find("_agent_name")) != map.end())
agentName = i->second.asString();
if ((i = map.find("_agent_epoch")) != map.end())
agentEpoch = i->second.asInt64();
}
ObjectId::operator types::Variant::Map() const
{
types::Variant::Map m;
mapEncode(m);
return m;
}
namespace qpid {
namespace management {
ostream& operator<<(ostream& out, const ObjectId& i)
{
uint64_t virtFirst = i.first;
if (i.agent)
virtFirst |= i.agent->getFirst();
out << ((virtFirst & 0xF000000000000000LL) >> 60) <<
"-" << ((virtFirst & 0x0FFF000000000000LL) >> 48) <<
"-" << ((virtFirst & 0x0000FFFFF0000000LL) >> 28) <<
"-" << i.agentName <<
"-" << i.second <<
"(" << i.v2Key << ")";
return out;
}
}}
ManagementObject::ManagementObject(Manageable* _core) :
createTime(qpid::sys::Duration(sys::EPOCH, sys::now())),
destroyTime(0), updateTime(createTime), configChanged(true),
instChanged(true), deleted(false),
coreObject(_core), flags(0), forcePublish(false) {}
void ManagementObject::setUpdateTime()
{
updateTime = sys::Duration(sys::EPOCH, sys::now());
}
void ManagementObject::resourceDestroy()
{
QPID_LOG(trace, "Management object marked deleted: " << getObjectId().getV2Key());
destroyTime = sys::Duration(sys::EPOCH, sys::now());
deleted = true;
}
int ManagementObject::maxThreads = 1;
int ManagementObject::nextThreadIndex = 0;
void ManagementObject::writeTimestamps (string& buf) const
{
char _data[4000];
qpid::framing::Buffer body(_data, 4000);
body.putShortString (getPackageName ());
body.putShortString (getClassName ());
body.putBin128 (getMd5Sum ());
body.putLongLong (updateTime);
body.putLongLong (createTime);
body.putLongLong (destroyTime);
uint32_t len = body.getPosition();
body.reset();
body.getRawData(buf, len);
string oid;
objectId.encode(oid);
buf += oid;
}
void ManagementObject::readTimestamps (const string& buf)
{
char _data[4000];
qpid::framing::Buffer body(_data, 4000);
string unused;
uint8_t unusedUuid[16];
body.checkAvailable(buf.length());
body.putRawData(buf);
body.reset();
body.getShortString(unused);
body.getShortString(unused);
body.getBin128(unusedUuid);
updateTime = body.getLongLong();
createTime = body.getLongLong();
destroyTime = body.getLongLong();
}
uint32_t ManagementObject::writeTimestampsSize() const
{
return 1 + getPackageName().length() + // str8
1 + getClassName().length() + // str8
16 + // bin128
8 + // uint64
8 + // uint64
8 + // uint64
objectId.encodedSize(); // objectId
}
void ManagementObject::writeTimestamps (types::Variant::Map& map) const
{
// types::Variant::Map oid, sid;
// sid["_package_name"] = getPackageName();
// sid["_class_name"] = getClassName();
// sid["_hash"] = qpid::types::Uuid(getMd5Sum());
// map["_schema_id"] = sid;
// objectId.mapEncode(oid);
// map["_object_id"] = oid;
map["_update_ts"] = updateTime;
map["_create_ts"] = createTime;
map["_delete_ts"] = destroyTime;
}
void ManagementObject::readTimestamps (const types::Variant::Map& map)
{
types::Variant::Map::const_iterator i;
if ((i = map.find("_update_ts")) != map.end())
updateTime = i->second.asUint64();
if ((i = map.find("_create_ts")) != map.end())
createTime = i->second.asUint64();
if ((i = map.find("_delete_ts")) != map.end())
destroyTime = i->second.asUint64();
}
void ManagementObject::setReference(ObjectId) {}
int ManagementObject::getThreadIndex() {
static QPID_TSS int thisIndex = -1;
if (thisIndex == -1) {
Mutex::ScopedLock mutex(accessLock);
thisIndex = nextThreadIndex;
if (nextThreadIndex < maxThreads - 1)
nextThreadIndex++;
}
return thisIndex;
}
// void ManagementObject::mapEncode(types::Variant::Map& map,
// bool includeProperties,
// bool includeStatistics)
// {
// types::Variant::Map values;
// writeTimestamps(map);
// mapEncodeValues(values, includeProperties, includeStatistics);
// map["_values"] = values;
// }
// void ManagementObject::mapDecode(const types::Variant::Map& map)
// {
// types::Variant::Map::const_iterator i;
// readTimestamps(map);
// if ((i = map.find("_values")) != map.end())
// mapDecodeValues(i->second.asMap());
// }
| 26.310881 | 95 | 0.615203 | [
"object"
] |
b4d5d6b38f97070a3305c9404187e364cb3d6ffc | 5,950 | cpp | C++ | Sources/assimp/code/Common/Version.cpp | staminajim/Assimp | 142a47529ed2f2ad6c38a87b6d4f77a6cc4e8ff9 | [
"BSD-3-Clause"
] | null | null | null | Sources/assimp/code/Common/Version.cpp | staminajim/Assimp | 142a47529ed2f2ad6c38a87b6d4f77a6cc4e8ff9 | [
"BSD-3-Clause"
] | null | null | null | Sources/assimp/code/Common/Version.cpp | staminajim/Assimp | 142a47529ed2f2ad6c38a87b6d4f77a6cc4e8ff9 | [
"BSD-3-Clause"
] | null | null | null | /*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2019, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
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.
---------------------------------------------------------------------------
*/
// Actually just a dummy, used by the compiler to build the precompiled header.
#include <Assimp/version.h>
#include <Assimp/scene.h>
#include "ScenePrivate.h"
static const unsigned int MajorVersion = 5;
static const unsigned int MinorVersion = 0;
// --------------------------------------------------------------------------------
// Legal information string - don't remove this.
static const char* LEGAL_INFORMATION =
"Open Asset Import Library (Assimp).\n"
"A free C/C++ library to import various 3D file formats into applications\n\n"
"(c) 2008-2020, assimp team\n"
"License under the terms and conditions of the 3-clause BSD license\n"
"https://github.com/assimp/assimp\n"
;
// ------------------------------------------------------------------------------------------------
// Get legal string
ASSIMP_API const char* aiGetLegalString () {
return LEGAL_INFORMATION;
}
// ------------------------------------------------------------------------------------------------
// Get Assimp minor version
ASSIMP_API unsigned int aiGetVersionMinor () {
return MinorVersion;
}
// ------------------------------------------------------------------------------------------------
// Get Assimp major version
ASSIMP_API unsigned int aiGetVersionMajor () {
return MajorVersion;
}
// ------------------------------------------------------------------------------------------------
// Get flags used for compilation
ASSIMP_API unsigned int aiGetCompileFlags () {
unsigned int flags = 0;
#ifdef ASSIMP_BUILD_BOOST_WORKAROUND
flags |= ASSIMP_CFLAGS_NOBOOST;
#endif
#ifdef ASSIMP_BUILD_SINGLETHREADED
flags |= ASSIMP_CFLAGS_SINGLETHREADED;
#endif
#ifdef ASSIMP_BUILD_DEBUG
flags |= ASSIMP_CFLAGS_DEBUG;
#endif
#ifdef ASSIMP_BUILD_DLL_EXPORT
flags |= ASSIMP_CFLAGS_SHARED;
#endif
#ifdef _STLPORT_VERSION
flags |= ASSIMP_CFLAGS_STLPORT;
#endif
return flags;
}
// include current build revision, which is even updated from time to time -- :-)
#include "revision.h"
// ------------------------------------------------------------------------------------------------
ASSIMP_API unsigned int aiGetVersionRevision() {
return GitVersion;
}
ASSIMP_API const char *aiGetBranchName() {
return GitBranch;
}
// ------------------------------------------------------------------------------------------------
ASSIMP_API aiScene::aiScene()
: mFlags(0)
, mRootNode(nullptr)
, mNumMeshes(0)
, mMeshes(nullptr)
, mNumMaterials(0)
, mMaterials(nullptr)
, mNumAnimations(0)
, mAnimations(nullptr)
, mNumTextures(0)
, mTextures(nullptr)
, mNumLights(0)
, mLights(nullptr)
, mNumCameras(0)
, mCameras(nullptr)
, mMetaData(nullptr)
, mPrivate(new Assimp::ScenePrivateData()) {
// empty
}
// ------------------------------------------------------------------------------------------------
ASSIMP_API aiScene::~aiScene() {
// delete all sub-objects recursively
delete mRootNode;
// To make sure we won't crash if the data is invalid it's
// much better to check whether both mNumXXX and mXXX are
// valid instead of relying on just one of them.
if (mNumMeshes && mMeshes)
for( unsigned int a = 0; a < mNumMeshes; a++)
delete mMeshes[a];
delete [] mMeshes;
if (mNumMaterials && mMaterials) {
for (unsigned int a = 0; a < mNumMaterials; ++a ) {
delete mMaterials[ a ];
}
}
delete [] mMaterials;
if (mNumAnimations && mAnimations)
for( unsigned int a = 0; a < mNumAnimations; a++)
delete mAnimations[a];
delete [] mAnimations;
if (mNumTextures && mTextures)
for( unsigned int a = 0; a < mNumTextures; a++)
delete mTextures[a];
delete [] mTextures;
if (mNumLights && mLights)
for( unsigned int a = 0; a < mNumLights; a++)
delete mLights[a];
delete [] mLights;
if (mNumCameras && mCameras)
for( unsigned int a = 0; a < mNumCameras; a++)
delete mCameras[a];
delete [] mCameras;
aiMetadata::Dealloc(mMetaData);
mMetaData = nullptr;
delete static_cast<Assimp::ScenePrivateData*>( mPrivate );
}
| 31.989247 | 99 | 0.597815 | [
"3d"
] |
b4d6e1beae920a118076d44182796237f4686641 | 44,413 | cpp | C++ | src/vm/eepolicy.cpp | ComeWithMe/coreclr | 1ab8b90ca9f8748776b00cc21cd5740b53dec67b | [
"MIT"
] | null | null | null | src/vm/eepolicy.cpp | ComeWithMe/coreclr | 1ab8b90ca9f8748776b00cc21cd5740b53dec67b | [
"MIT"
] | null | null | null | src/vm/eepolicy.cpp | ComeWithMe/coreclr | 1ab8b90ca9f8748776b00cc21cd5740b53dec67b | [
"MIT"
] | 1 | 2019-04-12T13:48:27.000Z | 2019-04-12T13:48:27.000Z | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
//
// ---------------------------------------------------------------------------
// EEPolicy.cpp
// ---------------------------------------------------------------------------
#include "common.h"
#include "eepolicy.h"
#include "corhost.h"
#include "dbginterface.h"
#include "eemessagebox.h"
#include "eventreporter.h"
#include "finalizerthread.h"
#include "threadsuspend.h"
#include "typestring.h"
#ifndef FEATURE_PAL
#include "dwreport.h"
#endif // !FEATURE_PAL
#include "eventtrace.h"
#undef ExitProcess
BYTE g_EEPolicyInstance[sizeof(EEPolicy)];
void InitEEPolicy()
{
WRAPPER_NO_CONTRACT;
new (g_EEPolicyInstance) EEPolicy();
}
EEPolicy::EEPolicy ()
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
}
CONTRACTL_END;
int n;
for (n = 0; n < MaxClrOperation; n++) {
m_Timeout[n] = INFINITE;
m_ActionOnTimeout[n] = eNoAction;
m_DefaultAction[n] = eNoAction;
}
m_Timeout[OPR_ProcessExit] = 40000;
m_ActionOnTimeout[OPR_ProcessExit] = eRudeExitProcess;
m_ActionOnTimeout[OPR_ThreadAbort] = eAbortThread;
m_ActionOnTimeout[OPR_ThreadRudeAbortInNonCriticalRegion] = eRudeAbortThread;
m_ActionOnTimeout[OPR_ThreadRudeAbortInCriticalRegion] = eRudeAbortThread;
m_DefaultAction[OPR_ThreadAbort] = eAbortThread;
m_DefaultAction[OPR_ThreadRudeAbortInNonCriticalRegion] = eRudeAbortThread;
m_DefaultAction[OPR_ThreadRudeAbortInCriticalRegion] = eRudeAbortThread;
m_DefaultAction[OPR_AppDomainUnload] = eUnloadAppDomain;
m_DefaultAction[OPR_AppDomainRudeUnload] = eRudeUnloadAppDomain;
m_DefaultAction[OPR_ProcessExit] = eExitProcess;
m_DefaultAction[OPR_FinalizerRun] = eNoAction;
for (n = 0; n < MaxClrFailure; n++) {
m_ActionOnFailure[n] = eNoAction;
}
m_ActionOnFailure[FAIL_CriticalResource] = eThrowException;
m_ActionOnFailure[FAIL_NonCriticalResource] = eThrowException;
m_ActionOnFailure[FAIL_OrphanedLock] = eNoAction;
m_ActionOnFailure[FAIL_FatalRuntime] = eRudeExitProcess;
// For CoreCLR, initialize the default action for AV processing to all
// all kind of code to catch AV exception. If the host wants, they can
// specify a different action for this.
m_ActionOnFailure[FAIL_AccessViolation] = eNoAction;
m_ActionOnFailure[FAIL_StackOverflow] = eRudeExitProcess;
m_ActionOnFailure[FAIL_CodeContract] = eThrowException;
m_unhandledExceptionPolicy = eRuntimeDeterminedPolicy;
}
BOOL EEPolicy::IsValidActionForOperation(EClrOperation operation, EPolicyAction action)
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
}
CONTRACTL_END;
switch (operation) {
case OPR_ThreadAbort:
return action >= eAbortThread &&
action < MaxPolicyAction;
case OPR_ThreadRudeAbortInNonCriticalRegion:
case OPR_ThreadRudeAbortInCriticalRegion:
return action >= eRudeAbortThread && action != eUnloadAppDomain &&
action < MaxPolicyAction;
case OPR_AppDomainUnload:
return action >= eUnloadAppDomain &&
action < MaxPolicyAction;
case OPR_AppDomainRudeUnload:
return action >= eRudeUnloadAppDomain &&
action < MaxPolicyAction;
case OPR_ProcessExit:
return action >= eExitProcess &&
action < MaxPolicyAction;
case OPR_FinalizerRun:
return action == eNoAction ||
(action >= eAbortThread &&
action < MaxPolicyAction);
default:
_ASSERT (!"Do not know valid action for this operation");
break;
}
return FALSE;
}
BOOL EEPolicy::IsValidActionForTimeout(EClrOperation operation, EPolicyAction action)
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
}
CONTRACTL_END;
switch (operation) {
case OPR_ThreadAbort:
return action > eAbortThread &&
action < MaxPolicyAction;
case OPR_ThreadRudeAbortInNonCriticalRegion:
case OPR_ThreadRudeAbortInCriticalRegion:
return action > eRudeUnloadAppDomain &&
action < MaxPolicyAction;
case OPR_AppDomainUnload:
return action > eUnloadAppDomain &&
action < MaxPolicyAction;
case OPR_AppDomainRudeUnload:
return action > eRudeUnloadAppDomain &&
action < MaxPolicyAction;
case OPR_ProcessExit:
return action > eExitProcess &&
action < MaxPolicyAction;
case OPR_FinalizerRun:
return action == eNoAction ||
(action >= eAbortThread &&
action < MaxPolicyAction);
default:
_ASSERT (!"Do not know valid action for this operation");
break;
}
return FALSE;
}
BOOL EEPolicy::IsValidActionForFailure(EClrFailure failure, EPolicyAction action)
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
}
CONTRACTL_END;
switch (failure) {
case FAIL_NonCriticalResource:
return action >= eThrowException &&
action < MaxPolicyAction;
case FAIL_CriticalResource:
return action >= eThrowException &&
action < MaxPolicyAction;
case FAIL_FatalRuntime:
return action >= eRudeExitProcess &&
action < MaxPolicyAction;
case FAIL_OrphanedLock:
return action >= eUnloadAppDomain &&
action < MaxPolicyAction;
case FAIL_AccessViolation:
// Allowed actions on failure are:
//
// eNoAction or eRudeExitProcess.
return ((action == eNoAction) || (action == eRudeExitProcess));
case FAIL_StackOverflow:
return action >= eRudeUnloadAppDomain &&
action < MaxPolicyAction;
case FAIL_CodeContract:
return action >= eThrowException &&
action <= eExitProcess;
default:
_ASSERTE (!"Do not know valid action for this failure");
break;
}
return FALSE;
}
HRESULT EEPolicy::SetTimeout(EClrOperation operation, DWORD timeout)
{
CONTRACTL
{
MODE_ANY;
GC_NOTRIGGER;
NOTHROW;
}
CONTRACTL_END;
if (static_cast<UINT>(operation) < MaxClrOperation)
{
m_Timeout[operation] = timeout;
if (operation == OPR_FinalizerRun &&
g_fEEStarted)
{
FastInterlockOr((DWORD*)&g_FinalizerWaiterStatus, FWS_WaitInterrupt);
FinalizerThread::SignalFinalizationDone(FALSE);
}
return S_OK;
}
else
{
return E_INVALIDARG;
}
}
HRESULT EEPolicy::SetActionOnTimeout(EClrOperation operation, EPolicyAction action)
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
}
CONTRACTL_END;
if (static_cast<UINT>(operation) < MaxClrOperation &&
IsValidActionForTimeout(operation, action))
{
m_ActionOnTimeout[operation] = action;
return S_OK;
}
else
{
return E_INVALIDARG;
}
}
EPolicyAction EEPolicy::GetFinalAction(EPolicyAction action, Thread *pThread)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(static_cast<UINT>(action) < MaxPolicyAction);
if (action < eAbortThread || action > eFastExitProcess)
{
return action;
}
while(TRUE)
{
// Look at default action. If the default action is more severe,
// use the default action instead.
EPolicyAction defaultAction = action;
switch (action)
{
case eAbortThread:
defaultAction = m_DefaultAction[OPR_ThreadAbort];
break;
case eRudeAbortThread:
if (pThread && !pThread->HasLockInCurrentDomain())
{
defaultAction = m_DefaultAction[OPR_ThreadRudeAbortInNonCriticalRegion];
}
else
{
defaultAction = m_DefaultAction[OPR_ThreadRudeAbortInCriticalRegion];
}
break;
case eUnloadAppDomain:
defaultAction = m_DefaultAction[OPR_AppDomainUnload];
break;
case eRudeUnloadAppDomain:
defaultAction = m_DefaultAction[OPR_AppDomainRudeUnload];
break;
case eExitProcess:
case eFastExitProcess:
defaultAction = m_DefaultAction[OPR_ProcessExit];
if (defaultAction < action)
{
defaultAction = action;
}
break;
default:
break;
}
_ASSERTE(static_cast<UINT>(defaultAction) < MaxPolicyAction);
if (defaultAction == action)
{
return action;
}
_ASSERTE(defaultAction > action);
action = defaultAction;
}
}
// Allow setting timeout and action in one call.
// If we decide to have atomical operation on Policy, we can use lock here
// while SetTimeout and SetActionOnTimeout can not.
HRESULT EEPolicy::SetTimeoutAndAction(EClrOperation operation, DWORD timeout, EPolicyAction action)
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
}
CONTRACTL_END;
if (static_cast<UINT>(operation) < MaxClrOperation &&
IsValidActionForTimeout(operation, action))
{
m_ActionOnTimeout[operation] = action;
m_Timeout[operation] = timeout;
if (operation == OPR_FinalizerRun &&
g_fEEStarted)
{
FastInterlockOr((DWORD*)&g_FinalizerWaiterStatus, FWS_WaitInterrupt);
FinalizerThread::SignalFinalizationDone(FALSE);
}
return S_OK;
}
else
{
return E_INVALIDARG;
}
}
HRESULT EEPolicy::SetDefaultAction(EClrOperation operation, EPolicyAction action)
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
}
CONTRACTL_END;
if (static_cast<UINT>(operation) < MaxClrOperation &&
IsValidActionForOperation(operation, action))
{
m_DefaultAction[operation] = action;
return S_OK;
}
else
{
return E_INVALIDARG;
}
}
HRESULT EEPolicy::SetActionOnFailure(EClrFailure failure, EPolicyAction action)
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
}
CONTRACTL_END;
if (static_cast<UINT>(failure) < MaxClrFailure &&
IsValidActionForFailure(failure, action))
{
m_ActionOnFailure[failure] = action;
return S_OK;
}
else
{
return E_INVALIDARG;
}
}
EPolicyAction EEPolicy::GetActionOnFailureNoHostNotification(EClrFailure failure)
{
CONTRACTL
{
MODE_ANY;
GC_NOTRIGGER;
NOTHROW;
}CONTRACTL_END;
_ASSERTE (failure < MaxClrFailure);
if (failure == FAIL_StackOverflow)
{
return m_ActionOnFailure[failure];
}
return GetFinalAction(m_ActionOnFailure[failure], GetThread());
}
EPolicyAction EEPolicy::GetActionOnFailure(EClrFailure failure)
{
CONTRACTL
{
MODE_ANY;
GC_NOTRIGGER;
NOTHROW;
}CONTRACTL_END;
_ASSERTE(static_cast<UINT>(failure) < MaxClrFailure);
if (failure == FAIL_StackOverflow)
{
return m_ActionOnFailure[failure];
}
EPolicyAction finalAction = GetActionOnFailureNoHostNotification(failure);
return finalAction;
}
void EEPolicy::NotifyHostOnTimeout(EClrOperation operation, EPolicyAction action)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
}
void EEPolicy::NotifyHostOnDefaultAction(EClrOperation operation, EPolicyAction action)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
}
void SafeExitProcess(UINT exitCode, BOOL fAbort = FALSE, ShutdownCompleteAction sca = SCA_ExitProcessWhenShutdownComplete)
{
STRESS_LOG2(LF_SYNC, LL_INFO10, "SafeExitProcess: exitCode = %d, fAbort = %d\n", exitCode, fAbort);
CONTRACTL
{
DISABLED(GC_TRIGGERS);
NOTHROW;
}
CONTRACTL_END;
// The runtime must be in the appropriate thread mode when we exit, so that we
// aren't surprised by the thread mode when our DLL_PROCESS_DETACH occurs, or when
// other DLLs call Release() on us in their detach [dangerous!], etc.
GCX_PREEMP_NO_DTOR();
FastInterlockExchange((LONG*)&g_fForbidEnterEE, TRUE);
// Note that for free and retail builds StressLog must also be enabled
if (g_pConfig && g_pConfig->StressLog())
{
if (CLRConfig::GetConfigValue(CLRConfig::UNSUPPORTED_BreakOnBadExit))
{
// Workaround for aspnet
PathString wszFilename;
bool bShouldAssert = true;
if (WszGetModuleFileName(NULL, wszFilename))
{
wszFilename.LowerCase();
if (wcsstr(wszFilename, W("aspnet_compiler")))
{
bShouldAssert = false;
}
}
unsigned goodExit = CLRConfig::GetConfigValue(CLRConfig::UNSUPPORTED_SuccessExit);
if (bShouldAssert && exitCode != goodExit)
{
_ASSERTE(!"Bad Exit value");
FAULT_NOT_FATAL(); // if we OOM we can simply give up
SetErrorMode(0); // Insure that we actually cause the messsage box to pop.
EEMessageBoxCatastrophic(IDS_EE_ERRORMESSAGETEMPLATE, IDS_EE_ERRORTITLE, exitCode, W("BreakOnBadExit: returning bad exit code"));
}
}
}
// If we call ExitProcess, other threads will be torn down
// so we don't get to debug their state. Stop this!
#ifdef _DEBUG
if (_DbgBreakCount)
_ASSERTE(!"In SafeExitProcess: An assert was hit on some other thread");
#endif
// Turn off exception processing, because if some other random DLL has a
// fault in DLL_PROCESS_DETACH, we could get called for exception handling.
// Since we've turned off part of the runtime, we can't, for instance,
// properly execute the GC that handling an exception might trigger.
g_fNoExceptions = true;
LOG((LF_EH, LL_INFO10, "SafeExitProcess: turning off exceptions\n"));
if (sca == SCA_ExitProcessWhenShutdownComplete)
{
// disabled because if we fault in this code path we will trigger our
// Watson code
CONTRACT_VIOLATION(ThrowsViolation);
#ifdef FEATURE_PAL
if (fAbort)
{
TerminateProcess(GetCurrentProcess(), exitCode);
}
#endif
EEPolicy::ExitProcessViaShim(exitCode);
}
}
// This is a helper to exit the process after coordinating with the shim. It is used by
// SafeExitProcess above, as well as from CorHost2::ExitProcess when we know that we must
// exit the process without doing further work to shutdown this runtime. This first attempts
// to call back to the Shim to shutdown any other runtimes within the process.
//
// IMPORTANT NOTE: exercise extreme caution when adding new calls to this method. It is highly
// likely that you want to call SafeExitProcess, or EEPolicy::HandleExitProcess instead of this.
// This function only exists to factor some common code out of the methods mentioned above.
//static
void EEPolicy::ExitProcessViaShim(UINT exitCode)
{
LIMITED_METHOD_CONTRACT;
// We must call back to the Shim in order to exit the process, as this may be just one
// runtime in a process with many. We need to give the other runtimes a chance to exit
// cleanly. If we can't make the call, or if the call fails for some reason, then we
// simply exit the process here, which is rude to the others, but the best we can do.
ExitProcess(exitCode);
}
//---------------------------------------------------------------------------------------
// HandleExitProcessHelper is used to shutdown the runtime as specified by the given
// action, then to exit the process. Note, however, that the process will not exit if
// sca is SCA_ReturnWhenShutdownComplete. In that case, this method will simply return after
// performing the shutdown actions.
//---------------------------------------------------------------------------------------
// If g_fFastExitProcess is 0, normal shutdown
// If g_fFastExitProcess is 1, fast shutdown. Only doing log.
// If g_fFastExitProcess is 2, do not run EEShutDown.
DWORD g_fFastExitProcess = 0;
extern void STDMETHODCALLTYPE EEShutDown(BOOL fIsDllUnloading);
static void HandleExitProcessHelper(EPolicyAction action, UINT exitCode, ShutdownCompleteAction sca)
{
WRAPPER_NO_CONTRACT;
switch (action) {
case eFastExitProcess:
g_fFastExitProcess = 1;
case eExitProcess:
if (g_fEEStarted)
{
EEShutDown(FALSE);
}
if (exitCode == 0)
{
exitCode = GetLatchedExitCode();
}
SafeExitProcess(exitCode, FALSE, sca);
break;
case eRudeExitProcess:
g_fFastExitProcess = 2;
SafeExitProcess(exitCode, TRUE, sca);
break;
default:
_ASSERTE (!"Invalid policy");
break;
}
}
EPolicyAction EEPolicy::DetermineResourceConstraintAction(Thread *pThread)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
EPolicyAction action;
if (pThread->HasLockInCurrentDomain()) {
action = GetEEPolicy()->GetActionOnFailure(FAIL_CriticalResource);
}
else
action = GetEEPolicy()->GetActionOnFailure(FAIL_NonCriticalResource);
AppDomain *pDomain = GetAppDomain();
// If it is default domain, we can not unload the appdomain
if (pDomain == SystemDomain::System()->DefaultDomain() &&
(action == eUnloadAppDomain || action == eRudeUnloadAppDomain))
{
action = eThrowException;
}
return action;
}
void EEPolicy::PerformResourceConstraintAction(Thread *pThread, EPolicyAction action, UINT exitCode, BOOL haveStack)
{
WRAPPER_NO_CONTRACT;
_ASSERTE(GetAppDomain() != NULL);
switch (action) {
case eThrowException:
// Caller is going to rethrow.
return;
break;
case eAbortThread:
pThread->UserAbort(Thread::TAR_Thread, TA_Safe, GetEEPolicy()->GetTimeout(OPR_ThreadAbort), Thread::UAC_Normal);
break;
case eRudeAbortThread:
pThread->UserAbort(Thread::TAR_Thread, TA_Rude, GetEEPolicy()->GetTimeout(OPR_ThreadAbort), Thread::UAC_Normal);
break;
case eExitProcess:
case eFastExitProcess:
case eRudeExitProcess:
HandleExitProcessFromEscalation(action, exitCode);
break;
default:
_ASSERTE (!"Invalid policy");
break;
}
}
void EEPolicy::HandleOutOfMemory()
{
WRAPPER_NO_CONTRACT;
_ASSERTE (g_pOutOfMemoryExceptionClass);
Thread *pThread = GetThread();
_ASSERTE (pThread);
EPolicyAction action = DetermineResourceConstraintAction(pThread);
// Check if we are executing in the context of a Constrained Execution Region.
if (action != eThrowException && Thread::IsExecutingWithinCer())
{
// Hitting OOM in a CER region should throw the OOM without regard to the escalation policy
// since the CER author has declared they are hardened against such failures. That's
// the whole point of CERs, to denote regions where code knows exactly how to deal with
// failures in an attempt to minimize the need for rollback or recycling.
return;
}
PerformResourceConstraintAction(pThread, action, HOST_E_EXITPROCESS_OUTOFMEMORY, TRUE);
}
//---------------------------------------------------------------------------------------
//
// EEPolicy::HandleStackOverflow - Handle stack overflow according to policy
//
// Arguments:
// detector:
// pLimitFrame: the limit of search for frames in order to decide if in SO tolerant
//
// Return Value:
// None.
//
// How is stack overflow handled?
// If stack overflows in non-hosted case, we terminate the process.
// For hosted case with escalation policy
// 1. If stack overflows in managed code, or in VM before switching to SO intolerant region, and the GC mode is Cooperative
// the domain is rudely unloaded, or the process is terminated if the current domain is default domain.
// a. This action is done through BEGIN_SO_TOLERANT_CODE if there is one.
// b. If there is not this macro on the stack, we mark the domain being unload requested, and when the thread
// dies or is recycled, we finish the AD unload.
// 2. If stack overflows in SO tolerant region, but the GC mode is Preemptive, the process is killed in vector handler, or our
// managed exception handler (COMPlusFrameHandler or ProcessCLRException).
// 3. If stack overflows in SO intolerant region, the process is killed as soon as the exception is seen by our vector handler, or
// our managed exception handler.
//
// The process is terminated if there is StackOverflow as all clr code is considered SO Intolerant.
void EEPolicy::HandleStackOverflow(StackOverflowDetector detector, void * pLimitFrame)
{
WRAPPER_NO_CONTRACT;
STRESS_LOG0(LF_EH, LL_INFO100, "In EEPolicy::HandleStackOverflow\n");
Thread *pThread = GetThread();
if (pThread == NULL)
{
// For security reason, it is not safe to continue execution if stack overflow happens
return;
}
EXCEPTION_POINTERS exceptionInfo;
GetCurrentExceptionPointers(&exceptionInfo);
_ASSERTE(exceptionInfo.ExceptionRecord);
EEPolicy::HandleFatalStackOverflow(&exceptionInfo);
}
// We provide WatsonLastChance with a SO exception record. The ExceptionAddress is set to 0
// here. This ExceptionPointers struct is handed off to the debugger as is. A copy of this struct
// is made before invoking Watson and the ExceptionAddress is set by inspecting the stack. Note
// that the ExceptionContext member is unused and so it's ok to set it to NULL.
static EXCEPTION_RECORD g_SOExceptionRecord = {
STATUS_STACK_OVERFLOW, // ExceptionCode
0, // ExceptionFlags
NULL, // ExceptionRecord
0, // ExceptionAddress
0, // NumberOfParameters
{} }; // ExceptionInformation
EXCEPTION_POINTERS g_SOExceptionPointers = {&g_SOExceptionRecord, NULL};
//---------------------------------------------------------------------------------------
// HandleExitProcess is used to shutdown the runtime, based on policy previously set,
// then to exit the process. Note, however, that the process will not exit if
// sca is SCA_ReturnWhenShutdownComplete. In that case, this method will simply return after
// performing the shutdown actions.
//---------------------------------------------------------------------------------------
void EEPolicy::HandleExitProcess(ShutdownCompleteAction sca)
{
WRAPPER_NO_CONTRACT;
STRESS_LOG0(LF_EH, LL_INFO100, "In EEPolicy::HandleExitProcess\n");
EPolicyAction action = GetEEPolicy()->GetDefaultAction(OPR_ProcessExit, NULL);
GetEEPolicy()->NotifyHostOnDefaultAction(OPR_ProcessExit,action);
HandleExitProcessHelper(action, 0, sca);
}
StackWalkAction LogCallstackForLogCallback(
CrawlFrame *pCF, //
VOID* pData // Caller's private data
)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
SmallStackSString *pWordAt = ((SmallStackSString*)pData);
MethodDesc *pMD = pCF->GetFunction();
_ASSERTE(pMD != NULL);
StackSString str;
str = *pWordAt;
TypeString::AppendMethodInternal(str, pMD, TypeString::FormatNamespace|TypeString::FormatFullInst|TypeString::FormatSignature);
PrintToStdErrW(str.GetUnicode());
PrintToStdErrA("\n");
return SWA_CONTINUE;
}
//---------------------------------------------------------------------------------------
//
// A worker to save managed stack trace.
//
// Arguments:
// None
//
// Return Value:
// None
//
inline void LogCallstackForLogWorker()
{
Thread* pThread = GetThread();
_ASSERTE (pThread);
SmallStackSString WordAt;
if (!WordAt.LoadResource(CCompRC::Optional, IDS_ER_WORDAT))
{
WordAt.Set(W(" at"));
}
else
{
WordAt.Insert(WordAt.Begin(), W(" "));
}
WordAt += W(" ");
pThread->StackWalkFrames(&LogCallstackForLogCallback, &WordAt, QUICKUNWIND | FUNCTIONSONLY);
}
//---------------------------------------------------------------------------------------
//
// Print information on fatal error to stderr.
//
// Arguments:
// exitCode - code of the fatal error
// pszMessage - error message (can be NULL)
// errorSource - details on the source of the error (can be NULL)
// argExceptionString - exception details (can be NULL)
//
// Return Value:
// None
//
void LogInfoForFatalError(UINT exitCode, LPCWSTR pszMessage, LPCWSTR errorSource, LPCWSTR argExceptionString)
{
WRAPPER_NO_CONTRACT;
Thread *pThread = GetThread();
EX_TRY
{
if (exitCode == (UINT)COR_E_FAILFAST)
{
PrintToStdErrA("Process terminated. ");
}
else
{
PrintToStdErrA("Fatal error. ");
}
if (errorSource != NULL)
{
PrintToStdErrW(errorSource);
PrintToStdErrA("\n");
}
if (pszMessage != NULL)
{
PrintToStdErrW(pszMessage);
}
else
{
// If no message was passed in, generate it from the exitCode
SString exitCodeMessage;
GetHRMsg(exitCode, exitCodeMessage);
PrintToStdErrW((LPCWSTR)exitCodeMessage);
}
PrintToStdErrA("\n");
if (pThread && errorSource == NULL)
{
LogCallstackForLogWorker();
if (argExceptionString != NULL) {
PrintToStdErrW(argExceptionString);
}
}
}
EX_CATCH
{
}
EX_END_CATCH(SwallowAllExceptions)
}
//This starts FALSE and then converts to true if HandleFatalError has ever been called by a GC thread
BOOL g_fFatalErrorOccuredOnGCThread = FALSE;
//
// Log an error to the event log if possible, then throw up a dialog box.
//
void EEPolicy::LogFatalError(UINT exitCode, UINT_PTR address, LPCWSTR pszMessage, PEXCEPTION_POINTERS pExceptionInfo, LPCWSTR errorSource, LPCWSTR argExceptionString)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_MODE_ANY;
_ASSERTE(pExceptionInfo != NULL);
// Log exception to StdErr
LogInfoForFatalError(exitCode, pszMessage, errorSource, argExceptionString);
if(ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PRIVATE_PROVIDER_Context, FailFast))
{
// Fire an ETW FailFast event
FireEtwFailFast(pszMessage,
(const PVOID)address,
((pExceptionInfo && pExceptionInfo->ExceptionRecord) ? pExceptionInfo->ExceptionRecord->ExceptionCode : 0),
exitCode,
GetClrInstanceId());
}
#ifndef FEATURE_PAL
// Write an event log entry. We do allocate some resources here (spread between the stack and maybe the heap for longer
// messages), so it's possible for the event write to fail. If needs be we can use a more elaborate scheme here in the future
// (maybe trying multiple approaches and backing off on failure, falling back on a limited size static buffer as a last
// resort). In all likelihood the Win32 event reporting mechanism requires resources though, so it's not clear how much
// effort we should put into this without knowing the benefit we'd receive.
EX_TRY
{
if (ShouldLogInEventLog())
{
// If the exit code is COR_E_FAILFAST then the fatal error was raised by managed code and the address argument points to a
// unicode message buffer rather than a faulting EIP.
EventReporter::EventReporterType failureType = EventReporter::ERT_UnmanagedFailFast;
if (exitCode == (UINT)COR_E_FAILFAST)
failureType = EventReporter::ERT_ManagedFailFast;
else if (exitCode == (UINT)COR_E_CODECONTRACTFAILED)
failureType = EventReporter::ERT_CodeContractFailed;
EventReporter reporter(failureType);
StackSString s(argExceptionString);
if ((exitCode == (UINT)COR_E_FAILFAST) || (exitCode == (UINT)COR_E_CODECONTRACTFAILED) || (exitCode == (UINT)CLR_E_GC_OOM))
{
if (pszMessage)
{
reporter.AddDescription((WCHAR*)pszMessage);
}
if (argExceptionString)
{
reporter.AddFailFastStackTrace(s);
}
if (exitCode != (UINT)CLR_E_GC_OOM)
LogCallstackForEventReporter(reporter);
}
else
{
// Fetch the localized Fatal Execution Engine Error text or fall back on a hardcoded variant if things get dire.
InlineSString<80> ssMessage;
InlineSString<80> ssErrorFormat;
if(!ssErrorFormat.LoadResource(CCompRC::Optional, IDS_ER_UNMANAGEDFAILFASTMSG ))
ssErrorFormat.Set(W("at IP %1 (%2) with exit code %3."));
SmallStackSString addressString;
addressString.Printf(W("%p"), pExceptionInfo? (UINT_PTR)pExceptionInfo->ExceptionRecord->ExceptionAddress : address);
// We should always have the reference to the runtime's instance
_ASSERTE(g_pMSCorEE != NULL);
// Setup the string to contain the runtime's base address. Thus, when customers report FEEE with just
// the event log entry containing this string, we can use the absolute and base addresses to determine
// where the fault happened inside the runtime.
SmallStackSString runtimeBaseAddressString;
runtimeBaseAddressString.Printf(W("%p"), g_pMSCorEE);
SmallStackSString exitCodeString;
exitCodeString.Printf(W("%x"), exitCode);
// Format the string
ssMessage.FormatMessage(FORMAT_MESSAGE_FROM_STRING, (LPCWSTR)ssErrorFormat, 0, 0, addressString, runtimeBaseAddressString,
exitCodeString);
reporter.AddDescription(ssMessage);
}
reporter.Report();
}
}
EX_CATCH
{
}
EX_END_CATCH(SwallowAllExceptions)
#endif // !FEATURE_PAL
#ifdef _DEBUG
// If we're native-only (Win32) debugging this process, we'd love to break now.
// However, we should not do this because a managed debugger attached to a
// SxS runtime also appears to be a native debugger. Unfortunately, the managed
// debugger won't handle any native event from another runtime, which means this
// breakpoint would go unhandled and terminate the process. Instead, we will let
// the process continue so at least the fatal error is logged rather than abrupt
// termination.
//
// This behavior can still be overridden if the right config value is set.
if (IsDebuggerPresent())
{
bool fBreak = (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_DbgOOBinFEEE) != 0);
if (fBreak)
{
DebugBreak();
}
}
#endif // _DEBUG
{
#ifdef DEBUGGING_SUPPORTED
//Give a managed debugger a chance if this fatal error is on a managed thread.
Thread *pThread = GetThread();
if (pThread && !g_fFatalErrorOccuredOnGCThread)
{
GCX_COOP();
OBJECTHANDLE ohException = NULL;
if (exitCode == (UINT)COR_E_STACKOVERFLOW)
{
// If we're going down because of stack overflow, go ahead and use the preallocated SO exception.
ohException = CLRException::GetPreallocatedStackOverflowExceptionHandle();
}
else
{
// Though we would like to remove the usage of ExecutionEngineException in any manner,
// we cannot. Its okay to use it in the case below since the process is terminating
// and this will serve as an exception object for debugger.
ohException = CLRException::GetPreallocatedExecutionEngineExceptionHandle();
}
// Preallocated exception handles can be null if FailFast is invoked before LoadBaseSystemClasses
// (in SystemDomain::Init) finished. See Dev10 Bug 677432 for the detail.
if (ohException != NULL)
{
// for fail-fast, if there's a LTO available then use that as the inner exception object
// for the FEEE we'll be reporting. this can help the Watson back-end to generate better
// buckets for apps that call Environment.FailFast() and supply an exception object.
OBJECTREF lto = pThread->LastThrownObject();
if (exitCode == static_cast<UINT>(COR_E_FAILFAST) && lto != NULL)
{
EXCEPTIONREF curEx = (EXCEPTIONREF)ObjectFromHandle(ohException);
curEx->SetInnerException(lto);
}
pThread->SetLastThrownObject(ObjectFromHandle(ohException), TRUE);
}
// If a managed debugger is already attached, and if that debugger is thinking it might be inclined to
// try to intercept this excepiton, then tell it that's not possible.
if (pThread->IsExceptionInProgress())
{
pThread->GetExceptionState()->GetFlags()->SetDebuggerInterceptNotPossible();
}
}
if (EXCEPTION_CONTINUE_EXECUTION == WatsonLastChance(pThread, pExceptionInfo, TypeOfReportedError::FatalError))
{
LOG((LF_EH, LL_INFO100, "EEPolicy::LogFatalError: debugger ==> EXCEPTION_CONTINUE_EXECUTION\n"));
_ASSERTE(!"Debugger should not have returned ContinueExecution");
}
#endif // DEBUGGING_SUPPORTED
}
}
void DisplayStackOverflowException()
{
LIMITED_METHOD_CONTRACT;
PrintToStdErrA("Stack overflow.\n");
}
void DECLSPEC_NORETURN EEPolicy::HandleFatalStackOverflow(EXCEPTION_POINTERS *pExceptionInfo, BOOL fSkipDebugger)
{
// This is fatal error. We do not care about SO mode any more.
// All of the code from here on out is robust to any failures in any API's that are called.
CONTRACT_VIOLATION(GCViolation | ModeViolation | FaultNotFatal | TakesLockViolation);
WRAPPER_NO_CONTRACT;
STRESS_LOG0(LF_EH, LL_INFO100, "In EEPolicy::HandleFatalStackOverflow\n");
DisplayStackOverflowException();
if(ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PRIVATE_PROVIDER_Context, FailFast))
{
// Fire an ETW FailFast event
FireEtwFailFast(W("StackOverflowException"),
(const PVOID)((pExceptionInfo && pExceptionInfo->ContextRecord) ? GetIP(pExceptionInfo->ContextRecord) : 0),
((pExceptionInfo && pExceptionInfo->ExceptionRecord) ? pExceptionInfo->ExceptionRecord->ExceptionCode : 0),
COR_E_STACKOVERFLOW,
GetClrInstanceId());
}
if (!fSkipDebugger)
{
Thread *pThread = GetThread();
BOOL fTreatAsNativeUnhandledException = FALSE;
if (pThread)
{
GCX_COOP();
// If we had a SO before preallocated exception objects are initialized, we will AV here. This can happen
// during the initialization of SystemDomain during EEStartup. Thus, setup the SO throwable only if its not
// NULL.
//
// When WatsonLastChance (WLC) is invoked below, it treats this case as UnhandledException. If there is no
// managed exception object available, we should treat this case as NativeUnhandledException. This aligns
// well with the fact that there cannot be a managed debugger attached at this point that will require
// LastChanceManagedException notification to be delivered. Also, this is the same as how
// we treat an unhandled exception as NativeUnhandled when throwable is not available.
OBJECTHANDLE ohSO = CLRException::GetPreallocatedStackOverflowExceptionHandle();
if (ohSO != NULL)
{
pThread->SafeSetThrowables(ObjectFromHandle(ohSO)
DEBUG_ARG(ThreadExceptionState::STEC_CurrentTrackerEqualNullOkHackForFatalStackOverflow),
TRUE);
}
else
{
// We dont have a throwable - treat this as native unhandled exception
fTreatAsNativeUnhandledException = TRUE;
}
}
FrameWithCookie<FaultingExceptionFrame> fef;
#if defined(WIN64EXCEPTIONS)
*((&fef)->GetGSCookiePtr()) = GetProcessGSCookie();
#endif // WIN64EXCEPTIONS
if (pExceptionInfo && pExceptionInfo->ContextRecord)
{
GCX_COOP();
fef.InitAndLink(pExceptionInfo->ContextRecord);
}
#ifndef FEATURE_PAL
if (IsWatsonEnabled() && (g_pDebugInterface != NULL))
{
_ASSERTE(pExceptionInfo != NULL);
ResetWatsonBucketsParams param;
param.m_pThread = pThread;
param.pExceptionRecord = pExceptionInfo->ExceptionRecord;
g_pDebugInterface->RequestFavor(ResetWatsonBucketsFavorWorker, reinterpret_cast<void *>(¶m));
}
#endif // !FEATURE_PAL
WatsonLastChance(pThread, pExceptionInfo,
(fTreatAsNativeUnhandledException == FALSE)? TypeOfReportedError::UnhandledException: TypeOfReportedError::NativeThreadUnhandledException);
}
TerminateProcess(GetCurrentProcess(), COR_E_STACKOVERFLOW);
UNREACHABLE();
}
#if defined(_TARGET_X86_) && defined(PLATFORM_WINDOWS)
// This noinline method is required to ensure that RtlCaptureContext captures
// the context of HandleFatalError. On x86 RtlCaptureContext will not capture
// the current method's context
// NOTE: explicitly turning off optimizations to force the compiler to spill to the
// stack and establish a stack frame. This is required to ensure that
// RtlCaptureContext captures the context of HandleFatalError
#pragma optimize("", off)
int NOINLINE WrapperClrCaptureContext(CONTEXT* context)
{
ClrCaptureContext(context);
return 0;
}
#pragma optimize("", on)
#endif // defined(_TARGET_X86_) && defined(PLATFORM_WINDOWS)
// This method must return a value to avoid getting non-actionable dumps on x86.
// If this method were a DECLSPEC_NORETURN then dumps would not provide the necessary
// context at the point of the failure
int NOINLINE EEPolicy::HandleFatalError(UINT exitCode, UINT_PTR address, LPCWSTR pszMessage /* = NULL */, PEXCEPTION_POINTERS pExceptionInfo /* = NULL */, LPCWSTR errorSource /* = NULL */, LPCWSTR argExceptionString /* = NULL */)
{
WRAPPER_NO_CONTRACT;
// All of the code from here on out is robust to any failures in any API's that are called.
FAULT_NOT_FATAL();
EXCEPTION_RECORD exceptionRecord;
EXCEPTION_POINTERS exceptionPointers;
CONTEXT context;
if (pExceptionInfo == NULL)
{
ZeroMemory(&exceptionPointers, sizeof(exceptionPointers));
ZeroMemory(&exceptionRecord, sizeof(exceptionRecord));
ZeroMemory(&context, sizeof(context));
context.ContextFlags = CONTEXT_CONTROL;
#if defined(_TARGET_X86_) && defined(PLATFORM_WINDOWS)
// Add a frame to ensure that the context captured is this method and not the caller
WrapperClrCaptureContext(&context);
#else // defined(_TARGET_X86_) && defined(PLATFORM_WINDOWS)
ClrCaptureContext(&context);
#endif
exceptionRecord.ExceptionCode = exitCode;
exceptionRecord.ExceptionAddress = reinterpret_cast< PVOID >(address);
exceptionPointers.ExceptionRecord = &exceptionRecord;
exceptionPointers.ContextRecord = &context;
pExceptionInfo = &exceptionPointers;
}
// All of the code from here on out is allowed to trigger a GC, even if we're in a no-trigger region. We're
// ripping the process down due to a fatal error... our invariants are already gone.
{
// This is fatal error. We do not care about SO mode any more.
// All of the code from here on out is robust to any failures in any API's that are called.
CONTRACT_VIOLATION(GCViolation | ModeViolation | FaultNotFatal | TakesLockViolation);
// Setting g_fFatalErrorOccuredOnGCThread allows code to avoid attempting to make GC mode transitions which could
// block indefinately if the fatal error occured during the GC.
if (IsGCSpecialThread() && GCHeapUtilities::IsGCInProgress())
{
g_fFatalErrorOccuredOnGCThread = TRUE;
}
// ThreadStore lock needs to be released before continuing with the FatalError handling should
// because debugger is going to take CrstDebuggerMutex, whose lock level is higher than that of
// CrstThreadStore. It should be safe to release the lock since execution will not be resumed
// after fatal errors.
if (ThreadStore::HoldingThreadStore(GetThread()))
{
ThreadSuspend::UnlockThreadStore();
}
g_fFastExitProcess = 2;
STRESS_LOG0(LF_CORDB,LL_INFO100, "D::HFE: About to call LogFatalError\n");
switch (GetEEPolicy()->GetActionOnFailure(FAIL_FatalRuntime))
{
case eRudeExitProcess:
LogFatalError(exitCode, address, pszMessage, pExceptionInfo, errorSource, argExceptionString);
SafeExitProcess(exitCode, TRUE);
break;
default:
_ASSERTE(!"Invalid action for FAIL_FatalRuntime");
break;
}
}
UNREACHABLE();
return -1;
}
void EEPolicy::HandleExitProcessFromEscalation(EPolicyAction action, UINT exitCode)
{
WRAPPER_NO_CONTRACT;
CONTRACT_VIOLATION(GCViolation);
_ASSERTE (action >= eExitProcess);
// If policy for ExitProcess is not default action, i.e. ExitProcess, we will use it.
// Otherwise overwrite it with passing arg action;
EPolicyAction todo = GetEEPolicy()->GetDefaultAction(OPR_ProcessExit, NULL);
if (todo == eExitProcess)
{
todo = action;
}
GetEEPolicy()->NotifyHostOnDefaultAction(OPR_ProcessExit,todo);
HandleExitProcessHelper(todo, exitCode, SCA_ExitProcessWhenShutdownComplete);
}
void EEPolicy::HandleCodeContractFailure(LPCWSTR pMessage, LPCWSTR pCondition, LPCWSTR pInnerExceptionAsString)
{
WRAPPER_NO_CONTRACT;
EEPolicy* pPolicy = GetEEPolicy();
// GetActionOnFailure will notify the host for us.
EPolicyAction action = pPolicy->GetActionOnFailure(FAIL_CodeContract);
Thread* pThread = GetThread();
switch(action) {
case eThrowException:
// Let managed code throw a ContractException (it's easier to pass the right parameters to the constructor).
break;
case eAbortThread:
pThread->UserAbort(Thread::TAR_Thread, TA_Safe, GetEEPolicy()->GetTimeout(OPR_ThreadAbort), Thread::UAC_Normal);
break;
case eRudeAbortThread:
pThread->UserAbort(Thread::TAR_Thread, TA_Rude, GetEEPolicy()->GetTimeout(OPR_ThreadAbort), Thread::UAC_Normal);
break;
case eExitProcess: // Merged w/ default case
default:
_ASSERTE(action == eExitProcess);
// Since we have no exception object, make sure
// UE tracker is clean so that RetrieveManagedBucketParameters
// does not take any bucket details.
#ifndef FEATURE_PAL
pThread->GetExceptionState()->GetUEWatsonBucketTracker()->ClearWatsonBucketDetails();
#endif // !FEATURE_PAL
pPolicy->HandleFatalError(COR_E_CODECONTRACTFAILED, NULL, pMessage);
break;
}
}
| 34.806426 | 229 | 0.645779 | [
"object",
"vector"
] |
b4df564ef23d479db68be2c2b2ae14a06dfac7b1 | 7,954 | cpp | C++ | Source/Dreemchest/Scene/Rendering/RenderCache.cpp | dmsovetov/Dreemchest | 39255c88943abc69c7fa0710b7ca8486c08260e0 | [
"MIT"
] | 11 | 2016-02-18T15:24:49.000Z | 2021-01-30T18:26:04.000Z | Source/Dreemchest/Scene/Rendering/RenderCache.cpp | dmsovetov/dreemchest | 39255c88943abc69c7fa0710b7ca8486c08260e0 | [
"MIT"
] | 2 | 2016-05-23T22:48:35.000Z | 2017-02-13T16:43:32.000Z | Source/Dreemchest/Scene/Rendering/RenderCache.cpp | dmsovetov/dreemchest | 39255c88943abc69c7fa0710b7ca8486c08260e0 | [
"MIT"
] | 3 | 2016-08-19T13:26:59.000Z | 2018-08-03T04:28:14.000Z | /**************************************************************************
The MIT License (MIT)
Copyright (c) 2015 Dmitry Sovetov
https://github.com/dmsovetov
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 "RenderCache.h"
#include "../Assets/Mesh.h"
#include "../Assets/Material.h"
#include "../Assets/Image.h"
DC_BEGIN_DREEMCHEST
namespace Scene {
// ** TestRenderCache::TestRenderCache
TestRenderCache::TestRenderCache( Assets::AssetsWPtr assets, RenderingContextWPtr context )
: m_assets( assets )
, m_context( context )
{
}
// ** TestRenderCache::create
RenderCachePtr TestRenderCache::create( Assets::AssetsWPtr assets, RenderingContextWPtr context )
{
return DC_NEW TestRenderCache( assets, context );
}
// ** TestRenderCache::requestInputLayout
InputLayout TestRenderCache::requestInputLayout( const VertexFormat& format )
{
InputLayouts::iterator i = m_inputLayouts.find( format );
if( i != m_inputLayouts.end() ) {
return i->second;
}
InputLayout id = m_context->requestInputLayout( format );
m_inputLayouts[format] = id;
return id;
}
// ** TestRenderCache::requestVertexBuffer
VertexBuffer_ TestRenderCache::requestVertexBuffer( const MeshHandle& mesh )
{
VertexBuffers::iterator i = m_vertexBuffers.find( mesh.asset().uniqueId() );
if( i != m_vertexBuffers.end() ) {
return i->second;
}
NIMBLE_BREAK_IF( mesh->chunkCount() == 0, "could not cache an empty mesh" );
const Mesh::VertexBuffer& vertices = mesh->vertexBuffer();
VertexFormat vertexFormat( VertexFormat::Normal | VertexFormat::TexCoord0 | VertexFormat::TexCoord1 );
VertexBuffer_ id = m_context->requestVertexBuffer( &vertices[0], vertices.size() * vertexFormat.vertexSize() );
m_vertexBuffers[mesh.asset().uniqueId()] = id;
LogVerbose( "renderCache", "vertex buffer with %d vertices created\n", vertices.size() );
return id;
}
// ** TestRenderCache::requestIndexBuffer
IndexBuffer_ TestRenderCache::requestIndexBuffer( const MeshHandle& mesh )
{
IndexBuffers::iterator i = m_indexBuffers.find( mesh.asset().uniqueId() );
if( i != m_indexBuffers.end() ) {
return i->second;
}
NIMBLE_BREAK_IF( mesh->chunkCount() == 0, "could not cache an empty mesh" );
const Mesh::IndexBuffer& indices = mesh->indexBuffer();
IndexBuffer_ id = m_context->requestIndexBuffer( &indices[0], indices.size() * sizeof( u16 ) );
m_indexBuffers[mesh.asset().uniqueId()] = id;
LogVerbose( "renderCache", "index buffer with %d indices created\n", indices.size() );
return id;
}
// ** TestRenderCache::requestMesh
const TestRenderCache::RenderableNode* TestRenderCache::requestMesh( const MeshHandle& asset )
{
// Return a NULL pointer for invalid meshes
if( !asset.isValid() ) {
return NULL;
}
NIMBLE_ABORT_IF( !asset.isLoaded(), "a mesh asset was not loaded" );
// Get an asset unique id
const Assets::AssetId& assetId = asset.asset().uniqueId();
// First lookup a cached material
RenderableNodeCache::iterator i = m_renderable.find( assetId );
if( i != m_renderable.end() ) {
return i->second.get();
}
// Create a new render node
RenderableNode* node = DC_NEW RenderableNode;
node->offset = 0;
node->count = asset->indexBuffer().size();
node->states.bindVertexBuffer( requestVertexBuffer( asset ) );
node->states.bindIndexBuffer( requestIndexBuffer( asset ) );
node->states.bindInputLayout( requestInputLayout( asset->vertexFormat() ) );
// Associate this material node with an asset identifier
m_renderable[assetId] = node;
LogVerbose( "renderCache", "renderable created from '%s'\n", asset.asset().name().c_str() );
return node;
}
// ** TestRenderCache::createRenderable
const TestRenderCache::RenderableNode* TestRenderCache::createRenderable( const void* vertices, s32 count, const VertexFormat& vertexFormat )
{
VertexBuffer_ vertexBuffer = m_context->requestVertexBuffer( vertices, count * vertexFormat.vertexSize() );
RenderableNode* node = DC_NEW RenderableNode;
node->offset = 0;
node->count = count;
node->states.bindVertexBuffer( vertexBuffer );
node->states.bindInputLayout( requestInputLayout( vertexFormat ) );
return node;
}
// ** TestRenderCache::requestMaterial
const TestRenderCache::MaterialNode* TestRenderCache::requestMaterial( const MaterialHandle& asset )
{
// Return a NULL pointer for invalid materials
if( !asset.isValid() ) {
return NULL;
}
NIMBLE_ABORT_IF( !asset.isLoaded(), "a material asset was not loaded" );
// Get an asset unique id
const Assets::AssetId& assetId = asset.asset().uniqueId();
// First lookup a cached material
MaterialNodeCache::iterator i = m_materials.find( assetId );
if( i != m_materials.end() ) {
return i->second.get();
}
// Create a new material node
MaterialNode* node = DC_NEW MaterialNode;
node->data.diffuse = asset->color( Material::Diffuse );
node->data.specular = asset->color( Material::Specular );
node->data.emission = asset->color( Material::Emission );
node->data.rim.color = Rgb( 1.0f, 0.0f, 0.0f );
node->data.rim.start = 0.25f;
node->data.rim.end = 1.0f;
node->data.rim.factor = 0.5f;
node->constantBuffer = m_context->deprecatedRequestConstantBuffer( &node->data, sizeof( RenderScene::CBuffer::Material ), RenderScene::CBuffer::Material::Layout );
// Now setup a material state block
node->states.bindConstantBuffer( node->constantBuffer, Constants::Material );
for( s32 i = 0; i < Material::TotalMaterialLayers; i++ ) {
Texture_ id = requestTexture( asset->texture( static_cast<Material::Layer>( i ) ) );
if( id ) {
node->states.bindTexture( id, i );
}
}
// Associate this material node with an asset identifier
m_materials[assetId] = node;
LogVerbose( "renderCache", "material '%s' created\n", asset.asset().name().c_str() );
return node;
}
// ** TestRenderCache::requestTexture
Texture_ TestRenderCache::requestTexture( const ImageHandle& image )
{
if( !image.isValid() ) {
return Texture_();
}
NIMBLE_ABORT_IF( !image.isLoaded(), "an image asset was not loaded" );
Textures::iterator i = m_textures.find( image.asset().uniqueId() );
if( i != m_textures.end() ) {
return i->second;
}
const Image& data = *image;
Texture_ id = m_context->requestTexture2D( &data.mipLevel( 0 )[0], data.width(), data.height(), data.bytesPerPixel() == 3 ? Renderer::PixelRgb8 : Renderer::PixelRgba8 );
m_textures[image.asset().uniqueId()] = id;
LogVerbose( "renderCache", "texture created for '%s'\n", image.asset().name().c_str() );
return id;
}
} // namespace Scene
DC_END_DREEMCHEST
| 34.4329 | 173 | 0.680287 | [
"mesh",
"render"
] |
b4e0a6b3bd9de4b23917cb58d4d8d2f6f0d7b069 | 25,449 | cpp | C++ | src/mongo/db/storage/mmap_v1/dur_recover.cpp | leifwalsh/mongo | 4cf51324255f76a110246f6d1646dc8cda570141 | [
"Apache-2.0"
] | 29 | 2015-01-13T02:34:23.000Z | 2022-01-30T16:57:10.000Z | src/mongo/db/storage/mmap_v1/dur_recover.cpp | leifwalsh/mongo | 4cf51324255f76a110246f6d1646dc8cda570141 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/storage/mmap_v1/dur_recover.cpp | leifwalsh/mongo | 4cf51324255f76a110246f6d1646dc8cda570141 | [
"Apache-2.0"
] | 12 | 2015-01-24T08:40:28.000Z | 2017-10-04T17:23:39.000Z | // @file dur_recover.cpp crash recovery via the journal
/**
* Copyright (C) 2009 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kJournal
#include "mongo/platform/basic.h"
#include "mongo/db/storage/mmap_v1/dur_recover.h"
#include <fcntl.h>
#include <iomanip>
#include <iostream>
#include <sys/stat.h>
#include "mongo/db/operation_context_impl.h"
#include "mongo/db/storage/mmap_v1/dur_commitjob.h"
#include "mongo/db/storage/mmap_v1/dur_journal.h"
#include "mongo/db/storage/mmap_v1/dur_journalformat.h"
#include "mongo/db/storage/mmap_v1/dur_stats.h"
#include "mongo/db/storage/mmap_v1/durop.h"
#include "mongo/db/storage/mmap_v1/durable_mapped_file.h"
#include "mongo/db/storage/mmap_v1/mmap_v1_options.h"
#include "mongo/util/bufreader.h"
#include "mongo/util/checksum.h"
#include "mongo/util/compress.h"
#include "mongo/util/exit.h"
#include "mongo/util/hex.h"
#include "mongo/util/log.h"
#include "mongo/util/mongoutils/str.h"
#include "mongo/util/startup_test.h"
namespace mongo {
using boost::shared_ptr;
using std::auto_ptr;
using std::endl;
using std::hex;
using std::map;
using std::pair;
using std::setw;
using std::string;
using std::stringstream;
using std::vector;
/**
* Thrown when a journal section is corrupt. This is considered OK as long as it occurs while
* processing the last file. Processing stops at the first corrupt section.
*
* Any logging about the nature of the corruption should happen before throwing as this class
* contains no data.
*/
class JournalSectionCorruptException {};
namespace dur {
// The singleton recovery job object
RecoveryJob& RecoveryJob::_instance = *(new RecoveryJob());
void removeJournalFiles();
boost::filesystem::path getJournalDir();
struct ParsedJournalEntry { /*copyable*/
ParsedJournalEntry() : e(0) { }
// relative path of database for the operation.
// might be a pointer into mmaped Journal file
const char *dbName;
// those are pointers into the memory mapped journal file
const JEntry *e; // local db sentinel is already parsed out here into dbName
// if not one of the two simple JEntry's above, this is the operation:
boost::shared_ptr<DurOp> op;
};
/**
* Get journal filenames, in order. Throws if unexpected content found.
*/
static void getFiles(boost::filesystem::path dir, vector<boost::filesystem::path>& files) {
map<unsigned,boost::filesystem::path> m;
for ( boost::filesystem::directory_iterator i( dir );
i != boost::filesystem::directory_iterator();
++i ) {
boost::filesystem::path filepath = *i;
string fileName = boost::filesystem::path(*i).leaf().string();
if( str::startsWith(fileName, "j._") ) {
unsigned u = str::toUnsigned( str::after(fileName, '_') );
if( m.count(u) ) {
uasserted(13531, str::stream() << "unexpected files in journal directory " << dir.string() << " : " << fileName);
}
m.insert( pair<unsigned,boost::filesystem::path>(u,filepath) );
}
}
for( map<unsigned,boost::filesystem::path>::iterator i = m.begin(); i != m.end(); ++i ) {
if( i != m.begin() && m.count(i->first - 1) == 0 ) {
uasserted(13532,
str::stream() << "unexpected file in journal directory " << dir.string()
<< " : " << boost::filesystem::path(i->second).leaf().string() << " : can't find its preceding file");
}
files.push_back(i->second);
}
}
/** read through the memory mapped data of a journal file (journal/j._<n> file)
throws
*/
class JournalSectionIterator {
MONGO_DISALLOW_COPYING(JournalSectionIterator);
public:
JournalSectionIterator(const JSectHeader& h,
const void *compressed,
unsigned compressedLen,
bool doDurOpsRecovering)
: _h(h),
_lastDbName(0),
_doDurOps(doDurOpsRecovering) {
verify(doDurOpsRecovering);
if (!uncompress((const char *)compressed, compressedLen, &_uncompressed)) {
// We check the checksum before we uncompress, but this may still fail as the
// checksum isn't foolproof.
log() << "couldn't uncompress journal section" << endl;
throw JournalSectionCorruptException();
}
const char *p = _uncompressed.c_str();
verify(compressedLen == _h.sectionLen() - sizeof(JSectFooter) - sizeof(JSectHeader));
_entries = auto_ptr<BufReader>(new BufReader(p, _uncompressed.size()));
}
// We work with the uncompressed buffer when doing a WRITETODATAFILES (for speed)
JournalSectionIterator(const JSectHeader &h, const void *p, unsigned len)
: _entries(new BufReader((const char *)p, len)),
_h(h),
_lastDbName(0),
_doDurOps(false) {
}
bool atEof() const { return _entries->atEof(); }
unsigned long long seqNumber() const { return _h.seqNumber; }
/** get the next entry from the log. this function parses and combines JDbContext and JEntry's.
* throws on premature end of section.
*/
void next(ParsedJournalEntry& e) {
unsigned lenOrOpCode;
_entries->read(lenOrOpCode);
if (lenOrOpCode > JEntry::OpCode_Min) {
switch( lenOrOpCode ) {
case JEntry::OpCode_Footer: {
verify( false );
}
case JEntry::OpCode_FileCreated:
case JEntry::OpCode_DropDb: {
e.dbName = 0;
boost::shared_ptr<DurOp> op = DurOp::read(lenOrOpCode, *_entries);
if (_doDurOps) {
e.op = op;
}
return;
}
case JEntry::OpCode_DbContext: {
_lastDbName = (const char*) _entries->pos();
const unsigned limit = _entries->remaining();
const unsigned len = strnlen(_lastDbName, limit);
if (_lastDbName[len] != '\0') {
log() << "problem processing journal file during recovery";
throw JournalSectionCorruptException();
}
_entries->skip(len+1); // skip '\0' too
_entries->read(lenOrOpCode); // read this for the fall through
}
// fall through as a basic operation always follows jdbcontext, and we don't have anything to return yet
default:
// fall through
;
}
}
// JEntry - a basic write
verify( lenOrOpCode && lenOrOpCode < JEntry::OpCode_Min );
_entries->rewind(4);
e.e = (JEntry *) _entries->skip(sizeof(JEntry));
e.dbName = e.e->isLocalDbContext() ? "local" : _lastDbName;
verify( e.e->len == lenOrOpCode );
_entries->skip(e.e->len);
}
private:
auto_ptr<BufReader> _entries;
const JSectHeader _h;
const char *_lastDbName; // pointer into mmaped journal file
const bool _doDurOps;
string _uncompressed;
};
static string fileName(const char* dbName, int fileNo) {
stringstream ss;
ss << dbName << '.';
verify( fileNo >= 0 );
if( fileNo == JEntry::DotNsSuffix )
ss << "ns";
else
ss << fileNo;
// relative name -> full path name
boost::filesystem::path full(storageGlobalParams.dbpath);
full /= ss.str();
return full.string();
}
RecoveryJob::RecoveryJob()
: _recovering(false),
_lastDataSyncedFromLastRun(0),
_lastSeqMentionedInConsoleLog(1) {
}
RecoveryJob::~RecoveryJob() {
DESTRUCTOR_GUARD(
if (!_mmfs.empty()) {}
close();
)
}
void RecoveryJob::close() {
boost::lock_guard<boost::mutex> lk(_mx);
_close();
}
void RecoveryJob::_close() {
MongoFile::flushAll(true);
_mmfs.clear();
}
RecoveryJob::Last::Last() : mmf(NULL), fileNo(-1) {
// Make sure the files list does not change from underneath
LockMongoFilesShared::assertAtLeastReadLocked();
}
DurableMappedFile* RecoveryJob::Last::newEntry(const dur::ParsedJournalEntry& entry, RecoveryJob& rj) {
int num = entry.e->getFileNo();
if( num == fileNo && entry.dbName == dbName )
return mmf;
string fn = fileName(entry.dbName, num);
MongoFile *file;
{
MongoFileFinder finder; // must release lock before creating new DurableMappedFile
file = finder.findByPath(fn);
}
if (file) {
verify(file->isDurableMappedFile());
mmf = (DurableMappedFile*)file;
}
else {
if( !rj._recovering ) {
log() << "journal error applying writes, file " << fn << " is not open" << endl;
verify(false);
}
boost::shared_ptr<DurableMappedFile> sp (new DurableMappedFile);
verify(sp->open(fn, false));
rj._mmfs.push_back(sp);
mmf = sp.get();
}
// we do this last so that if an exception were thrown, there isn't any wrong memory
dbName = entry.dbName;
fileNo = num;
return mmf;
}
void RecoveryJob::write(Last& last, const ParsedJournalEntry& entry) {
//TODO(mathias): look into making some of these dasserts
verify(entry.e);
verify(entry.dbName);
DurableMappedFile *mmf = last.newEntry(entry, *this);
if ((entry.e->ofs + entry.e->len) <= mmf->length()) {
verify(mmf->view_write());
verify(entry.e->srcData());
void* dest = (char*)mmf->view_write() + entry.e->ofs;
memcpy(dest, entry.e->srcData(), entry.e->len);
stats.curr()->_writeToDataFilesBytes += entry.e->len;
}
else {
massert(13622, "Trying to write past end of file in WRITETODATAFILES", _recovering);
}
}
void RecoveryJob::applyEntry(Last& last, const ParsedJournalEntry& entry, bool apply, bool dump) {
if( entry.e ) {
if( dump ) {
stringstream ss;
ss << " BASICWRITE " << setw(20) << entry.dbName << '.';
if( entry.e->isNsSuffix() )
ss << "ns";
else
ss << setw(2) << entry.e->getFileNo();
ss << ' ' << setw(6) << entry.e->len << ' ' << /*hex << setw(8) << (size_t) fqe.srcData << dec <<*/
" " << hexdump(entry.e->srcData(), entry.e->len);
log() << ss.str() << endl;
}
if( apply ) {
write(last, entry);
}
}
else if(entry.op) {
// a DurOp subclass operation
if( dump ) {
log() << " OP " << entry.op->toString() << endl;
}
if( apply ) {
if( entry.op->needFilesClosed() ) {
_close(); // locked in processSection
}
entry.op->replay();
}
}
}
void RecoveryJob::applyEntries(const vector<ParsedJournalEntry> &entries) {
const bool apply =
(mmapv1GlobalOptions.journalOptions & MMAPV1Options::JournalScanOnly) == 0;
const bool dump =
(mmapv1GlobalOptions.journalOptions & MMAPV1Options::JournalDumpJournal);
if (dump) {
log() << "BEGIN section" << endl;
}
Last last;
for (vector<ParsedJournalEntry>::const_iterator i = entries.begin(); i != entries.end(); ++i) {
applyEntry(last, *i, apply, dump);
}
if (dump) {
log() << "END section" << endl;
}
}
void RecoveryJob::processSection(const JSectHeader *h, const void *p, unsigned len, const JSectFooter *f) {
LockMongoFilesShared lkFiles; // for RecoveryJob::Last
boost::lock_guard<boost::mutex> lk(_mx);
// Check the footer checksum before doing anything else.
if (_recovering) {
verify( ((const char *)h) + sizeof(JSectHeader) == p );
if (!f->checkHash(h, len + sizeof(JSectHeader))) {
log() << "journal section checksum doesn't match";
throw JournalSectionCorruptException();
}
}
if( _recovering && _lastDataSyncedFromLastRun > h->seqNumber + ExtraKeepTimeMs ) {
if( h->seqNumber != _lastSeqMentionedInConsoleLog ) {
static int n;
if( ++n < 10 ) {
log() << "recover skipping application of section seq:" << h->seqNumber << " < lsn:" << _lastDataSyncedFromLastRun << endl;
}
else if( n == 10 ) {
log() << "recover skipping application of section more..." << endl;
}
_lastSeqMentionedInConsoleLog = h->seqNumber;
}
return;
}
auto_ptr<JournalSectionIterator> i;
if( _recovering ) {
i = auto_ptr<JournalSectionIterator>(new JournalSectionIterator(*h, p, len, _recovering));
}
else {
i = auto_ptr<JournalSectionIterator>(new JournalSectionIterator(*h, /*after header*/p, /*w/out header*/len));
}
// we use a static so that we don't have to reallocate every time through. occasionally we
// go back to a small allocation so that if there were a spiky growth it won't stick forever.
static vector<ParsedJournalEntry> entries;
entries.clear();
/** TEMP uncomment
RARELY OCCASIONALLY {
if( entries.capacity() > 2048 ) {
entries.shrink_to_fit();
entries.reserve(2048);
}
}
*/
// first read all entries to make sure this section is valid
ParsedJournalEntry e;
while( !i->atEof() ) {
i->next(e);
entries.push_back(e);
}
// got all the entries for one group commit. apply them:
applyEntries(entries);
}
/** apply a specific journal file, that is already mmap'd
@param p start of the memory mapped file
@return true if this is detected to be the last file (ends abruptly)
*/
bool RecoveryJob::processFileBuffer(const void *p, unsigned len) {
try {
unsigned long long fileId;
BufReader br(p,len);
{
// read file header
JHeader h;
br.read(h);
if (!h.valid()) {
log() << "Journal file header invalid. This could indicate corruption, or "
<< "an unclean shutdown while writing the first section in a journal "
<< "file.";
throw JournalSectionCorruptException();
}
if( !h.versionOk() ) {
log() << "journal file version number mismatch got:" << hex << h._version
<< " expected:" << hex << (unsigned) JHeader::CurrentVersion
<< ". if you have just upgraded, recover with old version of mongod, terminate cleanly, then upgrade."
<< endl;
// Not using JournalSectionCurruptException as we don't want to ignore
// journal files on upgrade.
uasserted(13536, str::stream() << "journal version number mismatch " << h._version);
}
fileId = h.fileId;
if (mmapv1GlobalOptions.journalOptions &
MMAPV1Options::JournalDumpJournal) {
log() << "JHeader::fileId=" << fileId << endl;
}
}
// read sections
while ( !br.atEof() ) {
JSectHeader h;
br.peek(h);
if( h.fileId != fileId ) {
if (kDebugBuild || (mmapv1GlobalOptions.journalOptions &
MMAPV1Options::JournalDumpJournal)) {
log() << "Ending processFileBuffer at differing fileId want:" << fileId << " got:" << h.fileId << endl;
log() << " sect len:" << h.sectionLen() << " seqnum:" << h.seqNumber << endl;
}
return true;
}
unsigned slen = h.sectionLen();
unsigned dataLen = slen - sizeof(JSectHeader) - sizeof(JSectFooter);
const char *hdr = (const char *) br.skip(h.sectionLenWithPadding());
const char *data = hdr + sizeof(JSectHeader);
const char *footer = data + dataLen;
processSection((const JSectHeader*) hdr, data, dataLen, (const JSectFooter*) footer);
// ctrl c check
uassert(ErrorCodes::Interrupted, "interrupted during journal recovery", !inShutdown());
}
}
catch (const BufReader::eof&) {
if (mmapv1GlobalOptions.journalOptions & MMAPV1Options::JournalDumpJournal)
log() << "ABRUPT END" << endl;
return true; // abrupt end
}
catch (const JournalSectionCorruptException&) {
if (mmapv1GlobalOptions.journalOptions & MMAPV1Options::JournalDumpJournal)
log() << "ABRUPT END" << endl;
return true; // abrupt end
}
return false; // non-abrupt end
}
/** apply a specific journal file */
bool RecoveryJob::processFile(boost::filesystem::path journalfile) {
log() << "recover " << journalfile.string() << endl;
try {
if( boost::filesystem::file_size( journalfile.string() ) == 0 ) {
log() << "recover info " << journalfile.string() << " has zero length" << endl;
return true;
}
} catch(...) {
// if something weird like a permissions problem keep going so the massert down below can happen (presumably)
log() << "recover exception checking filesize" << endl;
}
MemoryMappedFile f;
void *p = f.mapWithOptions(journalfile.string().c_str(), MongoFile::READONLY | MongoFile::SEQUENTIAL);
massert(13544, str::stream() << "recover error couldn't open " << journalfile.string(), p);
return processFileBuffer(p, (unsigned) f.length());
}
/** @param files all the j._0 style files we need to apply for recovery */
void RecoveryJob::go(vector<boost::filesystem::path>& files) {
log() << "recover begin" << endl;
LockMongoFilesExclusive lkFiles; // for RecoveryJob::Last
_recovering = true;
// load the last sequence number synced to the datafiles on disk before the last crash
_lastDataSyncedFromLastRun = journalReadLSN();
log() << "recover lsn: " << _lastDataSyncedFromLastRun << endl;
for( unsigned i = 0; i != files.size(); ++i ) {
bool abruptEnd = processFile(files[i]);
if( abruptEnd && i+1 < files.size() ) {
log() << "recover error: abrupt end to file " << files[i].string() << ", yet it isn't the last journal file" << endl;
close();
uasserted(13535, "recover abrupt journal file end");
}
}
close();
if (mmapv1GlobalOptions.journalOptions & MMAPV1Options::JournalScanOnly) {
uasserted(13545, str::stream() << "--durOptions "
<< (int) MMAPV1Options::JournalScanOnly
<< " (scan only) specified");
}
log() << "recover cleaning up" << endl;
removeJournalFiles();
log() << "recover done" << endl;
okToCleanUp = true;
_recovering = false;
}
void _recover() {
verify(storageGlobalParams.dur);
boost::filesystem::path p = getJournalDir();
if( !exists(p) ) {
log() << "directory " << p.string() << " does not exist, there will be no recovery startup step" << endl;
okToCleanUp = true;
return;
}
vector<boost::filesystem::path> journalFiles;
getFiles(p, journalFiles);
if( journalFiles.empty() ) {
log() << "recover : no journal files present, no recovery needed" << endl;
okToCleanUp = true;
return;
}
RecoveryJob::get().go(journalFiles);
}
/** recover from a crash
called during startup
throws on error
*/
void replayJournalFilesAtStartup() {
// we use a lock so that exitCleanly will wait for us
// to finish (or at least to notice what is up and stop)
OperationContextImpl txn;
ScopedTransaction transaction(&txn, MODE_X);
Lock::GlobalWrite lk(txn.lockState());
_recover(); // throws on interruption
}
struct BufReaderY { int a,b; };
class BufReaderUnitTest : public StartupTest {
public:
void run() {
BufReader r((void*) "abcdabcdabcd", 12);
char x;
BufReaderY y;
r.read(x); //cout << x; // a
verify( x == 'a' );
r.read(y);
r.read(x);
verify( x == 'b' );
}
} brunittest;
} // namespace dur
} // namespace mongo
| 40.459459 | 147 | 0.511965 | [
"object",
"vector"
] |
b4e115229c31de2153bf7991dc11c459ea0bfdba | 19,300 | hpp | C++ | src/hotspot/share/adlc/forms.hpp | siweilxy/openjdkstudy | 8597674ec1d6809faf55cbee1f45f4e9149d670d | [
"Apache-2.0"
] | 1 | 2020-12-26T04:52:15.000Z | 2020-12-26T04:52:15.000Z | src/hotspot/share/adlc/forms.hpp | siweilxy/openjdkstudy | 8597674ec1d6809faf55cbee1f45f4e9149d670d | [
"Apache-2.0"
] | 1 | 2020-12-26T04:57:19.000Z | 2020-12-26T04:57:19.000Z | src/hotspot/share/adlc/forms.hpp | siweilxy/openjdkstudy | 8597674ec1d6809faf55cbee1f45f4e9149d670d | [
"Apache-2.0"
] | 1 | 2021-12-06T01:13:18.000Z | 2021-12-06T01:13:18.000Z | /*
* Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef SHARE_ADLC_FORMS_HPP
#define SHARE_ADLC_FORMS_HPP
// FORMS.HPP - ADL Parser Generic and Utility Forms Classes
#define TRUE 1
#define FALSE 0
// DEFINITIONS OF LEGAL ATTRIBUTE TYPES
#define INS_ATTR 0
#define OP_ATTR 1
// DEFINITIONS OF LEGAL CONSTRAINT TYPES
// Class List
class Form;
class InstructForm;
class MachNodeForm;
class OperandForm;
class OpClassForm;
class AttributeForm;
class RegisterForm;
class PipelineForm;
class SourceForm;
class EncodeForm;
class Component;
class Constraint;
class Predicate;
class MatchRule;
class Attribute;
class Effect;
class ExpandRule;
class RewriteRule;
class ConstructRule;
class FormatRule;
class Peephole;
class EncClass;
class Interface;
class RegInterface;
class ConstInterface;
class MemInterface;
class CondInterface;
class Opcode;
class InsEncode;
class RegDef;
class RegClass;
class CodeSnippetRegClass;
class ConditionalRegClass;
class AllocClass;
class ResourceForm;
class PipeClassForm;
class PeepMatch;
class PeepConstraint;
class PeepReplace;
class MatchList;
class ArchDesc;
//------------------------------FormDict---------------------------------------
// Dictionary containing Forms, and objects derived from forms
class FormDict {
private:
Dict _form; // map names, char*, to their Form* or NULL
// Disable public use of constructor, copy-ctor, operator =, operator ==
FormDict( );
FormDict &operator =( const FormDict & );
// == compares two dictionaries; they must have the same keys (their keys
// must match using CmpKey) and they must have the same values (pointer
// comparison). If so 1 is returned, if not 0 is returned.
bool operator ==(const FormDict &d) const; // Compare dictionaries for equal
public:
// cmp is a key comparision routine. hash is a routine to hash a key.
// FormDict( CmpKey cmp, Hash hash );
FormDict( CmpKey cmp, Hash hash, Arena *arena );
FormDict( const FormDict & fd ); // Deep-copy guts
~FormDict();
// Return # of key-value pairs in dict
int Size(void) const;
// Insert inserts the given key-value pair into the dictionary. The prior
// value of the key is returned; NULL if the key was not previously defined.
const Form *Insert(const char *name, Form *form); // A new key-value
// Find finds the value of a given key; or NULL if not found.
// The dictionary is NOT changed.
const Form *operator [](const char *name) const; // Do a lookup
void dump();
};
// ***** Master Class for ADL Parser Forms *****
//------------------------------Form-------------------------------------------
class Form {
public:
static Arena *arena; // arena used by forms
private:
static Arena *generate_arena(); // allocate arena used by forms
protected:
int _ftype; // Indicator for derived class type
public:
// Public Data
Form *_next; // Next pointer for form lists
int _linenum; // Line number for debugging
// Dynamic type check for common forms.
virtual OpClassForm *is_opclass() const;
virtual OperandForm *is_operand() const;
virtual InstructForm *is_instruction() const;
virtual MachNodeForm *is_machnode() const;
virtual AttributeForm *is_attribute() const;
virtual Effect *is_effect() const;
virtual ResourceForm *is_resource() const;
virtual PipeClassForm *is_pipeclass() const;
// Check if this form is an operand usable for cisc-spilling
virtual bool is_cisc_reg(FormDict &globals) const { return false; }
virtual bool is_cisc_mem(FormDict &globals) const { return false; }
// Public Methods
Form(int formType=0, int line=0)
: _next(NULL), _linenum(line), _ftype(formType) { };
virtual ~Form() {};
virtual bool ideal_only() const {
assert(0,"Check of ideal status on non-instruction/operand form.\n");
return FALSE;
}
// Check constraints after parsing
virtual bool verify() { return true; }
virtual void dump() { output(stderr); } // Debug printer
// Write info to output files
virtual void output(FILE *fp) { fprintf(fp,"Form Output"); }
public:
// ADLC types, match the last character on ideal operands and instructions
enum DataType {
none = 0, // Not a simple type
idealI = 1, // Integer type
idealP = 2, // Pointer types, oop(s)
idealL = 3, // Long type
idealF = 4, // Float type
idealD = 5, // Double type
idealB = 6, // Byte type
idealC = 7, // Char type
idealS = 8, // String type
idealN = 9, // Narrow oop types
idealNKlass = 10, // Narrow klass types
idealV = 11 // Vector type
};
// Convert ideal name to a DataType, return DataType::none if not a 'ConX'
Form::DataType ideal_to_const_type(const char *ideal_type_name) const;
// Convert ideal name to a DataType, return DataType::none if not a 'sRegX
Form::DataType ideal_to_sReg_type(const char *name) const;
// Convert ideal name to a DataType, return DataType::none if not a 'RegX
Form::DataType ideal_to_Reg_type(const char *name) const;
// Convert ideal name to a DataType, return DataType::none if not a 'LoadX
Form::DataType is_load_from_memory(const char *opType) const;
// Convert ideal name to a DataType, return DataType::none if not a 'StoreX
Form::DataType is_store_to_memory(const char *opType) const;
// ADLC call types, matched with ideal world
enum CallType {
invalid_type = 0, // invalid call type
JAVA_STATIC = 1, // monomorphic entry
JAVA_DYNAMIC = 2, // possibly megamorphic, inline cache call
JAVA_COMPILED = 3, // callee will be compiled java
JAVA_INTERP = 4, // callee will be executed by interpreter
JAVA_NATIVE = 5, // native entrypoint
JAVA_RUNTIME = 6, // runtime entrypoint
JAVA_LEAF = 7 // calling leaf
};
// Interface types for operands and operand classes
enum InterfaceType {
no_interface = 0, // unknown or inconsistent interface type
constant_interface = 1, // interface to constants
register_interface = 2, // interface to registers
memory_interface = 3, // interface to memory
conditional_interface = 4 // interface for condition codes
};
virtual Form::InterfaceType interface_type(FormDict &globals) const;
enum CiscSpillInfo {
Not_cisc_spillable = AdlcVMDeps::Not_cisc_spillable,
Maybe_cisc_spillable = 0,
Is_cisc_spillable = 1
// ...
};
// LEGAL FORM TYPES
enum {
INS,
OPER,
OPCLASS,
SRC,
ADEF,
REG,
PIPE,
CNST,
PRED,
ATTR,
MAT,
ENC,
FOR,
EXP,
REW,
EFF,
RDEF,
RCL,
ACL,
RES,
PCL,
PDEF,
REGL,
RESL,
STAL,
COMP,
PEEP,
RESO
};
};
//------------------------------FormList---------------------------------------
class FormList {
private:
Form *_root;
Form *_tail;
Form *_cur;
int _justReset; // Set immediately after reset
Form *_cur2; // Nested iterator
int _justReset2;
public:
void addForm(Form * entry) {
if (_tail==NULL) { _root = _tail = _cur = entry;}
else { _tail->_next = entry; _tail = entry;}
};
Form * current() { return _cur; };
Form * iter() { if (_justReset) _justReset = 0;
else if (_cur) _cur = _cur->_next;
return _cur;};
void reset() { if (_root) {_cur = _root; _justReset = 1;} };
// Second iterator, state is internal
Form * current2(){ return _cur2; };
Form * iter2() { if (_justReset2) _justReset2 = 0;
else if (_cur2) _cur2 = _cur2->_next;
return _cur2;};
void reset2() { if (_root) {_cur2 = _root; _justReset2 = 1;} };
int count() {
int count = 0; reset();
for( Form *cur; (cur = iter()) != NULL; ) { ++count; };
return count;
}
void dump() {
reset();
Form *cur;
for(; (cur = iter()) != NULL; ) {
cur->dump();
};
}
bool verify() {
bool verified = true;
reset();
Form *cur;
for(; (cur = iter()) != NULL; ) {
if ( ! cur->verify() ) verified = false;
};
return verified;
}
void output(FILE* fp) {
reset();
Form *cur;
for( ; (cur = iter()) != NULL; ) {
cur->output(fp);
};
}
FormList() { _justReset = 1; _justReset2 = 1; _root = NULL; _tail = NULL; _cur = NULL; _cur2 = NULL;};
~FormList();
};
//------------------------------NameList---------------------------------------
// Extendable list of pointers, <char *>
class NameList {
friend class PreserveIter;
private:
int _cur; // Insert next entry here; count of entries
int _max; // Number of spaces allocated
const char **_names; // Array of names
protected:
int _iter; // position during iteration
bool _justReset; // Set immediately after reset
public:
static const char *_signal; // reserved user-defined string
static const char *_signal2; // reserved user-defined string
static const char *_signal3; // reserved user-defined string
enum { Not_in_list = -1 };
void addName(const char *name);
void add_signal();
void clear(); // Remove all entries
int count() const;
void reset(); // Reset iteration
const char *iter(); // after reset(), first element : else next
const char *current(); // return current element in iteration.
const char *peek(int skip = 1); // returns element + skip in iteration if there is one
bool current_is_signal(); // Return 'true' if current entry is signal
bool is_signal(const char *entry); // Return true if entry is a signal
bool search(const char *); // Search for a name in the list
int index(const char *); // Return index of name in list
const char *name (intptr_t index);// Return name at index in list
void dump(); // output to stderr
void output(FILE *fp); // Output list of names to 'fp'
NameList();
~NameList();
};
// Convenience class to preserve iteration state since iterators are
// internal instead of being external.
class PreserveIter {
private:
NameList* _list;
int _iter;
bool _justReset;
public:
PreserveIter(NameList* nl) {
_list = nl;
_iter = _list->_iter;
_justReset = _list->_justReset;
}
~PreserveIter() {
_list->_iter = _iter;
_list->_justReset = _justReset;
}
};
//------------------------------NameAndList------------------------------------
// Storage for a name and an associated list of names
class NameAndList {
private:
const char *_name;
NameList _list;
public:
NameAndList(char *name);
~NameAndList();
// Add to entries in list
void add_entry(const char *entry);
// Access the name and its associated list.
const char *name() const;
void reset();
const char *iter();
int count() { return _list.count(); }
// Return the "index" entry in the list, zero-based
const char *operator[](int index);
void dump(); // output to stderr
void output(FILE *fp); // Output list of names to 'fp'
};
//------------------------------ComponentList---------------------------------
// Component lists always have match rule operands first, followed by parameter
// operands which do not appear in the match list (in order of declaration).
class ComponentList : private NameList {
private:
int _matchcnt; // Count of match rule operands
public:
// This is a batch program. (And I have a destructor bug!)
void operator delete( void *ptr ) {}
void insert(Component *component, bool mflag);
void insert(const char *name, const char *opType, int usedef, bool mflag);
int count();
int match_count() { return _matchcnt; } // Get count of match rule opers
Component *iter(); // after reset(), first element : else next
Component *match_iter(); // after reset(), first element : else next
Component *post_match_iter(); // after reset(), first element : else next
void reset(); // Reset iteration
Component *current(); // return current element in iteration.
// Return element at "position", else NULL
Component *operator[](int position);
Component *at(int position) { return (*this)[position]; }
// Return first component having this name.
const Component *search(const char *name);
// Return number of USEs + number of DEFs
int num_operands();
// Return zero-based position in list; -1 if not in list.
int operand_position(const char *name, int usedef, Form *fm);
// Find position for this name, regardless of use/def information
int operand_position(const char *name);
// Find position for this name when looked up for output via "format"
int operand_position_format(const char *name, Form *fm);
// Find position for the Label when looked up for output via "format"
int label_position();
// Find position for the Method when looked up for output via "format"
int method_position();
void dump(); // output to stderr
void output(FILE *fp); // Output list of names to 'fp'
ComponentList();
~ComponentList();
};
//------------------------------SourceForm-------------------------------------
class SourceForm : public Form {
private:
public:
// Public Data
char *_code; // Buffer for storing code text
// Public Methods
SourceForm(char* code);
~SourceForm();
virtual const char* classname() { return "SourceForm"; }
void dump(); // Debug printer
void output(FILE *fp); // Write output files
};
class HeaderForm : public SourceForm {
public:
HeaderForm(char* code) : SourceForm(code) { }
virtual const char* classname() { return "HeaderForm"; }
};
class PreHeaderForm : public SourceForm {
public:
PreHeaderForm(char* code) : SourceForm(code) { }
virtual const char* classname() { return "PreHeaderForm"; }
};
//------------------------------Expr------------------------------------------
#define STRING_BUFFER_LENGTH 2048
// class Expr represents integer expressions containing constants and addition
// Value must be in range zero through maximum positive integer. 32bits.
// Expected use: instruction and operand costs
class Expr {
public:
enum {
Zero = 0,
Max = 0x7fffffff
};
const char *_external_name; // if !NULL, then print this instead of _expr
const char *_expr;
int _min_value;
int _max_value;
Expr();
Expr(const char *cost);
Expr(const char *name, const char *expression, int min_value, int max_value);
Expr *clone() const;
bool is_unknown() const { return (this == Expr::get_unknown()); }
bool is_zero() const { return (_min_value == Expr::Zero && _max_value == Expr::Zero); }
bool less_than_or_equal(const Expr *c) const { return (_max_value <= c->_min_value); }
void add(const Expr *c);
void add(const char *c);
void add(const char *c, ArchDesc &AD); // check if 'c' is defined in <arch>.ad
void set_external_name(const char *name) { _external_name = name; }
const char *as_string() const { return (_external_name != NULL ? _external_name : _expr); }
void print() const;
void print_define(FILE *fp) const;
void print_assert(FILE *fp) const;
static Expr *get_unknown(); // Returns pointer to shared unknown cost instance
static char *buffer() { return &external_buffer[0]; }
static bool init_buffers(); // Fill buffers with 0
static bool check_buffers(); // if buffer use may have overflowed, assert
private:
static Expr *_unknown_expr;
static char string_buffer[STRING_BUFFER_LENGTH];
static char external_buffer[STRING_BUFFER_LENGTH];
static bool _init_buffers;
const char *compute_expr(const Expr *c1, const Expr *c2); // cost as string after adding 'c1' and 'c2'
int compute_min (const Expr *c1, const Expr *c2); // minimum after adding 'c1' and 'c2'
int compute_max (const Expr *c1, const Expr *c2); // maximum after adding 'c1' and 'c2'
const char *compute_external(const Expr *c1, const Expr *c2); // external name after adding 'c1' and 'c2'
};
//------------------------------ExprDict---------------------------------------
// Dictionary containing Exprs
class ExprDict {
private:
Dict _expr; // map names, char*, to their Expr* or NULL
NameList _defines; // record the order of definitions entered with define call
// Disable public use of constructor, copy-ctor, operator =, operator ==
ExprDict( );
ExprDict( const ExprDict & ); // Deep-copy guts
ExprDict &operator =( const ExprDict & );
// == compares two dictionaries; they must have the same keys (their keys
// must match using CmpKey) and they must have the same values (pointer
// comparison). If so 1 is returned, if not 0 is returned.
bool operator ==(const ExprDict &d) const; // Compare dictionaries for equal
public:
// cmp is a key comparision routine. hash is a routine to hash a key.
ExprDict( CmpKey cmp, Hash hash, Arena *arena );
~ExprDict();
// Return # of key-value pairs in dict
int Size(void) const;
// define inserts the given key-value pair into the dictionary,
// and records the name in order for later output, ...
const Expr *define(const char *name, Expr *expr);
// Insert inserts the given key-value pair into the dictionary. The prior
// value of the key is returned; NULL if the key was not previously defined.
const Expr *Insert(const char *name, Expr *expr); // A new key-value
// Find finds the value of a given key; or NULL if not found.
// The dictionary is NOT changed.
const Expr *operator [](const char *name) const; // Do a lookup
void print_defines(FILE *fp);
void print_asserts(FILE *fp);
void dump();
};
#endif // SHARE_ADLC_FORMS_HPP
| 32.166667 | 108 | 0.630259 | [
"vector"
] |
b4e1d7498f9ce71e589f426c7f87ddaee1decfc4 | 4,232 | cpp | C++ | qtglass.cpp | ianbannerman/QtGlass | 1628b9e766b9767f052219ea4c79e27d4773efa1 | [
"MIT"
] | 4 | 2018-12-31T06:33:22.000Z | 2019-09-07T08:12:12.000Z | qtglass.cpp | ianbannerman/QtGlass | 1628b9e766b9767f052219ea4c79e27d4773efa1 | [
"MIT"
] | null | null | null | qtglass.cpp | ianbannerman/QtGlass | 1628b9e766b9767f052219ea4c79e27d4773efa1 | [
"MIT"
] | 1 | 2019-02-14T01:45:45.000Z | 2019-02-14T01:45:45.000Z | #include "qtglass.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QtGlass w;
//Remove the default tan system background from the window
w.setAttribute(Qt::WA_TranslucentBackground);
//Set an initial window size
w.setMinimumSize(800, 600);
//Extend the Aero glass frame into the window
QtWin::extendFrameIntoClientArea(&w, -1, -1, -1, -1);
//Draw the window
w.show();
return a.exec();
}
QtGlass::QtGlass(QWidget *parent)
: QMainWindow(parent)
{
}
QtGlass::~QtGlass()
{
}
//Capture window messaging events
bool QtGlass::nativeEvent(const QByteArray& eventType, void* message, long* result)
{
//Cast the window message to a type we can work with
MSG *msg = static_cast<MSG *>(message);
//Check if DWM handled the message; if it did, it wasn't in our client area and we can ignore it
if (DwmDefWindowProc(msg->hwnd, msg->message, msg->wParam, msg->lParam, (LRESULT*)result))
return true;
//Get the window rectangle
RECT winrect;
GetWindowRect(msg->hwnd, &winrect);
//Condition based on the message type
switch (msg->message)
{
//On show window, update the frame
case WM_SHOWWINDOW:
{
SetWindowPos(
msg->hwnd,
NULL,
winrect.left,
winrect.top,
winrect.right - winrect.left,
winrect.bottom - winrect.top,
SWP_FRAMECHANGED
);
return false;
}
//On calculate size, remove the frame
case WM_NCCALCSIZE:
{
if (msg->wParam)
{
//Set the result to 0 to remove the window frame and caption items extending the client area into the frame
//https://msdn.microsoft.com/en-us/library/windows/desktop/ms632634.aspx
*result = 0;
//Return true to indicate we've acted on this event
return true;
}
}
//Allow dragging the window
case WM_NCHITTEST:
{
//Get the size of the title bar
const int titleSize = GetSystemMetrics(SM_CYCAPTION);
//Get Y mouse coordinate
long y = GET_Y_LPARAM(msg->lParam);
//If the mouse is within the title bar area, allow dragging the window
if (y >= winrect.top && y < winrect.top + titleSize)
{
*result = HTCAPTION;
return true;
}
/*To allow dragging from within the entire window if the mouse event was not processed by a child object, uncomment this*/
//QWidget *action = QApplication::widgetAt(QCursor::pos());
//if (action == this)
//{
// *result = HTCAPTION;
// return true;
//}
/* To allow resizing the window, uncomment this */
////Get X and Y mouse coordinates
//long x = GET_X_LPARAM(msg->lParam);
//long y = GET_Y_LPARAM(msg->lParam);
//
////Set the border size to show the resize cursor for
//const int border_width = 8; /* in pixels */
////left border
//if (x >= winrect.left && x < winrect.left + border_width)
//{
// *result = HTLEFT;
// return true;
//}
////right border
//if (x < winrect.right && x >= winrect.right - border_width)
//{
// *result = HTRIGHT;
// return true;
//}
////bottom border
//if (y < winrect.bottom && y >= winrect.bottom - border_width)
//{
// *result = HTBOTTOM;
// return true;
//}
////top border
//if (y >= winrect.top && y < winrect.top + border_width)
//{
// *result = HTTOP;
// return true;
//}
////bottom left corner
//if (x >= winrect.left && x < winrect.left + border_width &&
// y < winrect.bottom && y >= winrect.bottom - border_width)
//{
// *result = HTBOTTOMLEFT;
// return true;
//}
////bottom right corner
//if (x < winrect.right && x >= winrect.right - border_width &&
// y < winrect.bottom && y >= winrect.bottom - border_width)
//{
// *result = HTBOTTOMRIGHT;
// return true;
//}
////top left corner
//if (x >= winrect.left && x < winrect.left + border_width &&
// y >= winrect.top && y < winrect.top + border_width)
//{
// *result = HTTOPLEFT;
// return true;
//}
////top right corner
//if (x < winrect.right && x >= winrect.right - border_width &&
// y >= winrect.top && y < winrect.top + border_width)
//{
// *result = HTTOPRIGHT;
// return true;
//}
}
}
//Pass the event on if it wasn't for us to react to
return QWidget::nativeEvent(eventType, message, result);
} | 24.462428 | 125 | 0.62689 | [
"object"
] |
b4e2787e5fe5ca7c4bdc334a5b8253d736d3067c | 2,538 | cpp | C++ | x265/source/common/vec/vec-primitives.cpp | xu5343/ffmpegtoolkit_CentOS7 | 974496c709a1c8c69034e46ae5ce7101cf03716f | [
"Apache-2.0"
] | 14 | 2019-02-26T22:22:32.000Z | 2022-03-03T07:06:58.000Z | x265/source/common/vec/vec-primitives.cpp | xu5343/ffmpegtoolkit_CentOS7 | 974496c709a1c8c69034e46ae5ce7101cf03716f | [
"Apache-2.0"
] | null | null | null | x265/source/common/vec/vec-primitives.cpp | xu5343/ffmpegtoolkit_CentOS7 | 974496c709a1c8c69034e46ae5ce7101cf03716f | [
"Apache-2.0"
] | 7 | 2019-05-17T19:14:10.000Z | 2021-08-31T01:54:40.000Z | /*****************************************************************************
* Copyright (C) 2013-2017 MulticoreWare, Inc
*
* Authors: Steve Borho <steve@borho.org>
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA.
*
* This program is also available under a commercial proprietary license.
* For more information, contact us at license @ x265.com.
*****************************************************************************/
#include "primitives.h"
#include "x265.h"
/* The #if logic here must match the file lists in CMakeLists.txt */
#if X265_ARCH_X86
#if defined(__INTEL_COMPILER)
#define HAVE_SSE3
#define HAVE_SSSE3
#define HAVE_SSE4
#define HAVE_AVX2
#elif defined(__GNUC__)
#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#if __clang__ || GCC_VERSION >= 40300 /* gcc_version >= gcc-4.3.0 */
#define HAVE_SSE3
#define HAVE_SSSE3
#define HAVE_SSE4
#endif
#if __clang__ || GCC_VERSION >= 40700 /* gcc_version >= gcc-4.7.0 */
#define HAVE_AVX2
#endif
#elif defined(_MSC_VER)
#define HAVE_SSE3
#define HAVE_SSSE3
#define HAVE_SSE4
#if _MSC_VER >= 1700 // VC11
#define HAVE_AVX2
#endif
#endif // compiler checks
#endif // if X265_ARCH_X86
namespace X265_NS {
// private x265 namespace
void setupIntrinsicDCT_sse3(EncoderPrimitives&);
void setupIntrinsicDCT_ssse3(EncoderPrimitives&);
void setupIntrinsicDCT_sse41(EncoderPrimitives&);
/* Use primitives for the best available vector architecture */
void setupInstrinsicPrimitives(EncoderPrimitives &p, int cpuMask)
{
#ifdef HAVE_SSE3
if (cpuMask & X265_CPU_SSE3)
{
setupIntrinsicDCT_sse3(p);
}
#endif
#ifdef HAVE_SSSE3
if (cpuMask & X265_CPU_SSSE3)
{
setupIntrinsicDCT_ssse3(p);
}
#endif
#ifdef HAVE_SSE4
if (cpuMask & X265_CPU_SSE4)
{
setupIntrinsicDCT_sse41(p);
}
#endif
(void)p;
(void)cpuMask;
}
}
| 29.511628 | 83 | 0.693065 | [
"vector"
] |
b4e4b2917a3bbc7836fae661899bd221309c4efe | 1,928 | cpp | C++ | 2017-08-05/J.cpp | tangjz/Three-Investigators | 46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52 | [
"MIT"
] | 3 | 2018-04-02T06:00:51.000Z | 2018-05-29T04:46:29.000Z | 2017-08-05/J.cpp | tangjz/Three-Investigators | 46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52 | [
"MIT"
] | 2 | 2018-03-31T17:54:30.000Z | 2018-05-02T11:31:06.000Z | 2017-08-05/J.cpp | tangjz/Three-Investigators | 46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52 | [
"MIT"
] | 2 | 2018-10-07T00:08:06.000Z | 2021-06-28T11:02:59.000Z | #include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define mkp make_pair
#define fi first
#define se second
#define ll long long
#define M 1000000007
#define all(a) a.begin(), a.end()
const int maxn = 100100;
const int maxp = maxn * 18;
int son[maxp][2], cnt[maxp];
int a[maxn], fa[maxn][18], dep[maxn], rt[maxn];
int tot;
vector<int> g[maxn];
int n, m;
void insert(int &t, int dp, int v, int pre_t){
t = ++tot;
son[t][0] = son[pre_t][0];
son[t][1] = son[pre_t][1];
cnt[t] = cnt[pre_t] + 1;
if(dp < 0) return;
bool x = v >> dp & 1;
insert(son[t][x], dp - 1, v, son[pre_t][x]);
}
void build(int t){
insert(rt[t], 15, a[t], rt[fa[t][0]]);
dep[t] = dep[fa[t][0]] + 1;
for(int i = 1; fa[t][i - 1]; ++i)
fa[t][i] = fa[fa[t][i - 1]][i - 1];
for(int v : g[t]){
if(v == fa[t][0]) continue;
memset(fa[v], 0, sizeof(fa[v]));
fa[v][0] = t;
build(v);
}
}
int lca(int u, int v){
if(dep[u] > dep[v]) swap(u, v);
for(int i = 16, dist = dep[v] - dep[u]; i >= 0; --i)
if(dist >> i & 1) v = fa[v][i];
if(u == v) return u;
for(int i = 16; i >= 0; --i)
if(fa[u][i] != fa[v][i]) u = fa[u][i], v = fa[v][i];
return fa[u][0];
}
int query(int dp, int t1, int t2, int t3, int v){
if(dp < 0) return 0;
bool x = v >> dp & 1;
int tmp = cnt[son[t1][x ^ 1]] + cnt[son[t2][x ^ 1]] - 2 * cnt[son[t3][x ^ 1]];
if(tmp) return 1 << dp | query(dp - 1, son[t1][x ^ 1], son[t2][x ^ 1], son[t3][x ^ 1], v);
else return query(dp - 1, son[t1][x], son[t2][x], son[t3][x], v);
}
int main(){
while(~scanf("%d%d", &n, &m)){
for(int i = 1; i <= n; ++i) scanf("%d", a + i), rt[i] = 0, g[i].clear();
for(int i = 1; i < n; ++i){
static int u, v;
scanf("%d%d", &u, &v);
g[u].pb(v);
g[v].pb(u);
}
tot = 0;
build(1);
while(m--){
static int x, y, z;
scanf("%d%d%d", &x, &y, &z);
int g = lca(x, y);
printf("%d\n", max(a[g] ^ z, query(15, rt[x], rt[y], rt[g], z)));
}
}
return 0;
}
| 23.512195 | 91 | 0.503112 | [
"vector"
] |
b4e550bdfab2934120de7fdc89ad65a7dac1d015 | 1,378 | cc | C++ | Codeforces/248 Division 2/Problem B/B.cc | VastoLorde95/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 170 | 2017-07-25T14:47:29.000Z | 2022-01-26T19:16:31.000Z | Codeforces/248 Division 2/Problem B/B.cc | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | null | null | null | Codeforces/248 Division 2/Problem B/B.cc | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 55 | 2017-07-28T06:17:33.000Z | 2021-10-31T03:06:22.000Z | #include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<map>
#include<set>
#include<vector>
#include<utility>
#include<queue>
#include<stack>
#define sd(x) scanf("%d",&x)
#define sd2(x,y) scanf("%d%d",&x,&y)
#define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z)
#define fi first
#define se second
#define pb(x) push_back(x)
#define mp(x,y) make_pair(x,y)
#define LET(x, a) __typeof(a) x(a)
#define foreach(it, v) for(LET(it, v.begin()); it != v.end(); it++)
#define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define __ freopen("input.txt", "r", stdin);freopen("output.txt", "w", stdout);
#define tr(x) cout<<x<<endl;
#define tr2(x,y) cout<<x<<" "<<y<<endl;
#define tr3(x,y,z) cout<<x<<" "<<y<<" "<<z<<endl;
#define tr4(w,x,y,z) cout<<w<<" "<<x<<" "<<y<<" "<<z<<endl;
using namespace std;
int n;
int v[100100];
long long s1[100100], s2[100100];
int main(){
sd(n);
for(int i = 1; i <= n; i++){
sd(v[i]);
}
for(int i = 1; i <= n; i++){
s1[i] = s1[i-1] + v[i];
}
sort(v+1,v+n+1);
// for(int i = 1; i <= n; i++) cout << v[i] << " "; cout << endl;
for(int i = 1; i <= n; i++){
s2[i] = s2[i-1] + v[i];
// tr2(i, s2[i]);
}
int m; sd(m);
while(m--){
int type, l, r; sd3(type, l, r);
if(type == 1){
cout << s1[r]-s1[l-1] << "\n";
}
else{
cout << s2[r]-s2[l-1] << "\n";
}
}
return 0;
}
| 21.2 | 79 | 0.548621 | [
"vector"
] |
b4e6a25b596fa079a362cf8eafa1a6410c534c2c | 512 | cpp | C++ | MaximumLengthOfRepeatedSubarray/maximum_length_of_repeated_subarray.cpp | suzyz/leetcode_practice | e22dc5a81e065dc962e5561b14ac84b9a2302e8a | [
"MIT"
] | 1 | 2019-10-07T05:00:21.000Z | 2019-10-07T05:00:21.000Z | MaximumLengthOfRepeatedSubarray/maximum_length_of_repeated_subarray.cpp | suzyz/leetcode_practice | e22dc5a81e065dc962e5561b14ac84b9a2302e8a | [
"MIT"
] | null | null | null | MaximumLengthOfRepeatedSubarray/maximum_length_of_repeated_subarray.cpp | suzyz/leetcode_practice | e22dc5a81e065dc962e5561b14ac84b9a2302e8a | [
"MIT"
] | null | null | null | // O(N^2) space.
class Solution {
public:
int f[1002][1002];
int findLength(vector<int>& A, vector<int>& B) {
int n = A.size(), m = B.size(), ans = 0;
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
if (A[i] == B[j])
{
int pre;
if (i == 0 || j == 0)
pre = 0;
else
pre = f[i-1][j-1];
f[i][j] = pre+1;
ans = max(ans, f[i][j]);
}
return ans;
}
}; | 21.333333 | 52 | 0.341797 | [
"vector"
] |
b4e70bf525e2c32133e01941e731c06d5f73ad4a | 9,694 | hpp | C++ | openstudiocore/src/utilities/idd/IddRegex.hpp | pepsi7959/OpenstudioThai | fb18afb8b983f71dd5eb171e753dac7d9a4b811b | [
"blessing"
] | 1 | 2015-06-28T09:06:24.000Z | 2015-06-28T09:06:24.000Z | openstudiocore/src/utilities/idd/IddRegex.hpp | pepsi7959/OpenstudioThai | fb18afb8b983f71dd5eb171e753dac7d9a4b811b | [
"blessing"
] | 11 | 2015-05-05T16:16:33.000Z | 2017-08-10T08:15:50.000Z | openstudiocore/src/utilities/idd/IddRegex.hpp | pepsi7959/OpenstudioThai | fb18afb8b983f71dd5eb171e753dac7d9a4b811b | [
"blessing"
] | 1 | 2017-09-23T12:51:13.000Z | 2017-09-23T12:51:13.000Z | /**********************************************************************
* Copyright (c) 2008-2015, 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
**********************************************************************/
#ifndef UTILITIES_IDD_IDDREGEX_HPP
#define UTILITIES_IDD_IDDREGEX_HPP
#include "../UtilitiesAPI.hpp"
#include "../core/StaticInitializer.hpp"
#include <boost/regex.hpp>
namespace openstudio{
namespace iddRegex{
/// name of the comment only object automatically added to the idd
UTILITIES_API const std::string &commentOnlyObjectName();
/// text of the comment only object automatically added to the idd
UTILITIES_API const std::string &commentOnlyObjectText();
/// Search for IDD version in line
/// matches[1], version identifier
UTILITIES_API const boost::regex &version();
/// Search for IDD build in line
/// matches[1], build identifier
UTILITIES_API const boost::regex &build();
/// Search for IDD header, each line must start with '!', no preceding whitespace
/// matches[1], header
UTILITIES_API const boost::regex &header();
/// Match comment only line
/// matches[1], comment
UTILITIES_API const boost::regex &commentOnlyLine();
/// Match content then comment
/// matches[1], content
/// matches[2], comment if any
UTILITIES_API const boost::regex &contentAndCommentLine();
/// Match group identifier
/// matches[1], group name
UTILITIES_API const boost::regex &group();
/// Match include-file identifier
/// matches[1], included Idd file name
UTILITIES_API const boost::regex &includeFile();
/// Match remove-object identifier
/// matches[1], object in included Idd file that should not be included in this file
UTILITIES_API const boost::regex &removeObject();
/// Match line with either a ',' or a ';' that are not preceded by '!'
/// matches[1], before separator
/// matches[2], after separator
UTILITIES_API const boost::regex &line();
/// Match an object memo property
/// matches[1], memo text
UTILITIES_API const boost::regex &memoProperty();
/// Match an object note property
/// matches[1], note text
UTILITIES_API const boost::regex ¬eProperty();
/// Match an object with no fields in the idd
/// matches[1], before separator
/// matches[2], after separator
UTILITIES_API const boost::regex &objectNoFields();
/// Match an object with one or more fields in the idd
/// matches[1], object text
/// matches[2], field(s) text
UTILITIES_API const boost::regex &objectAndFields();
/// Match an object unique property
UTILITIES_API const boost::regex &uniqueProperty();
/// Match an object required property
UTILITIES_API const boost::regex &requiredObjectProperty();
/// Match an object obsolete property
/// matches[1], reason for obsolete
UTILITIES_API const boost::regex &obsoleteProperty();
/// Match an object hasURL property
UTILITIES_API const boost::regex &hasurlProperty();
/// Match an object extensible property
/// matches[1], number of last fields to extend
UTILITIES_API const boost::regex &extensibleProperty();
/// Match an object format property
/// matches[1], format text
UTILITIES_API const boost::regex &formatProperty();
/// Match an object min fields property
/// matches[1], min number of fields
UTILITIES_API const boost::regex &minFieldsProperty();
/// Match an object max fields property
/// matches[1], max number of fields
UTILITIES_API const boost::regex &maxFieldsProperty();
/// Match a field declaration in the idd
/// A or N, then one or more numbers then white space and then a ',' or ';'
/// matches[1], alpha or numeric indicator
/// matches[2], alpha or numeric number
/// matches[3], after separator
UTILITIES_API const boost::regex &field();
/// Match the closing field in an idd object
/// matches[1], all previous text
/// matches[2], the last field
UTILITIES_API const boost::regex &closingField();
/// Match the last field declaration in a string, may or may not be the closing field
/// matches[1], all previous text
/// matches[2], the last field
UTILITIES_API const boost::regex &lastField();
/// Match a field name
/// matches[1], the field name
UTILITIES_API const boost::regex &name();
/// Match a field field name property
/// matches[1], the field name
UTILITIES_API const boost::regex &nameProperty();
/// Match a field required property
UTILITIES_API const boost::regex &requiredFieldProperty();
/// Match a field autosizable property
UTILITIES_API const boost::regex &autosizableProperty();
/// Match a field autocalculatable property
UTILITIES_API const boost::regex &autocalculatableProperty();
/// Match a field retaincase property
UTILITIES_API const boost::regex &retaincaseProperty();
/// Match a field units property
/// matches[1], the field units
UTILITIES_API const boost::regex &unitsProperty();
/// Match a field ip units property
/// matches[1], the field ip units
UTILITIES_API const boost::regex &ipUnitsProperty();
/// Match a field exclusive minimum property
/// matches[1], the field exclusive minimum
UTILITIES_API const boost::regex &minExclusiveProperty();
/// Match a field inclusive minimum property
/// matches[1], the field inclusive minimum
UTILITIES_API const boost::regex &minInclusiveProperty();
/// Match a field exclusive maximum property
/// matches[1], the field exclusive maximum
UTILITIES_API const boost::regex &maxExclusiveProperty();
/// Match a field inclusive maximum property
/// matches[1], the field inclusive maximum
UTILITIES_API const boost::regex &maxInclusiveProperty();
/// Match a field deprecated property
/// matches[1], reason for deprecated
UTILITIES_API const boost::regex &deprecatedProperty();
/// Match a field default property
/// matches[1], default value
UTILITIES_API const boost::regex &defaultProperty();
/// Match a field default property with either autocalculate or autosize
UTILITIES_API const boost::regex &automaticDefault();
/// Match a field type property
/// matches[1], type
UTILITIES_API const boost::regex &typeProperty();
/// Match a field key property
/// matches[1], key value
UTILITIES_API const boost::regex &keyProperty();
/// Match a field object-list property
/// matches[1], object-list value
UTILITIES_API const boost::regex &objectListProperty();
/// Match a field external-list property
/// matches[1], external-list value
UTILITIES_API const boost::regex &externalListProperty();
/// Match a field reference property
/// matches[1], reference value
UTILITIES_API const boost::regex &referenceProperty();
/// Match begin extensible
UTILITIES_API const boost::regex &beginExtensible();
/// Match begin extensible
UTILITIES_API const boost::regex &beginExtensibleProperty();
/// Match a field or object level comment
/// matches[1], after '\' until next '\'
/// matches[2], after second '\' (may be empty)
UTILITIES_API const boost::regex &metaDataComment();
/// Match IDD names that correspond to a Version object.
UTILITIES_API const boost::regex &versionObjectName();
namespace detail {
struct IddRegexInitializer : StaticInitializer<IddRegexInitializer>
{
static void initialize()
{
commentOnlyObjectName();
commentOnlyObjectText();
version();
build();
header();
commentOnlyLine();
contentAndCommentLine();
group();
includeFile();
removeObject();
line();
memoProperty();
noteProperty();
objectNoFields();
objectAndFields();
uniqueProperty();
requiredObjectProperty();
obsoleteProperty();
hasurlProperty();
extensibleProperty();
formatProperty();
minFieldsProperty();
maxFieldsProperty();
field();
closingField();
lastField();
name();
nameProperty();
requiredFieldProperty();
autosizableProperty();
autocalculatableProperty();
retaincaseProperty();
unitsProperty();
ipUnitsProperty();
minExclusiveProperty();
minInclusiveProperty();
maxExclusiveProperty();
maxInclusiveProperty();
deprecatedProperty();
defaultProperty();
automaticDefault();
typeProperty();
keyProperty();
objectListProperty();
externalListProperty();
referenceProperty();
beginExtensible();
beginExtensibleProperty();
metaDataComment();
versionObjectName();
}
};
struct MakeSureIddRegexInitializerIsInitialized
{
MakeSureIddRegexInitializerIsInitialized()
{
}
IddRegexInitializer m_i;
};
}
} // iddRegex
} // openstudio
#endif // UTILITIES_IDD_IDDREGEX_HPP
| 32.313333 | 87 | 0.683722 | [
"object"
] |
b4ea34a63cdd16843dc75c1d271467bcd670f740 | 1,759 | cpp | C++ | Luogu/P4862/dp_observation.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2018-02-14T01:59:31.000Z | 2018-03-28T03:30:45.000Z | Luogu/P4862/dp_observation.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | null | null | null | Luogu/P4862/dp_observation.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2017-12-30T02:46:35.000Z | 2018-03-28T03:30:49.000Z | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <string>
#include <cstring>
#include <iomanip>
#include <climits>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <functional>
#include <iterator>
using namespace std;
#define SIZE 2010
int dp[SIZE];
long long int fiboPfxSum[SIZE];
int fiboPt;
void initFiboPfxSum()
{
fiboPfxSum[0] = 0;
fiboPfxSum[1] = 1;
fiboPfxSum[2] = 2;
long long int prev = 1, cnt = 1;
fiboPt = 3;
while (fiboPt < SIZE && fiboPfxSum[fiboPt - 1] <= 1e18)
{
long long int nxt = cnt + prev;
prev = cnt, cnt = nxt;
fiboPfxSum[fiboPt] = fiboPfxSum[fiboPt - 1] + nxt;
fiboPt++;
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int a, b, qNum;
cin >> a >> b >> qNum;
if (a == 2 && b == 1)
{
// Observation part: Fibonacci
initFiboPfxSum();
while (qNum--)
{
long long int cnt;
cin >> cnt;
if (cnt == 1)
{
cout << 0 << endl;
continue;
}
int pos = lower_bound(fiboPfxSum + 0, fiboPfxSum + fiboPt, cnt - 1) - fiboPfxSum;
cout << pos + 1 << endl;
}
return 0;
}
dp[1] = 0;
for (int i = 2; i < SIZE; i++)
{
dp[i] = INT_MAX;
for (int j = 1; j < i; j++)
{
dp[i] = min(dp[i], max(dp[j] + a, dp[i - j] + b));
}
}
while (qNum--)
{
int cnt;
cin >> cnt;
cout << dp[cnt] << endl;
}
return 0;
} | 19.544444 | 94 | 0.457078 | [
"vector"
] |
b4eaa4782e03e285623927f2341b50cb079d5eb6 | 1,480 | cpp | C++ | Cplus/DetectSquares.cpp | JumHorn/leetcode | 1447237ae8fc3920b19f60b30c71a84b088cc200 | [
"MIT"
] | 1 | 2018-01-22T12:06:28.000Z | 2018-01-22T12:06:28.000Z | Cplus/DetectSquares.cpp | JumHorn/leetcode | 1447237ae8fc3920b19f60b30c71a84b088cc200 | [
"MIT"
] | null | null | null | Cplus/DetectSquares.cpp | JumHorn/leetcode | 1447237ae8fc3920b19f60b30c71a84b088cc200 | [
"MIT"
] | null | null | null | #include <vector>
using namespace std;
class DetectSquares
{
public:
DetectSquares() : data(2000000)
{
}
void add(vector<int> point)
{
int x = point[0], y = point[1];
++data[encode(x, y)];
}
int count(vector<int> point)
{
int x = point[0], y = point[1], res = 0;
//左下
for (int l = 1; x - l >= 0 && y - l >= 0; ++l)
{
int p1 = x - l, p2 = y - l;
int q1 = p1, q2 = y;
int r1 = x, r2 = p2;
res += data[encode(p1, p2)] * data[encode(q1, q2)] * data[encode(r1, r2)];
}
//右上
for (int l = 1; x + l < LEN && y + l < LEN; ++l)
{
int p1 = x + l, p2 = y + l;
int q1 = x, q2 = p2;
int r1 = p1, r2 = y;
res += data[encode(p1, p2)] * data[encode(q1, q2)] * data[encode(r1, r2)];
}
//左上
for (int l = 1; x - l >= 0 && y + l < LEN; ++l)
{
int p1 = x - l, p2 = y + l;
int q1 = p1, q2 = y;
int r1 = x, r2 = p2;
res += data[encode(p1, p2)] * data[encode(q1, q2)] * data[encode(r1, r2)];
}
//右下
for (int l = 1; x + l < LEN && y - l >= 0; ++l)
{
int p1 = x + l, p2 = y - l;
int q1 = x, q2 = p2;
int r1 = p1, r2 = y;
res += data[encode(p1, p2)] * data[encode(q1, q2)] * data[encode(r1, r2)];
}
return res;
}
int encode(int x, int y)
{
return x * LEN + y;
}
private:
int LEN = 1001;
vector<int> data; // x*1001+y
};
/**
* Your DetectSquares object will be instantiated and called as such:
* DetectSquares* obj = new DetectSquares();
* obj->add(point);
* int param_2 = obj->count(point);
*/ | 21.142857 | 77 | 0.504054 | [
"object",
"vector"
] |
b4f35466435f0391c348f9109b549a7ac429a605 | 52,144 | hpp | C++ | src/stage/batched/host/KokkosKernels_Test_BlockCrs.hpp | crtrott/kokkos-kernels | 0dba50f62188eb82da35bb4fe0211c7783300903 | [
"BSD-3-Clause"
] | null | null | null | src/stage/batched/host/KokkosKernels_Test_BlockCrs.hpp | crtrott/kokkos-kernels | 0dba50f62188eb82da35bb4fe0211c7783300903 | [
"BSD-3-Clause"
] | null | null | null | src/stage/batched/host/KokkosKernels_Test_BlockCrs.hpp | crtrott/kokkos-kernels | 0dba50f62188eb82da35bb4fe0211c7783300903 | [
"BSD-3-Clause"
] | null | null | null | #include <cassert>
#include <vector>
#include <algorithm>
#if defined(__KOKKOSKERNELS_INTEL_MKL__)
#include "mkl.h"
#endif
#include "Kokkos_Core.hpp"
#include "impl/Kokkos_Timer.hpp"
#include "KokkosKernels_Util.hpp"
#include "KokkosKernels_Vector.hpp"
#include "KokkosKernels_Gemv_Decl.hpp"
#include "KokkosKernels_Gemv_Serial_Impl.hpp"
#include "KokkosKernels_Trsv_Decl.hpp"
#include "KokkosKernels_Trsv_Serial_Impl.hpp"
#include "KokkosKernels_Gemm_Decl.hpp"
#include "KokkosKernels_Gemm_Serial_Impl.hpp"
#include "KokkosKernels_Gemm_Team_Impl.hpp"
#include "KokkosKernels_Trsm_Serial_Decl.hpp"
#include "KokkosKernels_Trsm_Serial_Impl.hpp"
#include "KokkosKernels_LU_Serial_Decl.hpp"
#include "KokkosKernels_LU_Serial_Impl.hpp"
#include "KokkosKernels_Test_BlockCrs_Util.hpp"
namespace KokkosKernels {
namespace Test {
template <typename ExecSpace>
class BlockCrsMatrixVectorProductByRow {
public:
typedef BlockCrsMatrix<ExecSpace> block_crs_matrix_type;
typedef typename block_crs_matrix_type::crs_graph_type crs_graph_type;
typedef BlockMultiVector<ExecSpace> block_multi_vector_type;
private:
ConstUnmanagedViewType<typename crs_graph_type::row_ptr_type> _rowptr;
ConstUnmanagedViewType<typename crs_graph_type::col_idx_type> _colidx;
ConstUnmanagedViewType<typename block_crs_matrix_type::value_array_type> _A;
ConstUnmanagedViewType<typename block_multi_vector_type::value_array_type> _x;
/**/ UnmanagedViewType<typename block_multi_vector_type::value_array_type> _y;
ordinal_type _blocksize;
public:
// A thread maps to a point row of the matrix.
// loop = blksize*m
KOKKOS_INLINE_FUNCTION
void operator()(const ordinal_type idx) const {
// index of blockrow and row in a block
const ordinal_type i = idx/_blocksize;
const ordinal_type ii = idx%_blocksize;
// loop over multivectors
const ordinal_type jend = _y.dimension_0();
for (ordinal_type j=0;j<jend;++j) {
scalar_type tmp = 0;
// block row
const ordinal_type
cbegin = _rowptr(i), cend = _rowptr(i+1);
for (ordinal_type c=cbegin;c<cend;++c) {
const ordinal_type col = _colidx(c);
for (ordinal_type jj=0;jj<_blocksize;++jj)
tmp += _A(col,ii,jj)*_x(j, col, jj);
}
_y(j, i, ii) = tmp;
}
}
void run(const block_crs_matrix_type A,
const block_multi_vector_type x,
const block_multi_vector_type y) {
_rowptr = A.CrsGraph().rowptr;
_colidx = A.CrsGraph().colidx;
_blocksize = A.BlockSize();
_A = A.Values();
_x = x.Values();
_y = y.Values();
Kokkos::parallel_for(_x.dimension_1()*_blocksize, *this);
}
};
template <typename ExecSpace>
class BlockCrsMatrixVectorProductByBlockRow {
public:
typedef BlockCrsMatrix<ExecSpace> block_crs_matrix_type;
typedef typename block_crs_matrix_type::crs_graph_type crs_graph_type;
typedef BlockMultiVector<ExecSpace> block_multi_vector_type;
private:
ConstUnmanagedViewType<typename crs_graph_type::row_ptr_type> _rowptr;
ConstUnmanagedViewType<typename crs_graph_type::col_idx_type> _colidx;
ConstUnmanagedViewType<typename block_crs_matrix_type::value_array_type> _A;
ConstUnmanagedViewType<typename block_multi_vector_type::value_array_type> _x;
/**/ UnmanagedViewType<typename block_multi_vector_type::value_array_type> _y;
ordinal_type _blocksize;
public:
// A thread maps to a row block of the matrix.
// loop = m
KOKKOS_INLINE_FUNCTION
void operator()(const ordinal_type i) const {
// loop over multivector colums
const ordinal_type jend = _y.dimension_0();
for (ordinal_type j=0;j<jend;++j) {
// set zero
for (ordinal_type ii=0;ii<_blocksize;++ii)
_y(j, i, ii) = 0;
// block row
const ordinal_type
cbegin = _rowptr(i), cend = _rowptr(i+1);
for (ordinal_type c=cbegin;c<cend;++c) {
const ordinal_type col = _colidx(c);
for (ordinal_type ii=0;ii<_blocksize;++ii) {
scalar_type tmp = 0;
for (ordinal_type jj=0;jj<_blocksize;++jj)
tmp += _A(col,ii,jj)*_x(j, col, jj);
_y(j, i, ii) += tmp;
}
}
}
}
void run(const block_crs_matrix_type A,
const block_multi_vector_type x,
const block_multi_vector_type y) {
_rowptr = A.CrsGraph().rowptr;
_colidx = A.CrsGraph().colidx;
_blocksize = A.BlockSize();
_A = A.Values();
_x = x.Values();
_y = y.Values();
Kokkos::parallel_for(_x.dimension_1(), *this);
}
};
template <typename ExecSpace, typename ValueType>
class ExtractBlockTridiagMatrices {
public:
typedef ExecSpace exec_space;
typedef ValueType value_type;
typedef StructuredBlock structured_block_mesh_type;
typedef BlockCrsMatrix<exec_space> block_crs_matrix_type;
typedef typename block_crs_matrix_type::crs_graph_type crs_graph_type;
typedef BlockTridiagMatrices<exec_space,value_type> block_tridiag_matrices_type;
private:
structured_block_mesh_type _mesh;
ordinal_type _blocksize;
ConstUnmanagedViewType<typename crs_graph_type::row_ptr_type> _rowptr;
ConstUnmanagedViewType<typename crs_graph_type::row_idx_type> _rowidx;
ConstUnmanagedViewType<typename crs_graph_type::col_idx_type> _colidx;
ConstUnmanagedViewType<typename block_crs_matrix_type::value_array_type> _A;
/**/ UnmanagedViewType<typename block_tridiag_matrices_type::value_array_type> _TA, _TB, _TC;
public:
ExtractBlockTridiagMatrices(const structured_block_mesh_type mesh)
: _mesh(mesh) {}
template<typename TViewType,
typename AViewType>
KOKKOS_INLINE_FUNCTION
void
elementwise_copy(const TViewType &T,
const AViewType &A,
const ordinal_type ij,
const ordinal_type k,
const ordinal_type c,
const ordinal_type blocksize) const {
for (ordinal_type ii=0;ii<blocksize;++ii)
for (ordinal_type jj=0;jj<blocksize;++jj)
tdiag_val(T, ij, k, ii, jj) = A(c, ii, jj);
}
// A thread maps nonzero blocks
KOKKOS_INLINE_FUNCTION
void operator()(const ordinal_type c) const {
const ordinal_type row = _rowidx[c], col = _colidx[c];
ordinal_type ri, rj, rk, ci, cj, ck;
_mesh.id2ijk(row, ri, rj, rk);
_mesh.id2ijk(col, ci, cj, ck);
if (ri == ci && rj == cj) {
const ordinal_type ij = _mesh.ij2id(ri, rj);
// consider connectivity to k-direction
switch (rk - ck) {
case 1: elementwise_copy(_TC, _A, ij, ck, c, _blocksize); break;
case 0: elementwise_copy(_TA, _A, ij, rk, c, _blocksize); break;
case -1: elementwise_copy(_TB, _A, ij, rk, c, _blocksize); break;
}
}
}
void run(const block_crs_matrix_type A,
const block_tridiag_matrices_type T) {
_rowptr = A.CrsGraph().rowptr;
_rowidx = A.CrsGraph().rowidx;
_colidx = A.CrsGraph().colidx;
_A = A.Values();
_TA = T.A();
_TB = T.B();
_TC = T.C();
_blocksize = A.BlockSize();
Kokkos::parallel_for(_A.dimension_0(), *this);
}
template<typename TViewType,
typename AViewType>
bool elementwise_check(const TViewType &T,
const AViewType &A,
const ordinal_type ij,
const ordinal_type k,
const ordinal_type c,
const ordinal_type blocksize) const {
const auto eps = 1e2*std::numeric_limits<scalar_type>::epsilon();
for (ordinal_type ii=0;ii<blocksize;++ii)
for (ordinal_type jj=0;jj<blocksize;++jj)
if ( std::abs(tdiag_val(T, ij, k, ii, jj) - A(c, ii, jj)) >= eps ) return false;
return true;
}
bool check() const {
auto rowptr = Kokkos::create_mirror_view(_rowptr); Kokkos::deep_copy(rowptr, _rowptr);
auto colidx = Kokkos::create_mirror_view(_colidx); Kokkos::deep_copy(colidx, _colidx);
auto TA = Kokkos::create_mirror_view(_TA); Kokkos::deep_copy(TA, _TA);
auto TB = Kokkos::create_mirror_view(_TB); Kokkos::deep_copy(TB, _TB);
auto TC = Kokkos::create_mirror_view(_TC); Kokkos::deep_copy(TC, _TC);
auto A = Kokkos::create_mirror_view(_A); Kokkos::deep_copy(A, _A);
const ordinal_type
ijend = adjustDimension<value_type>(_mesh.ni*_mesh.nj),
kend = _mesh.nk;
assert(ijend == TA.dimension_0()); assert((kend - 0) == TA.dimension_1());
assert(ijend == TB.dimension_0()); assert((kend - 1) == TB.dimension_1());
assert(ijend == TC.dimension_0()); assert((kend - 1) == TC.dimension_1());
for (ordinal_type ij=0;ij<ijend;++ij) {
ordinal_type i, j;
_mesh.id2ij(ij, i, j);
for (ordinal_type k=0;k<kend;++k) {
const ordinal_type row = _mesh.ijk2id(i, j, k),
idx_begin = rowptr[row],
idx_end = rowptr[row+1];
// check
bool found[3] = {}, same[3] = {};
for (ordinal_type idx=idx_begin;idx<idx_end;++idx) {
switch (row - colidx[idx]) {
case 1: same[2] = elementwise_check(TC, A, ij, k-1, idx, _blocksize); found[2] = true; break;
case 0: same[0] = elementwise_check(TA, A, ij, k, idx, _blocksize); found[0] = true; break;
case -1: same[1] = elementwise_check(TB, A, ij, k, idx, _blocksize); found[1] = true; break;
}
}
if (k == 0) assert(found[0] & same[0] && found[1] & same[1]);
else if (k == (kend-1)) assert(found[0] & same[0] && found[2] & same[2]);
else assert(found[0] & same[0] && found[1] & same[1] && found[2] & same[2]);
}
}
return true;
}
};
template <typename ExecSpace, typename ValueType,
typename LU_AlgoTagType,
typename Trsm_AlgoTagType,
typename Gemm_AlgoTagType>
class FactorizeBlockTridiagMatrices {
public:
typedef ExecSpace exec_space;
typedef ValueType value_type;
typedef BlockTridiagMatrices<exec_space,value_type> block_tridiag_matrices_type;
private:
ordinal_type _ntridiag, _m, _blocksize;
UnmanagedViewType<typename block_tridiag_matrices_type::value_array_type> _TA, _TB, _TC;
public:
FactorizeBlockTridiagMatrices() {}
// A thread maps nonzero blocks
KOKKOS_INLINE_FUNCTION
void operator()(const ordinal_type ij) const {
auto A = Kokkos::subview(_TA, ij, Kokkos::ALL(), Kokkos::ALL(), Kokkos::ALL());
auto B = Kokkos::subview(_TB, ij, Kokkos::ALL(), Kokkos::ALL(), Kokkos::ALL());
auto C = Kokkos::subview(_TC, ij, Kokkos::ALL(), Kokkos::ALL(), Kokkos::ALL());
const ordinal_type kend = _m - 1;
for (ordinal_type k=0;k<kend;++k) {
auto AA = Kokkos::subview(A, k, Kokkos::ALL(), Kokkos::ALL());
auto BB = Kokkos::subview(B, k, Kokkos::ALL(), Kokkos::ALL());
auto CC = Kokkos::subview(C, k, Kokkos::ALL(), Kokkos::ALL());
auto DD = Kokkos::subview(A, k+1, Kokkos::ALL(), Kokkos::ALL());
Serial::LU<LU_AlgoTagType>
::invoke(AA);
Serial::Trsm<Side::Left,Uplo::Lower,Trans::NoTranspose,Diag::Unit,Trsm_AlgoTagType>
::invoke(1.0, AA, BB);
Serial::Trsm<Side::Right,Uplo::Upper,Trans::NoTranspose,Diag::NonUnit,Trsm_AlgoTagType>
::invoke(1.0, AA, CC);
Serial::Gemm<Trans::NoTranspose,Trans::NoTranspose,Gemm_AlgoTagType>
::invoke(-1.0, CC, BB, 1.0, DD);
}
auto AA = Kokkos::subview(A, kend, Kokkos::ALL(), Kokkos::ALL());
Serial::LU<LU_AlgoTagType>
::invoke(AA);
}
double FlopCount(const block_tridiag_matrices_type T) {
const int
ntridiag = T.NumTridiagMatrices(),
m = T.NumRows(),
blocksize = T.BlockSize();
return ntridiag*( (m-1)*(LU_FlopCount(blocksize, blocksize) +
Trsm_Lower_FlopCountLower(blocksize, blocksize) +
Trsm_Upper_FlopCountUpper(blocksize, blocksize) +
Gemm_FlopCount(blocksize, blocksize, blocksize)) +
LU_FlopCount(blocksize, blocksize) );
}
// for batched blas check
void run(const block_tridiag_matrices_type T, const bool fake = false) {
_ntridiag = T.NumTridiagMatrices();
_m = T.NumRows();
_blocksize = T.BlockSize();
_TA = T.A();
_TB = T.B();
_TC = T.C();
// parallel over the instances of tridiagonal matrices
if (!fake)
Kokkos::parallel_for(_ntridiag, *this);
}
template<typename AViewType, typename LViewType, typename UViewType>
void a_subtract_mult_l_and_u(const ordinal_type tl, const ordinal_type il, AViewType A,
const ordinal_type tr, const ordinal_type ir, LViewType L, UViewType U) {
for (ordinal_type ii=0;ii<_blocksize;++ii)
for (ordinal_type jj=0;jj<_blocksize;++jj)
for (ordinal_type kk=0;kk<_blocksize;++kk) {
const auto l = ( ii == kk ? 1 :
ii > kk ? tdiag_val(L, tr, ir, ii, kk) : 0 );
const auto u = ( kk <= jj ? tdiag_val(U, tr, ir, kk, jj) : 0 );
tdiag_val(A, tl, il, ii, jj) -= l*u;
}
}
template<typename AViewType, typename BViewType, typename CViewType>
void a_subtract_mult_b_and_c(const ordinal_type tl, const ordinal_type il, AViewType A,
const ordinal_type tr, const ordinal_type ir, BViewType B, CViewType C) {
for (ordinal_type ii=0;ii<_blocksize;++ii)
for (ordinal_type jj=0;jj<_blocksize;++jj)
for (ordinal_type kk=0;kk<_blocksize;++kk)
tdiag_val(A, tl, il, ii, jj) -= ( tdiag_val(B, tr, ir, ii, kk)*
tdiag_val(C, tr, ir, kk, jj) );
}
template<typename AViewType, typename LViewType, typename BViewType>
void a_subtract_mult_l_and_b(const ordinal_type tl, const ordinal_type il, AViewType A,
const ordinal_type tr, const ordinal_type ir, LViewType L, BViewType B) {
for (ordinal_type ii=0;ii<_blocksize;++ii)
for (ordinal_type jj=0;jj<_blocksize;++jj)
for (ordinal_type kk=0;kk<_blocksize;++kk) {
const auto l = ( ii == kk ? 1.0 :
ii > kk ? tdiag_val(L, tr, ir, ii, kk) : 0 );
tdiag_val(A, tl, il, ii, jj) -= l*tdiag_val(B, tr, ir, kk, jj);
}
}
template<typename AViewType, typename BViewType, typename UViewType>
void a_subtract_mult_b_and_u(const ordinal_type tl, const ordinal_type il, AViewType A,
const ordinal_type tr, const ordinal_type ir, BViewType B, UViewType U) {
for (ordinal_type ii=0;ii<_blocksize;++ii)
for (ordinal_type jj=0;jj<_blocksize;++jj)
for (ordinal_type kk=0;kk<_blocksize;++kk) {
const auto u = ( kk <= jj ? tdiag_val(U, tr, ir, kk, jj) : 0 );
tdiag_val(A, tl, il, ii, jj) -= tdiag_val(B, tr, ir, ii, kk)*u;
}
}
bool check(const block_tridiag_matrices_type T) {
// factors
auto DD = Kokkos::create_mirror_view(_TA); Kokkos::deep_copy(DD, _TA);
auto UU = Kokkos::create_mirror_view(_TB); Kokkos::deep_copy(UU, _TB);
auto LL = Kokkos::create_mirror_view(_TC); Kokkos::deep_copy(LL, _TC);
// input A
auto A = Kokkos::create_mirror_view(T.A()); Kokkos::deep_copy(A, T.A());
auto B = Kokkos::create_mirror_view(T.B()); Kokkos::deep_copy(B, T.B());
auto C = Kokkos::create_mirror_view(T.C()); Kokkos::deep_copy(C, T.C());
// diffs
Kokkos::View<value_type****,Kokkos::DefaultHostExecutionSpace>
AA("AA", _ntridiag, _m, _blocksize, _blocksize),
BB("BB", _ntridiag, _m-1, _blocksize, _blocksize),
CC("CC", _ntridiag, _m-1, _blocksize, _blocksize);
Kokkos::deep_copy(AA, A);
Kokkos::deep_copy(BB, B);
Kokkos::deep_copy(CC, C);
// Check | A - L U | / | A |
for (ordinal_type t=0;t<_ntridiag;++t) {
a_subtract_mult_l_and_u(t, 0, AA,
t, 0, DD, DD);
for (ordinal_type i=1;i<_m;++i) {
a_subtract_mult_l_and_u(t, i, AA,
t, i, DD, DD);
a_subtract_mult_b_and_c(t, i, AA,
t, i-1, LL, UU);
a_subtract_mult_l_and_b(t, i-1, BB,
t, i-1, DD, UU);
a_subtract_mult_b_and_u(t, i-1, CC,
t, i-1, LL, DD);
}
}
double norm = 0, diff = 0;
for (ordinal_type t=0;t<_ntridiag;++t) {
for (ordinal_type ii=0;ii<_blocksize;++ii)
for (ordinal_type jj=0;jj<_blocksize;++jj) {
norm += std::abs(tdiag_val(A ,t, 0, ii, jj));
diff += std::abs(tdiag_val(AA,t, 0, ii, jj));
}
for (ordinal_type i=1;i<_m;++i)
for (ordinal_type ii=0;ii<_blocksize;++ii)
for (ordinal_type jj=0;jj<_blocksize;++jj) {
norm += std::abs(tdiag_val(A ,t, i, ii, jj));
diff += std::abs(tdiag_val(AA,t, i, ii, jj));
norm += std::abs(tdiag_val(B ,t, i-1, ii, jj));
diff += std::abs(tdiag_val(BB,t, i-1, ii, jj));
norm += std::abs(tdiag_val(C ,t, i-1, ii, jj));
diff += std::abs(tdiag_val(CC,t, i-1, ii, jj));
}
}
//std::cout << "tridiag factor check norm = " << norm << " diff = " << diff << std::endl;
const bool r_val = diff/norm < 1e2*std::numeric_limits<scalar_type>::epsilon();
return r_val;
}
};
template <typename ExecSpace, typename ValueType,
typename Trsv_AlgoTagType,
typename Gemv_AlgoTagType>
class SolveBlockTridiagMatrices {
public:
typedef ExecSpace exec_space;
typedef ValueType value_type;
typedef BlockTridiagMatrices<exec_space,value_type> block_tridiag_matrices_type;
typedef PartitionedBlockMultiVector<exec_space,value_type> partitioned_block_multi_vector_type;
private:
ordinal_type _ntridiag, _m, _blocksize, _nvectors;
ConstUnmanagedViewType<typename block_tridiag_matrices_type::value_array_type> _TA, _TB, _TC;
ConstUnmanagedViewType<typename partitioned_block_multi_vector_type::value_array_type> _b;
/**/ UnmanagedViewType<typename partitioned_block_multi_vector_type::value_array_type> _x;
public:
SolveBlockTridiagMatrices() {}
KOKKOS_INLINE_FUNCTION
void operator()(const ordinal_type ij) const {
auto A = Kokkos::subview(_TA, ij, Kokkos::ALL(), Kokkos::ALL(), Kokkos::ALL());
auto B = Kokkos::subview(_TB, ij, Kokkos::ALL(), Kokkos::ALL(), Kokkos::ALL());
auto C = Kokkos::subview(_TC, ij, Kokkos::ALL(), Kokkos::ALL(), Kokkos::ALL());
///
/// loop over multivectors
///
for (int jvec=0;jvec<_nvectors;++jvec) {
auto x = Kokkos::subview(_x, ij, jvec, Kokkos::ALL(), Kokkos::ALL());
auto b = Kokkos::subview(_b, ij, jvec, Kokkos::ALL(), Kokkos::ALL());
///
/// forward substitution
///
{
const bool is_same_x_and_b = (x.data() == b.data());
{
auto x0 = Kokkos::subview(x, 0, Kokkos::ALL());
auto b0 = Kokkos::subview(b, 0, Kokkos::ALL());
if (!is_same_x_and_b)
for (ordinal_type ii=0;ii<_blocksize;++ii)
x0(ii) = b0(ii);
}
const ordinal_type kend = _m - 1;
for (ordinal_type k=0;k<kend;++k) {
auto LT = Kokkos::subview(A, k, Kokkos::ALL(), Kokkos::ALL());
auto LB = Kokkos::subview(C, k, Kokkos::ALL(), Kokkos::ALL());
auto xt = Kokkos::subview(x, k, Kokkos::ALL());
auto xb = Kokkos::subview(x, k+1, Kokkos::ALL());
auto bb = Kokkos::subview(b, k+1, Kokkos::ALL());
if (!is_same_x_and_b)
for (ordinal_type ii=0;ii<_blocksize;++ii)
xb(ii) = bb(ii);
Serial::Trsv<Uplo::Lower,Trans::NoTranspose,Diag::Unit,Trsv_AlgoTagType>
::invoke(1.0, LT, xt);
Serial::Gemv<Trans::NoTranspose,Gemv_AlgoTagType>
::invoke(-1.0, LB, xt, 1.0, xb);
}
auto LL = Kokkos::subview(A, kend, Kokkos::ALL(), Kokkos::ALL());
auto xx = Kokkos::subview(x, kend, Kokkos::ALL());
Serial::Trsv<Uplo::Lower,Trans::NoTranspose,Diag::Unit,Trsv_AlgoTagType>
::invoke(1.0, LL, xx);
}
///
/// backward substitution
///
{
const ordinal_type kbegin = _m - 1;
for (ordinal_type k=kbegin;k>0;--k) {
auto UT = Kokkos::subview(B, k-1, Kokkos::ALL(), Kokkos::ALL());
auto UB = Kokkos::subview(A, k, Kokkos::ALL(), Kokkos::ALL());
auto xt = Kokkos::subview(x, k-1, Kokkos::ALL());
auto xb = Kokkos::subview(x, k, Kokkos::ALL());
Serial::Trsv<Uplo::Upper,Trans::NoTranspose,Diag::NonUnit,Trsv_AlgoTagType>
::invoke(1.0, UB, xb);
Serial::Gemv<Trans::NoTranspose,Gemv_AlgoTagType>
::invoke(-1.0, UT, xb, 1.0, xt);
}
auto UU = Kokkos::subview(A, 0, Kokkos::ALL(), Kokkos::ALL());
auto xx = Kokkos::subview(x, 0, Kokkos::ALL());
Serial::Trsv<Uplo::Upper,Trans::NoTranspose,Diag::NonUnit,Trsv_AlgoTagType>
::invoke(1.0, UU, xx);
}
}
}
void run(const block_tridiag_matrices_type T,
const partitioned_block_multi_vector_type x,
const partitioned_block_multi_vector_type b) {
assert(T.NumTridiagMatrices() == x.NumPartitions());
assert(T.NumRows() == x.NumRows());
assert(T.BlockSize() == x.BlockSize());
_ntridiag = T.NumTridiagMatrices();
_m = T.NumRows();
_blocksize = T.BlockSize();
_nvectors = x.NumVectors();
_TA = T.A();
_TB = T.B();
_TC = T.C();
_x = x.Values();
_b = b.Values();
// parallel over the instances of tridiagonal matrices
Kokkos::parallel_for(_ntridiag, *this);
}
template<typename RViewType, typename AViewType, typename XViewType>
void r_subtract_mult_a_and_x(const ordinal_type tr, const ordinal_type ir, RViewType R,
const ordinal_type ta, const ordinal_type ia, AViewType A,
const ordinal_type tx, const ordinal_type ix, XViewType X) {
for (ordinal_type kk=0;kk<_nvectors;++kk)
for (ordinal_type ii=0;ii<_blocksize;++ii)
for (ordinal_type jj=0;jj<_blocksize;++jj)
tdiag_val(R, tr, kk, ir, ii) -= tdiag_val(A, ta, ia, ii, jj) * tdiag_val(X, tx, kk, ix, jj);
}
bool check(const block_tridiag_matrices_type T,
const partitioned_block_multi_vector_type b) {
// input A
auto AA = Kokkos::create_mirror_view(T.A()); Kokkos::deep_copy(AA, T.A());
auto BB = Kokkos::create_mirror_view(T.B()); Kokkos::deep_copy(BB, T.B());
auto CC = Kokkos::create_mirror_view(T.C()); Kokkos::deep_copy(CC, T.C());
auto bb = Kokkos::create_mirror_view(b.Values()); Kokkos::deep_copy(bb, b.Values());
auto xx = Kokkos::create_mirror_view(_x); Kokkos::deep_copy(xx, _x);
// diffs
Kokkos::View<value_type****,Kokkos::DefaultHostExecutionSpace>
rr("rr", bb.dimension_0(), bb.dimension_1(), bb.dimension_2(), bb.dimension_3());
Kokkos::deep_copy(rr, bb);
// Check | Ax - b | / | b |
for (ordinal_type t=0;t<_ntridiag;++t) {
r_subtract_mult_a_and_x(t, 0, rr,
t, 0, AA,
t, 0, xx);
r_subtract_mult_a_and_x(t, 0, rr,
t, 0, BB,
t, 1, xx);
for (ordinal_type i=1;i<(_m-1);++i) {
r_subtract_mult_a_and_x(t, i, rr,
t, i-1, CC,
t, i-1, xx);
r_subtract_mult_a_and_x(t, i, rr,
t, i, AA,
t, i, xx);
r_subtract_mult_a_and_x(t, i, rr,
t, i, BB,
t, i+1, xx);
}
r_subtract_mult_a_and_x(t, _m-1, rr,
t, _m-2, CC,
t, _m-2, xx);
r_subtract_mult_a_and_x(t, _m-1, rr,
t, _m-1, AA,
t, _m-1, xx);
}
double norm = 0, diff = 0;
for (ordinal_type t=0;t<_ntridiag;++t)
for (ordinal_type jvec=0;jvec<_nvectors;++jvec)
for (ordinal_type i=0;i<_m;++i)
for (ordinal_type ii=0;ii<_blocksize;++ii) {
norm += std::abs(tdiag_val(bb, t, jvec, i, ii));
diff += std::abs(tdiag_val(rr, t, jvec, i, ii));
}
//std::cout << "tridiag solve check norm = " << norm << " diff = " << diff << std::endl;
const bool r_val = diff/norm < 1e2*std::numeric_limits<scalar_type>::epsilon();
return r_val;
}
};
// unit tests
template<typename DeviceSpace, typename ValueType = scalar_type>
void run(const ordinal_type ni, const ordinal_type nj, const ordinal_type nk,
const ordinal_type blocksize,
const ordinal_type nrhs,
const int test_mkl = 0) {
typedef Kokkos::DefaultHostExecutionSpace HostSpace;
bool success = true;
StructuredBlock mesh(ni, nj, nk);
// Test StructuredBlock.
for (ordinal_type c=0;c<mesh.size();++c) {
ordinal_type i, j, k;
mesh.id2ijk(c, i, j, k);
TEST_ASSERT(i >= 0 && i < mesh.ni, success);
TEST_ASSERT(j >= 0 && j < mesh.nj, success);
TEST_ASSERT(k >= 0 && k < mesh.nk, success);
TEST_ASSERT(mesh.ijk2id(i, j, k) == c, success);
}
// Graph construction
CrsGraph<HostSpace> graph_host = create_graph_host_for_structured_block(mesh, StencilShape::cross);
// Crs matrix and multi vector construction
BlockCrsMatrix<HostSpace> A_host(graph_host, blocksize);
fill_block_crs_matrix_host(A_host);
// Device mirroring
auto A_device = create_mirror<DeviceSpace>(A_host);
deep_copy(A_device, A_host);
// Test Matrix Vector product
{
const ordinal_type m = graph_host.NumRows();
BlockMultiVector<HostSpace> x_host(nrhs, m, blocksize);
fill_block_multi_vector_host(x_host);
auto x_device = create_mirror<DeviceSpace>(x_host);
deep_copy(x_device, x_host);
BlockMultiVector<DeviceSpace> y1_device(nrhs, m, blocksize), y2_device(nrhs, m, blocksize);
{
BlockCrsMatrixVectorProductByRow<DeviceSpace> matvec;
matvec.run(A_device, x_device, y1_device);
}
{
BlockCrsMatrixVectorProductByBlockRow<DeviceSpace> matvec;
matvec.run(A_device, x_device, y2_device);
}
const double rdiff = compute_relative_diff(y1_device.Values(), y2_device.Values());
TEST_ASSERT(rdiff <= 1e2*std::numeric_limits<scalar_type>::epsilon(), success);
}
// Test Block TriDiag Extraction
BlockTridiagMatrices<DeviceSpace,ValueType> T_device
= create_block_tridiag_matrices<DeviceSpace,ValueType>(mesh.ni*mesh.nj,
mesh.nk,
blocksize);
{
ExtractBlockTridiagMatrices<DeviceSpace,ValueType> extblk(mesh);
extblk.run(A_device, T_device);
TEST_ASSERT(extblk.check(), success);
}
BlockTridiagMatrices<DeviceSpace,ValueType> T_org_device
= create_block_tridiag_matrices<DeviceSpace,ValueType>(mesh.ni*mesh.nj,
mesh.nk,
blocksize);
deep_copy(T_org_device, T_device);
// Test Block TriDiag Factorization
switch (test_mkl) {
case 0: {
FactorizeBlockTridiagMatrices<DeviceSpace,
ValueType,
Algo::LU::Blocked,
Algo::Trsm::Blocked,
Algo::Gemm::Blocked> factorblk;
factorblk.run(T_device);
TEST_ASSERT(factorblk.check(T_org_device), success);
break;
}
case 1: {
FactorizeBlockTridiagMatrices<DeviceSpace,
ValueType,
Algo::LU::CompactMKL,
Algo::Trsm::CompactMKL,
Algo::Gemm::CompactMKL> factorblk;
factorblk.run(T_device);
TEST_ASSERT(factorblk.check(T_org_device), success);
break;
}
case 2: {
const int ntridiags = adjustDimension<ValueType>(mesh.ni*mesh.nj), nrows = mesh.nk;
Kokkos::View<ValueType****,DeviceSpace> TA("TA_mkl", nrows, ntridiags, blocksize, blocksize);
Kokkos::View<ValueType****,DeviceSpace> TB("TB_mkl", nrows-1, ntridiags, blocksize, blocksize);
Kokkos::View<ValueType****,DeviceSpace> TC("TC_mkl", nrows-1, ntridiags, blocksize, blocksize);
// change the order to store the matrix
for (int i=0;i<nrows;++i)
for (int j=0;j<ntridiags;++j)
for (int k=0;k<blocksize;++k)
for (int l=0;l<blocksize;++l) {
TA(i,j,k,l) = T_device.A()(j,i,k,l);
if (i<(nrows-1)) {
TB(i,j,k,l) = T_device.B()(j,i,k,l);
TC(i,j,k,l) = T_device.C()(j,i,k,l);
}
}
// matrix factorization
{
MKL_INT blksize[1] = { blocksize };
MKL_INT lda[1] = { TA.stride_2() };
MKL_INT ldb[1] = { TB.stride_2() };
MKL_INT ldc[1] = { TC.stride_2() };
MKL_INT size_per_grp[1] = { ntridiags*(sizeof(ValueType)/sizeof(double)) };
struct {
CBLAS_SIDE side[1] = {CblasLeft};
CBLAS_UPLO uplo[1] = {CblasLower};
CBLAS_TRANSPOSE transA[1] = {CblasNoTrans};
CBLAS_DIAG diag[1] = {CblasUnit};
double alpha[1] = { 1.0 };
} trsm_lower_params;
struct {
CBLAS_SIDE side[1] = {CblasRight};
CBLAS_UPLO uplo[1] = {CblasUpper};
CBLAS_TRANSPOSE transA[1] = {CblasNoTrans};
CBLAS_DIAG diag[1] = {CblasNonUnit};
double alpha[1] = { 1.0 };
} trsm_upper_params;
struct {
CBLAS_TRANSPOSE transA[1] = {CblasNoTrans};
CBLAS_TRANSPOSE transB[1] = {CblasNoTrans};
double alpha[1] = { -1.0 };
double beta[1] = { 1.0 };
} gemm_params;
compact_t A_p, B_p, C_p;
A_p.layout = CblasRowMajor;
A_p.rows = blksize;
A_p.cols = blksize;
A_p.stride = lda;
A_p.group_count = 1;
A_p.size_per_group = size_per_grp;
A_p.format = sizeof(ValueType)/sizeof(double);
B_p.layout = CblasRowMajor;
B_p.rows = blksize;
B_p.cols = blksize;
B_p.stride = ldb;
B_p.group_count = 1;
B_p.size_per_group = size_per_grp;
B_p.format = sizeof(ValueType)/sizeof(double);
C_p.layout = CblasRowMajor;
C_p.rows = blksize;
C_p.cols = blksize;
C_p.stride = ldb;
C_p.group_count = 1;
C_p.size_per_group = size_per_grp;
C_p.format = sizeof(ValueType)/sizeof(double);
const int iend = nrows - 1;
for (int i=0;i<iend;++i) {
A_p.mat = (double*)&TA(i, 0, 0, 0);
LAPACKE_dgetrf_compute_batch(&A_p);
B_p.mat = (double*)&TB(i, 0, 0, 0);
cblas_dtrsm_compute_batch(trsm_lower_params.side,
trsm_lower_params.uplo,
trsm_lower_params.transA,
trsm_lower_params.diag,
trsm_lower_params.alpha,
&A_p,
&B_p);
C_p.mat = (double*)&TC(i, 0, 0, 0);
cblas_dtrsm_compute_batch(trsm_upper_params.side,
trsm_upper_params.uplo,
trsm_upper_params.transA,
trsm_upper_params.diag,
trsm_upper_params.alpha,
&A_p,
&C_p);
A_p.mat = (double*)&TA(i+1, 0, 0, 0);
cblas_dgemm_compute_batch(gemm_params.transA,
gemm_params.transB,
gemm_params.alpha,
&C_p,
&B_p,
gemm_params.beta,
&A_p);
}
A_p.mat = (double*)&TA(iend, 0, 0, 0);
LAPACKE_dgetrf_compute_batch(&A_p);
}
// put back to original matrix for checking
for (int i=0;i<nrows;++i)
for (int j=0;j<ntridiags;++j)
for (int k=0;k<blocksize;++k)
for (int l=0;l<blocksize;++l) {
T_device.A()(j,i,k,l) = TA(i,j,k,l);
if (i<(nrows-1)) {
T_device.B()(j,i,k,l) = TB(i,j,k,l);
T_device.C()(j,i,k,l) = TC(i,j,k,l);
}
}
// checking
{
FactorizeBlockTridiagMatrices<DeviceSpace,
ValueType,
Algo::LU::Blocked,
Algo::Trsm::Blocked,
Algo::Gemm::Blocked> factorblk;
const bool fake = true;
factorblk.run(T_device, fake);
TEST_ASSERT(factorblk.check(T_org_device), success);
}
break;
}
}
// Test Block TriDiag Solve
{
PartitionedBlockMultiVector<HostSpace,ValueType> b_host
= create_partitioned_block_multi_vector<HostSpace,ValueType>(mesh.ni*mesh.nj,
nrhs,
mesh.nk,
blocksize);
fill_partitioned_block_multi_vector_host(b_host, mesh.ni*mesh.nj);
auto b_device = create_mirror<DeviceSpace>(b_host);
deep_copy(b_device, b_host);
PartitionedBlockMultiVector<DeviceSpace,ValueType> x_device
= create_partitioned_block_multi_vector<DeviceSpace,ValueType>(mesh.ni*mesh.nj,
nrhs,
mesh.nk,
blocksize);
if (test_mkl) {
SolveBlockTridiagMatrices<DeviceSpace,
ValueType,
Algo::Trsv::CompactMKL,
Algo::Gemv::CompactMKL> solveblk;
solveblk.run(T_device, x_device, b_device);
TEST_ASSERT(solveblk.check(T_org_device, b_device), success);
} else {
SolveBlockTridiagMatrices<DeviceSpace,
ValueType,
Algo::Trsv::Blocked,
Algo::Gemv::Blocked> solveblk;
solveblk.run(T_device, x_device, b_device);
TEST_ASSERT(solveblk.check(T_org_device, b_device), success);
}
}
if (!success)
std::cout << "Unit Tests:: Failed:: "
<< " ni = " << ni << " nj = " << nj << " nk = " << nk
<< " blocksize = " << blocksize << " nrhs = " << nrhs << " \n";
}
// performance tests
template<typename DeviceSpace, typename ValueType = scalar_type>
int run(const Input &input, const int test_mkl = 0) {
typedef Kokkos::DefaultHostExecutionSpace HostSpace;
const ordinal_type niter = 50;
int dontopt = 0;
bool success = true;
///
/// construct a discrete system of equations
///
const ordinal_type
ni = input.ni,
nj = input.nj,
nk = input.nk,
blocksize = input.bs,
nrhs = input.nrhs;
StructuredBlock mesh(ni, nj, nk);
// something is not copyable ... don't know why yet...
BlockCrsMatrix<DeviceSpace> A_device;
double t_fill_block_crs_matrix = 0.0, t_fill_graph = 0.0;
{
const StencilShape::Enum stencil_shape = input.stencil_shape;
CrsGraph<HostSpace> graph_host;
{
Timer timer("Fill Graph _______________");
timer.reset();
graph_host = create_graph_host_for_structured_block(mesh, stencil_shape);
t_fill_graph = timer.seconds();
}
BlockCrsMatrix<HostSpace> A_host(graph_host, blocksize);
{
Timer timer("Fill Block CRS Matrix_______________");
timer.reset();
fill_block_crs_matrix_host(A_host);
t_fill_block_crs_matrix = timer.seconds();
}
A_device = create_mirror<DeviceSpace>(A_host);
deep_copy(A_device, A_host);
}
// memory size
const double memsize_A = A_device.Values().dimension_0()*blocksize*blocksize*8;
///
/// matrix vector multiplication test
///
double t_matvec = 0.0;
double t_fill_block_multi_vector = 0.0;
{
const ordinal_type m = mesh.size();
BlockMultiVector<HostSpace> x_host(nrhs, m, blocksize);
{
Timer timer("Fill Block Multi Vector______________");
timer.reset();
fill_block_multi_vector_host(x_host);
t_fill_block_multi_vector = timer.seconds();
}
auto x_device = create_mirror<DeviceSpace>(x_host);
deep_copy(x_device, x_host);
BlockMultiVector<DeviceSpace> y_device(nrhs, m, blocksize);
{
//BlockCrsMatrixVectorProductByRow<DeviceSpace> matvec;
BlockCrsMatrixVectorProductByBlockRow<DeviceSpace> matvec;
{
Timer timer("50 BlockCrsMatrixVectorProduct");
timer.reset();
for (ordinal_type i=0;i<niter;++i) {
matvec.run(A_device, x_device, y_device);
dontopt += i;
}
t_matvec = timer.seconds();
}
}
}
///
/// block tridiag extraction test
///
const double memsize_T = ni*nj*(3*(nk-1)*blocksize*blocksize + blocksize*blocksize)*8;
double t_extract = 0.0;
BlockTridiagMatrices<DeviceSpace,ValueType> T_device
= create_block_tridiag_matrices<DeviceSpace,ValueType>(ni*nj, nk, blocksize);
{
ExtractBlockTridiagMatrices<DeviceSpace,ValueType> extblk(mesh);
{
Timer timer("ExtractBlockTridiagMatrices");
timer.reset();
extblk.run(A_device, T_device);
t_extract = timer.seconds();
}
if (input.check) TEST_ASSERT(extblk.check(), success);
}
// keep original matrix for check
BlockTridiagMatrices<DeviceSpace,ValueType> T_org_device
= create_block_tridiag_matrices<DeviceSpace,ValueType>(ni*nj, nk, blocksize);
deep_copy(T_org_device, T_device);
///
/// block tridiag factorization test
///
double t_factorize = 0.0, f_factorize = 0.0;
switch (test_mkl) {
case 0: {
FactorizeBlockTridiagMatrices<DeviceSpace,
ValueType,
Algo::LU::Blocked,
Algo::Trsm::Blocked,
Algo::Gemm::Blocked> factorblk;
f_factorize = factorblk.FlopCount(T_device)*(sizeof(ValueType)/sizeof(double));
{
Timer timer("FactorizeBlockTridiagMatrices");
timer.reset();
factorblk.run(T_device);
t_factorize = timer.seconds();
}
if (input.check) TEST_ASSERT(factorblk.check(T_org_device), success);
break;
}
case 1: {
FactorizeBlockTridiagMatrices<DeviceSpace,
ValueType,
Algo::LU::CompactMKL,
Algo::Trsm::CompactMKL,
Algo::Gemm::CompactMKL> factorblk;
f_factorize = factorblk.FlopCount(T_device)*(sizeof(ValueType)/sizeof(double));
{
Timer timer("FactorizeBlockTridiagMatrices");
timer.reset();
factorblk.run(T_device);
t_factorize = timer.seconds();
}
if (input.check) TEST_ASSERT(factorblk.check(T_org_device), success);
break;
}
case 2: {
const int ntridiags = adjustDimension<ValueType>(mesh.ni*mesh.nj), nrows = mesh.nk;
Kokkos::View<ValueType****,DeviceSpace> TA("TA_mkl", nrows, ntridiags, blocksize, blocksize);
Kokkos::View<ValueType****,DeviceSpace> TB("TB_mkl", nrows-1, ntridiags, blocksize, blocksize);
Kokkos::View<ValueType****,DeviceSpace> TC("TC_mkl", nrows-1, ntridiags, blocksize, blocksize);
// change the order to store the matrix
for (int i=0;i<nrows;++i)
for (int j=0;j<ntridiags;++j)
for (int k=0;k<blocksize;++k)
for (int l=0;l<blocksize;++l) {
TA(i,j,k,l) = T_device.A()(j,i,k,l);
if (i<(nrows-1)) {
TB(i,j,k,l) = T_device.B()(j,i,k,l);
TC(i,j,k,l) = T_device.C()(j,i,k,l);
}
}
{
// matrix factorization
Timer timer("FactorizeBlockTridiagMatrices");
MKL_INT blksize[1] = { blocksize };
MKL_INT lda[1] = { TA.stride_2() };
MKL_INT ldb[1] = { TB.stride_2() };
MKL_INT ldc[1] = { TC.stride_2() };
MKL_INT size_per_grp[1] = { ntridiags*sizeof(ValueType)/sizeof(double) };
struct {
CBLAS_SIDE side[1] = {CblasLeft};
CBLAS_UPLO uplo[1] = {CblasLower};
CBLAS_TRANSPOSE transA[1] = {CblasNoTrans};
CBLAS_DIAG diag[1] = {CblasUnit};
double alpha[1] = { 1.0 };
} trsm_lower_params;
struct {
CBLAS_SIDE side[1] = {CblasRight};
CBLAS_UPLO uplo[1] = {CblasUpper};
CBLAS_TRANSPOSE transA[1] = {CblasNoTrans};
CBLAS_DIAG diag[1] = {CblasNonUnit};
double alpha[1] = { 1.0 };
} trsm_upper_params;
struct {
CBLAS_TRANSPOSE transA[1] = {CblasNoTrans};
CBLAS_TRANSPOSE transB[1] = {CblasNoTrans};
double alpha[1] = { -1.0 };
double beta[1] = { 1.0 };
} gemm_params;
compact_t A_p, B_p, C_p;
A_p.layout = CblasRowMajor;
A_p.rows = blksize;
A_p.cols = blksize;
A_p.stride = lda;
A_p.group_count = 1;
A_p.size_per_group = size_per_grp;
A_p.format = sizeof(ValueType)/sizeof(double);
B_p.layout = CblasRowMajor;
B_p.rows = blksize;
B_p.cols = blksize;
B_p.stride = ldb;
B_p.group_count = 1;
B_p.size_per_group = size_per_grp;
B_p.format = sizeof(ValueType)/sizeof(double);
C_p.layout = CblasRowMajor;
C_p.rows = blksize;
C_p.cols = blksize;
C_p.stride = ldb;
C_p.group_count = 1;
C_p.size_per_group = size_per_grp;
C_p.format = sizeof(ValueType)/sizeof(double);
timer.reset();
const int iend = nrows - 1;
for (int i=0;i<iend;++i) {
A_p.mat = (double*)&TA(i, 0, 0, 0);
B_p.mat = (double*)&TB(i, 0, 0, 0);
C_p.mat = (double*)&TC(i, 0, 0, 0);
LAPACKE_dgetrf_compute_batch(&A_p);
cblas_dtrsm_compute_batch(trsm_lower_params.side,
trsm_lower_params.uplo,
trsm_lower_params.transA,
trsm_lower_params.diag,
trsm_lower_params.alpha,
&A_p,
&B_p);
cblas_dtrsm_compute_batch(trsm_upper_params.side,
trsm_upper_params.uplo,
trsm_upper_params.transA,
trsm_upper_params.diag,
trsm_upper_params.alpha,
&A_p,
&C_p);
cblas_dgemm_compute_batch(gemm_params.transA,
gemm_params.transB,
gemm_params.alpha,
&A_p,
&B_p,
gemm_params.beta,
&C_p);
}
A_p.mat = (double*)&TA(iend, 0, 0, 0);
LAPACKE_dgetrf_compute_batch(&A_p);
t_factorize = timer.seconds();
}
// put back to original matrix for checking
for (int i=0;i<nrows;++i)
for (int j=0;j<ntridiags;++j)
for (int k=0;k<blocksize;++k)
for (int l=0;l<blocksize;++l) {
T_device.A()(j,i,k,l) = TA(i,j,k,l);
if (i<(nrows-1)) {
T_device.B()(j,i,k,l) = TB(i,j,k,l);
T_device.C()(j,i,k,l) = TC(i,j,k,l);
}
}
//if (input.check) TEST_ASSERT(factorblk.check(T_org_device), success);
}
}
///
/// block tridiag solve test
///
double t_solve = 0.0;
{
PartitionedBlockMultiVector<HostSpace,ValueType> b_host
= create_partitioned_block_multi_vector<HostSpace,ValueType>(ni*nj,
nrhs,
nk,
blocksize);
fill_partitioned_block_multi_vector_host(b_host, ni*nj);
auto b_device = create_mirror<DeviceSpace>(b_host);
deep_copy(b_device, b_host);
PartitionedBlockMultiVector<DeviceSpace,ValueType> x_device
= create_partitioned_block_multi_vector<HostSpace,ValueType>(ni*nj,
nrhs,
nk,
blocksize);
if (test_mkl) {
SolveBlockTridiagMatrices<DeviceSpace,
ValueType,
Algo::Trsv::CompactMKL,
Algo::Gemv::CompactMKL> solveblk;
{
Timer timer("50 SolveBlockTridiagMatrices");
timer.reset();
for (ordinal_type i=0;i<niter;++i) {
solveblk.run(T_device, x_device, b_device);
dontopt += i;
}
t_solve = timer.seconds();
}
if (input.check) TEST_ASSERT(solveblk.check(T_org_device, b_host), success);
} else {
SolveBlockTridiagMatrices<DeviceSpace,
ValueType,
Algo::Trsv::Blocked,
Algo::Gemv::Blocked> solveblk;
{
Timer timer("50 SolveBlockTridiagMatrices");
timer.reset();
for (ordinal_type i=0;i<niter;++i) {
solveblk.run(T_device, x_device, b_device);
dontopt += i;
}
t_solve = timer.seconds();
}
if (input.check) TEST_ASSERT(solveblk.check(T_org_device, b_host), success);
}
}
const double t_matvec_per_iter = t_matvec/double(niter), t_solve_per_iter = t_solve/double(niter);
// std::cout << "KokkosKernels:: time fill graph = " << t_fill_graph << std::endl;
// std::cout << "KokkosKernels:: time fill crs = " << t_fill_block_crs_matrix << std::endl;
// std::cout << "KokkosKernels:: time fill mv = " << t_fill_block_multi_vector << std::endl;
std::cout << " matvec = " << t_matvec_per_iter << std::endl;
std::cout << " extract = " << t_extract << " extract/matvec = " << (t_extract/t_matvec_per_iter) << std::endl;
std::cout << " factor = " << t_factorize << " factor/matvec = " << (t_factorize/t_matvec_per_iter) << std::endl;
//std::cout << " factor = " << t_factorize << " factor/matvec = " << (t_factorize/t_matvec_per_iter) << " flop = " << f_factorize << " flop/s = " << (f_factorize/t_factorize) << std::endl;
std::cout << " solve = " << t_solve_per_iter << " solve/matvec = " << (t_solve_per_iter/t_matvec_per_iter) << std::endl;
//std::cout << " memory used = " << (memsize_A + memsize_T) << std::endl;
return dontopt;
}
}
}
| 40.801252 | 205 | 0.524586 | [
"mesh",
"vector"
] |
b4f417e3dcdf27aae7342118a5d27e405406540c | 4,921 | cc | C++ | src/yb/master/yql_tables_vtable.cc | pritamdamania87/yugabyte-db | 70355f6c9248356e84cf21588013ea477fd04a5d | [
"Apache-2.0",
"CC0-1.0"
] | 1 | 2021-01-15T00:24:31.000Z | 2021-01-15T00:24:31.000Z | src/yb/master/yql_tables_vtable.cc | pritamdamania87/yugabyte-db | 70355f6c9248356e84cf21588013ea477fd04a5d | [
"Apache-2.0",
"CC0-1.0"
] | null | null | null | src/yb/master/yql_tables_vtable.cc | pritamdamania87/yugabyte-db | 70355f6c9248356e84cf21588013ea477fd04a5d | [
"Apache-2.0",
"CC0-1.0"
] | null | null | null | // Copyright (c) YugaByte, 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 "yb/common/redis_constants_common.h"
#include "yb/common/ql_value.h"
#include "yb/master/catalog_manager.h"
#include "yb/master/yql_tables_vtable.h"
namespace yb {
namespace master {
YQLTablesVTable::YQLTablesVTable(const Master* const master)
: YQLVirtualTable(master::kSystemSchemaTablesTableName, master, CreateSchema()) {
}
Status YQLTablesVTable::RetrieveData(const QLReadRequestPB& request,
std::unique_ptr<QLRowBlock>* vtable) const {
vtable->reset(new QLRowBlock(schema_));
std::vector<scoped_refptr<TableInfo> > tables;
master_->catalog_manager()->GetAllTables(&tables, true);
for (scoped_refptr<TableInfo> table : tables) {
// Hide redis table from YQL.
if (table->name() == common::kRedisTableName) {
continue;
}
// Get namespace for table.
NamespaceIdentifierPB nsId;
nsId.set_id(table->namespace_id());
scoped_refptr<NamespaceInfo> nsInfo;
RETURN_NOT_OK(master_->catalog_manager()->FindNamespace(nsId, &nsInfo));
// Create appropriate row for the table;
QLRow& row = (*vtable)->Extend();
RETURN_NOT_OK(SetColumnValue(kKeyspaceName, nsInfo->name(), &row));
RETURN_NOT_OK(SetColumnValue(kTableName, table->name(), &row));
// Create appropriate flags entry.
QLValuePB flags_set;
QLValue::set_set_value(&flags_set);
QLValuePB flags_elem;
QLValue::set_string_value("compound", &flags_elem);
*QLValue::add_set_elem(&flags_set) = flags_elem;
RETURN_NOT_OK(SetColumnValue(kFlags, flags_set, &row));
// Create appropriate table uuid entry.
Uuid uuid;
// Note: table id is in host byte order.
RETURN_NOT_OK(uuid.FromHexString(table->id()));
RETURN_NOT_OK(SetColumnValue(kId, uuid, &row));
// Set the values for the table properties.
Schema schema;
RETURN_NOT_OK(table->GetSchema(&schema));
// Adjusting precision, we use milliseconds internally, CQL uses seconds.
// Sanity check, larger TTL values should be caught during analysis.
DCHECK_LE(schema.table_properties().DefaultTimeToLive(),
MonoTime::kMillisecondsPerSecond * std::numeric_limits<int32>::max());
int32_t cql_ttl = static_cast<int32_t>(
schema.table_properties().DefaultTimeToLive() / MonoTime::kMillisecondsPerSecond);
RETURN_NOT_OK(SetColumnValue(kDefaultTimeToLive, cql_ttl, &row));
}
return Status::OK();
}
Schema YQLTablesVTable::CreateSchema() const {
SchemaBuilder builder;
CHECK_OK(builder.AddHashKeyColumn(kKeyspaceName, QLType::Create(DataType::STRING)));
CHECK_OK(builder.AddKeyColumn(kTableName, QLType::Create(DataType::STRING)));
CHECK_OK(builder.AddColumn(kBloomFilterChance, QLType::Create(DataType::DOUBLE)));
CHECK_OK(builder.AddColumn(kCaching, QLType::CreateTypeMap(DataType::STRING, DataType::STRING)));
CHECK_OK(builder.AddColumn(kCdc, QLType::Create(DataType::BOOL)));
CHECK_OK(builder.AddColumn(kComment, QLType::Create(DataType::STRING)));
CHECK_OK(builder.AddColumn(kCompaction,
QLType::CreateTypeMap(DataType::STRING, DataType::STRING)));
CHECK_OK(builder.AddColumn(kCompression,
QLType::CreateTypeMap(DataType::STRING, DataType::STRING)));
CHECK_OK(builder.AddColumn(kCrcCheck, QLType::Create(DataType::DOUBLE)));
CHECK_OK(builder.AddColumn(kLocalReadRepair, QLType::Create(DataType::DOUBLE)));
CHECK_OK(builder.AddColumn(kDefaultTimeToLive, QLType::Create(DataType::INT32)));
CHECK_OK(builder.AddColumn(kExtensions,
QLType::CreateTypeMap(DataType::STRING, DataType::BINARY)));
CHECK_OK(builder.AddColumn(kFlags, QLType::CreateTypeSet(DataType::STRING)));
CHECK_OK(builder.AddColumn(kGcGraceSeconds, QLType::Create(DataType::INT32)));
CHECK_OK(builder.AddColumn(kId, QLType::Create(DataType::UUID)));
CHECK_OK(builder.AddColumn(kMaxIndexInterval, QLType::Create(DataType::INT32)));
CHECK_OK(builder.AddColumn(kMemTableFlushPeriod, QLType::Create(DataType::INT32)));
CHECK_OK(builder.AddColumn(kMinIndexInterval, QLType::Create(DataType::INT32)));
CHECK_OK(builder.AddColumn(kReadRepairChance, QLType::Create(DataType::DOUBLE)));
CHECK_OK(builder.AddColumn(kSpeculativeRetry, QLType::Create(DataType::STRING)));
return builder.Build();
}
} // namespace master
} // namespace yb
| 45.564815 | 100 | 0.729933 | [
"vector"
] |
b4f761ffd1b8b5f6b447f7621232376eeda91e88 | 120,324 | cpp | C++ | mlir/lib/Dialect/Linalg/Transforms/ComprehensiveBufferize.cpp | zhongwuzw/llvm-project | 19e1b0b2057e7ae59adebed84a1e8015148683fc | [
"Apache-2.0"
] | null | null | null | mlir/lib/Dialect/Linalg/Transforms/ComprehensiveBufferize.cpp | zhongwuzw/llvm-project | 19e1b0b2057e7ae59adebed84a1e8015148683fc | [
"Apache-2.0"
] | null | null | null | mlir/lib/Dialect/Linalg/Transforms/ComprehensiveBufferize.cpp | zhongwuzw/llvm-project | 19e1b0b2057e7ae59adebed84a1e8015148683fc | [
"Apache-2.0"
] | null | null | null | //===- ComprehensiveBufferize.cpp - Single pass bufferization -------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Perform inplace bufferization within function boundaries.
// This is a specialized pass that supports inplace analysis for a fixed subset
// of ops that have well-defined inplace semantics.
// This pass caters to high-performance codegen where buffer reuse is deemed
// critical: the pass should fail if the bufferized form of the function needs
// to return any buffer.
// Generic control-flow and branching are unsupported.
// Composability with extensible set of ops is not a first-class concern.
//
// Bufferization occurs by:
// a. performing an inPlace analysis `inPlaceAnalysisFuncOpBody`
// which marks each operation within the function with the
// `kInPlaceResultsAttrName` attribute.
// b. traversing each operation in the function and rewriting it in
// buffer form and keeping a BlockAndValueMapping mapping of the
// rewrites. New allocations are introduced during this step.
// TODO: Allocation + depending op hoisting to outermost enclosing
// sequential scope.
// c. at the end of this bufferization, 3 cases may occur:
// i. inplaceable function arguments may be reused in place after the
// function itself has been bufferized. This is encoded by IR resembling:
//
// ```
// #map = affine_map<(d0)[s0, s1] -> (d0 * s1 + s0)>
// func @foo(%A: tensor<?xf32> {linalg.inplaceable = true})
// -> tensor<?xf32> {
// %0 = memref.buffer_cast %A : memref<?xf32, #map>
// // ... uses of %0
// %res = memref.tensor_load %0 : memref<?xf32, #map>
// return %res : tensor<?xf32>
// }
// ```
//
// this is the cue for the bufferization of the function foo (and calls
// to it) may bufferize to `func @foo(%A: memref<?xf32, some_layout>)`.
// To fully achieve bufferization, an additional analysis is needed to
// determine whether function argument/operand pairs bufferize to a
// single inplace buffer argument (i.e. functions may return tensors in
// arbitrary order that may not match argument numbers).
//
// ii. results that don't map to an inplaceable function argument are
// generally allocated. Since memref semantics wrt ownership of the
// underlying memory region are not well-defined, comprehensive
// bufferization chooses to perform allocations in a scoped fashion:
// returning memrefs is always considered illegal.
// Such scenarios are encoded by IR resembling:
//
// ```
// #map = affine_map<(d0)[s0, s1] -> (d0 * s1 + s0)>
// func @foo(%A: tensor<?xf32> {linalg.inplaceable = true})
// -> tensor<?xf32> {
// %0 = memref.buffer_cast %A : memref<?xf32, #map>
// %1 = memref.dim %0, %c0 : memref<?xf32, #map>
// %2 = memref.alloc(%1) : memref<?xf32>
// %3 = memref.cast %2 : memref<?xf32> to memref<?xf32, #map>
// // ... uses of %3
// memref.dealloc %2 : memref<?xf32, #map>
// %res = memref.tensor_load %3 : memref<?xf32, #map>
// return %res : tensor<?xf32>
// }
// ```
//
// this is the cue for the bufferization of the function foo (and calls
// to it) that it must bufferize to `func @foo(%A: memref<?xf32,
// some_layout>,
// %B: memref<?xf32, some_layout>)` (i.e. make a cloned
// allocation of the result tensor)
// To fully achieve bufferization, the alloc/dealloc pair must be lifted
// out of the function at each call site.
//
// iii. as an optimization over ii., it may be possible to reuse an argument
// and only want to return a slice.
// This may forego allocation by letting *all* callers decide whether to
// pass a new *aliasing* memref function argument (i.e. a subview).
// Without loss of generality, callers may agree to allocate a new buffer
// to avoid this aliasing. Such scenarios are encoded by IR resembling:
//
// ```
// #map = affine_map<(d0)[s0, s1] -> (d0 * s1 + s0)>
// func @foo(%arg0: tensor<?xf32> {linalg.inplaceable = true})
// -> tensor<4xf32> {
// %0 = memref.buffer_cast %arg0 : memref<?xf32, #map>
// %1 = memref.subview %0[0] [4] [1] : memref<?xf32, #map> to
// memref<4xf32, #map>
// // ... inplace computes into %1
// %3 = memref.tensor_load %1 : memref<4xf32, #map>
// return %3 : tensor<4xf32>
// }
// ```
//
// Note: In the future, it may be worthwhile to design special bufferization
// ops to encode the desired semantics at function boundaries for i., ii. and
// iii.
//
// Lastly, note that layout map chosen to bufferize is the most dynamic
// canonical strided layout of the proper rank. This ensures compatibility with
// expected layouts after transformations. Combinations of memref.cast +
// canonicalization are responsible for clean ups.
#include "PassDetail.h"
#include "mlir/Dialect/Linalg/IR/LinalgOps.h"
#include "mlir/Dialect/Linalg/Passes.h"
#include "mlir/Dialect/Linalg/Transforms/Transforms.h"
#include "mlir/Dialect/Linalg/Utils/Utils.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/SCF/SCF.h"
#include "mlir/Dialect/Utils/StaticValueUtils.h"
#include "mlir/Dialect/Vector/VectorOps.h"
#include "mlir/IR/Operation.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Pass/PassManager.h"
#include "mlir/Transforms/BufferUtils.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
#include "mlir/Transforms/Passes.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/EquivalenceClasses.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/ADT/SetOperations.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/TypeSwitch.h"
#define DEBUG_TYPE "comprehensive-func-bufferize"
using namespace mlir;
using namespace linalg;
using namespace tensor;
#define DBGS() (llvm::dbgs() << '[' << DEBUG_TYPE << "] ")
#define LDBG(X) LLVM_DEBUG(DBGS() << X)
//===----------------------------------------------------------------------===//
// Generic helpers.
//===----------------------------------------------------------------------===//
static bool isaTensor(Type t) { return t.isa<TensorType>(); }
/// Return the FuncOp called by `callOp`.
static FuncOp getCalledFunction(CallOpInterface callOp) {
SymbolRefAttr sym = callOp.getCallableForCallee().dyn_cast<SymbolRefAttr>();
if (!sym)
return nullptr;
return dyn_cast_or_null<FuncOp>(
SymbolTable::lookupNearestSymbolFrom(callOp, sym));
}
/// Return the unique ReturnOp that terminates `funcOp`.
/// Return nullptr if there is no such unique ReturnOp.
static ReturnOp getAssumedUniqueReturnOp(FuncOp funcOp) {
ReturnOp returnOp;
for (Block &b : funcOp.body()) {
if (auto candidateOp = dyn_cast<ReturnOp>(b.getTerminator())) {
if (returnOp)
return nullptr;
returnOp = candidateOp;
}
}
return returnOp;
}
//===----------------------------------------------------------------------===//
// Bufferization-specific BlockAndValueMapping support with debugging.
//===----------------------------------------------------------------------===//
/// Wrapper for better debugging.
static void map(BlockAndValueMapping &bvm, ValueRange keys, ValueRange values) {
assert(!keys.empty() && "Unexpected empty keys");
LDBG("Map: " << keys.front() << " to " << values.front() << '\n');
return bvm.map(keys, values);
}
/// Wrapper for better debugging.
static void map(BlockAndValueMapping &bvm, Value key, Value value) {
LDBG("Map: " << key << " to " << value << '\n');
return bvm.map(key, value);
}
/// Wrapper for better debugging.
static Value lookup(const BlockAndValueMapping &bvm, Value key) {
// TODO: if key comes from bbArg, forward.
assert(key.getType().isa<TensorType>());
Value v = bvm.lookupOrNull(key);
if (v)
return v;
Operation *parentOp;
if (auto bbArg = key.dyn_cast<BlockArgument>()) {
if (isa<FuncOp>(key.getParentBlock()->getParentOp()))
parentOp = key.getParentBlock()->getParentOp();
else
parentOp = key.getParentBlock()->getParentOp()->getParentOfType<FuncOp>();
} else {
parentOp = key.getDefiningOp()->getParentOfType<FuncOp>();
}
LDBG("In func:\n" << *parentOp << "NO VALUE FOR KEY: " << key << '\n');
(void)parentOp;
return Value();
}
//===----------------------------------------------------------------------===//
// Bufferization-specific attribute manipulation.
// These could be simplified with helper structs on the side, for now attributes
// allow simple embedding in the IR which simplifies testing.
// This could also be folded in BufferizationAliasInfo or a Bufferizer class
// that uses BufferizationAliasInfo.
//===----------------------------------------------------------------------===//
/// Attribute marker to specify op results that can be bufferized inPlace.
constexpr StringLiteral kInPlaceResultsAttrName = "__inplace_results_attr__";
// TODO: proper enum.
enum class InPlaceSpec {
False,
True,
None,
};
static StringRef stringify(InPlaceSpec val) {
switch (val) {
case InPlaceSpec::False:
return "false";
case InPlaceSpec::True:
return "true";
case InPlaceSpec::None:
return "none";
}
return "";
}
static Optional<InPlaceSpec> symbolize(StringRef str) {
return StringSwitch<Optional<InPlaceSpec>>(str)
.Case("false", InPlaceSpec::False)
.Case("true", InPlaceSpec::True)
.Case("none", InPlaceSpec::None)
.Default(None);
}
/// Mark whether OpResult can actually be bufferized inplace.
/// If `inPlace` is `InPlaceSpec::True`, the use-def chain analysis has
/// guaranteed that no subsequent write would occur to the bufferized
/// tensor value (i.e. the result can be bufferized inPlace).
static void setInPlaceOpResult(OpResult opResult,
InPlaceSpec inPlace = InPlaceSpec::True) {
if (!opResult)
return;
Operation *op = opResult.getOwner();
auto attr =
op->getAttr(kInPlaceResultsAttrName).dyn_cast_or_null<ArrayAttr>();
SmallVector<StringRef> inPlaceVector =
attr ? SmallVector<StringRef>(
llvm::to_vector<4>(attr.getAsValueRange<StringAttr>()))
: SmallVector<StringRef>(op->getNumResults(),
stringify(InPlaceSpec::None));
LDBG("->set inPlace=" << stringify(inPlace) << ": " << *op
<< " @idx=" << opResult.getResultNumber() << '\n');
inPlaceVector[opResult.getResultNumber()] = stringify(inPlace);
op->setAttr(kInPlaceResultsAttrName,
OpBuilder(op).getStrArrayAttr(inPlaceVector));
}
/// Get the InPlaceSpec attribute entry `kInPlaceResultsAttrName` for
/// `opResult`. If the result is `InPlaceSpec::True`, the use-def chain analysis
/// has guaranteed that no subsequent read of the tensor value occurs and the
/// result can be buferized inPlace.
/// If no InPlaceSpec attribute has been set for `opResult`, return
/// InPlaceSpec::None.
static InPlaceSpec getInPlace(OpResult opResult) {
if (!opResult)
return InPlaceSpec::None;
Operation *op = opResult.getOwner();
auto attr =
op->getAttr(kInPlaceResultsAttrName).dyn_cast_or_null<ArrayAttr>();
if (!attr)
return InPlaceSpec::None;
// Must return a proper value.
return *symbolize(*(attr.getAsValueRange<StringAttr>().begin() +
opResult.getResultNumber()));
}
/// Get inPlace information for `bbArg`.
/// FuncOp allow argument attributes, we use those to encode the information.
/// BlockArgument of other ops delegate to their owner's parent op.
static InPlaceSpec getInPlace(BlockArgument bbArg) {
if (auto funcOp = dyn_cast<FuncOp>(bbArg.getOwner()->getParentOp())) {
BoolAttr inplaceAttr = funcOp.getArgAttrOfType<BoolAttr>(
bbArg.getArgNumber(), LinalgDialect::kInplaceableAttrName);
if (!inplaceAttr)
return InPlaceSpec::None;
return inplaceAttr.getValue() ? InPlaceSpec::True : InPlaceSpec::False;
}
// Interestingly, scf::ForOp's and TiledLoop's bbArg can **always** be viewed
// inplace from the perspective of ops nested under:
// 1. Either the matching iter operand is not bufferized inplace and an
// alloc + optional copy makes the bbArg itself inplaceable.
// 2. Or the matching iter operand is bufferized inplace and bbArg just
// bufferizes to that too.
if (isa<scf::ForOp, TiledLoopOp>(bbArg.getOwner()->getParentOp()))
return InPlaceSpec::True;
// Unknown cases.
return InPlaceSpec::None;
}
/// Set the attribute that triggers inplace bufferization on a FuncOp argument
/// `bbArg`.
static void
setInPlaceFuncArgument(BlockArgument bbArg,
InPlaceSpec inPlaceSpec = InPlaceSpec::True) {
auto funcOp = cast<FuncOp>(bbArg.getOwner()->getParentOp());
funcOp.setArgAttr(
bbArg.getArgNumber(), LinalgDialect::kInplaceableAttrName,
BoolAttr::get(bbArg.getContext(), inPlaceSpec == InPlaceSpec::True));
}
/// Remove the attribute that triggers inplace bufferization on a FuncOp
/// argument `bbArg`.
static void removeBufferizationFuncArguments(BlockArgument bbArg) {
auto funcOp = cast<FuncOp>(bbArg.getOwner()->getParentOp());
funcOp.removeArgAttr(bbArg.getArgNumber(),
LinalgDialect::kBufferLayoutAttrName);
funcOp.removeArgAttr(bbArg.getArgNumber(),
LinalgDialect::kInplaceableAttrName);
}
LLVM_ATTRIBUTE_UNUSED static InPlaceSpec getInPlace(Value v) {
if (auto bbArg = v.dyn_cast<BlockArgument>())
return getInPlace(bbArg);
return getInPlace(v.cast<OpResult>());
}
//===----------------------------------------------------------------------===//
// Op-specific semantics helper to retrieve matching inplaceable result.
// These should become proper interfaces interfaces when the time is right.
// Modulo better naming, these helpers / interfaces comprise information on:
// 1. Whether an op has a known bufferization behavior (i.e. an instance of
// BufferizableOpInterface).
// 2. Whether an op, when bufferized inplace, can guarantee an
// (OpOperand, OpResult) pair bufferizes to equivalent (i.e. the same)
// buffers in memory.
// 3. Whether an op operand, when bufferized inplace, aliases a return value.
// 4. Whether an op return value, when bufferized inplace, aliases an operand.
// 5. Wheher an op bufferizes to a memory read.
// 6. Wheher an op bufferizes to a memory write.
// These interfaces are necessary to distinguish between various cases and allow
// special inplace behavior for (ExtractSliceOp, InsertSliceOp) pairs.
//===----------------------------------------------------------------------===//
/// Return `true` if the op is explicitly supported by bufferization or if it
/// has no result tensors.
/// Other cases must be conservative.
static bool hasKnownBufferizationAliasingBehavior(Operation *op) {
return
// clang-format off
isa<CallOpInterface,
tensor::CastOp,
ConstantOp,
tensor::DimOp,
ExtractSliceOp,
scf::ForOp,
InsertSliceOp,
InitTensorOp,
LinalgOp,
ReturnOp,
TiledLoopOp,
VectorTransferOpInterface,
linalg::YieldOp,
scf::YieldOp>(op)
// clang-format on
|| (none_of(op->getResultTypes(), isaTensor) &&
none_of(op->getOperandTypes(), isaTensor));
}
/// Return the OpResult that may bufferize into the same buffer as `opOperand`
/// when the op is bufferized inplace.
/// Return null if no such result exists.
static OpResult getInplaceableOpResult(TiledLoopOp op, OpOperand &opOperand) {
return op.getTiedOpResult(opOperand);
}
/// Return the OpResult that may bufferize into the same buffer as `opOperand`
/// when the op is bufferized inplace.
/// Return null if no such result exists.
static OpResult getInplaceableOpResult(scf::ForOp forOp, OpOperand &opOperand) {
if (!opOperand.get().getType().isa<RankedTensorType>())
return OpResult();
return forOp.getResultForOpOperand(opOperand);
}
/// Return the OpResult that may bufferize into the same buffer as `opOperand`
/// when the op is bufferized inplace.
/// Return null if no such result exists.
static OpResult getInplaceableOpResult(LinalgOp linalgOp,
OpOperand &opOperand) {
if (!opOperand.get().getType().isa<RankedTensorType>())
return OpResult();
// For now assume inputs are never inplaceable.
// TODO: refine this.
if (opOperand.getOperandNumber() < linalgOp.getNumInputs())
return OpResult();
int64_t outputOperandIndex =
opOperand.getOperandNumber() - linalgOp.getNumInputs();
int64_t numOutputBuffers = 0;
for (unsigned idx = 0; idx < outputOperandIndex; ++idx)
if (!linalgOp.getOutputOperand(idx)->get().getType().isa<TensorType>())
++numOutputBuffers;
return linalgOp->getResult(outputOperandIndex - numOutputBuffers);
}
/// Return the OpResult that may bufferize into the same buffer as `opOperand`
/// when the op is bufferized inplace.
/// Return null if no such result exists.
static OpResult getInplaceableOpResult(VectorTransferOpInterface op,
OpOperand &opOperand) {
if (opOperand.get() != op.source() ||
!op.source().getType().isa<TensorType>())
return OpResult();
return op->getResult(0);
}
/// Return the OpResult that may bufferize into the same buffer as `opOperand`
/// when the op is bufferized inplace.
/// Return null if no such result exists.
static OpResult getInplaceableOpResult(InsertSliceOp op, OpOperand &opOperand) {
if (opOperand.get() != op.dest())
return OpResult();
return op->getResult(0);
}
/// Return the OpResult that may bufferize into the same buffer as `opOperand`
/// when the op is bufferized inplace.
/// Return null if no such result exists.
static OpResult getInplaceableOpResult(tensor::CastOp op,
OpOperand &opOperand) {
return op->getResult(0);
}
/// Return the OpResult that may bufferize into the same buffer as `opOperand`
/// when the op is bufferized inplace.
/// The inplace analysis uses this information along with interfering read
/// analysis to determine which op results reuse the same buffer as some
/// operand.
static OpResult getInplaceableOpResult(OpOperand &opOperand) {
return TypeSwitch<Operation *, OpResult>(opOperand.getOwner())
// clang-format off
// Ops that perform destructive updates on operand(s) to produce
// result(s).
.Case<tensor::CastOp,
scf::ForOp,
InsertSliceOp,
LinalgOp,
TiledLoopOp,
VectorTransferOpInterface>(
[&](auto op) { return getInplaceableOpResult(op, opOperand); })
// ExtractSliceOp is special, when bufferized inplace it just returns an
// alias to its operand. Its result is never inplaceable on its operand.
.Case([&](ExtractSliceOp op) { return OpResult(); })
// CallOpInterface is special, it needs to wait for the callee to be
// bufferized and needs to inspect the BufferAliasInfo object. It can't
// make a proper determination by itself and needs to be conservative.
.Case([&](CallOpInterface op) { return OpResult(); })
// Other ops.
.Default([&](Operation *op) { return OpResult(); });
// clang-format on
}
/// Determine which OpOperand* will alias with `result` if the op is bufferized
/// in place.
/// Return None if the owner of `opOperand` does not have known
/// bufferization aliasing behavior, which indicates that the op must allocate
/// all of its tensor results.
/// TODO: in the future this may need to evolve towards a list of OpOperand*.
static Optional<OpOperand *> getAliasingOpOperand(OpResult result) {
if (!hasKnownBufferizationAliasingBehavior(result.getDefiningOp()))
return None;
return TypeSwitch<Operation *, OpOperand *>(result.getDefiningOp())
.Case([&](tensor::CastOp op) { return &op->getOpOperand(0); })
.Case([&](ConstantOp op) { return &op->getOpOperand(0); })
.Case([&](ExtractSliceOp op) { return &op->getOpOperand(0); })
// In the case of scf::ForOp, this currently assumes the iter_args / yield
// are 1-1. This may fail and is verified at the end.
// TODO: update this.
.Case([&](scf::ForOp op) {
return &op.getIterOpOperands()[result.getResultNumber()];
})
.Case([&](InsertSliceOp op) { return &op->getOpOperand(1); })
.Case([&](LinalgOp op) {
return op.getOutputTensorOperands()[result.getResultNumber()];
})
.Case([&](TiledLoopOp op) {
// TODO: TiledLoopOp helper method to avoid leaking impl details.
return &op->getOpOperand(op.getNumControlOperands() +
op.getNumInputs() + result.getResultNumber());
})
.Case([&](vector::TransferWriteOp op) { return &op->getOpOperand(1); })
.Default([&](Operation *op) {
op->dump();
llvm_unreachable("unexpected defining op");
return nullptr;
});
}
/// Determine which OpResult will alias with `opOperand` if the op is bufferized
/// in place. This is a superset of `getInplaceableOpResult`.
/// Return None if the owner of `opOperand` does not have known
/// bufferization aliasing behavior, which indicates that the op must allocate
/// all of its tensor results.
/// TODO: in the future this may need to evolve towards a list of OpResult.
static Optional<OpResult> getAliasingOpResult(OpOperand &opOperand) {
if (!hasKnownBufferizationAliasingBehavior(opOperand.getOwner()))
return None;
return TypeSwitch<Operation *, OpResult>(opOperand.getOwner())
// These terminators legitimately have no result.
.Case<ReturnOp, linalg::YieldOp, scf::YieldOp>(
[&](auto op) { return OpResult(); })
// DimOp has no tensor result.
.Case<tensor::DimOp>([&](auto op) { return None; })
// ConstantOp is never inplaceable.
.Case([&](ConstantOp op) { return op->getResult(0); })
// ExtractSliceOp is different: its result is not inplaceable on op.source
// but when bufferized inplace, the result is an aliasing subregion of
// op.source.
.Case([&](ExtractSliceOp op) { return op->getResult(0); })
// All other ops, including scf::ForOp, return the result of
// `getInplaceableOpResult`.
.Default(
[&](Operation *op) { return getInplaceableOpResult(opOperand); });
}
/// Return true if `opOperand` bufferizes to a memory read.
static bool bufferizesToMemoryRead(OpOperand &opOperand) {
Optional<OpResult> maybeOpResult = getAliasingOpResult(opOperand);
// Unknown op that returns a tensor. The inplace analysis does not support
// it. Conservatively return true.
if (!maybeOpResult)
return true;
// ExtractSliceOp alone doesn't bufferize to a memory read, one of its uses
// may.
if (isa<ExtractSliceOp>(opOperand.getOwner()))
return false;
// scf::ForOp alone doesn't bufferize to a memory read, one of the uses of its
// matching bbArg may.
if (auto forOp = dyn_cast<scf::ForOp>(opOperand.getOwner())) {
for (OpOperand &use :
forOp.getRegionIterArgForOpOperand(opOperand).getUses())
if (bufferizesToMemoryRead(use))
return true;
return false;
}
// TiledLoop alone doesn't bufferize to a memory read, one of the uses of its
// matching bbArg may.
if (auto tiledLoopOp = dyn_cast<TiledLoopOp>(opOperand.getOwner())) {
for (OpOperand &use : tiledLoopOp.getTiedBlockArgument(opOperand).getUses())
if (bufferizesToMemoryRead(use))
return true;
return false;
}
// CallOpInterface alone doesn't bufferize to a memory read, one of the uses
// of the matching bbArg may. It is the responsibility of the caller to
// inspect bbArgs. In the absence of a BufferizationAliasInfo, we need to be
// conservative.
if (auto callOp = dyn_cast<CallOpInterface>(opOperand.getOwner()))
return true;
if (auto linalgOp = dyn_cast<LinalgOp>(opOperand.getOwner()))
return linalgOp.isInputTensor(&opOperand) ||
linalgOp.isInitTensor(&opOperand);
// All other cases are considered to bufferize to memory reads.
// In particular, terminators are often the last use and need to be considered
// as reads to return the proper value and avoid WAW clobbers.
return true;
}
/// Return true if `opOperand` bufferizes to a memory write.
/// If inPlaceSpec is different from InPlaceSpec::None, additionally require the
/// write to match the inplace specification.
static bool
bufferizesToMemoryWrite(OpOperand &opOperand,
InPlaceSpec inPlaceSpec = InPlaceSpec::None) {
// These terminators are not writes.
if (isa<ReturnOp, linalg::YieldOp, scf::YieldOp>(opOperand.getOwner()))
return false;
// ExtractSliceOp alone doesn't bufferize to a memory write, one of its uses
// may.
if (isa<ExtractSliceOp>(opOperand.getOwner()))
return false;
// CallOpInterface alone doesn't bufferize to a memory write, one of the uses
// of the matching bbArg may. It is the responsibility of the caller to
// inspect bbArgs. In the absence of a BufferizationAliasInfo, we need to be
// conservative.
if (auto callOp = dyn_cast<CallOpInterface>(opOperand.getOwner()))
return true;
Optional<OpResult> maybeOpResult = getAliasingOpResult(opOperand);
// Unknown op that returns a tensor. The inplace analysis does not support
// it. Conservatively return true.
if (!maybeOpResult)
return true;
// Supported op without a matching result for opOperand (e.g. ReturnOp).
// This does not bufferize to a write.
if (!*maybeOpResult)
return false;
// If we have a matching OpResult, this is a write.
// Additionally allow to restrict to only inPlace write, if so specified.
return inPlaceSpec == InPlaceSpec::None ||
getInPlace(*maybeOpResult) == inPlaceSpec;
}
//===----------------------------------------------------------------------===//
// Bufferization-specific alias analysis.
//===----------------------------------------------------------------------===//
namespace {
/// The BufferizationAliasInfo class maintains a list of buffer aliases and
/// equivalence classes to support bufferization.
/// ExtractSliceOps have special behavior, they act as a level of indirection
/// for bufferization. They don't create reads or writes themselves and analysis
/// needs to look through their uses.
/// ExtractSliceOp + InsertSliceOp have special joint behavior: they may
/// bufferize to the same buffer (i.e. subview), which is what introduces the
/// need for bufferization classes.
/// Some of these functionalities could be refactored in a Bufferizer class that
/// uses BufferizationAliasInfo.
class BufferizationAliasInfo {
public:
/// Specify fine-grain relationship between buffers to enable more analysis.
enum class BufferRelation {
None,
// TODO: ResultContainsOperand,
// TODO: OperandContainsResult,
Equivalent
};
explicit BufferizationAliasInfo(Operation *rootOp);
/// Add a new entry for `v` in the `aliasInfo` and `equivalentInfo`. In the
/// beginning the alias and equivalence sets only contain `v` itself.
void createAliasInfoEntry(Value v);
/// Insert an info entry for `newValue` and merge its alias set with that of
/// `alias`.
void insertNewBufferAlias(Value newValue, Value alias);
/// Insert an info entry for `newValue` and merge its alias set with that of
/// `alias`. Additionally, merge their equivalence classes.
void insertNewBufferEquivalence(Value newValue, Value alias);
/// Return true if the buffer to which `operand` would bufferize aliases a
/// buffer that is known to not be writeable. This implies that the matching
/// OpResult cannot be bufferized inplace.
bool aliasesNonWriteableBuffer(OpOperand &operand) const;
/// Return true if the buffer to which `operand` would bufferize is equivalent
/// to some buffer write.
bool aliasesInPlaceWrite(Value v) const;
/// Set the inPlace bufferization spec to true.
/// Merge result's and operand's aliasing sets and iterate to a fixed point.
void bufferizeInPlace(OpResult result, OpOperand &operand,
BufferRelation bufferRelation = BufferRelation::None);
/// Set the inPlace bufferization spec to false.
void bufferizeOutOfPlace(OpResult result);
/// Return true if it is possible to find an inplace write W among the uses of
/// aliasInfo[result], and a read R among the uses of aliasInfo[result],
/// such that W and R interfere.
/// Such a (W, R) pair is an interference to the inplace bufferization of
/// rootWrite when:
/// 1. R is not known properly dominate W (i.e. the effects of the write may
/// be visible from R).
/// 2. one cannot find an intermediate clobbering write `C` to W, such that
/// C interleaved between W and R (i.e. W -> C -> R where -> denotes
/// dominance).
bool
wouldCreateReadAfterWriteInterference(OpResult result,
const DominanceInfo &domInfo) const;
/// Return true if `v1` and `v2` bufferize to equivalent buffers.
bool areEquivalentBufferizedValues(Value v1, Value v2) const {
return equivalentInfo.getLeaderValue(v1) ==
equivalentInfo.getLeaderValue(v2);
}
/// Return true if the source of an `insertSliceOp` bufferizes to an
/// equivalent ExtractSliceOp.
bool isSourceEquivalentToAMatchingInplaceExtractSliceOp(
InsertSliceOp insertSliceOp) const;
/// Apply `fun` to all the members of the equivalence class of `v`.
void applyOnEquivalenceClass(Value v, function_ref<void(Value)> fun) const;
/// Print to `os`.
void print(raw_ostream &os) const;
/// Print to `errs()`.
void dump() const { print(llvm::errs()); }
private:
/// Check that aliasInfo for `v` exists and return a reference to it.
DenseSet<Value> &getAliasInfoRef(Value v);
const DenseSet<Value> &getAliasInfoRef(Value v) const {
return const_cast<BufferizationAliasInfo *>(this)->getAliasInfoRef(v);
}
/// Union all the aliasing sets of all aliases of v1 and v2.
bool mergeAliases(Value v1, Value v2);
/// Iteratively merge alias sets until a fixed-point.
void mergeAliasesToFixedPoint();
/// Return true if the (ExtractSliceOp, InsertSliceOp) pair match (i.e.
/// equivalent operand / result and same offset/sizes/strides specification).
///
/// This is one particular type of relationship between ops on tensors that
/// reduce to an equivalence on buffers. This should be generalized and
/// exposed as interfaces on the proper types.
bool areEquivalentExtractSliceOps(ExtractSliceOp st, InsertSliceOp sti) const;
/// Return true if there is a `candidateOp` that would write to memory after
/// bufferization and such that:
/// 1. The written buffer is equivalent to either `aliasingRead` or
/// `aliasingWrite` under the inPlace bufferization decisions taken
/// so far.
/// 2. `aliasingWrite` properly dominates `candidateOp`.
/// 3. `candidateOp` properly dominates `aliasingReadOp`.
// TODO: richer clobbering analysis with container-containee relationship
// instead of equivalence.
bool existsInterleavedValueClobber(OpOperand &aliasingRead,
OpOperand &aliasingWrite,
const DominanceInfo &domInfo) const;
/// Return true if there is a write that:
/// 1. Properly dominates aliasingReadOp.
/// 2. Is properly dominated by aliasingWriteOp.
/// 3. Clobbers the write that would be interfering with the read.
///
/// Case discussion:
/// ================
/// Case 1: rootRead is produced by opToBufferize,
/// Case 2: rootWrite is produced by opToBufferize,
/// Common case:
/// - aliasingReadOp is a read to an alias of rootRead.
/// - aliasingWriteOp is an inplace write to an alias of rootWrite.
/// - aliasingWriteOp dominates aliasingReadOp.
///
/// ```
/// // Either case 1:
/// %rootRead = opToBufferize(%rootWrite)
/// aliasingWriteOp(%aliasingWrite = alias(%rootWrite)) // inplace
/// aliasingReadOp( %aliasingRead = alias(%rootRead))
/// ```
///
/// ```
/// // Or case 2:
/// %rootWrite = opToBufferize(%rootRead)
/// aliasingWriteOp(%aliasingWrite = alias(%rootWrite)) // inplace
/// aliasingReadOp( %aliasingRead = alias(%rootRead))
/// ```
///
/// Capture possible cases where `aliasingWriteOp(alias(%rootWrite))` has no
/// visible effect on `aliasingReadOp(alias(%rootRead))`.
bool isClobberedWriteBeforeRead(Operation *opToBufferize,
OpOperand &aliasingRead,
OpOperand &aliasingWrite,
const DominanceInfo &domInfo) const;
/// EquivalenceClasses wants comparable elements because it uses std::set.
/// ValueWrapper wraps Value and uses pointer comparison on the defining op.
/// This is a poor man's comparison but it's not like UnionFind needs ordering
/// anyway ..
struct ValueWrapper {
ValueWrapper(Value val) : v(val) {}
operator Value() const { return v; }
bool operator<(const ValueWrapper &wrap) const {
return v.getImpl() < wrap.v.getImpl();
}
bool operator==(const ValueWrapper &wrap) const { return v == wrap.v; }
Value v;
};
/// Auxiliary structure to store all the values a given value aliases with.
/// These are the conservative cases that can further decompose into
/// "equivalent" buffer relationships.
DenseMap<Value, DenseSet<Value>> aliasInfo;
/// Auxiliary structure to store all the equivalent buffer classes.
llvm::EquivalenceClasses<ValueWrapper> equivalentInfo;
};
} // namespace
BufferizationAliasInfo::BufferizationAliasInfo(Operation *rootOp) {
rootOp->walk([&](Operation *op) {
for (Value v : op->getResults())
if (v.getType().isa<TensorType>())
createAliasInfoEntry(v);
for (Region &r : op->getRegions())
for (Block &b : r.getBlocks())
for (auto bbArg : b.getArguments())
if (bbArg.getType().isa<TensorType>())
createAliasInfoEntry(bbArg);
});
}
/// Add a new entry for `v` in the `aliasInfo` and `equivalentInfo`. In the
/// beginning the alias and equivalence sets only contain `v` itself.
void BufferizationAliasInfo::createAliasInfoEntry(Value v) {
DenseSet<Value> selfSet;
selfSet.insert(v);
aliasInfo.try_emplace(v, selfSet);
equivalentInfo.insert(v);
}
/// Insert an info entry for `newValue` and merge its alias set with that of
/// `alias`.
void BufferizationAliasInfo::insertNewBufferAlias(Value newValue, Value alias) {
assert(aliasInfo.find(alias) != aliasInfo.end() && "Missing alias entry");
createAliasInfoEntry(newValue);
mergeAliases(newValue, alias);
mergeAliasesToFixedPoint();
}
/// Insert an info entry for `newValue` and merge its alias set with that of
/// `alias`. Additionally, merge their equivalence classes.
void BufferizationAliasInfo::insertNewBufferEquivalence(Value newValue,
Value alias) {
insertNewBufferAlias(newValue, alias);
equivalentInfo.unionSets(newValue, alias);
}
/// Return true if the buffer to which `operand` would bufferize aliases a
/// buffer that is known to not be writeable. This implies that the matching
/// OpResult cannot be bufferized inplace.
bool BufferizationAliasInfo::aliasesNonWriteableBuffer(
OpOperand &operand) const {
LDBG("----Start aliasesNonWriteableBuffer\n");
LDBG("-------for operand #" << operand.getOperandNumber() << ": "
<< *(operand.getOwner()) << '\n');
for (Value v : getAliasInfoRef(operand.get())) {
LDBG("-----------examine: " << v << '\n');
if (auto bbArg = v.dyn_cast<BlockArgument>()) {
if (getInPlace(bbArg) == InPlaceSpec::True) {
LDBG("-----------bbArg is writeable -> skip: " << bbArg << '\n');
continue;
}
LDBG("-----------notWriteable\n");
return true;
}
if (Operation *op = v.getDefiningOp()) {
if (isa<ConstantOp>(op) || !hasKnownBufferizationAliasingBehavior(op)) {
LDBG("-----------notWriteable\n");
return true;
}
}
}
LDBG("---->operand is writeable\n");
return false;
}
/// Return true if the buffer to which `operand` would bufferize is equivalent
/// to some buffer write.
bool BufferizationAliasInfo::aliasesInPlaceWrite(Value value) const {
LDBG("----Start aliasesInPlaceWrite\n");
LDBG("-------for : " << value << '\n');
for (Value v : getAliasInfoRef(value)) {
for (auto &use : v.getUses()) {
if (bufferizesToMemoryWrite(use, InPlaceSpec::True)) {
LDBG("-----------wants to bufferize to inPlace write: "
<< *use.getOwner() << '\n');
return true;
}
}
}
LDBG("----------->does not alias an inplace write\n");
return false;
}
/// Set the inPlace bufferization spec to true.
/// Merge result's and operand's aliasing sets and iterates to a fixed point.
void BufferizationAliasInfo::bufferizeInPlace(OpResult result,
OpOperand &operand,
BufferRelation bufferRelation) {
setInPlaceOpResult(result, InPlaceSpec::True);
if (mergeAliases(result, operand.get()))
mergeAliasesToFixedPoint();
if (bufferRelation == BufferRelation::Equivalent)
equivalentInfo.unionSets(result, operand.get());
// Dump the updated analysis.
LLVM_DEBUG(dump());
}
/// Set the inPlace bufferization spec to false.
void BufferizationAliasInfo::bufferizeOutOfPlace(OpResult result) {
setInPlaceOpResult(result, InPlaceSpec::False);
}
/// Return true if it is possible to find an inplace write W among the uses of
/// aliasInfo[result], and a read R among the uses of aliasInfo[result],
/// such that W and R interfere.
/// Such a (W, R) pair is an interference to the inplace bufferization of
/// rootWrite when:
/// 1. R is not known properly dominate W (i.e. the effects of the write may
/// be visible from R).
/// 2. one cannot find an intermediate clobbering write `C` to W, such that
/// C interleaved between W and R (i.e. W -> C -> R where -> denotes
/// dominance).
bool BufferizationAliasInfo::wouldCreateReadAfterWriteInterference(
OpResult result, const DominanceInfo &domInfo) const {
Optional<OpOperand *> maybeAliasingOperand = getAliasingOpOperand(result);
if (!maybeAliasingOperand)
return false;
Operation *opToBufferize = result.getDefiningOp();
Value root = (*maybeAliasingOperand)->get();
LDBG("----Start wouldCreateReadAfterWriteInterference\n");
LDBG("--------rootValue: " << root << "\n");
// Collect:
// 1. all the inplace write uses of some alias of `root`.
// 2. all the write uses that belong to `opToBufferize`.
// opToBufferize is not yet inplace, we want to determine if it can be inplace
// so we also consider all its write uses, not just the inplace ones.
DenseSet<OpOperand *> usesWrite;
for (Value vWrite : getAliasInfoRef(root)) {
for (auto &uWrite : vWrite.getUses()) {
if (!bufferizesToMemoryWrite(uWrite))
continue;
if (uWrite.getOwner() == opToBufferize ||
bufferizesToMemoryWrite(uWrite, InPlaceSpec::True))
usesWrite.insert(&uWrite);
}
}
for (Value vWrite : getAliasInfoRef(result))
for (auto &uWrite : vWrite.getUses())
if (bufferizesToMemoryWrite(uWrite, InPlaceSpec::True))
usesWrite.insert(&uWrite);
// Collect all the reads of some alias of `root`.
// opToBufferize is not yet inplace, we want to determine if it can be inplace
// so we also consider all read uses of its result.
DenseSet<OpOperand *> usesRead;
auto &aliasListRead = getAliasInfoRef(root);
for (Value vRead : aliasListRead)
for (auto &uRead : vRead.getUses())
if (bufferizesToMemoryRead(uRead))
usesRead.insert(&uRead);
for (Value vRead : getAliasInfoRef(result))
for (auto &uRead : vRead.getUses())
if (bufferizesToMemoryRead(uRead))
usesRead.insert(&uRead);
for (OpOperand *uRead : usesRead) {
Operation *aliasingReadOp = uRead->getOwner();
LDBG("----++++aliasRead #" << uRead->getOperandNumber()
<< " in: " << *aliasingReadOp << '\n');
for (OpOperand *uWrite : usesWrite) {
// Don't consider self-use of the same operand for interference.
// Multiple different uses within the same op is fair game though.
if (uWrite == uRead)
continue;
Operation *aliasingWriteOp = uWrite->getOwner();
LDBG("---- aliasWrite #" << uWrite->getOperandNumber()
<< " in: " << *aliasingWriteOp << '\n');
// If the candidate write is the one that produces the read value (in the
// SSA def-use sense), this is not considered an interference.
if (getInplaceableOpResult(*uWrite) == uRead->get())
continue;
// If aliasingReadOp properly dominates aliasingWriteOp, the read cannot
// be affected by the write: there is no interference.
if (domInfo.properlyDominates(aliasingReadOp, aliasingWriteOp))
continue;
// At this point, aliasingWriteOp properly dominates aliasingReadOp or
// there is no clear dominance and we need to be conservative.
LDBG("---->found RaW interference\n");
LDBG(" Interfering read (op #" << uRead->getOperandNumber()
<< "): " << *aliasingReadOp << '\n');
LDBG(" Interfering write (op #" << uWrite->getOperandNumber()
<< "): " << *aliasingWriteOp << '\n');
LDBG("---->opportunity to clobber RaW interference\n");
if (isClobberedWriteBeforeRead(opToBufferize, *uRead, *uWrite, domInfo)) {
LDBG("---->clobbered! -> skip\n");
continue;
}
LDBG("---->not clobbered -> found an interference\n");
return true;
}
}
LDBG("----No interference found\n");
return false;
}
/// Return true if the source of a `insertSliceOp` bufferizes to an
/// equivalent ExtractSliceOp that bufferizes inplace.
bool BufferizationAliasInfo::isSourceEquivalentToAMatchingInplaceExtractSliceOp(
InsertSliceOp insertSliceOp) const {
LDBG("isSourceEquivalentToAMatchingInplaceExtractSliceOp: " << *insertSliceOp
<< '\n');
auto leaderIt = equivalentInfo.findLeader(insertSliceOp.source());
for (auto mit = leaderIt, meit = equivalentInfo.member_end(); mit != meit;
++mit) {
auto extractSliceOp =
dyn_cast_or_null<ExtractSliceOp>(mit->v.getDefiningOp());
if (extractSliceOp &&
areEquivalentExtractSliceOps(extractSliceOp, insertSliceOp) &&
getInPlace(extractSliceOp.result()) == InPlaceSpec::True) {
LDBG("\tfound: " << *mit->v.getDefiningOp() << '\n');
return true;
}
}
LDBG("\tnot equivalent\n");
return false;
}
/// Apply `fun` to all the members of the equivalence class of `v`.
void BufferizationAliasInfo::applyOnEquivalenceClass(
Value v, function_ref<void(Value)> fun) const {
auto leaderIt = equivalentInfo.findLeader(v);
for (auto mit = leaderIt, meit = equivalentInfo.member_end(); mit != meit;
++mit) {
fun(mit->v);
}
}
void BufferizationAliasInfo::print(raw_ostream &os) const {
os << "\n/========================== AliasInfo "
"==========================\n";
for (auto it : aliasInfo) {
os << "|\n| -- source: " << it.getFirst() << '\n';
for (auto v : it.getSecond())
os << "| ---- target: " << v << '\n';
}
os << "|\n\\====================== End AliasInfo "
"======================\n\n";
os << "\n/********************* Equivalent Buffers *********************\n";
for (auto it = equivalentInfo.begin(), eit = equivalentInfo.end(); it != eit;
++it) {
if (!it->isLeader())
continue;
Value leader = it->getData();
os << "|\n| -- leader: " << leader << '\n';
for (auto mit = equivalentInfo.member_begin(it),
meit = equivalentInfo.member_end();
mit != meit; ++mit) {
Value v = static_cast<Value>(*mit);
os << "| ---- equivalent member: " << v << '\n';
}
}
os << "|\n\\***************** End Equivalent Buffers *****************\n\n";
}
DenseSet<Value> &BufferizationAliasInfo::getAliasInfoRef(Value v) {
auto it = aliasInfo.find(v);
if (it == aliasInfo.end())
llvm_unreachable("Missing alias");
return it->getSecond();
}
/// Union all the aliasing sets of all aliases of v1 and v2.
bool BufferizationAliasInfo::mergeAliases(Value v1, Value v2) {
// Avoid invalidation of iterators by pre unioning the aliases for v1 and v2.
bool changed = set_union(getAliasInfoRef(v1), getAliasInfoRef(v2)) ||
set_union(getAliasInfoRef(v2), getAliasInfoRef(v1));
for (auto v : getAliasInfoRef(v1))
if (v != v1)
changed |= set_union(getAliasInfoRef(v), getAliasInfoRef(v2));
for (auto v : getAliasInfoRef(v2))
if (v != v2)
changed |= set_union(getAliasInfoRef(v), getAliasInfoRef(v1));
return changed;
}
/// Iteratively merge alias sets until a fixed-point.
void BufferizationAliasInfo::mergeAliasesToFixedPoint() {
while (true) {
bool changed = false;
for (auto it : aliasInfo)
for (auto v : it.getSecond())
changed |= mergeAliases(it.getFirst(), v);
if (!changed)
break;
}
}
/// This is one particular type of relationship between ops on tensors that
/// reduce to an equivalence on buffers. This should be generalized and exposed
/// as interfaces on the proper types.
bool BufferizationAliasInfo::areEquivalentExtractSliceOps(
ExtractSliceOp st, InsertSliceOp sti) const {
if (!st || !sti)
return false;
if (!equivalentInfo.isEquivalent(st.source(), sti.dest()))
return false;
if (!sameOffsetsSizesAndStrides(st, sti, isEqualConstantIntOrValue))
return false;
if (!equivalentInfo.isEquivalent(st.result(), sti.source()))
return false;
return true;
}
/// Return true if there is a `candidateOp` that would write to memory after
/// bufferization and such that:
/// 1. The written buffer is equivalent to either `aliasingRead` or
/// `aliasingWrite` under the inPlace bufferization decisions taken
/// so far.
/// 2. `aliasingWrite` properly dominates `candidateOp`.
/// 3. `candidateOp` properly dominates `aliasingReadOp`.
// TODO: richer clobbering analysis with container-containee relationship
// instead of equivalence.
bool BufferizationAliasInfo::existsInterleavedValueClobber(
OpOperand &aliasingRead, OpOperand &aliasingWrite,
const DominanceInfo &domInfo) const {
Operation *aliasingReadOp = aliasingRead.getOwner();
Operation *aliasingWriteOp = aliasingWrite.getOwner();
assert(!domInfo.properlyDominates(aliasingReadOp, aliasingWriteOp) &&
"Unexpected aliasingReadOp properly dominates aliasingWriteOp");
for (Value valueToClobber : {aliasingRead.get(), aliasingWrite.get()}) {
auto leaderIt = equivalentInfo.findLeader(valueToClobber);
for (auto mit = leaderIt, meit = equivalentInfo.member_end(); mit != meit;
++mit) {
/// Note: the "would write to memory after bufferization" condition is
/// verified by `candidateOp` since it would produce a value that
/// bufferizes to an equivalent buffer.
Operation *candidateOp = mit->v.getDefiningOp();
if (!candidateOp)
continue;
LDBG("---->clobbering candidate: " << *candidateOp << '\n');
if (domInfo.properlyDominates(aliasingWriteOp, candidateOp) &&
domInfo.properlyDominates(candidateOp, aliasingReadOp))
return true;
}
}
return false;
}
/// Return true if there is a write that:
/// 1. Properly dominates aliasingReadOp.
/// 2. Is properly dominated by aliasingWriteOp.
/// 3. Clobbers the write that would be interfering with the read.
///
bool BufferizationAliasInfo::isClobberedWriteBeforeRead(
Operation *opToBufferize, OpOperand &aliasingRead, OpOperand &aliasingWrite,
const DominanceInfo &domInfo) const {
Operation *aliasingReadOp = aliasingRead.getOwner();
Operation *aliasingWriteOp = aliasingWrite.getOwner();
assert(!domInfo.properlyDominates(aliasingReadOp, aliasingWriteOp) &&
"Unexpected aliasingReadOp properly dominates aliasingWriteOp");
// Bail if the write does not dominate the read: it may clobber but only on
// a strict subset of paths, which is not enough for safety.
if (!domInfo.dominates(aliasingWriteOp, aliasingReadOp)) {
LDBG("---->no clobbering: write does not dominate read\n");
return false;
}
// The case `opToBufferize` isa ExtractSliceOp is important enough that we
// look for it specifically. The key information to discover is whether the
// aliasing read or write come from a matching InsertSliceOp.
// Such a pattern is introduced by tiling and is the key inplace condition
// not to miss.
if (auto extractSliceOp = dyn_cast<ExtractSliceOp>(opToBufferize)) {
if (auto insertSliceOp = dyn_cast<InsertSliceOp>(aliasingReadOp)) {
// %1 = extract_slice %0[%offset_sizes_and_strides_1]
//
// ... // 0 or more of inplace compute that reduces to: %X is an
// // aliasingWrite equivalent to %1.
// %W = inplace_write(%1)
//
// // aliasingRead %Y in insert_slice
// ... = insert_slice %W into %R[%offset_sizes_and_strides_1]
if (aliasingRead.get() == insertSliceOp.dest() &&
// TODO: This is currently too restrictive and misses clobberings.
// When available, use container-containee analysis: the condition
// should be that the `aliasingWrite` is contained within
// `insertSliceOp.source()`.
equivalentInfo.isEquivalent(aliasingWrite.get(),
insertSliceOp.source()) &&
areEquivalentExtractSliceOps(extractSliceOp, insertSliceOp)) {
LDBG("---->clobbering matching extract_slice/insert_slice\n");
return true;
}
// %1 = extract_slice %0[%offset_sizes_and_strides_1]
//
// ... // bunch of inplace ops that reduce to %X, equivalent to %1.
// %X = inplace_write(%1)
//
// // aliasingRead %X in insert_slice
// // aliasingWrite %Y in insert_slice
// ... = insert_slice %X into %Y[%offset_sizes_and_strides_1]
if (aliasingReadOp == aliasingWriteOp) {
assert(aliasingRead.get() == insertSliceOp.source() &&
"expected read to source of insert_slice");
assert(aliasingWrite.get() == insertSliceOp.dest() &&
"expected write to dest of insert_slice");
if (areEquivalentExtractSliceOps(extractSliceOp, insertSliceOp)) {
LDBG("---->clobbering matching extract_slice/insert_slice\n");
return true;
}
}
}
}
// General case: look for a properly interleaved clobber of either exactly
// `aliasingRead` or `aliasingWrite`.
// TODO: Relax this to inclusion instead of double inclusion (a.k.a
// equivalence). We will need to compute container-containee relationship.
return existsInterleavedValueClobber(aliasingRead, aliasingWrite, domInfo);
}
//===----------------------------------------------------------------------===//
// Forward declarations.
//===----------------------------------------------------------------------===//
/// Return the op with Allocate MemoryEffect if `v` is equivalent to an such
/// an op. Return null otherwise.
static Operation *getEquivalentAlloc(Value value,
const BufferizationAliasInfo &aliasInfo);
/// Return the first argument of the enclosing FuncOp that is equivalent to `v`.
/// Return null if no such bbArg can be found.
static BlockArgument
getEquivalentEnclosingFuncBBArg(Value v,
const BufferizationAliasInfo &aliasInfo);
//===----------------------------------------------------------------------===//
// Bufferization-specific MemRefType support.
//===----------------------------------------------------------------------===//
/// Return a contiguous MemRefType (i.e. with canonical/empty layout map)
/// with the same shape as `shapedType` and specified `layout` and
/// `addressSpace`.
static MemRefType getContiguousMemRefType(ShapedType shapedType,
ArrayRef<AffineMap> layout = {},
unsigned addressSpace = 0) {
if (RankedTensorType tensorType = shapedType.dyn_cast<RankedTensorType>())
return MemRefType::get(tensorType.getShape(), tensorType.getElementType(),
layout, addressSpace);
MemRefType memrefType = shapedType.cast<MemRefType>();
return MemRefType::get(memrefType.getShape(), memrefType.getElementType(),
layout, addressSpace);
}
/// Return a contiguous MemRefType (i.e. with canonical/empty layout map)
/// with the same shape as `shapedType` and specified `layout` and
/// `addressSpace` or an UnrankedMemRefType otherwise.
static Type getContiguousOrUnrankedMemRefType(Type type,
ArrayRef<AffineMap> layout = {},
unsigned addressSpace = 0) {
if (type.isa<RankedTensorType, MemRefType>())
return getContiguousMemRefType(type.cast<ShapedType>(), layout,
addressSpace);
assert(layout.empty() && "expected empty layout with UnrankedMemRefType");
return UnrankedMemRefType::get(getElementTypeOrSelf(type), addressSpace);
}
/// Return a MemRefType to which the `tensorType` can be bufferized in a
/// composable fashion. The layout must be the most dynamic possible and
/// canonicalize away once bufferization is finished.
static MemRefType getDynamicMemRefType(RankedTensorType tensorType,
unsigned addressSpace = 0) {
// TODO: address space decisions to connect with the actual alloc.
int64_t dynamicOffset = ShapedType::kDynamicStrideOrOffset;
SmallVector<int64_t> dynamicStrides(tensorType.getRank(),
ShapedType::kDynamicStrideOrOffset);
AffineMap stridedLayout = makeStridedLinearLayoutMap(
dynamicStrides, dynamicOffset, tensorType.getContext());
return MemRefType::get(tensorType.getShape(), tensorType.getElementType(),
stridedLayout, addressSpace);
}
/// Return the FunctionType with `argumentTypes` and `resultTypes` where each
/// tensor is replaced by the corresponding buffer type.
/// In order for all the callers to agree, this *must* bufferize to the most
/// dynamic buffer type supported.
/// A later pass across all CallOps in the module can decide whether to simplify
/// the types of to version according to some cost model.
static FunctionType getBufferizedFunctionType(MLIRContext *ctx,
TypeRange argumentTypes,
TypeRange resultTypes) {
auto rewrite = [](Type t) -> Type {
// TODO: non-zero address space.
// TODO: layout information if relevant.
if (auto rankedTensorType = t.dyn_cast<RankedTensorType>())
return getDynamicMemRefType(rankedTensorType);
if (auto tensorType = t.dyn_cast<TensorType>())
return getContiguousOrUnrankedMemRefType(tensorType);
return t;
};
auto argTypes = llvm::to_vector<4>(llvm::map_range(argumentTypes, rewrite));
auto retTypes = llvm::to_vector<4>(llvm::map_range(resultTypes, rewrite));
return FunctionType::get(ctx, argTypes, retTypes);
}
/// If an entry for `funcOp` is available in `bufferizedFunctionTypes`, return
/// it. Otherwise, construct a new entry based on `argumentTypes` and
/// `resultTypes`.
// TODO: improve the layering.
static FunctionType getOrCreateBufferizedFunctionType(
FuncOp funcOp, TypeRange argumentTypes, TypeRange resultTypes,
DenseMap<FuncOp, FunctionType> &bufferizedFunctionTypes) {
auto it = bufferizedFunctionTypes.find(funcOp);
if (it != bufferizedFunctionTypes.end())
return it->second;
auto it2 = bufferizedFunctionTypes.try_emplace(
funcOp, getBufferizedFunctionType(funcOp.getContext(), argumentTypes,
resultTypes));
LDBG("FT: " << funcOp.getType() << " -> " << it2.first->second << "\n");
return it2.first->second;
}
//===----------------------------------------------------------------------===//
// Bufferization-specific scoped alloc/dealloc insertion support.
//===----------------------------------------------------------------------===//
/// Create an Allocop/DeAllocOp pair, where the AllocOp is after
/// `shapedValue.getDefiningOp` (or at the top of the block in case of a
/// bbArg) and the DeallocOp is at the end of the block.
static Value
createNewAllocDeallocPairForShapedValue(OpBuilder &b, Location loc,
Value shapedValue,
BufferizationAliasInfo &aliasInfo) {
// Take a guard before anything else.
OpBuilder::InsertionGuard g(b);
// TODO: non-zero address space.
// TODO: layout information if relevant.
// Cannot allocate an unranked memref so just always go for the contiguous
// form.
MemRefType allocMemRefType =
getContiguousMemRefType(shapedValue.getType().cast<ShapedType>());
assert(shapedValue.getType().isa<ShapedType>());
MemRefType memRefType = shapedValue.getType().dyn_cast<MemRefType>();
memRefType = memRefType ? memRefType : allocMemRefType;
if (auto bbArg = shapedValue.dyn_cast<BlockArgument>()) {
b.setInsertionPointToStart(bbArg.getOwner());
loc = bbArg.getOwner()->getParentOp()->getLoc();
} else {
b.setInsertionPointAfter(shapedValue.getDefiningOp());
loc = shapedValue.getDefiningOp()->getLoc();
}
// Compute the dynamic part of the shape.
SmallVector<Value> dynShape;
for (auto dim : enumerate(memRefType.getShape()))
if (dim.value() == ShapedType::kDynamicSize)
dynShape.push_back(createOrFoldDimOp(b, loc, shapedValue, dim.index()));
Value allocated = b.create<memref::AllocOp>(loc, allocMemRefType, dynShape);
aliasInfo.createAliasInfoEntry(allocated);
Value casted = allocated;
if (memRefType != allocMemRefType) {
casted = b.create<memref::CastOp>(loc, memRefType, allocated);
aliasInfo.insertNewBufferEquivalence(casted, allocated);
}
b.setInsertionPoint(allocated.getParentBlock()->getTerminator());
b.create<memref::DeallocOp>(loc, allocated);
return casted;
}
//===----------------------------------------------------------------------===//
// Bufferization as simple BlockAndValueMapping rewrites.
//===----------------------------------------------------------------------===//
/// Helper function for LinalgOp bufferization.
/// Examines each result and determines whether it bufferizes inplace on an
/// operand.
/// If the opResult bufferizes inplace, just reuse the existing buffer.
/// Otherwise allocate a new buffer to hold the result.
/// When allocating a new buffer, analyze whether `op` want to read form that
/// buffer. In such a case, insert a copy to ensure the newly allocated buffer
/// is properly initialiazed.
static void allocateBuffersForResults(OpBuilder &b, Location loc, LinalgOp op,
SmallVectorImpl<Value> &resultBuffers,
BlockAndValueMapping &bvm,
BufferizationAliasInfo &aliasInfo) {
// Take a guard before anything else.
OpBuilder::InsertionGuard g(b);
// TODO: provide the proper interface to iterate on OpResults and get the
// matching OpOperands.
for (OpOperand *opOperand : op.getOutputOperands()) {
Value output = opOperand->get();
assert(output.getType().isa<TensorType>() && "expected tensor type");
// If output tensor is marked inPlace, just use the buffer.
// The following uses internal knowledge of the position of inplaceable
// operand / results.
OpResult opResult = getInplaceableOpResult(*opOperand);
if (getInPlace(opResult) == InPlaceSpec::True) {
Value v = lookup(bvm, output);
assert(v && "missing buffer");
resultBuffers.push_back(v);
continue;
}
// Otherwise, `op` is not inplaceable and we need to allocate its result.
Value dimTensor = bvm.lookupOrDefault(output);
Value alloc =
createNewAllocDeallocPairForShapedValue(b, loc, dimTensor, aliasInfo);
b.setInsertionPointAfter(alloc.getDefiningOp());
resultBuffers.push_back(alloc);
// Additionally, if the output buffer is used, clone its value for now.
if (op.payloadUsesValueFromOperand(opOperand)) {
Value v = lookup(bvm, output);
b.create<CopyOp>(loc, v, alloc);
}
}
if (op->getNumResults())
map(bvm, op->getResults(), resultBuffers);
}
/// Generic conversion for any LinalgOp on tensors.
static LogicalResult bufferize(OpBuilder &b, LinalgOp op,
BlockAndValueMapping &bvm,
BufferizationAliasInfo &aliasInfo) {
// Take a guard before anything else.
OpBuilder::InsertionGuard g(b);
// Ensure op has only tensors. Allow mixed tensor-buffer mode on a per-need
// basis.
if (!op.hasTensorSemantics())
return op->emitError() << "op does not have tensor semantics";
b.setInsertionPoint(op);
Location loc = op.getLoc();
SmallVector<Value> newInputBuffers;
newInputBuffers.reserve(op.getNumInputs());
for (OpOperand *opOperand : op.getInputOperands()) {
if (op.isScalar(opOperand)) {
newInputBuffers.push_back(opOperand->get());
continue;
}
newInputBuffers.push_back(lookup(bvm, opOperand->get()));
assert(newInputBuffers.back() && "missing buffer");
}
SmallVector<Value> newOutputBuffers;
// Try to allocate new buffers depending on op's inplace semantics.
allocateBuffersForResults(b, loc, op, newOutputBuffers, bvm, aliasInfo);
// Clone the newly bufferized op.
SmallVector<Value> newOperands = newInputBuffers;
newOperands.append(newOutputBuffers.begin(), newOutputBuffers.end());
op.clone(b, loc, /*resultTypes=*/TypeRange{}, newOperands);
// Replace the results of the old op with the new output buffers.
if (op->getNumResults())
map(bvm, op->getResults(), newOutputBuffers);
// The original op will be DCE'd away later.
return success();
}
/// In a first approximation, all the function arguments of a FuncOp are marked
/// inplaceable. For now, it is the responsibility of the `callOp` bufferization
/// to allow FuncOp that are inplaceable to write inPlace.
static LogicalResult
bufferize(OpBuilder &b, CallOpInterface callOp, BlockAndValueMapping &bvm,
BufferizationAliasInfo &aliasInfo,
DenseMap<FuncOp, FunctionType> &bufferizedFunctionTypes) {
FuncOp funcOp = getCalledFunction(callOp);
assert(isa<CallOp>(callOp.getOperation()) && funcOp &&
"expected Callop to a FuncOp");
// If nothing to do then we are done.
if (!llvm::any_of(funcOp.getType().getInputs(), isaTensor) &&
!llvm::any_of(funcOp.getType().getResults(), isaTensor))
return success();
// Take a guard before anything else.
OpBuilder::InsertionGuard g(b);
b.setInsertionPoint(callOp);
// 1. Filter return types:
// - if the callee is bodiless / external, we cannot inspect it and we
// cannot assume anything. We can just assert that it does not return a
// tensor as this would have to bufferize to "return a memref", whose
// semantics is ill-defined.
// - if the callee has a body, we perform inter-procedural equivalence
// analysis. When successful, a result folds onto an operand. When
// unsuccessful, additional work is needed to either:
// * hoist a result into an inplaceable operand or
// * devise a better representation to truly return a buffer.
SmallVector<Type> resultTypes;
SmallVector<Value> hoistedArguments;
if (funcOp.body().empty()) {
if (llvm::any_of(funcOp.getType().getResults(), isaTensor))
return callOp->emitError()
<< "cannot bufferize bodiless function that returns a tensor";
} else {
ReturnOp returnOp = getAssumedUniqueReturnOp(funcOp);
assert(returnOp && "expected func with single return op");
// For each FuncOp result, keep track of which inplace argument it reuses.
for (OpOperand &returnOperand : returnOp->getOpOperands()) {
Type returnType = returnOperand.get().getType();
if (!isaTensor(returnType)) {
resultTypes.push_back(returnType);
continue;
}
// If return operand is equivalent to some bbArg, no need to return it.
Value returnVal = returnOperand.get();
if (BlockArgument bbArg =
getEquivalentEnclosingFuncBBArg(returnVal, aliasInfo)) {
Value oldRes = callOp->getResult(returnOperand.getOperandNumber());
int64_t idx = bbArg.getArgNumber();
Value buffer = lookup(bvm, callOp->getOperand(idx));
assert(buffer && "expected bufferized value");
// Add CallOp operand/result equivalence: this is interprocedural info.
aliasInfo.insertNewBufferEquivalence(oldRes, buffer);
map(bvm, oldRes, buffer);
// Add a TensorLoadOp to kill all uses of the CallOp return.
// Replace all uses of the CallOp results so we can erase the CallOp.
// This TensorLoadOp must fold/DCE away or bufferization should be
// considered failed.
Value tensorLoad =
b.create<memref::TensorLoadOp>(callOp.getLoc(), buffer);
oldRes.replaceAllUsesWith(tensorLoad);
// Add new op equivalence info.
aliasInfo.insertNewBufferEquivalence(tensorLoad, buffer);
map(bvm, tensorLoad, buffer);
continue;
}
// TODO: Need to hoist above function boundary.
if (Operation *allocOp = getEquivalentAlloc(returnVal, aliasInfo)) {
hoistedArguments.push_back(allocOp->getResult(0));
continue;
}
// Other cases legitimately need to return a tensor, this is currently not
// supported. For instance, if hoisting across function boundary has
// failed, it may be due to e.g. data-dependent sizes. In such a case, we
// would we need a better type than memref.
resultTypes.push_back(returnType);
int64_t returnIdx = returnOperand.getOperandNumber();
return returnOp->emitError()
<< "buffer result #" << returnIdx << " not produced by an alloc\n";
}
}
// 2. Compute bufferized FunctionType.
SmallVector<Type> argumentTypes{callOp->getOperandTypes()};
ValueRange hoistedArgs{hoistedArguments};
llvm::append_range(argumentTypes, hoistedArgs.getTypes());
// Get the bufferized FunctionType for funcOp or construct it if not yet
// available.
FunctionType bufferizedFuncType = getOrCreateBufferizedFunctionType(
funcOp, argumentTypes, resultTypes, bufferizedFunctionTypes);
// 3. Rewrite tensor operands as memrefs based on `bufferizedFuncType`.
SmallVector<Value> newOperands;
newOperands.reserve(callOp->getNumOperands());
for (OpOperand &opOperand : callOp->getOpOperands()) {
Value tensorOperand = opOperand.get();
// Non-tensor operands are just copied.
if (!tensorOperand.getType().isa<TensorType>()) {
newOperands.push_back(tensorOperand);
continue;
}
// Tensor operands are guaranteed to have been buferized.
int64_t idx = opOperand.getOperandNumber();
Value buffer = lookup(bvm, tensorOperand);
assert(buffer && "expected bufferized value");
// Caller / callee type mistmatch is handled with a CastOp.
auto memRefType = bufferizedFuncType.getInput(idx);
// Since we don't yet have a clear layout story, buffer_cast may
// conservatively turn tensors into more dynamic memref than necessary.
// If the memref type of the callee fails, introduce an extra memref.cast
// that will either canonicalize away or fail compilation until we can do
// something better.
if (buffer.getType() != memRefType) {
Value castBuffer =
b.create<memref::CastOp>(callOp.getLoc(), memRefType, buffer);
// Add new op equivalence info.
aliasInfo.insertNewBufferEquivalence(castBuffer, buffer);
map(bvm, tensorOperand, castBuffer);
buffer = castBuffer;
}
newOperands.push_back(buffer);
}
// 4. Create the new CallOp.
Operation *newCallOp = b.create<CallOp>(callOp.getLoc(), funcOp.sym_name(),
resultTypes, newOperands);
newCallOp->setAttrs(callOp->getAttrs());
return success();
}
/// tensor::CastOp bufferizes to memref::CastOp.
static LogicalResult bufferize(OpBuilder &b, tensor::CastOp castOp,
BlockAndValueMapping &bvm,
BufferizationAliasInfo &aliasInfo) {
// Take a guard before anything else.
OpBuilder::InsertionGuard g(b);
b.setInsertionPoint(castOp);
Type sourceType = lookup(bvm, castOp.source()).getType();
auto rankedMemRefType = sourceType.dyn_cast<MemRefType>();
auto unrankedMemRefType = sourceType.dyn_cast<UnrankedMemRefType>();
assert(rankedMemRefType || unrankedMemRefType);
unsigned memorySpace = rankedMemRefType
? rankedMemRefType.getMemorySpaceAsInt()
: unrankedMemRefType.getMemorySpaceAsInt();
TensorType tensorType = castOp.getResult().getType().cast<TensorType>();
ArrayRef<AffineMap> affineMaps =
rankedMemRefType && tensorType.isa<RankedTensorType>()
? rankedMemRefType.getAffineMaps()
: ArrayRef<AffineMap>{};
Type memRefType = getContiguousOrUnrankedMemRefType(
castOp.getResult().getType(), affineMaps, memorySpace);
Value res = b.create<memref::CastOp>(castOp.getLoc(), memRefType,
lookup(bvm, castOp.source()));
aliasInfo.insertNewBufferEquivalence(res, castOp.getResult());
map(bvm, castOp.getResult(), res);
return success();
}
static LogicalResult bufferize(OpBuilder &b, ConstantOp constantOp,
BlockAndValueMapping &bvm,
BufferizationAliasInfo &aliasInfo,
GlobalCreator &globalCreator) {
assert(constantOp.getType().dyn_cast<RankedTensorType>() &&
"not a constant ranked tensor");
// Take a guard before anything else.
OpBuilder::InsertionGuard g(b);
b.setInsertionPoint(constantOp);
auto globalMemref = globalCreator.getGlobalFor(constantOp);
Value memref = b.create<memref::GetGlobalOp>(
constantOp.getLoc(), globalMemref.type(), globalMemref.getName());
aliasInfo.insertNewBufferEquivalence(memref, constantOp.getResult());
map(bvm, constantOp, memref);
return success();
}
/// DimOp tensor operand is modified inplace. This allows leaving dead
/// tensors behind that will get DCE'd.
static LogicalResult bufferize(OpBuilder &b, tensor::DimOp dimOp,
BlockAndValueMapping &bvm,
BufferizationAliasInfo &aliasInfo) {
// Take a guard before anything else.
OpBuilder::InsertionGuard g(b);
b.setInsertionPoint(dimOp);
if (dimOp.source().getType().isa<RankedTensorType>()) {
Value v = lookup(bvm, dimOp.source());
assert(v && "missing buffer");
dimOp.result().replaceAllUsesWith(
b.create<memref::DimOp>(dimOp.getLoc(), v, dimOp.index()));
}
return success();
}
static LogicalResult bufferize(OpBuilder &b, scf::ForOp forOp,
BlockAndValueMapping &bvm,
BufferizationAliasInfo &aliasInfo) {
// Take a guard before anything else.
OpBuilder::InsertionGuard g(b);
Location loc = forOp.getLoc();
// If inPlace, just forward the buffer.
// Otherwise alloc and copy.
b.setInsertionPoint(forOp);
for (OpResult opResult : forOp->getResults()) {
if (!opResult.getType().isa<TensorType>())
continue;
// TODO: Atm we bail on unranked TensorType because we don't know how to
// alloc an UnrankedMemRefType + its underlying ranked MemRefType.
assert(opResult.getType().isa<RankedTensorType>() &&
"unsupported unranked tensor");
OpOperand &opOperand = forOp.getOpOperandForResult(opResult);
Value operand = opOperand.get();
Value operandBuffer = lookup(bvm, operand);
Value resultBuffer = operandBuffer;
if (getInPlace(opResult) != InPlaceSpec::True) {
resultBuffer =
createNewAllocDeallocPairForShapedValue(b, loc, operand, aliasInfo);
// If the tensor comes from `linalg::InitTensorOp`, the value is
// unitialized and we do not need to copy.
// TODO: "matching bbArg does not bufferize to a read" is a more general
// check.
if (!operand.getDefiningOp<linalg::InitTensorOp>())
b.create<linalg::CopyOp>(forOp.getLoc(), operandBuffer, resultBuffer);
}
BlockArgument bbArg = forOp.getRegionIterArgForOpOperand(opOperand);
aliasInfo.createAliasInfoEntry(resultBuffer);
aliasInfo.insertNewBufferEquivalence(bbArg, resultBuffer);
map(bvm, bbArg, resultBuffer);
map(bvm, opResult, resultBuffer);
}
return success();
}
/// FuncOp always creates TensorToMemRef ops.
static LogicalResult bufferize(OpBuilder &b, FuncOp funcOp,
BlockAndValueMapping &bvm,
BufferizationAliasInfo &aliasInfo) {
// Take a guard before anything else.
OpBuilder::InsertionGuard g(b);
b.setInsertionPointToStart(&funcOp.body().front());
for (auto bbArg : funcOp.getArguments()) {
auto tensorType = bbArg.getType().dyn_cast<TensorType>();
if (!tensorType)
continue;
auto rankedTensorType = tensorType.dyn_cast<RankedTensorType>();
// Cast the tensor to the most dynamic buffer possible. Further
// canonicalizations will clean up.
Type memRefType = rankedTensorType
? getDynamicMemRefType(rankedTensorType)
: getContiguousOrUnrankedMemRefType(tensorType);
Value bufferCast =
b.create<memref::BufferCastOp>(funcOp.getLoc(), memRefType, bbArg);
aliasInfo.insertNewBufferEquivalence(bufferCast, bbArg);
map(bvm, bbArg, bufferCast);
}
return success();
}
/// InitTensor always allocates.
/// TODO: consider hoisting across function boundaries prior to bufferization.
static LogicalResult bufferize(OpBuilder &b, InitTensorOp initTensorOp,
BlockAndValueMapping &bvm,
BufferizationAliasInfo &aliasInfo) {
// Take a guard before anything else.
OpBuilder::InsertionGuard g(b);
b.setInsertionPoint(initTensorOp);
Value alloc = createNewAllocDeallocPairForShapedValue(
b, initTensorOp->getLoc(), initTensorOp.result(), aliasInfo);
map(bvm, initTensorOp.result(), alloc);
return success();
}
/// ReturnOp always creates memref::TensorLoadOp.
static LogicalResult bufferize(OpBuilder &b, ReturnOp returnOp,
BlockAndValueMapping &bvm,
BufferizationAliasInfo &aliasInfo) {
// Take a guard before anything else.
OpBuilder::InsertionGuard g(b);
b.setInsertionPoint(returnOp);
assert(isa<FuncOp>(returnOp->getParentOp()) &&
"only support FuncOp parent for ReturnOp");
for (OpOperand &operand : returnOp->getOpOperands()) {
auto tensorType = operand.get().getType().dyn_cast<TensorType>();
if (!tensorType)
continue;
Value v = lookup(bvm, operand.get());
assert(v && "missing buffer for result");
Value returnTensor = b.create<memref::TensorLoadOp>(returnOp.getLoc(), v);
operand.set(returnTensor);
aliasInfo.insertNewBufferEquivalence(returnTensor, v);
map(bvm, returnTensor, v);
}
return success();
}
/// Bufferization for TiledLoopOp..
static LogicalResult bufferize(OpBuilder &b, TiledLoopOp tiledLoopOp,
BlockAndValueMapping &bvm,
BufferizationAliasInfo &aliasInfo) {
// Allocate output buffers if needed, forward output tensor args to the
// terminator.
Operation *yieldOp = tiledLoopOp.getBody()->getTerminator();
Block *body = tiledLoopOp.getBody();
// Take copies of the old input and output operands, so we can insert inplace
// easily.
auto oldInputs = llvm::to_vector<4>(tiledLoopOp.inputs());
auto oldOutputs = llvm::to_vector<4>(tiledLoopOp.outputs());
int numLoops = tiledLoopOp.getNumLoops();
int numControlOperands = tiledLoopOp.getNumControlOperands();
// Add buffers for outputs and the corresponding block arguments.
// Keep separate iterators to increment without further leaking impl. details.
// Start with outputs to avoid interference from new input buffers.
int numNewOutputBuffers = 0;
int resultIndex = 0;
int oldOutputBBArgIndex = numLoops + oldInputs.size();
int nextOutputBBArgIndex = numLoops + oldInputs.size() + oldOutputs.size();
int nextOutputOperandIndex =
numControlOperands + oldInputs.size() + oldOutputs.size();
for (Value oldOutputTensor : oldOutputs) {
if (!oldOutputTensor.getType().isa<TensorType>()) {
// Skip and increment the old bbarg index only.
++oldOutputBBArgIndex;
// Do not increment resultIndex as only tensors are returned.
// TODO: better interface to avoid leaking such impl details.
continue;
}
assert(oldOutputTensor.getType().isa<RankedTensorType>() &&
"bufferizable output must be a ranked tensor");
Value outputBuffer = lookup(bvm, oldOutputTensor);
const OpResult &opResult = tiledLoopOp->getResult(resultIndex);
OpOperand &yieldOperand = yieldOp->getOpOperand(resultIndex);
// If the result is not inplaceable, need to allocate a copy for it.
if (getInPlace(opResult) != InPlaceSpec::True) {
auto loc = tiledLoopOp.getLoc();
Value alloc = createNewAllocDeallocPairForShapedValue(
b, loc, oldOutputTensor, aliasInfo);
// If the tensor comes from `linalg::InitTensorOp`, the value is
// unitialized and we do not need to copy.
// TODO: "matching bbArg does not bufferize to a read" is a more general
// check.
if (!oldOutputTensor.getDefiningOp<linalg::InitTensorOp>()) {
b.setInsertionPointAfter(alloc.getDefiningOp());
b.create<linalg::CopyOp>(loc, outputBuffer, alloc);
}
outputBuffer = alloc;
}
// Insert mapping and aliasing info.
aliasInfo.createAliasInfoEntry(outputBuffer);
aliasInfo.insertNewBufferEquivalence(opResult, outputBuffer);
map(bvm, opResult, outputBuffer);
// Insert new operand and bbArg.
tiledLoopOp->insertOperands(nextOutputOperandIndex, outputBuffer);
BlockArgument newBufferBBArg =
body->insertArgument(nextOutputBBArgIndex, outputBuffer.getType());
BlockArgument oldTensorBBArg = body->getArgument(oldOutputBBArgIndex);
// Insert mapping and aliasing info.
aliasInfo.createAliasInfoEntry(newBufferBBArg);
aliasInfo.insertNewBufferEquivalence(oldTensorBBArg, newBufferBBArg);
map(bvm, oldTensorBBArg, newBufferBBArg);
// Set operand of `linalg.yield` to the bbArg so it just canonicalizes away
// later.
yieldOperand.set(oldTensorBBArg);
// Increment indices.
++numNewOutputBuffers;
++resultIndex;
++oldOutputBBArgIndex;
++nextOutputBBArgIndex;
++nextOutputOperandIndex;
}
// Add buffers for inputs and the corresponding block arguments.
// Keep separate iterators to increment without further leaking impl. details.
int numNewInputBuffers = 0;
int oldInputBBArgIndex = numLoops;
int nextInputBBArgIndex = numLoops + oldInputs.size();
int nextInputOperandIndex = numControlOperands + oldInputs.size();
for (Value oldInputTensor : oldInputs) {
if (!oldInputTensor.getType().isa<TensorType>()) {
// Skip and increment the old bbarg index only.
++oldInputBBArgIndex;
continue;
}
Value inputBuffer = lookup(bvm, oldInputTensor);
assert(inputBuffer && " missing buffer for operand");
// Insert new operand and bbArg.
tiledLoopOp->insertOperands(nextInputOperandIndex, inputBuffer);
BlockArgument newBufferBBArg =
body->insertArgument(nextInputBBArgIndex, inputBuffer.getType());
BlockArgument oldTensorBBArg = body->getArgument(oldInputBBArgIndex);
// Insert mapping and aliasing info.
aliasInfo.createAliasInfoEntry(newBufferBBArg);
aliasInfo.insertNewBufferEquivalence(oldTensorBBArg, newBufferBBArg);
map(bvm, oldTensorBBArg, newBufferBBArg);
// Increment indices.
++numNewInputBuffers;
++oldInputBBArgIndex;
++nextInputBBArgIndex;
++nextInputOperandIndex;
}
// Update segment sizes.
// TODO: Helper method to avoid leaking impl details.
tiledLoopOp->setAttr(
TiledLoopOp::getOperandSegmentSizeAttr(),
b.getI32VectorAttr(
{numLoops, numLoops, numLoops,
static_cast<int>(oldInputs.size()) + numNewInputBuffers,
static_cast<int>(oldOutputs.size()) + numNewOutputBuffers}));
return success();
}
/// Bufferize ExtractSliceOp to subview with optional alloc + copy depending on
/// whether or not it is marked inplaceable.
/// Note that `getInplaceableOpResult` on a ExtractSliceOp always returns null.
/// As consequence a ExtractSliceOp always alloc + copy when taken in
/// isolation.
static LogicalResult bufferize(OpBuilder &b, ExtractSliceOp extractSliceOp,
BlockAndValueMapping &bvm,
BufferizationAliasInfo &aliasInfo) {
LDBG("bufferize: " << *extractSliceOp << '\n');
// Take a guard before anything else.
OpBuilder::InsertionGuard g(b);
b.setInsertionPoint(extractSliceOp);
Location loc = extractSliceOp.getLoc();
// Bail if source was not bufferized.
Value srcMemref = lookup(bvm, extractSliceOp.source());
if (!srcMemref)
return failure();
auto srcMemrefType = srcMemref.getType().cast<MemRefType>();
auto dstTensorType =
extractSliceOp.result().getType().cast<RankedTensorType>();
// If not inplaceable, alloc.
Value alloc;
auto inPlace = getInPlace(extractSliceOp->getResult(0));
if (inPlace != InPlaceSpec::True) {
alloc = createNewAllocDeallocPairForShapedValue(
b, loc, extractSliceOp.result(), aliasInfo);
b.setInsertionPointAfter(alloc.getDefiningOp());
}
// Bufferize to subview.
auto subviewMemRefType =
memref::SubViewOp::inferRankReducedResultType(
dstTensorType.getRank(), srcMemrefType,
extractSliceOp.getMixedOffsets(), extractSliceOp.getMixedSizes(),
extractSliceOp.getMixedStrides())
.cast<MemRefType>();
Value subView = b.create<memref::SubViewOp>(
loc, subviewMemRefType, srcMemref, extractSliceOp.getMixedOffsets(),
extractSliceOp.getMixedSizes(), extractSliceOp.getMixedStrides());
// Insert new alias.
aliasInfo.insertNewBufferAlias(subView, srcMemref);
/// If not inplaceable, copy.
if (alloc) {
b.create<CopyOp>(extractSliceOp.getLoc(), subView, alloc);
subView = alloc;
}
map(bvm, extractSliceOp.result(), subView);
return success();
}
static LogicalResult bufferize(OpBuilder &b, InsertSliceOp insertSliceOp,
BlockAndValueMapping &bvm,
BufferizationAliasInfo &aliasInfo) {
LDBG("bufferize: " << *insertSliceOp << '\n');
// Take a guard before anything else.
OpBuilder::InsertionGuard g(b);
b.setInsertionPoint(insertSliceOp);
Location loc = insertSliceOp.getLoc();
Value dstMemref = lookup(bvm, insertSliceOp.dest());
if (!dstMemref)
return failure();
auto inPlace = getInPlace(insertSliceOp->getResult(0));
if (inPlace != InPlaceSpec::True) {
// Since insert_slice arise from tiling and introducing loops, this
// case is generally a deal breaker. When used with loops, this ends up
// cloning the whole tensor on every single iteration and is a symptom
// of a catastrophically bad scheduling decision.
// TODO: be very loud about it or even consider failing the pass.
Value newDstMemref = createNewAllocDeallocPairForShapedValue(
b, loc, insertSliceOp.result(), aliasInfo);
b.setInsertionPointAfter(newDstMemref.getDefiningOp());
b.create<CopyOp>(insertSliceOp.getLoc(), dstMemref, newDstMemref);
dstMemref = newDstMemref;
}
auto dstMemrefType = dstMemref.getType().cast<MemRefType>();
Value srcMemref = lookup(bvm, insertSliceOp.source());
if (!srcMemref)
return failure();
auto subviewMemRefType =
memref::SubViewOp::inferRankReducedResultType(
insertSliceOp.getSourceType().getRank(), dstMemrefType,
insertSliceOp.getMixedOffsets(), insertSliceOp.getMixedSizes(),
insertSliceOp.getMixedStrides())
.cast<MemRefType>();
// A copy of the source buffer is needed if either:
// - The producer of `source` is not inplace. This is the case where a
// slice is computed out of place into the inplace full tensor.
// - The result is not inplace. This is the case where the whole tensor is
// cloned and the clone needs to be updated.
if (!aliasInfo.isSourceEquivalentToAMatchingInplaceExtractSliceOp(
insertSliceOp) ||
inPlace != InPlaceSpec::True) {
LDBG("insert_slice needs extra source copy: " << insertSliceOp.source()
<< " -> copy\n");
// Take a subview of the dst.
Value subView = b.create<memref::SubViewOp>(
loc, subviewMemRefType, dstMemref, insertSliceOp.getMixedOffsets(),
insertSliceOp.getMixedSizes(), insertSliceOp.getMixedStrides());
// Insert new alias.
aliasInfo.insertNewBufferAlias(subView, dstMemref);
b.create<CopyOp>(insertSliceOp.getLoc(), srcMemref, subView);
}
map(bvm, insertSliceOp.result(), dstMemref);
return success();
}
static LogicalResult bufferize(OpBuilder &b, VectorTransferOpInterface op,
BlockAndValueMapping &bvm,
BufferizationAliasInfo &aliasInfo) {
// Take a guard before anything else.
OpBuilder::InsertionGuard g(b);
b.setInsertionPoint(op);
Location loc = op.getLoc();
if (op.getShapedType().isa<MemRefType>())
return failure();
/// transfer_read from buffer always reads from the bufferized
/// op.source().
if (auto readOp = dyn_cast<vector::TransferReadOp>(op.getOperation())) {
Value v = lookup(bvm, op.source());
assert(v && "missing buffer");
readOp.sourceMutable().assign(v);
return success();
}
auto inPlace = getInPlace(op->getResult(0));
auto writeOp = cast<vector::TransferWriteOp>(op.getOperation());
// If transfer_write is not inPlace, allocate a new buffer.
Value newInputBuffer;
if (inPlace != InPlaceSpec::True) {
newInputBuffer = createNewAllocDeallocPairForShapedValue(
b, loc, writeOp.result(), aliasInfo);
b.setInsertionPointAfter(newInputBuffer.getDefiningOp());
map(bvm, writeOp.result(), newInputBuffer);
} else {
// InPlace write will result in memref.tensor_load(x) which must
// canonicalize away with one of it uses.
newInputBuffer = lookup(bvm, writeOp.source());
assert(newInputBuffer && "missing buffer");
}
// Create a new transfer_write on buffer that doesn't have a return value.
// Leave the previous transfer_write to dead code as it still has uses at
// this point.
b.create<vector::TransferWriteOp>(
loc, writeOp.vector(), newInputBuffer, writeOp.indices(),
writeOp.permutation_map(),
writeOp.in_bounds() ? *writeOp.in_bounds() : ArrayAttr());
map(bvm, op->getResult(0), newInputBuffer);
return success();
}
static LogicalResult bufferize(OpBuilder &b, scf::YieldOp yieldOp,
BlockAndValueMapping &bvm,
BufferizationAliasInfo &aliasInfo) {
// Take a guard before anything else.
OpBuilder::InsertionGuard g(b);
b.setInsertionPoint(yieldOp);
scf::ForOp forOp = dyn_cast<scf::ForOp>(yieldOp->getParentOp());
assert(forOp && "only support scf::ForOp parent for scf::YieldOp");
for (OpOperand &operand : yieldOp->getOpOperands()) {
auto tensorType = operand.get().getType().dyn_cast<TensorType>();
if (!tensorType)
continue;
OpOperand &forOperand = forOp.getOpOperandForResult(
forOp->getResult(operand.getOperandNumber()));
auto bbArg = forOp.getRegionIterArgForOpOperand(forOperand);
Value yieldedBuffer = lookup(bvm, operand.get());
Value bbArgBuffer = lookup(bvm, bbArg);
if (!aliasInfo.areEquivalentBufferizedValues(yieldedBuffer, bbArgBuffer)) {
// TODO: this could get resolved with copies but it can also turn into
// swaps so we need to be careful about order of copies.
return yieldOp->emitError()
<< "Yield operand #" << operand.getOperandNumber()
<< " does not bufferize to an equivalent buffer to the matching"
<< " enclosing scf::for operand";
}
// Buffers are equivalent so the work is already done and we just yield the
// bbArg so that it later canonicalizes away.
operand.set(bbArg);
}
return success();
}
/// Bufferization for linalg::YieldOp either does not involve tensors or just
/// results in later canonicalization. In either case it does nothing.
static LogicalResult bufferize(OpBuilder &b, linalg::YieldOp yieldOp,
BlockAndValueMapping &bvm,
BufferizationAliasInfo &aliasInfo) {
// Take a guard before anything else.
OpBuilder::InsertionGuard g(b);
b.setInsertionPoint(yieldOp);
// No tensors -> success.
if (!llvm::any_of(yieldOp.getOperandTypes(), isaTensor))
return success();
// linalg::YieldOp nested under TiledLoop must just canonicalize.
if (yieldOp->getParentOfType<TiledLoopOp>())
return success();
llvm_unreachable("unexpected yieldOp");
}
/// Bufferization for tensor::ExtractOp just translate to memref.load, it only
/// reads the tensor.
static LogicalResult bufferize(OpBuilder &b, tensor::ExtractOp extractOp,
BlockAndValueMapping &bvm,
BufferizationAliasInfo &aliasInfo) {
// Take a guard before anything else.
OpBuilder::InsertionGuard g(b);
b.setInsertionPoint(extractOp);
Location loc = extractOp.getLoc();
Value srcMemref = lookup(bvm, extractOp.tensor());
Value l = b.create<memref::LoadOp>(loc, srcMemref, extractOp.indices());
extractOp.replaceAllUsesWith(l);
return success();
}
//===----------------------------------------------------------------------===//
// Bufferization analyses.
//===----------------------------------------------------------------------===//
///
/// Rationale for bufferizing `%1 = tensor.extract_slice %0[...]` inplace.
/// ===========================================================
///
/// When bufferized out of place, a ExtractSlice lowers to alloc + copy. This
/// cannot change the flow of information for either the source or the
/// result buffers.
///
/// When bufferized inplace, a ExtractSliceOp does not by itself create any read
/// or write from memory. Instead, it has the effect of merging the alias sets
/// of the source and the result buffers.
///
/// An analysis is required to ensure inplace bufferization would not result in
/// RaW dependence violations.
static LogicalResult
bufferizableInPlaceAnalysis(ExtractSliceOp extractSliceOp,
BufferizationAliasInfo &aliasInfo,
const DominanceInfo &domInfo) {
LDBG('\n');
LDBG("Inplace analysis for extract_slice: " << *extractSliceOp << '\n');
// If `extractSliceOp` were to be bufferized inplace, it cannot end up
// aliasing a write into a non-writeable buffer.
bool wouldCreateAliasingWriteToNonWriteableBuffer =
aliasInfo.aliasesInPlaceWrite(extractSliceOp.result()) &&
aliasInfo.aliasesNonWriteableBuffer(extractSliceOp->getOpOperand(0));
if (wouldCreateAliasingWriteToNonWriteableBuffer)
LDBG("->the corresponding buffer is not writeable\n");
else
LDBG("->bufferizes to writeable inplace buffer\n");
// In any of extractSliceOp.result's aliases, can we find 2 such that we hit
// an interfering write?
OpResult r = extractSliceOp->getResult(0);
OpOperand &s = extractSliceOp->getOpOperand(0);
bool foundInterference =
wouldCreateAliasingWriteToNonWriteableBuffer ||
aliasInfo.wouldCreateReadAfterWriteInterference(r, domInfo);
if (foundInterference)
aliasInfo.bufferizeOutOfPlace(r);
else
aliasInfo.bufferizeInPlace(r, s);
LDBG("Done inplace analysis for extract_slice\n");
return success();
}
/// Analyze the (opOperand, result) pair to determine whether the result can
/// be bufferized inPlace. If successful, InPlaceSpec::True is set for
/// `result`. Otherwise, InPlaceSpec::False is set for `result`.
static LogicalResult
bufferizableInPlaceAnalysis(OpOperand &operand, OpResult result,
BufferizationAliasInfo &aliasInfo,
const DominanceInfo &domInfo) {
Operation *op = result.getDefiningOp();
assert(result && !isa<ExtractSliceOp>(op) &&
"expected OpResult not coming from a ExtractSliceOp");
(void)op;
int64_t resultNumber = result.getResultNumber();
(void)resultNumber;
LDBG('\n');
LDBG("Inplace analysis for result #" << resultNumber << " (operand #"
<< operand.getOperandNumber() << ") in "
<< result << '\n');
// `result` must bufferize to a writeable buffer to be a candidate.
// This means the operand must not alias either:
// 1. a function bbArg that is not inplaceable or
// 2. a constant op.
// to be considered for inplace bufferization
bool wouldCreateAliasingWriteToNonWriteableBuffer =
aliasInfo.aliasesNonWriteableBuffer(operand);
if (wouldCreateAliasingWriteToNonWriteableBuffer)
LDBG("->the corresponding buffer is not writeable\n");
else
LDBG("->bufferizes to writeable inplace buffer\n");
assert(result == getInplaceableOpResult(operand));
bool foundInterference =
wouldCreateAliasingWriteToNonWriteableBuffer ||
aliasInfo.wouldCreateReadAfterWriteInterference(result, domInfo);
if (foundInterference)
aliasInfo.bufferizeOutOfPlace(result);
else
// TODO: Atm, all inplace bufferizations yield equivalent tensors. Support
// more cases on a per-need basis.
aliasInfo.bufferizeInPlace(
result, operand, BufferizationAliasInfo::BufferRelation::Equivalent);
LDBG("Done inplace analysis for result #" << resultNumber << '\n');
return success();
}
/// Analyze the `funcOp` body to determine which OpResults are inplaceable.
static LogicalResult
inPlaceAnalysisFuncOpBody(FuncOp funcOp, BufferizationAliasInfo &aliasInfo,
const DominanceInfo &domInfo) {
LLVM_DEBUG(llvm::dbgs() << "\n\n");
LDBG("Begin InPlaceAnalysisFuncOpInternals:\n" << funcOp << '\n');
assert(funcOp && funcOp->getNumRegions() > 0 && !funcOp.body().empty() &&
"expected a funcOp definition with a body");
// Collect ops so we can build our own traversal.
SmallVector<ExtractSliceOp> extractSliceOps;
SmallVector<InsertSliceOp> insertSliceOps;
SmallVector<Operation *> nonSliceOps;
funcOp.walk([&](Operation *op) {
if (auto extractSliceOp = dyn_cast<ExtractSliceOp>(op))
return extractSliceOps.push_back(extractSliceOp);
if (auto insertSliceOp = dyn_cast<InsertSliceOp>(op))
return insertSliceOps.push_back(insertSliceOp);
// No tensors => no buffers.
if (none_of(op->getOperandTypes(), isaTensor) &&
none_of(op->getResultTypes(), isaTensor))
return;
nonSliceOps.push_back(op);
});
// Bufferize InsertSliceOp greedily: we almost never want to bufferize
// the tensor "inserted into" to become out-of-place. This implementation
// does not distinguish between different InsertSliceOp. If we want
// finer-grained behavior, we could order the InsertSliceOp with some metric.
// Walk InsertSliceOp in reverse for better interference behavior.
for (InsertSliceOp insertSliceOp : reverse(insertSliceOps)) {
OpOperand &destOpOperand = insertSliceOp->getOpOperand(1);
if (failed(bufferizableInPlaceAnalysis(
destOpOperand, getInplaceableOpResult(destOpOperand), aliasInfo,
domInfo)))
return failure();
}
// Analyze all ops that return a tensors, except ExtractSliceOp and
// InsertSliceOp which are handled separately.
// Walk other ops in reverse for better interference behavior.
for (Operation *op : reverse(nonSliceOps))
for (OpOperand &opOperand : op->getOpOperands())
if (OpResult result = getInplaceableOpResult(opOperand))
if (result.getType().isa<TensorType>() &&
failed(bufferizableInPlaceAnalysis(opOperand, result, aliasInfo,
domInfo)))
return failure();
// Finally, bufferize ExtractSliceOp.
// Walk ExtractSliceOps in reverse for better clobbering behavior: it is
// easier to detect clobbers of smaller slices before larger ones.
for (ExtractSliceOp extractSliceOp : reverse(extractSliceOps))
if (failed(bufferizableInPlaceAnalysis(extractSliceOp, aliasInfo, domInfo)))
return failure();
LDBG("End InPlaceAnalysisFuncOpInternals:\n" << funcOp << '\n');
return success();
}
//===----------------------------------------------------------------------===//
// Bufferization entry-point for functions.
//===----------------------------------------------------------------------===//
static LogicalResult bufferizeFuncOpInternals(
FuncOp funcOp, BlockAndValueMapping &bvm, BufferizationAliasInfo &aliasInfo,
DenseMap<FuncOp, FunctionType> &bufferizedFunctionTypes,
GlobalCreator &globalCreator) {
LLVM_DEBUG(llvm::dbgs() << "\n\n");
LDBG("Begin BufferizeFuncOpInternals:\n" << funcOp << '\n');
OpBuilder b(funcOp->getContext());
/// Start by bufferizing `funcOp` arguments.
if (failed(bufferize(b, funcOp, bvm, aliasInfo)))
return failure();
// Walk in PreOrder to ensure ops with regions are handled before their body.
// Since walk has to be PreOrder, we need to erase ops that require it
// separately: this is the case for CallOp
// clang-format off
SmallVector<Operation *> toErase;
WalkResult result = funcOp.walk<WalkOrder::PreOrder>([&](Operation *op)
-> WalkResult {
WalkResult result =
TypeSwitch<Operation *, LogicalResult>(op)
// Skip BufferCast and TensorLoad ops.
.Case<memref::BufferCastOp,
memref::TensorLoadOp>([&](auto) { return success(); })
.Case<tensor::CastOp,
tensor::DimOp,
ExtractSliceOp,
scf::ForOp,
InitTensorOp,
InsertSliceOp,
tensor::ExtractOp,
LinalgOp,
ReturnOp,
TiledLoopOp,
VectorTransferOpInterface,
linalg::YieldOp,
scf::YieldOp>([&](auto op) {
LDBG("Begin bufferize:\n" << op << '\n');
return bufferize(b, op, bvm, aliasInfo);
})
.Case([&](CallOpInterface op) {
LDBG("Begin bufferize:\n" << op << '\n');
return bufferize(b, op, bvm, aliasInfo, bufferizedFunctionTypes);
})
.Case([&](ConstantOp op) {
if (!isaTensor(op.getResult().getType()))
return success();
LDBG("Begin bufferize:\n" << op << '\n');
return bufferize(b, op, bvm, aliasInfo, globalCreator);
})
.Default([&](Operation *op) -> LogicalResult {
auto isaTensor = [](Type t) { return t.isa<TensorType>(); };
if (any_of(op->getOperandTypes(), isaTensor) ||
any_of(op->getResultTypes(), isaTensor))
return op->emitError() << "unsupported op with tensors";
return success();
});
// Register post-walk erasure, if necessary.
if (isa<CallOpInterface>(op))
if (llvm::any_of(op->getOperandTypes(), isaTensor) ||
llvm::any_of(op->getResultTypes(), isaTensor))
toErase.push_back(op);
return result;
});
// clang-format on
LDBG("End BufferizeFuncOpInternals:\n" << funcOp << '\n');
for (Operation *op : toErase)
op->erase();
return failure(result.wasInterrupted());
}
//===----------------------------------------------------------------------===//
// Bufferization entry-point for modules.
//===----------------------------------------------------------------------===//
/// Return the op with Allocate MemoryEffect if `v` is equivalent to such an
/// an op. Return null otherwise.
static Operation *getEquivalentAlloc(Value value,
const BufferizationAliasInfo &aliasInfo) {
Operation *res = nullptr;
aliasInfo.applyOnEquivalenceClass(value, [&](Value v) {
if (!res)
if (auto interface =
dyn_cast_or_null<MemoryEffectOpInterface>(v.getDefiningOp()))
if (auto effect =
interface.getEffectOnValue<MemoryEffects::Allocate>(v))
res = v.getDefiningOp();
});
return res;
}
/// Return the first argument of the enclosing FuncOp that is equivalent to `v`.
/// Return null if no such bbArg can be found.
static BlockArgument
getEquivalentEnclosingFuncBBArg(Value v,
const BufferizationAliasInfo &aliasInfo) {
if (!v.getType().isa<RankedTensorType>())
return nullptr;
Operation *op = v.getParentBlock()->getParentOp();
FuncOp funcOp = dyn_cast<FuncOp>(op);
if (!funcOp)
funcOp = op->getParentOfType<FuncOp>();
assert(funcOp && "expected non-null FuncOp");
for (BlockArgument bbArg : funcOp.getArguments()) {
if (!bbArg.getType().isa<RankedTensorType>())
continue;
if (aliasInfo.areEquivalentBufferizedValues(v, bbArg))
return bbArg;
}
return nullptr;
}
/// Rewrite the `funcOp` arguments analysis return values and terminator into
/// buffer form (using the canonical memref layout for now), according to the
/// inPlace-bufferizable information of the function arguments.
/// This relies on a buffer equivalence analysis of each return operand. When a
/// result buffer is equivalent to:
/// 1. a BlockArgument of `funcOp`, it can be dropped from the return values
/// and becomes inplaceable at all callers. This assumes all CallOp perform
/// the necessary work to clone operands so as to make them inplaceable.
// Reliance on this logic will need to be relaxed in thefuture.
/// 2. an op with an Alloc effect, this currently fails bufferization but is a
/// candidate for hoisting and creating a new inplace operand at all caller
/// sites.
/// 3. if such a hoisting for 2. is not possible (e.g. data-dependent that
/// prevents hoisting), this is currently unsupported and will require a
/// refcounted buffer type.
static LogicalResult bufferizeFuncOpBoundary(
FuncOp funcOp, BufferizationAliasInfo &aliasInfo,
DenseMap<FuncOp, FunctionType> &bufferizedFunctionTypes) {
LLVM_DEBUG(DBGS() << "Begin bufferizeFuncOpBoundary:\n" << funcOp << "\n");
// If nothing to do then we are done.
if (!llvm::any_of(funcOp.getType().getInputs(), isaTensor) &&
!llvm::any_of(funcOp.getType().getResults(), isaTensor))
return success();
// Get the bufferized FunctionType for funcOp or construct it if not yet
// available.
// TODO: Atm we have 3 cases:
// 1. if a function is called from within the Module, it must have bufferized
// to inplaceable tensor results.
// 2. if it is bodiless, it must have bufferized and is not allowed to have
// result tensors.
// 3. if it is not called internally, it still must bufferize to inplaceable
// tensor results and we construct it now (e.g. top-level function called
// externally).
// -> Figure out a better layering.
TypeRange resultTypes;
// Corner case: Bodiless FuncOp
// ============================
// The body of such functions is assumed opaque and we can't know the
// bufferization contract they want to enforce atm.
// As a consequence, only support functions that don't return any tensor atm.
if (funcOp.getBody().empty()) {
if (llvm::any_of(funcOp.getType().getResults(), isaTensor))
return funcOp->emitError() << "cannot bufferize bodiless function that "
<< "returns a tensor";
FunctionType bufferizedFuncType =
getOrCreateBufferizedFunctionType(funcOp, funcOp.getType().getInputs(),
TypeRange{}, bufferizedFunctionTypes);
funcOp.setType(bufferizedFuncType);
LLVM_DEBUG(DBGS() << "End bufferizeFuncOpBoundary no fun body: " << funcOp);
return success();
}
// Support only single return-terminated block in the function.
ReturnOp returnOp = getAssumedUniqueReturnOp(funcOp);
assert(returnOp && "expected func with single return op");
// 1. For each FuncOp result, keep track of which inplace argument it reuses.
SmallVector<Value> returnValues;
for (OpOperand &returnOperand : returnOp->getOpOperands()) {
// If not a renturn tensor type just forward it.
if (!returnOperand.get().getType().isa<RankedTensorType>()) {
returnValues.push_back(returnOperand.get());
continue;
}
// If return operand is equivalent to some bbArg, no need to return it.
Value returnVal = returnOperand.get();
if (getEquivalentEnclosingFuncBBArg(returnVal, aliasInfo))
continue;
// TODO: Need to hoist above function boundary.
if (Operation *allocOp = getEquivalentAlloc(returnVal, aliasInfo)) {
returnValues.push_back(allocOp->getResult(0));
continue;
}
// Other cases legitimately need to return a tensor, this is currently not
// supported. For instance, if hoisting across function boundary has
// failed, it may be due to e.g. data-dependent sizes. In such a case, we
// would need a better type than memref.
int64_t returnIdx = returnOperand.getOperandNumber();
return returnOp->emitError()
<< "buffer result #" << returnIdx << " not produced by an alloc\n";
}
// 2. Rewrite the terminator without the inPlace bufferizable values.
ValueRange retValues{returnValues};
FunctionType bufferizedFuncType = getOrCreateBufferizedFunctionType(
funcOp, funcOp.getType().getInputs(), retValues.getTypes(),
bufferizedFunctionTypes);
OpBuilder b(returnOp);
b.create<ReturnOp>(returnOp.getLoc(), returnValues);
returnOp->erase();
// 3. Rewrite the bbArgs.
// Iterate on the original `numArgs` and replace them in order.
// This guarantees the argument order still matches after the rewrite.
Block &frontBlock = funcOp.body().front();
unsigned numArgs = frontBlock.getNumArguments();
for (unsigned idx = 0; idx < numArgs; ++idx) {
auto bbArg = frontBlock.getArgument(0);
auto tensorType = bbArg.getType().dyn_cast<TensorType>();
// Non-tensor types are just forwarded.
if (!tensorType) {
frontBlock.addArgument(bbArg.getType());
bbArg.replaceAllUsesWith(frontBlock.getArguments().back());
frontBlock.eraseArgument(0);
continue;
}
// Get the buffer type from the bufferized function type.
Type memrefType = bufferizedFuncType.getInput(idx);
Value memref = frontBlock.addArgument(memrefType);
OpBuilder b(funcOp->getContext());
b.setInsertionPointToStart(&frontBlock);
// Replace all uses of bbArg through a BufferCastOp by a memref::CastOp.
for (auto &use : llvm::make_early_inc_range(bbArg.getUses())) {
if (auto bufferCastOp = dyn_cast<memref::BufferCastOp>(use.getOwner())) {
auto castOp = b.create<memref::CastOp>(
funcOp.getLoc(), bufferCastOp.memref().getType(), memref);
bufferCastOp.memref().replaceAllUsesWith(castOp);
aliasInfo.insertNewBufferEquivalence(castOp.dest(),
bufferCastOp.memref());
}
}
// Replace all remaining uses by a tensor_load.
if (!bbArg.use_empty()) {
auto tensorLoadOp =
b.create<memref::TensorLoadOp>(funcOp.getLoc(), memref);
aliasInfo.insertNewBufferEquivalence(tensorLoadOp, bbArg);
bbArg.replaceAllUsesWith(tensorLoadOp);
}
frontBlock.eraseArgument(0);
// TODO: add support to erase aliasInfo entries if deemed necessary.
}
// 4. Rewrite the FuncOp type to buffer form.
funcOp.setType(bufferizedFuncType);
LLVM_DEBUG(DBGS() << "End bufferizeFuncOpBoundary:\n" << funcOp);
return success();
}
/// Store all functions of the `moduleOp` in `orderedFuncOps`, sorted by
/// callee-caller order (i.e. callees without callers first).
/// Store the map of FuncOp to all its callers in `callerMap`.
/// Return `failure()` if a cycle of calls is detected or if we are unable to
/// retrieve the called FuncOp from any CallOpInterface.
static LogicalResult
getFuncOpsOrderedByCalls(ModuleOp moduleOp,
SmallVectorImpl<FuncOp> &orderedFuncOps,
DenseMap<FuncOp, DenseSet<Operation *>> &callerMap) {
// For each FuncOp, the set of functions called by it (i.e. the union of
// symbols of all nested CallOpInterfaceOp).
DenseMap<FuncOp, DenseSet<FuncOp>> calledBy;
// For each FuncOp, the number of CallOpInterface it contains.
DenseMap<FuncOp, unsigned> numberCallOpsContainedInFuncOp;
WalkResult res = moduleOp.walk([&](FuncOp funcOp) -> WalkResult {
if (!funcOp.body().empty()) {
ReturnOp returnOp = getAssumedUniqueReturnOp(funcOp);
if (!returnOp)
return funcOp->emitError()
<< "cannot bufferize a FuncOp with tensors and "
"without a unique ReturnOp";
}
numberCallOpsContainedInFuncOp[funcOp] = 0;
return funcOp.walk([&](CallOpInterface callOp) -> WalkResult {
// Only support CallOp for now.
if (!isa<CallOp>(callOp.getOperation()))
return callOp->emitError() << "expected a CallOp";
FuncOp calledFunction = getCalledFunction(callOp);
assert(calledFunction && "could not retrieved called FuncOp");
auto it = callerMap.try_emplace(calledFunction, DenseSet<Operation *>{});
it.first->getSecond().insert(callOp);
if (calledBy[calledFunction].count(funcOp) == 0) {
calledBy[calledFunction].insert(funcOp);
numberCallOpsContainedInFuncOp[funcOp]++;
}
return WalkResult::advance();
});
});
if (res.wasInterrupted())
return failure();
// Iteratively remove function operation that do not call any of the
// functions remaining in the callCounter map and add them to the worklist.
while (!numberCallOpsContainedInFuncOp.empty()) {
auto it = llvm::find_if(numberCallOpsContainedInFuncOp,
[](auto entry) { return entry.getSecond() == 0; });
if (it == numberCallOpsContainedInFuncOp.end())
return moduleOp.emitOpError(
"expected callgraph to be free of circular dependencies.");
orderedFuncOps.push_back(it->getFirst());
for (auto callee : calledBy[it->getFirst()])
numberCallOpsContainedInFuncOp[callee]--;
numberCallOpsContainedInFuncOp.erase(it);
}
return success();
}
namespace {
struct LinalgComprehensiveModuleBufferize
: public LinalgComprehensiveModuleBufferizeBase<
LinalgComprehensiveModuleBufferize> {
void runOnOperation() override;
void getDependentDialects(DialectRegistry ®istry) const override {
registry.insert<linalg::LinalgDialect, memref::MemRefDialect>();
}
};
} // end namespace
static void applyEnablingTransformations(ModuleOp moduleOp) {
RewritePatternSet patterns(moduleOp.getContext());
patterns.add<GeneralizePadTensorOpPattern>(moduleOp.getContext());
(void)applyPatternsAndFoldGreedily(moduleOp, std::move(patterns));
}
static void
foreachCaller(const DenseMap<FuncOp, DenseSet<Operation *>> &callerMap,
FuncOp callee, llvm::function_ref<void(Operation *)> doit) {
auto itCallers = callerMap.find(callee);
if (itCallers == callerMap.end())
return;
for (Operation *caller : itCallers->second)
doit(caller);
}
/// Postprocess the linalg.buffer_layout annotation across function boundaries.
/// This is a purely mechanical process that may later become part of a
/// separate pass with its own layout assignment heuristic.
static void layoutPostProcessing(ModuleOp moduleOp) {
SmallVector<FuncOp> orderedFuncOps;
DenseMap<FuncOp, DenseSet<Operation *>> callerMap;
auto res = getFuncOpsOrderedByCalls(moduleOp, orderedFuncOps, callerMap);
(void)res;
assert(succeeded(res) && "unexpected getFuncOpsOrderedByCalls failure");
for (FuncOp funcOp : orderedFuncOps) {
DenseMap<Operation *, SmallVector<Value>> operandsPerCaller;
foreachCaller(callerMap, funcOp, [&](Operation *caller) {
operandsPerCaller.try_emplace(caller, SmallVector<Value>());
});
SmallVector<Type> argumentTypes;
// Iterate on each function argument and check it it was marked with a
// desired layout.
for (auto it : llvm::enumerate(funcOp.getType().getInputs())) {
int argNumber = it.index();
Type inputType = it.value();
auto memrefType = inputType.dyn_cast<MemRefType>();
auto layoutAttr = funcOp.getArgAttrOfType<AffineMapAttr>(
argNumber, LinalgDialect::kBufferLayoutAttrName);
AffineMap desiredLayoutMap =
layoutAttr ? layoutAttr.getValue() : AffineMap();
AffineMap currentLayoutMap =
memrefType ? getStridedLinearLayoutMap(memrefType) : AffineMap();
if (!memrefType || !layoutAttr || desiredLayoutMap == currentLayoutMap) {
argumentTypes.push_back(inputType);
foreachCaller(callerMap, funcOp, [&](Operation *caller) {
operandsPerCaller.find(caller)->getSecond().push_back(
caller->getOperand(argNumber));
});
continue;
}
// Compute the buffer type with desired layout and add to input argument
// types.
MemRefType desiredMemrefType = MemRefType::get(
memrefType.getShape(), memrefType.getElementType(), desiredLayoutMap);
argumentTypes.push_back(desiredMemrefType);
// If funcOp's body is not empty, change the bbArg type and propagate.
if (!funcOp.body().empty()) {
BlockArgument bbArg = funcOp.getArgument(argNumber);
bbArg.setType(desiredMemrefType);
OpBuilder b(bbArg.getContext());
b.setInsertionPointToStart(bbArg.getOwner());
// Cast back to the original memrefType and let it canonicalize.
Value cast =
b.create<memref::CastOp>(funcOp.getLoc(), memrefType, bbArg);
bbArg.replaceAllUsesExcept(cast, cast.getDefiningOp());
}
// Cast to desired buffer type on all callers to `funcOp`.
// TODO: on the callee side, this may even have to trigger a copy to
// change the layout. For now let the memref::CastOp fail to verify in
// such cases.
auto castArg = [&](Operation *caller) {
OpBuilder b(caller);
Value newOperand = b.create<memref::CastOp>(
funcOp.getLoc(), desiredMemrefType, caller->getOperand(argNumber));
operandsPerCaller.find(caller)->getSecond().push_back(newOperand);
};
foreachCaller(callerMap, funcOp, castArg);
}
// Set operands with cast buffer on all callers to `funcOp`.
foreachCaller(callerMap, funcOp, [&](Operation *caller) {
caller->setOperands(operandsPerCaller.lookup(caller));
});
// Finally set the funcOp type to update the arguments.
auto newFuncType = FunctionType::get(moduleOp.getContext(), argumentTypes,
funcOp.getType().getResults());
funcOp.setType(newFuncType);
}
}
void LinalgComprehensiveModuleBufferize::runOnOperation() {
ModuleOp moduleOp = getOperation();
applyEnablingTransformations(moduleOp);
SmallVector<FuncOp> orderedFuncOps;
DenseMap<FuncOp, DenseSet<Operation *>> callerMap;
DenseMap<FuncOp, FunctionType> bufferizedFunctionTypes;
if (failed(getFuncOpsOrderedByCalls(moduleOp, orderedFuncOps, callerMap)))
return signalPassFailure();
GlobalCreator globalCreator(moduleOp);
DominanceInfo domInfo(moduleOp);
BufferizationAliasInfo aliasInfo(moduleOp);
// Interestingly, all function args that are not visible outside of a module
// can be fully bufferized inplace by guaranteeing the CallOp is bufferized
// inplace. Therefore, we just bufferize funcOp as if none of its results were
// inplaceable, detect which operands are cloned internally and decide what to
// do at call sites.
for (FuncOp funcOp : orderedFuncOps) {
// No body => no analysis.
if (funcOp.body().empty())
continue;
// In a first approximation:
// =========================
// If the function is called, we can allocate on the caller side which lets
// us force inplace arguments at function boundaries.
// TODO: do not rely on this behavior.
if (callerMap.find(funcOp) != callerMap.end())
for (BlockArgument bbArg : funcOp.getArguments())
if (bbArg.getType().isa<TensorType>())
setInPlaceFuncArgument(bbArg);
// If the analysis fails, just return.
if (failed(inPlaceAnalysisFuncOpBody(funcOp, aliasInfo, domInfo))) {
signalPassFailure();
return;
}
// Bufferization phase.
if (!testAnalysisOnly) {
BlockAndValueMapping tensorToBufferMap;
if (failed(bufferizeFuncOpInternals(funcOp, tensorToBufferMap, aliasInfo,
bufferizedFunctionTypes,
globalCreator))) {
signalPassFailure();
return;
}
}
}
// Don't drop the attributes if we only want to report the analysis.
if (testAnalysisOnly)
return;
for (FuncOp funcOp : orderedFuncOps) {
// Note: It would be good to apply cleanups here but we cannot as aliasInfo
// would be invalidated.
if (failed(bufferizeFuncOpBoundary(funcOp, aliasInfo,
bufferizedFunctionTypes))) {
signalPassFailure();
return;
}
}
// Perform a post-processing pass of layout modification at function boundary
// according to the kBufferLayoutAttrName.
layoutPostProcessing(moduleOp);
// Post-pass cleanup of inplaceable and buffer_layout attributes.
moduleOp.walk(
[&](Operation *op) { op->removeAttr(kInPlaceResultsAttrName); });
moduleOp.walk([&](FuncOp op) {
for (BlockArgument bbArg : op.getArguments())
removeBufferizationFuncArguments(bbArg);
});
OpPassManager cleanupPipeline(OpPassManager("module"));
cleanupPipeline.addPass(createCanonicalizerPass());
cleanupPipeline.addPass(createCSEPass());
cleanupPipeline.addPass(createLoopInvariantCodeMotionPass());
(void)runPipeline(cleanupPipeline, moduleOp);
}
std::unique_ptr<Pass> mlir::createLinalgComprehensiveModuleBufferizePass() {
return std::make_unique<LinalgComprehensiveModuleBufferize>();
}
| 42.577495 | 80 | 0.666883 | [
"object",
"shape",
"vector",
"model"
] |
b4f8d21ad871795a792d1916a13472a567050e96 | 7,581 | cpp | C++ | Riptide Remastered/Riptide-Remastered/Cheat/InventoryChanger/InventoryChanger.cpp | Baseult/Riptide-Remastered | a8abef14a266b10a4831562ad3e6f21b78f181cc | [
"MIT"
] | 14 | 2019-02-12T18:44:12.000Z | 2022-01-02T20:23:16.000Z | pChanger/Cheat/InventoryChanger/InventoryChanger.cpp | TimDaHacka/pChanger | 03c957fffbce4e8233d49d3c73f9787b70f32cdc | [
"MIT"
] | 5 | 2019-05-16T17:55:47.000Z | 2020-10-29T18:42:33.000Z | Riptide Remastered/Riptide-Remastered/Cheat/InventoryChanger/InventoryChanger.cpp | Baseult/Riptide-Remastered | a8abef14a266b10a4831562ad3e6f21b78f181cc | [
"MIT"
] | 6 | 2019-02-04T17:53:50.000Z | 2021-09-29T15:31:23.000Z | #include "InventoryChanger.h"
#include <vector>
void CInventoryChanger::PostRetrieveMessage(uint32_t* punMsgType, void* pubDest, uint32_t cubDest, uint32_t* pcubMsgSize)
{
uint32_t MessageType = *punMsgType & 0x7FFFFFFF;
if (MessageType == k_EMsgGCCStrike15_v2_MatchmakingGC2ClientHello && Settings::ProfileChanger::enabled) {
CMsgGCCStrike15_v2_MatchmakingGC2ClientHello Message;
try
{
if (!Message.ParsePartialFromArray((void*)((DWORD)pubDest + 8), *pcubMsgSize - 8))
return;
}
catch (...)
{
return;
}
if (Settings::ProfileChanger::ban != 0) {
Message.set_penalty_reason(Settings::ProfileChanger::ban);
Message.set_penalty_seconds(Settings::ProfileChanger::time);
}
if (Settings::ProfileChanger::level != 0) {
Message.set_player_level(Settings::ProfileChanger::level);
}
if (Settings::ProfileChanger::xp != 0) {
Message.set_player_cur_xp(Settings::ProfileChanger::xp);
}
PlayerRankingInfo* Ranking = Message.mutable_ranking();
Ranking->set_account_id(Interfaces::SteamUser()->GetSteamID().GetAccountID());
if (Settings::ProfileChanger::rank_id != 0) {
Ranking->set_rank_id(Settings::ProfileChanger::rank_id);
}
if (Settings::ProfileChanger::wins != 0) {
Ranking->set_wins(Settings::ProfileChanger::wins);
}
PlayerCommendationInfo* Commendation = Message.mutable_commendation();
if (Settings::ProfileChanger::cmd_friendly != 0) {
Commendation->set_cmd_friendly(Settings::ProfileChanger::cmd_friendly);
}
if (Settings::ProfileChanger::cmd_leader != 0) {
Commendation->set_cmd_leader(Settings::ProfileChanger::cmd_leader);
}
if (Settings::ProfileChanger::cmd_teaching != 0) {
Commendation->set_cmd_teaching(Settings::ProfileChanger::cmd_teaching);
}
if ((uint32_t)Message.ByteSize() <= cubDest - 8)
{
Message.SerializeToArray((void*)((DWORD)pubDest + 8), Message.ByteSize());
*pcubMsgSize = Message.ByteSize() + 8;
}
}
if (MessageType == k_EMsgGCClientWelcome) {
CMsgClientWelcome Message;
try
{
if (!Message.ParsePartialFromArray((void*)((DWORD)pubDest + 8), *pcubMsgSize - 8))
return;
}
catch (...)
{
return;
}
if (Message.outofdate_subscribed_caches_size() <= 0)
return;
CMsgSOCacheSubscribed* Cache = Message.mutable_outofdate_subscribed_caches(0);
for (int i = 0; i < Cache->objects_size(); i++)
{
CMsgSOCacheSubscribed::SubscribedType* Object = Cache->mutable_objects(i);
if (!Object->has_type_id())
continue;
if (Object->type_id() == 1) {
for (int j = 0; j < Object->object_data_size(); j++)
{
std::string* ObjectData = Object->mutable_object_data(j);
CSOEconItem Item;
if (!Item.ParseFromArray((void*)const_cast<char*>(ObjectData->data()), ObjectData->size()))
continue;
if (Item.equipped_state_size() <= 0)
continue;
if (Settings::MedalChanger::equipped_medal_override)
{
CSOEconItemEquipped* EquippedState = Item.mutable_equipped_state(0);
if (EquippedState->new_class() == 0 && EquippedState->new_slot() == 55)
{
Item.clear_equipped_state();
ObjectData->resize(Item.ByteSize());
Item.SerializeToArray((void*)const_cast<char*>(ObjectData->data()), Item.ByteSize());
}
}
}
ApplyMedals(Object);
ApplySkins(Object);
}
}
if ((uint32_t)Message.ByteSize() <= cubDest - 8)
{
Message.SerializeToArray((void*)((DWORD)pubDest + 8), Message.ByteSize());
*pcubMsgSize = Message.ByteSize() + 8;
}
}
}
bool CInventoryChanger::PreSendMessage(uint32_t &unMsgType, void* pubData, uint32_t &cubData)
{
if (!Settings::InventoryChanger::enabled)
return true;
uint32_t MessageType = unMsgType & 0x7FFFFFFF;
if (MessageType == k_EMsgGCAdjustItemEquippedState) {
CMsgAdjustItemEquippedState Message;
try
{
if (!Message.ParsePartialFromArray((void*)((DWORD)pubData + 8), cubData - 8))
return true;
}
catch (...)
{
return true;
}
if (!Message.has_item_id() || !Message.has_new_class() || !Message.has_new_slot())
return true;
uint32_t item_id = (uint32_t)Message.item_id() - 20000;
if (item_id < 1 || item_id > Settings::InventoryChanger::weapons.size()) {
return true;
}
auto weapon = Settings::InventoryChanger::weapons[item_id - 1];
g_SkinChangerCfg[weapon.itemDefinitionIndex].flFallbackWear = weapon.wear;
g_SkinChangerCfg[weapon.itemDefinitionIndex].iItemDefinitionIndex = weapon.itemDefinitionIndex;
g_SkinChangerCfg[weapon.itemDefinitionIndex].nFallbackPaintKit = weapon.paintKit;
ForceFullUpdate();
return false;
}
return true;
}
void CInventoryChanger::ApplySkins(CMsgSOCacheSubscribed::SubscribedType* pInventoryCacheObject)
{
if (!Settings::InventoryChanger::enabled) {
return;
}
int c = 20001;
for (auto weapon : Settings::InventoryChanger::weapons) {
CSOEconItem Skin;
Skin.set_id(c);
Skin.set_account_id(Interfaces::SteamUser()->GetSteamID().GetAccountID());
Skin.set_def_index(weapon.itemDefinitionIndex);
Skin.set_inventory(c);
Skin.set_origin(24);
Skin.set_quantity(1);
Skin.set_level(1);
Skin.set_style(0);
Skin.set_flags(0);
Skin.set_in_use(false);
Skin.set_original_id(0);
Skin.set_rarity(weapon.rarity);
Skin.set_quality(0);
auto PaintKitAttribute = Skin.add_attribute();
float PaintKitAttributeValue = (float)weapon.paintKit;
PaintKitAttribute->set_def_index(6);
PaintKitAttribute->set_value_bytes(&PaintKitAttributeValue, 4);
auto SeedAttribute = Skin.add_attribute();
float SeedAttributeValue = (float)weapon.seed;
SeedAttribute->set_def_index(7);
SeedAttribute->set_value_bytes(&SeedAttributeValue, 4);
auto WearAttribute = Skin.add_attribute();
float WearAttributeValue = weapon.wear;
WearAttribute->set_def_index(8);
WearAttribute->set_value_bytes(&WearAttributeValue, 4);
pInventoryCacheObject->add_object_data(Skin.SerializeAsString());
c++;
}
}
void CInventoryChanger::ApplyMedals(CMsgSOCacheSubscribed::SubscribedType* pInventoryCacheObject)
{
if (!Settings::MedalChanger::enabled) {
return;
}
int c = 10001;
for (uint32_t MedalIndex : Settings::MedalChanger::medals)
{
CSOEconItem Medal;
Medal.set_account_id(Interfaces::SteamUser()->GetSteamID().GetAccountID());
Medal.set_origin(9);
Medal.set_rarity(6);
Medal.set_quantity(1);
Medal.set_quality(4);
Medal.set_level(1);
CSOEconItemAttribute* TimeAcquiredAttribute = Medal.add_attribute();
uint32_t TimeAcquiredAttributeValue = 0;
TimeAcquiredAttribute->set_def_index(222);
TimeAcquiredAttribute->set_value_bytes(&TimeAcquiredAttributeValue, 4);
Medal.set_def_index(MedalIndex);
Medal.set_inventory(c);
Medal.set_id(c);
if (Settings::MedalChanger::equipped_medal_override && Settings::MedalChanger::equipped_medal == MedalIndex)
{
CSOEconItemEquipped* EquippedState = Medal.add_equipped_state();
EquippedState->set_new_class(0);
EquippedState->set_new_slot(55);
}
pInventoryCacheObject->add_object_data(Medal.SerializeAsString());
c++;
}
}
| 9.27907 | 121 | 0.666271 | [
"object",
"vector"
] |
b4f9d03d6c7ed70301066969dd7bfc04a6dcaeb0 | 54,867 | cpp | C++ | mp/src/game/shared/predictioncopy.cpp | ozxybox/source-sdk-2013 | 17dbb5ca5c2aa0e9cfc5360b098833d8b009e79c | [
"Unlicense"
] | 4 | 2022-03-08T04:03:06.000Z | 2022-03-09T06:51:54.000Z | mp/src/game/shared/predictioncopy.cpp | ozxybox/source-sdk-2013 | 17dbb5ca5c2aa0e9cfc5360b098833d8b009e79c | [
"Unlicense"
] | null | null | null | mp/src/game/shared/predictioncopy.cpp | ozxybox/source-sdk-2013 | 17dbb5ca5c2aa0e9cfc5360b098833d8b009e79c | [
"Unlicense"
] | 1 | 2022-03-17T12:22:45.000Z | 2022-03-17T12:22:45.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "cbase.h"
#if !defined( NO_ENTITY_PREDICTION )
#if defined( CLIENT_DLL )
#include "igamesystem.h"
#endif
#include <memory.h>
#include <stdarg.h>
#include "tier0/dbg.h"
#include "tier1/strtools.h"
#include "predictioncopy.h"
#include "engine/ivmodelinfo.h"
#include "tier1/fmtstr.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
// --------------------------------------------------------------
//
// CSave
//
// --------------------------------------------------------------
static const char *g_FieldTypes[ FIELD_TYPECOUNT ] =
{
"FIELD_VOID", // FIELD_VOID
"FIELD_FLOAT", // FIELD_FLOAT
"FIELD_STRING", // FIELD_STRING
"FIELD_VECTOR", // FIELD_VECTOR
"FIELD_QUATERNION", // FIELD_QUATERNION
"FIELD_INTEGER", // FIELD_INTEGER
"FIELD_BOOLEAN", // FIELD_BOOLEAN
"FIELD_SHORT", // FIELD_SHORT
"FIELD_CHARACTER", // FIELD_CHARACTER
"FIELD_COLOR32", // FIELD_COLOR32
"FIELD_EMBEDDED", // FIELD_EMBEDDED (handled specially)
"FIELD_CUSTOM", // FIELD_CUSTOM (handled specially)
"FIELD_CLASSPTR", // FIELD_CLASSPTR
"FIELD_EHANDLE", // FIELD_EHANDLE
"FIELD_EDICT", // FIELD_EDICT
"FIELD_POSITION_VECTOR",// FIELD_POSITION_VECTOR
"FIELD_TIME", // FIELD_TIME
"FIELD_TICK", // FIELD_TICK
"FIELD_MODELNAME", // FIELD_MODELNAME
"FIELD_SOUNDNAME", // FIELD_SOUNDNAME
"FIELD_INPUT", // FIELD_INPUT (uses custom type)
"FIELD_FUNCTION", // FIELD_FUNCTION
"FIELD_VMATRIX",
"FIELD_VMATRIX_WORLDSPACE",
"FIELD_MATRIX3X4_WORLDSPACE",
"FIELD_INTERVAL" // FIELD_INTERVAL
"FIELD_MODELINDEX" // FIELD_MODELINDEX
};
CPredictionCopy::CPredictionCopy( int type, void *dest, bool dest_packed, void const *src, bool src_packed,
bool counterrors /*= false*/, bool reporterrors /*= false*/, bool performcopy /*= true*/,
bool describefields /*= false*/, FN_FIELD_COMPARE func /*= NULL*/ )
{
m_nType = type;
m_pDest = dest;
m_pSrc = src;
m_nDestOffsetIndex = dest_packed ? TD_OFFSET_PACKED : TD_OFFSET_NORMAL;
m_nSrcOffsetIndex = src_packed ? TD_OFFSET_PACKED : TD_OFFSET_NORMAL;
m_bErrorCheck = counterrors;
m_bReportErrors = reporterrors;
m_bPerformCopy = performcopy;
m_bDescribeFields = describefields;
m_pCurrentField = NULL;
m_pCurrentMap = NULL;
m_pCurrentClassName = NULL;
m_bShouldReport = false;
m_bShouldDescribe = false;
m_nErrorCount = 0;
m_FieldCompareFunc = func;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *fmt -
// ... -
//-----------------------------------------------------------------------------
void CPredictionCopy::ReportFieldsDiffer( const char *fmt, ... )
{
++m_nErrorCount;
if ( !m_bShouldReport )
return;
if ( m_bDescribeFields && m_FieldCompareFunc )
return;
Assert( m_pCurrentMap );
Assert( m_pCurrentClassName );
const char *fieldname = "empty";
int flags = 0;
if ( m_pCurrentField )
{
flags = m_pCurrentField->flags;
fieldname = m_pCurrentField->fieldName ? m_pCurrentField->fieldName : "NULL";
}
va_list argptr;
char data[ 4096 ];
int len;
va_start(argptr, fmt);
len = Q_vsnprintf(data, sizeof( data ), fmt, argptr);
va_end(argptr);
if ( m_nErrorCount == 1 )
{
Msg( "\n" );
}
Msg( "%03i %s::%s - %s",
m_nErrorCount,
m_pCurrentClassName,
fieldname,
data );
m_bShouldReport = false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *fmt -
// ... -
//-----------------------------------------------------------------------------
void CPredictionCopy::DescribeFields( difftype_t dt, const char *fmt, ... )
{
if ( !m_bShouldDescribe )
return;
if ( !m_FieldCompareFunc )
return;
Assert( m_pCurrentMap );
Assert( m_pCurrentClassName );
const char *fieldname = "empty";
int flags = 0;
if ( m_pCurrentField )
{
flags = m_pCurrentField->flags;
fieldname = m_pCurrentField->fieldName ? m_pCurrentField->fieldName : "NULL";
}
va_list argptr;
char data[ 4096 ];
int len;
va_start(argptr, fmt);
len = Q_vsnprintf(data, sizeof( data ), fmt, argptr);
va_end(argptr);
bool isnetworked = ( flags & FTYPEDESC_INSENDTABLE ) ? true : false;
bool isnoterrorchecked = ( flags & FTYPEDESC_NOERRORCHECK ) ? true : false;
( *m_FieldCompareFunc )(
m_pCurrentClassName,
fieldname,
g_FieldTypes[ m_pCurrentField->fieldType ],
isnetworked,
isnoterrorchecked,
dt != IDENTICAL ? true : false,
dt == WITHINTOLERANCE ? true : false,
data
);
m_bShouldDescribe = false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CPredictionCopy::CanCheck( void )
{
Assert( m_pCurrentField );
if ( m_pCurrentField->flags & FTYPEDESC_NOERRORCHECK )
{
return false;
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : size -
// *outdata -
// *indata -
//-----------------------------------------------------------------------------
/*
void CPredictionCopy::CopyData( difftype_t dt, int size, char *outdata, const char *indata )
{
if ( !m_bPerformCopy )
return;
if ( dt == IDENTICAL )
return;
memcpy( outdata, indata, size );
}
*/
CPredictionCopy::difftype_t CPredictionCopy::CompareData( int size, char *outdata, const char *indata )
{
if ( !m_bErrorCheck )
return DIFFERS;
if ( CanCheck() )
{
if ( memcmp( outdata, indata, size ) )
{
return DIFFERS;
}
else
{
// No difference, so no need to copy
return IDENTICAL;
}
}
// Fields differ
return IDENTICAL;
}
void CPredictionCopy::DescribeData( difftype_t dt, int size, char *outdata, const char *indata )
{
if ( !m_bErrorCheck )
return;
if ( dt == DIFFERS )
{
ReportFieldsDiffer( "binary data differs (%i bytes)\n", size );
}
DescribeFields( dt, "binary (%i bytes)\n", size );
}
void CPredictionCopy::WatchData( difftype_t dt, int size, char *outdata, const char *indata )
{
if ( m_pWatchField != m_pCurrentField )
return;
WatchMsg( "binary (%i bytes)", size );
}
void CPredictionCopy::DescribeShort( difftype_t dt, short *outvalue, const short *invalue, int count )
{
if ( !m_bErrorCheck )
return;
if ( dt == DIFFERS )
{
int i = 0;
ReportFieldsDiffer( "short differs (net %i pred %i) diff(%i)\n", (int)(invalue[i]), (int)(outvalue[i]), (int)(outvalue[i] - invalue[i]) );
}
DescribeFields( dt, "short (%i)\n", (int)(outvalue[0]) );
}
void CPredictionCopy::WatchShort( difftype_t dt, short *outvalue, const short *invalue, int count )
{
if ( m_pWatchField != m_pCurrentField )
return;
WatchMsg( "short (%i)", (int)(outvalue[0]) );
}
#if defined( CLIENT_DLL )
#include "cdll_int.h"
#endif
void CPredictionCopy::DescribeInt( difftype_t dt, int *outvalue, const int *invalue, int count )
{
if ( !m_bErrorCheck )
return;
if ( dt == DIFFERS )
{
int i = 0;
ReportFieldsDiffer( "int differs (net %i pred %i) diff(%i)\n", invalue[i], outvalue[i], outvalue[i] - invalue[i] );
}
#if defined( CLIENT_DLL )
bool described = false;
if ( m_pCurrentField->flags & FTYPEDESC_MODELINDEX )
{
int modelindex = outvalue[0];
model_t const *m = modelinfo->GetModel( modelindex );
if ( m )
{
described = true;
char shortfile[ 512 ];
shortfile[ 0 ] = 0;
Q_FileBase( modelinfo->GetModelName( m ), shortfile, sizeof( shortfile ) );
DescribeFields( dt, "integer (%i->%s)\n", outvalue[0], shortfile );
}
}
if ( !described )
{
DescribeFields( dt, "integer (%i)\n", outvalue[0] );
}
#else
DescribeFields( dt, "integer (%i)\n", outvalue[0] );
#endif
}
void CPredictionCopy::WatchInt( difftype_t dt, int *outvalue, const int *invalue, int count )
{
if ( m_pWatchField != m_pCurrentField )
return;
#if defined( CLIENT_DLL )
bool described = false;
if ( m_pCurrentField->flags & FTYPEDESC_MODELINDEX )
{
int modelindex = outvalue[0];
model_t const *m = modelinfo->GetModel( modelindex );
if ( m )
{
described = true;
char shortfile[ 512 ];
shortfile[ 0 ] = 0;
Q_FileBase( modelinfo->GetModelName( m ), shortfile, sizeof( shortfile ) );
WatchMsg( "integer (%i->%s)", outvalue[0], shortfile );
}
}
if ( !described )
{
WatchMsg( "integer (%i)", outvalue[0] );
}
#else
WatchMsg( "integer (%i)", outvalue[0] );
#endif
}
void CPredictionCopy::DescribeBool( difftype_t dt, bool *outvalue, const bool *invalue, int count )
{
if ( !m_bErrorCheck )
return;
if ( dt == DIFFERS )
{
int i = 0;
ReportFieldsDiffer( "bool differs (net %s pred %s)\n", (invalue[i]) ? "true" : "false", (outvalue[i]) ? "true" : "false" );
}
DescribeFields( dt, "bool (%s)\n", (outvalue[0]) ? "true" : "false" );
}
void CPredictionCopy::WatchBool( difftype_t dt, bool *outvalue, const bool *invalue, int count )
{
if ( m_pWatchField != m_pCurrentField )
return;
WatchMsg( "bool (%s)", (outvalue[0]) ? "true" : "false" );
}
void CPredictionCopy::DescribeFloat( difftype_t dt, float *outvalue, const float *invalue, int count )
{
if ( !m_bErrorCheck )
return;
if ( dt == DIFFERS )
{
int i = 0;
ReportFieldsDiffer( "float differs (net %f pred %f) diff(%f)\n", invalue[ i ], outvalue[ i ], outvalue[ i ] - invalue[ i ] );
}
DescribeFields( dt, "float (%f)\n", outvalue[ 0 ] );
}
void CPredictionCopy::WatchFloat( difftype_t dt, float *outvalue, const float *invalue, int count )
{
if ( m_pWatchField != m_pCurrentField )
return;
WatchMsg( "float (%f)", outvalue[ 0 ] );
}
void CPredictionCopy::DescribeString( difftype_t dt, char *outstring, const char *instring )
{
if ( !m_bErrorCheck )
return;
if ( dt == DIFFERS )
{
ReportFieldsDiffer( "string differs (net %s pred %s)\n", instring, outstring );
}
DescribeFields( dt, "string (%s)\n", outstring );
}
void CPredictionCopy::WatchString( difftype_t dt, char *outstring, const char *instring )
{
if ( m_pWatchField != m_pCurrentField )
return;
WatchMsg( "string (%s)", outstring );
}
void CPredictionCopy::DescribeVector( difftype_t dt, Vector& outValue, const Vector &inValue )
{
if ( !m_bErrorCheck )
return;
if ( dt == DIFFERS )
{
Vector delta = outValue - inValue;
ReportFieldsDiffer( "vec differs (net %f %f %f - pred %f %f %f) delta(%f %f %f)\n",
inValue.x, inValue.y, inValue.z,
outValue.x, outValue.y, outValue.z,
delta.x, delta.y, delta.z );
}
DescribeFields( dt, "vector (%f %f %f)\n",
outValue.x, outValue.y, outValue.z );
}
void CPredictionCopy::DescribeVector( difftype_t dt, Vector* outValue, const Vector *inValue, int count )
{
if ( !m_bErrorCheck )
return;
if ( dt == DIFFERS )
{
int i = 0;
Vector delta = outValue[ i ] - inValue[ i ];
ReportFieldsDiffer( "vec[] differs (1st diff) (net %f %f %f - pred %f %f %f) delta(%f %f %f)\n",
inValue[i].x, inValue[i].y, inValue[i].z,
outValue[i].x, outValue[i].y, outValue[i].z,
delta.x, delta.y, delta.z );
}
DescribeFields( dt, "vector (%f %f %f)\n",
outValue[0].x, outValue[0].y, outValue[0].z );
}
void CPredictionCopy::WatchVector( difftype_t dt, Vector& outValue, const Vector &inValue )
{
if ( m_pWatchField != m_pCurrentField )
return;
WatchMsg( "vector (%f %f %f)", outValue.x, outValue.y, outValue.z );
}
void CPredictionCopy::WatchVector( difftype_t dt, Vector* outValue, const Vector *inValue, int count )
{
if ( m_pWatchField != m_pCurrentField )
return;
WatchMsg( "vector (%f %f %f)", outValue[0].x, outValue[0].y, outValue[0].z );
}
void CPredictionCopy::DescribeQuaternion( difftype_t dt, Quaternion& outValue, const Quaternion &inValue )
{
if ( !m_bErrorCheck )
return;
if ( dt == DIFFERS )
{
Quaternion delta;
for ( int i = 0; i < 4; i++ )
{
delta[i] = outValue[i] - inValue[i];
}
ReportFieldsDiffer( "quaternion differs (net %f %f %f %f - pred %f %f %f %f) delta(%f %f %f %f)\n",
inValue[0], inValue[1], inValue[2], inValue[3],
outValue[0], outValue[1], outValue[2], outValue[3],
delta[0], delta[1], delta[2], delta[3] );
}
DescribeFields( dt, "quaternion (%f %f %f %f)\n",
outValue[0], outValue[1], outValue[2], outValue[3] );
}
void CPredictionCopy::DescribeQuaternion( difftype_t dt, Quaternion* outValue, const Quaternion *inValue, int count )
{
if ( !m_bErrorCheck )
return;
if ( dt == DIFFERS )
{
int i = 0;
Quaternion delta;
for ( int j = 0; j < 4; j++ )
{
delta[j] = outValue[i][j] - inValue[i][j];
}
ReportFieldsDiffer( "quaternion[] differs (1st diff) (net %f %f %f %f - pred %f %f %f %f) delta(%f %f %f %f)\n",
(float)inValue[i][0], (float)inValue[i][1], (float)inValue[i][2], (float)inValue[i][3],
(float)outValue[i][0], (float)outValue[i][1], (float)outValue[i][2], (float)outValue[i][3],
delta[0], delta[1], delta[2], delta[3] );
}
DescribeFields( dt, "quaternion (%f %f %f %f)\n",
(float)outValue[0][0], (float)outValue[0][1], (float)outValue[0][2], (float)outValue[0][3] );
}
void CPredictionCopy::WatchQuaternion( difftype_t dt, Quaternion& outValue, const Quaternion &inValue )
{
if ( m_pWatchField != m_pCurrentField )
return;
WatchMsg( "quaternion (%f %f %f %f)", (float)outValue[0], (float)outValue[1], (float)outValue[2], (float)outValue[3] );
}
void CPredictionCopy::WatchQuaternion( difftype_t dt, Quaternion* outValue, const Quaternion *inValue, int count )
{
if ( m_pWatchField != m_pCurrentField )
return;
WatchMsg( "quaternion (%f %f %f %f)", outValue[0][0], outValue[0][1], outValue[0][2], outValue[0][3] );
}
void CPredictionCopy::DescribeEHandle( difftype_t dt, EHANDLE *outvalue, EHANDLE const *invalue, int count )
{
if ( !m_bErrorCheck )
return;
if ( dt == DIFFERS )
{
int i = 0;
ReportFieldsDiffer( "EHandles differ (net) 0x%p (pred) 0x%p\n", (void const *)invalue[ i ].Get(), (void *)outvalue[ i ].Get() );
}
#if defined( CLIENT_DLL )
C_BaseEntity *ent = outvalue[0].Get();
if ( ent )
{
const char *classname = ent->GetClassname();
if ( !classname[0] )
{
classname = typeid( *ent ).name();
}
DescribeFields( dt, "EHandle (0x%p->%s)", (void *)outvalue[ 0 ], classname );
}
else
{
DescribeFields( dt, "EHandle (NULL)" );
}
#else
DescribeFields( dt, "EHandle (0x%p)", (void *)outvalue[ 0 ] );
#endif
}
void CPredictionCopy::WatchEHandle( difftype_t dt, EHANDLE *outvalue, EHANDLE const *invalue, int count )
{
if ( m_pWatchField != m_pCurrentField )
return;
#if defined( CLIENT_DLL )
C_BaseEntity *ent = outvalue[0].Get();
if ( ent )
{
const char *classname = ent->GetClassname();
if ( !classname[0] )
{
classname = typeid( *ent ).name();
}
WatchMsg( "EHandle (0x%p->%s)", (void *)outvalue[ 0 ], classname );
}
else
{
WatchMsg( "EHandle (NULL)" );
}
#else
WatchMsg( "EHandle (0x%p)", (void *)outvalue[ 0 ] );
#endif
}
void CPredictionCopy::CopyShort( difftype_t dt, short *outvalue, const short *invalue, int count )
{
if ( !m_bPerformCopy )
return;
if ( dt == IDENTICAL )
return;
CopyData( dt, sizeof(short) * count, (char *)outvalue, (const char *)invalue );
}
CPredictionCopy::difftype_t CPredictionCopy::CompareShort( short *outvalue, const short *invalue, int count )
{
if ( !m_bErrorCheck )
return DIFFERS;
if ( CanCheck() )
{
for ( int i = 0; i < count; i++ )
{
if ( outvalue[ i ] == invalue[ i ] )
continue;
return DIFFERS;
}
}
return IDENTICAL;
}
void CPredictionCopy::CopyInt( difftype_t dt, int *outvalue, const int *invalue, int count )
{
if ( !m_bPerformCopy )
return;
if ( dt == IDENTICAL )
return;
CopyData( dt, sizeof(int) * count, (char *)outvalue, (const char *)invalue );
}
CPredictionCopy::difftype_t CPredictionCopy::CompareInt( int *outvalue, const int *invalue, int count )
{
if ( !m_bErrorCheck )
return DIFFERS;
if ( CanCheck() )
{
for ( int i = 0; i < count; i++ )
{
if ( outvalue[ i ] == invalue[ i ] )
continue;
ReportFieldsDiffer( "int differs (net %i pred %i) diff(%i)\n", invalue[i], outvalue[i], outvalue[i] - invalue[i] );
return DIFFERS;
}
}
return IDENTICAL;
}
void CPredictionCopy::CopyBool( difftype_t dt, bool *outvalue, const bool *invalue, int count )
{
if ( !m_bPerformCopy )
return;
if ( dt == IDENTICAL )
return;
CopyData( dt, sizeof( bool ) * count, (char *)outvalue, (const char *)invalue );
}
CPredictionCopy::difftype_t CPredictionCopy::CompareBool( bool *outvalue, const bool *invalue, int count )
{
if ( !m_bErrorCheck )
return DIFFERS;
if ( CanCheck() )
{
for ( int i = 0; i < count; i++ )
{
if ( outvalue[ i ] == invalue[ i ] )
continue;
return DIFFERS;
}
}
return IDENTICAL;
}
void CPredictionCopy::CopyFloat( difftype_t dt, float *outvalue, const float *invalue, int count )
{
if ( !m_bPerformCopy )
return;
if ( dt == IDENTICAL )
return;
CopyData( dt, sizeof( float ) * count, (char *)outvalue, (const char *)invalue );
}
CPredictionCopy::difftype_t CPredictionCopy::CompareFloat( float *outvalue, const float *invalue, int count )
{
if ( !m_bErrorCheck )
return DIFFERS;
difftype_t retval = IDENTICAL;
if ( CanCheck() )
{
float tolerance = m_pCurrentField->fieldTolerance;
Assert( tolerance >= 0.0f );
bool usetolerance = tolerance > 0.0f;
for ( int i = 0; i < count; i++ )
{
if ( outvalue[ i ] == invalue[ i ] )
continue;
if ( usetolerance &&
( fabs( outvalue[ i ] - invalue[ i ] ) <= tolerance ) )
{
retval = WITHINTOLERANCE;
continue;
}
return DIFFERS;
}
}
return retval;
}
void CPredictionCopy::CopyString( difftype_t dt, char *outstring, const char *instring )
{
if ( !m_bPerformCopy )
return;
if ( dt == IDENTICAL )
return;
CopyData( dt, Q_strlen( instring ) + 1, (char *)outstring, (const char *)instring );
}
CPredictionCopy::difftype_t CPredictionCopy::CompareString( char *outstring, const char *instring )
{
if ( !m_bErrorCheck )
return DIFFERS;
if ( CanCheck() )
{
if ( Q_strcmp( outstring, instring ) )
{
return DIFFERS;
}
}
return IDENTICAL;
}
void CPredictionCopy::CopyVector( difftype_t dt, Vector& outValue, const Vector &inValue )
{
CopyVector( dt, &outValue, &inValue, 1 );
}
void CPredictionCopy::CopyQuaternion( difftype_t dt, Quaternion& outValue, const Quaternion &inValue )
{
CopyQuaternion( dt, &outValue, &inValue, 1 );
}
CPredictionCopy::difftype_t CPredictionCopy::CompareVector( Vector& outValue, const Vector &inValue )
{
if ( !m_bErrorCheck )
return DIFFERS;
if ( CanCheck() )
{
float tolerance = m_pCurrentField->fieldTolerance;
Assert( tolerance >= 0.0f );
if ( outValue != inValue && ( tolerance > 0.0f ) )
{
Vector delta = outValue - inValue;
if ( fabs( delta.x ) <= tolerance &&
fabs( delta.y ) <= tolerance &&
fabs( delta.z ) <= tolerance )
{
return WITHINTOLERANCE;
}
}
return DIFFERS;
}
return IDENTICAL;
}
static int QuaternionCompare (const Quaternion& q1, const Quaternion& q2 )
{
for ( int i = 0; i < 4; i++ )
{
if ( q1[i] != q2[i] )
return 0;
}
return 1;
}
CPredictionCopy::difftype_t CPredictionCopy::CompareQuaternion( Quaternion& outValue, const Quaternion &inValue )
{
if ( !m_bErrorCheck )
return DIFFERS;
if ( CanCheck() )
{
float tolerance = m_pCurrentField->fieldTolerance;
Assert( tolerance >= 0.0f );
if ( QuaternionCompare( outValue, inValue ) == 0
&& ( tolerance > 0.0f ) )
{
Quaternion delta;
for ( int j = 0; j < 4; j++ )
{
delta[j] = outValue[j] - inValue[j];
}
if ( fabs( delta[0] ) <= tolerance &&
fabs( delta[1] ) <= tolerance &&
fabs( delta[2] ) <= tolerance &&
fabs( delta[3] ) <= tolerance )
{
return WITHINTOLERANCE;
}
}
return DIFFERS;
}
return IDENTICAL;
}
void CPredictionCopy::CopyVector( difftype_t dt, Vector* outValue, const Vector *inValue, int count )
{
if ( !m_bPerformCopy )
return;
if ( dt == IDENTICAL )
return;
CopyData( dt, sizeof( Vector ) * count, (char *)outValue, (const char *)inValue );
}
void CPredictionCopy::CopyQuaternion( difftype_t dt, Quaternion* outValue, const Quaternion *inValue, int count )
{
if ( !m_bPerformCopy )
return;
if ( dt == IDENTICAL )
return;
CopyData( dt, sizeof( Quaternion ) * count, (char *)outValue, (const char *)inValue );
}
CPredictionCopy::difftype_t CPredictionCopy::CompareVector( Vector* outValue, const Vector *inValue, int count )
{
if ( !m_bErrorCheck )
return DIFFERS;
difftype_t retval = IDENTICAL;
if ( CanCheck() )
{
float tolerance = m_pCurrentField->fieldTolerance;
Assert( tolerance >= 0.0f );
for ( int i = 0; i < count; i++ )
{
if ( outValue[ i ] == inValue[ i ] )
continue;
Vector delta = outValue[ i ] - inValue[ i ];
if ( tolerance > 0.0f )
{
if ( fabs( delta.x ) <= tolerance &&
fabs( delta.y ) <= tolerance &&
fabs( delta.z ) <= tolerance )
{
retval = WITHINTOLERANCE;
continue;
}
}
return DIFFERS;
}
}
return retval;
}
CPredictionCopy::difftype_t CPredictionCopy::CompareQuaternion( Quaternion* outValue, const Quaternion *inValue, int count )
{
if ( !m_bErrorCheck )
return DIFFERS;
difftype_t retval = IDENTICAL;
if ( CanCheck() )
{
float tolerance = m_pCurrentField->fieldTolerance;
Assert( tolerance >= 0.0f );
for ( int i = 0; i < count; i++ )
{
if ( QuaternionCompare( outValue[ i ], inValue[ i ] ) )
continue;
Quaternion delta;
for ( int j = 0; j < 4; j++ )
{
delta[j] = outValue[i][j] - inValue[i][j];
}
if ( tolerance > 0.0f )
{
if ( fabs( delta[0] ) <= tolerance &&
fabs( delta[1] ) <= tolerance &&
fabs( delta[2] ) <= tolerance &&
fabs( delta[3] ) <= tolerance )
{
retval = WITHINTOLERANCE;
continue;
}
}
return DIFFERS;
}
}
return retval;
}
void CPredictionCopy::CopyEHandle( difftype_t dt, EHANDLE *outvalue, EHANDLE const *invalue, int count )
{
if ( !m_bPerformCopy )
return;
if ( dt == IDENTICAL )
return;
for ( int i = 0; i < count; i++ )
{
outvalue[ i ] = invalue[ i ];
}
}
CPredictionCopy::difftype_t CPredictionCopy::CompareEHandle( EHANDLE *outvalue, EHANDLE const *invalue, int count )
{
if ( !m_bErrorCheck )
return DIFFERS;
int i;
if ( CanCheck() )
{
for ( i = 0; i < count; i++ )
{
if ( outvalue[ i ].Get() == invalue[ i ].Get() )
continue;
return DIFFERS;
}
}
return IDENTICAL;
}
void CPredictionCopy::CopyFields( int chain_count, datamap_t *pRootMap, typedescription_t *pFields, int fieldCount )
{
int i;
int flags;
int fieldOffsetSrc;
int fieldOffsetDest;
int fieldSize;
m_pCurrentMap = pRootMap;
if ( !m_pCurrentClassName )
{
m_pCurrentClassName = pRootMap->dataClassName;
}
for ( i = 0; i < fieldCount; i++ )
{
m_pCurrentField = &pFields[ i ];
flags = m_pCurrentField->flags;
// Mark any subchains first
if ( m_pCurrentField->override_field != NULL )
{
m_pCurrentField->override_field->override_count = chain_count;
}
// Skip this field?
if ( m_pCurrentField->override_count == chain_count )
{
continue;
}
// Always recurse into embeddeds
if ( m_pCurrentField->fieldType != FIELD_EMBEDDED )
{
// Don't copy fields that are private to server or client
if ( flags & FTYPEDESC_PRIVATE )
continue;
// For PC_NON_NETWORKED_ONLYs skip any fields that are present in the network send tables
if ( m_nType == PC_NON_NETWORKED_ONLY && ( flags & FTYPEDESC_INSENDTABLE ) )
continue;
// For PC_NETWORKED_ONLYs skip any fields that are not present in the network send tables
if ( m_nType == PC_NETWORKED_ONLY && !( flags & FTYPEDESC_INSENDTABLE ) )
continue;
}
void *pOutputData;
void const *pInputData;
fieldOffsetDest = m_pCurrentField->fieldOffset[ m_nDestOffsetIndex ];
fieldOffsetSrc = m_pCurrentField->fieldOffset[ m_nSrcOffsetIndex ];
fieldSize = m_pCurrentField->fieldSize;
pOutputData = (void *)((char *)m_pDest + fieldOffsetDest );
pInputData = (void const *)((char *)m_pSrc + fieldOffsetSrc );
// Assume we can report
m_bShouldReport = m_bReportErrors;
m_bShouldDescribe = true;
bool bShouldWatch = m_pWatchField == m_pCurrentField;
difftype_t difftype;
switch( m_pCurrentField->fieldType )
{
case FIELD_EMBEDDED:
{
typedescription_t *save = m_pCurrentField;
void *saveDest = m_pDest;
void const *saveSrc = m_pSrc;
const char *saveName = m_pCurrentClassName;
m_pCurrentClassName = m_pCurrentField->td->dataClassName;
// FIXME: Should this be done outside the FIELD_EMBEDDED case??
// Don't follow the pointer if we're reading from a compressed packet
m_pSrc = pInputData;
if ( ( flags & FTYPEDESC_PTR ) && (m_nSrcOffsetIndex == PC_DATA_NORMAL) )
{
m_pSrc = *((void**)m_pSrc);
}
m_pDest = pOutputData;
if ( ( flags & FTYPEDESC_PTR ) && (m_nDestOffsetIndex == PC_DATA_NORMAL) )
{
m_pDest = *((void**)m_pDest);
}
CopyFields( chain_count, pRootMap, m_pCurrentField->td->dataDesc, m_pCurrentField->td->dataNumFields );
m_pCurrentClassName = saveName;
m_pCurrentField = save;
m_pDest = saveDest;
m_pSrc = saveSrc;
}
break;
case FIELD_FLOAT:
{
difftype = CompareFloat( (float *)pOutputData, (float const *)pInputData, fieldSize );
CopyFloat( difftype, (float *)pOutputData, (float const *)pInputData, fieldSize );
if ( m_bErrorCheck && m_bShouldDescribe ) DescribeFloat( difftype, (float *)pOutputData, (float const *)pInputData, fieldSize );
if ( bShouldWatch ) WatchFloat( difftype, (float *)pOutputData, (float const *)pInputData, fieldSize );
}
break;
case FIELD_TIME:
case FIELD_TICK:
Assert( 0 );
break;
case FIELD_STRING:
{
difftype = CompareString( (char *)pOutputData, (char const*)pInputData );
CopyString( difftype, (char *)pOutputData, (char const*)pInputData );
if ( m_bErrorCheck && m_bShouldDescribe ) DescribeString( difftype,(char *)pOutputData, (char const*)pInputData );
if ( bShouldWatch ) WatchString( difftype,(char *)pOutputData, (char const*)pInputData );
}
break;
case FIELD_MODELINDEX:
Assert( 0 );
break;
case FIELD_MODELNAME:
case FIELD_SOUNDNAME:
Assert( 0 );
break;
case FIELD_CUSTOM:
Assert( 0 );
break;
case FIELD_CLASSPTR:
case FIELD_EDICT:
Assert( 0 );
break;
case FIELD_POSITION_VECTOR:
Assert( 0 );
break;
case FIELD_VECTOR:
{
difftype = CompareVector( (Vector *)pOutputData, (Vector const *)pInputData, fieldSize );
CopyVector( difftype, (Vector *)pOutputData, (Vector const *)pInputData, fieldSize );
if ( m_bErrorCheck && m_bShouldDescribe ) DescribeVector( difftype, (Vector *)pOutputData, (Vector const *)pInputData, fieldSize );
if ( bShouldWatch ) WatchVector( difftype, (Vector *)pOutputData, (Vector const *)pInputData, fieldSize );
}
break;
case FIELD_QUATERNION:
{
difftype = CompareQuaternion( (Quaternion *)pOutputData, (Quaternion const *)pInputData, fieldSize );
CopyQuaternion( difftype, (Quaternion *)pOutputData, (Quaternion const *)pInputData, fieldSize );
if ( m_bErrorCheck && m_bShouldDescribe ) DescribeQuaternion( difftype, (Quaternion *)pOutputData, (Quaternion const *)pInputData, fieldSize );
if ( bShouldWatch ) WatchQuaternion( difftype, (Quaternion *)pOutputData, (Quaternion const *)pInputData, fieldSize );
}
break;
case FIELD_COLOR32:
{
difftype = CompareData( 4*fieldSize, (char *)pOutputData, (const char *)pInputData );
CopyData( difftype, 4*fieldSize, (char *)pOutputData, (const char *)pInputData );
if ( m_bErrorCheck && m_bShouldDescribe ) DescribeData( difftype, 4*fieldSize, (char *)pOutputData, (const char *)pInputData );
if ( bShouldWatch ) WatchData( difftype, 4*fieldSize, (char *)pOutputData, (const char *)pInputData );
}
break;
case FIELD_BOOLEAN:
{
difftype = CompareBool( (bool *)pOutputData, (bool const *)pInputData, fieldSize );
CopyBool( difftype, (bool *)pOutputData, (bool const *)pInputData, fieldSize );
if ( m_bErrorCheck && m_bShouldDescribe ) DescribeBool( difftype, (bool *)pOutputData, (bool const *)pInputData, fieldSize );
if ( bShouldWatch ) WatchBool( difftype, (bool *)pOutputData, (bool const *)pInputData, fieldSize );
}
break;
case FIELD_INTEGER:
{
difftype = CompareInt( (int *)pOutputData, (int const *)pInputData, fieldSize );
CopyInt( difftype, (int *)pOutputData, (int const *)pInputData, fieldSize );
if ( m_bErrorCheck && m_bShouldDescribe ) DescribeInt( difftype, (int *)pOutputData, (int const *)pInputData, fieldSize );
if ( bShouldWatch ) WatchInt( difftype, (int *)pOutputData, (int const *)pInputData, fieldSize );
}
break;
case FIELD_SHORT:
{
difftype = CompareShort( (short *)pOutputData, (short const *)pInputData, fieldSize );
CopyShort( difftype, (short *)pOutputData, (short const *)pInputData, fieldSize );
if ( m_bErrorCheck && m_bShouldDescribe ) DescribeShort( difftype, (short *)pOutputData, (short const *)pInputData, fieldSize );
if ( bShouldWatch ) WatchShort( difftype, (short *)pOutputData, (short const *)pInputData, fieldSize );
}
break;
case FIELD_CHARACTER:
{
difftype = CompareData( fieldSize, ((char *)pOutputData), (const char *)pInputData );
CopyData( difftype, fieldSize, ((char *)pOutputData), (const char *)pInputData );
int valOut = *((char *)pOutputData);
int valIn = *((const char *)pInputData);
if ( m_bErrorCheck && m_bShouldDescribe ) DescribeInt( difftype, &valOut, &valIn, fieldSize );
if ( bShouldWatch ) WatchData( difftype, fieldSize, ((char *)pOutputData), (const char *)pInputData );
}
break;
case FIELD_EHANDLE:
{
difftype = CompareEHandle( (EHANDLE *)pOutputData, (EHANDLE const *)pInputData, fieldSize );
CopyEHandle( difftype, (EHANDLE *)pOutputData, (EHANDLE const *)pInputData, fieldSize );
if ( m_bErrorCheck && m_bShouldDescribe ) DescribeEHandle( difftype, (EHANDLE *)pOutputData, (EHANDLE const *)pInputData, fieldSize );
if ( bShouldWatch ) WatchEHandle( difftype, (EHANDLE *)pOutputData, (EHANDLE const *)pInputData, fieldSize );
}
break;
case FIELD_FUNCTION:
{
Assert( 0 );
}
break;
case FIELD_VOID:
{
// Don't do anything, it's an empty data description
}
break;
default:
{
Warning( "Bad field type\n" );
Assert(0);
}
break;
}
}
m_pCurrentClassName = NULL;
}
void CPredictionCopy::TransferData_R( int chaincount, datamap_t *dmap )
{
// Copy from here first, then baseclasses
CopyFields( chaincount, dmap, dmap->dataDesc, dmap->dataNumFields );
if ( dmap->baseMap )
{
TransferData_R( chaincount, dmap->baseMap );
}
}
static int g_nChainCount = 1;
static typedescription_t *FindFieldByName_R( const char *fieldname, datamap_t *dmap )
{
int c = dmap->dataNumFields;
for ( int i = 0; i < c; i++ )
{
typedescription_t *td = &dmap->dataDesc[ i ];
if ( td->fieldType == FIELD_VOID )
continue;
if ( td->fieldType == FIELD_EMBEDDED )
{
// TODO: this will only find the first subclass with the variable of the specified name
// At some point we might want to support multiple levels of overriding automatically
typedescription_t *ret = FindFieldByName_R( fieldname, td->td );
if ( ret )
{
return ret;
}
}
if ( !V_stricmp( td->fieldName, fieldname ) )
{
return td;
}
}
if ( dmap->baseMap )
{
return FindFieldByName_R( fieldname, dmap->baseMap );
}
return NULL;
}
void ValidateChains_R( datamap_t *dmap )
{
dmap->chains_validated = true;
int c = dmap->dataNumFields;
for ( int i = 0; i < c; i++ )
{
typedescription_t *td = &dmap->dataDesc[ i ];
if ( td->fieldType == FIELD_VOID )
continue;
if ( td->fieldType == FIELD_EMBEDDED )
{
ValidateChains_R( td->td );
continue;
}
if ( !( td->flags & FTYPEDESC_OVERRIDE ) )
continue;
if ( dmap->baseMap )
{
typedescription_t *basefield = FindFieldByName_R( td->fieldName, dmap->baseMap );
if ( basefield )
{
td->override_field = basefield;
}
}
}
if ( dmap->baseMap )
{
if ( !dmap->baseMap->chains_validated )
{
ValidateChains_R( dmap->baseMap );
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *fieldname -
// *dmap -
// Output : typedescription_t
//-----------------------------------------------------------------------------
typedescription_t *FindFieldByName( const char *fieldname, datamap_t *dmap )
{
return FindFieldByName_R( fieldname, dmap );
}
static ConVar pwatchent( "pwatchent", "-1", FCVAR_CHEAT, "Entity to watch for prediction system changes." );
static ConVar pwatchvar( "pwatchvar", "", FCVAR_CHEAT, "Entity variable to watch in prediction system for changes." );
//-----------------------------------------------------------------------------
// Purpose:
// Input : *fmt -
// ... -
//-----------------------------------------------------------------------------
void CPredictionCopy::WatchMsg( const char *fmt, ... )
{
Assert( m_pCurrentField && (m_pCurrentField == m_pWatchField) );
Assert( m_pOperation );
va_list argptr;
char data[ 4096 ];
int len;
va_start(argptr, fmt);
len = Q_vsnprintf(data, sizeof( data ), fmt, argptr);
va_end(argptr);
Msg( "%i %s %s : %s\n", gpGlobals->tickcount, m_pOperation, m_pCurrentField->fieldName, data );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *operation -
// entindex -
// *dmap -
//-----------------------------------------------------------------------------
void CPredictionCopy::DetermineWatchField( const char *operation, int entindex, datamap_t *dmap )
{
m_pWatchField = NULL;
m_pOperation = operation;
if ( !m_pOperation || !m_pOperation[0] )
return;
int enttowatch = pwatchent.GetInt();
if ( enttowatch < 0 )
return;
if ( entindex != enttowatch )
return;
// See if they specified a field
if ( pwatchvar.GetString()[0] == 0 )
return;
m_pWatchField = FindFieldByName( pwatchvar.GetString(), dmap );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *operation -
// entindex -
// *dmap -
// Output : int
//-----------------------------------------------------------------------------
int CPredictionCopy::TransferData( const char *operation, int entindex, datamap_t *dmap )
{
++g_nChainCount;
if ( !dmap->chains_validated )
{
ValidateChains_R( dmap );
}
DetermineWatchField( operation, entindex, dmap );
TransferData_R( g_nChainCount, dmap );
return m_nErrorCount;
}
/*
//-----------------------------------------------------------------------------
// Purpose: Simply dumps all data fields in object
//-----------------------------------------------------------------------------
class CPredictionDescribeData
{
public:
CPredictionDescribeData( void const *src );
void DescribeShort( const short *invalue, int count );
void DescribeInt( const int *invalue, int count );
void DescribeBool( const bool *invalue, int count );
void DescribeFloat( const float *invalue, int count );
void DescribeData( int size, const char *indata );
void DescribeString( const char *instring );
void DescribeVector( const Vector &inValue );
void DescribeVector( const Vector *inValue, int count );
void DescribeEHandle( EHANDLE const *invalue, int count );
void DescribeFields( datamap_t *pMap, typedescription_t *pFields, int fieldCount );
private:
void const *m_pSrc;
void Describe( const char *fmt, ... );
typedescription_t *m_pCurrentField;
char const *m_pCurrentClassName;
datamap_t *m_pCurrentMap;
};
*/
CPredictionDescribeData::CPredictionDescribeData( void const *src, bool src_packed, FN_FIELD_DESCRIPTION func /*= 0*/ )
{
m_pSrc = src;
m_nSrcOffsetIndex = src_packed ? TD_OFFSET_PACKED : TD_OFFSET_NORMAL;
m_pCurrentField = NULL;
m_pCurrentMap = NULL;
m_pCurrentClassName = NULL;
m_bShouldReport = false;
m_FieldDescFunc = func;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *fmt -
// ... -
//-----------------------------------------------------------------------------
void CPredictionDescribeData::Describe( const char *fmt, ... )
{
// if ( !m_bShouldReport )
// return;
Assert( m_pCurrentMap );
Assert( m_pCurrentClassName );
const char *fieldname = "empty";
int flags = 0;
if ( m_pCurrentField )
{
flags = m_pCurrentField->flags;
fieldname = m_pCurrentField->fieldName ? m_pCurrentField->fieldName : "NULL";
}
va_list argptr;
char data[ 4096 ];
int len;
va_start(argptr, fmt);
len = Q_vsnprintf(data, sizeof( data ), fmt, argptr);
va_end(argptr);
bool isprivate = ( flags & FTYPEDESC_PRIVATE ) ? true : false;
bool isnetworked = ( flags & FTYPEDESC_INSENDTABLE ) ? true : false;
if ( m_FieldDescFunc )
{
(*m_FieldDescFunc)(
m_pCurrentClassName,
m_pCurrentField->fieldName,
g_FieldTypes[ m_pCurrentField->fieldType ],
isnetworked,
data );
}
else
{
char suffix[ 128 ];
suffix[ 0 ] = 0;
if ( isprivate )
{
Q_strncat( suffix, "private", sizeof( suffix ), COPY_ALL_CHARACTERS );
}
if ( isnetworked )
{
if ( suffix[ 0 ] )
{
Q_strncat( suffix, " - ", sizeof( suffix ), COPY_ALL_CHARACTERS );
}
Q_strncat( suffix, "net", sizeof( suffix ), COPY_ALL_CHARACTERS );
}
if ( suffix[ 0 ] )
{
Msg( "%s::%s(%s) - %s",
m_pCurrentClassName,
fieldname,
suffix,
data );
}
else
{
Msg( "%s::%s - %s",
m_pCurrentClassName,
fieldname,
data );
}
}
m_bShouldReport = false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : size -
// *outdata -
// *indata -
//-----------------------------------------------------------------------------
void CPredictionDescribeData::DescribeData( int size, const char *indata )
{
if ( !indata )
return;
Describe( "binary (%i bytes)\n", size );
}
void CPredictionDescribeData::DescribeShort( const short *invalue, int count )
{
Describe( "short (%i)\n", (int)(invalue[0]) );
}
void CPredictionDescribeData::DescribeInt( const int *invalue, int count )
{
for ( int i = 0; i < count; ++i )
{
Describe( "[%i] integer (%i)\n", i, invalue[i] );
}
}
void CPredictionDescribeData::DescribeBool( const bool *invalue, int count )
{
Describe( "bool (%s)\n", (invalue[0]) ? "true" : "false" );
}
void CPredictionDescribeData::DescribeFloat( const float *invalue, int count )
{
Describe( "float (%f)\n", invalue[ 0 ] );
}
void CPredictionDescribeData::DescribeString( const char *instring )
{
Describe( "string (%s)\n", instring );
}
void CPredictionDescribeData::DescribeVector( const Vector &inValue )
{
Describe( "vector (%f %f %f)\n",
inValue.x, inValue.y, inValue.z );
}
void CPredictionDescribeData::DescribeVector( const Vector *inValue, int count )
{
Describe( "vector (%f %f %f)\n",
inValue[0].x, inValue[0].y, inValue[0].z );
}
void CPredictionDescribeData::DescribeQuaternion( const Quaternion &inValue )
{
Describe( "quaternion (%f %f %f %f)\n",
inValue[0], inValue[1], inValue[2], inValue[3] );
}
void CPredictionDescribeData::DescribeQuaternion( const Quaternion *inValue, int count )
{
Describe( "quaternion (%f %f %f %f)\n",
inValue[0][0], inValue[0][1], inValue[0][2], inValue[0][3] );
}
void CPredictionDescribeData::DescribeEHandle( EHANDLE const *invalue, int count )
{
Describe( "EHandle (%p)\n", (void *)invalue[ 0 ] );
}
void CPredictionDescribeData::DescribeFields_R( int chain_count, datamap_t *pRootMap, typedescription_t *pFields, int fieldCount )
{
int i;
int flags;
int fieldOffsetSrc;
int fieldSize;
m_pCurrentMap = pRootMap;
if ( !m_pCurrentClassName )
{
m_pCurrentClassName = pRootMap->dataClassName;
}
for ( i = 0; i < fieldCount; i++ )
{
m_pCurrentField = &pFields[ i ];
flags = m_pCurrentField->flags;
// Mark any subchains first
if ( m_pCurrentField->override_field != NULL )
{
m_pCurrentField->override_field->override_count = chain_count;
}
// Skip this field?
if ( m_pCurrentField->override_count == chain_count )
{
continue;
}
void const *pInputData;
fieldOffsetSrc = m_pCurrentField->fieldOffset[ m_nSrcOffsetIndex ];
fieldSize = m_pCurrentField->fieldSize;
pInputData = (void const *)((char *)m_pSrc + fieldOffsetSrc );
// Assume we can report
m_bShouldReport = true;
switch( m_pCurrentField->fieldType )
{
case FIELD_EMBEDDED:
{
typedescription_t *save = m_pCurrentField;
void const *saveSrc = m_pSrc;
const char *saveName = m_pCurrentClassName;
m_pCurrentClassName = m_pCurrentField->td->dataClassName;
m_pSrc = pInputData;
if ( ( flags & FTYPEDESC_PTR ) && (m_nSrcOffsetIndex == PC_DATA_NORMAL) )
{
m_pSrc = *((void**)m_pSrc);
}
DescribeFields_R( chain_count, pRootMap, m_pCurrentField->td->dataDesc, m_pCurrentField->td->dataNumFields );
m_pCurrentClassName = saveName;
m_pCurrentField = save;
m_pSrc = saveSrc;
}
break;
case FIELD_FLOAT:
DescribeFloat( (float const *)pInputData, fieldSize );
break;
case FIELD_TIME:
case FIELD_TICK:
Assert( 0 );
break;
case FIELD_STRING:
DescribeString( (char const*)pInputData );
break;
case FIELD_MODELNAME:
case FIELD_SOUNDNAME:
Assert( 0 );
break;
case FIELD_MODELINDEX:
Assert( 0 );
break;
case FIELD_CUSTOM:
Assert( 0 );
break;
case FIELD_CLASSPTR:
case FIELD_EDICT:
break;
case FIELD_POSITION_VECTOR:
Assert( 0 );
break;
case FIELD_VECTOR:
DescribeVector( (const Vector *)pInputData, fieldSize );
break;
case FIELD_QUATERNION:
DescribeQuaternion( ( const Quaternion * )pInputData, fieldSize );
break;
case FIELD_COLOR32:
DescribeData( 4*fieldSize, (const char *)pInputData );
break;
case FIELD_BOOLEAN:
DescribeBool( (bool const *)pInputData, fieldSize );
break;
case FIELD_INTEGER:
DescribeInt( (int const *)pInputData, fieldSize );
break;
case FIELD_SHORT:
DescribeShort( (short const *)pInputData, fieldSize );
break;
case FIELD_CHARACTER:
DescribeData( fieldSize, (const char *)pInputData );
break;
case FIELD_EHANDLE:
DescribeEHandle( (EHANDLE const *)pInputData, fieldSize );
break;
case FIELD_FUNCTION:
Assert( 0 );
break;
case FIELD_VOID:
Describe( "FIELD_VOID: empty field\n" );
break;
default:
Warning( "Bad field type\n" );
Assert(0);
break;
}
}
m_pCurrentClassName = NULL;
}
void CPredictionDescribeData::DumpDescription( datamap_t *pMap )
{
++g_nChainCount;
if ( !pMap->chains_validated )
{
ValidateChains_R( pMap );
}
while ( pMap )
{
DescribeFields_R( g_nChainCount, pMap, pMap->dataDesc, pMap->dataNumFields );
pMap = pMap->baseMap;
}
}
#if defined( CLIENT_DLL )
CValueChangeTracker::CValueChangeTracker() :
m_bActive( false ),
m_bTracking( false )
{
Q_memset( m_OrigValueBuf, 0, sizeof( m_OrigValueBuf ) );
}
C_BaseEntity *CValueChangeTracker::GetEntity()
{
return m_hEntityToTrack.Get();
}
void CValueChangeTracker::GetValue( char *buf, size_t bufsize )
{
buf[ 0 ] = 0;
Assert( IsActive() );
if ( !m_hEntityToTrack.Get() )
return;
void const *pInputData = ( const void * )m_hEntityToTrack.Get();
typedescription_t *td = NULL;
for ( int i = 0; i < m_FieldStack.Count(); ++i )
{
td = m_FieldStack[ i ];
Assert( ( i == ( m_FieldStack.Count() -1 ) ) ||
( td->fieldType & FIELD_EMBEDDED ) );
int fieldOffsetSrc = td->fieldOffset[ TD_OFFSET_NORMAL ];
const void *pSaveSrc = (const void *)( (char *)pInputData + fieldOffsetSrc );
if ( ( td->flags & FTYPEDESC_PTR ) &&
( td->fieldType & FIELD_EMBEDDED ) )
{
pInputData = *(const void **)pSaveSrc;
}
else
{
pInputData = (void const *)((char *)pSaveSrc );
}
}
if ( !td || !pInputData )
return;
int fieldType = td->fieldType;
switch( fieldType )
{
default:
case FIELD_EMBEDDED:
case FIELD_MODELNAME:
case FIELD_SOUNDNAME:
case FIELD_CUSTOM:
case FIELD_CLASSPTR:
case FIELD_EDICT:
case FIELD_POSITION_VECTOR:
case FIELD_VOID:
case FIELD_FUNCTION:
{
Assert( 0 );
}
break;
case FIELD_FLOAT:
case FIELD_TIME:
Q_snprintf( buf, bufsize, "%f", *(float const *)pInputData );
break;
case FIELD_STRING:
Q_snprintf( buf, bufsize, "%s", (char const*)pInputData );
break;
case FIELD_VECTOR:
{
const Vector *pVec = (const Vector *)pInputData;
Q_snprintf( buf, bufsize, "%f %f %f", pVec->x, pVec->y, pVec->z );
}
break;
case FIELD_QUATERNION:
{
const Quaternion *p = ( const Quaternion * )pInputData;
Q_snprintf( buf, bufsize, "%f %f %f %f", p->x, p->y, p->z, p->w );
}
break;
case FIELD_COLOR32:
{
const Color *color = ( const Color * )pInputData;
Q_snprintf( buf, bufsize, "%d %d %d %d", color->r(), color->g(), color->b(), color->a() );
}
break;
case FIELD_BOOLEAN:
Q_snprintf( buf, bufsize, "%s", (*(const bool *)pInputData) ? "true" : "false" );
break;
case FIELD_INTEGER:
case FIELD_TICK:
case FIELD_MODELINDEX:
Q_snprintf( buf, bufsize, "%i", *(const int*)pInputData );
break;
case FIELD_SHORT:
Q_snprintf( buf, bufsize, "%i", (int)*(const short*)pInputData );
break;
case FIELD_CHARACTER:
Q_snprintf( buf, bufsize, "%c", *(const char *)pInputData );
break;
case FIELD_EHANDLE:
Q_snprintf( buf, bufsize, "eh 0x%p", (void const *)((const EHANDLE *)pInputData)->Get() );
break;
}
}
void CValueChangeTracker::StartTrack( char const *pchContext )
{
if ( !IsActive() )
return;
m_strContext = pchContext;
// Grab current value into scratch buffer
GetValue( m_OrigValueBuf, sizeof( m_OrigValueBuf ) );
m_bTracking = true;
}
void CValueChangeTracker::EndTrack()
{
if ( !IsActive() )
return;
if ( !m_bTracking )
return;
m_bTracking = false;
char final[ eChangeTrackerBufSize ];
GetValue( final, sizeof( final ) );
CUtlString *history = &m_History[ m_History.AddToTail() ];
if ( Q_stricmp( final, m_OrigValueBuf ) )
{
history->Set( CFmtStr( "+++ %-20.20s: %s (was %s)", m_strContext.String(), final, m_OrigValueBuf ) );
}
else
{
history->Set( CFmtStr( " %-20.20s: %s", m_strContext.String(), final ) );
}
Msg( ":%s\n", history->String() );
}
void CValueChangeTracker::ClearTracking()
{
m_bActive = false;
m_bTracking = false;
m_hEntityToTrack = NULL;
m_strFieldName = "";
m_History.RemoveAll();
m_FieldStack.RemoveAll();
}
static bool FindFieldStackByName_R( const char *fieldname, datamap_t *dmap, CUtlVector< typedescription_t * >& stack )
{
int c = dmap->dataNumFields;
for ( int i = 0; i < c; i++ )
{
typedescription_t *td = &dmap->dataDesc[ i ];
if ( td->fieldType == FIELD_VOID )
continue;
stack.AddToTail( td );
if ( td->fieldType == FIELD_EMBEDDED )
{
// TODO: this will only find the first subclass with the variable of the specified name
// At some point we might want to support multiple levels of overriding automatically
bool ret = FindFieldStackByName_R( fieldname, td->td, stack );
if ( ret )
{
return ret;
}
}
if ( !Q_stricmp( td->fieldName, fieldname ) )
{
return true;
}
stack.FindAndRemove( td );
}
if ( dmap->baseMap )
{
return FindFieldStackByName_R( fieldname, dmap->baseMap, stack );
}
return false;
}
void CValueChangeTracker::SetupTracking( C_BaseEntity *ent, char const *pchFieldName )
{
ClearTracking();
// Find the field
datamap_t *dmap = ent->GetPredDescMap();
if ( !dmap )
{
Msg( "No prediction datamap_t for entity %d/%s\n", ent->m_index, ent->GetClassname() );
return;
}
bool bFound = FindFieldStackByName_R( pchFieldName, dmap, m_FieldStack );
if ( !bFound || !m_FieldStack.Count() )
{
Msg( "No field '%s' in datamap_t for entity %d/%s\n", pchFieldName, ent->m_index, ent->GetClassname() );
return;
}
m_hEntityToTrack = ent;
m_strFieldName = pchFieldName;
m_bActive = true;
}
void CValueChangeTracker::Reset()
{
m_History.RemoveAll();
}
bool CValueChangeTracker::IsActive() const
{
return m_bActive;
}
void CValueChangeTracker::Spew()
{
if ( IsActive() )
{
for ( int i = 0 ; i < m_History.Count(); ++i )
{
Msg( "%s\n", m_History[ i ].String() );
}
}
Reset();
}
static CValueChangeTracker g_ChangeTracker;
CValueChangeTracker *g_pChangeTracker = &g_ChangeTracker;
CON_COMMAND_F( cl_pred_track, "<entindex> <fieldname>: Track changes to entity index entindex, for field fieldname.", 0 )
{
g_pChangeTracker->ClearTracking();
if ( args.ArgC() != 3 )
{
Msg( "cl_pred_track <entindex> <fieldname>\n" );
return;
}
int iEntIndex = Q_atoi( args[1] );
C_BaseEntity *ent = cl_entitylist->GetBaseEntity( iEntIndex );
if ( !ent )
{
Msg( "cl_pred_track: Unknown ent index %d\n", iEntIndex );
return;
}
g_pChangeTracker->SetupTracking( ent, args[2] );
}
#endif
#if defined( CLIENT_DLL ) && defined( COPY_CHECK_STRESSTEST )
class CPredictionCopyTester : public IGameSystem
{
public:
// Init, shutdown
virtual void Init()
{
RunTests();
Remove( this );
}
virtual void Shutdown() {}
// Level init, shutdown
virtual void LevelInit() {}
// The level is shutdown in two parts
virtual void LevelShutdownPreEntity() {}
// Entities are deleted / released here...
virtual void LevelShutdownPostEntity() {}
// end of level shutdown
// Called before rendering
virtual void PreRender ( ) {}
// Called after rendering
virtual void PostRender() {}
// Gets called each frame
virtual void Update( float frametime ) {}
private:
void RunTests( void );
};
IGameSystem* GetPredictionCopyTester( void )
{
static CPredictionCopyTester s_PredictionCopyTesterSystem;
return &s_PredictionCopyTesterSystem;
}
class CCopyTesterData
{
public:
CCopyTesterData()
{
m_CharValue = 'a';
m_ShortValue = (short)100;
m_IntValue = (int)100;
m_FloatValue = 1.0f;
Q_strncpy( m_szValue, "primarydata", sizeof( m_szValue ) );
m_Vector = Vector( 100, 100, 100 );
m_Bool = false;
m_Clr.r = m_Clr.g = m_Clr.b = m_Clr.a = 255;
m_Ptr = (void *)0xfedcba98;
// m_hEHandle = NULL;
}
void MakeDifferent( void )
{
m_CharValue = 'd';
m_ShortValue = (short)400;
m_IntValue = (int)400;
m_FloatValue = 4.0f;
Q_strncpy( m_szValue, "secondarydata", sizeof( m_szValue ) );
m_Vector = Vector( 400, 400, 400 );
m_Bool = true;
m_Clr.r = m_Clr.g = m_Clr.b = m_Clr.a = 1;
m_Ptr = (void *)0x00000001;
// m_hEHandle = (C_BaseEntity *)0x00000001;
}
DECLARE_PREDICTABLE();
char m_CharValue;
short m_ShortValue;
int m_IntValue;
float m_FloatValue;
char m_szValue[ 128 ];
Vector m_Vector;
bool m_Bool;
color32 m_Clr;
void *m_Ptr;
// EHANDLE m_hEHandle;
};
BEGIN_PREDICTION_DATA_NO_BASE( CCopyTesterData )
DEFINE_FIELD( CCopyTesterData, m_CharValue, FIELD_CHARACTER ),
DEFINE_FIELD( CCopyTesterData, m_ShortValue, FIELD_SHORT ),
DEFINE_FIELD( CCopyTesterData, m_IntValue, FIELD_INTEGER ),
DEFINE_FIELD( CCopyTesterData, m_FloatValue, FIELD_FLOAT ),
DEFINE_FIELD( CCopyTesterData, m_szValue, FIELD_STRING ),
DEFINE_FIELD( CCopyTesterData, m_Vector, FIELD_VECTOR ),
DEFINE_FIELD( CCopyTesterData, m_Bool, FIELD_BOOLEAN ),
DEFINE_FIELD( CCopyTesterData, m_Clr, FIELD_COLOR32 ),
// DEFINE_FIELD( CCopyTesterData, m_hEHandle, FIELD_EHANDLE ),
END_PREDICTION_DATA()
class CCopyTesterData2 : public C_BaseEntity
{
DECLARE_CLASS( CCopyTesterData2, C_BaseEntity );
public:
CCopyTesterData2()
{
CONSTRUCT_PREDICTABLE( CCopyTesterData2 );
m_CharValue = 'b';
m_ShortValue = (short)200;
m_IntValue = (int)200;
m_FloatValue = 2.0f;
}
void MakeDifferent( void )
{
m_CharValue = 'e';
m_ShortValue = (short)500;
m_IntValue = (int)500;
m_FloatValue = 5.0f;
m_FooData.MakeDifferent();
}
DECLARE_PREDICTABLE();
char m_CharValue;
short m_ShortValue;
int m_IntValue;
float m_FloatValue;
CCopyTesterData m_FooData;
};
BEGIN_PREDICTION_DATA_NO_BASE( CCopyTesterData2 )
DEFINE_FIELD( CCopyTesterData2, m_CharValue, FIELD_CHARACTER ),
DEFINE_FIELD( CCopyTesterData2, m_ShortValue, FIELD_SHORT ),
DEFINE_PRED_TYPEDESCRIPTION( CCopyTesterData2, m_FooData, CCopyTesterData ),
DEFINE_FIELD( CCopyTesterData2, m_IntValue, FIELD_INTEGER ),
DEFINE_FIELD( CCopyTesterData2, m_FloatValue, FIELD_FLOAT ),
END_PREDICTION_DATA()
void CPredictionCopyTester::RunTests( void )
{
CCopyTesterData2 *foo1, *foo2, *foo3;
foo1 = new CCopyTesterData2;
foo2 = new CCopyTesterData2;
foo3 = new CCopyTesterData2;
foo2->MakeDifferent();
{
Msg( "Comparing and copying == objects, should have zero diffcount\n" );
CPredictionCopy tester( PC_NON_NETWORKED_ONLY, foo1, false, foo3, false, true );
int diff_count = 0;
diff_count = tester.TransferData( foo3->GetPredDescMap(), foo1->GetPredDescMap()->dataDesc, foo1->GetPredDescMap()->dataNumFields );
Msg( "diff_count == %i\n", diff_count );
Assert( !diff_count );
}
{
Msg( "Simple compare of != objects, should spew and have non-zero diffcount\n" );
CPredictionCopy tester( PC_NON_NETWORKED_ONLY, foo1, false, foo2, false, true, false );
int diff_count = 0;
diff_count = tester.TransferData( foo2->GetPredDescMap(), foo1->GetPredDescMap()->dataDesc, foo1->GetPredDescMap()->dataNumFields );
Msg( "diff_count == %i (should be 12)\n", diff_count );
Assert( diff_count == 12 );
}
{
Msg( "Comparing and coyping same != objects, should spew and have non-zero diffcount\n" );
CPredictionCopy tester( PC_NON_NETWORKED_ONLY, foo1, false, foo2, false, true );
int diff_count = 0;
diff_count = tester.TransferData( foo2->GetPredDescMap(), foo1->GetPredDescMap()->dataDesc, foo1->GetPredDescMap()->dataNumFields );
Msg( "diff_count == %i (should be 12)\n", diff_count );
Assert( diff_count == 12 );
}
{
Msg( "Comparing and copying objects which were just made to coincide, should have zero diffcount\n" );
CPredictionCopy tester( PC_NON_NETWORKED_ONLY, foo1, false, foo2, false, true );
int diff_count = 0;
diff_count = tester.TransferData( foo2->GetPredDescMap(), foo1->GetPredDescMap()->dataDesc, foo1->GetPredDescMap()->dataNumFields );
Msg( "diff_count == %i\n", diff_count );
Assert( !diff_count );
}
{
CPredictionDescribeData describe( foo1, false );
describe.DumpDescription( foo1->GetPredDescMap(), foo1->GetPredDescMap()->dataDesc, foo1->GetPredDescMap()->dataNumFields );
}
delete foo3;
delete foo2;
delete foo1;
}
#endif // CLIENT_DLL
#endif // !NO_ENTITY_PREDICTION )
| 24.461436 | 147 | 0.644376 | [
"object",
"vector"
] |
b4fae84ff615afd0f681d0660aae6c7277a8bdee | 15,138 | cc | C++ | src/jla.cc | surhudm/jla_python | 4ec8386bba4ade446458f23f91eef9298c79b609 | [
"BSD-3-Clause-Clear"
] | 1 | 2017-03-09T08:58:45.000Z | 2017-03-09T08:58:45.000Z | src/jla.cc | surhudm/jla_python | 4ec8386bba4ade446458f23f91eef9298c79b609 | [
"BSD-3-Clause-Clear"
] | null | null | null | src/jla.cc | surhudm/jla_python | 4ec8386bba4ade446458f23f91eef9298c79b609 | [
"BSD-3-Clause-Clear"
] | null | null | null | #include "jla.h"
#include "ini.h"
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <cmath>
#define sq(x) x*x
//---------------------------- LAPACK headers ------------------------------------
#define dpotrf dpotrf_
#define dtrtrs dtrtrs_
extern "C" {
#include <cblas.h>
void dpotrf(const char * UPLO, int * N, double * A, int * LDA, int * INFO);
void dtrtrs(const char * UPLO, const char * TRANS, const char * DIAG, int * N,
int * NRHS, double * A, int * LDA, double * B, int * LDB, int *INFO);
}
using namespace std;
/***************************************************************************
* Full Likelihood *
***************************************************************************/
//-------------- Reading configuration and data from disk --------------------------
/*
* Store values read from the configuration file.
*/
struct Configuration{
int version;
double scriptmcut;
const char* data_file;
const char* C00;
const char* C11;
const char* C22;
const char* C01;
const char* C02;
const char* C12;
};
/*
* Handler for reading the config file through inih.
*/
static int configuration_handler(void* user, const char* section, const char* name,
const char* value)
{
Configuration* pconfig = (Configuration*)user;
#define MATCH(s, n) strcmp(section, s) == 0 && strcmp(name, n) == 0
if (MATCH("", "scriptmcut")) {
pconfig->scriptmcut = atof(value);
} else if (MATCH("", "data_file")) {
pconfig->data_file = strdup(value);
} else if (MATCH("", "mag_covmat_file")) {
pconfig->C00 = strdup(value);
} else if (MATCH("", "stretch_covmat_file")) {
pconfig->C11 = strdup(value);
} else if (MATCH("", "colour_covmat_file")) {
pconfig->C22 = strdup(value);
} else if (MATCH("", "mag_stretch_covmat_file")) {
pconfig->C01 = strdup(value);
} else if (MATCH("", "mag_colour_covmat_file")) {
pconfig->C02 = strdup(value);
} else if (MATCH("", "stretch_colour_covmat_file")) {
pconfig->C12 = strdup(value);
} else {
return 0; /* unknown section/name, error */
}
return 1;
}
/*
* Read one entry in the lightcurve file.
*/
istream & operator >> (istream & is, LCPar & sn)
{
is >> sn.name;
is >> sn.zcmb >> sn.zhel >> sn.dz >> sn.mb >> sn.dmb >> sn.x1 >> sn.dx1 >> sn.color
>> sn.dcolor >> sn.thirdvar >> sn.dthirdvar >> sn.tmax >> sn.dtmax >> sn.cov_m_s >> sn.cov_m_c
>> sn.cov_s_c >> sn.set >> sn.ra >> sn.dec >> sn.biascor;
return is;
}
/*
* Read square matrices from text files.
*
* Matrix file must constain space separated values, starts with one
* integer N (the matrix size) followed by at least N x N floating
* point values. The rest of the file is ignored.
*
* Return a pointer on a N x N double region containing the matrix
* values.
*/
double * read_matrix(const char * filename, int verbosity)
{
int N;
double * mat = NULL;
std::ifstream fid(filename);
if (!fid){
fid.close();
if (verbosity > 0)
cerr << "Fail to read file " << filename << endl;
exit(-1);
return mat;
}
if (verbosity > 1)
cout << "Reading file " << filename << endl;
fid >> N;
mat = (double *)malloc(sizeof(double) * N * N);
for (int i = 0; i < N * N; i++)
fid >> mat[i];
if (verbosity > 1)
cout << N << " x " << N << " values read from file " << filename << endl;
fid.close();
return mat;
}
/*
* Load JLA data according to information provided in the provided
* configuration file (typically data/jla.dataset)
*/
void JLALikelihood::read(const char * datasetfile)
{
Configuration config;
if (verbosity > 1)
cout << "Reading config from " << datasetfile << endl;
if (ini_parse(datasetfile, configuration_handler, &config) < 0)
{
if (verbosity > 0)
cerr << "Can't load '" << datasetfile << "'\n";
exit(-1);
}
scriptmcut = config.scriptmcut;
if (verbosity > 1)
cout << "Config loaded from '" << datasetfile << "': scriptmcut=" << config.scriptmcut << endl;
C00 = read_matrix(config.C00, verbosity);
C11 = read_matrix(config.C11, verbosity);
C22 = read_matrix(config.C22, verbosity);
C01 = read_matrix(config.C01, verbosity);
C02 = read_matrix(config.C02, verbosity);
C12 = read_matrix(config.C12, verbosity);
char buffer[1024];
if (verbosity > 1)
cout << "Reading light-curve parameters from '" << config.data_file << endl;
ifstream fid(config.data_file);
if (!fid){
if (verbosity > 0)
cerr << "Can't load '" << config.data_file << "'\n";
exit(-1);
}
while(fid.get() == '#')
fid.getline(buffer, 1024);
fid.unget();
while (fid)
{
LCPar SN;
fid >> SN;
if (fid)
lcpars.push_back(SN);
}
if (verbosity > 1)
cout << "Read " << lcpars.size() << " SNe in file " << config.data_file << endl;
}
// ----------------------- Computations ---------------------------------
/*
* Compute the negative log-likelihood of a set of distance modulii
* given the JLA sample (see Betoule et al. 2014, Eq. 15)
*
* Parameters:
* -----------
* - distanceModulli: a size N vector of double containing the
* predicted distance modulus for each SN in the JLA sample.
*
* - nuisanceParameters: a size 4 vector of double containing the
* distance estimate nuisance parameters in the order: alpha,
* beta, M, deltaM.
*
* Return:
* -------
* (-2) ln (L) if the computation is sucessfull, NaN otherwise.
*/
double JLALikelihood::computeLikelihood(double * distance_modulii,
double * nuisance_parameters)
{
double residuals[size()];
int status;
status = computeResiduals(distance_modulii, nuisance_parameters, residuals);
double chi2 = 0;
if (status == 0)
{
for (int i = 0; i < size(); i++){
chi2 += sq(residuals[i]);
}
}
else
chi2 = NAN;
if (verbosity > 2)
cout << "JLA likelihood evaluation: " << chi2 << endl;
return chi2;
}
/*
* Compute the standardized residuals of the JLA sample to the
* provided model of distance modulii.
*
* Minimisation algorithms specialised in quadratic criterion (such
* as Levenberg-Marquardt) typically needs the output of this
* method.
*
* Parameters:
* -----------
* - distanceModulli: a size N vector of double containing the
* predicted distance modulus for each SN in the JLA sample.
*
* - nuisanceParameters: a size 4 vector of double containing the
* distance estimate nuisance parameters in the order: alpha,
* beta, M, deltaM.
*
* - residuals: an allocated space for N double. Receive the
* standardized residuals r_i at the end of the execution.
* The minization criterion is $\chi^2 = \sum_i r_i^2$.
*
* Return:
* -------
* 0 if the computation is successful, -1 otherwise.
*/
int JLALikelihood::computeResiduals(double * distance_modulii, double * nuisance_parameters, double * residuals)
{
int n = lcpars.size();
double alpha = nuisance_parameters[0];
double beta = nuisance_parameters[1];
double M = nuisance_parameters[2];
double DeltaM = nuisance_parameters[3];
// Covariance matrix computation
double cov[sq(n)];
cblas_dcopy(sq(n), C00, 1, cov, 1);
cblas_daxpy(sq(n), sq(alpha), C11, 1, cov, 1);
cblas_daxpy(sq(n), sq(beta), C22, 1, cov, 1);
cblas_daxpy(sq(n), 2.0 * alpha, C01, 1, cov, 1);
cblas_daxpy(sq(n), -2.0 * beta, C02, 1, cov, 1);
cblas_daxpy(sq(n), -2.0 * alpha * beta, C12, 1, cov, 1);
for (int i = 0; i < n; i++)
{
LCPar sn = lcpars[i];
// Compute distance modulus estimate
residuals[i] = sn.mb - (M - alpha * sn.x1 + beta * sn.color + DeltaM * (sn.thirdvar > scriptmcut));
// Compute residuals
residuals[i] -= distance_modulii[i];
// Update the diagonal terms of the covariance matrix with statistical error
cov[i * n + i] += sq(sn.dmb) + sq(alpha * sn.dx1) + sq(beta * sn.dcolor)
+ 2.0 * alpha * sn.cov_m_s
- 2.0 * beta * sn.cov_m_c
- 2.0 * alpha * beta * sn.cov_s_c;
}
// Whiten the residuals
int nhrs = 1, info = 0;
dpotrf("U", &n, cov, &n, &info);
if (info != 0){
if (verbosity > 0)
cerr << "Cholesky Error: " << info << endl;
return -1;
}
dtrtrs("U", "T", "N", &n, &nhrs, cov, &n, residuals, &n, &info);
if (info != 0){
if (verbosity > 0)
cerr << "Solve Error: " << info << endl;
return -1;
}
return 0;
}
// -------------------------- Misc ---------------------------------------
double *JLALikelihood::computemu(double * nuisance_parameters)
{
int n = lcpars.size();
double alpha = nuisance_parameters[0];
double beta = nuisance_parameters[1];
double M = nuisance_parameters[2];
double DeltaM = nuisance_parameters[3];
double *mu = (double *)malloc(sizeof(double) * n);
for (int i = 0; i < n; i++)
{
LCPar sn = lcpars[i];
// Compute distance modulus estimate
mu[i] = sn.mb - (M - alpha * sn.x1 + beta * sn.color + DeltaM * (sn.thirdvar > scriptmcut));
}
return mu;
}
double * JLALikelihood::computecovariance(double * nuisance_parameters)
{
int n = lcpars.size();
double alpha = nuisance_parameters[0];
double beta = nuisance_parameters[1];
double M = nuisance_parameters[2];
double DeltaM = nuisance_parameters[3];
// Covariance matrix computation
double *cov = (double *)malloc(sizeof(double) * sq(n));
cblas_dcopy(sq(n), C00, 1, cov, 1);
cblas_daxpy(sq(n), sq(alpha), C11, 1, cov, 1);
cblas_daxpy(sq(n), sq(beta), C22, 1, cov, 1);
cblas_daxpy(sq(n), 2.0 * alpha, C01, 1, cov, 1);
cblas_daxpy(sq(n), -2.0 * beta, C02, 1, cov, 1);
cblas_daxpy(sq(n), -2.0 * alpha * beta, C12, 1, cov, 1);
for (int i = 0; i < n; i++)
{
LCPar sn = lcpars[i];
// Update the diagonal terms of the covariance matrix with statistical error
cov[i * n + i] += sq(sn.dmb) + sq(alpha * sn.dx1) + sq(beta * sn.dcolor)
+ 2.0 * alpha * sn.cov_m_s
- 2.0 * beta * sn.cov_m_c
- 2.0 * alpha * beta * sn.cov_s_c;
}
return cov;
}
/*
* Return the redshift of all SN in the sample.
*/
double * JLALikelihood::getZ()
{
double * z = (double *)malloc(sizeof(double) * size());
for (int i=0; i < size(); i++)
{
z[i] = lcpars[i].zcmb;
}
return z;
}
/*
* Return the redshift of all SN in the sample.
*/
double * JLALikelihood::getZhel()
{
double * z = (double *)malloc(sizeof(double) * size());
for (int i=0; i < size(); i++)
{
z[i] = lcpars[i].zhel;
}
return z;
}
/*
* Free the allocated memory
*/
JLALikelihood::~JLALikelihood()
{
if (C00 != NULL)
free(C00);
if (C11 != NULL)
free(C11);
if (C22 != NULL)
free(C22);
if (C01 != NULL)
free(C01);
if (C02 != NULL)
free(C02);
if (C12 != NULL)
free(C12);
}
/***************************************************************************
* Simplified Likelihood *
***************************************************************************/
/*
* Store values read from the configuration file.
*/
struct SimplifiedConfiguration{
int version;
const char* data_file;
const char* C00;
};
/*
* Handler for reading the config file through inih.
*/
static int simple_configuration_handler(void* user, const char* section, const char* name,
const char* value)
{
SimplifiedConfiguration* pconfig = (SimplifiedConfiguration*)user;
#define MATCH(s, n) strcmp(section, s) == 0 && strcmp(name, n) == 0
if (MATCH("", "data_file")) {
pconfig->data_file = strdup(value);
} else if (MATCH("", "mu_covmat_file")) {
pconfig->C00 = strdup(value);
} else {
return 0; /* unknown section/name, error */
}
return 1;
}
/*
* Read one entry in the lightcurve file.
*/
istream & operator >> (istream & is, DistanceModulus & mu)
{
is >> mu.zcmb >> mu.mu;
return is;
}
/*
* Load JLA data according to information provided in the provided
* configuration file (typically data/jla_simple.dataset)
*/
void SimplifiedJLALikelihood::read(const char * datasetfile)
{
SimplifiedConfiguration config;
if (verbosity > 1)
cout << "Reading config from " << datasetfile << endl;
if (ini_parse(datasetfile, simple_configuration_handler, &config) < 0)
{
if (verbosity > 0)
cerr << "Can't load '" << datasetfile << "'\n";
exit(-1);
}
if (verbosity > 1)
cout << "Config loaded from '" << datasetfile << "': binned distances" << endl;
C00 = read_matrix(config.C00, verbosity);
char buffer[1024];
if (verbosity > 1)
cout << "Reading binned distances from " << config.data_file << endl;
ifstream fid(config.data_file);
if (!fid){
if (verbosity > 0)
cerr << "Can't load '" << config.data_file << "'\n";
exit(-1);
}
while(fid.get() == '#')
fid.getline(buffer, 1024);
fid.unget();
while (fid)
{
DistanceModulus mu;
fid >> mu;
if (fid)
binned_distances.push_back(mu);
}
if (verbosity > 1)
cout << "Read " << binned_distances.size() << " bins in file " << config.data_file << endl;
// Invert the covariance matrix, once and for all
int info = 0;
int n = binned_distances.size();
dpotrf("U", &n, C00, &n, &info);
if (info != 0){
if (verbosity > 0)
cerr << "Cholesky Error: " << info << endl;
exit(-1);
}
}
/*
* Return the redshift of all SN in the sample.
*/
double * SimplifiedJLALikelihood::getZ()
{
double * z = (double *)malloc(sizeof(double) * size());
for (int i=0; i < size(); i++)
{
z[i] = binned_distances[i].zcmb;
}
return z;
}
/*
* Compute the standardized residuals of the JLA sample to the
* provided model of binned distance modulii.
*
* Minimisation algorithms specialised in quadratic criterion (such
* as Levenberg-Marquardt) typically needs the output of this
* method.
*
* Parameters:
* -----------
* - distanceModulli: a size N vector of double containing the
* predicted distance modulus at the node redshfits.
*
* - nuisanceParameters: a size 1 vector of double containing the
* Hubble diagram normalisation nuisance parameters: M.
*
* - residuals: an allocated space for N double. Receive the
* standardized residuals r_i at the end of the execution.
* The minization criterion is $\chi^2 = \sum_i r_i^2$.
*
* Return:
* -------
* 0 if the computation is successful, -1 otherwise.
*/
int SimplifiedJLALikelihood::computeResiduals(double * distance_modulii, double * nuisance_parameters, double * residuals)
{
int n = size();
double M = nuisance_parameters[0];
// Compute residuals
for (int i = 0; i < n; i++)
{
residuals[i] = binned_distances[i].mu - (M + distance_modulii[i]);
}
// Whiten the residuals
int nhrs = 1, info = 0;
dtrtrs("U", "T", "N", &n, &nhrs, C00, &n, residuals, &n, &info);
if (info != 0){
if (verbosity > 0)
cerr << "Solve Error: " << info << endl;
return -1;
}
return 0;
}
| 26.604569 | 122 | 0.585546 | [
"vector",
"model"
] |
3700ac9840d5fbe97d1cd84be5068b577deeeedc | 5,422 | cpp | C++ | Vendors/lepton/src/ExpressionTreeNode.cpp | vinaym815/opensim-core | 176e2ae7790f039357a79e89213ba1994f651a0a | [
"Apache-2.0"
] | 532 | 2015-03-13T18:51:10.000Z | 2022-03-27T08:08:29.000Z | Vendors/lepton/src/ExpressionTreeNode.cpp | vinaym815/opensim-core | 176e2ae7790f039357a79e89213ba1994f651a0a | [
"Apache-2.0"
] | 2,701 | 2015-01-03T21:33:34.000Z | 2022-03-30T07:13:41.000Z | Vendors/lepton/src/ExpressionTreeNode.cpp | vinaym815/opensim-core | 176e2ae7790f039357a79e89213ba1994f651a0a | [
"Apache-2.0"
] | 271 | 2015-02-16T23:25:29.000Z | 2022-03-30T20:12:17.000Z | /* -------------------------------------------------------------------------- *
* Lepton *
* -------------------------------------------------------------------------- *
* This is part of the Lepton expression parser originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions Copyright (c) 2005-2017 Stanford University and the Authors. *
* Authors: Peter Eastman *
* Contributors: *
* *
* 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, CONTRIBUTORS 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 "lepton/ExpressionTreeNode.h"
#include "lepton/Exception.h"
#include "lepton/Operation.h"
using namespace Lepton;
using namespace std;
ExpressionTreeNode::ExpressionTreeNode(Operation* operation, const vector<ExpressionTreeNode>& children) : operation(operation), children(children) {
if (static_cast<unsigned>(operation->getNumArguments()) != children.size())
throw Exception("Parse error: wrong number of arguments to function: "+operation->getName());
}
ExpressionTreeNode::ExpressionTreeNode(Operation* operation, const ExpressionTreeNode& child1, const ExpressionTreeNode& child2) : operation(operation) {
children.push_back(child1);
children.push_back(child2);
if (static_cast<unsigned>(operation->getNumArguments()) != children.size())
throw Exception("Parse error: wrong number of arguments to function: "+operation->getName());
}
ExpressionTreeNode::ExpressionTreeNode(Operation* operation, const ExpressionTreeNode& child) : operation(operation) {
children.push_back(child);
if (static_cast<unsigned>(operation->getNumArguments()) != children.size())
throw Exception("Parse error: wrong number of arguments to function: "+operation->getName());
}
ExpressionTreeNode::ExpressionTreeNode(Operation* operation) : operation(operation) {
if (static_cast<unsigned>(operation->getNumArguments()) != children.size())
throw Exception("Parse error: wrong number of arguments to function: "+operation->getName());
}
ExpressionTreeNode::ExpressionTreeNode(const ExpressionTreeNode& node) : operation(&node.getOperation() == NULL ? NULL : node.getOperation().clone()), children(node.getChildren()) {
}
ExpressionTreeNode::ExpressionTreeNode() : operation(NULL) {
}
ExpressionTreeNode::~ExpressionTreeNode() {
if (operation != NULL)
delete operation;
}
bool ExpressionTreeNode::operator!=(const ExpressionTreeNode& node) const {
if (node.getOperation() != getOperation())
return true;
if (getOperation().isSymmetric() && getChildren().size() == 2) {
if (getChildren()[0] == node.getChildren()[0] && getChildren()[1] == node.getChildren()[1])
return false;
if (getChildren()[0] == node.getChildren()[1] && getChildren()[1] == node.getChildren()[0])
return false;
return true;
}
for (int i = 0; i < (int) getChildren().size(); i++)
if (getChildren()[i] != node.getChildren()[i])
return true;
return false;
}
bool ExpressionTreeNode::operator==(const ExpressionTreeNode& node) const {
return !(*this != node);
}
ExpressionTreeNode& ExpressionTreeNode::operator=(const ExpressionTreeNode& node) {
if (operation != NULL)
delete operation;
operation = node.getOperation().clone();
children = node.getChildren();
return *this;
}
const Operation& ExpressionTreeNode::getOperation() const {
return *operation;
}
const vector<ExpressionTreeNode>& ExpressionTreeNode::getChildren() const {
return children;
}
| 50.203704 | 181 | 0.603836 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.